Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>src/motioncapture.cpp<|end_filename|> #include "libmotioncapture/motioncapture.h" namespace libmotioncapture { void MotionCapture::getObjectByName( const std::string& name, Object& result) const { std::vector<Object> objects; getObjects(objects); for(const auto& object : objects) { if (object.name() == name) { result = object; return; } } throw std::runtime_error("Object not found!"); } }
jungr-ait/libmotioncapture
<|start_filename|>package.json<|end_filename|> { "name": "mediasoup-custom", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node src/app.js", "mon": "nodemon src/app.js", "watch": "watchify public/index.js -o public/bundle.js -v", "lint": "npx prettier --write .", "docker-build": "docker build --tag dirvann/mediasoup-video-rooms .", "docker-run": "docker run --name dirvann-mediasoup-rooms -p 10000-10100:10000-10100 -p 3016:3016 dirvann/mediasoup-video-rooms", "docker-start": "docker start dirvann-mediasoup-rooms", "docker-stop": "docker stop dirvann-mediasoup-rooms", "compile-mediasoup-client": "npx browserify mediasoup-client-compile.js -o public/modules/mediasoupclient.min.js" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1", "httpolyglot": "^0.1.2", "mediasoup": "^3.8.2", "mediasoup-client": "^3.6.37", "socket.io": "^4.1.3" }, "devDependencies": { "prettier": "2.3.2" } } <|start_filename|>src/app.js<|end_filename|> const express = require('express') const app = express() const https = require('httpolyglot') const fs = require('fs') const mediasoup = require('mediasoup') const config = require('./config') const path = require('path') const Room = require('./Room') const Peer = require('./Peer') const options = { key: fs.readFileSync(path.join(__dirname, config.sslKey), 'utf-8'), cert: fs.readFileSync(path.join(__dirname, config.sslCrt), 'utf-8') } const httpsServer = https.createServer(options, app) const io = require('socket.io')(httpsServer) app.use(express.static(path.join(__dirname, '..', 'public'))) httpsServer.listen(config.listenPort, () => { console.log('Listening on https://' + config.listenIp + ':' + config.listenPort) }) // all mediasoup workers let workers = [] let nextMediasoupWorkerIdx = 0 /** * roomList * { * room_id: Room { * id: * router: * peers: { * id:, * name:, * master: [boolean], * transports: [Map], * producers: [Map], * consumers: [Map], * rtpCapabilities: * } * } * } */ let roomList = new Map() ;(async () => { await createWorkers() })() async function createWorkers() { let { numWorkers } = config.mediasoup for (let i = 0; i < numWorkers; i++) { let worker = await mediasoup.createWorker({ logLevel: config.mediasoup.worker.logLevel, logTags: config.mediasoup.worker.logTags, rtcMinPort: config.mediasoup.worker.rtcMinPort, rtcMaxPort: config.mediasoup.worker.rtcMaxPort }) worker.on('died', () => { console.error('mediasoup worker died, exiting in 2 seconds... [pid:%d]', worker.pid) setTimeout(() => process.exit(1), 2000) }) workers.push(worker) // log worker resource usage /*setInterval(async () => { const usage = await worker.getResourceUsage(); console.info('mediasoup Worker resource usage [pid:%d]: %o', worker.pid, usage); }, 120000);*/ } } io.on('connection', (socket) => { socket.on('createRoom', async ({ room_id }, callback) => { if (roomList.has(room_id)) { callback('already exists') } else { console.log('Created room', { room_id: room_id }) let worker = await getMediasoupWorker() roomList.set(room_id, new Room(room_id, worker, io)) callback(room_id) } }) socket.on('join', ({ room_id, name }, cb) => { console.log('User joined', { room_id: room_id, name: name }) if (!roomList.has(room_id)) { return cb({ error: 'Room does not exist' }) } roomList.get(room_id).addPeer(new Peer(socket.id, name)) socket.room_id = room_id cb(roomList.get(room_id).toJson()) }) socket.on('getProducers', () => { if (!roomList.has(socket.room_id)) return console.log('Get producers', { name: `${roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) // send all the current producer to newly joined member let producerList = roomList.get(socket.room_id).getProducerListForPeer() socket.emit('newProducers', producerList) }) socket.on('getRouterRtpCapabilities', (_, callback) => { console.log('Get RouterRtpCapabilities', { name: `${roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) try { callback(roomList.get(socket.room_id).getRtpCapabilities()) } catch (e) { callback({ error: e.message }) } }) socket.on('createWebRtcTransport', async (_, callback) => { console.log('Create webrtc transport', { name: `${roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) try { const { params } = await roomList.get(socket.room_id).createWebRtcTransport(socket.id) callback(params) } catch (err) { console.error(err) callback({ error: err.message }) } }) socket.on('connectTransport', async ({ transport_id, dtlsParameters }, callback) => { console.log('Connect transport', { name: `${roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) if (!roomList.has(socket.room_id)) return await roomList.get(socket.room_id).connectPeerTransport(socket.id, transport_id, dtlsParameters) callback('success') }) socket.on('produce', async ({ kind, rtpParameters, producerTransportId }, callback) => { if (!roomList.has(socket.room_id)) { return callback({ error: 'not is a room' }) } let producer_id = await roomList.get(socket.room_id).produce(socket.id, producerTransportId, rtpParameters, kind) console.log('Produce', { type: `${kind}`, name: `${roomList.get(socket.room_id).getPeers().get(socket.id).name}`, id: `${producer_id}` }) callback({ producer_id }) }) socket.on('consume', async ({ consumerTransportId, producerId, rtpCapabilities }, callback) => { //TODO null handling let params = await roomList.get(socket.room_id).consume(socket.id, consumerTransportId, producerId, rtpCapabilities) console.log('Consuming', { name: `${roomList.get(socket.room_id) && roomList.get(socket.room_id).getPeers().get(socket.id).name}`, producer_id: `${producerId}`, consumer_id: `${params.id}` }) callback(params) }) socket.on('resume', async (data, callback) => { await consumer.resume() callback() }) socket.on('getMyRoomInfo', (_, cb) => { cb(roomList.get(socket.room_id).toJson()) }) socket.on('disconnect', () => { console.log('Disconnect', { name: `${roomList.get(socket.room_id) && roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) if (!socket.room_id) return roomList.get(socket.room_id).removePeer(socket.id) }) socket.on('producerClosed', ({ producer_id }) => { console.log('Producer close', { name: `${roomList.get(socket.room_id) && roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) roomList.get(socket.room_id).closeProducer(socket.id, producer_id) }) socket.on('exitRoom', async (_, callback) => { console.log('Exit room', { name: `${roomList.get(socket.room_id) && roomList.get(socket.room_id).getPeers().get(socket.id).name}` }) if (!roomList.has(socket.room_id)) { callback({ error: 'not currently in a room' }) return } // close transports await roomList.get(socket.room_id).removePeer(socket.id) if (roomList.get(socket.room_id).getPeers().size === 0) { roomList.delete(socket.room_id) } socket.room_id = null callback('successfully exited room') }) }) // TODO remove - never used? function room() { return Object.values(roomList).map((r) => { return { router: r.router.id, peers: Object.values(r.peers).map((p) => { return { name: p.name } }), id: r.id } }) } /** * Get next mediasoup Worker. */ function getMediasoupWorker() { const worker = workers[nextMediasoupWorkerIdx] if (++nextMediasoupWorkerIdx === workers.length) nextMediasoupWorkerIdx = 0 return worker }
senatoreg/mediasoup-sfu-webrtc-video-rooms
<|start_filename|>Iterator/src/menu/item.cpp<|end_filename|> #include "item.h"
bergolho1337/Design-Patterns
<|start_filename|>allure-junit-platform/src/test/java/io/qameta/allure/junitplatform/features/TestWithSteps.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.junitplatform.features; import io.qameta.allure.Allure; import io.qameta.allure.model.Status; import io.qameta.allure.model.StepResult; import org.junit.jupiter.api.Test; import java.util.UUID; /** * @author charlie (<NAME>). */ public class TestWithSteps { @Test void testWithSteps() { step("first"); step("second"); step("third"); } protected final void step(final String stepName) { final String uuid = UUID.randomUUID().toString(); try { Allure.getLifecycle().startStep(uuid, new StepResult() .setName(stepName) .setStatus(Status.PASSED) ); } finally { Allure.getLifecycle().stopStep(uuid); } } } <|start_filename|>allure-attachments/src/main/java/io/qameta/allure/attachment/DefaultAttachmentProcessor.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.attachment; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import java.nio.charset.StandardCharsets; /** * @author charlie (<NAME>). */ public class DefaultAttachmentProcessor implements AttachmentProcessor<AttachmentData> { private final AllureLifecycle lifecycle; public DefaultAttachmentProcessor() { this(Allure.getLifecycle()); } public DefaultAttachmentProcessor(final AllureLifecycle lifecycle) { this.lifecycle = lifecycle; } @Override public void addAttachment(final AttachmentData attachmentData, final AttachmentRenderer<AttachmentData> renderer) { final AttachmentContent content = renderer.render(attachmentData); lifecycle.addAttachment( attachmentData.getName(), content.getContentType(), content.getFileExtension(), content.getContent().getBytes(StandardCharsets.UTF_8) ); } } <|start_filename|>allure-jsonunit/src/main/java/io/qameta/allure/jsonunit/JsonPatchListener.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jsonunit; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import net.javacrumbs.jsonunit.core.listener.Difference; import net.javacrumbs.jsonunit.core.listener.DifferenceContext; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.apache.commons.lang3.StringUtils; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * JsonUnit listener, that keeps difference and * return formatted json to represent deltas * (i.e. the output of jsondiffpatch.diff). */ public class JsonPatchListener implements DifferenceListener { private static final String UNKNOWN_TYPE_ERROR = "Difference has unknown type"; private static final ObjectMapper MAPPER = new ObjectMapper(); private final List<Difference> differences = new ArrayList<>(); private DifferenceContext context; @Override public void diff(final Difference difference, final DifferenceContext differenceContext) { this.context = differenceContext; differences.add(difference); } public List<Difference> getDifferences() { return differences; } public DifferenceContext getContext() { return context; } private String getPath(final Difference difference) { switch (difference.getType()) { case DIFFERENT: return difference.getActualPath(); case MISSING: return difference.getExpectedPath(); case EXTRA: return difference.getActualPath(); default: throw new IllegalArgumentException(UNKNOWN_TYPE_ERROR); } } @SuppressWarnings("ReturnCount") private List<Object> getPatch(final Difference difference) { final List<Object> result = new ArrayList<>(); switch (difference.getType()) { case DIFFERENT: result.add(difference.getExpected()); result.add(difference.getActual()); return result; case MISSING: result.add(difference.getExpected()); result.add(0); result.add(0); return result; case EXTRA: result.add(difference.getActual()); return result; default: throw new IllegalArgumentException(UNKNOWN_TYPE_ERROR); } } public DiffModel getDiffModel() { return new DiffModel( writeAsString(context.getActualSource(), "actual"), writeAsString(context.getExpectedSource(), "expected"), getJsonPatch()); } @SuppressWarnings({"all", "unchecked"}) public String getJsonPatch() { final Map<String, Object> jsonDiffPatch = new HashMap<>(); // take care of corner case when two jsons absolutelly different if (getDifferences().size() == 1) { final Difference difference = getDifferences().get(0); final String field = getPath(difference); if (field.isEmpty()) { final ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(getPatch(difference)); } catch (JsonProcessingException e) { throw new IllegalStateException("Could not process patch json", e); } } } getDifferences().forEach(difference -> { final String field = getPath(difference); Map<String, Object> currentMap = jsonDiffPatch; final String fieldWithDots = StringUtils.replace(field, "[", "."); final int len = fieldWithDots.length(); int left = 0; int right = 0; while (left < len) { right = fieldWithDots.indexOf('.', left); if (right == -1) { right = len; } String fieldName = fieldWithDots.substring(left, right); fieldName = StringUtils.remove(fieldName, "]"); if (right != len) { if (!fieldName.isEmpty()) { if (!currentMap.containsKey(fieldName)) { currentMap.put(fieldName, new HashMap<>()); } currentMap = (Map<String, Object>) currentMap.get(fieldName); } if (field.charAt(right) == '[') { if (!currentMap.containsKey(fieldName)) { currentMap.put("_t", "a"); } } } else { final List<?> actualExpectedValue = getPatch(difference); currentMap.put(fieldName, actualExpectedValue); } left = right + 1; } }); final ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(jsonDiffPatch); } catch (JsonProcessingException e) { throw new IllegalStateException("Could not process patch json", e); } } private static String writeAsString(final Object object, final String failDescription) { try { return MAPPER.writeValueAsString(object); } catch (JsonProcessingException e) { throw new UncheckedIOException(String.format("Could not process %s json", failDescription), e); } } } <|start_filename|>allure-junit-platform/src/test/java/io/qameta/allure/junitplatform/features/TestWithMethodLinks.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.junitplatform.features; import io.qameta.allure.Issue; import io.qameta.allure.Issues; import io.qameta.allure.Link; import io.qameta.allure.Links; import io.qameta.allure.TmsLink; import io.qameta.allure.TmsLinks; import org.junit.jupiter.api.Test; public class TestWithMethodLinks { @Test @Link(name = "LINK-1") @Links({ @Link(name = "LINK-2", url = "https://example.org/link/2"), @Link(url = "https://example.org/some-custom-link") }) @TmsLink("TMS-1") @TmsLinks({ @TmsLink("TMS-2"), @TmsLink("TMS-3") }) @Issue("ISSUE-1") @Issues({ @Issue("ISSUE-2"), @Issue("ISSUE-3") }) void someTest() { } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/LabelAnnotation.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation. Annotations marked by this annotation will be discovered * by Allure and added to test results as a label. * * @see Epic * @see Feature * @see Story */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE}) @Repeatable(LabelAnnotations.class) public @interface LabelAnnotation { String DEFAULT_VALUE = "$$$$$$$$__value__$$$$$$$$"; /** * The name of label. Some build-in names can be * found in {@link io.qameta.allure.util.ResultsUtils}. You can * also use any custom label name and create mapping for it in * Allure Enterprise or Allure 3. * * @return the name of label to add. */ String name(); /** * Th value of label. In not specified will take value from <code>value()</code> * method of target annotation. * * @return the value of label to add. */ String value() default DEFAULT_VALUE; } <|start_filename|>allure-attachments/src/test/java/io/qameta/allure/attachment/FreemarkerAttachmentRendererTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.attachment; import io.qameta.allure.attachment.http.HttpRequestAttachment; import io.qameta.allure.test.AllureFeatures; import org.junit.jupiter.api.Test; import static io.qameta.allure.attachment.testdata.TestData.randomHttpRequestAttachment; import static org.assertj.core.api.Assertions.assertThat; /** * @author charlie (<NAME>). */ class FreemarkerAttachmentRendererTest { @AllureFeatures.Attachments @Test void shouldRenderRequestAttachment() { final HttpRequestAttachment data = randomHttpRequestAttachment(); final DefaultAttachmentContent content = new FreemarkerAttachmentRenderer("http-request.ftl") .render(data); assertThat(content) .hasFieldOrPropertyWithValue("contentType", "text/html") .hasFieldOrPropertyWithValue("fileExtension", ".html") .hasFieldOrProperty("content"); } @AllureFeatures.Attachments @Test void shouldRenderResponseAttachment() { final HttpRequestAttachment data = randomHttpRequestAttachment(); final DefaultAttachmentContent content = new FreemarkerAttachmentRenderer("http-response.ftl") .render(data); assertThat(content) .hasFieldOrPropertyWithValue("contentType", "text/html") .hasFieldOrPropertyWithValue("fileExtension", ".html") .hasFieldOrProperty("content"); } } <|start_filename|>allure-java-commons/src/test/java/io/qameta/allure/util/NamingUtilsTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.util; import io.qameta.allure.testdata.DummyUser; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.stream.Stream; import static io.qameta.allure.util.NamingUtils.processNameTemplate; import static org.assertj.core.api.Assertions.assertThat; /** * @author charlie (<NAME>). */ class NamingUtilsTest { public static Stream<Arguments> data() { return Stream.of( Arguments.of("", Collections.singletonMap("a", "b"), ""), Arguments.of("", Collections.singletonMap("a", "b"), ""), Arguments.of("Hello word", Collections.emptyMap(), "Hello word"), Arguments.of("Hello {0}", Collections.singletonMap("0", "world"), "Hello world"), Arguments.of("Hello {method}", Collections.singletonMap("method", "world"), "Hello world"), Arguments.of("{missing}", Collections.emptyMap(), "{missing}"), Arguments.of("Hello {user}!", Collections.singletonMap("user", "Ivan"), "Hello Ivan!"), Arguments.of("Hello {user}", Collections.singletonMap("user", null), "Hello null"), Arguments.of("Hello {users}", Collections.singletonMap("users", Arrays.asList("Ivan", "Petr")), "Hello [Ivan, Petr]"), Arguments.of("Hello {users}", Collections.singletonMap("users", new String[]{"Ivan", "Petr"}), "Hello [Ivan, Petr]"), Arguments.of("Hello {users}", Collections.singletonMap("users", Collections.singletonMap("a", "b")), "Hello {a=b}"), Arguments.of("Password: {<PASSWORD>}", Collections.singletonMap("user", new DummyUser(null, "123", null)), "Password: <PASSWORD>"), Arguments.of("Passwords: {users.password}", Collections.singletonMap("users", new DummyUser[]{new DummyUser(null, "123", null)}), "Passwords: [123]"), Arguments.of("Passwords: {<PASSWORD>}", Collections.singletonMap("users", new DummyUser[]{null, new DummyUser(null, "123", null)}), "Passwords: [null, 123]"), Arguments.of("Passwords: {users.password}", Collections.singletonMap("users", new DummyUser[][]{null, {null, new DummyUser(null, "123", null)}}), "Passwords: [null, [null, 123]]") ); } @ParameterizedTest @MethodSource("data") public void shouldProcessTemplate(final String template, final Map<String, Object> parameters, final String expected) { final String actual = processNameTemplate(template, parameters); assertThat(actual) .describedAs("Should process template \"%s\" as \"%s\"", template, expected) .isEqualTo(expected); } } <|start_filename|>allure-java-migration/src/main/java/ru/yandex/qatools/allure/annotations/Severity.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 ru.yandex.qatools.allure.annotations; import ru.yandex.qatools.allure.model.SeverityLevel; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Each test has severity level. You can change test case severity * label using this annotation. * * @see ru.yandex.qatools.allure.model.SeverityLevel */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Severity { SeverityLevel value(); } <|start_filename|>allure-java-commons/src/test/java/io/qameta/allure/testdata/DummyUser.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testdata; import java.util.Arrays; /** * @author sskorol (<NAME>) */ public class DummyUser { private final DummyEmail[] emails; private final String password; private final DummyCard card; public DummyUser(final DummyEmail[] emails, final String password, DummyCard card) { this.emails = emails; this.password = password; this.card = card; } public DummyEmail[] getEmail() { return emails; } public String getPassword() { return password; } public DummyCard getCard() { return card; } @Override public String toString() { return "DummyUser{" + "emails='" + Arrays.toString(emails) + '\'' + ", password='" + password + '\'' + ", card=" + card + '}'; } } <|start_filename|>allure-citrus/src/main/java/io/qameta/allure/citrus/AllureCitrus.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.citrus; import com.consol.citrus.TestAction; import com.consol.citrus.TestCase; import com.consol.citrus.report.TestActionListener; import com.consol.citrus.report.TestListener; import com.consol.citrus.report.TestSuiteListener; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.Description; import io.qameta.allure.Epic; import io.qameta.allure.Feature; import io.qameta.allure.Story; import io.qameta.allure.model.Label; import io.qameta.allure.model.Link; import io.qameta.allure.model.Parameter; import io.qameta.allure.model.Stage; import io.qameta.allure.model.Status; import io.qameta.allure.model.StatusDetails; import io.qameta.allure.model.StepResult; import io.qameta.allure.model.TestResult; import io.qameta.allure.util.ResultsUtils; import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; import java.util.stream.Stream; import static io.qameta.allure.util.ResultsUtils.createFrameworkLabel; import static io.qameta.allure.util.ResultsUtils.createHostLabel; import static io.qameta.allure.util.ResultsUtils.createLanguageLabel; import static io.qameta.allure.util.ResultsUtils.createParameter; import static io.qameta.allure.util.ResultsUtils.createSuiteLabel; import static io.qameta.allure.util.ResultsUtils.createThreadLabel; import static io.qameta.allure.util.ResultsUtils.getProvidedLabels; /** * @author charlie (<NAME>). */ public class AllureCitrus implements TestListener, TestSuiteListener, TestActionListener { private final Map<TestCase, String> testUuids = new ConcurrentHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AllureLifecycle lifecycle; public AllureCitrus(final AllureLifecycle lifecycle) { this.lifecycle = lifecycle; } @SuppressWarnings("unused") public AllureCitrus() { this.lifecycle = Allure.getLifecycle(); } public AllureLifecycle getLifecycle() { return lifecycle; } @Override public void onStart() { //do nothing } @Override public void onStartSuccess() { //do nothing } @Override public void onStartFailure(final Throwable cause) { //do nothing } @Override public void onFinish() { //do nothing } @Override public void onFinishSuccess() { //do nothing } @Override public void onFinishFailure(final Throwable cause) { //do nothing } @Override public void onTestStart(final TestCase test) { startTestCase(test); } @Override public void onTestFinish(final TestCase test) { //do nothing } @Override public void onTestSuccess(final TestCase test) { stopTestCase(test, Status.PASSED, null); } @Override public void onTestFailure(final TestCase test, final Throwable cause) { final Status status = ResultsUtils.getStatus(cause).orElse(Status.BROKEN); final StatusDetails details = ResultsUtils.getStatusDetails(cause).orElse(null); stopTestCase(test, status, details); } @Override public void onTestSkipped(final TestCase test) { //do nothing } @Override public void onTestActionStart(final TestCase testCase, final TestAction testAction) { final String parentUuid = getUuid(testCase); final String uuid = UUID.randomUUID().toString(); getLifecycle().startStep(parentUuid, uuid, new StepResult().setName(testAction.getName())); } @Override public void onTestActionFinish(final TestCase testCase, final TestAction testAction) { getLifecycle().stopStep(); } @Override public void onTestActionSkipped(final TestCase testCase, final TestAction testAction) { //do nothing } private void startTestCase(final TestCase testCase) { final String uuid = createUuid(testCase); final TestResult result = new TestResult() .setUuid(uuid) .setName(testCase.getName()) .setStage(Stage.RUNNING); result.getLabels().addAll(getProvidedLabels()); final Optional<? extends Class<?>> testClass = Optional.ofNullable(testCase.getTestClass()); testClass.map(this::getLabels).ifPresent(result.getLabels()::addAll); testClass.map(this::getLinks).ifPresent(result.getLinks()::addAll); result.getLabels().addAll(Arrays.asList( createHostLabel(), createThreadLabel(), createFrameworkLabel("citrus"), createLanguageLabel("java") )); testClass.ifPresent(aClass -> { final String suiteName = aClass.getCanonicalName(); result.getLabels().add(createSuiteLabel(suiteName)); }); final Optional<String> classDescription = testClass.flatMap(this::getDescription); final String description = Stream.of(classDescription) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.joining("\n\n")); result.setDescription(description); getLifecycle().scheduleTestCase(result); getLifecycle().startTestCase(uuid); } private void stopTestCase(final TestCase testCase, final Status status, final StatusDetails details) { final String uuid = removeUuid(testCase); final Map<String, Object> definitions = testCase.getVariableDefinitions(); final List<Parameter> parameters = definitions.entrySet().stream() .map(entry -> createParameter(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); getLifecycle().updateTestCase(uuid, result -> { result.setParameters(parameters); result.setStage(Stage.FINISHED); result.setStatus(status); result.setStatusDetails(details); }); getLifecycle().stopTestCase(uuid); getLifecycle().writeTestCase(uuid); } private String createUuid(final TestCase testCase) { final String uuid = UUID.randomUUID().toString(); try { lock.writeLock().lock(); testUuids.put(testCase, uuid); } finally { lock.writeLock().unlock(); } return uuid; } private String getUuid(final TestCase testCase) { try { lock.readLock().lock(); return testUuids.get(testCase); } finally { lock.readLock().unlock(); } } private String removeUuid(final TestCase testCase) { try { lock.writeLock().lock(); return testUuids.remove(testCase); } finally { lock.writeLock().unlock(); } } private Optional<String> getDescription(final AnnotatedElement annotatedElement) { return getAnnotations(annotatedElement, Description.class) .map(Description::value) .findAny(); } private List<Label> getLabels(final AnnotatedElement annotatedElement) { return Stream.of( getAnnotations(annotatedElement, Epic.class).map(ResultsUtils::createLabel), getAnnotations(annotatedElement, Feature.class).map(ResultsUtils::createLabel), getAnnotations(annotatedElement, Story.class).map(ResultsUtils::createLabel) ).reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList()); } private List<Link> getLinks(final AnnotatedElement annotatedElement) { return Stream.of( getAnnotations(annotatedElement, io.qameta.allure.Link.class).map(ResultsUtils::createLink), getAnnotations(annotatedElement, io.qameta.allure.Issue.class).map(ResultsUtils::createLink), getAnnotations(annotatedElement, io.qameta.allure.TmsLink.class).map(ResultsUtils::createLink)) .reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList()); } private <T extends Annotation> Stream<T> getAnnotations(final AnnotatedElement annotatedElement, final Class<T> annotationClass) { final T annotation = annotatedElement.getAnnotation(annotationClass); return Stream.concat( extractRepeatable(annotatedElement, annotationClass).stream(), Objects.isNull(annotation) ? Stream.empty() : Stream.of(annotation) ); } @SuppressWarnings("unchecked") private <T extends Annotation> List<T> extractRepeatable(final AnnotatedElement annotatedElement, final Class<T> annotationClass) { if (annotationClass.isAnnotationPresent(Repeatable.class)) { final Repeatable repeatable = annotationClass.getAnnotation(Repeatable.class); final Class<? extends Annotation> wrapper = repeatable.value(); final Annotation annotation = annotatedElement.getAnnotation(wrapper); if (Objects.nonNull(annotation)) { try { final Method value = annotation.getClass().getMethod("value"); final Object annotations = value.invoke(annotation); return Arrays.asList((T[]) annotations); } catch (Exception e) { throw new IllegalStateException(e); } } } return Collections.emptyList(); } } <|start_filename|>allure-java-migration/src/test/java/io/qameta/allure/aspects/Allure1StepsAspectsTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.aspects; import io.qameta.allure.model.StepResult; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureResults; import org.junit.jupiter.api.Test; import ru.yandex.qatools.allure.annotations.Step; import static io.qameta.allure.test.RunUtils.runWithinTestContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class Allure1StepsAspectsTest { @Test void shouldSetupStepTitleFromAnnotation() { final AllureResults results = runWithinTestContext( () -> stepWithTitleAndWithParameter("parameter value"), Allure1StepsAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName) .containsExactly("step with title and parameter [parameter value]"); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .flatExtracting(StepResult::getParameters) .extracting("name", "value") .containsExactly(tuple("parameter", "parameter value")); } @Test void shouldSetupStepTitleFromMethodSignature() { final AllureResults results = runWithinTestContext( () -> stepWithoutTitleAndWithParameter("parameter value"), Allure1StepsAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName) .containsExactly("stepWithoutTitleAndWithParameter[parameter value]"); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .flatExtracting(StepResult::getParameters) .extracting("name", "value") .containsExactly(tuple("parameter", "parameter value")); } @SuppressWarnings("all") @Step void stepWithoutTitleAndWithParameter(String parameter) { } @SuppressWarnings("all") @Step("step with title and parameter [{0}]") void stepWithTitleAndWithParameter(String parameter) { } } <|start_filename|>allure-java-migration/src/main/java/io/qameta/allure/aspects/Allure1AttachAspects.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.aspects; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import ru.yandex.qatools.allure.annotations.Attachment; import java.nio.charset.StandardCharsets; import java.util.Objects; /** * Aspects (AspectJ) for handling {@link Attachment}. */ @Aspect public class Allure1AttachAspects { private static AllureLifecycle lifecycle; /** * Pointcut for things annotated with {@link ru.yandex.qatools.allure.annotations.Attachment}. */ @Pointcut("@annotation(ru.yandex.qatools.allure.annotations.Attachment)") public void withAttachmentAnnotation() { //pointcut body, should be empty } /** * Pointcut for any methods. */ @Pointcut("execution(* *(..))") public void anyMethod() { //pointcut body, should be empty } /** * Process data returned from method annotated with {@link ru.yandex.qatools.allure.annotations.Attachment} * If returned data is not a byte array, then use toString() method, and get bytes from it using. */ @AfterReturning(pointcut = "anyMethod() && withAttachmentAnnotation()", returning = "result") public void attachment(final JoinPoint joinPoint, final Object result) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); final Attachment attachment = methodSignature.getMethod().getAnnotation(Attachment.class); final String title = Allure1Utils.getTitle( attachment.value(), methodSignature.getName(), joinPoint.getThis(), joinPoint.getArgs() ); final byte[] bytes = (result instanceof byte[]) ? (byte[]) result : Objects.toString(result).getBytes(StandardCharsets.UTF_8); getLifecycle().addAttachment(title, attachment.type(), "", bytes); } /** * For tests only. */ public static void setLifecycle(final AllureLifecycle lifecycle) { Allure1AttachAspects.lifecycle = lifecycle; } public static AllureLifecycle getLifecycle() { if (Objects.isNull(lifecycle)) { lifecycle = Allure.getLifecycle(); } return lifecycle; } } <|start_filename|>allure-attachments/src/test/java/io/qameta/allure/attachment/testdata/TestData.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.attachment.testdata; import io.qameta.allure.attachment.AttachmentContent; import io.qameta.allure.attachment.DefaultAttachmentContent; import io.qameta.allure.attachment.http.HttpRequestAttachment; import io.qameta.allure.attachment.http.HttpResponseAttachment; import org.apache.commons.lang3.RandomStringUtils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; /** * @author charlie (<NAME>). */ public final class TestData { private TestData() { throw new IllegalStateException("Do not instance"); } public static String randomString() { return RandomStringUtils.randomAlphabetic(10); } public static HttpRequestAttachment randomHttpRequestAttachment() { return new HttpRequestAttachment( randomString(), randomString(), randomString(), randomString(), randomString(), randomMap(), randomMap() ); } public static HttpResponseAttachment randomHttpResponseAttachment() { return new HttpResponseAttachment( randomString(), randomString(), randomString(), ThreadLocalRandom.current().nextInt(), randomMap(), randomMap() ); } public static AttachmentContent randomAttachmentContent() { return new DefaultAttachmentContent(randomString(), randomString(), randomString()); } public static Map<String, String> randomMap() { final Map<String, String> map = new HashMap<>(); map.put(randomString(), randomString()); map.put(randomString(), randomString()); return map; } } <|start_filename|>allure-jsonunit/src/test/java/io/qameta/allure/jsonunit/JsonPatchMatcherTests.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jsonunit; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.ArgumentCaptor.forClass; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.function.BiConsumer; import org.hamcrest.Description; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import net.javacrumbs.jsonunit.core.Configuration; import net.javacrumbs.jsonunit.core.Option; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; class JsonPatchMatcherTests { private static final String JSON = "{\"key1\":\"value1\"}"; private static final String EMPTY = ""; @Test void shouldMatchWhenIgnoringPaths() { final String actual = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}"; final boolean result = JsonPatchMatcher.jsonEquals(JSON) .whenIgnoringPaths("key2", "key3") .matches(actual); assertThat(result).isTrue(); } @Test void shouldMatchWithOptions() { final boolean result = JsonPatchMatcher.jsonEquals("[1,2]") .withOptions(Options.empty().with(Option.IGNORING_ARRAY_ORDER)) .matches("[2,1]"); assertThat(result).isTrue(); } @Test void shouldMatchWhenOptions() { final boolean result = JsonPatchMatcher.jsonEquals("[1,2]") .when(Option.IGNORING_ARRAY_ORDER).matches("[2,1]"); assertThat(result).isTrue(); } @Test void shouldMatchWithToleranceDouble() { final boolean result = JsonPatchMatcher.jsonEquals("1.01") .withTolerance(0.01).matches("1"); assertThat(result).isTrue(); } @Test void shouldSetDifferenceListener() { final DifferenceListener listener = mock(DifferenceListener.class); final JsonPatchMatcher<?> matcher = (JsonPatchMatcher<?>) JsonPatchMatcher.jsonEquals(JSON) .withDifferenceListener(listener); acceptConfiguration(matcher, (f, c) -> { assertThat(c.getDifferenceListener()).isSameAs(listener); }); } @Test void shouldMatchWithToleranceBigDecimal() { final boolean result = JsonPatchMatcher.jsonEquals("1.01") .withTolerance(BigDecimal.valueOf(0.01)).matches("1"); assertThat(result).isTrue(); } @Test void shouldMatchWithMatcher() { final String expected = "{\"key\":\"${json-unit.matches:matcher}\"}"; final String actual = "{\"key\":\"value\"}"; final boolean result = JsonPatchMatcher.jsonEquals(expected) .withMatcher("matcher", equalTo("value")) .matches(actual); assertThat(result).isTrue(); } @Test void shouldDescribeTo() { final Description description = mock(Description.class); JsonPatchMatcher.jsonEquals(EMPTY).describeTo(description); verify(description).appendText("has no difference"); verifyNoMoreInteractions(description); } @Test void shouldDescribeMismatch() { final Description description = mock(Description.class); final JsonPatchMatcher<?> matcher = (JsonPatchMatcher<?>) JsonPatchMatcher.jsonEquals("data"); matcher.matches(EMPTY); final ArgumentCaptor<String> captor = forClass(String.class); matcher.describeMismatch(null, description); verify(description).appendText(captor.capture()); verifyNoMoreInteractions(description); assertThat(captor.getValue()).isNotBlank(); } @Test void shouldMatchAndNoRender() { final JsonPatchMatcher<?> matcher = (JsonPatchMatcher<?>) JsonPatchMatcher.jsonEquals(JSON); final JsonPatchListener listener = mockConfiguration(matcher); final boolean result = matcher.matches(JSON); assertThat(result).isTrue(); verify(listener, never()).getDiffModel(); } @Test void shouldNotMatchAndRender() { final JsonPatchMatcher<?> matcher = (JsonPatchMatcher<?>) JsonPatchMatcher.jsonEquals(JSON); final JsonPatchListener listener = mockConfiguration(matcher); final DiffModel diffModel = new DiffModel(EMPTY, EMPTY, EMPTY); doReturn(diffModel).when(listener).getDiffModel(); final boolean result = matcher.matches(EMPTY); assertThat(result).isFalse(); verify(listener).getDiffModel(); } private static JsonPatchListener mockConfiguration(JsonPatchMatcher<?> matcher) { final JsonPatchListener jsonPatchListener = mock(JsonPatchListener.class); acceptConfiguration(matcher, (f, c) -> { try { final Configuration configurationSpy = spy(c.withDifferenceListener(jsonPatchListener)); doReturn(configurationSpy).when(configurationSpy).withDifferenceListener(any()); f.set(matcher, configurationSpy); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Unable to mock configuration", e); } }); return jsonPatchListener; } private static void acceptConfiguration(JsonPatchMatcher<?> matcher, BiConsumer<Field, Configuration> consumer) { try { final Field configurationField = matcher.getClass().getSuperclass().getDeclaredField("configuration"); configurationField.setAccessible(true); consumer.accept(configurationField, (Configuration) configurationField.get(matcher)); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Unable to access configuration field", e); } } } <|start_filename|>allure-junit4/src/test/java/io/qameta/allure/junit4/samples/TestBasedOnSampleRunner.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.junit4.samples; import io.qameta.allure.junit4.DisplayName; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import java.lang.annotation.Annotation; @RunWith(TestBasedOnSampleRunner.SampleRunnerBasedOnNotClasses.class) public class TestBasedOnSampleRunner { public static class SampleRunnerBasedOnNotClasses extends Runner { @SuppressWarnings("unused") public SampleRunnerBasedOnNotClasses(Class testClass) { super(); } @Override public Description getDescription() { return Description.createTestDescription( "allure junit4 runner.test for non-existing classes (would be a class in normal runner)", "should correctly handle non-existing classes (would be method name in normal runner)", new DisplayName() { @Override public String value() { return "Some human readable name"; } @Override public Class<? extends Annotation> annotationType() { return DisplayName.class; } } ); } @Override public void run(RunNotifier notifier) { notifier.fireTestStarted(getDescription()); notifier.fireTestFinished(getDescription()); } } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/Attachment.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to mark methods that produce attachments. Returned value of such methods * will be copied and shown in the report as attachment. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Attachment { /** * The attachment name. * * @return the attachment name. */ String value() default ""; /** * Valid attachment MimeType, for example "text/plain" or "application/json". * * @return the attachment type. */ String type() default ""; /** * Optional attachment file extension. By default file extension will be determined by * provided media type. Should be started with dot. * * @return the attachment file extension. */ String fileExtension() default ""; } <|start_filename|>allure-java-commons-test/src/main/java/io/qameta/allure/test/AllurePredicates.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.test; import io.qameta.allure.model.Label; import io.qameta.allure.model.Status; import io.qameta.allure.model.TestResult; import java.util.Objects; import java.util.function.Predicate; /** * @author charlie (<NAME>). */ @SuppressWarnings({"PMD.ClassNamingConventions", "PMD.LinguisticNaming"}) public final class AllurePredicates { private AllurePredicates() { throw new IllegalStateException("Do not instance"); } public static Predicate<TestResult> hasStatus(final Status status) { return testResult -> status.equals(testResult.getStatus()); } public static Predicate<TestResult> hasLabel(final String name, final String value) { final Predicate<Label> labelPredicate = label -> Objects.equals(label.getName(), name) && Objects.equals(label.getValue(), value); return testResult -> testResult.getLabels().stream().anyMatch(labelPredicate); } } <|start_filename|>allure-spring-web/src/test/java/io/qameta/allure/springweb/AllureRestTemplateTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.springweb; import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import io.qameta.allure.model.Attachment; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureResults; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.stream.Stream; import static io.qameta.allure.test.RunUtils.runWithinTestContext; import static org.assertj.core.api.Assertions.assertThat; /** * @author choojoykin (<NAME>). */ @SuppressWarnings("unchecked") public class AllureRestTemplateTest { static Stream<String> attachmentNameProvider() { return Stream.of("Request", "Response"); } @ParameterizedTest @MethodSource(value = "attachmentNameProvider") void shouldCreateAttachment(final String attachmentName) { final AllureResults results = execute(); assertThat(results.getTestResults()) .flatExtracting(TestResult::getAttachments) .flatExtracting(Attachment::getName) .contains(attachmentName); } @ParameterizedTest @MethodSource(value = "attachmentNameProvider") void shouldCatchAttachmentBody(final String attachmentName) { final AllureResults results = execute(); final Attachment found = results.getTestResults().stream() .map(TestResult::getAttachments) .flatMap(Collection::stream) .filter(attachment -> Objects.equals(attachmentName, attachment.getName())) .findAny() .orElseThrow(() -> new RuntimeException("attachment not found")); assertThat(results.getAttachments()) .containsKeys(found.getSource()); } protected final AllureResults execute() { final RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); restTemplate.setInterceptors(Collections.singletonList(new AllureRestTemplate())); final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort()); return runWithinTestContext(() -> { server.start(); WireMock.configureFor(server.port()); WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/hello")).willReturn(WireMock.aResponse().withBody("some body"))); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<JsonNode> entity = new HttpEntity<>(headers); ResponseEntity<String> result = restTemplate.exchange(server.url("/hello"), HttpMethod.GET, entity, String.class); Assertions.assertEquals(result.getStatusCode(), HttpStatus.OK); } finally { server.stop(); } }); } } <|start_filename|>allure-jsonunit/src/main/java/io/qameta/allure/jsonunit/AllureConfigurableJsonMatcher.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jsonunit; import net.javacrumbs.jsonunit.core.Option; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Matcher; import java.math.BigDecimal; /** * @param <T> the type of matcher * @see net.javacrumbs.jsonunit.ConfigurableJsonMatcher */ public interface AllureConfigurableJsonMatcher<T> extends Matcher<T> { AllureConfigurableJsonMatcher<T> withTolerance(BigDecimal tolerance); AllureConfigurableJsonMatcher<T> withTolerance(double tolerance); AllureConfigurableJsonMatcher<T> when(Option first, Option... next); AllureConfigurableJsonMatcher<T> withOptions(Options options); AllureConfigurableJsonMatcher<T> withMatcher(String matcherName, Matcher<?> matcher); AllureConfigurableJsonMatcher<T> whenIgnoringPaths(String... paths); AllureConfigurableJsonMatcher<T> withDifferenceListener(DifferenceListener differenceListener); } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/listener/StepLifecycleListener.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.listener; import io.qameta.allure.model.StepResult; /** * Notifies about Allure step lifecycle events. * * @since 2.0 */ public interface StepLifecycleListener extends LifecycleListener { default void beforeStepStart(StepResult result) { //do nothing } default void afterStepStart(StepResult result) { //do nothing } default void beforeStepUpdate(StepResult result) { //do nothing } default void afterStepUpdate(StepResult result) { //do nothing } default void beforeStepStop(StepResult result) { //do nothing } default void afterStepStop(StepResult result) { //do nothing } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/util/ServiceLoaderUtils.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; /** * Internal service loader util. * * @see ServiceLoader * @since 2.0 */ public final class ServiceLoaderUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceLoaderUtils.class); private ServiceLoaderUtils() { throw new IllegalStateException("Do not instance"); } /** * Load implementation by given type. * * @param <T> type of implementation. * @param type the type of implementation to load. * @param classLoader the class loader to search for implementations. * @return loaded implementations. */ public static <T> List<T> load(final Class<T> type, final ClassLoader classLoader) { final List<T> loaded = new ArrayList<>(); final Iterator<T> iterator = ServiceLoader.load(type, classLoader).iterator(); while (hasNextSafely(iterator)) { try { final T next = iterator.next(); loaded.add(next); LOGGER.debug("Found {}", type); } catch (Exception e) { LOGGER.error("Could not load {}: {}", type, e); } } return loaded; } /** * Safely check for <pre>iterator.hasNext()</pre>. * * @param iterator specified iterator to check he presence of next element * @return {@code true} if the iteration has more elements, false otherwise */ private static boolean hasNextSafely(final Iterator iterator) { try { /* Throw a ServiceConfigurationError if a provider-configuration file violates the specified format, or if it names a provider class that cannot be found and instantiated, or if the result of instantiating the class is not assignable to the service type, or if any other kind of exception or error is thrown as the next provider is located and instantiated. @see http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html#iterator() */ return iterator.hasNext(); } catch (Exception e) { LOGGER.error("iterator.hasNext() failed", e); return false; } } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/listener/TestLifecycleListener.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.listener; import io.qameta.allure.model.TestResult; /** * Listener that notifies about Allure Lifecycle events. * * @since 2.0 */ public interface TestLifecycleListener extends LifecycleListener { default void beforeTestSchedule(TestResult result) { //do nothing } default void afterTestSchedule(TestResult result) { //do nothing } default void beforeTestUpdate(TestResult result) { //do nothing } default void afterTestUpdate(TestResult result) { //do nothing } default void beforeTestStart(TestResult result) { //do nothing } default void afterTestStart(TestResult result) { //do nothing } default void beforeTestStop(TestResult result) { //do nothing } default void afterTestStop(TestResult result) { //do nothing } default void beforeTestWrite(TestResult result) { //do nothing } default void afterTestWrite(TestResult result) { //do nothing } } <|start_filename|>allure-junit-platform/src/test/java/io/qameta/allure/junitplatform/features/DynamicTests.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.junitplatform.features; import io.qameta.allure.Epic; import io.qameta.allure.Feature; import io.qameta.allure.Owner; import io.qameta.allure.Stories; import io.qameta.allure.Story; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.stream.Stream; import static org.junit.jupiter.api.DynamicTest.dynamicTest; /** * @author charlie (<NAME>). */ @Epic("epic4") @Feature("feature4") @Story("story4") public class DynamicTests { @Epic("epic1") @Epic("epic2") @Epic("epic3") @Feature("feature1") @Feature("feature2") @Feature("feature3") @Story("story1") @Stories({ @Story("story2"), @Story("story3") }) @Owner("some-owner") @TestFactory Stream<DynamicTest> dynamicTestsFromStream() { return Stream.of("A", "B", "C").map( str -> dynamicTest("test" + str, () -> { })); } } <|start_filename|>allure-servlet-api/build.gradle.kts<|end_filename|> description = "Allure Servlet API v3 Integration" var servletApiVersion = "4.0.1" dependencies { api(project(":allure-attachments")) implementation("javax.servlet:javax.servlet-api:$servletApiVersion") } tasks.jar { manifest { attributes(mapOf( "Automatic-Module-Name" to "io.qameta.allure.servletapi" )) } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/internal/AllureStorage.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.internal; import io.qameta.allure.model.FixtureResult; import io.qameta.allure.model.StepResult; import io.qameta.allure.model.TestResult; import io.qameta.allure.model.TestResultContainer; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Internal Allure data storage. * * @since 2.0 */ public class AllureStorage { private final Map<String, Object> storage = new ConcurrentHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); public Optional<TestResultContainer> getContainer(final String uuid) { return get(uuid, TestResultContainer.class); } public Optional<TestResult> getTestResult(final String uuid) { return get(uuid, TestResult.class); } public Optional<FixtureResult> getFixture(final String uuid) { return get(uuid, FixtureResult.class); } public Optional<StepResult> getStep(final String uuid) { return get(uuid, StepResult.class); } public <T> Optional<T> get(final String uuid, final Class<T> clazz) { lock.readLock().lock(); try { Objects.requireNonNull(uuid, "Can't get item from storage: uuid can't be null"); return Optional.ofNullable(storage.get(uuid)) .filter(clazz::isInstance) .map(clazz::cast); } finally { lock.readLock().unlock(); } } public <T> T put(final String uuid, final T item) { lock.writeLock().lock(); try { Objects.requireNonNull(uuid, "Can't put item to storage: uuid can't be null"); storage.put(uuid, item); return item; } finally { lock.writeLock().unlock(); } } public void remove(final String uuid) { lock.writeLock().lock(); try { Objects.requireNonNull(uuid, "Can't remove item from storage: uuid can't be null"); storage.remove(uuid); } finally { lock.writeLock().unlock(); } } } <|start_filename|>allure-java-migration/src/main/java/io/qameta/allure/aspects/Allure1ParametersAspects.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.aspects; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.FieldSignature; import ru.yandex.qatools.allure.annotations.Parameter; import java.util.Objects; import static io.qameta.allure.util.ResultsUtils.createParameter; /** * Aspects for Allure1 Parameters. */ @SuppressWarnings("all") @Aspect public class Allure1ParametersAspects { private static AllureLifecycle lifecycle; @Pointcut("@annotation(ru.yandex.qatools.allure.annotations.Parameter)") public void withParameterAnnotation() { //pointcut body, should be empty } @Pointcut("set(* *)") public void setValueToAnyField() { //pointcut body, should be empty } @After("setValueToAnyField() && withParameterAnnotation()") public void parameterValueChanged(JoinPoint joinPoint) { try { FieldSignature fieldSignature = (FieldSignature) joinPoint.getSignature(); Parameter parameter = fieldSignature.getField().getAnnotation(Parameter.class); String name = parameter.value().isEmpty() ? fieldSignature.getName() : parameter.value(); String value = Objects.toString(joinPoint.getArgs()[0]); getLifecycle().updateTestCase(testResult -> testResult.getParameters().add(createParameter(name, value)) ); } catch (Exception ignored) { } } /** * For tests only. */ public static void setLifecycle(final AllureLifecycle allure) { lifecycle = allure; } public static AllureLifecycle getLifecycle() { if (Objects.isNull(lifecycle)) { lifecycle = Allure.getLifecycle(); } return lifecycle; } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/AllureResultsWriter.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure; import io.qameta.allure.model.TestResult; import io.qameta.allure.model.TestResultContainer; import java.io.InputStream; /** * @author charlie (<NAME>). * @since 1.0-BETA2 */ public interface AllureResultsWriter { /** * Writes Allure test result bean. * * @param testResult the given bean to write. * @throws AllureResultsWriteException if some error occurs * during operation. */ void write(TestResult testResult); /** * Writes Allure test result container bean. * * @param testResultContainer the given bean to write. * @throws AllureResultsWriteException if some error occurs * during operation. */ void write(TestResultContainer testResultContainer); /** * Writes given attachment. Will close the given stream. * * @param source the file name of the attachment. Make sure that file name * matches the following glob: <pre>*-attachment*</pre>. The right way * to generate attachment is generate UUID, determinate attachment * extension and then use it as <pre>{UUID}-attachment.{ext}</pre> * @param attachment the steam that contains attachment body. */ void write(String source, InputStream attachment); } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/Description.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation that allows to attach a description for a test or for a step. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Description { /** * Simple description text as String. * * @return Description text. */ String value() default ""; /** * Use annotated method's javadoc to extract description that * supports html markdown. * * @return boolean flag to enable description extraction from javadoc. */ boolean useJavaDoc() default false; } <|start_filename|>allure-testng/src/test/java/io/qameta/allure/testng/samples/BeforeMethods.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testng.samples; import io.qameta.allure.Step; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author charlie (<NAME>). */ public class BeforeMethods { @BeforeTest public void beforeTest() { } @AfterTest public void afterTest() { } @BeforeClass public void beforeClass() { } @AfterClass public void afterClass() { } @BeforeMethod(alwaysRun = true) public void beforeMethod1() { } @Step @BeforeMethod(alwaysRun = true) public void beforeMethod2() { } @Test public void test1() { } @Test public void test2() { } @Test public void test3() { } @AfterMethod(alwaysRun = true) public void afterMethod1() { } @AfterMethod(alwaysRun = true) public void afterMethod2() { } } <|start_filename|>allure-java-migration/src/main/java/ru/yandex/qatools/allure/annotations/Description.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 ru.yandex.qatools.allure.annotations; import ru.yandex.qatools.allure.model.DescriptionType; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Using this annotation you can add some text description * to test suite or test case. * <pre> * &#064;Test * &#064;Description("This is an example of my test") * public void myTest() throws Exception { * ... * } * </pre> * @see ru.yandex.qatools.allure.model.DescriptionType */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface Description { String value(); DescriptionType type() default DescriptionType.TEXT; } <|start_filename|>allure-testng/src/test/java/io/qameta/allure/testng/samples/ParallelDataProviderSample.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testng.samples; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Make sure this class can run without causing a ConcurrentModificationException. */ public class ParallelDataProviderSample { @DataProvider(parallel = true) Iterator<Integer[]> provide() { List<Integer[]> ret = new ArrayList<>(); for (int i = 0; i < 1000; i++) { ret.add(new Integer[]{i}); } return ret.iterator(); } @Test(dataProvider = "provide", invocationCount = 2, threadPoolSize = 2) public void checkCME(Integer i) { Assert.assertNotNull(i); } } <|start_filename|>allure-java-migration/src/test/java/io/qameta/allure/aspects/Allure1AttachAspectsTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.aspects; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureResults; import org.junit.jupiter.api.Test; import ru.yandex.qatools.allure.annotations.Attachment; import static io.qameta.allure.test.RunUtils.runWithinTestContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; /** * eroshenkoam * 30.04.17 */ class Allure1AttachAspectsTest { @Test void shouldSetupAttachmentTitleFromAnnotation() { final AllureResults results = runWithinTestContext( () -> attachmentWithTitleAndType("parameter value"), Allure1AttachAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getAttachments) .extracting("name", "type") .containsExactly(tuple("attachment with parameter value", "text/plain")); } @Test void shouldSetupAttachmentTitleFromMethodSignature() { final AllureResults results = runWithinTestContext( this::attachmentWithoutTitle, Allure1AttachAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getAttachments) .extracting("name", "type") .containsExactly(tuple("attachmentWithoutTitle", null)); } @Test void shouldProcessNullAttachment() { final AllureResults results = runWithinTestContext( this::attachmentWithNullValue, Allure1AttachAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getAttachments) .extracting("name", "type") .containsExactly(tuple("attachmentWithNullValue", null)); } @SuppressWarnings("all") @Attachment byte[] attachmentWithNullValue() { return null; } @SuppressWarnings("all") @Attachment byte[] attachmentWithoutTitle() { return new byte[]{}; } @SuppressWarnings({"all"}) @Attachment(value = "attachment with {0}", type = "text/plain") byte[] attachmentWithTitleAndType(String parameter) { return new byte[]{}; } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/listener/ContainerLifecycleListener.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.listener; import io.qameta.allure.model.TestResultContainer; /** * Notifies about Allure test container lifecycle. * * @since 2.0 */ public interface ContainerLifecycleListener extends LifecycleListener { default void beforeContainerStart(TestResultContainer container) { //do nothing } default void afterContainerStart(TestResultContainer container) { //do nothing } default void beforeContainerUpdate(TestResultContainer container) { //do nothing } default void afterContainerUpdate(TestResultContainer container) { //do nothing } default void beforeContainerStop(TestResultContainer container) { //do nothing } default void afterContainerStop(TestResultContainer container) { //do nothing } default void beforeContainerWrite(TestResultContainer container) { //do nothing } default void afterContainerWrite(TestResultContainer container) { //do nothing } } <|start_filename|>allure-testng/src/test/java/io/qameta/allure/testng/samples/ParallelMethods.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testng.samples; import io.qameta.allure.Step; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.util.stream.IntStream; /** * @author ehborisov */ public class ParallelMethods { @BeforeSuite public void beforeSuite() { stepOne(); } @BeforeTest public void beforeTest() { stepTwo(); } @BeforeTest public void beforeTest2() { } @BeforeSuite public void beforeSuite2() throws IOException { } @BeforeMethod public void beforeMethod() { stepThree(); } @BeforeMethod public void beforeMethod2() { stepThree(); } @Test public void test1() throws IOException { stepFour(); } @DataProvider(name = "dataProvider") public Object[][] provide() { return IntStream.range(0, 2000) .mapToObj(i -> new String[]{String.valueOf(i)}) .toArray(Object[][]::new); } @Test(dataProvider = "dataProvider") public void test2(String param) throws IOException { stepSix(); } @Step("Step one") public void stepOne() { } @Step("Step two") public void stepTwo() { } @Step("Step three") public void stepThree() { } @Step("Step four") public void stepFour() { } @Step("Step five") public void stepFive() { } @Step("Step six") public void stepSix() { } @Step("Step seven") public void stepSeven() { } @Step("Step eight") public void stepEight() { } @Step("Step nine") public void stepNine() { } @AfterSuite public void afterSuite() { stepSeven(); } @AfterTest public void afterTest() { stepEight(); } @AfterTest public void afterTest2() { stepEight(); } @AfterMethod public void afterMethod() { stepNine(); } } <|start_filename|>allure-spring-web/src/main/java/io/qameta/allure/springweb/AllureRestTemplate.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.springweb; import io.qameta.allure.attachment.AttachmentData; import io.qameta.allure.attachment.AttachmentProcessor; import io.qameta.allure.attachment.DefaultAttachmentProcessor; import io.qameta.allure.attachment.FreemarkerAttachmentRenderer; import io.qameta.allure.attachment.http.HttpRequestAttachment; import io.qameta.allure.attachment.http.HttpResponseAttachment; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.lang.NonNull; import org.springframework.util.StreamUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Allure interceptor for spring rest template. */ public class AllureRestTemplate implements ClientHttpRequestInterceptor { private String requestTemplatePath = "http-request.ftl"; private String responseTemplatePath = "http-response.ftl"; public AllureRestTemplate setRequestTemplate(final String templatePath) { this.requestTemplatePath = templatePath; return this; } public AllureRestTemplate setResponseTemplate(final String templatePath) { this.responseTemplatePath = templatePath; return this; } @SuppressWarnings("NullableProblems") @Override public ClientHttpResponse intercept(@NonNull final HttpRequest request, final byte[] body, @NonNull final ClientHttpRequestExecution execution) throws IOException { final AttachmentProcessor<AttachmentData> processor = new DefaultAttachmentProcessor(); final HttpRequestAttachment.Builder requestAttachmentBuilder = HttpRequestAttachment.Builder .create("Request", request.getURI().toString()) .setMethod(request.getMethodValue()) .setHeaders(toMapConverter(request.getHeaders())); if (body.length != 0) { requestAttachmentBuilder.setBody(new String(body, StandardCharsets.UTF_8)); } final HttpRequestAttachment requestAttachment = requestAttachmentBuilder.build(); processor.addAttachment(requestAttachment, new FreemarkerAttachmentRenderer(requestTemplatePath)); final ClientHttpResponse clientHttpResponse = execution.execute(request, body); final HttpResponseAttachment responseAttachment = HttpResponseAttachment.Builder .create("Response") .setResponseCode(clientHttpResponse.getRawStatusCode()) .setHeaders(toMapConverter(clientHttpResponse.getHeaders())) .setBody(StreamUtils.copyToString(clientHttpResponse.getBody(), StandardCharsets.UTF_8)) .build(); processor.addAttachment(responseAttachment, new FreemarkerAttachmentRenderer(responseTemplatePath)); return clientHttpResponse; } private static Map<String, String> toMapConverter(final Map<String, List<String>> items) { final Map<String, String> result = new HashMap<>(); items.forEach((key, value) -> result.put(key, String.join("; ", value))); return result; } } <|start_filename|>allure-java-commons/src/main/java/io/qameta/allure/listener/FixtureLifecycleListener.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.listener; import io.qameta.allure.model.FixtureResult; /** * Notifies about Allure test fixtures lifecycle events. * * @since 2.0 */ public interface FixtureLifecycleListener extends LifecycleListener { default void beforeFixtureStart(FixtureResult result) { //do nothing } default void afterFixtureStart(FixtureResult result) { //do nothing } default void beforeFixtureUpdate(FixtureResult result) { //do nothing } default void afterFixtureUpdate(FixtureResult result) { //do nothing } default void beforeFixtureStop(FixtureResult result) { //do nothing } default void afterFixtureStop(FixtureResult result) { //do nothing } } <|start_filename|>allure-jsonunit/src/main/java/io/qameta/allure/jsonunit/AbstractJsonPatchMatcher.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jsonunit; import java.math.BigDecimal; import org.hamcrest.Matcher; import net.javacrumbs.jsonunit.core.Configuration; import net.javacrumbs.jsonunit.core.Option; import net.javacrumbs.jsonunit.core.internal.Diff; import net.javacrumbs.jsonunit.core.internal.Options; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; /** * Сontains basic matcher functionality and implementation of methods for matching configuration. * * @param <T> the type */ @SuppressWarnings("unchecked") public abstract class AbstractJsonPatchMatcher<T> { private static final String EMPTY_PATH = ""; private static final String FULL_JSON = "fullJson"; private Configuration configuration = Configuration.empty(); private String differences; public T withTolerance(final BigDecimal tolerance) { this.configuration = configuration.withTolerance(tolerance); return (T) this; } public T withTolerance(final double tolerance) { this.configuration = configuration.withTolerance(tolerance); return (T) this; } public T when(final Option first, final Option... next) { this.configuration = configuration.when(first, next); return (T) this; } public T withOptions(final Options options) { this.configuration = configuration.withOptions(options); return (T) this; } public T withMatcher(final String matcherName, final Matcher matcher) { this.configuration = configuration.withMatcher(matcherName, matcher); return (T) this; } public T whenIgnoringPaths(final String... paths) { this.configuration = configuration.whenIgnoringPaths(paths); return (T) this; } public T withDifferenceListener(final DifferenceListener differenceListener) { this.configuration = configuration.withDifferenceListener(differenceListener); return (T) this; } public boolean matches(final Object expected, final Object actual) { final Diff diff = Diff.create(expected, actual, FULL_JSON, EMPTY_PATH, configuration); final boolean similar = diff.similar(); if (!similar) { differences = diff.differences(); render(configuration.getDifferenceListener()); } return similar; } protected abstract void render(DifferenceListener listener); public String getDifferences() { return differences; } public Configuration getConfiguration() { return configuration; } } <|start_filename|>allure-java-commons/src/test/java/io/qameta/allure/internal/AllureThreadContextTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.internal; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.assertj.core.api.Assertions.assertThat; /** * @author charlie (<NAME>). */ class AllureThreadContextTest { @Test void shouldCreateEmptyContext() { final AllureThreadContext context = new AllureThreadContext(); assertThat(context.getRoot()) .isEmpty(); assertThat(context.getCurrent()) .isEmpty(); } @Test void shouldStart() { final AllureThreadContext context = new AllureThreadContext(); final String first = UUID.randomUUID().toString(); final String second = UUID.randomUUID().toString(); context.start(first); context.start(second); assertThat(context.getRoot()) .hasValue(first); assertThat(context.getCurrent()) .hasValue(second); } @Test void shouldClear() { final AllureThreadContext context = new AllureThreadContext(); final String first = UUID.randomUUID().toString(); final String second = UUID.randomUUID().toString(); context.start(first); context.start(second); context.clear(); assertThat(context.getRoot()) .isEmpty(); } @Test void shouldStop() { final AllureThreadContext context = new AllureThreadContext(); final String first = UUID.randomUUID().toString(); final String second = UUID.randomUUID().toString(); final String third = UUID.randomUUID().toString(); context.start(first); context.start(second); context.start(third); context.stop(); assertThat(context.getCurrent()) .hasValue(second); context.stop(); assertThat(context.getCurrent()) .hasValue(first); context.stop(); assertThat(context.getCurrent()) .isEmpty(); } @Test void shouldIgnoreStopForEmpty() { final AllureThreadContext context = new AllureThreadContext(); context.stop(); assertThat(context.getRoot()) .isEmpty(); } @Test void shouldBeThreadSafe() throws ExecutionException, InterruptedException { final AllureThreadContext context = new AllureThreadContext(); final int threads = 1000; final int stepsCount = 200; final ExecutorService service = Executors.newFixedThreadPool(threads); final List<Callable<Optional<String>>> tasks = new ArrayList<>(); for (int i = 0; i < threads; i++) { tasks.add(() -> { for (int j = 0; j < stepsCount; j++) { context.start(UUID.randomUUID().toString()); context.stop(); } return context.getCurrent(); }); } final String base = "ROOT"; context.start(base); final List<Future<Optional<String>>> futures = service.invokeAll(tasks); for (Future<Optional<String>> future : futures) { final Optional<String> value = future.get(); assertThat(value) .hasValue(base); } } } <|start_filename|>allure-citrus/src/test/java/io/qameta/allure/citrus/AllureCitrusTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.citrus; import com.consol.citrus.Citrus; import com.consol.citrus.TestCase; import com.consol.citrus.actions.AbstractTestAction; import com.consol.citrus.actions.FailAction; import com.consol.citrus.config.CitrusSpringConfig; import com.consol.citrus.context.TestContext; import com.consol.citrus.dsl.design.DefaultTestDesigner; import com.consol.citrus.dsl.design.TestDesigner; import com.consol.citrus.report.TestActionListeners; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.Step; import io.qameta.allure.model.Parameter; import io.qameta.allure.model.Status; import io.qameta.allure.model.StatusDetails; import io.qameta.allure.model.StepResult; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureFeatures; import io.qameta.allure.test.AllureResults; import io.qameta.allure.test.AllureResultsWriterStub; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.Instant; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; /** * @author charlie (<NAME>). */ @SuppressWarnings("unchecked") class AllureCitrusTest { @AllureFeatures.Base @Test void shouldSetName() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("Simple test"); final AllureResults results = run(designer); assertThat(results.getTestResults()) .extracting(TestResult::getName) .containsExactly("Simple test"); } @AllureFeatures.PassedTests @Test void shouldSetStatus() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("Simple test"); final AllureResults results = run(designer); assertThat(results.getTestResults()) .extracting(TestResult::getStatus) .containsExactly(Status.PASSED); } @AllureFeatures.BrokenTests @Test void shouldSetBrokenStatus() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("Simple test"); designer.action(new FailAction()); final AllureResults results = run(designer); assertThat(results.getTestResults()) .extracting(TestResult::getStatus) .containsExactly(Status.BROKEN); } @AllureFeatures.FailedTests @Test void shouldSetFailedStatus() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("Simple test"); designer.action(new AbstractTestAction() { @Override public void doExecute(final TestContext context) { assertThat(true).isFalse(); } }); final AllureResults results = run(designer); assertThat(results.getTestResults()) .extracting(TestResult::getStatus) .containsExactly(Status.FAILED); } @AllureFeatures.FailedTests @Test void shouldSetStatusDetails() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("Simple test"); designer.action(new FailAction().setMessage("failed by design")); final AllureResults results = run(designer); assertThat(results.getTestResults()) .extracting(TestResult::getStatusDetails) .extracting(StatusDetails::getMessage) .containsExactly("failed by design"); } @AllureFeatures.Steps @Test void shouldAddSteps() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("<NAME>"); designer.echo("a"); designer.echo("b"); designer.echo("c"); final AllureResults results = run(designer); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName) .containsExactly("echo", "echo", "echo"); } @AllureFeatures.Steps @Test void shouldAddAllureSteps() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("<NAME>"); designer.action(new AbstractTestAction() { @Override public void doExecute(final TestContext context) { Allure.step("a"); Allure.step("b"); Allure.step("c"); } }); final AllureResults results = run(designer); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .flatExtracting(StepResult::getSteps) .extracting(StepResult::getName) .containsExactly("a", "b", "c"); } @AllureFeatures.Timings @Test void shouldSetStart() { final long before = Instant.now().toEpochMilli(); final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("<NAME>"); final AllureResults results = run(designer); final long after = Instant.now().toEpochMilli(); assertThat(results.getTestResults()) .extracting(TestResult::getStart) .allMatch(v -> v >= before && v <= after); } @AllureFeatures.Timings @Test void shouldSetStop() { final long before = Instant.now().toEpochMilli(); final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("<NAME>"); final AllureResults results = run(designer); final long after = Instant.now().toEpochMilli(); assertThat(results.getTestResults()) .extracting(TestResult::getStop) .allMatch(v -> v >= before && v <= after); } @AllureFeatures.Parameters @Test void shouldSetParameters() { final DefaultTestDesigner designer = new DefaultTestDesigner(); designer.name("<NAME>"); designer.variable("a", "first"); designer.variable("b", 123L); final AllureResults results = run(designer); assertThat(results.getTestResults()) .flatExtracting(TestResult::getParameters) .extracting(Parameter::getName, Parameter::getValue) .containsExactly( tuple("a", "first"), tuple("b", "123") ); } @Step("Run test case {testDesigner}") private AllureResults run(final TestDesigner testDesigner) { final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( CitrusSpringConfig.class, AllureCitrusConfig.class ); final Citrus citrus = Citrus.newInstance(applicationContext); final TestContext testContext = citrus.createTestContext(); final TestActionListeners listeners = applicationContext.getBean(TestActionListeners.class); final AllureLifecycle defaultLifecycle = Allure.getLifecycle(); final AllureLifecycle lifecycle = applicationContext.getBean(AllureLifecycle.class); try { Allure.setLifecycle(lifecycle); final TestCase testCase = testDesigner.getTestCase(); testCase.setTestActionListeners(listeners); citrus.run(testCase, testContext); } catch (Exception ignored) { } finally { Allure.setLifecycle(defaultLifecycle); } return applicationContext.getBean(AllureResultsWriterStub.class); } @Configuration public static class AllureCitrusConfig { @Bean public AllureResultsWriterStub resultsWriterStub() { return new AllureResultsWriterStub(); } @Bean public AllureLifecycle allureLifecycle(final AllureResultsWriterStub stub) { return new AllureLifecycle(stub); } @Bean public AllureCitrus allureCitrus(final AllureLifecycle lifecycle) { return new AllureCitrus(lifecycle); } } } <|start_filename|>allure-servlet-api/src/main/java/io/qameta/allure/servletapi/HttpServletAttachmentBuilder.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.servletapi; import io.qameta.allure.attachment.http.HttpRequestAttachment; import io.qameta.allure.attachment.http.HttpResponseAttachment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.util.Collections; import java.util.stream.Stream; import static io.qameta.allure.attachment.http.HttpRequestAttachment.Builder.create; import static io.qameta.allure.attachment.http.HttpResponseAttachment.Builder.create; /** * @author charlie (<NAME>). */ @SuppressWarnings("PMD.ClassNamingConventions") public final class HttpServletAttachmentBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(HttpServletAttachmentBuilder.class); private HttpServletAttachmentBuilder() { throw new IllegalStateException(); } public static HttpRequestAttachment buildRequest(final HttpServletRequest request) { final HttpRequestAttachment.Builder requestBuilder = create("Request", request.getRequestURI()); Collections.list(request.getHeaderNames()) .forEach(name -> { final String value = request.getHeader(name); requestBuilder.setHeader(name, value); }); Stream.of(request.getCookies()) .forEach(cookie -> requestBuilder.setCookie(cookie.getName(), cookie.getValue())); requestBuilder.setBody(getBody(request)); return requestBuilder.build(); } public static HttpResponseAttachment buildResponse(final HttpServletResponse response) { final HttpResponseAttachment.Builder responseBuilder = create("Response"); response.getHeaderNames() .forEach(name -> response.getHeaders(name) .forEach(value -> responseBuilder.setHeader(name, value))); return responseBuilder.build(); } public static String getBody(final HttpServletRequest request) { final StringBuilder sb = new StringBuilder(); try (BufferedReader reader = request.getReader()) { readBody(sb, reader); } catch (IOException e) { LOGGER.warn("Could not read request body", e); } return sb.toString(); } @SuppressWarnings("PMD.AssignmentInOperand") public static void readBody(final StringBuilder sb, final BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { sb.append(line); } } } <|start_filename|>allure-java-migration/src/main/java/io/qameta/allure/aspects/Allure1TestCaseAspects.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.aspects; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; import java.util.Objects; /** * Allure junit aspects. */ @Aspect public class Allure1TestCaseAspects { private static AllureLifecycle lifecycle; @Before("execution(@org.junit.Test * *.*(..))") public void junitTestStart(final JoinPoint joinPoint) { updateTestCase(joinPoint); } @Before("execution(@org.testng.annotations.Test * *.*(..))") public void testNgTestStart(final JoinPoint joinPoint) { updateTestCase(joinPoint); } private void updateTestCase(final JoinPoint joinPoint) { final MethodSignature signature = (MethodSignature) joinPoint.getSignature(); final Object[] args = joinPoint.getArgs(); final Allure1Annotations annotations = new Allure1Annotations(signature, args); getLifecycle().getCurrentTestCase().ifPresent(uuid -> { getLifecycle().updateTestCase(uuid, annotations::updateTitle); getLifecycle().updateTestCase(uuid, annotations::updateDescription); getLifecycle().updateTestCase(uuid, annotations::updateParameters); getLifecycle().updateTestCase(uuid, annotations::updateLabels); getLifecycle().updateTestCase(uuid, annotations::updateLinks); }); } /** * For tests only. */ public static void setLifecycle(final AllureLifecycle lifecycle) { Allure1TestCaseAspects.lifecycle = lifecycle; } public static AllureLifecycle getLifecycle() { if (Objects.isNull(lifecycle)) { lifecycle = Allure.getLifecycle(); } return lifecycle; } } <|start_filename|>allure-junit4/src/main/java/io/qameta/allure/junit4/AllureJunit4.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.junit4; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.model.Label; import io.qameta.allure.model.Link; import io.qameta.allure.model.Status; import io.qameta.allure.model.StatusDetails; import io.qameta.allure.model.TestResult; import io.qameta.allure.util.AnnotationUtils; import org.junit.Ignore; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; import static io.qameta.allure.util.AnnotationUtils.getLabels; import static io.qameta.allure.util.AnnotationUtils.getLinks; import static io.qameta.allure.util.ResultsUtils.createFrameworkLabel; import static io.qameta.allure.util.ResultsUtils.createHostLabel; import static io.qameta.allure.util.ResultsUtils.createLanguageLabel; import static io.qameta.allure.util.ResultsUtils.createPackageLabel; import static io.qameta.allure.util.ResultsUtils.createSuiteLabel; import static io.qameta.allure.util.ResultsUtils.createTestClassLabel; import static io.qameta.allure.util.ResultsUtils.createTestMethodLabel; import static io.qameta.allure.util.ResultsUtils.createThreadLabel; import static io.qameta.allure.util.ResultsUtils.getProvidedLabels; import static io.qameta.allure.util.ResultsUtils.getStatus; import static io.qameta.allure.util.ResultsUtils.getStatusDetails; import static io.qameta.allure.util.ResultsUtils.md5; /** * Allure Junit4 listener. */ @RunListener.ThreadSafe @SuppressWarnings({"PMD.ExcessiveImports", "PMD.CouplingBetweenObjects", "checkstyle:ClassFanOutComplexity"}) public class AllureJunit4 extends RunListener { private final ThreadLocal<String> testCases = new InheritableThreadLocal<String>() { @Override protected String initialValue() { return UUID.randomUUID().toString(); } }; private final AllureLifecycle lifecycle; public AllureJunit4() { this(Allure.getLifecycle()); } public AllureJunit4(final AllureLifecycle lifecycle) { this.lifecycle = lifecycle; } public AllureLifecycle getLifecycle() { return lifecycle; } @Override public void testRunStarted(final Description description) { //do nothing } @Override public void testRunFinished(final Result result) { //do nothing } @Override public void testStarted(final Description description) { final String uuid = testCases.get(); final TestResult result = createTestResult(uuid, description); getLifecycle().scheduleTestCase(result); getLifecycle().startTestCase(uuid); } @Override public void testFinished(final Description description) { final String uuid = testCases.get(); testCases.remove(); getLifecycle().updateTestCase(uuid, testResult -> { if (Objects.isNull(testResult.getStatus())) { testResult.setStatus(Status.PASSED); } }); getLifecycle().stopTestCase(uuid); getLifecycle().writeTestCase(uuid); } @Override public void testFailure(final Failure failure) { final String uuid = testCases.get(); getLifecycle().updateTestCase(uuid, testResult -> testResult .setStatus(getStatus(failure.getException()).orElse(null)) .setStatusDetails(getStatusDetails(failure.getException()).orElse(null)) ); } @Override public void testAssumptionFailure(final Failure failure) { final String uuid = testCases.get(); getLifecycle().updateTestCase(uuid, testResult -> testResult.setStatus(Status.SKIPPED) .setStatusDetails(getStatusDetails(failure.getException()).orElse(null)) ); } @Override public void testIgnored(final Description description) { final String uuid = testCases.get(); testCases.remove(); final TestResult result = createTestResult(uuid, description); result.setStatus(Status.SKIPPED); result.setStatusDetails(getIgnoredMessage(description)); result.setStart(System.currentTimeMillis()); getLifecycle().scheduleTestCase(result); getLifecycle().stopTestCase(uuid); getLifecycle().writeTestCase(uuid); } private Optional<String> getDisplayName(final Description result) { return Optional.ofNullable(result.getAnnotation(DisplayName.class)) .map(DisplayName::value); } private Optional<String> getDescription(final Description result) { return Optional.ofNullable(result.getAnnotation(io.qameta.allure.Description.class)) .map(io.qameta.allure.Description::value); } private List<Link> extractLinks(final Description description) { final List<Link> result = new ArrayList<>(getLinks(description.getAnnotations())); Optional.of(description) .map(Description::getTestClass) .map(AnnotationUtils::getLinks) .ifPresent(result::addAll); return result; } private List<Label> extractLabels(final Description description) { final List<Label> result = new ArrayList<>(getLabels(description.getAnnotations())); Optional.of(description) .map(Description::getTestClass) .map(AnnotationUtils::getLabels) .ifPresent(result::addAll); return result; } private String getHistoryId(final Description description) { return md5(description.getClassName() + description.getMethodName()); } private String getPackage(final Class<?> testClass) { return Optional.ofNullable(testClass) .map(Class::getPackage) .map(Package::getName) .orElse(""); } private StatusDetails getIgnoredMessage(final Description description) { final Ignore ignore = description.getAnnotation(Ignore.class); final String message = Objects.nonNull(ignore) && !ignore.value().isEmpty() ? ignore.value() : "Test ignored (without reason)!"; return new StatusDetails().setMessage(message); } private TestResult createTestResult(final String uuid, final Description description) { final String className = description.getClassName(); final String methodName = description.getMethodName(); final String name = Objects.nonNull(methodName) ? methodName : className; final String fullName = Objects.nonNull(methodName) ? String.format("%s.%s", className, methodName) : className; final String suite = Optional.ofNullable(description.getTestClass()) .map(it -> it.getAnnotation(DisplayName.class)) .map(DisplayName::value).orElse(className); final TestResult testResult = new TestResult() .setUuid(uuid) .setHistoryId(getHistoryId(description)) .setFullName(fullName) .setName(name); testResult.getLabels().addAll(getProvidedLabels()); testResult.getLabels().addAll(Arrays.asList( createPackageLabel(getPackage(description.getTestClass())), createTestClassLabel(className), createTestMethodLabel(name), createSuiteLabel(suite), createHostLabel(), createThreadLabel(), createFrameworkLabel("junit4"), createLanguageLabel("java") )); testResult.getLabels().addAll(extractLabels(description)); testResult.getLinks().addAll(extractLinks(description)); getDisplayName(description).ifPresent(testResult::setName); getDescription(description).ifPresent(testResult::setDescription); return testResult; } } <|start_filename|>allure-testng/src/test/java/io/qameta/allure/testng/samples/ParameterizedTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testng.samples; import io.qameta.allure.Step; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author <NAME> <EMAIL> */ public class ParameterizedTest { @BeforeMethod public void beforeMethod() { } @DataProvider public Object[][] testData() { return new String[][]{ {"param1"}, {"param2"} }; } @Test(dataProvider = "testData") public void parameterizedTest(String param) { step(param); } @Step public void step(String param) { } } <|start_filename|>allure-jbehave/src/test/java/io/qameta/allure/jbehave/AllureJbehaveTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jbehave; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.Issue; import io.qameta.allure.jbehave.samples.BrokenStorySteps; import io.qameta.allure.jbehave.samples.SimpleStorySteps; import io.qameta.allure.model.Parameter; import io.qameta.allure.model.Stage; import io.qameta.allure.model.Status; import io.qameta.allure.model.StatusDetails; import io.qameta.allure.model.StepResult; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureResults; import io.qameta.allure.test.AllureResultsWriterStub; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.embedder.NullEmbedderMonitor; import org.jbehave.core.io.LoadFromClasspath; import org.jbehave.core.reporters.NullStoryReporter; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.nio.file.Path; import java.time.Instant; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; /** * @author charlie (<NAME>). */ class AllureJbehaveTest { @TempDir Path temp; @Test void shouldSetName() { final AllureResults results = runStories("stories/simple.story"); assertThat(results.getTestResults()) .extracting(TestResult::getName) .containsExactlyInAnyOrder("Add a to b"); } @SuppressWarnings("unchecked") @Test void shouldAddNotPerformedSteps() { final AllureResults results = runStories("stories/long.story"); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName, StepResult::getStatus) .containsExactly( tuple("Given a is 5", Status.PASSED), tuple("And b is 10", Status.PASSED), tuple("When I add a to b", Status.PASSED), tuple("Then result is 15", Status.PASSED), tuple("Then result is 15", Status.PASSED), tuple("When I add a to b", Status.PASSED), tuple("Then result is 20", Status.FAILED), tuple("Then result is ⦅21⦆", null), tuple("Then result is ⦅22⦆", null), tuple("Then result is ⦅23⦆", null), tuple("When I add a to b", null), tuple("Then result is ⦅25⦆", null) ); } @Test void shouldSetStatus() { final AllureResults results = runStories("stories/simple.story"); assertThat(results.getTestResults()) .extracting(TestResult::getStatus) .containsExactlyInAnyOrder(Status.PASSED); } @Test void shouldSetFailedStatus() { final AllureResults results = runStories("stories/failed.story"); final List<TestResult> testResults = results.getTestResults(); assertThat(testResults) .extracting(TestResult::getStatus) .containsExactlyInAnyOrder(Status.FAILED); } @Test void shouldSetStatusDetails() { final AllureResults results = runStories("stories/failed.story"); assertThat(results.getTestResults()) .extracting(TestResult::getStatusDetails) .extracting(StatusDetails::getMessage) .containsExactlyInAnyOrder("expected: <15> but was: <123>"); } @Test void shouldSetBrokenStatus() { final AllureResults results = runStories("stories/broken.story"); assertThat(results.getTestResults()) .extracting(TestResult::getStatus) .containsExactlyInAnyOrder(Status.BROKEN); } @Test void shouldSetStage() { final AllureResults results = runStories("stories/simple.story"); assertThat(results.getTestResults()) .extracting(TestResult::getStage) .containsExactlyInAnyOrder(Stage.FINISHED); } @Test void shouldSetStart() { final long before = Instant.now().toEpochMilli(); final AllureResults results = runStories("stories/simple.story"); final long after = Instant.now().toEpochMilli(); assertThat(results.getTestResults()) .extracting(TestResult::getStart) .allMatch(v -> v >= before && v <= after); } @Test void shouldSetStop() { final long before = Instant.now().toEpochMilli(); final AllureResults results = runStories("stories/simple.story"); final long after = Instant.now().toEpochMilli(); assertThat(results.getTestResults()) .extracting(TestResult::getStop) .allMatch(v -> v >= before && v <= after); } @Test void shouldSetFullName() { final AllureResults results = runStories("stories/simple.story"); assertThat(results.getTestResults()) .extracting(TestResult::getFullName) .containsExactlyInAnyOrder("simple.story: Add a to b"); } @Test void shouldSetDescription() { final AllureResults results = runStories("stories/description.story"); final String expected = "This is description for current story.\n" + "It should appear on each scenario in report"; assertThat(results.getTestResults()) .extracting(TestResult::getDescription) .containsExactlyInAnyOrder( expected, expected ); } @Issue("238") @Test void shouldNotFailOnComments() { final AllureResults results = runStories("stories/comment.story"); assertThat(results.getTestResults()) .extracting(TestResult::getName, TestResult::getStatus) .containsExactlyInAnyOrder( tuple("Add a to b", Status.PASSED) ); } @Test void shouldProcessNotImplementedScenario() { final AllureResults results = runStories("stories/undefined.story"); assertThat(results.getTestResults()) .extracting(TestResult::getName, TestResult::getStatus) .containsExactlyInAnyOrder( tuple("Step is not implemented", null) ); } @Issue("145") @SuppressWarnings("unchecked") @Test void shouldAddParametersFromExamples() { final AllureResults results = runStories("stories/examples.story"); final List<TestResult> testResults = results.getTestResults(); assertThat(testResults) .hasSize(2); assertThat(testResults) .flatExtracting(TestResult::getParameters) .extracting(Parameter::getName, Parameter::getValue) .containsExactlyInAnyOrder( tuple("a", "1"), tuple("b", "3"), tuple("result", "4"), tuple("a", "2"), tuple("b", "4"), tuple("result", "6") ); } @Test void shouldRunMultiplyScenarios() { final AllureResults results = runStories("stories/multiply.story"); assertThat(results.getTestResults()) .extracting(TestResult::getName, TestResult::getStatus) .containsExactlyInAnyOrder( tuple("First", Status.PASSED), tuple("Second", Status.PASSED), tuple("Third", Status.PASSED) ); } @Issue("163") @Test void shouldNotFailIfGivenStoriesSpecified() { final AllureResults results = runStories("stories/given.story"); assertThat(results.getTestResults()) .extracting(TestResult::getName, TestResult::getStatus) .containsExactly(tuple("Add a to b", Status.PASSED)); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName) .containsExactly( "Given a is 5", "Given b is 10", "When I add a to b", "Then result is 15" ); } private AllureResults runStories(final String... storyResources) { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); final AllureLifecycle lifecycle = new AllureLifecycle(writer); final Embedder embedder = new Embedder(); embedder.useEmbedderMonitor(new NullEmbedderMonitor()); embedder.useEmbedderControls(new EmbedderControls() .doGenerateViewAfterStories(false) .doFailOnStoryTimeout(false) .doBatch(false) .doIgnoreFailureInStories(true) .doIgnoreFailureInView(true) .doVerboseFailures(false) .doVerboseFiltering(false) ); final AllureJbehave allureJbehave = new AllureJbehave(lifecycle); embedder.useConfiguration(new MostUsefulConfiguration() .useStoryLoader(new LoadFromClasspath(this.getClass())) .useStoryReporterBuilder(new ReportlessStoryReporterBuilder(temp.toFile()) .withReporters(allureJbehave) ) .useDefaultStoryReporter(new NullStoryReporter()) ); final InjectableStepsFactory stepsFactory = new InstanceStepsFactory( embedder.configuration(), new SimpleStorySteps(), new BrokenStorySteps() ); embedder.useCandidateSteps(stepsFactory.createCandidateSteps()); final AllureLifecycle cached = Allure.getLifecycle(); try { Allure.setLifecycle(lifecycle); embedder.runStoriesAsPaths(Arrays.asList(storyResources)); } finally { Allure.setLifecycle(cached); } return writer; } static class ReportlessStoryReporterBuilder extends StoryReporterBuilder { private final File outputDirectory; ReportlessStoryReporterBuilder(final File outputDirectory) { this.outputDirectory = outputDirectory; } @Override public File outputDirectory() { return outputDirectory; } } } <|start_filename|>allure-testng/src/test/java/io/qameta/allure/testng/samples/LinksOnTestsInherited.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testng.samples; import io.qameta.allure.Issue; import io.qameta.allure.Link; import io.qameta.allure.TmsLink; import org.testng.annotations.Test; /** * @author charlie (<NAME>). */ public class LinksOnTestsInherited extends LinksOnTests { @Override public void shouldHasLinks() throws Exception { super.shouldHasLinks(); } @Override @Test @Link("inheritedLink1") @Link("inheritedLink2") @Issue("inheritedIssue") @TmsLink("inheritedTmsLink") public void shouldHasLinksAsWell() throws Exception { super.shouldHasLinksAsWell(); } } <|start_filename|>allure-java-migration/src/test/java/io/qameta/allure/aspects/Allure1TestCaseAspectsTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.aspects; import io.qameta.allure.model.Label; import io.qameta.allure.model.Link; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureResults; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Issue; import ru.yandex.qatools.allure.annotations.Issues; import ru.yandex.qatools.allure.annotations.Parameter; import ru.yandex.qatools.allure.annotations.Severity; import ru.yandex.qatools.allure.annotations.Stories; import ru.yandex.qatools.allure.annotations.TestCaseId; import ru.yandex.qatools.allure.annotations.Title; import ru.yandex.qatools.allure.model.SeverityLevel; import java.util.stream.Stream; import static io.qameta.allure.test.RunUtils.runWithinTestContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; /** * eroshenkoam * 30.04.17 */ class Allure1TestCaseAspectsTest { static Stream<SimpleTest> testClassesProvider() { return Stream.of(new JunitTest(), new TestNgTest()); } @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessFeaturesAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLabels) .filteredOn(label -> label.getName().equals("feature")) .extracting(Label::getValue) .containsExactlyInAnyOrder("feature1", "feature2"); } @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessStoriesAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLabels) .filteredOn(label -> label.getName().equals("story")) .extracting(Label::getValue) .containsExactlyInAnyOrder("story1", "story2"); } @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessSeverityAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLabels) .filteredOn(label -> label.getName().equals("severity")) .extracting(Label::getValue) .containsExactlyInAnyOrder(SeverityLevel.CRITICAL.value()); } @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessIssuesAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLinks) .extracting(Link::getName) .containsExactlyInAnyOrder("ISSUE-1", "ISSUE-11", "ISSUE-2", "ISSUE-22", "TEST-1"); } @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessTitleAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getName) .containsExactlyInAnyOrder("testcase"); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLabels) .filteredOn(label -> label.getName().equals("suite")) .extracting(Label::getValue) .containsExactlyInAnyOrder("testsuite"); } @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessDescriptionAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getDescription) .containsExactlyInAnyOrder("testcase description"); } @SuppressWarnings("unchecked") @Issue("206") @ParameterizedTest @MethodSource("testClassesProvider") void shouldProcessParameterAnnotation(final SimpleTest simpleTest) { final AllureResults results = runWithinTestContext( simpleTest::testSomething, Allure1TestCaseAspects::setLifecycle, Allure1ParametersAspects::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getParameters) .extracting(io.qameta.allure.model.Parameter::getName, io.qameta.allure.model.Parameter::getValue) .containsExactlyInAnyOrder( tuple("parameterWithoutName", "testValue1"), tuple("customParameterName", "testValue2") ); } public interface SimpleTest { void testSomething(); } @Title("testsuite") @Issue("ISSUE-1") @Issues(@Issue("ISSUE-11")) @Stories("story1") @Features("feature1") public static class TestNgTest implements SimpleTest { @Parameter public String parameterWithoutName; @Parameter("customParameterName") private String parameterWithName; @Parameter private String uninitializedParameter; @Title("testcase") @Description("testcase description") @Issue("ISSUE-2") @Issues(@Issue("ISSUE-22")) @TestCaseId("TEST-1") @Stories("story2") @Features("feature2") @Severity(SeverityLevel.CRITICAL) @org.testng.annotations.Test public void testSomething() { parameterWithoutName = "testValue1"; parameterWithName = "testValue2"; } } @Title("testsuite") @Issue("ISSUE-1") @Issues(@Issue("ISSUE-11")) @Stories("story1") @Features("feature1") public static class JunitTest implements SimpleTest { @Parameter private String parameterWithoutName; @Parameter("customParameterName") private String parameterWithName; @Parameter private String uninitializedParameter; @Title("testcase") @Description("testcase description") @Issue("ISSUE-2") @Issues(@Issue("ISSUE-22")) @TestCaseId("TEST-1") @Stories("story2") @Features("feature2") @Severity(SeverityLevel.CRITICAL) @org.junit.Test public void testSomething() { parameterWithoutName = "testValue1"; parameterWithName = "testValue2"; } } } <|start_filename|>allure-java-commons-test/src/main/java/io/qameta/allure/test/RunUtils.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.test; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.aspects.AttachmentsAspects; import io.qameta.allure.aspects.StepsAspects; import io.qameta.allure.model.TestResult; import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Stream; import static io.qameta.allure.util.ResultsUtils.getStatus; import static io.qameta.allure.util.ResultsUtils.getStatusDetails; /** * @author charlie (<NAME>). */ public final class RunUtils { private RunUtils() { throw new IllegalStateException("do not instance"); } public static AllureResults runWithinTestContext(final Runnable runnable) { return runWithinTestContext( runnable, Allure::setLifecycle, StepsAspects::setLifecycle, AttachmentsAspects::setLifecycle ); } @SafeVarargs public static AllureResults runWithinTestContext(final Runnable runnable, final Consumer<AllureLifecycle>... configurers) { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); final AllureLifecycle lifecycle = new AllureLifecycle(writer); final String uuid = UUID.randomUUID().toString(); final TestResult result = new TestResult().setUuid(uuid); final AllureLifecycle cached = Allure.getLifecycle(); try { Stream.of(configurers).forEach(configurer -> configurer.accept(lifecycle)); lifecycle.scheduleTestCase(result); lifecycle.startTestCase(uuid); runnable.run(); } catch (Throwable e) { lifecycle.updateTestCase(uuid, testResult -> { getStatus(e).ifPresent(testResult::setStatus); getStatusDetails(e).ifPresent(testResult::setStatusDetails); }); } finally { lifecycle.stopTestCase(uuid); lifecycle.writeTestCase(uuid); Stream.of(configurers).forEach(configurer -> configurer.accept(cached)); } return writer; } } <|start_filename|>allure-attachments/src/test/java/io/qameta/allure/attachment/DefaultAttachmentProcessorTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.attachment; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.attachment.http.HttpRequestAttachment; import io.qameta.allure.test.AllureFeatures; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import static io.qameta.allure.attachment.testdata.TestData.randomAttachmentContent; import static io.qameta.allure.attachment.testdata.TestData.randomHttpRequestAttachment; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author charlie (<NAME>). */ class DefaultAttachmentProcessorTest { @SuppressWarnings("unchecked") @AllureFeatures.Attachments @Test void shouldProcessAttachments() { final HttpRequestAttachment attachment = randomHttpRequestAttachment(); final AllureLifecycle lifecycle = mock(AllureLifecycle.class); final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class); final AttachmentContent content = randomAttachmentContent(); doReturn(content) .when(renderer) .render(attachment); new DefaultAttachmentProcessor(lifecycle) .addAttachment(attachment, renderer); verify(renderer, times(1)).render(attachment); verify(lifecycle, times(1)) .addAttachment( eq(attachment.getName()), eq(content.getContentType()), eq(content.getFileExtension()), eq(content.getContent().getBytes(StandardCharsets.UTF_8)) ); } } <|start_filename|>allure-jsonunit/src/main/java/io/qameta/allure/jsonunit/JsonPatchMatcher.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jsonunit; import io.qameta.allure.attachment.DefaultAttachmentProcessor; import io.qameta.allure.attachment.FreemarkerAttachmentRenderer; import net.javacrumbs.jsonunit.core.listener.DifferenceListener; import org.hamcrest.Description; /** * JsonPatchMatcher is extension of JsonUnit matcher, * that generates pretty html attachment for differences. * * @param <T> the type */ @SuppressWarnings("unused") public final class JsonPatchMatcher<T> extends AbstractJsonPatchMatcher<AllureConfigurableJsonMatcher<T>> implements AllureConfigurableJsonMatcher<T> { private final Object expected; private JsonPatchMatcher(final Object expected) { this.expected = expected; } public static <T> AllureConfigurableJsonMatcher<T> jsonEquals(final Object expected) { return new JsonPatchMatcher<T>(expected); } @Override public boolean matches(final Object actual) { super.withDifferenceListener(new JsonPatchListener()); return super.matches(expected, actual); } @Override public void describeTo(final Description description) { description.appendText("has no difference"); } @Override public void describeMismatch(final Object item, final Description description) { description.appendText(super.getDifferences()); } @SuppressWarnings("deprecation") @Override public void _dont_implement_Matcher___instead_extend_BaseMatcher_() { //do nothing } @Override protected void render(final DifferenceListener listener) { final JsonPatchListener jsonDiffListener = (JsonPatchListener) listener; final DiffAttachment attachment = new DiffAttachment(jsonDiffListener.getDiffModel()); new DefaultAttachmentProcessor().addAttachment(attachment, new FreemarkerAttachmentRenderer("diff.ftl")); } } <|start_filename|>allure-okhttp3/src/test/java/io/qameta/allure/okhttp3/AllureOkHttp3Test.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.okhttp3; import com.github.tomakehurst.wiremock.WireMockServer; import io.qameta.allure.model.Attachment; import io.qameta.allure.model.TestResult; import io.qameta.allure.test.AllureResults; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Stream; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static io.qameta.allure.test.RunUtils.runWithinTestContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** * @author charlie (<NAME>). */ class AllureOkHttp3Test { private static final String BODY_STRING = "Hello world!"; private WireMockServer server; @BeforeEach void setUp() { server = new WireMockServer(options().dynamicPort()); server.start(); configureFor(server.port()); stubFor(get(urlEqualTo("/hello")) .willReturn(aResponse() .withBody(BODY_STRING))); } @AfterEach void tearDown() { if (Objects.nonNull(server)) { server.stop(); } } @Test void shouldCreateRequestAttachment() { final Request request = new Request.Builder() .url(server.url("hello")) .build(); final AllureResults results = execute(request, checkBody(BODY_STRING)); assertThat(results.getTestResults()) .flatExtracting(TestResult::getAttachments) .extracting(Attachment::getName) .contains("Request"); } @Test void shouldCreateResponseAttachment() { final Request request = new Request.Builder() .url(server.url("hello")) .build(); final AllureResults results = execute(request, checkBody(BODY_STRING)); assertThat(results.getTestResults()) .flatExtracting(TestResult::getAttachments) .extracting(Attachment::getName) .contains("Response"); } @SafeVarargs protected final AllureResults execute(final Request request, final Consumer<Response>... matchers) { final OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new AllureOkHttp3()) .build(); return runWithinTestContext(() -> { try { final Response response = client.newCall(request).execute(); Stream.of(matchers).forEach(matcher -> matcher.accept(response)); } catch (IOException e) { throw new RuntimeException("Could not execute request " + request, e); } }); } protected Consumer<Response> checkBody(final String expectedBody) { return response -> { try { final ResponseBody body = response.body(); if (Objects.isNull(body)) { fail("empty response body"); } assertThat(body.string()).isEqualTo(expectedBody); } catch (IOException e) { fail("could not read response body"); } }; } } <|start_filename|>allure-jsonunit/src/test/java/io/qameta/allure/jsonunit/JsonPatchListenerTest.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.jsonunit; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import net.javacrumbs.jsonunit.core.Configuration; import net.javacrumbs.jsonunit.core.Option; import net.javacrumbs.jsonunit.core.internal.Diff; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class JsonPatchListenerTest { private final JsonPatchListener listener = new JsonPatchListener(); @Test void shouldSeeEmptyDiffNodes() { Diff diff = Diff.create("{}", "{}", "", "", commonConfig()); diff.similar(); assertThat(listener.getDifferences()) .isEmpty(); } @Test void shouldSeeRemovedNode() { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()) .isEqualTo("{\"test\":[\"1\",0,0]}"); } @Test void shouldSeeAddedNode() { Diff diff = Diff.create("{}", "{\"test\": \"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[\"1\"]}"); } @Test void shouldSeeEmptyForCheckAnyNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.ignore}\"}", "{\"test\":\"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); } @Test void shouldSeeEmptyForCheckAnyBooleanNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.any-boolean}\"}", "{\"test\": true}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); } @Test void shouldSeeEmptyForCheckAnyNumberNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.any-number}\"}", "{\"test\": 11}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); } @Test void shouldSeeEmptyForCheckAnyStringNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.any-string}\"}", "{\"test\": \"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); } @Test void shouldSeeChangedStringNode() { Diff diff = Diff.create("{\"test\": \"1\"}", "{\"test\": \"2\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[\"1\",\"2\"]}"); } @Test void shouldSeeChangedNumberNode() { Diff diff = Diff.create("{\"test\": 1}", "{\"test\": 2 }", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[1,2]}"); } @Test void shouldSeeChangedBooleanNode() { Diff diff = Diff.create("{\"test\": true}", "{\"test\": false}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[true,false]}"); } @Test void shouldSeeChangedStructureNode() { Diff diff = Diff.create("{\"test\": \"1\"}", "{\"test\": false}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[\"1\",false]}"); } @Test void shouldSeeChangedArrayNode() { Diff diff = Diff.create("[1, 1]", "[1, 2]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"1\":[1,2],\"_t\":\"a\"}"); } @Test void shouldSeeRemovedArrayNode() { Diff diff = Diff.create("[1, 2]", "[1]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"1\":[2,0,0],\"_t\":\"a\"}"); } @Test void shouldSeeAddedArrayNode() { Diff diff = Diff.create("[1]", "[1, 2]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"1\":[2],\"_t\":\"a\"}"); } @Test void shouldSeeObjectDiffNodes() { Diff diff = Diff.create("{\"test\": { \"test1\": \"1\"}}", "{\"test\": { \"test1\": \"2\"} }", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":{\"test1\":[\"1\",\"2\"]}}"); } @Test void shouldSeeNullNode() { Diff diff = Diff.create(null, null, "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); } @Test void shouldWorkWhenIgnoringArrayOrder() { Diff diff = Diff.create("{\"test\": [[1,2],[2,3]]}", "{\"test\":[[4,2],[1,2]]}", "", "", commonConfig().when(Option.IGNORING_ARRAY_ORDER)); diff.similar(); assertThat(listener.getJsonPatch()). isEqualTo("{\"test\":{\"0\":{\"0\":[3,4],\"_t\":\"a\"},\"_t\":\"a\"}}"); } @Test void shouldSeeActualSource() throws JsonProcessingException { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(new ObjectMapper().writeValueAsString(listener.getContext().getActualSource())).isEqualTo("{}"); } @Test void shouldSeeExpectedSource() throws JsonProcessingException { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(new ObjectMapper().writeValueAsString(listener.getContext().getExpectedSource())).isEqualTo("{\"test\":\"1\"}"); } @Test void shouldSeeNodeChangeToArray() { Diff diff = Diff.create("{\"test\": \"1\"}", "[[1,2],[2,3],[1,1]]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("[{\"test\":\"1\"},[[1,2],[2,3],[1,1]]]"); } @Test void shouldArrayChangeToNode() { Diff diff = Diff.create("[[1,2],[2,3],[1,1]]", "{\"test\": \"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("[[[1,2],[2,3],[1,1]],{\"test\":\"1\"}]"); } @Test void shouldSeeDiffModel() { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); DiffModel model = listener.getDiffModel(); assertThat(model.getExpected()).isEqualTo("{\"test\":\"1\"}"); assertThat(model.getActual()).isEqualTo("{}"); assertThat(model.getPatch()).isEqualTo("{\"test\":[\"1\",0,0]}"); } private Configuration commonConfig() { return Configuration.empty().withDifferenceListener(listener); } } <|start_filename|>allure-cucumber-jvm/src/test/java/io/qameta/allure/cucumberjvm/samples/SimpleFeatureSteps.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.cucumberjvm.samples; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author charlie (<NAME>). */ public class SimpleFeatureSteps { private int a; private int b; private int c; @Given("^a is (\\d+)$") public void a_is(int arg1) { this.a = arg1; } @Given("^b is (\\d+)$") public void b_is(int arg1) { this.b = arg1; } @When("^I add a to b$") public void i_add_a_to_b() { this.c = this.a + this.b; } @Then("^result is (\\d+)$") public void result_is(int arg1) { assertEquals(this.c, arg1); } } <|start_filename|>allure-java-migration/src/main/java/ru/yandex/qatools/allure/annotations/Parameter.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 ru.yandex.qatools.allure.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * You can use this annotation to add parameters to your tests: * <pre> * &#064;Parameter("My Param") * private String myParameter; * * &#064;Test * public void myTest() throws Exception { * myParameter = "first"; * myParameter = "second"; * myParameter = "third"; * } * </pre> * All three values will be added to report * * Note that the initializations of constant fields (static final fields * where the initializer is a constant string object or primitive value) * are not join points, since Java requires their references to be inlined. * * value - it's name of parameter, field name by default */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) public @interface Parameter { String value() default ""; } <|start_filename|>allure-testng/src/test/java/io/qameta/allure/testng/samples/TestsWithSteps.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.testng.samples; import org.testng.SkipException; import org.testng.annotations.Test; import static io.qameta.allure.Allure.step; import static org.assertj.core.api.Assertions.assertThat; /** * @author <NAME> <EMAIL> */ public class TestsWithSteps { @Test public void testWithOneStep() { step("Sample step one"); } @Test public void failingByAssertion() { step("Sample step one"); step("Failing step", () -> { assertThat(2).isEqualTo(1); }); } @Test public void skipped() { step("Sample step one"); step("skipThisTest", () -> { throw new SkipException("Skipped"); }); } @Test public void brokenTest() { step("Sample step one"); step("broken", () -> { throw new RuntimeException("Exception"); }); } @Test public void brokenTestWithoutMessage() { step("Sample step one"); step("brokenWithoutMessage", () -> { throw new RuntimeException(); }); } } <|start_filename|>allure-java-commons-test/src/main/java/io/qameta/allure/test/AllureResultsWriterStub.java<|end_filename|> /* * Copyright 2019 Qameta Software OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 io.qameta.allure.test; import io.qameta.allure.AllureResultsWriter; import io.qameta.allure.model.TestResult; import io.qameta.allure.model.TestResultContainer; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** * @author <NAME> <EMAIL> */ @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") public class AllureResultsWriterStub implements AllureResultsWriter, AllureResults { private final List<TestResult> testResults = new CopyOnWriteArrayList<>(); private final List<TestResultContainer> testContainers = new CopyOnWriteArrayList<>(); private final Map<String, byte[]> attachments = new ConcurrentHashMap<>(); @Override public void write(final TestResult testResult) { testResults.add(testResult); } @Override public void write(final TestResultContainer testResultContainer) { testContainers.add(testResultContainer); } @Override public void write(final String source, final InputStream attachment) { try { final byte[] bytes = IOUtils.toByteArray(attachment); attachments.put(source, bytes); } catch (IOException e) { throw new RuntimeException("Could not read attachment content " + source, e); } } @Override public List<TestResult> getTestResults() { return testResults; } @Override public List<TestResultContainer> getTestResultContainers() { return testContainers; } @Override public Map<String, byte[]> getAttachments() { return attachments; } }
lilyYumakaeva/allure-java
<|start_filename|>site/fields/color/package.json<|end_filename|> { "name": "color", "description": "Kirby Color Picker Field", "author": "<NAME>", "license": "MIT", "version": "1.3.0", "type": "kirby-field" } <|start_filename|>kirby/vendor/erusev/parsedown-extra/test/data/compound_footnote.html<|end_filename|> <p>footnote <sup id="fnref1:1"><a href="#fn:1" class="footnote-ref">1</a></sup> and another one <sup id="fnref1:2"><a href="#fn:2" class="footnote-ref">2</a></sup></p> <div class="footnotes"> <hr /> <ol> <li id="fn:1"> <p>line 1 line 2</p> <blockquote> <p>quote</p> </blockquote> <p>another paragraph&#160;<a href="#fnref1:1" rev="footnote" class="footnote-backref">&#8617;</a></p> </li> <li id="fn:2"> <p>paragraph</p> <p>another paragraph&#160;<a href="#fnref1:2" rev="footnote" class="footnote-backref">&#8617;</a></p> </li> </ol> </div> <|start_filename|>kirby/vendor/erusev/parsedown-extra/test/data/markdown_inside_markup.html<|end_filename|> <div class="example"> <p><em>markdown</em></p> <p>This is another paragraph. It contains <em>inline markup</em>.</p> <div> _no markdown_ </div> </div> <hr /> <div> <p><em>markdown</em></p> <div> <p><em>markdown</em></p> </div> </div> <hr /> <div> _no markdown_ <div> <p><em>markdown</em></p> </div> </div> <hr /> <div markdown="0"> _no markdown_ </div>
thecamp-toolbox/poc_program_online
<|start_filename|>proto/core/contract/witness_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/witness_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type WitnessCreateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Url []byte `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"` } func (x *WitnessCreateContract) Reset() { *x = WitnessCreateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_witness_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WitnessCreateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*WitnessCreateContract) ProtoMessage() {} func (x *WitnessCreateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_witness_contract_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 WitnessCreateContract.ProtoReflect.Descriptor instead. func (*WitnessCreateContract) Descriptor() ([]byte, []int) { return file_core_contract_witness_contract_proto_rawDescGZIP(), []int{0} } func (x *WitnessCreateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *WitnessCreateContract) GetUrl() []byte { if x != nil { return x.Url } return nil } type WitnessUpdateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` UpdateUrl []byte `protobuf:"bytes,12,opt,name=update_url,json=updateUrl,proto3" json:"update_url,omitempty"` } func (x *WitnessUpdateContract) Reset() { *x = WitnessUpdateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_witness_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WitnessUpdateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*WitnessUpdateContract) ProtoMessage() {} func (x *WitnessUpdateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_witness_contract_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 WitnessUpdateContract.ProtoReflect.Descriptor instead. func (*WitnessUpdateContract) Descriptor() ([]byte, []int) { return file_core_contract_witness_contract_proto_rawDescGZIP(), []int{1} } func (x *WitnessUpdateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *WitnessUpdateContract) GetUpdateUrl() []byte { if x != nil { return x.UpdateUrl } return nil } type VoteWitnessContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Votes []*VoteWitnessContract_Vote `protobuf:"bytes,2,rep,name=votes,proto3" json:"votes,omitempty"` Support bool `protobuf:"varint,3,opt,name=support,proto3" json:"support,omitempty"` } func (x *VoteWitnessContract) Reset() { *x = VoteWitnessContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_witness_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *VoteWitnessContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*VoteWitnessContract) ProtoMessage() {} func (x *VoteWitnessContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_witness_contract_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 VoteWitnessContract.ProtoReflect.Descriptor instead. func (*VoteWitnessContract) Descriptor() ([]byte, []int) { return file_core_contract_witness_contract_proto_rawDescGZIP(), []int{2} } func (x *VoteWitnessContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *VoteWitnessContract) GetVotes() []*VoteWitnessContract_Vote { if x != nil { return x.Votes } return nil } func (x *VoteWitnessContract) GetSupport() bool { if x != nil { return x.Support } return false } type VoteWitnessContract_Vote struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields VoteAddress []byte `protobuf:"bytes,1,opt,name=vote_address,json=voteAddress,proto3" json:"vote_address,omitempty"` VoteCount int64 `protobuf:"varint,2,opt,name=vote_count,json=voteCount,proto3" json:"vote_count,omitempty"` } func (x *VoteWitnessContract_Vote) Reset() { *x = VoteWitnessContract_Vote{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_witness_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *VoteWitnessContract_Vote) String() string { return protoimpl.X.MessageStringOf(x) } func (*VoteWitnessContract_Vote) ProtoMessage() {} func (x *VoteWitnessContract_Vote) ProtoReflect() protoreflect.Message { mi := &file_core_contract_witness_contract_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 VoteWitnessContract_Vote.ProtoReflect.Descriptor instead. func (*VoteWitnessContract_Vote) Descriptor() ([]byte, []int) { return file_core_contract_witness_contract_proto_rawDescGZIP(), []int{2, 0} } func (x *VoteWitnessContract_Vote) GetVoteAddress() []byte { if x != nil { return x.VoteAddress } return nil } func (x *VoteWitnessContract_Vote) GetVoteCount() int64 { if x != nil { return x.VoteCount } return 0 } var File_core_contract_witness_contract_proto protoreflect.FileDescriptor var file_core_contract_witness_contract_proto_rawDesc = []byte{ 0x0a, 0x24, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x4e, 0x0a, 0x15, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x22, 0x5b, 0x0a, 0x15, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x55, 0x72, 0x6c, 0x22, 0xd8, 0x01, 0x0a, 0x13, 0x56, 0x6f, 0x74, 0x65, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x38, 0x0a, 0x05, 0x76, 0x6f, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x74, 0x65, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x56, 0x6f, 0x74, 0x65, 0x52, 0x05, 0x76, 0x6f, 0x74, 0x65, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x1a, 0x48, 0x0a, 0x04, 0x56, 0x6f, 0x74, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x76, 0x6f, 0x74, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x76, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_witness_contract_proto_rawDescOnce sync.Once file_core_contract_witness_contract_proto_rawDescData = file_core_contract_witness_contract_proto_rawDesc ) func file_core_contract_witness_contract_proto_rawDescGZIP() []byte { file_core_contract_witness_contract_proto_rawDescOnce.Do(func() { file_core_contract_witness_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_witness_contract_proto_rawDescData) }) return file_core_contract_witness_contract_proto_rawDescData } var file_core_contract_witness_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_core_contract_witness_contract_proto_goTypes = []interface{}{ (*WitnessCreateContract)(nil), // 0: protocol.WitnessCreateContract (*WitnessUpdateContract)(nil), // 1: protocol.WitnessUpdateContract (*VoteWitnessContract)(nil), // 2: protocol.VoteWitnessContract (*VoteWitnessContract_Vote)(nil), // 3: protocol.VoteWitnessContract.Vote } var file_core_contract_witness_contract_proto_depIdxs = []int32{ 3, // 0: protocol.VoteWitnessContract.votes:type_name -> protocol.VoteWitnessContract.Vote 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_core_contract_witness_contract_proto_init() } func file_core_contract_witness_contract_proto_init() { if File_core_contract_witness_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_witness_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WitnessCreateContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_witness_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WitnessUpdateContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_witness_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*VoteWitnessContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_witness_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*VoteWitnessContract_Vote); 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_core_contract_witness_contract_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_witness_contract_proto_goTypes, DependencyIndexes: file_core_contract_witness_contract_proto_depIdxs, MessageInfos: file_core_contract_witness_contract_proto_msgTypes, }.Build() File_core_contract_witness_contract_proto = out.File file_core_contract_witness_contract_proto_rawDesc = nil file_core_contract_witness_contract_proto_goTypes = nil file_core_contract_witness_contract_proto_depIdxs = nil } <|start_filename|>proto/api/zksnark.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: api/zksnark.proto package api import ( context "context" core "github.com/bytejedi/tron-sdk-go/proto/core" proto "github.com/golang/protobuf/proto" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type ZksnarkResponse_Code int32 const ( ZksnarkResponse_SUCCESS ZksnarkResponse_Code = 0 ZksnarkResponse_FAILED ZksnarkResponse_Code = 1 ) // Enum value maps for ZksnarkResponse_Code. var ( ZksnarkResponse_Code_name = map[int32]string{ 0: "SUCCESS", 1: "FAILED", } ZksnarkResponse_Code_value = map[string]int32{ "SUCCESS": 0, "FAILED": 1, } ) func (x ZksnarkResponse_Code) Enum() *ZksnarkResponse_Code { p := new(ZksnarkResponse_Code) *p = x return p } func (x ZksnarkResponse_Code) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ZksnarkResponse_Code) Descriptor() protoreflect.EnumDescriptor { return file_api_zksnark_proto_enumTypes[0].Descriptor() } func (ZksnarkResponse_Code) Type() protoreflect.EnumType { return &file_api_zksnark_proto_enumTypes[0] } func (x ZksnarkResponse_Code) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ZksnarkResponse_Code.Descriptor instead. func (ZksnarkResponse_Code) EnumDescriptor() ([]byte, []int) { return file_api_zksnark_proto_rawDescGZIP(), []int{1, 0} } type ZksnarkRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Transaction *core.Transaction `protobuf:"bytes,1,opt,name=transaction,proto3" json:"transaction,omitempty"` Sighash []byte `protobuf:"bytes,2,opt,name=sighash,proto3" json:"sighash,omitempty"` ValueBalance int64 `protobuf:"varint,3,opt,name=valueBalance,proto3" json:"valueBalance,omitempty"` TxId string `protobuf:"bytes,4,opt,name=txId,proto3" json:"txId,omitempty"` } func (x *ZksnarkRequest) Reset() { *x = ZksnarkRequest{} if protoimpl.UnsafeEnabled { mi := &file_api_zksnark_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ZksnarkRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ZksnarkRequest) ProtoMessage() {} func (x *ZksnarkRequest) ProtoReflect() protoreflect.Message { mi := &file_api_zksnark_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 ZksnarkRequest.ProtoReflect.Descriptor instead. func (*ZksnarkRequest) Descriptor() ([]byte, []int) { return file_api_zksnark_proto_rawDescGZIP(), []int{0} } func (x *ZksnarkRequest) GetTransaction() *core.Transaction { if x != nil { return x.Transaction } return nil } func (x *ZksnarkRequest) GetSighash() []byte { if x != nil { return x.Sighash } return nil } func (x *ZksnarkRequest) GetValueBalance() int64 { if x != nil { return x.ValueBalance } return 0 } func (x *ZksnarkRequest) GetTxId() string { if x != nil { return x.TxId } return "" } type ZksnarkResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Code ZksnarkResponse_Code `protobuf:"varint,1,opt,name=code,proto3,enum=protocol.ZksnarkResponse_Code" json:"code,omitempty"` } func (x *ZksnarkResponse) Reset() { *x = ZksnarkResponse{} if protoimpl.UnsafeEnabled { mi := &file_api_zksnark_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ZksnarkResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ZksnarkResponse) ProtoMessage() {} func (x *ZksnarkResponse) ProtoReflect() protoreflect.Message { mi := &file_api_zksnark_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 ZksnarkResponse.ProtoReflect.Descriptor instead. func (*ZksnarkResponse) Descriptor() ([]byte, []int) { return file_api_zksnark_proto_rawDescGZIP(), []int{1} } func (x *ZksnarkResponse) GetCode() ZksnarkResponse_Code { if x != nil { return x.Code } return ZksnarkResponse_SUCCESS } var File_api_zksnark_proto protoreflect.FileDescriptor var file_api_zksnark_proto_rawDesc = []byte{ 0x0a, 0x11, 0x61, 0x70, 0x69, 0x2f, 0x7a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x1a, 0x0f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x54, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9b, 0x01, 0x0a, 0x0e, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x37, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 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, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x69, 0x67, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x69, 0x67, 0x68, 0x61, 0x73, 0x68, 0x12, 0x22, 0x0a, 0x0c, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x78, 0x49, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x78, 0x49, 0x64, 0x22, 0x66, 0x0a, 0x0f, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x1f, 0x0a, 0x04, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x55, 0x43, 0x43, 0x45, 0x53, 0x53, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x41, 0x49, 0x4c, 0x45, 0x44, 0x10, 0x01, 0x32, 0x59, 0x0a, 0x0b, 0x54, 0x72, 0x6f, 0x6e, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x12, 0x4a, 0x0a, 0x11, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x12, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x19, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x49, 0x0a, 0x0c, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x61, 0x70, 0x69, 0x42, 0x0e, 0x5a, 0x6b, 0x73, 0x6e, 0x61, 0x72, 0x6b, 0x47, 0x72, 0x70, 0x63, 0x41, 0x50, 0x49, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_api_zksnark_proto_rawDescOnce sync.Once file_api_zksnark_proto_rawDescData = file_api_zksnark_proto_rawDesc ) func file_api_zksnark_proto_rawDescGZIP() []byte { file_api_zksnark_proto_rawDescOnce.Do(func() { file_api_zksnark_proto_rawDescData = protoimpl.X.CompressGZIP(file_api_zksnark_proto_rawDescData) }) return file_api_zksnark_proto_rawDescData } var file_api_zksnark_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_api_zksnark_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_api_zksnark_proto_goTypes = []interface{}{ (ZksnarkResponse_Code)(0), // 0: protocol.ZksnarkResponse.Code (*ZksnarkRequest)(nil), // 1: protocol.ZksnarkRequest (*ZksnarkResponse)(nil), // 2: protocol.ZksnarkResponse (*core.Transaction)(nil), // 3: protocol.Transaction } var file_api_zksnark_proto_depIdxs = []int32{ 3, // 0: protocol.ZksnarkRequest.transaction:type_name -> protocol.Transaction 0, // 1: protocol.ZksnarkResponse.code:type_name -> protocol.ZksnarkResponse.Code 1, // 2: protocol.TronZksnark.CheckZksnarkProof:input_type -> protocol.ZksnarkRequest 2, // 3: protocol.TronZksnark.CheckZksnarkProof:output_type -> protocol.ZksnarkResponse 3, // [3:4] is the sub-list for method output_type 2, // [2:3] 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_api_zksnark_proto_init() } func file_api_zksnark_proto_init() { if File_api_zksnark_proto != nil { return } if !protoimpl.UnsafeEnabled { file_api_zksnark_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ZksnarkRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_api_zksnark_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ZksnarkResponse); 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_api_zksnark_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 1, }, GoTypes: file_api_zksnark_proto_goTypes, DependencyIndexes: file_api_zksnark_proto_depIdxs, EnumInfos: file_api_zksnark_proto_enumTypes, MessageInfos: file_api_zksnark_proto_msgTypes, }.Build() File_api_zksnark_proto = out.File file_api_zksnark_proto_rawDesc = nil file_api_zksnark_proto_goTypes = nil file_api_zksnark_proto_depIdxs = nil } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // 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.SupportPackageIsVersion6 // TronZksnarkClient is the client API for TronZksnark service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type TronZksnarkClient interface { CheckZksnarkProof(ctx context.Context, in *ZksnarkRequest, opts ...grpc.CallOption) (*ZksnarkResponse, error) } type tronZksnarkClient struct { cc grpc.ClientConnInterface } func NewTronZksnarkClient(cc grpc.ClientConnInterface) TronZksnarkClient { return &tronZksnarkClient{cc} } func (c *tronZksnarkClient) CheckZksnarkProof(ctx context.Context, in *ZksnarkRequest, opts ...grpc.CallOption) (*ZksnarkResponse, error) { out := new(ZksnarkResponse) err := c.cc.Invoke(ctx, "/protocol.TronZksnark/CheckZksnarkProof", in, out, opts...) if err != nil { return nil, err } return out, nil } // TronZksnarkServer is the server API for TronZksnark service. type TronZksnarkServer interface { CheckZksnarkProof(context.Context, *ZksnarkRequest) (*ZksnarkResponse, error) } // UnimplementedTronZksnarkServer can be embedded to have forward compatible implementations. type UnimplementedTronZksnarkServer struct { } func (*UnimplementedTronZksnarkServer) CheckZksnarkProof(context.Context, *ZksnarkRequest) (*ZksnarkResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckZksnarkProof not implemented") } func RegisterTronZksnarkServer(s *grpc.Server, srv TronZksnarkServer) { s.RegisterService(&_TronZksnark_serviceDesc, srv) } func _TronZksnark_CheckZksnarkProof_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ZksnarkRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TronZksnarkServer).CheckZksnarkProof(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/protocol.TronZksnark/CheckZksnarkProof", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TronZksnarkServer).CheckZksnarkProof(ctx, req.(*ZksnarkRequest)) } return interceptor(ctx, in, info, handler) } var _TronZksnark_serviceDesc = grpc.ServiceDesc{ ServiceName: "protocol.TronZksnark", HandlerType: (*TronZksnarkServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "CheckZksnarkProof", Handler: _TronZksnark_CheckZksnarkProof_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "api/zksnark.proto", } <|start_filename|>proto/core/contract/smart_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/smart_contract.proto package contract import ( _ "github.com/bytejedi/tron-sdk-go/proto/core" proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type SmartContract_ABI_Entry_EntryType int32 const ( SmartContract_ABI_Entry_UnknownEntryType SmartContract_ABI_Entry_EntryType = 0 SmartContract_ABI_Entry_Constructor SmartContract_ABI_Entry_EntryType = 1 SmartContract_ABI_Entry_Function SmartContract_ABI_Entry_EntryType = 2 SmartContract_ABI_Entry_Event SmartContract_ABI_Entry_EntryType = 3 SmartContract_ABI_Entry_Fallback SmartContract_ABI_Entry_EntryType = 4 ) // Enum value maps for SmartContract_ABI_Entry_EntryType. var ( SmartContract_ABI_Entry_EntryType_name = map[int32]string{ 0: "UnknownEntryType", 1: "Constructor", 2: "Function", 3: "Event", 4: "Fallback", } SmartContract_ABI_Entry_EntryType_value = map[string]int32{ "UnknownEntryType": 0, "Constructor": 1, "Function": 2, "Event": 3, "Fallback": 4, } ) func (x SmartContract_ABI_Entry_EntryType) Enum() *SmartContract_ABI_Entry_EntryType { p := new(SmartContract_ABI_Entry_EntryType) *p = x return p } func (x SmartContract_ABI_Entry_EntryType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SmartContract_ABI_Entry_EntryType) Descriptor() protoreflect.EnumDescriptor { return file_core_contract_smart_contract_proto_enumTypes[0].Descriptor() } func (SmartContract_ABI_Entry_EntryType) Type() protoreflect.EnumType { return &file_core_contract_smart_contract_proto_enumTypes[0] } func (x SmartContract_ABI_Entry_EntryType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use SmartContract_ABI_Entry_EntryType.Descriptor instead. func (SmartContract_ABI_Entry_EntryType) EnumDescriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{0, 0, 0, 0} } type SmartContract_ABI_Entry_StateMutabilityType int32 const ( SmartContract_ABI_Entry_UnknownMutabilityType SmartContract_ABI_Entry_StateMutabilityType = 0 SmartContract_ABI_Entry_Pure SmartContract_ABI_Entry_StateMutabilityType = 1 SmartContract_ABI_Entry_View SmartContract_ABI_Entry_StateMutabilityType = 2 SmartContract_ABI_Entry_Nonpayable SmartContract_ABI_Entry_StateMutabilityType = 3 SmartContract_ABI_Entry_Payable SmartContract_ABI_Entry_StateMutabilityType = 4 ) // Enum value maps for SmartContract_ABI_Entry_StateMutabilityType. var ( SmartContract_ABI_Entry_StateMutabilityType_name = map[int32]string{ 0: "UnknownMutabilityType", 1: "Pure", 2: "View", 3: "Nonpayable", 4: "Payable", } SmartContract_ABI_Entry_StateMutabilityType_value = map[string]int32{ "UnknownMutabilityType": 0, "Pure": 1, "View": 2, "Nonpayable": 3, "Payable": 4, } ) func (x SmartContract_ABI_Entry_StateMutabilityType) Enum() *SmartContract_ABI_Entry_StateMutabilityType { p := new(SmartContract_ABI_Entry_StateMutabilityType) *p = x return p } func (x SmartContract_ABI_Entry_StateMutabilityType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SmartContract_ABI_Entry_StateMutabilityType) Descriptor() protoreflect.EnumDescriptor { return file_core_contract_smart_contract_proto_enumTypes[1].Descriptor() } func (SmartContract_ABI_Entry_StateMutabilityType) Type() protoreflect.EnumType { return &file_core_contract_smart_contract_proto_enumTypes[1] } func (x SmartContract_ABI_Entry_StateMutabilityType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use SmartContract_ABI_Entry_StateMutabilityType.Descriptor instead. func (SmartContract_ABI_Entry_StateMutabilityType) EnumDescriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{0, 0, 0, 1} } type SmartContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OriginAddress []byte `protobuf:"bytes,1,opt,name=origin_address,json=originAddress,proto3" json:"origin_address,omitempty"` ContractAddress []byte `protobuf:"bytes,2,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` Abi *SmartContract_ABI `protobuf:"bytes,3,opt,name=abi,proto3" json:"abi,omitempty"` Bytecode []byte `protobuf:"bytes,4,opt,name=bytecode,proto3" json:"bytecode,omitempty"` CallValue int64 `protobuf:"varint,5,opt,name=call_value,json=callValue,proto3" json:"call_value,omitempty"` ConsumeUserResourcePercent int64 `protobuf:"varint,6,opt,name=consume_user_resource_percent,json=consumeUserResourcePercent,proto3" json:"consume_user_resource_percent,omitempty"` Name string `protobuf:"bytes,7,opt,name=name,proto3" json:"name,omitempty"` OriginEnergyLimit int64 `protobuf:"varint,8,opt,name=origin_energy_limit,json=originEnergyLimit,proto3" json:"origin_energy_limit,omitempty"` CodeHash []byte `protobuf:"bytes,9,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` TrxHash []byte `protobuf:"bytes,10,opt,name=trx_hash,json=trxHash,proto3" json:"trx_hash,omitempty"` } func (x *SmartContract) Reset() { *x = SmartContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmartContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmartContract) ProtoMessage() {} func (x *SmartContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 SmartContract.ProtoReflect.Descriptor instead. func (*SmartContract) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{0} } func (x *SmartContract) GetOriginAddress() []byte { if x != nil { return x.OriginAddress } return nil } func (x *SmartContract) GetContractAddress() []byte { if x != nil { return x.ContractAddress } return nil } func (x *SmartContract) GetAbi() *SmartContract_ABI { if x != nil { return x.Abi } return nil } func (x *SmartContract) GetBytecode() []byte { if x != nil { return x.Bytecode } return nil } func (x *SmartContract) GetCallValue() int64 { if x != nil { return x.CallValue } return 0 } func (x *SmartContract) GetConsumeUserResourcePercent() int64 { if x != nil { return x.ConsumeUserResourcePercent } return 0 } func (x *SmartContract) GetName() string { if x != nil { return x.Name } return "" } func (x *SmartContract) GetOriginEnergyLimit() int64 { if x != nil { return x.OriginEnergyLimit } return 0 } func (x *SmartContract) GetCodeHash() []byte { if x != nil { return x.CodeHash } return nil } func (x *SmartContract) GetTrxHash() []byte { if x != nil { return x.TrxHash } return nil } type CreateSmartContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` NewContract *SmartContract `protobuf:"bytes,2,opt,name=new_contract,json=newContract,proto3" json:"new_contract,omitempty"` CallTokenValue int64 `protobuf:"varint,3,opt,name=call_token_value,json=callTokenValue,proto3" json:"call_token_value,omitempty"` TokenId int64 `protobuf:"varint,4,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` } func (x *CreateSmartContract) Reset() { *x = CreateSmartContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CreateSmartContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*CreateSmartContract) ProtoMessage() {} func (x *CreateSmartContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 CreateSmartContract.ProtoReflect.Descriptor instead. func (*CreateSmartContract) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{1} } func (x *CreateSmartContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *CreateSmartContract) GetNewContract() *SmartContract { if x != nil { return x.NewContract } return nil } func (x *CreateSmartContract) GetCallTokenValue() int64 { if x != nil { return x.CallTokenValue } return 0 } func (x *CreateSmartContract) GetTokenId() int64 { if x != nil { return x.TokenId } return 0 } type TriggerSmartContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ContractAddress []byte `protobuf:"bytes,2,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` CallValue int64 `protobuf:"varint,3,opt,name=call_value,json=callValue,proto3" json:"call_value,omitempty"` Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` CallTokenValue int64 `protobuf:"varint,5,opt,name=call_token_value,json=callTokenValue,proto3" json:"call_token_value,omitempty"` TokenId int64 `protobuf:"varint,6,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` } func (x *TriggerSmartContract) Reset() { *x = TriggerSmartContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TriggerSmartContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*TriggerSmartContract) ProtoMessage() {} func (x *TriggerSmartContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 TriggerSmartContract.ProtoReflect.Descriptor instead. func (*TriggerSmartContract) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{2} } func (x *TriggerSmartContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *TriggerSmartContract) GetContractAddress() []byte { if x != nil { return x.ContractAddress } return nil } func (x *TriggerSmartContract) GetCallValue() int64 { if x != nil { return x.CallValue } return 0 } func (x *TriggerSmartContract) GetData() []byte { if x != nil { return x.Data } return nil } func (x *TriggerSmartContract) GetCallTokenValue() int64 { if x != nil { return x.CallTokenValue } return 0 } func (x *TriggerSmartContract) GetTokenId() int64 { if x != nil { return x.TokenId } return 0 } type ClearABIContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ContractAddress []byte `protobuf:"bytes,2,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` } func (x *ClearABIContract) Reset() { *x = ClearABIContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClearABIContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClearABIContract) ProtoMessage() {} func (x *ClearABIContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 ClearABIContract.ProtoReflect.Descriptor instead. func (*ClearABIContract) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{3} } func (x *ClearABIContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ClearABIContract) GetContractAddress() []byte { if x != nil { return x.ContractAddress } return nil } type UpdateSettingContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ContractAddress []byte `protobuf:"bytes,2,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` ConsumeUserResourcePercent int64 `protobuf:"varint,3,opt,name=consume_user_resource_percent,json=consumeUserResourcePercent,proto3" json:"consume_user_resource_percent,omitempty"` } func (x *UpdateSettingContract) Reset() { *x = UpdateSettingContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UpdateSettingContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdateSettingContract) ProtoMessage() {} func (x *UpdateSettingContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 UpdateSettingContract.ProtoReflect.Descriptor instead. func (*UpdateSettingContract) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{4} } func (x *UpdateSettingContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *UpdateSettingContract) GetContractAddress() []byte { if x != nil { return x.ContractAddress } return nil } func (x *UpdateSettingContract) GetConsumeUserResourcePercent() int64 { if x != nil { return x.ConsumeUserResourcePercent } return 0 } type UpdateEnergyLimitContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ContractAddress []byte `protobuf:"bytes,2,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` OriginEnergyLimit int64 `protobuf:"varint,3,opt,name=origin_energy_limit,json=originEnergyLimit,proto3" json:"origin_energy_limit,omitempty"` } func (x *UpdateEnergyLimitContract) Reset() { *x = UpdateEnergyLimitContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UpdateEnergyLimitContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdateEnergyLimitContract) ProtoMessage() {} func (x *UpdateEnergyLimitContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 UpdateEnergyLimitContract.ProtoReflect.Descriptor instead. func (*UpdateEnergyLimitContract) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{5} } func (x *UpdateEnergyLimitContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *UpdateEnergyLimitContract) GetContractAddress() []byte { if x != nil { return x.ContractAddress } return nil } func (x *UpdateEnergyLimitContract) GetOriginEnergyLimit() int64 { if x != nil { return x.OriginEnergyLimit } return 0 } type SmartContract_ABI struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Entrys []*SmartContract_ABI_Entry `protobuf:"bytes,1,rep,name=entrys,proto3" json:"entrys,omitempty"` } func (x *SmartContract_ABI) Reset() { *x = SmartContract_ABI{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmartContract_ABI) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmartContract_ABI) ProtoMessage() {} func (x *SmartContract_ABI) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 SmartContract_ABI.ProtoReflect.Descriptor instead. func (*SmartContract_ABI) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{0, 0} } func (x *SmartContract_ABI) GetEntrys() []*SmartContract_ABI_Entry { if x != nil { return x.Entrys } return nil } type SmartContract_ABI_Entry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Anonymous bool `protobuf:"varint,1,opt,name=anonymous,proto3" json:"anonymous,omitempty"` Constant bool `protobuf:"varint,2,opt,name=constant,proto3" json:"constant,omitempty"` Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` Inputs []*SmartContract_ABI_Entry_Param `protobuf:"bytes,4,rep,name=inputs,proto3" json:"inputs,omitempty"` Outputs []*SmartContract_ABI_Entry_Param `protobuf:"bytes,5,rep,name=outputs,proto3" json:"outputs,omitempty"` Type SmartContract_ABI_Entry_EntryType `protobuf:"varint,6,opt,name=type,proto3,enum=protocol.SmartContract_ABI_Entry_EntryType" json:"type,omitempty"` Payable bool `protobuf:"varint,7,opt,name=payable,proto3" json:"payable,omitempty"` StateMutability SmartContract_ABI_Entry_StateMutabilityType `protobuf:"varint,8,opt,name=stateMutability,proto3,enum=protocol.SmartContract_ABI_Entry_StateMutabilityType" json:"stateMutability,omitempty"` } func (x *SmartContract_ABI_Entry) Reset() { *x = SmartContract_ABI_Entry{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmartContract_ABI_Entry) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmartContract_ABI_Entry) ProtoMessage() {} func (x *SmartContract_ABI_Entry) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 SmartContract_ABI_Entry.ProtoReflect.Descriptor instead. func (*SmartContract_ABI_Entry) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{0, 0, 0} } func (x *SmartContract_ABI_Entry) GetAnonymous() bool { if x != nil { return x.Anonymous } return false } func (x *SmartContract_ABI_Entry) GetConstant() bool { if x != nil { return x.Constant } return false } func (x *SmartContract_ABI_Entry) GetName() string { if x != nil { return x.Name } return "" } func (x *SmartContract_ABI_Entry) GetInputs() []*SmartContract_ABI_Entry_Param { if x != nil { return x.Inputs } return nil } func (x *SmartContract_ABI_Entry) GetOutputs() []*SmartContract_ABI_Entry_Param { if x != nil { return x.Outputs } return nil } func (x *SmartContract_ABI_Entry) GetType() SmartContract_ABI_Entry_EntryType { if x != nil { return x.Type } return SmartContract_ABI_Entry_UnknownEntryType } func (x *SmartContract_ABI_Entry) GetPayable() bool { if x != nil { return x.Payable } return false } func (x *SmartContract_ABI_Entry) GetStateMutability() SmartContract_ABI_Entry_StateMutabilityType { if x != nil { return x.StateMutability } return SmartContract_ABI_Entry_UnknownMutabilityType } type SmartContract_ABI_Entry_Param struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Indexed bool `protobuf:"varint,1,opt,name=indexed,proto3" json:"indexed,omitempty"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` // SolidityType type = 3; } func (x *SmartContract_ABI_Entry_Param) Reset() { *x = SmartContract_ABI_Entry_Param{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_smart_contract_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmartContract_ABI_Entry_Param) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmartContract_ABI_Entry_Param) ProtoMessage() {} func (x *SmartContract_ABI_Entry_Param) ProtoReflect() protoreflect.Message { mi := &file_core_contract_smart_contract_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 SmartContract_ABI_Entry_Param.ProtoReflect.Descriptor instead. func (*SmartContract_ABI_Entry_Param) Descriptor() ([]byte, []int) { return file_core_contract_smart_contract_proto_rawDescGZIP(), []int{0, 0, 0, 0} } func (x *SmartContract_ABI_Entry_Param) GetIndexed() bool { if x != nil { return x.Indexed } return false } func (x *SmartContract_ABI_Entry_Param) GetName() string { if x != nil { return x.Name } return "" } func (x *SmartContract_ABI_Entry_Param) GetType() string { if x != nil { return x.Type } return "" } var File_core_contract_smart_contract_proto protoreflect.FileDescriptor var file_core_contract_smart_contract_proto_rawDesc = []byte{ 0x0a, 0x22, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x1a, 0x0f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x54, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xee, 0x08, 0x0a, 0x0d, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x25, 0x0a, 0x0e, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2d, 0x0a, 0x03, 0x61, 0x62, 0x69, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x41, 0x42, 0x49, 0x52, 0x03, 0x61, 0x62, 0x69, 0x12, 0x1a, 0x0a, 0x08, 0x62, 0x79, 0x74, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x62, 0x79, 0x74, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x63, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x41, 0x0a, 0x1d, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1a, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x2e, 0x0a, 0x13, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6f, 0x64, 0x65, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x63, 0x6f, 0x64, 0x65, 0x48, 0x61, 0x73, 0x68, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x78, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x78, 0x48, 0x61, 0x73, 0x68, 0x1a, 0xe1, 0x05, 0x0a, 0x03, 0x41, 0x42, 0x49, 0x12, 0x39, 0x0a, 0x06, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x41, 0x42, 0x49, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x73, 0x1a, 0x9e, 0x05, 0x0a, 0x05, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x6e, 0x6f, 0x6e, 0x79, 0x6d, 0x6f, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x61, 0x6e, 0x6f, 0x6e, 0x79, 0x6d, 0x6f, 0x75, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x06, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x41, 0x42, 0x49, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x52, 0x06, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x12, 0x41, 0x0a, 0x07, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x41, 0x42, 0x49, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x52, 0x07, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x73, 0x12, 0x3f, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x41, 0x42, 0x49, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x70, 0x61, 0x79, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x5f, 0x0a, 0x0f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x4d, 0x75, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x35, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x41, 0x42, 0x49, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x4d, 0x75, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x4d, 0x75, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x1a, 0x49, 0x0a, 0x05, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x12, 0x18, 0x0a, 0x07, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x65, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x22, 0x59, 0x0a, 0x09, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x10, 0x00, 0x12, 0x0f, 0x0a, 0x0b, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x6f, 0x72, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x46, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x10, 0x03, 0x12, 0x0c, 0x0a, 0x08, 0x46, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x10, 0x04, 0x22, 0x61, 0x0a, 0x13, 0x53, 0x74, 0x61, 0x74, 0x65, 0x4d, 0x75, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x12, 0x19, 0x0a, 0x15, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x4d, 0x75, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x54, 0x79, 0x70, 0x65, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x50, 0x75, 0x72, 0x65, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x56, 0x69, 0x65, 0x77, 0x10, 0x02, 0x12, 0x0e, 0x0a, 0x0a, 0x4e, 0x6f, 0x6e, 0x70, 0x61, 0x79, 0x61, 0x62, 0x6c, 0x65, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x50, 0x61, 0x79, 0x61, 0x62, 0x6c, 0x65, 0x10, 0x04, 0x22, 0xbb, 0x01, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x3a, 0x0a, 0x0c, 0x6e, 0x65, 0x77, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x0b, 0x6e, 0x65, 0x77, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x28, 0x0a, 0x10, 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x63, 0x61, 0x6c, 0x6c, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x22, 0xde, 0x01, 0x0a, 0x14, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x63, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x12, 0x28, 0x0a, 0x10, 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x63, 0x61, 0x6c, 0x6c, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x22, 0x62, 0x0a, 0x10, 0x43, 0x6c, 0x65, 0x61, 0x72, 0x41, 0x42, 0x49, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0xaa, 0x01, 0x0a, 0x15, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x41, 0x0a, 0x1d, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1a, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x22, 0x9b, 0x01, 0x0a, 0x19, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_smart_contract_proto_rawDescOnce sync.Once file_core_contract_smart_contract_proto_rawDescData = file_core_contract_smart_contract_proto_rawDesc ) func file_core_contract_smart_contract_proto_rawDescGZIP() []byte { file_core_contract_smart_contract_proto_rawDescOnce.Do(func() { file_core_contract_smart_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_smart_contract_proto_rawDescData) }) return file_core_contract_smart_contract_proto_rawDescData } var file_core_contract_smart_contract_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_core_contract_smart_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_core_contract_smart_contract_proto_goTypes = []interface{}{ (SmartContract_ABI_Entry_EntryType)(0), // 0: protocol.SmartContract.ABI.Entry.EntryType (SmartContract_ABI_Entry_StateMutabilityType)(0), // 1: protocol.SmartContract.ABI.Entry.StateMutabilityType (*SmartContract)(nil), // 2: protocol.SmartContract (*CreateSmartContract)(nil), // 3: protocol.CreateSmartContract (*TriggerSmartContract)(nil), // 4: protocol.TriggerSmartContract (*ClearABIContract)(nil), // 5: protocol.ClearABIContract (*UpdateSettingContract)(nil), // 6: protocol.UpdateSettingContract (*UpdateEnergyLimitContract)(nil), // 7: protocol.UpdateEnergyLimitContract (*SmartContract_ABI)(nil), // 8: protocol.SmartContract.ABI (*SmartContract_ABI_Entry)(nil), // 9: protocol.SmartContract.ABI.Entry (*SmartContract_ABI_Entry_Param)(nil), // 10: protocol.SmartContract.ABI.Entry.Param } var file_core_contract_smart_contract_proto_depIdxs = []int32{ 8, // 0: protocol.SmartContract.abi:type_name -> protocol.SmartContract.ABI 2, // 1: protocol.CreateSmartContract.new_contract:type_name -> protocol.SmartContract 9, // 2: protocol.SmartContract.ABI.entrys:type_name -> protocol.SmartContract.ABI.Entry 10, // 3: protocol.SmartContract.ABI.Entry.inputs:type_name -> protocol.SmartContract.ABI.Entry.Param 10, // 4: protocol.SmartContract.ABI.Entry.outputs:type_name -> protocol.SmartContract.ABI.Entry.Param 0, // 5: protocol.SmartContract.ABI.Entry.type:type_name -> protocol.SmartContract.ABI.Entry.EntryType 1, // 6: protocol.SmartContract.ABI.Entry.stateMutability:type_name -> protocol.SmartContract.ABI.Entry.StateMutabilityType 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_core_contract_smart_contract_proto_init() } func file_core_contract_smart_contract_proto_init() { if File_core_contract_smart_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_smart_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmartContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CreateSmartContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TriggerSmartContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClearABIContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UpdateSettingContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UpdateEnergyLimitContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmartContract_ABI); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmartContract_ABI_Entry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_smart_contract_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmartContract_ABI_Entry_Param); 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_core_contract_smart_contract_proto_rawDesc, NumEnums: 2, NumMessages: 9, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_smart_contract_proto_goTypes, DependencyIndexes: file_core_contract_smart_contract_proto_depIdxs, EnumInfos: file_core_contract_smart_contract_proto_enumTypes, MessageInfos: file_core_contract_smart_contract_proto_msgTypes, }.Build() File_core_contract_smart_contract_proto = out.File file_core_contract_smart_contract_proto_rawDesc = nil file_core_contract_smart_contract_proto_goTypes = nil file_core_contract_smart_contract_proto_depIdxs = nil } <|start_filename|>proto/core/TronInventoryItems.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/TronInventoryItems.proto package core import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type InventoryItems struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Type int32 `protobuf:"varint,1,opt,name=type,proto3" json:"type,omitempty"` Items [][]byte `protobuf:"bytes,2,rep,name=items,proto3" json:"items,omitempty"` } func (x *InventoryItems) Reset() { *x = InventoryItems{} if protoimpl.UnsafeEnabled { mi := &file_core_TronInventoryItems_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *InventoryItems) String() string { return protoimpl.X.MessageStringOf(x) } func (*InventoryItems) ProtoMessage() {} func (x *InventoryItems) ProtoReflect() protoreflect.Message { mi := &file_core_TronInventoryItems_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 InventoryItems.ProtoReflect.Descriptor instead. func (*InventoryItems) Descriptor() ([]byte, []int) { return file_core_TronInventoryItems_proto_rawDescGZIP(), []int{0} } func (x *InventoryItems) GetType() int32 { if x != nil { return x.Type } return 0 } func (x *InventoryItems) GetItems() [][]byte { if x != nil { return x.Items } return nil } var File_core_TronInventoryItems_proto protoreflect.FileDescriptor var file_core_TronInventoryItems_proto_rawDesc = []byte{ 0x0a, 0x1d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x54, 0x72, 0x6f, 0x6e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x3a, 0x0a, 0x0e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x42, 0x51, 0x0a, 0x0f, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x42, 0x12, 0x54, 0x72, 0x6f, 0x6e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x5a, 0x2a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_TronInventoryItems_proto_rawDescOnce sync.Once file_core_TronInventoryItems_proto_rawDescData = file_core_TronInventoryItems_proto_rawDesc ) func file_core_TronInventoryItems_proto_rawDescGZIP() []byte { file_core_TronInventoryItems_proto_rawDescOnce.Do(func() { file_core_TronInventoryItems_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_TronInventoryItems_proto_rawDescData) }) return file_core_TronInventoryItems_proto_rawDescData } var file_core_TronInventoryItems_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_core_TronInventoryItems_proto_goTypes = []interface{}{ (*InventoryItems)(nil), // 0: protocol.InventoryItems } var file_core_TronInventoryItems_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_core_TronInventoryItems_proto_init() } func file_core_TronInventoryItems_proto_init() { if File_core_TronInventoryItems_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_TronInventoryItems_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*InventoryItems); 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_core_TronInventoryItems_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_TronInventoryItems_proto_goTypes, DependencyIndexes: file_core_TronInventoryItems_proto_depIdxs, MessageInfos: file_core_TronInventoryItems_proto_msgTypes, }.Build() File_core_TronInventoryItems_proto = out.File file_core_TronInventoryItems_proto_rawDesc = nil file_core_TronInventoryItems_proto_goTypes = nil file_core_TronInventoryItems_proto_depIdxs = nil } <|start_filename|>proto/core/contract/account_contract.pb.go<|end_filename|> // // java-tron 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. // // java-tron 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/>. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/account_contract.proto package contract import ( core "github.com/bytejedi/tron-sdk-go/proto/core" proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type AccountCreateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` AccountAddress []byte `protobuf:"bytes,2,opt,name=account_address,json=accountAddress,proto3" json:"account_address,omitempty"` Type core.AccountType `protobuf:"varint,3,opt,name=type,proto3,enum=protocol.AccountType" json:"type,omitempty"` } func (x *AccountCreateContract) Reset() { *x = AccountCreateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_account_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AccountCreateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*AccountCreateContract) ProtoMessage() {} func (x *AccountCreateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_account_contract_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 AccountCreateContract.ProtoReflect.Descriptor instead. func (*AccountCreateContract) Descriptor() ([]byte, []int) { return file_core_contract_account_contract_proto_rawDescGZIP(), []int{0} } func (x *AccountCreateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *AccountCreateContract) GetAccountAddress() []byte { if x != nil { return x.AccountAddress } return nil } func (x *AccountCreateContract) GetType() core.AccountType { if x != nil { return x.Type } return core.AccountType_Normal } // Update account name. Account name is not unique now. type AccountUpdateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AccountName []byte `protobuf:"bytes,1,opt,name=account_name,json=accountName,proto3" json:"account_name,omitempty"` OwnerAddress []byte `protobuf:"bytes,2,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` } func (x *AccountUpdateContract) Reset() { *x = AccountUpdateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_account_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AccountUpdateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*AccountUpdateContract) ProtoMessage() {} func (x *AccountUpdateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_account_contract_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 AccountUpdateContract.ProtoReflect.Descriptor instead. func (*AccountUpdateContract) Descriptor() ([]byte, []int) { return file_core_contract_account_contract_proto_rawDescGZIP(), []int{1} } func (x *AccountUpdateContract) GetAccountName() []byte { if x != nil { return x.AccountName } return nil } func (x *AccountUpdateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } // Set account id if the account has no id. Account id is unique and case insensitive. type SetAccountIdContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AccountId []byte `protobuf:"bytes,1,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"` OwnerAddress []byte `protobuf:"bytes,2,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` } func (x *SetAccountIdContract) Reset() { *x = SetAccountIdContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_account_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SetAccountIdContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*SetAccountIdContract) ProtoMessage() {} func (x *SetAccountIdContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_account_contract_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 SetAccountIdContract.ProtoReflect.Descriptor instead. func (*SetAccountIdContract) Descriptor() ([]byte, []int) { return file_core_contract_account_contract_proto_rawDescGZIP(), []int{2} } func (x *SetAccountIdContract) GetAccountId() []byte { if x != nil { return x.AccountId } return nil } func (x *SetAccountIdContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } type AccountPermissionUpdateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Owner *core.Permission `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` //Empty is invalidate Witness *core.Permission `protobuf:"bytes,3,opt,name=witness,proto3" json:"witness,omitempty"` //Can be empty Actives []*core.Permission `protobuf:"bytes,4,rep,name=actives,proto3" json:"actives,omitempty"` //Empty is invalidate } func (x *AccountPermissionUpdateContract) Reset() { *x = AccountPermissionUpdateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_account_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AccountPermissionUpdateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*AccountPermissionUpdateContract) ProtoMessage() {} func (x *AccountPermissionUpdateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_account_contract_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 AccountPermissionUpdateContract.ProtoReflect.Descriptor instead. func (*AccountPermissionUpdateContract) Descriptor() ([]byte, []int) { return file_core_contract_account_contract_proto_rawDescGZIP(), []int{3} } func (x *AccountPermissionUpdateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *AccountPermissionUpdateContract) GetOwner() *core.Permission { if x != nil { return x.Owner } return nil } func (x *AccountPermissionUpdateContract) GetWitness() *core.Permission { if x != nil { return x.Witness } return nil } func (x *AccountPermissionUpdateContract) GetActives() []*core.Permission { if x != nil { return x.Actives } return nil } var File_core_contract_account_contract_proto protoreflect.FileDescriptor var file_core_contract_account_contract_proto_rawDesc = []byte{ 0x0a, 0x24, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x1a, 0x0f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x54, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x90, 0x01, 0x0a, 0x15, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x29, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x22, 0x5f, 0x0a, 0x15, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x21, 0x0a, 0x0c, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x5a, 0x0a, 0x14, 0x53, 0x65, 0x74, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0xd2, 0x01, 0x0a, 0x1f, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2a, 0x0a, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x12, 0x2e, 0x0a, 0x07, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x12, 0x2e, 0x0a, 0x07, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x73, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_account_contract_proto_rawDescOnce sync.Once file_core_contract_account_contract_proto_rawDescData = file_core_contract_account_contract_proto_rawDesc ) func file_core_contract_account_contract_proto_rawDescGZIP() []byte { file_core_contract_account_contract_proto_rawDescOnce.Do(func() { file_core_contract_account_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_account_contract_proto_rawDescData) }) return file_core_contract_account_contract_proto_rawDescData } var file_core_contract_account_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_core_contract_account_contract_proto_goTypes = []interface{}{ (*AccountCreateContract)(nil), // 0: protocol.AccountCreateContract (*AccountUpdateContract)(nil), // 1: protocol.AccountUpdateContract (*SetAccountIdContract)(nil), // 2: protocol.SetAccountIdContract (*AccountPermissionUpdateContract)(nil), // 3: protocol.AccountPermissionUpdateContract (core.AccountType)(0), // 4: protocol.AccountType (*core.Permission)(nil), // 5: protocol.Permission } var file_core_contract_account_contract_proto_depIdxs = []int32{ 4, // 0: protocol.AccountCreateContract.type:type_name -> protocol.AccountType 5, // 1: protocol.AccountPermissionUpdateContract.owner:type_name -> protocol.Permission 5, // 2: protocol.AccountPermissionUpdateContract.witness:type_name -> protocol.Permission 5, // 3: protocol.AccountPermissionUpdateContract.actives:type_name -> protocol.Permission 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_core_contract_account_contract_proto_init() } func file_core_contract_account_contract_proto_init() { if File_core_contract_account_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_account_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AccountCreateContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_account_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AccountUpdateContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_account_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SetAccountIdContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_account_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AccountPermissionUpdateContract); 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_core_contract_account_contract_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_account_contract_proto_goTypes, DependencyIndexes: file_core_contract_account_contract_proto_depIdxs, MessageInfos: file_core_contract_account_contract_proto_msgTypes, }.Build() File_core_contract_account_contract_proto = out.File file_core_contract_account_contract_proto_rawDesc = nil file_core_contract_account_contract_proto_goTypes = nil file_core_contract_account_contract_proto_depIdxs = nil } <|start_filename|>proto/core/contract/balance_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/balance_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type FreezeBalanceContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` FrozenBalance int64 `protobuf:"varint,2,opt,name=frozen_balance,json=frozenBalance,proto3" json:"frozen_balance,omitempty"` FrozenDuration int64 `protobuf:"varint,3,opt,name=frozen_duration,json=frozenDuration,proto3" json:"frozen_duration,omitempty"` Resource ResourceCode `protobuf:"varint,10,opt,name=resource,proto3,enum=protocol.ResourceCode" json:"resource,omitempty"` ReceiverAddress []byte `protobuf:"bytes,15,opt,name=receiver_address,json=receiverAddress,proto3" json:"receiver_address,omitempty"` } func (x *FreezeBalanceContract) Reset() { *x = FreezeBalanceContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_balance_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *FreezeBalanceContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*FreezeBalanceContract) ProtoMessage() {} func (x *FreezeBalanceContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_balance_contract_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 FreezeBalanceContract.ProtoReflect.Descriptor instead. func (*FreezeBalanceContract) Descriptor() ([]byte, []int) { return file_core_contract_balance_contract_proto_rawDescGZIP(), []int{0} } func (x *FreezeBalanceContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *FreezeBalanceContract) GetFrozenBalance() int64 { if x != nil { return x.FrozenBalance } return 0 } func (x *FreezeBalanceContract) GetFrozenDuration() int64 { if x != nil { return x.FrozenDuration } return 0 } func (x *FreezeBalanceContract) GetResource() ResourceCode { if x != nil { return x.Resource } return ResourceCode_BANDWIDTH } func (x *FreezeBalanceContract) GetReceiverAddress() []byte { if x != nil { return x.ReceiverAddress } return nil } type UnfreezeBalanceContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Resource ResourceCode `protobuf:"varint,10,opt,name=resource,proto3,enum=protocol.ResourceCode" json:"resource,omitempty"` ReceiverAddress []byte `protobuf:"bytes,15,opt,name=receiver_address,json=receiverAddress,proto3" json:"receiver_address,omitempty"` } func (x *UnfreezeBalanceContract) Reset() { *x = UnfreezeBalanceContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_balance_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UnfreezeBalanceContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*UnfreezeBalanceContract) ProtoMessage() {} func (x *UnfreezeBalanceContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_balance_contract_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 UnfreezeBalanceContract.ProtoReflect.Descriptor instead. func (*UnfreezeBalanceContract) Descriptor() ([]byte, []int) { return file_core_contract_balance_contract_proto_rawDescGZIP(), []int{1} } func (x *UnfreezeBalanceContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *UnfreezeBalanceContract) GetResource() ResourceCode { if x != nil { return x.Resource } return ResourceCode_BANDWIDTH } func (x *UnfreezeBalanceContract) GetReceiverAddress() []byte { if x != nil { return x.ReceiverAddress } return nil } type WithdrawBalanceContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` } func (x *WithdrawBalanceContract) Reset() { *x = WithdrawBalanceContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_balance_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WithdrawBalanceContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*WithdrawBalanceContract) ProtoMessage() {} func (x *WithdrawBalanceContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_balance_contract_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 WithdrawBalanceContract.ProtoReflect.Descriptor instead. func (*WithdrawBalanceContract) Descriptor() ([]byte, []int) { return file_core_contract_balance_contract_proto_rawDescGZIP(), []int{2} } func (x *WithdrawBalanceContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } type TransferContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ToAddress []byte `protobuf:"bytes,2,opt,name=to_address,json=toAddress,proto3" json:"to_address,omitempty"` Amount int64 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` } func (x *TransferContract) Reset() { *x = TransferContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_balance_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransferContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransferContract) ProtoMessage() {} func (x *TransferContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_balance_contract_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 TransferContract.ProtoReflect.Descriptor instead. func (*TransferContract) Descriptor() ([]byte, []int) { return file_core_contract_balance_contract_proto_rawDescGZIP(), []int{3} } func (x *TransferContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *TransferContract) GetToAddress() []byte { if x != nil { return x.ToAddress } return nil } func (x *TransferContract) GetAmount() int64 { if x != nil { return x.Amount } return 0 } var File_core_contract_balance_contract_proto protoreflect.FileDescriptor var file_core_contract_balance_contract_proto_rawDesc = []byte{ 0x0a, 0x24, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x1a, 0x1a, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xeb, 0x01, 0x0a, 0x15, 0x46, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x32, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x9d, 0x01, 0x0a, 0x17, 0x55, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x32, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x3e, 0x0a, 0x17, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x6e, 0x0a, 0x10, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x74, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x74, 0x6f, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_balance_contract_proto_rawDescOnce sync.Once file_core_contract_balance_contract_proto_rawDescData = file_core_contract_balance_contract_proto_rawDesc ) func file_core_contract_balance_contract_proto_rawDescGZIP() []byte { file_core_contract_balance_contract_proto_rawDescOnce.Do(func() { file_core_contract_balance_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_balance_contract_proto_rawDescData) }) return file_core_contract_balance_contract_proto_rawDescData } var file_core_contract_balance_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_core_contract_balance_contract_proto_goTypes = []interface{}{ (*FreezeBalanceContract)(nil), // 0: protocol.FreezeBalanceContract (*UnfreezeBalanceContract)(nil), // 1: protocol.UnfreezeBalanceContract (*WithdrawBalanceContract)(nil), // 2: protocol.WithdrawBalanceContract (*TransferContract)(nil), // 3: protocol.TransferContract (ResourceCode)(0), // 4: protocol.ResourceCode } var file_core_contract_balance_contract_proto_depIdxs = []int32{ 4, // 0: protocol.FreezeBalanceContract.resource:type_name -> protocol.ResourceCode 4, // 1: protocol.UnfreezeBalanceContract.resource:type_name -> protocol.ResourceCode 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_core_contract_balance_contract_proto_init() } func file_core_contract_balance_contract_proto_init() { if File_core_contract_balance_contract_proto != nil { return } file_core_contract_common_proto_init() if !protoimpl.UnsafeEnabled { file_core_contract_balance_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*FreezeBalanceContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_balance_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UnfreezeBalanceContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_balance_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WithdrawBalanceContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_balance_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransferContract); 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_core_contract_balance_contract_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_balance_contract_proto_goTypes, DependencyIndexes: file_core_contract_balance_contract_proto_depIdxs, MessageInfos: file_core_contract_balance_contract_proto_msgTypes, }.Build() File_core_contract_balance_contract_proto = out.File file_core_contract_balance_contract_proto_rawDesc = nil file_core_contract_balance_contract_proto_goTypes = nil file_core_contract_balance_contract_proto_depIdxs = nil } <|start_filename|>abi/abi.go<|end_filename|> package abi import ( "encoding/json" "fmt" "math/big" "reflect" "strconv" "strings" "github.com/bytejedi/tron-sdk-go/keystore" ethabi "github.com/ethereum/go-ethereum/accounts/abi" ethcmn "github.com/ethereum/go-ethereum/common" "golang.org/x/crypto/sha3" ) // Param list type Param map[string]interface{} // loadFromJSON string into ABI data func loadFromJSON(jString string) ([]Param, error) { if len(jString) == 0 { return nil, nil } var data []Param err := json.Unmarshal([]byte(jString), &data) if err != nil { return nil, err } return data, nil } // Signature of a method func Signature(method string) []byte { // hash method hasher := sha3.NewLegacyKeccak256() hasher.Write([]byte(method)) b := hasher.Sum(nil) return b[:4] } func convetToAddress(v interface{}) (ethcmn.Address, error) { switch v.(type) { case string: addr, err := keystore.Base58ToAddress(v.(string)) if err != nil { return ethcmn.Address{}, fmt.Errorf("invalid address %s: %+v", v.(string), err) } return ethcmn.BytesToAddress(addr.Bytes()[len(addr.Bytes())-20:]), nil } return ethcmn.Address{}, fmt.Errorf("invalid address %v", v) } func convertToInt(ty ethabi.Type, v interface{}) interface{} { if ty.T == ethabi.IntTy && ty.Size <= 64 { tmp, _ := strconv.ParseInt(v.(string), 10, ty.Size) switch ty.Size { case 8: v = int8(tmp) case 16: v = int16(tmp) case 32: v = int32(tmp) case 64: v = tmp } } else if ty.T == ethabi.UintTy && ty.Size <= 64 { tmp, _ := strconv.ParseUint(v.(string), 10, ty.Size) switch ty.Size { case 8: v = uint8(tmp) case 16: v = uint16(tmp) case 32: v = uint32(tmp) case 64: v = tmp } } else { v, _ = new(big.Int).SetString(v.(string), 10) } return v } // getPaddedParam return padded params bytes func getPaddedParam(method *ethabi.Method, param []Param) ([]byte, error) { values := make([]interface{}, 0) for _, p := range param { if len(p) != 1 { return nil, fmt.Errorf("invalid param %+v", p) } for k, v := range p { if k == "uint" { k = "uint256" } else if strings.HasPrefix(k, "uint[") { k = strings.Replace(k, "uint[", "uint256[", 1) } ty, err := ethabi.NewType(k, "", nil) if err != nil { return nil, fmt.Errorf("invalid param %+v: %+v", p, err) } if ty.T == ethabi.SliceTy || ty.T == ethabi.ArrayTy { if ty.Elem.T == ethabi.AddressTy { tmp := v.([]interface{}) v = make([]ethcmn.Address, 0) for i := range tmp { addr, err := convetToAddress(tmp[i]) if err != nil { return nil, err } v = append(v.([]ethcmn.Address), addr) } } if (ty.Elem.T == ethabi.IntTy || ty.Elem.T == ethabi.UintTy) && reflect.TypeOf(v).Elem().Kind() == reflect.Interface { if ty.Elem.Size > 64 { tmp := make([]*big.Int, 0) for _, i := range v.([]interface{}) { if s, ok := i.(string); ok { value, _ := new(big.Int).SetString(s, 10) tmp = append(tmp, value) } else { return nil, fmt.Errorf("abi: cannot use %T as type string as argument", i) } } v = tmp } else { tmpI := make([]interface{}, 0) for _, i := range v.([]interface{}) { if s, ok := i.(string); ok { value, err := strconv.ParseUint(s, 10, ty.Elem.Size) if err != nil { return nil, err } tmpI = append(tmpI, value) } else { return nil, fmt.Errorf("abi: cannot use %T as type string as argument", i) } } switch ty.Elem.Size { case 8: tmp := make([]uint8, len(tmpI)) for i, sv := range tmpI { tmp[i] = uint8(sv.(uint64)) } v = tmp case 16: tmp := make([]uint16, len(tmpI)) for i, sv := range tmpI { tmp[i] = uint16(sv.(uint64)) } v = tmp case 32: tmp := make([]uint32, len(tmpI)) for i, sv := range tmpI { tmp[i] = uint32(sv.(uint64)) } v = tmp case 64: tmp := make([]uint64, len(tmpI)) for i, sv := range tmpI { tmp[i] = sv.(uint64) } v = tmp } } } } if ty.T == ethabi.AddressTy { if v, err = convetToAddress(v); err != nil { return nil, err } } if (ty.T == ethabi.IntTy || ty.T == ethabi.UintTy) && reflect.TypeOf(v).Kind() == reflect.String { v = convertToInt(ty, v) } values = append(values, v) } } // convert params to bytes return method.Inputs.PackValues(values) } // Pack data into bytes func Pack(method *ethabi.Method, paramsJson string) ([]byte, error) { params, err := loadFromJSON(paramsJson) if err != nil { return nil, err } bz, err := getPaddedParam(method, params) if err != nil { return nil, err } return append(method.ID, bz...), nil } // DecodeOutputs unpack outputs data func DecodeOutputs(method *ethabi.Method, outputs []byte) (interface{}, error) { res, err := method.Outputs.UnpackValues(outputs) if err != nil { return string(outputs), nil } return res, nil } <|start_filename|>proto/core/contract/proposal_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/proposal_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type ProposalApproveContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ProposalId int64 `protobuf:"varint,2,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` IsAddApproval bool `protobuf:"varint,3,opt,name=is_add_approval,json=isAddApproval,proto3" json:"is_add_approval,omitempty"` // add or remove approval } func (x *ProposalApproveContract) Reset() { *x = ProposalApproveContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_proposal_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ProposalApproveContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ProposalApproveContract) ProtoMessage() {} func (x *ProposalApproveContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_proposal_contract_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 ProposalApproveContract.ProtoReflect.Descriptor instead. func (*ProposalApproveContract) Descriptor() ([]byte, []int) { return file_core_contract_proposal_contract_proto_rawDescGZIP(), []int{0} } func (x *ProposalApproveContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ProposalApproveContract) GetProposalId() int64 { if x != nil { return x.ProposalId } return 0 } func (x *ProposalApproveContract) GetIsAddApproval() bool { if x != nil { return x.IsAddApproval } return false } type ProposalCreateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Parameters map[int64]int64 `protobuf:"bytes,2,rep,name=parameters,proto3" json:"parameters,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` } func (x *ProposalCreateContract) Reset() { *x = ProposalCreateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_proposal_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ProposalCreateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ProposalCreateContract) ProtoMessage() {} func (x *ProposalCreateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_proposal_contract_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 ProposalCreateContract.ProtoReflect.Descriptor instead. func (*ProposalCreateContract) Descriptor() ([]byte, []int) { return file_core_contract_proposal_contract_proto_rawDescGZIP(), []int{1} } func (x *ProposalCreateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ProposalCreateContract) GetParameters() map[int64]int64 { if x != nil { return x.Parameters } return nil } type ProposalDeleteContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ProposalId int64 `protobuf:"varint,2,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` } func (x *ProposalDeleteContract) Reset() { *x = ProposalDeleteContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_proposal_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ProposalDeleteContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ProposalDeleteContract) ProtoMessage() {} func (x *ProposalDeleteContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_proposal_contract_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 ProposalDeleteContract.ProtoReflect.Descriptor instead. func (*ProposalDeleteContract) Descriptor() ([]byte, []int) { return file_core_contract_proposal_contract_proto_rawDescGZIP(), []int{2} } func (x *ProposalDeleteContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ProposalDeleteContract) GetProposalId() int64 { if x != nil { return x.ProposalId } return 0 } var File_core_contract_proposal_contract_proto protoreflect.FileDescriptor var file_core_contract_proposal_contract_proto_rawDesc = []byte{ 0x0a, 0x25, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x87, 0x01, 0x0a, 0x17, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x41, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x26, 0x0a, 0x0f, 0x69, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x5f, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x61, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x69, 0x73, 0x41, 0x64, 0x64, 0x41, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x61, 0x6c, 0x22, 0xce, 0x01, 0x0a, 0x16, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x50, 0x0a, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x1a, 0x3d, 0x0a, 0x0f, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x5e, 0x0a, 0x16, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x49, 0x64, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_proposal_contract_proto_rawDescOnce sync.Once file_core_contract_proposal_contract_proto_rawDescData = file_core_contract_proposal_contract_proto_rawDesc ) func file_core_contract_proposal_contract_proto_rawDescGZIP() []byte { file_core_contract_proposal_contract_proto_rawDescOnce.Do(func() { file_core_contract_proposal_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_proposal_contract_proto_rawDescData) }) return file_core_contract_proposal_contract_proto_rawDescData } var file_core_contract_proposal_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_core_contract_proposal_contract_proto_goTypes = []interface{}{ (*ProposalApproveContract)(nil), // 0: protocol.ProposalApproveContract (*ProposalCreateContract)(nil), // 1: protocol.ProposalCreateContract (*ProposalDeleteContract)(nil), // 2: protocol.ProposalDeleteContract nil, // 3: protocol.ProposalCreateContract.ParametersEntry } var file_core_contract_proposal_contract_proto_depIdxs = []int32{ 3, // 0: protocol.ProposalCreateContract.parameters:type_name -> protocol.ProposalCreateContract.ParametersEntry 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_core_contract_proposal_contract_proto_init() } func file_core_contract_proposal_contract_proto_init() { if File_core_contract_proposal_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_proposal_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ProposalApproveContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_proposal_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ProposalCreateContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_proposal_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ProposalDeleteContract); 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_core_contract_proposal_contract_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_proposal_contract_proto_goTypes, DependencyIndexes: file_core_contract_proposal_contract_proto_depIdxs, MessageInfos: file_core_contract_proposal_contract_proto_msgTypes, }.Build() File_core_contract_proposal_contract_proto = out.File file_core_contract_proposal_contract_proto_rawDesc = nil file_core_contract_proposal_contract_proto_goTypes = nil file_core_contract_proposal_contract_proto_depIdxs = nil } <|start_filename|>proto/core/contract/asset_issue_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/asset_issue_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type AssetIssueContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Id string `protobuf:"bytes,41,opt,name=id,proto3" json:"id,omitempty"` OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Name []byte `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` Abbr []byte `protobuf:"bytes,3,opt,name=abbr,proto3" json:"abbr,omitempty"` TotalSupply int64 `protobuf:"varint,4,opt,name=total_supply,json=totalSupply,proto3" json:"total_supply,omitempty"` FrozenSupply []*AssetIssueContract_FrozenSupply `protobuf:"bytes,5,rep,name=frozen_supply,json=frozenSupply,proto3" json:"frozen_supply,omitempty"` TrxNum int32 `protobuf:"varint,6,opt,name=trx_num,json=trxNum,proto3" json:"trx_num,omitempty"` Precision int32 `protobuf:"varint,7,opt,name=precision,proto3" json:"precision,omitempty"` Num int32 `protobuf:"varint,8,opt,name=num,proto3" json:"num,omitempty"` StartTime int64 `protobuf:"varint,9,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` EndTime int64 `protobuf:"varint,10,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` Order int64 `protobuf:"varint,11,opt,name=order,proto3" json:"order,omitempty"` // useless VoteScore int32 `protobuf:"varint,16,opt,name=vote_score,json=voteScore,proto3" json:"vote_score,omitempty"` Description []byte `protobuf:"bytes,20,opt,name=description,proto3" json:"description,omitempty"` Url []byte `protobuf:"bytes,21,opt,name=url,proto3" json:"url,omitempty"` FreeAssetNetLimit int64 `protobuf:"varint,22,opt,name=free_asset_net_limit,json=freeAssetNetLimit,proto3" json:"free_asset_net_limit,omitempty"` PublicFreeAssetNetLimit int64 `protobuf:"varint,23,opt,name=public_free_asset_net_limit,json=publicFreeAssetNetLimit,proto3" json:"public_free_asset_net_limit,omitempty"` PublicFreeAssetNetUsage int64 `protobuf:"varint,24,opt,name=public_free_asset_net_usage,json=publicFreeAssetNetUsage,proto3" json:"public_free_asset_net_usage,omitempty"` PublicLatestFreeNetTime int64 `protobuf:"varint,25,opt,name=public_latest_free_net_time,json=publicLatestFreeNetTime,proto3" json:"public_latest_free_net_time,omitempty"` } func (x *AssetIssueContract) Reset() { *x = AssetIssueContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_asset_issue_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AssetIssueContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*AssetIssueContract) ProtoMessage() {} func (x *AssetIssueContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_asset_issue_contract_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 AssetIssueContract.ProtoReflect.Descriptor instead. func (*AssetIssueContract) Descriptor() ([]byte, []int) { return file_core_contract_asset_issue_contract_proto_rawDescGZIP(), []int{0} } func (x *AssetIssueContract) GetId() string { if x != nil { return x.Id } return "" } func (x *AssetIssueContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *AssetIssueContract) GetName() []byte { if x != nil { return x.Name } return nil } func (x *AssetIssueContract) GetAbbr() []byte { if x != nil { return x.Abbr } return nil } func (x *AssetIssueContract) GetTotalSupply() int64 { if x != nil { return x.TotalSupply } return 0 } func (x *AssetIssueContract) GetFrozenSupply() []*AssetIssueContract_FrozenSupply { if x != nil { return x.FrozenSupply } return nil } func (x *AssetIssueContract) GetTrxNum() int32 { if x != nil { return x.TrxNum } return 0 } func (x *AssetIssueContract) GetPrecision() int32 { if x != nil { return x.Precision } return 0 } func (x *AssetIssueContract) GetNum() int32 { if x != nil { return x.Num } return 0 } func (x *AssetIssueContract) GetStartTime() int64 { if x != nil { return x.StartTime } return 0 } func (x *AssetIssueContract) GetEndTime() int64 { if x != nil { return x.EndTime } return 0 } func (x *AssetIssueContract) GetOrder() int64 { if x != nil { return x.Order } return 0 } func (x *AssetIssueContract) GetVoteScore() int32 { if x != nil { return x.VoteScore } return 0 } func (x *AssetIssueContract) GetDescription() []byte { if x != nil { return x.Description } return nil } func (x *AssetIssueContract) GetUrl() []byte { if x != nil { return x.Url } return nil } func (x *AssetIssueContract) GetFreeAssetNetLimit() int64 { if x != nil { return x.FreeAssetNetLimit } return 0 } func (x *AssetIssueContract) GetPublicFreeAssetNetLimit() int64 { if x != nil { return x.PublicFreeAssetNetLimit } return 0 } func (x *AssetIssueContract) GetPublicFreeAssetNetUsage() int64 { if x != nil { return x.PublicFreeAssetNetUsage } return 0 } func (x *AssetIssueContract) GetPublicLatestFreeNetTime() int64 { if x != nil { return x.PublicLatestFreeNetTime } return 0 } type TransferAssetContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AssetName []byte `protobuf:"bytes,1,opt,name=asset_name,json=assetName,proto3" json:"asset_name,omitempty"` // this field is token name before the proposal ALLOW_SAME_TOKEN_NAME is active, otherwise it is token id and token is should be in string format. OwnerAddress []byte `protobuf:"bytes,2,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ToAddress []byte `protobuf:"bytes,3,opt,name=to_address,json=toAddress,proto3" json:"to_address,omitempty"` Amount int64 `protobuf:"varint,4,opt,name=amount,proto3" json:"amount,omitempty"` } func (x *TransferAssetContract) Reset() { *x = TransferAssetContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_asset_issue_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransferAssetContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransferAssetContract) ProtoMessage() {} func (x *TransferAssetContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_asset_issue_contract_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 TransferAssetContract.ProtoReflect.Descriptor instead. func (*TransferAssetContract) Descriptor() ([]byte, []int) { return file_core_contract_asset_issue_contract_proto_rawDescGZIP(), []int{1} } func (x *TransferAssetContract) GetAssetName() []byte { if x != nil { return x.AssetName } return nil } func (x *TransferAssetContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *TransferAssetContract) GetToAddress() []byte { if x != nil { return x.ToAddress } return nil } func (x *TransferAssetContract) GetAmount() int64 { if x != nil { return x.Amount } return 0 } type UnfreezeAssetContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` } func (x *UnfreezeAssetContract) Reset() { *x = UnfreezeAssetContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_asset_issue_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UnfreezeAssetContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*UnfreezeAssetContract) ProtoMessage() {} func (x *UnfreezeAssetContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_asset_issue_contract_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 UnfreezeAssetContract.ProtoReflect.Descriptor instead. func (*UnfreezeAssetContract) Descriptor() ([]byte, []int) { return file_core_contract_asset_issue_contract_proto_rawDescGZIP(), []int{2} } func (x *UnfreezeAssetContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } type UpdateAssetContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Description []byte `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` Url []byte `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` NewLimit int64 `protobuf:"varint,4,opt,name=new_limit,json=newLimit,proto3" json:"new_limit,omitempty"` NewPublicLimit int64 `protobuf:"varint,5,opt,name=new_public_limit,json=newPublicLimit,proto3" json:"new_public_limit,omitempty"` } func (x *UpdateAssetContract) Reset() { *x = UpdateAssetContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_asset_issue_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UpdateAssetContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdateAssetContract) ProtoMessage() {} func (x *UpdateAssetContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_asset_issue_contract_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 UpdateAssetContract.ProtoReflect.Descriptor instead. func (*UpdateAssetContract) Descriptor() ([]byte, []int) { return file_core_contract_asset_issue_contract_proto_rawDescGZIP(), []int{3} } func (x *UpdateAssetContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *UpdateAssetContract) GetDescription() []byte { if x != nil { return x.Description } return nil } func (x *UpdateAssetContract) GetUrl() []byte { if x != nil { return x.Url } return nil } func (x *UpdateAssetContract) GetNewLimit() int64 { if x != nil { return x.NewLimit } return 0 } func (x *UpdateAssetContract) GetNewPublicLimit() int64 { if x != nil { return x.NewPublicLimit } return 0 } type ParticipateAssetIssueContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ToAddress []byte `protobuf:"bytes,2,opt,name=to_address,json=toAddress,proto3" json:"to_address,omitempty"` AssetName []byte `protobuf:"bytes,3,opt,name=asset_name,json=assetName,proto3" json:"asset_name,omitempty"` // this field is token name before the proposal ALLOW_SAME_TOKEN_NAME is active, otherwise it is token id and token is should be in string format. Amount int64 `protobuf:"varint,4,opt,name=amount,proto3" json:"amount,omitempty"` // the amount of drops } func (x *ParticipateAssetIssueContract) Reset() { *x = ParticipateAssetIssueContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_asset_issue_contract_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ParticipateAssetIssueContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ParticipateAssetIssueContract) ProtoMessage() {} func (x *ParticipateAssetIssueContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_asset_issue_contract_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 ParticipateAssetIssueContract.ProtoReflect.Descriptor instead. func (*ParticipateAssetIssueContract) Descriptor() ([]byte, []int) { return file_core_contract_asset_issue_contract_proto_rawDescGZIP(), []int{4} } func (x *ParticipateAssetIssueContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ParticipateAssetIssueContract) GetToAddress() []byte { if x != nil { return x.ToAddress } return nil } func (x *ParticipateAssetIssueContract) GetAssetName() []byte { if x != nil { return x.AssetName } return nil } func (x *ParticipateAssetIssueContract) GetAmount() int64 { if x != nil { return x.Amount } return 0 } type AssetIssueContract_FrozenSupply struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields FrozenAmount int64 `protobuf:"varint,1,opt,name=frozen_amount,json=frozenAmount,proto3" json:"frozen_amount,omitempty"` FrozenDays int64 `protobuf:"varint,2,opt,name=frozen_days,json=frozenDays,proto3" json:"frozen_days,omitempty"` } func (x *AssetIssueContract_FrozenSupply) Reset() { *x = AssetIssueContract_FrozenSupply{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_asset_issue_contract_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AssetIssueContract_FrozenSupply) String() string { return protoimpl.X.MessageStringOf(x) } func (*AssetIssueContract_FrozenSupply) ProtoMessage() {} func (x *AssetIssueContract_FrozenSupply) ProtoReflect() protoreflect.Message { mi := &file_core_contract_asset_issue_contract_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 AssetIssueContract_FrozenSupply.ProtoReflect.Descriptor instead. func (*AssetIssueContract_FrozenSupply) Descriptor() ([]byte, []int) { return file_core_contract_asset_issue_contract_proto_rawDescGZIP(), []int{0, 0} } func (x *AssetIssueContract_FrozenSupply) GetFrozenAmount() int64 { if x != nil { return x.FrozenAmount } return 0 } func (x *AssetIssueContract_FrozenSupply) GetFrozenDays() int64 { if x != nil { return x.FrozenDays } return 0 } var File_core_contract_asset_issue_contract_proto protoreflect.FileDescriptor var file_core_contract_asset_issue_contract_proto_rawDesc = []byte{ 0x0a, 0x28, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x69, 0x73, 0x73, 0x75, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x91, 0x06, 0x0a, 0x12, 0x41, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x29, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x61, 0x62, 0x62, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x61, 0x62, 0x62, 0x72, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x12, 0x4e, 0x0a, 0x0d, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x0c, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x72, 0x78, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x74, 0x72, 0x78, 0x4e, 0x75, 0x6d, 0x12, 0x1c, 0x0a, 0x09, 0x70, 0x72, 0x65, 0x63, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x70, 0x72, 0x65, 0x63, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x6e, 0x75, 0x6d, 0x18, 0x08, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x18, 0x10, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x76, 0x6f, 0x74, 0x65, 0x53, 0x63, 0x6f, 0x72, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x6c, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x12, 0x2f, 0x0a, 0x14, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x16, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x66, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x3c, 0x0a, 0x1b, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x17, 0x20, 0x01, 0x28, 0x03, 0x52, 0x17, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x46, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x3c, 0x0a, 0x1b, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x18, 0x20, 0x01, 0x28, 0x03, 0x52, 0x17, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x46, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3c, 0x0a, 0x1b, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x19, 0x20, 0x01, 0x28, 0x03, 0x52, 0x17, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x46, 0x72, 0x65, 0x65, 0x4e, 0x65, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x1a, 0x54, 0x0a, 0x0c, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x12, 0x23, 0x0a, 0x0d, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x64, 0x61, 0x79, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x44, 0x61, 0x79, 0x73, 0x22, 0x92, 0x01, 0x0a, 0x15, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x61, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x74, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x74, 0x6f, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x3c, 0x0a, 0x15, 0x55, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0xb5, 0x01, 0x0a, 0x13, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x28, 0x0a, 0x10, 0x6e, 0x65, 0x77, 0x5f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x6e, 0x65, 0x77, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x22, 0x9a, 0x01, 0x0a, 0x1d, 0x50, 0x61, 0x72, 0x74, 0x69, 0x63, 0x69, 0x70, 0x61, 0x74, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x74, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x74, 0x6f, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x61, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_asset_issue_contract_proto_rawDescOnce sync.Once file_core_contract_asset_issue_contract_proto_rawDescData = file_core_contract_asset_issue_contract_proto_rawDesc ) func file_core_contract_asset_issue_contract_proto_rawDescGZIP() []byte { file_core_contract_asset_issue_contract_proto_rawDescOnce.Do(func() { file_core_contract_asset_issue_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_asset_issue_contract_proto_rawDescData) }) return file_core_contract_asset_issue_contract_proto_rawDescData } var file_core_contract_asset_issue_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_core_contract_asset_issue_contract_proto_goTypes = []interface{}{ (*AssetIssueContract)(nil), // 0: protocol.AssetIssueContract (*TransferAssetContract)(nil), // 1: protocol.TransferAssetContract (*UnfreezeAssetContract)(nil), // 2: protocol.UnfreezeAssetContract (*UpdateAssetContract)(nil), // 3: protocol.UpdateAssetContract (*ParticipateAssetIssueContract)(nil), // 4: protocol.ParticipateAssetIssueContract (*AssetIssueContract_FrozenSupply)(nil), // 5: protocol.AssetIssueContract.FrozenSupply } var file_core_contract_asset_issue_contract_proto_depIdxs = []int32{ 5, // 0: protocol.AssetIssueContract.frozen_supply:type_name -> protocol.AssetIssueContract.FrozenSupply 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_core_contract_asset_issue_contract_proto_init() } func file_core_contract_asset_issue_contract_proto_init() { if File_core_contract_asset_issue_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_asset_issue_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AssetIssueContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_asset_issue_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransferAssetContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_asset_issue_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UnfreezeAssetContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_asset_issue_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UpdateAssetContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_asset_issue_contract_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ParticipateAssetIssueContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_asset_issue_contract_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AssetIssueContract_FrozenSupply); 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_core_contract_asset_issue_contract_proto_rawDesc, NumEnums: 0, NumMessages: 6, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_asset_issue_contract_proto_goTypes, DependencyIndexes: file_core_contract_asset_issue_contract_proto_depIdxs, MessageInfos: file_core_contract_asset_issue_contract_proto_msgTypes, }.Build() File_core_contract_asset_issue_contract_proto = out.File file_core_contract_asset_issue_contract_proto_rawDesc = nil file_core_contract_asset_issue_contract_proto_goTypes = nil file_core_contract_asset_issue_contract_proto_depIdxs = nil } <|start_filename|>examples/main.go<|end_filename|> package main import ( "bytes" "encoding/hex" "fmt" "io/ioutil" "log" "github.com/bytejedi/tron-sdk-go/abi" "github.com/bytejedi/tron-sdk-go/keystore" "github.com/bytejedi/tron-sdk-go/utils" ethabi "github.com/ethereum/go-ethereum/accounts/abi" ethcmn "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/miguelmota/go-ethereum-hdwallet" "github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39/wordlists" ) func main() { keystorePassword := "password" // Set wordlist bip39.SetWordList(wordlists.English) entropy, err := bip39.NewEntropy(256) if err != nil { log.Fatal(err) } mnemonic, _ := bip39.NewMnemonic(entropy) seed := bip39.NewSeed(mnemonic, keystorePassword) wallet, err := hdwallet.NewFromSeed(seed) if err != nil { log.Fatal(err) } path := hdwallet.MustParseDerivationPath("m/44'/195'/0'/0/0") account, err := wallet.Derive(path, false) if err != nil { log.Fatal(err) } privKeyHex, err := wallet.PrivateKeyHex(account) if err != nil { log.Fatal(err) } pubKeyHex, err := wallet.PublicKeyHex(account) if err != nil { log.Fatal(err) } privateKeyECDSA, err := wallet.PrivateKey(account) if err != nil { log.Fatal(err) } publicKeyECDSA, err := wallet.PublicKey(account) if err != nil { log.Fatal(err) } keystoreKey := keystore.NewKeyFromECDSA(privateKeyECDSA) keyjson, err := keystore.EncryptKey(keystoreKey, keystorePassword, keystore.StandardScryptN, keystore.StandardScryptP) if err != nil { log.Fatal(err) } tronAddress := keystore.PubkeyToAddress(*publicKeyECDSA) fmt.Println("mnemonic:", mnemonic) fmt.Println("base58 address:", tronAddress.String()) fmt.Println("hex address:", hex.EncodeToString(tronAddress)) fmt.Println("private key:", privKeyHex) fmt.Println("public key:", pubKeyHex) fmt.Println("keystore:", string(keyjson)) abiJson, err := ioutil.ReadFile("./abi.json") if err != nil { log.Fatal(err) } a, err := ethabi.JSON(bytes.NewReader(abiJson)) if err != nil { log.Fatal(err) } method := a.Methods["prepareMint"] paramJson := "[{\"uint256\":\"1212\"},{\"uint256[4]\":[\"2\",\"3\",\"4\",\"5\"]},{\"uint256[2]\":[\"39\",\"10\"]},{\"address\":\"TCQRkmYMbb8bzrZfrtcokox8hwVmY3DCVP\"},{\"address[4]\":[\"TCudRMFJDPChH2FNjVb82cvbREMPNUm1pj\",\"TCudRMFJDPChH2FNjVb82cvbREMPNUm1pj\",\"TCudRMFJDPChH2FNjVb82cvbREMPNUm1pj\",\"TCudRMFJDPChH2FNjVb82cvbREMPNUm1pj\"]},{\"uint256\":\"4\"}]" paddedParamBytes, err := abi.Pack(&method, paramJson) if err != nil { log.Fatal(err) } paddedParamHex := utils.Bytes2Hex(paddedParamBytes) fmt.Println("triggersmartcontract.parameter:", paddedParamHex) // sign txId := "966f7f2c4aa31eafcc48a8e21554bd2f7a5b517890ccaec78beea249358b429a" txHashBytes := ethcmn.Hex2Bytes(txId) key, err := keystore.DecryptKey(keyjson, keystorePassword) if err != nil { log.Fatal(err) } defer keystore.ZeroKey(key.PrivateKey) signature, err := crypto.Sign(txHashBytes, key.PrivateKey) if err != nil { log.Fatal(err) } fmt.Println("sig from keystore:", utils.Bytes2Hex(signature)) signature2, err := crypto.Sign(txHashBytes, privateKeyECDSA) if err != nil { log.Fatal(err) } fmt.Println("sig from private key:", utils.Bytes2Hex(signature2)) } <|start_filename|>utils/utils.go<|end_filename|> package utils import ( "github.com/bwmarrin/snowflake" ) var node *snowflake.Node func init() { var err error node, err = snowflake.NewNode(1) if err != nil { panic(err) } } func GenerateID() int64 { return node.Generate().Int64() } func GenerateIDString() string { return node.Generate().String() } func StringInSlice(a string, list []string) bool { for _, b := range list { if b == a { return true } } return false } <|start_filename|>keystore/crypto.go<|end_filename|> package keystore import ( "crypto/aes" "crypto/cipher" ) func aesCTRXOR(key, inText, iv []byte) ([]byte, error) { // AES-128 is selected due to size of encryptKey. aesBlock, err := aes.NewCipher(key) if err != nil { return nil, err } stream := cipher.NewCTR(aesBlock, iv) outText := make([]byte, len(inText)) stream.XORKeyStream(outText, inText) return outText, err } func aesCBCDecrypt(key, cipherText, iv []byte) ([]byte, error) { aesBlock, err := aes.NewCipher(key) if err != nil { return nil, err } decrypter := cipher.NewCBCDecrypter(aesBlock, iv) paddedPlaintext := make([]byte, len(cipherText)) decrypter.CryptBlocks(paddedPlaintext, cipherText) plaintext := pkcs7Unpad(paddedPlaintext) if plaintext == nil { return nil, ErrDecrypt } return plaintext, err } // From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes func pkcs7Unpad(in []byte) []byte { if len(in) == 0 { return nil } padding := in[len(in)-1] if int(padding) > len(in) || padding > aes.BlockSize { return nil } else if padding == 0 { return nil } for i := len(in) - 1; i > len(in)-int(padding)-1; i-- { if in[i] != padding { return nil } } return in[:len(in)-int(padding)] } <|start_filename|>utils/hmac.go<|end_filename|> package utils import ( "crypto/aes" "crypto/cipher" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "errors" "io" "net/url" "sort" "github.com/google/uuid" ) // HmacSign sign the request data func HmacSign(mapParams map[string]string, method, hostname, path, secretKey string) string { mapCloned := make(map[string]string) for key, value := range mapParams { mapCloned[key] = url.QueryEscape(value) } strParams := Map2UrlQueryBySort(mapCloned) strPayload := method + "\n" + hostname + "\n" + path + "\n" + strParams return ComputeHmac256(strPayload, secretKey) } // Map2UrlQueryBySort format map params to a string func Map2UrlQueryBySort(mapParams map[string]string) string { var keys []string for key := range mapParams { keys = append(keys, key) } sort.Strings(keys) var strParams string for _, key := range keys { strParams += key + "=" + mapParams[key] + "&" } // remove "&" at the end of line if len(strParams) > 0 { strParams = string([]rune(strParams)[:len(strParams)-1]) } return strParams } // ComputeHmac256 compute HMAC SHA256 func ComputeHmac256(strMessage string, strSecret string) string { key := []byte(strSecret) h := hmac.New(sha256.New, key) h.Write([]byte(strMessage)) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } func GenerateAccessKey() string { return base64.StdEncoding.EncodeToString([]byte(uuid.New().String())) } func GenerateSecretKey() string { return base64.StdEncoding.EncodeToString([]byte(uuid.New().String() + GenerateIDString())) } func Encrypter(plaintext string, aesSecretKey []byte) (ciphertext string, err error) { plainbytes, err := base64.StdEncoding.DecodeString(plaintext) if err != nil { return ciphertext, err } block, err := aes.NewCipher(aesSecretKey) if err != nil { return ciphertext, err } cipherbytes := make([]byte, aes.BlockSize+len(plainbytes)) iv := cipherbytes[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return ciphertext, err } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(cipherbytes[aes.BlockSize:], plainbytes) return base64.StdEncoding.EncodeToString(cipherbytes), nil } func Decrypter(ciphertext string, aesSecretKey []byte) (plaintext string, err error) { cipherbytes, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return plaintext, err } block, err := aes.NewCipher(aesSecretKey) if err != nil { return plaintext, err } if len(cipherbytes) < aes.BlockSize { return plaintext, errors.New("ciphertext too short") } iv := cipherbytes[:aes.BlockSize] cipherbytes = cipherbytes[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) stream.XORKeyStream(cipherbytes, cipherbytes) return base64.StdEncoding.EncodeToString(cipherbytes), nil } <|start_filename|>keystore/wallet.go<|end_filename|> package keystore import ( "bytes" "github.com/ethereum/go-ethereum/crypto" ) // keystoreWallet implements the Wallet interface for the original // keystore. type keystoreWallet struct { account Account // Single account contained in this wallet keystore *KeyStore // Keystore where the account originates from } // URL implements Wallet, returning the URL of the account within. func (w *keystoreWallet) URL() URL { return w.account.URL } // Status implements Wallet, returning whether the account held by the // keystore wallet is unlocked or not. func (w *keystoreWallet) Status() (string, error) { w.keystore.mu.RLock() defer w.keystore.mu.RUnlock() if _, ok := w.keystore.unlocked[w.account.Address.String()]; ok { return "Unlocked", nil } return "Locked", nil } // Open implements Wallet, but is a noop for plain wallets since there // is no connection or decryption step necessary to access the list of account. func (w *keystoreWallet) Open(passphrase string) error { return nil } // Close implements Wallet, but is a noop for plain wallets since there // is no meaningful open operation. func (w *keystoreWallet) Close() error { return nil } // Accounts implements Wallet, returning an account list consisting of // a single account that the plain kestore wallet contains. func (w *keystoreWallet) Accounts() []Account { return []Account{w.account} } // Contains implements Wallet, returning whether a particular account is // or is not wrapped by this wallet instance. func (w *keystoreWallet) Contains(account Account) bool { return bytes.Equal(account.Address, w.account.Address) && (account.URL == (URL{}) || account.URL == w.account.URL) } // Derive implements Wallet, but is a noop for plain wallets since there // is no notion of hierarchical account derivation for plain keystore account. func (w *keystoreWallet) Derive(path DerivationPath, pin bool) (Account, error) { return Account{}, ErrNotSupported } // signHash attempts to sign the given hash with // the given account. If the wallet does not wrap this particular account, an // error is returned to avoid account leakage (even though in theory we may be // able to sign via our shared keystore backend). func (w *keystoreWallet) signHash(acc Account, hash []byte) ([]byte, error) { // Make sure the requested account is contained within if !w.Contains(acc) { return nil, ErrUnknownAccount } // Account seems valid, request the keystore to sign return w.keystore.SignHash(acc, hash) } // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed func (w *keystoreWallet) SignData(acc Account, mimeType string, data []byte) ([]byte, error) { return w.signHash(acc, crypto.Keccak256(data)) } // SignDataWithPassphrase signs keccak256(data). The mimetype parameter describes the type of data being signed func (w *keystoreWallet) SignDataWithPassphrase(acc Account, passphrase, mimeType string, data []byte) ([]byte, error) { // Make sure the requested account is contained within if !w.Contains(acc) { return nil, ErrUnknownAccount } // Account seems valid, request the keystore to sign return w.keystore.SignHashWithPassphrase(acc, passphrase, crypto.Keccak256(data)) } func (w *keystoreWallet) SignText(acc Account, text []byte) ([]byte, error) { return w.signHash(acc, TextHash(text)) } // SignTxWithPassphrase implements Wallet, attempting to sign the given // transaction with the given account using passphrase as extra authentication. func (w *keystoreWallet) SignTxWithPassphrase(acc Account, passphrase, rawData, txHash string) ([]byte, error) { // Make sure the requested account is contained within if !w.Contains(acc) { return nil, ErrUnknownAccount } // Account seems valid, request the keystore to sign return w.keystore.SignTxWithPassphrase(acc, passphrase, rawData, txHash) } <|start_filename|>proto/core/Tron.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/Tron.proto package core import ( proto "github.com/golang/protobuf/proto" any "github.com/golang/protobuf/ptypes/any" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type AccountType int32 const ( AccountType_Normal AccountType = 0 AccountType_AssetIssue AccountType = 1 AccountType_Contract AccountType = 2 ) // Enum value maps for AccountType. var ( AccountType_name = map[int32]string{ 0: "Normal", 1: "AssetIssue", 2: "Contract", } AccountType_value = map[string]int32{ "Normal": 0, "AssetIssue": 1, "Contract": 2, } ) func (x AccountType) Enum() *AccountType { p := new(AccountType) *p = x return p } func (x AccountType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AccountType) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[0].Descriptor() } func (AccountType) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[0] } func (x AccountType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AccountType.Descriptor instead. func (AccountType) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{0} } type ReasonCode int32 const ( ReasonCode_REQUESTED ReasonCode = 0 ReasonCode_BAD_PROTOCOL ReasonCode = 2 ReasonCode_TOO_MANY_PEERS ReasonCode = 4 ReasonCode_DUPLICATE_PEER ReasonCode = 5 ReasonCode_INCOMPATIBLE_PROTOCOL ReasonCode = 6 ReasonCode_NULL_IDENTITY ReasonCode = 7 ReasonCode_PEER_QUITING ReasonCode = 8 ReasonCode_UNEXPECTED_IDENTITY ReasonCode = 9 ReasonCode_LOCAL_IDENTITY ReasonCode = 10 ReasonCode_PING_TIMEOUT ReasonCode = 11 ReasonCode_USER_REASON ReasonCode = 16 ReasonCode_RESET ReasonCode = 17 ReasonCode_SYNC_FAIL ReasonCode = 18 ReasonCode_FETCH_FAIL ReasonCode = 19 ReasonCode_BAD_TX ReasonCode = 20 ReasonCode_BAD_BLOCK ReasonCode = 21 ReasonCode_FORKED ReasonCode = 22 ReasonCode_UNLINKABLE ReasonCode = 23 ReasonCode_INCOMPATIBLE_VERSION ReasonCode = 24 ReasonCode_INCOMPATIBLE_CHAIN ReasonCode = 25 ReasonCode_TIME_OUT ReasonCode = 32 ReasonCode_CONNECT_FAIL ReasonCode = 33 ReasonCode_TOO_MANY_PEERS_WITH_SAME_IP ReasonCode = 34 ReasonCode_UNKNOWN ReasonCode = 255 ) // Enum value maps for ReasonCode. var ( ReasonCode_name = map[int32]string{ 0: "REQUESTED", 2: "BAD_PROTOCOL", 4: "TOO_MANY_PEERS", 5: "DUPLICATE_PEER", 6: "INCOMPATIBLE_PROTOCOL", 7: "NULL_IDENTITY", 8: "PEER_QUITING", 9: "UNEXPECTED_IDENTITY", 10: "LOCAL_IDENTITY", 11: "PING_TIMEOUT", 16: "USER_REASON", 17: "RESET", 18: "SYNC_FAIL", 19: "FETCH_FAIL", 20: "BAD_TX", 21: "BAD_BLOCK", 22: "FORKED", 23: "UNLINKABLE", 24: "INCOMPATIBLE_VERSION", 25: "INCOMPATIBLE_CHAIN", 32: "TIME_OUT", 33: "CONNECT_FAIL", 34: "TOO_MANY_PEERS_WITH_SAME_IP", 255: "UNKNOWN", } ReasonCode_value = map[string]int32{ "REQUESTED": 0, "BAD_PROTOCOL": 2, "TOO_MANY_PEERS": 4, "DUPLICATE_PEER": 5, "INCOMPATIBLE_PROTOCOL": 6, "NULL_IDENTITY": 7, "PEER_QUITING": 8, "UNEXPECTED_IDENTITY": 9, "LOCAL_IDENTITY": 10, "PING_TIMEOUT": 11, "USER_REASON": 16, "RESET": 17, "SYNC_FAIL": 18, "FETCH_FAIL": 19, "BAD_TX": 20, "BAD_BLOCK": 21, "FORKED": 22, "UNLINKABLE": 23, "INCOMPATIBLE_VERSION": 24, "INCOMPATIBLE_CHAIN": 25, "TIME_OUT": 32, "CONNECT_FAIL": 33, "TOO_MANY_PEERS_WITH_SAME_IP": 34, "UNKNOWN": 255, } ) func (x ReasonCode) Enum() *ReasonCode { p := new(ReasonCode) *p = x return p } func (x ReasonCode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ReasonCode) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[1].Descriptor() } func (ReasonCode) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[1] } func (x ReasonCode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ReasonCode.Descriptor instead. func (ReasonCode) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{1} } type Proposal_State int32 const ( Proposal_PENDING Proposal_State = 0 Proposal_DISAPPROVED Proposal_State = 1 Proposal_APPROVED Proposal_State = 2 Proposal_CANCELED Proposal_State = 3 ) // Enum value maps for Proposal_State. var ( Proposal_State_name = map[int32]string{ 0: "PENDING", 1: "DISAPPROVED", 2: "APPROVED", 3: "CANCELED", } Proposal_State_value = map[string]int32{ "PENDING": 0, "DISAPPROVED": 1, "APPROVED": 2, "CANCELED": 3, } ) func (x Proposal_State) Enum() *Proposal_State { p := new(Proposal_State) *p = x return p } func (x Proposal_State) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Proposal_State) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[2].Descriptor() } func (Proposal_State) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[2] } func (x Proposal_State) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Proposal_State.Descriptor instead. func (Proposal_State) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{2, 0} } type Permission_PermissionType int32 const ( Permission_Owner Permission_PermissionType = 0 Permission_Witness Permission_PermissionType = 1 Permission_Active Permission_PermissionType = 2 ) // Enum value maps for Permission_PermissionType. var ( Permission_PermissionType_name = map[int32]string{ 0: "Owner", 1: "Witness", 2: "Active", } Permission_PermissionType_value = map[string]int32{ "Owner": 0, "Witness": 1, "Active": 2, } ) func (x Permission_PermissionType) Enum() *Permission_PermissionType { p := new(Permission_PermissionType) *p = x return p } func (x Permission_PermissionType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Permission_PermissionType) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[3].Descriptor() } func (Permission_PermissionType) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[3] } func (x Permission_PermissionType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Permission_PermissionType.Descriptor instead. func (Permission_PermissionType) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{9, 0} } type Transaction_Contract_ContractType int32 const ( Transaction_Contract_AccountCreateContract Transaction_Contract_ContractType = 0 Transaction_Contract_TransferContract Transaction_Contract_ContractType = 1 Transaction_Contract_TransferAssetContract Transaction_Contract_ContractType = 2 Transaction_Contract_VoteAssetContract Transaction_Contract_ContractType = 3 Transaction_Contract_VoteWitnessContract Transaction_Contract_ContractType = 4 Transaction_Contract_WitnessCreateContract Transaction_Contract_ContractType = 5 Transaction_Contract_AssetIssueContract Transaction_Contract_ContractType = 6 Transaction_Contract_WitnessUpdateContract Transaction_Contract_ContractType = 8 Transaction_Contract_ParticipateAssetIssueContract Transaction_Contract_ContractType = 9 Transaction_Contract_AccountUpdateContract Transaction_Contract_ContractType = 10 Transaction_Contract_FreezeBalanceContract Transaction_Contract_ContractType = 11 Transaction_Contract_UnfreezeBalanceContract Transaction_Contract_ContractType = 12 Transaction_Contract_WithdrawBalanceContract Transaction_Contract_ContractType = 13 Transaction_Contract_UnfreezeAssetContract Transaction_Contract_ContractType = 14 Transaction_Contract_UpdateAssetContract Transaction_Contract_ContractType = 15 Transaction_Contract_ProposalCreateContract Transaction_Contract_ContractType = 16 Transaction_Contract_ProposalApproveContract Transaction_Contract_ContractType = 17 Transaction_Contract_ProposalDeleteContract Transaction_Contract_ContractType = 18 Transaction_Contract_SetAccountIdContract Transaction_Contract_ContractType = 19 Transaction_Contract_CustomContract Transaction_Contract_ContractType = 20 Transaction_Contract_CreateSmartContract Transaction_Contract_ContractType = 30 Transaction_Contract_TriggerSmartContract Transaction_Contract_ContractType = 31 Transaction_Contract_GetContract Transaction_Contract_ContractType = 32 Transaction_Contract_UpdateSettingContract Transaction_Contract_ContractType = 33 Transaction_Contract_ExchangeCreateContract Transaction_Contract_ContractType = 41 Transaction_Contract_ExchangeInjectContract Transaction_Contract_ContractType = 42 Transaction_Contract_ExchangeWithdrawContract Transaction_Contract_ContractType = 43 Transaction_Contract_ExchangeTransactionContract Transaction_Contract_ContractType = 44 Transaction_Contract_UpdateEnergyLimitContract Transaction_Contract_ContractType = 45 Transaction_Contract_AccountPermissionUpdateContract Transaction_Contract_ContractType = 46 Transaction_Contract_ClearABIContract Transaction_Contract_ContractType = 48 Transaction_Contract_UpdateBrokerageContract Transaction_Contract_ContractType = 49 Transaction_Contract_ShieldedTransferContract Transaction_Contract_ContractType = 51 ) // Enum value maps for Transaction_Contract_ContractType. var ( Transaction_Contract_ContractType_name = map[int32]string{ 0: "AccountCreateContract", 1: "TransferContract", 2: "TransferAssetContract", 3: "VoteAssetContract", 4: "VoteWitnessContract", 5: "WitnessCreateContract", 6: "AssetIssueContract", 8: "WitnessUpdateContract", 9: "ParticipateAssetIssueContract", 10: "AccountUpdateContract", 11: "FreezeBalanceContract", 12: "UnfreezeBalanceContract", 13: "WithdrawBalanceContract", 14: "UnfreezeAssetContract", 15: "UpdateAssetContract", 16: "ProposalCreateContract", 17: "ProposalApproveContract", 18: "ProposalDeleteContract", 19: "SetAccountIdContract", 20: "CustomContract", 30: "CreateSmartContract", 31: "TriggerSmartContract", 32: "GetContract", 33: "UpdateSettingContract", 41: "ExchangeCreateContract", 42: "ExchangeInjectContract", 43: "ExchangeWithdrawContract", 44: "ExchangeTransactionContract", 45: "UpdateEnergyLimitContract", 46: "AccountPermissionUpdateContract", 48: "ClearABIContract", 49: "UpdateBrokerageContract", 51: "ShieldedTransferContract", } Transaction_Contract_ContractType_value = map[string]int32{ "AccountCreateContract": 0, "TransferContract": 1, "TransferAssetContract": 2, "VoteAssetContract": 3, "VoteWitnessContract": 4, "WitnessCreateContract": 5, "AssetIssueContract": 6, "WitnessUpdateContract": 8, "ParticipateAssetIssueContract": 9, "AccountUpdateContract": 10, "FreezeBalanceContract": 11, "UnfreezeBalanceContract": 12, "WithdrawBalanceContract": 13, "UnfreezeAssetContract": 14, "UpdateAssetContract": 15, "ProposalCreateContract": 16, "ProposalApproveContract": 17, "ProposalDeleteContract": 18, "SetAccountIdContract": 19, "CustomContract": 20, "CreateSmartContract": 30, "TriggerSmartContract": 31, "GetContract": 32, "UpdateSettingContract": 33, "ExchangeCreateContract": 41, "ExchangeInjectContract": 42, "ExchangeWithdrawContract": 43, "ExchangeTransactionContract": 44, "UpdateEnergyLimitContract": 45, "AccountPermissionUpdateContract": 46, "ClearABIContract": 48, "UpdateBrokerageContract": 49, "ShieldedTransferContract": 51, } ) func (x Transaction_Contract_ContractType) Enum() *Transaction_Contract_ContractType { p := new(Transaction_Contract_ContractType) *p = x return p } func (x Transaction_Contract_ContractType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Transaction_Contract_ContractType) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[4].Descriptor() } func (Transaction_Contract_ContractType) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[4] } func (x Transaction_Contract_ContractType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Transaction_Contract_ContractType.Descriptor instead. func (Transaction_Contract_ContractType) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16, 0, 0} } type Transaction_ResultCode int32 const ( Transaction_Result_SUCESS Transaction_ResultCode = 0 Transaction_Result_FAILED Transaction_ResultCode = 1 ) // Enum value maps for Transaction_ResultCode. var ( Transaction_ResultCode_name = map[int32]string{ 0: "SUCESS", 1: "FAILED", } Transaction_ResultCode_value = map[string]int32{ "SUCESS": 0, "FAILED": 1, } ) func (x Transaction_ResultCode) Enum() *Transaction_ResultCode { p := new(Transaction_ResultCode) *p = x return p } func (x Transaction_ResultCode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Transaction_ResultCode) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[5].Descriptor() } func (Transaction_ResultCode) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[5] } func (x Transaction_ResultCode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Transaction_ResultCode.Descriptor instead. func (Transaction_ResultCode) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16, 1, 0} } type Transaction_ResultContractResult int32 const ( Transaction_Result_DEFAULT Transaction_ResultContractResult = 0 Transaction_Result_SUCCESS Transaction_ResultContractResult = 1 Transaction_Result_REVERT Transaction_ResultContractResult = 2 Transaction_Result_BAD_JUMP_DESTINATION Transaction_ResultContractResult = 3 Transaction_Result_OUT_OF_MEMORY Transaction_ResultContractResult = 4 Transaction_Result_PRECOMPILED_CONTRACT Transaction_ResultContractResult = 5 Transaction_Result_STACK_TOO_SMALL Transaction_ResultContractResult = 6 Transaction_Result_STACK_TOO_LARGE Transaction_ResultContractResult = 7 Transaction_Result_ILLEGAL_OPERATION Transaction_ResultContractResult = 8 Transaction_Result_STACK_OVERFLOW Transaction_ResultContractResult = 9 Transaction_Result_OUT_OF_ENERGY Transaction_ResultContractResult = 10 Transaction_Result_OUT_OF_TIME Transaction_ResultContractResult = 11 Transaction_Result_JVM_STACK_OVER_FLOW Transaction_ResultContractResult = 12 Transaction_Result_UNKNOWN Transaction_ResultContractResult = 13 Transaction_Result_TRANSFER_FAILED Transaction_ResultContractResult = 14 ) // Enum value maps for Transaction_ResultContractResult. var ( Transaction_ResultContractResult_name = map[int32]string{ 0: "DEFAULT", 1: "SUCCESS", 2: "REVERT", 3: "BAD_JUMP_DESTINATION", 4: "OUT_OF_MEMORY", 5: "PRECOMPILED_CONTRACT", 6: "STACK_TOO_SMALL", 7: "STACK_TOO_LARGE", 8: "ILLEGAL_OPERATION", 9: "STACK_OVERFLOW", 10: "OUT_OF_ENERGY", 11: "OUT_OF_TIME", 12: "JVM_STACK_OVER_FLOW", 13: "UNKNOWN", 14: "TRANSFER_FAILED", } Transaction_ResultContractResult_value = map[string]int32{ "DEFAULT": 0, "SUCCESS": 1, "REVERT": 2, "BAD_JUMP_DESTINATION": 3, "OUT_OF_MEMORY": 4, "PRECOMPILED_CONTRACT": 5, "STACK_TOO_SMALL": 6, "STACK_TOO_LARGE": 7, "ILLEGAL_OPERATION": 8, "STACK_OVERFLOW": 9, "OUT_OF_ENERGY": 10, "OUT_OF_TIME": 11, "JVM_STACK_OVER_FLOW": 12, "UNKNOWN": 13, "TRANSFER_FAILED": 14, } ) func (x Transaction_ResultContractResult) Enum() *Transaction_ResultContractResult { p := new(Transaction_ResultContractResult) *p = x return p } func (x Transaction_ResultContractResult) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Transaction_ResultContractResult) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[6].Descriptor() } func (Transaction_ResultContractResult) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[6] } func (x Transaction_ResultContractResult) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Transaction_ResultContractResult.Descriptor instead. func (Transaction_ResultContractResult) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16, 1, 1} } type TransactionInfoCode int32 const ( TransactionInfo_SUCESS TransactionInfoCode = 0 TransactionInfo_FAILED TransactionInfoCode = 1 ) // Enum value maps for TransactionInfoCode. var ( TransactionInfoCode_name = map[int32]string{ 0: "SUCESS", 1: "FAILED", } TransactionInfoCode_value = map[string]int32{ "SUCESS": 0, "FAILED": 1, } ) func (x TransactionInfoCode) Enum() *TransactionInfoCode { p := new(TransactionInfoCode) *p = x return p } func (x TransactionInfoCode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TransactionInfoCode) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[7].Descriptor() } func (TransactionInfoCode) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[7] } func (x TransactionInfoCode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TransactionInfoCode.Descriptor instead. func (TransactionInfoCode) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{17, 0} } type BlockInventory_Type int32 const ( BlockInventory_SYNC BlockInventory_Type = 0 BlockInventory_ADVTISE BlockInventory_Type = 1 BlockInventory_FETCH BlockInventory_Type = 2 ) // Enum value maps for BlockInventory_Type. var ( BlockInventory_Type_name = map[int32]string{ 0: "SYNC", 1: "ADVTISE", 2: "FETCH", } BlockInventory_Type_value = map[string]int32{ "SYNC": 0, "ADVTISE": 1, "FETCH": 2, } ) func (x BlockInventory_Type) Enum() *BlockInventory_Type { p := new(BlockInventory_Type) *p = x return p } func (x BlockInventory_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (BlockInventory_Type) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[8].Descriptor() } func (BlockInventory_Type) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[8] } func (x BlockInventory_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use BlockInventory_Type.Descriptor instead. func (BlockInventory_Type) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{24, 0} } type Inventory_InventoryType int32 const ( Inventory_TRX Inventory_InventoryType = 0 Inventory_BLOCK Inventory_InventoryType = 1 ) // Enum value maps for Inventory_InventoryType. var ( Inventory_InventoryType_name = map[int32]string{ 0: "TRX", 1: "BLOCK", } Inventory_InventoryType_value = map[string]int32{ "TRX": 0, "BLOCK": 1, } ) func (x Inventory_InventoryType) Enum() *Inventory_InventoryType { p := new(Inventory_InventoryType) *p = x return p } func (x Inventory_InventoryType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Inventory_InventoryType) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[9].Descriptor() } func (Inventory_InventoryType) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[9] } func (x Inventory_InventoryType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Inventory_InventoryType.Descriptor instead. func (Inventory_InventoryType) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{25, 0} } type Items_ItemType int32 const ( Items_ERR Items_ItemType = 0 Items_TRX Items_ItemType = 1 Items_BLOCK Items_ItemType = 2 Items_BLOCKHEADER Items_ItemType = 3 ) // Enum value maps for Items_ItemType. var ( Items_ItemType_name = map[int32]string{ 0: "ERR", 1: "TRX", 2: "BLOCK", 3: "BLOCKHEADER", } Items_ItemType_value = map[string]int32{ "ERR": 0, "TRX": 1, "BLOCK": 2, "BLOCKHEADER": 3, } ) func (x Items_ItemType) Enum() *Items_ItemType { p := new(Items_ItemType) *p = x return p } func (x Items_ItemType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Items_ItemType) Descriptor() protoreflect.EnumDescriptor { return file_core_Tron_proto_enumTypes[10].Descriptor() } func (Items_ItemType) Type() protoreflect.EnumType { return &file_core_Tron_proto_enumTypes[10] } func (x Items_ItemType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Items_ItemType.Descriptor instead. func (Items_ItemType) EnumDescriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{26, 0} } // AccountId, (name, address) use name, (null, address) use address, (name, null) use name, type AccountId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name []byte `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` } func (x *AccountId) Reset() { *x = AccountId{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AccountId) String() string { return protoimpl.X.MessageStringOf(x) } func (*AccountId) ProtoMessage() {} func (x *AccountId) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 AccountId.ProtoReflect.Descriptor instead. func (*AccountId) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{0} } func (x *AccountId) GetName() []byte { if x != nil { return x.Name } return nil } func (x *AccountId) GetAddress() []byte { if x != nil { return x.Address } return nil } // vote message type Vote struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // the super rep address VoteAddress []byte `protobuf:"bytes,1,opt,name=vote_address,json=voteAddress,proto3" json:"vote_address,omitempty"` // the vote num to this super rep. VoteCount int64 `protobuf:"varint,2,opt,name=vote_count,json=voteCount,proto3" json:"vote_count,omitempty"` } func (x *Vote) Reset() { *x = Vote{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Vote) String() string { return protoimpl.X.MessageStringOf(x) } func (*Vote) ProtoMessage() {} func (x *Vote) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Vote.ProtoReflect.Descriptor instead. func (*Vote) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{1} } func (x *Vote) GetVoteAddress() []byte { if x != nil { return x.VoteAddress } return nil } func (x *Vote) GetVoteCount() int64 { if x != nil { return x.VoteCount } return 0 } // Proposal type Proposal struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ProposalId int64 `protobuf:"varint,1,opt,name=proposal_id,json=proposalId,proto3" json:"proposal_id,omitempty"` ProposerAddress []byte `protobuf:"bytes,2,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"` Parameters map[int64]int64 `protobuf:"bytes,3,rep,name=parameters,proto3" json:"parameters,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` ExpirationTime int64 `protobuf:"varint,4,opt,name=expiration_time,json=expirationTime,proto3" json:"expiration_time,omitempty"` CreateTime int64 `protobuf:"varint,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` Approvals [][]byte `protobuf:"bytes,6,rep,name=approvals,proto3" json:"approvals,omitempty"` State Proposal_State `protobuf:"varint,7,opt,name=state,proto3,enum=protocol.Proposal_State" json:"state,omitempty"` } func (x *Proposal) Reset() { *x = Proposal{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Proposal) String() string { return protoimpl.X.MessageStringOf(x) } func (*Proposal) ProtoMessage() {} func (x *Proposal) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Proposal.ProtoReflect.Descriptor instead. func (*Proposal) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{2} } func (x *Proposal) GetProposalId() int64 { if x != nil { return x.ProposalId } return 0 } func (x *Proposal) GetProposerAddress() []byte { if x != nil { return x.ProposerAddress } return nil } func (x *Proposal) GetParameters() map[int64]int64 { if x != nil { return x.Parameters } return nil } func (x *Proposal) GetExpirationTime() int64 { if x != nil { return x.ExpirationTime } return 0 } func (x *Proposal) GetCreateTime() int64 { if x != nil { return x.CreateTime } return 0 } func (x *Proposal) GetApprovals() [][]byte { if x != nil { return x.Approvals } return nil } func (x *Proposal) GetState() Proposal_State { if x != nil { return x.State } return Proposal_PENDING } // Exchange type Exchange struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ExchangeId int64 `protobuf:"varint,1,opt,name=exchange_id,json=exchangeId,proto3" json:"exchange_id,omitempty"` CreatorAddress []byte `protobuf:"bytes,2,opt,name=creator_address,json=creatorAddress,proto3" json:"creator_address,omitempty"` CreateTime int64 `protobuf:"varint,3,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` FirstTokenId []byte `protobuf:"bytes,6,opt,name=first_token_id,json=firstTokenId,proto3" json:"first_token_id,omitempty"` FirstTokenBalance int64 `protobuf:"varint,7,opt,name=first_token_balance,json=firstTokenBalance,proto3" json:"first_token_balance,omitempty"` SecondTokenId []byte `protobuf:"bytes,8,opt,name=second_token_id,json=secondTokenId,proto3" json:"second_token_id,omitempty"` SecondTokenBalance int64 `protobuf:"varint,9,opt,name=second_token_balance,json=secondTokenBalance,proto3" json:"second_token_balance,omitempty"` } func (x *Exchange) Reset() { *x = Exchange{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Exchange) String() string { return protoimpl.X.MessageStringOf(x) } func (*Exchange) ProtoMessage() {} func (x *Exchange) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Exchange.ProtoReflect.Descriptor instead. func (*Exchange) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{3} } func (x *Exchange) GetExchangeId() int64 { if x != nil { return x.ExchangeId } return 0 } func (x *Exchange) GetCreatorAddress() []byte { if x != nil { return x.CreatorAddress } return nil } func (x *Exchange) GetCreateTime() int64 { if x != nil { return x.CreateTime } return 0 } func (x *Exchange) GetFirstTokenId() []byte { if x != nil { return x.FirstTokenId } return nil } func (x *Exchange) GetFirstTokenBalance() int64 { if x != nil { return x.FirstTokenBalance } return 0 } func (x *Exchange) GetSecondTokenId() []byte { if x != nil { return x.SecondTokenId } return nil } func (x *Exchange) GetSecondTokenBalance() int64 { if x != nil { return x.SecondTokenBalance } return 0 } type ChainParameters struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ChainParameter []*ChainParameters_ChainParameter `protobuf:"bytes,1,rep,name=chainParameter,proto3" json:"chainParameter,omitempty"` } func (x *ChainParameters) Reset() { *x = ChainParameters{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ChainParameters) String() string { return protoimpl.X.MessageStringOf(x) } func (*ChainParameters) ProtoMessage() {} func (x *ChainParameters) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 ChainParameters.ProtoReflect.Descriptor instead. func (*ChainParameters) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{4} } func (x *ChainParameters) GetChainParameter() []*ChainParameters_ChainParameter { if x != nil { return x.ChainParameter } return nil } // Account type Account struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // account nick name AccountName []byte `protobuf:"bytes,1,opt,name=account_name,json=accountName,proto3" json:"account_name,omitempty"` Type AccountType `protobuf:"varint,2,opt,name=type,proto3,enum=protocol.AccountType" json:"type,omitempty"` // the create address Address []byte `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` // the trx balance Balance int64 `protobuf:"varint,4,opt,name=balance,proto3" json:"balance,omitempty"` // the votes Votes []*Vote `protobuf:"bytes,5,rep,name=votes,proto3" json:"votes,omitempty"` // the other asset owned by this account Asset map[string]int64 `protobuf:"bytes,6,rep,name=asset,proto3" json:"asset,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` // the other asset owned by this account,key is assetId AssetV2 map[string]int64 `protobuf:"bytes,56,rep,name=assetV2,proto3" json:"assetV2,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` // the frozen balance for bandwidth Frozen []*Account_Frozen `protobuf:"bytes,7,rep,name=frozen,proto3" json:"frozen,omitempty"` // bandwidth, get from frozen NetUsage int64 `protobuf:"varint,8,opt,name=net_usage,json=netUsage,proto3" json:"net_usage,omitempty"` //Frozen balance provided by other accounts to this account AcquiredDelegatedFrozenBalanceForBandwidth int64 `protobuf:"varint,41,opt,name=acquired_delegated_frozen_balance_for_bandwidth,json=acquiredDelegatedFrozenBalanceForBandwidth,proto3" json:"acquired_delegated_frozen_balance_for_bandwidth,omitempty"` //Freeze and provide balances to other accounts DelegatedFrozenBalanceForBandwidth int64 `protobuf:"varint,42,opt,name=delegated_frozen_balance_for_bandwidth,json=delegatedFrozenBalanceForBandwidth,proto3" json:"delegated_frozen_balance_for_bandwidth,omitempty"` // this account create time CreateTime int64 `protobuf:"varint,9,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` // this last operation time, including transfer, voting and so on. //FIXME fix grammar LatestOprationTime int64 `protobuf:"varint,10,opt,name=latest_opration_time,json=latestOprationTime,proto3" json:"latest_opration_time,omitempty"` // witness block producing allowance Allowance int64 `protobuf:"varint,11,opt,name=allowance,proto3" json:"allowance,omitempty"` // last withdraw time LatestWithdrawTime int64 `protobuf:"varint,12,opt,name=latest_withdraw_time,json=latestWithdrawTime,proto3" json:"latest_withdraw_time,omitempty"` // not used so far Code []byte `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"` IsWitness bool `protobuf:"varint,14,opt,name=is_witness,json=isWitness,proto3" json:"is_witness,omitempty"` IsCommittee bool `protobuf:"varint,15,opt,name=is_committee,json=isCommittee,proto3" json:"is_committee,omitempty"` // frozen asset(for asset issuer) FrozenSupply []*Account_Frozen `protobuf:"bytes,16,rep,name=frozen_supply,json=frozenSupply,proto3" json:"frozen_supply,omitempty"` // asset_issued_name AssetIssuedName []byte `protobuf:"bytes,17,opt,name=asset_issued_name,json=assetIssuedName,proto3" json:"asset_issued_name,omitempty"` AssetIssued_ID []byte `protobuf:"bytes,57,opt,name=asset_issued_ID,json=assetIssuedID,proto3" json:"asset_issued_ID,omitempty"` LatestAssetOperationTime map[string]int64 `protobuf:"bytes,18,rep,name=latest_asset_operation_time,json=latestAssetOperationTime,proto3" json:"latest_asset_operation_time,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` LatestAssetOperationTimeV2 map[string]int64 `protobuf:"bytes,58,rep,name=latest_asset_operation_timeV2,json=latestAssetOperationTimeV2,proto3" json:"latest_asset_operation_timeV2,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` FreeNetUsage int64 `protobuf:"varint,19,opt,name=free_net_usage,json=freeNetUsage,proto3" json:"free_net_usage,omitempty"` FreeAssetNetUsage map[string]int64 `protobuf:"bytes,20,rep,name=free_asset_net_usage,json=freeAssetNetUsage,proto3" json:"free_asset_net_usage,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` FreeAssetNetUsageV2 map[string]int64 `protobuf:"bytes,59,rep,name=free_asset_net_usageV2,json=freeAssetNetUsageV2,proto3" json:"free_asset_net_usageV2,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` LatestConsumeTime int64 `protobuf:"varint,21,opt,name=latest_consume_time,json=latestConsumeTime,proto3" json:"latest_consume_time,omitempty"` LatestConsumeFreeTime int64 `protobuf:"varint,22,opt,name=latest_consume_free_time,json=latestConsumeFreeTime,proto3" json:"latest_consume_free_time,omitempty"` // the identity of this account, case insensitive AccountId []byte `protobuf:"bytes,23,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"` AccountResource *Account_AccountResource `protobuf:"bytes,26,opt,name=account_resource,json=accountResource,proto3" json:"account_resource,omitempty"` CodeHash []byte `protobuf:"bytes,30,opt,name=codeHash,proto3" json:"codeHash,omitempty"` OwnerPermission *Permission `protobuf:"bytes,31,opt,name=owner_permission,json=ownerPermission,proto3" json:"owner_permission,omitempty"` WitnessPermission *Permission `protobuf:"bytes,32,opt,name=witness_permission,json=witnessPermission,proto3" json:"witness_permission,omitempty"` ActivePermission []*Permission `protobuf:"bytes,33,rep,name=active_permission,json=activePermission,proto3" json:"active_permission,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[5] 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_core_Tron_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 Account.ProtoReflect.Descriptor instead. func (*Account) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{5} } func (x *Account) GetAccountName() []byte { if x != nil { return x.AccountName } return nil } func (x *Account) GetType() AccountType { if x != nil { return x.Type } return AccountType_Normal } func (x *Account) GetAddress() []byte { if x != nil { return x.Address } return nil } func (x *Account) GetBalance() int64 { if x != nil { return x.Balance } return 0 } func (x *Account) GetVotes() []*Vote { if x != nil { return x.Votes } return nil } func (x *Account) GetAsset() map[string]int64 { if x != nil { return x.Asset } return nil } func (x *Account) GetAssetV2() map[string]int64 { if x != nil { return x.AssetV2 } return nil } func (x *Account) GetFrozen() []*Account_Frozen { if x != nil { return x.Frozen } return nil } func (x *Account) GetNetUsage() int64 { if x != nil { return x.NetUsage } return 0 } func (x *Account) GetAcquiredDelegatedFrozenBalanceForBandwidth() int64 { if x != nil { return x.AcquiredDelegatedFrozenBalanceForBandwidth } return 0 } func (x *Account) GetDelegatedFrozenBalanceForBandwidth() int64 { if x != nil { return x.DelegatedFrozenBalanceForBandwidth } return 0 } func (x *Account) GetCreateTime() int64 { if x != nil { return x.CreateTime } return 0 } func (x *Account) GetLatestOprationTime() int64 { if x != nil { return x.LatestOprationTime } return 0 } func (x *Account) GetAllowance() int64 { if x != nil { return x.Allowance } return 0 } func (x *Account) GetLatestWithdrawTime() int64 { if x != nil { return x.LatestWithdrawTime } return 0 } func (x *Account) GetCode() []byte { if x != nil { return x.Code } return nil } func (x *Account) GetIsWitness() bool { if x != nil { return x.IsWitness } return false } func (x *Account) GetIsCommittee() bool { if x != nil { return x.IsCommittee } return false } func (x *Account) GetFrozenSupply() []*Account_Frozen { if x != nil { return x.FrozenSupply } return nil } func (x *Account) GetAssetIssuedName() []byte { if x != nil { return x.AssetIssuedName } return nil } func (x *Account) GetAssetIssued_ID() []byte { if x != nil { return x.AssetIssued_ID } return nil } func (x *Account) GetLatestAssetOperationTime() map[string]int64 { if x != nil { return x.LatestAssetOperationTime } return nil } func (x *Account) GetLatestAssetOperationTimeV2() map[string]int64 { if x != nil { return x.LatestAssetOperationTimeV2 } return nil } func (x *Account) GetFreeNetUsage() int64 { if x != nil { return x.FreeNetUsage } return 0 } func (x *Account) GetFreeAssetNetUsage() map[string]int64 { if x != nil { return x.FreeAssetNetUsage } return nil } func (x *Account) GetFreeAssetNetUsageV2() map[string]int64 { if x != nil { return x.FreeAssetNetUsageV2 } return nil } func (x *Account) GetLatestConsumeTime() int64 { if x != nil { return x.LatestConsumeTime } return 0 } func (x *Account) GetLatestConsumeFreeTime() int64 { if x != nil { return x.LatestConsumeFreeTime } return 0 } func (x *Account) GetAccountId() []byte { if x != nil { return x.AccountId } return nil } func (x *Account) GetAccountResource() *Account_AccountResource { if x != nil { return x.AccountResource } return nil } func (x *Account) GetCodeHash() []byte { if x != nil { return x.CodeHash } return nil } func (x *Account) GetOwnerPermission() *Permission { if x != nil { return x.OwnerPermission } return nil } func (x *Account) GetWitnessPermission() *Permission { if x != nil { return x.WitnessPermission } return nil } func (x *Account) GetActivePermission() []*Permission { if x != nil { return x.ActivePermission } return nil } type Key struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Weight int64 `protobuf:"varint,2,opt,name=weight,proto3" json:"weight,omitempty"` } func (x *Key) Reset() { *x = Key{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Key) String() string { return protoimpl.X.MessageStringOf(x) } func (*Key) ProtoMessage() {} func (x *Key) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Key.ProtoReflect.Descriptor instead. func (*Key) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{6} } func (x *Key) GetAddress() []byte { if x != nil { return x.Address } return nil } func (x *Key) GetWeight() int64 { if x != nil { return x.Weight } return 0 } type DelegatedResource struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields From []byte `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` To []byte `protobuf:"bytes,2,opt,name=to,proto3" json:"to,omitempty"` FrozenBalanceForBandwidth int64 `protobuf:"varint,3,opt,name=frozen_balance_for_bandwidth,json=frozenBalanceForBandwidth,proto3" json:"frozen_balance_for_bandwidth,omitempty"` FrozenBalanceForEnergy int64 `protobuf:"varint,4,opt,name=frozen_balance_for_energy,json=frozenBalanceForEnergy,proto3" json:"frozen_balance_for_energy,omitempty"` ExpireTimeForBandwidth int64 `protobuf:"varint,5,opt,name=expire_time_for_bandwidth,json=expireTimeForBandwidth,proto3" json:"expire_time_for_bandwidth,omitempty"` ExpireTimeForEnergy int64 `protobuf:"varint,6,opt,name=expire_time_for_energy,json=expireTimeForEnergy,proto3" json:"expire_time_for_energy,omitempty"` } func (x *DelegatedResource) Reset() { *x = DelegatedResource{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DelegatedResource) String() string { return protoimpl.X.MessageStringOf(x) } func (*DelegatedResource) ProtoMessage() {} func (x *DelegatedResource) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 DelegatedResource.ProtoReflect.Descriptor instead. func (*DelegatedResource) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{7} } func (x *DelegatedResource) GetFrom() []byte { if x != nil { return x.From } return nil } func (x *DelegatedResource) GetTo() []byte { if x != nil { return x.To } return nil } func (x *DelegatedResource) GetFrozenBalanceForBandwidth() int64 { if x != nil { return x.FrozenBalanceForBandwidth } return 0 } func (x *DelegatedResource) GetFrozenBalanceForEnergy() int64 { if x != nil { return x.FrozenBalanceForEnergy } return 0 } func (x *DelegatedResource) GetExpireTimeForBandwidth() int64 { if x != nil { return x.ExpireTimeForBandwidth } return 0 } func (x *DelegatedResource) GetExpireTimeForEnergy() int64 { if x != nil { return x.ExpireTimeForEnergy } return 0 } type Authority struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Account *AccountId `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"` PermissionName []byte `protobuf:"bytes,2,opt,name=permission_name,json=permissionName,proto3" json:"permission_name,omitempty"` } func (x *Authority) Reset() { *x = Authority{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Authority) String() string { return protoimpl.X.MessageStringOf(x) } func (*Authority) ProtoMessage() {} func (x *Authority) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Authority.ProtoReflect.Descriptor instead. func (*Authority) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{8} } func (x *Authority) GetAccount() *AccountId { if x != nil { return x.Account } return nil } func (x *Authority) GetPermissionName() []byte { if x != nil { return x.PermissionName } return nil } type Permission struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Type Permission_PermissionType `protobuf:"varint,1,opt,name=type,proto3,enum=protocol.Permission_PermissionType" json:"type,omitempty"` Id int32 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` //Owner id=0, Witness id=1, Active id start by 2 PermissionName string `protobuf:"bytes,3,opt,name=permission_name,json=permissionName,proto3" json:"permission_name,omitempty"` Threshold int64 `protobuf:"varint,4,opt,name=threshold,proto3" json:"threshold,omitempty"` ParentId int32 `protobuf:"varint,5,opt,name=parent_id,json=parentId,proto3" json:"parent_id,omitempty"` Operations []byte `protobuf:"bytes,6,opt,name=operations,proto3" json:"operations,omitempty"` //1 bit 1 contract Keys []*Key `protobuf:"bytes,7,rep,name=keys,proto3" json:"keys,omitempty"` } func (x *Permission) Reset() { *x = Permission{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Permission) String() string { return protoimpl.X.MessageStringOf(x) } func (*Permission) ProtoMessage() {} func (x *Permission) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Permission.ProtoReflect.Descriptor instead. func (*Permission) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{9} } func (x *Permission) GetType() Permission_PermissionType { if x != nil { return x.Type } return Permission_Owner } func (x *Permission) GetId() int32 { if x != nil { return x.Id } return 0 } func (x *Permission) GetPermissionName() string { if x != nil { return x.PermissionName } return "" } func (x *Permission) GetThreshold() int64 { if x != nil { return x.Threshold } return 0 } func (x *Permission) GetParentId() int32 { if x != nil { return x.ParentId } return 0 } func (x *Permission) GetOperations() []byte { if x != nil { return x.Operations } return nil } func (x *Permission) GetKeys() []*Key { if x != nil { return x.Keys } return nil } // Witness type Witness struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` VoteCount int64 `protobuf:"varint,2,opt,name=voteCount,proto3" json:"voteCount,omitempty"` PubKey []byte `protobuf:"bytes,3,opt,name=pubKey,proto3" json:"pubKey,omitempty"` Url string `protobuf:"bytes,4,opt,name=url,proto3" json:"url,omitempty"` TotalProduced int64 `protobuf:"varint,5,opt,name=totalProduced,proto3" json:"totalProduced,omitempty"` TotalMissed int64 `protobuf:"varint,6,opt,name=totalMissed,proto3" json:"totalMissed,omitempty"` LatestBlockNum int64 `protobuf:"varint,7,opt,name=latestBlockNum,proto3" json:"latestBlockNum,omitempty"` LatestSlotNum int64 `protobuf:"varint,8,opt,name=latestSlotNum,proto3" json:"latestSlotNum,omitempty"` IsJobs bool `protobuf:"varint,9,opt,name=isJobs,proto3" json:"isJobs,omitempty"` } func (x *Witness) Reset() { *x = Witness{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Witness) String() string { return protoimpl.X.MessageStringOf(x) } func (*Witness) ProtoMessage() {} func (x *Witness) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Witness.ProtoReflect.Descriptor instead. func (*Witness) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{10} } func (x *Witness) GetAddress() []byte { if x != nil { return x.Address } return nil } func (x *Witness) GetVoteCount() int64 { if x != nil { return x.VoteCount } return 0 } func (x *Witness) GetPubKey() []byte { if x != nil { return x.PubKey } return nil } func (x *Witness) GetUrl() string { if x != nil { return x.Url } return "" } func (x *Witness) GetTotalProduced() int64 { if x != nil { return x.TotalProduced } return 0 } func (x *Witness) GetTotalMissed() int64 { if x != nil { return x.TotalMissed } return 0 } func (x *Witness) GetLatestBlockNum() int64 { if x != nil { return x.LatestBlockNum } return 0 } func (x *Witness) GetLatestSlotNum() int64 { if x != nil { return x.LatestSlotNum } return 0 } func (x *Witness) GetIsJobs() bool { if x != nil { return x.IsJobs } return false } // Vote Change type Votes struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` OldVotes []*Vote `protobuf:"bytes,2,rep,name=old_votes,json=oldVotes,proto3" json:"old_votes,omitempty"` NewVotes []*Vote `protobuf:"bytes,3,rep,name=new_votes,json=newVotes,proto3" json:"new_votes,omitempty"` } func (x *Votes) Reset() { *x = Votes{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Votes) String() string { return protoimpl.X.MessageStringOf(x) } func (*Votes) ProtoMessage() {} func (x *Votes) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Votes.ProtoReflect.Descriptor instead. func (*Votes) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{11} } func (x *Votes) GetAddress() []byte { if x != nil { return x.Address } return nil } func (x *Votes) GetOldVotes() []*Vote { if x != nil { return x.OldVotes } return nil } func (x *Votes) GetNewVotes() []*Vote { if x != nil { return x.NewVotes } return nil } type TXOutput struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` PubKeyHash []byte `protobuf:"bytes,2,opt,name=pubKeyHash,proto3" json:"pubKeyHash,omitempty"` } func (x *TXOutput) Reset() { *x = TXOutput{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TXOutput) String() string { return protoimpl.X.MessageStringOf(x) } func (*TXOutput) ProtoMessage() {} func (x *TXOutput) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 TXOutput.ProtoReflect.Descriptor instead. func (*TXOutput) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{12} } func (x *TXOutput) GetValue() int64 { if x != nil { return x.Value } return 0 } func (x *TXOutput) GetPubKeyHash() []byte { if x != nil { return x.PubKeyHash } return nil } type TXInput struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RawData *TXInputRaw `protobuf:"bytes,1,opt,name=raw_data,json=rawData,proto3" json:"raw_data,omitempty"` Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"` } func (x *TXInput) Reset() { *x = TXInput{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TXInput) String() string { return protoimpl.X.MessageStringOf(x) } func (*TXInput) ProtoMessage() {} func (x *TXInput) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 TXInput.ProtoReflect.Descriptor instead. func (*TXInput) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{13} } func (x *TXInput) GetRawData() *TXInputRaw { if x != nil { return x.RawData } return nil } func (x *TXInput) GetSignature() []byte { if x != nil { return x.Signature } return nil } type TXOutputs struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Outputs []*TXOutput `protobuf:"bytes,1,rep,name=outputs,proto3" json:"outputs,omitempty"` } func (x *TXOutputs) Reset() { *x = TXOutputs{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TXOutputs) String() string { return protoimpl.X.MessageStringOf(x) } func (*TXOutputs) ProtoMessage() {} func (x *TXOutputs) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 TXOutputs.ProtoReflect.Descriptor instead. func (*TXOutputs) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{14} } func (x *TXOutputs) GetOutputs() []*TXOutput { if x != nil { return x.Outputs } return nil } type ResourceReceipt struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields EnergyUsage int64 `protobuf:"varint,1,opt,name=energy_usage,json=energyUsage,proto3" json:"energy_usage,omitempty"` EnergyFee int64 `protobuf:"varint,2,opt,name=energy_fee,json=energyFee,proto3" json:"energy_fee,omitempty"` OriginEnergyUsage int64 `protobuf:"varint,3,opt,name=origin_energy_usage,json=originEnergyUsage,proto3" json:"origin_energy_usage,omitempty"` EnergyUsageTotal int64 `protobuf:"varint,4,opt,name=energy_usage_total,json=energyUsageTotal,proto3" json:"energy_usage_total,omitempty"` NetUsage int64 `protobuf:"varint,5,opt,name=net_usage,json=netUsage,proto3" json:"net_usage,omitempty"` NetFee int64 `protobuf:"varint,6,opt,name=net_fee,json=netFee,proto3" json:"net_fee,omitempty"` Result Transaction_ResultContractResult `protobuf:"varint,7,opt,name=result,proto3,enum=protocol.Transaction_ResultContractResult" json:"result,omitempty"` } func (x *ResourceReceipt) Reset() { *x = ResourceReceipt{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ResourceReceipt) String() string { return protoimpl.X.MessageStringOf(x) } func (*ResourceReceipt) ProtoMessage() {} func (x *ResourceReceipt) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 ResourceReceipt.ProtoReflect.Descriptor instead. func (*ResourceReceipt) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{15} } func (x *ResourceReceipt) GetEnergyUsage() int64 { if x != nil { return x.EnergyUsage } return 0 } func (x *ResourceReceipt) GetEnergyFee() int64 { if x != nil { return x.EnergyFee } return 0 } func (x *ResourceReceipt) GetOriginEnergyUsage() int64 { if x != nil { return x.OriginEnergyUsage } return 0 } func (x *ResourceReceipt) GetEnergyUsageTotal() int64 { if x != nil { return x.EnergyUsageTotal } return 0 } func (x *ResourceReceipt) GetNetUsage() int64 { if x != nil { return x.NetUsage } return 0 } func (x *ResourceReceipt) GetNetFee() int64 { if x != nil { return x.NetFee } return 0 } func (x *ResourceReceipt) GetResult() Transaction_ResultContractResult { if x != nil { return x.Result } return Transaction_Result_DEFAULT } type Transaction struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RawData *TransactionRaw `protobuf:"bytes,1,opt,name=raw_data,json=rawData,proto3" json:"raw_data,omitempty"` // only support size = 1, repeated list here for muti-sig extension Signature [][]byte `protobuf:"bytes,2,rep,name=signature,proto3" json:"signature,omitempty"` Ret []*Transaction_Result `protobuf:"bytes,5,rep,name=ret,proto3" json:"ret,omitempty"` } func (x *Transaction) Reset() { *x = Transaction{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Transaction) String() string { return protoimpl.X.MessageStringOf(x) } func (*Transaction) ProtoMessage() {} func (x *Transaction) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Transaction.ProtoReflect.Descriptor instead. func (*Transaction) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16} } func (x *Transaction) GetRawData() *TransactionRaw { if x != nil { return x.RawData } return nil } func (x *Transaction) GetSignature() [][]byte { if x != nil { return x.Signature } return nil } func (x *Transaction) GetRet() []*Transaction_Result { if x != nil { return x.Ret } return nil } type TransactionInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Id []byte `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Fee int64 `protobuf:"varint,2,opt,name=fee,proto3" json:"fee,omitempty"` BlockNumber int64 `protobuf:"varint,3,opt,name=blockNumber,proto3" json:"blockNumber,omitempty"` BlockTimeStamp int64 `protobuf:"varint,4,opt,name=blockTimeStamp,proto3" json:"blockTimeStamp,omitempty"` ContractResult [][]byte `protobuf:"bytes,5,rep,name=contractResult,proto3" json:"contractResult,omitempty"` ContractAddress []byte `protobuf:"bytes,6,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` Receipt *ResourceReceipt `protobuf:"bytes,7,opt,name=receipt,proto3" json:"receipt,omitempty"` Log []*TransactionInfo_Log `protobuf:"bytes,8,rep,name=log,proto3" json:"log,omitempty"` Result TransactionInfoCode `protobuf:"varint,9,opt,name=result,proto3,enum=protocol.TransactionInfoCode" json:"result,omitempty"` ResMessage []byte `protobuf:"bytes,10,opt,name=resMessage,proto3" json:"resMessage,omitempty"` AssetIssueID string `protobuf:"bytes,14,opt,name=assetIssueID,proto3" json:"assetIssueID,omitempty"` WithdrawAmount int64 `protobuf:"varint,15,opt,name=withdraw_amount,json=withdrawAmount,proto3" json:"withdraw_amount,omitempty"` UnfreezeAmount int64 `protobuf:"varint,16,opt,name=unfreeze_amount,json=unfreezeAmount,proto3" json:"unfreeze_amount,omitempty"` InternalTransactions []*InternalTransaction `protobuf:"bytes,17,rep,name=internal_transactions,json=internalTransactions,proto3" json:"internal_transactions,omitempty"` ExchangeReceivedAmount int64 `protobuf:"varint,18,opt,name=exchange_received_amount,json=exchangeReceivedAmount,proto3" json:"exchange_received_amount,omitempty"` ExchangeInjectAnotherAmount int64 `protobuf:"varint,19,opt,name=exchange_inject_another_amount,json=exchangeInjectAnotherAmount,proto3" json:"exchange_inject_another_amount,omitempty"` ExchangeWithdrawAnotherAmount int64 `protobuf:"varint,20,opt,name=exchange_withdraw_another_amount,json=exchangeWithdrawAnotherAmount,proto3" json:"exchange_withdraw_another_amount,omitempty"` ExchangeId int64 `protobuf:"varint,21,opt,name=exchange_id,json=exchangeId,proto3" json:"exchange_id,omitempty"` ShieldedTransactionFee int64 `protobuf:"varint,22,opt,name=shielded_transaction_fee,json=shieldedTransactionFee,proto3" json:"shielded_transaction_fee,omitempty"` } func (x *TransactionInfo) Reset() { *x = TransactionInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransactionInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionInfo) ProtoMessage() {} func (x *TransactionInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 TransactionInfo.ProtoReflect.Descriptor instead. func (*TransactionInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{17} } func (x *TransactionInfo) GetId() []byte { if x != nil { return x.Id } return nil } func (x *TransactionInfo) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *TransactionInfo) GetBlockNumber() int64 { if x != nil { return x.BlockNumber } return 0 } func (x *TransactionInfo) GetBlockTimeStamp() int64 { if x != nil { return x.BlockTimeStamp } return 0 } func (x *TransactionInfo) GetContractResult() [][]byte { if x != nil { return x.ContractResult } return nil } func (x *TransactionInfo) GetContractAddress() []byte { if x != nil { return x.ContractAddress } return nil } func (x *TransactionInfo) GetReceipt() *ResourceReceipt { if x != nil { return x.Receipt } return nil } func (x *TransactionInfo) GetLog() []*TransactionInfo_Log { if x != nil { return x.Log } return nil } func (x *TransactionInfo) GetResult() TransactionInfoCode { if x != nil { return x.Result } return TransactionInfo_SUCESS } func (x *TransactionInfo) GetResMessage() []byte { if x != nil { return x.ResMessage } return nil } func (x *TransactionInfo) GetAssetIssueID() string { if x != nil { return x.AssetIssueID } return "" } func (x *TransactionInfo) GetWithdrawAmount() int64 { if x != nil { return x.WithdrawAmount } return 0 } func (x *TransactionInfo) GetUnfreezeAmount() int64 { if x != nil { return x.UnfreezeAmount } return 0 } func (x *TransactionInfo) GetInternalTransactions() []*InternalTransaction { if x != nil { return x.InternalTransactions } return nil } func (x *TransactionInfo) GetExchangeReceivedAmount() int64 { if x != nil { return x.ExchangeReceivedAmount } return 0 } func (x *TransactionInfo) GetExchangeInjectAnotherAmount() int64 { if x != nil { return x.ExchangeInjectAnotherAmount } return 0 } func (x *TransactionInfo) GetExchangeWithdrawAnotherAmount() int64 { if x != nil { return x.ExchangeWithdrawAnotherAmount } return 0 } func (x *TransactionInfo) GetExchangeId() int64 { if x != nil { return x.ExchangeId } return 0 } func (x *TransactionInfo) GetShieldedTransactionFee() int64 { if x != nil { return x.ShieldedTransactionFee } return 0 } type TransactionRet struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockNumber int64 `protobuf:"varint,1,opt,name=blockNumber,proto3" json:"blockNumber,omitempty"` BlockTimeStamp int64 `protobuf:"varint,2,opt,name=blockTimeStamp,proto3" json:"blockTimeStamp,omitempty"` Transactioninfo []*TransactionInfo `protobuf:"bytes,3,rep,name=transactioninfo,proto3" json:"transactioninfo,omitempty"` } func (x *TransactionRet) Reset() { *x = TransactionRet{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransactionRet) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionRet) ProtoMessage() {} func (x *TransactionRet) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 TransactionRet.ProtoReflect.Descriptor instead. func (*TransactionRet) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{18} } func (x *TransactionRet) GetBlockNumber() int64 { if x != nil { return x.BlockNumber } return 0 } func (x *TransactionRet) GetBlockTimeStamp() int64 { if x != nil { return x.BlockTimeStamp } return 0 } func (x *TransactionRet) GetTransactioninfo() []*TransactionInfo { if x != nil { return x.Transactioninfo } return nil } type Transactions struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Transactions []*Transaction `protobuf:"bytes,1,rep,name=transactions,proto3" json:"transactions,omitempty"` } func (x *Transactions) Reset() { *x = Transactions{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Transactions) String() string { return protoimpl.X.MessageStringOf(x) } func (*Transactions) ProtoMessage() {} func (x *Transactions) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Transactions.ProtoReflect.Descriptor instead. func (*Transactions) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{19} } func (x *Transactions) GetTransactions() []*Transaction { if x != nil { return x.Transactions } return nil } type TransactionSign struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Transaction *Transaction `protobuf:"bytes,1,opt,name=transaction,proto3" json:"transaction,omitempty"` PrivateKey []byte `protobuf:"bytes,2,opt,name=privateKey,proto3" json:"privateKey,omitempty"` } func (x *TransactionSign) Reset() { *x = TransactionSign{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransactionSign) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionSign) ProtoMessage() {} func (x *TransactionSign) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 TransactionSign.ProtoReflect.Descriptor instead. func (*TransactionSign) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{20} } func (x *TransactionSign) GetTransaction() *Transaction { if x != nil { return x.Transaction } return nil } func (x *TransactionSign) GetPrivateKey() []byte { if x != nil { return x.PrivateKey } return nil } type BlockHeader struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RawData *BlockHeaderRaw `protobuf:"bytes,1,opt,name=raw_data,json=rawData,proto3" json:"raw_data,omitempty"` WitnessSignature []byte `protobuf:"bytes,2,opt,name=witness_signature,json=witnessSignature,proto3" json:"witness_signature,omitempty"` } func (x *BlockHeader) Reset() { *x = BlockHeader{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[21] 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_core_Tron_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 BlockHeader.ProtoReflect.Descriptor instead. func (*BlockHeader) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{21} } func (x *BlockHeader) GetRawData() *BlockHeaderRaw { if x != nil { return x.RawData } return nil } func (x *BlockHeader) GetWitnessSignature() []byte { if x != nil { return x.WitnessSignature } return nil } // block type Block struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Transactions []*Transaction `protobuf:"bytes,1,rep,name=transactions,proto3" json:"transactions,omitempty"` BlockHeader *BlockHeader `protobuf:"bytes,2,opt,name=block_header,json=blockHeader,proto3" json:"block_header,omitempty"` } func (x *Block) Reset() { *x = Block{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[22] 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_core_Tron_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 Block.ProtoReflect.Descriptor instead. func (*Block) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{22} } func (x *Block) GetTransactions() []*Transaction { if x != nil { return x.Transactions } return nil } func (x *Block) GetBlockHeader() *BlockHeader { if x != nil { return x.BlockHeader } return nil } type ChainInventory struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Ids []*ChainInventory_BlockId `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` RemainNum int64 `protobuf:"varint,2,opt,name=remain_num,json=remainNum,proto3" json:"remain_num,omitempty"` } func (x *ChainInventory) Reset() { *x = ChainInventory{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ChainInventory) String() string { return protoimpl.X.MessageStringOf(x) } func (*ChainInventory) ProtoMessage() {} func (x *ChainInventory) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 ChainInventory.ProtoReflect.Descriptor instead. func (*ChainInventory) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{23} } func (x *ChainInventory) GetIds() []*ChainInventory_BlockId { if x != nil { return x.Ids } return nil } func (x *ChainInventory) GetRemainNum() int64 { if x != nil { return x.RemainNum } return 0 } // Inventory type BlockInventory struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Ids []*BlockInventory_BlockId `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` Type BlockInventory_Type `protobuf:"varint,2,opt,name=type,proto3,enum=protocol.BlockInventory_Type" json:"type,omitempty"` } func (x *BlockInventory) Reset() { *x = BlockInventory{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BlockInventory) String() string { return protoimpl.X.MessageStringOf(x) } func (*BlockInventory) ProtoMessage() {} func (x *BlockInventory) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 BlockInventory.ProtoReflect.Descriptor instead. func (*BlockInventory) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{24} } func (x *BlockInventory) GetIds() []*BlockInventory_BlockId { if x != nil { return x.Ids } return nil } func (x *BlockInventory) GetType() BlockInventory_Type { if x != nil { return x.Type } return BlockInventory_SYNC } type Inventory struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Type Inventory_InventoryType `protobuf:"varint,1,opt,name=type,proto3,enum=protocol.Inventory_InventoryType" json:"type,omitempty"` Ids [][]byte `protobuf:"bytes,2,rep,name=ids,proto3" json:"ids,omitempty"` } func (x *Inventory) Reset() { *x = Inventory{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Inventory) String() string { return protoimpl.X.MessageStringOf(x) } func (*Inventory) ProtoMessage() {} func (x *Inventory) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Inventory.ProtoReflect.Descriptor instead. func (*Inventory) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{25} } func (x *Inventory) GetType() Inventory_InventoryType { if x != nil { return x.Type } return Inventory_TRX } func (x *Inventory) GetIds() [][]byte { if x != nil { return x.Ids } return nil } type Items struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Type Items_ItemType `protobuf:"varint,1,opt,name=type,proto3,enum=protocol.Items_ItemType" json:"type,omitempty"` Blocks []*Block `protobuf:"bytes,2,rep,name=blocks,proto3" json:"blocks,omitempty"` BlockHeaders []*BlockHeader `protobuf:"bytes,3,rep,name=block_headers,json=blockHeaders,proto3" json:"block_headers,omitempty"` Transactions []*Transaction `protobuf:"bytes,4,rep,name=transactions,proto3" json:"transactions,omitempty"` } func (x *Items) Reset() { *x = Items{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Items) String() string { return protoimpl.X.MessageStringOf(x) } func (*Items) ProtoMessage() {} func (x *Items) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Items.ProtoReflect.Descriptor instead. func (*Items) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{26} } func (x *Items) GetType() Items_ItemType { if x != nil { return x.Type } return Items_ERR } func (x *Items) GetBlocks() []*Block { if x != nil { return x.Blocks } return nil } func (x *Items) GetBlockHeaders() []*BlockHeader { if x != nil { return x.BlockHeaders } return nil } func (x *Items) GetTransactions() []*Transaction { if x != nil { return x.Transactions } return nil } // DynamicProperties type DynamicProperties struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields LastSolidityBlockNum int64 `protobuf:"varint,1,opt,name=last_solidity_block_num,json=lastSolidityBlockNum,proto3" json:"last_solidity_block_num,omitempty"` } func (x *DynamicProperties) Reset() { *x = DynamicProperties{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DynamicProperties) String() string { return protoimpl.X.MessageStringOf(x) } func (*DynamicProperties) ProtoMessage() {} func (x *DynamicProperties) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 DynamicProperties.ProtoReflect.Descriptor instead. func (*DynamicProperties) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{27} } func (x *DynamicProperties) GetLastSolidityBlockNum() int64 { if x != nil { return x.LastSolidityBlockNum } return 0 } type DisconnectMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Reason ReasonCode `protobuf:"varint,1,opt,name=reason,proto3,enum=protocol.ReasonCode" json:"reason,omitempty"` } func (x *DisconnectMessage) Reset() { *x = DisconnectMessage{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[28] 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_core_Tron_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 DisconnectMessage.ProtoReflect.Descriptor instead. func (*DisconnectMessage) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{28} } func (x *DisconnectMessage) GetReason() ReasonCode { if x != nil { return x.Reason } return ReasonCode_REQUESTED } type HelloMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields From *Endpoint `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` Version int32 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` GenesisBlockId *HelloMessage_BlockId `protobuf:"bytes,4,opt,name=genesisBlockId,proto3" json:"genesisBlockId,omitempty"` SolidBlockId *HelloMessage_BlockId `protobuf:"bytes,5,opt,name=solidBlockId,proto3" json:"solidBlockId,omitempty"` HeadBlockId *HelloMessage_BlockId `protobuf:"bytes,6,opt,name=headBlockId,proto3" json:"headBlockId,omitempty"` } func (x *HelloMessage) Reset() { *x = HelloMessage{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *HelloMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*HelloMessage) ProtoMessage() {} func (x *HelloMessage) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 HelloMessage.ProtoReflect.Descriptor instead. func (*HelloMessage) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{29} } func (x *HelloMessage) GetFrom() *Endpoint { if x != nil { return x.From } return nil } func (x *HelloMessage) GetVersion() int32 { if x != nil { return x.Version } return 0 } func (x *HelloMessage) GetTimestamp() int64 { if x != nil { return x.Timestamp } return 0 } func (x *HelloMessage) GetGenesisBlockId() *HelloMessage_BlockId { if x != nil { return x.GenesisBlockId } return nil } func (x *HelloMessage) GetSolidBlockId() *HelloMessage_BlockId { if x != nil { return x.SolidBlockId } return nil } func (x *HelloMessage) GetHeadBlockId() *HelloMessage_BlockId { if x != nil { return x.HeadBlockId } return nil } type InternalTransaction struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // internalTransaction identity, the root InternalTransaction hash // should equals to root transaction id. Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` // the one send trx (TBD: or token) via function CallerAddress []byte `protobuf:"bytes,2,opt,name=caller_address,json=callerAddress,proto3" json:"caller_address,omitempty"` // the one recieve trx (TBD: or token) via function TransferToAddress []byte `protobuf:"bytes,3,opt,name=transferTo_address,json=transferToAddress,proto3" json:"transferTo_address,omitempty"` CallValueInfo []*InternalTransaction_CallValueInfo `protobuf:"bytes,4,rep,name=callValueInfo,proto3" json:"callValueInfo,omitempty"` Note []byte `protobuf:"bytes,5,opt,name=note,proto3" json:"note,omitempty"` Rejected bool `protobuf:"varint,6,opt,name=rejected,proto3" json:"rejected,omitempty"` } func (x *InternalTransaction) Reset() { *x = InternalTransaction{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *InternalTransaction) String() string { return protoimpl.X.MessageStringOf(x) } func (*InternalTransaction) ProtoMessage() {} func (x *InternalTransaction) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 InternalTransaction.ProtoReflect.Descriptor instead. func (*InternalTransaction) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{30} } func (x *InternalTransaction) GetHash() []byte { if x != nil { return x.Hash } return nil } func (x *InternalTransaction) GetCallerAddress() []byte { if x != nil { return x.CallerAddress } return nil } func (x *InternalTransaction) GetTransferToAddress() []byte { if x != nil { return x.TransferToAddress } return nil } func (x *InternalTransaction) GetCallValueInfo() []*InternalTransaction_CallValueInfo { if x != nil { return x.CallValueInfo } return nil } func (x *InternalTransaction) GetNote() []byte { if x != nil { return x.Note } return nil } func (x *InternalTransaction) GetRejected() bool { if x != nil { return x.Rejected } return false } type DelegatedResourceAccountIndex struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Account []byte `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"` FromAccounts [][]byte `protobuf:"bytes,2,rep,name=fromAccounts,proto3" json:"fromAccounts,omitempty"` ToAccounts [][]byte `protobuf:"bytes,3,rep,name=toAccounts,proto3" json:"toAccounts,omitempty"` } func (x *DelegatedResourceAccountIndex) Reset() { *x = DelegatedResourceAccountIndex{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DelegatedResourceAccountIndex) String() string { return protoimpl.X.MessageStringOf(x) } func (*DelegatedResourceAccountIndex) ProtoMessage() {} func (x *DelegatedResourceAccountIndex) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 DelegatedResourceAccountIndex.ProtoReflect.Descriptor instead. func (*DelegatedResourceAccountIndex) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{31} } func (x *DelegatedResourceAccountIndex) GetAccount() []byte { if x != nil { return x.Account } return nil } func (x *DelegatedResourceAccountIndex) GetFromAccounts() [][]byte { if x != nil { return x.FromAccounts } return nil } func (x *DelegatedResourceAccountIndex) GetToAccounts() [][]byte { if x != nil { return x.ToAccounts } return nil } type NodeInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BeginSyncNum int64 `protobuf:"varint,1,opt,name=beginSyncNum,proto3" json:"beginSyncNum,omitempty"` Block string `protobuf:"bytes,2,opt,name=block,proto3" json:"block,omitempty"` SolidityBlock string `protobuf:"bytes,3,opt,name=solidityBlock,proto3" json:"solidityBlock,omitempty"` //connect information CurrentConnectCount int32 `protobuf:"varint,4,opt,name=currentConnectCount,proto3" json:"currentConnectCount,omitempty"` ActiveConnectCount int32 `protobuf:"varint,5,opt,name=activeConnectCount,proto3" json:"activeConnectCount,omitempty"` PassiveConnectCount int32 `protobuf:"varint,6,opt,name=passiveConnectCount,proto3" json:"passiveConnectCount,omitempty"` TotalFlow int64 `protobuf:"varint,7,opt,name=totalFlow,proto3" json:"totalFlow,omitempty"` PeerInfoList []*NodeInfo_PeerInfo `protobuf:"bytes,8,rep,name=peerInfoList,proto3" json:"peerInfoList,omitempty"` ConfigNodeInfo *NodeInfo_ConfigNodeInfo `protobuf:"bytes,9,opt,name=configNodeInfo,proto3" json:"configNodeInfo,omitempty"` MachineInfo *NodeInfo_MachineInfo `protobuf:"bytes,10,opt,name=machineInfo,proto3" json:"machineInfo,omitempty"` CheatWitnessInfoMap map[string]string `protobuf:"bytes,11,rep,name=cheatWitnessInfoMap,proto3" json:"cheatWitnessInfoMap,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (x *NodeInfo) Reset() { *x = NodeInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeInfo) ProtoMessage() {} func (x *NodeInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 NodeInfo.ProtoReflect.Descriptor instead. func (*NodeInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{32} } func (x *NodeInfo) GetBeginSyncNum() int64 { if x != nil { return x.BeginSyncNum } return 0 } func (x *NodeInfo) GetBlock() string { if x != nil { return x.Block } return "" } func (x *NodeInfo) GetSolidityBlock() string { if x != nil { return x.SolidityBlock } return "" } func (x *NodeInfo) GetCurrentConnectCount() int32 { if x != nil { return x.CurrentConnectCount } return 0 } func (x *NodeInfo) GetActiveConnectCount() int32 { if x != nil { return x.ActiveConnectCount } return 0 } func (x *NodeInfo) GetPassiveConnectCount() int32 { if x != nil { return x.PassiveConnectCount } return 0 } func (x *NodeInfo) GetTotalFlow() int64 { if x != nil { return x.TotalFlow } return 0 } func (x *NodeInfo) GetPeerInfoList() []*NodeInfo_PeerInfo { if x != nil { return x.PeerInfoList } return nil } func (x *NodeInfo) GetConfigNodeInfo() *NodeInfo_ConfigNodeInfo { if x != nil { return x.ConfigNodeInfo } return nil } func (x *NodeInfo) GetMachineInfo() *NodeInfo_MachineInfo { if x != nil { return x.MachineInfo } return nil } func (x *NodeInfo) GetCheatWitnessInfoMap() map[string]string { if x != nil { return x.CheatWitnessInfoMap } return nil } type ChainParameters_ChainParameter struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Value int64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"` } func (x *ChainParameters_ChainParameter) Reset() { *x = ChainParameters_ChainParameter{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ChainParameters_ChainParameter) String() string { return protoimpl.X.MessageStringOf(x) } func (*ChainParameters_ChainParameter) ProtoMessage() {} func (x *ChainParameters_ChainParameter) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 ChainParameters_ChainParameter.ProtoReflect.Descriptor instead. func (*ChainParameters_ChainParameter) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{4, 0} } func (x *ChainParameters_ChainParameter) GetKey() string { if x != nil { return x.Key } return "" } func (x *ChainParameters_ChainParameter) GetValue() int64 { if x != nil { return x.Value } return 0 } // frozen balance type Account_Frozen struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields FrozenBalance int64 `protobuf:"varint,1,opt,name=frozen_balance,json=frozenBalance,proto3" json:"frozen_balance,omitempty"` // the frozen trx balance ExpireTime int64 `protobuf:"varint,2,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"` // the expire time } func (x *Account_Frozen) Reset() { *x = Account_Frozen{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Account_Frozen) String() string { return protoimpl.X.MessageStringOf(x) } func (*Account_Frozen) ProtoMessage() {} func (x *Account_Frozen) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Account_Frozen.ProtoReflect.Descriptor instead. func (*Account_Frozen) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{5, 0} } func (x *Account_Frozen) GetFrozenBalance() int64 { if x != nil { return x.FrozenBalance } return 0 } func (x *Account_Frozen) GetExpireTime() int64 { if x != nil { return x.ExpireTime } return 0 } type Account_AccountResource struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // energy resource, get from frozen EnergyUsage int64 `protobuf:"varint,1,opt,name=energy_usage,json=energyUsage,proto3" json:"energy_usage,omitempty"` // the frozen balance for energy FrozenBalanceForEnergy *Account_Frozen `protobuf:"bytes,2,opt,name=frozen_balance_for_energy,json=frozenBalanceForEnergy,proto3" json:"frozen_balance_for_energy,omitempty"` LatestConsumeTimeForEnergy int64 `protobuf:"varint,3,opt,name=latest_consume_time_for_energy,json=latestConsumeTimeForEnergy,proto3" json:"latest_consume_time_for_energy,omitempty"` //Frozen balance provided by other accounts to this account AcquiredDelegatedFrozenBalanceForEnergy int64 `protobuf:"varint,4,opt,name=acquired_delegated_frozen_balance_for_energy,json=acquiredDelegatedFrozenBalanceForEnergy,proto3" json:"acquired_delegated_frozen_balance_for_energy,omitempty"` //Frozen balances provided to other accounts DelegatedFrozenBalanceForEnergy int64 `protobuf:"varint,5,opt,name=delegated_frozen_balance_for_energy,json=delegatedFrozenBalanceForEnergy,proto3" json:"delegated_frozen_balance_for_energy,omitempty"` // storage resource, get from market StorageLimit int64 `protobuf:"varint,6,opt,name=storage_limit,json=storageLimit,proto3" json:"storage_limit,omitempty"` StorageUsage int64 `protobuf:"varint,7,opt,name=storage_usage,json=storageUsage,proto3" json:"storage_usage,omitempty"` LatestExchangeStorageTime int64 `protobuf:"varint,8,opt,name=latest_exchange_storage_time,json=latestExchangeStorageTime,proto3" json:"latest_exchange_storage_time,omitempty"` } func (x *Account_AccountResource) Reset() { *x = Account_AccountResource{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Account_AccountResource) String() string { return protoimpl.X.MessageStringOf(x) } func (*Account_AccountResource) ProtoMessage() {} func (x *Account_AccountResource) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_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 Account_AccountResource.ProtoReflect.Descriptor instead. func (*Account_AccountResource) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{5, 7} } func (x *Account_AccountResource) GetEnergyUsage() int64 { if x != nil { return x.EnergyUsage } return 0 } func (x *Account_AccountResource) GetFrozenBalanceForEnergy() *Account_Frozen { if x != nil { return x.FrozenBalanceForEnergy } return nil } func (x *Account_AccountResource) GetLatestConsumeTimeForEnergy() int64 { if x != nil { return x.LatestConsumeTimeForEnergy } return 0 } func (x *Account_AccountResource) GetAcquiredDelegatedFrozenBalanceForEnergy() int64 { if x != nil { return x.AcquiredDelegatedFrozenBalanceForEnergy } return 0 } func (x *Account_AccountResource) GetDelegatedFrozenBalanceForEnergy() int64 { if x != nil { return x.DelegatedFrozenBalanceForEnergy } return 0 } func (x *Account_AccountResource) GetStorageLimit() int64 { if x != nil { return x.StorageLimit } return 0 } func (x *Account_AccountResource) GetStorageUsage() int64 { if x != nil { return x.StorageUsage } return 0 } func (x *Account_AccountResource) GetLatestExchangeStorageTime() int64 { if x != nil { return x.LatestExchangeStorageTime } return 0 } type TXInputRaw struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields TxID []byte `protobuf:"bytes,1,opt,name=txID,proto3" json:"txID,omitempty"` Vout int64 `protobuf:"varint,2,opt,name=vout,proto3" json:"vout,omitempty"` PubKey []byte `protobuf:"bytes,3,opt,name=pubKey,proto3" json:"pubKey,omitempty"` } func (x *TXInputRaw) Reset() { *x = TXInputRaw{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TXInputRaw) String() string { return protoimpl.X.MessageStringOf(x) } func (*TXInputRaw) ProtoMessage() {} func (x *TXInputRaw) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[43] 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 TXInputRaw.ProtoReflect.Descriptor instead. func (*TXInputRaw) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{13, 0} } func (x *TXInputRaw) GetTxID() []byte { if x != nil { return x.TxID } return nil } func (x *TXInputRaw) GetVout() int64 { if x != nil { return x.Vout } return 0 } func (x *TXInputRaw) GetPubKey() []byte { if x != nil { return x.PubKey } return nil } type Transaction_Contract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Type Transaction_Contract_ContractType `protobuf:"varint,1,opt,name=type,proto3,enum=protocol.Transaction_Contract_ContractType" json:"type,omitempty"` Parameter *any.Any `protobuf:"bytes,2,opt,name=parameter,proto3" json:"parameter,omitempty"` Provider []byte `protobuf:"bytes,3,opt,name=provider,proto3" json:"provider,omitempty"` ContractName []byte `protobuf:"bytes,4,opt,name=ContractName,proto3" json:"ContractName,omitempty"` PermissionId int32 `protobuf:"varint,5,opt,name=Permission_id,json=PermissionId,proto3" json:"Permission_id,omitempty"` } func (x *Transaction_Contract) Reset() { *x = Transaction_Contract{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Transaction_Contract) String() string { return protoimpl.X.MessageStringOf(x) } func (*Transaction_Contract) ProtoMessage() {} func (x *Transaction_Contract) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[44] 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 Transaction_Contract.ProtoReflect.Descriptor instead. func (*Transaction_Contract) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16, 0} } func (x *Transaction_Contract) GetType() Transaction_Contract_ContractType { if x != nil { return x.Type } return Transaction_Contract_AccountCreateContract } func (x *Transaction_Contract) GetParameter() *any.Any { if x != nil { return x.Parameter } return nil } func (x *Transaction_Contract) GetProvider() []byte { if x != nil { return x.Provider } return nil } func (x *Transaction_Contract) GetContractName() []byte { if x != nil { return x.ContractName } return nil } func (x *Transaction_Contract) GetPermissionId() int32 { if x != nil { return x.PermissionId } return 0 } type Transaction_Result struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Fee int64 `protobuf:"varint,1,opt,name=fee,proto3" json:"fee,omitempty"` Ret Transaction_ResultCode `protobuf:"varint,2,opt,name=ret,proto3,enum=protocol.Transaction_ResultCode" json:"ret,omitempty"` ContractRet Transaction_ResultContractResult `protobuf:"varint,3,opt,name=contractRet,proto3,enum=protocol.Transaction_ResultContractResult" json:"contractRet,omitempty"` AssetIssueID string `protobuf:"bytes,14,opt,name=assetIssueID,proto3" json:"assetIssueID,omitempty"` WithdrawAmount int64 `protobuf:"varint,15,opt,name=withdraw_amount,json=withdrawAmount,proto3" json:"withdraw_amount,omitempty"` UnfreezeAmount int64 `protobuf:"varint,16,opt,name=unfreeze_amount,json=unfreezeAmount,proto3" json:"unfreeze_amount,omitempty"` ExchangeReceivedAmount int64 `protobuf:"varint,18,opt,name=exchange_received_amount,json=exchangeReceivedAmount,proto3" json:"exchange_received_amount,omitempty"` ExchangeInjectAnotherAmount int64 `protobuf:"varint,19,opt,name=exchange_inject_another_amount,json=exchangeInjectAnotherAmount,proto3" json:"exchange_inject_another_amount,omitempty"` ExchangeWithdrawAnotherAmount int64 `protobuf:"varint,20,opt,name=exchange_withdraw_another_amount,json=exchangeWithdrawAnotherAmount,proto3" json:"exchange_withdraw_another_amount,omitempty"` ExchangeId int64 `protobuf:"varint,21,opt,name=exchange_id,json=exchangeId,proto3" json:"exchange_id,omitempty"` ShieldedTransactionFee int64 `protobuf:"varint,22,opt,name=shielded_transaction_fee,json=shieldedTransactionFee,proto3" json:"shielded_transaction_fee,omitempty"` } func (x *Transaction_Result) Reset() { *x = Transaction_Result{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Transaction_Result) String() string { return protoimpl.X.MessageStringOf(x) } func (*Transaction_Result) ProtoMessage() {} func (x *Transaction_Result) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[45] 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 Transaction_Result.ProtoReflect.Descriptor instead. func (*Transaction_Result) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16, 1} } func (x *Transaction_Result) GetFee() int64 { if x != nil { return x.Fee } return 0 } func (x *Transaction_Result) GetRet() Transaction_ResultCode { if x != nil { return x.Ret } return Transaction_Result_SUCESS } func (x *Transaction_Result) GetContractRet() Transaction_ResultContractResult { if x != nil { return x.ContractRet } return Transaction_Result_DEFAULT } func (x *Transaction_Result) GetAssetIssueID() string { if x != nil { return x.AssetIssueID } return "" } func (x *Transaction_Result) GetWithdrawAmount() int64 { if x != nil { return x.WithdrawAmount } return 0 } func (x *Transaction_Result) GetUnfreezeAmount() int64 { if x != nil { return x.UnfreezeAmount } return 0 } func (x *Transaction_Result) GetExchangeReceivedAmount() int64 { if x != nil { return x.ExchangeReceivedAmount } return 0 } func (x *Transaction_Result) GetExchangeInjectAnotherAmount() int64 { if x != nil { return x.ExchangeInjectAnotherAmount } return 0 } func (x *Transaction_Result) GetExchangeWithdrawAnotherAmount() int64 { if x != nil { return x.ExchangeWithdrawAnotherAmount } return 0 } func (x *Transaction_Result) GetExchangeId() int64 { if x != nil { return x.ExchangeId } return 0 } func (x *Transaction_Result) GetShieldedTransactionFee() int64 { if x != nil { return x.ShieldedTransactionFee } return 0 } type TransactionRaw struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RefBlockBytes []byte `protobuf:"bytes,1,opt,name=ref_block_bytes,json=refBlockBytes,proto3" json:"ref_block_bytes,omitempty"` RefBlockNum int64 `protobuf:"varint,3,opt,name=ref_block_num,json=refBlockNum,proto3" json:"ref_block_num,omitempty"` RefBlockHash []byte `protobuf:"bytes,4,opt,name=ref_block_hash,json=refBlockHash,proto3" json:"ref_block_hash,omitempty"` Expiration int64 `protobuf:"varint,8,opt,name=expiration,proto3" json:"expiration,omitempty"` Auths []*Authority `protobuf:"bytes,9,rep,name=auths,proto3" json:"auths,omitempty"` // transaction note Data []byte `protobuf:"bytes,10,opt,name=data,proto3" json:"data,omitempty"` //only support size = 1, repeated list here for extension Contract []*Transaction_Contract `protobuf:"bytes,11,rep,name=contract,proto3" json:"contract,omitempty"` // scripts not used Scripts []byte `protobuf:"bytes,12,opt,name=scripts,proto3" json:"scripts,omitempty"` Timestamp int64 `protobuf:"varint,14,opt,name=timestamp,proto3" json:"timestamp,omitempty"` FeeLimit int64 `protobuf:"varint,18,opt,name=fee_limit,json=feeLimit,proto3" json:"fee_limit,omitempty"` } func (x *TransactionRaw) Reset() { *x = TransactionRaw{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[46] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransactionRaw) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionRaw) ProtoMessage() {} func (x *TransactionRaw) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[46] 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 TransactionRaw.ProtoReflect.Descriptor instead. func (*TransactionRaw) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{16, 2} } func (x *TransactionRaw) GetRefBlockBytes() []byte { if x != nil { return x.RefBlockBytes } return nil } func (x *TransactionRaw) GetRefBlockNum() int64 { if x != nil { return x.RefBlockNum } return 0 } func (x *TransactionRaw) GetRefBlockHash() []byte { if x != nil { return x.RefBlockHash } return nil } func (x *TransactionRaw) GetExpiration() int64 { if x != nil { return x.Expiration } return 0 } func (x *TransactionRaw) GetAuths() []*Authority { if x != nil { return x.Auths } return nil } func (x *TransactionRaw) GetData() []byte { if x != nil { return x.Data } return nil } func (x *TransactionRaw) GetContract() []*Transaction_Contract { if x != nil { return x.Contract } return nil } func (x *TransactionRaw) GetScripts() []byte { if x != nil { return x.Scripts } return nil } func (x *TransactionRaw) GetTimestamp() int64 { if x != nil { return x.Timestamp } return 0 } func (x *TransactionRaw) GetFeeLimit() int64 { if x != nil { return x.FeeLimit } return 0 } type TransactionInfo_Log struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Topics [][]byte `protobuf:"bytes,2,rep,name=topics,proto3" json:"topics,omitempty"` Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` } func (x *TransactionInfo_Log) Reset() { *x = TransactionInfo_Log{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[47] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransactionInfo_Log) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionInfo_Log) ProtoMessage() {} func (x *TransactionInfo_Log) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[47] 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 TransactionInfo_Log.ProtoReflect.Descriptor instead. func (*TransactionInfo_Log) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{17, 0} } func (x *TransactionInfo_Log) GetAddress() []byte { if x != nil { return x.Address } return nil } func (x *TransactionInfo_Log) GetTopics() [][]byte { if x != nil { return x.Topics } return nil } func (x *TransactionInfo_Log) GetData() []byte { if x != nil { return x.Data } return nil } type BlockHeaderRaw struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Timestamp int64 `protobuf:"varint,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` TxTrieRoot []byte `protobuf:"bytes,2,opt,name=txTrieRoot,proto3" json:"txTrieRoot,omitempty"` ParentHash []byte `protobuf:"bytes,3,opt,name=parentHash,proto3" json:"parentHash,omitempty"` //bytes nonce = 5; //bytes difficulty = 6; Number int64 `protobuf:"varint,7,opt,name=number,proto3" json:"number,omitempty"` WitnessId int64 `protobuf:"varint,8,opt,name=witness_id,json=witnessId,proto3" json:"witness_id,omitempty"` WitnessAddress []byte `protobuf:"bytes,9,opt,name=witness_address,json=witnessAddress,proto3" json:"witness_address,omitempty"` Version int32 `protobuf:"varint,10,opt,name=version,proto3" json:"version,omitempty"` AccountStateRoot []byte `protobuf:"bytes,11,opt,name=accountStateRoot,proto3" json:"accountStateRoot,omitempty"` } func (x *BlockHeaderRaw) Reset() { *x = BlockHeaderRaw{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BlockHeaderRaw) String() string { return protoimpl.X.MessageStringOf(x) } func (*BlockHeaderRaw) ProtoMessage() {} func (x *BlockHeaderRaw) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[48] 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 BlockHeaderRaw.ProtoReflect.Descriptor instead. func (*BlockHeaderRaw) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{21, 0} } func (x *BlockHeaderRaw) GetTimestamp() int64 { if x != nil { return x.Timestamp } return 0 } func (x *BlockHeaderRaw) GetTxTrieRoot() []byte { if x != nil { return x.TxTrieRoot } return nil } func (x *BlockHeaderRaw) GetParentHash() []byte { if x != nil { return x.ParentHash } return nil } func (x *BlockHeaderRaw) GetNumber() int64 { if x != nil { return x.Number } return 0 } func (x *BlockHeaderRaw) GetWitnessId() int64 { if x != nil { return x.WitnessId } return 0 } func (x *BlockHeaderRaw) GetWitnessAddress() []byte { if x != nil { return x.WitnessAddress } return nil } func (x *BlockHeaderRaw) GetVersion() int32 { if x != nil { return x.Version } return 0 } func (x *BlockHeaderRaw) GetAccountStateRoot() []byte { if x != nil { return x.AccountStateRoot } return nil } type ChainInventory_BlockId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` Number int64 `protobuf:"varint,2,opt,name=number,proto3" json:"number,omitempty"` } func (x *ChainInventory_BlockId) Reset() { *x = ChainInventory_BlockId{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ChainInventory_BlockId) String() string { return protoimpl.X.MessageStringOf(x) } func (*ChainInventory_BlockId) ProtoMessage() {} func (x *ChainInventory_BlockId) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[49] 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 ChainInventory_BlockId.ProtoReflect.Descriptor instead. func (*ChainInventory_BlockId) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{23, 0} } func (x *ChainInventory_BlockId) GetHash() []byte { if x != nil { return x.Hash } return nil } func (x *ChainInventory_BlockId) GetNumber() int64 { if x != nil { return x.Number } return 0 } type BlockInventory_BlockId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` Number int64 `protobuf:"varint,2,opt,name=number,proto3" json:"number,omitempty"` } func (x *BlockInventory_BlockId) Reset() { *x = BlockInventory_BlockId{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BlockInventory_BlockId) String() string { return protoimpl.X.MessageStringOf(x) } func (*BlockInventory_BlockId) ProtoMessage() {} func (x *BlockInventory_BlockId) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[50] 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 BlockInventory_BlockId.ProtoReflect.Descriptor instead. func (*BlockInventory_BlockId) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{24, 0} } func (x *BlockInventory_BlockId) GetHash() []byte { if x != nil { return x.Hash } return nil } func (x *BlockInventory_BlockId) GetNumber() int64 { if x != nil { return x.Number } return 0 } type HelloMessage_BlockId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` Number int64 `protobuf:"varint,2,opt,name=number,proto3" json:"number,omitempty"` } func (x *HelloMessage_BlockId) Reset() { *x = HelloMessage_BlockId{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *HelloMessage_BlockId) String() string { return protoimpl.X.MessageStringOf(x) } func (*HelloMessage_BlockId) ProtoMessage() {} func (x *HelloMessage_BlockId) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[51] 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 HelloMessage_BlockId.ProtoReflect.Descriptor instead. func (*HelloMessage_BlockId) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{29, 0} } func (x *HelloMessage_BlockId) GetHash() []byte { if x != nil { return x.Hash } return nil } func (x *HelloMessage_BlockId) GetNumber() int64 { if x != nil { return x.Number } return 0 } type InternalTransaction_CallValueInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // trx (TBD: or token) value CallValue int64 `protobuf:"varint,1,opt,name=callValue,proto3" json:"callValue,omitempty"` // TBD: tokenName, trx should be empty TokenId string `protobuf:"bytes,2,opt,name=tokenId,proto3" json:"tokenId,omitempty"` } func (x *InternalTransaction_CallValueInfo) Reset() { *x = InternalTransaction_CallValueInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *InternalTransaction_CallValueInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*InternalTransaction_CallValueInfo) ProtoMessage() {} func (x *InternalTransaction_CallValueInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[52] 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 InternalTransaction_CallValueInfo.ProtoReflect.Descriptor instead. func (*InternalTransaction_CallValueInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{30, 0} } func (x *InternalTransaction_CallValueInfo) GetCallValue() int64 { if x != nil { return x.CallValue } return 0 } func (x *InternalTransaction_CallValueInfo) GetTokenId() string { if x != nil { return x.TokenId } return "" } type NodeInfo_PeerInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields LastSyncBlock string `protobuf:"bytes,1,opt,name=lastSyncBlock,proto3" json:"lastSyncBlock,omitempty"` RemainNum int64 `protobuf:"varint,2,opt,name=remainNum,proto3" json:"remainNum,omitempty"` LastBlockUpdateTime int64 `protobuf:"varint,3,opt,name=lastBlockUpdateTime,proto3" json:"lastBlockUpdateTime,omitempty"` SyncFlag bool `protobuf:"varint,4,opt,name=syncFlag,proto3" json:"syncFlag,omitempty"` HeadBlockTimeWeBothHave int64 `protobuf:"varint,5,opt,name=headBlockTimeWeBothHave,proto3" json:"headBlockTimeWeBothHave,omitempty"` NeedSyncFromPeer bool `protobuf:"varint,6,opt,name=needSyncFromPeer,proto3" json:"needSyncFromPeer,omitempty"` NeedSyncFromUs bool `protobuf:"varint,7,opt,name=needSyncFromUs,proto3" json:"needSyncFromUs,omitempty"` Host string `protobuf:"bytes,8,opt,name=host,proto3" json:"host,omitempty"` Port int32 `protobuf:"varint,9,opt,name=port,proto3" json:"port,omitempty"` NodeId string `protobuf:"bytes,10,opt,name=nodeId,proto3" json:"nodeId,omitempty"` ConnectTime int64 `protobuf:"varint,11,opt,name=connectTime,proto3" json:"connectTime,omitempty"` AvgLatency float64 `protobuf:"fixed64,12,opt,name=avgLatency,proto3" json:"avgLatency,omitempty"` SyncToFetchSize int32 `protobuf:"varint,13,opt,name=syncToFetchSize,proto3" json:"syncToFetchSize,omitempty"` SyncToFetchSizePeekNum int64 `protobuf:"varint,14,opt,name=syncToFetchSizePeekNum,proto3" json:"syncToFetchSizePeekNum,omitempty"` SyncBlockRequestedSize int32 `protobuf:"varint,15,opt,name=syncBlockRequestedSize,proto3" json:"syncBlockRequestedSize,omitempty"` UnFetchSynNum int64 `protobuf:"varint,16,opt,name=unFetchSynNum,proto3" json:"unFetchSynNum,omitempty"` BlockInPorcSize int32 `protobuf:"varint,17,opt,name=blockInPorcSize,proto3" json:"blockInPorcSize,omitempty"` HeadBlockWeBothHave string `protobuf:"bytes,18,opt,name=headBlockWeBothHave,proto3" json:"headBlockWeBothHave,omitempty"` IsActive bool `protobuf:"varint,19,opt,name=isActive,proto3" json:"isActive,omitempty"` Score int32 `protobuf:"varint,20,opt,name=score,proto3" json:"score,omitempty"` NodeCount int32 `protobuf:"varint,21,opt,name=nodeCount,proto3" json:"nodeCount,omitempty"` InFlow int64 `protobuf:"varint,22,opt,name=inFlow,proto3" json:"inFlow,omitempty"` DisconnectTimes int32 `protobuf:"varint,23,opt,name=disconnectTimes,proto3" json:"disconnectTimes,omitempty"` LocalDisconnectReason string `protobuf:"bytes,24,opt,name=localDisconnectReason,proto3" json:"localDisconnectReason,omitempty"` RemoteDisconnectReason string `protobuf:"bytes,25,opt,name=remoteDisconnectReason,proto3" json:"remoteDisconnectReason,omitempty"` } func (x *NodeInfo_PeerInfo) Reset() { *x = NodeInfo_PeerInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[54] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeInfo_PeerInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeInfo_PeerInfo) ProtoMessage() {} func (x *NodeInfo_PeerInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[54] 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 NodeInfo_PeerInfo.ProtoReflect.Descriptor instead. func (*NodeInfo_PeerInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{32, 1} } func (x *NodeInfo_PeerInfo) GetLastSyncBlock() string { if x != nil { return x.LastSyncBlock } return "" } func (x *NodeInfo_PeerInfo) GetRemainNum() int64 { if x != nil { return x.RemainNum } return 0 } func (x *NodeInfo_PeerInfo) GetLastBlockUpdateTime() int64 { if x != nil { return x.LastBlockUpdateTime } return 0 } func (x *NodeInfo_PeerInfo) GetSyncFlag() bool { if x != nil { return x.SyncFlag } return false } func (x *NodeInfo_PeerInfo) GetHeadBlockTimeWeBothHave() int64 { if x != nil { return x.HeadBlockTimeWeBothHave } return 0 } func (x *NodeInfo_PeerInfo) GetNeedSyncFromPeer() bool { if x != nil { return x.NeedSyncFromPeer } return false } func (x *NodeInfo_PeerInfo) GetNeedSyncFromUs() bool { if x != nil { return x.NeedSyncFromUs } return false } func (x *NodeInfo_PeerInfo) GetHost() string { if x != nil { return x.Host } return "" } func (x *NodeInfo_PeerInfo) GetPort() int32 { if x != nil { return x.Port } return 0 } func (x *NodeInfo_PeerInfo) GetNodeId() string { if x != nil { return x.NodeId } return "" } func (x *NodeInfo_PeerInfo) GetConnectTime() int64 { if x != nil { return x.ConnectTime } return 0 } func (x *NodeInfo_PeerInfo) GetAvgLatency() float64 { if x != nil { return x.AvgLatency } return 0 } func (x *NodeInfo_PeerInfo) GetSyncToFetchSize() int32 { if x != nil { return x.SyncToFetchSize } return 0 } func (x *NodeInfo_PeerInfo) GetSyncToFetchSizePeekNum() int64 { if x != nil { return x.SyncToFetchSizePeekNum } return 0 } func (x *NodeInfo_PeerInfo) GetSyncBlockRequestedSize() int32 { if x != nil { return x.SyncBlockRequestedSize } return 0 } func (x *NodeInfo_PeerInfo) GetUnFetchSynNum() int64 { if x != nil { return x.UnFetchSynNum } return 0 } func (x *NodeInfo_PeerInfo) GetBlockInPorcSize() int32 { if x != nil { return x.BlockInPorcSize } return 0 } func (x *NodeInfo_PeerInfo) GetHeadBlockWeBothHave() string { if x != nil { return x.HeadBlockWeBothHave } return "" } func (x *NodeInfo_PeerInfo) GetIsActive() bool { if x != nil { return x.IsActive } return false } func (x *NodeInfo_PeerInfo) GetScore() int32 { if x != nil { return x.Score } return 0 } func (x *NodeInfo_PeerInfo) GetNodeCount() int32 { if x != nil { return x.NodeCount } return 0 } func (x *NodeInfo_PeerInfo) GetInFlow() int64 { if x != nil { return x.InFlow } return 0 } func (x *NodeInfo_PeerInfo) GetDisconnectTimes() int32 { if x != nil { return x.DisconnectTimes } return 0 } func (x *NodeInfo_PeerInfo) GetLocalDisconnectReason() string { if x != nil { return x.LocalDisconnectReason } return "" } func (x *NodeInfo_PeerInfo) GetRemoteDisconnectReason() string { if x != nil { return x.RemoteDisconnectReason } return "" } type NodeInfo_ConfigNodeInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields CodeVersion string `protobuf:"bytes,1,opt,name=codeVersion,proto3" json:"codeVersion,omitempty"` P2PVersion string `protobuf:"bytes,2,opt,name=p2pVersion,proto3" json:"p2pVersion,omitempty"` ListenPort int32 `protobuf:"varint,3,opt,name=listenPort,proto3" json:"listenPort,omitempty"` DiscoverEnable bool `protobuf:"varint,4,opt,name=discoverEnable,proto3" json:"discoverEnable,omitempty"` ActiveNodeSize int32 `protobuf:"varint,5,opt,name=activeNodeSize,proto3" json:"activeNodeSize,omitempty"` PassiveNodeSize int32 `protobuf:"varint,6,opt,name=passiveNodeSize,proto3" json:"passiveNodeSize,omitempty"` SendNodeSize int32 `protobuf:"varint,7,opt,name=sendNodeSize,proto3" json:"sendNodeSize,omitempty"` MaxConnectCount int32 `protobuf:"varint,8,opt,name=maxConnectCount,proto3" json:"maxConnectCount,omitempty"` SameIpMaxConnectCount int32 `protobuf:"varint,9,opt,name=sameIpMaxConnectCount,proto3" json:"sameIpMaxConnectCount,omitempty"` BackupListenPort int32 `protobuf:"varint,10,opt,name=backupListenPort,proto3" json:"backupListenPort,omitempty"` BackupMemberSize int32 `protobuf:"varint,11,opt,name=backupMemberSize,proto3" json:"backupMemberSize,omitempty"` BackupPriority int32 `protobuf:"varint,12,opt,name=backupPriority,proto3" json:"backupPriority,omitempty"` DbVersion int32 `protobuf:"varint,13,opt,name=dbVersion,proto3" json:"dbVersion,omitempty"` MinParticipationRate int32 `protobuf:"varint,14,opt,name=minParticipationRate,proto3" json:"minParticipationRate,omitempty"` SupportConstant bool `protobuf:"varint,15,opt,name=supportConstant,proto3" json:"supportConstant,omitempty"` MinTimeRatio float64 `protobuf:"fixed64,16,opt,name=minTimeRatio,proto3" json:"minTimeRatio,omitempty"` MaxTimeRatio float64 `protobuf:"fixed64,17,opt,name=maxTimeRatio,proto3" json:"maxTimeRatio,omitempty"` AllowCreationOfContracts int64 `protobuf:"varint,18,opt,name=allowCreationOfContracts,proto3" json:"allowCreationOfContracts,omitempty"` AllowAdaptiveEnergy int64 `protobuf:"varint,19,opt,name=allowAdaptiveEnergy,proto3" json:"allowAdaptiveEnergy,omitempty"` } func (x *NodeInfo_ConfigNodeInfo) Reset() { *x = NodeInfo_ConfigNodeInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[55] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeInfo_ConfigNodeInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeInfo_ConfigNodeInfo) ProtoMessage() {} func (x *NodeInfo_ConfigNodeInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[55] 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 NodeInfo_ConfigNodeInfo.ProtoReflect.Descriptor instead. func (*NodeInfo_ConfigNodeInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{32, 2} } func (x *NodeInfo_ConfigNodeInfo) GetCodeVersion() string { if x != nil { return x.CodeVersion } return "" } func (x *NodeInfo_ConfigNodeInfo) GetP2PVersion() string { if x != nil { return x.P2PVersion } return "" } func (x *NodeInfo_ConfigNodeInfo) GetListenPort() int32 { if x != nil { return x.ListenPort } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetDiscoverEnable() bool { if x != nil { return x.DiscoverEnable } return false } func (x *NodeInfo_ConfigNodeInfo) GetActiveNodeSize() int32 { if x != nil { return x.ActiveNodeSize } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetPassiveNodeSize() int32 { if x != nil { return x.PassiveNodeSize } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetSendNodeSize() int32 { if x != nil { return x.SendNodeSize } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetMaxConnectCount() int32 { if x != nil { return x.MaxConnectCount } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetSameIpMaxConnectCount() int32 { if x != nil { return x.SameIpMaxConnectCount } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetBackupListenPort() int32 { if x != nil { return x.BackupListenPort } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetBackupMemberSize() int32 { if x != nil { return x.BackupMemberSize } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetBackupPriority() int32 { if x != nil { return x.BackupPriority } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetDbVersion() int32 { if x != nil { return x.DbVersion } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetMinParticipationRate() int32 { if x != nil { return x.MinParticipationRate } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetSupportConstant() bool { if x != nil { return x.SupportConstant } return false } func (x *NodeInfo_ConfigNodeInfo) GetMinTimeRatio() float64 { if x != nil { return x.MinTimeRatio } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetMaxTimeRatio() float64 { if x != nil { return x.MaxTimeRatio } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetAllowCreationOfContracts() int64 { if x != nil { return x.AllowCreationOfContracts } return 0 } func (x *NodeInfo_ConfigNodeInfo) GetAllowAdaptiveEnergy() int64 { if x != nil { return x.AllowAdaptiveEnergy } return 0 } type NodeInfo_MachineInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ThreadCount int32 `protobuf:"varint,1,opt,name=threadCount,proto3" json:"threadCount,omitempty"` DeadLockThreadCount int32 `protobuf:"varint,2,opt,name=deadLockThreadCount,proto3" json:"deadLockThreadCount,omitempty"` CpuCount int32 `protobuf:"varint,3,opt,name=cpuCount,proto3" json:"cpuCount,omitempty"` TotalMemory int64 `protobuf:"varint,4,opt,name=totalMemory,proto3" json:"totalMemory,omitempty"` FreeMemory int64 `protobuf:"varint,5,opt,name=freeMemory,proto3" json:"freeMemory,omitempty"` CpuRate float64 `protobuf:"fixed64,6,opt,name=cpuRate,proto3" json:"cpuRate,omitempty"` JavaVersion string `protobuf:"bytes,7,opt,name=javaVersion,proto3" json:"javaVersion,omitempty"` OsName string `protobuf:"bytes,8,opt,name=osName,proto3" json:"osName,omitempty"` JvmTotalMemoery int64 `protobuf:"varint,9,opt,name=jvmTotalMemoery,proto3" json:"jvmTotalMemoery,omitempty"` JvmFreeMemory int64 `protobuf:"varint,10,opt,name=jvmFreeMemory,proto3" json:"jvmFreeMemory,omitempty"` ProcessCpuRate float64 `protobuf:"fixed64,11,opt,name=processCpuRate,proto3" json:"processCpuRate,omitempty"` MemoryDescInfoList []*NodeInfo_MachineInfo_MemoryDescInfo `protobuf:"bytes,12,rep,name=memoryDescInfoList,proto3" json:"memoryDescInfoList,omitempty"` DeadLockThreadInfoList []*NodeInfo_MachineInfo_DeadLockThreadInfo `protobuf:"bytes,13,rep,name=deadLockThreadInfoList,proto3" json:"deadLockThreadInfoList,omitempty"` } func (x *NodeInfo_MachineInfo) Reset() { *x = NodeInfo_MachineInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[56] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeInfo_MachineInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeInfo_MachineInfo) ProtoMessage() {} func (x *NodeInfo_MachineInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[56] 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 NodeInfo_MachineInfo.ProtoReflect.Descriptor instead. func (*NodeInfo_MachineInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{32, 3} } func (x *NodeInfo_MachineInfo) GetThreadCount() int32 { if x != nil { return x.ThreadCount } return 0 } func (x *NodeInfo_MachineInfo) GetDeadLockThreadCount() int32 { if x != nil { return x.DeadLockThreadCount } return 0 } func (x *NodeInfo_MachineInfo) GetCpuCount() int32 { if x != nil { return x.CpuCount } return 0 } func (x *NodeInfo_MachineInfo) GetTotalMemory() int64 { if x != nil { return x.TotalMemory } return 0 } func (x *NodeInfo_MachineInfo) GetFreeMemory() int64 { if x != nil { return x.FreeMemory } return 0 } func (x *NodeInfo_MachineInfo) GetCpuRate() float64 { if x != nil { return x.CpuRate } return 0 } func (x *NodeInfo_MachineInfo) GetJavaVersion() string { if x != nil { return x.JavaVersion } return "" } func (x *NodeInfo_MachineInfo) GetOsName() string { if x != nil { return x.OsName } return "" } func (x *NodeInfo_MachineInfo) GetJvmTotalMemoery() int64 { if x != nil { return x.JvmTotalMemoery } return 0 } func (x *NodeInfo_MachineInfo) GetJvmFreeMemory() int64 { if x != nil { return x.JvmFreeMemory } return 0 } func (x *NodeInfo_MachineInfo) GetProcessCpuRate() float64 { if x != nil { return x.ProcessCpuRate } return 0 } func (x *NodeInfo_MachineInfo) GetMemoryDescInfoList() []*NodeInfo_MachineInfo_MemoryDescInfo { if x != nil { return x.MemoryDescInfoList } return nil } func (x *NodeInfo_MachineInfo) GetDeadLockThreadInfoList() []*NodeInfo_MachineInfo_DeadLockThreadInfo { if x != nil { return x.DeadLockThreadInfoList } return nil } type NodeInfo_MachineInfo_MemoryDescInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` InitSize int64 `protobuf:"varint,2,opt,name=initSize,proto3" json:"initSize,omitempty"` UseSize int64 `protobuf:"varint,3,opt,name=useSize,proto3" json:"useSize,omitempty"` MaxSize int64 `protobuf:"varint,4,opt,name=maxSize,proto3" json:"maxSize,omitempty"` UseRate float64 `protobuf:"fixed64,5,opt,name=useRate,proto3" json:"useRate,omitempty"` } func (x *NodeInfo_MachineInfo_MemoryDescInfo) Reset() { *x = NodeInfo_MachineInfo_MemoryDescInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[57] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeInfo_MachineInfo_MemoryDescInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeInfo_MachineInfo_MemoryDescInfo) ProtoMessage() {} func (x *NodeInfo_MachineInfo_MemoryDescInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[57] 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 NodeInfo_MachineInfo_MemoryDescInfo.ProtoReflect.Descriptor instead. func (*NodeInfo_MachineInfo_MemoryDescInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{32, 3, 0} } func (x *NodeInfo_MachineInfo_MemoryDescInfo) GetName() string { if x != nil { return x.Name } return "" } func (x *NodeInfo_MachineInfo_MemoryDescInfo) GetInitSize() int64 { if x != nil { return x.InitSize } return 0 } func (x *NodeInfo_MachineInfo_MemoryDescInfo) GetUseSize() int64 { if x != nil { return x.UseSize } return 0 } func (x *NodeInfo_MachineInfo_MemoryDescInfo) GetMaxSize() int64 { if x != nil { return x.MaxSize } return 0 } func (x *NodeInfo_MachineInfo_MemoryDescInfo) GetUseRate() float64 { if x != nil { return x.UseRate } return 0 } type NodeInfo_MachineInfo_DeadLockThreadInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` LockName string `protobuf:"bytes,2,opt,name=lockName,proto3" json:"lockName,omitempty"` LockOwner string `protobuf:"bytes,3,opt,name=lockOwner,proto3" json:"lockOwner,omitempty"` State string `protobuf:"bytes,4,opt,name=state,proto3" json:"state,omitempty"` BlockTime int64 `protobuf:"varint,5,opt,name=blockTime,proto3" json:"blockTime,omitempty"` WaitTime int64 `protobuf:"varint,6,opt,name=waitTime,proto3" json:"waitTime,omitempty"` StackTrace string `protobuf:"bytes,7,opt,name=stackTrace,proto3" json:"stackTrace,omitempty"` } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) Reset() { *x = NodeInfo_MachineInfo_DeadLockThreadInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_Tron_proto_msgTypes[58] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeInfo_MachineInfo_DeadLockThreadInfo) ProtoMessage() {} func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) ProtoReflect() protoreflect.Message { mi := &file_core_Tron_proto_msgTypes[58] 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 NodeInfo_MachineInfo_DeadLockThreadInfo.ProtoReflect.Descriptor instead. func (*NodeInfo_MachineInfo_DeadLockThreadInfo) Descriptor() ([]byte, []int) { return file_core_Tron_proto_rawDescGZIP(), []int{32, 3, 1} } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetName() string { if x != nil { return x.Name } return "" } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetLockName() string { if x != nil { return x.LockName } return "" } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetLockOwner() string { if x != nil { return x.LockOwner } return "" } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetState() string { if x != nil { return x.State } return "" } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetBlockTime() int64 { if x != nil { return x.BlockTime } return 0 } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetWaitTime() int64 { if x != nil { return x.WaitTime } return 0 } func (x *NodeInfo_MachineInfo_DeadLockThreadInfo) GetStackTrace() string { if x != nil { return x.StackTrace } return "" } var File_core_Tron_proto protoreflect.FileDescriptor var file_core_Tron_proto_rawDesc = []byte{ 0x0a, 0x0f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x54, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x13, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x39, 0x0a, 0x09, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x48, 0x0a, 0x04, 0x56, 0x6f, 0x74, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x76, 0x6f, 0x74, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x76, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0xb4, 0x03, 0x0a, 0x08, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x42, 0x0a, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x61, 0x6c, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x61, 0x6c, 0x73, 0x12, 0x2e, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x1a, 0x3d, 0x0a, 0x0f, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x41, 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x50, 0x45, 0x4e, 0x44, 0x49, 0x4e, 0x47, 0x10, 0x00, 0x12, 0x0f, 0x0a, 0x0b, 0x44, 0x49, 0x53, 0x41, 0x50, 0x50, 0x52, 0x4f, 0x56, 0x45, 0x44, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x41, 0x50, 0x50, 0x52, 0x4f, 0x56, 0x45, 0x44, 0x10, 0x02, 0x12, 0x0c, 0x0a, 0x08, 0x43, 0x41, 0x4e, 0x43, 0x45, 0x4c, 0x45, 0x44, 0x10, 0x03, 0x22, 0xa5, 0x02, 0x0a, 0x08, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x64, 0x12, 0x27, 0x0a, 0x0f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x66, 0x69, 0x72, 0x73, 0x74, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x2e, 0x0a, 0x13, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x66, 0x69, 0x72, 0x73, 0x74, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x26, 0x0a, 0x0f, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x30, 0x0a, 0x14, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x12, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x22, 0x9d, 0x01, 0x0a, 0x0f, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x12, 0x50, 0x0a, 0x0e, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x2e, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x52, 0x0e, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x1a, 0x38, 0x0a, 0x0e, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xb0, 0x16, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x21, 0x0a, 0x0c, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x29, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x24, 0x0a, 0x05, 0x76, 0x6f, 0x74, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x74, 0x65, 0x52, 0x05, 0x76, 0x6f, 0x74, 0x65, 0x73, 0x12, 0x32, 0x0a, 0x05, 0x61, 0x73, 0x73, 0x65, 0x74, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x41, 0x73, 0x73, 0x65, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x05, 0x61, 0x73, 0x73, 0x65, 0x74, 0x12, 0x38, 0x0a, 0x07, 0x61, 0x73, 0x73, 0x65, 0x74, 0x56, 0x32, 0x18, 0x38, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x41, 0x73, 0x73, 0x65, 0x74, 0x56, 0x32, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x61, 0x73, 0x73, 0x65, 0x74, 0x56, 0x32, 0x12, 0x30, 0x0a, 0x06, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x52, 0x06, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x65, 0x74, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x6e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x63, 0x0a, 0x2f, 0x61, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x5f, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x62, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x18, 0x29, 0x20, 0x01, 0x28, 0x03, 0x52, 0x2a, 0x61, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x44, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x42, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x12, 0x52, 0x0a, 0x26, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x62, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x18, 0x2a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x22, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x42, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x30, 0x0a, 0x14, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x6f, 0x70, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x12, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x4f, 0x70, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x30, 0x0a, 0x14, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x03, 0x52, 0x12, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x69, 0x73, 0x5f, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x69, 0x73, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x12, 0x21, 0x0a, 0x0c, 0x69, 0x73, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0b, 0x69, 0x73, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x65, 0x12, 0x3d, 0x0a, 0x0d, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x18, 0x10, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x52, 0x0c, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x53, 0x75, 0x70, 0x70, 0x6c, 0x79, 0x12, 0x2a, 0x0a, 0x11, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x69, 0x73, 0x73, 0x75, 0x65, 0x64, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x26, 0x0a, 0x0f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x69, 0x73, 0x73, 0x75, 0x65, 0x64, 0x5f, 0x49, 0x44, 0x18, 0x39, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x61, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x64, 0x49, 0x44, 0x12, 0x6e, 0x0a, 0x1b, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x12, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x18, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x74, 0x0a, 0x1d, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x56, 0x32, 0x18, 0x3a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x56, 0x32, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x1a, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x56, 0x32, 0x12, 0x24, 0x0a, 0x0e, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x13, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x66, 0x72, 0x65, 0x65, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x59, 0x0a, 0x14, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x14, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x46, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x11, 0x66, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x5f, 0x0a, 0x16, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x6e, 0x65, 0x74, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x56, 0x32, 0x18, 0x3b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x46, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x56, 0x32, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x13, 0x66, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x56, 0x32, 0x12, 0x2e, 0x0a, 0x13, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x66, 0x72, 0x65, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x16, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x46, 0x72, 0x65, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x17, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x4c, 0x0a, 0x10, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x0f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x6f, 0x64, 0x65, 0x48, 0x61, 0x73, 0x68, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x63, 0x6f, 0x64, 0x65, 0x48, 0x61, 0x73, 0x68, 0x12, 0x3f, 0x0a, 0x10, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x1f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x12, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x20, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x41, 0x0a, 0x11, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x21, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x1a, 0x50, 0x0a, 0x06, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x1a, 0x38, 0x0a, 0x0a, 0x41, 0x73, 0x73, 0x65, 0x74, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x3a, 0x0a, 0x0c, 0x41, 0x73, 0x73, 0x65, 0x74, 0x56, 0x32, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x4b, 0x0a, 0x1d, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x4d, 0x0a, 0x1f, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x56, 0x32, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x44, 0x0a, 0x16, 0x46, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x46, 0x0a, 0x18, 0x46, 0x72, 0x65, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x4e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x56, 0x32, 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, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x85, 0x04, 0x0a, 0x0f, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x53, 0x0a, 0x19, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x2e, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x52, 0x16, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x12, 0x42, 0x0a, 0x1e, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1a, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x46, 0x6f, 0x72, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x12, 0x5d, 0x0a, 0x2c, 0x61, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x5f, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x27, 0x61, 0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x44, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x12, 0x4c, 0x0a, 0x23, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1f, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3f, 0x0a, 0x1c, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x19, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x37, 0x0a, 0x03, 0x4b, 0x65, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0xa3, 0x02, 0x0a, 0x11, 0x44, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x74, 0x6f, 0x12, 0x3f, 0x0a, 0x1c, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x62, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x19, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x42, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x12, 0x39, 0x0a, 0x19, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x66, 0x72, 0x6f, 0x7a, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x46, 0x6f, 0x72, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x12, 0x39, 0x0a, 0x19, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x62, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x46, 0x6f, 0x72, 0x42, 0x61, 0x6e, 0x64, 0x77, 0x69, 0x64, 0x74, 0x68, 0x12, 0x33, 0x0a, 0x16, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x13, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x46, 0x6f, 0x72, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x22, 0x63, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x2d, 0x0a, 0x07, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x52, 0x07, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0xb2, 0x02, 0x0a, 0x0a, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x37, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x21, 0x0a, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4b, 0x65, 0x79, 0x52, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x22, 0x34, 0x0a, 0x0e, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x09, 0x0a, 0x05, 0x4f, 0x77, 0x6e, 0x65, 0x72, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x41, 0x63, 0x74, 0x69, 0x76, 0x65, 0x10, 0x02, 0x22, 0x99, 0x02, 0x0a, 0x07, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1c, 0x0a, 0x09, 0x76, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x76, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x12, 0x24, 0x0a, 0x0d, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x65, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x4d, 0x69, 0x73, 0x73, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x4d, 0x69, 0x73, 0x73, 0x65, 0x64, 0x12, 0x26, 0x0a, 0x0e, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x12, 0x24, 0x0a, 0x0d, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x53, 0x6c, 0x6f, 0x74, 0x4e, 0x75, 0x6d, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x53, 0x6c, 0x6f, 0x74, 0x4e, 0x75, 0x6d, 0x12, 0x16, 0x0a, 0x06, 0x69, 0x73, 0x4a, 0x6f, 0x62, 0x73, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x69, 0x73, 0x4a, 0x6f, 0x62, 0x73, 0x22, 0x7b, 0x0a, 0x05, 0x56, 0x6f, 0x74, 0x65, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2b, 0x0a, 0x09, 0x6f, 0x6c, 0x64, 0x5f, 0x76, 0x6f, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x74, 0x65, 0x52, 0x08, 0x6f, 0x6c, 0x64, 0x56, 0x6f, 0x74, 0x65, 0x73, 0x12, 0x2b, 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x76, 0x6f, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x74, 0x65, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x56, 0x6f, 0x74, 0x65, 0x73, 0x22, 0x40, 0x0a, 0x08, 0x54, 0x58, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x48, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x48, 0x61, 0x73, 0x68, 0x22, 0xa0, 0x01, 0x0a, 0x07, 0x54, 0x58, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x30, 0x0a, 0x08, 0x72, 0x61, 0x77, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x58, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x2e, 0x72, 0x61, 0x77, 0x52, 0x07, 0x72, 0x61, 0x77, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x1a, 0x45, 0x0a, 0x03, 0x72, 0x61, 0x77, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x78, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x74, 0x78, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x76, 0x6f, 0x75, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x76, 0x6f, 0x75, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x22, 0x39, 0x0a, 0x09, 0x54, 0x58, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x73, 0x12, 0x2c, 0x0a, 0x07, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x58, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x52, 0x07, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x73, 0x22, 0xac, 0x02, 0x0a, 0x0f, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x66, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x46, 0x65, 0x65, 0x12, 0x2e, 0x0a, 0x13, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x5f, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x2c, 0x0a, 0x12, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x10, 0x65, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x55, 0x73, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x65, 0x74, 0x5f, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x6e, 0x65, 0x74, 0x55, 0x73, 0x61, 0x67, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x65, 0x74, 0x5f, 0x66, 0x65, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6e, 0x65, 0x74, 0x46, 0x65, 0x65, 0x12, 0x43, 0x0a, 0x06, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x06, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x22, 0x80, 0x14, 0x0a, 0x0b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x34, 0x0a, 0x08, 0x72, 0x61, 0x77, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x72, 0x61, 0x77, 0x52, 0x07, 0x72, 0x61, 0x77, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x2e, 0x0a, 0x03, 0x72, 0x65, 0x74, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x03, 0x72, 0x65, 0x74, 0x1a, 0xf4, 0x08, 0x0a, 0x08, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x3f, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x32, 0x0a, 0x09, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x09, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x22, 0x0a, 0x0c, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0x8d, 0x07, 0x0a, 0x0c, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x19, 0x0a, 0x15, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x00, 0x12, 0x14, 0x0a, 0x10, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x01, 0x12, 0x19, 0x0a, 0x15, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x02, 0x12, 0x15, 0x0a, 0x11, 0x56, 0x6f, 0x74, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x03, 0x12, 0x17, 0x0a, 0x13, 0x56, 0x6f, 0x74, 0x65, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x04, 0x12, 0x19, 0x0a, 0x15, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x05, 0x12, 0x16, 0x0a, 0x12, 0x41, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x06, 0x12, 0x19, 0x0a, 0x15, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x08, 0x12, 0x21, 0x0a, 0x1d, 0x50, 0x61, 0x72, 0x74, 0x69, 0x63, 0x69, 0x70, 0x61, 0x74, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x09, 0x12, 0x19, 0x0a, 0x15, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x0a, 0x12, 0x19, 0x0a, 0x15, 0x46, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x0b, 0x12, 0x1b, 0x0a, 0x17, 0x55, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x0c, 0x12, 0x1b, 0x0a, 0x17, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x0d, 0x12, 0x19, 0x0a, 0x15, 0x55, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x0e, 0x12, 0x17, 0x0a, 0x13, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x0f, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x10, 0x12, 0x1b, 0x0a, 0x17, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x41, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x11, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x61, 0x6c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x12, 0x12, 0x18, 0x0a, 0x14, 0x53, 0x65, 0x74, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x13, 0x12, 0x12, 0x0a, 0x0e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x14, 0x12, 0x17, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x1e, 0x12, 0x18, 0x0a, 0x14, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x53, 0x6d, 0x61, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x1f, 0x12, 0x0f, 0x0a, 0x0b, 0x47, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x20, 0x12, 0x19, 0x0a, 0x15, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x21, 0x12, 0x1a, 0x0a, 0x16, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x29, 0x12, 0x1a, 0x0a, 0x16, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x2a, 0x12, 0x1c, 0x0a, 0x18, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x2b, 0x12, 0x1f, 0x0a, 0x1b, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x2c, 0x12, 0x1d, 0x0a, 0x19, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x2d, 0x12, 0x23, 0x0a, 0x1f, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x2e, 0x12, 0x14, 0x0a, 0x10, 0x43, 0x6c, 0x65, 0x61, 0x72, 0x41, 0x42, 0x49, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x30, 0x12, 0x1b, 0x0a, 0x17, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x72, 0x6f, 0x6b, 0x65, 0x72, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x31, 0x12, 0x1c, 0x0a, 0x18, 0x53, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x33, 0x1a, 0x8b, 0x07, 0x0a, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x66, 0x65, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x66, 0x65, 0x65, 0x12, 0x33, 0x0a, 0x03, 0x72, 0x65, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x52, 0x03, 0x72, 0x65, 0x74, 0x12, 0x4d, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x74, 0x12, 0x22, 0x0a, 0x0c, 0x61, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x49, 0x44, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x61, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x49, 0x44, 0x12, 0x27, 0x0a, 0x0f, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x75, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x10, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x75, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x38, 0x0a, 0x18, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x12, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x43, 0x0a, 0x1e, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x13, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x41, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x20, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x5f, 0x61, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x14, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1d, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x41, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x15, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x64, 0x12, 0x38, 0x0a, 0x18, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x65, 0x65, 0x18, 0x16, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x65, 0x65, 0x22, 0x1e, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x0a, 0x0a, 0x06, 0x53, 0x55, 0x43, 0x45, 0x53, 0x53, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x41, 0x49, 0x4c, 0x45, 0x44, 0x10, 0x01, 0x22, 0xb1, 0x02, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x0b, 0x0a, 0x07, 0x44, 0x45, 0x46, 0x41, 0x55, 0x4c, 0x54, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x55, 0x43, 0x43, 0x45, 0x53, 0x53, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x52, 0x45, 0x56, 0x45, 0x52, 0x54, 0x10, 0x02, 0x12, 0x18, 0x0a, 0x14, 0x42, 0x41, 0x44, 0x5f, 0x4a, 0x55, 0x4d, 0x50, 0x5f, 0x44, 0x45, 0x53, 0x54, 0x49, 0x4e, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x03, 0x12, 0x11, 0x0a, 0x0d, 0x4f, 0x55, 0x54, 0x5f, 0x4f, 0x46, 0x5f, 0x4d, 0x45, 0x4d, 0x4f, 0x52, 0x59, 0x10, 0x04, 0x12, 0x18, 0x0a, 0x14, 0x50, 0x52, 0x45, 0x43, 0x4f, 0x4d, 0x50, 0x49, 0x4c, 0x45, 0x44, 0x5f, 0x43, 0x4f, 0x4e, 0x54, 0x52, 0x41, 0x43, 0x54, 0x10, 0x05, 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x54, 0x41, 0x43, 0x4b, 0x5f, 0x54, 0x4f, 0x4f, 0x5f, 0x53, 0x4d, 0x41, 0x4c, 0x4c, 0x10, 0x06, 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x54, 0x41, 0x43, 0x4b, 0x5f, 0x54, 0x4f, 0x4f, 0x5f, 0x4c, 0x41, 0x52, 0x47, 0x45, 0x10, 0x07, 0x12, 0x15, 0x0a, 0x11, 0x49, 0x4c, 0x4c, 0x45, 0x47, 0x41, 0x4c, 0x5f, 0x4f, 0x50, 0x45, 0x52, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x08, 0x12, 0x12, 0x0a, 0x0e, 0x53, 0x54, 0x41, 0x43, 0x4b, 0x5f, 0x4f, 0x56, 0x45, 0x52, 0x46, 0x4c, 0x4f, 0x57, 0x10, 0x09, 0x12, 0x11, 0x0a, 0x0d, 0x4f, 0x55, 0x54, 0x5f, 0x4f, 0x46, 0x5f, 0x45, 0x4e, 0x45, 0x52, 0x47, 0x59, 0x10, 0x0a, 0x12, 0x0f, 0x0a, 0x0b, 0x4f, 0x55, 0x54, 0x5f, 0x4f, 0x46, 0x5f, 0x54, 0x49, 0x4d, 0x45, 0x10, 0x0b, 0x12, 0x17, 0x0a, 0x13, 0x4a, 0x56, 0x4d, 0x5f, 0x53, 0x54, 0x41, 0x43, 0x4b, 0x5f, 0x4f, 0x56, 0x45, 0x52, 0x5f, 0x46, 0x4c, 0x4f, 0x57, 0x10, 0x0c, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x0d, 0x12, 0x13, 0x0a, 0x0f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x46, 0x45, 0x52, 0x5f, 0x46, 0x41, 0x49, 0x4c, 0x45, 0x44, 0x10, 0x0e, 0x1a, 0xe7, 0x02, 0x0a, 0x03, 0x72, 0x61, 0x77, 0x12, 0x26, 0x0a, 0x0f, 0x72, 0x65, 0x66, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x72, 0x65, 0x66, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x22, 0x0a, 0x0d, 0x72, 0x65, 0x66, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x72, 0x65, 0x66, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x12, 0x24, 0x0a, 0x0e, 0x72, 0x65, 0x66, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x72, 0x65, 0x66, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x61, 0x73, 0x68, 0x12, 0x1e, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x29, 0x0a, 0x05, 0x61, 0x75, 0x74, 0x68, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x52, 0x05, 0x61, 0x75, 0x74, 0x68, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x12, 0x3a, 0x0a, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x73, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x73, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x66, 0x65, 0x65, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x12, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x66, 0x65, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x22, 0xe8, 0x07, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x66, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x66, 0x65, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x26, 0x0a, 0x0e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x26, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x33, 0x0a, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x52, 0x07, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x12, 0x2f, 0x0a, 0x03, 0x6c, 0x6f, 0x67, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4c, 0x6f, 0x67, 0x52, 0x03, 0x6c, 0x6f, 0x67, 0x12, 0x36, 0x0a, 0x06, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x52, 0x06, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x72, 0x65, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x72, 0x65, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x22, 0x0a, 0x0c, 0x61, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x49, 0x44, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x61, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x49, 0x44, 0x12, 0x27, 0x0a, 0x0f, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x75, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x10, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x75, 0x6e, 0x66, 0x72, 0x65, 0x65, 0x7a, 0x65, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x52, 0x0a, 0x15, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x11, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x14, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x12, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x43, 0x0a, 0x1e, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x61, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x13, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x41, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x20, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x5f, 0x61, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x14, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1d, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x41, 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x15, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x64, 0x12, 0x38, 0x0a, 0x18, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x65, 0x65, 0x18, 0x16, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x65, 0x65, 0x1a, 0x4b, 0x0a, 0x03, 0x4c, 0x6f, 0x67, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x06, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x1e, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x0a, 0x0a, 0x06, 0x53, 0x55, 0x43, 0x45, 0x53, 0x53, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x41, 0x49, 0x4c, 0x45, 0x44, 0x10, 0x01, 0x22, 0x9f, 0x01, 0x0a, 0x0e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x74, 0x12, 0x20, 0x0a, 0x0b, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x26, 0x0a, 0x0e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x43, 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x66, 0x6f, 0x22, 0x49, 0x0a, 0x0c, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x39, 0x0a, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 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, 0x22, 0x6a, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x69, 0x67, 0x6e, 0x12, 0x37, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 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, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x22, 0xfc, 0x02, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x34, 0x0a, 0x08, 0x72, 0x61, 0x77, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x2e, 0x72, 0x61, 0x77, 0x52, 0x07, 0x72, 0x61, 0x77, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2b, 0x0a, 0x11, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x10, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x1a, 0x89, 0x02, 0x0a, 0x03, 0x72, 0x61, 0x77, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x1e, 0x0a, 0x0a, 0x74, 0x78, 0x54, 0x72, 0x69, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x74, 0x78, 0x54, 0x72, 0x69, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x48, 0x61, 0x73, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x48, 0x61, 0x73, 0x68, 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x49, 0x64, 0x12, 0x27, 0x0a, 0x0f, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x77, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x10, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x10, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x22, 0x7c, 0x0a, 0x05, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x39, 0x0a, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 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, 0x38, 0x0a, 0x0c, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x52, 0x0b, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x22, 0x9a, 0x01, 0x0a, 0x0e, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x32, 0x0a, 0x03, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x52, 0x03, 0x69, 0x64, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x72, 0x65, 0x6d, 0x61, 0x69, 0x6e, 0x4e, 0x75, 0x6d, 0x1a, 0x35, 0x0a, 0x07, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x22, 0xd8, 0x01, 0x0a, 0x0e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x32, 0x0a, 0x03, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x52, 0x03, 0x69, 0x64, 0x73, 0x12, 0x31, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x1a, 0x35, 0x0a, 0x07, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x22, 0x28, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, 0x08, 0x0a, 0x04, 0x53, 0x59, 0x4e, 0x43, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x41, 0x44, 0x56, 0x54, 0x49, 0x53, 0x45, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x46, 0x45, 0x54, 0x43, 0x48, 0x10, 0x02, 0x22, 0x79, 0x0a, 0x09, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x35, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x03, 0x69, 0x64, 0x73, 0x22, 0x23, 0x0a, 0x0d, 0x49, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x54, 0x52, 0x58, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x01, 0x22, 0x8f, 0x02, 0x0a, 0x05, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x2c, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x27, 0x0a, 0x06, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x06, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x3a, 0x0a, 0x0d, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x52, 0x0c, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x12, 0x39, 0x0a, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 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, 0x22, 0x38, 0x0a, 0x08, 0x49, 0x74, 0x65, 0x6d, 0x54, 0x79, 0x70, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x45, 0x52, 0x52, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x54, 0x52, 0x58, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x48, 0x45, 0x41, 0x44, 0x45, 0x52, 0x10, 0x03, 0x22, 0x4a, 0x0a, 0x11, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x12, 0x35, 0x0a, 0x17, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x14, 0x6c, 0x61, 0x73, 0x74, 0x53, 0x6f, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x22, 0x41, 0x0a, 0x11, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x2c, 0x0a, 0x06, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x06, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x22, 0xf3, 0x02, 0x0a, 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x26, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x46, 0x0a, 0x0e, 0x67, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x52, 0x0e, 0x67, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x42, 0x0a, 0x0c, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x52, 0x0c, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x40, 0x0a, 0x0b, 0x68, 0x65, 0x61, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x52, 0x0b, 0x68, 0x65, 0x61, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x1a, 0x35, 0x0a, 0x07, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x22, 0xcb, 0x02, 0x0a, 0x13, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x61, 0x6c, 0x6c, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x63, 0x61, 0x6c, 0x6c, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x54, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x11, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x54, 0x6f, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x51, 0x0a, 0x0d, 0x63, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x43, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0d, 0x63, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x6f, 0x74, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x6e, 0x6f, 0x74, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x1a, 0x47, 0x0a, 0x0d, 0x43, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x63, 0x61, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x22, 0x7d, 0x0a, 0x1d, 0x44, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x22, 0x0a, 0x0c, 0x66, 0x72, 0x6f, 0x6d, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0c, 0x66, 0x72, 0x6f, 0x6d, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x74, 0x6f, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0a, 0x74, 0x6f, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x22, 0xbf, 0x1a, 0x0a, 0x08, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x22, 0x0a, 0x0c, 0x62, 0x65, 0x67, 0x69, 0x6e, 0x53, 0x79, 0x6e, 0x63, 0x4e, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x62, 0x65, 0x67, 0x69, 0x6e, 0x53, 0x79, 0x6e, 0x63, 0x4e, 0x75, 0x6d, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x24, 0x0a, 0x0d, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x30, 0x0a, 0x13, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x13, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x2e, 0x0a, 0x12, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x12, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x30, 0x0a, 0x13, 0x70, 0x61, 0x73, 0x73, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52, 0x13, 0x70, 0x61, 0x73, 0x73, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x46, 0x6c, 0x6f, 0x77, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x46, 0x6c, 0x6f, 0x77, 0x12, 0x3f, 0x0a, 0x0c, 0x70, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0c, 0x70, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x49, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x40, 0x0a, 0x0b, 0x6d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0b, 0x6d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x5d, 0x0a, 0x13, 0x63, 0x68, 0x65, 0x61, 0x74, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x49, 0x6e, 0x66, 0x6f, 0x4d, 0x61, 0x70, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x43, 0x68, 0x65, 0x61, 0x74, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x49, 0x6e, 0x66, 0x6f, 0x4d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x13, 0x63, 0x68, 0x65, 0x61, 0x74, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x49, 0x6e, 0x66, 0x6f, 0x4d, 0x61, 0x70, 0x1a, 0x46, 0x0a, 0x18, 0x43, 0x68, 0x65, 0x61, 0x74, 0x57, 0x69, 0x74, 0x6e, 0x65, 0x73, 0x73, 0x49, 0x6e, 0x66, 0x6f, 0x4d, 0x61, 0x70, 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, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0xc8, 0x07, 0x0a, 0x08, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x24, 0x0a, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x53, 0x79, 0x6e, 0x63, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x53, 0x79, 0x6e, 0x63, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x1c, 0x0a, 0x09, 0x72, 0x65, 0x6d, 0x61, 0x69, 0x6e, 0x4e, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x72, 0x65, 0x6d, 0x61, 0x69, 0x6e, 0x4e, 0x75, 0x6d, 0x12, 0x30, 0x0a, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x79, 0x6e, 0x63, 0x46, 0x6c, 0x61, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x73, 0x79, 0x6e, 0x63, 0x46, 0x6c, 0x61, 0x67, 0x12, 0x38, 0x0a, 0x17, 0x68, 0x65, 0x61, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x57, 0x65, 0x42, 0x6f, 0x74, 0x68, 0x48, 0x61, 0x76, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x17, 0x68, 0x65, 0x61, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x57, 0x65, 0x42, 0x6f, 0x74, 0x68, 0x48, 0x61, 0x76, 0x65, 0x12, 0x2a, 0x0a, 0x10, 0x6e, 0x65, 0x65, 0x64, 0x53, 0x79, 0x6e, 0x63, 0x46, 0x72, 0x6f, 0x6d, 0x50, 0x65, 0x65, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x10, 0x6e, 0x65, 0x65, 0x64, 0x53, 0x79, 0x6e, 0x63, 0x46, 0x72, 0x6f, 0x6d, 0x50, 0x65, 0x65, 0x72, 0x12, 0x26, 0x0a, 0x0e, 0x6e, 0x65, 0x65, 0x64, 0x53, 0x79, 0x6e, 0x63, 0x46, 0x72, 0x6f, 0x6d, 0x55, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x6e, 0x65, 0x65, 0x64, 0x53, 0x79, 0x6e, 0x63, 0x46, 0x72, 0x6f, 0x6d, 0x55, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x61, 0x76, 0x67, 0x4c, 0x61, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0a, 0x61, 0x76, 0x67, 0x4c, 0x61, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x28, 0x0a, 0x0f, 0x73, 0x79, 0x6e, 0x63, 0x54, 0x6f, 0x46, 0x65, 0x74, 0x63, 0x68, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x73, 0x79, 0x6e, 0x63, 0x54, 0x6f, 0x46, 0x65, 0x74, 0x63, 0x68, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x36, 0x0a, 0x16, 0x73, 0x79, 0x6e, 0x63, 0x54, 0x6f, 0x46, 0x65, 0x74, 0x63, 0x68, 0x53, 0x69, 0x7a, 0x65, 0x50, 0x65, 0x65, 0x6b, 0x4e, 0x75, 0x6d, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x73, 0x79, 0x6e, 0x63, 0x54, 0x6f, 0x46, 0x65, 0x74, 0x63, 0x68, 0x53, 0x69, 0x7a, 0x65, 0x50, 0x65, 0x65, 0x6b, 0x4e, 0x75, 0x6d, 0x12, 0x36, 0x0a, 0x16, 0x73, 0x79, 0x6e, 0x63, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x05, 0x52, 0x16, 0x73, 0x79, 0x6e, 0x63, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x24, 0x0a, 0x0d, 0x75, 0x6e, 0x46, 0x65, 0x74, 0x63, 0x68, 0x53, 0x79, 0x6e, 0x4e, 0x75, 0x6d, 0x18, 0x10, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x75, 0x6e, 0x46, 0x65, 0x74, 0x63, 0x68, 0x53, 0x79, 0x6e, 0x4e, 0x75, 0x6d, 0x12, 0x28, 0x0a, 0x0f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x6e, 0x50, 0x6f, 0x72, 0x63, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x11, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x6e, 0x50, 0x6f, 0x72, 0x63, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x30, 0x0a, 0x13, 0x68, 0x65, 0x61, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x57, 0x65, 0x42, 0x6f, 0x74, 0x68, 0x48, 0x61, 0x76, 0x65, 0x18, 0x12, 0x20, 0x01, 0x28, 0x09, 0x52, 0x13, 0x68, 0x65, 0x61, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x57, 0x65, 0x42, 0x6f, 0x74, 0x68, 0x48, 0x61, 0x76, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x69, 0x73, 0x41, 0x63, 0x74, 0x69, 0x76, 0x65, 0x18, 0x13, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x69, 0x73, 0x41, 0x63, 0x74, 0x69, 0x76, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x18, 0x14, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x6f, 0x64, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x15, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x6e, 0x6f, 0x64, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x69, 0x6e, 0x46, 0x6c, 0x6f, 0x77, 0x18, 0x16, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x69, 0x6e, 0x46, 0x6c, 0x6f, 0x77, 0x12, 0x28, 0x0a, 0x0f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x18, 0x17, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x12, 0x34, 0x0a, 0x15, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x18, 0x20, 0x01, 0x28, 0x09, 0x52, 0x15, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x12, 0x36, 0x0a, 0x16, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x19, 0x20, 0x01, 0x28, 0x09, 0x52, 0x16, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x1a, 0xa2, 0x06, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x20, 0x0a, 0x0b, 0x63, 0x6f, 0x64, 0x65, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x63, 0x6f, 0x64, 0x65, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x32, 0x70, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x32, 0x70, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x50, 0x6f, 0x72, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x6c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x26, 0x0a, 0x0e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x64, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x26, 0x0a, 0x0e, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x28, 0x0a, 0x0f, 0x70, 0x61, 0x73, 0x73, 0x69, 0x76, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x70, 0x61, 0x73, 0x73, 0x69, 0x76, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x22, 0x0a, 0x0c, 0x73, 0x65, 0x6e, 0x64, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x73, 0x65, 0x6e, 0x64, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x28, 0x0a, 0x0f, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x34, 0x0a, 0x15, 0x73, 0x61, 0x6d, 0x65, 0x49, 0x70, 0x4d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x05, 0x52, 0x15, 0x73, 0x61, 0x6d, 0x65, 0x49, 0x70, 0x4d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x2a, 0x0a, 0x10, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x50, 0x6f, 0x72, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x05, 0x52, 0x10, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x2a, 0x0a, 0x10, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x4d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x05, 0x52, 0x10, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x4d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x26, 0x0a, 0x0e, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x50, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x50, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x1c, 0x0a, 0x09, 0x64, 0x62, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x64, 0x62, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x32, 0x0a, 0x14, 0x6d, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x74, 0x69, 0x63, 0x69, 0x70, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x61, 0x74, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x05, 0x52, 0x14, 0x6d, 0x69, 0x6e, 0x50, 0x61, 0x72, 0x74, 0x69, 0x63, 0x69, 0x70, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x61, 0x74, 0x65, 0x12, 0x28, 0x0a, 0x0f, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x12, 0x22, 0x0a, 0x0c, 0x6d, 0x69, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x18, 0x10, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0c, 0x6d, 0x69, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x12, 0x22, 0x0a, 0x0c, 0x6d, 0x61, 0x78, 0x54, 0x69, 0x6d, 0x65, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x18, 0x11, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x54, 0x69, 0x6d, 0x65, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x12, 0x3a, 0x0a, 0x18, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x43, 0x72, 0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x66, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x73, 0x18, 0x12, 0x20, 0x01, 0x28, 0x03, 0x52, 0x18, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x43, 0x72, 0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4f, 0x66, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x73, 0x12, 0x30, 0x0a, 0x13, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x41, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x18, 0x13, 0x20, 0x01, 0x28, 0x03, 0x52, 0x13, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x41, 0x64, 0x61, 0x70, 0x74, 0x69, 0x76, 0x65, 0x45, 0x6e, 0x65, 0x72, 0x67, 0x79, 0x1a, 0xbb, 0x07, 0x0a, 0x0b, 0x4d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x20, 0x0a, 0x0b, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x30, 0x0a, 0x13, 0x64, 0x65, 0x61, 0x64, 0x4c, 0x6f, 0x63, 0x6b, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x13, 0x64, 0x65, 0x61, 0x64, 0x4c, 0x6f, 0x63, 0x6b, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x70, 0x75, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x63, 0x70, 0x75, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x20, 0x0a, 0x0b, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x12, 0x1e, 0x0a, 0x0a, 0x66, 0x72, 0x65, 0x65, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x66, 0x72, 0x65, 0x65, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x70, 0x75, 0x52, 0x61, 0x74, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x01, 0x52, 0x07, 0x63, 0x70, 0x75, 0x52, 0x61, 0x74, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x6a, 0x61, 0x76, 0x61, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6a, 0x61, 0x76, 0x61, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6f, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x0f, 0x6a, 0x76, 0x6d, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x6d, 0x6f, 0x65, 0x72, 0x79, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0f, 0x6a, 0x76, 0x6d, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x6d, 0x6f, 0x65, 0x72, 0x79, 0x12, 0x24, 0x0a, 0x0d, 0x6a, 0x76, 0x6d, 0x46, 0x72, 0x65, 0x65, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0d, 0x6a, 0x76, 0x6d, 0x46, 0x72, 0x65, 0x65, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x12, 0x26, 0x0a, 0x0e, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x43, 0x70, 0x75, 0x52, 0x61, 0x74, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0e, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x43, 0x70, 0x75, 0x52, 0x61, 0x74, 0x65, 0x12, 0x5d, 0x0a, 0x12, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x44, 0x65, 0x73, 0x63, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x44, 0x65, 0x73, 0x63, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x12, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x44, 0x65, 0x73, 0x63, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x69, 0x0a, 0x16, 0x64, 0x65, 0x61, 0x64, 0x4c, 0x6f, 0x63, 0x6b, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x44, 0x65, 0x61, 0x64, 0x4c, 0x6f, 0x63, 0x6b, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x16, 0x64, 0x65, 0x61, 0x64, 0x4c, 0x6f, 0x63, 0x6b, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x4c, 0x69, 0x73, 0x74, 0x1a, 0x8e, 0x01, 0x0a, 0x0e, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x44, 0x65, 0x73, 0x63, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x69, 0x6e, 0x69, 0x74, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x69, 0x6e, 0x69, 0x74, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x75, 0x73, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x61, 0x78, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x6d, 0x61, 0x78, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x52, 0x61, 0x74, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x52, 0x07, 0x75, 0x73, 0x65, 0x52, 0x61, 0x74, 0x65, 0x1a, 0xd2, 0x01, 0x0a, 0x12, 0x44, 0x65, 0x61, 0x64, 0x4c, 0x6f, 0x63, 0x6b, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x6c, 0x6f, 0x63, 0x6b, 0x4f, 0x77, 0x6e, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6c, 0x6f, 0x63, 0x6b, 0x4f, 0x77, 0x6e, 0x65, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x77, 0x61, 0x69, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x77, 0x61, 0x69, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x63, 0x6b, 0x54, 0x72, 0x61, 0x63, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x73, 0x74, 0x61, 0x63, 0x6b, 0x54, 0x72, 0x61, 0x63, 0x65, 0x2a, 0x37, 0x0a, 0x0b, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0a, 0x0a, 0x06, 0x4e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x41, 0x73, 0x73, 0x65, 0x74, 0x49, 0x73, 0x73, 0x75, 0x65, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x10, 0x02, 0x2a, 0xc7, 0x03, 0x0a, 0x0a, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x0d, 0x0a, 0x09, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x42, 0x41, 0x44, 0x5f, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x10, 0x02, 0x12, 0x12, 0x0a, 0x0e, 0x54, 0x4f, 0x4f, 0x5f, 0x4d, 0x41, 0x4e, 0x59, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x53, 0x10, 0x04, 0x12, 0x12, 0x0a, 0x0e, 0x44, 0x55, 0x50, 0x4c, 0x49, 0x43, 0x41, 0x54, 0x45, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x10, 0x05, 0x12, 0x19, 0x0a, 0x15, 0x49, 0x4e, 0x43, 0x4f, 0x4d, 0x50, 0x41, 0x54, 0x49, 0x42, 0x4c, 0x45, 0x5f, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x10, 0x06, 0x12, 0x11, 0x0a, 0x0d, 0x4e, 0x55, 0x4c, 0x4c, 0x5f, 0x49, 0x44, 0x45, 0x4e, 0x54, 0x49, 0x54, 0x59, 0x10, 0x07, 0x12, 0x10, 0x0a, 0x0c, 0x50, 0x45, 0x45, 0x52, 0x5f, 0x51, 0x55, 0x49, 0x54, 0x49, 0x4e, 0x47, 0x10, 0x08, 0x12, 0x17, 0x0a, 0x13, 0x55, 0x4e, 0x45, 0x58, 0x50, 0x45, 0x43, 0x54, 0x45, 0x44, 0x5f, 0x49, 0x44, 0x45, 0x4e, 0x54, 0x49, 0x54, 0x59, 0x10, 0x09, 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x4f, 0x43, 0x41, 0x4c, 0x5f, 0x49, 0x44, 0x45, 0x4e, 0x54, 0x49, 0x54, 0x59, 0x10, 0x0a, 0x12, 0x10, 0x0a, 0x0c, 0x50, 0x49, 0x4e, 0x47, 0x5f, 0x54, 0x49, 0x4d, 0x45, 0x4f, 0x55, 0x54, 0x10, 0x0b, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x53, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x41, 0x53, 0x4f, 0x4e, 0x10, 0x10, 0x12, 0x09, 0x0a, 0x05, 0x52, 0x45, 0x53, 0x45, 0x54, 0x10, 0x11, 0x12, 0x0d, 0x0a, 0x09, 0x53, 0x59, 0x4e, 0x43, 0x5f, 0x46, 0x41, 0x49, 0x4c, 0x10, 0x12, 0x12, 0x0e, 0x0a, 0x0a, 0x46, 0x45, 0x54, 0x43, 0x48, 0x5f, 0x46, 0x41, 0x49, 0x4c, 0x10, 0x13, 0x12, 0x0a, 0x0a, 0x06, 0x42, 0x41, 0x44, 0x5f, 0x54, 0x58, 0x10, 0x14, 0x12, 0x0d, 0x0a, 0x09, 0x42, 0x41, 0x44, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x15, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x4f, 0x52, 0x4b, 0x45, 0x44, 0x10, 0x16, 0x12, 0x0e, 0x0a, 0x0a, 0x55, 0x4e, 0x4c, 0x49, 0x4e, 0x4b, 0x41, 0x42, 0x4c, 0x45, 0x10, 0x17, 0x12, 0x18, 0x0a, 0x14, 0x49, 0x4e, 0x43, 0x4f, 0x4d, 0x50, 0x41, 0x54, 0x49, 0x42, 0x4c, 0x45, 0x5f, 0x56, 0x45, 0x52, 0x53, 0x49, 0x4f, 0x4e, 0x10, 0x18, 0x12, 0x16, 0x0a, 0x12, 0x49, 0x4e, 0x43, 0x4f, 0x4d, 0x50, 0x41, 0x54, 0x49, 0x42, 0x4c, 0x45, 0x5f, 0x43, 0x48, 0x41, 0x49, 0x4e, 0x10, 0x19, 0x12, 0x0c, 0x0a, 0x08, 0x54, 0x49, 0x4d, 0x45, 0x5f, 0x4f, 0x55, 0x54, 0x10, 0x20, 0x12, 0x10, 0x0a, 0x0c, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x5f, 0x46, 0x41, 0x49, 0x4c, 0x10, 0x21, 0x12, 0x1f, 0x0a, 0x1b, 0x54, 0x4f, 0x4f, 0x5f, 0x4d, 0x41, 0x4e, 0x59, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x53, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x53, 0x41, 0x4d, 0x45, 0x5f, 0x49, 0x50, 0x10, 0x22, 0x12, 0x0c, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0xff, 0x01, 0x42, 0x47, 0x0a, 0x0f, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x42, 0x08, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x5a, 0x2a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_Tron_proto_rawDescOnce sync.Once file_core_Tron_proto_rawDescData = file_core_Tron_proto_rawDesc ) func file_core_Tron_proto_rawDescGZIP() []byte { file_core_Tron_proto_rawDescOnce.Do(func() { file_core_Tron_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_Tron_proto_rawDescData) }) return file_core_Tron_proto_rawDescData } var file_core_Tron_proto_enumTypes = make([]protoimpl.EnumInfo, 11) var file_core_Tron_proto_msgTypes = make([]protoimpl.MessageInfo, 59) var file_core_Tron_proto_goTypes = []interface{}{ (AccountType)(0), // 0: protocol.AccountType (ReasonCode)(0), // 1: protocol.ReasonCode (Proposal_State)(0), // 2: protocol.Proposal.State (Permission_PermissionType)(0), // 3: protocol.Permission.PermissionType (Transaction_Contract_ContractType)(0), // 4: protocol.Transaction.Contract.ContractType (Transaction_ResultCode)(0), // 5: protocol.Transaction.Result.code (Transaction_ResultContractResult)(0), // 6: protocol.Transaction.Result.contractResult (TransactionInfoCode)(0), // 7: protocol.TransactionInfo.code (BlockInventory_Type)(0), // 8: protocol.BlockInventory.Type (Inventory_InventoryType)(0), // 9: protocol.Inventory.InventoryType (Items_ItemType)(0), // 10: protocol.Items.ItemType (*AccountId)(nil), // 11: protocol.AccountId (*Vote)(nil), // 12: protocol.Vote (*Proposal)(nil), // 13: protocol.Proposal (*Exchange)(nil), // 14: protocol.Exchange (*ChainParameters)(nil), // 15: protocol.ChainParameters (*Account)(nil), // 16: protocol.Account (*Key)(nil), // 17: protocol.Key (*DelegatedResource)(nil), // 18: protocol.DelegatedResource (*Authority)(nil), // 19: protocol.authority (*Permission)(nil), // 20: protocol.Permission (*Witness)(nil), // 21: protocol.Witness (*Votes)(nil), // 22: protocol.Votes (*TXOutput)(nil), // 23: protocol.TXOutput (*TXInput)(nil), // 24: protocol.TXInput (*TXOutputs)(nil), // 25: protocol.TXOutputs (*ResourceReceipt)(nil), // 26: protocol.ResourceReceipt (*Transaction)(nil), // 27: protocol.Transaction (*TransactionInfo)(nil), // 28: protocol.TransactionInfo (*TransactionRet)(nil), // 29: protocol.TransactionRet (*Transactions)(nil), // 30: protocol.Transactions (*TransactionSign)(nil), // 31: protocol.TransactionSign (*BlockHeader)(nil), // 32: protocol.BlockHeader (*Block)(nil), // 33: protocol.Block (*ChainInventory)(nil), // 34: protocol.ChainInventory (*BlockInventory)(nil), // 35: protocol.BlockInventory (*Inventory)(nil), // 36: protocol.Inventory (*Items)(nil), // 37: protocol.Items (*DynamicProperties)(nil), // 38: protocol.DynamicProperties (*DisconnectMessage)(nil), // 39: protocol.DisconnectMessage (*HelloMessage)(nil), // 40: protocol.HelloMessage (*InternalTransaction)(nil), // 41: protocol.InternalTransaction (*DelegatedResourceAccountIndex)(nil), // 42: protocol.DelegatedResourceAccountIndex (*NodeInfo)(nil), // 43: protocol.NodeInfo nil, // 44: protocol.Proposal.ParametersEntry (*ChainParameters_ChainParameter)(nil), // 45: protocol.ChainParameters.ChainParameter (*Account_Frozen)(nil), // 46: protocol.Account.Frozen nil, // 47: protocol.Account.AssetEntry nil, // 48: protocol.Account.AssetV2Entry nil, // 49: protocol.Account.LatestAssetOperationTimeEntry nil, // 50: protocol.Account.LatestAssetOperationTimeV2Entry nil, // 51: protocol.Account.FreeAssetNetUsageEntry nil, // 52: protocol.Account.FreeAssetNetUsageV2Entry (*Account_AccountResource)(nil), // 53: protocol.Account.AccountResource (*TXInputRaw)(nil), // 54: protocol.TXInput.raw (*Transaction_Contract)(nil), // 55: protocol.Transaction.Contract (*Transaction_Result)(nil), // 56: protocol.Transaction.Result (*TransactionRaw)(nil), // 57: protocol.Transaction.raw (*TransactionInfo_Log)(nil), // 58: protocol.TransactionInfo.Log (*BlockHeaderRaw)(nil), // 59: protocol.BlockHeader.raw (*ChainInventory_BlockId)(nil), // 60: protocol.ChainInventory.BlockId (*BlockInventory_BlockId)(nil), // 61: protocol.BlockInventory.BlockId (*HelloMessage_BlockId)(nil), // 62: protocol.HelloMessage.BlockId (*InternalTransaction_CallValueInfo)(nil), // 63: protocol.InternalTransaction.CallValueInfo nil, // 64: protocol.NodeInfo.CheatWitnessInfoMapEntry (*NodeInfo_PeerInfo)(nil), // 65: protocol.NodeInfo.PeerInfo (*NodeInfo_ConfigNodeInfo)(nil), // 66: protocol.NodeInfo.ConfigNodeInfo (*NodeInfo_MachineInfo)(nil), // 67: protocol.NodeInfo.MachineInfo (*NodeInfo_MachineInfo_MemoryDescInfo)(nil), // 68: protocol.NodeInfo.MachineInfo.MemoryDescInfo (*NodeInfo_MachineInfo_DeadLockThreadInfo)(nil), // 69: protocol.NodeInfo.MachineInfo.DeadLockThreadInfo (*Endpoint)(nil), // 70: protocol.Endpoint (*any.Any)(nil), // 71: google.protobuf.Any } var file_core_Tron_proto_depIdxs = []int32{ 44, // 0: protocol.Proposal.parameters:type_name -> protocol.Proposal.ParametersEntry 2, // 1: protocol.Proposal.state:type_name -> protocol.Proposal.State 45, // 2: protocol.ChainParameters.chainParameter:type_name -> protocol.ChainParameters.ChainParameter 0, // 3: protocol.Account.type:type_name -> protocol.AccountType 12, // 4: protocol.Account.votes:type_name -> protocol.Vote 47, // 5: protocol.Account.asset:type_name -> protocol.Account.AssetEntry 48, // 6: protocol.Account.assetV2:type_name -> protocol.Account.AssetV2Entry 46, // 7: protocol.Account.frozen:type_name -> protocol.Account.Frozen 46, // 8: protocol.Account.frozen_supply:type_name -> protocol.Account.Frozen 49, // 9: protocol.Account.latest_asset_operation_time:type_name -> protocol.Account.LatestAssetOperationTimeEntry 50, // 10: protocol.Account.latest_asset_operation_timeV2:type_name -> protocol.Account.LatestAssetOperationTimeV2Entry 51, // 11: protocol.Account.free_asset_net_usage:type_name -> protocol.Account.FreeAssetNetUsageEntry 52, // 12: protocol.Account.free_asset_net_usageV2:type_name -> protocol.Account.FreeAssetNetUsageV2Entry 53, // 13: protocol.Account.account_resource:type_name -> protocol.Account.AccountResource 20, // 14: protocol.Account.owner_permission:type_name -> protocol.Permission 20, // 15: protocol.Account.witness_permission:type_name -> protocol.Permission 20, // 16: protocol.Account.active_permission:type_name -> protocol.Permission 11, // 17: protocol.authority.account:type_name -> protocol.AccountId 3, // 18: protocol.Permission.type:type_name -> protocol.Permission.PermissionType 17, // 19: protocol.Permission.keys:type_name -> protocol.Key 12, // 20: protocol.Votes.old_votes:type_name -> protocol.Vote 12, // 21: protocol.Votes.new_votes:type_name -> protocol.Vote 54, // 22: protocol.TXInput.raw_data:type_name -> protocol.TXInput.raw 23, // 23: protocol.TXOutputs.outputs:type_name -> protocol.TXOutput 6, // 24: protocol.ResourceReceipt.result:type_name -> protocol.Transaction.Result.contractResult 57, // 25: protocol.Transaction.raw_data:type_name -> protocol.Transaction.raw 56, // 26: protocol.Transaction.ret:type_name -> protocol.Transaction.Result 26, // 27: protocol.TransactionInfo.receipt:type_name -> protocol.ResourceReceipt 58, // 28: protocol.TransactionInfo.log:type_name -> protocol.TransactionInfo.Log 7, // 29: protocol.TransactionInfo.result:type_name -> protocol.TransactionInfo.code 41, // 30: protocol.TransactionInfo.internal_transactions:type_name -> protocol.InternalTransaction 28, // 31: protocol.TransactionRet.transactioninfo:type_name -> protocol.TransactionInfo 27, // 32: protocol.Transactions.transactions:type_name -> protocol.Transaction 27, // 33: protocol.TransactionSign.transaction:type_name -> protocol.Transaction 59, // 34: protocol.BlockHeader.raw_data:type_name -> protocol.BlockHeader.raw 27, // 35: protocol.Block.transactions:type_name -> protocol.Transaction 32, // 36: protocol.Block.block_header:type_name -> protocol.BlockHeader 60, // 37: protocol.ChainInventory.ids:type_name -> protocol.ChainInventory.BlockId 61, // 38: protocol.BlockInventory.ids:type_name -> protocol.BlockInventory.BlockId 8, // 39: protocol.BlockInventory.type:type_name -> protocol.BlockInventory.Type 9, // 40: protocol.Inventory.type:type_name -> protocol.Inventory.InventoryType 10, // 41: protocol.Items.type:type_name -> protocol.Items.ItemType 33, // 42: protocol.Items.blocks:type_name -> protocol.Block 32, // 43: protocol.Items.block_headers:type_name -> protocol.BlockHeader 27, // 44: protocol.Items.transactions:type_name -> protocol.Transaction 1, // 45: protocol.DisconnectMessage.reason:type_name -> protocol.ReasonCode 70, // 46: protocol.HelloMessage.from:type_name -> protocol.Endpoint 62, // 47: protocol.HelloMessage.genesisBlockId:type_name -> protocol.HelloMessage.BlockId 62, // 48: protocol.HelloMessage.solidBlockId:type_name -> protocol.HelloMessage.BlockId 62, // 49: protocol.HelloMessage.headBlockId:type_name -> protocol.HelloMessage.BlockId 63, // 50: protocol.InternalTransaction.callValueInfo:type_name -> protocol.InternalTransaction.CallValueInfo 65, // 51: protocol.NodeInfo.peerInfoList:type_name -> protocol.NodeInfo.PeerInfo 66, // 52: protocol.NodeInfo.configNodeInfo:type_name -> protocol.NodeInfo.ConfigNodeInfo 67, // 53: protocol.NodeInfo.machineInfo:type_name -> protocol.NodeInfo.MachineInfo 64, // 54: protocol.NodeInfo.cheatWitnessInfoMap:type_name -> protocol.NodeInfo.CheatWitnessInfoMapEntry 46, // 55: protocol.Account.AccountResource.frozen_balance_for_energy:type_name -> protocol.Account.Frozen 4, // 56: protocol.Transaction.Contract.type:type_name -> protocol.Transaction.Contract.ContractType 71, // 57: protocol.Transaction.Contract.parameter:type_name -> google.protobuf.Any 5, // 58: protocol.Transaction.Result.ret:type_name -> protocol.Transaction.Result.code 6, // 59: protocol.Transaction.Result.contractRet:type_name -> protocol.Transaction.Result.contractResult 19, // 60: protocol.Transaction.raw.auths:type_name -> protocol.authority 55, // 61: protocol.Transaction.raw.contract:type_name -> protocol.Transaction.Contract 68, // 62: protocol.NodeInfo.MachineInfo.memoryDescInfoList:type_name -> protocol.NodeInfo.MachineInfo.MemoryDescInfo 69, // 63: protocol.NodeInfo.MachineInfo.deadLockThreadInfoList:type_name -> protocol.NodeInfo.MachineInfo.DeadLockThreadInfo 64, // [64:64] is the sub-list for method output_type 64, // [64:64] is the sub-list for method input_type 64, // [64:64] is the sub-list for extension type_name 64, // [64:64] is the sub-list for extension extendee 0, // [0:64] is the sub-list for field type_name } func init() { file_core_Tron_proto_init() } func file_core_Tron_proto_init() { if File_core_Tron_proto != nil { return } file_core_Discover_proto_init() if !protoimpl.UnsafeEnabled { file_core_Tron_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AccountId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Vote); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Proposal); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Exchange); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ChainParameters); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[5].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_core_Tron_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Key); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DelegatedResource); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Authority); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Permission); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Witness); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Votes); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TXOutput); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TXInput); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TXOutputs); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ResourceReceipt); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Transaction); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransactionInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransactionRet); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Transactions); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransactionSign); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[21].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_core_Tron_proto_msgTypes[22].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 } } file_core_Tron_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ChainInventory); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BlockInventory); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Inventory); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Items); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DynamicProperties); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[28].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_core_Tron_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*HelloMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*InternalTransaction); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DelegatedResourceAccountIndex); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ChainParameters_ChainParameter); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Account_Frozen); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[42].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Account_AccountResource); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[43].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TXInputRaw); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[44].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Transaction_Contract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[45].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Transaction_Result); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[46].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransactionRaw); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[47].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransactionInfo_Log); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[48].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BlockHeaderRaw); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[49].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ChainInventory_BlockId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[50].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BlockInventory_BlockId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[51].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*HelloMessage_BlockId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[52].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*InternalTransaction_CallValueInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[54].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeInfo_PeerInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[55].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeInfo_ConfigNodeInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[56].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeInfo_MachineInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[57].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeInfo_MachineInfo_MemoryDescInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_Tron_proto_msgTypes[58].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeInfo_MachineInfo_DeadLockThreadInfo); 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_core_Tron_proto_rawDesc, NumEnums: 11, NumMessages: 59, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_Tron_proto_goTypes, DependencyIndexes: file_core_Tron_proto_depIdxs, EnumInfos: file_core_Tron_proto_enumTypes, MessageInfos: file_core_Tron_proto_msgTypes, }.Build() File_core_Tron_proto = out.File file_core_Tron_proto_rawDesc = nil file_core_Tron_proto_goTypes = nil file_core_Tron_proto_depIdxs = nil } <|start_filename|>proto/core/contract/shield_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/shield_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type AuthenticationPath struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value []bool `protobuf:"varint,1,rep,packed,name=value,proto3" json:"value,omitempty"` } func (x *AuthenticationPath) Reset() { *x = AuthenticationPath{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthenticationPath) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthenticationPath) ProtoMessage() {} func (x *AuthenticationPath) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 AuthenticationPath.ProtoReflect.Descriptor instead. func (*AuthenticationPath) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{0} } func (x *AuthenticationPath) GetValue() []bool { if x != nil { return x.Value } return nil } type MerklePath struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AuthenticationPaths []*AuthenticationPath `protobuf:"bytes,1,rep,name=authentication_paths,json=authenticationPaths,proto3" json:"authentication_paths,omitempty"` Index []bool `protobuf:"varint,2,rep,packed,name=index,proto3" json:"index,omitempty"` Rt []byte `protobuf:"bytes,3,opt,name=rt,proto3" json:"rt,omitempty"` } func (x *MerklePath) Reset() { *x = MerklePath{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MerklePath) String() string { return protoimpl.X.MessageStringOf(x) } func (*MerklePath) ProtoMessage() {} func (x *MerklePath) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 MerklePath.ProtoReflect.Descriptor instead. func (*MerklePath) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{1} } func (x *MerklePath) GetAuthenticationPaths() []*AuthenticationPath { if x != nil { return x.AuthenticationPaths } return nil } func (x *MerklePath) GetIndex() []bool { if x != nil { return x.Index } return nil } func (x *MerklePath) GetRt() []byte { if x != nil { return x.Rt } return nil } type OutputPoint struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` Index int32 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"` } func (x *OutputPoint) Reset() { *x = OutputPoint{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *OutputPoint) String() string { return protoimpl.X.MessageStringOf(x) } func (*OutputPoint) ProtoMessage() {} func (x *OutputPoint) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 OutputPoint.ProtoReflect.Descriptor instead. func (*OutputPoint) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{2} } func (x *OutputPoint) GetHash() []byte { if x != nil { return x.Hash } return nil } func (x *OutputPoint) GetIndex() int32 { if x != nil { return x.Index } return 0 } type OutputPointInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OutPoints []*OutputPoint `protobuf:"bytes,1,rep,name=out_points,json=outPoints,proto3" json:"out_points,omitempty"` BlockNum int32 `protobuf:"varint,2,opt,name=block_num,json=blockNum,proto3" json:"block_num,omitempty"` } func (x *OutputPointInfo) Reset() { *x = OutputPointInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *OutputPointInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*OutputPointInfo) ProtoMessage() {} func (x *OutputPointInfo) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 OutputPointInfo.ProtoReflect.Descriptor instead. func (*OutputPointInfo) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{3} } func (x *OutputPointInfo) GetOutPoints() []*OutputPoint { if x != nil { return x.OutPoints } return nil } func (x *OutputPointInfo) GetBlockNum() int32 { if x != nil { return x.BlockNum } return 0 } type PedersenHash struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Content []byte `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` } func (x *PedersenHash) Reset() { *x = PedersenHash{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PedersenHash) String() string { return protoimpl.X.MessageStringOf(x) } func (*PedersenHash) ProtoMessage() {} func (x *PedersenHash) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 PedersenHash.ProtoReflect.Descriptor instead. func (*PedersenHash) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{4} } func (x *PedersenHash) GetContent() []byte { if x != nil { return x.Content } return nil } type IncrementalMerkleTree struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Left *PedersenHash `protobuf:"bytes,1,opt,name=left,proto3" json:"left,omitempty"` Right *PedersenHash `protobuf:"bytes,2,opt,name=right,proto3" json:"right,omitempty"` Parents []*PedersenHash `protobuf:"bytes,3,rep,name=parents,proto3" json:"parents,omitempty"` } func (x *IncrementalMerkleTree) Reset() { *x = IncrementalMerkleTree{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *IncrementalMerkleTree) String() string { return protoimpl.X.MessageStringOf(x) } func (*IncrementalMerkleTree) ProtoMessage() {} func (x *IncrementalMerkleTree) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 IncrementalMerkleTree.ProtoReflect.Descriptor instead. func (*IncrementalMerkleTree) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{5} } func (x *IncrementalMerkleTree) GetLeft() *PedersenHash { if x != nil { return x.Left } return nil } func (x *IncrementalMerkleTree) GetRight() *PedersenHash { if x != nil { return x.Right } return nil } func (x *IncrementalMerkleTree) GetParents() []*PedersenHash { if x != nil { return x.Parents } return nil } type IncrementalMerkleVoucher struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Tree *IncrementalMerkleTree `protobuf:"bytes,1,opt,name=tree,proto3" json:"tree,omitempty"` Filled []*PedersenHash `protobuf:"bytes,2,rep,name=filled,proto3" json:"filled,omitempty"` Cursor *IncrementalMerkleTree `protobuf:"bytes,3,opt,name=cursor,proto3" json:"cursor,omitempty"` CursorDepth int64 `protobuf:"varint,4,opt,name=cursor_depth,json=cursorDepth,proto3" json:"cursor_depth,omitempty"` Rt []byte `protobuf:"bytes,5,opt,name=rt,proto3" json:"rt,omitempty"` OutputPoint *OutputPoint `protobuf:"bytes,10,opt,name=output_point,json=outputPoint,proto3" json:"output_point,omitempty"` } func (x *IncrementalMerkleVoucher) Reset() { *x = IncrementalMerkleVoucher{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *IncrementalMerkleVoucher) String() string { return protoimpl.X.MessageStringOf(x) } func (*IncrementalMerkleVoucher) ProtoMessage() {} func (x *IncrementalMerkleVoucher) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 IncrementalMerkleVoucher.ProtoReflect.Descriptor instead. func (*IncrementalMerkleVoucher) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{6} } func (x *IncrementalMerkleVoucher) GetTree() *IncrementalMerkleTree { if x != nil { return x.Tree } return nil } func (x *IncrementalMerkleVoucher) GetFilled() []*PedersenHash { if x != nil { return x.Filled } return nil } func (x *IncrementalMerkleVoucher) GetCursor() *IncrementalMerkleTree { if x != nil { return x.Cursor } return nil } func (x *IncrementalMerkleVoucher) GetCursorDepth() int64 { if x != nil { return x.CursorDepth } return 0 } func (x *IncrementalMerkleVoucher) GetRt() []byte { if x != nil { return x.Rt } return nil } func (x *IncrementalMerkleVoucher) GetOutputPoint() *OutputPoint { if x != nil { return x.OutputPoint } return nil } type IncrementalMerkleVoucherInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Vouchers []*IncrementalMerkleVoucher `protobuf:"bytes,1,rep,name=vouchers,proto3" json:"vouchers,omitempty"` Paths [][]byte `protobuf:"bytes,2,rep,name=paths,proto3" json:"paths,omitempty"` } func (x *IncrementalMerkleVoucherInfo) Reset() { *x = IncrementalMerkleVoucherInfo{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *IncrementalMerkleVoucherInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*IncrementalMerkleVoucherInfo) ProtoMessage() {} func (x *IncrementalMerkleVoucherInfo) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 IncrementalMerkleVoucherInfo.ProtoReflect.Descriptor instead. func (*IncrementalMerkleVoucherInfo) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{7} } func (x *IncrementalMerkleVoucherInfo) GetVouchers() []*IncrementalMerkleVoucher { if x != nil { return x.Vouchers } return nil } func (x *IncrementalMerkleVoucherInfo) GetPaths() [][]byte { if x != nil { return x.Paths } return nil } type SpendDescription struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ValueCommitment []byte `protobuf:"bytes,1,opt,name=value_commitment,json=valueCommitment,proto3" json:"value_commitment,omitempty"` Anchor []byte `protobuf:"bytes,2,opt,name=anchor,proto3" json:"anchor,omitempty"` // merkle root Nullifier []byte `protobuf:"bytes,3,opt,name=nullifier,proto3" json:"nullifier,omitempty"` // used for check double spend Rk []byte `protobuf:"bytes,4,opt,name=rk,proto3" json:"rk,omitempty"` // used for check spend authority signature Zkproof []byte `protobuf:"bytes,5,opt,name=zkproof,proto3" json:"zkproof,omitempty"` SpendAuthoritySignature []byte `protobuf:"bytes,6,opt,name=spend_authority_signature,json=spendAuthoritySignature,proto3" json:"spend_authority_signature,omitempty"` } func (x *SpendDescription) Reset() { *x = SpendDescription{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SpendDescription) String() string { return protoimpl.X.MessageStringOf(x) } func (*SpendDescription) ProtoMessage() {} func (x *SpendDescription) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 SpendDescription.ProtoReflect.Descriptor instead. func (*SpendDescription) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{8} } func (x *SpendDescription) GetValueCommitment() []byte { if x != nil { return x.ValueCommitment } return nil } func (x *SpendDescription) GetAnchor() []byte { if x != nil { return x.Anchor } return nil } func (x *SpendDescription) GetNullifier() []byte { if x != nil { return x.Nullifier } return nil } func (x *SpendDescription) GetRk() []byte { if x != nil { return x.Rk } return nil } func (x *SpendDescription) GetZkproof() []byte { if x != nil { return x.Zkproof } return nil } func (x *SpendDescription) GetSpendAuthoritySignature() []byte { if x != nil { return x.SpendAuthoritySignature } return nil } type ReceiveDescription struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ValueCommitment []byte `protobuf:"bytes,1,opt,name=value_commitment,json=valueCommitment,proto3" json:"value_commitment,omitempty"` NoteCommitment []byte `protobuf:"bytes,2,opt,name=note_commitment,json=noteCommitment,proto3" json:"note_commitment,omitempty"` Epk []byte `protobuf:"bytes,3,opt,name=epk,proto3" json:"epk,omitempty"` // for Encryption CEnc []byte `protobuf:"bytes,4,opt,name=c_enc,json=cEnc,proto3" json:"c_enc,omitempty"` // Encryption for incoming, decrypt it with ivk COut []byte `protobuf:"bytes,5,opt,name=c_out,json=cOut,proto3" json:"c_out,omitempty"` // Encryption for audit, decrypt it with ovk Zkproof []byte `protobuf:"bytes,6,opt,name=zkproof,proto3" json:"zkproof,omitempty"` } func (x *ReceiveDescription) Reset() { *x = ReceiveDescription{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ReceiveDescription) String() string { return protoimpl.X.MessageStringOf(x) } func (*ReceiveDescription) ProtoMessage() {} func (x *ReceiveDescription) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 ReceiveDescription.ProtoReflect.Descriptor instead. func (*ReceiveDescription) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{9} } func (x *ReceiveDescription) GetValueCommitment() []byte { if x != nil { return x.ValueCommitment } return nil } func (x *ReceiveDescription) GetNoteCommitment() []byte { if x != nil { return x.NoteCommitment } return nil } func (x *ReceiveDescription) GetEpk() []byte { if x != nil { return x.Epk } return nil } func (x *ReceiveDescription) GetCEnc() []byte { if x != nil { return x.CEnc } return nil } func (x *ReceiveDescription) GetCOut() []byte { if x != nil { return x.COut } return nil } func (x *ReceiveDescription) GetZkproof() []byte { if x != nil { return x.Zkproof } return nil } type ShieldedTransferContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields TransparentFromAddress []byte `protobuf:"bytes,1,opt,name=transparent_from_address,json=transparentFromAddress,proto3" json:"transparent_from_address,omitempty"` // transparent address FromAmount int64 `protobuf:"varint,2,opt,name=from_amount,json=fromAmount,proto3" json:"from_amount,omitempty"` SpendDescription []*SpendDescription `protobuf:"bytes,3,rep,name=spend_description,json=spendDescription,proto3" json:"spend_description,omitempty"` ReceiveDescription []*ReceiveDescription `protobuf:"bytes,4,rep,name=receive_description,json=receiveDescription,proto3" json:"receive_description,omitempty"` BindingSignature []byte `protobuf:"bytes,5,opt,name=binding_signature,json=bindingSignature,proto3" json:"binding_signature,omitempty"` TransparentToAddress []byte `protobuf:"bytes,6,opt,name=transparent_to_address,json=transparentToAddress,proto3" json:"transparent_to_address,omitempty"` // transparent address ToAmount int64 `protobuf:"varint,7,opt,name=to_amount,json=toAmount,proto3" json:"to_amount,omitempty"` // the amount to transparent to_address } func (x *ShieldedTransferContract) Reset() { *x = ShieldedTransferContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_shield_contract_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ShieldedTransferContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ShieldedTransferContract) ProtoMessage() {} func (x *ShieldedTransferContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_shield_contract_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 ShieldedTransferContract.ProtoReflect.Descriptor instead. func (*ShieldedTransferContract) Descriptor() ([]byte, []int) { return file_core_contract_shield_contract_proto_rawDescGZIP(), []int{10} } func (x *ShieldedTransferContract) GetTransparentFromAddress() []byte { if x != nil { return x.TransparentFromAddress } return nil } func (x *ShieldedTransferContract) GetFromAmount() int64 { if x != nil { return x.FromAmount } return 0 } func (x *ShieldedTransferContract) GetSpendDescription() []*SpendDescription { if x != nil { return x.SpendDescription } return nil } func (x *ShieldedTransferContract) GetReceiveDescription() []*ReceiveDescription { if x != nil { return x.ReceiveDescription } return nil } func (x *ShieldedTransferContract) GetBindingSignature() []byte { if x != nil { return x.BindingSignature } return nil } func (x *ShieldedTransferContract) GetTransparentToAddress() []byte { if x != nil { return x.TransparentToAddress } return nil } func (x *ShieldedTransferContract) GetToAmount() int64 { if x != nil { return x.ToAmount } return 0 } var File_core_contract_shield_contract_proto protoreflect.FileDescriptor var file_core_contract_shield_contract_proto_rawDesc = []byte{ 0x0a, 0x23, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x73, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x2a, 0x0a, 0x12, 0x41, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x74, 0x68, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x08, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x83, 0x01, 0x0a, 0x0a, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x12, 0x4f, 0x0a, 0x14, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x74, 0x68, 0x52, 0x13, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x74, 0x68, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x02, 0x20, 0x03, 0x28, 0x08, 0x52, 0x05, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x12, 0x0e, 0x0a, 0x02, 0x72, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x72, 0x74, 0x22, 0x37, 0x0a, 0x0b, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x14, 0x0a, 0x05, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x22, 0x64, 0x0a, 0x0f, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x34, 0x0a, 0x0a, 0x6f, 0x75, 0x74, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x09, 0x6f, 0x75, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x22, 0x28, 0x0a, 0x0c, 0x50, 0x65, 0x64, 0x65, 0x72, 0x73, 0x65, 0x6e, 0x48, 0x61, 0x73, 0x68, 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, 0xa3, 0x01, 0x0a, 0x15, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x54, 0x72, 0x65, 0x65, 0x12, 0x2a, 0x0a, 0x04, 0x6c, 0x65, 0x66, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x64, 0x65, 0x72, 0x73, 0x65, 0x6e, 0x48, 0x61, 0x73, 0x68, 0x52, 0x04, 0x6c, 0x65, 0x66, 0x74, 0x12, 0x2c, 0x0a, 0x05, 0x72, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x64, 0x65, 0x72, 0x73, 0x65, 0x6e, 0x48, 0x61, 0x73, 0x68, 0x52, 0x05, 0x72, 0x69, 0x67, 0x68, 0x74, 0x12, 0x30, 0x0a, 0x07, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x64, 0x65, 0x72, 0x73, 0x65, 0x6e, 0x48, 0x61, 0x73, 0x68, 0x52, 0x07, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x73, 0x22, 0xa5, 0x02, 0x0a, 0x18, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x56, 0x6f, 0x75, 0x63, 0x68, 0x65, 0x72, 0x12, 0x33, 0x0a, 0x04, 0x74, 0x72, 0x65, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x54, 0x72, 0x65, 0x65, 0x52, 0x04, 0x74, 0x72, 0x65, 0x65, 0x12, 0x2e, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x50, 0x65, 0x64, 0x65, 0x72, 0x73, 0x65, 0x6e, 0x48, 0x61, 0x73, 0x68, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x12, 0x37, 0x0a, 0x06, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x54, 0x72, 0x65, 0x65, 0x52, 0x06, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x5f, 0x64, 0x65, 0x70, 0x74, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x44, 0x65, 0x70, 0x74, 0x68, 0x12, 0x0e, 0x0a, 0x02, 0x72, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x72, 0x74, 0x12, 0x38, 0x0a, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x0b, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x22, 0x74, 0x0a, 0x1c, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x56, 0x6f, 0x75, 0x63, 0x68, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x3e, 0x0a, 0x08, 0x76, 0x6f, 0x75, 0x63, 0x68, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x49, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x4d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x56, 0x6f, 0x75, 0x63, 0x68, 0x65, 0x72, 0x52, 0x08, 0x76, 0x6f, 0x75, 0x63, 0x68, 0x65, 0x72, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x68, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x05, 0x70, 0x61, 0x74, 0x68, 0x73, 0x22, 0xd9, 0x01, 0x0a, 0x10, 0x53, 0x70, 0x65, 0x6e, 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x29, 0x0a, 0x10, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6e, 0x63, 0x68, 0x6f, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x61, 0x6e, 0x63, 0x68, 0x6f, 0x72, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x75, 0x6c, 0x6c, 0x69, 0x66, 0x69, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x6e, 0x75, 0x6c, 0x6c, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x72, 0x6b, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x72, 0x6b, 0x12, 0x18, 0x0a, 0x07, 0x7a, 0x6b, 0x70, 0x72, 0x6f, 0x6f, 0x66, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x7a, 0x6b, 0x70, 0x72, 0x6f, 0x6f, 0x66, 0x12, 0x3a, 0x0a, 0x19, 0x73, 0x70, 0x65, 0x6e, 0x64, 0x5f, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x17, 0x73, 0x70, 0x65, 0x6e, 0x64, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x22, 0xbe, 0x01, 0x0a, 0x12, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x29, 0x0a, 0x10, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x6e, 0x6f, 0x74, 0x65, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x6e, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x65, 0x70, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x65, 0x70, 0x6b, 0x12, 0x13, 0x0a, 0x05, 0x63, 0x5f, 0x65, 0x6e, 0x63, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x63, 0x45, 0x6e, 0x63, 0x12, 0x13, 0x0a, 0x05, 0x63, 0x5f, 0x6f, 0x75, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x63, 0x4f, 0x75, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x7a, 0x6b, 0x70, 0x72, 0x6f, 0x6f, 0x66, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x7a, 0x6b, 0x70, 0x72, 0x6f, 0x6f, 0x66, 0x22, 0x8d, 0x03, 0x0a, 0x18, 0x53, 0x68, 0x69, 0x65, 0x6c, 0x64, 0x65, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x38, 0x0a, 0x18, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x16, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x66, 0x72, 0x6f, 0x6d, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x66, 0x72, 0x6f, 0x6d, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x47, 0x0a, 0x11, 0x73, 0x70, 0x65, 0x6e, 0x64, 0x5f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x53, 0x70, 0x65, 0x6e, 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x73, 0x70, 0x65, 0x6e, 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x13, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x5f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x12, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x11, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x10, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x34, 0x0a, 0x16, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x6f, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x14, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x54, 0x6f, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x6f, 0x5f, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x74, 0x6f, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_shield_contract_proto_rawDescOnce sync.Once file_core_contract_shield_contract_proto_rawDescData = file_core_contract_shield_contract_proto_rawDesc ) func file_core_contract_shield_contract_proto_rawDescGZIP() []byte { file_core_contract_shield_contract_proto_rawDescOnce.Do(func() { file_core_contract_shield_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_shield_contract_proto_rawDescData) }) return file_core_contract_shield_contract_proto_rawDescData } var file_core_contract_shield_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 11) var file_core_contract_shield_contract_proto_goTypes = []interface{}{ (*AuthenticationPath)(nil), // 0: protocol.AuthenticationPath (*MerklePath)(nil), // 1: protocol.MerklePath (*OutputPoint)(nil), // 2: protocol.OutputPoint (*OutputPointInfo)(nil), // 3: protocol.OutputPointInfo (*PedersenHash)(nil), // 4: protocol.PedersenHash (*IncrementalMerkleTree)(nil), // 5: protocol.IncrementalMerkleTree (*IncrementalMerkleVoucher)(nil), // 6: protocol.IncrementalMerkleVoucher (*IncrementalMerkleVoucherInfo)(nil), // 7: protocol.IncrementalMerkleVoucherInfo (*SpendDescription)(nil), // 8: protocol.SpendDescription (*ReceiveDescription)(nil), // 9: protocol.ReceiveDescription (*ShieldedTransferContract)(nil), // 10: protocol.ShieldedTransferContract } var file_core_contract_shield_contract_proto_depIdxs = []int32{ 0, // 0: protocol.MerklePath.authentication_paths:type_name -> protocol.AuthenticationPath 2, // 1: protocol.OutputPointInfo.out_points:type_name -> protocol.OutputPoint 4, // 2: protocol.IncrementalMerkleTree.left:type_name -> protocol.PedersenHash 4, // 3: protocol.IncrementalMerkleTree.right:type_name -> protocol.PedersenHash 4, // 4: protocol.IncrementalMerkleTree.parents:type_name -> protocol.PedersenHash 5, // 5: protocol.IncrementalMerkleVoucher.tree:type_name -> protocol.IncrementalMerkleTree 4, // 6: protocol.IncrementalMerkleVoucher.filled:type_name -> protocol.PedersenHash 5, // 7: protocol.IncrementalMerkleVoucher.cursor:type_name -> protocol.IncrementalMerkleTree 2, // 8: protocol.IncrementalMerkleVoucher.output_point:type_name -> protocol.OutputPoint 6, // 9: protocol.IncrementalMerkleVoucherInfo.vouchers:type_name -> protocol.IncrementalMerkleVoucher 8, // 10: protocol.ShieldedTransferContract.spend_description:type_name -> protocol.SpendDescription 9, // 11: protocol.ShieldedTransferContract.receive_description:type_name -> protocol.ReceiveDescription 12, // [12:12] is the sub-list for method output_type 12, // [12:12] is the sub-list for method input_type 12, // [12:12] is the sub-list for extension type_name 12, // [12:12] is the sub-list for extension extendee 0, // [0:12] is the sub-list for field type_name } func init() { file_core_contract_shield_contract_proto_init() } func file_core_contract_shield_contract_proto_init() { if File_core_contract_shield_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_shield_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthenticationPath); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MerklePath); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*OutputPoint); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*OutputPointInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PedersenHash); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*IncrementalMerkleTree); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*IncrementalMerkleVoucher); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*IncrementalMerkleVoucherInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SpendDescription); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ReceiveDescription); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_shield_contract_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ShieldedTransferContract); 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_core_contract_shield_contract_proto_rawDesc, NumEnums: 0, NumMessages: 11, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_shield_contract_proto_goTypes, DependencyIndexes: file_core_contract_shield_contract_proto_depIdxs, MessageInfos: file_core_contract_shield_contract_proto_msgTypes, }.Build() File_core_contract_shield_contract_proto = out.File file_core_contract_shield_contract_proto_rawDesc = nil file_core_contract_shield_contract_proto_goTypes = nil file_core_contract_shield_contract_proto_depIdxs = nil } <|start_filename|>proto/core/contract/common.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/common.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type ResourceCode int32 const ( ResourceCode_BANDWIDTH ResourceCode = 0 ResourceCode_ENERGY ResourceCode = 1 ) // Enum value maps for ResourceCode. var ( ResourceCode_name = map[int32]string{ 0: "BANDWIDTH", 1: "ENERGY", } ResourceCode_value = map[string]int32{ "BANDWIDTH": 0, "ENERGY": 1, } ) func (x ResourceCode) Enum() *ResourceCode { p := new(ResourceCode) *p = x return p } func (x ResourceCode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ResourceCode) Descriptor() protoreflect.EnumDescriptor { return file_core_contract_common_proto_enumTypes[0].Descriptor() } func (ResourceCode) Type() protoreflect.EnumType { return &file_core_contract_common_proto_enumTypes[0] } func (x ResourceCode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ResourceCode.Descriptor instead. func (ResourceCode) EnumDescriptor() ([]byte, []int) { return file_core_contract_common_proto_rawDescGZIP(), []int{0} } var File_core_contract_common_proto protoreflect.FileDescriptor var file_core_contract_common_proto_rawDesc = []byte{ 0x0a, 0x1a, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2a, 0x29, 0x0a, 0x0c, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x0d, 0x0a, 0x09, 0x42, 0x41, 0x4e, 0x44, 0x57, 0x49, 0x44, 0x54, 0x48, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x45, 0x4e, 0x45, 0x52, 0x47, 0x59, 0x10, 0x01, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_common_proto_rawDescOnce sync.Once file_core_contract_common_proto_rawDescData = file_core_contract_common_proto_rawDesc ) func file_core_contract_common_proto_rawDescGZIP() []byte { file_core_contract_common_proto_rawDescOnce.Do(func() { file_core_contract_common_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_common_proto_rawDescData) }) return file_core_contract_common_proto_rawDescData } var file_core_contract_common_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_core_contract_common_proto_goTypes = []interface{}{ (ResourceCode)(0), // 0: protocol.ResourceCode } var file_core_contract_common_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_core_contract_common_proto_init() } func file_core_contract_common_proto_init() { if File_core_contract_common_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_core_contract_common_proto_rawDesc, NumEnums: 1, NumMessages: 0, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_common_proto_goTypes, DependencyIndexes: file_core_contract_common_proto_depIdxs, EnumInfos: file_core_contract_common_proto_enumTypes, }.Build() File_core_contract_common_proto = out.File file_core_contract_common_proto_rawDesc = nil file_core_contract_common_proto_goTypes = nil file_core_contract_common_proto_depIdxs = nil } <|start_filename|>proto/core/contract/storage_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/storage_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type BuyStorageBytesContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Bytes int64 `protobuf:"varint,2,opt,name=bytes,proto3" json:"bytes,omitempty"` // storage bytes for buy } func (x *BuyStorageBytesContract) Reset() { *x = BuyStorageBytesContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_storage_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BuyStorageBytesContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*BuyStorageBytesContract) ProtoMessage() {} func (x *BuyStorageBytesContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_storage_contract_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 BuyStorageBytesContract.ProtoReflect.Descriptor instead. func (*BuyStorageBytesContract) Descriptor() ([]byte, []int) { return file_core_contract_storage_contract_proto_rawDescGZIP(), []int{0} } func (x *BuyStorageBytesContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *BuyStorageBytesContract) GetBytes() int64 { if x != nil { return x.Bytes } return 0 } type BuyStorageContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Quant int64 `protobuf:"varint,2,opt,name=quant,proto3" json:"quant,omitempty"` // trx quantity for buy storage (sun) } func (x *BuyStorageContract) Reset() { *x = BuyStorageContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_storage_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BuyStorageContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*BuyStorageContract) ProtoMessage() {} func (x *BuyStorageContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_storage_contract_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 BuyStorageContract.ProtoReflect.Descriptor instead. func (*BuyStorageContract) Descriptor() ([]byte, []int) { return file_core_contract_storage_contract_proto_rawDescGZIP(), []int{1} } func (x *BuyStorageContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *BuyStorageContract) GetQuant() int64 { if x != nil { return x.Quant } return 0 } type SellStorageContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` StorageBytes int64 `protobuf:"varint,2,opt,name=storage_bytes,json=storageBytes,proto3" json:"storage_bytes,omitempty"` } func (x *SellStorageContract) Reset() { *x = SellStorageContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_storage_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SellStorageContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*SellStorageContract) ProtoMessage() {} func (x *SellStorageContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_storage_contract_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 SellStorageContract.ProtoReflect.Descriptor instead. func (*SellStorageContract) Descriptor() ([]byte, []int) { return file_core_contract_storage_contract_proto_rawDescGZIP(), []int{2} } func (x *SellStorageContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *SellStorageContract) GetStorageBytes() int64 { if x != nil { return x.StorageBytes } return 0 } type UpdateBrokerageContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` Brokerage int32 `protobuf:"varint,2,opt,name=brokerage,proto3" json:"brokerage,omitempty"` // 1 mean 1% } func (x *UpdateBrokerageContract) Reset() { *x = UpdateBrokerageContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_storage_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UpdateBrokerageContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdateBrokerageContract) ProtoMessage() {} func (x *UpdateBrokerageContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_storage_contract_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 UpdateBrokerageContract.ProtoReflect.Descriptor instead. func (*UpdateBrokerageContract) Descriptor() ([]byte, []int) { return file_core_contract_storage_contract_proto_rawDescGZIP(), []int{3} } func (x *UpdateBrokerageContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *UpdateBrokerageContract) GetBrokerage() int32 { if x != nil { return x.Brokerage } return 0 } var File_core_contract_storage_contract_proto protoreflect.FileDescriptor var file_core_contract_storage_contract_proto_rawDesc = []byte{ 0x0a, 0x24, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x54, 0x0a, 0x17, 0x42, 0x75, 0x79, 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0x4f, 0x0a, 0x12, 0x42, 0x75, 0x79, 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x22, 0x5f, 0x0a, 0x13, 0x53, 0x65, 0x6c, 0x6c, 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x5c, 0x0a, 0x17, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x72, 0x6f, 0x6b, 0x65, 0x72, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1c, 0x0a, 0x09, 0x62, 0x72, 0x6f, 0x6b, 0x65, 0x72, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x62, 0x72, 0x6f, 0x6b, 0x65, 0x72, 0x61, 0x67, 0x65, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_storage_contract_proto_rawDescOnce sync.Once file_core_contract_storage_contract_proto_rawDescData = file_core_contract_storage_contract_proto_rawDesc ) func file_core_contract_storage_contract_proto_rawDescGZIP() []byte { file_core_contract_storage_contract_proto_rawDescOnce.Do(func() { file_core_contract_storage_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_storage_contract_proto_rawDescData) }) return file_core_contract_storage_contract_proto_rawDescData } var file_core_contract_storage_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_core_contract_storage_contract_proto_goTypes = []interface{}{ (*BuyStorageBytesContract)(nil), // 0: protocol.BuyStorageBytesContract (*BuyStorageContract)(nil), // 1: protocol.BuyStorageContract (*SellStorageContract)(nil), // 2: protocol.SellStorageContract (*UpdateBrokerageContract)(nil), // 3: protocol.UpdateBrokerageContract } var file_core_contract_storage_contract_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_core_contract_storage_contract_proto_init() } func file_core_contract_storage_contract_proto_init() { if File_core_contract_storage_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_storage_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BuyStorageBytesContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_storage_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BuyStorageContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_storage_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SellStorageContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_storage_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UpdateBrokerageContract); 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_core_contract_storage_contract_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_storage_contract_proto_goTypes, DependencyIndexes: file_core_contract_storage_contract_proto_depIdxs, MessageInfos: file_core_contract_storage_contract_proto_msgTypes, }.Build() File_core_contract_storage_contract_proto = out.File file_core_contract_storage_contract_proto_rawDesc = nil file_core_contract_storage_contract_proto_goTypes = nil file_core_contract_storage_contract_proto_depIdxs = nil } <|start_filename|>proto/core/contract/exchange_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/exchange_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type ExchangeCreateContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` FirstTokenId []byte `protobuf:"bytes,2,opt,name=first_token_id,json=firstTokenId,proto3" json:"first_token_id,omitempty"` FirstTokenBalance int64 `protobuf:"varint,3,opt,name=first_token_balance,json=firstTokenBalance,proto3" json:"first_token_balance,omitempty"` SecondTokenId []byte `protobuf:"bytes,4,opt,name=second_token_id,json=secondTokenId,proto3" json:"second_token_id,omitempty"` SecondTokenBalance int64 `protobuf:"varint,5,opt,name=second_token_balance,json=secondTokenBalance,proto3" json:"second_token_balance,omitempty"` } func (x *ExchangeCreateContract) Reset() { *x = ExchangeCreateContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_exchange_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ExchangeCreateContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ExchangeCreateContract) ProtoMessage() {} func (x *ExchangeCreateContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_exchange_contract_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 ExchangeCreateContract.ProtoReflect.Descriptor instead. func (*ExchangeCreateContract) Descriptor() ([]byte, []int) { return file_core_contract_exchange_contract_proto_rawDescGZIP(), []int{0} } func (x *ExchangeCreateContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ExchangeCreateContract) GetFirstTokenId() []byte { if x != nil { return x.FirstTokenId } return nil } func (x *ExchangeCreateContract) GetFirstTokenBalance() int64 { if x != nil { return x.FirstTokenBalance } return 0 } func (x *ExchangeCreateContract) GetSecondTokenId() []byte { if x != nil { return x.SecondTokenId } return nil } func (x *ExchangeCreateContract) GetSecondTokenBalance() int64 { if x != nil { return x.SecondTokenBalance } return 0 } type ExchangeInjectContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ExchangeId int64 `protobuf:"varint,2,opt,name=exchange_id,json=exchangeId,proto3" json:"exchange_id,omitempty"` TokenId []byte `protobuf:"bytes,3,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` Quant int64 `protobuf:"varint,4,opt,name=quant,proto3" json:"quant,omitempty"` } func (x *ExchangeInjectContract) Reset() { *x = ExchangeInjectContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_exchange_contract_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ExchangeInjectContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ExchangeInjectContract) ProtoMessage() {} func (x *ExchangeInjectContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_exchange_contract_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 ExchangeInjectContract.ProtoReflect.Descriptor instead. func (*ExchangeInjectContract) Descriptor() ([]byte, []int) { return file_core_contract_exchange_contract_proto_rawDescGZIP(), []int{1} } func (x *ExchangeInjectContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ExchangeInjectContract) GetExchangeId() int64 { if x != nil { return x.ExchangeId } return 0 } func (x *ExchangeInjectContract) GetTokenId() []byte { if x != nil { return x.TokenId } return nil } func (x *ExchangeInjectContract) GetQuant() int64 { if x != nil { return x.Quant } return 0 } type ExchangeWithdrawContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ExchangeId int64 `protobuf:"varint,2,opt,name=exchange_id,json=exchangeId,proto3" json:"exchange_id,omitempty"` TokenId []byte `protobuf:"bytes,3,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` Quant int64 `protobuf:"varint,4,opt,name=quant,proto3" json:"quant,omitempty"` } func (x *ExchangeWithdrawContract) Reset() { *x = ExchangeWithdrawContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_exchange_contract_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ExchangeWithdrawContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ExchangeWithdrawContract) ProtoMessage() {} func (x *ExchangeWithdrawContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_exchange_contract_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 ExchangeWithdrawContract.ProtoReflect.Descriptor instead. func (*ExchangeWithdrawContract) Descriptor() ([]byte, []int) { return file_core_contract_exchange_contract_proto_rawDescGZIP(), []int{2} } func (x *ExchangeWithdrawContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ExchangeWithdrawContract) GetExchangeId() int64 { if x != nil { return x.ExchangeId } return 0 } func (x *ExchangeWithdrawContract) GetTokenId() []byte { if x != nil { return x.TokenId } return nil } func (x *ExchangeWithdrawContract) GetQuant() int64 { if x != nil { return x.Quant } return 0 } type ExchangeTransactionContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` ExchangeId int64 `protobuf:"varint,2,opt,name=exchange_id,json=exchangeId,proto3" json:"exchange_id,omitempty"` TokenId []byte `protobuf:"bytes,3,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` Quant int64 `protobuf:"varint,4,opt,name=quant,proto3" json:"quant,omitempty"` Expected int64 `protobuf:"varint,5,opt,name=expected,proto3" json:"expected,omitempty"` } func (x *ExchangeTransactionContract) Reset() { *x = ExchangeTransactionContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_exchange_contract_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ExchangeTransactionContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*ExchangeTransactionContract) ProtoMessage() {} func (x *ExchangeTransactionContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_exchange_contract_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 ExchangeTransactionContract.ProtoReflect.Descriptor instead. func (*ExchangeTransactionContract) Descriptor() ([]byte, []int) { return file_core_contract_exchange_contract_proto_rawDescGZIP(), []int{3} } func (x *ExchangeTransactionContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *ExchangeTransactionContract) GetExchangeId() int64 { if x != nil { return x.ExchangeId } return 0 } func (x *ExchangeTransactionContract) GetTokenId() []byte { if x != nil { return x.TokenId } return nil } func (x *ExchangeTransactionContract) GetQuant() int64 { if x != nil { return x.Quant } return 0 } func (x *ExchangeTransactionContract) GetExpected() int64 { if x != nil { return x.Expected } return 0 } var File_core_contract_exchange_contract_proto protoreflect.FileDescriptor var file_core_contract_exchange_contract_proto_rawDesc = []byte{ 0x0a, 0x25, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0xed, 0x01, 0x0a, 0x16, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x24, 0x0a, 0x0e, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x66, 0x69, 0x72, 0x73, 0x74, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x2e, 0x0a, 0x13, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x66, 0x69, 0x72, 0x73, 0x74, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x26, 0x0a, 0x0f, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0d, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x30, 0x0a, 0x14, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x12, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x22, 0x8f, 0x01, 0x0a, 0x16, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x6e, 0x6a, 0x65, 0x63, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x22, 0x91, 0x01, 0x0a, 0x18, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x57, 0x69, 0x74, 0x68, 0x64, 0x72, 0x61, 0x77, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x22, 0xb0, 0x01, 0x0a, 0x1b, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x71, 0x75, 0x61, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_exchange_contract_proto_rawDescOnce sync.Once file_core_contract_exchange_contract_proto_rawDescData = file_core_contract_exchange_contract_proto_rawDesc ) func file_core_contract_exchange_contract_proto_rawDescGZIP() []byte { file_core_contract_exchange_contract_proto_rawDescOnce.Do(func() { file_core_contract_exchange_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_exchange_contract_proto_rawDescData) }) return file_core_contract_exchange_contract_proto_rawDescData } var file_core_contract_exchange_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_core_contract_exchange_contract_proto_goTypes = []interface{}{ (*ExchangeCreateContract)(nil), // 0: protocol.ExchangeCreateContract (*ExchangeInjectContract)(nil), // 1: protocol.ExchangeInjectContract (*ExchangeWithdrawContract)(nil), // 2: protocol.ExchangeWithdrawContract (*ExchangeTransactionContract)(nil), // 3: protocol.ExchangeTransactionContract } var file_core_contract_exchange_contract_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_core_contract_exchange_contract_proto_init() } func file_core_contract_exchange_contract_proto_init() { if File_core_contract_exchange_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_exchange_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ExchangeCreateContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_exchange_contract_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ExchangeInjectContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_exchange_contract_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ExchangeWithdrawContract); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_core_contract_exchange_contract_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ExchangeTransactionContract); 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_core_contract_exchange_contract_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_exchange_contract_proto_goTypes, DependencyIndexes: file_core_contract_exchange_contract_proto_depIdxs, MessageInfos: file_core_contract_exchange_contract_proto_msgTypes, }.Build() File_core_contract_exchange_contract_proto = out.File file_core_contract_exchange_contract_proto_rawDesc = nil file_core_contract_exchange_contract_proto_goTypes = nil file_core_contract_exchange_contract_proto_depIdxs = nil } <|start_filename|>proto/core/contract/vote_asset_contract.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.23.0 // protoc v3.12.0 // source: core/contract/vote_asset_contract.proto package contract import ( proto "github.com/golang/protobuf/proto" 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) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type VoteAssetContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields OwnerAddress []byte `protobuf:"bytes,1,opt,name=owner_address,json=ownerAddress,proto3" json:"owner_address,omitempty"` VoteAddress [][]byte `protobuf:"bytes,2,rep,name=vote_address,json=voteAddress,proto3" json:"vote_address,omitempty"` Support bool `protobuf:"varint,3,opt,name=support,proto3" json:"support,omitempty"` Count int32 `protobuf:"varint,5,opt,name=count,proto3" json:"count,omitempty"` } func (x *VoteAssetContract) Reset() { *x = VoteAssetContract{} if protoimpl.UnsafeEnabled { mi := &file_core_contract_vote_asset_contract_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *VoteAssetContract) String() string { return protoimpl.X.MessageStringOf(x) } func (*VoteAssetContract) ProtoMessage() {} func (x *VoteAssetContract) ProtoReflect() protoreflect.Message { mi := &file_core_contract_vote_asset_contract_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 VoteAssetContract.ProtoReflect.Descriptor instead. func (*VoteAssetContract) Descriptor() ([]byte, []int) { return file_core_contract_vote_asset_contract_proto_rawDescGZIP(), []int{0} } func (x *VoteAssetContract) GetOwnerAddress() []byte { if x != nil { return x.OwnerAddress } return nil } func (x *VoteAssetContract) GetVoteAddress() [][]byte { if x != nil { return x.VoteAddress } return nil } func (x *VoteAssetContract) GetSupport() bool { if x != nil { return x.Support } return false } func (x *VoteAssetContract) GetCount() int32 { if x != nil { return x.Count } return 0 } var File_core_contract_vote_asset_contract_proto protoreflect.FileDescriptor var file_core_contract_vote_asset_contract_proto_rawDesc = []byte{ 0x0a, 0x27, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2f, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x8b, 0x01, 0x0a, 0x11, 0x56, 0x6f, 0x74, 0x65, 0x41, 0x73, 0x73, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x21, 0x0a, 0x0c, 0x76, 0x6f, 0x74, 0x65, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0b, 0x76, 0x6f, 0x74, 0x65, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x4f, 0x0a, 0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x72, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x79, 0x74, 0x65, 0x6a, 0x65, 0x64, 0x69, 0x2f, 0x74, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x64, 0x6b, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_core_contract_vote_asset_contract_proto_rawDescOnce sync.Once file_core_contract_vote_asset_contract_proto_rawDescData = file_core_contract_vote_asset_contract_proto_rawDesc ) func file_core_contract_vote_asset_contract_proto_rawDescGZIP() []byte { file_core_contract_vote_asset_contract_proto_rawDescOnce.Do(func() { file_core_contract_vote_asset_contract_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_contract_vote_asset_contract_proto_rawDescData) }) return file_core_contract_vote_asset_contract_proto_rawDescData } var file_core_contract_vote_asset_contract_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_core_contract_vote_asset_contract_proto_goTypes = []interface{}{ (*VoteAssetContract)(nil), // 0: protocol.VoteAssetContract } var file_core_contract_vote_asset_contract_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_core_contract_vote_asset_contract_proto_init() } func file_core_contract_vote_asset_contract_proto_init() { if File_core_contract_vote_asset_contract_proto != nil { return } if !protoimpl.UnsafeEnabled { file_core_contract_vote_asset_contract_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*VoteAssetContract); 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_core_contract_vote_asset_contract_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_core_contract_vote_asset_contract_proto_goTypes, DependencyIndexes: file_core_contract_vote_asset_contract_proto_depIdxs, MessageInfos: file_core_contract_vote_asset_contract_proto_msgTypes, }.Build() File_core_contract_vote_asset_contract_proto = out.File file_core_contract_vote_asset_contract_proto_rawDesc = nil file_core_contract_vote_asset_contract_proto_goTypes = nil file_core_contract_vote_asset_contract_proto_depIdxs = nil } <|start_filename|>keystore/init.go<|end_filename|> package keystore import ( "os" ) var KS *KeyStore // Init make keystore directory and initialize KS func Init(p string) { if _, err := os.Stat(p); os.IsNotExist(err) { if err := os.MkdirAll(p, 0700); err != nil { panic(err) } } KS = NewKeyStore(p, StandardScryptN, StandardScryptP) }
bytejedi/tron-sdk-go
<|start_filename|>upstream/helm_test.go<|end_filename|> /* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package upstream import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) func TestUnserialiseHelm(t *testing.T) { validYamls := []string{ "flavour: helm\nrepo: http://example.com/repo\nchart: example", "flavour: helm\nrepo: https://example.com/repo\nchart: example", "flavour: helm\nrepo: https://example.com/repo\nchart: example\nconstraints: < 1.0.0", } for _, valid := range validYamls { var u Helm err := yaml.Unmarshal([]byte(valid), &u) require.NoError(t, err) } } func TestInvalidHelmValues(t *testing.T) { var err error h0 := Helm{ // Missing repo Chart: "example", } _, err = h0.LatestVersion() require.Error(t, err) invalidURL := "not-a-repo" h1 := Helm{ Repo: invalidURL, Chart: "example", } _, err = h1.LatestVersion() require.Error(t, err) invalidProtocol := "ftp://repo.example.com" h2 := Helm{ Repo: invalidProtocol, Chart: "example", } _, err = h2.LatestVersion() require.Error(t, err) invalidConstraint := "invalid-constraint" h3 := Helm{ Repo: "http://example.com/test", Chart: "example", Constraints: invalidConstraint, } _, err = h3.LatestVersion() require.Error(t, err) emptyChartName := "" h4 := Helm{ Repo: "http://example.com/test", Chart: emptyChartName, } _, err = h4.LatestVersion() require.Error(t, err) } // Now onto tests that connect to a "real" Helm repo! // We need to set up a local webserver to serve the Helm repo index // (As far as I can tell, it can't read directly from a file) // We do that by instantiating an httptest server in each test that requires it func helmHandler(rw http.ResponseWriter, req *http.Request) { url := req.URL.String() switch url { case "/": fmt.Fprint(rw, "zeitgeist testing server") case "/index.yaml": index, err := ioutil.ReadFile("../testdata/helm-repo/index.yaml") if err != nil { panic("Cannot open helm repo test file") } fmt.Fprint(rw, string(index)) case "/broken-repo/index.yaml": fmt.Fprint(rw, "bad yaml here } !") default: rw.WriteHeader(404) } } // Negative tests func TestHelmRepoNotFoundLocal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(helmHandler)) defer server.Close() h := Helm{ Repo: server.URL + "/not-a-repo/", Chart: "dependency", } latestVersion, err := h.LatestVersion() require.Error(t, err) require.Empty(t, latestVersion) } func TestHelmBrokenRepoLocal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(helmHandler)) defer server.Close() h := Helm{ Repo: server.URL + "/broken-repo/", Chart: "dependency", } latestVersion, err := h.LatestVersion() require.Error(t, err) require.Empty(t, latestVersion) } func TestHelmChartNotFoundLocal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(helmHandler)) defer server.Close() h := Helm{ Repo: server.URL, Chart: "chart-doesnt-exist", } latestVersion, err := h.LatestVersion() require.Error(t, err) require.Empty(t, latestVersion) } func TestHelmUnsatisfiableConstraintLocal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(helmHandler)) defer server.Close() h := Helm{ Repo: server.URL, Chart: "dependency", Constraints: "> 5.0.0", } latestVersion, err := h.LatestVersion() require.Error(t, err) require.Empty(t, latestVersion) } // Happy tests func TestHelmHappyPathLocal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(helmHandler)) defer server.Close() h := Helm{ Repo: server.URL, Chart: "dependency", } latestVersion, err := h.LatestVersion() require.NoError(t, err) require.NotEmpty(t, latestVersion) require.Equal(t, latestVersion, "0.2.0") h2 := Helm{ Repo: server.URL, Chart: "dependency-two", } latestVersion2, err := h2.LatestVersion() require.NoError(t, err) require.NotEmpty(t, latestVersion2) require.Equal(t, latestVersion2, "2.0.0") } func TestHelmHappyPathWithConstraintLocal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(helmHandler)) defer server.Close() h := Helm{ Repo: server.URL, Chart: "dependency", Constraints: "< 0.2.0", } latestVersion, err := h.LatestVersion() require.NoError(t, err) require.NotEmpty(t, latestVersion) require.Equal(t, latestVersion, "0.1.2") } <|start_filename|>upstream/helm.go<|end_filename|> /* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package upstream import ( "io/ioutil" "net/url" "os" "strings" "github.com/blang/semver" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "helm.sh/helm/v3/pkg/cli" "helm.sh/helm/v3/pkg/getter" "helm.sh/helm/v3/pkg/repo" ) // Helm upstream representation type Helm struct { Base `mapstructure:",squash"` // Helm repository URL, e.g. https://grafana.github.io/helm-charts Repo string // Helm chart name in this repository Chart string // Optional: semver constraints, e.g. < 2.0.0 // Will have no effect if the dependency does not follow Semver Constraints string } // LatestVersion returns the latest non-draft, non-prerelease Helm Release // for the given repository (depending on the Constraints if set). func (upstream Helm) LatestVersion() (string, error) { log.Debug("Using Helm flavour") return latestChartVersion(upstream) } func latestChartVersion(upstream Helm) (string, error) { // Sanity checking if upstream.Repo == "" { return "", errors.Errorf("invalid helm upstream: missing repo argument") } if upstream.Chart == "" { return "", errors.Errorf("invalid helm upstream: missing chart argument") } parsedRepo, err := url.Parse(upstream.Repo) if err != nil { return "", errors.Errorf("invalid helm repo url: %s", upstream.Repo) } s := parsedRepo.Scheme if s != "http" && s != "https" && s != "oci" { // We currently only support http-based and oci repos (Helm defaults) // Helm allows custom handlers via plugins, but I've never seen it in practice - could be added later if needed return "", errors.Errorf("invalid helm repo: %s, only http, https and oci are supported", upstream.Repo) } var useSemverConstraints bool var expectedRange semver.Range semverConstraints := upstream.Constraints if semverConstraints == "" { useSemverConstraints = false } else { useSemverConstraints = true validatedExpectedRange, err := semver.ParseRange(semverConstraints) if err != nil { return "", errors.Errorf("invalid semver constraints range: %#v", upstream.Constraints) } expectedRange = validatedExpectedRange } // First, get the repo index // Helm expects a cache directory, so we create a temporary one cacheDir, err := ioutil.TempDir("", "zeitgeist-helm-cache") if err != nil { log.Errorf("failed to create temporary directory for Helm cache") return "", err } defer os.RemoveAll(cacheDir) cfg := repo.Entry{ Name: "zeitgeist", URL: upstream.Repo, } settings := cli.EnvSettings{ PluginsDirectory: "", RepositoryCache: cacheDir, } re, err := repo.NewChartRepository(&cfg, getter.All(&settings)) if err != nil { log.Errorf("failed to instantiate the Helm Chart Repository") return "", err } log.Debugf("Downloading repo index for %s...", upstream.Repo) indexFile, err := re.DownloadIndexFile() if err != nil { log.Errorf("failed to download index file for repo %s", upstream.Repo) return "", err } log.Debugf("Loading repo index for %s...", upstream.Repo) index, err := repo.LoadIndexFile(indexFile) if err != nil { log.Errorf("failed to load index file for repo %s", upstream.Repo) return "", err } chartVersions := index.Entries[upstream.Chart] if chartVersions == nil { return "", errors.Errorf("no chart for %s found in repository %s", upstream.Chart, upstream.Repo) } // Iterate over versions and get the first newer version // (Or the first version that matches our semver constraints, if defined) // Versions are already ordered, cf https://github.com/helm/helm/blob/6a3daaa7aa5b89a150042cadcbe869b477bb62a1/pkg/repo/index.go#L344 for _, chartVersion := range chartVersions { chartVersionStr := strings.TrimPrefix(chartVersion.Version, "v") if useSemverConstraints { version, err := semver.Parse(chartVersionStr) if err != nil { log.Debugf("Error parsing version %s (%#v) as semver, cannot validate semver constraints", chartVersionStr, err) } else if !expectedRange(version) { log.Debugf("Skipping release not matching range constraints (%s): %s\n", upstream.Constraints, chartVersionStr) continue } } log.Debugf("Found latest matching release: %s\n", chartVersionStr) return chartVersionStr, nil } // No latest version found – no versions? Only prereleases? return "", errors.Errorf("no potential version found") }
sparebank1utvikling/zeitgeist
<|start_filename|>lib/pdf_viewer_plugin.dart<|end_filename|> import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:pdf_viewer_plugin/src/android_viewers/android_pdf_viewer.dart'; import 'package:pdf_viewer_plugin/src/ios_viewers/cupertino_pfd_viewer.dart'; export 'package:pdf_viewer_plugin/src/android_viewers/surface_android_pdf_viewer.dart'; typedef void PdfViewerCreatedCallback(); class CreationParams { CreationParams({ this.path, }); final String? path; @override String toString() { return '$runtimeType(path: $path)'; } } abstract class PdfViewerPlatform { Widget build({ BuildContext? context, CreationParams? creationParams, Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers, }); } class PdfView extends StatefulWidget { /// Creates a new PdfView. const PdfView({ Key? key, required this.path, this.gestureRecognizers, this.gestureNavigationEnabled = false, }) : super(key: key); static PdfViewerPlatform? _platform; /// Sets a custom [PdfViewerPlatform]. /// /// This property can be set to use a custom platform implementation for PdfViews. /// /// Setting `platform` doesn't affect [PdfView]s that were already created. /// /// The default value is [AndroidPdfViewer] on Android and [CupertinoPdfViewer] on iOS. static set platform(PdfViewerPlatform? platform) { _platform = platform; } /// The PdfView platform that's used by this PdfView. /// /// The default value is [AndroidPdfViewer] on Android and [CupertinoPdfViewer] on iOS. static PdfViewerPlatform get platform { if (_platform == null) { switch (defaultTargetPlatform) { case TargetPlatform.android: _platform = AndroidPdfViewer(); break; case TargetPlatform.iOS: _platform = CupertinoPdfViewer(); break; default: throw UnsupportedError( "Trying to use the default PdfView implementation for $defaultTargetPlatform but there isn't a default one"); } } return _platform!; } /// Which gestures should be consumed by the PdfView. /// /// It is possible for other gesture recognizers to be competing with the Pdf View on pointer /// events, e.g if the Pdf View is inside a [ListView] the [ListView] will want to handle /// vertical drags. The Pdf View will claim gestures that are recognized by any of the /// recognizers on this list. /// /// When this set is empty or null, the Pdf View will only handle pointer events for gestures that /// were not claimed by any other gesture recognizer. final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers; /// The initial path to load. final String path; /// A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations. /// /// This only works on iOS. /// /// By default `gestureNavigationEnabled` is false. final bool gestureNavigationEnabled; @override State<StatefulWidget> createState() => _PdfViewState(); } class _PdfViewState extends State<PdfView> { @override Widget build(BuildContext context) { return PdfView.platform.build( context: context, gestureRecognizers: widget.gestureRecognizers, creationParams: _creationParamsFromWidget(widget), ); } } CreationParams _creationParamsFromWidget(PdfView widget) { return CreationParams( path: widget.path, ); } <|start_filename|>android/src/main/java/dev/britto/pdf_viewer_plugin/PdfViewer.java<|end_filename|> package dev.britto.pdf_viewer_plugin; import com.github.barteksc.pdfviewer.PDFView; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import java.io.File; import java.util.Map; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.platform.PlatformView; /// Disable the PdfView recycle when onDetachedFromWindow is called, fixing the /// flutter hot reload. class CustomPDFView extends PDFView { boolean enableRecycle = true; public CustomPDFView(Context context, AttributeSet set) { super(context, set); } @Override protected void onDetachedFromWindow() { Log.i("PdfViewer", "onDetachedFromWindow"); enableRecycle = false; super.onDetachedFromWindow(); enableRecycle = true; } @Override public void recycle() { if (enableRecycle) { super.recycle(); } } } public class PdfViewer implements PlatformView, MethodCallHandler { final MethodChannel methodChannel; private PDFView pdfView; private String filePath; PdfViewer(final Context context, MethodChannel methodChannel, Map<String, Object> params, View containerView) { // Log.i("PdfViewer", "init"); this.methodChannel = methodChannel; this.methodChannel.setMethodCallHandler(this); if (!params.containsKey("filePath")) { return; } filePath = (String)params.get("filePath"); pdfView = new CustomPDFView(context, null); loadPdfView(); } @Override public void onMethodCall(MethodCall call, Result result) { if (call.method.equals("getPdfViewer")) { result.success(null); } else { result.notImplemented(); } } private void loadPdfView() { pdfView.fromFile(new File(filePath)) .enableSwipe(true) // allows to block changing pages using swipe .swipeHorizontal(false) .enableDoubletap(true) .defaultPage(0) .load(); } @Override public View getView() { return pdfView; } @Override public void onFlutterViewAttached(@NonNull View flutterView) { // Log.i("PdfViewer", "onFlutterViewAttached"); } @Override public void onFlutterViewDetached() { // Log.i("PdfViewer", "onFlutterViewDetached"); } @Override public void dispose() { // Log.i("PdfViewer", "dispose"); methodChannel.setMethodCallHandler(null); } } <|start_filename|>example/lib/main.dart<|end_filename|> import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:path_provider/path_provider.dart'; import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final sampleUrl = 'http://www.africau.edu/images/default/sample.pdf'; String? pdfFlePath; Future<String> downloadAndSavePdf() async { final directory = await getApplicationDocumentsDirectory(); final file = File('${directory.path}/sample.pdf'); if (await file.exists()) { return file.path; } final response = await http.get(Uri.parse(sampleUrl)); await file.writeAsBytes(response.bodyBytes); return file.path; } void loadPdf() async { pdfFlePath = await downloadAndSavePdf(); setState(() {}); } @override Widget build(BuildContext context) { return MaterialApp( home: Builder(builder: (context) { return Scaffold( backgroundColor: Colors.black, appBar: AppBar( title: Text('Plugin example app'), ), body: Center( child: Column( children: <Widget>[ ElevatedButton( child: Text("Load pdf"), onPressed: loadPdf, ), if (pdfFlePath != null) Expanded( child: Container( child: PdfView(path: pdfFlePath!), ), ) else Text("Pdf is not Loaded"), ], ), ), ); }), ); } }
lubritto/Pdf_Viewer_Plugin
<|start_filename|>example/js/bundle.js<|end_filename|> (function () { 'use strict'; /* json-format v.1.1 http://github.com/phoboslab/json-format Released under MIT license: http://www.opensource.org/licenses/mit-license.php */ var p = [], push = function(m) { return '\\' + p.push(m) + '\\'; }, pop = function(m, i) { return p[i - 1] }, tabs = function(count) { return new Array(count + 1).join('\t'); }; function jsonFormat(json) { p = []; var out = "", indent = 0; // Extract backslashes and strings json = json .replace(/\\./g, push) .replace(/(".*?"|'.*?')/g, push) .replace(/\s+/, ''); // Indent and insert newlines for (var i = 0; i < json.length; i++) { var c = json.charAt(i); switch (c) { case '{': out += c + "\n" + tabs(++indent); break; case '[': out += c + "\n" + tabs(++indent); break; case ']': out += "\n" + tabs(--indent) + c; break; case '}': out += "\n" + tabs(--indent) + c; break; case ',': if (/\d/.test(json.charAt(i - 1))) { out += ", "; } else { out += ",\n" + tabs(indent); } break; case ':': out += ": "; break; default: out += c; break; } } // Strip whitespace from numeric arrays and put backslashes // and strings back in out = out .replace(/\[[\d,\s]+?\]/g, function(m) { return m.replace(/\s/g, ''); }) // number arrays .replace(/\[\s*(\d)/g, function(a, b) { return '[' + b; }) .replace(/(\d)\s*\]/g, function(a, b) { return b + ']'; }) .replace(/\{\s*\}/g, '{}') // empty objects .replace(/\\(\d+)\\/g, pop) // strings .replace(/\\(\d+)\\/g, pop); // backslashes in strings return out; } function xmlFormat(xml) { var formatted = ''; var reg = /(>)(<)(\/*)/g; xml = xml.replace(reg, '$1\r\n$2$3'); var pad = 0; xml.split('\r\n').forEach(function(node, index) { var indent = 0; if (node.match(/.+<\/\w[^>]*>$/)) { indent = 0; } else if (node.match(/^<\/\w/)) { if (pad != 0) { pad -= 1; } } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) { indent = 1; } else { indent = 0; } var padding = ''; for (var i = 0; i < pad; i++) { padding += ' '; } formatted += padding + node + '\r\n'; pad += indent; }); return formatted; } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn) { var module = { exports: {} }; return fn(module, module.exports), module.exports; } /* BSD-2-Clause @preserve */ var wmsCapabilities_min = createCommonjsModule(function (module, exports) { (function(f,m){module.exports=m();})(commonjsGlobal,function(){function f(a){return void 0!==a}function m(a,c,b){if(a.nodeType===u.CDATA_SECTION||a.nodeType===u.TEXT){ c?b.push(String(a.nodeValue).replace(/(\r\n|\r|\n)/g,"")):b.push(a.nodeValue); }else { for(a=a.firstChild;a;a=a.nextSibling){ m(a,c,b); } }return b}function F(a){for(a= a.nextElementSibling||a.nextSibling;a&&a.nodeType!==u.ELEMENT;){ a=a.nextSibling; }return a}function h(a,c,b){b=f(b)?b:{};var d;var n=0;for(d=a.length;n<d;++n){ b[a[n]]=c; }return b}function A(a,c){return function(b,d){b=a.call(f(c)?c:this,b,d);f(b)&&d[d.length-1].push(b);}}function l(a,c,b,d,e){d.push(a);for(a=b.firstElementChild||b.firstChild;a&&a.nodeType!==u.ELEMENT;){ a=a.nextSibling; }for(;a;a=F(a)){ b=c[a.namespaceURI||null],f(b)&&(b=b[a.localName],f(b)&&b.call(e,a,d)); }return d.pop()}function b(a,c,b){return function(d, e){var n=a.call(f(b)?b:this,d,e);f(n)&&(e=e[e.length-1],d=f(c)?c:d.localName,e[d]=n);}}function k(a,c,b){return function(d,e){var n=a.call(f(b)?b:this,d,e);if(f(n)){e=e[e.length-1];d=f(c)?c:d.localName;var g=[];(d in e?e[d]:e[d]=g).push(n);}}}function r(a){if(a=/^\s*(true|1)|(false|0)\s*$/.exec(a)){ return f(a[1])||!1 }}function t(a){return p(m(a,!1,[]).join(""))}function p(a){if(a=/^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(a)){ return parseFloat(a[1]) }}function w(a){return v(m(a,!1,[]).join(""))}function v(a){if(a= /^\s*(\d+)\s*$/.exec(a)){ return parseInt(a[1],10) }}function e(a){return m(a,!1,[]).join("").replace(G,"")}function x(a){return a.getAttributeNS("http://www.w3.org/1999/xlink","href")}function B(a){return [p(a.getAttribute("minx")),p(a.getAttribute("miny")),p(a.getAttribute("maxx")),p(a.getAttribute("maxy"))]}function q(a,c){return l({},H,a,c)}function y(a,c){return l({},I,a,c)}function C(a,c){c=q(a,c);if(f(c)){ return a=[v(a.getAttribute("width")),v(a.getAttribute("height"))],c.size=a,c }}function D(a,c){return l([], J,a,c)}var u={ELEMENT:1,ATTRIBUTE:2,TEXT:3,CDATA_SECTION:4,ENTITY_REFERENCE:5,ENTITY:6,PROCESSING_INSTRUCTION:7,COMMENT:8,DOCUMENT:9,DOCUMENT_TYPE:10,DOCUMENT_FRAGMENT:11,NOTATION:12},z=function(a){this._parser=new a;};z.prototype.toDocument=function(a){return this._parser.parseFromString(a,"application/xml")};z.prototype.getAllTextContent=function(a,c){return m(a,c,[]).join("").join("")};var G=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,g=[null,"http://www.opengis.net/wms"],M=h(g,{Service:b(function(a,c){return l({}, K,a,c)}),Capability:b(function(a,c){return l({},L,a,c)})}),L=h(g,{Request:b(function(a,c){return l({},N,a,c)}),Exception:b(function(a,c){return l([],O,a,c)}),Layer:b(function(a,c){var b=r(a.getAttribute("queryable"));return l({queryable:f(b)?b:!1},E,a,c)})}),K=h(g,{Name:b(e),Title:b(e),Abstract:b(e),KeywordList:b(D),OnlineResource:b(x),ContactInformation:b(function(a,c){return l({},P,a,c)}),Fees:b(e),AccessConstraints:b(e),LayerLimit:b(w),MaxWidth:b(w),MaxHeight:b(w)}),P=h(g,{ContactPersonPrimary:b(function(a, c){return l({},Q,a,c)}),ContactPosition:b(e),ContactAddress:b(function(a,c){return l({},R,a,c)}),ContactVoiceTelephone:b(e),ContactFacsimileTelephone:b(e),ContactElectronicMailAddress:b(e)}),Q=h(g,{ContactPerson:b(e),ContactOrganization:b(e)}),R=h(g,{AddressType:b(e),Address:b(e),City:b(e),StateOrProvince:b(e),PostCode:b(e),Country:b(e)}),O=h(g,{Format:A(e)}),E=h(g,{Name:b(e),Title:b(e),Abstract:b(e),KeywordList:b(D),CRS:k(e),SRS:k(e),EX_GeographicBoundingBox:b(function(a,c){var b=l({},S,a,c);if(f(b)){a= b.westBoundLongitude;c=b.southBoundLatitude;var d=b.eastBoundLongitude;b=b.northBoundLatitude;if(f(a)&&f(c)&&f(d)&&f(b)){ return [a,c,d,b] }}}),LatLonBoundingBox:b(function(a,b){a=B(a);if(f(a[0])&&f(a[1])&&f(a[2])&&f(a[3])){ return a }}),BoundingBox:k(function(a,b){b=B(a);var c=[p(a.getAttribute("resx")),p(a.getAttribute("resy"))];return {crs:a.getAttribute("CRS")||a.getAttribute("SRS"),extent:b,res:c}}),Dimension:k(function(a,b){return {name:a.getAttribute("name"),units:a.getAttribute("units"),unitSymbol:a.getAttribute("unitSymbol"), "default":a.getAttribute("default"),multipleValues:r(a.getAttribute("multipleValues")),nearestValue:r(a.getAttribute("nearestValue")),current:r(a.getAttribute("current")),values:e(a)}}),Attribution:b(function(a,b){return l({},T,a,b)}),AuthorityURL:k(function(a,b){b=q(a,b);if(f(b)){ return b.name=a.getAttribute("name"),b }}),Identifier:k(e),MetadataURL:k(function(a,b){b=q(a,b);if(f(b)){ return b.type=a.getAttribute("type"),b }}),DataURL:k(q),FeatureListURL:k(q),Style:k(function(a,b){return l({},U,a,b)}),MinScaleDenominator:b(t), MaxScaleDenominator:b(t),ScaleHint:b(function(a,b){b=parseFloat(a.getAttribute("min"));a=parseFloat(a.getAttribute("max"));return {min:b,max:a}}),Layer:k(function(a,b){var c=b[b.length-1];b=l({},E,a,b);if(f(b)){var d=r(a.getAttribute("queryable"));f(d)||(d=c.queryable);b.queryable=f(d)?d:!1;d=v(a.getAttribute("cascaded"));f(d)||(d=c.cascaded);b.cascaded=d;d=r(a.getAttribute("opaque"));f(d)||(d=c.opaque);b.opaque=f(d)?d:!1;d=r(a.getAttribute("noSubsets"));f(d)||(d=c.noSubsets);b.noSubsets=f(d)?d:!1; d=p(a.getAttribute("fixedWidth"));f(d)||(d=c.fixedWidth);b.fixedWidth=d;a=p(a.getAttribute("fixedHeight"));f(a)||(a=c.fixedHeight);b.fixedHeight=a;a=["Style","CRS","AuthorityURL"];d=0;for(var e=a.length;d<e;d++){var g=a[d],h=c[g];if(f(h)){var k=[];k=g in b?b[g]:b[g]=k;k=k.concat(h);b[g]=k;}}a="EX_GeographicBoundingBox BoundingBox Dimension Attribution MinScaleDenominator MaxScaleDenominator".split(" ");d=0;for(e=a.length;d<e;d++){ g=a[d],f(b[g])||(b[g]=c[g]); }return b}})}),T=h(g,{Title:b(e),OnlineResource:b(x), LogoURL:b(C)}),S=h(g,{westBoundLongitude:b(t),eastBoundLongitude:b(t),southBoundLatitude:b(t),northBoundLatitude:b(t)}),N=h(g,{GetCapabilities:b(y),GetMap:b(y),GetFeatureInfo:b(y)}),I=h(g,{Format:k(e),DCPType:k(function(a,b){return l({},V,a,b)})}),V=h(g,{HTTP:b(function(a,b){return l({},W,a,b)})}),W=h(g,{Get:b(q),Post:b(q)}),U=h(g,{Name:b(e),Title:b(e),Abstract:b(e),LegendURL:k(C),StyleSheetURL:b(q),StyleURL:b(q)}),H=h(g,{Format:b(e),OnlineResource:b(x)}),J=h(g,{Keyword:A(e)});g=function(a,b){b|| "undefined"===typeof window||(b=window.DOMParser);this.version=void 0;this._parser=new z(b);this._data=a;};g.prototype.data=function(a){this._data=a;return this};g.prototype.toJSON=function(a){a=a||this._data;return this.parse(a)};g.prototype.parse=function(a){return this._readFromDocument(this._parser.toDocument(a))};g.prototype._readFromDocument=function(a){for(a=a.firstChild;a;a=a.nextSibling){ if(a.nodeType==u.ELEMENT){ return this.readFromNode(a); } }return null};g.prototype.readFromNode=function(a){this.version= a.getAttribute("version");return l({version:this.version},M,a,[])||null};return g}); //# sourceMappingURL=wms-capabilities.min.js.map }); //import Spinner from 'spin.js'; //////////////////////////////////////////////////////////////////////////////// var serviceSelect = document.getElementById('service'); var xml = document.getElementById('xml'); var json = document.getElementById('json'); var input = document.getElementById('input-area'); // the only open CORS proxy I could find var parser = new wmsCapabilities_min(); function showInput() { xml.style.display = 'none'; input.style.display = 'inline-block'; } function hideInput() { xml.style.display = 'inline-block'; input.style.display = 'none'; } function update(xmlString) { xml.textContent = xmlFormat(xmlString); Prism.highlightElement(xml); json.textContent = jsonFormat(JSON.stringify(parser.parse(xmlString))); Prism.highlightElement(json); } serviceSelect.addEventListener('change', function() { if (serviceSelect.value !== '') { hideInput(); fetch(serviceSelect.value) .then(function (response) { return response.text(); }) .then(function (xmlString) { return update(xmlString); }); } }, false); xml.addEventListener('click', showInput, false); input.addEventListener('paste', function() { setTimeout(function() { update(input.value); hideInput(); }, 50); }, false); }()); <|start_filename|>example/css/style.css<|end_filename|> html, body { margin: 0; padding: 0; color: #F0F1F1; background: #4A4D4E; } .topcoat-select { padding: 0; margin: 0; font: inherit; color: inherit; background: transparent; border: none; } .topcoat-select { vertical-align: top; outline: none; } .topcoat-select { cursor: default; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .topcoat-select { -moz-box-sizing: border-box; box-sizing: border-box; background-clip: padding-box; } .topcoat-select { position: relative; display: inline-block; vertical-align: top; } .topcoat-select:disabled { opacity: 0.3; cursor: default; pointer-events: none; } .topcoat-select { -moz-appearance: none; -webkit-appearance: none; } .topcoat-select::-ms-expand { display: none; } /* topdoc name: Topcoat Select description: A component that lets you select things modifiers: :disabled: Disabled state :focus: Focused :invalid: Hover state markup: <select class="topcoat-select"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <select class="topcoat-select" disabled> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> tags: - desktop - mobile - text - input */ .topcoat-select { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; cursor: pointer; appearance: button; text-indent: 0.01px; text-overflow: ''; padding: 0.7rem 1.3rem 0.7rem 1rem; font-size: 16px; font-weight: 400; height: 3rem; letter-spacing: 1px; color: hsl(180, 2%, 78%); text-shadow: 0 -1px hsla(0, 0%, 0%, 0.69); border-radius: 6px; background-color: hsl(180, 1%, 35%); box-shadow: inset 0 1px hsl(0, 0%, 45%); border: 1px solid hsl(180, 1%, 20%); background-image: url('../img/dropdown.svg'); background-repeat: no-repeat; background-position: center right; } .topcoat-select:hover { background-color: hsl(200, 2%, 39%); } .topcoat-select:active { background-color: hsl(210, 2%, 25%); box-shadow: inset 0 1px hsla(0, 0%, 0%, 0.05); } .topcoat-select:focus { border: 1px solid hsl(227, 100%, 50%); box-shadow: 0 0 0 2px hsl(208, 82%, 69%); outline: 0; } h2, h3 { font-weight: 300; } .container { margin: 0 auto; } .container a { color: #288edf; text-decoration: none; } .container a:hover { text-decoration: underline; } .container header { position: relative; } .container header:before { content: ''; width: 100%; display: block; position: absolute; left: 0; top: 23px; } .container .wrapper { padding: 30px; } .container .github-button { color: transparent; } .container .code, .container .code:focus { max-height: 350px; margin-right: 20px; border-radius: 0.5em; border: 0.3em solid hsl(0, 0%, 33%); box-shadow: 1px 1px 0.5em black inset; margin: 0; overflow: auto; padding: 1em; background: hsl(0, 0%, 8%); color: white; direction: ltr; font-family: Consolas, Monaco, 'Andale Mono', monospace; text-align: left; text-shadow: 0 -0.1em 0.2em black; white-space: pre; word-spacing: normal; word-break: normal; line-height: 1.5; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none; width: 95%; } .container #input-area { display: none; } .container .outputs { clear: both; padding-bottom: 40px; } .container .output { width: 49%; vertical-align: top; display: inline-block; min-width: 600px; } @media (min-width: 900px) { #map { width: 60%; height: 100%; } #controls { width: 40%; } #controls .control.range { display: inline-block; } } <|start_filename|>src/parsers.js<|end_filename|> import XMLParser, { makeObjectPropertySetter, makeObjectPropertyPusher, makeParsersNS, pushParseAndPop, makeArrayPusher } from './xml_parser'; import { readString, readDecimalString, readBooleanString, readNonNegativeIntegerString, readNonNegativeInteger, readDecimal } from './xsd'; import { readHref } from './xlink'; import setIfUndefined from './utils/setifundefined'; import isDef from './utils/isdef'; /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Attribution object. */ function readAttribution(node, objectStack) { return pushParseAndPop({}, ATTRIBUTION_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @return {ol.Extent} Bounding box object. */ function readBoundingBoxExtent (node) { return [ readDecimalString(node.getAttribute('minx')), readDecimalString(node.getAttribute('miny')), readDecimalString(node.getAttribute('maxx')), readDecimalString(node.getAttribute('maxy')) ]; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object} Bounding box object. */ function readBoundingBox (node, objectStack) { const extent = readBoundingBoxExtent(node); const resolutions = [ readDecimalString(node.getAttribute('resx')), readDecimalString(node.getAttribute('resy')) ]; return { 'crs': node.getAttribute('CRS') || node.getAttribute('SRS'), extent, res: resolutions }; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {ol.Extent|undefined} Bounding box object. */ function readLatLonBoundingBox (node, objectStack) { const extent = readBoundingBoxExtent(node); if (!isDef(extent[0]) || !isDef(extent[1]) || !isDef(extent[2]) || !isDef(extent[3])) { return undefined; } return extent; } /** * @privat * @param {Node} node Node * @param {Arra.<Object>} objectStack Object stack * @return {Object} */ function readScaleHint (node, objectStack) { const min = parseFloat(node.getAttribute('min')); const max = parseFloat(node.getAttribute('max')); return { min, max }; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {ol.Extent|undefined} Bounding box object. */ function readEXGeographicBoundingBox (node, objectStack) { const geographicBoundingBox = pushParseAndPop({}, EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS, node, objectStack); if (!isDef(geographicBoundingBox)) return undefined; const westBoundLongitude = /** @type {number|undefined} */ (geographicBoundingBox['westBoundLongitude']); const southBoundLatitude = /** @type {number|undefined} */ (geographicBoundingBox['southBoundLatitude']); const eastBoundLongitude = /** @type {number|undefined} */ (geographicBoundingBox['eastBoundLongitude']); const northBoundLatitude = /** @type {number|undefined} */ (geographicBoundingBox['northBoundLatitude']); if (!isDef(westBoundLongitude) || !isDef(southBoundLatitude) || !isDef(eastBoundLongitude) || !isDef(northBoundLatitude)) { return undefined; } return [ westBoundLongitude, southBoundLatitude, eastBoundLongitude, northBoundLatitude ]; } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Object|undefined} Capability object. */ function readCapability (node, objectStack) { return pushParseAndPop({}, CAPABILITY_PARSERS, node, objectStack); } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Object|undefined} Service object. */ function readService (node, objectStack) { return pushParseAndPop({}, SERVICE_PARSERS, node, objectStack); } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Object|undefined} Contact information object. */ function readContactInformation (node, objectStack) { return pushParseAndPop({}, CONTACT_INFORMATION_PARSERS, node, objectStack); } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Object|undefined} Contact person object. */ function readContactPersonPrimary (node, objectStack) { return pushParseAndPop({}, CONTACT_PERSON_PARSERS, node, objectStack); } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Object|undefined} Contact address object. */ function readContactAddress (node, objectStack) { return pushParseAndPop({}, CONTACT_ADDRESS_PARSERS, node, objectStack); } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Array.<string>|undefined} Format array. */ function readException (node, objectStack) { return pushParseAndPop( [], EXCEPTION_PARSERS, node, objectStack); } /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @private * @return {Object|undefined} Layer object. */ function readCapabilityLayer (node, objectStack) { const queryable = readBooleanString(node.getAttribute('queryable')); return pushParseAndPop({ queryable: isDef(queryable) ? queryable : false }, LAYER_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Layer object. */ function readLayer (node, objectStack) { var parentLayerObject = /** @type {Object.<string,*>} */ (objectStack[objectStack.length - 1]); const layerObject = /** @type {Object.<string,*>} */ (pushParseAndPop({}, LAYER_PARSERS, node, objectStack)); if (!isDef(layerObject)) return undefined; let queryable = readBooleanString(node.getAttribute('queryable')); if (!isDef(queryable)) { queryable = parentLayerObject['queryable']; } layerObject['queryable'] = isDef(queryable) ? queryable : false; let cascaded = readNonNegativeIntegerString(node.getAttribute('cascaded')); if (!isDef(cascaded)) { cascaded = parentLayerObject['cascaded']; } layerObject['cascaded'] = cascaded; let opaque = readBooleanString(node.getAttribute('opaque')); if (!isDef(opaque)) { opaque = parentLayerObject['opaque']; } layerObject['opaque'] = isDef(opaque) ? opaque : false; let noSubsets = readBooleanString(node.getAttribute('noSubsets')); if (!isDef(noSubsets)) { noSubsets = parentLayerObject['noSubsets']; } layerObject['noSubsets'] = isDef(noSubsets) ? noSubsets : false; let fixedWidth = readDecimalString(node.getAttribute('fixedWidth')); if (!isDef(fixedWidth)) { fixedWidth = parentLayerObject['fixedWidth']; } layerObject['fixedWidth'] = fixedWidth; let fixedHeight = readDecimalString(node.getAttribute('fixedHeight')); if (!isDef(fixedHeight)) { fixedHeight = parentLayerObject['fixedHeight']; } layerObject['fixedHeight'] = fixedHeight; // See 7.2.4.8 const addKeys = ['Style', 'CRS', 'AuthorityURL']; for (let i = 0, len = addKeys.length; i < len; i++) { const key = addKeys[i]; const parentValue = parentLayerObject[key]; if (isDef(parentValue)) { let childValue = setIfUndefined(layerObject, key, []); childValue = childValue.concat(parentValue); layerObject[key] = childValue; } } const replaceKeys = ['EX_GeographicBoundingBox', 'BoundingBox', 'Dimension', 'Attribution', 'MinScaleDenominator', 'MaxScaleDenominator' ]; for (let i = 0, len = replaceKeys.length; i < len; i++) { const key = replaceKeys[i]; const childValue = layerObject[key]; if (!isDef(childValue)) { const parentValue = parentLayerObject[key]; layerObject[key] = parentValue; } } return layerObject; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object} Dimension object. */ function readDimension (node, objectStack) { return { 'name': node.getAttribute('name'), 'units': node.getAttribute('units'), 'unitSymbol': node.getAttribute('unitSymbol'), 'default': node.getAttribute('default'), 'multipleValues': readBooleanString(node.getAttribute('multipleValues')), 'nearestValue': readBooleanString(node.getAttribute('nearestValue')), 'current': readBooleanString(node.getAttribute('current')), 'values': readString(node) }; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Online resource object. */ function readFormatOnlineresource (node, objectStack) { return pushParseAndPop({}, FORMAT_ONLINERESOURCE_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Request object. */ function readRequest (node, objectStack) { return pushParseAndPop({}, REQUEST_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} DCP type object. */ function readDCPType (node, objectStack) { return pushParseAndPop({}, DCPTYPE_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} HTTP object. */ function readHTTP (node, objectStack) { return pushParseAndPop({}, HTTP_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Operation type object. */ function readOperationType (node, objectStack) { return pushParseAndPop({}, OPERATIONTYPE_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Online resource object. */ function readSizedFormatOnlineresource (node, objectStack) { var formatOnlineresource = readFormatOnlineresource(node, objectStack); if (isDef(formatOnlineresource)) { const size = [ readNonNegativeIntegerString(node.getAttribute('width')), readNonNegativeIntegerString(node.getAttribute('height')) ]; formatOnlineresource['size'] = size; return formatOnlineresource; } return undefined; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Authority URL object. */ function readAuthorityURL (node, objectStack) { var authorityObject = readFormatOnlineresource(node, objectStack); if (isDef(authorityObject)) { authorityObject['name'] = node.getAttribute('name'); return authorityObject; } return undefined; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Metadata URL object. */ function readMetadataURL (node, objectStack) { var metadataObject = readFormatOnlineresource(node, objectStack); if (isDef(metadataObject)) { metadataObject['type'] = node.getAttribute('type'); return metadataObject; } return undefined; } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Object|undefined} Style object. */ function readStyle (node, objectStack) { return pushParseAndPop({}, STYLE_PARSERS, node, objectStack); } /** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Array.<string>|undefined} Keyword list. */ function readKeywordList (node, objectStack) { return pushParseAndPop( [], KEYWORDLIST_PARSERS, node, objectStack); } /** * @const * @type {Array.<string>} */ const NAMESPACE_URIS = [ null, 'http://www.opengis.net/wms' ]; /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ export const PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Service': makeObjectPropertySetter(readService), 'Capability': makeObjectPropertySetter(readCapability) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const CAPABILITY_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Request': makeObjectPropertySetter(readRequest), 'Exception': makeObjectPropertySetter(readException), 'Layer': makeObjectPropertySetter(readCapabilityLayer) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const SERVICE_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Name': makeObjectPropertySetter(readString), 'Title': makeObjectPropertySetter(readString), 'Abstract': makeObjectPropertySetter(readString), 'KeywordList': makeObjectPropertySetter(readKeywordList), 'OnlineResource': makeObjectPropertySetter(readHref), 'ContactInformation': makeObjectPropertySetter(readContactInformation), 'Fees': makeObjectPropertySetter(readString), 'AccessConstraints': makeObjectPropertySetter(readString), 'LayerLimit': makeObjectPropertySetter(readNonNegativeInteger), 'MaxWidth': makeObjectPropertySetter(readNonNegativeInteger), 'MaxHeight': makeObjectPropertySetter(readNonNegativeInteger) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const CONTACT_INFORMATION_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'ContactPersonPrimary': makeObjectPropertySetter(readContactPersonPrimary), 'ContactPosition': makeObjectPropertySetter(readString), 'ContactAddress': makeObjectPropertySetter(readContactAddress), 'ContactVoiceTelephone': makeObjectPropertySetter(readString), 'ContactFacsimileTelephone': makeObjectPropertySetter(readString), 'ContactElectronicMailAddress': makeObjectPropertySetter(readString) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const CONTACT_PERSON_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'ContactPerson': makeObjectPropertySetter(readString), 'ContactOrganization': makeObjectPropertySetter(readString) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const CONTACT_ADDRESS_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'AddressType': makeObjectPropertySetter(readString), 'Address': makeObjectPropertySetter(readString), 'City': makeObjectPropertySetter(readString), 'StateOrProvince': makeObjectPropertySetter(readString), 'PostCode': makeObjectPropertySetter(readString), 'Country': makeObjectPropertySetter(readString) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const EXCEPTION_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Format': makeArrayPusher(readString) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const LAYER_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Name': makeObjectPropertySetter(readString), 'Title': makeObjectPropertySetter(readString), 'Abstract': makeObjectPropertySetter(readString), 'KeywordList': makeObjectPropertySetter(readKeywordList), 'CRS': makeObjectPropertyPusher(readString), 'SRS': makeObjectPropertyPusher(readString), 'EX_GeographicBoundingBox': makeObjectPropertySetter(readEXGeographicBoundingBox), 'LatLonBoundingBox': makeObjectPropertySetter(readLatLonBoundingBox), 'BoundingBox': makeObjectPropertyPusher(readBoundingBox), 'Dimension': makeObjectPropertyPusher(readDimension), 'Attribution': makeObjectPropertySetter(readAttribution), 'AuthorityURL': makeObjectPropertyPusher(readAuthorityURL), 'Identifier': makeObjectPropertyPusher(readString), 'MetadataURL': makeObjectPropertyPusher(readMetadataURL), 'DataURL': makeObjectPropertyPusher(readFormatOnlineresource), 'FeatureListURL': makeObjectPropertyPusher(readFormatOnlineresource), 'Style': makeObjectPropertyPusher(readStyle), 'MinScaleDenominator': makeObjectPropertySetter(readDecimal), 'MaxScaleDenominator': makeObjectPropertySetter(readDecimal), 'ScaleHint': makeObjectPropertySetter(readScaleHint), 'Layer': makeObjectPropertyPusher(readLayer) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const ATTRIBUTION_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Title': makeObjectPropertySetter(readString), 'OnlineResource': makeObjectPropertySetter(readHref), 'LogoURL': makeObjectPropertySetter(readSizedFormatOnlineresource) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS = makeParsersNS(NAMESPACE_URIS, { 'westBoundLongitude': makeObjectPropertySetter(readDecimal), 'eastBoundLongitude': makeObjectPropertySetter(readDecimal), 'southBoundLatitude': makeObjectPropertySetter(readDecimal), 'northBoundLatitude': makeObjectPropertySetter(readDecimal) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const REQUEST_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'GetCapabilities': makeObjectPropertySetter( readOperationType), 'GetMap': makeObjectPropertySetter( readOperationType), 'GetFeatureInfo': makeObjectPropertySetter( readOperationType) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const OPERATIONTYPE_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Format': makeObjectPropertyPusher(readString), 'DCPType': makeObjectPropertyPusher( readDCPType) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const DCPTYPE_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'HTTP': makeObjectPropertySetter( readHTTP) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const HTTP_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Get': makeObjectPropertySetter( readFormatOnlineresource), 'Post': makeObjectPropertySetter( readFormatOnlineresource) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const STYLE_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Name': makeObjectPropertySetter(readString), 'Title': makeObjectPropertySetter(readString), 'Abstract': makeObjectPropertySetter(readString), 'LegendURL': makeObjectPropertyPusher(readSizedFormatOnlineresource), 'StyleSheetURL': makeObjectPropertySetter(readFormatOnlineresource), 'StyleURL': makeObjectPropertySetter(readFormatOnlineresource) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const FORMAT_ONLINERESOURCE_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Format': makeObjectPropertySetter(readString), 'OnlineResource': makeObjectPropertySetter(readHref) }); /** * @const * @type {Object.<string, Object.<string, XMLParser.Parser>>} * @private */ const KEYWORDLIST_PARSERS = makeParsersNS( NAMESPACE_URIS, { 'Keyword': makeArrayPusher(readString) }); <|start_filename|>rollup.config.js<|end_filename|> import buble from '@rollup/plugin-buble'; import commonjs from '@rollup/plugin-commonjs'; import nodeResolve from '@rollup/plugin-node-resolve'; import compiler from '@ampproject/rollup-plugin-closure-compiler'; import browsersync from 'rollup-plugin-browsersync'; import { name, description, license, version } from './package.json'; const banner = ` /** * ${name} @${version} * @description ${description} * @license ${license} * @preserve */ ` export default [{ input: 'src/index.js', output: { file: 'dist/wms-capabilities.js', format: 'umd', name: 'WMSCapabilities', sourcemap: true, banner }, plugins: [ buble(), ] }, { input: 'src/index.js', output: { file: 'dist/wms-capabilities.min.js', format: 'umd', name: 'WMSCapabilities', sourcemap: true, banner }, plugins: [ buble(), compiler({ }) ] }, { input: 'example/js/app.js', output: { file: 'example/js/bundle.js', format: 'iife' }, plugins: [ (process.argv[2].indexOf('w') !== -1) ? browsersync({ server: '.', port: 3002 }) : null, nodeResolve(), commonjs(), buble(), ] }]; <|start_filename|>test/index.js<|end_filename|> "use strict"; import tape from 'tape'; import WMSCapabilities from '../dist/wms-capabilities'; import fs from 'fs'; import path from 'path'; import { DOMParser } from 'xmldom'; tape('WMSCapabilities', function(t) { t.test('forecasts.xml', function(t) { var url = path.join(process.cwd(), './test/fixtures/forecasts.xml'); var xml = fs.readFileSync(url, { encoding: 'utf-8' }); var json = new WMSCapabilities(undefined, DOMParser).parse(xml); t.ok(json, 'got result'); t.equal(typeof json, 'object', 'parsed'); t.equal(json.Capability.Layer.Layer[2].Name, "world_rivers", 'contents'); t.end(); }); t.test('obs.xml', function(t) { var url = path.join(process.cwd(), './test/fixtures/obs.xml'); var xml = fs.readFileSync(url, { encoding: 'utf-8' }); var json = new WMSCapabilities(xml, DOMParser).toJSON(); t.ok(json, 'got result'); t.equal(typeof json, 'object', 'parsed'); t.equal(json.Capability.Layer.Layer[2].Name, "world_rivers", 'contents'); t.end(); }); t.test('wwa.xml', function(t) { var url = path.join(process.cwd(), './test/fixtures/wwa.xml') var xml = fs.readFileSync(url, { encoding: 'utf-8' }); var json = new WMSCapabilities(xml, DOMParser).toJSON(); t.ok(json, 'got result'); t.equal(typeof json, 'object', 'parsed'); t.equal(json.Capability.Layer.Layer[2].Name, "world_rivers", 'contents'); t.end(); }); t.test('analyses.xml', function(t) { var url = path.join(process.cwd(), './test/fixtures/analyses.xml'); var xml = fs.readFileSync(url, { encoding: 'utf-8' }); var json = new WMSCapabilities(xml, DOMParser).toJSON(); t.ok(json, 'got result'); t.equal(typeof json, 'object', 'parsed'); t.equal(json.Capability.Layer.Layer[2].Name, "world_countries_label", 'contents'); t.end(); }); t.test('dmsp.xml', function(t) { var url = path.join(process.cwd(), './test/fixtures/dmsp.xml'); var xml = fs.readFileSync(url, { encoding: 'utf-8' }); var json = new WMSCapabilities(xml, DOMParser).toJSON(); t.ok(json, 'got result'); t.equal(typeof json, 'object', 'parsed'); t.equal(json.Capability.Layer.Layer[2].Name, "eez", 'contents'); t.end(); }); t.end(); }); <|start_filename|>src/externs.js<|end_filename|> /** * Externs file for google closure compiler */ // this makes GCC play with browserify /** * @param {*=}o * @param {*=}u */ window.require = function(o, u) {}; /** * @type {Object} */ window.module = { exports: {} }; window['WMSCapabilities'] = function () {}; /** * @class WMSCapabilities * @constructor */ window['WMSCapabilities'] = function() {}; /** * @param {String} xmlString * @return {WMSCapabilities} */ window['WMSCapabilities'].prototype.data = function(xmlString) {}; /** * @param {String=} xmlString * @return {Object} */ window['WMSCapabilities'].prototype.toJSON = function(xmlString) {}; /** * @param {String} xmlString * @return {Object} */ window['WMSCapabilities'].prototype.parse = function(xmlString) {}; <|start_filename|>src/xsd.js<|end_filename|> import isDef from './utils/isdef'; import { padNumber, trim } from './utils/string'; import XMLParser, { getAllTextContent } from './xml_parser'; /** * @const * @type {string} */ export const NAMESPACE_URI = 'http://www.w3.org/2001/XMLSchema'; /** * @param {Node} node Node. * @return {boolean|undefined} Boolean. */ export function readBoolean (node) { const s = getAllTextContent(node, false); return readBooleanString(s); } /** * @param {string} string String. * @return {boolean|undefined} Boolean. */ export function readBooleanString (string) { const m = /^\s*(true|1)|(false|0)\s*$/.exec(string); if (m) { return isDef(m[1]) || false; } else { return undefined; } } /** * @param {Node} node Node. * @return {number|undefined} DateTime in seconds. */ export function readDateTime (node) { const s = getAllTextContent(node, false); const re = /^\s*(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|(?:([+\-])(\d{2})(?::(\d{2}))?))\s*$/; const m = re.exec(s); if (m) { const year = parseInt(m[1], 10); const month = parseInt(m[2], 10) - 1; const day = parseInt(m[3], 10); const hour = parseInt(m[4], 10); const minute = parseInt(m[5], 10); const second = parseInt(m[6], 10); let dateTime = Date.UTC(year, month, day, hour, minute, second) / 1000; if (m[7] != 'Z') { const sign = m[8] == '-' ? -1 : 1; dateTime += sign * 60 * parseInt(m[9], 10); if (isDef(m[10])) { dateTime += sign * 60 * 60 * parseInt(m[10], 10); } } return dateTime; } else { return undefined; } } /** * @param {Node} node Node. * @return {number|undefined} Decimal. */ export function readDecimal (node) { return readDecimalString(getAllTextContent(node, false)); } /** * @param {string} string String. * @return {number|undefined} Decimal. */ export function readDecimalString (string) { // FIXME check spec const m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string); if (m) { return parseFloat(m[1]); } else { return undefined; } } /** * @param {Node} node Node. * @return {number|undefined} Non negative integer. */ export function readNonNegativeInteger (node) { return readNonNegativeIntegerString(getAllTextContent(node, false)); } /** * @param {string} string String. * @return {number|undefined} Non negative integer. */ export function readNonNegativeIntegerString (string) { const m = /^\s*(\d+)\s*$/.exec(string); if (m) { return parseInt(m[1], 10); } else { return undefined; } } /** * @param {Node} node Node. * @return {string|undefined} String. */ export function readString (node) { return trim(getAllTextContent(node, false)); } /** * @param {Node} node Node to append a TextNode with the boolean to. * @param {boolean} bool Boolean. */ export function writeBooleanTextNode (node, bool) { writeStringTextNode(node, (bool) ? '1' : '0'); } /** * @param {Node} node Node to append a TextNode with the dateTime to. * @param {number} dateTime DateTime in seconds. */ export function writeDateTimeTextNode (node, dateTime) { const date = new Date(dateTime * 1000); const string = date.getUTCFullYear() + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + 'Z'; node.appendChild(XMLParser.DOCUMENT.createTextNode(string)); }; /** * @param {Node} node Node to append a TextNode with the decimal to. * @param {number} decimal Decimal. */ export function writeDecimalTextNode (node, decimal) { const string = decimal.toPrecision(); node.appendChild(XMLParser.DOCUMENT.createTextNode(string)); } /** * @param {Node} node Node to append a TextNode with the decimal to. * @param {number} nonNegativeInteger Non negative integer. */ export function writeNonNegativeIntegerTextNode (node, nonNegativeInteger) { const string = nonNegativeInteger.toString(); node.appendChild(XMLParser.DOCUMENT.createTextNode(string)); } /** * @param {Node} node Node to append a TextNode with the string to. * @param {string} string String. */ export function writeStringTextNode (node, string) { node.appendChild(XMLParser.DOCUMENT.createTextNode(string)); } <|start_filename|>src/utils/isdef.js<|end_filename|> /** * Returns true if the specified value is not undefined. * * @param {?} val Variable to test. * @return {Boolean} Whether variable is defined. */ export default (val) => val !== void 0; <|start_filename|>package.json<|end_filename|> { "name": "wms-capabilities", "version": "0.5.1", "description": "WMS service Capabilities > JSON, based on openlayers ", "main": "dist/wms-capabilities.min.js", "bin": { "wmscapabilities": "bin/wmscapabilities" }, "scripts": { "test": "node -r reify test/index.js | tap-spec", "start": "npm run watch-js & npm run watch-css", "watch-css": "catw -c 'lessc -' 'example/less/*.less' -o example/css/style.css -v", "watch-js": "rollup -cw", "build-less": "lessc example/less/style.less > example/css/style.css", "build-css": "npm run build-less", "build-js": "rollup -c", "build": "npm run build-js && npm run build-css" }, "repository": { "type": "git", "url": "https://github.com/w8r/wms-capabilities.git" }, "devDependencies": { "@ampproject/rollup-plugin-closure-compiler": "^0.26.0", "@rollup/plugin-buble": "^0.21.3", "@rollup/plugin-commonjs": "^18.0.0", "@rollup/plugin-node-resolve": "^11.2.1", "lessc": "^1.0.2", "reify": "^0.20.12", "rollup": "^2.45.2", "rollup-plugin-browsersync": "^1.3.1", "tap-spec": "^5.0.0", "tape": "^5.2.2", "xmldom": "^0.6.0" }, "dependencies": { "minimist": "^1.2.5" }, "keywords": [ "gis", "wms", "getcapabilities", "xml", "json" ], "author": "<NAME> <<EMAIL>>", "license": "BSD-2-Clause", "bugs": { "url": "https://github.com/w8r/wms-capabilities/issues" }, "homepage": "https://github.com/w8r/wms-capabilities" } <|start_filename|>src/xlink.js<|end_filename|> /** * @const * @type {string} */ const NAMESPACE_URI = 'http://www.w3.org/1999/xlink'; /** * @param {Node} node Node. * @return {Boolean|undefined} Boolean. */ export function readHref (node) { return node.getAttributeNS(NAMESPACE_URI, 'href'); } <|start_filename|>src/index.js<|end_filename|> import XMLParser, { pushParseAndPop } from './xml_parser'; import nodeTypes from './node_types'; import { PARSERS } from './parsers'; export default class WMS { /** * WMS Capabilities parser * * @param {String=} xmlString * @constructor */ constructor(xmlString, DOMParser) { if (!DOMParser && typeof window !== 'undefined') { DOMParser = window.DOMParser; } /** * @type {String} */ this.version = undefined; /** * @type {XMLParser} */ this._parser = new XMLParser(DOMParser); /** * @type {String=} */ this._data = xmlString; } /** * @param {String} xmlString * @return {WMS} */ data (xmlString) { this._data = xmlString; return this; } /** * @param {String=} xmlString * @return {Object|null} */ toJSON (xmlString) { xmlString = xmlString || this._data; return this.parse(xmlString); } /** * @return {String} xml * @return {Object|null} */ parse (xmlString) { return this.readFromDocument(this._parser.toDocument(xmlString)); } /** * @param {Document} doc * @return {Object|null} */ readFromDocument (doc) { for (let node = doc.firstChild; node; node = node.nextSibling) { if (node.nodeType == nodeTypes.ELEMENT) { return this.readFromNode(node); } } return null; } /** * @param {DOMNode} node * @return {Object} */ readFromNode (node) { this.version = node.getAttribute('version'); const wmsCapabilityObject = pushParseAndPop({ 'version': this.version }, PARSERS, node, []); return wmsCapabilityObject || null; } } <|start_filename|>src/utils/setifundefined.js<|end_filename|> /** * Adds a key-value pair to the object/map/hash if it doesn't exist yet. * * @param {Object.<K,V>} obj The object to which to add the key-value pair. * @param {String} key The key to add. * @param {V} value The value to add if the key wasn't present. * @return {V} The value of the entry at the end of the function. * @template K,V */ export default (obj, key, value) => key in obj ? obj[key] : (obj[key] = value); <|start_filename|>example/js/app.js<|end_filename|> import jsonFormat from './json-format'; import xmlFormat from './xml-format'; import WMSCapabilities from '../../dist/wms-capabilities.min'; //import Spinner from 'spin.js'; //////////////////////////////////////////////////////////////////////////////// var serviceSelect = document.getElementById('service'); var xml = document.getElementById('xml'); var json = document.getElementById('json'); var input = document.getElementById('input-area'); // the only open CORS proxy I could find var parser = new WMSCapabilities(); function showInput() { xml.style.display = 'none'; input.style.display = 'inline-block'; } function hideInput() { xml.style.display = 'inline-block'; input.style.display = 'none'; } function update(xmlString) { xml.textContent = xmlFormat(xmlString); Prism.highlightElement(xml); json.textContent = jsonFormat(JSON.stringify(parser.parse(xmlString))); Prism.highlightElement(json); } serviceSelect.addEventListener('change', function() { if (serviceSelect.value !== '') { hideInput(); fetch(serviceSelect.value) .then(response => response.text()) .then(xmlString => update(xmlString)); } }, false); xml.addEventListener('click', showInput, false); input.addEventListener('paste', function() { setTimeout(function() { update(input.value); hideInput(); }, 50); }, false);
w8r/wms-capabilities
<|start_filename|>generation/Windows/other/helper-types/other-helper-types.h<|end_filename|> // This file is intentionally empty and only exists to centralize generation of the helper types for TerraFX. <|start_filename|>generation/TerraFX.h<|end_filename|> #include <WinSock2.h> #include <ws2ipdef.h> #include <windns.h> #include <Windows.h> <|start_filename|>samples/WinForms/MainForm.Designer.cs<|end_filename|> namespace TerraFX.Samples.WinForms { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._splitContainer = new System.Windows.Forms.SplitContainer(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this._samplesListBox = new System.Windows.Forms.ListBox(); this.button1 = new System.Windows.Forms.Button(); this._dxPanel = new TerraFX.Samples.WinForms.DXPanel(); this.colorDialog1 = new System.Windows.Forms.ColorDialog(); ((System.ComponentModel.ISupportInitialize)(this._splitContainer)).BeginInit(); this._splitContainer.Panel1.SuspendLayout(); this._splitContainer.Panel2.SuspendLayout(); this._splitContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.SuspendLayout(); // // _splitContainer // this._splitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this._splitContainer.Location = new System.Drawing.Point(0, 0); this._splitContainer.Name = "_splitContainer"; // // _splitContainer.Panel1 // this._splitContainer.Panel1.Controls.Add(this.splitContainer1); // // _splitContainer.Panel2 // this._splitContainer.Panel2.Controls.Add(this._dxPanel); this._splitContainer.Size = new System.Drawing.Size(800, 450); this._splitContainer.SplitterDistance = 266; this._splitContainer.TabIndex = 0; this._splitContainer.Text = "splitContainer1"; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this._samplesListBox); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.button1); this.splitContainer1.Size = new System.Drawing.Size(266, 450); this.splitContainer1.SplitterDistance = 200; this.splitContainer1.TabIndex = 0; this.splitContainer1.Text = "splitContainer1"; // // _samplesListBox // this._samplesListBox.Dock = System.Windows.Forms.DockStyle.Fill; this._samplesListBox.FormattingEnabled = true; this._samplesListBox.ItemHeight = 15; this._samplesListBox.Location = new System.Drawing.Point(0, 0); this._samplesListBox.Name = "_samplesListBox"; this._samplesListBox.Size = new System.Drawing.Size(266, 200); this._samplesListBox.TabIndex = 1; this._samplesListBox.SelectedIndexChanged += new System.EventHandler(this.samplesListBox_SelectedIndexChanged); // // button1 // this.button1.Location = new System.Drawing.Point(3, 3); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(260, 23); this.button1.TabIndex = 0; this.button1.Text = "Background Color"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.backgroundColorButton_Click); // // _dxPanel // this._dxPanel.BackColor = System.Drawing.SystemColors.Control; this._dxPanel.Dock = System.Windows.Forms.DockStyle.Fill; this._dxPanel.DXSample = null; this._dxPanel.Location = new System.Drawing.Point(0, 0); this._dxPanel.Name = "_dxPanel"; this._dxPanel.Size = new System.Drawing.Size(530, 450); this._dxPanel.TabIndex = 0; this._dxPanel.UseWarpDevice = false; // // colorDialog1 // this.colorDialog1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(102))))); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this._splitContainer); this.Name = "MainForm"; this.Text = "MainForm"; this.Load += new System.EventHandler(this.MainForm_Load); this._splitContainer.Panel1.ResumeLayout(false); this._splitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this._splitContainer)).EndInit(); this._splitContainer.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer _splitContainer; private System.Windows.Forms.ListBox _samplesListBox; private TerraFX.Samples.WinForms.DXPanel _dxPanel; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ColorDialog colorDialog1; } } <|start_filename|>generation/Windows/other/mssign32/mssign32.h<|end_filename|> // Code sourced from from https://docs.microsoft.com/en-us/windows/win32/appxpkg/how-to-programmatically-sign-a-package // Copyright © Microsoft. All rights reserved. License information available at https://github.com/MicrosoftDocs/win32/blob/docs/LICENSE-CODE #include <wincrypt.h> extern "C" { typedef struct _SIGNER_FILE_INFO { DWORD cbSize; LPCWSTR pwszFileName; HANDLE hFile; }SIGNER_FILE_INFO, *PSIGNER_FILE_INFO; typedef struct _SIGNER_BLOB_INFO { DWORD cbSize; GUID *pGuidSubject; DWORD cbBlob; BYTE *pbBlob; LPCWSTR pwszDisplayName; }SIGNER_BLOB_INFO, *PSIGNER_BLOB_INFO; typedef struct _SIGNER_SUBJECT_INFO { DWORD cbSize; DWORD *pdwIndex; DWORD dwSubjectChoice; union { SIGNER_FILE_INFO *pSignerFileInfo; SIGNER_BLOB_INFO *pSignerBlobInfo; }; }SIGNER_SUBJECT_INFO, *PSIGNER_SUBJECT_INFO; // dwSubjectChoice should be one of the following: #define SIGNER_SUBJECT_FILE 0x01 #define SIGNER_SUBJECT_BLOB 0x02 typedef struct _SIGNER_ATTR_AUTHCODE { DWORD cbSize; BOOL fCommercial; BOOL fIndividual; LPCWSTR pwszName; LPCWSTR pwszInfo; }SIGNER_ATTR_AUTHCODE, *PSIGNER_ATTR_AUTHCODE; typedef struct _SIGNER_SIGNATURE_INFO { DWORD cbSize; ALG_ID algidHash; DWORD dwAttrChoice; union { SIGNER_ATTR_AUTHCODE *pAttrAuthcode; }; PCRYPT_ATTRIBUTES psAuthenticated; PCRYPT_ATTRIBUTES psUnauthenticated; }SIGNER_SIGNATURE_INFO, *PSIGNER_SIGNATURE_INFO; // dwAttrChoice should be one of the following: #define SIGNER_NO_ATTR 0x00 #define SIGNER_AUTHCODE_ATTR 0x01 typedef struct _SIGNER_PROVIDER_INFO { DWORD cbSize; LPCWSTR pwszProviderName; DWORD dwProviderType; DWORD dwKeySpec; DWORD dwPvkChoice; union { LPWSTR pwszPvkFileName; LPWSTR pwszKeyContainer; }; }SIGNER_PROVIDER_INFO, *PSIGNER_PROVIDER_INFO; //dwPvkChoice should be one of the following: #define PVK_TYPE_FILE_NAME 0x01 #define PVK_TYPE_KEYCONTAINER 0x02 typedef struct _SIGNER_SPC_CHAIN_INFO { DWORD cbSize; LPCWSTR pwszSpcFile; DWORD dwCertPolicy; HCERTSTORE hCertStore; }SIGNER_SPC_CHAIN_INFO, *PSIGNER_SPC_CHAIN_INFO; typedef struct _SIGNER_CERT_STORE_INFO { DWORD cbSize; PCCERT_CONTEXT pSigningCert; DWORD dwCertPolicy; HCERTSTORE hCertStore; }SIGNER_CERT_STORE_INFO, *PSIGNER_CERT_STORE_INFO; //dwCertPolicy can be a combination of the following flags: #define SIGNER_CERT_POLICY_STORE 0x01 #define SIGNER_CERT_POLICY_CHAIN 0x02 #define SIGNER_CERT_POLICY_SPC 0x04 #define SIGNER_CERT_POLICY_CHAIN_NO_ROOT 0x08 typedef struct _SIGNER_CERT { DWORD cbSize; DWORD dwCertChoice; union { LPCWSTR pwszSpcFile; SIGNER_CERT_STORE_INFO *pCertStoreInfo; SIGNER_SPC_CHAIN_INFO *pSpcChainInfo; }; HWND hwnd; }SIGNER_CERT, *PSIGNER_CERT; //dwCertChoice should be one of the following #define SIGNER_CERT_SPC_FILE 0x01 #define SIGNER_CERT_STORE 0x02 #define SIGNER_CERT_SPC_CHAIN 0x03 typedef struct _SIGNER_CONTEXT { DWORD cbSize; DWORD cbBlob; BYTE *pbBlob; }SIGNER_CONTEXT, *PSIGNER_CONTEXT; typedef struct _SIGNER_SIGN_EX2_PARAMS { DWORD dwFlags; PSIGNER_SUBJECT_INFO pSubjectInfo; PSIGNER_CERT pSigningCert; PSIGNER_SIGNATURE_INFO pSignatureInfo; PSIGNER_PROVIDER_INFO pProviderInfo; DWORD dwTimestampFlags; PCSTR pszAlgorithmOid; PCWSTR pwszTimestampURL; PCRYPT_ATTRIBUTES pCryptAttrs; PVOID pSipData; PSIGNER_CONTEXT *pSignerContext; PVOID pCryptoPolicy; PVOID pReserved; } SIGNER_SIGN_EX2_PARAMS, *PSIGNER_SIGN_EX2_PARAMS; typedef struct _APPX_SIP_CLIENT_DATA { PSIGNER_SIGN_EX2_PARAMS pSignerParams; IUnknown* pAppxSipState; } APPX_SIP_CLIENT_DATA, *PAPPX_SIP_CLIENT_DATA; HRESULT WINAPI SignerSignEx2( _In_ DWORD dwFlags, _In_ SIGNER_SUBJECT_INFO *pSubjectInfo, _In_ SIGNER_CERT *pSignerCert, _In_ SIGNER_SIGNATURE_INFO *pSignatureInfo, _In_opt_ SIGNER_PROVIDER_INFO *pProviderInfo, _In_opt_ DWORD dwTimestampFlags, _In_opt_ PCSTR pszTimestampAlgorithmOid, _In_opt_ PCWSTR pwszHttpTimeStamp, _In_opt_ PCRYPT_ATTRIBUTES psRequest, _In_opt_ PVOID pSipData, _Out_ SIGNER_CONTEXT **ppSignerContext, _In_opt_ PCERT_STRONG_SIGN_PARA pCryptoPolicy, _Reserved_ PVOID pReserved ); }
JeremyKuhne/terrafx.interop.windows
<|start_filename|>docs/asset-manifest.json<|end_filename|> { "main.css": "static/css/main.58a98a35.css", "main.css.map": "static/css/main.58a98a35.css.map", "main.js": "static/js/main.ff10fcce.js", "main.js.map": "static/js/main.ff10fcce.js.map" } <|start_filename|>src/components/EmojiZone.css<|end_filename|> .EmojiZone { flex: 2; width: 100%; height: 20rem; margin: 0 0 0 0.725rem; border: 2px solid #313131; border-radius: 5px; box-sizing: border-box; overflow-x: hidden; } .EmojiZone-list { height: calc(100% - 2.5rem); margin: 0; padding: 0 1.5rem; list-style: none; overflow: auto; } @media (max-width: 37.5em) { .EmojiZone { margin: 0.725rem 0 0; max-height: 24rem; } } <|start_filename|>src/components/Spinner.css<|end_filename|> .Spinner { display: flex; align-items: center; justify-content: center; animation: spin 1s infinite ease-in-out; } .Spinner svg { height: 1.5rem; width: 1.5rem; } @keyframes spin { from { transform:rotate(0deg); } to { transform:rotate(359deg); } } <|start_filename|>src/components/DropZone.js<|end_filename|> import React, { Component } from "react"; import "./DropZone.css"; import Ascender from "ascender"; class DropZone extends Component { dropZoneRef = React.createRef(); componentDidMount = () => { this.dropZone = new Ascender(this.dropZoneRef.current); this.dropZone.on("file:added", file => this.props.addFile(file)); }; componentWillUnmount = () => { // Tidy up Ascender listeners this.dropZone.destroy(); this.dropZone = null; }; render() { return ( <form className="DropZone" ref={this.dropZoneRef}> <h1 className="DropZone-title"> Drag Files Here or{" "} <span className="DropZone-prompt">Browse&nbsp;To&nbsp;Select</span> </h1> </form> ); } } export default DropZone; <|start_filename|>src/components/EmojiZone.js<|end_filename|> import React, { Component } from "react"; import EmojiItem from "./EmojiItem"; import ZipDownloadContainer from "./ZipDownloadContainer"; import "./EmojiZone.css"; class EmojiZone extends Component { render() { return ( <div className="EmojiZone"> <ul className="EmojiZone-list"> {Object.keys(this.props.images).map(key => { return ( <EmojiItem key={key} image={this.props.images[key]} imageKey={key} removeImage={this.props.removeImage} /> ); })} </ul> <ZipDownloadContainer files={this.props.images} /> </div> ); } } export default EmojiZone; <|start_filename|>src/components/App.js<|end_filename|> import React, { Component } from "react"; import imageType from "image-type"; import DropZone from "./DropZone"; import EmojiZone from "./EmojiZone"; import resizeImageForSlack from "../resizeImageForSlack"; import { getId } from "../utils"; import "./App.css"; class App extends Component { state = { images: {} }; addFile = file => { file.getBinary().then(binary => { const type = this.getFileType(binary); if (!type) { // Invalid image return; } const images = { ...this.state.images }; const key = getId.next().value; images[key] = { original: file, resizedBlob: null, resizedImgUrl: null, error: false, ready: false }; this.setState({ images }); this.resizeFile(file, type, key); }); }; getFileType(binary) { const validTypes = ["png", "jpg"]; const fileType = imageType(binary); return fileType && validTypes.indexOf(fileType.ext) > -1 ? fileType : null; } resizeFile = async (file, type, key) => { const resizedBlob = await resizeImageForSlack(file, type); const images = { ...this.state.images }; images[key].resizedBlob = resizedBlob; images[key].resizedImgUrl = URL.createObjectURL(resizedBlob); images[key].error = !Boolean(resizedBlob); images[key].ready = true; this.setState({ images }); }; removeImage = key => { const images = { ...this.state.images }; delete images[key]; this.setState({ images }); }; renderAppBody = () => { const emojiZoneNode = ( <EmojiZone images={this.state.images} removeImage={this.removeImage} /> ); const hasImages = Object.keys(this.state.images).length; return ( <div className="App-body"> <DropZone addFile={this.addFile} /> {hasImages ? emojiZoneNode : null} </div> ); }; render() { return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Slackmojize</h1> <h2> <img className="App-parrot-left" src="./parrot.gif" alt="Parrot" /> Easily resize images for Slack&nbsp;Emojis <img className="App-parrot-right" src="./rightparrot.gif" alt="Right Parrot" /> </h2> </header> {this.renderAppBody()} <footer className="App-footer"> Hacked together by{" "} <a href="https://github.com/jamsinclair/slackmojize">jamsinclair</a> </footer> </div> ); } } export default App; <|start_filename|>src/components/App.css<|end_filename|> .App { max-width: 50rem; padding: 1rem; width: 100%; margin: 0 auto; } .App-header { margin-bottom: 2rem; text-align: center; } .App-logo { animation: App-logo-spin infinite 20s linear; height: 80px; } .App-title { display: inline-block; padding: 1.5rem 2.5rem; margin: 0; font-size: 3rem; border-bottom: 4px solid #444; } .App-parrot-left { margin-right: 0.5rem; } .App-parrot-right { margin-left: 0.5rem; } .App-body { display: flex; min-height: 20rem; } .App-footer { padding: 2rem; color: #666; text-align: center; } @media (max-width: 37.5em) { .App-body { flex-direction: column; } } <|start_filename|>src/components/Spinner.js<|end_filename|> import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCircleNotch } from "@fortawesome/free-solid-svg-icons"; import "./Spinner.css"; const Spinner = ({ className }) => ( <div className={`Spinner ${className}`}> <FontAwesomeIcon icon={faCircleNotch} size="1x" /> </div> ); export default Spinner; <|start_filename|>src/components/DropZone.css<|end_filename|> .DropZone { display: flex; justify-content: center; align-items: center; flex: 1; cursor: pointer; width: 100%; margin: 0 auto; padding: 2.5rem; border: 2px dashed #313131; border-radius: 5px; box-sizing: border-box; text-align: center; } .DropZone-title { margin: 0; font-size: 1.5rem; } .DropZone-prompt { text-decoration: underline; } .DropZone:hover .DropZone-prompt { color: #72AAAA; } <|start_filename|>src/components/ZipDownloadButton.css<|end_filename|> .ZipDownloadButton { display: flex; align-items: center; justify-content: center; font-weight: 700; height: 2.5rem; width: 100%; background-color: inherit; border-top: 2px solid #313131; color: inherit; cursor: pointer; transition-property: color, background-color; transition-duration: 0.1s; transition-timing-function: linear; user-select: none; } .ZipDownloadButton:hover { color: #ffffff; background: #313131; } .ZipDownloadButton--disabled, .ZipDownloadButton--loading { background: #313131; cursor: wait; color: #ffffff; opacity: 0.8; } .ZipDownloadButton .Spinner { margin-right: 0.5rem; } <|start_filename|>src/components/ZipDownloadButton.js<|end_filename|> import React from "react"; import "./ZipDownloadButton.css"; const ZipDownloadButton = ({ disabled, download, loading }) => { const disabledClass = disabled ? "ZipDownloadButton--disabled" : ""; return ( <a onClick={() => !loading && download()} className={`ZipDownloadButton ${disabledClass}`} > <span>Download All</span> </a> ); }; export default ZipDownloadButton; <|start_filename|>src/components/EmojiItem.css<|end_filename|> .EmojiItem { display: flex; align-items: center; border-bottom: 1px solid #313131; padding: 1rem 0; } .EmojiItem--loading { opacity: 0.6; pointer-events: none; } .EmojiItem:last-child { border: none; } .EmojiItem-icon, .EmojiItem-image { flex: 0 2rem; height: 2rem; width: 2rem; } .EmojiItem-icon { display: flex; align-items: center; justify-content: center; } .EmojiItem-name-error, .EmojiItem-icon--error { color: #EC6363; } .EmojiItem-name { flex: 1; padding: 0.625rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .EmojiItem-action { cursor: pointer; padding: 0 0.5rem; } .EmojiItem-action, .EmojiItem-action--download:visited, .EmojiItem-action--remove:visited { color: inherit; } .EmojiItem-action--download:hover { color: #72AAAA; } .EmojiItem-action--remove:hover { color: #EC6363; } <|start_filename|>src/components/EmojiItem.js<|end_filename|> import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faExclamationCircle, faDownload, faTrashAlt } from "@fortawesome/free-solid-svg-icons"; import Spinner from "./Spinner"; import "./EmojiItem.css"; const renderEmojiImage = image => { if (image.error) { return ( <div className="EmojiItem-icon EmojiItem-icon--error"> <FontAwesomeIcon icon={faExclamationCircle} size="1x" /> </div> ); } if (!image.ready) { return <Spinner className="EmojiItem-icon" />; } return ( <img className="EmojiItem-image" src={image.resizedImgUrl} alt={image.original.name} /> ); }; const ErrorMessage = ({ error }) => { if (!error) { return null; } return <span className="EmojiItem-name-error">Error Resizing: </span>; }; const RemoveAction = ({ removeImage, imageKey }) => ( <span className="EmojiItem-action EmojiItem-action--remove" onClick={() => removeImage(imageKey)} > <FontAwesomeIcon icon={faTrashAlt} size="1x" /> </span> ); const DownloadAction = ({ image }) => { if (image.error) { return null; } return ( <a className="EmojiItem-action EmojiItem-action--download" download={image.original.data.name} href={image.resizedImgUrl} > <FontAwesomeIcon icon={faDownload} size="1x" /> </a> ); }; const EmojiItem = ({ image, imageKey, removeImage }) => { const isLoading = !image.ready; return ( <li className={`EmojiItem ${isLoading ? "EmojiItem--loading" : ""}`}> {renderEmojiImage(image)} <div className="EmojiItem-name"> <ErrorMessage error={image.error} /> {image.original.data.name} </div> <div className="EmojiItem-actions"> <DownloadAction image={image} /> <RemoveAction removeImage={removeImage} imageKey={imageKey} /> </div> </li> ); }; export default EmojiItem; <|start_filename|>src/resizeImageForSlack.js<|end_filename|> import picaModule from "pica/dist/pica"; const pica = picaModule(); const MAX_FILE_SIZE = 64000; const MAX_HEIGHT = 128; const MAX_WIDTH = 128; const resizeImageForSlack = async (file, type) => { const alpha = type.mime === "image/png"; const img = await _createImageFromUri(file); const fromCanvas = _createCanvasForImage(img, alpha); const toCanvas = _createSlackCanvas(); let quality = 1; let outputBlob; await pica.resize(fromCanvas, toCanvas, { alpha, unsharpAmount: 60, unsharpRadius: 0.6, unsharpThreshold: 2 }); do { outputBlob = await pica.toBlob(toCanvas, type.mime, quality); quality -= 0.1; } while (quality > 0.4 && outputBlob.size > MAX_FILE_SIZE); if (outputBlob.size > MAX_FILE_SIZE) { outputBlob = null; } return outputBlob; }; const _createCanvasForImage = (img, alpha) => { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const max = Math.max(img.width, img.height); canvas.width = max; canvas.height = max; // JPEG images do not support alpha // Fill background with white for better slack emoji appearance if (!alpha) { ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, canvas.width, canvas.height); } ctx.drawImage( img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2 ); return canvas; }; const _createSlackCanvas = () => { const canvas = document.createElement("canvas"); canvas.width = MAX_HEIGHT; canvas.height = MAX_WIDTH; return canvas; }; const _createImageFromUri = async file => { const img = document.createElement("img"); const uri = await file.getDataUri(); return new Promise(resolve => { img.onload = () => { resolve(img); }; img.src = uri; }); }; export default resizeImageForSlack; <|start_filename|>src/components/ZipDownloadContainer.js<|end_filename|> import React, { Component } from "react"; import ZipDownloadButton from "./ZipDownloadButton"; import JsZip from "jszip"; import { saveAs } from "file-saver"; class ZipDownloadContainer extends Component { download = () => { this.createZipFile().then(fileContent => saveAs(fileContent, "slackmojis.zip") ); }; createZipFile = () => { const zip = new JsZip(); for (let key in this.props.files) { const file = this.props.files[key]; zip.file(file.original.data.name, file.resizedBlob); } return zip.generateAsync({ type: "blob" }); }; render() { const fileKeys = Object.keys(this.props.files); if (!fileKeys.length) { return null; } // Files can only be ready to download when all uris are populated // @todo Clean this up. Simple property whether file is ready would be great const filesNotReady = fileKeys.some(key => { return !this.props.files[key].ready; }); return ( <ZipDownloadButton disabled={filesNotReady} download={this.download} /> ); } } export default ZipDownloadContainer; <|start_filename|>src/utils.js<|end_filename|> function* idMaker(prefix = "") { let index = 0; while (index < index + 1) yield prefix + index++; } export const getId = idMaker("slm");
jamsinclair/slackmojize
<|start_filename|>public/reserve/js/controllers/reservation_add.js<|end_filename|> //advice_all.js angular .module('app') .controller('reservationAddControl', reservationAddControl) reservationAddControl.$inject = ['$scope', '$http']; function reservationAddControl($scope, $http) { $scope.refresh_tables = function(floor) { $http.get("/api/user/tables/status/"+floor) .then(function(response) { $scope.tables = response.data.tables; }); }; $scope.reserve = function(table_id) { window.location.href = "#!/reservation/add/" + table_id; }; $scope.floor_change = function() { $scope.refresh_tables($scope.selected_floor.id); }; $http.get("/api/floors/get") .then(function(response) { $scope.floors = response.data.data; $scope.selected_floor = $scope.floors[0]; $scope.refresh_tables($scope.floors[0].id) }); } <|start_filename|>public/reserve/js/controllers/reservation_add_detail.js<|end_filename|> //advice_all.js angular .module('app', ['ngRoute']) .controller('reservationAddDetailControl', reservationAddDetailControl) reservationAddDetailControl.$inject = ['$scope', '$http', '$stateParams']; function reservationAddDetailControl($scope, $http, $stateParams) { $scope.table_id = $stateParams.table_id; $scope.seats = {}; $scope.seats.selected = "-1"; $scope.doReserve = function() { var data = { floor_id: $scope.table.floor.id, table_id: $scope.table.id, seat_id: $scope.seats.selected, arrive_at: $('#reserve_time').val() }; $http.post("/api/user/reservation/add", data).then(function(response) { if (response.data.success == false) { toastr.error(response.data.msg, '错误') } else { window.location.href = "/reserve/home#!/reservation/all" } }); }; var myDate = new Date(); myDate.setHours(22); myDate.setMinutes(30); $('#reserve_time').datetimepicker('update', new Date()); $('#reserve_time').datetimepicker('remove'); $('#reserve_time').datetimepicker({ format: "yyyy-mm-dd hh:ii", autoclose: true, startDate: new Date(), endDate: myDate, startView: 1, minuteStep: 30, pickerPosition: "bottom-right" }); $http.get("/api/table/" + $scope.table_id + "/detail") .then(function(response) { $scope.table = response.data; }); } <|start_filename|>public/reserve/js/controllers/main.js<|end_filename|> //main.js angular .module('app') .controller('mainControl', mainControl); //convert Hex to RGBA function convertHex(hex,opacity){ hex = hex.replace('#',''); r = parseInt(hex.substring(0,2), 16); g = parseInt(hex.substring(2,4), 16); b = parseInt(hex.substring(4,6), 16); result = 'rgba('+r+','+g+','+b+','+opacity/100+')'; return result; } mainControl.$inject = ['$scope', '$http']; function mainControl($scope, $http) { $http.get("/api/user/info") .then(function(response) { $scope.reservation = response.data.reservation; $scope.reservations_count = response.data.reservation.all_count; $scope.user_info = response.data.user_info; }); } <|start_filename|>public/reserve/js/controllers/reservation_all.js<|end_filename|> //advice_all.js angular .module('app') .controller('reservationAllControl', reservationAllControl) .filter('to_trusted', ['$sce', function($sce){ return function(text) { return $sce.trustAsHtml(text); }; }]); reservationAllControl.$inject = ['$scope', '$http']; function reservationAllControl($scope, $http) { $scope.status_color = ["#32CD32", "#000000", "#00BFFF", "#DC143C"]; $scope.generate_color = function(id) { return { "color" : $scope.status_color[id] }; }; $scope.generate_button = function(id) { return "<button type='button' class='btn btn-link' style='margin-top: -4px;' onclick='cancel_reservation("+id+")'>取消预约</button>"; }; $scope.render_page = function() { $http.get("/api/user/reservation/all") .then(function(response) { $scope.count = response.data.count; $scope.reservation_all = response.data.data; console.log($scope.reservation_all); setTimeout(function(){ $scope.DataTable = $("#all_table").DataTable({ "searching": true, language: { processing: "处理中", lengthMenu: "每页显示_MENU_条", search: "搜索:", info: "显示 _START_ 到 _END_ 条, 共 _TOTAL_ 条", infoEmpty: "显示 0 到 0 条, 共 0 条", loadingRecords: "正在加载...", zeroRecords: "没有预约", emptyTable: "没有预约", paginate: { first: "第一页", previous: "上一页", next: "下一页", last: "最后页" }, }, "ordering": false }); },0); }); } $scope.render_page(); } function cancel_reservation(id) { $.get("/api/user/reservation/cancel/"+id, function(result){ if (result.success == false) { toastr.error(result.msg, '错误') } else { window.location.reload(); } }); }
SE407-2017/FinalProject-library-seats-reservation
<|start_filename|>src/components/Header/Navbar.js<|end_filename|> import React, { useState, useEffect } from 'react' import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem, NavbarText, } from 'reactstrap' import './header.css' import logo1 from '../../assets/logo1.png' const IndexNavbar = (props) => { const [isOpen, setIsOpen] = useState(false) const toggle = () => setIsOpen(!isOpen) const deleteCred = () => { localStorage.removeItem('creds') window.location.assign('/') } var prevScrollpos = window.pageYOffset window.onscroll = function () { var currentScrollPos = window.pageYOffset if (prevScrollpos > currentScrollPos) { document.getElementById('navbar').style.top = '0' } else { document.getElementById('navbar').style.top = '-70px' } prevScrollpos = currentScrollPos } const creds = JSON.parse(localStorage.getItem('creds')) const [uu, setuu] = useState() // console.log(uu); const handle = '/profile/' + uu useEffect(() => { if (creds) { setuu(creds.username) } }, []) if (creds) { return ( <div> <Navbar id="navbar" color="dark" light expand="md" style={{ background: 'transparent !important', paddingRight: '3% ' }} > <NavbarBrand href="/" light> <img src={logo1} id="BrandLogo" /> CODEDIGGER </NavbarBrand> <NavbarToggler onClick={toggle} /> <Collapse isOpen={isOpen} navbar> <Nav className="ml-auto" navbar> <NavItem style={{ color: 'white' }}> <NavLink style={{ color: 'white' }} href="/problems"> Problems </NavLink> </NavItem> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Practice </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href="/topicwise/practice" > Topicwise </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/levelwise/practice" > Levelwise </NavLink> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Ladders </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href="/topicwise/ladder"> Topicwise </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/levelwise/ladder"> Levelwise </NavLink> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <NavItem style={{ color: 'white' }}> <NavLink style={{ color: 'white' }} href="/contest"> Contests </NavLink> </NavItem> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Upsolve </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href="/upsolve/codeforces" > Codeforces </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/upsolve/codechef"> Codechef </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/upsolve/atcoder"> Atcoder </NavLink> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> {/* <NavItem> <NavLink href="/profile">Hello, {creds.username}</NavLink> </NavItem> */} <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Hello, {creds.username} </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href={handle}> Profile </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/updateProfile"> Edit Profile </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href={`/change_password_request`} > Edit Password </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href={`/list/${uu}`}> Problem Lists </NavLink> </DropdownItem> <DropdownItem> <NavItem> <NavLink className="dropdown_link" onClick={deleteCred}> Log Out </NavLink> </NavItem> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> </Nav> </Collapse> </Navbar> </div> ) } else return ( <div> <Navbar id="navbar" color="dark" light expand="md" style={{ background: 'transparent !important', paddingLeft: '3%', paddingRight: '4% ', }} > <NavbarBrand href="/" light> <img src={logo1} id="BrandLogo" /> CODEDIGGER </NavbarBrand> <NavbarToggler onClick={toggle} /> <Collapse isOpen={isOpen} navbar> <Nav className="ml-auto" navbar> <NavItem style={{ color: 'white' }}> <NavLink style={{ color: 'white' }} href="/problems"> Problems </NavLink> </NavItem> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Practice </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href="/topicwise/practice" > Topicwise </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/levelwise/practice" > Levelwise </NavLink> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Ladders </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href="/topicwise/ladder"> Topicwise </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/levelwise/ladder"> Levelwise </NavLink> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret style={{ color: 'white' }}> Upsolve </DropdownToggle> <DropdownMenu left className="dropdown_background"> <DropdownItem> <NavLink className="dropdown_link" href="/upsolve/codeforces" > Codeforces </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/upsolve/codechef"> Codechef </NavLink> </DropdownItem> <DropdownItem> <NavLink className="dropdown_link" href="/upsolve/atcoder"> Atcoder </NavLink> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> {/* <NavItem> <NavLink href="/profile">Hello, {creds.username}</NavLink> </NavItem> */} <NavItem> <NavLink style={{ color: 'white' }} href="/login"> Login/Register </NavLink> </NavItem> </Nav> </Collapse> </Navbar> {/* <br/> <br/> <br/> */} </div> ) } export default IndexNavbar
santushtisharma10/Frontend
<|start_filename|>.serge-mapping.json<|end_filename|> { "@d2l/d2l-attachment": "@d2l/d2l-attachment/d2l-attachment.serge.json", "d2l-activities": "d2l-activities/activities.serge.json", "d2l-assessment-quality-dashboard": "d2l-assessment-quality-dashboard/insights-assessment-quality-dashboard.serge.json", "d2l-engagement-dashboard": "d2l-engagement-dashboard/insights-engagement-dashboard.serge.json", "@brightspace-hmc/foundation-components": "@brightspace-hmc/foundation-components/foundation-components.serge.json", "d2l-cpd": "d2l-cpd/continuous-professional-development.serge.json", "d2l-custom-early-progress-report": "d2l-custom-early-progress-report/custom-early-progress-report.serge.json", "d2l-copy-assignment-to-other-courses": "d2l-copy-assignment-to-other-courses/copy-assignment-to-other-courses.serge.json", "d2l-module-scheduler": "d2l-module-scheduler/module-scheduler.serge.json", "@brightspace-ui/htmleditor": "@brightspace-ui/htmleditor/htmleditor.serge.json", "d2l-consistent-evaluation": "d2l-consistent-evaluation/consistent-evaluation.serge.json", "d2l-sequences": "d2l-sequences/d2l-sequences.serge.json" }
Brightspace/brightspace-integration
<|start_filename|>BlazorBarcodeScanner.ZXing.JS/Exceptions/StartDecodingFailedException.cs<|end_filename|> using System; namespace BlazorBarcodeScanner.ZXing.JS.Exceptions { public class StartDecodingFailedException : Exception { public StartDecodingFailedException(string message, Exception e) : base(message, e) { } } } <|start_filename|>BlazorBarcodeScanner.ZXing.JS/JsInteropClass.cs<|end_filename|> using Microsoft.JSInterop; using System; using System.Linq; namespace BlazorBarcodeScanner.ZXing.JS { public class JsInteropClass { [JSInvokable] public static void ReceiveBarcode(string barcodeText) { /* Unfortunately JS is unable to invoke public methods of internal classes. Thus * we route the call to the internal class at this point. This allows us to hide away * the rest of the interop from the component's client. */ BarcodeReaderInterop.OnBarcodeReceived(barcodeText); } [JSInvokable] public static void ReceiveError(object error) { // What to do with the knowledge that an error happened? // Looking at current examples this might indicate issues with one of the decoders // (namely BrowserQRCodeReader appears to throw errors occasionally...) } [JSInvokable] public static void ReceiveNotFound() { BarcodeReaderInterop.OnNotFoundReceived(); } } } <|start_filename|>BlazorBarcodeScanner.ZXing.JS/DecodingChangedArgs.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlazorBarcodeScanner.ZXing.JS { public class DecodingChangedArgs { public BarcodeReader Sender; public bool IsDecoding; } }
fabiankuehne/BlazorBarcodeScanner
<|start_filename|>OCDemo/MyThemes.h<|end_filename|> // // MyThemes.h // SwiftTheme // // Created by Gesen on 16/5/26. // Copyright © 2016年 Gesen. All rights reserved. // #import <Foundation/Foundation.h> typedef enum { MyThemesTypeRed = 0, MyThemesTypeYellow, MyThemesTypeBlue, MyThemesTypeNight } MyThemesType; @interface MyThemes : NSObject + (void)switchTo:(MyThemesType)type; + (void)switchToNext; + (void)switchNight:(BOOL)isToNight; + (BOOL)isNight; + (void)restoreLastTheme; + (void)saveLastTheme; @end <|start_filename|>SwiftTheme/SwiftTheme.h<|end_filename|> // // SwiftTheme.h // SwiftTheme // // Created by Gesen on 16/1/23. // Copyright © 2016年 Gesen. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for SwiftTheme. FOUNDATION_EXPORT double SwiftThemeVersionNumber; //! Project version string for SwiftTheme. FOUNDATION_EXPORT const unsigned char SwiftThemeVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftTheme/PublicHeader.h> <|start_filename|>OCDemo/SelectThemeCell.h<|end_filename|> // // SelectThemeCell.h // SwiftTheme // // Created by Gesen on 16/5/27. // Copyright © 2016年 Gesen. All rights reserved. // #import "BaseCell.h" @interface SelectThemeCell : BaseCell @property (nonatomic, weak) IBOutlet UILabel *title; @property (nonatomic, weak) IBOutlet UIImageView *themeIcon; @end <|start_filename|>OCDemo/AppDelegate.h<|end_filename|> // // AppDelegate.h // OCDemo // // Created by Gesen on 16/5/26. // Copyright © 2016年 Gesen. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end <|start_filename|>OCDemo/ChangeThemeCell.h<|end_filename|> // // ChangeThemeCell.h // SwiftTheme // // Created by Gesen on 16/5/27. // Copyright © 2016年 Gesen. All rights reserved. // #import "BaseCell.h" @interface ChangeThemeCell : BaseCell @property (nonatomic, weak) IBOutlet UIButton *changeTheme; @end <|start_filename|>Pods/Headers/Private/SSZipArchive/prng.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/aes/prng.h <|start_filename|>OCDemo/ListViewController.h<|end_filename|> // // ListViewController.h // SwiftTheme // // Created by Gesen on 16/5/26. // Copyright © 2016年 Gesen. All rights reserved. // #import <UIKit/UIKit.h> @interface ListViewController : UITableViewController @end <|start_filename|>SwiftTheme-tvOS/SwiftTheme_tvOS.h<|end_filename|> // // SwiftTheme_tvOS.h // SwiftTheme-tvOS // // Created by GeSen on 2017/10/8. // Copyright © 2017年 Gesen. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for SwiftTheme_tvOS. FOUNDATION_EXPORT double SwiftTheme_tvOSVersionNumber; //! Project version string for SwiftTheme_tvOS. FOUNDATION_EXPORT const unsigned char SwiftTheme_tvOSVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftTheme_tvOS/PublicHeader.h> <|start_filename|>Pods/SSZipArchive/SSZipArchive/minizip/ioapi_buf.c<|end_filename|> /* ioapi_buf.c -- IO base function header for compress/uncompress .zip files using zlib + zip or unzip API This version of ioapi is designed to buffer IO. Copyright (C) 2012-2017 <NAME> https://github.com/nmoinvaz/minizip This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "zlib.h" #include "ioapi.h" #include "ioapi_buf.h" #ifndef IOBUF_BUFFERSIZE # define IOBUF_BUFFERSIZE (UINT16_MAX) #endif #if defined(_WIN32) # include <conio.h> # define PRINTF _cprintf # define VPRINTF _vcprintf #else # define PRINTF printf # define VPRINTF vprintf #endif //#define IOBUF_VERBOSE #ifdef __GNUC__ #ifndef max #define max(x,y) ({ \ const typeof(x) _x = (x); \ const typeof(y) _y = (y); \ (void) (&_x == &_y); \ _x > _y ? _x : _y; }) #endif /* __GNUC__ */ #ifndef min #define min(x,y) ({ \ const typeof(x) _x = (x); \ const typeof(y) _y = (y); \ (void) (&_x == &_y); \ _x < _y ? _x : _y; }) #endif #endif typedef struct ourstream_s { char readbuf[IOBUF_BUFFERSIZE]; uint32_t readbuf_len; uint32_t readbuf_pos; uint32_t readbuf_hits; uint32_t readbuf_misses; char writebuf[IOBUF_BUFFERSIZE]; uint32_t writebuf_len; uint32_t writebuf_pos; uint32_t writebuf_hits; uint32_t writebuf_misses; uint64_t position; voidpf stream; } ourstream_t; #if defined(IOBUF_VERBOSE) # define print_buf(o,s,f,...) print_buf_internal(o,s,f,__VA_ARGS__); #else # define print_buf(o,s,f,...) #endif void print_buf_internal(voidpf opaque, voidpf stream, char *format, ...) { ourstream_t *streamio = (ourstream_t *)stream; va_list arglist; PRINTF("Buf stream %p - ", streamio); va_start(arglist, format); VPRINTF(format, arglist); va_end(arglist); } voidpf fopen_buf_internal_func(voidpf opaque, voidpf stream, uint32_t number_disk, int mode) { ourstream_t *streamio = NULL; if (stream == NULL) return NULL; streamio = (ourstream_t *)malloc(sizeof(ourstream_t)); if (streamio == NULL) return NULL; memset(streamio, 0, sizeof(ourstream_t)); streamio->stream = stream; print_buf(opaque, streamio, "open [num %d mode %d]\n", number_disk, mode); return streamio; } voidpf ZCALLBACK fopen_buf_func(voidpf opaque, const char *filename, int mode) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; voidpf stream = bufio->filefunc.zopen_file(bufio->filefunc.opaque, filename, mode); return fopen_buf_internal_func(opaque, stream, 0, mode); } voidpf ZCALLBACK fopen64_buf_func(voidpf opaque, const void *filename, int mode) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; voidpf stream = bufio->filefunc64.zopen64_file(bufio->filefunc64.opaque, filename, mode); return fopen_buf_internal_func(opaque, stream, 0, mode); } voidpf ZCALLBACK fopendisk_buf_func(voidpf opaque, voidpf stream_cd, uint32_t number_disk, int mode) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream_cd; voidpf *stream = bufio->filefunc.zopendisk_file(bufio->filefunc.opaque, streamio->stream, number_disk, mode); return fopen_buf_internal_func(opaque, stream, number_disk, mode); } voidpf ZCALLBACK fopendisk64_buf_func(voidpf opaque, voidpf stream_cd, uint32_t number_disk, int mode) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream_cd; voidpf stream = bufio->filefunc64.zopendisk64_file(bufio->filefunc64.opaque, streamio->stream, number_disk, mode); return fopen_buf_internal_func(opaque, stream, number_disk, mode); } long fflush_buf(voidpf opaque, voidpf stream) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; uint32_t total_bytes_to_write = 0; uint32_t bytes_to_write = streamio->writebuf_len; uint32_t bytes_left_to_write = streamio->writebuf_len; long bytes_written = 0; while (bytes_left_to_write > 0) { if (bufio->filefunc64.zwrite_file != NULL) bytes_written = bufio->filefunc64.zwrite_file(bufio->filefunc64.opaque, streamio->stream, streamio->writebuf + (bytes_to_write - bytes_left_to_write), bytes_left_to_write); else bytes_written = bufio->filefunc.zwrite_file(bufio->filefunc.opaque, streamio->stream, streamio->writebuf + (bytes_to_write - bytes_left_to_write), bytes_left_to_write); streamio->writebuf_misses += 1; print_buf(opaque, stream, "write flush [%d:%d len %d]\n", bytes_to_write, bytes_left_to_write, streamio->writebuf_len); if (bytes_written < 0) return bytes_written; total_bytes_to_write += bytes_written; bytes_left_to_write -= bytes_written; streamio->position += bytes_written; } streamio->writebuf_len = 0; streamio->writebuf_pos = 0; return total_bytes_to_write; } uint32_t ZCALLBACK fread_buf_func(voidpf opaque, voidpf stream, void *buf, uint32_t size) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; uint32_t buf_len = 0; uint32_t bytes_to_read = 0; uint32_t bytes_to_copy = 0; uint32_t bytes_left_to_read = size; uint32_t bytes_read = 0; print_buf(opaque, stream, "read [size %ld pos %lld]\n", size, streamio->position); if (streamio->writebuf_len > 0) { print_buf(opaque, stream, "switch from write to read, not yet supported [%lld]\n", streamio->position); } while (bytes_left_to_read > 0) { if ((streamio->readbuf_len == 0) || (streamio->readbuf_pos == streamio->readbuf_len)) { if (streamio->readbuf_len == IOBUF_BUFFERSIZE) { streamio->readbuf_pos = 0; streamio->readbuf_len = 0; } bytes_to_read = IOBUF_BUFFERSIZE - (streamio->readbuf_len - streamio->readbuf_pos); if (bufio->filefunc64.zread_file != NULL) bytes_read = bufio->filefunc64.zread_file(bufio->filefunc64.opaque, streamio->stream, streamio->readbuf + streamio->readbuf_pos, bytes_to_read); else bytes_read = bufio->filefunc.zread_file(bufio->filefunc.opaque, streamio->stream, streamio->readbuf + streamio->readbuf_pos, bytes_to_read); streamio->readbuf_misses += 1; streamio->readbuf_len += bytes_read; streamio->position += bytes_read; print_buf(opaque, stream, "filled [read %d/%d buf %d:%d pos %lld]\n", bytes_read, bytes_to_read, streamio->readbuf_pos, streamio->readbuf_len, streamio->position); if (bytes_read == 0) break; } if ((streamio->readbuf_len - streamio->readbuf_pos) > 0) { bytes_to_copy = min(bytes_left_to_read, (uint32_t)(streamio->readbuf_len - streamio->readbuf_pos)); memcpy((char *)buf + buf_len, streamio->readbuf + streamio->readbuf_pos, bytes_to_copy); buf_len += bytes_to_copy; bytes_left_to_read -= bytes_to_copy; streamio->readbuf_hits += 1; streamio->readbuf_pos += bytes_to_copy; print_buf(opaque, stream, "emptied [copied %d remaining %d buf %d:%d pos %lld]\n", bytes_to_copy, bytes_left_to_read, streamio->readbuf_pos, streamio->readbuf_len, streamio->position); } } return size - bytes_left_to_read; } uint32_t ZCALLBACK fwrite_buf_func(voidpf opaque, voidpf stream, const void *buf, uint32_t size) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; uint32_t bytes_to_write = size; uint32_t bytes_left_to_write = size; uint32_t bytes_to_copy = 0; int64_t ret = 0; print_buf(opaque, stream, "write [size %ld len %d pos %lld]\n", size, streamio->writebuf_len, streamio->position); if (streamio->readbuf_len > 0) { streamio->position -= streamio->readbuf_len; streamio->position += streamio->readbuf_pos; streamio->readbuf_len = 0; streamio->readbuf_pos = 0; print_buf(opaque, stream, "switch from read to write [%lld]\n", streamio->position); if (bufio->filefunc64.zseek64_file != NULL) ret = bufio->filefunc64.zseek64_file(bufio->filefunc64.opaque, streamio->stream, streamio->position, ZLIB_FILEFUNC_SEEK_SET); else ret = bufio->filefunc.zseek_file(bufio->filefunc.opaque, streamio->stream, (uint32_t)streamio->position, ZLIB_FILEFUNC_SEEK_SET); if (ret != 0) return (uint32_t)-1; } while (bytes_left_to_write > 0) { bytes_to_copy = min(bytes_left_to_write, (uint32_t)(IOBUF_BUFFERSIZE - min(streamio->writebuf_len, streamio->writebuf_pos))); if (bytes_to_copy == 0) { if (fflush_buf(opaque, stream) <= 0) return 0; continue; } memcpy(streamio->writebuf + streamio->writebuf_pos, (char *)buf + (bytes_to_write - bytes_left_to_write), bytes_to_copy); print_buf(opaque, stream, "write copy [remaining %d write %d:%d len %d]\n", bytes_to_copy, bytes_to_write, bytes_left_to_write, streamio->writebuf_len); bytes_left_to_write -= bytes_to_copy; streamio->writebuf_pos += bytes_to_copy; streamio->writebuf_hits += 1; if (streamio->writebuf_pos > streamio->writebuf_len) streamio->writebuf_len += streamio->writebuf_pos - streamio->writebuf_len; } return size - bytes_left_to_write; } uint64_t ftell_buf_internal_func(voidpf opaque, voidpf stream, uint64_t position) { ourstream_t *streamio = (ourstream_t *)stream; streamio->position = position; print_buf(opaque, stream, "tell [pos %llu readpos %d writepos %d err %d]\n", streamio->position, streamio->readbuf_pos, streamio->writebuf_pos, errno); if (streamio->readbuf_len > 0) position -= (streamio->readbuf_len - streamio->readbuf_pos); if (streamio->writebuf_len > 0) position += streamio->writebuf_pos; return position; } long ZCALLBACK ftell_buf_func(voidpf opaque, voidpf stream) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; uint64_t position = bufio->filefunc.ztell_file(bufio->filefunc.opaque, streamio->stream); return (long)ftell_buf_internal_func(opaque, stream, position); } uint64_t ZCALLBACK ftell64_buf_func(voidpf opaque, voidpf stream) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; uint64_t position = bufio->filefunc64.ztell64_file(bufio->filefunc64.opaque, streamio->stream); return ftell_buf_internal_func(opaque, stream, position); } int fseek_buf_internal_func(voidpf opaque, voidpf stream, uint64_t offset, int origin) { ourstream_t *streamio = (ourstream_t *)stream; print_buf(opaque, stream, "seek [origin %d offset %llu pos %lld]\n", origin, offset, streamio->position); switch (origin) { case ZLIB_FILEFUNC_SEEK_SET: if (streamio->writebuf_len > 0) { if ((offset >= streamio->position) && (offset <= streamio->position + streamio->writebuf_len)) { streamio->writebuf_pos = (uint32_t)(offset - streamio->position); return 0; } } if ((streamio->readbuf_len > 0) && (offset < streamio->position) && (offset >= streamio->position - streamio->readbuf_len)) { streamio->readbuf_pos = (uint32_t)(offset - (streamio->position - streamio->readbuf_len)); return 0; } if (fflush_buf(opaque, stream) < 0) return -1; streamio->position = offset; break; case ZLIB_FILEFUNC_SEEK_CUR: if (streamio->readbuf_len > 0) { if (offset <= (streamio->readbuf_len - streamio->readbuf_pos)) { streamio->readbuf_pos += (uint32_t)offset; return 0; } offset -= (streamio->readbuf_len - streamio->readbuf_pos); streamio->position += offset; } if (streamio->writebuf_len > 0) { if (offset <= (streamio->writebuf_len - streamio->writebuf_pos)) { streamio->writebuf_pos += (uint32_t)offset; return 0; } //offset -= (streamio->writebuf_len - streamio->writebuf_pos); } if (fflush_buf(opaque, stream) < 0) return -1; break; case ZLIB_FILEFUNC_SEEK_END: if (streamio->writebuf_len > 0) { streamio->writebuf_pos = streamio->writebuf_len; return 0; } break; } streamio->readbuf_len = 0; streamio->readbuf_pos = 0; streamio->writebuf_len = 0; streamio->writebuf_pos = 0; return 1; } long ZCALLBACK fseek_buf_func(voidpf opaque, voidpf stream, uint32_t offset, int origin) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; long ret = -1; if (bufio->filefunc.zseek_file == NULL) return ret; ret = fseek_buf_internal_func(opaque, stream, offset, origin); if (ret == 1) ret = bufio->filefunc.zseek_file(bufio->filefunc.opaque, streamio->stream, offset, origin); return ret; } long ZCALLBACK fseek64_buf_func(voidpf opaque, voidpf stream, uint64_t offset, int origin) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; long ret = -1; if (bufio->filefunc64.zseek64_file == NULL) return ret; ret = fseek_buf_internal_func(opaque, stream, offset, origin); if (ret == 1) ret = bufio->filefunc64.zseek64_file(bufio->filefunc64.opaque, streamio->stream, offset, origin); return ret; } int ZCALLBACK fclose_buf_func(voidpf opaque, voidpf stream) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; int ret = 0; fflush_buf(opaque, stream); print_buf(opaque, stream, "close\n"); if (streamio->readbuf_hits + streamio->readbuf_misses > 0) print_buf(opaque, stream, "read efficency %.02f%%\n", (streamio->readbuf_hits / ((float)streamio->readbuf_hits + streamio->readbuf_misses)) * 100); if (streamio->writebuf_hits + streamio->writebuf_misses > 0) print_buf(opaque, stream, "write efficency %.02f%%\n", (streamio->writebuf_hits / ((float)streamio->writebuf_hits + streamio->writebuf_misses)) * 100); if (bufio->filefunc64.zclose_file != NULL) ret = bufio->filefunc64.zclose_file(bufio->filefunc64.opaque, streamio->stream); else ret = bufio->filefunc.zclose_file(bufio->filefunc.opaque, streamio->stream); free(streamio); return ret; } int ZCALLBACK ferror_buf_func(voidpf opaque, voidpf stream) { ourbuffer_t *bufio = (ourbuffer_t *)opaque; ourstream_t *streamio = (ourstream_t *)stream; if (bufio->filefunc64.zerror_file != NULL) return bufio->filefunc64.zerror_file(bufio->filefunc64.opaque, streamio->stream); return bufio->filefunc.zerror_file(bufio->filefunc.opaque, streamio->stream); } void fill_buffer_filefunc(zlib_filefunc_def *pzlib_filefunc_def, ourbuffer_t *ourbuf) { pzlib_filefunc_def->zopen_file = fopen_buf_func; pzlib_filefunc_def->zopendisk_file = fopendisk_buf_func; pzlib_filefunc_def->zread_file = fread_buf_func; pzlib_filefunc_def->zwrite_file = fwrite_buf_func; pzlib_filefunc_def->ztell_file = ftell_buf_func; pzlib_filefunc_def->zseek_file = fseek_buf_func; pzlib_filefunc_def->zclose_file = fclose_buf_func; pzlib_filefunc_def->zerror_file = ferror_buf_func; pzlib_filefunc_def->opaque = ourbuf; } void fill_buffer_filefunc64(zlib_filefunc64_def *pzlib_filefunc_def, ourbuffer_t *ourbuf) { pzlib_filefunc_def->zopen64_file = fopen64_buf_func; pzlib_filefunc_def->zopendisk64_file = fopendisk64_buf_func; pzlib_filefunc_def->zread_file = fread_buf_func; pzlib_filefunc_def->zwrite_file = fwrite_buf_func; pzlib_filefunc_def->ztell64_file = ftell64_buf_func; pzlib_filefunc_def->zseek64_file = fseek64_buf_func; pzlib_filefunc_def->zclose_file = fclose_buf_func; pzlib_filefunc_def->zerror_file = ferror_buf_func; pzlib_filefunc_def->opaque = ourbuf; } <|start_filename|>OCDemo/SelectThemeViewController.h<|end_filename|> // // SelectThemeViewController.h // SwiftTheme // // Created by Gesen on 16/5/27. // Copyright © 2016年 Gesen. All rights reserved. // #import <UIKit/UIKit.h> @interface SelectThemeViewController : UIViewController @end <|start_filename|>OCDemo/Global.h<|end_filename|> // // Global.h // SwiftTheme // // Created by Gesen on 16/5/26. // Copyright © 2016年 Gesen. All rights reserved. // #define globalStatusBarStringStyles @[@"LightContent", @"Default", @"LightContent", @"LightContent"] #define globalBackgroundColorPicker [ThemeColorPicker pickerWithColors:@[@"#fff", @"#fff", @"#fff", @"#292b38"]] #define globalTextColorPicker [ThemeColorPicker pickerWithColors:@[@"#000", @"#000", @"#000", @"#ECF0F1"]] #define globalBarTextColors @[@"#FFF", @"#000", @"#FFF", @"#FFF"] #define globalBarTextColorPicker [ThemeColorPicker pickerWithColors:globalBarTextColors] #define globalBarTintColorPicker [ThemeColorPicker pickerWithColors: @[@"#EB4F38", @"#F4C600", @"#56ABE4", @"#01040D"]] <|start_filename|>Pods/Headers/Private/SSZipArchive/aestab.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/aes/aestab.h <|start_filename|>Pods/Headers/Private/SSZipArchive/pwd2key.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/aes/pwd2key.h <|start_filename|>Pods/Headers/Private/SSZipArchive/minishared.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/minishared.h <|start_filename|>OCDemo/AboutCell.h<|end_filename|> // // AboutCell.h // SwiftTheme // // Created by Gesen on 16/5/26. // Copyright © 2016年 Gesen. All rights reserved. // #import "BaseCell.h" @interface AboutCell : BaseCell @property (nonatomic, weak) IBOutlet UILabel *content; @end <|start_filename|>Pods/Headers/Private/SSZipArchive/ioapi_mem.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/ioapi_mem.h <|start_filename|>Pods/Headers/Private/SSZipArchive/brg_types.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/aes/brg_types.h <|start_filename|>Pods/Headers/Private/SSZipArchive/ioapi_buf.h<|end_filename|> ../../../SSZipArchive/SSZipArchive/minizip/ioapi_buf.h <|start_filename|>OCDemo/SwitchNightCell.h<|end_filename|> // // SwitchNightCell.h // SwiftTheme // // Created by Gesen on 16/5/27. // Copyright © 2016年 Gesen. All rights reserved. // #import "BaseCell.h" @interface SwitchNightCell : BaseCell @property (nonatomic, weak) IBOutlet UILabel *title; @property (nonatomic, weak) IBOutlet UIImageView *nightIcon; @property (nonatomic, weak) IBOutlet UISwitch *nightSwitch; @end
sendyhalim/SwiftTheme
<|start_filename|>tests/test-server/sample_responses/github_list_prs.json<|end_filename|> { "total_count": 1, "incomplete_results": false, "items": [ { "url": "https://api.github.com/repos/timnlupo/juypterlabpr-test/issues/1", "repository_url": "https://api.github.com/repos/timnlupo/juypterlabpr-test", "labels_url": "https://api.github.com/repos/timnlupo/juypterlabpr-test/issues/1/labels{/name}", "comments_url": "https://api.github.com/repos/timnlupo/juypterlabpr-test/issues/1/comments", "events_url": "https://api.github.com/repos/timnlupo/juypterlabpr-test/issues/1/events", "html_url": "https://github.com/timnlupo/juypterlabpr-test/pull/1", "id": 457075994, "node_id": "MDExOlB1bGxSZXF1ZXN0Mjg4OTYxNDU4", "number": 1, "title": "Interesting PR for feature", "user": { "login": "timnlupo", "id": 9003282, "node_id": "MDQ6VXNlcjkwMDMyODI=", "avatar_url": "https://avatars1.githubusercontent.com/u/9003282?v=4", "gravatar_id": "", "url": "https://api.github.com/users/timnlupo", "html_url": "https://github.com/timnlupo", "followers_url": "https://api.github.com/users/timnlupo/followers", "following_url": "https://api.github.com/users/timnlupo/following{/other_user}", "gists_url": "https://api.github.com/users/timnlupo/gists{/gist_id}", "starred_url": "https://api.github.com/users/timnlupo/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/timnlupo/subscriptions", "organizations_url": "https://api.github.com/users/timnlupo/orgs", "repos_url": "https://api.github.com/users/timnlupo/repos", "events_url": "https://api.github.com/users/timnlupo/events{/privacy}", "received_events_url": "https://api.github.com/users/timnlupo/received_events", "type": "User", "site_admin": false }, "labels": [], "state": "open", "locked": false, "assignee": null, "assignees": [], "milestone": null, "comments": 0, "created_at": "2019-06-17T18:02:42Z", "updated_at": "2019-06-21T21:51:17Z", "closed_at": null, "author_association": "OWNER", "pull_request": { "url": "https://api.github.com/repos/timnlupo/juypterlabpr-test/pulls/1", "html_url": "https://github.com/timnlupo/juypterlabpr-test/pull/1", "diff_url": "https://github.com/timnlupo/juypterlabpr-test/pull/1.diff", "patch_url": "https://github.com/timnlupo/juypterlabpr-test/pull/1.patch" }, "body": "This is a feature that tests a bunch of different types", "score": 1 } ] } <|start_filename|>tests/test-server/sample_responses/github_current_user.json<|end_filename|> { "login":"timnlupo", "id":9003282, "node_id":"MDQ6VXNlcjkwMDMyODI=", "avatar_url":"https://avatars1.githubusercontent.com/u/9003282?v=4", "gravatar_id":"", "url":"https://api.github.com/users/timnlupo", "html_url":"https://github.com/timnlupo", "followers_url":"https://api.github.com/users/timnlupo/followers", "following_url":"https://api.github.com/users/timnlupo/following{/other_user}", "gists_url":"https://api.github.com/users/timnlupo/gists{/gist_id}", "starred_url":"https://api.github.com/users/timnlupo/starred{/owner}{/repo}", "subscriptions_url":"https://api.github.com/users/timnlupo/subscriptions", "organizations_url":"https://api.github.com/users/timnlupo/orgs", "repos_url":"https://api.github.com/users/timnlupo/repos", "events_url":"https://api.github.com/users/timnlupo/events{/privacy}", "received_events_url":"https://api.github.com/users/timnlupo/received_events", "type":"User", "site_admin":false, "name":"<NAME>", "company":"@amazon", "blog":"http://timlupo.com", "location":"Los Angeles, CA", "email":"<EMAIL>", "hireable":null, "bio":null, "public_repos":10, "public_gists":0, "followers":24, "following":14, "created_at":"2014-10-03T00:35:16Z", "updated_at":"2019-06-18T16:15:26Z" } <|start_filename|>tests/test-server/sample_responses/github_comments_post.json<|end_filename|> { "url":"https://api.github.com/repos/timnlupo/juypterlabpr-test/pulls/comments/299659626", "pull_request_review_id":257117322, "id":299659626, "node_id":"MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDI5OTY1OTYyNg==", "diff_hunk":"@@ -25,6 +25,33 @@\n \"print('hi')\\n\",\n \"print(1+1)\"\n ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"## Some information\\n\",", "path":"test.ipynb", "position":9, "original_position":9, "commit_id":"02fb374e022fbe7aaa4cd69c0dc3928e6422dfaa", "original_commit_id":"02fb374e022fbe7aaa4cd69c0dc3928e6422dfaa", "user":{ "login":"timnlupo", "id":9003282, "node_id":"MDQ6VXNlcjkwMDMyODI=", "avatar_url":"https://avatars1.githubusercontent.com/u/9003282?v=4", "gravatar_id":"", "url":"https://api.github.com/users/timnlupo", "html_url":"https://github.com/timnlupo", "followers_url":"https://api.github.com/users/timnlupo/followers", "following_url":"https://api.github.com/users/timnlupo/following{/other_user}", "gists_url":"https://api.github.com/users/timnlupo/gists{/gist_id}", "starred_url":"https://api.github.com/users/timnlupo/starred{/owner}{/repo}", "subscriptions_url":"https://api.github.com/users/timnlupo/subscriptions", "organizations_url":"https://api.github.com/users/timnlupo/orgs", "repos_url":"https://api.github.com/users/timnlupo/repos", "events_url":"https://api.github.com/users/timnlupo/events{/privacy}", "received_events_url":"https://api.github.com/users/timnlupo/received_events", "type":"User", "site_admin":false }, "body":"test", "created_at":"2019-07-02T19:58:38Z", "updated_at":"2019-07-02T19:58:38Z", "html_url":"https://github.com/timnlupo/juypterlabpr-test/pull/1#discussion_r299659626", "pull_request_url":"https://api.github.com/repos/timnlupo/juypterlabpr-test/pulls/1", "author_association":"OWNER", "_links":{ "self":{ "href":"https://api.github.com/repos/timnlupo/juypterlabpr-test/pulls/comments/299659626" }, "html":{ "href":"https://github.com/timnlupo/juypterlabpr-test/pull/1#discussion_r299659626" }, "pull_request":{ "href":"https://api.github.com/repos/timnlupo/juypterlabpr-test/pulls/1" } }, "in_reply_to_id":296364299 }
timnlupo/pull-requests
<|start_filename|>client_test.go<|end_filename|> package jpush import ( "context" "strconv" "testing" . "github.com/smartystreets/goconvey/convey" ) const ( appKey = "<KEY>" masterSecret = "ed431429270144d3ed53555b" ) func TestPush(t *testing.T) { Convey("test client push", t, func() { cli := NewClient(2, SetAppKey(appKey), SetMasterSecret(masterSecret), SetCIDCount(2), ) pushID, err := cli.GetPushID(context.Background()) So(err, ShouldBeNil) So(pushID, ShouldNotBeEmpty) payload := &Payload{ Platform: NewPlatform().All(), Audience: NewAudience().All(), Notification: &Notification{ Alert: "推送通知测试", }, Options: &Options{ SendNO: 1, }, CID: pushID, } err = cli.Push(context.Background(), payload, func(ctx context.Context, result *PushResult, err error) { Convey("async callback", t, func() { So(err, ShouldBeNil) So(result, ShouldNotBeNil) So(result.SendNO, ShouldEqual, strconv.Itoa(payload.Options.SendNO)) }) }) So(err, ShouldBeNil) cli.Terminate() }) } func TestPushValidate(t *testing.T) { Convey("test client push validate", t, func() { cli := NewClient(2, SetAppKey(appKey), SetMasterSecret(masterSecret), SetCIDCount(2), ) payload := &Payload{ Platform: NewPlatform().All(), Audience: NewAudience().All(), Notification: &Notification{ Alert: "推送通知测试2", }, Options: &Options{ SendNO: 2, }, } err := cli.PushValidate(context.Background(), payload, func(ctx context.Context, result *PushResult, err error) { Convey("async callback", t, func() { So(err, ShouldBeNil) So(result, ShouldNotBeNil) So(result.SendNO, ShouldEqual, strconv.Itoa(payload.Options.SendNO)) }) }) So(err, ShouldBeNil) cli.Terminate() }) } <|start_filename|>request.go<|end_filename|> package jpush import ( "context" "encoding/json" "io" "strconv" "github.com/LyricTian/req" ) // Error 错误 type Error struct { StatusCode int `json:"status_code"` ErrorItem *ErrorItem `json:"error,omitempty"` HeaderItem *HeaderItem `json:"header,omitempty"` } func (e *Error) Error() string { buf, _ := json.MarshalIndent(e, "", " ") return string(buf) } // NewErrorItem 创建错误项实例 func NewErrorItem(code int, message string) *ErrorItem { return &ErrorItem{ Code: code, Message: message, } } // ErrorItem 错误项 type ErrorItem struct { Code int `json:"code"` Message string `json:"message"` } // HeaderItem 响应头 type HeaderItem struct { XRateLimitQuota int `json:"X-Rate-Limit-Quota"` XRateLimitRemaining int `json:"X-Rate-Limit-Remaining"` XRateLimitReset int `json:"X-Rate-Limit-Reset"` } // jpush request func pushRequest(ctx context.Context, opts *options, router, method string, body io.Reader) (req.Responser, error) { urlStr := req.RequestURL(opts.host, router) resp, err := req.Do(ctx, urlStr, method, body, req.SetBasicAuth(opts.appKey, opts.masterSecret)) if err != nil { return nil, err } else if code := resp.StatusCode(); code != 200 { e := &Error{ StatusCode: code, } var result struct { Error *ErrorItem `json:"error"` } buf, err := resp.Bytes() if err != nil { e.ErrorItem = NewErrorItem(0, err.Error()) return nil, e } err = json.Unmarshal(buf, &result) if err != nil { e.ErrorItem = NewErrorItem(0, string(buf)) return nil, e } e.ErrorItem = result.Error if code == 429 { header := new(HeaderItem) header.XRateLimitQuota, _ = strconv.Atoi(resp.Response().Header.Get("X-Rate-Limit-Quota")) header.XRateLimitRemaining, _ = strconv.Atoi(resp.Response().Header.Get("X-Rate-Limit-Remaining")) header.XRateLimitReset, _ = strconv.Atoi(resp.Response().Header.Get("X-Rate-Limit-Reset")) e.HeaderItem = header } return nil, e } return resp, nil } <|start_filename|>job.go<|end_filename|> package jpush import ( "context" "net/http" "strings" "time" "github.com/LyricTian/queue" ) func newPushJob(opts *options, queue queue.Queuer, cidClient *CIDClient) *pushJob { return &pushJob{ opts: opts, queue: queue, cidClient: cidClient, } } type pushJob struct { opts *options queue queue.Queuer cidClient *CIDClient payload *Payload ctx context.Context callback PushResultHandle } func (j *pushJob) Reset(ctx context.Context, payload *Payload, callback PushResultHandle) { j.payload = payload j.ctx = ctx j.callback = callback } func (j *pushJob) handleError(err error) { if err == nil { return } if e, ok := err.(*Error); ok { if e.StatusCode == 429 || e.StatusCode == 404 { j.queue.Push(j) // 如果当前推送频次超出限制,则将任务重新放入队列,并休眠等待 if e.HeaderItem != nil && e.HeaderItem.XRateLimitReset > 0 { time.Sleep(time.Second * time.Duration(e.HeaderItem.XRateLimitReset)) } return } j.callback(j.ctx, nil, err) } else { if v := err.Error(); strings.Contains(v, "connection refused") { j.queue.Push(j) return } j.callback(j.ctx, nil, err) } } func (j *pushJob) Job() { if j.payload.CID == "" { cid, err := j.cidClient.GetPushID(j.ctx) if err != nil { j.handleError(err) return } j.payload.CID = cid } resp, err := pushRequest(j.ctx, j.opts, "/v3/push", http.MethodPost, j.payload.Reader()) if err != nil { j.handleError(err) return } result := new(PushResult) err = resp.JSON(result) if err != nil { j.callback(j.ctx, nil, err) return } j.callback(j.ctx, result, nil) }
ib1ack/jpush-go
<|start_filename|>src/config_map.h<|end_filename|> #ifndef __CONFIG_MAP__ #define __CONFIG_MAP__ // // Virtual EEPROM addresses & defaults for config variables. // Emulator uses append-only log & multiphase commits to guarantee // atomic writes. // // Current sensor shunt resistance (mOhm) #define CFG_SHUNT_RESISTANCE_ADDR 1 #define CFG_SHUNT_RESISTANCE_DEFAULT 10.0f // RPM at max voltage without load #define CFG_RPM_MAX_ADDR 2 #define CFG_RPM_MAX_DEFAULT 37500.0f // Minimal allowed speed (RPM) #define CFG_RPM_MIN_LIMIT_ADDR 3 #define CFG_RPM_MIN_LIMIT_DEFAULT 5000.0f // Maximal allowed speed (RPM) #define CFG_RPM_MAX_LIMIT_ADDR 4 #define CFG_RPM_MAX_LIMIT_DEFAULT 30000.0f // Knob initial zone where motor should not run (% of max range). #define CFG_DEAD_ZONE_WIDTH_ADDR 5 #define CFG_DEAD_ZONE_WIDTH_DEFAULT 2.0f // ADRC parameters (auto-calibrated). #define CFG_ADRC_KP_ADDR 6 #define CFG_ADRC_KP_DEFAULT 1.0f #define CFG_ADRC_KOBSERVERS_ADDR 7 #define CFG_ADRC_KOBSERVERS_DEFAULT 1.0f #define CFG_ADRC_P_CORR_COEFF_ADDR 8 #define CFG_ADRC_P_CORR_COEFF_DEFAULT 0.0f // Constructive coefficient between normalized motor speed. // and back-EMF equivalent resistance (auto-calibrated). #define CFG_REKV_TO_SPEED_FACTOR_ADDR 9 #define CFG_REKV_TO_SPEED_FACTOR_DEFAULT 450.0f // Active resistance interpolaion table (depends on triac phase). #define CFG_R_INTERP_TABLE_START_ADDR 10 #define CFG_R_INTERP_TABLE_LENGTH 7 #endif <|start_filename|>src/app.h<|end_filename|> #ifndef __APP_H__ #define __APP_H__ #include <stdint.h> float eeprom_float_read(uint32_t addr, float dflt); void eeprom_float_write(uint32_t addr, float val); #include "io.h" extern Io io; #include "meter.h" extern Meter meter; #include "regulator_adrc.h" extern Regulator regulator; #endif <|start_filename|>src/calibrator/calibrator_noise.h<|end_filename|> #ifndef __CALIBRATOR_NOISE__ #define __CALIBRATOR_NOISE__ // Calibrate noise & OP offset #include "../math/fix16_math.h" #include "../yield.h" #include "../app.h" class CalibratorNoise { public: bool tick(io_data_t &io_data) { YIELDABLE; io.setpoint = 0; YIELD_UNTIL(io_data.zero_cross_up, false); acc_counter = 0; acc_p_sum_2e64 = 0; acc_i2_sum_2e64 = 0; acc_i_sum = 0; while (!io_data.zero_cross_down) { YIELD(false); acc_p_sum_2e64 += (int64_t)(io_data.voltage) * io_data.current; acc_i2_sum_2e64 += (uint64_t)(io_data.current) * io_data.current; acc_i_sum += io_data.current; acc_counter++; } // Store OP offset io.cfg_current_offset = acc_i_sum / acc_counter; // Store noise tresholds (4x of noise value) { if (acc_p_sum_2e64 < 0) acc_p_sum_2e64 = 0; meter.cfg_min_p_sum_2e64 = acc_p_sum_2e64 * 4; meter.cfg_min_i2_sum_2e64 = acc_i2_sum_2e64 * 2; } return true; } private: uint16_t acc_counter = 0; int64_t acc_p_sum_2e64 = 0; int64_t acc_i2_sum_2e64 = 0; uint32_t acc_i_sum = 0; }; #endif <|start_filename|>hal/stm32f072cb/stm32cube/Src/tim.c<|end_filename|> /** ****************************************************************************** * @file tim.c * @brief This file provides code for the configuration * of the TIM instances. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "tim.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ TIM_HandleTypeDef htim15; /* TIM15 init function */ void MX_TIM15_Init(void) { TIM_MasterConfigTypeDef sMasterConfig = {0}; TIM_IC_InitTypeDef sConfigIC = {0}; htim15.Instance = TIM15; htim15.Init.Prescaler = 0; htim15.Init.CounterMode = TIM_COUNTERMODE_UP; htim15.Init.Period = 65535; htim15.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim15.Init.RepetitionCounter = 0; htim15.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_IC_Init(&htim15) != HAL_OK) { Error_Handler(); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim15, &sMasterConfig) != HAL_OK) { Error_Handler(); } sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING; sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI; sConfigIC.ICPrescaler = TIM_ICPSC_DIV1; sConfigIC.ICFilter = 0; if (HAL_TIM_IC_ConfigChannel(&htim15, &sConfigIC, TIM_CHANNEL_2) != HAL_OK) { Error_Handler(); } } void HAL_TIM_IC_MspInit(TIM_HandleTypeDef* tim_icHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(tim_icHandle->Instance==TIM15) { /* USER CODE BEGIN TIM15_MspInit 0 */ /* USER CODE END TIM15_MspInit 0 */ /* TIM15 clock enable */ __HAL_RCC_TIM15_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**TIM15 GPIO Configuration PA3 ------> TIM15_CH2 */ GPIO_InitStruct.Pin = GPIO_PIN_3; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF0_TIM15; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN TIM15_MspInit 1 */ /* USER CODE END TIM15_MspInit 1 */ } } void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef* tim_icHandle) { if(tim_icHandle->Instance==TIM15) { /* USER CODE BEGIN TIM15_MspDeInit 0 */ /* USER CODE END TIM15_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_TIM15_CLK_DISABLE(); /**TIM15 GPIO Configuration PA3 ------> TIM15_CH2 */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_3); /* USER CODE BEGIN TIM15_MspDeInit 1 */ /* USER CODE END TIM15_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <|start_filename|>src/regulator_adrc.h<|end_filename|> #ifndef __SPEED_CONTROLLER__ #define __SPEED_CONTROLLER__ #include "app.h" #include "config_map.h" #include "math/fix16_math.h" // ADRC iteration frequency, Hz. To fit math in fix16 without overflow. // Observers in ADRC system must have performance much higher // than motor performance, so set iteration frequency to 1000 Hz #define APP_ADRC_FREQUENCY 1000 // b0 = K/T, where K=1 due to speed and triac setpoint normalization, // T - motor time constant, estimated by calibration (see calibrator_adrc.h) #define ADRC_BO 5.0f constexpr int freq_divisor = APP_TICK_FREQUENCY / APP_ADRC_FREQUENCY; // Coefficient used by ADRC observers integrators constexpr fix16_t integr_coeff = F16(1.0 / APP_ADRC_FREQUENCY); class Regulator { public: // Output power [0..1] for triac control fix16_t out_power = 0; // ADRC coefficients fix16_t cfg_adrc_Kp; fix16_t cfg_adrc_Kobservers; fix16_t cfg_adrc_p_corr_coeff; fix16_t adrc_b0_inv; // 1-st order ADRC system inside by this article // https://arxiv.org/pdf/1908.04596.pdf // void tick(fix16_t knob, fix16_t speed) { // Downscale input frequency to avoid fixed poind overflow. // 40000Hz => 40Hz if (tick_freq_divide_counter >= freq_divisor) tick_freq_divide_counter = 0; if (tick_freq_divide_counter > 0) { tick_freq_divide_counter++; return; } tick_freq_divide_counter++; knob_normalized = normalize_knob(knob); regulator_speed_out = speed_adrc_tick(speed); out_power = regulator_speed_out; } // Load config from emulated EEPROM void configure() { cfg_dead_zone_width_norm = fix16_from_float(eeprom_float_read(CFG_DEAD_ZONE_WIDTH_ADDR, CFG_DEAD_ZONE_WIDTH_DEFAULT) / 100.0f); float _rpm_max = eeprom_float_read(CFG_RPM_MAX_ADDR, CFG_RPM_MAX_DEFAULT); cfg_rpm_max_limit_norm = fix16_from_float( eeprom_float_read(CFG_RPM_MAX_LIMIT_ADDR, CFG_RPM_MAX_LIMIT_DEFAULT) / _rpm_max ); float _rpm_min_limit = eeprom_float_read(CFG_RPM_MIN_LIMIT_ADDR, CFG_RPM_MIN_LIMIT_DEFAULT); // Don't allow too small low limit // ~ 3000 for 35000 max limit if (_rpm_min_limit < _rpm_max * 0.085f) _rpm_min_limit = _rpm_max * 0.085f; cfg_rpm_min_limit_norm = fix16_from_float(_rpm_min_limit / _rpm_max); knob_norm_coeff = fix16_div( cfg_rpm_max_limit_norm - cfg_rpm_min_limit_norm, fix16_one - cfg_dead_zone_width_norm ); cfg_adrc_Kp = fix16_from_float(eeprom_float_read(CFG_ADRC_KP_ADDR, CFG_ADRC_KP_DEFAULT)); cfg_adrc_Kobservers = fix16_from_float(eeprom_float_read(CFG_ADRC_KOBSERVERS_ADDR, CFG_ADRC_KOBSERVERS_DEFAULT)); cfg_adrc_p_corr_coeff = fix16_from_float(eeprom_float_read(CFG_ADRC_P_CORR_COEFF_ADDR, CFG_ADRC_P_CORR_COEFF_DEFAULT)); adrc_b0_inv = F16(1.0f / ADRC_BO); adrc_update_observers_parameters(); reset_state(); } // Calculate internal observers parameters L1, L2 // based on current cfg_adrc_Kobservers value void adrc_update_observers_parameters() { adrc_L1 = 2 * fix16_mul(cfg_adrc_Kobservers, cfg_adrc_Kp); adrc_L2 = fix16_mul(fix16_mul(cfg_adrc_Kobservers, cfg_adrc_Kp), fix16_mul(cfg_adrc_Kobservers, cfg_adrc_Kp)); } // Reset internal regulator state void reset_state() { adrc_speed_estimated = 0; adrc_correction = 0; regulator_speed_out = 0; // Skip iteration to allow meter resync tick_freq_divide_counter = 1; } private: // Control dead zone width near 0, when motor should not run. fix16_t cfg_dead_zone_width_norm; // Config limits are now in normalized [0.0..1.0] form of max motor RPM. fix16_t cfg_rpm_max_limit_norm; fix16_t cfg_rpm_min_limit_norm; // Cache for knob normalization, calculated on config load fix16_t knob_norm_coeff = F16(1); // knob value normalized to range (cfg_rpm_min_limit..cfg_rpm_max_limit) fix16_t knob_normalized; fix16_t adrc_correction; fix16_t adrc_speed_estimated; fix16_t adrc_L1; fix16_t adrc_L2; fix16_t regulator_speed_out = 0; uint32_t tick_freq_divide_counter = 0; // Apply min/max limits to knob output fix16_t normalize_knob(fix16_t knob) { if (knob < cfg_dead_zone_width_norm) return 0; return fix16_mul( (knob - cfg_dead_zone_width_norm), knob_norm_coeff ) + cfg_rpm_min_limit_norm; } fix16_t speed_adrc_tick(fix16_t speed) { // 1-st order ADRC by https://arxiv.org/pdf/1908.04596.pdf (augmented) // Proportional correction signal, // makes reaction to motor load change // significantly faster fix16_t adrc_p_correction = fix16_mul((speed - adrc_speed_estimated), cfg_adrc_p_corr_coeff); // u0 - output of linear proportional controller in ADRC system fix16_t u0 = fix16_mul((knob_normalized - adrc_speed_estimated), cfg_adrc_Kp); // 2 state observers: // - speed observer (adrc_speed_estimated) // - generalized disturbance observer (adrc_correction) adrc_correction += fix16_mul(fix16_mul(speed - adrc_speed_estimated, adrc_L2), integr_coeff); adrc_speed_estimated += fix16_mul(u0 + fix16_mul(adrc_L1, (speed - adrc_speed_estimated)), integr_coeff); adrc_speed_estimated = fix16_clamp( adrc_speed_estimated, cfg_rpm_min_limit_norm, cfg_rpm_max_limit_norm ); fix16_t output = fix16_mul((u0 - adrc_correction - adrc_p_correction), adrc_b0_inv); // Anti-Windup // 0 <= output <= 1 // // output = (u0 - adrc_correction)/b0, // so if output = cfg_rpm_min_limit_norm -> adrc_correction = u0 - b0 * cfg_rpm_min_limit_norm if (output < cfg_rpm_min_limit_norm) { output = cfg_rpm_min_limit_norm; adrc_correction = u0 - fix16_div(cfg_rpm_min_limit_norm, adrc_b0_inv); } // output = (u0 - adrc_correction)/b0, // so if output = cfg_rpm_max_limit_norm -> adrc_correction = u0 - b0 * cfg_rpm_max_limit_norm if (output > cfg_rpm_max_limit_norm) { output = cfg_rpm_max_limit_norm; adrc_correction = u0 - fix16_div(cfg_rpm_max_limit_norm, adrc_b0_inv); } return output; } }; #endif <|start_filename|>src/calibrator/calibrator_adrc.h<|end_filename|> #ifndef __CALIBRATOR_ADRC__ #define __CALIBRATOR_ADRC__ #include "../math/fix16_math.h" #include "../app.h" #include <limits.h> #include <cmath> #include "etl/cyclic_value.h" // Minimal reasonable adrc_Kp * b0 value #define MIN_ADRC_KPdivB0 0.3 // Minimal adrc_Kobservers value (observers disabled) #define MIN_ADRC_KOBSERVERS 0.0 // Safe adrc_Kobservers value for adrc_Kp calibration #define SAFE_ADRC_KOBSERVERS 1.0 // Minimal adrc_p_corr_coeff is 0 (proportional correction disabled) #define MIN_ADRC_P_CORR_COEFF 0.0 #define INIT_KP_ITERATION_STEP 4.0 #define INIT_OBSERVERS_ITERATION_STEP 4.0 #define INIT_P_CORR_COEFF_ITERATION_STEP 5.0 // Scale down ADRC coefficients to this value for safety #define ADRC_SAFETY_SCALE 0.6 #define ADRC_P_CORR_COEFF_SAFETY_SCALE 0.6 // Maximal setpoint for picking motor speed factor #define SPEED_FACTOR_SETPOINT 0.8 // Maximum speed oscillation amplitude // and speed overshoot values // for ADRC_KP and ADRC_KOBSERVERS adjustment #define MAX_AMPLITUDE 3.0 // Maximum speed oscillation amplitude // and speed overshoot values // for ADRC_P_CORR_COEFF adjustment #define MAX_P_CORR_COEFF_AMPLITUDE 3.0 #define MAX_OVERSHOOT 0.15 // Setpoint values for start and // stop time measurement. #define LOW_SPEED_SETPOINT 0.35 #define HIGH_SPEED_SETPOINT 0.7 // Speed data is noisy, so start/stop // time is measured when speed crosses // SPEED_MEASURE_THRESHOLD and then recalculated // to more narrow SPEED_IDEAL_THRESHOLD. #define SPEED_MEASURE_THRESHOLD 0.15 #define SPEED_IDEAL_THRESHOLD 0.02 // Assume that motor is 1-st order dynamic system. // It will cross SPEED_IDEAL_THRESHOLD // at ideal time = measured time * start_stop_adjust static const fix16_t start_stop_adjust = fix16_from_float( (float)(log(SPEED_IDEAL_THRESHOLD) / log(SPEED_MEASURE_THRESHOLD)) ); // Frequency scale for data save when measure start/stop time. // Helps to save used memory #define SPEED_DATA_SAVE_RATIO 10 // Max 10 seconds to store data on start/stop time measure #define SPEED_DATA_SAVE_TIME_MAX 10 // Lowpass coefficient value // LOWPASS_FC - cutoff frequency, Hz // LOWPASS_FD - sampling frequency, Hz #define LOWPASS_FC 5.0 #define LOWPASS_FS 50.0 #define LOWPASS_FILTER_ALPHA ((2.0 * M_PI / LOWPASS_FS * LOWPASS_FC) \ / (2.0 * M_PI / LOWPASS_FS * LOWPASS_FC + 1.0)) class CalibratorADRC { public: bool tick(io_data_t &io_data) { YIELDABLE; // // Before start time measure motor must run at steady low speed // io.setpoint = F16(LOW_SPEED_SETPOINT); speed_tracker.reset(); while (!speed_tracker.is_stable_or_exceeded()) { YIELD(false); if (!io_data.zero_cross_up) continue; speed_tracker.push(meter.speed); } // // Apply high speed power and record process of speed rise, // until speed become stable // io.setpoint = F16(HIGH_SPEED_SETPOINT); speed_tracker.reset(); speed_data_idx = 0; start_time_ticks = 0; start_stop_scaler_cyclic_cnt = 0; while (!speed_tracker.is_stable_or_exceeded()) { YIELD(false); start_time_ticks++; if (!io_data.zero_cross_up) continue; if (speed_data_idx < speed_data_length) { // Apply lowpass filtration filtered_speed = fix16_mul( F16(LOWPASS_FILTER_ALPHA), meter.speed ) + fix16_mul( F16(1.0 - LOWPASS_FILTER_ALPHA), (speed_data_idx == 0) ? meter.speed : filtered_speed ); if (start_stop_scaler_cyclic_cnt++ == 0) { start_speed_data[speed_data_idx++] = filtered_speed; } } speed_tracker.push(meter.speed); } start_speed_data_len = speed_data_idx; // // Now measure stop time (reverse process) // io.setpoint = F16(LOW_SPEED_SETPOINT); speed_tracker.reset(); speed_data_idx = 0; stop_time_ticks = 0; start_stop_scaler_cyclic_cnt = 0; while (!speed_tracker.is_stable_or_exceeded()) { YIELD(false); stop_time_ticks++; if (!io_data.zero_cross_up) continue; if (speed_data_idx < speed_data_length) { // Apply lowpass filtration filtered_speed = fix16_mul( F16(LOWPASS_FILTER_ALPHA), meter.speed ) + fix16_mul( F16(1.0 - LOWPASS_FILTER_ALPHA), (speed_data_idx == 0) ? meter.speed : filtered_speed ); if (start_stop_scaler_cyclic_cnt++ == 0) { stop_speed_data[speed_data_idx++] = filtered_speed; } } speed_tracker.push(meter.speed); } stop_speed_data_len = speed_data_idx; motor_start_stop_time = calculate_start_stop_time( start_speed_data_len, start_speed_data, stop_speed_data_len, stop_speed_data ); // // Pick motor scaling factor // // Reset scaling factor meter.cfg_rekv_to_speed_factor = fix16_one; io.setpoint = F16(SPEED_FACTOR_SETPOINT); speed_tracker.reset(); // At setpoint=1.0 motor may work unstable // due to heavy sparking at the commutator // So measure at setpoint=0.8 and then // linearly extrapolate // Wait for stable speed while (!speed_tracker.is_stable_or_exceeded()) { YIELD(false); if (!io_data.zero_cross_up) continue; speed_tracker.push(meter.speed); } // Extrapolate measured value to setpoint=1.0 float speed_factor = fix16_to_float(fix16_div(speed_tracker.average(), F16(SPEED_FACTOR_SETPOINT))); eeprom_float_write( CFG_REKV_TO_SPEED_FACTOR_ADDR, speed_factor ); meter.configure(); // // Calculate speed setting values for picking ADRC regulator parameters // fix16_t cfg_rpm_max_limit = fix16_from_float( eeprom_float_read(CFG_RPM_MAX_LIMIT_ADDR, CFG_RPM_MAX_LIMIT_DEFAULT) ); fix16_t cfg_rpm_min_limit = fix16_from_float( eeprom_float_read(CFG_RPM_MIN_LIMIT_ADDR, CFG_RPM_MIN_LIMIT_DEFAULT) ); fix16_t rpm_min_rel = fix16_div(cfg_rpm_min_limit, cfg_rpm_max_limit); adrc_kp_speed_setting = rpm_min_rel; adrc_observers_speed_setting = rpm_min_rel; adrc_p_corr_coeff_speed_setting = rpm_min_rel; // // Pick ADRC_KP coeff value by half cut method // iterations_count = 0; regulator.cfg_adrc_p_corr_coeff = F16(MIN_ADRC_P_CORR_COEFF); adrc_param_attempt_value = fix16_div(F16(MIN_ADRC_KPdivB0), regulator.adrc_b0_inv); // TODO - Measure period duration for correct operation at 50 and 60 Hz measure_amplitude_ticks_max = fix16_to_int(motor_start_stop_time * 50); iteration_step = fix16_div(F16(INIT_KP_ITERATION_STEP), regulator.adrc_b0_inv); // Set ADRC_KOBSERVERS to safe value regulator.cfg_adrc_Kobservers = F16(SAFE_ADRC_KOBSERVERS); while (iterations_count < max_iterations) { speed_tracker.reset(); // Wait for stable speed with minimal // ADRC_KP and safe ADRC_KOBSERVERS regulator.cfg_adrc_Kp = fix16_div(F16(MIN_ADRC_KPdivB0), regulator.adrc_b0_inv); regulator.adrc_update_observers_parameters(); while (!speed_tracker.is_stable_or_exceeded()) { regulator.tick(adrc_kp_speed_setting, meter.speed); io.setpoint = regulator.out_power; YIELD(false); if (!io_data.zero_cross_up) continue; speed_tracker.push(meter.speed); }; // // Measure amplitude // regulator.cfg_adrc_Kp = adrc_param_attempt_value; regulator.adrc_update_observers_parameters(); measure_amplitude_max_speed = 0; measure_amplitude_min_speed = fix16_maximum; measure_amplitude_ticks = 0; median_filter.reset(); ticks_cnt = 0; while (measure_amplitude_ticks < measure_amplitude_ticks_max) { regulator.tick(adrc_kp_speed_setting, meter.speed); io.setpoint = regulator.out_power; YIELD(false); if (!io_data.zero_cross_up) continue; ticks_cnt++; median_filter.add(meter.speed); if (ticks_cnt >= 12) { fix16_t filtered_speed = median_filter.result(); median_filter.reset(); ticks_cnt = 0; if (measure_amplitude_max_speed < filtered_speed) { measure_amplitude_max_speed = filtered_speed; } if (measure_amplitude_min_speed > filtered_speed) { measure_amplitude_min_speed = filtered_speed; } } measure_amplitude_ticks++; } fix16_t amplitude = measure_amplitude_max_speed - measure_amplitude_min_speed; // Save amplitude of first iteration as reference // to compare values of next iterations to this value if (iterations_count == 0) first_iteration_amplitude = amplitude; // If amplitude is less than margin value // step for next iteration should be positive, // otherwise - negative if (amplitude <= fix16_mul(first_iteration_amplitude, F16(MAX_AMPLITUDE))) { iteration_step = abs(iteration_step); } else iteration_step = -abs(iteration_step); adrc_param_attempt_value += iteration_step; iteration_step /= 2; iterations_count++; } adrc_kp_calibrated_value = fix16_mul(adrc_param_attempt_value, F16(ADRC_SAFETY_SCALE)); // // Pick ADRC_KOBSERVERS coeff value by half cut method // iterations_count = 0; adrc_param_attempt_value = F16(MIN_ADRC_KOBSERVERS); // TODO - Measure period duration for correct operation at 50 and 60 Hz measure_amplitude_ticks_max = fix16_to_int(motor_start_stop_time * 50); iteration_step = F16(INIT_OBSERVERS_ITERATION_STEP); // Set ADRC_KP to calibrated value regulator.cfg_adrc_Kp = adrc_kp_calibrated_value; while (iterations_count < max_iterations) { speed_tracker.reset(); // Wait for stable speed with calibrated // ADRC_KP and minimal ADRC_KOBSERVERS regulator.cfg_adrc_Kobservers = F16(MIN_ADRC_KOBSERVERS); regulator.adrc_update_observers_parameters(); while (!speed_tracker.is_stable_or_exceeded()) { regulator.tick(adrc_observers_speed_setting, meter.speed); io.setpoint = regulator.out_power; YIELD(false); if (!io_data.zero_cross_up) continue; speed_tracker.push(meter.speed); }; // // Measure amplitude // regulator.cfg_adrc_Kobservers = adrc_param_attempt_value; regulator.adrc_update_observers_parameters(); measure_amplitude_max_speed = 0; measure_amplitude_min_speed = fix16_maximum; measure_amplitude_ticks = 0; median_filter.reset(); ticks_cnt = 0; while (measure_amplitude_ticks < measure_amplitude_ticks_max) { regulator.tick(adrc_observers_speed_setting, meter.speed); io.setpoint = regulator.out_power; YIELD(false); if (!io_data.zero_cross_up) continue; ticks_cnt++; median_filter.add(meter.speed); if (ticks_cnt >= 12) { fix16_t filtered_speed = median_filter.result(); median_filter.reset(); ticks_cnt = 0; if (measure_amplitude_max_speed < filtered_speed) { measure_amplitude_max_speed = filtered_speed; } if (measure_amplitude_min_speed > filtered_speed) { measure_amplitude_min_speed = filtered_speed; } } measure_amplitude_ticks++; } fix16_t amplitude = measure_amplitude_max_speed - measure_amplitude_min_speed; // Save amplitude of first iteration as reference // to compare values of next iterations to this value if (iterations_count == 0) first_iteration_amplitude = amplitude; // If amplitude is less than margin value // step for next iteration should be positive, // otherwise - negative if (amplitude <= fix16_mul(first_iteration_amplitude, F16(MAX_AMPLITUDE))) { iteration_step = abs(iteration_step); } else iteration_step = -abs(iteration_step); adrc_param_attempt_value += iteration_step; iteration_step /= 2; iterations_count++; } adrc_observers_calibrated_value = fix16_mul(adrc_param_attempt_value, F16(ADRC_SAFETY_SCALE)); // // Pick ADRC_P_CORR_COEFF value by half cut method // iterations_count = 0; adrc_param_attempt_value = F16(MIN_ADRC_P_CORR_COEFF); // TODO - Measure period duration for correct operation at 50 and 60 Hz measure_amplitude_ticks_max = fix16_to_int(motor_start_stop_time * 50); iteration_step = F16(INIT_P_CORR_COEFF_ITERATION_STEP); // Set ADRC_KP and ADRC_KOBSERVERS to calibrated values regulator.cfg_adrc_Kp = adrc_kp_calibrated_value; regulator.cfg_adrc_Kobservers = adrc_observers_calibrated_value; regulator.adrc_update_observers_parameters(); while (iterations_count < max_iterations) { speed_tracker.reset(); // Wait for stable speed with calibrated // ADRC_KP, calibrated ADRC_KOBSERVERS // and minimal ADRC_P_CORR_COEFF regulator.cfg_adrc_p_corr_coeff = F16(MIN_ADRC_P_CORR_COEFF); while (!speed_tracker.is_stable_or_exceeded()) { regulator.tick(adrc_p_corr_coeff_speed_setting, meter.speed); io.setpoint = regulator.out_power; YIELD(false); if (!io_data.zero_cross_up) continue; speed_tracker.push(meter.speed); }; // // Measure amplitude // regulator.cfg_adrc_p_corr_coeff = adrc_param_attempt_value; measure_amplitude_max_speed = 0; measure_amplitude_min_speed = fix16_maximum; measure_amplitude_ticks = 0; median_filter.reset(); ticks_cnt = 0; while (measure_amplitude_ticks < measure_amplitude_ticks_max) { regulator.tick(adrc_p_corr_coeff_speed_setting, meter.speed); io.setpoint = regulator.out_power; YIELD(false); if (!io_data.zero_cross_up) continue; ticks_cnt++; median_filter.add(meter.speed); if (ticks_cnt >= 12) { fix16_t filtered_speed = median_filter.result(); median_filter.reset(); ticks_cnt = 0; if (measure_amplitude_max_speed < filtered_speed) { measure_amplitude_max_speed = filtered_speed; } if (measure_amplitude_min_speed > filtered_speed) { measure_amplitude_min_speed = filtered_speed; } } measure_amplitude_ticks++; } fix16_t amplitude = measure_amplitude_max_speed - measure_amplitude_min_speed; // Save amplitude of first iteration as reference // to compare values of next iterations to this value if (iterations_count == 0) first_iteration_amplitude = amplitude; // If amplitude is less than margin value // step for next iteration should be positive, // otherwise - negative if (amplitude <= fix16_mul(first_iteration_amplitude, F16(MAX_P_CORR_COEFF_AMPLITUDE))) { iteration_step = abs(iteration_step); } else iteration_step = -abs(iteration_step); adrc_param_attempt_value += iteration_step; iteration_step /= 2; iterations_count++; } adrc_p_corr_coeff_calibrated_value = fix16_mul(adrc_param_attempt_value, F16(ADRC_P_CORR_COEFF_SAFETY_SCALE)); // // Store results // eeprom_float_write( CFG_ADRC_KP_ADDR, fix16_to_float(adrc_kp_calibrated_value) ); eeprom_float_write( CFG_ADRC_KOBSERVERS_ADDR, fix16_to_float(adrc_observers_calibrated_value) ); eeprom_float_write( CFG_ADRC_P_CORR_COEFF_ADDR, fix16_to_float(adrc_p_corr_coeff_calibrated_value) ); // // Reload config & flush garbage after unsync, caused by long EEPROM write. // regulator.configure(); meter.reset_state(); return true; } private: // Desireable accuracy of ADRC calibration is 0.1 // We need 7 iterations to achieve this accuracy // because (10 - 1)/2^7 = 0.07 < 0.1 enum { max_iterations = 7 }; int ticks_cnt = 0; // Holds buffer length for start/stop time calculation enum { speed_data_length = (int)(SPEED_DATA_SAVE_TIME_MAX * 60 / SPEED_DATA_SAVE_RATIO) }; // Speed settings for picking ADRC regulator parameters fix16_t adrc_kp_speed_setting; fix16_t adrc_observers_speed_setting; fix16_t adrc_p_corr_coeff_speed_setting; // Buffers for speed data for start/stop // time measurement fix16_t start_speed_data[speed_data_length]; fix16_t stop_speed_data[speed_data_length]; int speed_data_idx = 0; int start_time_ticks = 0; int stop_time_ticks = 0; etl::cyclic_value<uint32_t, 0, SPEED_DATA_SAVE_RATIO - 1> start_stop_scaler_cyclic_cnt; fix16_t filtered_speed = 0; fix16_t prev_speed = 0; int start_speed_data_len; int stop_speed_data_len; fix16_t adrc_param_attempt_value; fix16_t adrc_kp_calibrated_value; fix16_t adrc_observers_calibrated_value; fix16_t adrc_p_corr_coeff_calibrated_value; fix16_t iteration_step; fix16_t measure_amplitude_max_speed; fix16_t measure_amplitude_min_speed; // Holds value calculated during first attempt fix16_t first_iteration_amplitude; int iterations_count = 0; // History of measured speed. Used to detect stable values. // At 50Hz ~ 0.25s for single fetch, 9s timeout StabilityFilterTemplate<F16(2.0), 12, 12*39, 6> speed_tracker; int measure_attempts = 0; MedianIteratorTemplate<fix16_t, 32> median_filter; fix16_t motor_start_stop_time; int measure_amplitude_ticks = 0; int measure_amplitude_ticks_max; // Measure steady state speed with safe ADRC parameters // during 3 sec interval enum { measure_steadystate_ticks_max = 50*3 }; fix16_t overshoot_speed = 0; fix16_t steadystate_speed = 0; // Returns sum of start and stop times fix16_t calculate_start_stop_time( int start_len, fix16_t start_data[], int stop_len, fix16_t stop_data[] ) { fix16_t start_steady_speed = start_data[start_len - 1]; fix16_t start_initial_speed = start_data[0]; fix16_t speed_at_measure_threshold = fix16_mul( start_steady_speed, F16(1.0 - SPEED_MEASURE_THRESHOLD) ) + fix16_mul( start_initial_speed, F16(SPEED_MEASURE_THRESHOLD) ); fix16_t start_time_measured = 0; for (int i = 0; i < start_len; i++) { if (start_data[i] > speed_at_measure_threshold) { start_time_measured = fix16_from_float((float)(i * start_time_ticks) / (float)(start_len * APP_TICK_FREQUENCY)); break; } } fix16_t stop_steady_speed = stop_data[stop_len - 1]; fix16_t stop_initial_speed = stop_data[0]; speed_at_measure_threshold = fix16_mul( stop_steady_speed, F16(1.0 - SPEED_MEASURE_THRESHOLD) ) + fix16_mul( stop_initial_speed, F16(SPEED_MEASURE_THRESHOLD) ); fix16_t stop_time_measured = 0; for (int i = 0; i < stop_len; i++) { if (stop_data[i] < speed_at_measure_threshold) { stop_time_measured = fix16_from_float((float)(i * stop_time_ticks) / (float)(stop_len * APP_TICK_FREQUENCY)); break; } } fix16_t start_stop_time_measured = start_time_measured + stop_time_measured; // Assume that motor is 1-st order dynamic system, // calculate time when it will cross SPEED_IDEAL_THRESHOLD fix16_t start_stop_time = fix16_mul( start_stop_time_measured, start_stop_adjust ); return start_stop_time; } }; #endif <|start_filename|>src/calibrator/calibrator.h<|end_filename|> #ifndef __CALIBRATOR_H__ #define __CALIBRATOR_H__ // Detect when user dials knob 3 times, start calibration sequence and // update configuration. #include "math/fix16_math.h" #include "yield.h" #include "../app.h" #include "calibrator_wait_knob_dial.h" #include "calibrator_static.h" #include "calibrator_adrc.h" class Calibrator { public: // Returns: // // - false: we should continue in normal mode // - true: calibration started, we should stop other actions in main // loop until finished. // bool tick(io_data_t &io_data) { YIELDABLE; YIELD_UNTIL(wait_knob_dial.tick(io_data), false); YIELD_UNTIL(calibrate_static.tick(io_data), true); YIELD_UNTIL(calibrate_adrc.tick(io_data), true); return false; } private: // Nested FSM-s CalibratorWaitKnobDial wait_knob_dial; CalibratorStatic calibrate_static; CalibratorADRC calibrate_adrc; }; #endif <|start_filename|>src/meter.h<|end_filename|> #ifndef __METER__ #define __METER__ #include "math/fix16_math.h" #include "math/truncated_mean.h" #include "math/median.h" #include "config_map.h" #include "app_hal.h" #include "app.h" /* Meter. Process raw data to calculate virtual params: - speed */ class Meter { public: fix16_t speed = 0; bool is_r_calibrated = false; // Config info fix16_t cfg_rekv_to_speed_factor; // Noise calibration tresholds int64_t cfg_min_p_sum_2e64 = 0; int64_t cfg_min_i2_sum_2e64 = 0; // Input from triac driver to reflect triac setpoint. Needed for speed measure // to interpolate motor resistance. Autoupdated by triac driver. //fix16_t in_triac_setpoint = 0; const fix16_t cfg_r_table_setpoints[CFG_R_INTERP_TABLE_LENGTH] = { F16(0.1), F16(0.15), F16(0.2), F16(0.3), F16(0.4), F16(0.6), F16(1.0), }; fix16_t cfg_r_table_setpoints_inerp_inv[CFG_R_INTERP_TABLE_LENGTH] = {}; // Should be called with 40kHz frequency void tick(io_data_t &io_data) { speed_tick(io_data); } // Load config from emulated EEPROM void configure() { cfg_rekv_to_speed_factor = fix16_from_float( eeprom_float_read(CFG_REKV_TO_SPEED_FACTOR_ADDR, CFG_REKV_TO_SPEED_FACTOR_DEFAULT) ); #define R_CAL_CHECK_MARKER 123456789.0f for (int i = 0; i < CFG_R_INTERP_TABLE_LENGTH; i++) { cfg_r_table[i] = fix16_from_float( eeprom_float_read( i + CFG_R_INTERP_TABLE_START_ADDR, R_CAL_CHECK_MARKER ) ); } // Pre-calclate inverted coeff-s to avoid divisions // in `get_motor_resistance()` cfg_r_table_setpoints_inerp_inv[0] = fix16_one; for (int i = 1; i < CFG_R_INTERP_TABLE_LENGTH; i++) { if (cfg_r_table[i] - cfg_r_table[i - 1] > 0) { cfg_r_table_setpoints_inerp_inv[i] = fix16_div( fix16_one, cfg_r_table_setpoints[i] - cfg_r_table_setpoints[i - 1] ); } else cfg_r_table_setpoints_inerp_inv[i] = fix16_one; } is_r_calibrated = (cfg_r_table[0] == fix16_from_float(R_CAL_CHECK_MARKER)) ? false : true; reset_state(); } void reset_state() { speed = 0; p_sum_2e64 = 0; i2_sum_2e64 = 0; sum_counter = 0; io.out.clear(); } private: // Motor resistance interpolation table fix16_t cfg_r_table[CFG_R_INTERP_TABLE_LENGTH]; fix16_t cfg_r_interp_scale_inv_table[CFG_R_INTERP_TABLE_LENGTH]; fix16_t get_motor_resistance(fix16_t setpoint) { // Bounds check if (setpoint < cfg_r_table_setpoints[0]) return cfg_r_table[0]; if (setpoint >= fix16_one) return cfg_r_table[CFG_R_INTERP_TABLE_LENGTH - 1]; for (int i = 0; i < CFG_R_INTERP_TABLE_LENGTH - 1; i++) { if ((setpoint >= cfg_r_table_setpoints[i]) && (setpoint < cfg_r_table_setpoints[i + 1])) { fix16_t range_start = cfg_r_table[i]; fix16_t range_end = cfg_r_table[i + 1]; fix16_t scale = fix16_mul( setpoint - cfg_r_table_setpoints[i], cfg_r_table_setpoints_inerp_inv[i + 1] ); return fix16_mul(range_start, fix16_one - scale) + fix16_mul(range_end, scale); } } return cfg_r_table[0]; } int64_t p_sum_2e64 = 0; // active power << 32 int64_t i2_sum_2e64 = 0; // square of current << 32 uint16_t sum_counter = 0; void speed_tick(io_data_t &io_data) { // Don't try to calculate speed until R calibrated if (!is_r_calibrated) { speed = 0; return; } // Calculate sums // use 64 bits to prevent overflow (but sill keep dsired precision) p_sum_2e64 += (int64_t)io_data.voltage * io_data.current; i2_sum_2e64 += (uint64_t)io_data.current * io_data.current; sum_counter++; // Calculate speed at end of negative half-wave // In this case active power is equivalent to // Joule power, P = R * I^2 // R = P / I^2 // r_ekv is equivalent resistance created by back-EMF // r_ekv = R - R_motor if (io_data.zero_cross_up) { // 1. Filter noise. // 2. Avoid zero division. if (p_sum_2e64 > cfg_min_p_sum_2e64 && i2_sum_2e64 > cfg_min_i2_sum_2e64) { uint64_t p = p_sum_2e64, i2 = i2_sum_2e64; NORMALIZE_TO_31_BIT(p, i2); if (i2 > 0) { fix16_t r_ekv = fix16_div((fix16_t)p, (fix16_t)i2) - get_motor_resistance(io.setpoint); speed = fix16_div(r_ekv, cfg_rekv_to_speed_factor); } else speed = 0; // Clamp calculated speed value, speed can't be negative if (speed < 0) speed = 0; } else speed = 0; p_sum_2e64 = 0; i2_sum_2e64 = 0; sum_counter = 0; } } }; #endif
speedcontrols/ac_sc_grinder
<|start_filename|>gen_mocks.go<|end_filename|> package main // import "sourcegraph.com/sourcegraph/gen-mocks" import ( "bytes" "flag" "fmt" "go/ast" "go/build" "go/parser" "go/printer" "go/token" "io" "log" "os" "path/filepath" "regexp" "strings" "golang.org/x/tools/imports" ) var ( ifacePkgDir = flag.String("p", ".", "directory of package containing interface types") ifacePat = flag.String("i", ".+Service", "regexp pattern for selecting interface types by name") writeFiles = flag.Bool("w", false, "write over existing files in output directory (default: writes to stdout)") outDir = flag.String("o", ".", "output directory") outPkg = flag.String("outpkg", "", "output pkg name (default: same as input pkg)") namePrefix = flag.String("name_prefix", "Mock", "output: name prefix of mock impl types (e.g., T -> MockT)") noPassArgs = flag.String("no_pass_args", "", "don't pass args with this name from the interface method to the mock impl func") fset = token.NewFileSet() ) func main() { flag.Parse() log.SetFlags(0) bpkg, err := build.Import(*ifacePkgDir, ".", build.FindOnly) if err != nil { log.Fatal(err) } pat, err := regexp.Compile(*ifacePat) if err != nil { log.Fatal(err) } pkgs, err := parser.ParseDir(fset, *ifacePkgDir, nil, parser.AllErrors) if err != nil { log.Fatal(err) } for _, pkg := range pkgs { if pkg.Name == "main" || strings.HasSuffix(pkg.Name, "_test") { continue } ifaces, err := readIfaces(pkg, pat) if err != nil { log.Fatal(err) } if len(ifaces) == 0 { log.Printf("warning: package %q has no interface types matching %q", pkg.Name, *ifacePat) continue } var pkgName string if *outPkg == "" { pkgName = pkg.Name } else { pkgName = *outPkg } if err := writeMockImplFiles(*outDir, pkgName, pkg.Name, bpkg.ImportPath, ifaces); err != nil { log.Fatal(err) } } } // readIfaces returns a list of interface types in pkg that should be // mocked. func readIfaces(pkg *ast.Package, pat *regexp.Regexp) ([]*ast.TypeSpec, error) { var ifaces []*ast.TypeSpec ast.Walk(visitFn(func(node ast.Node) bool { switch node := node.(type) { case *ast.GenDecl: if node.Tok == token.TYPE { for _, spec := range node.Specs { tspec := spec.(*ast.TypeSpec) if _, ok := tspec.Type.(*ast.InterfaceType); !ok { continue } if name := tspec.Name.Name; pat.MatchString(name) { ifaces = append(ifaces, tspec) } } } return false default: return true } }), pkg) return ifaces, nil } type visitFn func(node ast.Node) (descend bool) func (v visitFn) Visit(node ast.Node) ast.Visitor { descend := v(node) if descend { return v } else { return nil } } func writeMockImplFiles(outDir, outPkg, ifacePkgName, ifacePkgPath string, svcIfaces []*ast.TypeSpec) error { if err := os.MkdirAll(outDir, 0700); err != nil { return err } decls := map[string][]ast.Decl{} // file -> decls for _, iface := range svcIfaces { filename := fset.Position(iface.Pos()).Filename filename = filepath.Join(outDir, strings.TrimSuffix(filepath.Base(filename), ".go")+"_mock.go") // mock method fields on struct var methFields []*ast.Field for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List { if meth, ok := methField.Type.(*ast.FuncType); ok { methFields = append(methFields, &ast.Field{ Names: []*ast.Ident{ast.NewIdent(methField.Names[0].Name + "_")}, Type: omitNoPassArgs(meth), }) } } // struct implementation type mockTypeName := *namePrefix + iface.Name.Name implType := &ast.GenDecl{Tok: token.TYPE, Specs: []ast.Spec{&ast.TypeSpec{ Name: ast.NewIdent(mockTypeName), Type: &ast.StructType{Fields: &ast.FieldList{List: methFields}}, }}} decls[filename] = append(decls[filename], implType) // struct methods for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List { if meth, ok := methField.Type.(*ast.FuncType); ok { synthesizeFieldNamesIfMissing(meth.Params) if ifacePkgName != outPkg { // TODO(sqs): check for import paths or dirs unequal, not pkg name qualifyPkgRefs(meth, ifacePkgName) } decls[filename] = append(decls[filename], &ast.FuncDecl{ Recv: &ast.FieldList{List: []*ast.Field{ { Names: []*ast.Ident{ast.NewIdent("s")}, Type: &ast.StarExpr{X: ast.NewIdent(mockTypeName)}, }, }}, Name: ast.NewIdent(methField.Names[0].Name), Type: meth, Body: &ast.BlockStmt{List: []ast.Stmt{ &ast.ReturnStmt{Results: []ast.Expr{ &ast.CallExpr{ Fun: &ast.SelectorExpr{ X: ast.NewIdent("s"), Sel: ast.NewIdent(methField.Names[0].Name + "_"), }, Args: fieldListToIdentList(meth.Params), Ellipsis: ellipsisIfNeeded(meth.Params), }, }}, }}, }) } } // compile-time implements checks var ifaceType ast.Expr if ifacePkgName == outPkg { ifaceType = ast.NewIdent(iface.Name.Name) } else { ifaceType = &ast.SelectorExpr{X: ast.NewIdent(ifacePkgName), Sel: ast.NewIdent(iface.Name.Name)} } decls[filename] = append(decls[filename], &ast.GenDecl{ Tok: token.VAR, Specs: []ast.Spec{ &ast.ValueSpec{ Names: []*ast.Ident{ast.NewIdent("_")}, Type: ifaceType, Values: []ast.Expr{ &ast.CallExpr{ Fun: &ast.ParenExpr{X: &ast.StarExpr{X: ast.NewIdent(mockTypeName)}}, Args: []ast.Expr{ast.NewIdent("nil")}, }, }, }, }, }) } for filename, decls := range decls { file := &ast.File{ Name: ast.NewIdent(outPkg), Decls: decls, } log.Println("#", filename) var w io.Writer if *writeFiles { f, err := os.Create(filename) if err != nil { return err } defer f.Close() w = f } else { w = os.Stdout } var buf bytes.Buffer if err := printer.Fprint(&buf, fset, file); err != nil { return err } // Always put blank lines between funcs. src := bytes.Replace(buf.Bytes(), []byte("}\nfunc"), []byte("}\n\nfunc"), -1) var err error src, err = imports.Process(filename, src, nil) if err != nil { return err } fmt.Fprintln(w, "// generated by gen-mocks; DO NOT EDIT") fmt.Fprintln(w) w.Write(src) } return nil } // qualifyPkgRefs qualifies all refs to non-package-qualified non-builtin types in f so that they refer to definitions in pkg. E.g., 'func(x MyType) -> func (x pkg.MyType)'. func qualifyPkgRefs(f *ast.FuncType, pkg string) { var qualify func(x ast.Expr) ast.Expr qualify = func(x ast.Expr) ast.Expr { switch y := x.(type) { case *ast.Ident: if ast.IsExported(y.Name) { return &ast.SelectorExpr{X: ast.NewIdent(pkg), Sel: y} } case *ast.StarExpr: y.X = qualify(y.X) case *ast.ArrayType: y.Elt = qualify(y.Elt) case *ast.MapType: y.Key = qualify(y.Key) y.Value = qualify(y.Value) } return x } for _, p := range f.Params.List { p.Type = qualify(p.Type) } for _, r := range f.Results.List { r.Type = qualify(r.Type) } } // synthesizeFieldNamesIfMissing adds synthesized variable names to fl // if it contains fields with no name. E.g., the field list in // `func(string, int)` would be converted to `func(v0 string, v1 // int)`. func synthesizeFieldNamesIfMissing(fl *ast.FieldList) { for i, f := range fl.List { if len(f.Names) == 0 { f.Names = []*ast.Ident{ast.NewIdent(fmt.Sprintf("v%d", i))} } } } func fieldListToIdentList(fl *ast.FieldList) []ast.Expr { var fs []ast.Expr for _, f := range fl.List { for _, name := range f.Names { if *noPassArgs == name.Name { continue } x := ast.Expr(ast.NewIdent(name.Name)) fs = append(fs, x) } } return fs } func hasEllipsis(fl *ast.FieldList) bool { if fl.List == nil { return false } lastField := fl.List[len(fl.List)-1] if len(lastField.Names) > 0 && lastField.Names[0].Name == *noPassArgs { return false } _, ok := lastField.Type.(*ast.Ellipsis) return ok } func ellipsisIfNeeded(fl *ast.FieldList) token.Pos { if hasEllipsis(fl) { return 1 } return 0 } func omitNoPassArgs(ft *ast.FuncType) *ast.FuncType { tmp := *ft // copy ft = &tmp tmp2 := *ft.Params ft.Params = &tmp2 var keepParams []*ast.Field for _, p := range ft.Params.List { if len(p.Names) == 1 && p.Names[0].Name == *noPassArgs { continue } keepParams = append(keepParams, p) } ft.Params.List = keepParams return ft } func astString(x ast.Expr) string { var buf bytes.Buffer if err := printer.Fprint(&buf, fset, x); err != nil { panic(err) } return buf.String() }
sourcegraph/gen-mocks
<|start_filename|>src/Itinero.API/Instances/Instance.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2017 <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 Itinero.LocalGeo; using Itinero.Profiles; using System.Collections.Generic; using Itinero.API.Models; using System.Linq; using Itinero.Algorithms.Networks.Analytics.Heatmaps; using Itinero.Algorithms.Networks.Analytics.Isochrones; using Itinero.Algorithms.Networks.Analytics.Trees; using Itinero.Transit; using System; namespace Itinero.API.Instances { /// <summary> /// Representation of a routing instance. Wraps a router and a router db. /// </summary> public class Instance : IInstance { private readonly MultimodalRouter _router; private readonly Dictionary<string, int> _defaultSeconds; /// <summary> /// Creates a new routing instances. /// </summary> public Instance(MultimodalRouter router, int carTime = 15 * 60, int pedestrianTime = 10 * 60, int bicycleTime = 5 * 60) { _router = router; _defaultSeconds = new Dictionary<string, int>(); _defaultSeconds.Add("car", carTime); _defaultSeconds.Add("pedestrian", pedestrianTime); _defaultSeconds.Add("bicycle", bicycleTime); } /// <summary> /// Gets the routerdb. /// </summary> public RouterDb RouterDb { get { return _router.Router.Db; } } /// <summary> /// Gets meta-data about this instance. /// </summary> /// <returns></returns> public InstanceMeta GetMeta() { var meta = new InstanceMeta(); meta.Id = _router.Router.Db.Guid.ToString(); meta.Meta = _router.Router.Db.Meta; var metaProfiles = new List<ProfileMeta>(); foreach(var vehicle in _router.Router.Db.GetSupportedVehicles()) { foreach(var profile in vehicle.GetProfiles()) { var metric = "custom"; switch(profile.Metric) { case ProfileMetric.DistanceInMeters: metric = "distance"; break; case ProfileMetric.TimeInSeconds: metric = "time"; break; } metaProfiles.Add(new ProfileMeta() { Metric = metric, Name = profile.FullName }); } } meta.Profiles = metaProfiles.ToArray(); meta.Contracted = _router.Router.Db.GetContractedProfiles().ToArray(); return meta; } /// <summary> /// Returns true if the given profile is supported. /// </summary> public bool Supports(string profile) { return _router.Router.Db.SupportProfile(profile); } /// <summary> /// Calculates a routing along the given coordinates. /// </summary> public Result<Route> Calculate(string profileName, Coordinate[] coordinates) { var profile = _router.Router.Db.GetSupportedProfile(profileName); var points = new RouterPoint[coordinates.Length]; for(var i = 0; i < coordinates.Length; i++) { var result = _router.Router.TryResolve(profile, coordinates[i], 200); if (result.IsError) { result = _router.Router.TryResolve(profile, coordinates[i], 2000); } points[i] = result.Value; } if (!_router.Router.Db.HasContractedFor(profile)) { Logging.Logger.Log("Instance", Logging.TraceEventType.Warning, "RouterDb is not optimized for profile {0}, it doesn't contain a contracted graph for this profile.", profileName); } return _router.Router.TryCalculate(profile, points); } /// <summary> /// Calculates a heatmap. /// </summary> public Result<HeatmapResult> CalculateHeatmap(string profileName, Coordinate coordinate, int max) { var profile = _router.Router.Db.GetSupportedProfile(profileName); var point = _router.Router.Resolve(profile, coordinate, 200); return new Result<HeatmapResult>(_router.Router.CalculateHeatmap(profile, point, max)); } /// <summary> /// Calculates isochrones. /// </summary> public Result<List<Polygon>> CalculateIsochrones(string profileName, Coordinate coordinate, float[] limits) { var profile = _router.Router.Db.GetSupportedProfile(profileName); var point = _router.Router.Resolve(profile, coordinate, 200); return new Result<List<Polygon>>(_router.Router.CalculateIsochrones(profile, point, limits.ToList())); } /// <summary> /// Calculates a tree. /// </summary> public Result<Algorithms.Networks.Analytics.Trees.Models.Tree> CalculateTree(string profileName, Coordinate coordinate, int max) { var profile = _router.Router.Db.GetSupportedProfile(profileName); lock (_router) { var point = _router.Router.Resolve(profile, coordinate, 200); return new Result<Algorithms.Networks.Analytics.Trees.Models.Tree>(_router.Router.CalculateTree(profile, point, max)); } } /// <summary> /// Tries to calculate an earliest arrival route. /// </summary> public Result<Route> TryEarliestArrival(DateTime departureTime, string sourceProfileName, Coordinate sourceLocation, string targetProfileName, Coordinate targetLocation, Dictionary<string, object> parameters) { var sourceProfile = _router.Router.Db.GetSupportedProfile(sourceProfileName); var targetProfile = _router.Router.Db.GetSupportedProfile(targetProfileName); var sourcePoint = _router.Router.TryResolve(sourceProfile, sourceLocation, 1000); if (sourcePoint.IsError) { return sourcePoint.ConvertError<Route>(); } var targetPoint = _router.Router.TryResolve(targetProfile, targetLocation, 1000); if (targetPoint.IsError) { return targetPoint.ConvertError<Route>(); } int maxSecondsSource = 0; if (parameters.ContainsKey("sourceTime") && parameters["sourceTime"] is int && (int)parameters["sourceTime"] > 0) { // override the default source time. maxSecondsSource = (int)parameters["sourceTime"]; } else { // get the default source time. if (!_defaultSeconds.TryGetValue(sourceProfile.Name, out maxSecondsSource)) { maxSecondsSource = 30 * 60; } } int maxSecondsTarget = 0; if (parameters.ContainsKey("targetTime") && parameters["targetTime"] is int && (int)parameters["targetTime"] > 0) { // override the default target time. maxSecondsTarget = (int)parameters["targetTime"]; } else { // get the default target time. if (!_defaultSeconds.TryGetValue(targetProfile.Name, out maxSecondsTarget)) { maxSecondsTarget = 30 * 60; } } return _router.TryEarliestArrival(departureTime, sourcePoint.Value, sourceProfile, targetPoint.Value, targetProfile, new EarliestArrivalSettings() { MaxSecondsSource = maxSecondsSource, MaxSecondsTarget = maxSecondsTarget }); } } } <|start_filename|>src/Itinero.API/Models/InstanceMetaExtensions.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.IO; namespace Itinero.API.Models { /// <summary> /// Contains extension methods for the routerdb meta. /// </summary> public static class InstanceMetaExtensions { /// <summary> /// Converts the router db meta to json. /// </summary> public static void ToJson(this InstanceMeta routerDbMeta, TextWriter writer) { var jsonWriter = new IO.Json.JsonWriter(writer); jsonWriter.WriteOpen(); jsonWriter.WritePropertyName("id"); jsonWriter.WritePropertyValue(routerDbMeta.Id); if (routerDbMeta.Meta != null) { jsonWriter.WriteOpen(); foreach(var attribute in routerDbMeta.Meta) { jsonWriter.WritePropertyName(attribute.Key); jsonWriter.WritePropertyValue(attribute.Value); } jsonWriter.WriteClose(); } if (routerDbMeta.Profiles != null) { jsonWriter.WritePropertyName("Profiles"); jsonWriter.WriteArrayOpen(); for (var i = 0; i < routerDbMeta.Profiles.Length; i++) { var profile = routerDbMeta.Profiles[i]; jsonWriter.WriteArrayOpen(); jsonWriter.WriteOpen(); jsonWriter.WritePropertyName("name"); jsonWriter.WritePropertyValue(profile.Name); jsonWriter.WritePropertyName("metric"); jsonWriter.WritePropertyValue(profile.Metric.ToInvariantString()); jsonWriter.WriteClose(); jsonWriter.WriteArrayClose(); } jsonWriter.WriteArrayClose(); } if (routerDbMeta.Contracted != null) { jsonWriter.WritePropertyName("Profiles"); jsonWriter.WriteArrayOpen(); for (var i = 0; i < routerDbMeta.Contracted.Length; i++) { var profile = routerDbMeta.Contracted[i]; jsonWriter.WriteArrayOpen(); jsonWriter.WriteArrayValue(profile); jsonWriter.WriteArrayClose(); } jsonWriter.WriteArrayClose(); } } } } <|start_filename|>src/Itinero.API/Content/itinero.JSONP.js<|end_filename|> // itinero JSONP call wrapper // [wrapper for JSONP calls with DOM cleaning, fencing, timout handling] itinero = { DEFAULT: { JSONP_TIMEOUT: 100000 } }; itinero.JSONP = { // storage to keep track of unfinished JSONP calls fences: {}, callbacks: {}, timeouts: {}, timers: {}, // default callback routines late: function() {}, empty: function() {}, // init JSONP call call: function(source, callback_function, timeout_function, timeout, id, parameters) { // only one active JSONP call per id if (itinero.JSONP.fences[id] == true) return false; itinero.JSONP.fences[id] = true; // wrap timeout function itinero.JSONP.timeouts[id] = function (response) { try { timeout_function(response, parameters); } finally { itinero.JSONP.callbacks[id] = itinero.JSONP.late; // clean functions itinero.JSONP.timeouts[id] = itinero.JSONP.empty; itinero.JSONP.fences[id] = undefined; // clean fence } }; // wrap callback function itinero.JSONP.callbacks[id] = function (response) { clearTimeout(itinero.JSONP.timers[id]); // clear timeout timer itinero.JSONP.timers[id] = undefined; try { callback_function(response, parameters); // actual wrapped callback } finally { itinero.JSONP.callbacks[id] = itinero.JSONP.empty; // clean functions itinero.JSONP.timeouts[id] = itinero.JSONP.late; itinero.JSONP.fences[id] = undefined; // clean fence } }; // clean DOM var jsonp = document.getElementById('jsonp_'+id); if(jsonp) jsonp.parentNode.removeChild(jsonp); // add script to DOM var script = document.createElement('script'); script.type = 'text/javascript'; script.id = 'jsonp_' + id; script.src = source.replace(/%jsonp/, "itinero.JSONP.callbacks." + id); document.head.appendChild(script); // start timeout timer itinero.JSONP.timers[id] = setTimeout(itinero.JSONP.timeouts[id], timeout); return true; }, clear: function(id) { clearTimeout(itinero.JSONP.timers[id]); // clear timeout timer itinero.JSONP.callbacks[id] = itinero.JSONP.empty; // clean functions itinero.JSONP.timeouts[id] = itinero.JSONP.empty; itinero.JSONP.fences[id] = undefined; // clean fence // clean DOM var jsonp = document.getElementById('jsonp_'+id); if(jsonp) jsonp.parentNode.removeChild(jsonp); }, // reset all data reset: function() { itinero.JSONP.fences = {}; itinero.JSONP.callbacks = {}; itinero.JSONP.timeouts = {}; itinero.JSONP.timers = {}; } }; <|start_filename|>src/Itinero.API/Modules/UIModule.cs<|end_filename|> using Itinero.API.Instances; using Nancy; using System; namespace Itinero.API.Modules { /// <summary> /// A module with a testing UI. /// </summary> public class UIModule : NancyModule { public UIModule() { Get("/", _ => { var model = InstanceManager.GetMeta(); return View["instances", model]; }); Get("{instance}", _ => { // get instance and check if active. string instanceName = _.instance; IInstance instance; if (!InstanceManager.TryGet(instanceName, out instance)) { // oeps, instance not active! return Negotiate.WithStatusCode(HttpStatusCode.NotFound); } var center = instance.RouterDb.EstimateCenter(); var siteBase = this.Request.Url.SiteBase; dynamic model = new { Name = instanceName, SiteBase = siteBase, CenterLat = center.Latitude.ToInvariantString(), CenterLon = center.Longitude.ToInvariantString() }; return View["instance", model]; }); } } } <|start_filename|>src/Itinero.API/Bootstrapper.cs<|end_filename|> using Itinero.API.FileMonitoring; using Itinero.API.Instances; using Itinero.IO.Osm; using Itinero.Logging; using Itinero.Osm.Vehicles; using Itinero.Transit; using Itinero.Transit.Data; using OsmSharp.Streams; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Itinero.API { /// <summary> /// A boot strapper to load and reload instances. /// </summary> public static class Bootstrapper { private static List<IFilesMonitor> _fileMonitors = new List<IFilesMonitor>(); /// <summary> /// Initializes all routing instance from the configuration in the configuration file. /// </summary> public static void BootFromConfiguration(string path) { try { // register vehicle profiles. Vehicle.RegisterVehicles(); // load all .routerdb files. var dataDirectory = new DirectoryInfo(path); if (!dataDirectory.Exists) { throw new DirectoryNotFoundException( string.Format("Configured data directory doesn't exist: {0}", dataDirectory.FullName)); } Logger.Log("Bootstrapper", TraceEventType.Information, "Loading all routerdb's from path: {0}", dataDirectory.FullName); // load all relevant files. var routingFiles = dataDirectory.GetFiles("*.routerdb").Concat( dataDirectory.GetFiles("*.multimodaldb")); if (routingFiles.Count() == 0) { throw new DirectoryNotFoundException( string.Format("No .routerdb files found in {0}", dataDirectory.FullName)); } // load each routerdb on other threads. foreach (var file in routingFiles) { var thread = new Thread((state) => { var localFile = state as FileInfo; if (Bootstrapper.LoadInstance(localFile)) { var monitor = new FilesMonitor<FileInfo>((f) => { return Bootstrapper.LoadInstance(f); }, localFile); monitor.Start(); monitor.AddFile(file.FullName); _fileMonitors.Add(monitor); } }); thread.Start(file); } // check if there are folder with OSM-XML or OSM-PBF file. var subDirs = dataDirectory.EnumerateDirectories(); foreach(var subDir in subDirs) { var osmFiles = subDir.EnumerateFiles("*.osm").Concat( subDir.EnumerateFiles("*.osm.pbf")).ToArray(); if (osmFiles.Length > 0) { var thread = new Thread((state) => { var localDirectory = state as DirectoryInfo; if (Bootstrapper.LoadInstanceFromFolder(localDirectory)) { var monitor = new FilesMonitor<DirectoryInfo>((f) => { return Bootstrapper.LoadInstanceFromFolder(f); }, localDirectory); monitor.Start(); // add osm and osm-pbf files. foreach(var osmFile in osmFiles) { monitor.AddFile(osmFile.FullName); } foreach(var luaFile in subDir.EnumerateFiles("*.lua")) { monitor.AddFile(luaFile.FullName); } _fileMonitors.Add(monitor); } }); thread.Start(subDir); } } } catch (Exception ex) { Logger.Log("Bootstrapper", TraceEventType.Critical, "Failed to start service: {0}", ex.ToInvariantString()); } } /// <summary> /// Loads an instance from a routing file. /// </summary> public static bool LoadInstance(FileInfo file) { try { if (!file.Exists) { return false; } Logger.Log("Bootstrapper", TraceEventType.Information, "Loading instance {1} from: {0}", file.FullName, file.Name.GetNameUntilFirstDot()); if (file.Name.EndsWith("routerdb")) { RouterDb routerDb; using (var stream = File.OpenRead(file.FullName)) { routerDb = RouterDb.Deserialize(stream); } var multimodalDb = new MultimodalDb(routerDb, new TransitDb()); var multimodalRouter = new MultimodalRouter(multimodalDb, Itinero.Osm.Vehicles.Vehicle.Pedestrian.Fastest()); var instance = new Instances.Instance(multimodalRouter); InstanceManager.Register(file.Name.GetNameUntilFirstDot(), instance); } else if (file.Name.EndsWith("multimodaldb")) { MultimodalDb routerDb; using (var stream = File.OpenRead(file.FullName)) { routerDb = MultimodalDb.Deserialize(stream); } var multimodalRouter = new MultimodalRouter(routerDb, Itinero.Osm.Vehicles.Vehicle.Pedestrian.Fastest()); var instance = new Instances.Instance(multimodalRouter); InstanceManager.Register(file.Name.GetNameUntilFirstDot(), instance); } Logger.Log("Bootstrapper", TraceEventType.Information, "Loaded instance {1} from: {0}", file.FullName, file.Name.GetNameUntilFirstDot()); return true; } catch (Exception ex) { Logger.Log("Bootstrapper", TraceEventType.Critical, "Failed to load file {0}: {1}", file, ex.ToInvariantString()); } return false; } /// <summary> /// Loads an instance from a folder. /// </summary> /// <returns></returns> public static bool LoadInstanceFromFolder(DirectoryInfo folder) { try { if (!folder.Exists) { return false; } Logger.Log("Bootstrapper", TraceEventType.Information, "Loading instance {1} from: {0}", folder.FullName, folder.Name); var profiles = new List<Itinero.Profiles.Vehicle>(); foreach (var luaFile in folder.EnumerateFiles("*.lua")) { try { using (var stream = luaFile.OpenRead()) { profiles.Add(Itinero.Profiles.DynamicVehicle.LoadFromStream(stream)); } Logger.Log("Bootstrapper", TraceEventType.Information, "Loaded profile {0}.", luaFile.FullName); } catch(Exception ex) { Logger.Log("Bootstrapper", TraceEventType.Error, "Failed loading profile {0}:{1}", luaFile.FullName, ex.ToInvariantString()); } } if (profiles.Count == 0) { Logger.Log("Bootstrapper", TraceEventType.Information, "Loading instance {1} from: {0}, no vehicle profiles found or they could not be loaded.", folder.FullName, folder.Name); return true; } var osmFile = folder.EnumerateFiles("*.osm").Concat( folder.EnumerateFiles("*.osm.pbf")).First(); var routerDb = new RouterDb(); using (var osmFileStream = osmFile.OpenRead()) { OsmStreamSource source; if (osmFile.FullName.EndsWith(".osm")) { source = new XmlOsmStreamSource(osmFileStream); } else { source = new PBFOsmStreamSource(osmFileStream); } routerDb.LoadOsmData(source, profiles.ToArray()); } var multimodalDb = new MultimodalDb(routerDb, new TransitDb()); var multimodalRouter = new MultimodalRouter(multimodalDb, Itinero.Osm.Vehicles.Vehicle.Pedestrian.Fastest()); var instance = new Instances.Instance(multimodalRouter); InstanceManager.Register(folder.Name, instance); Logger.Log("Bootstrapper", TraceEventType.Information, "Loaded instance {1} from: {0}", folder.FullName, folder.Name); return true; } catch (Exception ex) { Logger.Log("Bootstrapper", TraceEventType.Critical, "Failed to load instance {1} from: {0}, {2}", folder.FullName, folder.Name, ex.ToInvariantString()); } return false; } /// <summary> /// Gets the substring until the first dot. /// </summary> private static string GetNameUntilFirstDot(this string name) { var dotIdx = name.IndexOf('.'); if (dotIdx == 0) { throw new Exception("No '.' found in file name."); } return name.Substring(0, dotIdx); } } } <|start_filename|>src/Itinero.API/FileMonitoring/IFilesMonitor.cs<|end_filename|> namespace Itinero.API.FileMonitoring { /// <summary> /// A non-generic abstract representation of a files monitor. /// </summary> public interface IFilesMonitor { /// <summary> /// Starts monitoring. /// </summary> void Start(); /// <summary> /// Stops monitoring. /// </summary> void Stop(); } } <|start_filename|>src/Itinero.API/Extensions.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2017 <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 Itinero.LocalGeo; namespace Itinero.API { /// <summary> /// Contains some extension methods. /// </summary> public static class Extensions { /// <summary> /// Estimates the center location of the given routerdb. /// </summary> public static Coordinate EstimateCenter(this RouterDb db) { var latitudeTotal = 0d; var longitudeTotal = 0d; var count = 0; uint stepSize = 25; for(uint v = 0; v < db.Network.VertexCount; v += stepSize) { var coordinate = db.Network.GetVertex(v); count++; latitudeTotal += coordinate.Latitude; longitudeTotal += coordinate.Longitude; } return new Coordinate((float)(latitudeTotal / count), (float)(longitudeTotal / count)); } } } <|start_filename|>src/Itinero.API/Instances/InstanceManager.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Itinero.API.Models; using System.Collections.Generic; using System.Linq; namespace Itinero.API.Instances { /// <summary> /// Holds and manages routing instances. /// </summary> public static class InstanceManager { /// <summary> /// Holds the routing service instances. /// </summary> private static readonly Dictionary<string, IInstance> _items = new Dictionary<string, IInstance>(); /// <summary> /// Gets meta-data. /// </summary> /// <returns></returns> public static Meta GetMeta() { return new Meta() { Instances = _items.Keys.ToArray() }; } /// <summary> /// Returns true if the given instance is active. /// </summary> public static bool IsActive(string name) { return _items.ContainsKey(name); } /// <summary> /// Returns true if there is at least one instance. /// </summary> public static bool HasInstances => _items.Count > 0; /// <summary> /// Returns the routing module instance with the given name. /// </summary> public static bool TryGet(string name, out IInstance instance) { return _items.TryGetValue(name, out instance); } /// <summary> /// Registers a new instance. /// </summary> public static void Register(string name, IInstance instance) { _items[name] = instance; } } } <|start_filename|>src/Itinero.API/Modules/MetaModule.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Nancy; using Itinero.API.Instances; using System; namespace Itinero.API.Modules { /// <summary> /// A module responsible for service meta-data. /// </summary> public class MetaModule : NancyModule { /// <summary> /// Creates a new meta model. /// </summary> public MetaModule() { Get("meta", _ => { return this.DoGetMeta(_); }); Get("{instance}/meta", _ => { return this.DoGetInstanceMeta(_); }); } /// <summary> /// Executes the get meta call. /// </summary> private object DoGetMeta(dynamic _) { this.EnableCors(); return InstanceManager.GetMeta(); } /// <summary> /// Executes the get meta call for an instance. /// </summary> private object DoGetInstanceMeta(dynamic _) { this.EnableCors(); // get instance and check if active. string instanceName = _.instance; IInstance instance; if (!InstanceManager.TryGet(instanceName, out instance)) { // oeps, instance not active! return Negotiate.WithStatusCode(HttpStatusCode.NotFound); } return Negotiate.WithContentType("application/json").WithModel(instance.GetMeta()); } } } <|start_filename|>src/Itinero.API/FileMonitoring/FileMonitor.cs<|end_filename|> using System; using System.IO; using System.Threading; namespace Itinero.API.FileMonitoring { /// <summary> /// Represents a file monitor that continually monitors a file for changes. /// </summary> internal class FileMonitor { private const int MonitorInterval = 9 * 1000; private readonly FileInfo _fileInfo; // Holds the fileinfo of the file to monitor. private readonly Timer _timer; // Holds the timer to poll file changes. /// <summary> /// Creates a new file monitor for the given file. /// </summary> /// <param name="path"></param> public FileMonitor(string path) { _fileInfo = new FileInfo(path); _timestamp = _fileInfo.LastWriteTime.Ticks; _timer = new Timer(Tick, null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Starts monitoring. /// </summary> public void Start() { _fileInfo.Refresh(); _timestamp = _fileInfo.LastWriteTime.Ticks; _timer.Change(MonitorInterval, MonitorInterval); } /// <summary> /// Stops monitoring. /// </summary> public void Stop() { _timer.Change(Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Returns true if the file is available for reading and not in a state that is changing. /// </summary> /// <returns></returns> public bool IsAvailable() { lock (_sync) { _fileInfo.Refresh(); if (!_fileInfo.Exists) { return false; } return !IsFileLocked(_fileInfo); } } /// <summary> /// An action to report that the file has changed and is accessible. /// </summary> public Action<FileMonitor> FileChanged { get; set; } private long _timestamp; // Holds the last modified timestamp. private readonly object _sync = new object(); // Holds an object that is used to sync the timer. /// <summary> /// Called when the timer ticks. /// </summary> /// <param name="state"></param> private void Tick(object state) { lock (_sync) { if (FileChanged != null) { _fileInfo.Refresh(); if (_fileInfo.Exists) { if (_timestamp != _fileInfo.LastWriteTime.Ticks) { // file has been written to. _timestamp = _fileInfo.LastWriteTime.Ticks; FileChanged(this); } } } } } /// <summary> /// Not so nice code to check if a file is locked. /// </summary> /// <param name="file"></param> /// <returns></returns> private static bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.Read); } catch { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { stream?.Dispose(); } //file is not locked return false; } } } <|start_filename|>src/Itinero.API/Instances/IInstance.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Itinero.Algorithms.Networks.Analytics.Heatmaps; using Itinero.API.Models; using Itinero.LocalGeo; using System; using System.Collections.Generic; namespace Itinero.API.Instances { /// <summary> /// Abstract representation of a routing instance. /// </summary> public interface IInstance { /// <summary> /// Gets meta-data about the instance with the given name. /// </summary> InstanceMeta GetMeta(); /// <summary> /// Returns true if the given profile is supported. /// </summary> bool Supports(string profile); /// <summary> /// Gets the routerdb. /// </summary> RouterDb RouterDb { get; } /// <summary> /// Calculates a route along the given coordinates. /// </summary> Result<Route> Calculate(string profile, Coordinate[] coordinates); /// <summary> /// Calculates a heatmap. /// </summary> Result<HeatmapResult> CalculateHeatmap(string profile, Coordinate coordinate, int max); /// <summary> /// Calculates isochrones. /// </summary> Result<List<Polygon>> CalculateIsochrones(string profile, Coordinate coordinate, float[] limits); /// <summary> /// Calculates a tree. /// </summary> Result<Algorithms.Networks.Analytics.Trees.Models.Tree> CalculateTree(string profile, Coordinate coordinate, int max); /// <summary> /// Calculates a route from source to target. /// </summary> Result<Route> TryEarliestArrival(DateTime departureTime, string sourceProfile, Coordinate sourceLocation, string targetProfile, Coordinate targetLocation, Dictionary<string, object> parameters); } } <|start_filename|>src/Itinero.API/Responses/GeoJsonResponseProcessor.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Nancy; using Nancy.Responses.Negotiation; using Itinero.API.Reponses; using System; using System.Collections.Generic; using Itinero.LocalGeo; namespace Itinero.API.Responses { /// <summary> /// A response processor to format GeoJSON. /// </summary> public class GeoJsonResponseProcessor : IResponseProcessor { private static readonly IEnumerable<Tuple<string, MediaRange>> extensionMappings = new[] { new Tuple<string, MediaRange>("json", new MediaRange("application/json")) }; /// <summary> /// Creates a new GeoJSON repsonse processor. /// </summary> public GeoJsonResponseProcessor() { } /// <summary> /// Gets a set of mappings that map a given extension (such as .json) /// to a media range that can be sent to the client in a vary header. /// </summary> public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get { return extensionMappings; } } /// <summary> /// Determines whether the the processor can handle a given content type and model /// </summary> /// <param name="requestedMediaRange">Content type requested by the client</param> /// <param name="model">The model for the given media range</param> /// <param name="context">The nancy context</param> /// <returns>A ProcessorMatch result that determines the priority of the processor</returns> public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { if (model is Route) { if (IsExactJsonContentType(requestedMediaRange)) { return new ProcessorMatch { ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.ExactMatch }; } if (IsWildcardJsonContentType(requestedMediaRange)) { return new ProcessorMatch { ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.NonExactMatch }; } } if (model is List<Polygon>) { if (IsExactJsonContentType(requestedMediaRange)) { return new ProcessorMatch { ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.ExactMatch }; } if (IsWildcardJsonContentType(requestedMediaRange)) { return new ProcessorMatch { ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.NonExactMatch }; } } if (model is List<Tuple<float, float, List<Coordinate>>>) { if (IsExactJsonContentType(requestedMediaRange)) { return new ProcessorMatch { ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.ExactMatch }; } if (IsWildcardJsonContentType(requestedMediaRange)) { return new ProcessorMatch { ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.NonExactMatch }; } } return new ProcessorMatch { ModelResult = MatchResult.DontCare, RequestedContentTypeResult = MatchResult.NoMatch }; } /// <summary> /// Process the response /// </summary> /// <param name="requestedMediaRange">Content type requested by the client</param> /// <param name="model">The model for the given media range</param> /// <param name="context">The nancy context</param> /// <returns>A response</returns> public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { if (model is Route) { return new RouteGeoJsonResponse(model as Route); } if (model is List<Polygon>) { return new PolygonsGeoJsonResponse(model as List<Polygon>); } if (model is List<Tuple<float, float, List<Coordinate>>>) { return new LinesGeoJsonResponse(model as List<Tuple<float, float, List<Coordinate>>>); } throw new ArgumentOutOfRangeException("GeoJsonResponseProcessor can only process Routes."); } private static bool IsExactJsonContentType(MediaRange requestedContentType) { if (requestedContentType.Type.IsWildcard && requestedContentType.Subtype.IsWildcard) { return true; } return requestedContentType.Matches("application/json") || requestedContentType.Matches("text/json"); } private static bool IsWildcardJsonContentType(MediaRange requestedContentType) { if (!requestedContentType.Type.IsWildcard && !string.Equals("application", requestedContentType.Type, StringComparison.OrdinalIgnoreCase)) { return false; } if (requestedContentType.Subtype.IsWildcard) { return true; } var subtypeString = requestedContentType.Subtype.ToString(); return (subtypeString.StartsWith("vnd", StringComparison.OrdinalIgnoreCase) && subtypeString.EndsWith("+json", StringComparison.OrdinalIgnoreCase)); } } } <|start_filename|>src/Itinero.API/NancyExtensions.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Nancy; namespace Itinero.API { /// <summary> /// Contains extensions for nancy. /// </summary> public static class NancyExtensions { /// <summary> /// Adds cors headers to reposonse. /// </summary> public static void EnableCors(this NancyModule module) { module.After.AddItemToEndOfPipeline(x => { x.Response.WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "POST,GET") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type"); }); } } } <|start_filename|>src/Itinero.API/FileMonitoring/FilesMonitor.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Itinero.API.FileMonitoring { /// <summary> /// A file monitor monitoring all files relevant to one instance. /// </summary> public class FilesMonitor<T> : IFilesMonitor { private readonly int _intervalInMillis; private readonly List<FileMonitor> _filesToMonitor; // The list of files to monitor. private bool _hasChanged; // Holds the has changed flag. private long _lastChange; // Holds the last change. private readonly Timer _timer; // Holds the timer. private readonly Func<T, bool> _trigger; // Called when file(s) have changed. private readonly T _param; // Holds the parameters to pass to the trigger. private readonly object _sync = new object(); // Holds the sync object. /// <summary> /// Creates a new instance monitor. /// </summary> public FilesMonitor(Func<T, bool> trigger, T param, int intervalInMillis = 60 * 1000) { _filesToMonitor = new List<FileMonitor>(); _hasChanged = false; _lastChange = DateTime.Now.Ticks; _trigger = trigger; _param = param; _intervalInMillis = intervalInMillis; _timer = new Timer(Tick, null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Starts to monitor. /// </summary> public void Start() { _hasChanged = false; _lastChange = DateTime.Now.Ticks; _timer.Change(_intervalInMillis, _intervalInMillis); foreach (var monitor in _filesToMonitor) { monitor.FileChanged += monitor_FileChanged; monitor.Start(); } } /// <summary> /// Called when one for the file monitors detects a change. /// </summary> /// <param name="sender"></param> void monitor_FileChanged(FileMonitor sender) { lock (_sync) { _hasChanged = true; _lastChange = DateTime.Now.Ticks; } } /// <summary> /// Stops monitoring. /// </summary> public void Stop() { foreach (var monitor in _filesToMonitor) { monitor.Stop(); // ReSharper disable once DelegateSubtraction // It is okay here: http://stackoverflow.com/questions/11180068/delegate-subtraction-has-unpredictable-result-in-resharper-c monitor.FileChanged -= monitor_FileChanged; } _timer.Change(Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Adds a new file to monitor. /// </summary> /// <param name="path"></param> public void AddFile(string path) { if (File.Exists(path)) { _filesToMonitor.Add(new FileMonitor(path)); } } /// <summary> /// Called when the timer ticks. /// </summary> private void Tick(object state) { lock (_sync) { if (_hasChanged) { var timeSpan = new TimeSpan(DateTime.Now.Ticks - _lastChange); if (timeSpan.TotalMilliseconds > (float)_intervalInMillis / 2) { // more than 4 mins ago when the last change was reported. bool isAvailable = true; foreach (var monitor in _filesToMonitor) { if (!monitor.IsAvailable()) { _hasChanged = true; _lastChange = DateTime.Now.Ticks; isAvailable = false; break; } } if (isAvailable) { // call reload. _hasChanged = false; if (!_trigger(_param)) { // loading failed, try again in 5 mins. _hasChanged = true; _lastChange = DateTime.Now.Ticks; } } } } } } } } <|start_filename|>build.bat<|end_filename|> dotnet restore dotnet build ./src/Itinero.API <|start_filename|>src/Itinero.API/Startup.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Nancy.Owin; using Microsoft.Extensions.Configuration; namespace Itinero.API { public class Startup { public IConfigurationRoot Configuration { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true); if (env.IsEnvironment("Development")) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. //builder.AddApplicationInsightsSettings(true); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); var routingFilePath = Configuration["routingfilepath"]; Bootstrapper.BootFromConfiguration(routingFilePath); } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseOwin(x => x.UseNancy()); } } } <|start_filename|>src/Itinero.API/Modules/MultimodalModule.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Itinero.API.Instances; using Itinero.LocalGeo; using Itinero.Logging; using Itinero.Profiles; using Nancy; using System; using System.Collections.Generic; using System.Globalization; namespace Itinero.API.Modules { /// <summary> /// A module responsible for routing calls. /// </summary> public class MultimodalModule : NancyModule { public MultimodalModule() { Get("{instance}/multimodal", _ => { return this.DoRouting(_); }); } private object DoRouting(dynamic _) { try { this.EnableCors(); // get instance and check if active. string instanceName = _.instance; IInstance instance; if (!InstanceManager.TryGet(instanceName, out instance)) { // oeps, instance not active! return Negotiate.WithStatusCode(HttpStatusCode.NotFound); } if (string.IsNullOrWhiteSpace(this.Request.Query.loc.ToString())) { // no loc parameters. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("loc parameter not found or request invalid."); } var locs = this.Request.Query.loc.ToString().Split(','); if (locs.Length < 4) { // less than two loc parameters. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("only one loc parameter found or request invalid."); } var coordinates = new Coordinate[locs.Length / 2]; for (int idx = 0; idx < coordinates.Length; idx++) { float lat, lon = 0f; if (float.TryParse(locs[idx * 2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lat) && float.TryParse(locs[idx * 2 + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lon)) { // parsing was successful. coordinates[idx] = new Coordinate(lat, lon); } else { // invalid formatting. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("location coordinates are invalid."); } } // get profile. string profilesParameter = "car"; // assume profile is the default. if (!string.IsNullOrWhiteSpace(this.Request.Query.profile)) { // a vehicle was defined. profilesParameter = this.Request.Query.profile; } var profiles = new List<string>(); var profileNames = profilesParameter.Split('|'); for (var i = 0; i < profileNames.Length; i++) { // check for support for the given vehicle. if (!instance.Supports(profileNames[i])) { // vehicle is not supported. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel( string.Format("Profile with name '{0}' is unsupported by this instance.", profileNames[i])); } profiles.Add(profileNames[i]); } // parse time. if (string.IsNullOrWhiteSpace(this.Request.Query.time)) { // there is a format field. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("No valid time parameter found."); } DateTime dt; string pattern = "yyyyMMddHHmm"; if (!DateTime.TryParseExact(this.Request.Query.time, pattern, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { // could not parse date. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel( string.Format("No valid time parameter found, could not parse date: {0}. Expected to be in format yyyyMMddHHmm.")); } var sourceTime = -1; var targetTime = -1; if (this.Request.Query.locTime != null) { var locTime = this.Request.Query.locTime.Split(','); if (locTime.Length >= 2) { if (!int.TryParse(locTime[0], out sourceTime) || !int.TryParse(locTime[locTime.Length - 1], out targetTime)) { // parsing failed. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("location timings present but could not be parsed."); } } } // build parameters. var parameters = new Dictionary<string, object>(); parameters["sourceTime"] = sourceTime; parameters["targetTime"] = targetTime; // calculate route. var route = instance.TryEarliestArrival(dt, profiles[0], coordinates[0], profiles[profiles.Count - 1], coordinates[coordinates.Length - 1], parameters); if (route == null || route.IsError) { // route could not be calculated. return Negotiate.WithStatusCode(HttpStatusCode.NoContent).WithModel( string.Format("Route could not be calculated: {0}", route.ErrorMessage)); } return route.Value; } catch (Exception) { // an unhandled exception! return Negotiate.WithStatusCode(HttpStatusCode.InternalServerError); } } } } <|start_filename|>src/Itinero.API/Modules/RoutingModule.cs<|end_filename|> // The MIT License (MIT) // Copyright (c) 2016 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE using Nancy; using Itinero.API.Instances; using Itinero.LocalGeo; namespace Itinero.API.Modules { /// <summary> /// A module responsible for routing calls. /// </summary> public class RoutingModule : NancyModule { public RoutingModule() { Get("{instance}/routing", _ => { return this.DoRouting(_); }); } private object DoRouting(dynamic _) { this.EnableCors(); // get instance and check if active. string instanceName = _.instance; IInstance instance; if (!InstanceManager.TryGet(instanceName, out instance)) { // oeps, instance not active! return Negotiate.WithStatusCode(HttpStatusCode.NotFound); } if (string.IsNullOrWhiteSpace(this.Request.Query.loc.ToString())) { // no loc parameters. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("loc parameter not found or request invalid."); } var locs = this.Request.Query.loc.ToString().Split(','); if (locs.Length < 4) { // less than two loc parameters. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("only one loc parameter found or request invalid."); } var coordinates = new Coordinate[locs.Length / 2]; for (int idx = 0; idx < coordinates.Length; idx++) { float lat, lon = 0f; if (float.TryParse(locs[idx * 2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lat) && float.TryParse(locs[idx * 2 + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lon)) { // parsing was successful. coordinates[idx] = new Coordinate(lat, lon); } else { // invalid formatting. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel("location coordinates are invalid."); } } // get profile. string profileName = "car"; // assume car is the default. if (!string.IsNullOrWhiteSpace(this.Request.Query.profile)) { // a vehicle was defined. profileName = this.Request.Query.profile; } if (!instance.Supports(profileName)) {// vehicle not found or not registered. return Negotiate.WithStatusCode(HttpStatusCode.NotAcceptable).WithModel( string.Format("Profile with name '{0}' not found.", profileName)); } // tries to calculate the given route. var result = instance.Calculate(profileName, coordinates); if (result.IsError) { return Negotiate.WithStatusCode(HttpStatusCode.NotFound); } return result.Value; } } } <|start_filename|>src/Itinero.API/Content/itinero.api.js<|end_filename|> // API MANAGEMENT. // an interface to the itinero-API. itinero.api = { // defines different vehicle options. Vehicles: { Pedestrian: 'pedestrian', Bicycle: 'bicycle', Car: 'car' }, id: 1, // sends a requests for multimodal route. multimodal: function (url, vehicles, time, locations, callback, error, context) { // increase request id. this.id++; var requestString = '/multimodal?callback=%jsonp'; // add vehicle parameter. requestString += '&vehicle=' + vehicles[0]; for (var i = 1; i < vehicles.length; i++) { requestString = requestString + '|' + vehicles[i]; } // add time parameter. requestString = requestString + '&time=' + time.getFullYear() + itinero.Utils.pad(time.getMonth() + 1, 2) + itinero.Utils.pad(time.getDate(), 2) + itinero.Utils.pad(time.getHours(), 2) + itinero.Utils.pad(time.getMinutes(), 2); for (var i = 0; i < locations.length; i++) { requestString += '&loc=' + locations[i].lat.toFixed(6) + ',' + locations[i].lon.toFixed(6); } // aad instructions. requestString = requestString + '&instructions=true' // execute JSONP request. var currentId = this.id; itinero.JSONP.call( url + requestString, function (response) { // success. $.proxy(callback, context)(response, currentId); }, function (response) { // timeout. $.proxy(error, context)(response, currentId); }, itinero.DEFAULT.JSONP_TIMEOUT, 'route' + this.id, {} ); }, // sends a requests for multimodal route. routing: function (url, options, callback, error, context) { // increase request id. this.id++; var requestString = '/routing?callback=%jsonp'; // add vehicle parameter. requestString += '&profile=' + options.profile; // add locations. for (var i = 0; i < options.locations.length; i++) { requestString += '&loc=' + options.locations[i].lat.toFixed(6) + ',' + options.locations[i].lon.toFixed(6); } // sort. if (options.sort) { requestString += '&sort=true'; } // instructions. if (options.instructions) { requestString += '&instructions=true'; } // execute JSONP request. var currentId = this.id; itinero.JSONP.call( url + requestString, function (response) { // success. $.proxy(callback, context)(response, currentId); }, function (response) { // timeout. $.proxy(error, context)(response, currentId); }, itinero.DEFAULT.JSONP_TIMEOUT, 'route' + this.id, {} ); }, // sends a requests for multimodal route. alongjustone: function (url, vehicles, locations, callback, error, context) { // increase request id. this.id++; var requestString = '/alongjustone?callback=%jsonp'; // add vehicle parameter. requestString += '&vehicle=' + vehicles[0]; for (var i = 1; i < vehicles.length; i++) { requestString = requestString + '|' + vehicles[i]; } // add time parameter. for (var i = 0; i < locations.length; i++) { requestString += '&loc=' + locations[i].lat.toFixed(6) + ',' + locations[i].lon.toFixed(6); } // execute JSONP request. var currentId = this.id; itinero.JSONP.call( url + requestString, function (response) { // success. $.proxy(callback, context)(response, currentId, locations); }, function (response) { // timeout. $.proxy(error, context)(response, currentId); }, itinero.DEFAULT.JSONP_TIMEOUT, 'route' + this.id, {} ); } };
elecay/routing-api
<|start_filename|>lib/v-blur.js<|end_filename|> function createDirective (opts = {}) { const options = Object.assign({ opacity: 0.5, filter: 'blur(1.5px)', transition: 'all .2s linear' }, opts) // Note: We attach the options to the exposed object to allow changing the // options dynamically after directive instantiation. const directive = { options } directive.blur = function (el, bindingValue) { if (typeof bindingValue !== 'boolean' && typeof bindingValue !== 'object') { throw new Error( 'Expected directive binding value type to be a boolean or an object but found ' + `${typeof bindingValue} instead` ) } if (typeof bindingValue === 'boolean') { bindingValue = { isBlurred: bindingValue } } const opacity = bindingValue.opacity || options.opacity const filter = bindingValue.filter || options.filter const transition = bindingValue.transition || options.transition el.style.opacity = bindingValue.isBlurred ? opacity : 1 el.style.filter = bindingValue.isBlurred ? filter : 'none' el.style.transition = transition el.style.pointerEvents = bindingValue.isBlurred ? 'none' : 'auto'; el.style.userSelect = bindingValue.isBlurred ? 'none' : 'auto' ; } directive.bind = function (el, binding) { directive.blur(el, binding.value) } directive.update = function (el, binding) { directive.blur(el, binding.value) } return directive } export default createDirective
ndelvalle/v-blur
<|start_filename|>example/example-3d.js<|end_filename|> "use strict" var shell = require("gl-now")({tickRate:2}) var camera = require("game-shell-orbit-camera")(shell) var mat4 = require("gl-matrix").mat4 var createSimplicialComplex = require("gl-simplicial-complex") var triangulation = require("../delaunay.js")(3) var sc = require("simplicial-complex") var createAxes = require("gl-axes") var mesh, axes function finiteVertex(c) { return (c[0] > 3) && (c[1] > 3) } var tt = -1.0 function updateTriangulation() { var randPoint = [ 2*Math.random()-1, 2*Math.random()-1, 2*Math.random()-1 ] //var randPoint = [tt,tt,tt] //tt += 0.1 triangulation.insert(randPoint) var cells = sc.skeleton(triangulation.cells, 1)//.filter(finiteVertex) var points = triangulation.points for(var i=4; i<points.length; ++i) { cells.push([i]) } mesh.update({ cells: cells, positions: points, pointSize: 5, meshColor: [0,0,0] }) } shell.on("gl-init", function() { var gl = shell.gl gl.enable(gl.DEPTH_TEST) mesh = createSimplicialComplex(gl, {cells: [], positions: []}) axes = createAxes(shell.gl, {bounds: [[-1,-1,-1],[1,1,1]], tickSpacing: [0.1,0.1,0.1], gridColor:[0.5,0.5,0.5]}) //setInterval(updateTriangulation, 2000) }) shell.on("tick", function() { if(shell.press("space")) { updateTriangulation() } }) shell.on("gl-render", function() { var cameraParameters = { view: camera.view(), projection: mat4.perspective(mat4.create(), Math.PI/4.0, shell.width/shell.height, 0.1, 1000.0) } mesh.draw(cameraParameters) axes.draw(cameraParameters) }) <|start_filename|>delaunay.js<|end_filename|> "use strict" var iota = require("iota-array") var orientation = require("robust-orientation") var pointInSimplex = require("robust-point-in-simplex") var inSphere = require("robust-in-sphere") module.exports = createDelaunayTriangulation function Simplex(triangulation, vertices, children, next, prev) { this.triangulation = triangulation this.vertices = vertices this.children = children this.next = next this.prev = prev } var proto = Simplex.prototype proto.insert = function(p) { if(this.children) { for(var i=0; i<this.children.length; ++i) { if(this.children[i].contains(this.triangulation.points[p])) { this.children[i].insert(p) } } } else { //Unlink from list this.prev.next = this.next this.next.prev = this.prev this.next = this.prev = null //Add child this.children = [] for(var i=this.vertices.length-1; i>=0; --i) { //Remove from dual var v = this.vertices[i] var d = this.triangulation._dual[v] for(var j=d.length-1; j>=0; --j) { if(d[j] === this) { d[j] = d[d.length-1] d.pop() break } } //Add child var nv = this.vertices.slice() nv[i] = p var child = new Simplex(this.triangulation, nv, null, this.triangulation.next, this.triangulation) if(!child.degenerate()) { this.children.push(child) this.triangulation.next.prev = child this.triangulation.next = child for(var j=0; j<nv.length; ++j) { this.triangulation._dual[nv[j]].push(child) } } } } } proto.contains = function(p) { var pointList = new Array(this.vertices.length) for(var i=0; i<this.vertices.length; ++i) { pointList[i] = this.triangulation.points[this.vertices[i]] } return pointInSimplex(pointList, p) >= 0 } proto.degenerate = function() { var pointList = new Array(this.vertices.length) for(var i=0; i<this.vertices.length; ++i) { pointList[i] = this.triangulation.points[this.vertices[i]] } return orientation.apply(undefined, pointList) === 0 } function DelaunayTriangulation(points, dual, root) { this.points = points this._dual = dual this._root = root this.next = this this.prev = this } var dproto = DelaunayTriangulation.prototype dproto.dual = function(v) { var d = this._dual[v] var r = [] for(var i=0; i<d.length; ++i) { r.push(d[i].vertices) } return r } function removeFromDual(triangulation, simplex) { for(var i=0; i<simplex.vertices.length; ++i) { var d = triangulation._dual[simplex.vertices[i]] for(var j=0; j<d.length; ++j) { if(d[j] === simplex) { d[j] = d[d.length-1] d.pop() break } } } } dproto.insert = function(p) { var v = this.points.length this.points.push(p) this._dual.push([]) this._root.insert(v) //Fix up delaunay condition var to_visit = this._dual[v].slice() while(to_visit.length > 0) { var c = to_visit[to_visit.length-1] to_visit.pop() if(c.children) { continue } //Get opposite simplex var points = new Array(c.vertices.length+1) var v_sum = 0 for(var i=0; i<c.vertices.length; ++i) { points[i] = this.points[c.vertices[i]] v_sum ^= c.vertices[i] } //Walk over simplex vertices var i = c.vertices.indexOf(v) var d = this._dual[c.vertices[(i+1)%c.vertices.length]] var opposite var opposite_index search_opposite: for(var j=0; j<d.length; ++j) { opposite = d[j] if(opposite === c) { continue } opposite_index = v_sum ^ v for(var k=0; k<opposite.vertices.length; ++k) { opposite_index ^= opposite.vertices[k] if(c.vertices[k] !== v && opposite.vertices.indexOf(c.vertices[k]) < 0) { continue search_opposite } } //Check if legal points[c.vertices.length] = this.points[opposite_index] var s = inSphere.apply(undefined, points) if(s > 0) { //TODO: Test if flip is valid //Unlink cells removeFromDual(this, c) c.children = [] c.next.prev = c.prev c.prev.next = c.next c.next = c.prev = null removeFromDual(this, opposite) opposite.children = [] opposite.next.prev = opposite.prev opposite.prev.next = opposite.next opposite.next = opposite.prev = null for(var k=0; k<c.vertices.length; ++k) { if(c.vertices[k] === v) { continue } var nv = c.vertices.slice() nv[k] = opposite_index //Create and link cell var nchild = new Simplex(this, nv, null, this.next, this) this.next.prev = nchild this.next = nchild for(var l=0; l<nv.length; ++l) { this._dual[nv[l]].push(nchild) } //Add to child pointers c.children.push(nchild) opposite.children.push(nchild) //Mark to visit to_visit.push(nchild) } } } } } dproto.locate = function(p) { var c = this._root while(c.children) { for(var i=0; i<c.children.length; ++i) { if(c.children[i].contains(p)) { c = c.children[i] break } } } return c.vertices } Object.defineProperty(dproto, "cells", { get: function() { var r = [] for(var cur=this.next; cur !== this; cur = cur.next) { r.push(cur.vertices) } return r } }) function createBoundingSimplex(dimension) { var result = new Array(dimension+1) for(var i=0; i<=dimension; ++i) { result[i] = new Array(dimension) } for(var i=1; i<=dimension; ++i) { result[i][i-1] = 10 for(var j=0; j<i-1; ++j) { result[i][j] = 0.0 } for(var j=0; j<i; ++j) { result[j][i-1] = -10 } } return result } function createDelaunayTriangulation(dimension, points) { var bounds = createBoundingSimplex(dimension) var root = new Simplex(null, iota(dimension+1), null, null, null) var dual = new Array(dimension+1) for(var i=0; i<dual.length; ++i) { dual[i] = [root] } var triangulation = new DelaunayTriangulation(bounds, dual, root) root.triangulation = triangulation root.next = root.prev = triangulation triangulation.next = triangulation.prev = root if(points) { for(var i=0; i<points.length; ++i) { triangulation.insert(points[i]) } } return triangulation } <|start_filename|>test/test.js<|end_filename|> "use strict" var tape = require("tape") var createTriangulation = require("../delaunay.js") tape("2d delaunay", function(t) { var tri = createTriangulation(2) tri.insert([0,0]) tri.insert([0,1]) tri.insert([1,0]) t.equals(tri.points.length, 6) t.end() }) <|start_filename|>example/example-2d.js<|end_filename|> "use strict" var shell = require("game-shell")() var triangulation = require("../delaunay")(2) var canvas var context shell.on("init", function() { canvas = document.createElement("canvas") canvas.width = shell.width canvas.height = shell.height context = canvas.getContext("2d") shell.element.appendChild(canvas) }) shell.on("resize", function(w, h) { canvas.width = w canvas.height = h }) shell.on("tick", function() { if(shell.wasDown("mouse-1")) { var w = canvas.width var h = canvas.height triangulation.insert([shell.mouseX/w, shell.mouseY/h]) } }) shell.on("render", function() { var w = canvas.width var h = canvas.height var mouse = [shell.mouseX/w, shell.mouseY/h] context.setTransform( w, 0, 0, h, 0, 0) context.fillStyle = "#fff" context.fillRect(0,0,w,h) context.strokeStyle = "#000" context.lineWidth = Math.min(1.0/w, 1.0/h) var cells = triangulation.cells var points = triangulation.points var cell = triangulation.locate(mouse) context.fillStyle = "#b83" context.beginPath() context.moveTo(points[cell[0]][0], points[cell[0]][1]) for(var j=1; j<cell.length; ++j) { context.lineTo(points[cell[j]][0], points[cell[j]][1]) } context.closePath() context.fill() for(var i=0; i<cells.length; ++i) { var cell = cells[i] context.beginPath() context.moveTo(points[cell[0]][0], points[cell[0]][1]) for(var j=1; j<cell.length; ++j) { context.lineTo(points[cell[j]][0], points[cell[j]][1]) } context.closePath() context.stroke() } context.fillStyle = "#000" for(var i=0; i<points.length; ++i) { context.beginPath() context.arc(points[i][0], points[i][1], 5.0/w, 0, 2*Math.PI) context.closePath() context.fill() } context.fillStyle = "#f00" context.beginPath() context.arc(mouse[0], mouse[1], 5.0/w, 0, 2*Math.PI) context.closePath() context.fill() })
mikolalysenko/incremental-delaunay
<|start_filename|>aesm/Dockerfile<|end_filename|> FROM ubuntu:18.04 ARG PSW_PKG_VERSION=2.9.101.2-bionic1 RUN apt-get update && apt-get install -y apt-utils RUN apt-get install -y dkms gnupg2 apt-transport-https software-properties-common curl && \ curl -fsSL https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key | apt-key add - && \ add-apt-repository "deb https://download.01.org/intel-sgx/sgx_repo/ubuntu bionic main" && \ apt-get update && \ apt-get install -y \ libsgx-launch=$PSW_PKG_VERSION \ libsgx-aesm-epid-plugin=$PSW_PKG_VERSION \ libsgx-aesm-pce-plugin=$PSW_PKG_VERSION \ libsgx-pce-logic=1.6.100.2-bionic1 \ libsgx-ae-le=$PSW_PKG_VERSION \ libsgx-ae-epid=$PSW_PKG_VERSION \ libsgx-aesm-launch-plugin=$PSW_PKG_VERSION \ libsgx-aesm-launch-plugin=$PSW_PKG_VERSION \ libsgx-enclave-common=$PSW_PKG_VERSION \ libsgx-urts=$PSW_PKG_VERSION \ libsgx-epid=$PSW_PKG_VERSION \ libsgx-urts=$PSW_PKG_VERSION \ libsgx-uae-service=$PSW_PKG_VERSION \ libsgx-quote-ex=$PSW_PKG_VERSION \ libsgx-urts=$PSW_PKG_VERSION \ sgx-aesm-service=$PSW_PKG_VERSION RUN mkdir -p /var/run/aesmd/ && chown -R aesmd:aesmd /var/run/aesmd/ && chmod 0755 /var/run/aesmd/ USER aesmd WORKDIR /opt/intel/sgx-aesm-service/aesm ENV LD_LIBRARY_PATH=/opt/intel/sgx-aesm-service/aesm VOLUME /var/run/aesmd CMD ./aesm_service --no-daemon
advanca/advanca
<|start_filename|>src/main/java/ListComprehension.java<|end_filename|> import org.apache.commons.lang3.tuple.Pair; import java.util.*; import java.util.function.*; import java.util.stream.Collectors; @SuppressWarnings("unchecked") public class ListComprehension<T> { private Function<T, T> outputExpression = x -> x; private BiFunction<T, T,?> pairOutputExpression = (x,y) -> Pair.of(x,y); ListComprehension() { } public void setOutputExpression(Function<T, T> outputExpression) { this.outputExpression = outputExpression; } public void setPairOutputExpression(BiFunction<T, T,?> pairOutputExpression) { this.pairOutputExpression = pairOutputExpression; } public List<T> suchThat(Consumer<Var> predicates){ Var x = new Var<T>(); predicates.accept(x); return (List<T>) x.value().stream().map(outputExpression).collect(Collectors.toList()); } public List<Pair<T, T>> suchThat(BiConsumer<Var, Var> predicates){ Var x = new Var<T>(); Var y = new Var<T>(); predicates.accept(x,y); return (List<Pair<T, T>>) x.value(y).stream() .map(pair -> pairOutputExpression.apply((T) ((Pair) pair).getLeft(), (T) ((Pair) pair).getRight())) .collect(Collectors.toList()); } public ListComprehension<T> giveMeAll(Function<T, T> resultTransformer) { this.setOutputExpression(resultTransformer); return this; } public ListComprehension<T> giveMeAll(BiFunction<T, T, ?> resultTransformer) { this.setPairOutputExpression(resultTransformer); return this; } public class Var<T> { private Set<T> belongsTo = new HashSet<>(); private Set<Predicate<T>> predicates = new HashSet<>(); private Set<BiPredicate<T, T>> biPredicates = new HashSet<>(); Var() { this.predicates.add(x -> true); this.biPredicates.add((x, y) -> true); } public Var belongsTo(List<T> c) { this.belongsTo.addAll(c); return this; } public Var is(Predicate<T> p) { this.predicates.add(p); return this; } public Var holds(Predicate<T> p) { return is(p); } public Var is(BiPredicate<T, T> p) { this.biPredicates.add(p); return this; } public Var holds(BiPredicate<T, T> p) { return is(p); } public List<T> value() { return intersect(predicates.stream() .map(condition -> belongsTo.stream() .filter(condition) .collect(Collectors.toList())) .collect(Collectors.toList())); } private List<T> intersect(List<List<T>> lists) { return belongsTo.stream() .filter(x -> lists.stream() .filter(list -> list.contains(x)).count() == lists.size()) .collect(Collectors.toList()); } public List<Pair<T, T>> value(Var yVar) { List<BiPredicate<T, T>> allBiPredicates = new LinkedList<>(); allBiPredicates.addAll(this.biPredicates); allBiPredicates.addAll((Collection<? extends BiPredicate<T, T>>) yVar.biPredicates.stream() .map(new Function<BiPredicate<T, T>,BiPredicate<T, T>>() { @Override public BiPredicate apply(BiPredicate p) { return new BiPredicate<T, T>() { @Override public boolean test(T x, T y) { return p.test(y,x); } }; } }).collect(Collectors.toList())); List<Pair<T, T>> pairs = new LinkedList<>(); this.value().stream().map(new Function<T, Boolean>() { @Override public Boolean apply(T x) { yVar.value().stream().map(new Function<T, Boolean>() { @Override public Boolean apply(T y) { return pairs.add(Pair.of(x, y)); } }).collect(Collectors.toList()); return null; } }).collect(Collectors.toList()); return pairs.stream().filter(pair -> holdsAll(allBiPredicates, pair)).collect(Collectors.toList()); } public boolean holdsAll(List<BiPredicate<T,T>> predicates, Pair<T,T> pair) { return predicates.stream().filter(p -> p.test(pair.getLeft(),pair.getRight())).count() == predicates.size(); } public <G> List<G> concat(List<List<G>> lists) { List<G> list = new LinkedList<>(); lists.stream().map(l -> { list.addAll(l); return l; }).collect(Collectors.toList()); return list; } } } <|start_filename|>src/test/java/ListComprehensionPerfTests.java<|end_filename|> import org.apache.commons.lang3.tuple.Pair; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import static org.junit.Assert.*; /** * Created by farolfo on 7/19/16. */ public class ListComprehensionPerfTests { /** * Test for { x | x E {1,2,3,4,...} ^ x is even } using List Comprehensions */ @Test public void filterLCTest() { List<Long> bigList = createBigList(); long startTime = System.nanoTime(); List<Long> evens = filter(bigList, (Long x) -> x % 2 == 0); long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } /** * Test for { x | x E {1,2,3,4,...} ^ x is even } using filter */ @Test public void filterFUNCTest() { List<Long> bigList = createBigList(); long startTime = System.nanoTime(); List<Long> evens = bigList.stream().filter((Long x) -> x % 2 == 0).collect(Collectors.toList()); long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } /** * Test for { x | x E {1,2,3,4,...} ^ x is even } using for+if */ @Test public void filterFORTest() { List<Long> bigList = createBigList(); long startTime = System.nanoTime(); List<Long> evens = new ArrayList<>(); for (int i = 0; i < bigList.size(); i++) { if (bigList.get(i) % 2 == 0) { evens.add(bigList.get(i)); } } long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } private List<Long> createBigList() { return createBigList(100000000); } private List<Long> createBigList(int cant) { List l = new ArrayList<>(); for (int i = 0; i<cant; i++) { l.add(Math.round(Math.random() * 70)); } return l; } public <T> List<T> filter(List<T> list, Predicate<T> p) { return new ListComprehension<T>() .suchThat(s -> { s.belongsTo(list); s.holds(p); }); } /** * Test for { x * 2 | x E {1,2,3,4, ...} } with List Comprehensions */ @Test public void mapLCTest() { List<Long> bigList = createBigList(); long startTime = System.nanoTime(); List<Long> duplicated = map(bigList, (Long x) -> x * 2); long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } /** * Test for { x * 2 | x E {1,2,3,4, ...} } with Map */ @Test public void mapFUNCTest() { List<Long> bigList = createBigList(); long startTime = System.nanoTime(); List<Long> duplicated = bigList.stream().map((Long x) -> x * 2).collect(Collectors.toList()); long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } /** * Test for { x * 2 | x E {1,2,3,4, ...} } with for */ @Test public void mapFORTest() { List<Long> bigList = createBigList(); long startTime = System.nanoTime(); List<Long> duplicated = new ArrayList<>(); for (int i = 0; i < bigList.size(); i++) { duplicated.add(bigList.get(i) * 2); } long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } public <T> List<T> map(List<T> list, Function<T,T> f) { return new ListComprehension<T>() .giveMeAll(t -> f.apply(t)) .suchThat(s -> { s.belongsTo(list); }); } /** * Test for { (x,y) | x E {1,2, ...} ^ y E {3,4 ,...} } with List Comprehensions */ @Test public void cartesianProductLCTest() { List<Long> bigList1 = createBigList(10000); List<Long> bigList2 = createBigList(10000); long startTime = System.nanoTime(); List<Pair<Long,Long>> cartesianProduct = new ListComprehension<Long>().suchThat((x, y) -> { x.belongsTo(bigList1); y.belongsTo(bigList2); }); long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } /** * Test for { (x,y) | x E {1,2, ...} ^ y E {3,4, ...} } with For */ @Test public void cartesianProductFORTest() { List<Long> bigList1 = createBigList(10000); List<Long> bigList2 = createBigList(10000); long startTime = System.nanoTime(); List<Pair<Long,Long>> cartesianProduct = new ArrayList<>(); for(Long x : bigList1) { for(Long y : bigList2) { cartesianProduct.add(Pair.of(x, y)); } } long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } /** * Test for { (x,y) | x E {1,2, ...} ^ y E {3,4, ...} } with Map */ @Test public void cartesianProductMAPTest() { List<Long> bigList1 = createBigList(10000); List<Long> bigList2 = createBigList(10000); long startTime = System.nanoTime(); List<Pair<Long,Long>> cartesianProduct = new ArrayList<>(); bigList1.stream().map((Long x) -> { return bigList2.stream().map((Long y) -> { return cartesianProduct.add(Pair.of(x, y)); }); }); long estimatedTime = System.nanoTime() - startTime; System.out.println("Time: " + estimatedTime); } } <|start_filename|>src/test/java/ListComprehensionTest.java<|end_filename|> import org.apache.commons.lang3.tuple.Pair; import org.junit.Ignore; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; @SuppressWarnings("unchecked") public class ListComprehensionTest { /** * Test for { x | x E {1,2,3,4} ^ x is even } */ @Test public void filterTest() { List<Integer> someIntegers = Arrays.asList(1, 2, 3, 4); List<Integer> actualEvens = Arrays.asList(2, 4); List<Integer> evens = filter(someIntegers, (Integer x) -> x % 2 == 0); assertThat(evens, is(actualEvens)); } public <T> List<T> filter(List<T> list, Predicate<T> p) { return new ListComprehension<T>() .suchThat(s -> { s.belongsTo(list); s.holds(p); }); } /** * Test for { x * 2 | x E {1,2,3,4} } */ @Test public void mapTest() { List<Integer> someIntegers = Arrays.asList(1, 2, 3, 4); List<Integer> actualDuplicated = Arrays.asList(2, 4, 6, 8); List<Integer> duplicated = map(someIntegers, (Integer x) -> x * 2); assertThat(duplicated, is(actualDuplicated)); } public <T> List<T> map(List<T> list, Function<T,T> f) { return new ListComprehension<T>() .giveMeAll(t -> f.apply(t)) .suchThat(s -> { s.belongsTo(list); }); } /** * Test for { (x,y) | x E {1,2} ^ y E {3,4} } */ @Test public void cartesianProductTest() { List<Integer> someIntegers = Arrays.asList(1, 2); List<Integer> moreIntegers = Arrays.asList(3, 4); List<Pair<Integer,Integer>> actualCartesianProduct = Arrays.asList(Pair.of(1,3), Pair.of(1,4), Pair.of(2,3), Pair.of(2,4)); List<Pair<Integer,Integer>> cartesianProduct = new ListComprehension<Integer>().suchThat((x, y) -> { x.belongsTo(someIntegers); y.belongsTo(moreIntegers); }); assertThat(cartesianProduct, is(actualCartesianProduct)); } /** * Test for { (x,y) | x E {1,2,3} ^ y E {4,5,6} ^ x * 2 = y } */ @Test public void relationBetweenXYTest() { List<Integer> someIntegers = Arrays.asList(1, 2, 3); List<Integer> moreIntegers = Arrays.asList(4, 5, 6); List<Pair<Integer,Integer>> actualDoublePairs = Arrays.asList(Pair.of(2,4), Pair.of(3,6)); BiPredicate<Integer, Integer> condition = (x, y) -> x * 2 == y; List<Pair<Integer,Integer>> doublePairs = new ListComprehension<Integer>().suchThat((x, y) -> { x.belongsTo(someIntegers); y.belongsTo(moreIntegers); x.holds(condition); }); assertThat(doublePairs, is(actualDoublePairs)); } }
farolfo/list-comprehension-in-java
<|start_filename|>categories/editorials.html<|end_filename|> --- layout: template-category slug: editorials title: Editorials description: "Opinionated and less news-specific takes on AI topics" redirect_from: - /editorials/ - /editorials.php/ --- <|start_filename|>categories/overviews.html<|end_filename|> --- layout: template-category slug: overviews title: Overviews description: "In-depth summaries of topics related to AI" redirect_from: - /overviews/ - /overviews.php/ --- <|start_filename|>_includes/post-sidebar.html<|end_filename|> <div class="page-meta mr-4 small"> <!-- {% if site.owner.disqus-shortname and page.comments or site.comments %} <span class="page-comments d-none d-md-block mt-2"> <img width="21px" class="mr-1" src="{{site.baseurl}}/assets/img/icons/comments.svg"> <a class="text-muted" href="#disqus_thread">Comment</a> </span> {% endif %} --> <div id="sidebar-above-toc"> <h6 class="d-none d-md-block mt-2 lh14">{{page.title}}</h6> {% if site.owner.google.ad-client and site.owner.google.ad-slot %} {% include ad-sidebar.html %} {% endif %} <div class="text-muted"> <span class="page-date date published"> <time datetime="{{ page.date | date_to_xmlschema }}"> {{ page.date | date: "%B %d, %Y" }} </time> </span> {% if page.modified %} <span class="page-date date modified"> <time datetime="{{ page.modified }}"> {{ page.modified | date: "%B %d, %Y" }} </time> </span> {% endif %} </div> {% if page.author %} {% if page.author.first %} {% for a in page.author %} {% assign author = site.data.authors[a] %} {% include sidebar-author.html %} {% endfor %} {% else %} {% assign author = site.data.authors[page.author] %} {% include sidebar-author.html %} {% endif %} {% endif %} {% if page.sidebartoc %} <hr> </div> <nav id="mytoc" data-spy="affix" style="overflow-y: auto;" data-toggle="mytoc"></nav> {% else %} </div> {% endif %} </div> <|start_filename|>categories/briefs.html<|end_filename|> --- layout: template-category slug: briefs title: Briefs description: "Concise yet thorough articles that summarize an important recent news story" redirect_from: - /briefs/ - /briefs.php/ --- <|start_filename|>categories/digests.html<|end_filename|> --- layout: template-category slug: digests title: Last Week in AI description: "Weekly digests of the most important recent media stories about AI" redirect_from: - /digests/ - /digests.php/ --- <|start_filename|>_layouts/page.html<|end_filename|> --- layout: default --- {% unless page.display_title == false %} <div class="row"> <div class="col-md-12 mb-2rem"> <h1 class="text-black">{{page.title}}</h1> <h4 class="font-weight-light lh14">{{page.excerpt}}</h4> </div> </div> {% endunless %} <div class="inpage"> {{ content }} </div> <|start_filename|>_includes/sidebar.html<|end_filename|> <div class="thesidebar sticky-top"> <h6 class="font1 fancy-title text-uppercase"><span>Featured</span></h6> {% assign posts=site.posts | where:"featured", true %} {% for post in posts %} <div class="d-flex featured"> {% if post.image.external %} <img src="{{ post.image.external }}" class="featuredthumb" alt="{{ post.title }}"> {% else %} <img src="{{ site.baseurl }}/{{ post.image.feature }}" class="featuredthumb" alt="{{ post.title }}"> {% endif %} <div class="wrap-feat-content ml-4"> <div class="list-categories"> {% for category in post.categories %} <style>.{{category}}-color {color: #{{ site[category] }};}</style> <a class="text-uppercase {{category}}-color catstyle" href="{{site.baseurl}}/categories/{{ category | replace: " ","-" }}">{{ category }}</a> <span class="sepcat">/</span> {% endfor %} {% for tag in post.tags %} <a class="text-capitalize text-muted" href="{{site.baseurl}}/tags#{{ tag | replace: " ","-" }}">{{ tag }}</a><span class="sep">, </span> {% endfor %} </div> <a href="{{ site.baseurl }}{{ post.url }}"> <h5 class="text-black"> <span class="effect-underline"> {{ post.title }} </span> </h5> </a> </div> </div> {% endfor %} {% unless page.url contains "tags" %} <h6 class="font1 fancy-title text-uppercase mt-4" style="margin-bottom:1.2rem;"><span>Explore</span></h6> <div class="d-block"> {% include tagcloud.html %} </div> <a class="d-inline-block text-black small rounded-0 font500" href="{{site.baseurl}}/tags">&rarr; view all topics</a> {% endunless %} </div> <|start_filename|>_includes/tagcloud.html<|end_filename|> {% assign tags_max = 0 %} {% for tag in site.tags %} {% if tag[1].size > tags_max %} {% assign tags_max = tag[1].size %} {% endif %} {% endfor %} <ul class="tag-box inline"> {% for i in (1..tags_max) reversed %} {% for tag in site.tags %} {% if tag[1].size == i %} <li> <a href="{{site.baseurl}}/tags#{{ tag[0] | | replace: ' ', '-'}}">{{ tag[0] }} <span>{{ tag[1].size }}</span></a> </li> {% endif %} {% endfor %} {% endfor %} </ul> <|start_filename|>_includes/social-icons.html<|end_filename|> <div class="social-icons"> {%- for footer_link in site.footer_links -%} {%- if footer_link.url contains "://" -%} {%- assign url = footer_link.url -%} {%- else -%} {%- assign url = footer_link.url | relative_url -%} {%- endif -%} <a target="_blank" class="social-icon" href="{{ url }}"> <img alt="social" src="{{ site.baseurl }}/{{footer_link.icon}}"> </a> {%- endfor -%} </div> <|start_filename|>_layouts/template-category.html<|end_filename|> --- layout: default --- <div class="row"> <div class="col-md-12 mb-4"> <h1 class="text-black">{{page.title}}</h1> <h4 class="font-weight-light">{{page.description}} | <b><a href="https://lastweekin.ai/subscribe">Subscribe here!</a></b></h4> </div> </div> <div class="row"> <div class="col-md-8"> <h6 class="font1 fancy-title text-uppercase"> <span>{{ page.title }}</span> </h6> <div class="row mt-3 cardrecent"> {% for post in site.posts %} {% if post.categories contains page.slug %} <div class="col-md-6 mb-30"> {% include themecard.html %} </div> {% endif %} {% endfor %} </div> </div> <div class="col-md-4"> {% include sidebar.html %} </div> </div> <|start_filename|>_pages/tags.html<|end_filename|> --- title: "Topics" layout: page permalink: "/tags.html" --- <div class="row"> <div class="col-md-8"> {% capture site_tags %}{% for tag in site.tags %}{{ tag | first }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %} {% assign tags_list = site_tags | split:',' | sort %} <ul class="tag-box inline"> {% for item in (0..site.tags.size) %} {% unless forloop.last %} {% capture this_word %}{{ tags_list[item] | strip_newlines }}{% endcapture %} <li><a href="#{{ this_word | replace: " ","-"}}">{{ this_word }} <span>{{ site.tags[this_word].size }}</span></a></li> {% endunless %} {% endfor %} </ul> {% for item in (0..site.tags.size) %} {% unless forloop.last %} {% capture this_word %}{{ tags_list[item] | strip_newlines }}{% endcapture %} <h5 class="mt-5 mb-2" id="{{ this_word | replace: " ","-"}}">{{ this_word }}</h5> <ul class="post-list"> {% for post in site.tags[this_word] %}{% if post.title != null %} <li><a class="text-black row justify-content-between border-0" href="{{site.baseurl}}{{ post.url }}"><div class="col-md-9">{{ post.title }}</div><span class="entry-date small col-md-3 text-right small text-muted"><time datetime="{{ post.date | date_to_xmlschema }}">{{ post.date | date: "%B %d, %Y" }}</time></span></a></li> {% endif %}{% endfor %} </ul> {% endunless %} {% endfor %} </div> <div class="col-md-4"> {% include sidebar.html %} </div> </div> <|start_filename|>_pages/authors.html<|end_filename|> --- title: "Authors" description: "Our amazing contributors at Skynet Today" layout: page permalink: "/authors.html" share: true --- <div class="row"> <div class="col-md-8"> <h6 class="font1 fancy-title text-uppercase"> <span>Posts by</span> </h6> <div class="gap-y listrecent listrecent listauthor"> {% for author in site.data.authors %} <div class="authorbox p-5 border-left border-right border-top" id="{{author[1].name | downcase | replace: ' ', '_' | replace: '.', '_'| replace: 'ö', 'o'}}"> <div class="row"> <div class="col-12 col-md-2 mb-4 mb-md-0"><img width="120" alt="{{ author[1].name }}" src="{{site.baseurl}}/assets/img/authors/{{ author[1].avatar }}" class="rounded-circle"></div> <div class="col"> <h5 class="text-black mb-2 d-block"> {{ author[1].name }} </h5> {% if author[1].web %} <a class="text-muted d-block small" target="_blank" href="{{ author[1].web }}">★ {{ author[1].web | replace: 'https://', '' | replace: 'http://', '' | replace: 'www.', '' }}</a> {% endif %} {% if author[1].twitter %} <a class="text-muted d-block" target="_blank" href="https://twitter.com/{{ author[1].twitter }}"> <small class="d-inline-block mt-1 font-weight-normal">@{{ author[1].twitter }}</small> </a> {% endif %} {% if author[1].description %} <div class="d-block mt-3 font500">{{ author[1].description }}</div> {% endif %} {% assign posts = site.posts | where: "author", author[0] %} <ul class="mt-4 post-list"> {% for post in posts %} <li><a class="text-black" href="{{site.baseurl}}{{post.url}}">{{ post.title }}</a></li> {% endfor %} </ul> </div> </div> </div> {% endfor %} </div> </div> <div class="col-md-4"> <div class="sticky-top"> <h6 class="font1 fancy-title text-uppercase"><span>Contribute</span></h6> <h5>Skynet Today is seeking collaborators and editorial submissions!</h5> <p>AI misinformation, overhyping, and doomsaying are more rampant than ever and our small team could sure benefit from a few more excited and knowledgeable collaborators and contributors.</p> <p> If you want to contribute to this site as either a collaborator or with a submission, reach out via our email (<b>editorial @ <EMAIL></b>) or use the button below.</p> <p>Tell us a bit about your background and how you would like to contribute to Skynet Today, and we’ll take it from there!</p> <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLScDRqeP_jaI10g-AMy_CvqVhjgyi0xF783QKT0O10f3R-sw_g/viewform" class="mb-2 btn btn-dark bg-black text-white border-0 rounded-0">Contribute to Skynet Today</a> </div> </div> </div>
SkynetToday/skynet-today
<|start_filename|>.original/spine-v.1.6.2/src/local.coffee<|end_filename|> Spine = @Spine or require('spine') Spine.Model.Local = extended: -> testLocalStorage = 'spine' + new Date().getTime() try localStorage.setItem(testLocalStorage, testLocalStorage) localStorage.removeItem(testLocalStorage) catch e return @change @saveLocal @fetch @loadLocal saveLocal: -> result = JSON.stringify(@) localStorage[@className] = result loadLocal: (options = {})-> options.clear = true unless options.hasOwnProperty('clear') result = localStorage[@className] @refresh(result or [], options) module?.exports = Spine.Model.Local
skylark-integration/skylark-spine
<|start_filename|>cmake/MacOSX.cmake<|end_filename|> ############################################################################### ## ## Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ## Contact: Tegesoft Information (<EMAIL>) ## ## This file is part of the CAMP library. ## ## The MIT License (MIT) ## ## Copyright (c) 2009-2014 TEGESO/TEGESOFT ## ## 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. ## ############################################################################### # Apple MacOS X # Configure to build universal binaries. # Build intel 32-bit on 10.4 and intel 32/64-bit on >= 10.5 if(APPLE AND NOT NON_NATIVE_TARGET) if(NOT OSX_CONFIG_HAS_BEEN_RUN_BEFORE) # Make sure the version of CMake is compatible with this script if(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4 AND ${CMAKE_PATCH_VERSION} LESS 7) message(STATUS "Warning: A critical CMake bug exists in 2.4.6 and below. " "Trying to build Universal Binaries will result in a compile " "error that seems unrelated. Either avoid building Universal " "Binaries by changing the CMAKE_OSX_ARCHITECTURES field to list " "only your architecture, or upgrade to a newer version of CMake.") endif() # Determine the correct SDK if(NOT FORCE_32BIT AND (EXISTS /Developer/SDKs/10.5.sdk OR EXISTS /Developer/SDKs/MacOSX10.6.sdk)) set(CMAKE_OSX_ARCHITECTURES "i386;x86_64" CACHE STRING "Build architectures for OSX" FORCE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=10.5" CACHE STRING "Flags used by the compiler during all build types." FORCE) else() if(EXISTS /Developer/SDKs/MacOSX10.4u.sdk OR FORCE_32BIT) set(CMAKE_OSX_ARCHITECTURES "i386" CACHE STRING "Build architectures for OSX" FORCE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=10.4 -m32" CACHE STRING "Flags used by the compiler during all build types." FORCE) else() # No Universal Binary support endif() endif() set(OSX_CONFIG_HAS_BEEN_RUN_BEFORE TRUE) endif(NOT OSX_CONFIG_HAS_BEEN_RUN_BEFORE) endif(APPLE AND NOT NON_NATIVE_TARGET) if(OSX_ARCHITECTURES_OVERRIDE) set(CMAKE_OSX_ARCHITECTURES ${OSX_ARCHITECTURES_OVERRIDE}) endif() if(APPLE) message(STATUS "Compiling for Mac OS X architecture(s): " ${CMAKE_OSX_ARCHITECTURES}) endif()
lailongwei/ponder
<|start_filename|>Dockerfile<|end_filename|> FROM python:3.8-alpine COPY . /rancher-gitlab-deploy/ WORKDIR /rancher-gitlab-deploy RUN python /rancher-gitlab-deploy/setup.py install RUN ln -s /usr/local/bin/rancher-gitlab-deploy /usr/local/bin/upgrade CMD rancher-gitlab-deploy
dimw/rancher-gitlab-deploy
<|start_filename|>Dockerfile<|end_filename|> FROM nvidia/cuda:10.1-cudnn7-devel-ubuntu18.04 ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ git \ curl \ libglib2.0-0 \ software-properties-common \ python3.6-dev \ python3-pip \ python3-tk \ firefox \ libcanberra-gtk-module \ nano WORKDIR /tmp RUN pip3 install --upgrade pip RUN pip3 install setuptools RUN pip3 install matplotlib numpy pandas scipy tqdm pyyaml easydict scikit-image bridson Pillow ninja RUN pip3 install imgaug mxboard graphviz RUN pip3 install albumentations --no-deps RUN pip3 install opencv-python-headless RUN pip3 install Cython RUN pip3 install torch RUN pip3 install torchvision RUN pip3 install scikit-learn RUN pip3 install tensorboard RUN mkdir /work WORKDIR /work RUN chmod -R 777 /work && chmod -R 777 /root ENV TINI_VERSION v0.18.0 ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /usr/bin/tini RUN chmod +x /usr/bin/tini ENTRYPOINT [ "/usr/bin/tini", "--" ] CMD [ "/bin/bash" ]
qinliuliuqin/ritm_interactive_segmentation
<|start_filename|>app/feed/mocks.js<|end_filename|> let cards = [ { type: 'update', user: { name: 'John\nAppleseed', picture: 'http://lorempixel.com/80/80/people/1/', }, card: { text: "I am working on implementing Facebook Paper like interactions today." } }, { type: 'photo', user: { name: 'Vinay\nSingh', picture: 'http://lorempixel.com/80/80/people/2/', }, card: { image: "http://i.imgur.com/iliFxTz.jpg", text: "Gotta munch on some thing while I get this to work." } }, { type: 'question', user: { name: 'Ravi\nAnand', picture: 'http://lorempixel.com/80/80/people/3/', }, card: { text: "Is it really possible that animations can be paused in flight to keep the interface always responsive?" } }, { type: 'deadline', user: { name: 'John\nAppleseed', picture: 'http://lorempixel.com/80/80/people/4/', }, card: { text: "Gotta ship this soon!" } }, { type: 'photo', user: { name: 'Vinay\nSingh', picture: 'http://lorempixel.com/80/80/people/5/', }, card: { image: "http://i.imgur.com/Ui3oFTh.jpg", text: "If this works, I need a party!" } }, { type: 'question', user: { name: 'Ravi\nAnand', picture: 'http://lorempixel.com/80/80/people/6/', }, card: { text: "The Animated library for React Native is pretty amazing, right?" } }, { type: 'photo', user: { name: 'Vinay\nSingh', picture: 'http://lorempixel.com/80/80/people/7/', }, card: { image: "http://i.imgur.com/HOXLJJS.jpg", text: "Looks like there is something to eat here." } }, ]; module.exports = cards; <|start_filename|>app/feed/CardTop.js<|end_filename|> import React, { Component } from 'react'; import { StyleSheet, Text, Image, View, } from 'react-native'; class CardTop extends Component { render() { let { userPicture, userName, lightColor, darkColor, badgeText } = this.props return ( <View style={{ flexDirection: 'row' }}> <Image style={styles.profilePicture} source={{ height: 80, width: 80, uri: userPicture }} /> <Text style={styles.displayName}> {userName} </Text> <View style={styles.badgeSection} > <View style={[styles.badgeSlug, { backgroundColor: lightColor }]} > <Text style={[styles.badgeText,{ color: darkColor }]}> {badgeText} </Text> </View> </View> </View> ) } } const styles = StyleSheet.create({ profilePicture: { width: 50, height: 50, borderRadius: 25, backgroundColor: 'white', margin: 20, marginRight: 10 }, displayName: { backgroundColor: 'transparent', color: 'white', marginLeft: 0, marginTop: 22, fontSize: 20, marginBottom: 5, }, badgeSection: { flex: 1, alignItems: 'flex-end', marginRight: 20, justifyContent: 'center' }, badgeSlug: { borderRadius: 15, paddingVertical: 5, paddingHorizontal: 12, }, badgeText: { textAlign: 'center', fontSize: 10, fontWeight: 'bold' }, }); module.exports = CardTop; <|start_filename|>app/feed/types.js<|end_filename|> let types = { 'photo': { title: 'PHOTO', colorDark: 'black', colorLight: 'white', reaction: '📷' }, 'question': { title: 'QUESTION', colorDark: '#00301B', colorLight: '#00AA4E', reaction: '🤓' }, 'deadline': { title: 'DEADLINE', colorDark: '#A91400', colorLight: '#FF5505', reaction: '😱' }, 'update': { title: 'UPDATE', colorDark: '#032269', colorLight: '#27AFFF', reaction: '👏' } }; module.exports = types;
brentvatne/rn-paper-interface
<|start_filename|>test/index.js<|end_filename|> const path = require('path') const test = require('tape') const fs = require('fs') const mdjson = require('../') test('should assert input types', function (t) { t.plan(1) t.throws(mdjson, /markdown string/) }) test('should return a parsed obj', function (t) { t.plan(2) fs.readFile(path.resolve(__dirname, 'text.md'), 'utf8', function (err, res) { t.notOk(err) const obj = mdjson(res) t.deepLooseEqual(obj, { 'my heading': { raw: 'oh wow, amazing', html: '<p>oh wow, amazing</p>' }, 'another heading': { raw: 'gorgeous copy, stunning', html: '<p>gorgeous copy, stunning</p>' } }) }) }) test('should handle multiple paragraphs', function (t) { const fixture = path.resolve(__dirname, 'text-multi.md') const markdown = fs.readFileSync(fixture, 'utf8') const tree = mdjson(markdown) t.deepEqual(tree, { 'first heading': { html: '<p>Hi there!</p>\n<p>This content runs over multiple lines...</p>', raw: ' Hi there!\n\nThis content runs over multiple lines...' }, 'second heading': { html: '<p>As does this one.\nYup.</p>\n<p>With even more whitespace :O</p>', raw: 'As does this one.\nYup.\n\nWith even more whitespace :O' } }) t.end() }) test('should ignore text before headings', function (t) { const fixture = path.resolve(__dirname, 'text-pre-headings.md') const markdown = fs.readFileSync(fixture, 'utf8') const tree = mdjson(markdown) t.deepEqual(tree, { 'Main Content': { html: '<p>Goes here</p>', raw: 'Goes here' } }) t.end() }) <|start_filename|>package.json<|end_filename|> { "name": "mdjson", "version": "2.0.1", "description": "Transform markdown to an object where headings are keys", "main": "index.js", "scripts": { "test": "standard && NODE_ENV=test node test/index.js", "test-cov": "standard && NODE_ENV=test istanbul cover test/index.js" }, "repository": "yoshuawuyts/mdjson", "keywords": [ "markdown", "parse", "json" ], "license": "MIT", "dependencies": { "mdast": "^0.26.0", "mdast-html": "^0.1.0" }, "devDependencies": { "istanbul": "^0.3.13", "standard": "^3.6.1", "tape": "^4.0.0" }, "files": [ "LICENSE", "index.js", "README.md" ] } <|start_filename|>index.js<|end_filename|> const html = require('mdast-html') const assert = require('assert') const mdast = require('mdast') module.exports = mdjson // map a markdown string to an object // with `html` and `raw` fields // str -> obj function mdjson (txt) { assert.equal(typeof txt, 'string', 'input should be a markdown string') const toHtml = mdast().use(html) const lexer = mdast() const tokens = lexer.parse(txt).children const res = {} var key = '' tokens.forEach(function (token, i) { if (token.type === 'heading') { key = token.children[0].value res[key] = [] return } if (!key) return res[key].push(token) }) Object.keys(res).forEach(function (key) { const tree = { type: 'root', children: res[key] } res[key] = { raw: trimRight(lexer.stringify(tree)), html: trimRight(toHtml.stringify(tree)) } }) return res } // trim whitespace at the // end of a string // str -> str function trimRight (value) { return value.replace(/\n+$/, '') }
yoshuawuyts/mdjson
<|start_filename|>test/cmq_queue_test.go<|end_filename|> package test import ( "testing" "github.com/NETkiddy/cmq-go" ) var secretId = "YourTencentSecretId" var secretKey = "YourTencentSecretKey" var endpointQueue = "https://cmq-queue-sh.api.qcloud.com" var endpointQueueInner = "http://cmq-queue-sh.api.tencentyun.com" //----------------------------------------------------------------- // 创建队列 func Test_CreateQueue(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) meta := cmq_go.QueueMeta{} meta.PollingWaitSeconds = 10 meta.VisibilityTimeout = 10 meta.MaxMsgSize = 1048576 meta.MsgRetentionSeconds = 345600 err, _ := account.CreateQueue("queue-test-001", meta) if err != nil { t.Errorf("queue-test-001 created failed, %v", err.Error()) return } t.Log("queue-test-001 created") err, _ = account.CreateQueue("queue-test-002", meta) if err != nil { t.Errorf("queue-test-002 created failed, %v", err.Error()) return } t.Log("queue-test-002 created") } // 列出当前帐号下所有队列名字 func Test_ListQueue(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) totalCount, queueList, err, _ := account.ListQueue("", -1, -1) if err != nil { t.Error(err) return } t.Logf("totalCount: %v", totalCount) t.Logf("queueList: %v", queueList) } // 删除队列 func Test_DeleteQueue(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) err, _ := account.DeleteQueue("queue-test-002") if err != nil { t.Error(err) return } } // 获得队列实例 func Test_GetQueue(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) queue := account.GetQueue("queue-test-001") t.Logf("GetQueue: %v", queue) } //----------------------------------------------------------------- // 设置队列属性 func Test_SetQueueAttributes(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) meta := cmq_go.QueueMeta{} meta.PollingWaitSeconds = 10 meta.VisibilityTimeout = 10 meta.MaxMsgSize = 1048576 meta.MsgRetentionSeconds = 345600 queue := account.GetQueue("queue-test-001") err, _ := queue.SetQueueAttributes(meta) if err != nil { t.Error(err) return } } //----------------------------------------------------------------- // 获取队列属性 func Test_GetQueueAttributes(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) queue := account.GetQueue("queue-test-001") newMeta, err, _ := queue.GetQueueAttributes() if err != nil { t.Error(err) return } t.Logf("GetQueueAttributes: %v", newMeta) } // 发送,接受,删除消息 func Test_SendReceiveDeleteMessage(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) queue := account.GetQueue("queue-test-001") // send msgId, err, _ := queue.SendMessage("hello world") if err != nil { t.Error(err) return } t.Logf("SendMessage msgId: %v", msgId) // receive msg, err, code := queue.ReceiveMessage(10) if err != nil { if code == 7000{ t.Logf("no message") }else if code == 6070{ t.Logf("too many unacked(inactive messages or delayed messages)") }else { t.Error(err) return } } t.Logf("ReceiveMessage msgId: %v", msg.MsgId) // delete err, _ = queue.DeleteMessage(msg.ReceiptHandle) if err != nil { t.Error(err) return } t.Logf("DeleteMessage msgId: %v", msg.MsgId) } // 批量发送,接收,删除消息 func Test_BatchSendReceiveDeleteMessage(t *testing.T) { account := cmq_go.NewAccount(endpointQueue, secretId, secretKey) queue := account.GetQueue("queue-test-001") // batch send msgBodys := []string{"hello world", "foo", "bar"} msgIds, err, _ := queue.BatchSendMessage(msgBodys) if err != nil { t.Error(err) return } t.Logf("BatchSendMessage msgId: %v", msgIds) // batch receive msgs, err, _ := queue.BatchReceiveMessage(10, 10) if err != nil { t.Error(err) return } handlers := make([]string, 0) msgIds = msgIds[0:0] for _, msg := range msgs { handlers = append(handlers, msg.ReceiptHandle) msgIds = append(msgIds, msg.MsgId) } t.Logf("BatchReceiveMessage msgIds: %v", msgIds) // batch delete err, _ = queue.BatchDeleteMessage(handlers) if err != nil { t.Error(err) return } t.Logf("BatchDeleteMessage msgId: %v", msgIds) } <|start_filename|>cmq_tool.go<|end_filename|> package cmq_go type CMQTool struct { } <|start_filename|>account.go<|end_filename|> package cmq_go import ( "fmt" "strconv" "encoding/json" "net/http" ) const ( DEFAULT_ERROR_CODE = -1 ) type Account struct { client *CMQClient } func NewAccount(endpoint, secretId, secretKey string) *Account { return &Account{ client: NewCMQClient(endpoint, "/v2/index.php", secretId, secretKey, "POST"), } } func (this *Account) SetProxy(proxyUrl string) *Account{ this.client.setProxy(proxyUrl) return this } func (this *Account) UnsetProxy() *Account{ this.client.unsetProxy() return this } func (this *Account) SetTransport(transport http.RoundTripper) *Account{ this.client.CmqHttp.SetTransport(transport) return this } func (this *Account) setSignMethod(method string) (err error) { return this.client.setSignMethod(method) } func (this *Account) CreateQueue(queueName string, queueMeta QueueMeta) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) if queueName == "" { err = fmt.Errorf("createQueue failed: queueName is empty") //log.Printf("%v", err.Error()) return } param["queueName"] = queueName if queueMeta.MaxMsgHeapNum > 0 { param["maxMsgHeapNum"] = strconv.Itoa(queueMeta.MaxMsgHeapNum) } if queueMeta.PollingWaitSeconds > 0 { param["pollingWaitSeconds"] = strconv.Itoa(queueMeta.PollingWaitSeconds) } if queueMeta.VisibilityTimeout > 0 { param["visibilityTimeout"] = strconv.Itoa(queueMeta.VisibilityTimeout) } if queueMeta.MaxMsgSize > 0 { param["maxMsgSize"] = strconv.Itoa(queueMeta.MaxMsgSize) } if queueMeta.MsgRetentionSeconds > 0 { param["msgRetentionSeconds"] = strconv.Itoa(queueMeta.MsgRetentionSeconds) } if queueMeta.RewindSeconds > 0 { param["rewindSeconds"] = strconv.Itoa(queueMeta.RewindSeconds) } _, err, code = doCall(this.client, param, "CreateQueue") if err != nil { //log.Printf("client.call CreateQueue failed: %v\n", err.Error()) return } return } func (this *Account) DeleteQueue(queueName string) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) if queueName == "" { err = fmt.Errorf("deleteQueue failed: queueName is empty") //log.Printf("%v", err.Error()) return } param["queueName"] = queueName _, err, code = doCall(this.client, param, "DeleteQueue") if err != nil { //log.Printf("client.call DeleteQueue failed: %v\n", err.Error()) return } return } func (this *Account) ListQueue(searchWord string, offset, limit int) ( totalCount int, queueList []string, err error, code int) { code = DEFAULT_ERROR_CODE queueList = make([]string, 0) param := make(map[string]string) if searchWord != "" { param["searchWord"] = searchWord } if offset >= 0 { param["offset"] = strconv.Itoa(offset) } if limit > 0 { param["limit"] = strconv.Itoa(limit) } resMap, err, code := doCall(this.client, param, "ListQueue") if err != nil { //log.Printf("client.call ListQueue failed: %v\n", err.Error()) return } totalCount = int(resMap["totalCount"].(float64)) resQueueList := resMap["queueList"].([]interface{}) for _, v := range resQueueList { queue := v.(map[string]interface{}) queueList = append(queueList, queue["queueName"].(string)) } return } func (this *Account) GetQueue(queueName string) (queue *Queue) { return NewQueue(queueName, this.client) } func (this *Account) GetTopic(topicName string) (topic *Topic) { return NewTopic(topicName, this.client) } func (this *Account) CreateTopic(topicName string, maxMsgSize int) (err error, code int) { err, code = _createTopic(this.client, topicName, maxMsgSize, 1) return } func _createTopic(client *CMQClient, topicName string, maxMsgSize, filterType int) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) if topicName == "" { err = fmt.Errorf("createTopic failed: topicName is empty") //log.Printf("%v", err.Error()) return } param["topicName"] = topicName param["filterType"] = strconv.Itoa(filterType) if maxMsgSize < 1024 || maxMsgSize > 1048576 { err = fmt.Errorf("createTopic failed: Invalid parameter: maxMsgSize > 1024KB or maxMsgSize < 1KB") //log.Printf("%v", err.Error()) return } param["maxMsgSize"] = strconv.Itoa(maxMsgSize) _, err, code = doCall(client, param, "CreateTopic") if err != nil { //log.Printf("client.call CreateTopic failed: %v\n", err.Error()) return } return } func (this *Account) DeleteTopic(topicName string) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) if topicName == "" { err = fmt.Errorf("deleteTopic failed: topicName is empty") //log.Printf("%v", err.Error()) return } param["topicName"] = topicName _, err, code = doCall(this.client, param, "DeleteTopic") if err != nil { //log.Printf("client.call DeleteTopic failed: %v\n", err.Error()) return } return } func (this *Account) ListTopic(searchWord string, offset, limit int) ( totalCount int, topicList []string, err error, code int) { code = DEFAULT_ERROR_CODE topicList = make([]string, 0) param := make(map[string]string) if searchWord != "" { param["searchWord"] = searchWord } if offset > 0 { param["offset"] = strconv.Itoa(offset) } if limit > 0 { param["limit"] = strconv.Itoa(limit) } resMap, err, code := doCall(this.client, param, "ListTopic") if err != nil { //log.Printf("client.call ListTopic failed: %v\n", err.Error()) return } totalCount = int(resMap["totalCount"].(float64)) resTopicList := resMap["topicList"].([]interface{}) for _, v := range resTopicList { topic := v.(map[string]interface{}) topicList = append(topicList, topic["topicName"].(string)) } return } func (this *Account) CreateSubscribe(topicName, subscriptionName, endpoint, protocol, notifyContentFormat string) ( err error, code int) { err, code = _createSubscribe( this.client, topicName, subscriptionName, endpoint, protocol, nil, nil, NotifyStrategyDefault, notifyContentFormat) return } func _createSubscribe(client *CMQClient, topicName, subscriptionName, endpoint, protocol string, filterTag []string, bindingKey []string, notifyStrategy, notifyContentFormat string) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) if topicName == "" { err = fmt.Errorf("createSubscribe failed: topicName is empty") //log.Printf("%v", err.Error()) return } param["topicName"] = topicName if subscriptionName == "" { err = fmt.Errorf("createSubscribe failed: subscriptionName is empty") //log.Printf("%v", err.Error()) return } param["subscriptionName"] = subscriptionName if endpoint == "" { err = fmt.Errorf("createSubscribe failed: endpoint is empty") //log.Printf("%v", err.Error()) return } param["endpoint"] = endpoint if protocol == "" { err = fmt.Errorf("createSubscribe failed: protocal is empty") //log.Printf("%v", err.Error()) return } param["protocol"] = protocol if notifyStrategy == "" { err = fmt.Errorf("createSubscribe failed: notifyStrategy is empty") //log.Printf("%v", err.Error()) return } param["notifyStrategy"] = notifyStrategy if notifyContentFormat == "" { err = fmt.Errorf("createSubscribe failed: notifyContentFormat is empty") //log.Printf("%v", err.Error()) return } param["notifyContentFormat"] = notifyContentFormat if filterTag != nil { for i, tag := range filterTag { param["filterTag."+strconv.Itoa(i+1)] = tag } } if bindingKey != nil { for i, key := range bindingKey { param["bindingKey."+strconv.Itoa(i+1)] = key } } _, err, code = doCall(client, param, "Subscribe") if err != nil { //log.Printf("client.call Subscribe failed: %v\n", err.Error()) return } return } func (this *Account) DeleteSubscribe(topicName, subscriptionName string) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) if topicName == "" { err = fmt.Errorf("createSubscribe failed: topicName is empty") //log.Printf("%v", err.Error()) return } param["topicName"] = topicName if subscriptionName == "" { err = fmt.Errorf("createSubscribe failed: subscriptionName is empty") //log.Printf("%v", err.Error()) return } param["subscriptionName"] = subscriptionName _, err, code = doCall(this.client, param, "Unsubscribe") if err != nil { //log.Printf("client.call Unsubscribe failed: %v\n", err.Error()) return } return } func (this *Account) GetSubscription(topicName, subscriptionName string) *Subscription { return NewSubscription(topicName, subscriptionName, this.client) } func doCall(client *CMQClient, param map[string]string, opration string) (resMap map[string]interface{}, err error, code int) { code = DEFAULT_ERROR_CODE res, err := client.call(opration, param) if err != nil { //log.Printf("client.call %v failed: %v\n", opration, err.Error()) return } //log.Printf("res: %v", res) resMap = make(map[string]interface{}, 0) err = json.Unmarshal([]byte(res), &resMap) if err != nil { //log.Printf(err.Error()) return } code = int(resMap["code"].(float64)) if code != 0 { err = fmt.Errorf("%v failed: code: %v, message: %v, requestId: %v", opration, code, resMap["message"], resMap["requestId"]) //log.Printf(err.Error()) return } return } <|start_filename|>cmq_http.go<|end_filename|> package cmq_go import ( "time" "net/http" "fmt" "io/ioutil" "net/url" "bytes" "errors" "net" ) const ( DEFAULT_HTTP_TIMEOUT = 3000 //ms ) type CMQHttp struct { isKeepAlive bool conn *http.Client } var DefaultTransport = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 500, MaxIdleConnsPerHost: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } func NewCMQHttp() *CMQHttp { return &CMQHttp{ isKeepAlive: true, conn: &http.Client{ Timeout: DEFAULT_HTTP_TIMEOUT * time.Millisecond, Transport: DefaultTransport, }, } } func (this *CMQHttp) setProxy(proxyUrlStr string) (err error) { if proxyUrlStr == "" { return } proxyUrl, err := url.Parse(proxyUrlStr) if err != nil { return } transport, err := this.getTransport() if err != nil { return } transport.Proxy = http.ProxyURL(proxyUrl) return } func (this *CMQHttp) unsetProxy() (err error) { transport, err := this.getTransport() if err != nil { return } transport.Proxy = nil return } func (this *CMQHttp) getTransport() (*http.Transport, error) { if this.conn.Transport == nil { this.SetTransport(DefaultTransport) } if transport, ok := this.conn.Transport.(*http.Transport); ok { return transport, nil } return nil, errors.New("transport is not an *http.Transport instance") } func (this *CMQHttp) SetTransport(transport http.RoundTripper) { this.conn.Transport = transport } func (this *CMQHttp) request(method, urlStr, reqStr string, userTimeout int) (result string, err error) { timeout := DEFAULT_HTTP_TIMEOUT if userTimeout >= 0 { timeout += userTimeout } this.conn.Timeout = time.Duration(timeout) * time.Millisecond req, err := http.NewRequest(method, urlStr, bytes.NewReader([]byte(reqStr))) if err != nil { return "", fmt.Errorf("make http req error %v", err) } resp, err := this.conn.Do(req) if err != nil { return "", fmt.Errorf("http error %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("http error code %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("read http resp body error %v", err) } result = string(body) return } <|start_filename|>queue_meta.go<|end_filename|> package cmq_go const ( /** 缺省消息接收长轮询等待时间 */ DEFAULT_POLLING_WAIT_SECONDS = 0 /** 缺省消息可见性超时 */ DEFAULT_VISIBILITY_TIMEOUT = 30 /** 缺省消息最大长度,单位字节 */ DEFAULT_MAX_MSG_SIZE = 1048576 /** 缺省消息保留周期,单位秒 */ DEFAULT_MSG_RETENTION_SECONDS = 345600 ) type QueueMeta struct { /** 最大堆积消息数 */ MaxMsgHeapNum int /** 消息接收长轮询等待时间 */ PollingWaitSeconds int /** 消息可见性超时 */ VisibilityTimeout int /** 消息最大长度 */ MaxMsgSize int /** 消息保留周期 */ MsgRetentionSeconds int /** 队列创建时间 */ CreateTime int /** 队列属性最后修改时间 */ LastModifyTime int /** 队列处于Active状态的消息总数 */ ActiveMsgNum int /** 队列处于Inactive状态的消息总数 */ InactiveMsgNum int /** 已删除的消息,但还在回溯保留时间内的消息数量 */ RewindMsgNum int /** 消息最小未消费时间 */ MinMsgTime int /** 延时消息数量 */ DelayMsgNum int /** 回溯时间 */ RewindSeconds int } <|start_filename|>test/cmq_topic_test.go<|end_filename|> package test import ( "testing" "github.com/NETkiddy/cmq-go" ) var endpointTopic = "https://cmq-topic-sh.api.qcloud.com" var endpointTopicInner = "http://cmq-topic-sh.api.tencentyun.com" //----------------------------------------------------------------- // 创建主题 func Test_CreateTopic(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) err, _ := account.CreateTopic("topic-test-001", 2048) if err != nil { t.Errorf("topic-test-001 created failed, %v", err.Error()) return } t.Log("topic-test-001 created") err, _ = account.CreateTopic("topic-test-002", 4096) if err != nil { t.Errorf("topic-test-002 created failed, %v", err.Error()) return } t.Log("topic-test-002 created") } // 删除主题 func Test_ListTopic(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) totalCount, topicList, err, _ := account.ListTopic("", -1, -1) if err != nil { t.Errorf("ListTopic failed, %v", err.Error()) return } t.Logf("totalCount, %v", totalCount) t.Logf("topicList, %v", topicList) } // 获取主题 func Test_GetTopic(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) topic := account.GetTopic("topic-test-001") t.Logf("GetTopic, %v", *topic) } // 删除主题 func Test_DeleteTopic(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) err, _ := account.DeleteTopic("topic-test-001") if err != nil { t.Errorf("DeleteTopic failed, %v", err.Error()) return } t.Logf("DeleteTopic, %v", "topic-test-001") } //----------------------------------------------------------------- // 设置,获取主题属性 func Test_GetSetTopicAttributes(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) topic := account.GetTopic("topic-test-001") t.Logf("GetTopic, %v", *topic) // get meta meta, err, _ := topic.GetTopicAttributes() if err != nil { t.Errorf("GetTopicAttributes failed, %v", err.Error()) return } t.Logf("GetTopicAttributes, before set, %v", meta) // set meta meta.MaxMsgSize = 32768 topic.SetTopicAttributes(meta.MaxMsgSize) // get meta newMeta, err, _ := topic.GetTopicAttributes() if err != nil { t.Errorf("GetTopicAttributes failed, %v", err.Error()) return } t.Logf("GetTopicAttributes, after set, %v", newMeta) } // 创建订阅者 func Test_CreateSubscribe(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) err, _ := account.CreateSubscribe("topic-test-001", "sub-test", "queue-test-001", "queue", "SIMPLIFIED") if err != nil { t.Errorf("CreateSubscribe failed, %v", err.Error()) return } t.Logf("CreateSubscribe succeed") } // 获取订阅者 func Test_GetSubscribe(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) // get sub := account.GetSubscription("topic-test-001", "sub-test") t.Logf("GetSubscription succeed: %v", sub) // set meta meta, err, _ := sub.GetSubscriptionAttributes() if err != nil { t.Errorf("CreateSubscribe failed, %v", err.Error()) return } t.Logf("GetSubscriptionAttributes succeed: %v", meta) } // 获取所有主题订阅者 func Test_ListSubscription(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) topic := account.GetTopic("topic-test-001") t.Logf("GetTopic, %v", topic) totalCount, subscriptionList, err, _ := topic.ListSubscription(-1, -1, "") if err != nil { t.Errorf("ListSubscription failed, %v", err.Error()) return } t.Logf("ListSubscription totalCount, %v", totalCount) t.Logf("ListSubscription subscriptionList, %v", subscriptionList) } // 发布消息 func Test_PublishMessage(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) topic := account.GetTopic("topic-test-001") t.Logf("GetTopic, %v", topic) msgId, err, _ := topic.PublishMessage("hello world") if err != nil { t.Errorf("PublishMessage failed, %v", err.Error()) return } t.Logf("PublishMessage msgId, %v", msgId) } // 批量发布消息 func Test_BatchPublishMessage(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) topic := account.GetTopic("topic-test-001") t.Logf("GetTopic, %v", topic) msgs := []string{"hello world", "foo", "bar"} msgIds, err, _ := topic.BatchPublishMessage(msgs) if err != nil { t.Errorf("BatchPublishMessage failed, %v", err.Error()) return } t.Logf("BatchPublishMessage msgIds, %v", msgIds) } // 删除主题订阅者 func Test_DeleteSubscription(t *testing.T) { account := cmq_go.NewAccount(endpointTopic, secretId, secretKey) err, _ := account.DeleteSubscribe("topic-test-001", "sub-test") if err != nil { t.Errorf("DeleteSubscribe failed, %v", err.Error()) return } t.Logf("DeleteSubscribe succeed") } <|start_filename|>topic_meta.go<|end_filename|> package cmq_go type TopicMeta struct { // 当前该主题的消息堆积数 MsgCount int // 消息最大长度,取值范围1024-1048576 Byte(即1-1024K),默认1048576 MaxMsgSize int //消息在主题中最长存活时间,从发送到该主题开始经过此参数指定的时间后, //不论消息是否被成功推送给用户都将被删除,单位为秒。固定为一天,该属性不能修改。 MsgRetentionSeconds int //创建时间 CreateTime int //修改属性信息最近时间 LastModifyTime int LoggingEnabled int FilterType int } func NewTopicMeta() *TopicMeta { return &TopicMeta{ MsgCount: 0, MaxMsgSize: 1048576, MsgRetentionSeconds: 86400, CreateTime: 0, LastModifyTime: 0, LoggingEnabled: 0, FilterType: 1, } } <|start_filename|>queue.go<|end_filename|> package cmq_go import ( "strconv" "fmt" ) type Queue struct { queueName string client *CMQClient } func NewQueue(queueName string, client *CMQClient) (queue *Queue) { return &Queue{ queueName: queueName, client: client, } } func (this *Queue) SetQueueAttributes(queueMeta QueueMeta) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["queueName"] = this.queueName if queueMeta.MaxMsgHeapNum > 0 { param["maxMsgHeapNum"] = strconv.Itoa(queueMeta.MaxMsgHeapNum) } if queueMeta.PollingWaitSeconds > 0 { param["pollingWaitSeconds"] = strconv.Itoa(queueMeta.PollingWaitSeconds) } if queueMeta.VisibilityTimeout > 0 { param["visibilityTimeout"] = strconv.Itoa(queueMeta.VisibilityTimeout) } if queueMeta.MaxMsgSize > 0 { param["maxMsgSize"] = strconv.Itoa(queueMeta.MaxMsgSize) } if queueMeta.MsgRetentionSeconds > 0 { param["msgRetentionSeconds"] = strconv.Itoa(queueMeta.MsgRetentionSeconds) } if queueMeta.RewindSeconds > 0 { param["rewindSeconds"] = strconv.Itoa(queueMeta.RewindSeconds) } _, err, code = doCall(this.client, param, "SetQueueAttributes") if err != nil { //log.Printf("client.call SetQueueAttributes failed: %v\n", err.Error()) return } return } func (this *Queue) GetQueueAttributes() (queueMeta QueueMeta, err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["queueName"] = this.queueName resMap, err, code := doCall(this.client, param, "GetQueueAttributes") if err != nil { //log.Printf("client.call GetQueueAttributes failed: %v\n", err.Error()) return } queueMeta.MaxMsgHeapNum = int(resMap["maxMsgHeapNum"].(float64)) queueMeta.PollingWaitSeconds = int(resMap["pollingWaitSeconds"].(float64)) queueMeta.VisibilityTimeout = int(resMap["visibilityTimeout"].(float64)) queueMeta.MaxMsgSize = int(resMap["maxMsgSize"].(float64)) queueMeta.MsgRetentionSeconds = int(resMap["msgRetentionSeconds"].(float64)) queueMeta.CreateTime = int(resMap["createTime"].(float64)) queueMeta.LastModifyTime = int(resMap["lastModifyTime"].(float64)) queueMeta.ActiveMsgNum = int(resMap["activeMsgNum"].(float64)) queueMeta.InactiveMsgNum = int(resMap["inactiveMsgNum"].(float64)) queueMeta.RewindMsgNum = int(resMap["rewindMsgNum"].(float64)) queueMeta.MinMsgTime = int(resMap["minMsgTime"].(float64)) queueMeta.DelayMsgNum = int(resMap["delayMsgNum"].(float64)) queueMeta.RewindSeconds = int(resMap["rewindSeconds"].(float64)) return } func (this *Queue) SendMessage(msgBody string) (messageId string, err error, code int) { messageId, err, code = _sendMessage(this.client, msgBody, this.queueName, 0) return } func (this *Queue) SendDelayMessage(msgBody string, delaySeconds int) (messageId string, err error, code int) { messageId, err, code = _sendMessage(this.client, msgBody, this.queueName, delaySeconds) return } func _sendMessage(client *CMQClient, msgBody, queueName string, delaySeconds int) (messageId string, err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["queueName"] = queueName param["msgBody"] = msgBody param["delaySeconds"] = strconv.Itoa(delaySeconds) resMap, err, code := doCall(client, param, "SendMessage") if err != nil { //log.Printf("client.call GetQueueAttributes failed: %v\n", err.Error()) return } messageId = resMap["msgId"].(string) return } func (this *Queue) BatchSendMessage(msgBodys []string) (messageIds []string, err error, code int) { messageIds, err, code = _batchSendMessage(this.client, msgBodys, this.queueName, 0) return } func (this *Queue) BatchSendDelayMessage(msgBodys []string, delaySeconds int) (messageIds []string, err error, code int) { messageIds, err, code = _batchSendMessage(this.client, msgBodys, this.queueName, delaySeconds) return } func _batchSendMessage(client *CMQClient, msgBodys []string, queueName string, delaySeconds int) (messageIds []string, err error, code int) { code = DEFAULT_ERROR_CODE messageIds = make([]string, 0) if len(msgBodys) == 0 || len(msgBodys) > 16 { err = fmt.Errorf("message size is 0 or more than 16") //log.Printf("%v", err.Error()) return } param := make(map[string]string) param["queueName"] = queueName for i, msgBody := range msgBodys { param["msgBody."+strconv.Itoa(i+1)] = msgBody } param["delaySeconds"] = strconv.Itoa(delaySeconds) resMap, err, code := doCall(client, param, "BatchSendMessage") if err != nil { //log.Printf("client.call BatchSendMessage failed: %v\n", err.Error()) return } msgList := resMap["msgList"].([]interface{}) for _, v := range msgList { msg := v.(map[string]interface{}) messageIds = append(messageIds, msg["msgId"].(string)) } return } func (this *Queue) ReceiveMessage(pollingWaitSeconds int) (msg Message, err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["queueName"] = this.queueName if pollingWaitSeconds >= 0 { param["UserpollingWaitSeconds"] = strconv.Itoa(pollingWaitSeconds * 1000) param["pollingWaitSeconds"] = strconv.Itoa(pollingWaitSeconds) } else { param["UserpollingWaitSeconds"] = strconv.Itoa(30000) } resMap, err, code := doCall(this.client, param, "ReceiveMessage") if err != nil { //log.Printf("client.call ReceiveMessage failed: %v\n", err.Error()) return } msg.MsgId = resMap["msgId"].(string) msg.ReceiptHandle = resMap["receiptHandle"].(string) msg.MsgBody = resMap["msgBody"].(string) msg.EnqueueTime = int64(resMap["enqueueTime"].(float64)) msg.NextVisibleTime = int64(resMap["nextVisibleTime"].(float64)) msg.FirstDequeueTime = int64(resMap["firstDequeueTime"].(float64)) msg.DequeueCount = int(resMap["dequeueCount"].(float64)) return } func (this *Queue) BatchReceiveMessage(numOfMsg, pollingWaitSeconds int) (msgs []Message, err error, code int) { code = DEFAULT_ERROR_CODE msgs = make([]Message, 0) param := make(map[string]string) param["queueName"] = this.queueName param["numOfMsg"] = strconv.Itoa(numOfMsg) if pollingWaitSeconds >= 0 { param["UserpollingWaitSeconds"] = strconv.Itoa(pollingWaitSeconds * 1000) param["pollingWaitSeconds"] = strconv.Itoa(pollingWaitSeconds) } else { param["UserpollingWaitSeconds"] = strconv.Itoa(30000) } resMap, err, code := doCall(this.client, param, "BatchReceiveMessage") if err != nil { //log.Printf("client.call BatchReceiveMessage failed: %v\n", err.Error()) return } msgInfoList := resMap["msgInfoList"].([]interface{}) for _, v := range msgInfoList { msgInfo := v.(map[string]interface{}) msg := Message{} msg.MsgId = msgInfo["msgId"].(string) msg.ReceiptHandle = msgInfo["receiptHandle"].(string) msg.MsgBody = msgInfo["msgBody"].(string) msg.EnqueueTime = int64(msgInfo["enqueueTime"].(float64)) msg.NextVisibleTime = int64(msgInfo["nextVisibleTime"].(float64)) msg.FirstDequeueTime = int64(msgInfo["firstDequeueTime"].(float64)) msg.DequeueCount = int(msgInfo["dequeueCount"].(float64)) msgs = append(msgs, msg) } return } func (this *Queue) DeleteMessage(receiptHandle string) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["queueName"] = this.queueName param["receiptHandle"] = receiptHandle _, err, code = doCall(this.client, param, "DeleteMessage") if err != nil { //log.Printf("client.call DeleteMessage failed: %v\n", err.Error()) return } return } func (this *Queue) BatchDeleteMessage(receiptHandles []string) (err error, code int) { code = DEFAULT_ERROR_CODE if len(receiptHandles) == 0 { return } param := make(map[string]string) param["queueName"] = this.queueName for i, receiptHandle := range receiptHandles { param["receiptHandle."+strconv.Itoa(i+1)] = receiptHandle } _, err, code = doCall(this.client, param, "BatchDeleteMessage") if err != nil { //log.Printf("client.call BatchDeleteMessage failed: %v\n", err.Error()) return } return } func (this *Queue) RewindQueue(backTrackingTime int) (err error, code int) { code = DEFAULT_ERROR_CODE if backTrackingTime <= 0 { return } param := make(map[string]string) param["queueName"] = this.queueName param["startConsumeTime"] = strconv.Itoa(backTrackingTime) _, err, code = doCall(this.client, param, "RewindQueue") if err != nil { //log.Printf("client.call RewindQueue failed: %v\n", err.Error()) return } return } <|start_filename|>subscription_meta.go<|end_filename|> package cmq_go const ( NotifyStrategyDefault = "BACKOFF_RETRY" NotifyContentFormatDefault = "JSON" NotifyContentFormatSimplified = "SIMPLIFIED" ) type SubscriptionMeta struct { //Subscription 订阅的主题所有者的appId TopicOwner string //订阅的终端地址 Endpoint string //订阅的协议 Protocal string //推送消息出现错误时的重试策略 NotifyStrategy string //向 Endpoint 推送的消息内容格式 NotifyContentFormat string //描述了该订阅中消息过滤的标签列表(仅标签一致的消息才会被推送) FilterTag []string //Subscription 的创建时间,从 1970-1-1 00:00:00 到现在的秒值 CreateTime int //修改 Subscription 属性信息最近时间,从 1970-1-1 00:00:00 到现在的秒值 LastModifyTime int //该订阅待投递的消息数 MsgCount int BindingKey []string } func NewSubscriptionMeta() *SubscriptionMeta { return &SubscriptionMeta{ TopicOwner: "", Endpoint: "", Protocal: "", NotifyStrategy: NotifyStrategyDefault, NotifyContentFormat: NotifyContentFormatDefault, FilterTag: nil, CreateTime: 0, LastModifyTime: 0, MsgCount: 0, BindingKey: nil, } } <|start_filename|>sign.go<|end_filename|> package cmq_go import ( "crypto/sha1" "crypto/sha256" "hash" "crypto/hmac" "encoding/base64" ) const ( SIGN_ALGORITHM_SHA1 = "sha1" ) func Sign(src, key, method string) string{ var mac hash.Hash if method == SIGN_ALGORITHM_SHA1{ mac = hmac.New(sha1.New, []byte(key)) }else{ mac = hmac.New(sha256.New, []byte(key)) } mac.Write([]byte(src)) return base64.StdEncoding.EncodeToString(mac.Sum(nil)) } <|start_filename|>subscription.go<|end_filename|> package cmq_go import ( "strconv" ) type Subscription struct { topicName string subscriptionName string client *CMQClient } func NewSubscription(topicName, subscriptionName string, client *CMQClient) *Subscription { return &Subscription{ topicName: topicName, subscriptionName: subscriptionName, client: client, } } func (this *Subscription) ClearFilterTags() (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["topicName"] = this.topicName param["subscriptionName "] = this.subscriptionName _, err, code = doCall(this.client, param, "ClearSubscriptionFilterTags") if err != nil { //log.Printf("client.call ClearSubscriptionFilterTags failed: %v\n", err.Error()) return } return } func (this *Subscription) SetSubscriptionAttributes(meta SubscriptionMeta) (err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["topicName"] = this.topicName param["subscriptionName "] = this.subscriptionName if meta.NotifyStrategy != "" { param["notifyStrategy"] = meta.NotifyStrategy } if meta.NotifyContentFormat != "" { param["notifyContentFormat"] = meta.NotifyContentFormat } if meta.FilterTag != nil { for i, flag := range meta.FilterTag { param["filterTag."+strconv.Itoa(i+1)] = flag } } if meta.BindingKey != nil { for i, binding := range meta.BindingKey { param["bindingKey."+strconv.Itoa(i+1)] = binding } } _, err, code = doCall(this.client, param, "SetSubscriptionAttributes") if err != nil { //log.Printf("client.call SetSubscriptionAttributes failed: %v\n", err.Error()) return } return } func (this *Subscription) GetSubscriptionAttributes() (meta *SubscriptionMeta, err error, code int) { code = DEFAULT_ERROR_CODE param := make(map[string]string) param["topicName"] = this.topicName param["subscriptionName"] = this.subscriptionName resMap, err, code := doCall(this.client, param, "GetSubscriptionAttributes") if err != nil { //log.Printf("client.call GetSubscriptionAttributes failed: %v\n", err.Error()) return } meta = NewSubscriptionMeta() meta.FilterTag = make([]string, 0) meta.BindingKey = make([]string, 0) meta.TopicOwner = resMap["topicOwner"].(string) meta.Endpoint = resMap["endpoint"].(string) meta.Protocal = resMap["protocol"].(string) meta.NotifyStrategy = resMap["notifyStrategy"].(string) meta.NotifyContentFormat = resMap["notifyContentFormat"].(string) meta.CreateTime = int(resMap["createTime"].(float64)) meta.LastModifyTime = int(resMap["lastModifyTime"].(float64)) meta.MsgCount = int(resMap["msgCount"].(float64)) if filterTag, found := resMap["filterTag"]; found { for _, v := range filterTag.([]interface{}) { filter := v.(string) meta.FilterTag = append(meta.FilterTag, filter) } } if bindingKey, found := resMap["bindingKey"]; found { for _, v := range bindingKey.([]interface{}) { binding := v.(string) meta.BindingKey = append(meta.BindingKey, binding) } } return } <|start_filename|>message.go<|end_filename|> package cmq_go type Message struct { /** 服务器返回的消息ID */ MsgId string /** 每次消费唯一的消息句柄,用于删除等操作 */ ReceiptHandle string /** 消息体 */ MsgBody string /** 消息发送到队列的时间,从 1970年1月1日 00:00:00 000 开始的毫秒数 */ EnqueueTime int64 /** 消息下次可见的时间,从 1970年1月1日 00:00:00 000 开始的毫秒数 */ NextVisibleTime int64 /** 消息第一次出队列的时间,从 1970年1月1日 00:00:00 000 开始的毫秒数 */ FirstDequeueTime int64 /** 出队列次数 */ DequeueCount int MsgTag []string }
whua3/cmq-go
<|start_filename|>casting.js<|end_filename|> /* Magic Mirror * Module: MMM-chromecast * * By flo * MIT Licensed * * Using https://github.com/DeMille/url-cast-receiver as chromecast receiver */ var applicationID = '5CB45E5A' , namespace = 'urn:x-cast:com.url.cast' , receiverDead = false , session = null; function initializeCastApi() { var sessionRequest = new chrome.cast.SessionRequest(applicationID); var apiConfig = new chrome.cast.ApiConfig( sessionRequest, sessionListener, receiverListener ); chrome.cast.initialize( apiConfig, onSuccess.bind(this, 'initialized ok'), onErr ); } function onErr(err) { console.log('Err: ' + JSON.stringify(err)); } function onSuccess(msg) { console.log('Sucess: ' + msg); } function sessionListener(newSession) { console.log('New session ID:' + newSession.sessionId); session = newSession; session.addUpdateListener(sessionUpdateListener); session.addMessageListener(namespace, receiveMessage); sendMessage({type:"loc",url: document.location.href}); } function receiverListener(e) { (e === 'available') ? console.log('receiver found') : console.log('no receivers found'); } function sessionUpdateListener(isAlive) { if (!isAlive) { session = null; } console.log('Session is alive?: ', isAlive); } function receiveMessage(namespace, msg) { console.log('Receiver said: ' + msg); } function sendMessage(msg) { if (receiverDead || !session) return; // send msg session.sendMessage( namespace, msg, function() { console.log('Message sent: ', msg); notify('Message sent: ' + JSON.stringify(msg)); }, onErr ); if (msg.type === 'loc') { receiverDead = true; } } function notify(msg) { var el = document.getElementById('notifications'), notice = document.createElement('div'); if (el == null) return; notice.className = 'notification'; notice.innerHTML = msg; el.appendChild(notice); // notice self destruct timer setTimeout(function () { el.removeChild(notice); }, 5000); } <|start_filename|>MMM-chromecast.js<|end_filename|> /* Magic Mirror * Module: MMM-chromecast * * By flo * MIT Licensed */ Module.register("MMM-chromecast", { getScripts: function() { return ["//www.gstatic.com/cv/js/sender/v1/cast_sender.js","casting.js"]; }, notificationReceived: function(notification, payload, sender) { if (notification === "DOM_OBJECTS_CREATED") { //Note: should react to window event but event listeners don't work initializeCastApi(); } }, getDom: function() { var wrapper = document.createElement('div'); return wrapper; } });
flo80/MMM-chromecast
<|start_filename|>.vscode/settings.json<|end_filename|> { "editor.tabSize": 4, "editor.renderWhitespace": "none", "editor.insertSpaces": true, "typescript.reportStyleChecksAsWarnings": true, "editor.trimAutoWhitespace": true, "tslint.jsEnable": true, "tslint.run": "onType", "typescript.tsdk": "node_modules/typescript/lib", }
admariner/data-forge-plot
<|start_filename|>Dockerfile<|end_filename|> FROM scratch COPY VERSION / <|start_filename|>hack/mkdocs/Dockerfile<|end_filename|> FROM squidfunk/mkdocs-material:7.3.4 RUN pip install \ mdx_truly_sane_lists \ mkdocs-awesome-pages-plugin <|start_filename|>Makefile<|end_filename|> .PHONY: help docs build-docs help: @echo "Run make docs or make build-docs" ## check documents http://localhost:8000 docs: edp-docs-image @docker run --rm -it \ -p 8000:8000 \ -v ${PWD}:/docs \ --entrypoint mkdocs \ edp-docs serve --dev-addr=0.0.0.0:8000 build-docs: edp-docs-image @docker run --rm -it \ -v ${PWD}:/docs \ --entrypoint mkdocs \ edp-docs build edp-docs-image: @docker build -t edp-docs hack/mkdocs
epam/edp-install
<|start_filename|>sessiondescription_test.go<|end_filename|> package sdp const ( exampleAttrExtmap1 = "extmap:1 http://example.com/082005/ext.htm#ttime" exampleAttrExtmap1Line = exampleAttrExtmap1 exampleAttrExtmap2 = "extmap:2/sendrecv http://example.com/082005/ext.htm#xmeta short" exampleAttrExtmap2Line = exampleAttrExtmap2 failingAttrExtmap1 = "extmap:257/sendrecv http://example.com/082005/ext.htm#xmeta short" failingAttrExtmap1Line = attributeKey + failingAttrExtmap1 failingAttrExtmap2 = "extmap:2/blorg http://example.com/082005/ext.htm#xmeta short" failingAttrExtmap2Line = attributeKey + failingAttrExtmap2 ) <|start_filename|>direction.go<|end_filename|> package sdp import "errors" //Direction is a marker for transmission directon of an endpoint type Direction int const ( //DirectionSendRecv is for bidirectional communication DirectionSendRecv Direction = iota + 1 //DirectionSendOnly is for outgoing communication DirectionSendOnly //DirectionRecvOnly is for incoming communication DirectionRecvOnly //DirectionInactive is for no communication DirectionInactive ) const ( directionSendRecvStr = "sendrecv" directionSendOnlyStr = "sendonly" directionRecvOnlyStr = "recvonly" directionInactiveStr = "inactive" directionUnknownStr = "" ) var errDirectionString = errors.New("invalid direction string") // NewDirection defines a procedure for creating a new direction from a raw // string. func NewDirection(raw string) (Direction, error) { switch raw { case directionSendRecvStr: return DirectionSendRecv, nil case directionSendOnlyStr: return DirectionSendOnly, nil case directionRecvOnlyStr: return DirectionRecvOnly, nil case directionInactiveStr: return DirectionInactive, nil default: return Direction(unknown), errDirectionString } } func (t Direction) String() string { switch t { case DirectionSendRecv: return directionSendRecvStr case DirectionSendOnly: return directionSendOnlyStr case DirectionRecvOnly: return directionRecvOnlyStr case DirectionInactive: return directionInactiveStr default: return directionUnknownStr } } <|start_filename|>direction_test.go<|end_filename|> package sdp import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewDirection(t *testing.T) { passingtests := []struct { value string expected Direction }{ {"sendrecv", DirectionSendRecv}, {"sendonly", DirectionSendOnly}, {"recvonly", DirectionRecvOnly}, {"inactive", DirectionInactive}, } failingtests := []string{ "", "notadirection", } for i, u := range passingtests { dir, err := NewDirection(u.value) assert.NoError(t, err) assert.Equal(t, u.expected, dir, "%d: %+v", i, u) } for _, u := range failingtests { _, err := NewDirection(u) assert.Error(t, err) } } func TestDirection_String(t *testing.T) { tests := []struct { actual Direction expected string }{ {Direction(unknown), directionUnknownStr}, {DirectionSendRecv, "sendrecv"}, {DirectionSendOnly, "sendonly"}, {DirectionRecvOnly, "recvonly"}, {DirectionInactive, "inactive"}, } for i, u := range tests { assert.Equal(t, u.expected, u.actual.String(), "%d: %+v", i, u) } }
jbrady42/sdp
<|start_filename|>specs/slow-processing.test.js<|end_filename|> 'use strict' /* global describe, it */ const request = require('supertest') describe('Slow requests processing', () => { let server const service = require('../index')({ prioRequestsProcessing: false }) service.get('/hello', (req, res) => { res.send(200) }) it('should start the service with "prioRequestsProcessing: FALSE"', async () => { server = await service.start(~~process.env.PORT) }) it('should GET 200 on /hello', async () => { await request(server) .get('/hello') .expect(200) }) it('should successfully terminate the service', async () => { await service.close() }) }) <|start_filename|>demos/socket.io-https-server.js<|end_filename|> 'use strict' const http = require('https') const pem = require('pem') pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => { if (err) console.error(err) const app = require('../index')({ server: http.createServer({ key: keys.serviceKey, cert: keys.certificate }) }) const io = require('socket.io')() io.on('connection', socket => { console.log(socket.id) }) io.listen(app.getServer()) io.set('origins', '*:*') app.start(3000) }) <|start_filename|>specs/routes-chaining.test.js<|end_filename|> 'use strict' /* global describe, it */ const request = require('supertest') describe('Routes registration - method chaining', () => { let server const service = require('../index')() const op200 = (req, res) => { res.send() } service .get('/', op200) .post('/', op200) .get('/chain', op200) it('should start service', async () => { server = await service.start(~~process.env.PORT) }) it('should GET 200 for all registered routes', async () => { await request(server) .get('/') .expect(200) await request(server) .post('/') .expect(200) await request(server) .get('/chain') .expect(200) }) it('should successfully terminate the service', async () => { await service.close() }) }) <|start_filename|>performance/native-http3.js<|end_filename|> 'use strict' const http2 = require('http2') const pem = require('pem') pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => { if (err) console.error(err) const service = http2.createSecureServer({ key: keys.serviceKey, cert: keys.certificate }) // streams API example service.on('stream', (stream, headers) => { if (headers[':path'] === '/hi' && headers[':method'] === 'GET') { stream.respond({ 'content-type': 'text/html', ':status': 200 }) stream.end('Hello World!') } else { stream.respond({ ':status': 404 }) stream.end() } }) service.listen(3000) }) <|start_filename|>demos/swagger/controllers/Helloer.js<|end_filename|> 'use strict' module.exports = (router) => { router.get('/sayHi/:name', (req, res) => { res.send({ name: req.swagger.params.name.value, format: req.swagger.params.format.value }) }) return router } <|start_filename|>specs/disable-response-event.test.js<|end_filename|> 'use strict' /* global describe, it */ const request = require('supertest') const expect = require('chai').expect describe('Disable Response Event', () => { let server const service = require('../index')({ disableResponseEvent: true }) service.use((req, res, next) => { const now = new Date().getTime() res.on('response', (e) => { e.res.setHeader('x-response-time', new Date().getTime() - now) }) return next() }) service.get('/hello', (req, res) => { res.send(200) }) it('should start the service with "disableResponseEvent: TRUE"', async () => { server = await service.start(~~process.env.PORT) }) it('should GET 200 on /hello and no response header', async () => { await request(server) .get('/hello') .expect(200) .then((response) => { expect(response.headers['x-response-time']).to.equal(undefined) }) }) it('should successfully terminate the service', async () => { await service.close() }) }) <|start_filename|>demos/raw-body.js<|end_filename|> 'use strict' const service = require('./../index')({}) const rawbody = require('raw-body') service.use(async (req, res, next) => { try { await rawbody(req, { length: req.headers['content-length'], limit: '500kb' }) } catch (err) { res.statusCode = 400 res.statusMessage = err.message } next() }) service.post('/upload', (req, res) => { // ... manage file upload res.send() }) service.start() <|start_filename|>performance/fastify-validation-serialization.js<|end_filename|> 'use strict' const fastify = require('fastify')() fastify.route({ method: 'GET', url: '/:name/:age', schema: { params: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' } } }, response: { 200: { type: 'object', properties: { msg: { type: 'string' }, name: { type: 'boolean' }, age: { type: 'number' }, numbers: { type: 'array', items: { type: 'number' } } } } } }, handler: async (request) => { const { name, age } = request.params return { msg: `Dear ${name}, you still can learn at your ${age}s ` + 'that fastify is awesome ;)', name, age, numbers: [...Array(1000).keys()] } } }) fastify.listen(3000) <|start_filename|>performance/restana-minimal-low.js<|end_filename|> 'use strict' const low = require('0http/lib/server/low') const service = require('../index')({ prioRequestsProcessing: false, server: low() }) service.get('/hi', (req, res) => { res.send('Hello World!') }) service.start(3000, (socket) => { if (socket) { console.log('HTTP server running at http://localhost:3000') } }) <|start_filename|>demos/swagger/index.js<|end_filename|> 'use strict' const service = require('./../../index')({}) const swagger = require('swagger-tools') const spec = require('./swagger.json') const helloerController = require('./controllers/Helloer') swagger.initializeMiddleware(spec, async (middleware) => { service.use(middleware.swaggerMetadata()) service.use(middleware.swaggerValidator()) service.use(middleware.swaggerUi()) service.use('/api', helloerController(service.newRouter())) await service.start(8000) console.log('API documentation is now running at http://localhost:8000/docs/') }) <|start_filename|>performance/koa-minimal-json.js<|end_filename|> 'use strict' const Koa = require('koa') const service = new Koa() const router = require('koa-router')() router.get('/hi', async (ctx) => { ctx.body = { msg: 'Hello World!' } ctx.status = 200 }) service.use(router.routes()) service.listen(3000) <|start_filename|>performance/restify-minimal-json.js<|end_filename|> 'use strict' const restify = require('restify') const server = restify.createServer() server.get('/hi', (req, res, next) => { res.send({ msg: 'Hello World!' }) next() }) server.listen(3000) <|start_filename|>performance/express-minimal-json.js<|end_filename|> 'use strict' const service = require('express')({}) service.get('/hi', (req, res) => { res.send({ msg: 'Hello World!' }) }) service.listen(3000) <|start_filename|>demos/https-service.js<|end_filename|> 'use strict' const https = require('https') const pem = require('pem') pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => { if (err) console.error(err) const service = require('./../index')({ server: https.createServer({ key: keys.serviceKey, cert: keys.certificate }) }) service.get('/v1/welcome', (req, res) => { res.send('Hello World!') }) service.start() }) <|start_filename|>demos/express-jwt.js<|end_filename|> 'use strict' const service = require('./../index')({}) const jwt = require('express-jwt') service.use( jwt({ secret: 'shhhhhhared-secret' }).unless({ path: ['/login'] }) ) service.get('/login', (req, res) => { res.send() }) service.get('/protected', (req, res) => { res.send() }) // start the server service.start() <|start_filename|>specs/elastic-apm.test.js<|end_filename|> 'use strict' /* global describe, it, beforeEach */ const expect = require('chai').expect const request = require('supertest') const elasticApm = require('./../libs/elastic-apm') describe('Elastic APM Instrumentation', () => { let server let pattern = null const { patch } = elasticApm({ apm: { setTransactionName (name) { pattern = name } } }) beforeEach(() => { pattern = null }) const service = require('../index')() patch(service) service.get('/hello', (req, res) => { res.send('Hello World!') }) service.get('/user/:id', (req, res) => { res.send({ id: req.params.id }) }) it('should start service', async () => { server = await service.start(~~process.env.PORT) }) it('should set transaction name = route pattern (/hello)', async () => { await request(server) .get('/hello') .expect(200) .then((response) => { expect(response.text).to.equal('Hello World!') }) expect(pattern).to.equal('GET /hello') }) it('should not set pattern on 404', async () => { await request(server) .get('/404') .expect(404) expect(pattern).to.equal(null) }) it('should set transaction name = route pattern (/user/:id)', async () => { await request(server) .get('/user/restana') .expect(200) .then((response) => { expect(response.body.id).to.equal('restana') }) expect(pattern).to.equal('GET /user/:id') }) it('should successfully terminate the service', async () => { await service.close() }) }) <|start_filename|>performance/native-http2.js<|end_filename|> 'use strict' const http = require('http2') const service = http.createServer() // backward API compatibility service.on('request', (req, res) => { if (req.method === 'GET' && req.url === '/hi') { res.writeHead(200, { 'Content-Type': 'text/plain' }) res.end('Hello World!') } else { res.statusCode = 404 res.end() } }) service.listen(3000) <|start_filename|>libs/apm-base.js<|end_filename|> 'use strict' const methods = require('./methods') module.exports = (options) => { const agent = options.apm || options.agent return { patch (app) { methods.forEach(method => { const ref = app[method] app[method] = (path, ...args) => { args.unshift((req, res, next) => { agent.setTransactionName(`${req.method} ${path}`) return next() }) return ref(path, args) } }) } } } <|start_filename|>demos/morgan.js<|end_filename|> 'use strict' const service = require('./../index')({}) const morgan = require('morgan') service.use(morgan('tiny')) service.get('/v1/welcome', (req, res) => { res.send('Hello World!') }) // start the server service.start() <|start_filename|>performance/polka-minimal.js<|end_filename|> 'use strict' const service = require('polka')({}) service.get('/hi', (req, res) => { res.end('Hello World!') }) service.listen(3000) <|start_filename|>demos/response-time.js<|end_filename|> 'use strict' const service = require('./../index')({}) // custom middleware to attach the X-Response-Time header to the response service.use(require('response-time')()) // the /v1/welcome route handler service.get('/v1/welcome', (req, res) => { res.send('Hello World!') }) // start the server service.start() <|start_filename|>libs/tasks/postinstall.js<|end_filename|> 'use strict' if (process.env.NODE_ENV !== 'production') { console.log('\u001b[32mLove restana? Take 30 seconds to share your happiness:\u001b[22m\u001b[39m\n > \u001b[96m\u001b[1mhttps://goo.gl/forms/qlBwrf5raqfQwteH3\u001b[0m\n') } <|start_filename|>libs/newrelic-apm.js<|end_filename|> 'use strict' const apm = require('./apm-base') /** * New Relic APM custom instrumentation * * Supported features: * - route names */ module.exports = (options) => apm(options)
silverwind/ana
<|start_filename|>DTXMania2/ステージ/07演奏/動画の表示サイズ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.演奏 { enum 動画の表示サイズ : int { 全画面 = 0, 中央寄せ = 1, } } <|start_filename|>FDK/イメージ/GraphicResources.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { public class GraphicResources : IDisposable { // プロパティ /// <summary> /// メインフォームインスタンスのウィンドウハンドル。 /// </summary> /// <remarks> /// GUIスレッド 以 外 のスレッドから参照する場合は、Form.Handle ではなくこのメンバを参照すること。 /// (Form のメンバはすべて、必ずGUIスレッドから参照されなれければならないため。) /// </remarks> public IntPtr Handle { get; set; } = IntPtr.Zero; /// <summary> /// 設計(プログラム側)で想定する固定画面サイズ[dpx]。 /// </summary> /// <remarks> /// 物理画面サイズはユーザが自由に変更できるが、プログラム側では常に設計画面サイズを使うことで、 /// 物理画面サイズに依存しない座標をハードコーディングできるようにする。 /// プログラム内では設計画面におけるピクセルの単位として「dpx (designed pixel)」と称することがある。 /// なお、int より float での利用が多いので、Size や Size2 ではなく Size2F を使う。 /// (int 同士ということを忘れて、割り算しておかしくなるケースも多発したので。) /// </remarks> public SharpDX.Size2F 設計画面サイズ { get; private set; } /// <summary> /// 実際の画面サイズ(ウィンドウのクライアントサイズ)。 /// </summary> public SharpDX.Size2F 物理画面サイズ { get; private set; } /// <summary> /// 等倍3D平面での画面左上の3D座標。 /// D2D描画では使用しないこと。 /// </summary> /// <remarks> /// 等倍3D平面については <see cref="等倍3D平面描画用の変換行列を取得する"/> を参照。 /// </remarks> public SharpDX.Vector3 画面左上dpx => new SharpDX.Vector3( -設計画面サイズ.Width / 2f, +設計画面サイズ.Height / 2f, 0f ); /// <summary> /// 現在時刻から、DirectComposition Engine による次のフレーム表示時刻までの間隔[秒]を返す。 /// </summary> /// <remarks> /// この時刻の仕様と使い方については、以下を参照。 /// Architecture and components - MSDN /// https://msdn.microsoft.com/en-us/library/windows/desktop/hh437350.aspx /// </remarks> public double 次のDComp表示までの残り時間sec { get { var fs = DCompDevice2.FrameStatistics; return ( fs.NextEstimatedFrameTime - fs.CurrentTime ) / fs.TimeFrequency; } } // イベント public event EventHandler スワップチェーンに依存しないグラフィックリソースの作成; public event EventHandler スワップチェーンに依存しないグラフィックリソースの解放; public event EventHandler スワップチェーンに依存するグラフィックリソースの作成; public event EventHandler スワップチェーンに依存するグラフィックリソースの解放; // プロパティ/スワップチェーンに依存しないグラフィックリソース public SharpDX.Direct3D11.Device1 D3D11Device1 { get; private set; } = null!; /// <summary> /// アプリは、D3D11Device1.ImmediateContext ではなくこちらを使用すること。 /// </summary> /// <remarks> /// D3D11Device1.ImmediateContext を参照すると、内部のCOM参照カウンタを1つカウントアップする。 /// これを Release するには Dispose() するしかないが、Dispose() すると、COM参照のカウントダウンだけでなく /// D3D11Device1.ImmediateContext 自体を破棄してしまう。 /// 従って、D3D11Device1.ImmediateContext は、最初に一度だけ参照し、最後に一度だけ Dispose() する運用にする。 /// </remarks> public SharpDX.Direct3D11.DeviceContext 既定のD3D11DeviceContext { get; private set; } = null!; public SharpDX.DXGI.Output1 DXGIOutput1 { get; private set; } = null!; public SharpDX.MediaFoundation.DXGIDeviceManager MFDXGIDeviceManager { get; private set; } = null!; public SharpDX.Direct2D1.Factory1 D2D1Factory1 { get; private set; } = null!; public SharpDX.Direct2D1.Device D2D1Device { get; private set; } = null!; public SharpDX.Direct2D1.DeviceContext 既定のD2D1DeviceContext { get; private set; } = null!; public SharpDX.DirectComposition.DesktopDevice DCompDevice2 { get; private set; } = null!; // IDCompositionDevice2 から派生 public SharpDX.DirectComposition.Visual2 DCompVisual2ForSwapChain { get; private set; } = null!; public SharpDX.DirectComposition.Target DCompTarget { get; private set; } = null!; public SharpDX.WIC.ImagingFactory2 WicImagingFactory2 { get; private set; } = null!; public SharpDX.DirectWrite.Factory DWriteFactory { get; private set; } = null!; private void _スワップチェーンに依存しないグラフィックリソースを作成する() { using var _ = new LogBlock( Log.現在のメソッド名 ); #region " MediaFoundation をセットアップする。" //---------------- SharpDX.MediaFoundation.MediaManager.Startup(); //---------------- #endregion #region " D3Dデバイスを作成する。" //---------------- using( var d3dDevice = new SharpDX.Direct3D11.Device( SharpDX.Direct3D.DriverType.Hardware, #if DEBUG // D3D11 Debugメッセージは、Visual Studio のプロジェクトプロパティで「ネイティブコードのデバッグを有効にする」を ON にしないと表示されない。 // なお、「ネイティブコードのデバッグを有効にする」を有効にしてアプリケーションを実行すると、速度が恐ろしく低下する。 SharpDX.Direct3D11.DeviceCreationFlags.Debug | #endif SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, // D2Dで必須 new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_11_0 } ) ) // D3D11.1 を使うが機能レベルは 11_0 でいい { // ID3D11Device1 を取得する。(Windows8.1 以降のPCで実装されている。) D3D11Device1 = d3dDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); } // D3D11デバイスから ID3D11VideoDevice が取得できることを確認する。 // (DXVAを使った動画の再生で必須。Windows8 以降のPCで実装されている。) using( var videoDevice = D3D11Device1.QueryInterfaceOrNull<SharpDX.Direct3D11.VideoDevice>() ) { // ↓以下のコメントを外すと、グラフィックデバッグで例外が発生する。 //if( videoDevice is null ) // throw new Exception( "Direct3D11デバイスが、ID3D11VideoDevice をサポートしていません。" ); } //---------------- #endregion #region " 既定のD3Dデバイスコンテキストを作成する。" //---------------- 既定のD3D11DeviceContext = D3D11Device1.ImmediateContext; //---------------- #endregion using var dxgiDevice1 = D3D11Device1.QueryInterface<SharpDX.DXGI.Device1>(); #region " DXGIデバイスのレイテンシを設定する。" //---------------- dxgiDevice1.MaximumFrameLatency = 1; //---------------- #endregion #region " 既定のDXGI出力を取得する。" //---------------- using( var dxgiAdapter = dxgiDevice1.Adapter ) using( var output = dxgiAdapter.Outputs[ 0 ] ) // 「現在のDXGI出力」を取得することはできないので[0]で固定。 DXGIOutput1 = output.QueryInterface<SharpDX.DXGI.Output1>(); //---------------- #endregion #region " DXGIデバイスマネージャを生成し、D3Dデバイスを登録する。MediaFoundationで必須。" //---------------- MFDXGIDeviceManager = new SharpDX.MediaFoundation.DXGIDeviceManager(); MFDXGIDeviceManager.ResetDevice( D3D11Device1 ); //---------------- #endregion #region " D3D10 マルチスレッドモードを ON に設定する。D3D11 はスレッドセーフだが、MediaFoundation でDXVAを使う場合は必須。" //---------------- using( var multithread = D3D11Device1.QueryInterfaceOrNull<SharpDX.Direct3D.DeviceMultithread>() ) { if( multithread is null ) throw new Exception( "Direct3D11デバイスが、ID3D10Multithread をサポートしていません。" ); multithread.SetMultithreadProtected( true ); } //---------------- #endregion #region " D2Dファクトリを作成する。" //---------------- D2D1Factory1 = new SharpDX.Direct2D1.Factory1( SharpDX.Direct2D1.FactoryType.MultiThreaded, #if DEBUG // D2D Debugメッセージは、Visual Studio のプロジェクトプロパティで「ネイティブコードのデバッグを有効にする」を ON にしないと表示されない。 // なお、「ネイティブコードのデバッグを有効にする」を有効にしてアプリケーションを実行すると、速度が恐ろしく低下する。 SharpDX.Direct2D1.DebugLevel.Information #else SharpDX.Direct2D1.DebugLevel.None #endif ); //---------------- #endregion #region " D2Dデバイスを作成する。" //---------------- D2D1Device = new SharpDX.Direct2D1.Device( D2D1Factory1, dxgiDevice1 ); //---------------- #endregion #region " 既定のD2Dデバイスコンテキストを作成する。" //---------------- 既定のD2D1DeviceContext = new SharpDX.Direct2D1.DeviceContext( D2D1Device, SharpDX.Direct2D1.DeviceContextOptions.EnableMultithreadedOptimizations ) { TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale, // Grayscale がすべての Windows ストアアプリで推奨される。らしい。 }; //---------------- #endregion #region " DirectCompositionデバイスを作成する。" //---------------- DCompDevice2 = new SharpDX.DirectComposition.DesktopDevice( D2D1Device ); //---------------- #endregion #region " スワップチェーン用のVisualを作成する。" //---------------- DCompVisual2ForSwapChain = new SharpDX.DirectComposition.Visual2( DCompDevice2 ); DCompVisual2ForSwapChain.BitmapInterpolationMode = SharpDX.DirectComposition.BitmapInterpolationMode.Linear; //---------------- #endregion #region " DirectCompositionターゲットを作成し、Visualツリーのルートにスワップチェーン用Visualを設定する。" //---------------- DCompTarget = SharpDX.DirectComposition.Target.FromHwnd( DCompDevice2, Handle, topmost: true ); DCompTarget.Root = DCompVisual2ForSwapChain; //---------------- #endregion #region " WICイメージングファクトリを作成する。" //---------------- WicImagingFactory2 = new SharpDX.WIC.ImagingFactory2(); //---------------- #endregion #region " DirectWriteファクトリを作成する。" //---------------- DWriteFactory = new SharpDX.DirectWrite.Factory( SharpDX.DirectWrite.FactoryType.Shared ); //---------------- #endregion } private void _スワップチェーンに依存しないグラフィックリソースを解放する() { using var _ = new LogBlock( Log.現在のメソッド名 ); #region " DirectWrite ファクトリを解放する。" //---------------- DWriteFactory.Dispose(); //---------------- #endregion #region " WICイメージングファクトリを解放する。" //---------------- WicImagingFactory2.Dispose(); //---------------- #endregion #region " DirectCompositionターゲットを解放する。" //---------------- DCompTarget.Dispose(); //---------------- #endregion #region " スワップチェーン用のVisualを解放する。" //---------------- DCompVisual2ForSwapChain.Dispose(); //---------------- #endregion #region " DirectCompositionデバイスを解放する。" //---------------- DCompDevice2.Dispose(); //---------------- #endregion #region " 既定のD2Dデバイスコンテキストを解放する。" //---------------- 既定のD2D1DeviceContext.Dispose(); //---------------- #endregion #region " D2Dデバイスを解放する。" //---------------- D2D1Device.Dispose(); //---------------- #endregion #region " D2Dファクトリを解放する。" //---------------- D2D1Factory1.Dispose(); //---------------- #endregion #region " DXGIデバイスマネージャを解放する。" //---------------- MFDXGIDeviceManager.Dispose(); //---------------- #endregion #region " DXGI出力を解放する。" //---------------- DXGIOutput1.Dispose(); //---------------- #endregion #region " 既定のD3Dデバイスコンテキストを解放する。" //---------------- 既定のD3D11DeviceContext.ClearState(); 既定のD3D11DeviceContext.Flush(); 既定のD3D11DeviceContext.Dispose(); //---------------- #endregion #region " D3Dデバイスを解放する。" //---------------- #if DEBUG // ReportLiveDeviceObjects。 // デバッガの「ネイティブデバッグを有効にする」をオンにすれば表示される。 using( var debug = new SharpDX.Direct3D11.DeviceDebug( D3D11Device1 ) ) { D3D11Device1.Dispose(); debug.ReportLiveDeviceObjects( SharpDX.Direct3D11.ReportingLevel.Detail | SharpDX.Direct3D11.ReportingLevel.IgnoreInternal ); } #endif //---------------- #endregion #region " MediaFoundation をシャットダウンする。" //---------------- SharpDX.MediaFoundation.MediaManager.Shutdown(); //---------------- #endregion } // プロパティ/スワップチェーン public SharpDX.DXGI.SwapChain1 DXGISwapChain1 { get; private set; } = null!; private void _スワップチェーンを作成する() { using var _ = new LogBlock( Log.現在のメソッド名 ); // DirectComposition用スワップチェーンを作成する。 var swapChainDesc = new SharpDX.DXGI.SwapChainDescription1() { BufferCount = 2, Width = (int)設計画面サイズ.Width, // スワップチェーンのサイズは、物理画面サイズによらず、常に設計画面サイズと同じ。 Height = (int)設計画面サイズ.Height, // Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // D2D をサポートするなら B8G8R8A8 を指定する必要がある。 AlphaMode = SharpDX.DXGI.AlphaMode.Ignore, // Premultiplied にすると、ウィンドウの背景(デスクトップ画像)と加算合成される。(意味ない) Stereo = false, SampleDescription = new SharpDX.DXGI.SampleDescription( 1, 0 ), // マルチサンプリングは使わない。 SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential, // SwapChainForComposition での必須条件。 Scaling = SharpDX.DXGI.Scaling.Stretch, // SwapChainForComposition での必須条件。 Usage = SharpDX.DXGI.Usage.RenderTargetOutput, Flags = SharpDX.DXGI.SwapChainFlags.None, // https://msdn.microsoft.com/en-us/library/windows/desktop/bb174579.aspx // > You cannot call SetFullscreenState on a swap chain that you created with IDXGIFactory2::CreateSwapChainForComposition. // よって、以下のフラグは使用禁止。 //Flags = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch, }; using var dxgiDevice1 = D3D11Device1.QueryInterface<SharpDX.DXGI.Device1>(); using var dxgiAdapter = dxgiDevice1!.Adapter; using var dxgiFactory2 = dxgiAdapter!.GetParent<SharpDX.DXGI.Factory2>(); DXGISwapChain1 = new SharpDX.DXGI.SwapChain1( dxgiFactory2, D3D11Device1, ref swapChainDesc ); // CreateSwapChainForComposition() //DXGISwapChain1 = new SharpDX.DXGI.SwapChain1( dxgiFactory2, D3D11Device1, this.Handle, ref swapChainDesc ); // CreateSwapChainForHWnd() // 標準機能である PrintScreen と Alt+Enter は使わない。 dxgiFactory2!.MakeWindowAssociation( Handle, SharpDX.DXGI.WindowAssociationFlags.IgnoreAll //SharpDX.DXGI.WindowAssociationFlags.IgnorePrintScreen | //SharpDX.DXGI.WindowAssociationFlags.IgnoreAltEnter ); // スワップチェーンの DXGIサーフェスを Visual のコンテンツに指定してコミット。 DCompVisual2ForSwapChain.Content = DXGISwapChain1; this._D2D用Visualのスケールをバックバッファに合わせる(); DCompDevice2.Commit(); } private void _スワップチェーンを解放する() { using var _ = new LogBlock( Log.現在のメソッド名 ); // スワップチェーンの DXGIサーフェスを Visual のコンテンツから解除してコミット。 DCompVisual2ForSwapChain.Content = null; DCompDevice2.Commit(); DXGISwapChain1.Dispose(); } // プロパティ/スワップチェーンに依存するグラフィックリソース /// <summary> /// スワップチェーンのバックバッファに対する既定のレンダーターゲットビュー。 /// </summary> public SharpDX.Direct3D11.RenderTargetView 既定のD3D11RenderTargetView { get; private set; } = null!; /// <summary> /// スワップチェーンのバックバッファに対する既定の深度ステンシル。 /// </summary> public SharpDX.Direct3D11.Texture2D 既定のD3D11DepthStencil { get; private set; } = null!; /// <summary> /// スワップチェーンのバックバッファに対する既定の深度ステンシルビュー。 /// </summary> public SharpDX.Direct3D11.DepthStencilView 既定のD3D11DepthStencilView { get; private set; } = null!; /// <summary> /// スワップチェーンのバックバッファに対する既定の深度ステンシルステート。 /// </summary> public SharpDX.Direct3D11.DepthStencilState 既定のD3D11DepthStencilState { get; private set; } = null!; /// <summary> /// スワップチェーンのバックバッファに対する既定のビューポートの配列。 /// </summary> public SharpDX.Mathematics.Interop.RawViewportF[] 既定のD3D11ViewPort { get; private set; } = null!; /// <summary> /// スワップチェーンのバックバッファとメモリを共有するD2Dレンダービットマップ。 /// </summary> /// <remarks> /// これにD2Dで描画を行うことは、すなわちD3Dスワップチェーンのバックバッファに描画することを意味する。 /// </remarks> public SharpDX.Direct2D1.Bitmap1 既定のD2D1RenderBitmap1 { get; private set; } = null!; private void _スワップチェーンに依存するグラフィックリソースを作成する() { using var _ = new LogBlock( Log.現在のメソッド名 ); // D3D 関連 using( var backbufferTexture2D = DXGISwapChain1.GetBackBuffer<SharpDX.Direct3D11.Texture2D>( 0 ) ) { #region " バックバッファに対する既定のD3D11レンダーターゲットビューを作成する。" //---------------- 既定のD3D11RenderTargetView = new SharpDX.Direct3D11.RenderTargetView( D3D11Device1, backbufferTexture2D ); //---------------- #endregion #region " バックバッファに対する既定の深度ステンシル、既定の深度ステンシルビュー、既定の深度ステンシルステートを作成する。" //---------------- // 既定の深度ステンシル 既定のD3D11DepthStencil = new SharpDX.Direct3D11.Texture2D( D3D11Device1, new SharpDX.Direct3D11.Texture2DDescription { Width = backbufferTexture2D.Description.Width, // バックバッファと同じサイズ Height = backbufferTexture2D.Description.Height, // MipLevels = 1, ArraySize = 1, Format = SharpDX.DXGI.Format.D32_Float, // 32bit Depth SampleDescription = backbufferTexture2D.Description.SampleDescription, // バックバッファと同じサンプル記述 Usage = SharpDX.Direct3D11.ResourceUsage.Default, BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, // CPUからはアクセスしない OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None, } ); // 既定の深度ステンシルビュー 既定のD3D11DepthStencilView = new SharpDX.Direct3D11.DepthStencilView( D3D11Device1, 既定のD3D11DepthStencil, new SharpDX.Direct3D11.DepthStencilViewDescription { Format = 既定のD3D11DepthStencil.Description.Format, Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D, Flags = SharpDX.Direct3D11.DepthStencilViewFlags.None, Texture2D = new SharpDX.Direct3D11.DepthStencilViewDescription.Texture2DResource() { MipSlice = 0, }, } ); // 既定の深度ステンシルステート 既定のD3D11DepthStencilState = new SharpDX.Direct3D11.DepthStencilState( D3D11Device1, new SharpDX.Direct3D11.DepthStencilStateDescription { IsDepthEnabled = false, // 深度無効 IsStencilEnabled = false, // ステンシルテスト無効 DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All, // 書き込む DepthComparison = SharpDX.Direct3D11.Comparison.Less, // 手前の物体を描画 StencilReadMask = 0, StencilWriteMask = 0, // 面が表を向いている場合のステンシル・テストの設定 FrontFace = new SharpDX.Direct3D11.DepthStencilOperationDescription() { FailOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持 DepthFailOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持 PassOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持 Comparison = SharpDX.Direct3D11.Comparison.Never, // 常に失敗 }, // 面が裏を向いている場合のステンシル・テストの設定 BackFace = new SharpDX.Direct3D11.DepthStencilOperationDescription() { FailOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持 DepthFailOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持 PassOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持 Comparison = SharpDX.Direct3D11.Comparison.Always, // 常に成功 }, } ); //---------------- #endregion #region " バックバッファに対する既定のビューポートを作成する。" //---------------- 既定のD3D11ViewPort = new SharpDX.Mathematics.Interop.RawViewportF[] { new SharpDX.Mathematics.Interop.RawViewportF() { X = 0.0f, // バックバッファと同じサイズ Y = 0.0f, // Width = (float) backbufferTexture2D.Description.Width, // Height = (float) backbufferTexture2D.Description.Height, // MinDepth = 0.0f, // 近面Z: 0.0(最も近い) MaxDepth = 1.0f, // 遠面Z: 1.0(最も遠い) }, }; //---------------- #endregion } // D2D 関連 using( var backbufferSurface = DXGISwapChain1.GetBackBuffer<SharpDX.DXGI.Surface>( 0 ) ) { #region " バックバッファとメモリを共有する、既定のD2Dレンダーターゲットビットマップを作成する。" //---------------- 既定のD2D1RenderBitmap1 = new SharpDX.Direct2D1.Bitmap1( // このビットマップは、 既定のD2D1DeviceContext, backbufferSurface, // このDXGIサーフェス(スワップチェーンのバックバッファ)とメモリを共有する。 new SharpDX.Direct2D1.BitmapProperties1() { PixelFormat = new SharpDX.Direct2D1.PixelFormat( backbufferSurface.Description.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied ), BitmapOptions = SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw, } ); 既定のD2D1DeviceContext.Target = 既定のD2D1RenderBitmap1; 既定のD2D1DeviceContext.Transform = SharpDX.Matrix3x2.Identity; 既定のD2D1DeviceContext.PrimitiveBlend = SharpDX.Direct2D1.PrimitiveBlend.SourceOver; //---------------- #endregion } } private void _スワップチェーンに依存するグラフィックリソースを解放する() { using var _ = new LogBlock( Log.現在のメソッド名 ); #region " 既定の深度ステンシルステート、既定の深度ステンシルビュー、深度ステンシルを解放する。" //---------------- 既定のD3D11DepthStencilState.Dispose(); 既定のD3D11DepthStencilView.Dispose(); 既定のD3D11DepthStencil.Dispose(); //---------------- #endregion #region " 既定のD3D11レンダーターゲットビューを解放する。" //---------------- 既定のD3D11RenderTargetView.Dispose(); //---------------- #endregion #region " 既定のD2Dレンダーターゲットビットマップを解放する。" //---------------- 既定のD2D1DeviceContext.Target = null; 既定のD2D1RenderBitmap1.Dispose(); //---------------- #endregion } // 生成と終了 public GraphicResources() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.スワップチェーンに依存しないグラフィックリソースの作成 += ( s, e ) => this._スワップチェーンに依存しないグラフィックリソースを作成する(); this.スワップチェーンに依存しないグラフィックリソースの解放 += ( s, e ) => this._スワップチェーンに依存しないグラフィックリソースを解放する(); this.スワップチェーンに依存するグラフィックリソースの作成 += ( s, e ) => this._スワップチェーンに依存するグラフィックリソースを作成する(); this.スワップチェーンに依存するグラフィックリソースの解放 += ( s, e ) => this._スワップチェーンに依存するグラフィックリソースを解放する(); } public void 生成する( IntPtr hWindow, SharpDX.Size2F 設計画面サイズ, SharpDX.Size2F 物理画面サイズ ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this.Handle = hWindow; this.設計画面サイズ = 設計画面サイズ; this.物理画面サイズ = 物理画面サイズ; this.スワップチェーンに依存しないグラフィックリソースの作成( this, new EventArgs() ); this._スワップチェーンを作成する(); this.スワップチェーンに依存するグラフィックリソースの作成( this, new EventArgs() ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.スワップチェーンに依存するグラフィックリソースの解放( this, new EventArgs() ); this._スワップチェーンを解放する(); this.スワップチェーンに依存しないグラフィックリソースの解放( this, new EventArgs() ); } // その他 /// <summary> /// 物理画面サイズを変更する。 /// </summary> /// <param name="newSize">新しいサイズ。</param> /// <remarks> /// スワップチェーンのサイズは変更せず、レンダーターゲット(DirectComposition の Visual)の拡大率のみ変更する。 /// Direct3D については、何もしなくても自動的に拡大縮小される。 /// </remarks> public void 物理画面サイズを変更する( SharpDX.Size2F newSize ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this.物理画面サイズ = newSize; this._D2D用Visualのスケールをバックバッファに合わせる(); DCompDevice2.Commit(); } /// <summary> /// 等倍3D平面描画用のビュー行列と射影行列を生成して返す。 /// </summary> /// <remarks> /// 「等倍3D平面」とは、Z = 0 におけるビューポートサイズが <see cref="設計画面サイズ"/> に一致する平面である。 /// 例えば、設計画面サイズが 1024x720 の場合、等倍3D平面の表示可能な x, y の値域は (-512, -360)~(+512, +360) となる。 /// この平面を使うと、3Dモデルの配置やサイズ設定を設計画面サイズを基準に行うことができるようになる。 /// 本メソッドは、等倍3D平面を実現するためのビュー行列と射影行列を返す。 /// </remarks> public void 等倍3D平面描画用の変換行列を取得する( out SharpDX.Matrix ビュー行列, out SharpDX.Matrix 射影行列, float 視野角deg = 10f ) { var dz = this.設計画面サイズ.Height / ( 4.0f * MathF.Tan( SharpDX.MathUtil.DegreesToRadians( 視野角deg / 2.0f ) ) ); var カメラの位置 = new SharpDX.Vector3( 0f, 0f, -2f * dz ); var カメラの注視点 = new SharpDX.Vector3( 0f, 0f, 0f ); var カメラの上方向 = new SharpDX.Vector3( 0f, 1f, 0f ); ビュー行列 = SharpDX.Matrix.LookAtLH( カメラの位置, カメラの注視点, カメラの上方向 ); 射影行列 = SharpDX.Matrix.PerspectiveFovLH( SharpDX.MathUtil.DegreesToRadians( 視野角deg ), 設計画面サイズ.Width / 設計画面サイズ.Height, // アスペクト比 -dz, // 前方投影面までの距離 +dz ); // 後方投影面までの距離 } private void _D2D用Visualのスケールをバックバッファに合わせる() { using var trans = new SharpDX.DirectComposition.ScaleTransform( DCompDevice2 ); trans.SetScaleX( this.物理画面サイズ.Width / 設計画面サイズ.Width ); trans.SetScaleY( this.物理画面サイズ.Height / 設計画面サイズ.Height ); DCompVisual2ForSwapChain.SetTransform( trans ); } } } <|start_filename|>DTXMania2/ステージ/08結果/曲別SKILL.アイコン.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using SharpDX.Animation; using SharpDX.Direct2D1; namespace DTXMania2.結果 { partial class 曲別SKILL { class アイコン : IDisposable { // プロパティ public bool アニメ完了 => ( null != this._ストーリーボード ) && ( this._ストーリーボード.Status == StoryboardStatus.Ready ); // 生成と終了 public アイコン() { this._アイコン画像 = new 画像D2D( @"$(Images)\ResultStage\SkillsBySongIcon.png" ); } public virtual void Dispose() { this._不透明度?.Dispose(); this._半径倍率?.Dispose(); this._拡大角度rad?.Dispose(); this._ストーリーボード?.Dispose(); this._アイコン画像.Dispose(); } // 進行と描画 public void 開始する() { this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( Global.Animation.Manager ); #region " 拡大角度rad " //---------------- // 初期値 0.0 this._拡大角度rad?.Dispose(); this._拡大角度rad = new Variable( Global.Animation.Manager, initialValue: 0.0 ); // 待つ using( var 遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 曲別SKILL._最初の待機時間sec ) ) this._ストーリーボード.AddTransition( this._拡大角度rad, 遷移 ); // 2π へ using( var 遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 曲別SKILL._アニメ時間sec, finalValue: 2 * Math.PI ) ) this._ストーリーボード.AddTransition( this._拡大角度rad, 遷移 ); //---------------- #endregion #region " 半径倍率 " //---------------- // 初期値 1.0 this._半径倍率?.Dispose(); this._半径倍率 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); // 待つ using( var 遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 曲別SKILL._最初の待機時間sec ) ) this._ストーリーボード.AddTransition( this._半径倍率, 遷移 ); // 0.0 へ using( var 遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: 曲別SKILL._アニメ時間sec, finalValue: 0.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) this._ストーリーボード.AddTransition( this._半径倍率, 遷移 ); //---------------- #endregion #region " 不透明度 " //---------------- // 初期値 0.0 this._不透明度?.Dispose(); this._不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); // 待つ using( var 遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 曲別SKILL._最初の待機時間sec ) ) this._ストーリーボード.AddTransition( this._不透明度, 遷移 ); // 1.0 へ using( var 遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 曲別SKILL._アニメ時間sec, finalValue: 1.0 ) ) this._ストーリーボード.AddTransition( this._不透明度, 遷移 ); //---------------- #endregion // アニメーション開始 this._ストーリーボード.Schedule( Global.Animation.Timer.Time ); } public void アニメを完了する() { this._ストーリーボード?.Finish( 0.1 ); } public void 進行描画する( DeviceContext d2ddc, float x, float y ) { if( this._拡大角度rad is null || this._半径倍率 is null || this._不透明度 is null ) return; double 回転による拡大率 = Math.Abs( Math.Cos( this._拡大角度rad.Value ) ); // (0) 1 → 0 → 1(π) → 0 → 1 (2π) float 拡大率 = (float)( 1.0 + 回転による拡大率 * this._半径倍率.Value ); float 左位置dpx = x + ( ( 1.0f - 拡大率 ) * this._アイコン画像.サイズ.Width ) / 2.0f; float 上位置dpx = y + ( ( 1.0f - 拡大率 ) * this._アイコン画像.サイズ.Height ) / 2.0f; this._アイコン画像.描画する( d2ddc, 左位置dpx, 上位置dpx, 不透明度0to1: (float)this._不透明度.Value, X方向拡大率: 拡大率, Y方向拡大率: 拡大率 ); } // ローカル private readonly 画像D2D _アイコン画像; private Storyboard? _ストーリーボード = null; private Variable? _拡大角度rad = null; private Variable? _半径倍率 = null; private Variable? _不透明度 = null; } } } <|start_filename|>DTXMania2/ステージ/07演奏/曲別SKILL.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class 曲別SKILL : IDisposable { // 生成と終了 public 曲別SKILL() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_LargeBoldItalic.png", @"$(Images)\ParameterFont_LargeBoldItalic.yaml", 文字幅補正dpx: -6f ); this._ロゴ画像 = new 画像D2D( @"$(Images)\SkillIcon.png" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ロゴ画像.Dispose(); this._数字画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, double? スキル値 ) { if( !スキル値.HasValue ) return; var 描画領域 = new RectangleF( 108f, 780f - 40f, 275f, 98f ); string スキル値文字列 = スキル値.Value.ToString( "0.00" ).PadLeft( 6 ).Replace( ' ', 'o' ); // 右詰め、余白は'o'。 // 曲別SKILLアイコンを描画する var 変換行列2D = Matrix3x2.Scaling( 0.375f, 0.5f ) * Matrix3x2.Translation( 描画領域.X, 描画領域.Y ); this._ロゴ画像.描画する( d2ddc, 変換行列2D ); // 小数部を描画する this._数字画像.描画する( d2ddc, 描画領域.X + 90f + 105f, 描画領域.Y + ( 描画領域.Height * 0.2f ), スキル値文字列[ 4.. ], new Size2F( 0.65f, 0.8f ) ); // 整数部を描画する('.'含む) this._数字画像.描画する( d2ddc, 描画領域.X + 90f, 描画領域.Y, スキル値文字列[ 0..4 ], new Size2F( 0.65f, 1.0f ) ); } // ローカル private readonly フォント画像D2D _数字画像; private readonly 画像D2D _ロゴ画像; } } <|start_filename|>DTXMania2/保存データ/RecordDB/old/v006_RecordDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.old.RecordDBRecord { class v006_RecordDBRecord { public const int VERSION = 6; /// <summary> /// ユーザを一意に識別するID。 /// </summary> public string UserId { get; set; } /// <summary> /// 曲譜面ファイルのハッシュ値。 /// </summary> public string SongHashId { get; set; } /// <summary> /// スコア。 /// </summary> public int Score { get; set; } /// <summary> /// カウントマップラインのデータ。 /// 1ブロックを1文字('0':0~'C':12)で表し、<see cref="DTXMania.ステージ.演奏.カウントマップライン.カウントマップの最大要素数"/> 個の文字が並ぶ。 /// もし不足分があれば、'0' とみなされる。 /// </summary> public string CountMap { get; set; } /// <summary> /// 曲別SKILL。 /// </summary> public double Skill { get; set; } /// <summary> /// 達成率。 /// </summary> public double Achievement { get; set; } // 生成と終了 public v006_RecordDBRecord() { this.UserId = "Anonymous"; this.SongHashId = ""; this.Score = 0; this.CountMap = ""; this.Skill = 0.0; this.Achievement = 0.0; } public v006_RecordDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "UserId": this.UserId = record.GetString( i ); break; case "SongHashId": this.SongHashId = record.GetString( i ); break; case "Score": this.Score = record.GetInt32( i ); break; case "CountMap": this.CountMap = record.GetString( i ); break; case "Skill": this.Skill = record.GetDouble( i ); break; case "Achievement": this.Achievement = record.GetDouble( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public void InsertTo( SQLiteDB db ) { using var cmd = new SqliteCommand( "REPLACE INTO Records VALUES(" + $"'{this.UserId}'," + $"'{this.SongHashId}'" + $"{this.Score}," + $"'{this.CountMap}'," + $"{this.Skill}," + $"{this.Achievement}" + ")", db.Connection ); cmd.ExecuteNonQuery(); } } } <|start_filename|>FDK/イメージ/描画可能画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Direct3D11; namespace FDK { /// <summary> /// D2Dビットマップとメモリを共有するD3Dテクスチャを持つ画像。 /// D2Dビットマップに対してD2Dで描画を行い、それをD3Dテクスチャとして表示する。 /// </summary> public class 描画可能画像 : 画像 { // プロパティ /// <summary> /// 画像のD3Dテクスチャとメモリを共有するD2Dビットマップ。 /// </summary> public Bitmap1 Bitmap { get; protected set; } = null!; // 生成と終了 /// <summary> /// 指定した画像ファイルから描画可能画像を作成する。 /// </summary> public 描画可能画像( SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, VariablePath 画像ファイルパス, BindFlags bindFlags = BindFlags.ShaderResource ) : base( d3dDevice1, 画像ファイルパス, bindFlags | BindFlags.RenderTarget ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); this.Bitmap = this._作成したテクスチャとデータを共有するビットマップターゲットを作成する( d2dDeviceContext ); } /// <summary> /// 指定したサイズの、空の描画可能画像を作成する。 /// </summary> public 描画可能画像( SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, Size2F サイズ, BindFlags bindFlags = BindFlags.ShaderResource ) : base( d3dDevice1, サイズ, bindFlags | BindFlags.RenderTarget ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); this.Bitmap = this._作成したテクスチャとデータを共有するビットマップターゲットを作成する( d2dDeviceContext ); } public override void Dispose() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this.Bitmap.Dispose(); base.Dispose(); } // ローカル private Bitmap1 _作成したテクスチャとデータを共有するビットマップターゲットを作成する( SharpDX.Direct2D1.DeviceContext d2dDeviceContext ) { using var dxgiSurface = this.Texture.QueryInterfaceOrNull<SharpDX.DXGI.Surface>(); var bmpProp = new BitmapProperties1() { PixelFormat = new PixelFormat( dxgiSurface.Description.Format, AlphaMode.Premultiplied ), BitmapOptions = BitmapOptions.Target | BitmapOptions.CannotDraw, }; return new Bitmap1( d2dDeviceContext, dxgiSurface, bmpProp ); } } } <|start_filename|>SSTFormat/v004/SSTFプロパティ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SSTFormat.v004 { public static class SSTFプロパティ { // チップの属するレーン public static readonly Dictionary<チップ種別, レーン種別> チップtoレーンマップ = new Dictionary<チップ種別, レーン種別>() { #region " *** " //---------------- { チップ種別.Unknown, レーン種別.Unknown }, { チップ種別.LeftCrash, レーン種別.LeftCrash }, { チップ種別.Ride, レーン種別.Ride }, { チップ種別.Ride_Cup, レーン種別.Ride }, { チップ種別.China, レーン種別.China }, { チップ種別.Splash, レーン種別.Splash }, { チップ種別.HiHat_Open, レーン種別.HiHat }, { チップ種別.HiHat_HalfOpen, レーン種別.HiHat }, { チップ種別.HiHat_Close, レーン種別.HiHat }, { チップ種別.HiHat_Foot, レーン種別.Foot }, { チップ種別.Snare, レーン種別.Snare }, { チップ種別.Snare_OpenRim, レーン種別.Snare }, { チップ種別.Snare_ClosedRim, レーン種別.Snare }, { チップ種別.Snare_Ghost, レーン種別.Snare }, { チップ種別.Bass, レーン種別.Bass }, { チップ種別.LeftBass, レーン種別.Bass }, { チップ種別.Tom1, レーン種別.Tom1 }, { チップ種別.Tom1_Rim, レーン種別.Tom1 }, { チップ種別.Tom2, レーン種別.Tom2 }, { チップ種別.Tom2_Rim, レーン種別.Tom2 }, { チップ種別.Tom3, レーン種別.Tom3 }, { チップ種別.Tom3_Rim, レーン種別.Tom3 }, { チップ種別.RightCrash, レーン種別.RightCrash }, { チップ種別.BPM, レーン種別.BPM }, { チップ種別.小節線, レーン種別.Unknown }, { チップ種別.拍線, レーン種別.Unknown }, { チップ種別.背景動画, レーン種別.BGV }, { チップ種別.LeftCymbal_Mute, レーン種別.LeftCrash }, { チップ種別.RightCymbal_Mute, レーン種別.RightCrash }, { チップ種別.小節の先頭, レーン種別.Unknown }, { チップ種別.小節メモ, レーン種別.Unknown }, { チップ種別.BGM, レーン種別.BGM }, { チップ種別.GuitarAuto, レーン種別.Unknown }, // 以下、出力未対応 { チップ種別.BassAuto, レーン種別.Unknown }, { チップ種別.SE1, レーン種別.Unknown }, { チップ種別.SE2, レーン種別.Unknown }, { チップ種別.SE3, レーン種別.Unknown }, { チップ種別.SE4, レーン種別.Unknown }, { チップ種別.SE5, レーン種別.Unknown }, { チップ種別.SE6, レーン種別.Unknown }, { チップ種別.SE7, レーン種別.Unknown }, { チップ種別.SE8, レーン種別.Unknown }, { チップ種別.SE9, レーン種別.Unknown }, { チップ種別.SE10, レーン種別.Unknown }, { チップ種別.SE11, レーン種別.Unknown }, { チップ種別.SE12, レーン種別.Unknown }, { チップ種別.SE13, レーン種別.Unknown }, { チップ種別.SE14, レーン種別.Unknown }, { チップ種別.SE15, レーン種別.Unknown }, { チップ種別.SE16, レーン種別.Unknown }, { チップ種別.SE17, レーン種別.Unknown }, { チップ種別.SE18, レーン種別.Unknown }, { チップ種別.SE19, レーン種別.Unknown }, { チップ種別.SE20, レーン種別.Unknown }, { チップ種別.SE21, レーン種別.Unknown }, { チップ種別.SE22, レーン種別.Unknown }, { チップ種別.SE23, レーン種別.Unknown }, { チップ種別.SE24, レーン種別.Unknown }, { チップ種別.SE25, レーン種別.Unknown }, { チップ種別.SE26, レーン種別.Unknown }, { チップ種別.SE27, レーン種別.Unknown }, { チップ種別.SE28, レーン種別.Unknown }, { チップ種別.SE29, レーン種別.Unknown }, { チップ種別.SE30, レーン種別.Unknown }, { チップ種別.SE31, レーン種別.Unknown }, { チップ種別.SE32, レーン種別.Unknown }, //---------------- #endregion }; // チップの深さ /// <summary> /// チップの深さを数値で表したもの。 /// </summary> /// <remarks> /// 2つのチップが同じ位置に配置されている場合、チップの深さが「小さいほうが後」になる。 /// 例えば、深さ10と20のチップでは、深さ20のチップが先に描かれ、次に深さ10のチップが描かれる。 /// すなわち、チップが重なっている場合には、深さ10のチップが20のチップの上に重なる。 /// </remarks> public static readonly Dictionary<チップ種別, int> チップの深さ = new Dictionary<チップ種別, int>() { #region " *** " //----------------- { チップ種別.Ride_Cup, 50 }, { チップ種別.HiHat_Open, 50 }, { チップ種別.HiHat_HalfOpen, 50 }, { チップ種別.HiHat_Close, 50 }, { チップ種別.HiHat_Foot, 50 }, { チップ種別.Snare, 50 }, { チップ種別.Snare_OpenRim, 50 }, { チップ種別.Snare_ClosedRim, 50 }, { チップ種別.Snare_Ghost, 50 }, { チップ種別.Tom1, 50 }, { チップ種別.Tom1_Rim, 50 }, { チップ種別.BPM, 50 }, { チップ種別.Ride, 60 }, { チップ種別.Splash, 60 }, { チップ種別.Tom2, 60 }, { チップ種別.Tom2_Rim, 60 }, { チップ種別.LeftCrash, 70 }, { チップ種別.China, 70 }, { チップ種別.Tom3, 70 }, { チップ種別.Tom3_Rim, 70 }, { チップ種別.RightCrash, 70 }, { チップ種別.Bass, 74 }, { チップ種別.LeftBass, 75 }, { チップ種別.LeftCymbal_Mute, 76 }, { チップ種別.RightCymbal_Mute, 76 }, { チップ種別.小節線, 80 }, { チップ種別.拍線, 85 }, { チップ種別.背景動画, 90 }, { チップ種別.小節の先頭, 99 }, { チップ種別.小節メモ, 99 }, { チップ種別.GuitarAuto, 99 }, { チップ種別.BassAuto, 99 }, { チップ種別.BGM, 99 }, { チップ種別.SE1, 99 }, { チップ種別.SE2, 99 }, { チップ種別.SE3, 99 }, { チップ種別.SE4, 99 }, { チップ種別.SE5, 99 }, { チップ種別.SE6, 99 }, { チップ種別.SE7, 99 }, { チップ種別.SE8, 99 }, { チップ種別.SE9, 99 }, { チップ種別.SE10, 99 }, { チップ種別.SE11, 99 }, { チップ種別.SE12, 99 }, { チップ種別.SE13, 99 }, { チップ種別.SE14, 99 }, { チップ種別.SE15, 99 }, { チップ種別.SE16, 99 }, { チップ種別.SE17, 99 }, { チップ種別.SE18, 99 }, { チップ種別.SE19, 99 }, { チップ種別.SE20, 99 }, { チップ種別.SE21, 99 }, { チップ種別.SE22, 99 }, { チップ種別.SE23, 99 }, { チップ種別.SE24, 99 }, { チップ種別.SE25, 99 }, { チップ種別.SE26, 99 }, { チップ種別.SE27, 99 }, { チップ種別.SE28, 99 }, { チップ種別.SE29, 99 }, { チップ種別.SE30, 99 }, { チップ種別.SE31, 99 }, { チップ種別.SE32, 99 }, { チップ種別.Unknown, 99 }, //----------------- #endregion }; } } <|start_filename|>DTXMania2/ステージ/07演奏/譜面スクロール速度.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { /// <summary> /// 譜面スクロール速度の遷移と表示を行う。 /// </summary> /// <remarks> /// 譜面スクロール速度には、 ///  「ユーザ設定速度」 ///  「補間付き速度」 /// 2種類がある。 /// /// 本クラスが画面に表示する速度は常に「ユーザ設定速度」である。 /// これは外部から供給される値であり、本クラスでは参照のみ行う。 /// /// 「ユーザ設定速度」は通常 0.5 単位で増減するが、 /// 「補間付き速度」はその増減が滑らかになるよう、一定時間をかけて補完する値である。 /// これは本クラスで提供する。 /// /// 譜面上を流れるチップの表示位置計算には、本クラスで定義する <see cref="補間付き速度"/> プロパティの値を使うこと。 /// </remarks> class 譜面スクロール速度 : IDisposable { // プロパティ public double 補間付き速度 { get; protected set; } // 生成と終了 public 譜面スクロール速度( double ユーザ設定速度 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._文字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_Small.png", @"$(Images)\ParameterFont_Small.yaml", 文字幅補正dpx: -3f ); this.補間付き速度 = ユーザ設定速度; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._文字画像.Dispose(); } // 進行と描画 public void 進行する( double ユーザ設定速度 ) { // 現在の 補間付き速度 が ユーザ設定速度 と異なっているなら、近づける。 if( this.補間付き速度 < ユーザ設定速度 ) { #region " (A) 速度が上がった " //---------------- if( 0 > this._スクロール倍率追い付き用_最後の値 ) { this._スクロール倍率追い付き用カウンタ = new LoopCounter( 0, 1000, 10 ); // 0→100; 全部で10×1000 = 10000ms = 10sec あれば十分だろう this._スクロール倍率追い付き用_最後の値 = 0; } else { while( this._スクロール倍率追い付き用_最後の値 < this._スクロール倍率追い付き用カウンタ.現在値 ) { this.補間付き速度 += 0.025; this._スクロール倍率追い付き用_最後の値++; } this.補間付き速度 = Math.Min( this.補間付き速度, ユーザ設定速度 ); } //---------------- #endregion } else if( this.補間付き速度 > ユーザ設定速度 ) { #region " (B) 速度が下がった " //---------------- if( 0 > this._スクロール倍率追い付き用_最後の値 ) { this._スクロール倍率追い付き用カウンタ = new LoopCounter( 0, 1000, 10 ); // 0→100; 全部で10×1000 = 10000ms = 10sec あれば十分だろう this._スクロール倍率追い付き用_最後の値 = 0; } else { while( this._スクロール倍率追い付き用_最後の値 < this._スクロール倍率追い付き用カウンタ.現在値 ) { this.補間付き速度 -= 0.025; this._スクロール倍率追い付き用_最後の値++; } this.補間付き速度 = Math.Max( this.補間付き速度, ユーザ設定速度 ); } //---------------- #endregion } else { #region " (C) 速度は変わってない " //---------------- this._スクロール倍率追い付き用_最後の値 = -1; //---------------- #endregion } } public void 描画する( DeviceContext d2ddc, double ユーザ設定速度 ) { var 表示領域 = new RectangleF( 482, 985f, 48f, 24f ); this._文字画像.描画する( d2ddc, 表示領域.X, 表示領域.Y, ユーザ設定速度.ToString( "0.0" ) ); // 表示は 補間付き速度 ではない } // ローカル private readonly フォント画像D2D _文字画像; private LoopCounter _スクロール倍率追い付き用カウンタ = null!; private int _スクロール倍率追い付き用_最後の値 = -1; } } <|start_filename|>DTXMania2/イメージ/フォント画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using FDK; namespace DTXMania2 { class フォント画像 : FDK.フォント画像 { /// <summary> /// コンストラクタ。 /// 指定された画像ファイルと矩形リストyamlファイルを使って、フォント画像を生成する。 /// </summary> /// <param name="文字幅補正dpx">文字と文字の間の(横方向の)間隔。拡大率の影響は受けない。負数もOK。</param> /// <param name="不透明度">透明: 0 ~ 1 :不透明</param> public フォント画像( VariablePath 文字盤の画像ファイルパス, VariablePath 文字盤設定ファイルパス, float 文字幅補正dpx = 0f, float 不透明度 = 1f ) : base( Global.GraphicResources.D3D11Device1, Folder.カルチャを考慮した絶対パスを返す( 文字盤の画像ファイルパス.変数なしパス ), Folder.カルチャを考慮した絶対パスを返す( 文字盤設定ファイルパス.変数なしパス ), 文字幅補正dpx, 不透明度 ) { } /// <summary> /// 文字列を描画する。 /// </summary> /// <param name="基点のX位置">左揃えなら左端位置、右揃えなら右端位置のX座標。</param> /// <param name="拡大率">文字列の拡大率。null なら等倍。</param> /// <param name="右揃え">trueなら右揃え、falseなら左揃え。</param> public void 描画する( float 基点のX位置, float 上位置, string 表示文字列, Size2F? 拡大率 = null, bool 右揃え = false ) { base.描画する( Global.GraphicResources.既定のD3D11DeviceContext, Global.GraphicResources.設計画面サイズ, Global.GraphicResources.既定のD3D11ViewPort, Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView, Global.GraphicResources.既定のD3D11DepthStencilState, 基点のX位置, 上位置, 表示文字列, 拡大率, 右揃え ); } } } <|start_filename|>FDK/QueueMemoryStream.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace FDK { /// <summary> /// 読み込みと書き込みを別々のスレッドから行えるキュー。 /// </summary> public class QueueMemoryStream : MemoryTributary { public long 読み出し位置 { get { lock( this._Stream排他 ) return this._読み出し位置; } set { lock( this._Stream排他 ) this._読み出し位置 = Math.Clamp( value, min: 0, max: this._読み出し位置 + this.読み出し可能サイズ ); } } public long 書き込み位置 { get { lock( this._Stream排他 ) return this._書き込み位置; } protected set { lock( this._Stream排他 ) this._書き込み位置 = value; } } public long 読み出し可能サイズ { get { lock( this._Stream排他 ) return ( this._書き込み位置 - this._読み出し位置 ); } } public QueueMemoryStream() { } /// <summary> /// ストリームの現在の読み込み位置からデータを読み出す。 /// データが足りないなら、そろうまでブロックする。 /// </summary> /// <param name="buffer">読み込んだデータを格納する配列。</param> /// <param name="offset">格納を開始する <paramref name="buffer"/> の位置。0 から始まるインデックス値。</param> /// <param name="count">読み込むバイト数。</param> /// <returns>格納したバイト数。</returns> public override int Read( byte[] buffer, int offset, int count ) { lock( this._Stream排他 ) { // キャンセル済みなら何もしない。 if( this._Canceled ) return default; // データが足りないなら、そろうまでブロックする。 while( this.読み出し可能サイズ < count ) { // lock を解放してウェイトに入る。戻ってきたときには lock が再取得されている。 Monitor.Wait( this._Stream排他 ); // ブロックが解除されたとき、既にキャンセル済みだったら何もせず戻る。 if( this._Canceled ) return default; } this.Position = this.読み出し位置; int num = base.Read( buffer, offset, count ); this.読み出し位置 = this.Position; // キューの中身が変化したことを、Monitor.Wait してるスレッドへ通知する。 Monitor.PulseAll( this._Stream排他 ); return num; } } /// <summary> /// ストリームの現在の読み込み位置からデータを読み出す。 /// データが足りないときにブロックするか否かは引数で指定できる。 /// </summary> /// <param name="buffer">読み込んだデータを格納する配列。</param> /// <param name="offset">格納を開始する <paramref name="buffer"/> の位置。0 から始まるインデックス値。</param> /// <param name="count">読み込むバイト数。</param> /// <param name="データが足りないならブロックする">読みだせるデータが足りない場合の挙動。true ならデータがそろうまでブロックし、false ならあるだけ全部読みだしてすぐに戻る。</param> /// <returns>格納したバイト数。</returns> public int Read( byte[] buffer, int offset, int count, bool データが足りないならブロックする ) { if( データが足りないならブロックする ) return this.Read( buffer, offset, count ); lock( this._Stream排他 ) { // キャンセル済みなら何もしない。 if( this._Canceled ) return default; if( this.読み出し可能サイズ < count ) { // データが足りないなら、あるだけ全部読みだす。 count = (int)this.読み出し可能サイズ; } this.Position = this.読み出し位置; int num = base.Read( buffer, offset, count ); this.読み出し位置 = this.Position; // キューの中身が変化したことを、Monitor.Wait してるスレッドへ通知する。 Monitor.PulseAll( this._Stream排他 ); return num; } } /// <summary> /// ストリームの現在の書き込み位置からデータを書き込む。 /// </summary> /// <param name="buffer">ストリームに書き込むデータを持つ配列。</param> /// <param name="offset">書き込みを開始する <paramref name="buffer"/> の位置。0 から始まるインデックス値。</param> /// <param name="count">書き込むバイト数。</param> public override void Write( byte[] buffer, int offset, int count ) { lock( this._Stream排他 ) { // キャンセル済みなら何もしない。 if( this._Canceled ) return; this.Position = this.書き込み位置; base.Write( buffer, offset, count ); this.書き込み位置 = this.Position; // キューの中身が変化したことを、Monitor.Wait してるスレッドへ通知する。 Monitor.PulseAll( this._Stream排他 ); } } /// <summary> /// <see cref="Read"/> あるいは <see cref="Write(byte[], int, int)"/> でブロックしているスレッドにキャンセルを通知してブロックを解除する。 /// その後、Read も Write も無効とする。 /// </summary> public void Cancel() { this._Canceled = true; lock( this._Stream排他 ) { // Monitor.Wait してるスレッドへ通知する。 Monitor.PulseAll( this._Stream排他 ); } } private long _読み出し位置 = 0; private long _書き込み位置 = 0; private bool _Canceled = false; private readonly object _Stream排他 = new object(); } } <|start_filename|>DTXMania2/ステージ/アイキャッチ管理.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using FDK; namespace DTXMania2 { /// <summary> /// 全アイキャッチのインスタンスを保持する。 /// </summary> class アイキャッチ管理 : IDisposable { // プロパティ public アイキャッチ 現在のアイキャッチ { get; protected set; } // 生成と終了 public アイキャッチ管理() { using var _ = new LogBlock( Log.現在のメソッド名 ); // アイキャッチが増えたらここに追加する。 this._アイキャッチリスト = new Dictionary<string, アイキャッチ>() { { nameof( シャッター ), new シャッター() }, { nameof( 回転幕 ), new 回転幕() }, { nameof( GO ), new GO() }, { nameof( 半回転黒フェード ), new 半回転黒フェード() }, }; this.現在のアイキャッチ = this._アイキャッチリスト[ nameof( シャッター ) ]; // 最初は先頭のもの } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var kvp in this._アイキャッチリスト ) kvp.Value?.Dispose(); } // クローズ開始 /// <summary> /// 指定した名前のアイキャッチのクローズアニメーションを開始する。 /// </summary> /// <remarks> /// クローズしたアイキャッチをオープンする際には、クローズしたときと同じアイキャッチを使う必要がある。 /// ここで指定したアイキャッチは <see cref="現在のアイキャッチ"/> に保存されるので、 /// 遷移先のステージでオープンするアイキャッチには、これを使用すること。 /// </remarks> public void アイキャッチを選択しクローズする( string 名前 ) { this.現在のアイキャッチ = this._アイキャッチリスト[ 名前 ]; // 保存。 this.現在のアイキャッチ.クローズする(); } // ローカル private readonly Dictionary<string, アイキャッチ> _アイキャッチリスト; } } <|start_filename|>FDK/SQLiteDB.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Data.Sqlite; namespace FDK { /// <summary> /// SQLiteのデータベースを操作するクラスの共通機能。 /// </summary> public class SQLiteDB : IDisposable { // プロパティ /// <summary> /// データベースへの接続。 /// </summary> public SqliteConnection Connection { get; protected set; } = null!; /// <summary> /// データベースの user_version プロパティ。 /// </summary> public long UserVersion { get { using( var cmd = new SqliteCommand( "PRAGMA user_version", this.Connection ) ) { return (long)( cmd.ExecuteScalar() ?? throw new Exception( "SQLite DB からの user_version の取得に失敗しました。" ) ); } } set { using( var cmd = new SqliteCommand( $"PRAGMA user_version = {value}", this.Connection ) ) { cmd.ExecuteNonQuery(); } } } // 生成と終了 public SQLiteDB() { } public SQLiteDB( VariablePath DBファイルパス ) { this.Open( DBファイルパス ); } public virtual void Dispose() { this.Connection?.Close(); this.Connection?.Dispose(); // SQLite は接続を切断した後もロックを維持するので、GC でそれを解放する。 // 参考: https://stackoverrun.com/ja/q/3363188 GC.Collect(); } public void Open( VariablePath DBファイルパス ) { // DBへ接続し、開く。(DBファイルが存在しない場合は自動的に生成される。) var db接続文字列 = new SqliteConnectionStringBuilder() { DataSource = DBファイルパス.変数なしパス }.ToString(); this.Connection = new SqliteConnection( db接続文字列 ); this.Connection.Open(); } } } <|start_filename|>SSTFEditor/小節長倍率入力ダイアログ.designer.cs<|end_filename|> namespace SSTFEditor { partial class 小節長倍率入力ダイアログ { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( 小節長倍率入力ダイアログ ) ); this.label小節番号 = new System.Windows.Forms.Label(); this.label小節長倍率 = new System.Windows.Forms.Label(); this.checkBox後続設定 = new System.Windows.Forms.CheckBox(); this.buttonキャンセル = new System.Windows.Forms.Button(); this.buttonOK = new System.Windows.Forms.Button(); this.numericUpDown小節長の倍率 = new System.Windows.Forms.NumericUpDown(); this.textBox小節番号 = new System.Windows.Forms.TextBox(); ( (System.ComponentModel.ISupportInitialize) ( this.numericUpDown小節長の倍率 ) ).BeginInit(); this.SuspendLayout(); // // label小節番号 // resources.ApplyResources( this.label小節番号, "label小節番号" ); this.label小節番号.Name = "label小節番号"; // // label小節長倍率 // resources.ApplyResources( this.label小節長倍率, "label小節長倍率" ); this.label小節長倍率.Name = "label小節長倍率"; // // checkBox後続設定 // resources.ApplyResources( this.checkBox後続設定, "checkBox後続設定" ); this.checkBox後続設定.Name = "checkBox後続設定"; this.checkBox後続設定.UseVisualStyleBackColor = true; this.checkBox後続設定.KeyDown += new System.Windows.Forms.KeyEventHandler( this.checkBox後続設定_KeyDown ); // // buttonキャンセル // resources.ApplyResources( this.buttonキャンセル, "buttonキャンセル" ); this.buttonキャンセル.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonキャンセル.Name = "buttonキャンセル"; this.buttonキャンセル.UseVisualStyleBackColor = true; // // buttonOK // resources.ApplyResources( this.buttonOK, "buttonOK" ); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Name = "buttonOK"; this.buttonOK.UseVisualStyleBackColor = true; // // numericUpDown小節長の倍率 // this.numericUpDown小節長の倍率.DecimalPlaces = 3; resources.ApplyResources( this.numericUpDown小節長の倍率, "numericUpDown小節長の倍率" ); this.numericUpDown小節長の倍率.Increment = new decimal( new int[] { 5, 0, 0, 131072} ); this.numericUpDown小節長の倍率.Minimum = new decimal( new int[] { 1, 0, 0, 196608} ); this.numericUpDown小節長の倍率.Name = "numericUpDown小節長の倍率"; this.numericUpDown小節長の倍率.Value = new decimal( new int[] { 1, 0, 0, 0} ); this.numericUpDown小節長の倍率.KeyDown += new System.Windows.Forms.KeyEventHandler( this.numericUpDown小節長の倍率_KeyDown ); // // textBox小節番号 // this.textBox小節番号.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources( this.textBox小節番号, "textBox小節番号" ); this.textBox小節番号.Name = "textBox小節番号"; this.textBox小節番号.ReadOnly = true; // // C小節長倍率入力ダイアログ // resources.ApplyResources( this, "$this" ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ControlBox = false; this.Controls.Add( this.textBox小節番号 ); this.Controls.Add( this.label小節番号 ); this.Controls.Add( this.label小節長倍率 ); this.Controls.Add( this.checkBox後続設定 ); this.Controls.Add( this.buttonキャンセル ); this.Controls.Add( this.buttonOK ); this.Controls.Add( this.numericUpDown小節長の倍率 ); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "C小節長倍率入力ダイアログ"; ( (System.ComponentModel.ISupportInitialize) ( this.numericUpDown小節長の倍率 ) ).EndInit(); this.ResumeLayout( false ); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label小節番号; private System.Windows.Forms.Label label小節長倍率; private System.Windows.Forms.CheckBox checkBox後続設定; private System.Windows.Forms.Button buttonキャンセル; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.NumericUpDown numericUpDown小節長の倍率; private System.Windows.Forms.TextBox textBox小節番号; } } <|start_filename|>DTXMania2/ステージ/04選曲/選曲リスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Animation; using FDK; using DTXMania2.曲; namespace DTXMania2.選曲 { /// <summary> /// フォーカスリストの表示、スクロール、フォーカスノードの選択など。 /// </summary> /// <remarks> /// フォーカスノードを中心として、フォーカスリストから10ノードを表示する。 /// 画面に表示されるのは8行だが、スクロールを勘案して上下に1行ずつ追加し、計10行として扱う。 /// </remarks> class 選曲リスト : IDisposable { // 生成と終了 public 選曲リスト() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._カーソル位置 = 4; this._曲リスト全体のY軸移動オフセット = 0; this._スクロール用カウンタ = new 定間隔進行(); this._選択ノードの表示オフセットdpx = null; this._選択ノードの表示オフセットのストーリーボード = null; this._選択ノードのオフセットアニメをリセットする(); this._既定のノード画像 = new 画像D2D( @"$(Images)\DefaultPreviewImage.png" ); this._現行化前のノード画像 = new 画像D2D( @"$(Images)\PreviewImageWaitForActivation.png" ); this._成績アイコン = new 画像D2D( @"$(Images)\SelectStage\RecordIcon.png" ); this._成績アイコンの矩形リスト = new 矩形リスト( @"$(Images)\SelectStage\RecordIcon.yaml" ); this._評価アイコン = new 画像D2D( @"$(Images)\SelectStage\RatingIcon.png" ); this._評価アイコンの矩形リスト = new 矩形リスト( @"$(Images)\SelectStage\RatingIcon.yaml" ); this._達成率ゲージアイコン = new 画像D2D( @"$(Images)\AchivementIcon.png" ); this._達成率数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_LargeBoldItalic.png", @"$(Images)\ParameterFont_LargeBoldItalic.yaml", 文字幅補正dpx: -2f, 不透明度: 0.5f ); this._プレビュー音声 = new プレビュー音声(); this.フォーカスリストを優先して現行化する(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._選択ノードの表示オフセットのストーリーボード?.Dispose(); this._選択ノードの表示オフセットdpx?.Dispose(); this._プレビュー音声.Dispose(); this._達成率数字画像.Dispose(); this._達成率ゲージアイコン.Dispose(); this._評価アイコン.Dispose(); this._成績アイコン.Dispose(); this._現行化前のノード画像.Dispose(); this._既定のノード画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { var フォーカスノード = Global.App.曲ツリーリスト.SelectedItem!.フォーカスノード; #region " 曲リストの縦方向スクロール進行残があれば進行する。" //---------------- this._スクロール用カウンタ.経過時間の分だけ進行する( 1, () => { int オフセットの加減算速度 = 1; #region " カーソルが中央から遠いほど速くなるよう、オフセットの加減算速度(絶対値)を計算する。" //------------------ int 距離 = Math.Abs( 4 - this._カーソル位置 ); if( 2 > 距離 ) オフセットの加減算速度 = 1; else if( 4 > 距離 ) オフセットの加減算速度 = 2; else if( 6 > 距離 ) オフセットの加減算速度 = 3; else オフセットの加減算速度 = 4; //------------------ #endregion // オフセット と カーソル位置 を更新する。 if( ( 4 > this._カーソル位置 ) || ( ( 4 == this._カーソル位置 ) && ( 0 > this._曲リスト全体のY軸移動オフセット ) ) ) { #region " (A) パネルは、上から下へ、移動する。" //----------------- this._曲リスト全体のY軸移動オフセット += オフセットの加減算速度; // 1行分移動した if( 100 <= this._曲リスト全体のY軸移動オフセット ) { this._曲リスト全体のY軸移動オフセット -= 100; // 0 付近に戻る this._カーソル位置++; } //----------------- #endregion } else if( ( 4 < this._カーソル位置 ) || ( ( 4 == this._カーソル位置 ) && ( 0 < this._曲リスト全体のY軸移動オフセット ) ) ) { #region " (B) パネルは、下から上へ、移動する。" //----------------- this._曲リスト全体のY軸移動オフセット -= オフセットの加減算速度; // 1行分移動した if( -100 >= this._曲リスト全体のY軸移動オフセット ) { this._曲リスト全体のY軸移動オフセット += 100; // 0 付近に戻る this._カーソル位置--; } //----------------- #endregion } } ); //---------------- #endregion #region " フォーカスノードまたはフォーカス譜面が変更されていればプレビュー音声を再生する。" //---------------- if( this._現在のフォーカスノード != フォーカスノード ) { #region " (A) 別のノードがフォーカスされた場合 " //---------------- this._現在のフォーカスノード = フォーカスノード; this._プレビュー音声.停止する(); if( フォーカスノード is SongNode snode && null != snode.曲.フォーカス譜面 ) { // (A-a) 新しくフォーカスされたのは SongNode である if( !string.IsNullOrEmpty( snode.曲.フォーカス譜面.譜面.PreSound ) ) { // (A-a-a) SondNode のフォーカス譜面に PreSound 指定がある var 音声ファイルの絶対パス = Path.Combine( Path.GetDirectoryName( snode.曲.フォーカス譜面.譜面.ScorePath ) ?? @"\", snode.曲.フォーカス譜面.譜面.PreSound ); this._プレビュー音声.再生を予約する( 音声ファイルの絶対パス ); } else { // (A-a-b) SongNode のフォーカス譜面に PreSound 指定がない } } else { // (A-b) 新しくフォーカスされたのは SongNode ではない } //---------------- #endregion } else if( フォーカスノード is SongNode snode && null != snode.曲.フォーカス譜面 ) { #region " (B) フォーカスノードは変更されておらず、同一の SongNode のままである場合 " //---------------- if( this._現在のフォーカス譜面 != snode.曲.フォーカス譜面 ) { // (B-a) 同じ SongNode の別の譜面がフォーカスされた this._現在のフォーカス譜面 = snode.曲.フォーカス譜面; if( !string.IsNullOrEmpty( snode.曲.フォーカス譜面.譜面.PreSound ) ) { // (B-a-a) SondNode のフォーカス譜面に PreSound 指定がある var 音声ファイルの絶対パス = Path.Combine( Path.GetDirectoryName( snode.曲.フォーカス譜面.譜面.ScorePath ) ?? @"\", snode.曲.フォーカス譜面.譜面.PreSound ); this._プレビュー音声.再生を予約する( 音声ファイルの絶対パス ); } else { // (B-a-b) SongNode のフォーカス譜面に PreSound 指定がない } } else { // (B-b) 同じ SongNode の同じ譜面をフォーカスしたまま変わっていない } //---------------- #endregion } else { // (C) フォーカスノードは変更されておらず、それは SongNode でもない場合 → 何もしない } //---------------- #endregion #region " ノードを10行描画する。" //---------------- { var node = Global.App.曲ツリーリスト.SelectedItem!.フォーカスノード; if( node is null ) return; // 表示する最上行のノードまで戻る。 for( int i = 0; i < this._カーソル位置; i++ ) node = node.前のノード; // 10行描画する。 for( int i = 0; i < 10; i++ ) { this._リストを1行描画する( d2ddc, i, node ); node = node.次のノード; } } //---------------- #endregion } public void プレビュー音声を停止する() => this._プレビュー音声.停止する(); // リスト操作 public void 前のノードを選択する() { this._カーソル位置--; // 下限なし Global.App.曲ツリーリスト.SelectedItem!.前のノードをフォーカスする(); this._選択ノードのオフセットアニメをリセットする(); this.フォーカスノードを優先して現行化する(); } public void 次のノードを選択する() { this._カーソル位置++; // 上限なし Global.App.曲ツリーリスト.SelectedItem!.次のノードをフォーカスする(); this._選択ノードのオフセットアニメをリセットする(); this.フォーカスノードを優先して現行化する(); } public void BOXに入る() { var boxNode = Global.App.曲ツリーリスト.SelectedItem!.フォーカスノード as BoxNode; if( boxNode is null ) return; this._カーソル位置 = 4; this._曲リスト全体のY軸移動オフセット = 0; Global.App.曲ツリーリスト.SelectedItem!.フォーカスする( boxNode.子ノードリスト[ 0 ] ); this.フォーカスリストを優先して現行化する(); } public void BOXから出る() { var node = Global.App.曲ツリーリスト.SelectedItem!.フォーカスノード; if( node is null || node.親ノード is null ) return; this._カーソル位置 = 4; this._曲リスト全体のY軸移動オフセット = 0; Global.App.曲ツリーリスト.SelectedItem!.フォーカスする( node.親ノード ); this.フォーカスリストを優先して現行化する(); } public async void フォーカスリストを優先して現行化する() { var focusList = Global.App.曲ツリーリスト.SelectedItem!.フォーカスリスト; if( focusList.Any( ( node ) => !node.現行化済み ) ) { // 現行化スタックは FIFO なので、このスタックに Push するだけで他より優先して現行化されるようになる。 // このスタックには、すでに Push 済みのノードを重ねて Push しても構わない。(現行化済みのノードは単に無視されるため。) await Global.App.現行化.追加するAsync( focusList ); // さらに、SongNode 以外(BOX名や「戻る」など)を優先する。 await Global.App.現行化.追加するAsync( focusList.Where( ( node ) => !( node is SongNode ) ).ToArray() ); } } public void フォーカスノードを優先して現行化する() { this.指定したノードを優先して現行化する( Global.App.曲ツリーリスト.SelectedItem!.フォーカスノード ); } public async void 指定したノードを優先して現行化する( Node? node ) { if( null != node && node is SongNode && !node.現行化済み ) { await Global.App.現行化.追加するAsync( new Node[] { node } ); } } // ローカル /// <summary> /// カーソルの現在位置。 /// </summary> /// <remarks> /// 静止時は 4 。曲リストがスクロールしているときは、4より大きい整数(下から上にスクロール中)か、 /// または 4 より小さい整数(上から下にスクロール中)になる。 /// </remarks> private int _カーソル位置 = 4; private readonly 画像D2D _既定のノード画像; private readonly 画像D2D _現行化前のノード画像; private readonly 画像D2D _成績アイコン; private readonly 矩形リスト _成績アイコンの矩形リスト; private readonly 画像D2D _評価アイコン; private readonly 矩形リスト _評価アイコンの矩形リスト; private readonly 画像D2D _達成率ゲージアイコン; private readonly フォント画像D2D _達成率数字画像; private readonly 定間隔進行 _スクロール用カウンタ; private readonly プレビュー音声 _プレビュー音声; private Node? _現在のフォーカスノード = null; private Score? _現在のフォーカス譜面 = null; /// <summary> /// -100~100。曲リスト全体の表示位置を、負数は 上 へ、正数は 下 へずらす 。(正負と上下の対応に注意。) /// </summary> private int _曲リスト全体のY軸移動オフセット; /// <summary> /// 選択中の曲ノードエリアを左にずらす度合い。 /// -50f ~ 0f [dpx] 。 /// </summary> private Variable? _選択ノードの表示オフセットdpx; private Storyboard? _選択ノードの表示オフセットのストーリーボード; private const float _ノードの高さdpx = ( 913f / 8f ); /// <summary> /// 曲リスト(10行分)の合計表示領域の左上隅の座標。 /// </summary> /// <remarks> /// 基準というのは、曲リストがスクロールしていないときの位置、という意味。 /// </remarks> private readonly Vector3 _曲リストの基準左上隅座標dpx = new Vector3( 1065f, 145f - _ノードの高さdpx, 0f ); private readonly Vector3 _サムネイル表示サイズdpx = new Vector3( 100f, 100f, 0f ); /// <param name="行番号"> /// 一番上:0 ~ 9:一番下。 /// 「静止時の」可視範囲は 1~8。4 がフォーカスノード。 /// </param> private void _リストを1行描画する( DeviceContext d2ddc, int 行番号, Node node ) { bool 選択ノードである = ( 4 == 行番号 ); float 実数行番号 = 行番号 + this._曲リスト全体のY軸移動オフセット / 100.0f; var ノード左上dpx = new Vector2( this._曲リストの基準左上隅座標dpx.X + ( 選択ノードである ? (float)( this._選択ノードの表示オフセットdpx?.Value ?? 0f ) : 0f ), this._曲リストの基準左上隅座標dpx.Y + ( 実数行番号 * _ノードの高さdpx ) ); var preBlend = d2ddc.PrimitiveBlend; #region " 背景 " //---------------- d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; if( node is BoxNode ) { #region " BOXノードの背景 " //---------------- using var brush = new SolidColorBrush( d2ddc, new Color4( 0xffa3647c ) ); using var pathGeometry = new PathGeometry( Global.GraphicResources.D2D1Factory1 ); using( var sink = pathGeometry.Open() ) { sink.SetFillMode( FillMode.Winding ); sink.BeginFigure( new Vector2( ノード左上dpx.X, ノード左上dpx.Y + 8f ), FigureBegin.Filled ); // 点1 var points = new SharpDX.Mathematics.Interop.RawVector2[] { new Vector2( ノード左上dpx.X + 150f, ノード左上dpx.Y + 8f ), // → 点2 new Vector2( ノード左上dpx.X + 170f, ノード左上dpx.Y + 18f ), // → 点3 new Vector2( Global.GraphicResources.設計画面サイズ.Width, ノード左上dpx.Y + 18f ), // → 点4 new Vector2( Global.GraphicResources.設計画面サイズ.Width, ノード左上dpx.Y + _ノードの高さdpx ), // → 点5 new Vector2( ノード左上dpx.X, ノード左上dpx.Y + _ノードの高さdpx ), // → 点6 new Vector2( ノード左上dpx.X, ノード左上dpx.Y + 8f ), // → 点1 }; sink.AddLines( points ); sink.EndFigure( FigureEnd.Closed ); sink.Close(); } d2ddc.FillGeometry( pathGeometry, brush ); //---------------- #endregion } else if( node is BackNode || node is RandomSelectNode ) { #region " BACK, RandomSelectノードの背景 " //---------------- using var brush = new SolidColorBrush( d2ddc, Color4.Black ); using var pathGeometry = new PathGeometry( Global.GraphicResources.D2D1Factory1 ); using( var sink = pathGeometry.Open() ) { sink.SetFillMode( FillMode.Winding ); sink.BeginFigure( new Vector2( ノード左上dpx.X, ノード左上dpx.Y + 8f ), FigureBegin.Filled ); // 点1 var points = new SharpDX.Mathematics.Interop.RawVector2[] { new Vector2( ノード左上dpx.X + 150f, ノード左上dpx.Y + 8f ), // → 点2 new Vector2( ノード左上dpx.X + 170f, ノード左上dpx.Y + 18f ), // → 点3 new Vector2( Global.GraphicResources.設計画面サイズ.Width, ノード左上dpx.Y + 18f ), // → 点4 new Vector2( Global.GraphicResources.設計画面サイズ.Width, ノード左上dpx.Y + _ノードの高さdpx ),// → 点5 new Vector2( ノード左上dpx.X, ノード左上dpx.Y + _ノードの高さdpx ), // → 点6 new Vector2( ノード左上dpx.X, ノード左上dpx.Y + 8f ), // → 点1 }; sink.AddLines( points ); sink.EndFigure( FigureEnd.Closed ); sink.Close(); } d2ddc.FillGeometry( pathGeometry, brush ); //---------------- #endregion } else { #region " 既定の背景 " //---------------- using var brush = new SolidColorBrush( d2ddc, new Color4( 0f, 0f, 0f, 0.25f ) ); // 半透明の黒 d2ddc.FillRectangle( new RectangleF( ノード左上dpx.X, ノード左上dpx.Y, Global.GraphicResources.設計画面サイズ.Width - ノード左上dpx.X, _ノードの高さdpx ), brush ); //---------------- #endregion } d2ddc.PrimitiveBlend = preBlend; //---------------- #endregion #region " サムネイル画像 " //---------------- { // ノード画像を縮小して表示する。 var ノード画像 = node.現行化済み ? ( node.ノード画像 ?? this._既定のノード画像 ) : this._現行化前のノード画像; var ノード内サムネイルオフセットdpx = new Vector3( 58f, 4f, 0f ); var サムネイル表示左上dpx = new Vector2( ノード左上dpx.X + ノード内サムネイルオフセットdpx.X, ノード左上dpx.Y + ノード内サムネイルオフセットdpx.Y ); if( node is BoxNode ) { #region " BOXノードのサムネイル画像 → 普通のノードよりも少し小さく表示する(涙 " //---------------- var 変換行列2D = Matrix3x2.Scaling( this._サムネイル表示サイズdpx.X / ノード画像.サイズ.Width, this._サムネイル表示サイズdpx.Y / ノード画像.サイズ.Height ) * Matrix3x2.Scaling( 0.9f ) * // ちょっと小さく Matrix3x2.Translation( サムネイル表示左上dpx ) * Matrix3x2.Translation( 0f, +12f ); // ちょっと下へ ノード画像.描画する( d2ddc, 変換行列2D ); //---------------- #endregion } else if( node is BackNode || node is RandomSelectNode ) { // BACK, RandomSelectノードはサムネイル画像なし } else { #region " 既定のサムネイル画像 " //---------------- var 変換行列2D = Matrix3x2.Scaling( this._サムネイル表示サイズdpx.X / ノード画像.サイズ.Width, this._サムネイル表示サイズdpx.Y / ノード画像.サイズ.Height ) * Matrix3x2.Translation( サムネイル表示左上dpx ); ノード画像.描画する( d2ddc, 変換行列2D ); //---------------- #endregion } } //---------------- #endregion #region " 成績・評価 " //---------------- if( node is SongNode snode ) { var score = snode.曲.フォーカス譜面; if( null != score ) { if( score.最高記録を現行化済み && ( null != score.最高記録 ) ) { var 最高ランク = score.最高ランク!; var 達成率 = score.最高記録.Achievement; #region " 成績アイコン " //---------------- this._成績アイコン.描画する( d2ddc, ノード左上dpx.X + 6f, ノード左上dpx.Y + 57f, 転送元矩形: this._成績アイコンの矩形リスト[ 最高ランク.ToString()! ] ); //---------------- #endregion #region " 達成率ゲージ " //---------------- this._達成率ゲージアイコン.描画する( d2ddc, ノード左上dpx.X + 160f, ノード左上dpx.Y - 27f, X方向拡大率: 0.4f, Y方向拡大率: 0.4f ); this._達成率数字画像.描画する( d2ddc, ノード左上dpx.X + 204f, ノード左上dpx.Y + 4, score.最高記録.Achievement.ToString( "0.00" ).PadLeft( 6 ) + '%', 拡大率: new Size2F( 0.3f, 0.3f ) ); using var ゲージ色 = new SolidColorBrush( d2ddc, new Color( 184, 156, 231, 255 ) ); using var ゲージ枠色 = new SolidColorBrush( d2ddc, Color.White ); using var ゲージ背景色 = new SolidColorBrush( d2ddc, new Color( 0.25f, 0.25f, 0.25f, 1f ) ); using var ゲージ枠ジオメトリ = new PathGeometry( Global.GraphicResources.D2D1Factory1 ); using var ゲージジオメトリ = new PathGeometry( Global.GraphicResources.D2D1Factory1 ); var ゲージサイズdpx = new Size2F( 448f, 17f ); var ゲージ位置 = new Vector2( ノード左上dpx.X + 310f, ノード左上dpx.Y + 10f ); using( var sink = ゲージジオメトリ.Open() ) { var 割合0to1 = (float)( 達成率 / 100.0 ); var p = new Vector2[] { new Vector2( ゲージ位置.X, ゲージ位置.Y ), // 左上 new Vector2( ゲージ位置.X + ゲージサイズdpx.Width * 割合0to1, ゲージ位置.Y ), // 右上 new Vector2( ゲージ位置.X + ゲージサイズdpx.Width * 割合0to1 - 3f, ゲージ位置.Y + ゲージサイズdpx.Height ), // 右下 new Vector2( ゲージ位置.X - 3f, ゲージ位置.Y + ゲージサイズdpx.Height ), // 左下 }; sink.SetFillMode( FillMode.Winding ); sink.BeginFigure( p[ 0 ], FigureBegin.Filled ); sink.AddLine( p[ 1 ] ); sink.AddLine( p[ 2 ] ); sink.AddLine( p[ 3 ] ); sink.EndFigure( FigureEnd.Closed ); sink.Close(); } using( var sink = ゲージ枠ジオメトリ.Open() ) { var p = new Vector2[] { new Vector2( ゲージ位置.X, ゲージ位置.Y ), // 左上 new Vector2( ゲージ位置.X + ゲージサイズdpx.Width, ゲージ位置.Y ), // 右上 new Vector2( ゲージ位置.X + ゲージサイズdpx.Width - 3f, ゲージ位置.Y + ゲージサイズdpx.Height ), // 右下 new Vector2( ゲージ位置.X - 3f, ゲージ位置.Y + ゲージサイズdpx.Height ), // 左下 }; sink.SetFillMode( FillMode.Winding ); sink.BeginFigure( p[ 0 ], FigureBegin.Filled ); sink.AddLine( p[ 1 ] ); sink.AddLine( p[ 2 ] ); sink.AddLine( p[ 3 ] ); sink.EndFigure( FigureEnd.Closed ); sink.Close(); } d2ddc.FillGeometry( ゲージ枠ジオメトリ, ゲージ背景色 ); d2ddc.FillGeometry( ゲージジオメトリ, ゲージ色 ); d2ddc.DrawGeometry( ゲージジオメトリ, ゲージ枠色, 1f ); d2ddc.DrawGeometry( ゲージ枠ジオメトリ, ゲージ枠色, 2f ); //---------------- #endregion } #region " 評価アイコン " //---------------- if( score.譜面の属性を現行化済み ) { var 評価 = score.譜面の属性?.Rating ?? 0; // 0~4; nullは0扱い if( 0 < 評価 ) { this._評価アイコン.描画する( d2ddc, ノード左上dpx.X + 6f, ノード左上dpx.Y + 0f, 転送元矩形: this._評価アイコンの矩形リスト[ 評価.ToString() ] ); } } //---------------- #endregion } } //---------------- #endregion #region " タイトル文字列 " //---------------- //if( node.現行化済み ) --> タイトル文字列とサブタイトル文字列は現行前から生成されている。 { var image = node.タイトル文字列画像; // 最大幅を考慮して拡大率を決定する。 float 最大幅dpx = Global.GraphicResources.設計画面サイズ.Width - ノード左上dpx.X - 170f; if( null != image ) { image.描画する( d2ddc, ノード左上dpx.X + 170f, ノード左上dpx.Y + 20f, X方向拡大率: ( image.画像サイズdpx.Width <= 最大幅dpx ) ? 1f : 最大幅dpx / image.画像サイズdpx.Width ); } } //---------------- #endregion #region " サブタイトル文字列 " //---------------- if( 選択ノードである )//&& node.現行化済み ) --> タイトル文字列とサブタイトル文字列は現行前から生成されている。 { var image = node.サブタイトル文字列画像; // 最大幅を考慮して拡大率を決定する。 float 最大幅dpx = Global.GraphicResources.設計画面サイズ.Width - ノード左上dpx.X - 170f; if( null != image ) { image.描画する( d2ddc, ノード左上dpx.X + 190f, ノード左上dpx.Y + 70f, X方向拡大率: ( image.画像サイズdpx.Width <= 最大幅dpx ) ? 1f : 最大幅dpx / image.画像サイズdpx.Width ); } } //---------------- #endregion } private void _選択ノードのオフセットアニメをリセットする() { this._選択ノードの表示オフセットdpx?.Dispose(); this._選択ノードの表示オフセットdpx = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this._選択ノードの表示オフセットのストーリーボード?.Dispose(); this._選択ノードの表示オフセットのストーリーボード = new Storyboard( Global.Animation.Manager ); using( var 維持 = Global.Animation.TrasitionLibrary.Constant( 0.15 ) ) using( var 左へ移動 = Global.Animation.TrasitionLibrary.Linear( 0.07, finalValue: -50f ) ) { this._選択ノードの表示オフセットのストーリーボード.AddTransition( this._選択ノードの表示オフセットdpx, 維持 ); this._選択ノードの表示オフセットのストーリーボード.AddTransition( this._選択ノードの表示オフセットdpx, 左へ移動 ); } this._選択ノードの表示オフセットのストーリーボード.Schedule( Global.Animation.Timer.Time ); } } } <|start_filename|>DTXMania2/曲/WAV管理.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using CSCore; using FDK; namespace DTXMania2 { /// <summary> /// <see cref="スコア.WAVリスト"/> の各サウンドインスタンスを管理する。 /// サウンドの作成には <see cref="App.WAVキャッシュ"/> を使用する。 /// </summary> class WAV管理 : IDisposable { // 生成と終了 /// <param name="多重度"> /// 1サウンドの最大多重発声数。1以上。 /// </param> public WAV管理( int 多重度 = 4 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( 1 > 多重度 ) throw new ArgumentException( $"多重度が1未満に設定されています。[{多重度}]" ); this._既定の多重度 = 多重度; this._WAV情報リスト = new Dictionary<int, WAV情報>(); this._一時停止中の音声のリスト = new List<Sound>(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._一時停止中の音声のリスト.Clear(); // 参照なので要素はDisposeしない if( null != this._WAV情報リスト ) { foreach( var value in this._WAV情報リスト.Values ) value.Dispose(); this._WAV情報リスト.Clear(); } } // 登録、発声停止、再開 /// <summary> /// 指定したWAV番号にサウンドファイルを登録する。 /// </summary> /// <remarks> /// サウンドの生成に失敗した場合には登録を行わない。 /// </remarks> /// <param name="wav番号">登録する番号。0~1295。すでに登録されている場合は上書き更新される。</param> /// <param name="サウンドファイル">登録するサウンドファイルのパス。</param> public void 登録する( int wav番号, VariablePath サウンドファイル, bool 多重再生する, bool BGMである ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( ( 0 > wav番号 ) || ( 36 * 36 <= wav番号 ) ) throw new ArgumentOutOfRangeException( $"WAV番号が範囲(0~1295)を超えています。[{wav番号}]" ); if( !( File.Exists( サウンドファイル.変数なしパス ) ) ) { Log.WARNING( $"サウンドファイルが存在しません。[{サウンドファイル.変数付きパス}]" ); return; } // 先に ISampleSource を生成する。 var sampleSource = Global.App.WAVキャッシュ.作成する( サウンドファイル ); if( sampleSource is null ) { Log.WARNING( $"サウンドのデコードに失敗しました。[{サウンドファイル.変数付きパス}" ); return; } // サウンドを登録する。 if( this._WAV情報リスト.ContainsKey( wav番号 ) ) this._WAV情報リスト[ wav番号 ].Dispose(); // すでに登録済みなら先に解放する。 int 多重度 = ( 多重再生する ) ? this._既定の多重度 : 1; this._WAV情報リスト[ wav番号 ] = new WAV情報( wav番号, 多重度, BGMである ); this._WAV情報リスト[ wav番号 ].サウンドを生成する( Global.App.サウンドデバイス, sampleSource ); Log.Info( $"サウンドを読み込みました。[{サウンドファイル.変数付きパス}]" ); } /// <summary> /// 指定した番号のWAVを、指定したチップ種別として発声する。 /// </summary> /// <param name="音量">0:無音~1:原音</param> public void 発声する( int WAV番号, bool 発声前に消音する, 消音グループ種別 muteGroupType, bool BGM以外も再生する, float 音量 = 1f, double 再生開始時刻sec = 0.0 ) { if( !( this._WAV情報リスト.ContainsKey( WAV番号 ) ) ) return; // 未使用のWAV番号は無視。 if( !( BGM以外も再生する ) && !( this._WAV情報リスト[ WAV番号 ].BGMである ) ) return; // BGM以外を再生しない場合、BGM以外のWAV番号は無視。 // 指定があれば消音する。 if( 発声前に消音する && muteGroupType != 消音グループ種別.Unknown ) { // 発声時に指定された消音グループ種別に属するWAVサウンドをすべて停止する。 var 停止するWavContexts = this._WAV情報リスト .Where( ( kvp ) => ( kvp.Value.最後に発声したときの消音グループ種別 == muteGroupType ) ); foreach( var kvp in 停止するWavContexts ) kvp.Value.発声を停止する(); } // 発声する。 if( this._WAV情報リスト[ WAV番号 ].BGMである ) { // BGM なら BGMAdjust を適用する。 再生開始時刻sec += Global.App.演奏譜面.譜面.BGMAdjust / 1000.0; 再生開始時刻sec = Math.Max( 0.0, 再生開始時刻sec ); } this._WAV情報リスト[ WAV番号 ].発声する( muteGroupType, 音量, 再生開始時刻sec ); } public void すべての発声を停止する() { foreach( var kvp in this._WAV情報リスト ) kvp.Value.発声を停止する(); } public void 再生位置を移動する( int WAV番号, double 移動量sec ) { if( this._WAV情報リスト.ContainsKey( WAV番号 ) ) this._WAV情報リスト[ WAV番号 ].再生位置を移動する( 移動量sec ); } public void すべてのBGMの再生位置を移動する( double 移動量sec ) { foreach( var kvp in this._WAV情報リスト.Where( ( kvp ) => kvp.Value.BGMである ) ) kvp.Value.再生位置を移動する( 移動量sec ); } public void 再生中の音声をすべて一時停止する() { this._一時停止中の音声のリスト.Clear(); foreach( var kvp in this._WAV情報リスト ) { foreach( var sound in kvp.Value.Sounds.Where( ( sd ) => sd.再生中である ) ) { sound.Pause(); this._一時停止中の音声のリスト.Add( sound ); } } } public void 一時停止中の音声をすべて再開する() { foreach( var sound in this._一時停止中の音声のリスト ) sound.Resume(); } // ローカル private readonly List<Sound> _一時停止中の音声のリスト; private readonly int _既定の多重度; /// <summary> /// 全WAVの管理DB。KeyはWAV番号。 /// </summary> private readonly Dictionary<int, WAV情報> _WAV情報リスト; /// <summary> /// WAV ごとの管理情報。 /// </summary> private class WAV情報 : IDisposable { /// <summary> /// 0~1295。 /// </summary> public int WAV番号 { get; } /// <summary> /// この WAV に対応するサウンド。 /// </summary> /// <remarks> /// サウンドデータとして <see cref="ISampleSource"/> を使用し、多重度の数だけ存在することができる。 /// </remarks> public Sound[] Sounds { get; } public bool BGMである { get; } public 消音グループ種別 最後に発声したときの消音グループ種別 { get; protected set; } = 消音グループ種別.Unknown; public WAV情報( int wav番号, int 多重度, bool BGMである ) { if( ( 0 > wav番号 ) || ( 36 * 36 <= wav番号 ) ) throw new ArgumentOutOfRangeException( "WAV番号が不正です。" ); this.WAV番号 = wav番号; this.Sounds = new Sound[ 多重度 ]; this.BGMである = BGMである; } public virtual void Dispose() { foreach( var sd in this.Sounds ) sd.Dispose(); } /// <summary> /// 多重度の数だけ Sound を生成する。ただしソースは共通。 /// </summary> public void サウンドを生成する( SoundDevice device, ISampleSource sampleSource ) { for( int i = 0; i < this.Sounds.Length; i++ ) this.Sounds[ i ] = new Sound( device, sampleSource ); } /// <summary> /// 指定したチップ種別扱いでWAVサウンドを発声する。 /// </summary> /// <param name="音量">0:無音~1:原音</param> public void 発声する( 消音グループ種別 muteGroupType, float 音量, double 再生開始時刻sec = 0.0 ) { var sound = this.Sounds[ this._次に再生するSound番号 ]; if( sound.Length <= 再生開始時刻sec ) return; // 再生範囲外なので無視 this.最後に発声したときの消音グループ種別 = muteGroupType; // 発声。 sound.Volume = Math.Clamp( 音量, min: 0f, max: 1f ); sound.Play( 再生開始時刻sec ); // サウンドローテーション。 this._現在再生中のSound番号 = this._次に再生するSound番号; this._次に再生するSound番号 = ( this._次に再生するSound番号 + 1 ) % this.Sounds.Length; } public void 発声を停止する() { foreach( var sound in this.Sounds ) sound.Stop(); } public void 再生位置を移動する( double 移動量sec ) { if( 0 > this._現在再生中のSound番号 ) return; var sound = this.Sounds[ this._現在再生中のSound番号 ]; sound.Position += sound.秒ToFrame( 移動量sec ) * sound.WaveFormat.Channels; } private int _現在再生中のSound番号 = -1; private int _次に再生するSound番号 = 0; } } } <|start_filename|>DTXMania2/ステージ/04選曲/難易度と成績.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using FDK; using DTXMania2.曲; namespace DTXMania2.選曲 { class 難易度と成績 : IDisposable { // 外部接続アクション public Func<青い線> 青い線を取得する = () => throw new NotImplementedException(); // 生成と終了 public 難易度と成績() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_Large.png", @"$(Images)\ParameterFont_Large.yaml" ); this._見出し用TextFormat = new TextFormat( Global.GraphicResources.DWriteFactory, "Century Gothic", 16f ) { TextAlignment = TextAlignment.Trailing }; this._説明文用TextFormat = new TextFormat( Global.GraphicResources.DWriteFactory, "Century Gothic", 16f ) { TextAlignment = TextAlignment.Center }; this._黒透過ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( Color3.Black, 0.5f ) ); this._黒ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Color4.Black ); this._白ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Color4.White ); this._ULTIMATE色ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Song.難易度色リスト[ 4 ] ); this._MASTER色ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Song.難易度色リスト[ 3 ] ); this._EXTREME色ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Song.難易度色リスト[ 2 ] ); this._ADVANCED色ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Song.難易度色リスト[ 1 ] ); this._BASIC色ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Song.難易度色リスト[ 0 ] ); this._難易度パネル色 = new Brush[ 5 ] { this._BASIC色ブラシ, this._ADVANCED色ブラシ, this._EXTREME色ブラシ, this._MASTER色ブラシ, this._ULTIMATE色ブラシ, }; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._BASIC色ブラシ.Dispose(); this._ADVANCED色ブラシ.Dispose(); this._EXTREME色ブラシ.Dispose(); this._MASTER色ブラシ.Dispose(); this._ULTIMATE色ブラシ.Dispose(); this._白ブラシ.Dispose(); this._黒ブラシ.Dispose(); this._黒透過ブラシ.Dispose(); this._説明文用TextFormat.Dispose(); this._見出し用TextFormat.Dispose(); this._数字画像.Dispose(); } // 進行と描画 /// <param name="選択している難易度レベル"> /// 0:BASIC~4:ULTIMATE /// </param> public void 進行描画する( DeviceContext d2ddc, int 選択している難易度レベル, Node フォーカスノード ) { var 背景領域dpx = new RectangleF( 642f, 529f, 338f, 508f ); var preBlend = d2ddc.PrimitiveBlend; #region " 背景を描画する。" //---------------- d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; d2ddc.FillRectangle( 背景領域dpx, this._黒透過ブラシ ); d2ddc.PrimitiveBlend = preBlend; //---------------- #endregion var パネル位置リスト = new (float X, float Y)[ 5 ] { ( 背景領域dpx.X + 156f, 背景領域dpx.Y + 417f ), ( 背景領域dpx.X + 156f, 背景領域dpx.Y + 316f ), ( 背景領域dpx.X + 156f, 背景領域dpx.Y + 215f ), ( 背景領域dpx.X + 156f, 背景領域dpx.Y + 114f ), ( 背景領域dpx.X + 156f, 背景領域dpx.Y + 13f ), }; #region " 難易度パネル(背景)を描画する。" //---------------- for( int i = 0; i < 5; i++ ) this._難易度パネルの背景を1つ描画する( d2ddc, パネル位置リスト[ i ].X, パネル位置リスト[ i ].Y, this._難易度パネル色[ i ], this._黒ブラシ ); //---------------- #endregion #region " フォーカスノードが変更されていれば更新する。" //---------------- if( フォーカスノード != this._現在表示しているノード ) { this._現在表示しているノード = フォーカスノード; } //---------------- #endregion if( !( フォーカスノード is SongNode ) && !( フォーカスノード is RandomSelectNode ) ) return; // 上記2つ以外はここまで。 var 難易度ラベルリスト = new string[ 5 ]; var 難易度リスト = new double[ 5 ]; #region " 難易度ラベルリストと難易度リストを作成する。" //---------------- if( フォーカスノード is SongNode snode ) { for( int i = 0; i < 5; i++ ) { 難易度ラベルリスト[ i ] = snode.曲.譜面リスト[ i ]?.難易度ラベル ?? ""; 難易度リスト[ i ] = snode.曲.譜面リスト[ i ]?.譜面.Level ?? 5.0; } } else if( フォーカスノード is RandomSelectNode ) { for( int i = 0; i < 5; i++ ) { 難易度ラベルリスト[ i ] = SetDef.デフォルトのラベル[ i ]; 難易度リスト[ i ] = 0.0; } } //---------------- #endregion #region " 難易度パネル(テキスト、数値)を描画する。" //---------------- for( int i = 0; i < 5; i++ ) this._難易度パネルのテキストを1つ描画する( d2ddc, フォーカスノード, パネル位置リスト[ i ].X, パネル位置リスト[ i ].Y, 難易度ラベルリスト[ i ], 難易度リスト[ i ], this._白ブラシ ); //---------------- #endregion #region " 選択枠を描画する。" //---------------- var 青い線 = this.青い線を取得する(); if( null != 青い線 ) { var 青領域dpx = new RectangleF( 642f + 10f, 529f + 5f + ( 4 - 選択している難易度レベル ) * 101f, 338f - 20f, 100f ); var 太さdpx = 青い線.太さdpx; 青い線.描画する( d2ddc, new Vector2( 青領域dpx.Left - 太さdpx / 4f, 青領域dpx.Top ), 幅dpx: 青領域dpx.Width + 太さdpx / 2f ); // 上辺 青い線.描画する( d2ddc, new Vector2( 青領域dpx.Left, 青領域dpx.Top - 太さdpx / 4f ), 高さdpx: 青領域dpx.Height + 太さdpx / 2f ); // 左辺 青い線.描画する( d2ddc, new Vector2( 青領域dpx.Left - 太さdpx / 4f, 青領域dpx.Bottom ), 幅dpx: 青領域dpx.Width + 太さdpx / 2f ); // 下辺 青い線.描画する( d2ddc, new Vector2( 青領域dpx.Right, 青領域dpx.Top - 太さdpx / 4f ), 高さdpx: 青領域dpx.Height + 太さdpx / 2f ); // 右辺 } //---------------- #endregion } private void _難易度パネルの背景を1つ描画する( DeviceContext d2ddc, float 基点X, float 基点Y, Brush 見出し背景ブラシ, Brush 数値背景ブラシ ) { d2ddc.FillRectangle( new RectangleF( 基点X, 基点Y, 157f, 20f ), 見出し背景ブラシ ); d2ddc.FillRectangle( new RectangleF( 基点X, 基点Y + 20f, 157f, 66f ), 数値背景ブラシ ); } private void _難易度パネルのテキストを1つ描画する( DeviceContext d2ddc, Node node, float 基点X, float 基点Y, string 難易度ラベル, double 難易度値, Brush 文字ブラシ ) { // 難易度ラベル d2ddc.DrawText( 難易度ラベル, this._見出し用TextFormat, new RectangleF( 基点X + 4f, 基点Y, 157f - 8f, 18f ), 文字ブラシ ); if( node is RandomSelectNode ) { // RandomNode 用説明文 d2ddc.DrawText( string.Format( Properties.Resources.TXT_ランダムに選択, 難易度ラベル ), this._説明文用TextFormat, new RectangleF( 基点X + 4f, 基点Y + 30f, 157f - 8f, 40f ), 文字ブラシ ); } else if( !string.IsNullOrEmpty( 難易度ラベル ) && 0.00 != 難易度値 ) { // 難易度値 var 難易度値文字列 = 難易度値.ToString( "0.00" ).PadLeft( 1 ); // 整数部は2桁を保証(1桁なら十の位は空白文字) this._数字画像.描画する( d2ddc, 基点X + 84f, 基点Y + 38f, 難易度値文字列[ 2.. ], new Size2F( 0.5f, 0.5f ) ); // 小数部 this._数字画像.描画する( d2ddc, 基点X + 20f, 基点Y + 20f, 難易度値文字列[ 0..2 ], new Size2F( 0.7f, 0.7f ) ); // 整数部('.'含む) } } // ローカル private readonly フォント画像D2D _数字画像; private readonly TextFormat _見出し用TextFormat; private readonly TextFormat _説明文用TextFormat; private Node? _現在表示しているノード = null; private readonly SolidColorBrush _黒透過ブラシ; private readonly SolidColorBrush _黒ブラシ; private readonly SolidColorBrush _白ブラシ; private readonly SolidColorBrush _ULTIMATE色ブラシ; private readonly SolidColorBrush _MASTER色ブラシ; private readonly SolidColorBrush _EXTREME色ブラシ; private readonly SolidColorBrush _ADVANCED色ブラシ; private readonly SolidColorBrush _BASIC色ブラシ; private readonly Brush[] _難易度パネル色; } } <|start_filename|>DTXMania2/ステージ/07演奏/スコア表示.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { /// <summary> /// スコアの描画を行う。 /// スコアの計算については、<see cref="成績"/> クラスにて実装する。 /// </summary> class スコア表示 : IDisposable { // 生成と終了 public スコア表示() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._スコア数字画像 = new 画像D2D( @"$(Images)\PlayStage\ScoreNumber.png" ); this._スコア数字の矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\ScoreNumber.yaml" ); // 表示用 this._現在表示中のスコア = 0; this._前回表示した数字 = " 0"; this._各桁のアニメ = new 各桁のアニメ[ 9 ]; for( int i = 0; i < this._各桁のアニメ.Length; i++ ) this._各桁のアニメ[ i ] = new 各桁のアニメ(); // スコア計算用 this._判定toヒット数 = new Dictionary<判定種別, int>(); foreach( 判定種別? judge in Enum.GetValues( typeof( 判定種別 ) ) ) { if( judge.HasValue ) this._判定toヒット数.Add( judge.Value, 0 ); } } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var anim in this._各桁のアニメ ) anim.Dispose(); this._スコア数字画像.Dispose(); } // 進行と描画 /// <param name="全体の中央位置"> /// パネル(dc)の左上を原点とする座標。 /// </param> public void 進行描画する( DeviceContext d2ddc, Animation am, Vector2 全体の中央位置, 成績 現在の成績 ) { // 進行。 if( this._現在表示中のスコア < 現在の成績.Score ) { int 増分 = 現在の成績.Score - this._現在表示中のスコア; int 追っかけ分 = Math.Max( (int)( 増分 * 0.75 ), 1 ); // VPS に依存するけどまあいい this._現在表示中のスコア = Math.Min( this._現在表示中のスコア + 追っかけ分, 現在の成績.Score ); } int スコア値 = Math.Clamp( this._現在表示中のスコア, min: 0, max: 999999999 ); // プロパティには制限はないが、表示は999999999(9桁)でカンスト。 string 数字 = スコア値.ToString().PadLeft( 9 ); // 右詰め9桁、余白は ' '。 var 全体のサイズ = new Vector2( 62f * 9f, 99f ); // 固定とする // 1桁ずつ描画。 var 文字間隔補正 = -10f; var 文字の位置 = new Vector2( -( 全体のサイズ.X / 2f ), 0f ); var preTrans = d2ddc.Transform; for( int i = 0; i < 数字.Length; i++ ) { // 前回の文字と違うなら、桁アニメーション開始。 if( 数字[ i ] != this._前回表示した数字[ i ] ) this._各桁のアニメ[ i ].跳ね開始( am, 0.0 ); var 転送元矩形 = this._スコア数字の矩形リスト[ 数字[ i ].ToString() ]!; d2ddc.Transform = Matrix3x2.Translation( 文字の位置.X, 文字の位置.Y + (float)( this._各桁のアニメ[ i ].Yオフセット?.Value ?? 0.0f ) ) * Matrix3x2.Translation( 全体の中央位置 ) * preTrans; // todo: フォント画像D2D に置き換える? d2ddc.DrawBitmap( this._スコア数字画像.Bitmap, 1f, BitmapInterpolationMode.Linear, 転送元矩形.Value ); 文字の位置.X += ( 転送元矩形.Value.Width + 文字間隔補正 ) * 1f;// 画像矩形から表示矩形への拡大率.X; } d2ddc.Transform = preTrans; // 更新。 this._前回表示した数字 = 数字; } // ローカル /// <summary> /// <see cref="進行描画する(DeviceContext1, Vector2)"/> で更新される。 /// </summary> private int _現在表示中のスコア = 0; private readonly 画像D2D _スコア数字画像; private readonly 矩形リスト _スコア数字の矩形リスト; private readonly Dictionary<判定種別, int> _判定toヒット数; private string _前回表示した数字 = " 0"; // 桁ごとのアニメーション private class 各桁のアニメ : IDisposable { public Storyboard ストーリーボード = null!; public Variable Yオフセット = null!; public 各桁のアニメ() { } public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.Yオフセット?.Dispose(); } public void 跳ね開始( Animation am, double 遅延sec ) { this.Dispose(); this.ストーリーボード = new Storyboard( am.Manager ); this.Yオフセット = new Variable( am.Manager, initialValue: 0.0 ); var Yオフセットの遷移 = new List<Transition>() { am.TrasitionLibrary.Constant( 遅延sec ), am.TrasitionLibrary.Linear( 0.05, finalValue: -10.0 ), // 上へ移動 am.TrasitionLibrary.Linear( 0.05, finalValue: 0.0 ), // 下へ戻る }; for( int i = 0; i < Yオフセットの遷移.Count; i++ ) { this.ストーリーボード.AddTransition( this.Yオフセット, Yオフセットの遷移[ i ] ); Yオフセットの遷移[ i ].Dispose(); } this.ストーリーボード.Schedule( am.Timer.Time ); } }; private readonly 各桁のアニメ[] _各桁のアニメ; } } <|start_filename|>DTXMania2/ステージ/07演奏/レーンフレーム.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { /// <summary> /// チップの背景であり、レーン全体を示すフレーム画像。 /// </summary> class レーンフレーム : IDisposable { // static /// <summary> /// 画面全体に対する、レーンフレームの表示位置と範囲。 /// </summary> public static RectangleF 領域 => new RectangleF( 445f, 0f, 778f, 1080f ); public static Dictionary<表示レーン種別, float> レーン中央位置X = null!; public static Dictionary<表示レーン種別, Color4> レーン色 = null!; // 生成と終了 static レーンフレーム() { レーン中央位置X = new Dictionary<表示レーン種別, float>() { { 表示レーン種別.Unknown, 0f }, { 表示レーン種別.LeftCymbal, 489f }, { 表示レーン種別.HiHat, 570f }, { 表示レーン種別.Foot, 570f }, { 表示レーン種別.Snare, 699f }, { 表示レーン種別.Tom1, 812f }, { 表示レーン種別.Bass, 896f }, { 表示レーン種別.Tom2, 976f }, { 表示レーン種別.Tom3, 1088f }, { 表示レーン種別.RightCymbal, 1193f }, }; レーン色 = new Dictionary<表示レーン種別, Color4>() { { 表示レーン種別.Unknown, new Color4( 0x00000000 ) }, // ABGR { 表示レーン種別.LeftCymbal, new Color4( 0xff5a5a5a ) }, { 表示レーン種別.HiHat, new Color4( 0xff7d5235 ) }, { 表示レーン種別.Foot, new Color4( 0xff492d1f ) }, { 表示レーン種別.Snare, new Color4( 0xff406283 ) }, { 表示レーン種別.Tom1, new Color4( 0xff2e5730 ) }, { 表示レーン種別.Bass, new Color4( 0xff424141 ) }, { 表示レーン種別.Tom2, new Color4( 0xff323267 ) }, { 表示レーン種別.Tom3, new Color4( 0xff70565c ) }, { 表示レーン種別.RightCymbal, new Color4( 0xff606060 ) }, }; } public レーンフレーム() { using var _ = new LogBlock( Log.現在のメソッド名 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, int BGAの透明度, bool レーンラインを描画する = true ) { // レーンエリアを描画する。 { var color = Color4.Black; color.Alpha *= ( 100 - BGAの透明度 ) / 100.0f; // BGAの透明度0→100 のとき Alpha×1→×0 using( var laneBrush = new SolidColorBrush( d2ddc, color ) ) d2ddc.FillRectangle( レーンフレーム.領域, laneBrush ); } // レーンラインを描画する。 if( レーンラインを描画する ) { foreach( 表示レーン種別? displayLaneType in Enum.GetValues( typeof( 表示レーン種別 ) ) ) { if( !displayLaneType.HasValue || displayLaneType.Value == 表示レーン種別.Unknown ) continue; var レーンライン色 = レーン色[ displayLaneType.Value ]; レーンライン色.Alpha *= ( 100 - BGAの透明度 ) / 100.0f; // BGAの透明度0→100 のとき Alpha×1→×0 using( var laneLineBrush = new SolidColorBrush( d2ddc, レーンライン色 ) ) { d2ddc.FillRectangle( new RectangleF( レーン中央位置X[ displayLaneType.Value ] - 1, 0f, 3f, 領域.Height ), laneLineBrush ); } } } } } } <|start_filename|>DTXMania2/イメージ/画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct3D11; using FDK; namespace DTXMania2 { /// <summary> /// D3Dテクスチャを使った画像表示。 /// </summary> class 画像 : FDK.画像 { /// <summary> /// 指定した画像ファイルから画像を作成する。 /// </summary> public 画像( VariablePath 画像ファイルパス, BindFlags bindFlags = BindFlags.ShaderResource ) : base( Global.GraphicResources.D3D11Device1, Folder.カルチャを考慮した絶対パスを返す( 画像ファイルパス.変数なしパス ), bindFlags ) { } /// <summary> /// 指定したサイズの、空の画像を作成する。 /// </summary> public 画像( Size2F サイズ, BindFlags bindFlags = BindFlags.ShaderResource ) : base( Global.GraphicResources.D3D11Device1, サイズ, bindFlags ) { } /// <summary> /// 画像を描画する。 /// </summary> public void 描画する( float 左位置, float 上位置, float 不透明度0to1 = 1.0f, float X方向拡大率 = 1.0f, float Y方向拡大率 = 1.0f, RectangleF? 転送元矩形 = null ) { base.描画する( Global.GraphicResources.既定のD3D11DeviceContext, Global.GraphicResources.設計画面サイズ, Global.GraphicResources.既定のD3D11ViewPort, Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView, Global.GraphicResources.既定のD3D11DepthStencilState, 左位置, 上位置, 不透明度0to1, X方向拡大率, Y方向拡大率, 転送元矩形 ); } /// <summary> /// 画像を描画する。 /// </summary> /// <param name="ワールド行列変換">画像は原寸(<see cref="サイズ"/>)にスケーリングされており、その後にこのワールド行列が適用される。</param> /// <param name="転送元矩形">テクスチャ座標(値域0~1)で指定する。</param> public void 描画する( Matrix ワールド行列変換, float 不透明度0to1 = 1f, RectangleF? 転送元矩形 = null ) { base.描画する( Global.GraphicResources.既定のD3D11DeviceContext, Global.GraphicResources.設計画面サイズ, Global.GraphicResources.既定のD3D11ViewPort, Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView, Global.GraphicResources.既定のD3D11DepthStencilState, ワールド行列変換, 不透明度0to1, 転送元矩形 ); } } } <|start_filename|>FDK/CacheStore.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace FDK { /// <summary> /// ファイルから生成されるデータをキャッシュし、貸与する。 /// </summary> /// <remarks> /// 世代番号について: /// ・このクラスでは、「世代」という時間を管理する。 ///  世代は、0以上の整数であり、上限はない。 /// ・利用者は、任意のタイミングで、このクラスの世代番号を1つ進める(加算する)ことができる。 /// これ以外に、世代を変更する方法はない。 /// /// 生成データについて: /// ・ファイルから <see cref="ファイルからデータを生成する"/> を通じて生成したものが、生成データである。 /// ・生成データには、作成時点における世代番号が付与され、貸し出しのたびに現行化される。 /// ・利用者は、渡された生成データが IDisposable であったとしても、それを破棄してはならない。(レンタル品・共用物品なので) /// /// 古いデータの削除について: /// ・このクラスの世代番号が加算されたときには、指定された世代数(今は1)だけ残して、 ///  それより古い世代のインスタンスがすべて破棄(Dispose)される。 ///  そのため、世代番号を加算する前には、利用者がもつすべてのインスタンスへの参照を断っておくことが望ましい。 ///   /// 利用イメージ: /// (0) このクラスのインスタンスの生成後、外部依存アクションを接続すること。 /// (1) 利用者は、データを含んだファイルAを用意する。 /// (2) このクラスは、ファイルAからデータSを生成し、利用者に貸与する。 /// このとき、データSには、その時点での世代番号が付与される。 /// (3) 利用者は、データSを活用する。 /// (4) 利用者は、利用の終わったデータSへの参照を解放する。(これが返却にあたる。Disposeはしないこと!) /// (5) 利用者は、このクラスの世代を1つ進める。 /// (6) このクラスは、生成データのうち、世代が2つ以上離れているデータを破棄(Dispose)する。 /// (7) 利用者は、再び、データを含んだファイルAを用意する。 /// (8) このクラスは、ファイルAから生成済みのデータSを持っているので、それを利用者に貸与する。 /// このとき、データSに割り当てられている世代番号は、その時点での世代番号に更新される。 /// </remarks> public class CacheStore<T> : IDisposable where T : class { /// <summary> /// 指定したファイルからデータを生成して返す、外部依存アクション。 /// </summary> /// <remarks> /// このメソッドは内部利用用。 /// </remarks> public Func<VariablePath, T?>? ファイルからデータを生成する = null; /// <summary> /// 現在の世代番号。0 以上の整数、上限なし。 /// </summary> public int 現世代 { get; protected set; } = 0; public CacheStore() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._キャッシュデータリスト = new Dictionary<string, キャッシュ情報<T>>(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var kvp in this._キャッシュデータリスト ) ( kvp.Value as IDisposable )?.Dispose(); } /// <summary> /// 世代を1つ加算する。 /// </summary> public void 世代を進める() { using var _ = new LogBlock( Log.現在のメソッド名 ); // 今回の世代では貸与されなかった(=最終貸与世代が現時点の世代ではない)キャッシュデータをすべて破棄する。 var 削除対象リスト = this._キャッシュデータリスト .Where( ( kvp ) => kvp.Value.最終貸与世代 < this.現世代 ) .Select( ( kvp ) => kvp.Key ) .ToArray(); foreach( var key in 削除対象リスト ) { this._キャッシュデータリスト[ key ].Dispose(); this._キャッシュデータリスト.Remove( key ); } Log.Info( $"{this._キャッシュデータリスト.Count} 個のサウンドのうち、{削除対象リスト.Length} 個を削除しました。" ); // 世代番号を1つ加算する。 this.現世代++; } /// <summary> /// 指定されたファイルに対応するデータを(未生成なら)生成し、返す。 /// 生成に失敗したら null。 /// </summary> public T? 作成する( VariablePath ファイルパス ) { try { if( !File.Exists( ファイルパス.変数なしパス ) ) { Log.ERROR( $"ファイルが存在しません。[{ファイルパス.変数付きパス}]" ); return null; // 失敗 } var fileInfo = new FileInfo( ファイルパス.変数なしパス ); if( this._キャッシュデータリスト.TryGetValue( ファイルパス.変数なしパス, out var キャッシュ情報 ) ) // キャッシュにある { if( キャッシュ情報.ファイルの最終更新日時 == fileInfo.LastWriteTime ) // ファイルは更新されていない { #region " (A) データがキャッシュに存在していて、ファイルも更新されていない場合 → それを貸与する " //---------------- キャッシュ情報.最終貸与世代 = this.現世代; // 更新 return キャッシュ情報.生成データ; //---------------- #endregion } else { #region " (B) データがキャッシュに存在しているが、ファイルが更新されている場合 → 再作成して貸与する " //---------------- ( キャッシュ情報.生成データ as IDisposable )?.Dispose(); キャッシュ情報.生成データ = this.ファイルからデータを生成する?.Invoke( ファイルパス ); if( キャッシュ情報.生成データ is null ) { this._キャッシュデータリスト.Remove( ファイルパス.変数なしパス ); return null; // 失敗 } キャッシュ情報.ファイルの最終更新日時 = fileInfo.LastWriteTime; キャッシュ情報.最終貸与世代 = 現世代; return キャッシュ情報.生成データ; //---------------- #endregion } } else { #region " (C) データがキャッシュに存在しない場合 → 新規作成して貸与する " //---------------- var 生成データ = this.ファイルからデータを生成する?.Invoke( ファイルパス ); if( 生成データ is null ) return null; // 失敗 this._キャッシュデータリスト.Add( // キャッシュに追加 ファイルパス.変数なしパス, new キャッシュ情報<T>() { ファイルパス = ファイルパス, ファイルの最終更新日時 = fileInfo.LastWriteTime, 生成データ = 生成データ, 最終貸与世代 = this.現世代, } ); return 生成データ; //---------------- #endregion } } catch { return null; // 例外発生 } } /// <summary> /// キャッシュされる生成データとその関連情報。 /// </summary> /// <typeparam name="TS">データ型</typeparam> internal protected class キャッシュ情報<TS> : IDisposable where TS : class { /// <summary> /// ファイルから生成されたデータ。 /// </summary> public TS? 生成データ { get; set; } = null; /// <summary> /// <see cref="生成データ"/> のもとになったファイルのパス。 /// </summary> public VariablePath ファイルパス { get; set; } = ""; /// <summary> /// データがファイルから生成されたときの、そのファイルの最終更新日時。 /// </summary> public DateTime ファイルの最終更新日時 { get; set; } /// <summary> /// データが生成または最後に貸与されたときの世代番号。 /// 小さいほど古い。 /// </summary> public int 最終貸与世代 { get; set; } /// <summary> /// 生成データを破棄する。 /// </summary> public virtual void Dispose() { ( this.生成データ as IDisposable )?.Dispose(); this.生成データ = null; } } /// <summary> /// キャッシュデータのリスト。 /// [key: 生成元ファイルパス] /// </summary> internal protected Dictionary<string, キャッシュ情報<T>> _キャッシュデータリスト; } } <|start_filename|>SSTFEditor/編集レーン種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace SSTFEditor { enum 編集レーン種別 { BPM, 左シンバル, ハイハット, スネア, ハイタム, バス, ロータム, フロアタム, 右シンバル, BGV, BGM, Unknown, } } <|start_filename|>DTXMania2/保存データ/ScorePropertiesDB/ScorePropertiesDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2 { class ScorePropertiesDBRecord { // プロパティ public static int VERSION = 2; /// <summary> /// 譜面ファイルの絶対パス。主キー。 /// </summary> public string ScorePath { get; set; } /// <summary> /// ユーザID。主キー。 /// </summary> public string UserId { get; set; } /// <summary> /// 評価値。0~5。 /// </summary> public int Rating { get; set; } // 生成と終了 public ScorePropertiesDBRecord() { this.ScorePath = "unknownscore.sstf"; this.UserId = "Anonymous"; this.Rating = 0; } public ScorePropertiesDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "ScorePath": this.ScorePath = record.GetString( i ); break; case "UserId": this.UserId = record.GetString( i ); break; case "Rating": this.Rating = record.GetInt32( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public void InsertTo( SQLiteDB db, string table = "ScoreProperties" ) { using var cmd = new SqliteCommand( $"REPLACE INTO {table} VALUES(" + "@ScorePath," + "@UserId," + "@Rating" + ")", db.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@ScorePath", this.ScorePath ), new SqliteParameter( "@UserId", this.UserId ), new SqliteParameter( "@Rating", this.Rating ), } ); cmd.ExecuteNonQuery(); } /// <summary> /// テーブルがなければ作成するSQLを返す。 /// </summary> public static string GetCreateTableSQL( string table = "ScoreProperties" ) => $"CREATE TABLE IF NOT EXISTS {table}" + "( ScorePath NVARCHAR NOT NULL" + ", UserId NVARCHAR NOT NULL" + ", Rating INTEGER NOT NULL" + ", PRIMARY KEY(`ScorePath`, `UserId`)" + ")"; } } <|start_filename|>DTXMania2/ステージ/07演奏/コンボ表示.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class コンボ表示 : IDisposable { // 生成と終了 public コンボ表示() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._コンボ文字画像 = new 画像D2D( @"$(Images)\PlayStage\ComboNumber.png" ); this._コンボ文字の矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\ComboNumber.yaml" ); this._前回表示した値 = 0; this._前回表示した数字 = " "; this._各桁のアニメ = new 各桁のアニメ[ 4 ]; for( int i = 0; i < this._各桁のアニメ.Length; i++ ) this._各桁のアニメ[ i ] = new 各桁のアニメ(); this._百ごとのアニメ = new 百ごとのアニメ(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._百ごとのアニメ.Dispose(); foreach( var anim in this._各桁のアニメ ) anim.Dispose(); this._コンボ文字画像.Dispose(); } // 進行と描画 /// <param name="全体の中央位置"> /// パネル(dc)の左上を原点とする座標。 /// </param> public void 進行描画する( DeviceContext d2ddc, Vector2 全体の中央位置, 成績 現在の成績 ) { int Combo値 = Math.Clamp( 現在の成績.Combo, min: 0, max: 9999 ); // 表示は9999でカンスト。 if( Combo値 < 10 ) return; // 10未満は表示しない。 if( ( this._前回表示した値 % 100 ) > ( Combo値 % 100 ) ) { // 100を超えるたびアニメ開始。 this._百ごとのアニメ.開始( Global.Animation ); } var 数字 = Combo値.ToString().PadLeft( 4 ).Replace( ' ', 'o' ); // 右詰め4桁、余白は 'o'。 var 画像矩形から表示矩形への拡大率 = new Vector2( 264f / ( 142f * 4f ), 140f / 188f ); var 文字間隔補正 = -10f; var 全体の拡大率 = new Vector2( (float)( this._百ごとのアニメ.拡大率?.Value ?? 1.0 ) ); // 全体のサイズを算出。 var 全体のサイズ = new Vector2( 0f, 0f ); for( int i = 0; i < 数字.Length; i++ ) { var 矩形 = this._コンボ文字の矩形リスト[ 数字[ i ].ToString() ]!; 全体のサイズ.X += 矩形.Value.Width + 文字間隔補正; // 合計 全体のサイズ.Y = Math.Max( 全体のサイズ.Y, 矩形.Value.Height ); // 最大値 } 全体のサイズ *= 画像矩形から表示矩形への拡大率; // 全体の位置を修正。 全体の中央位置.Y -= 全体のサイズ.Y / 2f; var 振動幅 = (float)( this._百ごとのアニメ.振動幅?.Value ?? 0.0f ); if( 0.0f < 振動幅 ) { 全体の中央位置.X += Global.App.乱数.NextFloat( -振動幅, +振動幅 ); 全体の中央位置.Y += Global.App.乱数.NextFloat( -振動幅, +振動幅 ); } // 1桁ずつ描画。 var preTrans = d2ddc.Transform; #region " 数字を描画。" //---------------- { var 文字の位置 = new Vector2( -( 全体のサイズ.X / 2f ), 0f ); for( int i = 0; i < 数字.Length; i++ ) { if( 数字[ i ] != this._前回表示した数字[ i ] ) { // 桁アニメーション開始 this._各桁のアニメ[ i ].落下開始( Global.Animation ); // 1の位以外は、自分より上位の桁を順番に跳ねさせる。 if( 3 > i ) { for( int p = ( i - 1 ); p >= 0; p-- ) this._各桁のアニメ[ p ].跳ね開始( Global.Animation, 0.05 * ( ( i - 1 ) - p + 1 ) ); } } var 転送元矩形 = ( this._コンボ文字の矩形リスト[ 数字[ i ].ToString() ] )!; d2ddc.Transform = Matrix3x2.Scaling( 画像矩形から表示矩形への拡大率 ) * Matrix3x2.Translation( 文字の位置.X, 文字の位置.Y + (float)( this._各桁のアニメ[ i ].Yオフセット?.Value ?? 0.0f ) ) * Matrix3x2.Scaling( 全体の拡大率.X, 全体の拡大率.Y, center: new Vector2( 0f, 全体のサイズ.Y / 2f ) ) * Matrix3x2.Translation( 全体の中央位置 ) * preTrans; d2ddc.DrawBitmap( this._コンボ文字画像.Bitmap, (float)( this._各桁のアニメ[ i ].不透明度?.Value ?? 1.0f ), BitmapInterpolationMode.Linear, 転送元矩形.Value ); 文字の位置.X += ( 転送元矩形.Value.Width + 文字間隔補正 ) * 画像矩形から表示矩形への拡大率.X; } d2ddc.Transform = preTrans; } //---------------- #endregion #region " Combo を描画。" //---------------- { var 転送元矩形 = this._コンボ文字の矩形リスト[ "Combo" ]!; var 文字の位置 = new Vector2( 0f, 130f ); d2ddc.Transform = Matrix3x2.Scaling( 画像矩形から表示矩形への拡大率 ) * Matrix3x2.Translation( 文字の位置 ) * Matrix3x2.Scaling( 全体の拡大率 ) * Matrix3x2.Translation( 全体の中央位置 ) * preTrans; d2ddc.DrawBitmap( this._コンボ文字画像.Bitmap, 1.0f, BitmapInterpolationMode.Linear, 転送元矩形.Value ); d2ddc.Transform = preTrans; } //---------------- #endregion // 保存 this._前回表示した値 = 現在の成績.Combo; this._前回表示した数字 = 数字; } // ローカル private int _前回表示した値 = 0; private string _前回表示した数字 = " "; private readonly 画像D2D _コンボ文字画像; private readonly 矩形リスト _コンボ文字の矩形リスト; // 桁ごとのアニメーション private class 各桁のアニメ : IDisposable { public Storyboard ストーリーボード = null!; public Variable Yオフセット = null!; public Variable 不透明度 = null!; public 各桁のアニメ() { } public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.Yオフセット?.Dispose(); this.不透明度?.Dispose(); } public void 落下開始( Animation am ) { this.Dispose(); this.ストーリーボード = new Storyboard( am.Manager ); this.Yオフセット = new Variable( am.Manager, initialValue: -70.0 ); this.不透明度 = new Variable( am.Manager, initialValue: 1.0 ); var Yオフセットの遷移 = new List<Transition>() { am.TrasitionLibrary.Linear( 0.05, finalValue: 0.0 ), // 落下して am.TrasitionLibrary.Reversal( 0.03 ), // 短時間でベクトル反転(下から上へ)して am.TrasitionLibrary.Reversal( 0.05 ), // 上にはねて戻る }; for( int i = 0; i < Yオフセットの遷移.Count; i++ ) { this.ストーリーボード.AddTransition( this.Yオフセット, Yオフセットの遷移[ i ] ); Yオフセットの遷移[ i ].Dispose(); } this.ストーリーボード.Schedule( am.Timer.Time ); } public void 跳ね開始( Animation am, double 遅延sec ) { this.Dispose(); this.ストーリーボード = new Storyboard( am.Manager ); this.Yオフセット = new Variable( am.Manager, initialValue: 0.0 ); this.不透明度 = new Variable( am.Manager, initialValue: 1.0 ); var Yオフセットの遷移 = new List<Transition>() { am.TrasitionLibrary.Constant( 遅延sec ), am.TrasitionLibrary.Linear( 0.05, finalValue: -20.0 ), // 上へ移動して am.TrasitionLibrary.Linear( 0.05, finalValue: 0.0 ), // 下へ戻る }; for( int i = 0; i < Yオフセットの遷移.Count; i++ ) { this.ストーリーボード.AddTransition( this.Yオフセット, Yオフセットの遷移[ i ] ); Yオフセットの遷移[ i ].Dispose(); } this.ストーリーボード.Schedule( am.Timer.Time ); } }; private readonly 各桁のアニメ[] _各桁のアニメ; // 百ごとのアニメーション private class 百ごとのアニメ : IDisposable { public Storyboard ストーリーボード = null!; public Variable 拡大率 = null!; public Variable 振動幅 = null!; public 百ごとのアニメ() { } public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.拡大率?.Dispose(); this.振動幅?.Dispose(); } public void 開始( Animation am ) { this.Dispose(); this.ストーリーボード = new Storyboard( am.Manager ); this.拡大率 = new Variable( am.Manager, initialValue: 1.0 ); this.振動幅 = new Variable( am.Manager, initialValue: 0.0 ); var 拡大率の遷移 = new List<Transition>() { am.TrasitionLibrary.Linear( 0.08, finalValue: 1.25 ), am.TrasitionLibrary.Constant( 0.3 ), am.TrasitionLibrary.Linear( 0.08, finalValue: 1.0 ), }; for( int i = 0; i < 拡大率の遷移.Count; i++ ) { this.ストーリーボード.AddTransition( this.拡大率, 拡大率の遷移[ i ] ); 拡大率の遷移[ i ].Dispose(); } var 振動幅の遷移 = new List<Transition>() { am.TrasitionLibrary.Linear( 0.08, finalValue: 6.0 ), am.TrasitionLibrary.Constant( 0.3 ), am.TrasitionLibrary.Linear( 0.08, finalValue: 0.0 ), }; for( int i = 0; i < 振動幅の遷移.Count; i++ ) { this.ストーリーボード.AddTransition( this.振動幅, 振動幅の遷移[ i ] ); 振動幅の遷移[ i ].Dispose(); } this.ストーリーボード.Schedule( am.Timer.Time ); } }; private readonly 百ごとのアニメ _百ごとのアニメ; } } <|start_filename|>DTXMania2/保存データ/ScoreDB/old/v003_SongDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.old.SongDBRecord { class v003_SongDBRecord { public const int VERSION = 3; /// <summary> /// 曲譜面ファイルのハッシュ値。 /// 正確には一意じゃないけど、主キーとして扱う。 /// </summary> public string HashId { get; set; } /// <summary> /// 曲のタイトル。 /// </summary> public string Title { get; set; } /// <summary> /// 曲譜面ファイルへの絶対パス。 /// これも一意とする。(テーブル生成SQLで UNIQUE を付与している。) /// </summary> public string Path { get; set; } /// <summary> /// 曲譜面ファイルの最終更新時刻の文字列表記。 /// 文字列の書式は、System.DateTime.ToString("G") と同じ。(例: "08/17/2000 16:32:32") /// カルチャはシステム既定のものとする。 /// </summary> public string LastWriteTime { get; set; } /// <summary> /// 曲の難易度。0.00~9.99。 /// </summary> public double Level { get; set; } /// <summary> /// 最小BPM。null なら未取得。 /// </summary> public double? MinBPM { get; set; } /// <summary> /// 最大BPM。null なら未取得。 /// </summary> public double? MaxBPM { get; set; } /// <summary> /// 左シンバルの総ノーツ数。 /// </summary> public int TotalNotes_LeftCymbal { get; set; } /// <summary> /// ハイハットの総ノーツ数。 /// </summary> public int TotalNotes_HiHat { get; set; } /// <summary> /// 左ペダルまたは左バスの総ノーツ数。 /// </summary> public int TotalNotes_LeftPedal { get; set; } /// <summary> /// スネアの総ノーツ数。 /// </summary> public int TotalNotes_Snare { get; set; } /// <summary> /// バスの総ノーツ数。 /// </summary> public int TotalNotes_Bass { get; set; } /// <summary> /// ハイタムの総ノーツ数。 /// </summary> public int TotalNotes_HighTom { get; set; } /// <summary> /// ロータムの総ノーツ数。 /// </summary> public int TotalNotes_LowTom { get; set; } /// <summary> /// フロアタムの総ノーツ数。 /// </summary> public int TotalNotes_FloorTom { get; set; } /// <summary> /// 右シンバルの総ノーツ数。 /// </summary> public int TotalNotes_RightCymbal { get; set; } /// <summary> /// 曲のプレビュー画像。 /// </summary> public string PreImage { get; set; } /// <summary> /// 曲のアーティスト名。 /// </summary> public string Artist { get; set; } // 生成と終了 public v003_SongDBRecord() { this.HashId = ""; this.Title = "(no title)"; this.Path = ""; this.LastWriteTime = DateTime.Now.ToString( "G" ); this.Level = 5.00; this.MinBPM = null; this.MaxBPM = null; this.TotalNotes_LeftCymbal = 0; this.TotalNotes_HiHat = 0; this.TotalNotes_LeftPedal = 0; this.TotalNotes_Snare = 0; this.TotalNotes_Bass = 0; this.TotalNotes_HighTom = 0; this.TotalNotes_LowTom = 0; this.TotalNotes_FloorTom = 0; this.TotalNotes_RightCymbal = 0; this.PreImage = ""; this.Artist = ""; } } } <|start_filename|>DTXMania2/保存データ/ScoreDB/ScoreDB.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using FDK; namespace DTXMania2 { partial class ScoreDB : SQLiteDB { public static readonly VariablePath ScoreDBPath = new VariablePath( @"$(AppData)\ScoreDB.sqlite3" ); public ScoreDB( VariablePath? path = null ) : base() { path ??= ScoreDBPath; try { this.Open( path ); } catch( Exception e ) { Log.WARNING( $"エラーが発生したので、新しく作り直します。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); #region " DBファイルを削除 " //---------------- try { File.Delete( path.変数なしパス ); // ファイルがない場合には例外は出ない } catch( Exception e2 ) { var msg = $"曲データベースファイルの削除に失敗しました。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]"; Log.ERROR( msg ); throw new Exception( msg, e2 ); // どうしようもないので例外発出 } //---------------- #endregion this.Open( path ); } } } } <|start_filename|>DTXMania2/ステージ/08結果/難易度.下線.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Animation; namespace DTXMania2.結果 { partial class 難易度 { class 下線 : IDisposable { // プロパティ public bool アニメ完了 => ( null != this._ストーリーボード && this._ストーリーボード.Status == StoryboardStatus.Ready ); // 生成と終了 public 下線() { } public virtual void Dispose() { this._長さdpx?.Dispose(); this._ストーリーボード?.Dispose(); } // 進行と描画 public void 開始する() { this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( Global.Animation.Manager ); #region " 長さdpx のアニメ構築 " //---------------- // 初期値 0.0 this._長さdpx?.Dispose(); this._長さdpx = new Variable( Global.Animation.Manager, initialValue: 0.0 ); // 待つ using( var 遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 難易度._最初の待機時間sec ) ) this._ストーリーボード.AddTransition( this._長さdpx, 遷移 ); // 全長dpx へ using( var 遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: 難易度._アニメ時間sec / 3, finalValue: _全長dpx, accelerationRatio: 0.8, decelerationRatio: 0.2 ) ) this._ストーリーボード.AddTransition( this._長さdpx, 遷移 ); //---------------- #endregion // アニメーション開始 this._ストーリーボード.Schedule( Global.Animation.Timer.Time ); } public void アニメを完了する() { this._ストーリーボード?.Finish( 0.1 ); } public void 進行描画する( DeviceContext d2ddc, float x, float y ) { if( this._長さdpx is null ) return; float 長さdpx = (float)this._長さdpx.Value; using( var brush = new SolidColorBrush( d2ddc, Color4.White ) ) d2ddc.FillRectangle( new RectangleF( x + ( _全長dpx - 長さdpx ) / 2f, y, 長さdpx, 3f ), brush ); } // ローカル private const float _全長dpx = 513f; private Storyboard? _ストーリーボード = null; private Variable? _長さdpx = null; } } } <|start_filename|>FDK/Animation.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Animation; namespace FDK { /// <summary> /// Windows Animation API の wrapper。 /// </summary> public class Animation : IDisposable { // プロパティ public Manager Manager { get; protected set; } public Timer Timer { get; protected set; } public TransitionLibrary TrasitionLibrary { get; protected set; } // 生成と終了 public Animation() { this.Manager = new Manager(); this.Timer = new Timer(); this.TrasitionLibrary = new TransitionLibrary(); this._スレッドID = System.Threading.Thread.CurrentThread.ManagedThreadId; } public virtual void Dispose() { this.TrasitionLibrary.Dispose(); this.Timer.Dispose(); this.Manager.Dispose(); } // 進行と描画 public void 進行する() { Debug.Assert( System.Threading.Thread.CurrentThread.ManagedThreadId == this._スレッドID, "生成スレッドではありません。生成スレッドと同じスレッドで呼び出すこと!" ); this.Manager.Update( this.Timer.Time ); } // ローカル private int _スレッドID; } } <|start_filename|>DTXMania2/ステージ/07演奏/達成率表示.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class 達成率表示 : IDisposable { // 生成と終了 public 達成率表示() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_Large.png", @"$(Images)\ParameterFont_Large.yaml", 文字幅補正dpx: 0f ); this._達成率ロゴ画像 = new 画像D2D( @"$(Images)\CompletionRateIcon.png" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._達成率ロゴ画像.Dispose(); this._数字画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, float 達成率0to100 ) { var 描画領域 = new RectangleF( 200f, 650f, 165f, 80f ); string 達成率文字列 = MathUtil.NearEqual( 100f, 達成率0to100 ) ? "100.00%" : ' ' + ( 達成率0to100.ToString( "0.00" ) + '%' ).PadLeft( 6 ).Replace( ' ', 'o' ); // 右詰め、余白は'o'。例:"99.00%", "o8.12%", "o0.00%" // 達成率ロゴを描画する var 変換行列2D = Matrix3x2.Scaling( 0.4f, 0.5f ) * Matrix3x2.Translation( 描画領域.X - 76f, 描画領域.Y - 40f ); this._達成率ロゴ画像.描画する( d2ddc, 変換行列2D ); // 小数部を描画する('%'含む) this._数字画像.描画する( d2ddc, 描画領域.X + 86f, 描画領域.Y + ( 描画領域.Height * 0.2f ), 達成率文字列[ 4.. ], new Size2F( 0.5f, 0.8f ) ); // 整数部を描画する('.'含む) this._数字画像.描画する( d2ddc, 描画領域.X, 描画領域.Y, 達成率文字列[ 0..4 ], new Size2F( 0.5f, 1.0f ) ); } // ローカル private readonly フォント画像D2D _数字画像; private readonly 画像D2D _達成率ロゴ画像; } } <|start_filename|>FDK/イメージ/フォント画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct3D11; using SharpDX.Mathematics.Interop; namespace FDK { /// <summary> /// 文字盤(複数の文字を描いた1枚の画像)と、文字盤内での個々の文字の位置を表した矩形リストを使って、文字列を描画する。 /// 描画は Direct3D のテクスチャで行う。 /// </summary> public class フォント画像 : IImage, IDisposable { // プロパティ /// <summary> /// 文字と文字の間の(横方向の)間隔。拡大率の影響は受けない。負数もOK。 /// </summary> public float 文字幅補正dpx { get; set; } = 0f; /// <summary> /// 透明: 0 ~ 1 :不透明 /// </summary> public float 不透明度 { get; set; } = 1f; // 生成と終了 /// <summary> /// コンストラクタ。 /// 指定された画像ファイルと矩形リストyamlファイルを使って、フォント画像を生成する。 /// </summary> /// <param name="文字幅補正dpx">文字と文字の間の(横方向の)間隔。拡大率の影響は受けない。負数もOK。</param> /// <param name="不透明度">透明: 0 ~ 1 :不透明</param> public フォント画像( Device1 d3dDevice1, VariablePath 文字盤の画像ファイルパス, VariablePath 文字盤の矩形リストファイルパス, float 文字幅補正dpx = 0f, float 不透明度 = 1f ) { this._文字盤 = new 画像( d3dDevice1, 文字盤の画像ファイルパス ); this._矩形リスト = new 矩形リスト( 文字盤の矩形リストファイルパス ); this.文字幅補正dpx = 文字幅補正dpx; this.不透明度 = 不透明度; } public virtual void Dispose() { this._文字盤.Dispose(); } // 進行と描画 /// <summary> /// 文字列を描画する。 /// </summary> /// <param name="基点のX位置">左揃えなら左端位置、右揃えなら右端位置のX座標。</param> /// <param name="拡大率">文字列の拡大率。null なら等倍。</param> /// <param name="右揃え">trueなら右揃え、falseなら左揃え。</param> public void 描画する( DeviceContext d3dDeviceContext, Size2F 設計画面サイズdpx, RawViewportF[] viewports, DepthStencilView depthStencilView, RenderTargetView renderTargetView, DepthStencilState depthStencilState, float 基点のX位置, float 上位置, string 表示文字列, Size2F? 拡大率 = null, bool 右揃え = false ) { if( string.IsNullOrEmpty( 表示文字列 ) ) return; 拡大率 ??= new Size2F( 1, 1 ); if( !this._有効文字の矩形と文字数を抽出し文字列全体のサイズを返す( 表示文字列, 拡大率.Value, out Size2F 文字列全体のサイズ, out int 有効文字数, out var 有効文字矩形リスト ) ) return; // 有効文字がない if( 右揃え ) 基点のX位置 -= 文字列全体のサイズ.Width; for( int i = 0; i < 有効文字数; i++ ) { var 文字矩形 = 有効文字矩形リスト.ElementAt( i ); if( !文字矩形.HasValue ) continue; this._文字盤.描画する( d3dDeviceContext, 設計画面サイズdpx, viewports, depthStencilView, renderTargetView, depthStencilState, 基点のX位置, 上位置 + ( 文字列全体のサイズ.Height - 文字矩形.Value.Height * 拡大率.Value.Height ), this.不透明度, 拡大率.Value.Width, 拡大率.Value.Height, 文字矩形 ); 基点のX位置 += ( 文字矩形!.Value.Width * 拡大率.Value.Width + this.文字幅補正dpx ); } } // ローカル private readonly 画像 _文字盤; private readonly 矩形リスト _矩形リスト; private bool _有効文字の矩形と文字数を抽出し文字列全体のサイズを返す( string 表示文字列, Size2F 拡大率, out Size2F 文字列全体のサイズ, out int 有効文字数, out IEnumerable<RectangleF?> 有効文字矩形リスト ) { 文字列全体のサイズ = Size2F.Empty; 有効文字矩形リスト = from 文字 in 表示文字列 where ( null != this._矩形リスト[ 文字.ToString() ] ) select this._矩形リスト[ 文字.ToString() ]; 有効文字数 = 有効文字矩形リスト.Count(); if( 0 == 有効文字数 ) return false; foreach( var 文字矩形 in 有効文字矩形リスト ) { 文字列全体のサイズ.Width += 文字矩形!.Value.Width * 拡大率.Width + this.文字幅補正dpx; if( 文字列全体のサイズ.Height < 文字矩形!.Value.Height * 拡大率.Height ) // 文字列全体の高さは、最大の文字高に一致。 文字列全体のサイズ.Height = 文字矩形!.Value.Height * 拡大率.Height; } return true; } } } <|start_filename|>FDK/サウンド/Mixer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using CSCore; namespace FDK { /// <summary> /// オーディオミキサー。 /// 自身が <see cref="ISampleSource"/> であり、そのまま AudioClient のレンダリングターゲットに指定することで、無限の出力を生成する。 /// </summary> public class Mixer : ISampleSource { // プロパティ /// <summary> /// 音量。0.0(無音)~1.0(原音)~... 上限なし /// </summary> public float Volume { get => this._Volume; set => this._Volume = ( 0.0f > value ) ? throw new ArgumentOutOfRangeException() : //( 1.0f < value ) ? throw new ArgumentOutOfRangeException() : --> 上限なし。 value; } /// <summary> /// ミキサーのフォーマット。 /// </summary> public WaveFormat WaveFormat { get; } /// <summary> /// ミキサーはループするので、Position には 非対応。 /// </summary> public long Position { get => 0; set => throw new NotSupportedException(); } /// <summary> /// ミキサーはシークできない。 /// </summary> public bool CanSeek => false; /// <summary> /// ミキサーは無限にループするので、長さの概念はない。 /// </summary> public long Length => throw new NotSupportedException(); // 生成と終了 /// <summary> /// 指定したフォーマットを持つミキサーを生成する。 /// </summary> public Mixer( WaveFormat deviceWaveFormat ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // ミキサーのフォーマットは、デバイスのフォーマットをそのまま使う。 this.WaveFormat = ( deviceWaveFormat.Clone() as WaveFormat ) ?? throw new Exception( "WaveFormat ではありません。" ); } /// <summary> /// ミキサに登録されているサウンドをすべて停止し解放する。 /// </summary> public virtual void Dispose() { lock( this._スレッド間同期 ) { //foreach( var sound in this._Sounds ) // sound.Dispose(); --> Dispose()する = Stop()する = this._SoundsからRemoveするということなので、foreachは使えない。 var sound = (Sound?)null; while( null != ( sound = this._Sounds.Last?.Value ) ) sound.Dispose(); this._Sounds.Clear(); // すでに空のはずだが念のため。 } } // サウンド管理 /// <summary> /// <see cref="Sound"/> をミキサーに追加する。 /// 追加されると同時に、<see cref="Sound"/> の再生が開始される。 /// </summary> public void AddSound( Sound sound ) { if( sound is null ) throw new ArgumentNullException(); lock( this._スレッド間同期 ) { // すでに登録済み(まだ再生中)なら削除する。 if( this._Sounds.Contains( sound ) ) this._Sounds.Remove( sound ); // 再生も止まる。 // Soundのフォーマットがミキサーのフォーマットと適合するかをチェック。 if( !( this._フォーマットがミキサーと互換性がある( sound.WaveFormat ) ) ) { // 違った場合の変換はサポートしない。 throw new ArgumentException( "ミキサーと同じチャンネル数、サンプルレート、かつ 32bit float 型である必要があります。" ); } // サウンドリストに登録。 this._Sounds.AddLast( sound ); } } /// <summary> /// <see cref="Sound"/> をミキサーから除外する。 /// 除外されると同時に、<see cref="Sound"/> の再生は終了する。 /// </summary> public void RemoveSound( Sound sound ) { lock( this._スレッド間同期 ) { if( this._Sounds.Contains( sound ) ) this._Sounds.Remove( sound ); } } /// <summary> /// <see cref="Sound"/> がミキサーに登録されているかを調べる。 /// </summary> /// <returns> /// <see cref="Sound"/> がミキサーに追加済みなら true 。 /// </returns> public bool Contains( Sound sound ) { if( sound is null ) return false; lock( this._スレッド間同期 ) { return this._Sounds.Contains( sound ); } } // 出力 /// <summary> /// バッファにサウンドサンプルを出力する。 /// </summary> /// <returns> /// 実際に出力したサンプル数。 /// </returns> public int Read( float[] 出力バッファ, int 出力バッファの出力開始位置, int 出力サンプル数 ) { // ミキサに登録されている Sound の入力と、このメソッドが出力するデータは、いずれも常に 32bit-float である。 // これは this.WaveFormat.WaveFormatTag とは無関係なので注意。(this.WaveFormat は、チャンネル数とサンプルレートしか見てない。) if( 0 >= 出力サンプル数 ) return 0; lock( this._スレッド間同期 ) { // 中間バッファが十分あることを確認する。足りなければ新しく確保して戻ってくる。 this._中間バッファ = this._中間バッファ.CheckBuffer( 出力サンプル数 ); // サンプル数であり、フレーム数(サンプル数×チャンネル数)ではない。 // まずは無音で埋める。 Array.Clear( 出力バッファ, 0, 出力サンプル数 ); // その上に、ミキサに登録されているすべての Sound を加算合成する。 if( 0 < this._Sounds.Count ) { var 再生終了したSound一覧 = new List<Sound>(); foreach( var sound in this._Sounds ) { // 中間バッファにサウンドデータを受け取る。 int 受け取ったサンプル数 = sound.Read( this._中間バッファ, 0, 出力サンプル数 ); if( 0 < 受け取ったサンプル数 ) { // 中間バッファから出力バッファへ合成する。 for( int i = 出力バッファの出力開始位置, n = 0; n < 受け取ったサンプル数; i++, n++ ) { float data = this._中間バッファ[ n ] // 原音 * sound.Volume // 個別音量(Sound) * this._Volume; // マスタ音量(ミキサ) // 先に無音を出力済みなので、上書きかどうかを気にしないで常に加算。 出力バッファ[ i ] += data; } } else { // 再生終了。 再生終了したSound一覧.Add( sound ); } } // 再生が終了したSoundをサウンドリストから削除する。 foreach( var sound in 再生終了したSound一覧 ) sound.Stop(); // この中で自分でRemoveする 再生終了したSound一覧.Clear(); } } return 出力サンプル数; } // ローカル private readonly LinkedList<Sound> _Sounds = new LinkedList<Sound>(); private float _Volume = 1.0f; private float[]? _中間バッファ = null; private readonly object _スレッド間同期 = new object(); private bool _フォーマットがミキサーと互換性がある( WaveFormat waveFormat ) { // チャンネル数が違うと NG if( waveFormat.Channels != this.WaveFormat.Channels ) return false; // サンプルレートが違うと NG if( waveFormat.SampleRate != this.WaveFormat.SampleRate ) return false; // 以下、ミキサーフォーマットは IEEE Float であると想定。 // IeeeFloat なら OK if( waveFormat.WaveFormatTag == AudioEncoding.IeeeFloat ) return true; // Extensible である場合、 if( waveFormat.WaveFormatTag == AudioEncoding.Extensible ) { var waveFormatEx = waveFormat as WaveFormatExtensible ?? throw new Exception( "WaveFormatExtensible" ); // サブフォーマットが IEEE Float なら OK if( waveFormatEx.SubFormat == AudioSubTypes.IeeeFloat ) return true; } // それ以外は NG return false; } } } <|start_filename|>DTXMania2/イメージ/フォント画像D2D.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2 { /// <summary> /// 文字盤(1枚のビットマップ)の一部の矩形を文字として、文字列を表示する。 /// </summary> class フォント画像D2D : FDK.フォント画像D2D { public フォント画像D2D( VariablePath 文字盤の画像ファイルパス, VariablePath 文字盤の矩形リストファイルパス, float 文字幅補正dpx = 0f, float 不透明度 = 1f ) : base( Global.GraphicResources.WicImagingFactory2, Global.GraphicResources.既定のD2D1DeviceContext, Folder.カルチャを考慮した絶対パスを返す( 文字盤の画像ファイルパス.変数なしパス ), Folder.カルチャを考慮した絶対パスを返す( 文字盤の矩形リストファイルパス.変数なしパス ), 文字幅補正dpx, 不透明度 ) { } } } <|start_filename|>DTXMania2/曲/Def/SetDef.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using SharpDX; using FDK; namespace DTXMania2.曲 { partial class SetDef { // プロパティ public static readonly string[] デフォルトのラベル = new string[] { "BASIC", "ADVANCED", "EXTREME", "MASTER", "ULTIMATE" }; public List<Block> Blocks = new List<Block>(); // 生成と終了 public SetDef() { } public SetDef( VariablePath SetDefファイルパス ) : this() { this.読み込む( SetDefファイルパス ); } /// <summary> /// set.def ファイルを読み込む。 /// 内容は上書きされる。 /// </summary> public void 読み込む( VariablePath SetDefファイルパス ) { using var sr = new StreamReader( SetDefファイルパス.変数なしパス, Encoding.GetEncoding( 932/*Shift-JIS*/ ) ); var block = new Block(); var blockが有効 = false; string? 行; while( null != ( 行 = sr.ReadLine() ) ) { try { string パラメータ = ""; #region " TITLE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"TITLE", out パラメータ ) ) { if( blockが有効 ) { // 次のブロックに入ったので、現在のブロックを保存して新しいブロックを用意する。 _FILEの指定があるのにLxLABELが省略されているときはデフォルトの名前をセットする( block ); _LxLABELの指定があるのにFILEが省略されているときはなかったものとする( block ); this.Blocks.Add( block ); // リストに追加して block = new Block(); // 新規作成。 } block.Title = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " FONTCOLOR コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"FONTCOLOR", out パラメータ ) ) { if( !( パラメータ.StartsWith( "#" ) ) ) パラメータ = "#" + パラメータ; var sysColor = System.Drawing.ColorTranslator.FromHtml( $"{パラメータ}" ); block.FontColor = new Color( sysColor.R, sysColor.G, sysColor.B, sysColor.A ); blockが有効 = true; continue; } //--------------------- #endregion #region " L1FILE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L1FILE", out パラメータ ) ) { block.File[ 0 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L2FILE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L2FILE", out パラメータ ) ) { block.File[ 1 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L3FILE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L3FILE", out パラメータ ) ) { block.File[ 2 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L4FILE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L4FILE", out パラメータ ) ) { block.File[ 3 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L5FILE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L5FILE", out パラメータ ) ) { block.File[ 4 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L1LABEL コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L1LABEL", out パラメータ ) ) { block.Label[ 0 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L2LABEL コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L2LABEL", out パラメータ ) ) { block.Label[ 1 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L3LABEL コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L3LABEL", out パラメータ ) ) { block.Label[ 2 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L4LABEL コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L4LABEL", out パラメータ ) ) { block.Label[ 3 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion #region " L5LABEL コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"L5LABEL", out パラメータ ) ) { block.Label[ 4 ] = パラメータ; blockが有効 = true; continue; } //--------------------- #endregion } catch { // 例外は無視。 } } if( blockが有効 ) { _FILEの指定があるのにLxLABELが省略されているときはデフォルトの名前をセットする( block ); _LxLABELの指定があるのにFILEが省略されているときはなかったものとする( block ); this.Blocks.Add( block ); // リストに追加。 } } /// <summary> /// set.def ファイルに保存する。 /// </summary> public void 保存する( VariablePath SetDefファイルパス ) { using var sw = new StreamWriter( SetDefファイルパス.変数なしパス ); foreach( var block in this.Blocks ) { sw.WriteLine( $"#TITLE: {block.Title}" ); if( block.FontColor != Color.White ) sw.WriteLine( $"#FONTCOLOR: #{block.FontColor.R:X2}{block.FontColor.G:X2}{block.FontColor.B:X2}" ); for( int i = 0; i < block.File.Length; i++ ) { if( !string.IsNullOrEmpty( block.File[ i ] ) && !string.IsNullOrEmpty( block.Label[ i ] ) ) { sw.WriteLine( "" ); sw.WriteLine( $"L{i + 1}LABEL: {( string.IsNullOrEmpty( block.Label[ i ] ) ? デフォルトのラベル[ i ] : block.Label[ i ] )}" ); sw.WriteLine( $"L{i + 1}FILE: {block.File[ i ]}" ); } } } } // ローカル private static void _FILEの指定があるのにLxLABELが省略されているときはデフォルトの名前をセットする( Block block ) { for( int i = 0; i < 5; i++ ) { if( !string.IsNullOrEmpty( block.File[ i ] ) && string.IsNullOrEmpty( block.Label[ i ] ) ) { block.Label[ i ] = デフォルトのラベル[ i ]; } } } private static void _LxLABELの指定があるのにFILEが省略されているときはなかったものとする( Block block ) { for( int i = 0; i < 5; i++ ) { if( string.IsNullOrEmpty( block.File[ i ] ) && !string.IsNullOrEmpty( block.Label[ i ] ) ) { block.Label[ i ] = null; } } } } } <|start_filename|>FDK/ScreenMode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace FDK { /// <summary> /// ウィンドウモードと全画面モード(ボーダーレス)を切り替える。 /// </summary> public class ScreenMode { // プロパティ /// <summary> /// 現在ウィンドウモードであるならtrueを返す。 /// </summary> public bool IsWindowMode { get; private set; } = true; /// <summary> /// 現在全画面モードであるならtrueを返す。 /// </summary> public bool IsFullscreenMode { get => !IsWindowMode; set => IsWindowMode = !value; } // 生成と終了 public ScreenMode( Form form ) { this._Form = new WeakReference<Form>( form ); } // 画面モードの切り替え /// <summary> /// ウィンドウモードに切り替える。 /// </summary> public void ToWindowMode() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._Form.TryGetTarget( out Form? form ) ) { if( !( this.IsWindowMode ) ) { // UIスレッドで実行する。 form.BeginInvoke( new Action( () => { using var _ = new LogBlock( "ウィンドウモードへの切り替え" ); this.IsWindowMode = true; form.WindowState = FormWindowState.Normal; form.ClientSize = this._ClientSize; form.FormBorderStyle = this._formBorderStyle; Cursor.Show(); } ) ); } else { Log.WARNING( $"すでにウィンドウモードなので、何もしません。" ); } } } /// <summary> /// 全画面モードに切り替える。 /// </summary> public void ToFullscreenMode() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._Form.TryGetTarget( out Form? form ) ) { if( !( this.IsFullscreenMode ) ) { // UIスレッドで実行する。 form.BeginInvoke( new Action( () => { using var _ = new LogBlock( "全画面モードへの切り替え" ); this.IsFullscreenMode = true; // バックアップ this._ClientSize = form.ClientSize; this._formBorderStyle = form.FormBorderStyle; // 正確には、「全画面(fullscreen)」ではなく「最大化(maximize)」。 // 参考: http://www.atmarkit.co.jp/ait/articles/0408/27/news105.html form.WindowState = FormWindowState.Normal; form.FormBorderStyle = FormBorderStyle.None; form.WindowState = FormWindowState.Maximized; Cursor.Hide(); } ) ); } else { Log.WARNING( $"すでに全画面モードなので、何もしません。" ); } } } // ローカル private WeakReference<Form> _Form; private Size _ClientSize = new Size( 1024, 720 ); private FormBorderStyle _formBorderStyle = FormBorderStyle.Sizable; } } <|start_filename|>FDK/イメージ/カスタムTextRenderer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using SharpDX.Mathematics.Interop; namespace FDK { /// <summary> /// 縁取り文字やドロップシャドウなどに対応した、自分用のTextRenderer。 /// </summary> public class カスタムTextRenderer : TextRendererBase { #region " class DrawingEffect " //---------------- /// <summary> /// 描画オプション。 /// <see cref="TextLayout.SetDrawingEffect"/>で、任意の範囲の文字列に対して指定できる。 /// </summary> public class DrawingEffect : ComObject { public RenderTarget? renderTarget { get => ( null != this._wrRenderTarget && this._wrRenderTarget.TryGetTarget( out RenderTarget? rt ) ) ? rt : null; set => this._wrRenderTarget = ( null != value ) ? new WeakReference<RenderTarget>( value ) : null; } public Color4 文字の色 = Color.White; public Color4 背景の色 = Color.Transparent; public DrawingEffect() : this( null! ) { } public DrawingEffect( RenderTarget 描画先 ) { this.renderTarget = 描画先; // null OK } // COM参照カウンタを増やすのはなんかイヤなので、代わりに弱参照を保持。 private WeakReference<RenderTarget>? _wrRenderTarget; } //---------------- #endregion #region " class 縁取りDrawingEffect " //---------------- /// <summary> /// 描画オプション(縁取り文字)。 /// <see cref="TextLayout.SetDrawingEffect"/>で、任意の範囲の文字列に対して適用される。 /// </summary> public class 縁取りDrawingEffect : DrawingEffect { public Color4 縁の色 = Color.Black; public float 縁の太さ = 3.0f; public 縁取りDrawingEffect() : this( null! ) { } public 縁取りDrawingEffect( RenderTarget 描画先 ) : base( 描画先 ) { } } //---------------- #endregion #region " class ドロップシャドウDrawingEffect " //---------------- /// <summary> /// 描画オプション(ドロップシャドウ文字)。 /// <see cref="TextLayout.SetDrawingEffect"/>で、任意の範囲の文字列に対して適用される。 /// </summary> public class ドロップシャドウDrawingEffect : DrawingEffect { public Color4 影の色 = Color.Black; public float 影の距離 = 1.0f; public ドロップシャドウDrawingEffect() : this( null! ) { } public ドロップシャドウDrawingEffect( RenderTarget 描画先 ) : base( 描画先 ) { } } //---------------- #endregion public カスタムTextRenderer( SharpDX.Direct2D1.Factory1 d2dFactory1, DeviceContext d2dDeviceContext, Color4 既定の文字色, Color4 既定の背景色 ) : base() { this._D2DFactory1 = d2dFactory1; this._D2DDeviceContext = d2dDeviceContext; this._既定の文字色 = 既定の文字色; this._既定の背景色 = 既定の背景色; } protected override void Dispose( bool disposing ) { this._D2DDeviceContext = null!; this._D2DFactory1 = null!; } /// <summary> /// グリフ実行を描画する際に、<see cref="TextLayout.Draw"/> から呼び出されるコールバック。 /// </summary> /// <param name="clientDrawingContext"><see cref="TextLayout.Draw(object, TextRenderer, float, float)"/>で渡された、アプリ定義の描画コンテキスト。</param> /// <param name="baselineOriginX">グリフ実行のベースライン原点のピクセル位置(X座標)。</param> /// <param name="baselineOriginY">グリフ実行のベースライン原点のピクセル位置(Y座標)。</param> /// <param name="measuringMode">実行中にグリフを測定する方法。他のプロパティとともに、描画モードを決定するために使われる。</param> /// <param name="glyphRun">描画するグリフ実行。</param> /// <param name="glyphRunDescription">グリフ実行記述。オプション。この実行に関連する文字のプロパティを持つ。</param> /// <param name="clientDrawingEffect">非 null なら、TextLayout.SetDrawingEffect() で設定されている IUnknown 派生オブジェクトが格納されている。</param> /// <returns>成功すれば <see cref="Result.Ok"/>, 失敗したら <see cref="Result.Fail"/>。</returns> public override Result DrawGlyphRun( object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, ComObject clientDrawingEffect ) { using var パスジオメトリ = new PathGeometry( this._D2DFactory1 ); // グリフ実行の輪郭をパスジオメトリとして取得。 using( var sink = パスジオメトリ.Open() ) { glyphRun.FontFace.GetGlyphRunOutline( glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.Indices?.Count() ?? 0, glyphRun.IsSideways, ( 1 == ( glyphRun.BidiLevel % 2 ) ), // 奇数ならtrue sink ); sink.Close(); } // ジオメトリを描画する。 var 変換行列 = Matrix3x2.Translation( baselineOriginX, baselineOriginY ); // ベースラインの原点まで移動 using var 原点移動済みパスジオメトリ = new TransformedGeometry( this._D2DFactory1, パスジオメトリ, 変換行列 ); bool drawingEffectを解放する = false; #region " DrawingEffect の指定があれば受け取る。なければ既定の値で作る。" //---------------- var drawingEffect = ( clientDrawingContext as DrawingEffect ) ?? // Context 優先にしておく ( clientDrawingEffect as DrawingEffect ); if( drawingEffect is null ) { drawingEffect = new DrawingEffect( this._D2DDeviceContext ) { 文字の色 = this._既定の文字色, 背景の色 = this._既定の背景色, }; drawingEffectを解放する = true; } //---------------- #endregion var renderTarget = drawingEffect.renderTarget ?? // 指定されたレンダーターゲットを使う。 this._D2DDeviceContext; // 指定がなければ既定のDCを使う。 this._現在の変換行列 = renderTarget.Transform; this._現在のDPI = renderTarget.DotsPerInch.Width; #region " 背景を描画。" //---------------- if( drawingEffect.背景の色 != Color.Transparent ) { using var 背景ブラシ = new SolidColorBrush( renderTarget, drawingEffect.背景の色 ); float 送り幅の合計 = 0f; foreach( float 送り幅 in glyphRun.Advances ) 送り幅の合計 += 送り幅; var rc = new RectangleF() { Left = baselineOriginX, Top = baselineOriginY - glyphRun.FontSize * glyphRun.FontFace.Metrics.Ascent / glyphRun.FontFace.Metrics.DesignUnitsPerEm, Right = baselineOriginX + 送り幅の合計, Bottom = baselineOriginY + glyphRun.FontSize * glyphRun.FontFace.Metrics.Descent / glyphRun.FontFace.Metrics.DesignUnitsPerEm, }; // 塗りつぶす。 renderTarget.FillRectangle( rc, 背景ブラシ ); } //---------------- #endregion #region " 文字を描画。" //---------------- switch( drawingEffect ) { case 縁取りDrawingEffect effect: { using var 縁ブラシ = new SolidColorBrush( renderTarget, effect.縁の色 ); using var 文字ブラシ = new SolidColorBrush( renderTarget, effect.文字の色 ); using var strokeStyle = new StrokeStyle( this._D2DFactory1, new StrokeStyleProperties() { LineJoin = LineJoin.Miter } ); // 突き抜け防止 renderTarget.DrawGeometry( 原点移動済みパスジオメトリ, 縁ブラシ, effect.縁の太さ, strokeStyle ); renderTarget.FillGeometry( 原点移動済みパスジオメトリ, 文字ブラシ ); break; } case ドロップシャドウDrawingEffect effect: { using var 影ブラシ = new SolidColorBrush( renderTarget, effect.影の色 ); using var 文字ブラシ = new SolidColorBrush( renderTarget, effect.文字の色 ); var 影の変換行列 = 変換行列 * Matrix3x2.Translation( effect.影の距離, effect.影の距離 ); using var 影のパスジオメトリ = new TransformedGeometry( this._D2DFactory1, パスジオメトリ, 影の変換行列 ); renderTarget.FillGeometry( 影のパスジオメトリ, 影ブラシ ); renderTarget.FillGeometry( 原点移動済みパスジオメトリ, 文字ブラシ ); break; } case DrawingEffect effect: { using var 文字ブラシ = new SolidColorBrush( renderTarget, effect.文字の色 ); renderTarget.FillGeometry( 原点移動済みパスジオメトリ, 文字ブラシ ); break; } default: { throw new ArgumentException( "未知の DrawingEffect が指定されました。" ); } } //---------------- #endregion if( drawingEffectを解放する ) drawingEffect.Dispose(); // 作った場合は解放する。 return Result.Ok; } /// <summary> /// インラインオブジェクトを描画する際に、<see cref="TextLayout.Draw"/>から呼び出されるコールバック。 /// </summary> /// <param name="clientDrawingContext"></param> /// <param name="originX"></param> /// <param name="originY"></param> /// <param name="inlineObject"></param> /// <param name="isSideways"></param> /// <param name="isRightToLeft"></param> /// <param name="clientDrawingEffect"></param> /// <returns></returns> public override Result DrawInlineObject( object clientDrawingContext, float originX, float originY, InlineObject inlineObject, bool isSideways, bool isRightToLeft, ComObject clientDrawingEffect ) { // 未対応。 return base.DrawInlineObject( clientDrawingContext, originX, originY, inlineObject, isSideways, isRightToLeft, clientDrawingEffect ); } /// <summary> /// 打ち消し文字を描画する際に、<see cref="TextLayout.Draw"/>から呼び出されるコールバック。 /// </summary> /// <param name="clientDrawingContext"></param> /// <param name="baselineOriginX"></param> /// <param name="baselineOriginY"></param> /// <param name="strikethrough"></param> /// <param name="clientDrawingEffect"></param> /// <returns></returns> public override Result DrawStrikethrough( object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Strikethrough strikethrough, ComObject clientDrawingEffect ) { // 未対応。 return base.DrawStrikethrough( clientDrawingContext, baselineOriginX, baselineOriginY, ref strikethrough, clientDrawingEffect ); } /// <summary> /// 下線付き文字を描画する際に、<see cref="TextLayout.Draw"/>から呼び出されるコールバック。 /// </summary> /// <param name="clientDrawingContext"></param> /// <param name="baselineOriginX"></param> /// <param name="baselineOriginY"></param> /// <param name="underline"></param> /// <param name="clientDrawingEffect"></param> /// <returns></returns> public override Result DrawUnderline( object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Underline underline, ComObject clientDrawingEffect ) { // 未対応。 return base.DrawUnderline( clientDrawingContext, baselineOriginX, baselineOriginY, ref underline, clientDrawingEffect ); } /// <summary> /// ピクセルスナッピングが無効か否かを表す。 /// サブピクセルバーティカルプレースメントのアニメーションを行わない限り、推奨される既定値は false である。 /// </summary> /// <param name="clientDrawingContext"></param> /// <returns>ピクセルスナッピングが無効なら true 、有効なら false。</returns> public override bool IsPixelSnappingDisabled( object clientDrawingContext ) => false; /// <summary> /// 抽象座標から DIP への変形行列を返す。 /// </summary> /// <param name="clientDrawingContext"></param> /// <returns></returns> public override RawMatrix3x2 GetCurrentTransform( object clientDrawingContext ) => this._現在の変換行列; /// <summary> /// DIP ごとの物理ピクセル数を返す。 /// </summary> /// <param name="clientDrawingContext"></param> /// <returns></returns> public override float GetPixelsPerDip( object clientDrawingContext ) => this._現在のDPI; private SharpDX.Direct2D1.Factory1 _D2DFactory1; private SharpDX.Direct2D1.DeviceContext _D2DDeviceContext; private Color4 _既定の文字色; private Color4 _既定の背景色; private Matrix3x2 _現在の変換行列 = Matrix3x2.Identity; private float _現在のDPI = 96f; } } <|start_filename|>DTXMania2/ステージ/04選曲/QuickConfig/ラベル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; namespace DTXMania2.選曲.QuickConfig { class ラベル : IDisposable { // プロパティ public string 名前 { get; protected set; } = ""; // 生成と終了 public ラベル( string 名前 ) { this.名前 = 名前; this._項目名画像 = new 文字列画像D2D() { 表示文字列 = this.名前, フォントサイズpt = 34f, 前景色 = Color4.White }; } public virtual void Dispose() { this._項目名画像.Dispose(); } // 進行と描画 public virtual void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置 ) { this._項目名画像.描画する( d2ddc, 左位置, 上位置 ); } // ローカル protected readonly 文字列画像D2D _項目名画像; } } <|start_filename|>DTXMania2/曲/Tree/Node/BoxNode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2.曲 { // hack: box.def の PreImage 他への対応 class BoxNode : Node { // プロパティ public SelectableList<Node> 子ノードリスト { get; } = new SelectableList<Node>(); // 生成と終了 public BoxNode( string BOX名 ) { this.タイトル = BOX名; } public BoxNode( BoxDef def ) { this.タイトル = def.TITLE; this.サブタイトル = def.ARTIST ?? ""; } // その他 /// <summary> /// 子孫を直列に列挙する。 /// </summary> public IEnumerable<Node> Traverse() { // 幅優先探索。 // (1) すべての子ノード。 foreach( var child in this.子ノードリスト ) yield return child; // (2) すべてのBOXノードの子ノード。 foreach( var child in this.子ノードリスト ) { if( child is BoxNode box ) { foreach( var coc in box.Traverse() ) yield return coc; } } } } } <|start_filename|>FDK/サウンド/SoundDevice.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using CSCore; using CSCore.CoreAudioAPI; using CSCore.SoundOut; using CSCore.Win32; namespace FDK { /// <summary> /// WASAPI サウンドデバイス。 /// </summary> public class SoundDevice : IDisposable { // プロパティ public PlaybackState レンダリング状態 => this._レンダリング状態; public double 再生遅延sec { get; protected set; } /// <summary> /// デバイスのレンダリングフォーマット。 /// </summary> public WaveFormat WaveFormat { get; } /// <summary> /// レンダリングボリューム。 /// 0.0 (0%) ~ 1.0 (100%) 。 /// </summary> public float 音量 { get => this.Mixer.Volume; set { if( ( 0.0f > value ) || ( 1.0f < value ) ) throw new ArgumentOutOfRangeException( $"音量の値が、範囲(0~1)を超えています。[{value}]" ); this.Mixer.Volume = value; } } /// <summary> /// ミキサー。 /// </summary> internal Mixer Mixer { get; private set; } // 生成と終了 /// <summary> /// デバイスを初期化し、レンダリングを開始する。 /// </summary> public SoundDevice( AudioClientShareMode 共有モード, double バッファサイズsec = 0.010, WaveFormat? 希望フォーマット = null ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._共有モード = 共有モード; this.再生遅延sec = バッファサイズsec; this._レンダリング状態 = PlaybackState.Stopped; lock( this._スレッド間同期 ) { #region " MMDevice を生成し、AudioClient を取得する。" //---------------- this._MMDevice = MMDeviceEnumerator.DefaultAudioEndpoint( DataFlow.Render, // 方向 ... 書き込み Role.Console ); // 用途 ... ゲーム、システム通知音、音声命令 Log.Info( $"Device: {this._MMDevice.FriendlyName}" ); this._AudioClient = AudioClient.FromMMDevice( this._MMDevice ); //---------------- #endregion #region " フォーマットを決定する。" //---------------- this.WaveFormat = this._適切なフォーマットを調べて返す( 希望フォーマット ) ?? throw new NotSupportedException( "サポート可能な WaveFormat が見つかりませんでした。" ); Log.Info( $"WaveFormat: Channels={this.WaveFormat.Channels}, " + $"SampleRate={this.WaveFormat.SampleRate}, " + $"BytesPerSecond={this.WaveFormat.BytesPerSecond}, BlockAlign={this.WaveFormat.BlockAlign}, " + $"BitsPerSample={this.WaveFormat.BitsPerSample}" ); //---------------- #endregion #region " AudioClient を初期化する。" //---------------- try { long 期間100ns = ( this._共有モード == AudioClientShareMode.Shared ) ? 0 : // 共有モードの場合、0 を指定。 (long)( this.再生遅延sec * 10_000_000 + 0.5 ); // 排他モードの場合、コンストラクタで指定された値。 // イベント駆動で初期化。 this._AudioClient.Initialize( this._共有モード, AudioClientStreamFlags.StreamFlagsEventCallback, 期間100ns, 期間100ns, this.WaveFormat, Guid.Empty ); } catch( CoreAudioAPIException e ) { if( e.ErrorCode == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED ) { // 排他モードかつイベント駆動 の場合、このエラーコードが返されることがある。 // この場合、バッファサイズを調整して再度初期化する。 int サイズframe = this._AudioClient.GetBufferSize(); // アライメント済みサイズが取得できる。 this.再生遅延sec = (double)サイズframe / this.WaveFormat.SampleRate; long 期間100ns = (long)( this.再生遅延sec * 10_000_000 + 0.5 ); // 再度初期化。 this._AudioClient.Initialize( this._共有モード, AudioClientStreamFlags.StreamFlagsEventCallback, 期間100ns, 期間100ns, this.WaveFormat, Guid.Empty ); // それでも例外なら知らん。 } else { throw; } } // DevicePeriod をログ表示。 this._AudioClient.GetDevicePeriodNative( out long defaultDevicePeriod, out long minimumDevicePeriod ); if( this._共有モード == AudioClientShareMode.Shared ) Log.Info( $"DevicePeriod: {defaultDevicePeriod / 10_000}ms (Shared)" ); else Log.Info( $"DevicePeriod: {minimumDevicePeriod / 10_000}ms (Exclusive)" ); //---------------- #endregion #region " イベント駆動に使うイベントを生成し、AudioClient へ登録する。" //---------------- this._レンダリングイベント = new EventWaitHandle( false, EventResetMode.AutoReset ); this._AudioClient.SetEventHandle( this._レンダリングイベント.SafeWaitHandle.DangerousGetHandle() ); //---------------- #endregion #region " その他のインターフェースを取得する。" //---------------- this._AudioRenderClient = AudioRenderClient.FromAudioClient( this._AudioClient ); this._AudioClock = AudioClock.FromAudioClient( this._AudioClient ); //---------------- #endregion Log.Info( $"サウンドデバイスを生成しました。" ); #region " ミキサーを生成する。" //---------------- this.Mixer = new Mixer( this.WaveFormat ); //---------------- #endregion } this.レンダリングを開始する(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.レンダリングを停止する(); if( !this._レンダリング終了完了通知.WaitOne( 5000 ) ) throw new InvalidOperationException( "レンダリングの終了完了待ちでタイムアウトしました。" ); this.Mixer.Dispose(); this._AudioClock.Dispose(); this._AudioRenderClient.Dispose(); this._AudioClient.Dispose(); this._レンダリングイベント.Dispose(); this._MMDevice.Dispose(); } // レンダリング操作 /// <summary> /// レンダリングスレッドを生成し、ミキサーの出力のレンダリングを開始する。 /// </summary> public void レンダリングを開始する() { using var _ = new LogBlock( Log.現在のメソッド名 ); var 現在の状態 = PlaybackState.Stopped; lock( this._スレッド間同期 ) 現在の状態 = this._レンダリング状態; switch( 現在の状態 ) { case PlaybackState.Paused: this.レンダリングを再開する(); // 再開する。 break; case PlaybackState.Stopped: this._レンダリング起動完了通知 = new ManualResetEvent( false ); this._レンダリング終了完了通知 = new ManualResetEvent( false ); // レンダリングスレッドを生成する。 if( null != this._レンダリングスレッド ) // すでに起動してたら例外発出。 throw new InvalidOperationException( "レンダリングスレッドがすでに起動しています。" ); this._レンダリングスレッド = new Thread( this._レンダリングスレッドエントリ ) { Name = "WASAPI Playback", Priority = ThreadPriority.AboveNormal, // 標準よりやや上 }; this._レンダリングスレッド.SetApartmentState( ApartmentState.MTA ); // マルチスレッドアパートメント this._レンダリングスレッド.Start(); // 起動完了待ち。 if( !this._レンダリング起動完了通知.WaitOne( 5000 ) ) throw new InvalidOperationException( "レンダリングスレッドの起動完了待ちがタイムアウトしました。" ); Log.Info( "レンダリングスレッドを起動しました。" ); break; case PlaybackState.Playing: break; } } /// <summary> /// ミキサーの出力のレンダリングを一時停止する。 /// ミキサーに登録されているすべてのサウンドの再生が一時停止する。 /// </summary> public void レンダリングを一時停止する() { lock( this._スレッド間同期 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._レンダリング状態 == PlaybackState.Playing ) this._レンダリング状態 = PlaybackState.Paused; } } /// <summary> /// ミキサーの出力のレンダリングを再開する。 /// 一時停止状態にあるときのみ有効。 /// </summary> public void レンダリングを再開する() { lock( this._スレッド間同期 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._レンダリング状態 == PlaybackState.Paused ) this._レンダリング状態 = PlaybackState.Playing; } } /// <summary> /// ミキサーの出力のレンダリングを停止する。 /// ミキサーに登録されているすべてのサウンドの再生が停止する。 /// </summary> public void レンダリングを停止する() { lock( this._スレッド間同期 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._レンダリング状態 != PlaybackState.Stopped ) this._レンダリング状態 = PlaybackState.Stopped; } } // レンダリングスレッド /// <summary> /// WASAPIイベント駆動スレッドのエントリ。 /// </summary> private void _レンダリングスレッドエントリ() { var 元のMMCSS特性 = IntPtr.Zero; var encoding = AudioSubTypes.EncodingFromSubType( WaveFormatExtensible.SubTypeFromWaveFormat( this.WaveFormat ) ); try { #region " 初期化。" //---------------- int バッファサイズframe = this._AudioClient.BufferSize; var バッファ = new float[ バッファサイズframe * this.WaveFormat.Channels ]; // this._レンダリング先(ミキサー)の出力は 32bit-float で固定。 var gchバッファ = GCHandle.Alloc( バッファ, GCHandleType.Pinned ); // このスレッドの MMCSS 型を登録する。 string mmcssType; switch( this.再生遅延sec ) { case double 遅延 when( 0.0105 > 遅延 ): mmcssType = "Pro Audio"; break; case double 遅延 when( 0.0150 > 遅延 ): mmcssType = "Games"; break; default: mmcssType = "Audio"; break; } 元のMMCSS特性 = AvSetMmThreadCharacteristics( mmcssType, out int taskIndex ); this._AudioClient.Start(); this._レンダリング状態 = PlaybackState.Playing; this._レンダリング起動完了通知.Set(); //---------------- #endregion Log.Info( "レンダリングループを開始します。" ); #region " レンダリングループ。" //---------------- var イベントs = new WaitHandle[] { this._レンダリングイベント }; while( true ) { // イベントs[] のいずれかのイベントが発火する(またはタイムアウトする)まで待つ。 if( WaitHandle.WaitAny( waitHandles: イベントs, millisecondsTimeout: (int)( 3000.0 * this.再生遅延sec ), // 適正値は レイテンシ×3 [ms] (MSDNより) exitContext: false ) == WaitHandle.WaitTimeout ) { continue; // タイムアウトした=まだどのイベントもきてない。 } // 1ターン分をレンダリング。 lock( this._スレッド間同期 ) { // 状態チェック。 if( this._レンダリング状態 == PlaybackState.Stopped ) break; // ループを抜ける。 if( this._レンダリング状態 == PlaybackState.Paused ) continue; // 何もしない。 // バッファの空き容量を計算する。 int 未再生数frame = ( this._共有モード == AudioClientShareMode.Exclusive ) ? 0 : this._AudioClient.GetCurrentPadding(); int 空きframe = バッファサイズframe - 未再生数frame; if( 5 >= 空きframe ) continue; // あまりに空きが小さいなら、何もせずスキップする。 // 今回の読み込みサイズ(サンプル単位)を計算する。 int 読み込むサイズsample = (int)this._位置をブロック境界単位にそろえて返す( 空きframe * this.WaveFormat.Channels, // 前提・レンダリング先.WaveFormat と this.WaveFormat は同一。 this.WaveFormat.BlockAlign / this.WaveFormat.BytesPerSample ); if( 0 >= 読み込むサイズsample ) continue; // 今回は読み込まない。スキップする。 // ミキサーからの出力(32bit-float)をバッファに取得する。 int 読み込んだサイズsample = this.Mixer.Read( バッファ, 0, 読み込むサイズsample ); // バッファのデータをレンダリングフォーマットに変換しつつ、AudioRenderClient へ出力する。 IntPtr bufferPtr = this._AudioRenderClient.GetBuffer( 空きframe ); try { switch( encoding ) { case AudioEncoding.IeeeFloat: { #region " FLOAT32 → FLOAT32 " //---------------- Marshal.Copy( バッファ, 0, bufferPtr, 読み込んだサイズsample ); break; //---------------- #endregion } case AudioEncoding.Pcm: { switch( this.WaveFormat.BitsPerSample ) { case 24: { #region " FLOAT32 → PCM24 " //---------------- // ※ 以下のコードでは、まだ、まともに再生できない。おそらくザーッという大きいノイズだらけの音になる。 unsafe { byte* ptr = (byte*)bufferPtr.ToPointer(); // AudioRenderClient のバッファは GC 対象外なのでピン止め不要。 for( int i = 0; i < 読み込んだサイズsample; i++ ) { float data = バッファ[ i ]; if( -1.0f > data ) data = -1.0f; if( +1.0f < data ) data = +1.0f; uint sample32 = (uint)( data * 8388608f - 1f ); // 24bit PCM の値域は -8388608~+8388607 byte* psample32 = (byte*)&sample32; *ptr++ = *psample32++; *ptr++ = *psample32++; *ptr++ = *psample32++; } } break; //---------------- #endregion } case 16: { #region " FLOAT32 → PCM16 " //---------------- unsafe { byte* ptr = (byte*)bufferPtr.ToPointer(); // AudioRenderClient のバッファは GC 対象外なのでピン止め不要。 for( int i = 0; i < 読み込んだサイズsample; i++ ) { float data = バッファ[ i ]; if( -1.0f > data ) data = -1.0f; if( +1.0f < data ) data = +1.0f; short sample16 = (short)( data * short.MaxValue ); byte* psample16 = (byte*)&sample16; *ptr++ = *psample16++; *ptr++ = *psample16++; } } break; //---------------- #endregion } case 8: { #region " FLOAT32 → PCM8 " //---------------- unsafe { byte* ptr = (byte*)bufferPtr.ToPointer(); // AudioRenderClient のバッファは GC 対象外なのでピン止め不要。 for( int i = 0; i < 読み込んだサイズsample; i++ ) { float data = バッファ[ i ]; if( -1.0f > data ) data = -1.0f; if( +1.0f < data ) data = +1.0f; byte value = (byte)( ( data + 1 ) * 128f ); *ptr++ = unchecked(value); } } break; //---------------- #endregion } } break; } } } finally { int 出力したフレーム数 = 読み込んだサイズsample / this.WaveFormat.Channels; this._AudioRenderClient.ReleaseBuffer( 出力したフレーム数, ( 0 < 出力したフレーム数 ) ? AudioClientBufferFlags.None : AudioClientBufferFlags.Silent ); } // ミキサーからの出力がなくなったらレンダリングを停止する。 if( 0 == 読み込んだサイズsample ) this._レンダリング状態 = PlaybackState.Stopped; } } //---------------- #endregion #region " 終了。" //---------------- this._AudioClient.Stop(); this._AudioClient.Reset(); // ハードウェアの再生が終わるくらいまで、少し待つ。 Thread.Sleep( (int)( this.再生遅延sec * 1000 / 2 ) ); gchバッファ.Free(); //---------------- #endregion Log.Info( "レンダリングスレッドを終了します。" ); this._レンダリング終了完了通知.Set(); } //catch( Exception e ) ---> 例外をcatchするとスレッドが終了して無音になるだけなのでエラーに気づかない。例外はそのままスローする。 //{ // Log.ERROR( $"例外が発生しました。レンダリングスレッドを中断します。[{e.Message}]" ); //} finally { #region " 完了。" //---------------- if( 元のMMCSS特性 != IntPtr.Zero ) AvRevertMmThreadCharacteristics( 元のMMCSS特性 ); this._レンダリング起動完了通知.Set(); this._レンダリング終了完了通知.Set(); //---------------- #endregion } } // その他 /// <summary> /// 現在のデバイス位置を返す[秒]。 /// </summary> public double GetDevicePosition() { // AudioClock から現在のデバイス位置を取得する。 this.GetClock( out long position, out long qpcPosition, out long frequency ); // position ...... 現在のデバイス位置(デバイスからの報告) // frequency ..... 現在のデバイス周波数(デバイスからの報告) // qpcPosition ... デバイス位置を取得した時刻 [100ns単位; パフォーマンスカウンタの生値ではないので注意] // デバイス位置÷デバイス周波数 で、秒単位に換算できる。 double デバイス位置sec = (double)position / frequency; // デバイス位置の精度が荒い(階段状のとびとびの値になる)場合には、パフォーマンスカウンタで補間する。 if( position == this._最後のデバイス位置.position && 0 < position ) { // (A) デバイス位置が前回と同じである場合(ただし 0 を除く): // → 最後のデバイス位置における qpcPosition と今回の qpcPosition の差をデバイス位置secに加算する。 デバイス位置sec += ( qpcPosition - this._最後のデバイス位置.qpcPosition ) / 10_000_000.0; } else { // (B) デバイス位置が前回と異なる場合: // → 最後のデバイス位置を現在の値に更新する。今回のデバイス位置secは補間しない。 this._最後のデバイス位置 = (position, qpcPosition); } return デバイス位置sec; // ボツ1: // ↓サウンドデバイス固有のpositionを使う場合。なんかの拍子で、音飛びと同時に不連続になる? //return ( (double) position / frequency ); // ボツ2: // ↓パフォーマンスカウンタを使う場合。こちらで、音飛び&不連続現象が消えるか否かを検証中。 // なお、qpcPosition には、生カウンタではなく、100ns単位に修正された値が格納されているので注意。(GetClockの仕様) //return FDKUtilities.変換_100ns単位からsec単位へ( qpcPosition ); } // ローカル private volatile PlaybackState _レンダリング状態 = PlaybackState.Stopped; private AudioClientShareMode _共有モード; private AudioClock _AudioClock; private AudioRenderClient _AudioRenderClient; private AudioClient _AudioClient; private MMDevice _MMDevice; private (long position, long qpcPosition) _最後のデバイス位置 = (0, 0); private Thread _レンダリングスレッド = null!; private EventWaitHandle _レンダリングイベント; private readonly object _スレッド間同期 = new object(); private ManualResetEvent _レンダリング起動完了通知 = null!; private ManualResetEvent _レンダリング終了完了通知 = null!; /// <summary> /// 希望したフォーマットをもとに、適切なフォーマットを調べて返す。 /// </summary> /// <param name="waveFormat">希望するフォーマット</param> /// <param name="audioClient">AudioClient インスタンス。Initialize 前でも可。</param> /// <returns>適切なフォーマット。見つからなかったら null。</returns> private WaveFormat? _適切なフォーマットを調べて返す( WaveFormat? waveFormat ) { var 最も近いフォーマット = (WaveFormat?)null; var 最終的に決定されたフォーマット = (WaveFormat?)null; if( ( null != waveFormat ) && this._AudioClient!.IsFormatSupported( this._共有モード, waveFormat, out 最も近いフォーマット ) ) { // (A) そのまま使える。 最終的に決定されたフォーマット = waveFormat; } else if( null != 最も近いフォーマット ) { // (B) AudioClient が推奨フォーマットを返してきたので、それを採択する。 最終的に決定されたフォーマット = 最も近いフォーマット; } else { // (C) AudioClient からの提案がなかったので、共有モードのフォーマットを採択してみる。 var 共有モードのフォーマット = this._AudioClient.GetMixFormat(); if( ( null != 共有モードのフォーマット ) && this._AudioClient.IsFormatSupported( this._共有モード, 共有モードのフォーマット ) ) { 最終的に決定されたフォーマット = 共有モードのフォーマット; } else { // (D) 共有モードのフォーマットも NG である場合は、以下から探す。 bool found = this._AudioClient.IsFormatSupported( AudioClientShareMode.Exclusive, new WaveFormat( 48000, 24, 2, AudioEncoding.Pcm ), out WaveFormat closest ); 最終的に決定されたフォーマット = new[] { new WaveFormat( 48000, 32, 2, AudioEncoding.IeeeFloat ), new WaveFormat( 44100, 32, 2, AudioEncoding.IeeeFloat ), /* * 24bit PCM には対応しない。 * * https://msdn.microsoft.com/ja-jp/library/cc371566.aspx * > wFormatTag が WAVE_FORMAT_PCM の場合、wBitsPerSample は 8 または 16 でなければならない。 * > wFormatTag が WAVE_FORMAT_EXTENSIBLE の場合、この値は、任意の 8 の倍数を指定できる。 * * また、Realtek HD Audio の場合、IAudioClient.IsSupportedFormat() は 24bit PCM でも true を返してくるが、 * 単純に 1sample = 3byte で書き込んでも正常に再生できない。 * おそらく 32bit で包む必要があると思われるが、その方法は不明。 */ //new WaveFormat( 48000, 24, 2, AudioEncoding.Pcm ), //new WaveFormat( 44100, 24, 2, AudioEncoding.Pcm ), new WaveFormat( 48000, 16, 2, AudioEncoding.Pcm ), new WaveFormat( 44100, 16, 2, AudioEncoding.Pcm ), new WaveFormat( 48000, 8, 2, AudioEncoding.Pcm ), new WaveFormat( 44100, 8, 2, AudioEncoding.Pcm ), new WaveFormat( 48000, 32, 1, AudioEncoding.IeeeFloat ), new WaveFormat( 44100, 32, 1, AudioEncoding.IeeeFloat ), //new WaveFormat( 48000, 24, 1, AudioEncoding.Pcm ), //new WaveFormat( 44100, 24, 1, AudioEncoding.Pcm ), new WaveFormat( 48000, 16, 1, AudioEncoding.Pcm ), new WaveFormat( 44100, 16, 1, AudioEncoding.Pcm ), new WaveFormat( 48000, 8, 1, AudioEncoding.Pcm ), new WaveFormat( 44100, 8, 1, AudioEncoding.Pcm ), } .FirstOrDefault( ( format ) => ( this._AudioClient.IsFormatSupported( this._共有モード, format ) ) ); // (E) それでも見つからなかったら null のまま。 } } return 最終的に決定されたフォーマット; } /// <summary> /// 現在のデバイス位置を取得する。 /// </summary> private void GetClock( out long Pu64Position, out long QPCPosition, out long Pu64Frequency ) { lock( this._スレッド間同期 ) { this._AudioClock.GetFrequencyNative( out Pu64Frequency ); int hr = 0; long pos = 0; long qpcPos = 0; for( int リトライ回数 = 0; リトライ回数 < 10; リトライ回数++ ) // 最大10回までリトライ。 { hr = this._AudioClock.GetPositionNative( out pos, out qpcPos ); // ※IAudioClock::GetPosition() は、S_FALSE を返すことがある。 //  これは、WASAPI排他モードにおいて、GetPosition 時に優先度の高いイベントが発生しており //  規定時間内にデバイス位置を取得できなかった場合に返される。(MSDNより) if( ( (int)HResult.S_OK ) == hr ) { break; // OK } else if( ( (int)HResult.S_FALSE ) == hr ) { continue; // リトライ } else { throw new Win32ComException( hr, "IAudioClock", "GetPosition" ); } } Pu64Position = pos; QPCPosition = qpcPos; } } private long _位置をブロック境界単位にそろえて返す( long position, long blockAlign ) { return ( position - ( position % blockAlign ) ); } // Win32 private const int AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED = unchecked((int)0x88890019); private const int AUDCLNT_E_INVALID_DEVICE_PERIOD = unchecked((int)0x88890020); private const int AUDCLNT_E_NOT_INITIALIZED = unchecked((int)0x88890001); [DllImport( "Avrt.dll", CharSet = CharSet.Unicode )] private static extern IntPtr AvSetMmThreadCharacteristics( [MarshalAs( UnmanagedType.LPWStr )] string proAudio, out int taskIndex ); [DllImport( "Avrt.dll" )] private static extern bool AvRevertMmThreadCharacteristics( IntPtr avrtHandle ); } } <|start_filename|>SSTFEditor/ConfigXML.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; using System.Drawing; using System.Xml.Serialization; using System.Windows.Forms; namespace SSTFEditor { public class Config { /// <summary> /// 譜面コントロールのオートフォーカス。 /// これが true の場合、譜面エリアにマウスポインタが入ったら、譜面コントロールが自動的にフォーカスされる。 /// </summary> public bool AutoFocus = true; /// <summary> /// 最近使用したファイルの一覧をファイルメニューに表示する場合は true。 /// </summary> public bool ShowRecentUsedFiles = true; /// <summary> /// 最近使用したファイルの一覧に表示するファイル数の上限。 /// </summary> public int MaxOfUsedRecentFiles = 10; /// <summary> /// 最近使用したファイルの絶対パスの一覧。 /// </summary> public List<string> RecentUsedFiles = new List<string>(); /// <summary> /// ビュアーへのパス。 /// </summary> public string ViewerPath = @".\DTXMania2.exe"; /// <summary> /// 起動時のウィンドウ表示位置。 /// </summary> public Point WindowLocation = new Point( 100, 100 ); /// <summary> /// 起動時のウィンドウのクライアントサイズ。 /// </summary> public Size ClientSize = new Size( 710, 512 ); /// <summary> /// 起動時の譜面拡大率係数。1~13。 /// 譜面の拡大率(x1~x4) = 1.0 + (ViewScale - 1) * 0.25 で算出。 /// </summary> public int ViewScale = 1; /// <summary> /// .sstf 以外のファイル(SSTFoverDTXを除く)を開く際に、SSTF形式に変換するかどうかを /// 確認するダイアログを表示するなら true。 /// false の場合は無条件で変換される。 /// </summary> public bool DisplaysConfirmOfSSTFConversion = true; /// <summary> /// ライドレーンの表示位置が左ならtrue, 右ならfalse。 /// </summary> public bool RideLeft = false; /// <summary> /// チャイナレーンの表示位置が左ならtrue, 右ならfalse。 /// </summary> public bool ChinaLeft = false; /// <summary> /// スプラッシュレーンの表示位置が左ならtrue, 右ならfalse。 /// </summary> public bool SplashLeft = true; // メソッド public static Config 読み込む( string ファイル名 ) { Config config; try { config = FDK.Serializer.ファイルをデシリアライズしてインスタンスを生成する<Config>( ファイル名 ); } catch( Exception ) { config = new Config(); // 読み込めなかったら新規作成する。 } return config; } public void 保存する( string ファイル名 ) { try { FDK.Serializer.インスタンスをシリアライズしてファイルに保存する( ファイル名, this ); } catch( Exception e ) { MessageBox.Show( $"{Properties.Resources.MSG_ファイルの保存に失敗しました} [{ファイル名}]\n--------\n{e.ToString()}" ); } } public void ファイルを最近使ったファイルの一覧に追加する( string ファイル名 ) { // 絶対パスを取得する。 var ファイルパス = Path.GetFullPath( ファイル名 ); // 一覧に同じ文字列があったら一覧から削除する。 this.RecentUsedFiles.RemoveAll( ( path ) => { return path.Equals( ファイルパス ); } ); // 一覧の先頭に登録する。 this.RecentUsedFiles.Insert( 0, ファイルパス ); // 一定以上は記録しない。 if( this.RecentUsedFiles.Count > this.MaxOfUsedRecentFiles ) { int 超えてる数 = this.RecentUsedFiles.Count - this.MaxOfUsedRecentFiles; for( int i = 超えてる数; i > 0; i-- ) this.RecentUsedFiles.RemoveAt( this.MaxOfUsedRecentFiles + i - 1 ); } } } } <|start_filename|>DTXMania2/ステージ/07演奏/エキサイトゲージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Animation; using FDK; namespace DTXMania2.演奏 { class エキサイトゲージ : IDisposable { // 生成と終了 public エキサイトゲージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ゲージ枠通常 = new 画像D2D( @"$(Images)\PlayStage\ExciteGauge.png" ); this._ゲージ枠DANGER = new 画像D2D( @"$(Images)\PlayStage\ExciteGauge_Danger.png" ); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; this._通常ブラシ = new SolidColorBrush( d2ddc, new Color4( 0xfff9b200 ) ); // ABGR this._DANGERブラシ = new SolidColorBrush( d2ddc, new Color4( 0xff0000ff ) ); this._MAXブラシ = new SolidColorBrush( d2ddc, new Color4( 0xff00c9f4 ) ); this._ゲージ量 = new Variable( Global.Animation.Manager, initialValue: 0 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ゲージ量のストーリーボード?.Dispose(); this._ゲージ量.Dispose(); this._MAXブラシ.Dispose(); this._DANGERブラシ.Dispose(); this._通常ブラシ.Dispose(); this._ゲージ枠DANGER.Dispose(); this._ゲージ枠通常.Dispose(); } // 進行と描画 /// <param name="ゲージ量"> /// 0~1。 0.0で0%、1.0で100%。 /// </param> public void 進行描画する( DeviceContext d2ddc, double ゲージ量 ) { ゲージ量 = Math.Clamp( ゲージ量, min: 0f, max: 1f ); var MAXゲージ領域 = new RectangleF( 557f, 971f, 628f, 26f ); #region " 枠を描画。" //---------------- if( 0.25 > this._ゲージ量.Value ) { this._ゲージ枠DANGER.描画する( d2ddc, 540f, 955f ); } else { this._ゲージ枠通常.描画する( d2ddc, 540f, 955f ); } //---------------- #endregion #region " ゲージの進行。ゲージ量のゴールが動くたび、アニメーションを開始して追従する。" //---------------- if( ゲージ量 != this._ゲージ量.FinalValue ) { this._ゲージ量のストーリーボード?.Dispose(); this._ゲージ量のストーリーボード = new Storyboard( Global.Animation.Manager ); using( var 移動遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 0.4, finalValue: ゲージ量 ) ) using( var 跳ね返り遷移1 = Global.Animation.TrasitionLibrary.Reversal( duration: 0.2 ) ) using( var 跳ね返り遷移2 = Global.Animation.TrasitionLibrary.Reversal( duration: 0.2 ) ) { this._ゲージ量のストーリーボード.AddTransition( this._ゲージ量, 移動遷移 ); this._ゲージ量のストーリーボード.AddTransition( this._ゲージ量, 跳ね返り遷移1 ); this._ゲージ量のストーリーボード.AddTransition( this._ゲージ量, 跳ね返り遷移2 ); } this._ゲージ量のストーリーボード.Schedule( Global.Animation.Timer.Time ); } //---------------- #endregion #region " ゲージの描画。" //---------------- { var ゲージ領域 = MAXゲージ領域; ゲージ領域.Width *= Math.Min( (float)this._ゲージ量.Value, 1.0f ); var ブラシ = ( 0.25 > this._ゲージ量.Value ) ? this._DANGERブラシ : ( 1.0 <= this._ゲージ量.Value ) ? this._MAXブラシ : this._通常ブラシ; d2ddc.FillRectangle( ゲージ領域, ブラシ ); } //---------------- #endregion } // ローカル private readonly 画像D2D _ゲージ枠通常; private readonly 画像D2D _ゲージ枠DANGER; private readonly SolidColorBrush _通常ブラシ; // 青 private readonly SolidColorBrush _DANGERブラシ; // 赤 private readonly SolidColorBrush _MAXブラシ; // 橙 private readonly Variable _ゲージ量; private Storyboard _ゲージ量のストーリーボード = null!; } } <|start_filename|>DTXMania2/保存データ/ScoreDB/old/v006_SongDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.old.SongDBRecord { class v006_SongDBRecord { // プロパティ public const int VERSION = 6; /// <summary> /// 曲譜面ファイルのハッシュ値。 /// 正確には一意じゃないけど、主キーとして扱う。 /// </summary> public string HashId { get; set; } /// <summary> /// 曲のタイトル。 /// </summary> public string Title { get; set; } /// <summary> /// 曲譜面ファイルへの絶対パス。 /// これも一意とする。(テーブル生成SQLで UNIQUE を付与している。) /// </summary> public string Path { get; set; } /// <summary> /// 曲譜面ファイルの最終更新時刻の文字列表記。 /// 文字列の書式は、System.DateTime.ToString("G") と同じ。(例: "08/17/2000 16:32:32") /// カルチャはシステム既定のものとする。 /// </summary> public string LastWriteTime { get; set; } /// <summary> /// 曲の難易度。0.00~9.99。 /// </summary> public double Level { get; set; } /// <summary> /// 最小BPM。null なら未取得。 /// </summary> public double? MinBPM { get; set; } /// <summary> /// 最大BPM。null なら未取得。 /// </summary> public double? MaxBPM { get; set; } /// <summary> /// 左シンバルの総ノーツ数。 /// </summary> public int TotalNotes_LeftCymbal { get; set; } /// <summary> /// ハイハットの総ノーツ数。 /// </summary> public int TotalNotes_HiHat { get; set; } /// <summary> /// 左ペダルまたは左バスの総ノーツ数。 /// </summary> public int TotalNotes_LeftPedal { get; set; } /// <summary> /// スネアの総ノーツ数。 /// </summary> public int TotalNotes_Snare { get; set; } /// <summary> /// バスの総ノーツ数。 /// </summary> public int TotalNotes_Bass { get; set; } /// <summary> /// ハイタムの総ノーツ数。 /// </summary> public int TotalNotes_HighTom { get; set; } /// <summary> /// ロータムの総ノーツ数。 /// </summary> public int TotalNotes_LowTom { get; set; } /// <summary> /// フロアタムの総ノーツ数。 /// </summary> public int TotalNotes_FloorTom { get; set; } /// <summary> /// 右シンバルの総ノーツ数。 /// </summary> public int TotalNotes_RightCymbal { get; set; } /// <summary> /// 曲のプレビュー画像。 /// 曲譜面ファイル(<see cref="Path"/>)からの相対パス。 /// </summary> public string PreImage { get; set; } /// <summary> /// 曲のアーティスト名。 /// </summary> public string Artist { get; set; } /// <summary> /// 曲のプレビュー音声ファイルのパス。 /// 曲譜面ファイル(<see cref="Path"/>)からの相対パス。 /// </summary> public string PreSound { get; set; } /// <summary> /// この曲のBGMの再生タイミングを、この時間[ms]分だけ前後にずらす。(負数で早める、正数で遅める) /// </summary> public int BGMAdjust { get; set; } /// <summary> /// テーブルのカラム部分を列挙したSQL。 /// </summary> public static readonly string ColumnList = @"( HashId NVARCHAR NOT NULL PRIMARY KEY" + @", Title NVARCHAR NOT NULL" + @", Path NVARCHAR NOT NULL UNIQUE" + @", LastWriteTime NVARCHAR NOT NULL" + @", Level NUMERIC NOT NULL" + @", MinBPM NUMERIC" + @", MaxBPM NUMERIC" + @", TotalNotes_LeftCymbal INTEGER NOT NULL" + @", TotalNotes_HiHat INTEGER NOT NULL" + @", TotalNotes_LeftPedal INTEGER NOT NULL" + @", TotalNotes_Snare INTEGER NOT NULL" + @", TotalNotes_Bass INTEGER NOT NULL" + @", TotalNotes_HighTom INTEGER NOT NULL" + @", TotalNotes_LowTom INTEGER NOT NULL" + @", TotalNotes_FloorTom INTEGER NOT NULL" + @", TotalNotes_RightCymbal INTEGER NOT NULL" + @", PreImage NVARCHAR" + @", Artist NVARCHAR" + @", PreSound NVARCHAR" + @", BGMAdjust INTEGER NOT NULL" + @")"; // 生成と終了 public v006_SongDBRecord() { this.HashId = ""; this.Title = "(no title)"; this.Path = ""; this.LastWriteTime = DateTime.Now.ToString( "G" ); this.Level = 5.00; this.MinBPM = null; this.MaxBPM = null; this.TotalNotes_LeftCymbal = 0; this.TotalNotes_HiHat = 0; this.TotalNotes_LeftPedal = 0; this.TotalNotes_Snare = 0; this.TotalNotes_Bass = 0; this.TotalNotes_HighTom = 0; this.TotalNotes_LowTom = 0; this.TotalNotes_FloorTom = 0; this.TotalNotes_RightCymbal = 0; this.PreImage = ""; this.Artist = ""; this.PreSound = ""; this.BGMAdjust = 0; } public v006_SongDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "HashId": this.HashId = record.GetString( i ); break; case "Title": this.Title = record.GetString( i ); break; case "Path": this.Path = record.GetString( i ); break; case "LastWriteTime": this.LastWriteTime = record.GetString( i ); break; case "MinBPM": this.MinBPM = record.GetDouble( i ); break; case "MaxBPM": this.MaxBPM = record.GetDouble( i ); break; case "TotalNotes_LeftCymbal": this.TotalNotes_LeftCymbal = record.GetInt32( i ); break; case "TotalNotes_HiHat": this.TotalNotes_HiHat = record.GetInt32( i ); break; case "TotalNotes_LeftPedal": this.TotalNotes_LeftPedal = record.GetInt32( i ); break; case "TotalNotes_Snare": this.TotalNotes_Snare = record.GetInt32( i ); break; case "TotalNotes_Bass": this.TotalNotes_Bass = record.GetInt32( i ); break; case "TotalNotes_HighTom": this.TotalNotes_HighTom = record.GetInt32( i ); break; case "TotalNotes_LowTom": this.TotalNotes_LowTom = record.GetInt32( i ); break; case "TotalNotes_FloorTom": this.TotalNotes_FloorTom = record.GetInt32( i ); break; case "TotalNotes_RightCymbal": this.TotalNotes_RightCymbal = record.GetInt32( i ); break; case "PreImage": this.PreImage = record.GetString( i ); break; case "Artist": this.Artist = record.GetString( i ); break; case "PreSound": this.PreSound = record.GetString( i ); break; case "BGMAdjust": this.BGMAdjust = record.GetInt32( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public void ReplaceTo( SQLiteDB db ) { using var cmd = new SqliteCommand( "REPLACE INTO Records VALUES(" + $"'{this.HashId}'," + $"'{this.Title}'," + $"'{this.Path}'," + $"'{this.LastWriteTime}'," + $"{this.Level}," + $"{this.MinBPM}," + $"{this.MaxBPM}," + $"{this.TotalNotes_LeftCymbal}," + $"{this.TotalNotes_HiHat}," + $"{this.TotalNotes_LeftPedal}," + $"{this.TotalNotes_Snare}," + $"{this.TotalNotes_Bass}," + $"{this.TotalNotes_HighTom}," + $"{this.TotalNotes_LowTom}," + $"{this.TotalNotes_FloorTom}," + $"{this.TotalNotes_RightCymbal}," + $"'{this.PreImage}'," + $"'{this.Artist}'," + $"'{this.PreSound}'," + $"{this.BGMAdjust}" + ")", db.Connection ); cmd.ExecuteNonQuery(); } } } <|start_filename|>DTXMania2/ステージ/07演奏/判定パラメータ表示.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class 判定パラメータ表示 : IDisposable { // 生成と終了 public 判定パラメータ表示() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.パラメータ文字 = new フォント画像D2D( @"$(Images)\ParameterFont_Small.png", @"$(Images)\ParameterFont_Small.yaml" ); this._判定種別文字 = new 画像D2D( @"$(Images)\PlayStage\JudgeLabelForParameter.png" ); this.判定種別文字の矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\JudgeLabelForParameter.yaml" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._判定種別文字.Dispose(); this.パラメータ文字.Dispose(); } // 進行と描画 public virtual void 進行描画する( DeviceContext d2ddc, float x, float y, 成績 現在の成績 ) { var scaling = new Size2F( 1.0f, 1.4f ); var 判定別ヒット数 = 現在の成績.判定別ヒット数; var 割合表 = 現在の成績.判定別ヒット割合; int MaxCombo = 現在の成績.MaxCombo; int 合計 = 0; this.パラメータを一行描画する( d2ddc, x, y, scaling, 判定種別.PERFECT, 判定別ヒット数[ 判定種別.PERFECT ], 割合表[ 判定種別.PERFECT ] ); 合計 += 判定別ヒット数[ 判定種別.PERFECT ]; y += _改行幅dpx; this.パラメータを一行描画する( d2ddc, x, y, scaling, 判定種別.GREAT, 判定別ヒット数[ 判定種別.GREAT ], 割合表[ 判定種別.GREAT ] ); 合計 += 判定別ヒット数[ 判定種別.GREAT ]; y += _改行幅dpx; this.パラメータを一行描画する( d2ddc, x, y, scaling, 判定種別.GOOD, 判定別ヒット数[ 判定種別.GOOD ], 割合表[ 判定種別.GOOD ] ); 合計 += 判定別ヒット数[ 判定種別.GOOD ]; y += _改行幅dpx; this.パラメータを一行描画する( d2ddc, x, y, scaling, 判定種別.OK, 判定別ヒット数[ 判定種別.OK ], 割合表[ 判定種別.OK ] ); 合計 += 判定別ヒット数[ 判定種別.OK ]; y += _改行幅dpx; this.パラメータを一行描画する( d2ddc, x, y, scaling, 判定種別.MISS, 判定別ヒット数[ 判定種別.MISS ], 割合表[ 判定種別.MISS ] ); 合計 += 判定別ヒット数[ 判定種別.MISS ]; y += _改行幅dpx; y += 3f; // ちょっと間を開けて var 矩形 = this.判定種別文字の矩形リスト[ "MaxCombo" ]!; this._判定種別文字.描画する( d2ddc, x, y, 転送元矩形: 矩形, X方向拡大率: scaling.Width, Y方向拡大率: scaling.Height ); x += 矩形.Value.Width + 16f; this.数値を描画する( d2ddc, x, y, scaling, MaxCombo, 桁数: 4 ); this.数値を描画する( d2ddc, x + _dr, y, scaling, (int)Math.Floor( 100.0 * MaxCombo / 合計 ), 桁数: 3 ); // 切り捨てでいいやもう this.パラメータ文字.描画する( d2ddc, x + _dp, y, "%", scaling ); } // ローカル protected const float _dr = 78f; // 割合(%)までのXオフセット[dpx] protected const float _dp = 131f; // "%" 文字までのXオフセット[dpx] protected const float _改行幅dpx = 40f; protected readonly フォント画像D2D パラメータ文字; protected readonly 画像D2D _判定種別文字; protected readonly 矩形リスト 判定種別文字の矩形リスト; protected void パラメータを一行描画する( DeviceContext d2ddc, float x, float y, Size2F 拡大率, 判定種別 judge, int ヒット数, int ヒット割合, float 不透明度 = 1.0f ) { var 矩形 = this.判定種別文字の矩形リスト[ judge.ToString() ]!; this._判定種別文字.描画する( d2ddc, x, y - 4f, 不透明度, 転送元矩形: 矩形, X方向拡大率: 拡大率.Width, Y方向拡大率: 拡大率.Height ); x += 矩形.Value.Width + 16f; this.数値を描画する( d2ddc, x, y, 拡大率, ヒット数, 4, 不透明度 ); this.数値を描画する( d2ddc, x + _dr * 拡大率.Width, y, 拡大率, ヒット割合, 3, 不透明度 ); this.パラメータ文字.不透明度 = 不透明度; this.パラメータ文字.描画する( d2ddc, x + _dp * 拡大率.Width, y, "%", 拡大率 ); } protected void 数値を描画する( DeviceContext d2ddc, float x, float y, Size2F 拡大率, int 描画する数値, int 桁数, float 不透明度 = 1.0f ) { Debug.Assert( 1 <= 桁数 && 10 >= 桁数 ); // 最大10桁まで int 最大値 = (int)Math.Pow( 10, 桁数 ) - 1; // 1桁なら9, 2桁なら99, 3桁なら999, ... でカンスト。 int 判定数 = Math.Clamp( 描画する数値, min: 0, max: 最大値 ); // 丸める。 var 判定数文字列 = 判定数.ToString().PadLeft( 桁数 ).Replace( ' ', 'o' ); // グレーの '0' は 'o' で描画できる(矩形リスト参照)。 this.パラメータ文字.不透明度 = 不透明度; this.パラメータ文字.描画する( d2ddc, x, y, 判定数文字列, 拡大率 ); } } } <|start_filename|>DTXMania2/イメージ/LoadingSpinner.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { /// <summary> /// ローディングスピナー(回転画像アニメーション)。 /// </summary> class LoadingSpinner : IDisposable { const int _回転段数 = 9; // 生成と終了 public LoadingSpinner() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._Spinner画像 = new 画像D2D( @"$(Images)\LoadingSpinner.png" ); this._回転カウンタ = new LoopCounter( 0, _回転段数, 100 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._Spinner画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { var count = this._回転カウンタ.現在値; // 0~_回転段数-1 var 変換行列2D = Matrix3x2.Rotation( angle: (float)( 2.0 * Math.PI * ( (double)count / _回転段数 ) ), center: new Vector2( this._Spinner画像.サイズ.Width / 2f, this._Spinner画像.サイズ.Height / 2f ) ) * Matrix3x2.Translation( ( Global.GraphicResources.設計画面サイズ.Width - this._Spinner画像.サイズ.Width ) / 2f, ( Global.GraphicResources.設計画面サイズ.Height - this._Spinner画像.サイズ.Height ) / 2f ); this._Spinner画像.描画する( d2ddc, 変換行列2D ); } // ローカル private readonly 画像D2D _Spinner画像; private readonly LoopCounter _回転カウンタ; } } <|start_filename|>DTXMania2/ステージ/08結果/ランク.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX.Direct2D1; using FDK; using System.Threading; namespace DTXMania2.結果 { class ランク : IDisposable { // 生成と終了 public ランク() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ランクエフェクト = new Dictionary<ランク種別, EffekseerNET.Effect>() { { ランク種別.SS, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankSS.efkefc" ).変数なしパス ) }, { ランク種別.S, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankS.efkefc" ).変数なしパス ) }, { ランク種別.A, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankA.efkefc" ).変数なしパス ) }, { ランク種別.B, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankB.efkefc" ).変数なしパス ) }, { ランク種別.C, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankC.efkefc" ).変数なしパス ) }, { ランク種別.D, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankD.efkefc" ).変数なしパス ) }, { ランク種別.E, EffekseerNET.Effect.Create( Global.Effekseer.Manager, new VariablePath( @"$(Images)\ResultStage\rankE.efkefc" ).変数なしパス ) }, }; this._エフェクト開始イベント = new ManualResetEventSlim( false ); this._初めての進行描画 = true; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( 0 <= this._ランクエフェクトハンドル ) { Global.Effekseer.Manager.StopEffect( this._ランクエフェクトハンドル ); Global.Effekseer.Manager.SetShown( this._ランクエフェクトハンドル, false ); } this._エフェクト開始タイマ?.Dispose(); this._エフェクト開始イベント?.Dispose(); //foreach( var rankEffect in this._ランクエフェクト.Values ) // rankEffect.Dispose(); --> 不要 } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, ランク種別 rank ) { if( this._初めての進行描画 ) { this._初めての進行描画 = false; this._Rank = rank; // 0.6 秒後にエフェクト開始 this._エフェクト開始タイマ = new Timer( ( state ) => { this._エフェクト開始イベント.Set(); }, null, 600, Timeout.Infinite ); } if( 0 > this._ランクエフェクトハンドル ) { if( this._エフェクト開始イベント.IsSet ) { this._ランクエフェクトを開始する(); this._エフェクト開始イベント.Reset(); } } else { d2ddc.EndDraw(); // D2D中断 Global.Effekseer.描画する( this._ランクエフェクトハンドル ); d2ddc.BeginDraw(); // D2D再開 } } public void アニメを完了する() { this._エフェクト開始イベント.Set(); } private void _ランクエフェクトを開始する() { // エフェクトの再生を開始してハンドルを受け取る。 this._ランクエフェクトハンドル = Global.Effekseer.Manager.Play( this._ランクエフェクト[ this._Rank ], -4.5f, 0.4f, -0f ); // 少しだけ前傾させる。 Global.Effekseer.Manager.SetRotation( this._ランクエフェクトハンドル, new EffekseerNET.Vector3D( 1, 0, 0 ), 0.2f ); } // ローカル private readonly Dictionary<ランク種別, EffekseerNET.Effect> _ランクエフェクト; private int _ランクエフェクトハンドル = -1; private ManualResetEventSlim _エフェクト開始イベント = null!; private Timer _エフェクト開始タイマ = null!; private ランク種別 _Rank; private bool _初めての進行描画; } } <|start_filename|>FDK/ビデオ/Sources/MediaFoundationFileVideoSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using SharpDX; using SharpDX.Direct2D1; using SharpDX.MediaFoundation; namespace FDK { /// <summary> /// 動画ファイルのビデオストリームを MediaFoundation でデコードしフレームを生成するビデオソース。 /// </summary> public class MediaFoundationFileVideoSource : IVideoSource { // プロパティ /// <summary> /// ビデオの長さ[秒]。再生速度考慮済み。 /// </summary> /// <remarks> /// 再生速度は考慮済みなので、例えば再生速度が x0.5 である場合、総演奏時間はオリジナルの2倍になる。 /// </remarks> public double 総演奏時間sec { get; protected set; } public Size2F フレームサイズ { get; protected set; } public bool ループ再生する { get; set; } = false; public double 再生速度 { get; protected set; } = 1.0; /// <summary> /// ビデオが再生中(デコーダタスクが稼働中)ならtrue。 /// 一時停止中であってもtrue。 /// </summary> public bool IsPlaying => ( this._デコードタスク != null && !this._デコードタスク.IsCompleted ); // 生成と終了 public MediaFoundationFileVideoSource( DXGIDeviceManager deviceManager, DeviceContext d2dDeviceContext, VariablePath ファイルパス, double 再生速度 = 1.0 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._D2DDeviceContext = d2dDeviceContext; this.再生速度 = Math.Clamp( 再生速度, min: 0.01, max: 10.0 ); #region " フレームキューを生成。" //---------------- // キューサイズは3フレームとする。 this._FrameQueue = new BlockingQueue<VideoFrame>( 3 ); //---------------- #endregion #region " ファイルから SourceReaderEx を生成する。" //---------------- using( var ビデオ属性 = new MediaAttributes() ) { // DXVAに対応しているGPUの場合には、それをデコードに利用するよう指定する。 ビデオ属性.Set( SourceReaderAttributeKeys.D3DManager, deviceManager ); // 追加のビデオプロセッシングを有効にする。 ビデオ属性.Set( SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, true ); // 真偽値が bool だったり // 追加のビデオプロセッシングを有効にしたら、こちらは無効に。 ビデオ属性.Set( SinkWriterAttributeKeys.ReadwriteDisableConverters, 0 ); // int だったり // 属性を使って、SourceReaderEx を生成。 using var sourceReader = new SourceReader( ファイルパス.変数なしパス, ビデオ属性 ); // パスは URI 扱い this._SourceReaderEx = sourceReader.QueryInterface<SourceReaderEx>(); } // 最初のビデオストリームだけを選択。 this._SourceReaderEx.SetStreamSelection( SourceReaderIndex.AllStreams, false ); this._SourceReaderEx.SetStreamSelection( SourceReaderIndex.FirstVideoStream, true ); //---------------- #endregion #region " ビデオの長さ(総演奏時間)を取得する。" //---------------- { var mediaSourceDuration = this._SourceReaderEx.GetPresentationAttribute( SourceReaderIndex.MediaSource, PresentationDescriptionAttributeKeys.Duration ); this.総演奏時間sec = (long)( mediaSourceDuration / this.再生速度 / 10_000_000.0 ); } //---------------- #endregion #region " デコーダを選択し、完全メディアタイプを取得する。" //---------------- // 部分メディアタイプを設定する。 using( var 部分MediaType = new MediaType() ) { // フォーマットは ARGB32 で固定とする。(SourceReaderEx を使わない場合、H264 では ARGB32 が選べないので注意。) 部分MediaType.Set( MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video ); 部分MediaType.Set( MediaTypeAttributeKeys.Subtype, VideoFormatGuids.Argb32 ); // 部分メディアタイプを SourceReaderEx にセットする。SourceReaderEx は、必要なデコーダをロードするだろう。 this._SourceReaderEx.SetCurrentMediaType( SourceReaderIndex.FirstVideoStream, 部分MediaType ); } // 完成されたメディアタイプを取得する。 this._MediaType = this._SourceReaderEx.GetCurrentMediaType( SourceReaderIndex.FirstVideoStream ); //---------------- #endregion #region " ビデオのフレームサイズを取得する。(動画の途中でのサイズ変更は考慮しない。)" //---------------- long packedFrameSize = this._MediaType.Get( MediaTypeAttributeKeys.FrameSize ); this.フレームサイズ = new Size2F( ( packedFrameSize >> 32 ) & 0xFFFFFFFF, ( packedFrameSize ) & 0xFFFFFFFF ); //---------------- #endregion this._デコードキャンセル = new CancellationTokenSource(); this._デコード起動完了通知 = new ManualResetEventSlim( false ); this._一時停止解除通知 = new ManualResetEventSlim( true ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); // デコードを停止。 this.Stop(); this._デコードキャンセル?.Dispose(); this._FrameQueue?.Dispose(); this._MediaType?.Dispose(); this._SourceReaderEx?.Dispose(); } // 再生、停止 /// <summary> /// 指定した時刻からデコードを開始する。 /// </summary> /// <param name="再生開始時刻sec">再生開始時刻[秒]。再生速度を考慮済みであること。</param> public void Start( double 再生開始時刻sec ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( 再生開始時刻sec >= this.総演奏時間sec ) return; this._デコード起動完了通知.Reset(); this._一時停止解除通知.Set(); // (1) デコードタスク起動、デコード開始。 this._デコードタスク = Task.Factory.StartNew( // Task.Factory.StartNew は常に MTAThread this._デコードタスクエントリ, 再生開始時刻sec, this._デコードキャンセル.Token ); // (2) デコードから起動完了通知がくるまでブロック。 this._デコード起動完了通知.Wait(); } /// <summary> /// デコードを終了する。 /// </summary> public void Stop() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( ( null != this._デコードタスク ) && !( this._デコードタスク.IsCompleted ) ) // デコードタスク起動中? { // (1) デコードタスクにキャンセルを通知。 this._デコードキャンセル.Cancel(); // (2) デコードタスクがキューでブロックしてたら解除する。 this._FrameQueue.Cancel(); // (3) デコードタスクが一時停止中でブロックしてたら解除する。 this._一時停止解除通知.Set(); // (4) デコードタスクが終了するまで待つ。 if( !( this._デコードタスク.Wait( 5000 ) ) ) // 最大5秒 Log.ERROR( $"デコードタスクの終了がタイムアウトしました。" ); this._デコードタスク = null; } } /// <summary> /// デコードを一時停止する。 /// </summary> public void Pause() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._一時停止解除通知.Reset(); } /// <summary> /// デコードを再開する。 /// <see cref="Pause"/>で停止しているときのみ有効。 /// </summary> public void Resume() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._一時停止解除通知.Set(); // 解除 } // サンプル取得 /// <summary> /// 次に読みだされるフレームがあれば、その表示予定時刻[100ns単位]を返す。 /// フレームがなければ、ブロックせずにすぐ 負数 を返す。 /// </summary> public long Peek() { this._FrameQueue.Peek( out VideoFrame? frame ); return frame?.表示時刻100ns ?? -1; } /// <summary> /// フレームを1つ読みだす。 /// 再生中の場合、フレームが取得できるまでブロックする。 /// 再生が終了している場合は null を返す。 /// 取得したフレームは、使用が終わったら、呼び出し元で Dispose すること。 /// </summary> public VideoFrame? Read() { return this._FrameQueue.Take(); } /// <summary> /// MediaFoundation のビデオサンプルを D2DBitmap に変換して返す。 /// </summary> public unsafe Bitmap サンプルからビットマップを取得する( Sample sample ) { // 1. Sample → MediaBuffer using var mediaBuffer = sample.ConvertToContiguousBuffer(); // 2. MediaBuffer → DXGIBuffer using var dxgiBuffer = mediaBuffer.QueryInterface<DXGIBuffer>(); // 3. DXGIBuffer → DXGISurface(IntPtr) dxgiBuffer.GetResource( typeof( SharpDX.DXGI.Surface ).GUID, out IntPtr vDxgiSurface ); // 4. DXGISurface(IntPtr) → DXGISurface using var dxgiSurface = new SharpDX.DXGI.Surface( vDxgiSurface ); // 5. DXGISurface → Bitmap return new Bitmap( this._D2DDeviceContext, dxgiSurface, new BitmapProperties( new PixelFormat( dxgiSurface.Description.Format, AlphaMode.Ignore ) ) ); } // ローカル /// <summary> /// デコードされたビデオフレームを格納しておくキュー。 /// </summary> private readonly BlockingQueue<VideoFrame> _FrameQueue; private readonly MediaType _MediaType; private readonly SourceReaderEx _SourceReaderEx; private readonly DeviceContext _D2DDeviceContext; // デコード関連 private Task? _デコードタスク = null; private readonly CancellationTokenSource _デコードキャンセル; private readonly ManualResetEventSlim _デコード起動完了通知; private readonly ManualResetEventSlim _一時停止解除通知; private void _デコードタスクエントリ( object? obj引数 ) { Log.現在のスレッドに名前をつける( "ビデオデコード" ); Log.Info( "デコードタスクを開始します。" ); if( obj引数 is null ) { Log.ERROR( "引数が指定されていません。" ); return; } double 再生開始時刻sec = Math.Max( 0.0, (double)obj引数 ); // 再生速度考慮済み long 再生開始時刻100ns = (long)( 再生開始時刻sec * 10_000_000 + 0.5 ); #region " 再生開始時刻までシーク(1)。" //---------------- if( 0.0 < 再生開始時刻sec ) { if( this.総演奏時間sec <= 再生開始時刻sec ) { Log.Info( $"再生開始時刻が総演奏時間を超えています。タスクを終了します。" ); return; } // SourceReader には、再生速度を考慮しない時刻に戻して指定する必要がある。 // なお、再生開始時刻 が 0 ならこれを呼び出さないこと(ガタつきの原因になるため)。 this._SourceReaderEx.SetCurrentPosition( (long)( 再生開始時刻100ns * this.再生速度 ) ); } //---------------- #endregion // シーク(1)では、SetCurrentPosition() の仕様により、「指定された位置を超えない一番近いキーフレーム」までしか移動できない。 // なので、残りのシーク(キーフレームから再生開始時刻まで)を、メインループ内で引き続き行う。 // (残りのシークが終わって、ようやく デコード起動完了通知 がセットされる。) bool シーク中である = ( 0.0 < 再生開始時刻sec ); if( !シーク中である ) this._デコード起動完了通知.Set(); // シーク(2)はしない // メインループ。 while( true ) { // キャンセル通知があれば、ループを抜けてタスクを終了。 if( this._デコードキャンセル.Token.IsCancellationRequested ) { Log.Info( $"キャンセル通知を受信しました。" ); break; } // 一時停止中なら、解除通知がくるまでここでタスクをブロック。 this._一時停止解除通知.Wait(); if( !this._サンプルをひとつデコードしてフレームをキューへ格納する( 再生速度 ) ) break; // エラーまたは再生終了 if( シーク中である ) { #region " 再生開始時刻までシーク(2)。" //---------------- var frame = this._FrameQueue.Peek(); // 今格納されたフレームを参照 if( frame is null || frame.表示時刻100ns >= 再生開始時刻100ns ) { // シーク終了;今回のフレームから再生の対象(なのでTakeしない)。 シーク中である = false; // シークが終わったので、呼び出し元に起動完了を通知する。 this._デコード起動完了通知.Set(); } else { // 取り出して、すぐに破棄。 frame = this._FrameQueue.Take(); frame?.Dispose(); } //---------------- #endregion } } Log.Info( $"デコードタスクを終了します。" ); } /// <returns> /// 格納できた場合は true、エラーあるいは再生終了なら false。 /// </returns> private bool _サンプルをひとつデコードしてフレームをキューへ格納する( double 再生速度 ) { // SourceReaderEx から次のサンプルをひとつデコードする。 var サンプル = this._SourceReaderEx.ReadSample( SourceReaderIndex.FirstVideoStream, SourceReaderControlFlags.None, out int ストリーム番号, out var ストリームフラグ, out long サンプルの表示時刻100ns ); if( ストリームフラグ.HasFlag( SourceReaderFlags.Endofstream ) ) { Log.Info( $"ストリームが終了しました。" ); if( this.ループ再生する ) // ループするなら、 { Log.Info( $"ループ再生します。" ); this._SourceReaderEx.SetCurrentPosition( 0 ); // 先頭に戻って return _サンプルをひとつデコードしてフレームをキューへ格納する( 再生速度 ); // もう一回。 } else { return false; // ループしないなら再生終了 } } if( ストリームフラグ.HasFlag( SourceReaderFlags.Error ) || ストリームフラグ.HasFlag( SourceReaderFlags.AllEffectsremoved ) || //ストリームフラグ.HasFlag( SourceReaderFlags.Currentmediatypechanged ) || ストリームフラグ.HasFlag( SourceReaderFlags.Nativemediatypechanged ) || ストリームフラグ.HasFlag( SourceReaderFlags.Newstream ) || ストリームフラグ.HasFlag( SourceReaderFlags.StreamTick ) ) { Log.ERROR( $"デコード中にエラーが発生または未対応の状態変化が発生しました。" ); return false; // エラー } // ビデオフレームを生成してキューに格納する。 this._FrameQueue.Add( // キューがいっぱいなら、キューが空くまでブロックするので注意。 new VideoFrame() { Sample = サンプル, Bitmap = this.サンプルからビットマップを取得する( サンプル ), 表示時刻100ns = (long)( サンプルの表示時刻100ns / 再生速度 ), } ); return true; // 格納した } } } <|start_filename|>DTXMania2/ステージ/07演奏/ドラムチッププロパティリスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2.演奏 { class ドラムチッププロパティリスト { // プロパティ /// <summary> /// チップ種別をキーとする対応表。 /// </summary> public Dictionary<SSTF.チップ種別, ドラムチッププロパティ> チップtoプロパティ { get; protected set; } /// <summary> /// インデクサによるプロパティの取得。 /// </summary> public ドラムチッププロパティ this[ SSTF.チップ種別 chipType ] => this.チップtoプロパティ[ chipType ]; public 表示レーンの左右 表示レーンの左右 { get; protected set; } public 入力グループプリセット種別 入力グループプリセット種別 { get; protected set; } // 生成と終了 public ドラムチッププロパティリスト( 表示レーンの左右 表示レーンの左右, 入力グループプリセット種別 入力グループプリセット種別 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this.表示レーンの左右 = 表示レーンの左右; this.入力グループプリセット種別 = 入力グループプリセット種別; this.チップtoプロパティ = new Dictionary<SSTF.チップ種別, ドラムチッププロパティ>() { // ※以下、コメントアウト(=...)されている初期化子は、後で 反映する() メソッドを呼び出して設定される。 #region " チップ種別.Unknown " //---------------- [ SSTF.チップ種別.Unknown ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Unknown, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = false, AutoPlayON_自動ヒット_非表示 = false, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.LeftCrash " //---------------- [ SSTF.チップ種別.LeftCrash ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.LeftCrash, レーン種別 = SSTF.レーン種別.LeftCrash, 表示レーン種別 = 表示レーン種別.LeftCymbal, 表示チップ種別 = 表示チップ種別.LeftCymbal, ドラム入力種別 = ドラム入力種別.LeftCrash, AutoPlay種別 = AutoPlay種別.LeftCrash, //入力グループ種別 = ... 発声前消音 = false, 消音グループ種別 = 消音グループ種別.LeftCymbal, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Ride " //---------------- [ SSTF.チップ種別.Ride ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Ride, レーン種別 = SSTF.レーン種別.Ride, //表示レーン種別 = ... 表示チップ種別 = ( this.表示レーンの左右.Rideは左 ) ? 表示チップ種別.LeftRide : 表示チップ種別.RightRide, ドラム入力種別 = ドラム入力種別.Ride, //AutoPlay種別 = ... //入力グループ種別 = ... 発声前消音 = false, //消音グループ種別 = ... AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Ride_Cup " //---------------- [ SSTF.チップ種別.Ride_Cup ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Ride_Cup, レーン種別 = SSTF.レーン種別.Ride, //表示レーン種別 = ... 表示チップ種別 = ( this.表示レーンの左右.Rideは左 ) ? 表示チップ種別.LeftRide_Cup : 表示チップ種別.RightRide_Cup, ドラム入力種別 = ドラム入力種別.Ride, //AutoPlay種別 = ... //入力グループ種別 = ... 発声前消音 = false, //消音グループ種別 = ... AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.China " //---------------- [ SSTF.チップ種別.China ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.China, レーン種別 = SSTF.レーン種別.China, //表示レーン種別 = ... 表示チップ種別 = ( this.表示レーンの左右.Chinaは左 ) ? 表示チップ種別.LeftChina : 表示チップ種別.RightChina, ドラム入力種別 = ドラム入力種別.China, //AutoPlay種別 = ... //入力グループ種別 = ... 発声前消音 = false, //消音グループ種別 = ... AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Splash " //---------------- [ SSTF.チップ種別.Splash ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Splash, レーン種別 = SSTF.レーン種別.Splash, //表示レーン種別 = ... 表示チップ種別 = ( this.表示レーンの左右.Splashは左 ) ? 表示チップ種別.LeftSplash : 表示チップ種別.RightSplash, ドラム入力種別 = ドラム入力種別.Splash, //AutoPlay種別 = ... //入力グループ種別 = ... 発声前消音 = false, //消音グループ種別 = ... AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.HiHat_Open " //---------------- [ SSTF.チップ種別.HiHat_Open ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.HiHat_Open, レーン種別 = SSTF.レーン種別.HiHat, 表示レーン種別 = 表示レーン種別.HiHat, 表示チップ種別 = 表示チップ種別.HiHat_Open, ドラム入力種別 = ドラム入力種別.HiHat_Open, AutoPlay種別 = AutoPlay種別.HiHat, 入力グループ種別 = 入力グループ種別.HiHat, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.HiHat, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.HiHat_HalfOpen " //---------------- [ SSTF.チップ種別.HiHat_HalfOpen ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.HiHat_HalfOpen, レーン種別 = SSTF.レーン種別.HiHat, 表示レーン種別 = 表示レーン種別.HiHat, 表示チップ種別 = 表示チップ種別.HiHat_HalfOpen, ドラム入力種別 = ドラム入力種別.HiHat_Open, AutoPlay種別 = AutoPlay種別.HiHat, 入力グループ種別 = 入力グループ種別.HiHat, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.HiHat, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.HiHat_Close " //---------------- [ SSTF.チップ種別.HiHat_Close ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.HiHat_Close, レーン種別 = SSTF.レーン種別.HiHat, 表示レーン種別 = 表示レーン種別.HiHat, 表示チップ種別 = 表示チップ種別.HiHat, ドラム入力種別 = ドラム入力種別.HiHat_Close, AutoPlay種別 = AutoPlay種別.HiHat, 入力グループ種別 = 入力グループ種別.HiHat, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.HiHat, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.HiHat_Foot " //---------------- [ SSTF.チップ種別.HiHat_Foot ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.HiHat_Foot, レーン種別 = SSTF.レーン種別.Foot, 表示レーン種別 = 表示レーン種別.Foot, 表示チップ種別 = 表示チップ種別.Foot, ドラム入力種別 = ドラム入力種別.HiHat_Foot, AutoPlay種別 = AutoPlay種別.Foot, 入力グループ種別 = 入力グループ種別.HiHat, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.HiHat, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.Snare " //---------------- [ SSTF.チップ種別.Snare ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Snare, レーン種別 = SSTF.レーン種別.Snare, 表示レーン種別 = 表示レーン種別.Snare, 表示チップ種別 = 表示チップ種別.Snare, ドラム入力種別 = ドラム入力種別.Snare, AutoPlay種別 = AutoPlay種別.Snare, 入力グループ種別 = 入力グループ種別.Snare, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Snare_OpenRim " //---------------- [ SSTF.チップ種別.Snare_OpenRim ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Snare_OpenRim, レーン種別 = SSTF.レーン種別.Snare, 表示レーン種別 = 表示レーン種別.Snare, 表示チップ種別 = 表示チップ種別.Snare_OpenRim, ドラム入力種別 = ドラム入力種別.Snare_OpenRim, AutoPlay種別 = AutoPlay種別.Snare, 入力グループ種別 = 入力グループ種別.Snare, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Snare_ClosedRim " //---------------- [ SSTF.チップ種別.Snare_ClosedRim ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Snare_ClosedRim, レーン種別 = SSTF.レーン種別.Snare, 表示レーン種別 = 表示レーン種別.Snare, 表示チップ種別 = 表示チップ種別.Snare_ClosedRim, ドラム入力種別 = ドラム入力種別.Snare_ClosedRim, AutoPlay種別 = AutoPlay種別.Snare, 入力グループ種別 = 入力グループ種別.Snare, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Snare_Ghost " //---------------- [ SSTF.チップ種別.Snare_Ghost ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Snare_Ghost, レーン種別 = SSTF.レーン種別.Snare, 表示レーン種別 = 表示レーン種別.Snare, 表示チップ種別 = 表示チップ種別.Snare_Ghost, ドラム入力種別 = ドラム入力種別.Snare, AutoPlay種別 = AutoPlay種別.Snare, 入力グループ種別 = 入力グループ種別.Snare, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.Bass " //---------------- [ SSTF.チップ種別.Bass ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Bass, レーン種別 = SSTF.レーン種別.Bass, 表示レーン種別 = 表示レーン種別.Bass, 表示チップ種別 = 表示チップ種別.Bass, ドラム入力種別 = ドラム入力種別.Bass, AutoPlay種別 = AutoPlay種別.Bass, 入力グループ種別 = 入力グループ種別.Bass, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.LeftBass " //---------------- [ SSTF.チップ種別.LeftBass ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.LeftBass, レーン種別 = SSTF.レーン種別.Bass, 表示レーン種別 = 表示レーン種別.Bass, 表示チップ種別 = 表示チップ種別.Bass, ドラム入力種別 = ドラム入力種別.Bass, AutoPlay種別 = AutoPlay種別.Bass, //入力グループ種別 = 入力グループ種別.Bass, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Tom1 " //---------------- [ SSTF.チップ種別.Tom1 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Tom1, レーン種別 = SSTF.レーン種別.Tom1, 表示レーン種別 = 表示レーン種別.Tom1, 表示チップ種別 = 表示チップ種別.Tom1, ドラム入力種別 = ドラム入力種別.Tom1, AutoPlay種別 = AutoPlay種別.Tom1, 入力グループ種別 = 入力グループ種別.Tom1, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Tom1_Rim " //---------------- [ SSTF.チップ種別.Tom1_Rim ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Tom1_Rim, レーン種別 = SSTF.レーン種別.Tom1, 表示レーン種別 = 表示レーン種別.Tom1, 表示チップ種別 = 表示チップ種別.Tom1_Rim, ドラム入力種別 = ドラム入力種別.Tom1_Rim, AutoPlay種別 = AutoPlay種別.Tom1, 入力グループ種別 = 入力グループ種別.Tom1, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Tom2 " //---------------- [ SSTF.チップ種別.Tom2 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Tom2, レーン種別 = SSTF.レーン種別.Tom2, 表示レーン種別 = 表示レーン種別.Tom2, 表示チップ種別 = 表示チップ種別.Tom2, ドラム入力種別 = ドラム入力種別.Tom2, AutoPlay種別 = AutoPlay種別.Tom2, 入力グループ種別 = 入力グループ種別.Tom2, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Tom2_Rim " //---------------- [ SSTF.チップ種別.Tom2_Rim ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Tom2_Rim, レーン種別 = SSTF.レーン種別.Tom2, 表示レーン種別 = 表示レーン種別.Tom2, 表示チップ種別 = 表示チップ種別.Tom2_Rim, ドラム入力種別 = ドラム入力種別.Tom2_Rim, AutoPlay種別 = AutoPlay種別.Tom2, 入力グループ種別 = 入力グループ種別.Tom2, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Tom3 " //---------------- [ SSTF.チップ種別.Tom3 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Tom3, レーン種別 = SSTF.レーン種別.Tom3, 表示レーン種別 = 表示レーン種別.Tom3, 表示チップ種別 = 表示チップ種別.Tom3, ドラム入力種別 = ドラム入力種別.Tom3, AutoPlay種別 = AutoPlay種別.Tom3, 入力グループ種別 = 入力グループ種別.Tom3, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.Tom3_Rim " //---------------- [ SSTF.チップ種別.Tom3_Rim ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.Tom3_Rim, レーン種別 = SSTF.レーン種別.Tom3, 表示レーン種別 = 表示レーン種別.Tom3, 表示チップ種別 = 表示チップ種別.Tom3_Rim, ドラム入力種別 = ドラム入力種別.Tom3_Rim, AutoPlay種別 = AutoPlay種別.Tom3, 入力グループ種別 = 入力グループ種別.Tom3, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.RightCrash " //---------------- [ SSTF.チップ種別.RightCrash ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.RightCrash, レーン種別 = SSTF.レーン種別.RightCrash, 表示レーン種別 = 表示レーン種別.RightCymbal, 表示チップ種別 = 表示チップ種別.RightCymbal, ドラム入力種別 = ドラム入力種別.RightCrash, AutoPlay種別 = AutoPlay種別.RightCrash, //入力グループ種別 = ... 発声前消音 = false, 消音グループ種別 = 消音グループ種別.RightCymbal, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = true, AutoPlayON_Miss判定 = true, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = true, AutoPlayOFF_ユーザヒット_非表示 = true, AutoPlayOFF_ユーザヒット_判定 = true, AutoPlayOFF_Miss判定 = true, }, //---------------- #endregion #region " チップ種別.BPM " //---------------- [ SSTF.チップ種別.BPM ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.BPM, レーン種別 = SSTF.レーン種別.BPM, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = false, AutoPlayON_自動ヒット_非表示 = false, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.小節線 " //---------------- [ SSTF.チップ種別.小節線 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.小節線, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = false, AutoPlayON_自動ヒット_非表示 = false, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.拍線 " //---------------- [ SSTF.チップ種別.拍線 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.拍線, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = false, AutoPlayON_自動ヒット_非表示 = false, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.背景動画 " //---------------- [ SSTF.チップ種別.背景動画 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.背景動画, レーン種別 = SSTF.レーン種別.BGV, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.小節メモ " //---------------- [ SSTF.チップ種別.小節メモ ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.小節メモ, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = false, AutoPlayON_自動ヒット_非表示 = false, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.LeftCymbal_Mute " //---------------- [ SSTF.チップ種別.LeftCymbal_Mute ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.LeftCymbal_Mute, レーン種別 = SSTF.レーン種別.LeftCrash, 表示レーン種別 = 表示レーン種別.LeftCymbal, 表示チップ種別 = 表示チップ種別.LeftCymbal_Mute, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.LeftCrash, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.LeftCymbal, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.RightCymbal_Mute " //---------------- [ SSTF.チップ種別.RightCymbal_Mute ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.RightCymbal_Mute, レーン種別 = SSTF.レーン種別.RightCrash, 表示レーン種別 = 表示レーン種別.RightCymbal, 表示チップ種別 = 表示チップ種別.RightCymbal_Mute, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.RightCrash, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.RightCymbal, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.小節の先頭 " //---------------- [ SSTF.チップ種別.小節の先頭 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.小節の先頭, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = false, AutoPlayON_自動ヒット_非表示 = false, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = false, AutoPlayOFF_自動ヒット_非表示 = false, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.BGM " //---------------- [ SSTF.チップ種別.BGM ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.BGM, レーン種別 = SSTF.レーン種別.BGM, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = false, 消音グループ種別 = 消音グループ種別.Unknown, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE1 " //---------------- [ SSTF.チップ種別.SE1 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE1, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE1, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE2 " //---------------- [ SSTF.チップ種別.SE2 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE2, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE2, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE3 " //---------------- [ SSTF.チップ種別.SE3 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE3, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE3, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE4 " //---------------- [ SSTF.チップ種別.SE4 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE4, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE4, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE5 " //---------------- [ SSTF.チップ種別.SE5 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE5, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE5, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.GuitarAuto " //---------------- [ SSTF.チップ種別.GuitarAuto ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.GuitarAuto, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.Guitar, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.BassAuto " //---------------- [ SSTF.チップ種別.BassAuto ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.BassAuto, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.Bass, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE6 " //---------------- [ SSTF.チップ種別.SE6 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE6, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE6, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE7 " //---------------- [ SSTF.チップ種別.SE7 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE7, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE7, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE8 " //---------------- [ SSTF.チップ種別.SE8 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE8, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE8, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE9 " //---------------- [ SSTF.チップ種別.SE9 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE9, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE9, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE10 " //---------------- [ SSTF.チップ種別.SE10 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE10, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE10, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE11 " //---------------- [ SSTF.チップ種別.SE11 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE11, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE11, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE12 " //---------------- [ SSTF.チップ種別.SE12 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE12, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE12, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE13 " //---------------- [ SSTF.チップ種別.SE13 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE13, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE13, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE14 " //---------------- [ SSTF.チップ種別.SE14 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE14, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE14, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE15 " //---------------- [ SSTF.チップ種別.SE15 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE15, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE15, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE16 " //---------------- [ SSTF.チップ種別.SE16 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE16, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE16, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE17 " //---------------- [ SSTF.チップ種別.SE17 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE17, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE17, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE18 " //---------------- [ SSTF.チップ種別.SE18 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE18, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE18, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE19 " //---------------- [ SSTF.チップ種別.SE19 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE19, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE19, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE20 " //---------------- [ SSTF.チップ種別.SE20 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE20, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE20, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE21 " //---------------- [ SSTF.チップ種別.SE21 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE21, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE21, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE22 " //---------------- [ SSTF.チップ種別.SE22 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE22, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE22, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE23 " //---------------- [ SSTF.チップ種別.SE23 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE23, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE23, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE24 " //---------------- [ SSTF.チップ種別.SE24 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE24, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE24, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE25 " //---------------- [ SSTF.チップ種別.SE25 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE25, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE25, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE26 " //---------------- [ SSTF.チップ種別.SE26 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE26, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE26, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE27 " //---------------- [ SSTF.チップ種別.SE27 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE27, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE27, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE28 " //---------------- [ SSTF.チップ種別.SE28 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE28, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE28, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE29 " //---------------- [ SSTF.チップ種別.SE29 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE29, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE29, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE30 " //---------------- [ SSTF.チップ種別.SE30 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE30, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE30, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE31 " //---------------- [ SSTF.チップ種別.SE31 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE31, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE31, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion #region " チップ種別.SE32 " //---------------- [ SSTF.チップ種別.SE32 ] = new ドラムチッププロパティ() { チップ種別 = SSTF.チップ種別.SE32, レーン種別 = SSTF.レーン種別.Unknown, 表示レーン種別 = 表示レーン種別.Unknown, 表示チップ種別 = 表示チップ種別.Unknown, ドラム入力種別 = ドラム入力種別.Unknown, AutoPlay種別 = AutoPlay種別.Unknown, 入力グループ種別 = 入力グループ種別.Unknown, 発声前消音 = true, 消音グループ種別 = 消音グループ種別.SE32, AutoPlayON_自動ヒット_再生 = true, AutoPlayON_自動ヒット_非表示 = true, AutoPlayON_自動ヒット_判定 = false, AutoPlayON_Miss判定 = false, AutoPlayOFF_自動ヒット_再生 = true, AutoPlayOFF_自動ヒット_非表示 = true, AutoPlayOFF_自動ヒット_判定 = false, AutoPlayOFF_ユーザヒット_再生 = false, AutoPlayOFF_ユーザヒット_非表示 = false, AutoPlayOFF_ユーザヒット_判定 = false, AutoPlayOFF_Miss判定 = false, }, //---------------- #endregion }; this.反映する( 表示レーンの左右 ); this.反映する( 入力グループプリセット種別 ); } /// <summary> /// 表示レーンの左右に依存するメンバに対して一括設定を行う。 /// 依存しないメンバには何もしない。 /// </summary> public void 反映する( 表示レーンの左右 position ) { this.表示レーンの左右 = position; foreach( var kvp in this.チップtoプロパティ ) { switch( kvp.Key ) { case SSTF.チップ種別.Ride: kvp.Value.表示レーン種別 = ( this.表示レーンの左右.Rideは左 ) ? 表示レーン種別.LeftCymbal : 表示レーン種別.RightCymbal; kvp.Value.AutoPlay種別 = ( this.表示レーンの左右.Rideは左 ) ? AutoPlay種別.LeftCrash : AutoPlay種別.RightCrash; kvp.Value.消音グループ種別 = ( this.表示レーンの左右.Rideは左 ) ? 消音グループ種別.LeftCymbal : 消音グループ種別.RightCymbal; kvp.Value.表示チップ種別 = ( this.表示レーンの左右.Rideは左 ) ? 表示チップ種別.LeftRide : 表示チップ種別.RightRide; break; case SSTF.チップ種別.Ride_Cup: kvp.Value.表示レーン種別 = ( this.表示レーンの左右.Rideは左 ) ? 表示レーン種別.LeftCymbal : 表示レーン種別.RightCymbal; kvp.Value.AutoPlay種別 = ( this.表示レーンの左右.Rideは左 ) ? AutoPlay種別.LeftCrash : AutoPlay種別.RightCrash; kvp.Value.消音グループ種別 = ( this.表示レーンの左右.Rideは左 ) ? 消音グループ種別.LeftCymbal : 消音グループ種別.RightCymbal; kvp.Value.表示チップ種別 = ( this.表示レーンの左右.Rideは左 ) ? 表示チップ種別.LeftRide_Cup : 表示チップ種別.RightRide_Cup; break; case SSTF.チップ種別.China: kvp.Value.表示レーン種別 = ( this.表示レーンの左右.Chinaは左 ) ? 表示レーン種別.LeftCymbal : 表示レーン種別.RightCymbal; kvp.Value.AutoPlay種別 = ( this.表示レーンの左右.Chinaは左 ) ? AutoPlay種別.LeftCrash : AutoPlay種別.RightCrash; kvp.Value.消音グループ種別 = ( this.表示レーンの左右.Chinaは左 ) ? 消音グループ種別.LeftCymbal : 消音グループ種別.RightCymbal; kvp.Value.表示チップ種別 = ( this.表示レーンの左右.Chinaは左 ) ? 表示チップ種別.LeftChina : 表示チップ種別.RightChina; break; case SSTF.チップ種別.Splash: kvp.Value.表示レーン種別 = ( this.表示レーンの左右.Splashは左 ) ? 表示レーン種別.LeftCymbal : 表示レーン種別.RightCymbal; kvp.Value.AutoPlay種別 = ( this.表示レーンの左右.Splashは左 ) ? AutoPlay種別.LeftCrash : AutoPlay種別.RightCrash; kvp.Value.消音グループ種別 = ( this.表示レーンの左右.Splashは左 ) ? 消音グループ種別.LeftCymbal : 消音グループ種別.RightCymbal; kvp.Value.表示チップ種別 = ( this.表示レーンの左右.Splashは左 ) ? 表示チップ種別.LeftSplash : 表示チップ種別.RightSplash; break; } } } /// <summary> /// 指定されたプリセットに依存する入力グループ種別を一括設定する。 /// 依存しないメンバには何もしない。 /// </summary> public void 反映する( 入力グループプリセット種別 preset ) { this.入力グループプリセット種別 = preset; foreach( var kvp in this.チップtoプロパティ ) { switch( this.入力グループプリセット種別 ) { case 入力グループプリセット種別.シンバルフリー: { #region " シンバルフリー " //---------------- switch( kvp.Key ) { case SSTF.チップ種別.LeftCrash: case SSTF.チップ種別.Ride: case SSTF.チップ種別.Ride_Cup: case SSTF.チップ種別.China: case SSTF.チップ種別.Splash: // HiHat はシンバルフリーから除外。 //case SSTF.チップ種別.HiHat_Open: //case SSTF.チップ種別.HiHat_HalfOpen: //case SSTF.チップ種別.HiHat_Close: //case SSTF.チップ種別.HiHat_Foot: case SSTF.チップ種別.RightCrash: kvp.Value.入力グループ種別 = 入力グループ種別.Cymbal; break; case SSTF.チップ種別.LeftBass: kvp.Value.入力グループ種別 = 入力グループ種別.Bass; break; } break; //---------------- #endregion } case 入力グループプリセット種別.基本形: { #region " 基本形 " //---------------- switch( kvp.Key ) { case SSTF.チップ種別.LeftCrash: kvp.Value.入力グループ種別 = 入力グループ種別.LeftCymbal; break; case SSTF.チップ種別.Ride: case SSTF.チップ種別.Ride_Cup: kvp.Value.入力グループ種別 = 入力グループ種別.Ride; break; case SSTF.チップ種別.China: kvp.Value.入力グループ種別 = 入力グループ種別.China; break; case SSTF.チップ種別.Splash: kvp.Value.入力グループ種別 = 入力グループ種別.Splash; break; case SSTF.チップ種別.RightCrash: kvp.Value.入力グループ種別 = 入力グループ種別.RightCymbal; break; case SSTF.チップ種別.LeftBass: kvp.Value.入力グループ種別 = 入力グループ種別.Bass; break; } break; //---------------- #endregion } default: throw new Exception( $"未知の入力グループプリセット種別です。[{this.入力グループプリセット種別.ToString()}]" ); } } } } } <|start_filename|>DTXMania2/ステージ/04選曲/BPMパネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; using DTXMania2.曲; namespace DTXMania2.選曲 { class BPMパネル : IDisposable { // 生成と終了 public BPMパネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._BPMパネル = new 画像D2D( @"$(Images)\SelectStage\BpmPanel.png" ); this._パラメータ文字 = new フォント画像D2D( @"$(Images)\ParameterFont_Small.png", @"$(Images)\ParameterFont_Small.yaml", 文字幅補正dpx: 0f ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パラメータ文字.Dispose(); this._BPMパネル.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, Node フォーカスノード ) { var 領域 = new RectangleF( 78f, 455f, 357f, 55f ); this._BPMパネル.描画する( d2ddc, 領域.X - 5f, 領域.Y - 4f ); if( !( フォーカスノード is SongNode snode ) ) { // 現状、BPMを表示できるノードは SongNode のみ。 // SongNode 以外はパネルの表示だけで終わり。 return; } #region " フォーカスノードが変更されていれば情報を更新する。" //---------------- if( フォーカスノード != this._現在表示しているノード ) { this._現在表示しているノード = フォーカスノード; if( snode.曲.フォーカス譜面?.譜面と画像を現行化済み ?? false ) { this._最小BPM = snode.曲.フォーカス譜面!.譜面.MinBPM; this._最大BPM = snode.曲.フォーカス譜面!.譜面.MaxBPM; } else { this._最小BPM = null; this._最大BPM = null; } } //---------------- #endregion #region " BPM を描画する。" //---------------- if( this._最小BPM.HasValue && this._最大BPM.HasValue ) { if( 10.0 >= Math.Abs( this._最大BPM.Value - this._最小BPM.Value ) ) // 差が10以下なら同一値(A)とみなす。 { // (A) 「最小値」だけ描画。 this._パラメータ文字.描画する( d2ddc, 領域.X + 120f, 領域.Y, this._最小BPM.Value.ToString( "0" ).PadLeft( 3 ) ); } else { // (B) 「最小~最大」を描画。 this._パラメータ文字.描画する( d2ddc, 領域.X + 120f, 領域.Y, this._最小BPM.Value.ToString( "0" ) + "~" + this._最大BPM.Value.ToString( "0" ) ); } } //---------------- #endregion } // ローカル private readonly 画像D2D _BPMパネル; private readonly フォント画像D2D _パラメータ文字; private Node? _現在表示しているノード = null; private double? _最小BPM = null; private double? _最大BPM = null; } } <|start_filename|>DTXMania2/サウンド/システムサウンド.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using CSCore; using FDK; namespace DTXMania2 { class システムサウンド : IDisposable { // 生成と終了 public システムサウンド() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._種別toサウンドマップ = new Dictionary<システムサウンド種別, (ISampleSource source, PolySound sound)>(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var kvp in this._種別toサウンドマップ ) this.解放する( kvp.Key ); } /// <summary> /// すべてのシステムサウンドを生成する。 /// </summary> /// <remarks> /// 既に生成済みのサウンドは再生成しない。 /// </remarks> public void すべて生成する( SoundDevice device ) { foreach( システムサウンド種別? type in Enum.GetValues( typeof( システムサウンド種別 ) ) ) { if( type.HasValue ) this.読み込む( device, type.Value ); } } /// <summary> /// 指定されたシステムサウンドを生成する。 /// </summary> /// <remarks> /// 既に生成済みのサウンドは再生成しない。 /// </remarks> public void 読み込む( SoundDevice device, システムサウンド種別 type ) { // 既に生成済みなら何もしない。 if( this._種別toサウンドマップ.ContainsKey( type ) ) return; // ファイル名は、<Alias>.ogg とする。 var path = new VariablePath( $@"$(SystemSounds)\{type.GetAlias()}.ogg" ); path = Folder.カルチャを考慮した絶対パスを返す( path.変数なしパス ); // ファイルがないなら無視。 if( !File.Exists( path.変数なしパス ) ) { Log.WARNING( $"システムサウンドファイルが見つかりません。スキップします。[{path.変数付きパス}]" ); return; } // サンプルソースを読み込む。 var sampleSource = SampleSourceFactory.Create( device, path.変数なしパス, 1.0 ) ?? // システムサウンドは常に再生速度 = 1.0 throw new Exception( $"システムサウンドの読み込みに失敗しました。[{path.変数付きパス}]" ); // サウンドを生成してマップに登録。 var sound = new PolySound( device, sampleSource, 多重度: 2 ); this._種別toサウンドマップ[ type ] = (sampleSource, sound); Log.Info( $"システムサウンドを読み込みました。[{path.変数付きパス}]" ); } /// <summary> /// 指定されたシステムサウンドを解放する。 /// </summary> public void 解放する( システムサウンド種別 type ) { if( this._種別toサウンドマップ.ContainsKey( type ) ) { this._種別toサウンドマップ[ type ].sound.Dispose(); this._種別toサウンドマップ[ type ].source.Dispose(); this._種別toサウンドマップ.Remove( type ); } } // 再生と停止 public void 再生する( システムサウンド種別 type, bool ループ再生する = false ) { if( this._種別toサウンドマップ.TryGetValue( type, out var map ) ) map.sound?.Play( 0, ループ再生する ); } public void 停止する( システムサウンド種別 type ) { if( this._種別toサウンドマップ.TryGetValue( type, out var map ) ) map.sound?.Stop(); } public bool 再生中( システムサウンド種別 type ) { return this._種別toサウンドマップ.TryGetValue( type, out var map ) && map.sound.いずれかが再生中である; } // ローカル private Dictionary<システムサウンド種別, (ISampleSource source, PolySound sound)> _種別toサウンドマップ; } } <|start_filename|>DTXMania2/保存データ/RecordDB/RecordDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2 { class RecordDBRecord { // プロパティ public const int VERSION = 9; /// <summary> /// 譜面ファイルの絶対パス。主キー。 /// </summary> public string ScorePath { get; set; } /// <summary> /// ユーザを一意に識別するID。主キー。 /// </summary> public string UserId { get; set; } /// <summary> /// スコア(得点)。 /// </summary> public int Score { get; set; } /// <summary> /// カウントマップラインのデータ。 /// 1ブロックを1文字('0':0~'C':12)で表し、<see cref="DTXMania.ステージ.演奏.カウントマップライン.カウントマップの最大要素数"/> 個の文字が並ぶ。 /// もし不足分があれば、'0' とみなされる。 /// </summary> public string CountMap { get; set; } /// <summary> /// 達成率。 /// </summary> public double Achievement { get; set; } // 生成と終了 public RecordDBRecord() { this.ScorePath = ""; this.UserId = "Anonymous"; this.Score = 0; this.CountMap = ""; this.Achievement = 0.0; } public RecordDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// <see cref="SqliteDataReader"/>から現在のレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの <see cref="SqliteDataReader"/>。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "ScorePath": this.ScorePath = record.GetString( i ); break; case "UserId": this.UserId = record.GetString( i ); break; case "Score": this.Score = record.GetInt32( i ); break; case "CountMap": this.CountMap = record.GetString( i ); break; case "Achievement": this.Achievement = record.GetDouble( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public virtual void InsertTo( SQLiteDB db, string table = "Records" ) { using var cmd = new SqliteCommand( $"REPLACE INTO {table} VALUES" + "( @SongPath" + ", @UserId" + ", @Score" + ", @CountMap" + ", @Achievement" + ")", db.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@SongPath", this.ScorePath ), new SqliteParameter( "@UserId", this.UserId ), new SqliteParameter( "@Score", this.Score ), new SqliteParameter( "@CountMap", this.CountMap ), new SqliteParameter( "@Achievement", this.Achievement ), } ); cmd.ExecuteNonQuery(); } /// <summary> /// テーブルがなければ作成するSQLを返す。 /// </summary> public static string GetCreateTableSQL( string table = "Records" ) => $"CREATE TABLE IF NOT EXISTS {table}" + "( ScorePath NVARCHAR NOT NULL" + ", UserId NVARCHAR NOT NULL" + ", Score INTEGER NOT NULL" + ", CountMap NVARCHAR NOT NULL" + ", Achievement NUMERIC NOT NULL" + ", PRIMARY KEY(`ScorePath`,`UserId`)" + ")"; } } <|start_filename|>DTXMania2/ステージ/09終了/終了ステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using FDK; namespace DTXMania2.終了 { class 終了ステージ : IStage { // プロパティ public enum フェーズ { 開始, 表示中, 開始音終了待ち, 完了, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; // 生成と終了 public 終了ステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._背景画像 = new 画像D2D( @"$(Images)\ExitStage\Background.jpg" ); // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.開始; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._背景画像?.Dispose(); } // 進行と描画 public void 進行する() { switch( this.現在のフェーズ ) { case フェーズ.開始: { #region " 終了ステージ開始音を再生し、表示中フェーズへ。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.終了ステージ_開始音 ); this._カウンタ = new Counter( 0, 1, 値をひとつ増加させるのにかける時間ms: 1000 ); this.現在のフェーズ = フェーズ.表示中; //---------------- #endregion break; } case フェーズ.表示中: { #region " 一定時間が経過したら開始音終了待ちフェーズへ。" //---------------- if( this._カウンタ.終了値に達した ) this.現在のフェーズ = フェーズ.開始音終了待ち; //---------------- #endregion break; } case フェーズ.開始音終了待ち: { #region " 開始音の再生が終わったら完了フェーズへ。" //---------------- if( !Global.App.システムサウンド.再生中( システムサウンド種別.終了ステージ_開始音 ) ) this.現在のフェーズ = フェーズ.完了; //---------------- #endregion break; } case フェーズ.完了: { #region " 遷移終了。Appによるステージ遷移待ち。" //---------------- //---------------- #endregion break; } } } public void 描画する() { var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = SharpDX.Matrix3x2.Identity; d2ddc.BeginDraw(); this._背景画像.描画する( d2ddc, 0f, 0f ); d2ddc.EndDraw(); } // ローカル private readonly 画像D2D _背景画像; private Counter _カウンタ = null!; } } <|start_filename|>SSTFormat/old/v001_2/チップ種別.cs<|end_filename|> using System; namespace SSTFormat.v001_2 { /// <summary> /// チップの種別を表す整数値。 /// </summary> /// <remarks> /// 互換性を維持するために、将来にわたって不変な int 型の数値を、明確に定義する。 /// </remarks> public enum チップ種別 : int { Unknown = 0, LeftCrash = 1, Ride = 2, Ride_Cup = 3, China = 4, Splash = 5, HiHat_Open = 6, HiHat_HalfOpen = 7, HiHat_Close = 8, HiHat_Foot = 9, Snare = 10, Snare_OpenRim = 11, Snare_ClosedRim = 12, Snare_Ghost = 13, Bass = 14, Tom1 = 15, Tom1_Rim = 16, Tom2 = 17, Tom2_Rim = 18, Tom3 = 19, Tom3_Rim = 20, RightCrash = 21, BPM = 22, 小節線 = 23, 拍線 = 24, 背景動画 = 25, 小節メモ = 26, LeftCymbal_Mute = 27, RightCymbal_Mute = 28, 小節の先頭 = 29, // 増減した場合は、チップ.チップの深さ も更新すること。 } } <|start_filename|>DTXMania2/保存データ/UserConfig/UserConfig.Update.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Data.Sqlite; using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; using FDK; namespace DTXMania2 { partial class UserConfig { /// <summary> /// ユーザDBファイルを最新版に更新する。 /// </summary> /// <remarks> /// v012 移行にバージョンアップする場合は、RecordDB.sqlite3 の生成も行う。 /// </remarks> public static void 最新版にバージョンアップする() { using var _ = new LogBlock( Log.現在のメソッド名 ); var userdbPath = new VariablePath( @"$(AppData)\UserDB.sqlite3" ); var userYamls = Directory.EnumerateFiles( path: Folder.フォルダ変数の内容を返す( "AppData" ), searchPattern: @"User_*.yaml", searchOption: SearchOption.TopDirectoryOnly ); if( 0 < userYamls.Count() ) { #region " (A) User_*.yaml が存在している " //---------------- // それらを最新版にバージョンアップする。 foreach( var userYaml in userYamls ) _Yamlを最新版にバージョンアップする( userYaml ); //---------------- #endregion } else if( File.Exists( userdbPath.変数なしパス ) ) { #region " (B) User_*.yaml が存在せず UserDB.sqlite3 が存在している " //---------------- // Records レコードは、UserDB(v12)からRecordDBに分離された。 // ・UserDB v011 までは、UserDB の Records テーブルに格納されている。RecordDB.Records テーブルのレコードのバージョンは v001~v006(全部同一)。 // ・UserDB v012 以降は、UserDB から独立して、RecordDB.Records テーブルに格納される。Recordsのレコードのバージョンは v007。 var Users = new List<UserConfig>(); int userdb_version; #region " Users テーブルを最新版にして読み込む。" //---------------- using( var userdb = new SQLiteDB( userdbPath.変数なしパス ) ) { userdb_version = (int)userdb.UserVersion; using var idsQuery = new SqliteCommand( "SELECT * FROM Users", userdb.Connection ); var ids = idsQuery.ExecuteReader(); while( ids.Read() ) Users.Add( new UserConfig( ids ) ); } //---------------- #endregion #region " Users テーブルを User_*.yaml に出力する。" //---------------- foreach( var user in Users ) user.保存する(); //---------------- #endregion #region " RecordDB.sqlite3 がなければ新規作成する。" //---------------- if( !File.Exists( RecordDB.RecordDBPath.変数なしパス ) ) { using var recorddb = new RecordDB(); // ファイルがなければ新規作成される using var cmd = new SqliteCommand( $"CREATE TABLE Records { old.RecordDBRecord.v007_RecordDBRecord.ColumnList}", recorddb.Connection ); cmd.ExecuteNonQuery(); recorddb.UserVersion = old.RecordDBRecord.v007_RecordDBRecord.VERSION; Log.Info( $"RecordDB(v007) を生成しました。" ); } //---------------- #endregion if( 12 > userdb_version ) { #region " UserDB.Rcords テーブルを読み込み、RecordDB.Records テーブルへ出力する。" //---------------- using var userdb = new SQLiteDB( userdbPath.変数なしパス ); using var recorddb = new RecordDB(); foreach( var user in Users ) { using var recordsQuery = new SqliteCommand( $"SELECT * FROM Records WHERE Id = @UserId", userdb.Connection ); recordsQuery.Parameters.Add( new SqliteParameter( "@UserId", user.Id ) ); var records = recordsQuery.ExecuteReader(); while( records.Read() ) { var record = new old.RecordDBRecord.v007_RecordDBRecord( records ); // 読み込んで record.InsertTo( recorddb ); // 書き込む } } //---------------- #endregion } //---------------- #endregion } else { #region " (C) User_*.yamlも UserDB.sqlite3 も存在しない " //---------------- #region " 新規に User_*.yaml を生成する。" //---------------- var autoPlayer = new UserConfig() { Id = "AutoPlayer", Name = "AutoPlayer", AutoPlay_LeftCymbal = 1, AutoPlay_HiHat = 1, AutoPlay_LeftPedal = 1, AutoPlay_Snare = 1, AutoPlay_Bass = 1, AutoPlay_HighTom = 1, AutoPlay_LowTom = 1, AutoPlay_FloorTom = 1, AutoPlay_RightCymbal = 1, // 他は既定値 }; autoPlayer.保存する(); var guest = new UserConfig() { Id = "Guest", Name = "Guest", // 他は既定値 }; guest.保存する(); //---------------- #endregion #region " 新規に RecordDB.sqlite3 を生成する。" //---------------- var recorddbPath = new VariablePath( @"$(AppData)\RecordDB.sqlite3" ); // 念のため if( File.Exists( recorddbPath.変数なしパス ) ) File.Delete( recorddbPath.変数なしパス ); using var recorddb = new SQLiteDB( recorddbPath.変数なしパス ); // ファイルがなければ新規生成される。 using var cmd = new SqliteCommand( RecordDBRecord.GetCreateTableSQL(), recorddb.Connection ); cmd.ExecuteNonQuery(); recorddb.UserVersion = RecordDBRecord.VERSION; Log.Info( $"RecordDB を生成しました。" ); //---------------- #endregion //---------------- #endregion } } // ローカル /// <summary> /// YAMLファイルを最新版にバージョンアップする。 /// </summary> private static void _Yamlを最新版にバージョンアップする( VariablePath path ) { int version = 0; #region " YAML階層のルートノード 'Version' を検索し、バージョン値を取得する。" //---------------- { var yamlText = File.ReadAllText( path.変数なしパス ); var yamlStream = new YamlStream(); yamlStream.Load( new StringReader( yamlText ) ); var rootMapping = (YamlMappingNode)yamlStream.Documents[ 0 ].RootNode; var versionNode = new YamlScalarNode( "Version" ); if( rootMapping.Children.ContainsKey( versionNode ) ) { var versionValue = rootMapping.Children[ versionNode ] as YamlScalarNode; version = int.Parse( versionValue?.Value ?? "1" ); // 取得 } } //---------------- #endregion while( version < UserConfig.VERSION ) { switch( version ) { case 14: { #region " 14 → 最新版 " //---------------- // 変更がないので、全メンバを代入でコピーするよりも、v14をシリアライズ → v15でデシリアライズ するほうを選ぶ。 var v14yamlText = File.ReadAllText( path.変数なしパス ); var v14deserializer = new Deserializer(); var v14config = v14deserializer.Deserialize<old.UserConfig.v014_UserConfig>( v14yamlText ); var v14serializer = new SerializerBuilder() .WithTypeInspector( inner => new CommentGatheringTypeInspector( inner ) ) .WithEmissionPhaseObjectGraphVisitor( args => new CommentsObjectGraphVisitor( args.InnerVisitor ) ) .Build(); var v14yaml = v14serializer.Serialize( v14config ); var v15deserializer = new Deserializer(); var v15config = v15deserializer.Deserialize<UserConfig>( v14yamlText ); // 変更なし v15config.Version = UserConfig.VERSION; v15config.保存する(); version = v15config.Version; break; //---------------- #endregion } } } } } } <|start_filename|>DTXMania2/保存データ/RecordDB/RecordDB.Update.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2 { partial class RecordDB { public static void 最新版にバージョンアップする() { using var _ = new LogBlock( Log.現在のメソッド名 ); // Records レコードは、UserDB(v12)からRecordDBに分離された。 // ・UserDB v011 までは、UserDB の Records テーブルに格納されている。RecordDB.Records テーブルのレコードのバージョンは v001~v006(全部同一)。 // ・UserDB v012 以降は、UserDB から独立して、RecordDB.Records テーブルに格納される。Recordsのレコードのバージョンは v007。 if( File.Exists( RecordDBPath.変数なしパス ) ) { #region " (A) RecordDB.sqlite3 が存在している → 最新版にバージョンアップ。" //---------------- using var recorddb = new RecordDB(); int version = (int)recorddb.UserVersion; while( version < RecordDBRecord.VERSION ) { // RecordDB は v007 から。 switch( version ) { case 0: // 念のため(あったら無限ループになるため) { #region " 0 → 最新版 " //---------------- // テーブルを新規に作る。 foreach( var query in new[] { "PRAGMA foreign_keys = OFF", RecordDBRecord.GetCreateTableSQL(), "PRAGMA foreign_keys = ON" } ) { using var cmd = new SqliteCommand( query, recorddb.Connection ); cmd.ExecuteNonQuery(); } version = RecordDBRecord.VERSION; recorddb.UserVersion = version; Log.Info( $"RecordDB をバージョン {version} を作成しました。" ); break; //---------------- #endregion } case 7: { #region " 7 → 8 " //---------------- // テーブルを作り直す。REAL値が既にずれてるので、データ移行はしない。 foreach( var query in new[] { "PRAGMA foreign_keys = OFF", "DROP TABLE Records", $"CREATE TABLE Records {old.RecordDBRecord.v008_RecordDBRecord.ColumnList}", "PRAGMA foreign_keys = ON" } ) { using var cmd = new SqliteCommand( query, recorddb.Connection ); cmd.ExecuteNonQuery(); } version = old.RecordDBRecord.v008_RecordDBRecord.VERSION; recorddb.UserVersion = version; Log.Info( $"RecordDB をバージョン {version} に更新しました。データ移行はしません。" ); break; //---------------- #endregion } case 8: { #region " 8 → 最新版 " //---------------- // テーブルを作り直す。今までの成績は消失する。 foreach( var query in new[] { "PRAGMA foreign_keys = OFF", "DROP TABLE Records", RecordDBRecord.GetCreateTableSQL(), "PRAGMA foreign_keys = ON" } ) { using var cmd = new SqliteCommand( query, recorddb.Connection ); cmd.ExecuteNonQuery(); } version = RecordDBRecord.VERSION; recorddb.UserVersion = version; Log.Info( $"RecordDB をバージョン {version} に更新しました。データ移行はしません。" ); break; //---------------- #endregion } } } //---------------- #endregion } else { #region " (B) RecordDB.sqlite3 が存在しない → 何もしない " //---------------- // UserDB 側の Update で RecordDB.sqlite3 が生成されるのを待つ。 //---------------- #endregion } } } } <|start_filename|>DTXMania2/曲/現行化.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using SharpDX; using SharpDX.DirectWrite; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.曲 { /// <summary> /// <see cref="SongNode"/> を現行化する。 /// </summary> /// <remarks> /// 現行化とは、仮の初期状態から、最新の完全な状態に更新する処理である。 /// 具体的には、DB から作成された <see cref="SongNode"/> の情報を実際のファイルが持つ /// 最新の情報と比較して DB を更新したり、他の DB からデータを読み込んだり、 /// <see cref="SongNode"/> が持つ画像を生成したりする。 /// </remarks> class 現行化 { // プロパティ /// <summary> /// 現在、現行化処理中なら true, 停止中なら false。 /// </summary> public bool 現行化中 => this._現行化中.IsSet; // 開始と終了 /// <summary> /// 指定された曲ツリーの現行化を開始する。 /// </summary> /// <param name="root">曲ツリーのルートノードのリスト。</param> public void 開始する( IEnumerable<RootNode> roots, ユーザ設定 userConfig ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // 全ノードをスタックに投入。 this._現行化待ちスタック.Clear(); foreach( var root in roots ) foreach( var node in root.Traverse() ) this._現行化待ちスタック.Push( node ); this._現行化を開始する( userConfig ); } /// <summary> /// 現行化待ちスタックにノードリストを追加する。 /// </summary> /// <remarks> /// 現行化待ちスタックは LIFO なので、投入されたノードリストは優先的に現行化される。 /// </remarks> /// <param name="nodeList">追加するノードリスト。</param> public async Task 追加するAsync( ICollection<Node> nodeList ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); await Task.Run( () => { if( nodeList is Node[] nodeArray ) { this._現行化待ちスタック.PushRange( nodeArray ); } else { var _nodeArray = new Node[ nodeList.Count ]; nodeList.CopyTo( _nodeArray, 0 ); this._現行化待ちスタック.PushRange( _nodeArray ); } } ); } /// <summary> /// 現行化処理を一時停止する。 /// </summary> public void 一時停止する() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._タスク再開通知.Reset(); // 順番注意 this._タスク一時停止通知.Set(); // } /// <summary> /// 一時停止している現行化処理を再開する。 /// </summary> public void 再開する() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._タスク一時停止通知.Reset(); // 順番注意 this._タスク再開通知.Set(); // } /// <summary> /// 現行化タスクを終了する。 /// </summary> public void 終了する() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._現行化タスク is null ) { // タスクは走っていない。 } else if( this._現行化タスク.IsCompleted ) { // タスクはすでに終了済みである。 this._現行化タスク.Dispose(); this._現行化タスク = null; } else { // タスクが実行中である。 this._タスク再開通知.Set(); // 終了通知より先に再開を通知する。 this._タスク終了通知.Set(); if( !this._現行化タスク.Wait( 5000 ) ) throw new Exception( "現行化タスク終了待ちがタイムアウトしました。" ); this._現行化タスク.Dispose(); this._現行化タスク = null; } } /// <summary> /// 指定されたツリーの全譜面のユーザ依存の現行化フラグをリセットする。 /// </summary> public void リセットする( IEnumerable<RootNode> roots, ユーザ設定 userConfig ) { foreach( var root in roots ) { foreach( var node in root.Traverse() ) { if( node is SongNode snode ) { snode.現行化済み = false; foreach( var score in snode.曲.譜面リスト ) { if( score is null ) continue; //score.譜面と画像を現行化済み = false; --> ユーザに依存しないので現状維持 score.最高記録 = null; score.最高記録を現行化済み = false; score.譜面の属性 = null; score.譜面の属性を現行化済み = false; } } } } } public void すべての譜面について属性を現行化する( string userID ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // 指定されたユーザIDでDBに登録されているすべての譜面属性を取得する。 int 属性取得数 = 0; using var scorepropdb = new ScorePropertiesDB(); using var cmd = new SqliteCommand( "SELECT * FROM ScoreProperties WHERE UserId = @UserId", scorepropdb.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@UserId", userID ), } ); var result = cmd.ExecuteReader(); while( result.Read() ) { var prop = new ScorePropertiesDBRecord( result ); foreach( var score in Global.App.全譜面リスト.Where( ( s ) => s.譜面.ScorePath == prop.ScorePath ) ) { score.譜面の属性 = prop; score.譜面の属性を現行化済み = true; 属性取得数++; } } Log.Info( $"{属性取得数} 件の属性を更新しました。" ); } // 生成(static) public static 文字列画像D2D? タイトル文字列画像を生成する( string タイトル文字列 ) { try { var image = new 文字列画像D2D() { 表示文字列 = タイトル文字列, フォント名 = "HGMaruGothicMPRO", // "Meiryo", フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, フォントサイズpt = 40f, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 6f, 前景色 = Color4.Black, 背景色 = Color4.White, }; //Log.Info( $"タイトル画像を生成しました。[{タイトル文字列}]" ); return image; } catch( Exception e ) { Log.ERROR( $"タイトル画像の生成に失敗しました。[{タイトル文字列}][{e.Message}]" ); return null; } } public static 文字列画像D2D? サブタイトル文字列画像を生成する( string? サブタイトル文字列 ) { if( string.IsNullOrEmpty( サブタイトル文字列 ) ) return null; try { var image = new 文字列画像D2D() { 表示文字列 = サブタイトル文字列, フォント名 = "HGMaruGothicMPRO", // "Meiryo", フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, フォントサイズpt = 20f, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 4f, 前景色 = Color4.Black, 背景色 = Color4.White, }; //Log.Info( $"サブタイトル画像を生成しました。[{サブタイトル文字列}]" ); return image; } catch( Exception e ) { Log.ERROR( $"サブタイトル画像の生成に失敗しました。[{サブタイトル文字列}][{e.Message}]" ); return null; } } public static 画像D2D? ノード画像を生成する( VariablePath? ノード画像ファイルの絶対パス ) { if( ノード画像ファイルの絶対パス is null ) return null; try { var image = new 画像D2D( ノード画像ファイルの絶対パス.変数なしパス ); //Log.Info( $"ノード画像を生成しました。[{ノード画像ファイルの絶対パス.変数付きパス}]" ); return image; } catch( Exception e ) { Log.ERROR( $"ノード画像の生成に失敗しました。[{ノード画像ファイルの絶対パス.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); return null; } } // ローカル private ConcurrentStack<Node> _現行化待ちスタック = new ConcurrentStack<Node>(); private Task? _現行化タスク = null; private ManualResetEventSlim _タスク一時停止通知 = new ManualResetEventSlim(); private ManualResetEventSlim _タスク再開通知 = new ManualResetEventSlim(); private ManualResetEventSlim _タスク終了通知 = new ManualResetEventSlim(); private ManualResetEventSlim _現行化中 = new ManualResetEventSlim( false ); private void _現行化を開始する( ユーザ設定 userConfig ) { this._タスク終了通知.Reset(); this._現行化タスク = Task.Run( () => { //Log.現在のスレッドに名前をつける( "現行化" ); --> await 後にワーカスレッドが変わることがある Log.Info( "現行化タスクを開始しました。" ); while( !this._タスク終了通知.IsSet ) { // 一時停止通知が来ていたら、再開通知が来るまでブロックする。 if( this._タスク一時停止通知.IsSet ) this._タスク再開通知.Wait(); // スタックからノードを1つ取り出して現行化する。 if( this._現行化待ちスタック.TryPop( out var node ) ) { this._現行化中.Set(); this._ノードを現行化する( node, userConfig ); } else { // スタックが空だったら、少し待機してから繰り返し。 this._現行化中.Reset(); Thread.Sleep( 100 ); } } Log.Info( "現行化タスクを終了しました。" ); } ); } private void _ノードを現行化する( Node node, ユーザ設定 userConfig ) { #region " (1) ノードが持つすべての譜面の現行化 " //---------------- if( node is SongNode snode ) { using var scoredb = new ScoreDB(); using( var cmd = new SqliteCommand( "BEGIN", scoredb.Connection ) ) cmd.ExecuteNonQuery(); // すべての譜面について…… for( int i = 0; i < 5; i++ ) { var score = snode.曲.譜面リスト[ i ]; if( score is null ) continue; // 譜面がないなら無視 if( !File.Exists( score.譜面.ScorePath ) ) { Log.ERROR( $"ファイルが存在しません。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}]" ); snode.曲.譜面リスト[ i ]!.Dispose(); snode.曲.譜面リスト[ i ] = null; continue; // 譜面のファイルがないなら無視 } // (1-1) 譜面と画像 の現行化 if( !score.譜面と画像を現行化済み ) { #region " ファイルの更新を確認し、ScoreDB と score を現行化する。" //---------------- try { using var query = new SqliteCommand( "SELECT * FROM Scores WHERE ScorePath = @ScorePath", scoredb.Connection ); query.Parameters.Add( new SqliteParameter( "@ScorePath", score.譜面.ScorePath ) ); var result = query.ExecuteReader(); if( !result.Read() ) { // (A) ScoreDB に既存のレコードがない場合 #region " ScoreDBの レコードを新規追加し score を更新する。" //---------------- var record = new ScoreDBRecord( score.譜面.ScorePath, userConfig ); // レコードを ScoreDB に新規追加する。 record.ReplaceTo( scoredb ); // score にも反映する。 score.譜面.UpdateFrom( record ); // 完了。 Log.Info( $"ScoreDBに曲を追加しました。{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}" ); //---------------- #endregion } else { // (B) ScoreDB に既存のレコードがある場合 var record = new ScoreDBRecord( result ); string 譜面ファイルの最終更新日時 = File.GetLastWriteTime( score.譜面.ScorePath ).ToString( "G" ); if( record.LastWriteTime != 譜面ファイルの最終更新日時 ) { #region " (B-a) 譜面ファイルの最終更新日時が更新されている → ScoreDB のレコードと score を更新する。" //---------------- record = new ScoreDBRecord( score.譜面.ScorePath, userConfig ); // ScoreDB のレコードを置換する。 record.ReplaceTo( scoredb ); // score にも反映する。 score.譜面.UpdateFrom( record ); // 完了。 Log.Info( $"最終更新日時が変更されているため、曲の情報を更新しました。{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}" ); //---------------- #endregion } else { #region " (B-b) それ以外 → 何もしない " //---------------- //---------------- #endregion } } } catch( Exception e ) { Log.ERROR( $"譜面の現行化に失敗しました。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}]" ); // 続行 } //---------------- #endregion #region " 画像を現行化する。" //---------------- try { // タイトル文字列画像 if( score.タイトル文字列画像 is null || score.タイトル文字列画像.表示文字列 != score.譜面.Title ) { score.タイトル文字列画像?.Dispose(); score.タイトル文字列画像 = タイトル文字列画像を生成する( score.譜面.Title ); } // サブタイトル文字列画像 if( score.サブタイトル文字列画像 is null || score.サブタイトル文字列画像.表示文字列 != score.譜面.Artist ) { score.サブタイトル文字列画像?.Dispose(); score.サブタイトル文字列画像 = サブタイトル文字列画像を生成する( string.IsNullOrEmpty( score.譜面.Artist ) ? null : score.譜面.Artist ); } // プレビュー画像 score.プレビュー画像?.Dispose(); score.プレビュー画像 = ノード画像を生成する( string.IsNullOrEmpty( score.譜面.PreImage ) ? null : new VariablePath( Path.Combine( Path.GetDirectoryName( score.譜面.ScorePath ) ?? @"\", score.譜面.PreImage ) ) ); } catch( Exception e ) { Log.ERROR( $"譜面画像の現行化に失敗しました。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}]" ); // 続行 } //---------------- #endregion // 現行化の成否によらず完了。 score.譜面と画像を現行化済み = true; } // (1-2) 属性 の現行化 if( !score.譜面の属性を現行化済み ) { #region " 譜面の属性を現行化する。" //---------------- try { using var scorepropdb = new ScorePropertiesDB(); using var cmd = new SqliteCommand( "SELECT * FROM ScoreProperties WHERE ScorePath = @ScorePath AND UserId = @UserId", scorepropdb.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@ScorePath", score.譜面.ScorePath ), new SqliteParameter( "@UserId", userConfig.ID ), } ); var result = cmd.ExecuteReader(); if( result.Read() ) { score.譜面の属性 = new ScorePropertiesDBRecord( result ); Log.Info( $"譜面の属性を現行化しました。[{score.譜面.ScorePath}]" ); } } catch( Exception e ) { Log.ERROR( $"譜面の属性の現行化に失敗しました。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}]" ); // 続行 } // 現行化の成否によらず完了。 score.譜面の属性を現行化済み = true; //---------------- #endregion } // (1-3) 最高記録 の現行化 if( !score.最高記録を現行化済み ) { #region " 最高記録を現行化する。" //---------------- try { using var recorddb = new RecordDB(); using var cmd = new SqliteCommand( "SELECT * FROM Records WHERE ScorePath = @ScorePath AND UserId = @UserId", recorddb.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@ScorePath", score.譜面.ScorePath ), new SqliteParameter( "@UserId", userConfig.ID ), } ); var result = cmd.ExecuteReader(); if( result.Read() ) { score.最高記録 = new RecordDBRecord( result ); Log.Info( $"最高記録を現行化しました。[{score.譜面.ScorePath}]" ); } } catch( Exception e ) { Log.ERROR( $"最高記録の現行化に失敗しました。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( score.譜面.ScorePath )}]" ); // 続行 } // 現行化の成否によらず完了。 score.最高記録を現行化済み = true; //---------------- #endregion } } using( var cmd = new SqliteCommand( "END", scoredb.Connection ) ) cmd.ExecuteNonQuery(); } //---------------- #endregion #region " (2) ノード自身の現行化 " //---------------- if( !node.現行化済み ) { if( node is SongNode ) { // SongNode は生成不要。 // → App.全譜面リスト の構築時に、タイトル文字列画像とサブタイトル文字列画像だけ先に生成済み。 } else { // SongNode 以外は今生成する。 node.タイトル文字列画像 = タイトル文字列画像を生成する( node.タイトル ); node.サブタイトル文字列画像 = サブタイトル文字列画像を生成する( node.サブタイトル ); node.ノード画像 = ノード画像を生成する( node.ノード画像ファイルの絶対パス ); } // 生成の成否によらず完了。 node.現行化済み = true; } //---------------- #endregion } } } <|start_filename|>DTXMania2/曲/Song.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpDX; using FDK; namespace DTXMania2.曲 { /// <summary> /// 1~5個の個別の難易度を持つ曲をまとめるクラス。 /// </summary> partial class Song : IDisposable { // 外部依存アクション(static) /// <summary> /// 現在選択されている難易度レベル(0~4)を取得して返す。 /// 外部から設定すること。 /// </summary> public static Func<int> 現在の難易度レベル { get; set; } = () => throw new NotImplementedException(); // プロパティ /// <summary> /// 該当譜面がなければ null。 /// </summary> public Score? フォーカス譜面 => this.ユーザ希望難易度に最も近い難易度レベルの譜面を返す( Song.現在の難易度レベル() ); public Score?[] 譜面リスト { get; } = new Score?[ 5 ] { null, null, null, null, null }; public static Color4[] 難易度色リスト { get; } = new Color4[ 5 ] { new Color4( 0xfffe9551 ), // BASIC 相当 new Color4( 0xff00aaeb ), // ADVANCED 相当 new Color4( 0xff7d5cfe ), // EXTREME 相当 new Color4( 0xfffe55c6 ), // MASTER 相当 new Color4( 0xff2b28ff ), // ULTIMATE 相当 }; // 生成と終了 /// <summary> /// 単一譜面から生成する。 /// </summary> public Song( VariablePath 譜面ファイルの絶対パス ) { this.譜面リスト[ 2 ] = new Score() { 難易度ラベル = "FREE", 譜面 = new ScoreDBRecord() { //Title = "(new song!)", Title = Path.GetFileName( 譜面ファイルの絶対パス.変数なしパス ), ScorePath = 譜面ファイルの絶対パス.変数なしパス, }, 譜面の属性 = null, 最高記録 = null, }; } /// <summary> /// 複数譜面(set.def)から生成する。 /// </summary> public Song( SetDef.Block block, VariablePath setDefのあるフォルダの絶対パス ) { for( int i = 0; i < 5; i++ ) { if( string.IsNullOrEmpty( block.File[ i ] ) ) continue; var socre_path = Path.Combine( setDefのあるフォルダの絶対パス.変数なしパス, block.File[ i ]! ); this.譜面リスト[ i ] = new Score() { 難易度ラベル = block.Label[ i ] ?? SetDef.デフォルトのラベル[ i ], // LABEL は省略可 譜面 = new ScoreDBRecord() { //Title = "(new song!)", Title = Path.GetFileName( socre_path ), ScorePath = socre_path, }, 譜面の属性 = null, 最高記録 = null, }; } } public virtual void Dispose() { foreach( var score in this.譜面リスト ) score?.Dispose(); } // その他 public int ユーザ希望難易度に最も近い難易度レベルを返す( int ユーザ希望難易度レベル0to4 ) { if( null != this.譜面リスト[ ユーザ希望難易度レベル0to4 ] ) { // 希望難易度ぴったりの曲があったので、それを返す。 return ユーザ希望難易度レベル0to4; } else { // なければ、以下、希望難易度に最も近いレベルを検索して返す。 // 現在のアンカレベルから、難易度上向きに検索開始。 int 最も近いレベル = ユーザ希望難易度レベル0to4; for( int i = 0; i < 5; i++ ) { if( null != this.譜面リスト[ 最も近いレベル ] ) break; // 曲があった。 // 曲がなかったので次の難易度レベルへGo。(5以上になったら0に戻る。) 最も近いレベル = ( 最も近いレベル + 1 ) % 5; } if( 最も近いレベル == ユーザ希望難易度レベル0to4 ) { // 5回回って見つからなかったということはすべて null だということ。 //Log.ERROR( "譜面リストがすべて null です。" ); return ユーザ希望難易度レベル0to4; } // 見つかった曲がアンカより下のレベルだった場合…… // アンカから下向きに検索すれば、もっとアンカに近い曲(あるいは同じ曲)にヒットするはず。 if( 最も近いレベル < ユーザ希望難易度レベル0to4 ) { // 現在のアンカレベルから、難易度下向きに検索開始。 最も近いレベル = ユーザ希望難易度レベル0to4; for( int i = 0; i < 5; i++ ) { if( null != this.譜面リスト[ 最も近いレベル ] ) break; // 曲があった。 // 曲がなかったので次の難易度レベルへGo。(0未満になったら4に戻る。) 最も近いレベル = ( ( 最も近いレベル - 1 ) + 5 ) % 5; } } return 最も近いレベル; } } public Score ユーザ希望難易度に最も近い難易度レベルの譜面を返す( int ユーザ希望難易度レベル0to4 ) { int level0to4 = this.ユーザ希望難易度に最も近い難易度レベルを返す( ユーザ希望難易度レベル0to4 ); return this.譜面リスト[ level0to4 ]!; } } } <|start_filename|>DTXMania2/ステージ/07演奏/チップ光.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { /// <summary> /// チップがヒットされた時に放つ光。 /// </summary> class チップ光 : IDisposable { // 生成と終了 public チップ光() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._放射光 = new 画像D2D( @"$(Images)\PlayStage\ChipFlush.png" ) { 加算合成する = true }; this._光輪 = new 画像D2D( @"$(Images)\PlayStage\ChipFlushRing.png" ) { 加算合成する = true }; this._放射光の矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\ChipFlush.yaml" ); this._レーンtoステータス = new Dictionary<表示レーン種別, 表示レーンステータス>() { { 表示レーン種別.Unknown, new 表示レーンステータス( 表示レーン種別.Unknown ) }, { 表示レーン種別.LeftCymbal, new 表示レーンステータス( 表示レーン種別.LeftCymbal ) }, { 表示レーン種別.HiHat, new 表示レーンステータス( 表示レーン種別.HiHat ) }, { 表示レーン種別.Foot, new 表示レーンステータス( 表示レーン種別.Foot ) }, { 表示レーン種別.Snare, new 表示レーンステータス( 表示レーン種別.Snare ) }, { 表示レーン種別.Bass, new 表示レーンステータス( 表示レーン種別.Bass ) }, { 表示レーン種別.Tom1, new 表示レーンステータス( 表示レーン種別.Tom1 ) }, { 表示レーン種別.Tom2, new 表示レーンステータス( 表示レーン種別.Tom2 ) }, { 表示レーン種別.Tom3, new 表示レーンステータス( 表示レーン種別.Tom3 ) }, { 表示レーン種別.RightCymbal, new 表示レーンステータス( 表示レーン種別.RightCymbal ) }, }; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var kvp in this._レーンtoステータス ) kvp.Value.Dispose(); this._光輪.Dispose(); this._放射光.Dispose(); } // 表示開始 public void 表示を開始する( 表示レーン種別 lane ) { this._レーンtoステータス[ lane ].現在の状態 = 表示レーンステータス.状態.表示開始; } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { foreach( 表示レーン種別? レーン in Enum.GetValues( typeof( 表示レーン種別 ) ) ) { if( !レーン.HasValue ) continue; var status = this._レーンtoステータス[ レーン.Value ]; switch( status.現在の状態 ) { case 表示レーンステータス.状態.表示開始: { #region " 表示開始 " //---------------- status.アニメ用メンバを解放する(); // 初期状態 status.放射光の回転角 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); status.放射光の拡大率 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); status.光輪の拡大率 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); status.光輪の不透明度 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); status.ストーリーボード = new Storyboard( Global.Animation.Manager ); double 期間sec; #region " (1) 放射光 アニメーションの構築 " //---------------- { // シーン1. 回転しつつ拡大縮小 期間sec = 0.1; using( var 回転角の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 45.0 ) ) using( var 拡大率の遷移1 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec / 2.0, finalValue: 1.5 ) ) using( var 拡大率の遷移2 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec / 2.0, finalValue: 0.7 ) ) { status.ストーリーボード.AddTransition( status.放射光の回転角, 回転角の遷移 ); status.ストーリーボード.AddTransition( status.放射光の拡大率, 拡大率の遷移1 ); status.ストーリーボード.AddTransition( status.放射光の拡大率, 拡大率の遷移2 ); } // シーン2. 縮小して消滅 期間sec = 0.1; using( var 拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec / 2.0, finalValue: 0.0 ) ) { status.ストーリーボード.AddTransition( status.放射光の拡大率, 拡大率の遷移 ); } } //---------------- #endregion #region " (2) 光輪 アニメーションの構築 " //---------------- { // シーン1. ある程度まで拡大 期間sec = 0.05; using( var 光輪の拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.6 ) ) using( var 光輪の不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) { status.ストーリーボード.AddTransition( status.光輪の拡大率, 光輪の拡大率の遷移 ); status.ストーリーボード.AddTransition( status.光輪の不透明度, 光輪の不透明度の遷移 ); } // シーン2. ゆっくり拡大しつつ消える 期間sec = 0.15; using( var 光輪の拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.8 ) ) using( var 光輪の不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.0 ) ) { status.ストーリーボード.AddTransition( status.光輪の拡大率, 光輪の拡大率の遷移 ); status.ストーリーボード.AddTransition( status.光輪の不透明度, 光輪の不透明度の遷移 ); } } //---------------- #endregion // アニメーション 開始。 status.ストーリーボード.Schedule( Global.Animation.Timer.Time ); status.現在の状態 = 表示レーンステータス.状態.表示中; //---------------- #endregion break; } case 表示レーンステータス.状態.表示中: { #region " (1) 放射光 の進行描画。" //---------------- { var 転送元矩形dpx = this._放射光の矩形リスト[ レーン.Value.ToString() ]!; var w = 転送元矩形dpx!.Value.Width; var h = 転送元矩形dpx!.Value.Height; var sx = (float)status.放射光の拡大率.Value; var sy = (float)status.放射光の拡大率.Value; var 変換行列2D = Matrix3x2.Rotation( angle: MathUtil.DegreesToRadians( (float)status.放射光の回転角.Value ), center: new Vector2( w / 2f, h / 2f ) ) * Matrix3x2.Scaling( sx, sy ) * Matrix3x2.Translation( status.表示中央位置dpx.X - w * sx / 2f, status.表示中央位置dpx.Y - h * sy / 2f ); const float 不透明度 = 0.5f; // 眩しいので減光 this._放射光.描画する( d2ddc, 変換行列2D, 転送元矩形: 転送元矩形dpx, 不透明度0to1: 不透明度 ); } //---------------- #endregion #region " (2) 光輪 の進行描画。" //---------------- { var 転送元矩形dpx = this._放射光の矩形リスト[ レーン.Value.ToString() ]!; var w = 転送元矩形dpx!.Value.Width; var h = 転送元矩形dpx!.Value.Height; var sx = (float)status.光輪の拡大率.Value; var sy = (float)status.光輪の拡大率.Value; var 変換行列2D = Matrix3x2.Scaling( sx, sy ) * Matrix3x2.Translation( status.表示中央位置dpx.X - w * sx / 2f, status.表示中央位置dpx.Y - h * sy / 2f ); this._光輪.描画する( d2ddc, 変換行列2D, 転送元矩形: 転送元矩形dpx, 不透明度0to1: (float)status.光輪の不透明度.Value ); } //---------------- #endregion #region " 全部終わったら非表示へ。" //---------------- if( status.ストーリーボード is null || status.ストーリーボード.Status == StoryboardStatus.Ready ) status.現在の状態 = 表示レーンステータス.状態.非表示; //---------------- #endregion break; } } } } // ローカル private readonly 画像D2D _放射光; private readonly 画像D2D _光輪; private readonly 矩形リスト _放射光の矩形リスト; /// <summary> /// 以下の画像のアニメ&表示管理を行うクラス。 /// ・放射光 /// ・フレア(輪) /// </summary> private class 表示レーンステータス : IDisposable { public enum 状態 { 非表示, 表示開始, // 高速進行スレッドが設定 表示中, // 描画スレッドが設定 } public 状態 現在の状態 = 状態.非表示; public readonly Vector2 表示中央位置dpx; public Variable 放射光の回転角 = null!; public Variable 放射光の拡大率 = null!; public Variable 光輪の拡大率 = null!; public Variable 光輪の不透明度 = null!; public Storyboard ストーリーボード = null!; public 表示レーンステータス( 表示レーン種別 lane ) { this.現在の状態 = 状態.非表示; // 表示中央位置は、レーンごとに固定。 this.表示中央位置dpx = new Vector2( レーンフレーム.レーン中央位置X[ lane ], 演奏ステージ.ヒット判定位置Ydpx ); } public virtual void Dispose() { this.アニメ用メンバを解放する(); this.現在の状態 = 状態.非表示; } public void アニメ用メンバを解放する() { this.ストーリーボード?.Dispose(); this.放射光の回転角?.Dispose(); this.放射光の拡大率?.Dispose(); this.光輪の拡大率?.Dispose(); this.光輪の不透明度?.Dispose(); } } private readonly Dictionary<表示レーン種別, 表示レーンステータス> _レーンtoステータス; } } <|start_filename|>DTXMania2/App.cs<|end_filename|> using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.IO.Pipes; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using FDK; using DTXMania2.曲; using SSTF=SSTFormat.v004; namespace DTXMania2 { [DebuggerDisplay( "Form" )] // Form.ToString() の評価タイムアウト回避用。 public partial class App : Form { // プロパティ internal ドラム入力 ドラム入力 { get; private protected set; } = null!; internal Random 乱数 { get; } = new Random( DateTime.Now.Millisecond ); internal ScreenMode ScreenMode { get; private protected set; } = null!; internal SystemConfig システム設定 { get; set; } = null!; internal システムサウンド システムサウンド { get; private protected set; } = null!; internal ドラムサウンド ドラムサウンド { get; private protected set; } = null!; internal SoundDevice サウンドデバイス { get; private protected set; } = null!; internal SoundTimer サウンドタイマ { get; private protected set; } = null!; internal アイキャッチ管理 アイキャッチ管理 { get; private protected set; } = null!; internal SelectableList<ユーザ設定> ユーザリスト { get; } = new SelectableList<ユーザ設定>(); internal ユーザ設定 ログオン中のユーザ => this.ユーザリスト.SelectedItem!; internal List<Score> 全譜面リスト { get; } = new List<Score>(); internal List<Song> 全曲リスト { get; } = new List<Song>(); /// <summary> /// 曲ツリーのリスト。選曲画面の「表示方法選択パネル」で変更できる。<br/> /// [0]全曲、[1]評価順 で固定。 /// </summary> internal SelectableList<曲ツリー> 曲ツリーリスト { get; } = new SelectableList<曲ツリー>(); internal 現行化 現行化 { get; } = new 現行化(); internal CacheStore<CSCore.ISampleSource> WAVキャッシュ { get; private protected set; } = null!; internal IStage? ステージ { get; private protected set; } = null; /// <summary> /// アプリケーション再起動指示フラグ。 /// </summary> /// <remarks> /// <see cref="App"/> インスタンスの終了時にこのフラグが true になっている場合には、 /// このインスタンスの保持者(おそらくProgramクラス)は適切に再起動を行うこと。 /// </remarks> internal bool 再起動が必要 { get; private protected set; } = false; // 演奏ごとに更新されるプロパティ /// <summary> /// 演奏する譜面。<see cref="App.演奏スコア"/>の生成元。 /// 選曲ステージで選曲確定後に更新される。 /// </summary> /// <remarks> /// <see cref="RandomSelectNode"/> がフォーカスされている場合は、ここには譜面がランダムに設定されるため /// <see cref="曲ツリー.フォーカスノード"/> の譜面とは必ずしも一致しないので注意。 /// </remarks> internal Score 演奏譜面 { get; set; } = null!; /// <summary> /// 現在演奏中のスコア。 /// 曲読み込みステージで<see cref="App.演奏譜面"/>を読み込んで生成される。 /// </summary> internal SSTF.スコア 演奏スコア { get; set; } = null!; /// <summary> /// <see cref="App.演奏スコア"/> に対応して生成されたWAVサウンドインスタンスの管理。 /// </summary> internal WAV管理 WAV管理 { get; set; } = null!; /// <summary> /// <see cref="App.演奏スコア"/> に対応して生成されたAVI動画インスタンスの管理。 /// </summary> internal AVI管理 AVI管理 { get; set; } = null!; // 生成と終了 /// <summary> /// コンストラクタ。 /// </summary> internal App() { InitializeComponent(); } /// <summary> /// アプリケーションの起動処理を行う。 /// </summary> protected override void OnLoad( EventArgs e ) { // ※ このメソッドは GUI スレッドで実行されるので、後回しにできる初期化処理は進行描画タスクに回して、 //   なるべく早くこのメソッドを抜けること。 Log.Header( "アプリケーション起動" ); using var _ = new LogBlock( Log.現在のメソッド名 ); // フォームを設定する。 this.Text = $"DTXMania2 Release {int.Parse( Application.ProductVersion.Split( '.' ).ElementAt( 0 ) ):000}"; this.ClientSize = new Size( 1024, 576 ); this.Icon = Properties.Resources.DTXMania2; this.ScreenMode = new ScreenMode( this ); Global.App = this; Global.Handle = this.Handle; // サウンドデバイスとサウンドタイマを初期化する。これらは入力デバイスで使用されるので先に初期化する。 this.サウンドデバイス = new SoundDevice( CSCore.CoreAudioAPI.AudioClientShareMode.Shared ); // マスタ音量(小:0~1:大)... 0.5を超えるとだいたいWASAPI共有モードのリミッターに抑制されるようになる // ※サウンドデバイスの音量プロパティはコンストラクタの実行後でないと set できないので、初期化子にはしないこと。(した場合の挙動は不安定) this.サウンドデバイス.音量 = 0.5f; this.サウンドタイマ = new SoundTimer( this.サウンドデバイス ); // システム設定ファイルを読み込む。 SystemConfig.最新版にバージョンアップする(); this.システム設定 = SystemConfig.読み込む(); this._システム設定をもとにリソース関連のフォルダ変数を更新する(); // 入力デバイスを初期化する。これらは GUI スレッドで行う必要がある。 this.ドラム入力 = new ドラム入力( this.Handle, this.サウンドタイマ ); // メインループを別スレッドで開始する。 if( !this._進行描画タスクを起動する().WaitOne( 5000 ) ) throw new TimeoutException( "進行描画タスクの起動処理がタイムアウトしました。" ); // 初期化完了。(進行描画タスクの起動後に) this._未初期化 = false; // 全画面モードが設定されているならここで全画面に切り替える。 if( this.システム設定.全画面モードである ) this.ScreenMode.ToFullscreenMode(); base.OnLoad( e ); } /// <summary> /// アプリケーションの終了処理を行う。 /// </summary> protected override void OnClosing( CancelEventArgs e ) { Log.Header( "アプリケーション終了" ); using var _ = new LogBlock( Log.現在のメソッド名 ); // 進行描画タスクのメインループに終了指示を送り、終了するのを待つ。 this._進行描画タスクを終了する(); // システム設定ファイルを保存する。 this.システム設定.保存する(); // 入力デバイスを破棄する。 this.ドラム入力.Dispose(); // サウンドデバイスとサウンドタイマを破棄する。 this.サウンドタイマ.Dispose(); this.サウンドデバイス.Dispose(); this.WAVキャッシュ?.Dispose(); // WAVキャッシュの破棄は最後に。 // 未初期化状態へ。 this._未初期化 = true; base.OnClosing( e ); } /// <summary> /// 再起動フラグをセットして、アプリケーションを終了する。 /// </summary> internal void 再起動する() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.再起動が必要 = true; this.Close(); } // 進行と描画 private ManualResetEvent _進行描画タスクを起動する() { using var _ = new LogBlock( Log.現在のメソッド名 ); var 起動完了通知 = new ManualResetEvent( false ); var app = this; var hWindow = app.Handle; Task.Run( () => { Log.現在のスレッドに名前をつける( "進行描画" ); Log.Info( "進行描画タスクを起動しました。" ); this._進行描画タスクのNETスレッドID = Thread.CurrentThread.ManagedThreadId; Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; 起動完了通知.Set(); this._進行描画のメインループを実行する( app, hWindow ); } ); return 起動完了通知; } private void _進行描画タスクを終了する() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( Thread.CurrentThread.ManagedThreadId != this._進行描画タスクのNETスレッドID ) { // 進行描画タスクに終了を指示し、完了を待つ。 var msg = new TaskMessage( 宛先: TaskMessage.タスク名.進行描画, 内容: TaskMessage.内容名.終了指示 ); if( !Global.TaskMessageQueue.Post( msg ).Wait( 5000 ) ) // 最大5秒待つ throw new TimeoutException( "進行描画タスクの終了がタイムアウトしました。" ); } else { // ハングアップ回避; 念のため。 Log.WARNING( "進行描画タスクから呼び出されました。完了通知待ちをスキップします。" ); } } private void _進行描画のメインループを実行する( App app, IntPtr hWindow ) { try { #region " 初期化 " //---------------- this._パイプラインサーバを起動する(); UserConfig.最新版にバージョンアップする(); ScoreDB.最新版にバージョンアップする(); RecordDB.最新版にバージョンアップする(); ScorePropertiesDB.最新版にバージョンアップする(); Global.生成する( app, hWindow, 設計画面サイズ: new SharpDX.Size2F( 1920f, 1080f ), 物理画面サイズ: new SharpDX.Size2F( this.ClientSize.Width, this.ClientSize.Height ) ); 画像.全インスタンスで共有するリソースを作成する( Global.GraphicResources.D3D11Device1, @"$(Images)\TextureVS.cso", @"$(Images)\TexturePS.cso" ); this.システムサウンド = new システムサウンド(); // 個々のサウンドの生成は後工程で。 this.ドラムサウンド = new ドラムサウンド(); //       〃 this.WAVキャッシュ = new CacheStore<CSCore.ISampleSource>() { ファイルからデータを生成する = ( path ) => { // Viewerでの再生速度は、ビュアーモード時のみ反映する。 double 再生速度 = Global.Options.ビュアーモードである ? this.ログオン中のユーザ.再生速度 * Global.App.演奏スコア.Viewerでの再生速度 : this.ログオン中のユーザ.再生速度; return SampleSourceFactory.Create( this.サウンドデバイス, path, 再生速度 ); } }; this._ユーザリストにユーザを登録する(); this.アイキャッチ管理 = new アイキャッチ管理(); // 最初のステージを生成する。 Log.Header( "起動ステージ" ); this.ステージ = new 起動.起動ステージ(); //---------------- #endregion var スワップチェーン表示タスク = new PresentSwapChainVSync(); var tick = new ManualResetEvent( false ); TaskMessage? 終了指示メッセージ = null; while( true ) { tick.WaitOne( 1 ); #region " 自分宛のメッセージが届いていたら、すべて処理する。" //---------------- foreach( var msg in Global.TaskMessageQueue.Get( TaskMessage.タスク名.進行描画 ) ) { switch( msg.内容 ) { case TaskMessage.内容名.終了指示: 終了指示メッセージ = msg; break; case TaskMessage.内容名.サイズ変更: { var newSize = (Size)msg.引数![ 0 ]; Global.GraphicResources.物理画面サイズを変更する( new SharpDX.Size2F( newSize.Width, newSize.Height ) ); break; } } } // 終了指示が来てたらループを抜ける。 if( null != 終了指示メッセージ ) break; //---------------- #endregion #region " 進行し、描画し、表示する。" //---------------- Global.Animation.進行する(); Global.Effekseer.進行する(); this.ステージ?.進行する(); if( スワップチェーン表示タスク.表示待機中 ) { // 表示タスクがすでに起動されているなら、描画と表示は行わない。 } else { // 表示タスクが起動していないなら、描画して、表示タスクを起動する。 this.ステージ?.描画する(); スワップチェーン表示タスク.表示する( Global.GraphicResources.DXGISwapChain1! ); } //---------------- #endregion #region " ステージの現在のフェーズにより処理分岐。" //---------------- switch( this.ステージ ) { case 起動.起動ステージ stage: { #region " 完了 → タイトルステージまたは演奏ステージへ " //---------------- if( stage.現在のフェーズ == 起動.起動ステージ.フェーズ.完了 ) { this.ステージ.Dispose(); if( Global.Options.ビュアーモードである ) { #region " (A) ビュアーモードなら演奏ステージへ " //---------------- Log.Header( "ビュアーステージ" ); // AutoPlayer でログイン。 if( !this.ログオンする( "AutoPlayer" ) ) { MessageBox.Show( Properties.Resources.TXT_AutoPlayerでのログオンに失敗しました, "DTXMania2 error" ); this.ステージ = null; this._アプリを終了する(); } else { Log.Info( "AutoPlayer でログオンしました。" ); } this.ステージ = new 演奏.演奏ステージ(); //---------------- #endregion } else { #region " (B) 通常時はタイトルステージへ " //---------------- Log.Header( "タイトルステージ" ); this.ステージ = new タイトル.タイトルステージ(); //---------------- #endregion } } //---------------- #endregion break; } case タイトル.タイトルステージ stage: { #region " キャンセル → 終了ステージへ " //---------------- if( stage.現在のフェーズ == タイトル.タイトルステージ.フェーズ.キャンセル ) { this.ステージ.Dispose(); Log.Header( "終了ステージ" ); this.ステージ = new 終了.終了ステージ(); } //---------------- #endregion #region " 完了 → 認証ステージへ " //---------------- else if( stage.現在のフェーズ == タイトル.タイトルステージ.フェーズ.完了 ) { this.ステージ.Dispose(); Log.Header( "認証ステージ" ); this.ステージ = new 認証.認証ステージ(); } //---------------- #endregion break; } case 認証.認証ステージ stage: { #region " キャンセル → タイトルステージへ " //---------------- if( stage.現在のフェーズ == 認証.認証ステージ.フェーズ.キャンセル ) { this.ステージ.Dispose(); Log.Header( "タイトルステージ" ); this.ステージ = new タイトル.タイトルステージ(); } //---------------- #endregion #region " 完了 → 選曲ステージへ " //---------------- else if( stage.現在のフェーズ == 認証.認証ステージ.フェーズ.完了 ) { // 選択中のユーザでログインする。ログオン中のユーザがあれば先にログオフされる。 this.ログオンする( this.ユーザリスト[ stage.現在選択中のユーザ ].ID ?? "AutoPlayer" ); this.ステージ.Dispose(); Log.Header( "選曲ステージ" ); this.ステージ = new 選曲.選曲ステージ(); } //---------------- #endregion break; } case 選曲.選曲ステージ stage: { #region " キャンセル → タイトルステージへ " //---------------- if( stage.現在のフェーズ == 選曲.選曲ステージ.フェーズ.キャンセル ) { // 曲ツリーの現行化タスクが動いていれば、一時停止する。 this.現行化.一時停止する(); this.ステージ.Dispose(); Log.Header( "タイトルステージ" ); this.ステージ = new タイトル.タイトルステージ(); } //---------------- #endregion #region " 確定_選曲 → 曲読み込みステージへ " //---------------- else if( stage.現在のフェーズ == 選曲.選曲ステージ.フェーズ.確定_選曲 ) { this.ステージ.Dispose(); Log.Header( "曲読み込みステージ" ); this.ステージ = new 曲読み込み.曲読み込みステージ(); } //---------------- #endregion #region " 確定_設定 → 設定ステージへ " //---------------- else if( stage.現在のフェーズ == 選曲.選曲ステージ.フェーズ.確定_設定 ) { this.ステージ.Dispose(); Log.Header( "オプション設定ステージ" ); this.ステージ = new オプション設定.オプション設定ステージ(); } //---------------- #endregion break; } case オプション設定.オプション設定ステージ stage: { #region " 完了 → 選曲ステージへ " //---------------- if( stage.現在のフェーズ == オプション設定.オプション設定ステージ.フェーズ.完了 ) { this.ステージ.Dispose(); Log.Header( "選曲ステージ" ); this.ステージ = new 選曲.選曲ステージ(); } //---------------- #endregion break; } case 曲読み込み.曲読み込みステージ stage: { #region " キャンセル → 選曲ステージへ " //---------------- if( stage.現在のフェーズ == 曲読み込み.曲読み込みステージ.フェーズ.キャンセル ) { this.ステージ.Dispose(); Log.Header( "選曲ステージ" ); this.ステージ = new 選曲.選曲ステージ(); } //---------------- #endregion #region " 完了 → 演奏ステージへ " //---------------- else if( stage.現在のフェーズ == 曲読み込み.曲読み込みステージ.フェーズ.完了 ) { this.ステージ.Dispose(); Log.Header( "演奏ステージ" ); this.ステージ = new 演奏.演奏ステージ(); // 曲読み込みステージ画面をキャプチャする(演奏ステージのクロスフェードで使う) ( (演奏.演奏ステージ)this.ステージ ).キャプチャ画面 = 画面キャプチャ.取得する( Global.GraphicResources.D3D11Device1, Global.GraphicResources.DXGISwapChain1, Global.GraphicResources.既定のD3D11RenderTargetView, Global.GraphicResources.既定のD2D1DeviceContext ); } //---------------- #endregion break; } case 演奏.演奏ステージ stage: { #region " キャンセル完了 → 選曲ステージへ " //---------------- if( stage.現在のフェーズ == 演奏.演奏ステージ.フェーズ.キャンセル完了 ) // ビュアーモードではこのフェーズにはならない。 { this.ステージ.Dispose(); Log.Header( "選曲ステージ" ); this.ステージ = new 選曲.選曲ステージ(); } //---------------- #endregion #region " クリア → 結果ステージへ " //---------------- else if( stage.現在のフェーズ == 演奏.演奏ステージ.フェーズ.クリア ) { this.ステージ.Dispose(); Log.Header( "結果ステージ" ); this.ステージ = new 結果.結果ステージ( stage.成績 ); } //---------------- #endregion #region " 失敗 → 現在未対応 " //---------------- else if( stage.現在のフェーズ == 演奏.演奏ステージ.フェーズ.失敗 ) { // todo: 演奏失敗処理の実装 throw new NotImplementedException(); } //---------------- #endregion break; } case 結果.結果ステージ stage: { #region " 完了 → 選曲ステージへ " //---------------- if( stage.現在のフェーズ == 結果.結果ステージ.フェーズ.完了 ) { this.ステージ.Dispose(); Log.Header( "選曲ステージ" ); this.ステージ = new 選曲.選曲ステージ(); } //---------------- #endregion break; } case 終了.終了ステージ stage: { #region " 完了 → アプリ終了 " //---------------- if( stage.現在のフェーズ == 終了.終了ステージ.フェーズ.完了 ) { this._アプリを終了する(); } //---------------- #endregion break; } } //---------------- #endregion } #region " 終了 " //---------------- this._パイプラインサーバを終了する(); // これ以上受信しないよう真っ先に終了。 this.現行化.終了する(); this.ステージ?.Dispose(); this.アイキャッチ管理.Dispose(); foreach( var song in this.全曲リスト ) song.Dispose(); // 全譜面リストもここで解放される。 foreach( var tree in this.曲ツリーリスト ) tree.Dispose(); this.ドラムサウンド.Dispose(); this.システムサウンド.Dispose(); 画像.全インスタンスで共有するリソースを解放する(); Global.解放する(); //---------------- #endregion 終了指示メッセージ.完了通知.Set(); } #if !DEBUG // GUIスレッド以外のスレッドで発生した例外は、Debug 版だとデバッガがキャッチするが、 // Release 版だと何も表示されずスルーされるので、念のためログ出力しておく。 catch( Exception e ) { Log.ERROR( $"例外が発生しました。\n{e}" ); } #endif finally { Log.Info( "進行描画タスクを終了しました。" ); } } internal void 画面をクリアする() { var d3ddc = Global.GraphicResources.既定のD3D11DeviceContext; // 既定のD3Dレンダーターゲットビューを黒でクリアする。 d3ddc.ClearRenderTargetView( Global.GraphicResources.既定のD3D11RenderTargetView, SharpDX.Color4.Black ); // 既定の深度/ステンシルバッファをクリアする。 d3ddc.ClearDepthStencilView( Global.GraphicResources.既定のD3D11DepthStencilView, SharpDX.Direct3D11.DepthStencilClearFlags.Depth | SharpDX.Direct3D11.DepthStencilClearFlags.Stencil, depth: 1.0f, stencil: 0 ); } // ログオンとログオフ /// <summary> /// 指定されたユーザでログオンする。 /// 現在ログオン中のユーザがあれば、先にログオフする。 /// </summary> /// <param name="ユーザID"></param> /// <returns>ログオンに成功したらtrue。</returns> internal bool ログオンする( string ユーザID ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // 現在ログオン中のユーザがあれば、先にログオフする。 this.ログオフする(); // 新しいユーザを選択する。 if( !this.ユーザリスト.SelectItem( ( user ) => user.ID == ユーザID ) ) { Log.ERROR( $"ユーザ「{ユーザID}」のログオンに失敗しました。ユーザが存在しません。" ); return false; } var userConfig = this.ログオン中のユーザ; var roots = this.曲ツリーリスト.Select( ( t ) => t.ルートノード ); // すべての曲ツリーのユーザ依存情報をリセットし、属性のみ今ここで現行化する。 this.現行化.リセットする( roots, userConfig ); this.現行化.すべての譜面について属性を現行化する( userConfig.ID! ); // 評価順曲ツリーを新しい属性にあわせて再構築する。 if( !Global.Options.ビュアーモードである ) { var ratingTree = (曲ツリー_評価順)this.曲ツリーリスト[ 1 ]; // [1]評価順 ratingTree.再構築する(); } // すべての曲ツリーの現行化を開始する。 this.現行化.開始する( roots, this.ログオン中のユーザ ); // 選択する曲ツリーリストを初期化。 foreach( var tree in this.曲ツリーリスト ) tree.ルートノード.子ノードリスト.SelectFirst(); this.曲ツリーリスト.SelectFirst(); // 完了。 Log.Info( $"{ユーザID} でログオンしました。" ); return true; } /// <summary> /// 現在ログオン中のユーザをログオフする。 /// </summary> internal void ログオフする() { using var _ = new LogBlock( Log.現在のメソッド名 ); var userConfig = this.ユーザリスト.SelectedItem; if( null != userConfig ) { this.現行化.終了する(); Log.Info( $"{userConfig.ID} をログオフしました。" ); } // ユーザを未選択状態へ。 this.ユーザリスト.SelectItem( -1 ); } // ウィンドウサイズの変更 /* 次の2通りがある。 * * A.ユーザのドラッグによるサイズ変更。 * → ResizeBegin ~ ResizeEnd の範囲内で Resize が発生するがいったん無視し、ResizeEnd のタイミングでサイズの変更を行う。 * * B.最大化、最小化など。 * → ResizeBegin ~ ResizeEnd の範囲外で Resize が発生するので、そのタイミングでサイズの変更を行う。 */ protected override void OnResizeBegin( EventArgs e ) { this._リサイズ中 = true; // リサイズ開始 base.OnResizeBegin( e ); } protected override void OnResizeEnd( EventArgs e ) { this._リサイズ中 = false; // リサイズ終了(先に設定) if( this.WindowState == FormWindowState.Minimized ) { // (A) 最小化された → 何もしない } else if( this.ClientSize.IsEmpty ) { // (B) クライアントサイズが空 → たまに起きるらしい。スキップする。 } else { // (C) それ以外は Resize イベントハンドラへ委譲。 this.OnResize( e ); } base.OnResizeEnd( e ); } protected override void OnResize( EventArgs e ) { if( this._未初期化 || this._リサイズ中 ) { //Log.Info( "未初期化、またはリサイズ中なので無視します。" ); return; } else { using var _ = new LogBlock( Log.現在のメソッド名 ); Log.Info( $"新画面サイズ: {this.ClientSize}" ); // スワップチェーンとその依存リソースを解放し、改めて作成しなおすように進行描画タスクへ指示する。 var msg = new TaskMessage( 宛先: TaskMessage.タスク名.進行描画, 内容: TaskMessage.内容名.サイズ変更, 引数: new object[] { this.ClientSize } ); Global.TaskMessageQueue.Post( msg ); } base.OnResize( e ); } private bool _リサイズ中 = false; // パイプラインサーバ private CancellationTokenSource _PipeServerCancellationTokenSource = null!; private async void _パイプラインサーバを起動する() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this._PipeServerCancellationTokenSource?.Dispose(); this._PipeServerCancellationTokenSource = new CancellationTokenSource(); var cancelToken = this._PipeServerCancellationTokenSource.Token; await Task.Run( async () => { Log.Info( "パイプラインサーバを起動しました。" ); int 例外発生回数 = 0; bool ビュアーモードではない = !Global.Options.ビュアーモードである; while( !cancelToken.IsCancellationRequested ) { try { // パイプラインサーバを起動する。 using var pipeServer = new NamedPipeServerStream( pipeName: Program._ビュアー用パイプライン名, direction: PipeDirection.In, maxNumberOfServerInstances: 2 ); // 再起動の際に一時的に 2 個開く瞬間がある // クライアントの接続を待つ。 await pipeServer.WaitForConnectionAsync( cancelToken ); // キャンセルされたならループを抜ける。 if( cancelToken.IsCancellationRequested ) break; Log.Info( "パイプラインクライアントと接続しました。" ); // パイプラインからYAMLを受取る。 var ss = new StreamStringForNamedPipe( pipeServer ); var yamlText = ss.ReadString(); Trace.WriteLine( "受信文字列\n--- ここから ---" ); Trace.WriteLine( $"{yamlText}" ); Trace.WriteLine( "--- ここまで ---" ); if( yamlText.Nullまたは空である() || yamlText == "ping" ) continue; // 空送信またはテスト送信 // 受け取ったオプションは、ビュアーモードでなければ実行されない。 if( ビュアーモードではない ) continue; // YAMLからコマンドラインオプションを復元する。 var options = CommandLineOptions.FromYaml( yamlText ); // オプションを担当ステージに送る。 if( options.再生停止 ) { // 停止 演奏.演奏ステージ.OptionsQueue.Enqueue( options ); } else if( options.再生開始 ) { // 停止と 演奏.演奏ステージ.OptionsQueue.Enqueue( new CommandLineOptions() { 再生停止 = true } ); // 開始 演奏.演奏ステージ.OptionsQueue.Enqueue( options ); } else { // hack: その他のコマンドラインオプションへの対応 } } catch( Exception e ) { Log.ERROR( $"パイプラインサーバで例外が発生しました。[{e.Message}]" ); if( 10 < ++例外発生回数 ) { Log.ERROR( "例外発生回数が 10 を越えたので、異常と見なして終了します。" ); break; } } } Log.Info( "パイプラインサーバを終了しました。" ); } ); } private void _パイプラインサーバを終了する() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( !this._PipeServerCancellationTokenSource.IsCancellationRequested ) this._PipeServerCancellationTokenSource.Cancel(); //this._PipeServerCancellationTokenSource.Dispose(); } // ウィンドウメッセージ protected override void WndProc( ref Message m ) { const int WM_INPUT = 0x00FF; switch( m.Msg ) { case WM_INPUT: this.OnInput( m ); break; } base.WndProc( ref m ); } protected override void OnKeyDown( KeyEventArgs e ) { #region " F11 → 全画面/ウィンドウモードを切り替える。" //---------------- if( e.KeyCode == Keys.F11 ) { // ScreenMode は非同期処理なので、すぐに値が反映されるとは限らない。 // なので、ログオン中のユーザへの設定は、その変更より先に行なっておく。 this.システム設定.全画面モードである = this.ScreenMode.IsWindowMode; // 先に設定するので Mode が逆になっていることに注意。 if( this.ScreenMode.IsWindowMode ) this.ScreenMode.ToFullscreenMode(); else this.ScreenMode.ToWindowMode(); } //---------------- #endregion base.OnKeyDown( e ); } protected virtual void OnInput( in Message m ) { RawInput.RawInputData rawInputData; #region " RawInput データを取得する。" //---------------- unsafe { // RawInputData 構造体(可変長)の実サイズを取得する。 int dataSize = 0; if( 0 > RawInput.GetRawInputData( m.LParam, RawInput.DataType.Input, null, ref dataSize, Marshal.SizeOf<RawInput.RawInputHeader.Native>() ) ) { Log.ERROR( $"GetRawInputData(): error = { Marshal.GetLastWin32Error()}" ); return; } // RawInputData 構造体の実データを取得する。 var dataBytes = stackalloc byte[ dataSize ]; if( 0 > RawInput.GetRawInputData( m.LParam, RawInput.DataType.Input, dataBytes, &dataSize, Marshal.SizeOf<RawInput.RawInputHeader.Native>() ) ) { Log.ERROR( $"GetRawInputData(): error = { Marshal.GetLastWin32Error()}" ); return; } // 取得された実データは byte[] なので、これを RawInputData 構造体に変換する。 rawInputData = new RawInput.RawInputData( *( (RawInput.RawInputData.Native*)dataBytes ) ); } //---------------- #endregion this.ドラム入力.OnInput( rawInputData ); } // ローカル /// <summary> /// アプリの初期化が完了していなければ true。 /// 起動直後は true, OnLoad() で false, OnClosing() で true になる。 /// </summary> /// <remarks> /// アプリの OnLoad() より前に OnResize() が呼び出されることがあるので、その対策用。 /// </remarks> private bool _未初期化 = true; private int _進行描画タスクのNETスレッドID; private void _システム設定をもとにリソース関連のフォルダ変数を更新する() { // DrumSounds var drumSounds = this.システム設定.DrumSoundsFolder; Folder.フォルダ変数を追加または更新する( "DrumSounds", ( Path.IsPathRooted( drumSounds.変数なしパス ) ) ? drumSounds.変数なしパス : new VariablePath( @$"$(ResourcesRoot)\{drumSounds}" ).変数なしパス ); Log.Info( $"DrumSounds folder: {new VariablePath( Folder.フォルダ変数の内容を返す( "DrumSounds" ) ).変数付きパス}" ); // SystemSounds var systemSounds = this.システム設定.SystemSoundsFolder; Folder.フォルダ変数を追加または更新する( "SystemSounds", ( Path.IsPathRooted( systemSounds.変数なしパス ) ) ? systemSounds.変数なしパス : new VariablePath( @$"$(ResourcesRoot)\{systemSounds}" ).変数なしパス ); Log.Info( $"SystemSounds folder: {new VariablePath( Folder.フォルダ変数の内容を返す( "SystemSounds" ) ).変数付きパス}" ); // Images var images = this.システム設定.ImagesFolder; Folder.フォルダ変数を追加または更新する( "Images", ( Path.IsPathRooted( images.変数なしパス ) ) ? images.変数なしパス : new VariablePath( @$"$(ResourcesRoot)\{images}" ).変数なしパス ); Log.Info( $"Images folder: {new VariablePath( Folder.フォルダ変数の内容を返す( "Images" ) ).変数付きパス}" ); } private void _ユーザリストにユーザを登録する() { // パターンに該当するファイルをすべて列挙する。 var userYamls = Directory.EnumerateFiles( Folder.フォルダ変数の内容を返す( "AppData" ), @"User_*.yaml", SearchOption.TopDirectoryOnly ); int headLength = "User_".Length; int tailLength = ".yaml".Length; foreach( var userYaml in userYamls ) { // ファイル名からユーザIDを抽出。 var fname = Path.GetFileName( userYaml ); var userId = fname[ headLength..( fname.Length - tailLength ) ]; var userConfig = ユーザ設定.読み込む( userId ); this.ユーザリスト.Add( userConfig ); } } private void _アプリを終了する() { this.BeginInvoke( new Action( () => { // UIスレッドで実行する this.Close(); } ) ); } } } <|start_filename|>SSTFEditor/UndoRedo/セルBase.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace SSTFEditor.UndoRedo { class セルBase { public bool 所有権がある( object 所有者候補 ) => ( this.所有者ID == 所有者候補 ); public void 所有権を放棄する( object 現所有者 ) { if( this.所有者ID == 現所有者 ) this.所有者ID = null; } public virtual void Redoを実行する() { } public virtual void Undoを実行する() { } protected object 所有者ID = null; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネル/パネル_整数.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.オプション設定 { /// <summary> /// 数値ボックス。整数のみ、単位表示は任意。 /// </summary> class パネル_整数 : パネル { // プロパティ public int 最小値 { get; } public int 最大値 { get; } public int 現在の値 { get; set; } public int 増加減単位値 { get; set; } public string 単位 { get; set; } // 生成と終了 public パネル_整数( string パネル名, int 最小値, int 最大値, int 初期値, int 増加減単位値 = 1, string 単位 = "", Action<パネル>? 値の変更処理 = null, Color4? ヘッダ色 = null ) : base( パネル名, 値の変更処理, ヘッダ色 ) { this.最小値 = 最小値; this.最大値 = 最大値; this.現在の値 = 初期値; this.増加減単位値 = 増加減単位値; this.単位 = 単位; this._項目画像 = new 文字列画像D2D() { 表示文字列 = "", フォントサイズpt = 34f, 前景色 = Color4.White }; } public override void Dispose() { this._項目画像.Dispose(); base.Dispose(); // 忘れずに } public override string ToString() => $"{this.パネル名}, 最小値:{this.最小値}, 最大値:{this.最大値}, 増加減単位値:{this.増加減単位値}, 現在の値:{this.現在の値}"; // 入力 public override void 左移動キーが入力された() { // 値を減らす。 this.現在の値 = Math.Max( this.最小値, this.現在の値 - this.増加減単位値 ); base.左移動キーが入力された(); } public override void 右移動キーが入力された() { // 値を増やす。 this.現在の値 = Math.Min( this.最大値, this.現在の値 + this.増加減単位値 ); base.右移動キーが入力された(); } public override void 確定キーが入力された() { // 値を増やす。 this.現在の値 = ( this.現在の値 + this.増加減単位値 ); // 最大値を超えたら最小値へループ。 if( this.現在の値 > this.最大値 ) this.現在の値 = this.最小値; base.確定キーが入力された(); } // 進行と描画 public override void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置, bool 選択中 ) { // (1) パネルの下地と名前を描画。 base.進行描画する( d2ddc, 左位置, 上位置, 選択中 ); // (2) 値を描画。 this._項目画像.表示文字列 = $"{this.現在の値} {this.単位}"; this._項目画像.ビットマップを生成または更新する( d2ddc ); // このあと画像のサイズが必要になるので、先に生成/更新する。 float 拡大率Y = (float)this._パネルの高さ割合.Value; float 項目の上下マージン = this.項目領域.Height * ( 1f - 拡大率Y ) / 2f; var 項目矩形 = new RectangleF( x: this.項目領域.X + 左位置, y: this.項目領域.Y + 上位置 + 項目の上下マージン, width: this.項目領域.Width, height: this.項目領域.Height * 拡大率Y ); const float 左右マージンの最低値dpx = 20f; float 拡大率X = Math.Min( 1f, ( 項目矩形.Width - 左右マージンの最低値dpx ) / this._項目画像.画像サイズdpx.Width ); this._項目画像.描画する( d2ddc, 項目矩形.Left + ( 項目矩形.Width - this._項目画像.画像サイズdpx.Width * 拡大率X ) / 2f, 項目矩形.Top + ( 項目矩形.Height - this._項目画像.画像サイズdpx.Height * 拡大率Y ) / 2f, X方向拡大率: 拡大率X, Y方向拡大率: 拡大率Y ); } // ローカル private readonly 文字列画像D2D _項目画像; } } <|start_filename|>FDK/サウンド/Sources/XAOnMemoryWaveSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using CSCore; namespace FDK { /// <summary> /// 指定されたメディアファイルを XA としてデコードして、<see cref="CSCore.IWaveSource"/> オブジェクトを生成する。 /// リサンプラーなし版。 /// </summary> public unsafe class XAOnMemoryWaveSource : IWaveSource { // プロパティ public bool CanSeek => true; // オンメモリなので常にサポートする。 public WaveFormat WaveFormat { get; protected set; } /// <summary> /// デコード後のオーディオデータのすべての長さ[byte]。 /// </summary> public long Length => this._DecodedWaveData.Length; /// <summary> /// 現在の再生位置[byte]。 /// </summary> public long Position { get => this._Position; set => this._Position = this._位置をブロック境界単位にそろえて返す( value, this.WaveFormat.BlockAlign ); } // 生成と終了 /// <summary> /// コンストラクタ。 /// 指定されたファイルを指定されたフォーマットでデコードし、内部にオンメモリで保管する。 /// </summary> public XAOnMemoryWaveSource( VariablePath ファイルパス, WaveFormat deviceFormat ) { var bjxa = new bjxa.Decoder(); using var fs = new FileStream( ファイルパス.変数なしパス, FileMode.Open, FileAccess.Read ); // ヘッダを読み込んでフォーマットを得る。 var format = bjxa.ReadHeader( fs ); // WaveFormat プロパティを構築する。 this.WaveFormat = new WaveFormat( (int)format.SamplesRate, (int)format.SampleBits, (int)format.Channels, AudioEncoding.Pcm ); // デコードする。 var xabuf = new byte[ format.Blocks * format.BlockSizeXa ]; var pcmbuf = new short[ format.Blocks * format.BlockSizePcm ]; if( fs.Read( xabuf, 0, xabuf.Length ) != xabuf.Length ) throw new Exception( "xaデータの読み込みに失敗しました。" ); int ret = bjxa.Decode( xabuf, pcmbuf, out long pcm_data ); // Waveバッファに転送する。 this._DecodedWaveData = new byte[ pcmbuf.Length * 2 ]; //this._DecodedWaveData = new byte[ pcm_data * 2 ]; --> バッファが足りない Buffer.BlockCopy( pcmbuf, 0, this._DecodedWaveData, 0, this._DecodedWaveData.Length ); } public virtual void Dispose() { } // 出力 /// <summary> /// 連続したデータを読み込み、<see cref="Position"/> を読み込んだ数だけ進める。 /// </summary> /// <param name="buffer">読み込んだデータを格納するための配列。</param> /// <param name="offset"><paramref name="buffer"/> に格納を始める位置。</param> /// <param name="count">読み込む最大のデータ数。</param> /// <returns><paramref name="buffer"/> に読み込んだデータの総数。</returns> public int Read( byte[] buffer, int offset, int count ) { // ※ 音がめちゃくちゃになるとうざいので、このメソッド内では例外を出さないこと。 if( ( null == this._DecodedWaveData ) || ( null == buffer ) ) return 0; long 読み込み可能な最大count = ( this.Length - this._Position ); if( count > 読み込み可能な最大count ) count = (int)読み込み可能な最大count; if( 0 < count ) { Buffer.BlockCopy( src: this._DecodedWaveData, srcOffset: (int)this._Position, dst: buffer, dstOffset: offset, count: count ); this._Position += count; } return count; } // ローカル private byte[] _DecodedWaveData; private long _Position = 0; private long _位置をブロック境界単位にそろえて返す( long position, long blockAlign ) { return ( position - ( position % blockAlign ) ); } } } <|start_filename|>DTXMania2/保存データ/SystemConfig/old/v002_キーバインディング.cs<|end_filename|> using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Text.RegularExpressions; using System.Windows.Forms; using YamlDotNet.Core; using YamlDotNet.Serialization; namespace DTXMania2.old.SystemConfig { using IdKey = DTXMania2.SystemConfig.IdKey; class v002_キーバインディング : ICloneable { /// <summary> /// MIDI番号(0~7)とMIDIデバイス名のマッピング用 Dictionary。 /// </summary> public Dictionary<int, string> MIDIデバイス番号toデバイス名 { get; protected set; } /// <summary> /// キーボードの入力(<see cref="System.Windows.Forms.Keys"/>)からドラム入力へのマッピング用 Dictionary 。 /// </summary> [Description( "キーボードの入力割り当て(デバイスID,キーID: ドラム入力種別)" )] public Dictionary<IdKey, ドラム入力種別> キーボードtoドラム { get; protected set; } /// <summary> /// MIDI入力の入力(MIDIノート番号)からドラム入力へのマッピング用 Dictionary 。 /// </summary> public Dictionary<IdKey, ドラム入力種別> MIDItoドラム { get; protected set; } public int FootPedal最小値 { get; set; } public int FootPedal最大値 { get; set; } /// <summary> /// コンストラクタ。 /// </summary> public v002_キーバインディング() { this.FootPedal最小値 = 0; this.FootPedal最大値 = 90; // VH-11 の Normal Resolution での最大値 this.MIDIデバイス番号toデバイス名 = new Dictionary<int, string>(); this.キーボードtoドラム = new Dictionary<IdKey, ドラム入力種別>() { { new IdKey( 0, (int) Keys.Q ), ドラム入力種別.LeftCrash }, { new IdKey( 0, (int) Keys.Return ), ドラム入力種別.LeftCrash }, { new IdKey( 0, (int) Keys.A ), ドラム入力種別.HiHat_Open }, { new IdKey( 0, (int) Keys.Z ), ドラム入力種別.HiHat_Close }, { new IdKey( 0, (int) Keys.S ), ドラム入力種別.HiHat_Foot }, { new IdKey( 0, (int) Keys.X ), ドラム入力種別.Snare }, { new IdKey( 0, (int) Keys.C ), ドラム入力種別.Bass }, { new IdKey( 0, (int) Keys.Space ), ドラム入力種別.Bass }, { new IdKey( 0, (int) Keys.V ), ドラム入力種別.Tom1 }, { new IdKey( 0, (int) Keys.B ), ドラム入力種別.Tom2 }, { new IdKey( 0, (int) Keys.N ), ドラム入力種別.Tom3 }, { new IdKey( 0, (int) Keys.M ), ドラム入力種別.RightCrash }, { new IdKey( 0, (int) Keys.K ), ドラム入力種別.Ride }, }; this.MIDItoドラム = new Dictionary<IdKey, ドラム入力種別>() { // うちの環境(2017.6.11) { new IdKey( 0, 36 ), ドラム入力種別.Bass }, { new IdKey( 0, 30 ), ドラム入力種別.RightCrash }, { new IdKey( 0, 29 ), ドラム入力種別.RightCrash }, { new IdKey( 1, 51 ), ドラム入力種別.RightCrash }, { new IdKey( 1, 52 ), ドラム入力種別.RightCrash }, { new IdKey( 1, 57 ), ドラム入力種別.RightCrash }, { new IdKey( 0, 52 ), ドラム入力種別.RightCrash }, { new IdKey( 0, 43 ), ドラム入力種別.Tom3 }, { new IdKey( 0, 58 ), ドラム入力種別.Tom3 }, { new IdKey( 0, 42 ), ドラム入力種別.HiHat_Close }, { new IdKey( 0, 22 ), ドラム入力種別.HiHat_Close }, { new IdKey( 0, 26 ), ドラム入力種別.HiHat_Open }, { new IdKey( 0, 46 ), ドラム入力種別.HiHat_Open }, { new IdKey( 0, 44 ), ドラム入力種別.HiHat_Foot }, { new IdKey( 0, 255 ), ドラム入力種別.HiHat_Control }, // FDK の MidiIn クラスは、FootControl を ノート 255 として扱う。 { new IdKey( 0, 48 ), ドラム入力種別.Tom1 }, { new IdKey( 0, 50 ), ドラム入力種別.Tom1 }, { new IdKey( 0, 49 ), ドラム入力種別.LeftCrash }, { new IdKey( 0, 55 ), ドラム入力種別.LeftCrash }, { new IdKey( 1, 48 ), ドラム入力種別.LeftCrash }, { new IdKey( 1, 49 ), ドラム入力種別.LeftCrash }, { new IdKey( 1, 59 ), ドラム入力種別.LeftCrash }, { new IdKey( 0, 45 ), ドラム入力種別.Tom2 }, { new IdKey( 0, 47 ), ドラム入力種別.Tom2 }, { new IdKey( 0, 51 ), ドラム入力種別.Ride }, { new IdKey( 0, 59 ), ドラム入力種別.Ride }, { new IdKey( 0, 38 ), ドラム入力種別.Snare }, { new IdKey( 0, 40 ), ドラム入力種別.Snare }, { new IdKey( 0, 37 ), ドラム入力種別.Snare }, }; } /// <summary> /// メンバを共有しない深いコピーを返す。 /// </summary> public object Clone() { var clone = new v002_キーバインディング(); clone.MIDIデバイス番号toデバイス名 = new Dictionary<int, string>(); foreach( var kvp in this.MIDIデバイス番号toデバイス名 ) clone.MIDIデバイス番号toデバイス名.Add( kvp.Key, kvp.Value ); clone.キーボードtoドラム = new Dictionary<IdKey, ドラム入力種別>(); foreach( var kvp in this.キーボードtoドラム ) clone.キーボードtoドラム.Add( kvp.Key, kvp.Value ); clone.MIDItoドラム = new Dictionary<IdKey, ドラム入力種別>(); foreach( var kvp in this.MIDItoドラム ) clone.MIDItoドラム.Add( kvp.Key, kvp.Value ); clone.FootPedal最小値 = this.FootPedal最小値; clone.FootPedal最大値 = this.FootPedal最大値; return clone; } } } <|start_filename|>DTXMania2/ステージ/07演奏/演奏ステージ.cs<|end_filename|> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using SharpDX; using SharpDX.Direct2D1; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2.演奏 { class 演奏ステージ : IStage { // プロパティ public const float ヒット判定位置Ydpx = 847f; public enum フェーズ { 演奏状態初期化, フェードイン, 演奏開始, 表示, クリア, 失敗, キャンセル通知, キャンセル時フェードアウト, キャンセル完了, // 以下、ビュアーモード用。 指示待機, 曲読み込み開始, 曲読み込み完了待ち, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.キャンセル完了; /// <summary> /// フェードインアイキャッチの遷移元画面。 /// 利用前に、外部から設定される。 /// </summary> public Bitmap キャプチャ画面 { get; set; } = null!; public 成績 成績 { get; protected set; } = null!; /// <summary> /// ビュアーモード時、他プロセスから受け取ったオプションがここに格納される。 /// </summary> public static ConcurrentQueue<CommandLineOptions> OptionsQueue { get; } = new ConcurrentQueue<CommandLineOptions>(); /// <summary> /// ビュアーモードで変更可能。通常モードでは -1、 /// </summary> public static int 演奏開始小節番号 { get; set; } = -1; /// <summary> /// ビュアーモードで変更可能。通常モードでは無効。 /// </summary> public static bool ビュアーモードでドラム音を再生する { get; set; } = true; // 生成と終了 public 演奏ステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); var userConfig = Global.App.ログオン中のユーザ; this._背景画像 = new 画像D2D( @"$(Images)\PlayStage\Background.png" ); this._レーンフレーム = new レーンフレーム(); this._曲名パネル = new 曲名パネル(); this._ドラムキットとヒットバー = new ドラムキットとヒットバー(); this._レーンフラッシュ = new レーンフラッシュ(); this._ドラムチップ = new ドラムチップ(); this._判定文字列 = new 判定文字列(); this._チップ光 = new チップ光(); this._左サイドクリアパネル = new 左サイドクリアパネル(); this._右サイドクリアパネル = new 右サイドクリアパネル(); this._判定パラメータ表示 = new 判定パラメータ表示(); this._フェーズパネル = new フェーズパネル(); this._コンボ表示 = new コンボ表示(); this._クリアメーター = new クリアメーター(); this._スコア表示 = new スコア表示(); this._プレイヤー名表示 = new プレイヤー名表示() { 名前 = userConfig.名前 }; this._譜面スクロール速度 = new 譜面スクロール速度( userConfig.譜面スクロール速度 ); this._達成率表示 = new 達成率表示(); this._曲別SKILL = new 曲別SKILL(); this._エキサイトゲージ = new エキサイトゲージ(); this._システム情報 = new システム情報(); this._数字フォント中グレー48x64 = new フォント画像D2D( @"$(Images)\NumberFont48x64White.png", @"$(Images)\NumberFont48x64.yaml", 文字幅補正dpx: -16f, 不透明度: 0.3f ); this._小節線色 = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Color.White ); this._拍線色 = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Color.Gray ); this._スコア指定の背景画像 = null!; this._チップの演奏状態 = null!; this._フェードインカウンタ = new Counter(); this._LoadingSpinner = new LoadingSpinner(); this._早送りアイコン = new 早送りアイコン(); this.成績 = new 成績(); // 最初のフェーズへ。 this.現在のフェーズ = ( Global.Options.ビュアーモードである ) ? フェーズ.指示待機 : フェーズ.演奏状態初期化; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); #region " 演奏状態を終了する。" //---------------- this._描画開始チップ番号 = -1; //Global.App.WAV管理?.Dispose(); --> ここではまだ解放しない。 Global.App.AVI管理?.Dispose(); //---------------- #endregion // ユーザDBに変更があれば保存する。 Global.App.ログオン中のユーザ.保存する(); this.キャプチャ画面?.Dispose(); this._スコア指定の背景画像?.Dispose(); this._早送りアイコン.Dispose(); this._LoadingSpinner.Dispose(); this._拍線色.Dispose(); this._小節線色.Dispose(); this._数字フォント中グレー48x64.Dispose(); this._システム情報.Dispose(); this._エキサイトゲージ.Dispose(); this._曲別SKILL.Dispose(); this._達成率表示.Dispose(); this._譜面スクロール速度.Dispose(); this._プレイヤー名表示.Dispose(); this._スコア表示.Dispose(); this._クリアメーター.Dispose(); this._コンボ表示.Dispose(); this._フェーズパネル.Dispose(); this._判定パラメータ表示.Dispose(); this._右サイドクリアパネル.Dispose(); this._左サイドクリアパネル.Dispose(); this._チップ光.Dispose(); this._判定文字列.Dispose(); this._ドラムチップ.Dispose(); this._レーンフラッシュ.Dispose(); this._ドラムキットとヒットバー.Dispose(); this._曲名パネル.Dispose(); this._レーンフレーム.Dispose(); this._背景画像.Dispose(); } // 進行と描画 public void 進行する() { this._システム情報.FPSをカウントしプロパティを更新する(); CommandLineOptions? options = null!; var userConfig = Global.App.ログオン中のユーザ; #region " ビュアーモード時、オプションが届いていれば処理する。" //---------------- if( Global.Options.ビュアーモードである && OptionsQueue.TryDequeue( out options ) ) { if( options.再生停止 ) { Log.Info( "演奏を即時終了します。" ); Global.App.WAV管理?.すべての発声を停止する(); // DTXでのBGMサウンドはこっちに含まれる。 this.現在のフェーズ = フェーズ.指示待機; } } //---------------- #endregion switch( this.現在のフェーズ ) { case フェーズ.演奏状態初期化: { #region " 演奏状態を初期化し、演奏開始またはフェードインフェーズへ。" //---------------- this._演奏状態を初期化する(); this._フェードインカウンタ = new Counter( 0, 100, 10 ); // 次のフェーズへ。 this.現在のフェーズ = ( Global.Options.ビュアーモードである ) ? フェーズ.演奏開始 : フェーズ.フェードイン; //---------------- #endregion break; } case フェーズ.フェードイン: { #region " フェードインが完了したら演奏開始フェーズへ。" //---------------- if( this._フェードインカウンタ.終了値に達した ) { Log.Info( "演奏を開始します。" ); this.現在のフェーズ = フェーズ.演奏開始; } //---------------- #endregion break; } case フェーズ.演奏開始: { #region " 演奏を開始し、表示フェーズへ。" //---------------- // 現時点での入力をすべて取り出してクリアする。 Global.App.ドラム入力.すべての入力デバイスをポーリングする( 入力履歴を記録する: false ); // 演奏を開始する。 this._描画開始チップ番号 = -1; // -1 以外になれば演奏開始。 if( Global.Options.ビュアーモードである && 0 <= 演奏ステージ.演奏開始小節番号 ) { #region " (A) 演奏開始小節番号から演奏を開始する。" //---------------- this._指定小節へ移動する( 演奏ステージ.演奏開始小節番号, out this._描画開始チップ番号, out double 演奏開始時刻sec ); Global.App.サウンドタイマ.リセットする( 演奏開始時刻sec ); //---------------- #endregion } else { #region " (B) 最初から再生する。" //---------------- this._描画開始チップ番号 = 0; Global.App.サウンドタイマ.リセットする(); //---------------- #endregion } // 次のフェーズへ。 this._表示フェーズの結果 = 演奏結果.演奏中; this.現在のフェーズ = フェーズ.表示; //---------------- #endregion break; } case フェーズ.表示: { if( this._表示フェーズの結果 == 演奏結果.クリア ) { #region " 演奏をクリアしたら、クリア or 指示待機フェーズへ。" //---------------- this.現在のフェーズ = ( Global.Options.ビュアーモードである ) ? フェーズ.指示待機 : フェーズ.クリア; //---------------- #endregion } else if( this._表示フェーズの結果 == 演奏結果.失敗 ) { // todo: StageFailed したら失敗フェーズへ } else { this._入力とヒット処理を行う(); } break; } case フェーズ.キャンセル通知: { #region " フェードアウトを開始してキャセル時フェードアウトフェーズへ。" //---------------- Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( 半回転黒フェード ) ); this.現在のフェーズ = フェーズ.キャンセル時フェードアウト; //---------------- #endregion break; } case フェーズ.キャンセル時フェードアウト: { #region " フェードアウトが完了したらキャンセル完了フェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) this.現在のフェーズ = フェーズ.キャンセル完了; //---------------- #endregion break; } case フェーズ.クリア: { break; } case フェーズ.失敗: { // todo: 失敗フェーズの実装 break; } case フェーズ.キャンセル完了: { break; } // 以下、ビュアーモード用。 case フェーズ.指示待機: { #region " オプションが届いていれば、取り出して処理する。 " //---------------- if( options?.再生開始 ?? false ) { if( File.Exists( options.Filename ) ) { Global.App.演奏譜面 = new 曲.Score() { // 読み込みに必要な最低減の譜面情報で生成。 譜面 = new ScoreDBRecord() { ScorePath = options.Filename, }, }; 演奏ステージ.演奏開始小節番号 = options.再生開始小節番号; 演奏ステージ.ビュアーモードでドラム音を再生する = options.ドラム音を発声する; // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲読み込み開始; } else { Log.ERROR( $"ファイルが存在しません。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( options.Filename )}]" ); } } //---------------- #endregion break; } case フェーズ.曲読み込み開始: { #region " 曲読み込みタスクを起動し、曲読み込み完了待ちフェーズへ。" //---------------- this._曲読み込みタスク = Task.Run( () => { 曲読み込み.曲読み込みステージ.スコアを読み込む(); } ); // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲読み込み完了待ち; //---------------- #endregion break; } case フェーズ.曲読み込み完了待ち: { #region " 曲読み込みタスクが完了すれば演奏状態初期化フェーズへ。 " //---------------- if( this._曲読み込みタスク.IsCompleted ) this.現在のフェーズ = フェーズ.演奏状態初期化; //---------------- #endregion break; } } } public void 描画する() { this._システム情報.VPSをカウントする(); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.演奏状態初期化: break; case フェーズ.フェードイン: { #region " 演奏パーツなし画面&フェードインを描画する。" //---------------- Global.App.画面をクリアする(); d2ddc.BeginDraw(); this._演奏パーツなし背景画面を描画する( d2ddc ); this._キャプチャ画面を描画する( d2ddc, ( 1.0f - this._フェードインカウンタ.現在値の割合 ) ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.演奏開始: { #region " 演奏パーツなし画面を描画する。" //---------------- Global.App.画面をクリアする(); d2ddc.BeginDraw(); this._演奏パーツなし背景画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.表示: { #region " 演奏パーツあり画面を描画する。" //---------------- Global.App.画面をクリアする(); // D2DとD3Dの混在描画について: //  Direct2D の BeginDraw()~EndDraw() の負荷はかなり高い。(~30組/描画 程度が許容限界) //  そこで、描画メソッド全体を1つの BeginDraw() と EndDraw() で囲むことにする。 //  途中で Direct3D の Draw を行いたい場合には、いったん EndDraw()し、D3Dで描画し、そして再びBeginDraw()するようにする。 d2ddc.BeginDraw(); this._表示フェーズの結果 = this._演奏パーツあり背景画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.キャンセル通知: break; case フェーズ.キャンセル時フェードアウト: { #region " 演奏パーツあり画面&フェードアウトを描画する。" //---------------- Global.App.画面をクリアする(); d2ddc.BeginDraw(); this._演奏パーツあり背景画面を描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.クリア: { #region " 演奏パーツなし画面を描画する。" //---------------- Global.App.画面をクリアする(); d2ddc.BeginDraw(); this._演奏パーツなし背景画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.失敗: break; // todo: 失敗フェーズの実装 case フェーズ.キャンセル完了: { #region " フェードアウトを描画する。" //---------------- d2ddc.BeginDraw(); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } // 以下、ビュアーモード用。 case フェーズ.指示待機: case フェーズ.曲読み込み開始: { #region " 待機画面を描画する。" //---------------- Global.App.画面をクリアする(); d2ddc.BeginDraw(); this._ビュアーモードの待機時背景を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.曲読み込み完了待ち: { #region " 待機画面&ローディング画像を描画する。" //---------------- Global.App.画面をクリアする(); d2ddc.BeginDraw(); this._ビュアーモードの待機時背景を描画する( d2ddc ); this._LoadingSpinner.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } } } private void _入力とヒット処理を行う() { var userConfig = Global.App.ログオン中のユーザ; double 現在の演奏時刻sec = Global.App.サウンドタイマ.現在時刻sec; #region " (1) 自動ヒット処理; ユーザの入力がなくても、判定バーに達したら自動的にヒット扱いされるチップの処理。" //---------------- // 描画開始チップ(画面最下位のチップ)から後方(画面上方)のチップに向かって…… for( int i = this._描画開始チップ番号; ( 0 <= i ) && ( i < Global.App.演奏スコア.チップリスト.Count ); i++ ) { var chip = Global.App.演奏スコア.チップリスト[ i ]; var chipProperty = userConfig.ドラムチッププロパティリスト[ chip.チップ種別 ]; // チップの状態を確認。 this._チップと判定との距離と時間を計算する( 現在の演奏時刻sec, chip, out double ヒット判定バーと描画との時間sec, // 負数ならバー未達、0でバー直上、正数でバー通過。 out double ヒット判定バーと発声との時間sec, // out double ヒット判定バーとの距離dpx ); // bool チップはAutoPlayである = userConfig.AutoPlay[ chipProperty.AutoPlay種別 ]; bool チップはAutoPlayではない = !チップはAutoPlayである; bool チップはヒット済みである = this._チップの演奏状態[ chip ].ヒット済みである; bool チップはヒットされていない = !チップはヒット済みである; bool チップは発声済みである = this._チップの演奏状態[ chip ].発声済みである; bool チップは発声されていない = !チップは発声済みである; bool チップはMISSエリアに達している = ( ヒット判定バーと描画との時間sec - Global.App.システム設定.判定位置調整ms * 0.001 ) > userConfig.最大ヒット距離sec[ 判定種別.OK ]; bool チップは判定エリアに達していない = ( ヒット判定バーと描画との時間sec - Global.App.システム設定.判定位置調整ms * 0.001 ) < -userConfig.最大ヒット距離sec[ 判定種別.OK ]; bool チップの描画位置がヒット判定バーを通過した = ( 0 <= ヒット判定バーと描画との時間sec ); bool チップの発声位置がヒット判定バーを通過した = ( 0 <= ヒット判定バーと発声との時間sec ); // ループ終了判定。 if( チップは判定エリアに達していない ) break; // これ以降のチップはヒット判定する必要がないので、ここでループを抜ける。 // チップの状態に応じて、必要があれば自動ヒット処理を行う。 // (1-1) MISS 判定 if( チップはヒットされていない && チップはMISSエリアに達している ) { if( チップはAutoPlayである && chipProperty.AutoPlayON_Miss判定 ) { #region " MISS(A) 自動演奏(AutoPlay)チップ " //---------------- this._チップのヒット処理を行う( chip, 判定種別.MISS, chipProperty.AutoPlayON_自動ヒット_再生, chipProperty.AutoPlayON_自動ヒット_判定, chipProperty.AutoPlayON_自動ヒット_非表示, ヒット判定バーと描画との時間sec ); //---------------- #endregion } else if( チップはAutoPlayではない && chipProperty.AutoPlayOFF_Miss判定 ) { #region " MISS(B) 手動演奏チップ " //---------------- this._チップのヒット処理を行う( chip, 判定種別.MISS, chipProperty.AutoPlayOFF_ユーザヒット_再生, chipProperty.AutoPlayOFF_ユーザヒット_判定, chipProperty.AutoPlayOFF_ユーザヒット_非表示, ヒット判定バーと描画との時間sec ); //---------------- #endregion } } else { // (1-2-1) 自動ヒット判定(再生) if( チップの発声位置がヒット判定バーを通過した && チップは発声されていない ) // ヒット済みかどうかには関係ない { if( チップはAutoPlayである && chipProperty.AutoPlayON_自動ヒット_再生 ) { #region " 自動発声(A) 自動演奏(AutoPlay)チップ " //---------------- this._チップの再生を行う( chip, userConfig.ドラムの音を発声する ); this._チップの演奏状態[ chip ].発声済みである = true; //---------------- #endregion } else if( チップはAutoPlayではない && chipProperty.AutoPlayOFF_自動ヒット_再生 ) { #region " 自動発声(B) 手動演奏チップ " //---------------- this._チップの再生を行う( chip, userConfig.ドラムの音を発声する ); this._チップの演奏状態[ chip ].発声済みである = true; //---------------- #endregion } } // (1-2-2) 自動ヒット判定 if( チップの描画位置がヒット判定バーを通過した && チップはヒットされていない ) // else if ではない { if( チップはAutoPlayである && chipProperty.AutoPlayON_自動ヒット ) { #region " 自動ヒット(A) 自動演奏(AutoPlay)チップ " //---------------- this._チップのヒット処理を行う( chip, 判定種別.PERFECT, // AutoPlay 時は Perfect 扱い。 chipProperty.AutoPlayON_自動ヒット_再生, chipProperty.AutoPlayON_自動ヒット_判定, chipProperty.AutoPlayON_自動ヒット_非表示, ヒット判定バーと描画との時間sec ); this._ドラムキットとヒットバー.ヒットアニメ開始( chipProperty.表示レーン種別 ); //---------------- #endregion } else if( チップはAutoPlayではない && chipProperty.AutoPlayOFF_自動ヒット ) { #region " 自動ヒット(B) 手動演奏チップだがAutoPlayOFF時に自動ヒットするよう指定されているチップ " //---------------- this._チップのヒット処理を行う( chip, 判定種別.PERFECT, // AutoPlay OFF でも自動ヒットする場合は Perfect 扱い。 chipProperty.AutoPlayOFF_自動ヒット_再生, chipProperty.AutoPlayOFF_自動ヒット_判定, chipProperty.AutoPlayOFF_自動ヒット_非表示, ヒット判定バーと描画との時間sec ); this._ドラムキットとヒットバー.ヒットアニメ開始( chipProperty.表示レーン種別 ); //---------------- #endregion } } } } //---------------- #endregion Global.App.ドラム入力.すべての入力デバイスをポーリングする( 入力履歴を記録する: false ); if( 0 < Global.App.ドラム入力.ポーリング結果.Count ) { // 各入力に処理済みフラグを付与した、新しいリストを作成する。(要素はタプルであり値型なので注意。) (ドラム入力イベント 入力, bool 処理済み)[] 入力リスト = Global.App.ドラム入力.ポーリング結果.Select( ( ie ) => (ie, false) ).ToArray(); // 入力時刻を補正する。 foreach( var (入力, 処理済み) in 入力リスト ) 入力.InputEvent.TimeStamp -= Global.App.システム設定.判定位置調整ms * 0.001; #region " (2) ユーザ入力に対するチップのヒット判定とヒット処理。" //---------------- // 入力集合の判定は2回に分けて行う。1回目は入力グループを無効とし、2回目は有効とする。 // これにより、各入力は、入力グループに属するチップよりも自身が対応するチップを優先してヒット判定される。 // 例: // HH入力とRD入力は同一の入力グループに属しており、HH入力でRDチップをヒットしたり、RD入力でHHチップをヒットしたりすることができる。 // ここで、HHチップとRDチップが同時刻に配置されていて、そこへHH入力とRD入力が同時に行われた場合を考える。 // このような場合、HH入力はHHチップと、そしてRD入力はRDチップと、チップを取り違えることなくそれぞれ正しくヒット判定されなければならない。 // すなわち、自身が対応するチップがヒット判定可能である場合には、入力グループに属する他のチップよりも優先して判定されなければならない。 for( int i = 1; i <= 2; i++ ) { bool 入力グループが有効 = ( i != 1 ); // 1回目はfalse、2回目はtrue // すべての入力について…… for( int n = 0; n < 入力リスト.Length; n++ ) { if( 入力リスト[ n ].処理済み ) continue; var 入力 = 入力リスト[ n ].入力; if( this._ユーザヒット対象外である( 入力 ) ) continue; // ヒット判定対象外の入力は無視。 #region " (2-1) チップにヒットしてようがしてまいが、入力に対して起こすアクションを実行。" //---------------- { var dispLane = _入力に対応する表示レーン種別を返す( 入力 ); if( dispLane != 表示レーン種別.Unknown ) { this._ドラムキットとヒットバー.ヒットアニメ開始( dispLane ); this._レーンフラッシュ.開始する( dispLane ); } } //---------------- #endregion #region " (2-2) 手動ヒット処理; ユーザの入力に対してヒット可能なチップを検索し、あればヒット処理する。" //---------------- { // 入力に対応する一番近いチップを検索する。 var chip = this._指定された時刻に一番近いチップを返す( 入力.InputEvent.TimeStamp, this._描画開始チップ番号, 追加の検索条件: ( c ) => { #region " チップ c が入力にヒットしているなら true を返す。" //---------------- // ヒット済みチップは無視。 if( this._チップの演奏状態[ c ].ヒット済みである ) return false; // ドラムチッププロパティが無効のチップは無視。 var chipProperty = userConfig.ドラムチッププロパティリスト.チップtoプロパティ[ c.チップ種別 ]; if( chipProperty.ドラム入力種別 == ドラム入力種別.Unknown ) return false; // AutoPlay ON のチップは無視。 if( userConfig.AutoPlay[ chipProperty.AutoPlay種別 ] ) return false; // AutoPlay OFF のときユーザヒットの対象にならないチップは無視。 if( !chipProperty.AutoPlayOFF_ユーザヒット ) return false; // 距離と時刻を計算。 this._チップと判定との距離と時間を計算する( 現在の演奏時刻sec, c, out double ヒット判定バーと描画との時間sec, // 負数ならバー未達、0でバー直上、正数でバー通過。 out double ヒット判定バーと発声との時間sec, // out double ヒット判定バーとの距離dpx ); // // 入力時刻の補正とは別に、判定エリア/MISS判定のためのチップの時刻の補正も必要。 ヒット判定バーと描画との時間sec -= Global.App.システム設定.判定位置調整ms * 0.001; // 判定エリアに達していないチップは無視。 if( ヒット判定バーと描画との時間sec < -userConfig.最大ヒット距離sec[ 判定種別.OK ] ) return false; // MISSエリアに達しているチップは無視。 if( ヒット判定バーと描画との時間sec > userConfig.最大ヒット距離sec[ 判定種別.OK ] ) return false; // 入力に対応しないチップは無視……の前に入力グループ判定。 if( chipProperty.ドラム入力種別 != 入力.Type ) { if( 入力グループが有効 ) { // 入力グループ判定: // 1つの入力に対して、種類の異なる複数のチップがヒット判定対象になることができる。 // 例えば、Ride入力は、RideチップとRide_Cupチップのどちらにもヒットすることができる。 // 入力が属する入力グループ種別(任意個)を取得。 var 入力のヒット判定対象となる入力グループ種別集合 = from kvp in userConfig.ドラムチッププロパティリスト.チップtoプロパティ where kvp.Value.ドラム入力種別 == 入力.Type select kvp.Value.入力グループ種別; // チップの入力グループ種別が入力の入力グループ種別集合に含まれていないなら無視。 if( !入力のヒット判定対象となる入力グループ種別集合.Any( ( type ) => ( type == chipProperty.入力グループ種別 ) ) ) return false; } else { return false; // 無視。 } } // ここまで到達できれば、チップは入力にヒットしている。 return true; //---------------- #endregion } ); if( null != chip ) // あった { #region " チップの手動ヒット処理。" //---------------- var chipProperty = userConfig.ドラムチッププロパティリスト.チップtoプロパティ[ chip.チップ種別 ]; double 入力とチップの時間差sec = 入力.InputEvent.TimeStamp - chip.描画時刻sec; double 入力とチップの時間差の絶対値sec = Math.Abs( 入力とチップの時間差sec ); var ヒット判定 = ( 入力とチップの時間差の絶対値sec <= userConfig.最大ヒット距離sec[ 判定種別.PERFECT ] ) ? 判定種別.PERFECT : ( 入力とチップの時間差の絶対値sec <= userConfig.最大ヒット距離sec[ 判定種別.GREAT ] ) ? 判定種別.GREAT : ( 入力とチップの時間差の絶対値sec <= userConfig.最大ヒット距離sec[ 判定種別.GOOD ] ) ? 判定種別.GOOD : 判定種別.OK; this._チップのヒット処理を行う( chip, ヒット判定, chipProperty.AutoPlayOFF_ユーザヒット_再生 // ヒットすれば再生する? && userConfig.ドラムの音を発声する, //  自動演奏チップとは異なり、オプション設定の影響を受ける。 chipProperty.AutoPlayOFF_ユーザヒット_判定, // ヒットすれば判定する? chipProperty.AutoPlayOFF_ユーザヒット_非表示, // ヒットすれば非表示にする? 入力とチップの時間差sec ); this.成績.エキサイトゲージを更新する( ヒット判定 ); //---------------- #endregion 入力リスト[ n ].処理済み = true; } } //---------------- #endregion } } if( userConfig.ドラムの音を発声する ) { foreach( var (入力, 処理済み) in 入力リスト ) { if( !処理済み && !this._ユーザヒット対象外である( 入力 ) ) { #region " ヒットしなかった入力については空打ちと見なし、空打ち音を再生する。" //---------------- // 入力に一番近いチップ(ヒット・未ヒット問わず、入力グループは有効)を検索する。 var chip = this._指定された時刻に一番近いチップを返す( 入力.InputEvent.TimeStamp, 検索開始チップ番号: 0, // 常に先頭から 追加の検索条件: ( chip ) => { var prop = Global.App.ログオン中のユーザ.ドラムチッププロパティリスト.チップtoプロパティ[ chip.チップ種別 ]; if( prop.ドラム入力種別 != 入力.Type ) { // 入力グループ判定: // 1つの入力に対して、種類の異なる複数のチップがヒット判定対象になることができる。 // 例えば、Ride入力は、RideチップとRide_Cupチップのどちらにもヒットすることができる。 var 入力のヒット判定対象となる入力グループ種別集合 = from kvp in userConfig.ドラムチッププロパティリスト.チップtoプロパティ where kvp.Value.ドラム入力種別 == 入力.Type select kvp.Value.入力グループ種別; // チップの入力グループ種別が入力の入力グループ種別集合に含まれていないなら無視。 if( !入力のヒット判定対象となる入力グループ種別集合.Any( ( type ) => ( type == prop.入力グループ種別 ) ) ) return false; } return true; } ); if( null != chip ) // あった { var prop = Global.App.ログオン中のユーザ.ドラムチッププロパティリスト[ chip.チップ種別 ]; if( 0 == chip.チップサブID ) { // (A) SSTF の場合 → プリセットドラムを鳴らす。 Global.App.ドラムサウンド.再生する( prop.チップ種別, 0, prop.発声前消音, prop.消音グループ種別 ); } else { // (B) DTX他の場合 → チップのWAVを再生する。 Global.App.WAV管理.発声する( chip.チップサブID, // zz 番号を示す prop.発声前消音, prop.消音グループ種別, BGM以外も再生する: true, 音量: chip.音量 / (float)SSTF.チップ.最大音量 ); } } else { // SSTF, DTX他とも、該当するチップがなかった場合には無音となる。 } //---------------- #endregion } } } //---------------- #endregion #region " (3) 入力に応じたハイハットの開閉 " //---------------- foreach( var ev in Global.App.ドラム入力.MidiIns.入力イベントリスト.Where( ( ie ) => ( 255 == ie.Key ) && ( MidiIns.CTL_FOOTPEDAL == ie.Control ) ) ) this._ドラムキットとヒットバー.ハイハットの開度を設定する( ev.Velocity ); //---------------- #endregion } #region " (4) その他の操作。" //---------------- { var keyboard = Global.App.ドラム入力.Keyboard; if( !Global.Options.ビュアーモードである && keyboard.キーが押された( 0, Keys.Escape ) ) { #region " ESC → キャンセル通知フェーズへ(ビュアーモード時は無効)" //---------------- Log.Info( "ESC キーが押されました。演奏を中断します。" ); Global.App.WAV管理?.すべての発声を停止する(); // DTXでのBGMサウンドはこっちに含まれる。 this.現在のフェーズ = フェーズ.キャンセル通知; //---------------- #endregion } if( keyboard.キーが押された( 0, Keys.Up ) ) { if( keyboard.キーが押されている( 0, Keys.ShiftKey ) ) { #region " Shift+上 → BGMAdjust 増加 " //---------------- Global.App.演奏譜面.譜面.BGMAdjust += 10; // ms Global.App.WAV管理?.すべてのBGMの再生位置を移動する( +10.0 / 1000.0 ); // sec this._BGMAdjustをデータベースに保存する( Global.App.演奏譜面.譜面 ); //---------------- #endregion } else { #region " 上 → 譜面スクロールを加速 " //---------------- const double 最大倍率 = 8.0; userConfig.譜面スクロール速度 = Math.Min( userConfig.譜面スクロール速度 + 0.5, 最大倍率 ); //---------------- #endregion } } if( keyboard.キーが押された( 0, Keys.Down ) ) { if( keyboard.キーが押されている( 0, Keys.ShiftKey ) ) { #region " Shift+下 → BGMAdjust 減少 " //---------------- Global.App.演奏譜面.譜面.BGMAdjust -= 10; // ms Global.App.WAV管理?.すべてのBGMの再生位置を移動する( -10.0 / 1000.0 ); // sec this._BGMAdjustをデータベースに保存する( Global.App.演奏譜面.譜面 ); //---------------- #endregion } else { #region " 下 → 譜面スクロールを減速 " //---------------- const double 最小倍率 = 0.5; userConfig.譜面スクロール速度 = Math.Max( userConfig.譜面スクロール速度 - 0.5, 最小倍率 ); //---------------- #endregion } } } if( Global.App.ドラム入力.ドラムが入力された( ドラム入力種別.Pause_Resume ) ) { #region " Pause/Resume → 演奏の一時停止・再開 " //---------------- this._演奏を一時停止または再開する(); //---------------- #endregion } if( Global.App.ドラム入力.ドラムが入力された( ドラム入力種別.PlaySpeed_Up ) && 0 <= this._描画開始チップ番号 ) { #region " PageUp → 早送り;1小節先に進む " //---------------- // 現在時刻における小節番号を取得する。 int 現在の小節番号 = Global.App.演奏スコア.チップリスト[ this._描画開始チップ番号 ].小節番号; double 現在時刻sec = Global.App.サウンドタイマ.現在時刻sec; for( int i = this._描画開始チップ番号; i < Global.App.演奏スコア.チップリスト.Count; i++ ) { var chip = Global.App.演奏スコア.チップリスト[ i ]; if( chip.チップ種別 == SSTF.チップ種別.小節線 && 現在時刻sec <= chip.描画時刻sec ) break; 現在の小節番号 = chip.小節番号; } // 取得した小節の1つ次の小節へ移動する。 this._指定小節へ移動する( 現在の小節番号 + 1, out this._描画開始チップ番号, out double 演奏開始時刻sec ); Global.App.サウンドタイマ.リセットする( 演奏開始時刻sec ); this._クリアメーター.カウントマップをクリアする(); this._早送りアイコン.早送りする(); this.成績.無効 = true; //---------------- #endregion } if( Global.App.ドラム入力.ドラムが入力された( ドラム入力種別.PlaySpeed_Down ) && 0 <= this._描画開始チップ番号 ) { #region " PageDown → 早戻し;1小節前に戻る " //---------------- // こちらは描画開始チップの小節番号を基点とする。 int 現在の小節番号 = Global.App.演奏スコア.チップリスト[ this._描画開始チップ番号 ].小節番号; // 取得した小節の1つ前の小節へ移動する。 this._指定小節へ移動する( 現在の小節番号 - 1, out this._描画開始チップ番号, out double 演奏開始時刻sec ); Global.App.サウンドタイマ.リセットする( 演奏開始時刻sec ); this._クリアメーター.カウントマップをクリアする(); this._早送りアイコン.早戻しする(); this.成績.無効 = true; //---------------- #endregion } //---------------- #endregion } // ローカル 演奏結果 _表示フェーズの結果 = 演奏結果.演奏中; // 画面を構成するもの private readonly 画像D2D _背景画像; private 画像D2D _スコア指定の背景画像; private readonly 曲名パネル _曲名パネル; private readonly システム情報 _システム情報; private readonly レーンフレーム _レーンフレーム; private readonly ドラムキットとヒットバー _ドラムキットとヒットバー; private readonly ドラムチップ _ドラムチップ; private readonly 譜面スクロール速度 _譜面スクロール速度; private readonly エキサイトゲージ _エキサイトゲージ; private readonly フェーズパネル _フェーズパネル; private readonly クリアメーター _クリアメーター; private readonly 左サイドクリアパネル _左サイドクリアパネル; private readonly 右サイドクリアパネル _右サイドクリアパネル; private readonly 早送りアイコン _早送りアイコン; private void _演奏パーツなし背景画面を描画する( DeviceContext d2ddc ) { var userConfig = Global.App.ログオン中のユーザ; #region " スコア指定の壁紙 " //---------------- if( userConfig.スコア指定の背景画像を表示する ) { this._スコア指定の背景画像?.描画する( d2ddc, 0f, 0f, X方向拡大率: Global.GraphicResources.設計画面サイズ.Width / this._スコア指定の背景画像.サイズ.Width, Y方向拡大率: Global.GraphicResources.設計画面サイズ.Height / this._スコア指定の背景画像.サイズ.Height ); } //---------------- #endregion #region " 左サイドパネルへの描画と、左サイドパネルの表示 " //---------------- { var preTarget = d2ddc.Target; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Target = this._左サイドクリアパネル.クリアパネル.Bitmap; d2ddc.Transform = Matrix3x2.Identity; // 等倍描画(DPXtoDPX) d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; // 背景画像 d2ddc.Clear( new Color4( Color3.Black, 0f ) ); d2ddc.DrawBitmap( this._左サイドクリアパネル.背景.Bitmap, opacity: 1f, interpolationMode: InterpolationMode.Linear ); // プレイヤー名 this._プレイヤー名表示.進行描画する( d2ddc ); // スコア if( userConfig.ダーク == ダーク種別.OFF ) this._スコア表示.進行描画する( d2ddc, Global.Animation, new Vector2( +280f, +120f ), this.成績 ); // 達成率 this._達成率表示.進行描画する( d2ddc, (float)this.成績.Achievement ); // 判定パラメータ this._判定パラメータ表示.進行描画する( d2ddc, +118f, +372f, this.成績 ); // スキル this._曲別SKILL.進行描画する( d2ddc, 0f ); d2ddc.Flush(); // いったんここまで描画 d2ddc.Target = preTarget; d2ddc.Transform = preTrans; d2ddc.PrimitiveBlend = preBlend; ( (IUnknown)preTarget ).Release(); // 要Release } this._左サイドクリアパネル.進行描画する(); //---------------- #endregion #region " 右サイドパネルへの描画と、右サイトパネルの表示 " //---------------- { var preTarget = d2ddc.Target; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Target = this._右サイドクリアパネル.クリアパネル.Bitmap; d2ddc.Transform = Matrix3x2.Identity; // 等倍描画(DPXtoDPX) d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; // 背景画像 d2ddc.Clear( new Color4( Color3.Black, 0f ) ); d2ddc.DrawBitmap( this._右サイドクリアパネル.背景.Bitmap, opacity: 1f, interpolationMode: InterpolationMode.Linear ); d2ddc.Flush(); // いったんここまで描画 d2ddc.Target = preTarget; d2ddc.Transform = preTrans; d2ddc.PrimitiveBlend = preBlend; ( (IUnknown)preTarget ).Release(); // 要Release } this._右サイドクリアパネル.進行描画する(); //---------------- #endregion #region " レーンフレーム " //---------------- this._レーンフレーム.進行描画する( d2ddc, userConfig.レーンの透明度, レーンラインを描画する: ( userConfig.ダーク == ダーク種別.OFF ) ); //---------------- #endregion #region " 背景画像 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._背景画像.描画する( d2ddc, 0f, 0f ); //---------------- #endregion #region " 譜面スクロール速度 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._譜面スクロール速度.描画する( d2ddc, userConfig.譜面スクロール速度 ); //---------------- #endregion #region " エキサイトゲージ " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._エキサイトゲージ.進行描画する( d2ddc, this.成績.エキサイトゲージ量 ); //---------------- #endregion #region " クリアメーター " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._クリアメーター.進行描画する( d2ddc ); //---------------- #endregion #region " フェーズパネル " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._フェーズパネル.進行描画する( d2ddc ); //---------------- #endregion #region " 曲目パネル " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._曲名パネル.進行描画する( d2ddc ); //---------------- #endregion #region " ヒットバー " //---------------- if( userConfig.ダーク != ダーク種別.FULL ) this._ドラムキットとヒットバー.ヒットバーを進行描画する( d2ddc ); //---------------- #endregion #region " ドラムキット " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._ドラムキットとヒットバー.ドラムキットを進行描画する( d2ddc ); //---------------- #endregion } private 演奏結果 _演奏パーツあり背景画面を描画する( DeviceContext d2ddc ) { var result = 演奏結果.演奏中; var userConfig = Global.App.ログオン中のユーザ; double 演奏時刻sec = Global.App.サウンドタイマ.現在時刻sec; if( Global.Options.VSyncWait ) 演奏時刻sec += Global.GraphicResources.次のDComp表示までの残り時間sec; #region " 譜面スクロールの進行 " //---------------- // チップの表示より前に進行だけ行う。 this._譜面スクロール速度.進行する( userConfig.譜面スクロール速度 ); //---------------- #endregion #region " スコア指定の壁紙 " //---------------- if( userConfig.スコア指定の背景画像を表示する ) { this._スコア指定の背景画像?.描画する( d2ddc, 0f, 0f, X方向拡大率: Global.GraphicResources.設計画面サイズ.Width / this._スコア指定の背景画像.サイズ.Width, Y方向拡大率: Global.GraphicResources.設計画面サイズ.Height / this._スコア指定の背景画像.サイズ.Height ); } //---------------- #endregion #region " 動画 " //---------------- if( userConfig.演奏中に動画を表示する ) { foreach( var kvp in Global.App.AVI管理.動画リスト ) { int zz = kvp.Key; // zz 番号 var video = kvp.Value; // Video インスタンス if( video.再生中 ) { switch( userConfig.動画の表示サイズ ) { case 動画の表示サイズ.全画面: { #region " 100%全体表示 " //---------------- float w = Global.GraphicResources.設計画面サイズ.Width; float h = Global.GraphicResources.設計画面サイズ.Height; video.描画する( d2ddc, new RectangleF( 0f, 0f, w, h ) ); //---------------- #endregion break; } case 動画の表示サイズ.中央寄せ: { #region " 75%縮小表示 " //---------------- float w = Global.GraphicResources.設計画面サイズ.Width; float h = Global.GraphicResources.設計画面サイズ.Height; // (1) 画面いっぱいに描画。 video.描画する( d2ddc, new RectangleF( 0f, 0f, w, h ), 0.2f ); // 不透明度は 0.2 で暗くする。 // (2) ちょっと縮小して描画。 float 拡大縮小率 = 0.75f; float 上移動 = 100.0f; video.最後のフレームを再描画する( d2ddc, new RectangleF( // 直前に取得したフレームをそのまま描画。 w * ( 1f - 拡大縮小率 ) / 2f, h * ( 1f - 拡大縮小率 ) / 2f - 上移動, w * 拡大縮小率, h * 拡大縮小率 ) ); //---------------- #endregion break; } } } } } //---------------- #endregion #region " 左サイドパネルへの描画と、左サイドパネルの表示 " //---------------- { var preTarget = d2ddc.Target; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Target = this._左サイドクリアパネル.クリアパネル.Bitmap; d2ddc.Transform = Matrix3x2.Identity; // 等倍描画(DPXtoDPX) d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; // 背景画像 d2ddc.Clear( new Color4( Color3.Black, 0f ) ); d2ddc.DrawBitmap( this._左サイドクリアパネル.背景.Bitmap, opacity: 1f, interpolationMode: InterpolationMode.Linear ); // プレイヤー名 this._プレイヤー名表示.進行描画する( d2ddc ); // スコア if( userConfig.ダーク == ダーク種別.OFF ) this._スコア表示.進行描画する( d2ddc, Global.Animation, new Vector2( +280f, +120f ), this.成績 ); // 達成率 this._達成率表示.進行描画する( d2ddc, (float)this.成績.Achievement ); // 判定パラメータ this._判定パラメータ表示.進行描画する( d2ddc, +118f, +372f, this.成績 ); // スキル this._曲別SKILL.進行描画する( d2ddc, this.成績.スキル ); d2ddc.Flush(); // いったんここまで描画。 d2ddc.Target = preTarget; d2ddc.Transform = preTrans; d2ddc.PrimitiveBlend = preBlend; ( (IUnknown)preTarget ).Release(); // 要Release } this._左サイドクリアパネル.進行描画する(); //---------------- #endregion #region " 右サイドパネルへの描画と、右サイドパネルの表示 " //---------------- { var preTarget = d2ddc.Target; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Target = this._右サイドクリアパネル.クリアパネル.Bitmap; d2ddc.Transform = Matrix3x2.Identity; // 等倍描画(DPXtoDPX) d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; // 背景画像 d2ddc.Clear( new Color4( Color3.Black, 0f ) ); d2ddc.DrawBitmap( this._右サイドクリアパネル.背景.Bitmap, opacity: 1f, interpolationMode: InterpolationMode.Linear ); // コンボ this._コンボ表示.進行描画する( d2ddc, new Vector2( +228f + 264f / 2f, +234f ), this.成績 ); d2ddc.Flush(); // いったんここまで描画。 d2ddc.Target = preTarget; d2ddc.Transform = preTrans; d2ddc.PrimitiveBlend = preBlend; ( (IUnknown)preTarget ).Release(); // 要Release } this._右サイドクリアパネル.進行描画する(); //---------------- #endregion #region " レーンフレーム " //---------------- this._レーンフレーム.進行描画する( d2ddc, userConfig.レーンの透明度, レーンラインを描画する: ( userConfig.ダーク == ダーク種別.OFF ) ); //---------------- #endregion #region " レーンフラッシュ " //---------------- this._レーンフラッシュ.進行描画する( d2ddc ); //---------------- #endregion #region " 小節線拍線 " //---------------- if( userConfig.ダーク != ダーク種別.FULL ) this._小節線拍線を描画する( d2ddc, 演奏時刻sec ); //---------------- #endregion #region " 背景画像 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._背景画像.描画する( d2ddc, 0f, 0f ); //---------------- #endregion #region " 譜面スクロール速度 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._譜面スクロール速度.描画する( d2ddc, userConfig.譜面スクロール速度 ); //---------------- #endregion #region " エキサイトゲージ " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._エキサイトゲージ.進行描画する( d2ddc, this.成績.エキサイトゲージ量 ); //---------------- #endregion #region " クリアメーター, フェーズパネル " //---------------- double 曲の長さsec = Global.App.演奏スコア.チップリスト[ Global.App.演奏スコア.チップリスト.Count - 1 ].描画時刻sec; float 現在位置 = (float)( 1.0 - ( 曲の長さsec - 演奏時刻sec ) / 曲の長さsec ); // クリアメーター this.成績.CountMap = this._クリアメーター.カウント値を設定する( 現在位置, this.成績.判定別ヒット数 ); if( userConfig.ダーク == ダーク種別.OFF ) this._クリアメーター.進行描画する( d2ddc ); // フェーズパネル this._フェーズパネル.現在位置 = 現在位置; if( userConfig.ダーク == ダーク種別.OFF ) this._フェーズパネル.進行描画する( d2ddc ); //---------------- #endregion #region " 曲名パネル " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._曲名パネル.進行描画する( d2ddc ); //---------------- #endregion #region " ヒットバー " //---------------- if( userConfig.ダーク != ダーク種別.FULL ) this._ドラムキットとヒットバー.ヒットバーを進行描画する( d2ddc ); //---------------- #endregion #region " ドラムキット " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._ドラムキットとヒットバー.ドラムキットを進行描画する( d2ddc ); //---------------- #endregion // ↓クリア判定はこの中。 #region " ドラムチップ " //---------------- this._描画範囲内のすべてのチップに対して( 演奏時刻sec, ( SSTF.チップ chip, int index, double ヒット判定バーと描画との時間sec, double ヒット判定バーと発声との時間sec, double ヒット判定バーとの距離dpx ) => { result = this._ドラムチップ.進行描画する( d2ddc, ref this._描画開始チップ番号, this._チップの演奏状態[ chip ], chip, index, ヒット判定バーとの距離dpx ); } ); //---------------- #endregion #region " チップ光 " //---------------- this._チップ光.進行描画する( d2ddc ); //---------------- #endregion #region " 判定文字列 " //---------------- this._判定文字列.進行描画する( d2ddc ); //---------------- #endregion #region " 早送りアイコン " //---------------- this._早送りアイコン.進行描画する( d2ddc ); //---------------- #endregion #region " システム情報 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._システム情報.描画する( d2ddc, $"BGMAdjust: {Global.App.演奏譜面.譜面.BGMAdjust}" ); //---------------- #endregion return result; } private void _キャプチャ画面を描画する( DeviceContext d2ddc, float 不透明度 = 1.0f ) { Debug.Assert( null != this.キャプチャ画面, "キャプチャ画面が設定されていません。" ); d2ddc.DrawBitmap( this.キャプチャ画面, new RectangleF( 0f, 0f, Global.GraphicResources.設計画面サイズ.Width, Global.GraphicResources.設計画面サイズ.Height ), 不透明度, BitmapInterpolationMode.Linear ); } // 左サイドクリアパネル内に表示されるもの private readonly スコア表示 _スコア表示; private readonly プレイヤー名表示 _プレイヤー名表示; private readonly 判定パラメータ表示 _判定パラメータ表示; private readonly 達成率表示 _達成率表示; private readonly 曲別SKILL _曲別SKILL; // 右サイドクリアパネル内に表示されるもの private readonly コンボ表示 _コンボ表示; // 譜面上に表示されるもの private readonly レーンフラッシュ _レーンフラッシュ; private readonly 判定文字列 _判定文字列; private readonly チップ光 _チップ光; private readonly フォント画像D2D _数字フォント中グレー48x64; private readonly SolidColorBrush _小節線色; private readonly SolidColorBrush _拍線色; private void _小節線拍線を描画する( DeviceContext d2ddc, double 現在の演奏時刻sec ) { // 小節線・拍線 と チップ は描画階層(奥行き)が異なるので、別々のメソッドに分ける。 var userConfig = Global.App.ログオン中のユーザ; this._描画範囲内のすべてのチップに対して( 現在の演奏時刻sec, ( chip, index, ヒット判定バーと描画との時間sec, ヒット判定バーと発声との時間sec, ヒット判定バーとの距離dpx ) => { if( chip.チップ種別 == SSTF.チップ種別.小節線 ) { const float 小節線の厚みの半分 = 1f; float 上位置dpx = MathF.Round( (float)( ヒット判定位置Ydpx + ヒット判定バーとの距離dpx - 小節線の厚みの半分 ) ); // 小節線 if( userConfig.演奏中に小節線と拍線を表示する ) { const float x = 441f; const float w = 780f; d2ddc.DrawLine( new Vector2( x, 上位置dpx + 0f ), new Vector2( x + w, 上位置dpx + 0f ), this._小節線色 ); d2ddc.DrawLine( new Vector2( x, 上位置dpx + 1f ), new Vector2( x + w, 上位置dpx + 1f ), this._小節線色 ); } // 小節番号 if( userConfig.演奏中に小節番号を表示する ) { const float 右位置dpx = 441f + 780f - 24f; // -24f は適当なマージン。 this._数字フォント中グレー48x64.描画する( d2ddc, 右位置dpx, 上位置dpx - 84f, chip.小節番号.ToString(), 右揃え: true ); // -84f は適当なマージン。 } } else if( chip.チップ種別 == SSTF.チップ種別.拍線 ) { // 拍線 if( userConfig.演奏中に小節線と拍線を表示する ) { const float 拍線の厚みの半分 = 1f; float 上位置dpx = MathF.Round( (float)( ヒット判定位置Ydpx + ヒット判定バーとの距離dpx - 拍線の厚みの半分 ) ); d2ddc.DrawLine( new Vector2( 441f, 上位置dpx ), new Vector2( 441f + 780f, 上位置dpx ), this._拍線色 ); } } } ); } // 演奏状態、操作 /// <summary> /// <see cref="スコア.チップリスト"/> のうち、描画を始めるチップのインデックス番号。 /// 未演奏時・演奏終了時は -1 。 /// </summary> /// <remarks> /// 演奏開始直後は 0 で始まり、対象番号のチップが描画範囲を流れ去るたびに +1 される。 /// このメンバの更新は、高頻度進行タスクではなく、進行描画メソッドで行う。(低精度で構わないので) /// </remarks> private int _描画開始チップ番号 = -1; private Dictionary<SSTF.チップ, チップの演奏状態> _チップの演奏状態; private bool _一時停止中 = false; private void _演奏を一時停止または再開する() { if( !this._一時停止中 ) { this._一時停止中 = true; Global.App.サウンドタイマ.一時停止する(); Global.App.AVI管理.再生中の動画をすべて一時停止する(); Global.App.WAV管理.再生中の音声をすべて一時停止する(); } else { this._一時停止中 = false; Global.App.AVI管理.一時停止中の動画をすべて再開する(); Global.App.WAV管理.一時停止中の音声をすべて再開する(); Global.App.サウンドタイマ.再開する(); } } private void _BGMAdjustをデータベースに保存する( ScoreDBRecord 譜面レコード ) { Task.Run( () => { using( var scoredb = new ScoreDB() ) 譜面レコード.ReplaceTo( scoredb ); } ); } /// <summary> /// 指定された小節に演奏箇所を移動する。 /// </summary> /// <param name="移動先小節番号">移動先の小節番号。</param> /// <param name="描画開始チップ番号">移動先に位置する先頭のチップが返される。なければ 0 。</param> /// <param name="演奏開始時刻sec">移動先に移動した場合の演奏開始時刻[秒]。なければ 0.0 。</param> /// <remarks> /// 指定された小節に演奏箇所を移動し、新しい描画開始チップ番号と、新しい演奏開始時刻secを返す。 /// また、新しい演奏開始時刻sec より前のAVI/WAVチップについては、途中からの再生を行う。 /// </remarks> private void _指定小節へ移動する( int 移動先小節番号, out int 描画開始チップ番号, out double 演奏開始時刻sec ) { var score = Global.App.演奏スコア; // AVI動画、WAV音声を停止する。 Global.App.AVI管理.再生中の動画をすべて一時停止する(); Global.App.WAV管理.再生中の音声をすべて一時停止する(); // 一度、すべてのチップを未ヒット状態に戻す。 foreach( var chip in score.チップリスト ) this._チップの演奏状態[ chip ].ヒット前の状態にする(); // 移動先の小節番号が負数なら、一番最初へ移動。 if( 0 > 移動先小節番号 ) { 描画開始チップ番号 = 0; 演奏開始時刻sec = 0.0; return; } // 移動先小節番号に位置している最初のチップを検索する。 int 最初のチップ番号 = score.チップリスト.FindIndex( ( c ) => c.小節番号 >= 移動先小節番号 ); // 見つからなければ -1。 if( -1 == 最初のチップ番号 ) { // すべて演奏終了しているので、最後のチップを指定する。 描画開始チップ番号 = score.チップリスト.Count - 1; 演奏開始時刻sec = score.チップリスト.Last().発声時刻sec; return; } // 演奏開始時刻を、最初のチップの描画より少し手前に設定。 演奏開始時刻sec = Math.Max( 0.0, score.チップリスト[ 最初のチップ番号 ].描画時刻sec - 0.5 ); // 0.5 秒早く // 演奏開始時刻をもとに描画開始チップ番号を確定するとともに、全チップのヒット状態をリセットする。 描画開始チップ番号 = -1; for( int i = 0; i < score.チップリスト.Count; i++ ) { var chip = score.チップリスト[ i ]; if( chip.描画時刻sec >= 演奏開始時刻sec ) { // (A) 演奏開始時刻以降のチップ if( -1 == 描画開始チップ番号 ) 描画開始チップ番号 = i; // 先頭チップ break; } else { // (B) 演奏開始時刻より前のチップ → ヒット済みとする。 this._チップの演奏状態[ chip ].ヒット済みの状態にする(); } } // 必要なら、AVI動画, WAV音声の途中再生を行う。 #region " AVI動画の途中再生 " //---------------- if( Global.App.ログオン中のユーザ.演奏中に動画を表示する ) { var ヒット済みの動画チップリスト = from chip in score.チップリスト where chip.チップ種別 == SSTF.チップ種別.背景動画 //&& this._チップの演奏状態[ chip ].ヒット済みである --> 未ヒットも再構築する select chip; foreach( var aviChip in ヒット済みの動画チップリスト ) { int avi番号 = aviChip.チップサブID; if( Global.App.AVI管理.動画リスト.ContainsKey( avi番号 ) ) { Global.App.AVI管理.再構築する( avi番号 ); double 再生開始時刻sec = 演奏開始時刻sec - aviChip.発声時刻sec; if( 0 <= 再生開始時刻sec ) // 念のため。 Global.App.AVI管理.動画リスト[ avi番号 ]?.再生を開始する( 再生開始時刻sec ); } } } //---------------- #endregion #region " WAV音声の途中再生 " //---------------- { var ヒット済みのWAVチップリスト = from chip in score.チップリスト where ( chip.チップ種別 == SSTF.チップ種別.BGM ) && ( this._チップの演奏状態[ chip ].ヒット済みである ) select chip; foreach( var wavChip in ヒット済みのWAVチップリスト ) { var prop = Global.App.ログオン中のユーザ.ドラムチッププロパティリスト.チップtoプロパティ[ wavChip.チップ種別 ]; Global.App.WAV管理.発声する( wavChip.チップサブID, prop.発声前消音, prop.消音グループ種別, BGM以外も再生する: Global.App.ログオン中のユーザ.ドラムの音を発声する && Global.Options.ビュアーモードである && ビュアーモードでドラム音を再生する, 音量: wavChip.音量 / (float)SSTF.チップ.最大音量, 再生開始時刻sec: 演奏開始時刻sec - wavChip.発声時刻sec ); } } //---------------- #endregion } private void _演奏状態を初期化する() { this._描画開始チップ番号 = -1; // スコアに依存するデータを初期化する。 this.成績 = new 成績(); this._チップの演奏状態 = new Dictionary<SSTF.チップ, チップの演奏状態>(); foreach( var chip in Global.App.演奏スコア.チップリスト ) this._チップの演奏状態.Add( chip, new チップの演奏状態( chip ) ); this._スコア指定の背景画像 = string.IsNullOrEmpty( Global.App.演奏スコア.背景画像ファイル名 ) ? null! : new 画像D2D( Path.Combine( Global.App.演奏スコア.PATH_WAV, Global.App.演奏スコア.背景画像ファイル名 ) ); // PATH_WAV は絶対パス } // フェードイン(キャプチャ画像とステージ画像とのA-B変換)→ 既定のアイキャッチを使わないので独自管理する。 /// <summary> /// 読み込み画面: 0 ~ 1: 演奏画面 /// </summary> private Counter _フェードインカウンタ; // ドラムチップ関連 /// <summary> /// 現在の描画範囲内のすべてのチップに対して、指定された処理を実行する。 /// </summary> /// <remarks> /// 「描画範囲内のチップ」とは、<see cref="_描画開始チップ番号"/> のチップを画面最下位のチップとし、画面上端にはみ出すまでの間のすべてのチップを示す。 /// </remarks> /// <param name="適用する処理"> /// 引数は、順に、対象のチップ, チップ番号, ヒット判定バーと描画との時間sec, ヒット判定バーと発声との時間sec, ヒット判定バーとの距離dpx。 /// 時間と距離はいずれも、負数ならバー未達、0でバー直上、正数でバー通過。 /// </param> private void _描画範囲内のすべてのチップに対して( double 現在の演奏時刻sec, Action<SSTF.チップ, int, double, double, double> 適用する処理 ) { var score = Global.App.演奏スコア; // 描画開始チップから後方(画面最下位のチップから画面上方)のチップに向かって…… for( int i = this._描画開始チップ番号; ( 0 <= i ) && ( i < score.チップリスト.Count ); i++ ) { var chip = score.チップリスト[ i ]; this._チップと判定との距離と時間を計算する( 現在の演奏時刻sec, chip, out double ヒット判定バーと描画との時間sec, // 負数ならバー未達、0でバー直上、正数でバー通過。 out double ヒット判定バーと発声との時間sec, // out double ヒット判定バーとの距離dpx ); // // チップが画面外に出たならここで終了。 if( this._チップは画面上端より外に出ている( ヒット判定バーとの距離dpx ) ) break; // 適用する処理を呼び出す。開始判定(描画開始チップ番号の更新)もこの中で。 適用する処理( chip, i, ヒット判定バーと描画との時間sec, ヒット判定バーと発声との時間sec, ヒット判定バーとの距離dpx ); } } /// <summary> /// 指定された時刻における、チップとヒット判定バーとの間の距離と時間を算出する。 /// </summary> /// <param name="現在の演奏時刻sec"></param> /// <param name="chip"></param> /// <param name="ヒット判定バーと描画との時間sec">負数ならバー未達、0でバー直上、正数でバー通過。 </param> /// <param name="ヒット判定バーと発声との時間sec">負数ならバー未達、0でバー直上、正数でバー通過。 </param> /// <param name="ヒット判定バーとの距離dpx">負数ならバー未達、0でバー直上、正数でバー通過。 </param> private void _チップと判定との距離と時間を計算する( double 現在の演奏時刻sec, SSTF.チップ chip, out double ヒット判定バーと描画との時間sec, out double ヒット判定バーと発声との時間sec, out double ヒット判定バーとの距離dpx ) { const double _1秒あたりのピクセル数 = 0.14625 * 2.25 * 1000.0; // これを変えると、speed あたりの速度が変わる。 ヒット判定バーと描画との時間sec = 現在の演奏時刻sec - chip.描画時刻sec; ヒット判定バーと発声との時間sec = 現在の演奏時刻sec - chip.発声時刻sec; ヒット判定バーとの距離dpx = ヒット判定バーと描画との時間sec * _1秒あたりのピクセル数 * this._譜面スクロール速度.補間付き速度; } /// <summary> /// チップとヒット判定バーとの距離をもとに、チップが画面上端よりも上に(画面外に)出ているかを確認する。 /// </summary> /// <returns>チップが画面上端よりも上に(画面外に)でていれば true を返す。</returns> private bool _チップは画面上端より外に出ている( double ヒット判定バーとの距離dpx ) { const double チップが隠れるであろう適当なマージン = -40.0; return ( 演奏ステージ.ヒット判定位置Ydpx + ヒット判定バーとの距離dpx ) < チップが隠れるであろう適当なマージン; } /// <summary> /// 入力にヒットしたチップの処理(再生、判定、非表示化)を行う。 /// </summary> /// <param name="chip"></param> /// <param name="judge">ヒットしたチップの<see cref="判定種別"/>。</param> /// <param name="再生">チップを再生するならtrue。</param> /// <param name="判定">チップを判定するならtrue。</param> /// <param name="非表示">チップを非表示化するならtrue。</param> /// <param name="ヒット判定バーと発声との時間sec">負数でバー未達、0で直上、正数でバー通過。</param> /// <param name="入力とチップとの間隔sec">チップより入力が早ければ負数、遅ければ正数。</param> private void _チップのヒット処理を行う( SSTF.チップ chip, 判定種別 judge, bool 再生, bool 判定, bool 非表示, double 入力とチップとの間隔sec ) { this._チップの演奏状態[ chip ].ヒット済みである = true; if( 再生 && ( judge != 判定種別.MISS ) ) { #region " チップの発声がまだなら行う。" //---------------- // チップの発声時刻は、描画時刻と同じかそれより過去に位置するので、ここに来た時点で未発声なら発声していい。 // というか発声時刻が過去なのに未発声というならここが最後のチャンスなので、必ず発声しないといけない。 if( !this._チップの演奏状態[ chip ].発声済みである ) { this._チップの再生を行う( chip, Global.App.ログオン中のユーザ.ドラムの音を発声する ); this._チップの演奏状態[ chip ].発声済みである = true; } //---------------- #endregion } if( 判定 ) { #region " チップの判定処理を行う。" //---------------- var userConfig = Global.App.ログオン中のユーザ; var 対応表 = userConfig.ドラムチッププロパティリスト[ chip.チップ種別 ]; if( judge != 判定種別.MISS ) { this._チップ光.表示を開始する( 対応表.表示レーン種別 ); this._レーンフラッシュ.開始する( 対応表.表示レーン種別 ); } this._判定文字列.表示を開始する( 対応表.表示レーン種別, judge, 入力とチップとの間隔sec ); this.成績.成績を更新する( judge ); //---------------- #endregion } if( 非表示 ) { #region " チップを非表示にする。" //---------------- if( judge == 判定種別.MISS ) { // (A) MISSチップ → 最後まで表示し続ける。 } else { // (B) MISS以外 → 非表示。 this._チップの演奏状態[ chip ].可視 = false; } //---------------- #endregion } } private void _チップの再生を行う( SSTF.チップ chip, bool ドラムサウンドを再生する ) { var userConfig = Global.App.ログオン中のユーザ; if( chip.チップ種別 == SSTF.チップ種別.背景動画 ) { #region " (A) 背景動画チップ → AVI動画を再生する。" //---------------- if( userConfig.演奏中に動画を表示する ) { int AVI番号 = chip.チップサブID; if( Global.App.AVI管理.動画リスト.TryGetValue( AVI番号, out Video? video ) ) { // 止めても止めなくてもカクつくだろうが、止めておけば譜面は再開時にワープしない。 // ---> 2020/10/22: やっぱりコメントアウト // BGM 開始後に動画を開始する場合、ここでタイマを止めると、BGMと譜面で無視できない大きさの誤差が発生する。 // なので、ここでタイマを止めてはならない(ワープも致し方ない)。 //Global.App.サウンドタイマ.一時停止する(); video.再生を開始する(); //Global.App.サウンドタイマ.再開する(); } } //---------------- #endregion } else { if( Global.Options.ビュアーモードである && !演奏ステージ.ビュアーモードでドラム音を再生する && chip.チップ種別 != SSTF.チップ種別.BGM ) // BGM はドラムサウンドではない return; var chipProperty = userConfig.ドラムチッププロパティリスト.チップtoプロパティ[ chip.チップ種別 ]; if( 0 == chip.チップサブID && ドラムサウンドを再生する ) { #region " (B) チップサブIDがゼロ → SSTF準拠のドラムサウンドを再生する。" //---------------- // ドラムサウンドを持つチップなら発声する。(持つかどうかはこのメソッド↓内で判定される。) Global.App.ドラムサウンド.再生する( chip.チップ種別, 0, chipProperty.発声前消音, chipProperty.消音グループ種別, ( chip.音量 / (float)SSTF.チップ.最大音量 ) ); //---------------- #endregion } else { #region " (C) チップサブIDがある → DTX準拠のWAVサウンドを再生する。" //---------------- // WAVを持つチップなら発声する。(WAVを持つかどうかはこのメソッド↓内で判定される。) Global.App.WAV管理.発声する( chip. チップサブID, chipProperty.発声前消音, chipProperty.消音グループ種別, ドラムサウンドを再生する, 音量: ( chip.音量 / (float)SSTF.チップ.最大音量 ) ); //---------------- #endregion } } } /// <summary> /// 該当するチップが1つもなかったら null を返す。 /// </summary> private SSTF.チップ? _指定された時刻に一番近いチップを返す( double 時刻sec, int 検索開始チップ番号, Func<SSTF.チップ, bool> 追加の検索条件 ) { if( 0 > 検索開始チップ番号 ) return null; // 演奏が完全に終わっていたらチップも返さない。 var 一番近いチップ = (SSTF.チップ?)null; var 一番近いチップの時刻差の絶対値sec = (double)0.0; // すべてのチップについて、描画時刻の早い順に調べていく。 for( int i = 検索開始チップ番号; i < Global.App.演奏スコア.チップリスト.Count; i++ ) { var chip = Global.App.演奏スコア.チップリスト[ i ]; if( !追加の検索条件( chip ) ) continue; // 検索条件を満たさないチップは無視 var 今回の時刻差の絶対値sec = Math.Abs( chip.描画時刻sec - 時刻sec ); if( null != 一番近いチップ && 一番近いチップの時刻差の絶対値sec < 今回の時刻差の絶対値sec ) { // 時刻差の絶対値が前回より増えた → 前回のチップが指定時刻への再接近だった break; } // 更新して次へ 一番近いチップ = chip; 一番近いチップの時刻差の絶対値sec = 今回の時刻差の絶対値sec; } return 一番近いチップ; } private 表示レーン種別 _入力に対応する表示レーン種別を返す( ドラム入力イベント 入力 ) { var 表示レーン種別集合 = from kvp in Global.App.ログオン中のユーザ.ドラムチッププロパティリスト.チップtoプロパティ where kvp.Value.ドラム入力種別 == 入力.Type select kvp.Value.表示レーン種別; return ( 0 < 表示レーン種別集合.Count() ) ? 表示レーン種別集合.First() : 表示レーン種別.Unknown; } private bool _ユーザヒット対象外である( ドラム入力イベント 入力 ) { return !入力.InputEvent.押された || // 押下以外は対象外 入力.InputEvent.Control != 0 || // コントロールチェンジは対象外 入力.Type == ドラム入力種別.HiHat_Control || // ハイハットコントロールは対象外 入力.Type == ドラム入力種別.Unknown; // 未知の入力は対象外 } // ビュアーモード private readonly LoadingSpinner _LoadingSpinner; private Task _曲読み込みタスク = null!; private void _ビュアーモードの待機時背景を描画する( DeviceContext d2ddc ) { var userConfig = Global.App.ログオン中のユーザ; #region " 左サイドパネルへの描画と、左サイドパネルの表示 " //---------------- { var preTarget = d2ddc.Target; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Target = this._左サイドクリアパネル.クリアパネル.Bitmap; d2ddc.Transform = Matrix3x2.Identity; // 等倍描画(DPXtoDPX) d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; // 背景画像 d2ddc.Clear( new Color4( Color3.Black, 0f ) ); d2ddc.DrawBitmap( this._左サイドクリアパネル.背景.Bitmap, opacity: 1f, interpolationMode: InterpolationMode.Linear ); // プレイヤー名 this._プレイヤー名表示.進行描画する( d2ddc ); // スコア if( userConfig.ダーク == ダーク種別.OFF ) this._スコア表示.進行描画する( d2ddc, Global.Animation, new Vector2( +280f, +120f ), this.成績 ); // 達成率 this._達成率表示.進行描画する( d2ddc, (float)this.成績.Achievement ); // 判定パラメータ this._判定パラメータ表示.進行描画する( d2ddc, +118f, +372f, this.成績 ); // スキル this._曲別SKILL.進行描画する( d2ddc, 0f ); d2ddc.Flush(); // いったんここまで描画。 d2ddc.Target = preTarget; d2ddc.Transform = preTrans; d2ddc.PrimitiveBlend = preBlend; ( (IUnknown)preTarget ).Release(); // 要Release } this._左サイドクリアパネル.進行描画する(); //---------------- #endregion #region " 右サイドパネルへの描画と、右サイトパネルの表示 " //---------------- { var preTarget = d2ddc.Target; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Target = this._右サイドクリアパネル.クリアパネル.Bitmap; d2ddc.Transform = Matrix3x2.Identity; // 等倍描画(DPXtoDPX) d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; // 背景画像 d2ddc.Clear( new Color4( Color3.Black, 0f ) ); d2ddc.DrawBitmap( this._右サイドクリアパネル.背景.Bitmap, opacity: 1f, interpolationMode: InterpolationMode.Linear ); d2ddc.Flush(); // いったんここまで描画。 d2ddc.Target = preTarget; d2ddc.Transform = preTrans; d2ddc.PrimitiveBlend = preBlend; ( (IUnknown)preTarget ).Release(); // 要Release } this._右サイドクリアパネル.進行描画する(); //---------------- #endregion #region " レーンフレーム " //---------------- this._レーンフレーム.進行描画する( d2ddc, userConfig.レーンの透明度, レーンラインを描画する: ( userConfig.ダーク == ダーク種別.OFF ) ); //---------------- #endregion #region " 背景画像 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._背景画像.描画する( d2ddc, 0f, 0f ); //---------------- #endregion #region " 譜面スクロール速度 " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._譜面スクロール速度.描画する( d2ddc, userConfig.譜面スクロール速度 ); //---------------- #endregion #region " エキサイトゲージ " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._エキサイトゲージ.進行描画する( d2ddc, this.成績.エキサイトゲージ量 ); //---------------- #endregion #region " クリアメーター " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._クリアメーター.進行描画する( d2ddc ); //---------------- #endregion #region " フェーズパネル " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._フェーズパネル.進行描画する( d2ddc ); //---------------- #endregion #region " 曲目パネル " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._曲名パネル.進行描画する( d2ddc ); //---------------- #endregion #region " ヒットバー " //---------------- if( userConfig.ダーク != ダーク種別.FULL ) this._ドラムキットとヒットバー.ヒットバーを進行描画する( d2ddc ); //---------------- #endregion #region " ドラムキット " //---------------- if( userConfig.ダーク == ダーク種別.OFF ) this._ドラムキットとヒットバー.ドラムキットを進行描画する( d2ddc ); //---------------- #endregion } } } <|start_filename|>DTXMania2/ドラム入力/ドラム入力イベント.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2 { /// <summary> /// 単一のドラム入力イベントを表す。 /// </summary> class ドラム入力イベント { // Key public InputEvent InputEvent { get; protected set; } // Value public ドラム入力種別 Type { get; protected set; } public ドラム入力イベント( InputEvent 入力イベント, ドラム入力種別 ドラム入力種別 ) { this.InputEvent = 入力イベント; this.Type = ドラム入力種別; } public void Reset() { this.InputEvent = new InputEvent(); this.Type = ドラム入力種別.Unknown; } } } <|start_filename|>FDK/入力/InputEvent.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { /// <summary> /// 入力イベントデータの最小単位。全入力デバイスで共通。 /// </summary> public class InputEvent { /// <summary> /// 複数の同じ種類のデバイス同士を識別するための、内部デバイスID。 /// </summary> public int DeviceID { get; set; } /// <summary> /// イベントが発生したキーのコード。 /// 値の意味はデバイスに依存する。 /// </summary> public int Key { get; set; } /// <summary> /// キーが押されたのであれば true。 /// 「離された」プロパティとは排他。 /// </summary> public bool 押された { get; set; } /// <summary> /// キーが離されたのであれば true。 /// 「押された」プロパティとは排他。 /// </summary> public bool 離された { get => !( this.押された ); set => this.押された = !( value ); } /// <summary> /// このイベントが発生した時点のタイマの時刻[sec]。 /// </summary> public double TimeStamp { get; set; } /// <summary> /// 入力されたキーの強さ。 /// 値の意味はデバイスに依存する。 /// </summary> public int Velocity { get; set; } /// <summary> /// MIDIコントロールチェンジの番号。 /// 未使用なら 0 。 /// </summary> public int Control { get; set; } /// <summary> /// その他の情報。デバイス依存。 /// 未使用なら null 。 /// </summary> public string? Extra { get; set; } /// <summary> /// 可読文字列形式に変換して返す。 /// </summary> /// <returns></returns> public override string ToString() { return $"InputEvent[Key={Key}(0x{Key:X8}),押された={押された},TimeStamp={TimeStamp},Velocity={Velocity}]"; } } } <|start_filename|>FDK/ビデオ/Sources/IVideoSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; namespace FDK { public interface IVideoSource : IDisposable { /// <summary> /// ビデオフレームのサイズ[width, height]。 /// </summary> Size2F フレームサイズ { get; } /// <summary> /// ビデオが再生中(デコーダタスクが稼働中)ならtrue。 /// 一時停止中であってもtrue。 /// </summary> bool IsPlaying { get; } /// <summary> /// 指定した時刻からデコードを開始する。 /// </summary> void Start( double 再生開始時刻sec ); /// <summary> /// 次に読みだされるフレームがあれば、その表示予定時刻[100ns単位]を返す。 /// フレームがなければ、ブロックせずにすぐ 負数 を返す。 /// </summary> long Peek(); /// <summary> /// フレームを1つ読みだす。 /// 再生中の場合、フレームが取得できるまでブロックする。 /// 再生が終了している場合は null を返す。 /// 取得したフレームは、使用が終わったら、呼び出し元で Dispose すること。 /// </summary> VideoFrame? Read(); /// <summary> /// デコードを終了する。 /// </summary> void Stop(); /// <summary> /// デコードを一時停止する。 /// </summary> void Pause(); /// <summary> /// デコードを再開する。 /// <see cref="Pause"/>で停止しているときのみ有効。 /// </summary> void Resume(); } } <|start_filename|>DTXMania2/曲/Def/BoxDef.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using SharpDX; using FDK; namespace DTXMania2.曲 { /// <summary> /// BOX定義ファイルのマッピングクラス。 /// </summary> class BoxDef { // プロパティ /// <summary> /// BOX名。 /// </summary> public string TITLE { get; set; } = "(unknown)"; /// <summary> /// ボックスに関係するアーティスト名等。 /// 未指定なら null 。 /// </summary> public string? ARTIST { get; set; } = null; /// <summary> /// BOXへのコメント。 /// 未指定なら null 。 /// </summary> public string? COMMENT { get; set; } = null; /// <summary> /// BOXのプレビュー画像。 /// 未指定なら null 。 /// </summary> public string? PREIMAGE { get; set; } = null; /// <summary> /// BOXのプレビュー音声。 /// 未指定なら null 。 /// </summary> public string? PREVIEW { get; set; } = null; /// <summary> /// BOXのフォント色。 /// 未指定なら null 。 /// </summary> public Color? FONTCOLOR { get; set; } = null; /// <summary> /// BOX内の曲に適用される Perfect 範囲[秒]。 /// </summary> public double? PERFECTRANGE { get; set; } = null; /// <summary> /// BOX内の曲に適用される Great 範囲[秒]。 /// </summary> public double? GREATRANGE { get; set; } = null; /// <summary> /// BOX内の曲に適用される Good 範囲[秒]。 /// </summary> public double? GOODRANGE { get; set; } = null; /// <summary> /// BOX内の曲に適用される Ok 範囲[秒]。 /// </summary> public double? OKRANGE { get; set; } = null; /// <summary> /// スキンへのパス。 /// box.def のあるフォルダからの相対パス。 /// </summary> public string SKINPATH { get; set; } = ""; /// <summary> /// スキンへのパス(DTXMania Release 100 移行用)。 /// box.def のあるフォルダからの相対パス。 /// </summary> public string SKINPATH100 { get; set; } = ""; // 生成と終了 public BoxDef() { } public BoxDef( VariablePath boxDefファイルパス ) : this() { this.読み込む( boxDefファイルパス ); } public void 読み込む( VariablePath boxDefファイルパス ) { using var sr = new StreamReader( boxDefファイルパス.変数なしパス, Encoding.GetEncoding( 932/*Shift-JIS*/ ) ); string? 行; while( null != ( 行 = sr.ReadLine() ) ) { try { string パラメータ; #region " TITLE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"TITLE", out パラメータ ) ) { this.TITLE = パラメータ; continue; } //--------------------- #endregion #region " COMMENT コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"COMMENT", out パラメータ ) ) { this.COMMENT = パラメータ; continue; } //--------------------- #endregion #region " ARTIST コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"ARTIST", out パラメータ ) ) { this.ARTIST = パラメータ; continue; } //--------------------- #endregion #region " PREIMAGE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"PREIMAGE", out パラメータ ) ) { this.PREIMAGE = パラメータ; continue; } //--------------------- #endregion #region " PREVIEW コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"PREVIEW", out パラメータ ) ) { this.PREVIEW = パラメータ; continue; } //--------------------- #endregion #region " PERFECTRANGE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"PERFECTRANGE", out パラメータ ) ) { if( int.TryParse( パラメータ, out int value ) ) this.PERFECTRANGE = value / 0.001; else Log.ERROR( $"PERFECTRANGE の指定に誤りがあります。[{パラメータ}]" ); continue; } //--------------------- #endregion #region " GREATRANGE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"GREATRANGE", out パラメータ ) ) { if( int.TryParse( パラメータ, out int value ) ) this.GREATRANGE = value / 0.001; else Log.ERROR( $"GREATRANGE の指定に誤りがあります。[{パラメータ}]" ); continue; } //--------------------- #endregion #region " GOODRANGE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"GOODRANGE", out パラメータ ) ) { if( int.TryParse( パラメータ, out int value ) ) this.GOODRANGE = value / 0.001; else Log.ERROR( $"GOODRANGE の指定に誤りがあります。[{パラメータ}]" ); continue; } //--------------------- #endregion #region " OKRANGE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"OKRANGE", out パラメータ ) ) { if( int.TryParse( パラメータ, out int value ) ) this.OKRANGE = value / 0.001; else Log.ERROR( $"OKRANGE の指定に誤りがあります。[{パラメータ}]" ); continue; } //--------------------- #endregion #region " POORRANGE コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"POORRANGE", out パラメータ ) ) { if( int.TryParse( パラメータ, out int value ) ) this.OKRANGE = value / 0.001; else Log.ERROR( $"POORRANGE の指定に誤りがあります。[{パラメータ}]" ); continue; } //--------------------- #endregion #region " SKINPATH コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"SKINPATH", out パラメータ ) ) { this.SKINPATH = パラメータ; continue; } //--------------------- #endregion #region " SKINPATH100 コマンド " //--------------------- if( Global.コマンドのパラメータ文字列部分を返す( 行, @"SKINPATH100", out パラメータ ) ) { this.SKINPATH100 = パラメータ; continue; } //--------------------- #endregion } catch { // 例外は無視。 } } } public void 保存する( VariablePath boxDefファイルパス ) { using var sw = new StreamWriter( boxDefファイルパス.変数なしパス ); sw.WriteLine( $"#TITLE: {this.TITLE}" ); if( !string.IsNullOrEmpty( this.ARTIST ) ) sw.WriteLine( $"#ARTIST: {this.ARTIST}" ); if( !string.IsNullOrEmpty( this.COMMENT ) ) sw.WriteLine( $"#COMMENT: {this.COMMENT}" ); if( !string.IsNullOrEmpty( this.PREIMAGE ) ) sw.WriteLine( $"#PREIMAGE: {this.PREIMAGE}" ); if( !string.IsNullOrEmpty( this.PREVIEW ) ) sw.WriteLine( $"#PREVIEW: {this.PREVIEW}" ); if( null != this.FONTCOLOR ) sw.WriteLine( $"#FONTCOLOR: #{this.FONTCOLOR.Value.R:X2}{this.FONTCOLOR.Value.G:X2}{this.FONTCOLOR.Value.B:X2}" ); if( null != this.PERFECTRANGE ) sw.WriteLine( $"#PERFECTRANGE: {(int)( this.PERFECTRANGE * 1000 )}" ); if( null != this.GREATRANGE ) sw.WriteLine( $"#GREATRANGE: {(int)( this.GREATRANGE * 1000 )}" ); if( null != this.GOODRANGE ) sw.WriteLine( $"#GOODRANGE: {(int)( this.GOODRANGE * 1000 )}" ); if( null != this.OKRANGE ) sw.WriteLine( $"#OKRANGE: {(int)( this.OKRANGE * 1000 )}" ); if( !string.IsNullOrEmpty( this.SKINPATH ) ) sw.WriteLine( $"#SKINPATH: {this.SKINPATH}" ); if( !string.IsNullOrEmpty( this.SKINPATH100 ) ) sw.WriteLine( $"#SKINPATH100: {this.SKINPATH100}" ); } } } <|start_filename|>FDK/入力/KeyboardHID.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using SharpDX.Multimedia; namespace FDK { public class KeyboardHID : IDisposable { // プロパティ /// <summary> /// 発生した入力イベントのリスト。 /// <see cref="ポーリングする()"/> を呼び出す度に更新される。 /// </summary> public List<InputEvent> 入力イベントリスト { get; protected set; } = new List<InputEvent>(); // 生成と終了 public KeyboardHID( SoundTimer soundTimer ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._SoundTimer = soundTimer; // 登録したいデバイスの配列(ここでは1個)。 var devs = new RawInput.RawInputDevice[] { new RawInput.RawInputDevice { usUsagePage = UsagePage.Generic, // Genericページの usUsage = UsageId.GenericKeyboard, // Genericキーボード。 Flags = RawInput.DeviceFlags.None, hwndTarget = IntPtr.Zero, }, }; // デバイスを登録。 RawInput.RegisterRawInputDevices( devs, 1, Marshal.SizeOf<RawInput.RawInputDevice>() ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._SoundTimer = null!; } // WM_INPUT /// <summary> /// HIDキーボードからの WM_INPUT のコールバック。 /// </summary> /// <remarks> /// UIフォームのウィンドウメッセージループで WM_INPUT を受信した場合は、このコールバックを呼び出すこと。 /// </remarks> public void OnInput( in RawInput.RawInputData rawInput ) { if( rawInput.Header.Type != RawInput.DeviceType.Keyboard || rawInput.Keyboard is null ) return; // Keyboard 以外は無視。 var keyboard = rawInput.Keyboard!; // InputEvent 作成。 var inputEvent = new InputEvent() { DeviceID = 0, // 固定 Key = keyboard.VKey, // 仮想キーコード(VK_*) 押された = ( RawInput.ScanCodeFlags.Make == ( keyboard.Flags & RawInput.ScanCodeFlags.Break ) ), Velocity = 255, // 固定 TimeStamp = this._SoundTimer.現在時刻sec, Extra = keyboard.ExtraInformation.ToString( "X8" ), }; lock( this._一時入力イベントリスト ) { // 一時リストに追加。 this._一時入力イベントリスト.Add( inputEvent ); // キーの状態を更新。 this._現在のキーの押下状態[ inputEvent.Key ] = inputEvent.押された; } } // 入力 public void ポーリングする() { this.入力イベントリスト.Clear(); lock( this._一時入力イベントリスト ) { this.入力イベントリスト = this._一時入力イベントリスト; // 一時リストへの参照を直接渡して、 this._一時入力イベントリスト = new List<InputEvent>(); // 一時リストは新しく確保。 } } /// <summary> /// 最後のポーリングでキーが押されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">仮想キーコード(VK_*)。</param> public bool キーが押された( int deviceID, int key ) => this.キーが押された( deviceID, key, out _ ); /// <summary> /// 最後のポーリングでキーが押されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">仮想キーコード(VK_*)。</param> /// <param name="ev">対応する入力イベント。押されていないなら null 。</param> public bool キーが押された( int deviceID, int key, out InputEvent? ev ) { lock( this._一時入力イベントリスト ) { ev = this.入力イベントリスト.Find( ( item ) => ( item.Key == key && item.押された ) ); } return ( null != ev ); } /// <summary> /// 最後のポーリングでキーが押されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">キーコード。</param> public bool キーが押された( int deviceID, System.Windows.Forms.Keys key ) => this.キーが押された( deviceID, (int)key, out _ ); /// <summary> /// 最後のポーリングでキーが押されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">キーコード。</param> /// <param name="ev">対応する入力イベント。押されていないなら null 。</param> public bool キーが押された( int deviceID, System.Windows.Forms.Keys key, out InputEvent? ev ) => this.キーが押された( deviceID, (int)key, out ev ); /// <summary> /// 現在キーが押下状態ならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">仮想キーコード(VK_*)。</param> public bool キーが押されている( int deviceID, int key ) { lock( this._一時入力イベントリスト ) { return ( this._現在のキーの押下状態.TryGetValue( key, out bool 押されている ) ) ? 押されている : false; } } /// <summary> /// 現在キーが押下状態ならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">キーコード。</param> public bool キーが押されている( int deviceID, System.Windows.Forms.Keys key ) => this.キーが押されている( deviceID, (int)key ); /// <summary> /// 最後のポーリングでキーが離されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">仮想キーコード(VK_*)。</param> public bool キーが離された( int deviceID, int key ) => this.キーが離された( deviceID, key, out _ ); /// <summary> /// 最後のポーリングでキーが離されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">仮想キーコード(VK_*)。</param> /// <param name="ev">対応する入力イベント。押されていないなら null 。</param> public bool キーが離された( int deviceID, int key, out InputEvent? ev ) { lock( this._一時入力イベントリスト ) { ev = this.入力イベントリスト.Find( ( item ) => ( item.Key == key && item.離された ) ); } return ( null != ev ); } /// <summary> /// 最後のポーリングでキーが離されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">キーコード。</param> public bool キーが離された( int deviceID, System.Windows.Forms.Keys key ) => this.キーが離された( deviceID, (int)key, out _ ); /// <summary> /// 最後のポーリングでキーが離されたならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">キーコード。</param> /// <param name="ev">対応する入力イベント。押されていないなら null 。</param> public bool キーが離された( int deviceID, System.Windows.Forms.Keys key, out InputEvent? ev ) => this.キーが離された( deviceID, (int)key, out ev ); /// <summary> /// 現在キーが非押下状態ならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">仮想キーコード(VK_*)。</param> public bool キーが離されている( int deviceID, int key ) { lock( this._一時入力イベントリスト ) { return ( this._現在のキーの押下状態.TryGetValue( key, out bool 押されている ) ) ? !( 押されている ) : true; } } /// <summary> /// 現在キーが非押下状態ならtrueを返す。 /// </summary> /// <param name="deviceID">無効。常に 0 を指定。</param> /// <param name="key">キーコード。</param> public bool キーが離されている( int deviceID, System.Windows.Forms.Keys key ) => this.キーが離されている( deviceID, (int)key ); // ローカル /// <summary> /// <see cref="OnInput(in RawInput.RawInputData)"/> で受け取ったイベントを一時的に蓄えておくリスト。 /// </summary> /// <remarks> /// <see cref="ポーリングする()"/> の実行で、内容を <see cref="入力イベントリスト"/> にコピーしたのち、クリアされる。 /// アクセス時には必ずこのインスタンス自身を lock すること。 /// </remarks> private List<InputEvent> _一時入力イベントリスト = new List<InputEvent>(); /// <summary> /// 現在のキーの押下状態。 /// [key: 仮想キーコードをintにしたもの] /// true なら押されている状態、false なら離されている状態。 /// </summary> private readonly Dictionary<int, bool> _現在のキーの押下状態 = new Dictionary<int, bool>(); private SoundTimer _SoundTimer; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネル/パネル_ONOFFトグル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; namespace DTXMania2.オプション設定 { /// <summary> /// OFF と ON を切り替えられるスイッチ。 /// </summary> class パネル_ONOFFトグル : パネル_文字列リスト { public bool ONである { get => !( this.OFFである ); set => this.OFFである = !value; } public bool OFFである { get => ( 0 == this.現在選択されている選択肢の番号 ); set => this.現在選択されている選択肢の番号 = ( value ) ? 0 : 1; } // 生成と終了 public パネル_ONOFFトグル( string パネル名, bool 初期状態はON, Action<パネル>? 値の変更処理 = null ) : base( パネル名, new[] { ( Properties.Resources.TXT_OFF, Color.Red ), ( Properties.Resources.TXT_ON, Color4.White) }, ( 初期状態はON ) ? 1 : 0, 値の変更処理 ) { } public override void Dispose() { base.Dispose(); // 忘れずに } public override string ToString() => $"{this.パネル名}, 初期状態: {( this.ONである ? "ON" : "OFF" ) }"; } } <|start_filename|>FDK/ビデオ/Video.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.MediaFoundation; namespace FDK { public class Video : IDisposable { // プロパティ public bool 加算合成 { get; set; } = false; public bool 再生中 { get; protected set; } = false; public double 再生速度 { get; protected set; } = 1.0; // 生成と終了 protected Video() { this._再生タイマ = new QPCTimer(); } public Video( DXGIDeviceManager deviceManager, DeviceContext d2dDeviceContext, VariablePath ファイルパス, double 再生速度 = 1.0 ) : this() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.再生速度 = 再生速度; try { this._VideoSource = new MediaFoundationFileVideoSource( deviceManager, d2dDeviceContext, ファイルパス, 再生速度 ); } catch { Log.WARNING( $"動画のデコードに失敗しました。[{ファイルパス.変数付きパス}" ); this._VideoSource = null; return; } this._ファイルから生成した = true; } public Video( IVideoSource videoSource, double 再生速度 = 1.0 ) : this() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.再生速度 = 再生速度; this._VideoSource = videoSource; this._ファイルから生成した = false; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.再生を終了する(); if( this._ファイルから生成した ) this._VideoSource?.Dispose(); this._VideoSource = null; } // 再生、停止、再開 public void 再生を開始する( double 再生開始時刻sec = 0.0 ) { this._VideoSource?.Start( 再生開始時刻sec ); this._再生タイマ.リセットする( QPCTimer.秒をカウントに変換して返す( 再生開始時刻sec ) ); this.再生中 = true; } public void 再生を終了する() { this._VideoSource?.Stop(); this._最後に描画したフレーム?.Dispose(); this._最後に描画したフレーム = null; this.再生中 = false; } public void 一時停止する() { this._再生タイマ?.一時停止する(); this._VideoSource?.Pause(); } public void 再開する() { this._再生タイマ?.再開する(); this._VideoSource?.Resume(); } // 進行と描画 public void 描画する( DeviceContext d2ddc, RectangleF 描画先矩形, float 不透明度0to1 = 1.0f ) { if( this._VideoSource is null ) return; var 変換行列2D = Matrix3x2.Scaling( 描画先矩形.Width / this._VideoSource.フレームサイズ.Width, 描画先矩形.Height / this._VideoSource.フレームサイズ.Height ) * // 拡大縮小 Matrix3x2.Translation( 描画先矩形.Left, 描画先矩形.Top ); // 平行移動 this.描画する( d2ddc, 変換行列2D, 不透明度0to1 ); } public void 描画する( DeviceContext d2ddc, Matrix3x2 変換行列2D, float 不透明度0to1 = 1.0f ) { if( this._VideoSource is null ) return; long 次のフレームの表示予定時刻100ns = this._VideoSource.Peek(); // 次のフレームがなければ負数 if( 0 <= 次のフレームの表示予定時刻100ns ) { if( ( null != this._最後に描画したフレーム ) && ( 次のフレームの表示予定時刻100ns < this._最後に描画したフレーム.表示時刻100ns ) ) { // (A) 次のフレームが前のフレームより過去 → ループしたので、タイマをリセットしてから描画する。 this._再生タイマ.リセットする( QPCTimer.秒をカウントに変換して返す( (long)( 次のフレームの表示予定時刻100ns / 10_000_000.0 ) ) ); this._次のフレームを読み込んで描画する( d2ddc, 変換行列2D, 不透明度0to1 ); } else if( 次のフレームの表示予定時刻100ns <= this._再生タイマ.現在のリアルタイムカウント100ns ) { // (B) 次のフレームの表示時刻に達したので描画する。 this._次のフレームを読み込んで描画する( d2ddc, 変換行列2D, 不透明度0to1 ); } else { // (C) 次のフレームの表示時刻にはまだ達していない → 最後に描画したフレームを再描画しておく this.最後のフレームを再描画する( d2ddc, 変換行列2D, 不透明度0to1 ); } } else if( this._VideoSource.IsPlaying ) { // (D) デコードが追い付いてない。 this.最後のフレームを再描画する( d2ddc, 変換行列2D, 不透明度0to1 ); } else { // (E) ループせず再生が終わっている。 this._最後に描画したフレーム?.Dispose(); this._最後に描画したフレーム = null; } } public void 最後のフレームを再描画する( DeviceContext d2ddc, RectangleF 描画先矩形, float 不透明度0to1 = 1.0f ) { if( this._VideoSource is null ) return; var 変換行列2D = Matrix3x2.Scaling( 描画先矩形.Width / this._VideoSource.フレームサイズ.Width, 描画先矩形.Height / this._VideoSource.フレームサイズ.Height ) * // 拡大縮小 Matrix3x2.Translation( 描画先矩形.Left, 描画先矩形.Top ); // 平行移動 this.最後のフレームを再描画する( d2ddc, 変換行列2D, 不透明度0to1 ); } public void 最後のフレームを再描画する( DeviceContext d2ddc, Matrix3x2 変換行列2D, float 不透明度0to1 = 1.0f ) { if( this._最後に描画したフレーム is null ) return; this._フレームを描画する( d2ddc, 変換行列2D, 不透明度0to1, this._最後に描画したフレーム ); } // ローカル private IVideoSource? _VideoSource = null; /// <summary> /// <see cref="_VideoSource"/> をファイルから生成した場合は true、 /// 参照を受け取った場合は false。 /// </summary> private readonly bool _ファイルから生成した = false; private VideoFrame? _最後に描画したフレーム = null; private readonly QPCTimer _再生タイマ; private void _次のフレームを読み込んで描画する( DeviceContext d2ddc, Matrix3x2 変換行列2D, float 不透明度0to1 = 1.0f ) { if( this._VideoSource is null ) return; VideoFrame? 次のフレーム; // フレームドロップ判定 while( true ) { // 次のフレームを取得: // デコードが間に合ってない場合にはブロックする。 // ブロックされたくない場合は、事前に Peek() でチェックしておくこと。 次のフレーム = this._VideoSource.Read(); // フレームドロップ判定; // 次の次のフレームがすでに表示時刻を過ぎてるなら、次のフレームは破棄してループする。 var 次の次のフレームの表示予定時刻100ns = this._VideoSource.Peek(); if( 0 > 次の次のフレームの表示予定時刻100ns ) { // (A) 次の次のフレームがまだない場合 → ドロップ判定ループを抜けて描画へ。 break; } else { if( 次の次のフレームの表示予定時刻100ns <= this._再生タイマ.現在のキャプチャカウント100ns ) { // (B) 次の次のフレームが存在し、かつ表示予定時刻を過ぎてる場合 → 次のフレームは破棄してさらに次へ。 次のフレーム?.Dispose(); continue; } else { // (C) 次の次のフレームが存在し、かつ表示予定時刻をまだすぎてない場合 → ドロップ判定ループを抜けて描画へ。 break; } } } // 描画。 this._フレームを描画する( d2ddc, 変換行列2D, 不透明度0to1, 次のフレーム! ); // 更新。 this._最後に描画したフレーム?.Dispose(); this._最後に描画したフレーム = 次のフレーム; } private void _フレームを描画する( DeviceContext d2ddc, Matrix3x2 変換行列2D, float 不透明度0to1, VideoFrame 描画するフレーム ) { if( 描画するフレーム is null ) return; var preTrans = d2ddc.Transform; var preBlend = d2ddc.PrimitiveBlend; d2ddc.Transform = ( 変換行列2D ) * preTrans; d2ddc.PrimitiveBlend = ( this.加算合成 ) ? PrimitiveBlend.Add : PrimitiveBlend.SourceOver; d2ddc.DrawBitmap( 描画するフレーム.Bitmap, 不透明度0to1, InterpolationMode.NearestNeighbor ); d2ddc.PrimitiveBlend = preBlend; d2ddc.Transform = preTrans; } } } <|start_filename|>DTXMania2/ステージ/07演奏/ドラムキットとヒットバー.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class ドラムキットとヒットバー : IDisposable { // プロパティ /// <summary> /// 0.0:閉じてる ~ 1.0:開いてる /// </summary> public float ハイハットの開度 { get; protected set; } = 1f; // 生成と終了 public ドラムキットとヒットバー() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ドラムキット画像 = new 画像D2D( @"$(Images)\PlayStage\DrumKit_and_HitBar.png" ); this._パーツ画像の矩形リスト = new Dictionary<パーツ, RectangleF>(); this._パーツ画像の中心位置 = new Dictionary<パーツ, (float X, float Y)>(); var 設定ファイルパス = new VariablePath( @"$(Images)\PlayStage\DrumKit_and_HitBar.yaml" ); var yaml = File.ReadAllText( 設定ファイルパス.変数なしパス ); var deserializer = new YamlDotNet.Serialization.Deserializer(); var yamlMap = deserializer.Deserialize<YAMLマップ>( yaml ); foreach( var kvp in yamlMap.RectangleList ) { if( 4 == kvp.Value.Length ) this._パーツ画像の矩形リスト[ kvp.Key ] = new RectangleF( kvp.Value[ 0 ], kvp.Value[ 1 ], kvp.Value[ 2 ], kvp.Value[ 3 ] ); } foreach( var kvp in yamlMap.CenterPosition ) { if( 2 == kvp.Value.Length ) this._パーツ画像の中心位置[ kvp.Key ] = (kvp.Value[ 0 ], kvp.Value[ 1 ]); } this._振動パラメータ = new Dictionary<表示レーン種別, 振動パラメータ>(); foreach( 表示レーン種別? lane in Enum.GetValues( typeof( 表示レーン種別 ) ) ) { if( lane.HasValue ) this._振動パラメータ[ lane.Value ] = new 振動パラメータ(); } } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ドラムキット画像.Dispose(); } // 操作 /// <summary> /// ベロシティ(開:0~80:閉)に応じたハイハット開度を設定する。 /// </summary> /// <remarks> /// 80超えの指定も可能。 /// </remarks> public void ハイハットの開度を設定する( int ベロシティ値 ) { // ベロシティ80超えはすべて1.0(完全閉じ)とする。 this.ハイハットの開度 = 1f - ( Math.Min( ベロシティ値, 80 ) / 80f ); } public void ヒットアニメ開始( 表示レーン種別 lane ) { this._振動パラメータ[ lane ] = new 振動パラメータ { カウンタ = new Counter( 0, 100, 3 ), 振動幅 = 0f, }; } // 進行と描画 public void ドラムキットを進行描画する( DeviceContext d2ddc ) { float Bassの振動幅 = 0f; // Bass の振動は HiTom, LowTom にも影響する。 #region " Bass " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.Bass ].カウンタ; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 2 → 0 Bassの振動幅 = 最大振幅 * MathF.Sin( 10.0f * MathF.PI * counter.現在値の割合 ); // 10周 } this._パーツを描画する( d2ddc, パーツ.Bass, Y方向移動量: Bassの振動幅 ); } //---------------- #endregion #region " LowTom " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.Tom2 ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 2 → 0 振動幅 = 最大振幅 * MathF.Sin( 15.0f * MathF.PI * counter.現在値の割合 ); // 15周 } 振動幅 += Bassの振動幅; // Bassと連動する this._パーツを描画する( d2ddc, パーツ.LowTom, Y方向移動量: 振動幅 ); } //---------------- #endregion #region " HiTom " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.Tom1 ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 2 → 0 振動幅 = 最大振幅 * MathF.Sin( 15.0f * MathF.PI * counter.現在値の割合 ); // 15周 } 振動幅 += Bassの振動幅; // Bassと連動する this._パーツを描画する( d2ddc, パーツ.HiTom, Y方向移動量: 振動幅 ); } //---------------- #endregion #region " FloorTom " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.Tom3 ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 2 → 0 振動幅 = 最大振幅 * MathF.Sin( 10.0f * MathF.PI * counter.現在値の割合 ); // 10周 } this._パーツを描画する( d2ddc, パーツ.FloorTom, Y方向移動量: 振動幅 ); } //---------------- #endregion #region " Snare " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.Snare ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 5.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 5 → 0 振動幅 = 最大振幅 * MathF.Sin( 17.0f * MathF.PI * counter.現在値の割合 ); // 17周 } this._パーツを描画する( d2ddc, パーツ.Snare, Y方向移動量: 振動幅 ); } //---------------- #endregion #region " HiHat " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.HiHat ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = ( this.ハイハットの開度 < 0.2f ) ? 1f : ( 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ) ); // 2 → 0, 開度が小さい場合は 1。 振動幅 = 最大振幅 * MathF.Sin( 20.0f * MathF.PI * counter.現在値の割合 ); // 20周 } this._パーツを描画する( d2ddc, パーツ.HiHatBottom ); // Bottom は動かない。 this._パーツを描画する( d2ddc, パーツ.HiHatTop, Y方向移動量: 振動幅 - 20f * this.ハイハットの開度 ); } //---------------- #endregion #region " RightCymbal " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.RightCymbal ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 2 → 0 振動幅 = 最大振幅 * MathF.Sin( 20.0f * MathF.PI * counter.現在値の割合 ); // 20周 } this._パーツを描画する( d2ddc, パーツ.RightCymbalStand ); // Standは動かない。 this._パーツを描画する( d2ddc, パーツ.RightCymbal, Y方向移動量: 振動幅 ); this._パーツを描画する( d2ddc, パーツ.RightCymbalTop, Y方向移動量: 振動幅 ); } //---------------- #endregion #region " LeftCymbal " //---------------- { var counter = this._振動パラメータ[ 表示レーン種別.LeftCymbal ].カウンタ; float 振動幅 = 0; if( null != counter && counter.終了値に達していない ) { float 最大振幅 = 2.0f * MathF.Cos( MathF.PI / 2.0f * counter.現在値の割合 ); // 2 → 0 振動幅 = 最大振幅 * MathF.Sin( 20.0f * MathF.PI * counter.現在値の割合 ); // 20周 } this._パーツを描画する( d2ddc, パーツ.LeftCymbalStand ); // Standは動かない。 this._パーツを描画する( d2ddc, パーツ.LeftCymbal, Y方向移動量: 振動幅 ); this._パーツを描画する( d2ddc, パーツ.LeftCymbalTop, Y方向移動量: 振動幅 ); } //---------------- #endregion } public void ヒットバーを進行描画する( DeviceContext d2ddc ) { this._パーツを描画する( d2ddc, パーツ.Bar ); } private void _パーツを描画する( DeviceContext d2ddc, パーツ パーツ名, float X方向移動量 = 0f, float Y方向移動量 = 0f ) { var 中心位置 = this._パーツ画像の中心位置[ パーツ名 ]; var srcRect = this._パーツ画像の矩形リスト[ パーツ名 ]; this._ドラムキット画像.描画する( d2ddc, 中心位置.X - srcRect.Width / 2 + X方向移動量, 中心位置.Y - srcRect.Height / 2 + Y方向移動量, 転送元矩形: srcRect ); } // ローカル private readonly 画像D2D _ドラムキット画像; private readonly Dictionary<パーツ, RectangleF> _パーツ画像の矩形リスト; private readonly Dictionary<パーツ, (float X, float Y)> _パーツ画像の中心位置; private class 振動パラメータ { public Counter カウンタ = null!; public float 振動幅 = 0f; } private readonly Dictionary<表示レーン種別, 振動パラメータ> _振動パラメータ; private enum パーツ { LeftCymbalStand, LeftCymbal, LeftCymbalTop, RightCymbalStand, RightCymbal, RightCymbalTop, HiHatBottom, HiHatTop, Bass, Snare, HiTom, LowTom, FloorTom, Bar, } private class YAMLマップ { public Dictionary<パーツ, float[]> RectangleList { get; set; } = null!; public Dictionary<パーツ, float[]> CenterPosition { get; set; } = null!; } } } <|start_filename|>SSTFEditor/検索条件入力ダイアログ.designer.cs<|end_filename|> namespace SSTFEditor { partial class 検索条件入力ダイアログ { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(検索条件入力ダイアログ)); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.checkBox小節範囲指定 = new System.Windows.Forms.CheckBox(); this.buttonOK = new System.Windows.Forms.Button(); this.buttonキャンセル = new System.Windows.Forms.Button(); this.textBox小節範囲終了 = new System.Windows.Forms.TextBox(); this.textBox小節範囲開始 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.buttonAllレーン = new System.Windows.Forms.Button(); this.buttonClearレーン = new System.Windows.Forms.Button(); this.checkedListBoxレーン選択リスト = new System.Windows.Forms.CheckedListBox(); this.checkedListBoxチップ選択リスト = new System.Windows.Forms.CheckedListBox(); this.buttonAllチップ = new System.Windows.Forms.Button(); this.buttonClearチップ = new System.Windows.Forms.Button(); this.labelレーンから選択 = new System.Windows.Forms.Label(); this.labelチップから選択 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // checkBox小節範囲指定 // resources.ApplyResources(this.checkBox小節範囲指定, "checkBox小節範囲指定"); this.checkBox小節範囲指定.Name = "checkBox小節範囲指定"; this.toolTip1.SetToolTip(this.checkBox小節範囲指定, resources.GetString("checkBox小節範囲指定.ToolTip")); this.checkBox小節範囲指定.UseVisualStyleBackColor = true; this.checkBox小節範囲指定.CheckStateChanged += new System.EventHandler(this.checkBox小節範囲指定_CheckStateChanged); this.checkBox小節範囲指定.KeyDown += new System.Windows.Forms.KeyEventHandler(this.checkBox小節範囲指定_KeyDown); // // buttonOK // resources.ApplyResources(this.buttonOK, "buttonOK"); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Name = "buttonOK"; this.buttonOK.UseVisualStyleBackColor = true; // // buttonキャンセル // resources.ApplyResources(this.buttonキャンセル, "buttonキャンセル"); this.buttonキャンセル.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonキャンセル.Name = "buttonキャンセル"; this.buttonキャンセル.UseVisualStyleBackColor = true; // // textBox小節範囲終了 // resources.ApplyResources(this.textBox小節範囲終了, "textBox小節範囲終了"); this.textBox小節範囲終了.Name = "textBox小節範囲終了"; this.textBox小節範囲終了.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox小節範囲終了_KeyDown); // // textBox小節範囲開始 // resources.ApplyResources(this.textBox小節範囲開始, "textBox小節範囲開始"); this.textBox小節範囲開始.Name = "textBox小節範囲開始"; this.textBox小節範囲開始.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox小節範囲開始_KeyDown); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // buttonAllレーン // resources.ApplyResources(this.buttonAllレーン, "buttonAllレーン"); this.buttonAllレーン.Name = "buttonAllレーン"; this.buttonAllレーン.UseVisualStyleBackColor = true; this.buttonAllレーン.Click += new System.EventHandler(this.buttonAllレーン_Click); this.buttonAllレーン.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonAllレーン_KeyDown); // // buttonClearレーン // resources.ApplyResources(this.buttonClearレーン, "buttonClearレーン"); this.buttonClearレーン.Name = "buttonClearレーン"; this.buttonClearレーン.UseVisualStyleBackColor = true; this.buttonClearレーン.Click += new System.EventHandler(this.buttonClearレーン_Click); this.buttonClearレーン.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonClearレーン_KeyDown); // // checkedListBoxレーン選択リスト // resources.ApplyResources(this.checkedListBoxレーン選択リスト, "checkedListBoxレーン選択リスト"); this.checkedListBoxレーン選択リスト.FormattingEnabled = true; this.checkedListBoxレーン選択リスト.Name = "checkedListBoxレーン選択リスト"; this.checkedListBoxレーン選択リスト.KeyDown += new System.Windows.Forms.KeyEventHandler(this.checkedListBoxレーン選択リスト_KeyDown); // // checkedListBoxチップ選択リスト // resources.ApplyResources(this.checkedListBoxチップ選択リスト, "checkedListBoxチップ選択リスト"); this.checkedListBoxチップ選択リスト.FormattingEnabled = true; this.checkedListBoxチップ選択リスト.Name = "checkedListBoxチップ選択リスト"; // // buttonAllチップ // resources.ApplyResources(this.buttonAllチップ, "buttonAllチップ"); this.buttonAllチップ.Name = "buttonAllチップ"; this.buttonAllチップ.UseVisualStyleBackColor = true; this.buttonAllチップ.Click += new System.EventHandler(this.buttonAllチップ_Click); this.buttonAllチップ.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonAllチップ_KeyDown); // // buttonClearチップ // resources.ApplyResources(this.buttonClearチップ, "buttonClearチップ"); this.buttonClearチップ.Name = "buttonClearチップ"; this.buttonClearチップ.UseVisualStyleBackColor = true; this.buttonClearチップ.Click += new System.EventHandler(this.buttonClearチップ_Click); this.buttonClearチップ.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonClearチップ_KeyDown); // // labelレーンから選択 // resources.ApplyResources(this.labelレーンから選択, "labelレーンから選択"); this.labelレーンから選択.Name = "labelレーンから選択"; // // labelチップから選択 // resources.ApplyResources(this.labelチップから選択, "labelチップから選択"); this.labelチップから選択.Name = "labelチップから選択"; // // 検索条件入力ダイアログ // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ControlBox = false; this.Controls.Add(this.labelチップから選択); this.Controls.Add(this.labelレーンから選択); this.Controls.Add(this.buttonAllチップ); this.Controls.Add(this.buttonClearチップ); this.Controls.Add(this.checkedListBoxチップ選択リスト); this.Controls.Add(this.buttonAllレーン); this.Controls.Add(this.buttonClearレーン); this.Controls.Add(this.checkedListBoxレーン選択リスト); this.Controls.Add(this.checkBox小節範囲指定); this.Controls.Add(this.textBox小節範囲終了); this.Controls.Add(this.textBox小節範囲開始); this.Controls.Add(this.label2); this.Controls.Add(this.buttonOK); this.Controls.Add(this.buttonキャンセル); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "検索条件入力ダイアログ"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnFormClosing); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonキャンセル; private System.Windows.Forms.CheckBox checkBox小節範囲指定; private System.Windows.Forms.TextBox textBox小節範囲終了; private System.Windows.Forms.TextBox textBox小節範囲開始; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button buttonAllレーン; private System.Windows.Forms.Button buttonClearレーン; private System.Windows.Forms.CheckedListBox checkedListBoxレーン選択リスト; private System.Windows.Forms.CheckedListBox checkedListBoxチップ選択リスト; private System.Windows.Forms.Button buttonAllチップ; private System.Windows.Forms.Button buttonClearチップ; private System.Windows.Forms.Label labelレーンから選択; private System.Windows.Forms.Label labelチップから選択; } } <|start_filename|>DTXMania2/ステージ/04選曲/曲ステータスパネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; using DTXMania2.曲; using DTXMania2.演奏; namespace DTXMania2.選曲 { class 曲ステータスパネル : IDisposable { // 生成と終了 public 曲ステータスパネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._背景画像 = new 画像D2D( @"$(Images)\SelectStage\ScoreStatusPanel.png" ); // 色ブラシを作成。 var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; this._色 = new Dictionary<表示レーン種別, SolidColorBrush>() { { 表示レーン種別.LeftCymbal, new SolidColorBrush( d2ddc, new Color4( 0xff7b1fff ) ) }, { 表示レーン種別.HiHat, new SolidColorBrush( d2ddc, new Color4( 0xffffc06a ) ) }, { 表示レーン種別.Foot, new SolidColorBrush( d2ddc, new Color4( 0xffed4bff ) ) }, { 表示レーン種別.Snare, new SolidColorBrush( d2ddc, new Color4( 0xff16fefc ) ) }, { 表示レーン種別.Tom1, new SolidColorBrush( d2ddc, new Color4( 0xff00ff02 ) ) }, { 表示レーン種別.Bass, new SolidColorBrush( d2ddc, new Color4( 0xffff819b ) ) }, { 表示レーン種別.Tom2, new SolidColorBrush( d2ddc, new Color4( 0xff0000ff ) ) }, { 表示レーン種別.Tom3, new SolidColorBrush( d2ddc, new Color4( 0xff19a9ff ) ) }, { 表示レーン種別.RightCymbal, new SolidColorBrush( d2ddc, new Color4( 0xffffb55e ) ) }, }; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var kvp in this._色 ) kvp.Value.Dispose(); this._背景画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, Node フォーカスノード ) { var 領域dpx = new RectangleF( 320f, 532f, 239f, 505f ); this._背景画像.描画する( d2ddc, 領域dpx.X, 領域dpx.Y ); if( !( フォーカスノード is SongNode snode ) || snode.曲.フォーカス譜面 is null ) { // 現状、BPMを表示できるノードは SongNode のみ。 // SongNode 以外は背景の描画だけで終わり。 return; } #region " フォーカスノードが変更されていれば更新する。" //---------------- if( フォーカスノード != this._現在表示しているノード ) { this._現在表示しているノード = フォーカスノード; } //---------------- #endregion #region " Total Notes を描画する。" //---------------- { var map = snode.曲.フォーカス譜面.レーン別ノート数; if( null != map ) { const float Yオフセット = +2f; var Xオフセット = new Dictionary<表示レーン種別, float>() { { 表示レーン種別.LeftCymbal, + 70f }, { 表示レーン種別.HiHat, + 88f }, { 表示レーン種別.Foot, +106f }, { 表示レーン種別.Snare, +124f }, { 表示レーン種別.Tom1, +142f }, { 表示レーン種別.Bass, +160f }, { 表示レーン種別.Tom2, +178f }, { 表示レーン種別.Tom3, +196f }, { 表示レーン種別.RightCymbal, +214f }, }; foreach( 表示レーン種別? lane in Enum.GetValues( typeof( 表示レーン種別 ) ) ) { if( lane.HasValue && map.ContainsKey( lane.Value ) ) { var rc = new RectangleF( 領域dpx.X + Xオフセット[ lane.Value ], 領域dpx.Y + Yオフセット, 6f, 405f ); rc.Top = rc.Bottom - ( rc.Height * Math.Min( map[ lane.Value ], 250 ) / 250f ); d2ddc.FillRectangle( rc, this._色[ lane.Value ] ); } } } } //---------------- #endregion } // ローカル private readonly 画像D2D _背景画像; private readonly Dictionary<表示レーン種別, SolidColorBrush> _色; private Node? _現在表示しているノード = null; } } <|start_filename|>DTXMania2/ステージ/08結果/ランク種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.結果 { enum ランク種別 { SS, S, A, B, C, D, E, } } <|start_filename|>DTXMania2/ステージ/02タイトル/タイトルステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.タイトル { class タイトルステージ : IStage { // プロパティ public enum フェーズ { 表示, フェードアウト, 完了, キャンセル, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; // 生成と終了 public タイトルステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._舞台画像 = new 舞台画像(); this._システム情報 = new システム情報(); this._タイトルロゴ = new 画像D2D( @"$(Images)\TitleLogo.png" ); this._帯ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0f, 0f, 0f, 0.8f ) ); this._パッドを叩いてください = new 文字列画像D2D() { 表示文字列 = Properties.Resources.TXT_パッドを叩いてください, フォントサイズpt = 40f, 描画効果 = 文字列画像D2D.効果.縁取り, }; Global.App.システムサウンド.再生する( システムサウンド種別.タイトルステージ_開始音 ); Global.App.システムサウンド.再生する( システムサウンド種別.タイトルステージ_ループBGM, ループ再生する: true ); Global.App.ログオフする(); // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.表示; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); Global.App.システムサウンド.停止する( システムサウンド種別.タイトルステージ_開始音 ); Global.App.システムサウンド.停止する( システムサウンド種別.タイトルステージ_ループBGM ); //Global.App.システムサウンド.停止する( システムサウンド種別.タイトルステージ_確定音 ); --> 鳴らしっぱなしでいい this._パッドを叩いてください.Dispose(); this._帯ブラシ.Dispose(); this._タイトルロゴ.Dispose(); this._システム情報.Dispose(); this._舞台画像.Dispose(); } // 進行と描画 public void 進行する() { this._システム情報.FPSをカウントしプロパティを更新する(); Global.App.ドラム入力.すべての入力デバイスをポーリングする(); switch( this.現在のフェーズ ) { case フェーズ.表示: { #region " 入力処理。" //---------------- if( Global.App.ドラム入力.確定キーが入力された() ) { #region " 確定 → クローズアイキャッチを開始してフェードアウトへ " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.タイトルステージ_確定音 ); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( シャッター ) ); this.現在のフェーズ = フェーズ.フェードアウト; //---------------- #endregion } else if( Global.App.ドラム入力.キャンセルキーが入力された() ) { #region " キャンセル → キャンセルフェーズへ " //---------------- this.現在のフェーズ = フェーズ.キャンセル; //---------------- #endregion } //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " フェードアウト描画が完了したら完了フェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) this.現在のフェーズ = フェーズ.完了; //---------------- #endregion break; } case フェーズ.キャンセル: case フェーズ.完了: { #region " 遷移終了。Appによるステージ遷移を待つ。" //---------------- //---------------- #endregion break; } } } public void 描画する() { this._システム情報.VPSをカウントする(); var dc = Global.GraphicResources.既定のD2D1DeviceContext; dc.Transform = Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.表示: { #region " タイトル画面を描画する。" //---------------- dc.BeginDraw(); this._舞台画像.進行描画する( dc ); this._メッセージを描画する( dc ); this._タイトルロゴを描画する( dc ); this._システム情報.描画する( dc ); dc.EndDraw(); //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " タイトル画面&フェードアウトを描画する。" //---------------- dc.BeginDraw(); this._舞台画像.進行描画する( dc ); this._メッセージを描画する( dc ); this._タイトルロゴを描画する( dc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( dc ); this._システム情報.描画する( dc ); dc.EndDraw(); //---------------- #endregion break; } } } // ローカル private readonly 舞台画像 _舞台画像; private readonly システム情報 _システム情報; private readonly 画像D2D _タイトルロゴ; private readonly Brush _帯ブラシ; private readonly 文字列画像D2D _パッドを叩いてください; private void _タイトルロゴを描画する( DeviceContext d2ddc ) { this._タイトルロゴ.描画する( d2ddc, ( Global.GraphicResources.設計画面サイズ.Width - this._タイトルロゴ.サイズ.Width ) / 2f, ( Global.GraphicResources.設計画面サイズ.Height - this._タイトルロゴ.サイズ.Height ) / 2f - 100f ); } private void _メッセージを描画する( DeviceContext d2ddc ) { d2ddc.FillRectangle( new RectangleF( 0f, 800f, Global.GraphicResources.設計画面サイズ.Width, 80f ), this._帯ブラシ ); if( this._パッドを叩いてください.画像サイズdpx.Width == 0 ) { // 画像が未生成なら先に生成する。描画時に画像サイズが必要なため。 this._パッドを叩いてください.ビットマップを生成または更新する( d2ddc ); } this._パッドを叩いてください.描画する( d2ddc, Global.GraphicResources.設計画面サイズ.Width / 2f - this._パッドを叩いてください.画像サイズdpx.Width / 2f, 810f ); } } } <|start_filename|>DTXMania2/ステージ/04選曲/選曲ステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Animation; using FDK; using DTXMania2.曲; using SSTF=SSTFormat.v004; namespace DTXMania2.選曲 { class 選曲ステージ : IStage { // プロパティ public enum フェーズ { フェードイン, 表示, QuickConfig, フェードアウト, 確定_選曲, 確定_設定, キャンセル, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.確定_選曲; // 生成と終了 public 選曲ステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._舞台画像 = new 舞台画像( @"$(Images)\Background_Dark.jpg" ); this._システム情報 = new システム情報(); this._UpdatingSoglistパネル = new UpdatingSoglistパネル(); this._表示方法選択パネル = new 表示方法選択パネル(); this._青い線 = new 青い線(); this._選択曲枠ランナー = new 選択曲枠ランナー(); this._選曲リスト = new 選曲リスト(); this._難易度と成績 = new 難易度と成績(); this._難易度と成績.青い線を取得する = () => this._青い線; // 外部依存アクションの接続 this._曲ステータスパネル = new 曲ステータスパネル(); this._BPMパネル = new BPMパネル(); this._曲別スキルと達成率 = new 曲別スキルと達成率(); this._ステージタイマー = new 画像D2D( @"$(Images)\SelectStage\StageTimer.png" ); this._既定のノード画像 = new 画像D2D( @"$(Images)\DefaultPreviewImage.png" ); this._現行化前のノード画像 = new 画像D2D( @"$(Images)\PreviewImageWaitForActivation.png" ); this._SongNotFound = new 文字列画像D2D() { 表示文字列 = Properties.Resources.TXT_曲が見つかりません, }; this._QuickConfig画面 = null!; // 使用時に生成 this._フェートアウト後のフェーズ = フェーズ.確定_選曲; Global.App.システムサウンド.再生する( システムサウンド種別.選曲ステージ_開始音 ); Global.App.アイキャッチ管理.現在のアイキャッチ.オープンする(); this._導線アニメをリセットする(); // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.フェードイン; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); //this._QuickConfig画面.Dispose(); 使用時に破棄。 this._SongNotFound.Dispose(); this._現行化前のノード画像.Dispose(); this._既定のノード画像.Dispose(); this._ステージタイマー.Dispose(); this._曲別スキルと達成率.Dispose(); this._BPMパネル.Dispose(); this._曲ステータスパネル.Dispose(); this._難易度と成績.Dispose(); this._選曲リスト.Dispose(); this._選択曲枠ランナー.Dispose(); this._青い線.Dispose(); this._表示方法選択パネル.Dispose(); this._UpdatingSoglistパネル.Dispose(); this._システム情報.Dispose(); this._舞台画像.Dispose(); } // 進行と描画 public void 進行する() { this._システム情報.FPSをカウントしプロパティを更新する(); var 入力 = Global.App.ドラム入力; var 曲ツリー = Global.App.曲ツリーリスト.SelectedItem!; var フォーカスリスト = 曲ツリー.フォーカスリスト; var フォーカスノード = 曲ツリー.フォーカスノード!; 入力.すべての入力デバイスをポーリングする(); switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " フェードイン描画が完了したら次のフェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.オープン完了 ) { this.現在のフェーズ = フェーズ.表示; // 曲ツリーの現行化タスクが一時停止していれば、再開する。 Global.App.現行化.再開する(); } //---------------- #endregion break; } case フェーズ.表示: { #region " 入力処理。" //---------------- if( 入力.確定キーが入力された() && 1 < フォーカスリスト.Count ) // ノードが2つ以上ある(1つはランダムセレクト) { #region " 確定 " //---------------- if( フォーカスノード is BoxNode ) { #region " BOX の場合 → BOX に入る。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.決定音 ); this._選曲リスト.BOXに入る(); //---------------- #endregion } else if( フォーカスノード is BackNode ) { #region " Back の場合 → BOX から出る。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.決定音 ); this._選曲リスト.BOXから出る(); //---------------- #endregion } else if( フォーカスノード is RandomSelectNode randomNode ) { #region " RANDOM SELECT の場合 → ランダムに選曲してフェードアウトへ。" //---------------- // ランダムに選曲する。 var sn = randomNode.譜面をランダムに選んで返す(); if( sn.HasValue ) { // 選択曲の現行化がまだであれば完了を待つ。 if( !sn.Value.曲.現行化済み ) { this._選曲リスト.指定したノードを優先して現行化する( sn.Value.曲 ); while( !sn.Value.曲.現行化済み ) Thread.Sleep( 100 ); // 現行化完了待ち } // 曲ツリーの現行化タスクが動いていれば、一時停止する。 Global.App.現行化.一時停止する(); // 選曲する。 Global.App.演奏譜面 = sn.Value.譜面; Global.App.システムサウンド.再生する( システムサウンド種別.選曲ステージ_曲決定音 ); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( GO ) ); // 次のフェーズへ。 this._フェートアウト後のフェーズ = フェーズ.確定_選曲; this.現在のフェーズ = フェーズ.フェードアウト; } //---------------- #endregion } else if( フォーカスノード is SongNode snode && null != snode.曲.フォーカス譜面 ) { #region " 曲の場合 → 選曲してフェードアウトへ。" //---------------- // 選択曲の現行化がまだであれば完了を待つ。 if( !snode.現行化済み ) { this._選曲リスト.フォーカスノードを優先して現行化する(); while( !snode.現行化済み ) Thread.Sleep( 100 ); // 現行化完了待ち } // 曲ツリーの現行化タスクが動いていれば、一時停止する。 Global.App.現行化.一時停止する(); // 選曲する。 Global.App.演奏譜面 = snode.曲.フォーカス譜面; this._選曲リスト.プレビュー音声を停止する(); Global.App.システムサウンド.再生する( システムサウンド種別.選曲ステージ_曲決定音 ); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( GO ) ); // 次のフェーズへ。 this._フェートアウト後のフェーズ = フェーズ.確定_選曲; this.現在のフェーズ = フェーズ.フェードアウト; //---------------- #endregion } //---------------- #endregion } else if( 入力.キャンセルキーが入力された() ) { #region " キャンセル " //---------------- this._選曲リスト.プレビュー音声を停止する(); Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); if( null != フォーカスノード.親ノード!.親ノード ) { // BOX 内にいる場合 → BOX から出る。 this._選曲リスト.BOXから出る(); } else { // 曲階層のルートにいる場合 → キャンセルフェーズへ。 this.現在のフェーズ = フェーズ.キャンセル; } //---------------- #endregion } else if( 入力.上移動キーが入力された() ) { #region " 上移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._選曲リスト.前のノードを選択する(); this._導線アニメをリセットする(); //---------------- #endregion } else if( 入力.下移動キーが入力された() ) { #region " 下移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._選曲リスト.次のノードを選択する(); this._導線アニメをリセットする(); //---------------- #endregion } else if( 入力.左移動キーが入力された() ) { #region " 左移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); this._表示方法選択パネル.前のパネルを選択する(); //---------------- #endregion } else if( 入力.右移動キーが入力された() ) { #region " 右移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); this._表示方法選択パネル.次のパネルを選択する(); //---------------- #endregion } else if( 入力.シーケンスが入力された( new[] { SSTF.レーン種別.HiHat, SSTF.レーン種別.HiHat }, Global.App.ログオン中のユーザ.ドラムチッププロパティリスト ) ) { #region " HH×2 → 難易度変更 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); 曲ツリー.ユーザ希望難易度をひとつ増やす(); //---------------- #endregion } else if( 入力.シーケンスが入力された( new[] { SSTF.レーン種別.Bass, SSTF.レーン種別.Bass }, Global.App.ログオン中のユーザ.ドラムチッププロパティリスト ) ) { #region " BD×2 → QuickConfig画面を生成し、QuickConfig フェーズへ " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.決定音 ); this._選曲リスト.フォーカスノードを優先して現行化する(); this._QuickConfig画面 = new QuickConfig.QuickConfigパネル( song: ( フォーカスノード is SongNode snode ) ? snode.曲 : null, userId: Global.App.ログオン中のユーザ.ID! ); this.現在のフェーズ = フェーズ.QuickConfig; //---------------- #endregion } //---------------- #endregion break; } case フェーズ.QuickConfig: { #region " QuickConfig パネルの選択結果に従って次のフェーズへ。" //---------------- this._QuickConfig画面.進行する(); if( this._QuickConfig画面.現在のフェーズ == QuickConfig.QuickConfigパネル.フェーズ.完了_戻る ) { #region " 戻る → 表示フェーズへ " //---------------- this._QuickConfig画面.Dispose(); this.現在のフェーズ = フェーズ.表示; //---------------- #endregion } else if( this._QuickConfig画面.現在のフェーズ == QuickConfig.QuickConfigパネル.フェーズ.完了_オプション設定 ) { #region " オプション設定 → 確定_設定フェーズへ " //---------------- this._選曲リスト.プレビュー音声を停止する(); this._QuickConfig画面.Dispose(); this.現在のフェーズ = フェーズ.確定_設定; //---------------- #endregion } //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " 背景画面&フェードアウトを描画する。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) { // フェードアウト描画が完了したら次のフェーズへ。 this.現在のフェーズ = this._フェートアウト後のフェーズ; // フェードアウト開始時に設定済み } //---------------- #endregion break; } case フェーズ.確定_選曲: case フェーズ.確定_設定: case フェーズ.キャンセル: { #region " 遷移終了。Appによるステージ遷移を待つ。" //---------------- //---------------- #endregion break; } } } public void 描画する() { this._システム情報.VPSをカウントする(); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " 背景画面&フェードインを描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.表示: { #region " 背景画面を描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.QuickConfig: { #region " 背景画面&QuickConfigを描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); this._システム情報.描画する( d2ddc ); this._QuickConfig画面.描画する( d2ddc, 568f, 68f ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " 背景画面&フェードアウトを描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.確定_選曲: case フェーズ.確定_設定: case フェーズ.キャンセル: { break; } } } // ローカル private readonly 舞台画像 _舞台画像; private readonly システム情報 _システム情報; private readonly UpdatingSoglistパネル _UpdatingSoglistパネル; private readonly 表示方法選択パネル _表示方法選択パネル; private readonly 青い線 _青い線; private readonly 選択曲枠ランナー _選択曲枠ランナー; private readonly 選曲リスト _選曲リスト; private readonly 文字列画像D2D _SongNotFound; private readonly 難易度と成績 _難易度と成績; private readonly 曲ステータスパネル _曲ステータスパネル; private readonly BPMパネル _BPMパネル; private readonly 曲別スキルと達成率 _曲別スキルと達成率; private readonly 画像D2D _ステージタイマー; private QuickConfig.QuickConfigパネル _QuickConfig画面; private フェーズ _フェートアウト後のフェーズ; private void _その他パネルを描画する( DeviceContext d2ddc ) { var preBlend = d2ddc.PrimitiveBlend; d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; using( var ソートタブ上色 = new SolidColorBrush( d2ddc, new Color4( 0xFF121212 ) ) ) using( var ソートタブ下色 = new SolidColorBrush( d2ddc, new Color4( 0xFF1f1f1f ) ) ) { // 曲リストソートタブ d2ddc.FillRectangle( new RectangleF( 927f, 50f, 993f, 138f ), ソートタブ上色 ); d2ddc.FillRectangle( new RectangleF( 927f, 142f, 993f, 46f ), ソートタブ下色 ); } using( var 黒 = new SolidColorBrush( d2ddc, Color4.Black ) ) using( var 白 = new SolidColorBrush( d2ddc, Color4.White ) ) using( var 黒透過 = new SolidColorBrush( d2ddc, new Color4( Color3.Black, 0.5f ) ) ) using( var 灰透過 = new SolidColorBrush( d2ddc, new Color4( 0x80535353 ) ) ) { // インフォメーションバー d2ddc.FillRectangle( new RectangleF( 0f, 0f, 1920f, 50f ), 黒 ); d2ddc.DrawLine( new Vector2( 0f, 50f ), new Vector2( 1920f, 50f ), 白, strokeWidth: 1f ); // ボトムバー d2ddc.FillRectangle( new RectangleF( 0f, 1080f - 43f, 1920f, 1080f ), 黒 ); // プレビュー領域 d2ddc.FillRectangle( new RectangleF( 0f, 52f, 927f, 476f ), 黒透過 ); d2ddc.DrawRectangle( new RectangleF( 0f, 52f, 927f, 476f ), 灰透過, strokeWidth: 1f ); d2ddc.DrawLine( new Vector2( 1f, 442f ), new Vector2( 925f, 442f ), 灰透過, strokeWidth: 1f ); } d2ddc.PrimitiveBlend = preBlend; } private void _背景画面を描画する( DeviceContext d2ddc ) { var 曲ツリー = Global.App.曲ツリーリスト.SelectedItem!; if( 1 >= 曲ツリー.フォーカスリスト.Count ) // どのリストにも、最低減ランダムセレクトノードがある。 { // (A) ノードがない場合 → SongNotFound 画面 this._舞台画像.進行描画する( d2ddc ); this._表示方法選択パネル.進行描画する( d2ddc ); this._ステージタイマー.描画する( d2ddc, 1689f, 37f ); this._SongNotFound.描画する( d2ddc, 1150f, 400f ); } else { // (B) ノードがある場合 → 通常の画面 this._舞台画像.進行描画する( d2ddc ); this._選曲リスト.進行描画する( d2ddc ); this._その他パネルを描画する( d2ddc ); this._表示方法選択パネル.進行描画する( d2ddc ); this._難易度と成績.進行描画する( d2ddc, 曲ツリー.フォーカス難易度レベル, 曲ツリー.フォーカスノード! ); this._曲ステータスパネル.進行描画する( d2ddc, 曲ツリー.フォーカスノード! ); this._プレビュー画像を描画する( d2ddc, 曲ツリー.フォーカスノード! ); this._BPMパネル.進行描画する( d2ddc, 曲ツリー.フォーカスノード! ); this._曲別スキルと達成率.進行描画する( d2ddc, 曲ツリー.フォーカスノード! ); this._選択曲を囲む枠を描画する( d2ddc ); this._選択曲枠ランナー.進行描画する( d2ddc ); this._導線を描画する( d2ddc ); this._ステージタイマー.描画する( d2ddc, 1689f, 37f ); this._スクロールバーを描画する( d2ddc, 曲ツリー.フォーカスリスト ); this._UpdatingSoglistパネル.進行描画する( d2ddc, 40f, 740f ); } } private void _選択曲を囲む枠を描画する( DeviceContext d2ddc ) { var 矩形 = new RectangleF( 1015f, 485f, 905f, 113f ); this._青い線.描画する( d2ddc, new Vector2( 矩形.Left - _青枠のマージンdpx, 矩形.Top ), 幅dpx: 矩形.Width + _青枠のマージンdpx * 2f ); this._青い線.描画する( d2ddc, new Vector2( 矩形.Left - _青枠のマージンdpx, 矩形.Bottom ), 幅dpx: 矩形.Width + _青枠のマージンdpx * 2f ); this._青い線.描画する( d2ddc, new Vector2( 矩形.Left, 矩形.Top - _青枠のマージンdpx ), 高さdpx: 矩形.Height + _青枠のマージンdpx * 2f ); } private void _スクロールバーを描画する( DeviceContext d2ddc, SelectableList<Node> フォーカスリスト ) { int 曲数 = フォーカスリスト.Count; if( 2 > 曲数 ) return; // 1曲しかないなら表示しない。 var 全矩形 = new RectangleF( 1901f, 231f, 9f, 732f ); // 枠線含まず using var スクロールバー背景色 = new SolidColorBrush( d2ddc, new Color4( 0.2f, 0.2f, 0.2f, 1.0f ) ); using var スクロールバー枠色 = new SolidColorBrush( d2ddc, Color4.Black ); using var スクロールバーつまみ色 = new SolidColorBrush( d2ddc, Color4.White ); d2ddc.DrawRectangle( 全矩形, スクロールバー枠色, 4f ); d2ddc.FillRectangle( 全矩形, スクロールバー背景色 ); float 曲の高さ = 全矩形.Height / 曲数; var つまみ矩形 = new RectangleF( 全矩形.Left, 全矩形.Top + 曲の高さ * フォーカスリスト.SelectedIndex, 全矩形.Width, Math.Max( 2f, 曲の高さ ) ); // つまみは最小 2dpx 厚 d2ddc.FillRectangle( つまみ矩形, スクロールバーつまみ色 ); } // プレビュー画像 private readonly 画像D2D _既定のノード画像; private readonly 画像D2D _現行化前のノード画像; private readonly Vector3 _プレビュー画像表示位置dpx = new Vector3( 471f, 61f, 0f ); private readonly Vector3 _プレビュー画像表示サイズdpx = new Vector3( 444f, 444f, 0f ); private void _プレビュー画像を描画する( DeviceContext d2ddc, Node フォーカスノード ) { 画像D2D image = ( !フォーカスノード.現行化済み ) ? this._現行化前のノード画像 : ( フォーカスノード.ノード画像 is null ) ? this._既定のノード画像 : フォーカスノード.ノード画像; var 変換行列2D = Matrix3x2.Scaling( this._プレビュー画像表示サイズdpx.X / image.サイズ.Width, this._プレビュー画像表示サイズdpx.Y / image.サイズ.Height ) * Matrix3x2.Translation( this._プレビュー画像表示位置dpx.X, this._プレビュー画像表示位置dpx.Y ); image.描画する( d2ddc, 変換行列2D ); } // 導線 private Variable _上に伸びる導線の長さdpx = null!; private Variable _左に伸びる導線の長さdpx = null!; private Variable _プレビュー枠の長さdpx = null!; private Storyboard _導線のストーリーボード = null!; private const float _青枠のマージンdpx = 8f; private void _導線アニメをリセットする() { this._選択曲枠ランナー.リセットする(); this._上に伸びる導線の長さdpx?.Dispose(); this._上に伸びる導線の長さdpx = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this._左に伸びる導線の長さdpx?.Dispose(); this._左に伸びる導線の長さdpx = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this._プレビュー枠の長さdpx?.Dispose(); this._プレビュー枠の長さdpx = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this._導線のストーリーボード?.Dispose(); this._導線のストーリーボード = new Storyboard( Global.Animation.Manager ); double 期間 = 0.3; using( var 上に伸びる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 左に伸びる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 枠が広がる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) { this._導線のストーリーボード.AddTransition( this._上に伸びる導線の長さdpx, 上に伸びる ); this._導線のストーリーボード.AddTransition( this._左に伸びる導線の長さdpx, 左に伸びる ); this._導線のストーリーボード.AddTransition( this._プレビュー枠の長さdpx, 枠が広がる ); } 期間 = 0.07; using( var 上に伸びる = Global.Animation.TrasitionLibrary.Linear( 期間, finalValue: 209.0 ) ) using( var 左に伸びる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 枠が広がる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) { this._導線のストーリーボード.AddTransition( this._上に伸びる導線の長さdpx, 上に伸びる ); this._導線のストーリーボード.AddTransition( this._左に伸びる導線の長さdpx, 左に伸びる ); this._導線のストーリーボード.AddTransition( this._プレビュー枠の長さdpx, 枠が広がる ); } 期間 = 0.06; using( var 上に伸びる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 左に伸びる = Global.Animation.TrasitionLibrary.Linear( 期間, finalValue: 129.0 ) ) using( var 枠が広がる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) { this._導線のストーリーボード.AddTransition( this._上に伸びる導線の長さdpx, 上に伸びる ); this._導線のストーリーボード.AddTransition( this._左に伸びる導線の長さdpx, 左に伸びる ); this._導線のストーリーボード.AddTransition( this._プレビュー枠の長さdpx, 枠が広がる ); } 期間 = 0.07; using( var 維持 = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 上に伸びる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 左に伸びる = Global.Animation.TrasitionLibrary.Constant( 期間 ) ) using( var 枠が広がる = Global.Animation.TrasitionLibrary.Linear( 期間, finalValue: 444.0 + _青枠のマージンdpx * 2f ) ) { this._導線のストーリーボード.AddTransition( this._上に伸びる導線の長さdpx, 上に伸びる ); this._導線のストーリーボード.AddTransition( this._左に伸びる導線の長さdpx, 左に伸びる ); this._導線のストーリーボード.AddTransition( this._プレビュー枠の長さdpx, 枠が広がる ); } this._導線のストーリーボード.Schedule( Global.Animation.Timer.Time ); } private void _導線を描画する( DeviceContext d2ddc ) { var h = (float)this._上に伸びる導線の長さdpx.Value; this._青い線.描画する( d2ddc, new Vector2( 1044f, 485f - h ), 高さdpx: h ); var w = (float)this._左に伸びる導線の長さdpx.Value; this._青い線.描画する( d2ddc, new Vector2( 1046f - w, 278f ), 幅dpx: w ); var z = (float)this._プレビュー枠の長さdpx.Value; // マージン×2 込み var 上 = this._プレビュー画像表示位置dpx.Y; var 下 = this._プレビュー画像表示位置dpx.Y + this._プレビュー画像表示サイズdpx.Y; var 左 = this._プレビュー画像表示位置dpx.X; var 右 = this._プレビュー画像表示位置dpx.X + this._プレビュー画像表示サイズdpx.X; this._青い線.描画する( d2ddc, new Vector2( 右 + _青枠のマージンdpx - z, 上 ), 幅dpx: z ); // 上辺 this._青い線.描画する( d2ddc, new Vector2( 右 + _青枠のマージンdpx - z, 下 ), 幅dpx: z ); // 下辺 this._青い線.描画する( d2ddc, new Vector2( 左, 下 + _青枠のマージンdpx - z ), 高さdpx: z ); // 左辺 this._青い線.描画する( d2ddc, new Vector2( 右, 下 + _青枠のマージンdpx - z ), 高さdpx: z ); // 右辺 } } } <|start_filename|>FDK/イメージ/画像D2D.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpDX; using SharpDX.Direct2D1; using SharpDX.IO; using SharpDX.WIC; namespace FDK { /// <summary> /// D2Dビットマップを使った画像表示。 /// </summary> public class 画像D2D : IImage, IDisposable { // プロパティ public Bitmap1? Bitmap { get; protected set; } = null; // 生成に失敗した場合は null。 public bool 加算合成する { get; set; } = false; public Size2F サイズ { get; protected set; } // 生成と終了 public 画像D2D( ImagingFactory2 imagingFactory2, DeviceContext d2dDeviceContext, VariablePath 画像ファイルパス, BitmapProperties1? bitmapProperties1 = null ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); this.Bitmapを生成する( imagingFactory2, d2dDeviceContext, 画像ファイルパス, bitmapProperties1 ); } protected 画像D2D() { } public virtual void Dispose() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this.Bitmap?.Dispose(); this.Bitmap = null; } protected void Bitmapを生成する( ImagingFactory2 imagingFactory2, DeviceContext d2dDeviceContext, VariablePath 画像ファイルパス, BitmapProperties1? bitmapProperties1 = null ) { var decoder = (BitmapDecoder?)null; var sourceFrame = (BitmapFrameDecode?)null; var converter = (FormatConverter?)null; try { // 以下、生成に失敗しても例外は発生しない。ただ描画メソッドで表示されなくなるだけ。 #region " 事前チェック。" //----------------- if( string.IsNullOrEmpty( 画像ファイルパス.変数なしパス ) ) { Log.ERROR( $"画像ファイルパスが null または空文字列です。[{画像ファイルパス.変数付きパス}]" ); return; } if( !File.Exists( 画像ファイルパス.変数なしパス ) ) { Log.ERROR( $"画像ファイルが存在しません。[{画像ファイルパス.変数付きパス}]" ); return; } //----------------- #endregion #region " 画像ファイルに対応できるデコーダを見つける。" //----------------- try { decoder = new BitmapDecoder( imagingFactory2, 画像ファイルパス.変数なしパス, NativeFileAccess.Read, DecodeOptions.CacheOnLoad ); } catch( SharpDXException e ) { Log.ERROR( $"画像ファイルに対応するコーデックが見つかりません。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]" ); return; } //----------------- #endregion #region " 最初のフレームをデコードし、取得する。" //----------------- try { sourceFrame = decoder.GetFrame( 0 ); } catch( SharpDXException e ) { Log.ERROR( $"画像ファイルの最初のフレームのデコードに失敗しました。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]" ); return; } //----------------- #endregion #region " 32bitPBGRA へのフォーマットコンバータを生成する。" //----------------- try { // WICイメージングファクトリから新しいコンバータを生成。 converter = new FormatConverter( imagingFactory2 ); // コンバータに変換元フレームや変換後フォーマットなどを設定。 converter.Initialize( sourceRef: sourceFrame, dstFormat: SharpDX.WIC.PixelFormat.Format32bppPBGRA, // Premultiplied BGRA dither: BitmapDitherType.None, paletteRef: null, alphaThresholdPercent: 0.0, paletteTranslate: BitmapPaletteType.MedianCut ); } catch( SharpDXException e ) { Log.ERROR( $"32bitPBGRA へのフォーマットコンバータの生成または初期化に失敗しました。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]" ); return; } //----------------- #endregion #region " コンバータを使って、フレームを WICビットマップ経由で D2D ビットマップに変換する。" //----------------- try { // WIC ビットマップを D2D ビットマップに変換する。 this.Bitmap?.Dispose(); this.Bitmap = bitmapProperties1 switch { null => Bitmap1.FromWicBitmap( d2dDeviceContext, converter ), _ => Bitmap1.FromWicBitmap( d2dDeviceContext, converter, bitmapProperties1 ), }; } catch( SharpDXException e ) { Log.ERROR( $"Direct2D1.Bitmap1 への変換に失敗しました。(0x{e.HResult:x8})[{画像ファイルパス.変数付きパス}]" ); return; } //----------------- #endregion this.サイズ = new Size2F( this.Bitmap.PixelSize.Width, this.Bitmap.PixelSize.Height ); } finally { converter?.Dispose(); sourceFrame?.Dispose(); decoder?.Dispose(); } } // 進行と描画 /// <summary> /// 画像を描画する。 /// </summary> /// <param name="d2ddc">描画に使うデバイスコンテキスト。</param> /// <param name="左位置">画像の描画先範囲の左上隅X座標。</param> /// <param name="上位置">画像の描画先範囲の左上隅Y座標。</param> /// <param name="不透明度0to1">不透明度。(0:透明~1:不透明)</param> /// <param name="X方向拡大率">画像の横方向の拡大率。</param> /// <param name="Y方向拡大率">画像の縦方向の拡大率。</param> /// <param name="転送元矩形">画像の転送元範囲。</param> /// <param name="描画先矩形を整数境界に合わせる">true なら、描画先の転送先矩形の座標を float から int に丸める。</param> /// <param name="変換行列3D">射影行列。</param> /// <param name="レイヤーパラメータ>レイヤーを使う場合は指定する。</param> /// <remarks> /// Direct2D の転送先矩形は float で指定できるが、非整数の値(=物理ピクセル単位じゃない座標)を渡すと、表示画像がプラスマイナス1pxの範囲で乱れる。 /// これにより、数px程度の大きさの画像を移動させるとチカチカする原因になる。 /// それが困る場合には、「描画先矩形を整数境界に合わせる」に true を指定すること。 /// ただし、これを true にした場合、タイルのように並べて描画した場合に1pxずれる場合がある。この場合は false にすること。 /// </remarks> public virtual void 描画する( DeviceContext d2ddc, float 左位置, float 上位置, float 不透明度0to1 = 1.0f, float X方向拡大率 = 1.0f, float Y方向拡大率 = 1.0f, RectangleF? 転送元矩形 = null, bool 描画先矩形を整数境界に合わせる = false, Matrix? 変換行列3D = null, LayerParameters1? レイヤーパラメータ = null ) { if( this.Bitmap is null ) return; var preBlend = d2ddc.PrimitiveBlend; d2ddc.PrimitiveBlend = ( this.加算合成する ) ? PrimitiveBlend.Add : PrimitiveBlend.SourceOver; // 転送元・転送先矩形を算出する。 転送元矩形 ??= new RectangleF( 0f, 0f, this.サイズ.Width, this.サイズ.Height ); var 転送先矩形 = new RectangleF( x: 左位置, y: 上位置, width: 転送元矩形.Value.Width * X方向拡大率, height: 転送元矩形.Value.Height * Y方向拡大率 ); if( 描画先矩形を整数境界に合わせる ) { 転送先矩形.X = (float)Math.Round( 転送先矩形.X ); 転送先矩形.Y = (float)Math.Round( 転送先矩形.Y ); 転送先矩形.Width = (float)Math.Round( 転送先矩形.Width ); 転送先矩形.Height = (float)Math.Round( 転送先矩形.Height ); } // レイヤーパラメータの指定があれば、描画前に Layer を作成して、Push する。 var layer = (Layer?)null; if( レイヤーパラメータ.HasValue ) { layer = new Layer( d2ddc ); // 因果関係は分からないが、同じBOX内の曲が増えるとこの行の負荷が増大するので、必要時にしか生成しないこと。 d2ddc.PushLayer( レイヤーパラメータ.Value, layer ); } // D2Dレンダーターゲットに Bitmap を描画する。 d2ddc.DrawBitmap( bitmap: this.Bitmap, destinationRectangle: 転送先矩形, opacity: 不透明度0to1, interpolationMode: InterpolationMode.Linear, sourceRectangle: 転送元矩形, erspectiveTransformRef: 変換行列3D ); // null 指定可。 // レイヤーパラメータの指定があれば、描画後に Pop する。 if( null != layer ) { d2ddc.PopLayer(); layer.Dispose(); } d2ddc.PrimitiveBlend = preBlend; } /// <summary> /// 画像を描画する。 /// </summary> /// <param name="変換行列2D">Transform に適用する行列。</param> /// <param name="変換行列3D">射影行列。</param> /// <param name="不透明度0to1">不透明度。(0:透明~1:不透明)</param> /// <param name="転送元矩形">描画する画像範囲。</param> public virtual void 描画する( DeviceContext d2ddc, Matrix3x2? 変換行列2D = null, Matrix? 変換行列3D = null, float 不透明度0to1 = 1.0f, RectangleF? 転送元矩形 = null, LayerParameters1? レイヤーパラメータ = null ) { if( this.Bitmap is null ) return; // 画像の生成に失敗していたら何も描画しない。 var preBlend = d2ddc.PrimitiveBlend; var preTrans = d2ddc.Transform; d2ddc.PrimitiveBlend = ( this.加算合成する ) ? PrimitiveBlend.Add : PrimitiveBlend.SourceOver; d2ddc.Transform = ( 変換行列2D ?? Matrix3x2.Identity ) * preTrans; // レイヤーパラメータの指定があれば、描画前に Layer を作成して、Push する。 var layer = (Layer?)null; if( レイヤーパラメータ.HasValue ) { layer = new Layer( d2ddc ); // 因果関係は分からないが、同じBOX内の曲が増えるとこの行の負荷が増大するので、必要時にしか生成しないこと。 d2ddc.PushLayer( (LayerParameters1)レイヤーパラメータ, layer ); } // D2Dレンダーターゲットに this.Bitmap を描画する。 d2ddc.DrawBitmap( bitmap: this.Bitmap, destinationRectangle: null, opacity: 不透明度0to1, interpolationMode: InterpolationMode.Linear, sourceRectangle: 転送元矩形, erspectiveTransformRef: 変換行列3D ); // null 指定可。 // layer を作成したなら、描画後に Pop する。 if( null != layer ) { d2ddc.PopLayer(); layer.Dispose(); } d2ddc.PrimitiveBlend = preBlend; d2ddc.Transform = preTrans; } } } <|start_filename|>SSTFEditor/クリップボード.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace SSTFEditor { class クリップボード { public int アイテム数 => this.アイテムリスト.Count; public クリップボード( メインフォーム form ) { this.Form = form; } public void 現在選択されているチップをボードにコピーする() { this.アイテムリスト.Clear(); foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { if( chip.選択が確定している ) { this.アイテムリスト.Add( new アイテム() { チップ = new 描画用チップ( chip ) } ); } } } public void チップを指定位置から貼り付ける( int 貼り付け先頭の譜面内絶対位置grid ) { if( 0 == this.アイテム数 ) return; try { this.Form.UndoRedo管理.トランザクション記録を開始する(); // すべてのセルについて、チップ位置を、ボード内でもっとも位置が前にあるセルを 0grid とした相対値に変換する。 int 最小値grid = this.アイテムリスト[ 0 ].チップ.譜面内絶対位置grid; foreach( var cell in this.アイテムリスト ) { if( cell.チップ.譜面内絶対位置grid < 最小値grid ) 最小値grid = cell.チップ.譜面内絶対位置grid; } foreach( var cell in this.アイテムリスト ) cell.チップ.譜面内絶対位置grid -= 最小値grid; // すべてのセルについて、チップ位置を、実際に貼り付ける位置に変換する。 foreach( var cell in this.アイテムリスト ) cell.チップ.譜面内絶対位置grid += 貼り付け先頭の譜面内絶対位置grid; // チップを譜面に貼り付ける。 foreach( var cell in this.アイテムリスト ) { this.Form.譜面.チップを配置または置換する( this.Form.譜面.チップ種別to編集レーン[ cell.チップ.チップ種別 ], cell.チップ.チップ種別, cell.チップ.譜面内絶対位置grid, cell.チップ.チップ内文字列, cell.チップ.音量, cell.チップ.BPM, 選択確定中: true ); } } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.Form.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.Form.譜面をリフレッシュする(); this.Form.未保存である = true; } } protected class アイテム { public bool 貼り付け済み = false; public int グループID = 0; public 描画用チップ チップ = null; } protected メインフォーム Form; protected readonly List<アイテム> アイテムリスト = new List<アイテム>(); } } <|start_filename|>DTXMania2/Properties/Resources.Designer.cs<|end_filename|> //------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace DTXMania2.Properties { using System; /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスが ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 /// </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("DTXMania2.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// (アイコン) に類似した型 System.Drawing.Icon のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Icon DTXMania2 { get { object obj = ResourceManager.GetObject("DTXMania2", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Failed to log on as AutoPlayer. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_AutoPlayerでのログオンに失敗しました { get { return ResourceManager.GetString("TXT_AutoPlayerでのログオンに失敗しました", resourceCulture); } } /// <summary> /// China position に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_Chinaの表示位置 { get { return ResourceManager.GetString("TXT_Chinaの表示位置", resourceCulture); } } /// <summary> /// Now accepting inputs for the HID Keyboard. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_HIDKeyboardの受付を開始しました { get { return ResourceManager.GetString("TXT_HIDKeyboardの受付を開始しました", resourceCulture); } } /// <summary> /// MIDI IN [{0}] &apos;{1}&apos; started. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_MidiInの受付を開始しました { get { return ResourceManager.GetString("TXT_MidiInの受付を開始しました", resourceCulture); } } /// <summary> /// Disable に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_OFF { get { return ResourceManager.GetString("TXT_OFF", resourceCulture); } } /// <summary> /// Enable に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ON { get { return ResourceManager.GetString("TXT_ON", resourceCulture); } } /// <summary> /// Ride position に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_Rideの表示位置 { get { return ResourceManager.GetString("TXT_Rideの表示位置", resourceCulture); } } /// <summary> /// Splash position に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_Splashの表示位置 { get { return ResourceManager.GetString("TXT_Splashの表示位置", resourceCulture); } } /// <summary> /// Window に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ウィンドウ { get { return ResourceManager.GetString("TXT_ウィンドウ", resourceCulture); } } /// <summary> /// Options に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_オプション設定へ { get { return ResourceManager.GetString("TXT_オプション設定へ", resourceCulture); } } /// <summary> /// Enter a keyboard or MIDI signal. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_キーボードまたはMIDI信号を入力してください { get { return ResourceManager.GetString("TXT_キーボードまたはMIDI信号を入力してください", resourceCulture); } } /// <summary> /// Rating this song に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_この曲の評価 { get { return ResourceManager.GetString("TXT_この曲の評価", resourceCulture); } } /// <summary> /// Control Change に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_コントロールチェンジ { get { return ResourceManager.GetString("TXT_コントロールチェンジ", resourceCulture); } } /// <summary> /// Free cymbal に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_シンバルフリー { get { return ResourceManager.GetString("TXT_シンバルフリー", resourceCulture); } } /// <summary> /// Toggle all に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_すべてONOFF { get { return ResourceManager.GetString("TXT_すべてONOFF", resourceCulture); } } /// <summary> /// Dark mode に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ダークモード { get { return ResourceManager.GetString("TXT_ダークモード", resourceCulture); } } /// <summary> /// Full に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ダークモード_FULL { get { return ResourceManager.GetString("TXT_ダークモード_FULL", resourceCulture); } } /// <summary> /// Half に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ダークモード_HALF { get { return ResourceManager.GetString("TXT_ダークモード_HALF", resourceCulture); } } /// <summary> /// * The timing clock signal and the active signal are ignored. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_タイミングクロック信号_アクティブ信号は無視します { get { return ResourceManager.GetString("TXT_タイミングクロック信号_アクティブ信号は無視します", resourceCulture); } } /// <summary> /// Drums sound に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ドラムサウンド { get { return ResourceManager.GetString("TXT_ドラムサウンド", resourceCulture); } } /// <summary> /// Note Off に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ノートオフ { get { return ResourceManager.GetString("TXT_ノートオフ", resourceCulture); } } /// <summary> /// Note On に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ノートオン { get { return ResourceManager.GetString("TXT_ノートオン", resourceCulture); } } /// <summary> /// Hit any cymbal or Enter key に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_パッドを叩いてください { get { return ResourceManager.GetString("TXT_パッドを叩いてください", resourceCulture); } } /// <summary> /// Select a player. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_プレイヤーを選択してください { get { return ResourceManager.GetString("TXT_プレイヤーを選択してください", resourceCulture); } } /// <summary> /// Initialize user DB に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ユーザDBを初期化 { get { return ResourceManager.GetString("TXT_ユーザDBを初期化", resourceCulture); } } /// <summary> /// Select a song ///near {0} に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_ランダムに選択 { get { return ResourceManager.GetString("TXT_ランダムに選択", resourceCulture); } } /// <summary> /// Lane opacity に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_レーンの透明度 { get { return ResourceManager.GetString("TXT_レーンの透明度", resourceCulture); } } /// <summary> /// It is not possible to run more than one at a time. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_二重起動はできません { get { return ResourceManager.GetString("TXT_二重起動はできません", resourceCulture); } } /// <summary> /// * If there is more than 500 milliseconds between inputs, a blank line will be displayed between them. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_入力と入力の間が500ミリ秒以上開いた場合は間に空行を表示します { get { return ResourceManager.GetString("TXT_入力と入力の間が500ミリ秒以上開いた場合は間に空行を表示します", resourceCulture); } } /// <summary> /// Input assignment に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_入力割り当て { get { return ResourceManager.GetString("TXT_入力割り当て", resourceCulture); } } /// <summary> /// Fullscreen に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_全画面 { get { return ResourceManager.GetString("TXT_全画面", resourceCulture); } } /// <summary> /// Initialize に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_初期化 { get { return ResourceManager.GetString("TXT_初期化", resourceCulture); } } /// <summary> /// Show fast/slow に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_判定FASTSLOWの表示 { get { return ResourceManager.GetString("TXT_判定FASTSLOWの表示", resourceCulture); } } /// <summary> /// Judge position adjust に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_判定位置調整 { get { return ResourceManager.GetString("TXT_判定位置調整", resourceCulture); } } /// <summary> /// Right に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_右 { get { return ResourceManager.GetString("TXT_右", resourceCulture); } } /// <summary> /// Discard the changes? に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_変更を破棄していいですか { get { return ResourceManager.GetString("TXT_変更を破棄していいですか", resourceCulture); } } /// <summary> /// Show bar number に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_小節番号の表示 { get { return ResourceManager.GetString("TXT_小節番号の表示", resourceCulture); } } /// <summary> /// Show bar/beat lines に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_小節線と拍線の表示 { get { return ResourceManager.GetString("TXT_小節線と拍線の表示", resourceCulture); } } /// <summary> /// Left に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_左 { get { return ResourceManager.GetString("TXT_左", resourceCulture); } } /// <summary> /// Initialize record DB に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_成績DBを初期化 { get { return ResourceManager.GetString("TXT_成績DBを初期化", resourceCulture); } } /// <summary> /// Back に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_戻る { get { return ResourceManager.GetString("TXT_戻る", resourceCulture); } } /// <summary> /// Initialize song DB に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_曲DBを初期化 { get { return ResourceManager.GetString("TXT_曲DBを初期化", resourceCulture); } } /// <summary> /// Song not found... ///Hit BDx2 (in default SPACEx2) to select song folders. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_曲が見つかりません { get { return ResourceManager.GetString("TXT_曲が見つかりません", resourceCulture); } } /// <summary> /// Song folders に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_曲読み込みフォルダ { get { return ResourceManager.GetString("TXT_曲読み込みフォルダ", resourceCulture); } } /// <summary> /// Song speed に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_演奏スピード { get { return ResourceManager.GetString("TXT_演奏スピード", resourceCulture); } } /// <summary> /// Movie size に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_演奏中の動画サイズ { get { return ResourceManager.GetString("TXT_演奏中の動画サイズ", resourceCulture); } } /// <summary> /// Shrink to center に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_演奏中の動画サイズ_中央寄せ { get { return ResourceManager.GetString("TXT_演奏中の動画サイズ_中央寄せ", resourceCulture); } } /// <summary> /// Fullscreen に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_演奏中の動画サイズ_全画面 { get { return ResourceManager.GetString("TXT_演奏中の動画サイズ_全画面", resourceCulture); } } /// <summary> /// Show movie に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_演奏中の動画表示 { get { return ResourceManager.GetString("TXT_演奏中の動画表示", resourceCulture); } } /// <summary> /// Show wallpaper に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_演奏中の壁紙表示 { get { return ResourceManager.GetString("TXT_演奏中の壁紙表示", resourceCulture); } } /// <summary> /// Current assign to に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_現在の割り当て { get { return ResourceManager.GetString("TXT_現在の割り当て", resourceCulture); } } /// <summary> /// Screen mode に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_画面モード { get { return ResourceManager.GetString("TXT_画面モード", resourceCulture); } } /// <summary> /// Confirmation に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_確認 { get { return ResourceManager.GetString("TXT_確認", resourceCulture); } } /// <summary> /// Auto play に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_自動演奏 { get { return ResourceManager.GetString("TXT_自動演奏", resourceCulture); } } /// <summary> /// Initialize settings に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_設定を初期化 { get { return ResourceManager.GetString("TXT_設定を初期化", resourceCulture); } } /// <summary> /// Exit に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_設定完了 { get { return ResourceManager.GetString("TXT_設定完了", resourceCulture); } } /// <summary> /// Back に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_設定完了_戻る { get { return ResourceManager.GetString("TXT_設定完了_戻る", resourceCulture); } } /// <summary> /// Rating に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価 { get { return ResourceManager.GetString("TXT_評価", resourceCulture); } } /// <summary> /// ❤ に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価1 { get { return ResourceManager.GetString("TXT_評価1", resourceCulture); } } /// <summary> /// ❤❤ に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価2 { get { return ResourceManager.GetString("TXT_評価2", resourceCulture); } } /// <summary> /// ❤❤❤ に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価3 { get { return ResourceManager.GetString("TXT_評価3", resourceCulture); } } /// <summary> /// ❤❤❤❤ に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価4 { get { return ResourceManager.GetString("TXT_評価4", resourceCulture); } } /// <summary> /// ❤❤❤❤❤ に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価5 { get { return ResourceManager.GetString("TXT_評価5", resourceCulture); } } /// <summary> /// No rating に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価なし { get { return ResourceManager.GetString("TXT_評価なし", resourceCulture); } } /// <summary> /// Segoe UI emoji に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_評価記号用フォント { get { return ResourceManager.GetString("TXT_評価記号用フォント", resourceCulture); } } /// <summary> /// Scroll speed に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_譜面スピード { get { return ResourceManager.GetString("TXT_譜面スピード", resourceCulture); } } /// <summary> /// Size follows volume に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string TXT_音量によるサイズ変化 { get { return ResourceManager.GetString("TXT_音量によるサイズ変化", resourceCulture); } } } } <|start_filename|>FDK/QPCTimer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { /// <summary> /// パフォーマンスカウンタを使用した高精度タイマ。 /// </summary> /// <remarks> /// 以下の2種類の使い方を想定する。 /// (A) 正確に同一の時刻を複数の処理で共有できるように、現在時刻をキャプチャしてから取得する方法。 /// 1. 最初に「現在のカウントをキャプチャする()」を呼び出し、その時点での時刻を内部に保存する。 /// 2. キャプチャされたカウントを、「現在のキャプチャカウントを……取得する()」を呼び出して、希望する単位で取得する。 /// (次に1.を行うまで、2.はずっと同じ時刻を返し続ける。) /// (B) 常に現時刻(メソッド呼び出し時点の時刻)を取得する方法。 /// a. 「現在のリアルタイムカウントを……取得する()」を呼び出して、希望する単位で取得する。 /// または、 /// b. 「生カウントを取得する()」を呼び出して、生カウンタを取得する。 /// /// 時刻の単位としては、[カウント], [秒], [100ナノ秒] を用意する。 /// /// 用語: /// "カウント" …………………… タイマインスタンスの生成時(または前回のリセット時)から「前回キャプチャされた時点」までの、パフォーマンスカウンタの差分(相対値)。 /// "リアルタイムカウント" …… タイマインスタンスの生成時(または前回のリセット時)から「現時点」までの、パフォーマンスカウンタの差分(相対値)。 /// "生カウント" ………………… パフォーマンスカウンタの生の値。::QueryPerformanceCounter() で取得できる値に等しい。システム依存の絶対値。 /// </remarks> public class QPCTimer { /// <summary> /// カウントが無効であることを示す定数。 /// </summary> public const long 未使用 = -1; public static long 周波数 => Stopwatch.Frequency; public static long 生カウント => Stopwatch.GetTimestamp(); public static double 生カウント相対値を秒へ変換して返す( long 生カウント相対値 ) => (double)生カウント相対値 / QPCTimer.周波数; public static long 秒をカウントに変換して返す( double 秒 ) => (long)( 秒 * QPCTimer.周波数 ); public long 現在のキャプチャカウント { get { lock( this._スレッド間同期 ) { if( 0 != this._一時停止回数 ) { // 停止中。 return ( this._稼働中に一時停止した時点のキャプチャカウント - this._前回リセットした時点の生カウント ); } else { // 稼働中。 return ( this._最後にキャプチャされたカウント - this._前回リセットした時点の生カウント ); } } } } public long 現在のキャプチャカウント100ns => (long)( this.現在のキャプチャカウントsec * 10_000_000 + 0.5 ); public double 現在のキャプチャカウントsec => (double)this.現在のキャプチャカウント / QPCTimer.周波数; public long 現在のリアルタイムカウント { get { lock( this._スレッド間同期 ) { if( 0 != this._一時停止回数 ) { // 停止中。 return ( this._稼働中に一時停止した時点のキャプチャカウント - this._前回リセットした時点の生カウント ); } else { // 稼働中。 return ( QPCTimer.生カウント - this._前回リセットした時点の生カウント ); } } } } public long 現在のリアルタイムカウント100ns => (long)( this.現在のリアルタイムカウントsec * 10_000_000 + 0.5 ); public double 現在のリアルタイムカウントsec => (double)this.現在のリアルタイムカウント / QPCTimer.周波数; public long 前回リセットした時点の生カウント { get { lock( this._スレッド間同期 ) { return this._前回リセットした時点の生カウント; } } } public bool 停止中である { get { lock( this._スレッド間同期 ) { return ( 0 != this._一時停止回数 ); } } } public bool 稼働中である => !( this.停止中である ); public QPCTimer() { var 現在の生カウント = QPCTimer.生カウント; this._前回リセットした時点の生カウント = 現在の生カウント; this._最後にキャプチャされたカウント = 現在の生カウント; this._稼働中に一時停止した時点のキャプチャカウント = 現在の生カウント; this._一時停止回数 = 0; } public long 現在のカウントをキャプチャする() { lock( this._スレッド間同期 ) { this._最後にキャプチャされたカウント = QPCTimer.生カウント; return this._最後にキャプチャされたカウント; } } public void リセットする( long 新しいカウント = 0 ) { lock( this._スレッド間同期 ) { this._前回リセットした時点の生カウント = QPCTimer.生カウント - 新しいカウント; } } public void 一時停止する() { lock( this._スレッド間同期 ) { if( this.稼働中である ) { this._稼働中に一時停止した時点のキャプチャカウント = QPCTimer.生カウント; } this._一時停止回数++; } } public void 再開する() { lock( this._スレッド間同期 ) { if( this.停止中である ) { this._一時停止回数--; if( 0 >= this._一時停止回数 ) { this._最後にキャプチャされたカウント = QPCTimer.生カウント; this._前回リセットした時点の生カウント += this._最後にキャプチャされたカウント - this._稼働中に一時停止した時点のキャプチャカウント; } } } } private long _前回リセットした時点の生カウント = 0; private long _最後にキャプチャされたカウント = 0; private long _稼働中に一時停止した時点のキャプチャカウント = 0; private int _一時停止回数 = 0; private readonly object _スレッド間同期 = new object(); } } <|start_filename|>DTXMania2/ステージ/07演奏/ダーク種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.演奏 { enum ダーク種別 { OFF = 0, HALF = 1, FULL = 2, } } <|start_filename|>DTXMania2/保存データ/成績.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using DTXMania2.演奏; using DTXMania2.結果; using SSTF=SSTFormat.v004; namespace DTXMania2 { /// <summary> /// 成績情報。 /// </summary> /// <remarks> /// <see cref="App.演奏譜面"/> に依存するが、これが null の場合(ビュアーステージ初期状態で利用)でも動作する。 /// </remarks> class 成績 { // プロパティ /// <summary> /// ユーザを一意に識別するID。 /// </summary> public string UserId { get => this._Record.UserId; set => this._Record.UserId = value; } /// <summary> /// スコア。 /// </summary> public int Score { get => this._Record.Score; set => this._Record.Score = value; } /// <summary> /// カウントマップラインのデータ。 /// 1ブロックを1文字('0':0~'C':12)で表し、<see cref="カウントマップライン.カウントマップの最大要素数"/> 個の文字が並ぶ。 /// もし不足分があれば、'0' とみなされる。 /// </summary> public string CountMap { get => this._Record.CountMap; set => this._Record.CountMap = value; } /// <summary> /// 達成率。 /// </summary> public double Achievement { get => this._Record.Achievement; set => this._Record.Achievement = value; } /// <summary> /// 現在のコンボ数。 /// AutoPlayチップを含む。 /// </summary> public int Combo { get; protected set; } = 0; /// <summary> /// 現在までの最大コンボ数。 /// AutoPlayチップを含む。 /// </summary> public int MaxCombo { get; protected set; } = 0; /// <summary> /// エキサイトゲージの割合。空:0~1:最大 /// </summary> public float エキサイトゲージ量 { get; protected set; } /// <summary> /// 現在の設定において、ヒット対象になるノーツの数を返す。 /// AutoPlayチップを含む。 /// </summary> public int 総ノーツ数 { get; protected set; } = 0; /// <summary> /// 最終的に判定されたランク。 /// </summary> public ランク種別 ランク { get; protected set; } = ランク種別.E; /// <summary> /// 現在のスキル値。 /// </summary> public double スキル => 成績.スキルを算出する( this._難易度, this.Achievement ); /// <summary> /// 判定種別ごとのヒット数。 /// AutoPlayチップを含む。 /// </summary> public IReadOnlyDictionary<判定種別, int> 判定別ヒット数 => this._判定別ヒット数; /// <summary> /// 現在の <see cref="判定別ヒット数"/> から、判定種別ごとのヒット割合を算出して返す。 /// 判定種別のヒット割合は、すべて合計すればちょうど 100 になる。 /// ヒット数にはAutoPlayチップを含む。 /// </summary> public IReadOnlyDictionary<判定種別, int> 判定別ヒット割合 => this._ヒット割合を算出して返す(); /// <summary> /// このプロパティが true である場合、成績は無効である。(早戻しを使った等) /// </summary> public bool 無効 { get; set; } = false; // 生成と終了 public 成績() { this._ユーザ設定 = Global.App.ログオン中のユーザ; this._Record = new RecordDBRecord() { ScorePath = Global.App.演奏譜面?.譜面.ScorePath ?? "", UserId = this._ユーザ設定.ID!, Score = 0, Achievement = 0.0f, }; this.MaxCombo = 0; this.エキサイトゲージ量 = 0.75f; this.総ノーツ数 = ( Global.App.演奏スコア != null ) ? this._総ノーツ数を算出して返す( Global.App.演奏スコア, this._ユーザ設定 ) : 0; this._難易度 = Global.App.演奏スコア?.難易度 ?? 5.0; this._判定別ヒット数 = new Dictionary<判定種別, int>(); foreach( 判定種別? judge in Enum.GetValues( typeof( 判定種別 ) ) ) { if( judge.HasValue ) this._判定別ヒット数.Add( judge.Value, 0 ); } } // 更新 /// <summary> /// 判定に応じて成績(エキサイトゲージを除く)を更新する。 /// </summary> public void 成績を更新する( 判定種別 判定 ) { #region " ヒット数を加算する。" //---------------- this._判定別ヒット数[ 判定 ]++; //---------------- #endregion #region " コンボを加算する。" //---------------- if( 判定 == 判定種別.OK || 判定 == 判定種別.MISS ) { this.Combo = 0; // コンボ切れ } else { this.Combo++; this.MaxCombo = Math.Max( this.Combo, this.MaxCombo ); } //---------------- #endregion #region " スコアを加算する。" //---------------- const int 最大スコア = 100_0000; if( this.総ノーツ数 == this._判定別ヒット数[ 判定種別.PERFECT ] ) { // Excellent(最後のチップまですべてPERFECT)の場合、スコアは100万点ジャストに調整する。 this.Score = 最大スコア; } else { // それ以外は通常の加点。 double 基礎点 = ( 50 <= this.総ノーツ数 ) ? ( 100_0000.0 / ( 1275.0 + 50.0 * ( 総ノーツ数 - 50 ) ) ) : 1; // 総ノーツ数 0~50 の曲は常に基礎点 1 int コンボ数 = Math.Min( this.Combo, 50 ); // 最大50 this.Score += (int)Math.Floor( 基礎点 * コンボ数 * this._判定値表[ 判定 ] ); // 早送り/早戻しを使った場合、スコアが最大値を超えることがあるので、それを禁止する。 if( this.Score > 最大スコア ) this.Score = 最大スコア; } //---------------- #endregion double オプション補正0to1 = 1.0; #region " オプション補正を算出する。" //---------------- // AutoPlay を反映。 if( this._ユーザ設定.AutoPlayがすべてONである ) { // (A) AutoPlay がすべて ON → 補正なし(x1.0), ただしDBには保存されない。 オプション補正0to1 = 1.0; this.無効 = true; } else { // (B) AutoPlay が一部だけ ON → ON になっている個所に応じて補正する。 foreach( var kvp in this._ユーザ設定.AutoPlay ) { if( kvp.Value && this._Auto時の補正.ContainsKey( kvp.Key ) ) { オプション補正0to1 *= this._Auto時の補正[ kvp.Key ]; // 補正値は累積 } } } //---------------- #endregion #region " 達成率を更新する。" //---------------- this.Achievement = 達成率を算出する( this.総ノーツ数, // Auto含む this._判定別ヒット数[ 判定種別.PERFECT ], // Auto含む this._判定別ヒット数[ 判定種別.GREAT ], // Auto含む this.MaxCombo, // Auto含む オプション補正0to1 ); //---------------- #endregion #region " ランクを更新する。" //---------------- this.ランク = ランクを算出する( this.Achievement ); //---------------- #endregion } /// <summary> /// 判定に応じてエキサイトゲージを加減する。 /// </summary> public void エキサイトゲージを更新する( 判定種別 judge ) { this.エキサイトゲージ量 += judge switch { 判定種別.PERFECT => 0.025f, 判定種別.GREAT => 0.01f, 判定種別.GOOD => 0.005f, 判定種別.OK => 0f, _ => -0.08f, }; this.エキサイトゲージ量 = Math.Clamp( this.エキサイトゲージ量, min: 0f, max: 1f ); } // 算出(static) /// <summary> /// 達成率(0~99.99)を算出して返す。 /// </summary> /// <param name="総ノーツ数"></param> /// <param name="Perfect数"></param> /// <param name="Great数"></param> /// <param name="最大コンボ数"></param> /// <param name="オプション補正">0~1。</param> public static double 達成率を算出する( int 総ノーツ数, int Perfect数, int Great数, int 最大コンボ数, double オプション補正 ) { double 判定値 = _小数第3位以下切り捨て( ( Perfect数 * 85.0 + Great数 * 35.0 ) / 総ノーツ数 ); double COMBO値 = _小数第3位以下切り捨て( 最大コンボ数 * 15.0 / 総ノーツ数 ); // 判定値とCOMBO値にはAutoチップも含まれるので、すべてAutoPlayONであっても、達成率はゼロにはならない。 // その代わり、オプション補正でガシガシ削る。 double 達成率 = _小数第3位以下切り捨て( ( 判定値 + COMBO値 ) * オプション補正 ); // 早戻し/早送りを使った場合、達成率が 100 を越える場合があるのでそれを禁止。 if( 達成率 > 100.0 ) 達成率 = 100.0; return 達成率; } /// <summary> /// スキル値(0~199.80)を算出して返す。 /// </summary> public static double スキルを算出する( double 譜面レベル, double 達成率0to100 ) { return _小数第3位以下切り捨て( ( 達成率0to100 * 譜面レベル * 20.0 ) / 100.0 ); } /// <summary> /// 達成率(0~99.99)からランクを算出して返す。 /// </summary> public static ランク種別 ランクを算出する( double 達成率0to100 ) { return // 範囲 ( 95 <= 達成率0to100 ) ? ランク種別.SS : // 5 % ( 80 <= 達成率0to100 ) ? ランク種別.S : // 15 % ( 73 <= 達成率0to100 ) ? ランク種別.A : // 7 % ( 63 <= 達成率0to100 ) ? ランク種別.B : // 10 % ( 53 <= 達成率0to100 ) ? ランク種別.C : // 10 % ( 43 <= 達成率0to100 ) ? ランク種別.D : // 10 % ランク種別.E; // 43 % } // ローカル private RecordDBRecord _Record; private ユーザ設定 _ユーザ設定; private double _難易度; private Dictionary<判定種別, int> _判定別ヒット数; private readonly Dictionary<判定種別, double> _判定値表 = new Dictionary<判定種別, double>() { { 判定種別.PERFECT, 1.0 }, { 判定種別.GREAT, 0.5 }, { 判定種別.GOOD, 0.2 }, { 判定種別.OK, 0.0 }, { 判定種別.MISS, 0.0 }, }; /// <summary> /// Autoを使用した場合のオプション補正。 /// 達成率に乗じる数値なので、Autoにすると演奏が簡単になる(と思われる)ものほど補正値は小さくなる。 /// </summary> private readonly Dictionary<AutoPlay種別, double> _Auto時の補正 = new Dictionary<AutoPlay種別, double>() { { AutoPlay種別.LeftCrash, 0.9 }, { AutoPlay種別.HiHat, 0.5 }, { AutoPlay種別.Foot, 1.0 }, // Foot は判定に使われない。 { AutoPlay種別.Snare, 0.5 }, { AutoPlay種別.Bass, 0.5 }, { AutoPlay種別.Tom1, 0.7 }, { AutoPlay種別.Tom2, 0.7 }, { AutoPlay種別.Tom3, 0.8 }, { AutoPlay種別.RightCrash, 0.9 }, }; private IReadOnlyDictionary<判定種別, int> _ヒット割合を算出して返す() { // hack: ヒット割合の計算式は、本家とは一致していない。 int ヒット数の合計 = 0; var ヒット割合_実数 = new Dictionary<判定種別, double>(); // 実値(0~100) var ヒット割合_整数 = new Dictionary<判定種別, int>(); // 実値を整数にしてさらに補正した値(0~100) var ヒット数リスト = new List<(判定種別 judge, int hits)>(); var 切り捨てした = new Dictionary<判定種別, bool>(); 判定種別 判定; // ヒット数の合計を算出。 foreach( var kvp in this._判定別ヒット数 ) ヒット数の合計 += kvp.Value; // 各判定のヒット割合(実数)を算出。 foreach( var kvp in this._判定別ヒット数 ) { ヒット割合_実数.Add( kvp.Key, ( 100.0 * kvp.Value ) / ヒット数の合計 ); 切り捨てした.Add( kvp.Key, false ); // ついでに初期化。 } // ヒット数の大きいもの順(降順)に、リストを作成。 foreach( 判定種別? j in Enum.GetValues( typeof( 判定種別 ) ) ) { if( j.HasValue ) ヒット数リスト.Add( (j.Value, this.判定別ヒット数[ j.Value ]) ); } ヒット数リスト.Sort( ( x, y ) => ( y.hits - x.hits ) ); // 降順 // ヒット数が一番大きい判定は、ヒット割合の小数部を切り捨てる。 判定 = ヒット数リスト[ 0 ].judge; ヒット割合_整数.Add( 判定, (int)Math.Floor( ヒット割合_実数[ 判定 ] ) ); 切り捨てした[ 判定 ] = true; // 以下、二番目以降についてヒット割合(整数)を算出する。 int 整数割合の合計 = ヒット割合_整数[ 判定 ]; for( int i = 1; i < ヒット数リスト.Count; i++ ) { 判定 = ヒット数リスト[ i ].judge; // まずは四捨五入する。 ヒット割合_整数.Add( 判定, (int)Math.Round( ヒット割合_実数[ 判定 ], MidpointRounding.AwayFromZero ) ); // 合計が100になり、かつ、まだ後続に非ゼロがいるなら、値を -1 する。 // → まだ非ゼロの後続がいる場合は、ここで100になってはならない。逆に、後続がすべてゼロなら、ここで100にならなければならない。 if( 100 <= ( 整数割合の合計 + ヒット割合_整数[ 判定 ] ) ) { bool 後続にまだ非ゼロがいる = false; for( int n = ( i + 1 ); n < ヒット数リスト.Count; n++ ) { if( ヒット数リスト[ n ].hits > 0 ) { 後続にまだ非ゼロがいる = true; break; } } if( 後続にまだ非ゼロがいる ) { ヒット割合_整数[ 判定 ]--; 切り捨てした[ 判定 ] = true; } } // 合計に加算して、次へ。 整数割合の合計 += ヒット割合_整数[ 判定 ]; } // 合計が100に足りない場合は、「四捨五入した値と実数値との差の絶対値」が一番大きい判定に +1 する。 // ただし、「ヒット数が一番大きい判定」と、「切り捨てした判定」は除外する。 if( 100 > 整数割合の合計 ) { var 差の絶対値リスト = new List<(判定種別 judge, double 差の絶対値)>(); for( int i = 1; i < ヒット数リスト.Count; i++ ) // i = 0 (ヒット数が一番大きい判定)は除く { 判定 = ヒット数リスト[ i ].judge; 差の絶対値リスト.Add( (判定, Math.Abs( ヒット割合_実数[ 判定 ] - ヒット割合_整数[ 判定 ] )) ); } 差の絶対値リスト.Sort( ( x, y ) => (int)( y.差の絶対値 * 1000.0 - x.差の絶対値 * 1000.0 ) ); // 降順; 0.xxxx だと (int) で詰むが、1000倍したらだいたいOk // 余るときはたいてい 99 だと思うが、念のため、100になるまで降順に+1していく。 for( int i = 0; i < 差の絶対値リスト.Count; i++ ) { 判定 = 差の絶対値リスト[ i ].judge; if( 切り捨てした[ 判定 ] ) continue; // 切り捨てした判定は除く ヒット割合_整数[ 判定 ]++; 整数割合の合計++; if( 100 <= 整数割合の合計 ) break; } } return ヒット割合_整数; } /// <summary> /// スコアのチップリストのうち、判定対象のチップの数を返す。 /// </summary> private int _総ノーツ数を算出して返す( SSTF.スコア score, ユーザ設定 options ) { int 総ノーツ数 = 0; if( score is null ) return 総ノーツ数; foreach( var chip in score.チップリスト ) { var ドラムチッププロパティ = options.ドラムチッププロパティリスト[ chip.チップ種別 ]; bool AutoPlayである = options.AutoPlay[ ドラムチッププロパティ.AutoPlay種別 ]; bool 判定対象である = ( AutoPlayである ) ? ドラムチッププロパティ.AutoPlayON_自動ヒット_判定 : ドラムチッププロパティ.AutoPlayOFF_ユーザヒット_判定; if( 判定対象である ) 総ノーツ数++; } return 総ノーツ数; } private static double _小数第3位以下切り捨て( double v ) => Math.Truncate( 100.0 * v ) / 100.0; } } <|start_filename|>DTXMania2/保存データ/RecordDB/old/v003_RecordDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.old.RecordDBRecord { class v003_RecordDBRecord { public const int VERSION = 3; /// <summary> /// ユーザを一意に識別するID。 /// </summary> public string UserId { get; set; } /// <summary> /// 曲譜面ファイルのハッシュ値。 /// </summary> public string SongHashId { get; set; } /// <summary> /// スコア。 /// </summary> public int Score { get; set; } /// <summary> /// カウントマップラインのデータ。 /// 1ブロックを1文字('0':0~'C':12)で表し、<see cref="DTXMania.ステージ.演奏.カウントマップライン.カウントマップの最大要素数"/> 個の文字が並ぶ。 /// もし不足分があれば、'0' とみなされる。 /// </summary> public string CountMap { get; set; } /// <summary> /// 曲別SKILL。 /// </summary> public double Skill { get; set; } /// <summary> /// 達成率。 /// </summary> public double Achievement { get; set; } // 生成と終了 public v003_RecordDBRecord() { this.UserId = "Anonymous"; this.SongHashId = ""; this.Score = 0; this.CountMap = ""; this.Skill = 0.0; this.Achievement = 0.0; } } } <|start_filename|>DTXMania2/イメージ/文字列画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; namespace DTXMania2 { class 文字列画像 : FDK.文字列画像 { public 文字列画像() : base( Global.GraphicResources.D3D11Device1, Global.GraphicResources.DWriteFactory, Global.GraphicResources.D2D1Factory1, Global.GraphicResources.既定のD2D1DeviceContext, Global.GraphicResources.設計画面サイズ ) { } public void ビットマップを生成または更新する() { base.ビットマップを生成または更新する( Global.GraphicResources.DWriteFactory, Global.GraphicResources.D2D1Factory1, Global.GraphicResources.既定のD2D1DeviceContext, Global.GraphicResources.D3D11Device1 ); } public void 描画する( float 左位置, float 上位置, float 不透明度0to1 = 1.0f, float X方向拡大率 = 1.0f, float Y方向拡大率 = 1.0f ) { base.描画する( Global.GraphicResources.DWriteFactory, Global.GraphicResources.D2D1Factory1, Global.GraphicResources.既定のD2D1DeviceContext, Global.GraphicResources.D3D11Device1, Global.GraphicResources.既定のD3D11DeviceContext, Global.GraphicResources.設計画面サイズ, Global.GraphicResources.既定のD3D11ViewPort, Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView, Global.GraphicResources.既定のD3D11DepthStencilState, 左位置, 上位置, 不透明度0to1, X方向拡大率, Y方向拡大率 ); } public void 描画する( Matrix? 変換行列3D = null, float 不透明度0to1 = 1.0f ) { base.描画する( Global.GraphicResources.DWriteFactory, Global.GraphicResources.D2D1Factory1, Global.GraphicResources.既定のD2D1DeviceContext, Global.GraphicResources.D3D11Device1, Global.GraphicResources.既定のD3D11DeviceContext, Global.GraphicResources.設計画面サイズ, Global.GraphicResources.既定のD3D11ViewPort, Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView, Global.GraphicResources.既定のD3D11DepthStencilState, 変換行列3D, 不透明度0to1 ); } } } <|start_filename|>DTXMania2/サウンド/ドラムサウンド.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using CSCore; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2 { /// <summary> /// SSTFにおける既定のドラムサウンド。 /// </summary> class ドラムサウンド : IDisposable { private const int 多重度 = 4; // 生成と終了 public ドラムサウンド() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._チップtoコンテキスト = new Dictionary<(SSTF.チップ種別 chipType, int サブチップID), ドラムサウンドコンテキスト>(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._すべて解放する(); } public void すべて生成する( SoundDevice device ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._すべて解放する(); lock( this._Sound利用権 ) { // SSTの既定のサウンドを、subChipId = 0 としてプリセット登録する。 var soundList = new List<(SSTF.チップ種別 type, VariablePath path)>() { ( SSTF.チップ種別.LeftCrash, @"$(DrumSounds)\LeftCrash.wav" ), ( SSTF.チップ種別.Ride, @"$(DrumSounds)\Ride.wav" ), ( SSTF.チップ種別.Ride_Cup, @"$(DrumSounds)\RideCup.wav" ), ( SSTF.チップ種別.China, @"$(DrumSounds)\China.wav" ), ( SSTF.チップ種別.Splash, @"$(DrumSounds)\Splash.wav" ), ( SSTF.チップ種別.HiHat_Open, @"$(DrumSounds)\HiHatOpen.wav" ), ( SSTF.チップ種別.HiHat_HalfOpen, @"$(DrumSounds)\HiHatHalfOpen.wav" ), ( SSTF.チップ種別.HiHat_Close, @"$(DrumSounds)\HiHatClose.wav" ), ( SSTF.チップ種別.HiHat_Foot, @"$(DrumSounds)\HiHatFoot.wav" ), ( SSTF.チップ種別.Snare, @"$(DrumSounds)\Snare.wav" ), ( SSTF.チップ種別.Snare_OpenRim, @"$(DrumSounds)\SnareOpenRim.wav" ), ( SSTF.チップ種別.Snare_ClosedRim, @"$(DrumSounds)\SnareClosedRim.wav" ), ( SSTF.チップ種別.Snare_Ghost, @"$(DrumSounds)\SnareGhost.wav" ), ( SSTF.チップ種別.Bass, @"$(DrumSounds)\Bass.wav" ), ( SSTF.チップ種別.Tom1, @"$(DrumSounds)\Tom1.wav" ), ( SSTF.チップ種別.Tom1_Rim, @"$(DrumSounds)\Tom1Rim.wav" ), ( SSTF.チップ種別.Tom2, @"$(DrumSounds)\Tom2.wav" ), ( SSTF.チップ種別.Tom2_Rim, @"$(DrumSounds)\Tom2Rim.wav" ), ( SSTF.チップ種別.Tom3, @"$(DrumSounds)\Tom3.wav" ), ( SSTF.チップ種別.Tom3_Rim, @"$(DrumSounds)\Tom3Rim.wav" ), ( SSTF.チップ種別.RightCrash, @"$(DrumSounds)\RightCrash.wav" ), ( SSTF.チップ種別.LeftCymbal_Mute, @"$(DrumSounds)\LeftCymbalMute.wav" ), ( SSTF.チップ種別.RightCymbal_Mute, @"$(DrumSounds)\RightCymbalMute.wav" ), }; foreach( var sound in soundList ) { var path = new VariablePath( Folder.カルチャを考慮した絶対パスを返す( sound.path.変数なしパス ) ); if( !File.Exists( sound.path.変数なしパス ) ) { Log.ERROR( $"サウンドファイルが存在しません。[{path.変数付きパス}]" ); continue; } // サウンドファイルを読み込んでデコードする。 var sampleSource = SampleSourceFactory.Create( device, path.変数なしパス, 1.0 ); // ドラムサウンドは常に 1.0 if( sampleSource is null ) { Log.ERROR( $"サウンドの生成に失敗しました。[{path.変数付きパス}]" ); continue; } // コンテキストを作成する。 var context = new ドラムサウンドコンテキスト( sampleSource, ドラムサウンド.多重度 ); // 多重度分のサウンドを生成する。 for( int i = 0; i < context.Sounds.Length; i++ ) context.Sounds[ i ] = new Sound( device, context.SampleSource ); // コンテキストを辞書に追加する。 if( this._チップtoコンテキスト.ContainsKey( (sound.type, 0) ) ) { // すでに辞書に存在してるなら、解放してから削除する。 this._チップtoコンテキスト[ (sound.type, 0) ].Dispose(); this._チップtoコンテキスト.Remove( (sound.type, 0) ); } this._チップtoコンテキスト.Add( (sound.type, 0), context ); Log.Info( $"ドラムサウンドを生成しました。[({sound.type},0) = {path.変数付きパス}]" ); } } } private void _すべて解放する() { lock( this._Sound利用権 ) { foreach( var kvp in this._チップtoコンテキスト ) kvp.Value.Dispose(); this._チップtoコンテキスト.Clear(); } } // 再生 public void 再生する( SSTF.チップ種別 chipType, int subChipId, bool 発声前に消音する = false, 消音グループ種別 groupType = 消音グループ種別.Unknown, float 音量0to1 = 1f ) { lock( this._Sound利用権 ) { if( this._チップtoコンテキスト.TryGetValue( (chipType, subChipId), out var context ) ) { // 必要あれば、指定された消音グループ種別に属するドラムサウンドをすべて停止する。 if( 発声前に消音する && groupType != 消音グループ種別.Unknown ) { var 停止するコンテキストs = this._チップtoコンテキスト.Where( ( kvp ) => ( kvp.Value.最後に発声したときの消音グループ種別 == groupType ) ); foreach( var wavContext in 停止するコンテキストs ) foreach( var sound in wavContext.Value.Sounds ) sound.Stop(); } // 発声する。 context.発声する( groupType, 音量0to1 ); } else { // コンテキストがないなら何もしない。 } } } // ローカル private class ドラムサウンドコンテキスト : IDisposable { public ISampleSource SampleSource { get; } public Sound[] Sounds { get; } public 消音グループ種別 最後に発声したときの消音グループ種別 { get; protected set; } public ドラムサウンドコンテキスト( ISampleSource sampleSource, int 多重度 = 4 ) { this._多重度 = 多重度; this.SampleSource = sampleSource; this.Sounds = new Sound[ 多重度 ]; this.最後に発声したときの消音グループ種別 = 消音グループ種別.Unknown; } public virtual void Dispose() { for( int i = 0; i < this.Sounds.Length; i++ ) { if( this.Sounds[ i ] is null ) continue; if( this.Sounds[ i ].再生中である ) this.Sounds[ i ].Stop(); this.Sounds[ i ].Dispose(); } this.SampleSource.Dispose(); } public void 発声する( 消音グループ種別 type, float 音量 ) { this.最後に発声したときの消音グループ種別 = type; // サウンドを再生する。 if( null != this.Sounds[ this._次に再生するSound番号 ] ) { this.Sounds[ this._次に再生するSound番号 ].Volume = ( 0f > 音量 ) ? 0f : ( 1f < 音量 ) ? 1f : 音量; this.Sounds[ this._次に再生するSound番号 ].Play(); } // サウンドローテーション。 this._次に再生するSound番号 = ( this._次に再生するSound番号 + 1 ) % this._多重度; } private readonly int _多重度; private int _次に再生するSound番号 = 0; }; private Dictionary<(SSTF.チップ種別 chipType, int サブチップID), ドラムサウンドコンテキスト> _チップtoコンテキスト; private readonly object _Sound利用権 = new object(); } } <|start_filename|>DTXMania2/ステージ/07演奏/表示レーン種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.演奏 { /// <summary> /// チップや判定文字列の表示先となるレーンの種別。 /// </summary> enum 表示レーン種別 { Unknown, LeftCymbal, HiHat, Foot, // 左ペダル Snare, Bass, Tom1, Tom2, Tom3, RightCymbal, } } <|start_filename|>DTXMania2/ステージ/システム情報.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { class システム情報 : IDisposable { // プロパティ public int 現在のFPS => this._FPS.現在のFPS; public int 現在のVPS => this._FPS.現在のVPS; // 生成と終了 public システム情報() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._FPS = new FPS(); this._文字列画像 = new 文字列画像D2D(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._文字列画像.Dispose(); } // カウント public bool FPSをカウントしプロパティを更新する() => this._FPS.FPSをカウントしプロパティを更新する(); public void VPSをカウントする() => this._FPS.VPSをカウントする(); // 進行と描画 public void 描画する( DeviceContext d2ddc, string 追加文字列 = "" ) { double FPSの周期ms = ( 0 < this._FPS.現在のFPS ) ? ( 1000.0 / this._FPS.現在のFPS ) : -1.0; this._文字列画像.表示文字列 = $"VPS: {this._FPS.現在のVPS} / FPS: {this._FPS.現在のFPS} (" + FPSの周期ms.ToString( "0.000" ) + "ms)" + Environment.NewLine + $"GameMode: {_ONOFF[ GameMode.ゲームモードである ]}" + Environment.NewLine + 追加文字列; this._文字列画像.描画する( d2ddc, 0f, 0f ); } // ローカル private FPS _FPS; private readonly 文字列画像D2D _文字列画像; private readonly Dictionary<bool, string> _ONOFF = new Dictionary<bool, string> { { false, Properties.Resources.TXT_OFF }, { true, Properties.Resources.TXT_ON }, }; } } <|start_filename|>DTXMania2/ステージ/08結果/曲別SKILL.数値.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; namespace DTXMania2.結果 { partial class 曲別SKILL { class 数値 : IDisposable { // プロパティ public bool アニメ完了 => ( null != this._ストーリーボード ) && ( this._ストーリーボード.Status == StoryboardStatus.Ready ); // 生成と終了 public 数値() { this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_Large.png", @"$(Images)\ParameterFont_Large.yaml", 文字幅補正dpx: 0f ); } public virtual void Dispose() { this._不透明度?.Dispose(); this._左位置dpx?.Dispose(); this._ストーリーボード?.Dispose(); this._数字画像.Dispose(); } // 進行と描画 public void 開始する( double 数値 ) { string v = 数値.ToString( "0.00" ).PadLeft( 6 ); // 左余白は ' '。例:" 19.00", "199.99" this._スキル値文字列_整数部 = v[ 0..4 ]; // '.' 含む this._スキル値文字列_小数部 = v[ 4.. ]; this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( Global.Animation.Manager ); #region " 左位置dpx " //---------------- // 初期値 +200 this._左位置dpx?.Dispose(); this._左位置dpx = new Variable( Global.Animation.Manager, initialValue: +200.0 ); // 待つ using( var 遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 曲別SKILL._最初の待機時間sec ) ) this._ストーリーボード.AddTransition( this._左位置dpx, 遷移 ); // 0.0 へ using( var 遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: 曲別SKILL._アニメ時間sec / 2, finalValue: 0.0, accelerationRatio: 0.2, decelerationRatio: 0.8 ) ) this._ストーリーボード.AddTransition( this._左位置dpx, 遷移 ); //---------------- #endregion #region " 不透明度 " //---------------- // 初期値 0.0 this._不透明度?.Dispose(); this._不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); // 待つ using( var 遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 曲別SKILL._最初の待機時間sec ) ) this._ストーリーボード.AddTransition( this._不透明度, 遷移 ); // 1.0 へ using( var 遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 曲別SKILL._アニメ時間sec, finalValue: 1.0 ) ) this._ストーリーボード.AddTransition( this._不透明度, 遷移 ); //---------------- #endregion // アニメーション開始 this._ストーリーボード.Schedule( Global.Animation.Timer.Time ); } public void アニメを完了する() { this._ストーリーボード?.Finish( 0.1 ); } public void 進行描画する( DeviceContext d2ddc, float x, float y ) { if( this._左位置dpx is null || this._不透明度 is null ) return; this._数字画像.不透明度 = (float)this._不透明度.Value; float 左位置dpx = x + (float)this._左位置dpx.Value; // 整数部を描画する('.'含む) this._数字画像.描画する( d2ddc, 左位置dpx, y, this._スキル値文字列_整数部, new Size2F( 1.0f, 1.2f ) ); // 小数部を描画する this._数字画像.描画する( d2ddc, 左位置dpx + 180f, y + 17f, this._スキル値文字列_小数部, new Size2F( 1.0f, 1.0f ) ); } // ローカル private readonly フォント画像D2D _数字画像; private string _スキル値文字列_小数部 = ""; private string _スキル値文字列_整数部 = ""; // '.' 含む private Storyboard? _ストーリーボード = null; private Variable? _左位置dpx = null; private Variable? _不透明度 = null; } } } <|start_filename|>DTXMania2/保存データ/SystemConfig/old/v002_システム設定.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using FDK; namespace DTXMania2.old.SystemConfig { /// <summary> /// システム設定。 /// 全ユーザで共有される項目。 /// </summary> class v002_システム設定 { public const int VERSION = 2; public static readonly VariablePath 既定のシステム設定ファイルパス = @"$(AppData)\Configuration.yaml"; public int Version { get; set; } public v002_キーバインディング キー割り当て { get; set; } /// <summary> /// 曲ファイルを検索するフォルダのリスト。 /// </summary> public List<VariablePath> 曲検索フォルダ { get; protected set; } public Point ウィンドウ表示位置Viewerモード用 { get; set; } public Size ウィンドウサイズViewerモード用 { get; set; } /// <summary> /// チップヒットの判定位置を、判定バーからさらに上下に調整する。 /// -99~+99[ms] 。 /// </summary> /// <remarks> /// 判定バーの見かけの位置は変わらず、判定位置のみ移動する。 /// 入力機器の遅延対策であるが、入力機器とのヒモづけは行わないので、 /// 入力機器が変われば再調整が必要になる場合がある。 /// </remarks> public int 判定位置調整ms { get; set; } // 生成と終了 public static v002_システム設定 読み込む( VariablePath path ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // (1) 読み込み or 新規作成 var yaml = File.ReadAllText( path.変数なしパス ); var deserializer = new YamlDotNet.Serialization.Deserializer(); var config = deserializer.Deserialize<v002_システム設定>( yaml ); if( 2 != config.Version ) throw new Exception( "バージョンが違います。" ); // (2) 読み込み後の処理 // パスの指定がなければ、とりあえず exe のあるフォルダを検索対象にする。 if( 0 == config.曲検索フォルダ.Count ) config.曲検索フォルダ.Add( @"$(Exe)" ); return config; } public v002_システム設定() { this.Version = VERSION; this.キー割り当て = new v002_キーバインディング(); this.曲検索フォルダ = new List<VariablePath>() { @"$(Exe)" }; this.ウィンドウ表示位置Viewerモード用 = new Point( 100, 100 ); this.ウィンドウサイズViewerモード用 = new Size( 640, 360 ); this.判定位置調整ms = 0; } public void 保存する( VariablePath path ) { using var _ = new LogBlock( Log.現在のメソッド名 ); var serializer = new YamlDotNet.Serialization.SerializerBuilder() .WithTypeInspector( inner => new CommentGatheringTypeInspector( inner ) ) .WithEmissionPhaseObjectGraphVisitor( args => new CommentsObjectGraphVisitor( args.InnerVisitor ) ) .Build(); // ※ 値が既定値であるプロパティは出力されないので注意。 var yaml = serializer.Serialize( this ); File.WriteAllText( path.変数なしパス, yaml ); Log.Info( $"システム設定を保存しました。[{path.変数付きパス}]" ); } } } <|start_filename|>FDK/イメージ/IImage.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { public interface IImage : IDisposable { } } <|start_filename|>DTXMania2/ステージ/07演奏/チップの演奏状態.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SSTF=SSTFormat.v004; namespace DTXMania2.演奏 { /// <summary> /// チップに対応する、チップの演奏情報。 /// </summary> class チップの演奏状態 : ICloneable { // プロパティ public bool 可視 { get; set; } = true; public bool 不可視 { get => !this.可視; set => this.可視 = !value; } public bool ヒット済みである { get; set; } = false; public bool ヒットされていない { get => !this.ヒット済みである; set => this.ヒット済みである = !value; } public bool 発声済みである { get; set; } = false; public bool 発声されていない { get => !this.発声済みである; set => this.発声済みである = !value; } // 生成と終了 public チップの演奏状態( SSTF.チップ chip ) { this._chip = chip; this.ヒット前の状態にする(); } // 状態操作 public void ヒット前の状態にする() { this.可視 = ( Global.App.ログオン中のユーザ.ドラムチッププロパティリスト[ this._chip.チップ種別 ].表示チップ種別 != 表示チップ種別.Unknown ); this.ヒット済みである = false; this.発声済みである = false; } public void ヒット済みの状態にする() { this.可視 = false; this.ヒット済みである = true; this.発声済みである = true; } // IClonable 実装 public チップの演奏状態 Clone() { return (チップの演奏状態)this.MemberwiseClone(); } object ICloneable.Clone() { return this.Clone(); } // ローカル protected readonly SSTF.チップ _chip; } } <|start_filename|>DTXMania2/ステージ/03認証/認証ステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using FDK; namespace DTXMania2.認証 { /// <summary> /// ユーザ選択画面。 /// </summary> class 認証ステージ : IStage { // プロパティ public enum フェーズ { フェードイン, ユーザ選択, フェードアウト, 完了, キャンセル, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; public int 現在選択中のユーザ => this._ユーザリスト.選択中のユーザ; // 生成と終了 public 認証ステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._舞台画像 = new 舞台画像(); this._ウィンドウ画像 = new 画像D2D( @"$(Images)\AuthStage\UserSelectFrame.png" ); this._プレイヤーを選択してください = new 文字列画像D2D() { 表示文字列 = Properties.Resources.TXT_プレイヤーを選択してください, フォントサイズpt = 30f, 描画効果 = 文字列画像D2D.効果.ドロップシャドウ, }; this._ユーザリスト = new ユーザリスト(); this._システム情報 = new システム情報(); Global.App.アイキャッチ管理.現在のアイキャッチ.オープンする(); Global.App.システムサウンド.再生する( システムサウンド種別.認証ステージ_開始音 ); Global.App.システムサウンド.再生する( システムサウンド種別.認証ステージ_ループBGM, ループ再生する: true ); // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.フェードイン; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._システム情報.Dispose(); this._ユーザリスト.Dispose(); this._プレイヤーを選択してください.Dispose(); this._ウィンドウ画像.Dispose(); this._舞台画像.Dispose(); Global.App.システムサウンド.停止する( システムサウンド種別.認証ステージ_開始音 ); Global.App.システムサウンド.停止する( システムサウンド種別.認証ステージ_ループBGM ); //Global.App.システムサウンド.停止する( システムサウンド種別.認証ステージ_ログイン音 ); // --> 鳴りっぱなしでいい } // 進行と描画 public void 進行する() { this._システム情報.FPSをカウントしプロパティを更新する(); Global.App.ドラム入力.すべての入力デバイスをポーリングする(); switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " 認証画面&フェードインを描画する。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.オープン完了 ) { // フェードイン描画が完了したらユーザ選択フェーズへ。 this.現在のフェーズ = フェーズ.ユーザ選択; } //---------------- #endregion break; } case フェーズ.ユーザ選択: { #region " 入力処理。" //---------------- if( Global.App.ドラム入力.確定キーが入力された() ) { #region " 確定 → フェードアウトフェーズへ " //---------------- Global.App.システムサウンド.停止する( システムサウンド種別.認証ステージ_ループBGM ); Global.App.システムサウンド.再生する( システムサウンド種別.認証ステージ_ログイン音 ); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( 回転幕 ) ); this.現在のフェーズ = フェーズ.フェードアウト; //---------------- #endregion } else if( Global.App.ドラム入力.キャンセルキーが入力された() ) { #region " キャンセル → キャンセルフェーズへ " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); this.現在のフェーズ = フェーズ.キャンセル; //---------------- #endregion } else if( Global.App.ドラム入力.上移動キーが入力された() ) { #region " 上移動 → 前のユーザを選択 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._ユーザリスト.前のユーザを選択する(); //---------------- #endregion } else if( Global.App.ドラム入力.下移動キーが入力された() ) { #region " 下移動 → 次のユーザを選択 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._ユーザリスト.次のユーザを選択する(); //---------------- #endregion } //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " 背景画面&フェードアウトを描画する。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) { // アイキャッチが完了したら完了フェーズへ。 this.現在のフェーズ = フェーズ.完了; } //---------------- #endregion break; } case フェーズ.完了: case フェーズ.キャンセル: { #region " 遷移終了。Appによるステージ遷移を待つ。" //---------------- //---------------- #endregion break; } } } public void 描画する() { this._システム情報.VPSをカウントする(); var 描画領域 = new RectangleF( 566f, 60f, 784f, 943f ); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " 認証画面&フェードインを描画する。" //---------------- d2ddc.BeginDraw(); this._舞台画像.進行描画する( d2ddc, 黒幕付き: true ); this._ウィンドウ画像.描画する( d2ddc, 描画領域.X, 描画領域.Y ); this._プレイヤーを選択してください.描画する( d2ddc, 描画領域.X + 28f, 描画領域.Y + 45f ); this._ユーザリスト.進行描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.ユーザ選択: { #region " 認証画面を描画する。" //---------------- d2ddc.BeginDraw(); this._舞台画像.進行描画する( d2ddc, 黒幕付き: true ); this._ウィンドウ画像.描画する( d2ddc, 描画領域.X, 描画領域.Y ); this._プレイヤーを選択してください.描画する( d2ddc, 描画領域.X + 28f, 描画領域.Y + 45f ); this._ユーザリスト.進行描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " 背景画面&フェードアウトを描画する。" //---------------- d2ddc.BeginDraw(); this._舞台画像.進行描画する( d2ddc, true ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.完了: case フェーズ.キャンセル: { break; } } } // ローカル private readonly 舞台画像 _舞台画像; private readonly 画像D2D _ウィンドウ画像; private readonly 文字列画像D2D _プレイヤーを選択してください; private readonly ユーザリスト _ユーザリスト; private readonly システム情報 _システム情報; } } <|start_filename|>DTXMania2/ステージ/パッド矢印.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { class パッド矢印 : IDisposable { // プロパティ public enum 種類 { 上_Tom1, 下_Tom2, 左_Snare, 右_Tom3, }; // 生成と終了 public パッド矢印() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._矢印画像 = new 画像D2D( @"$(Images)\PadArrow.png" ); this._矢印の矩形リスト = new 矩形リスト( @"$(Images)\PadArrow.yaml" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._矢印画像.Dispose(); } // 進行と描画 public void 描画する( DeviceContext d2ddc, 種類 type, Vector2 中央位置dpx, float 拡大率 = 1f ) { var 矩形 = type switch { 種類.上_Tom1 => this._矢印の矩形リスト[ "Up" ], 種類.下_Tom2 => this._矢印の矩形リスト[ "Down" ], 種類.左_Snare => this._矢印の矩形リスト[ "Left" ], 種類.右_Tom3 => this._矢印の矩形リスト[ "Right" ], _ => throw new Exception( "未対応の種類です。" ), }; if( 矩形 is null ) return; var 左上位置dpx = new Vector3( 中央位置dpx.X - 矩形.Value.Width * 拡大率 / 2f, 中央位置dpx.Y - 矩形.Value.Height * 拡大率 / 2f, 0f ); var 変換行列 = Matrix.Scaling( 拡大率 ) * Matrix.Translation( 左上位置dpx ); this._矢印画像.描画する( d2ddc, 変換行列, 転送元矩形: 矩形 ); } // ローカル private readonly 画像D2D _矢印画像; private readonly 矩形リスト _矢印の矩形リスト; } } <|start_filename|>DTXMania2/ステージ/07演奏/判定文字列.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class 判定文字列 : IDisposable { // 生成と終了 public 判定文字列() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._判定文字列画像 = new 画像D2D( @"$(Images)\PlayStage\JudgeLabel.png" ); this._判定文字列の矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\JudgeLabel.yaml" ); this._FastSlow数字画像 = new 画像D2D( @"$(Images)\PlayStage\FastSlowNumber.png" ); this._FastSlow数字の矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\FastSlowNumber.yaml" ); this._レーンtoステータス = new Dictionary<表示レーン種別, 表示レーンステータス>() { { 表示レーン種別.Unknown, new 表示レーンステータス( 表示レーン種別.Unknown ) }, { 表示レーン種別.LeftCymbal, new 表示レーンステータス( 表示レーン種別.LeftCymbal ) }, { 表示レーン種別.HiHat, new 表示レーンステータス( 表示レーン種別.HiHat ) }, { 表示レーン種別.Foot, new 表示レーンステータス( 表示レーン種別.Foot ) }, { 表示レーン種別.Snare, new 表示レーンステータス( 表示レーン種別.Snare ) }, { 表示レーン種別.Bass, new 表示レーンステータス( 表示レーン種別.Bass ) }, { 表示レーン種別.Tom1, new 表示レーンステータス( 表示レーン種別.Tom1 ) }, { 表示レーン種別.Tom2, new 表示レーンステータス( 表示レーン種別.Tom2 ) }, { 表示レーン種別.Tom3, new 表示レーンステータス( 表示レーン種別.Tom3 ) }, { 表示レーン種別.RightCymbal, new 表示レーンステータス( 表示レーン種別.RightCymbal ) }, }; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var kvp in this._レーンtoステータス ) kvp.Value.Dispose(); this._判定文字列画像.Dispose(); this._FastSlow数字画像.Dispose(); } // 表示開始 public void 表示を開始する( 表示レーン種別 lane, 判定種別 judge, double fastSlowSec ) { var status = this._レーンtoステータス[ lane ]; status.判定種別 = judge; status.FastSlow値sec = fastSlowSec; status.現在の状態 = 表示レーンステータス.状態.表示開始; } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { foreach( 表示レーン種別? レーン in Enum.GetValues( typeof( 表示レーン種別 ) ) ) { if( !レーン.HasValue ) continue; var status = this._レーンtoステータス[ レーン.Value ]; switch( status.現在の状態 ) { case 表示レーンステータス.状態.表示開始: { status.アニメ用メンバを解放する(); #region " (1) 光 アニメーションを構築 " //---------------- if( status.判定種別 == 判定種別.PERFECT ) // 今のところ、光はPERFECT時のみ表示。 { // 初期状態 status.光の回転角 = new Variable( Global.Animation.Manager, initialValue: 0 ); status.光のX方向拡大率 = new Variable( Global.Animation.Manager, initialValue: 1.2 ); status.光のY方向拡大率 = new Variable( Global.Animation.Manager, initialValue: 0.25 ); status.光のストーリーボード = new Storyboard( Global.Animation.Manager ); double 期間sec; // シーン1. 小さい状態からすばやく展開 期間sec = 0.03; using( var 回転角の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: -100.0 ) ) // [degree] using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 1.0 ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 1.0 ) ) { status.光のストーリーボード.AddTransition( status.光の回転角, 回転角の遷移 ); status.光のストーリーボード.AddTransition( status.光のX方向拡大率, X方向拡大率の遷移 ); status.光のストーリーボード.AddTransition( status.光のY方向拡大率, Y方向拡大率の遷移 ); } // シーン2. 大きい状態でゆっくり消える 期間sec = 0.29; using( var 回転角の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: -140.0 ) ) // [degree] using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.0 ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) { status.光のストーリーボード.AddTransition( status.光の回転角, 回転角の遷移 ); status.光のストーリーボード.AddTransition( status.光のX方向拡大率, X方向拡大率の遷移 ); status.光のストーリーボード.AddTransition( status.光のY方向拡大率, Y方向拡大率の遷移 ); } // 開始 status.光のストーリーボード.Schedule( Global.Animation.Timer.Time ); } else { status.光のストーリーボード = null; } //---------------- #endregion #region " (2) 判定文字(影)アニメーションを構築 " //---------------- { // 初期状態 status.文字列影の相対Y位置dpx = new Variable( Global.Animation.Manager, initialValue: +40.0 ); status.文字列影の不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); status.文字列影のストーリーボード = new Storyboard( Global.Animation.Manager ); double 期間sec; // シーン1. 完全透明のまま下から上に移動。 期間sec = 0.05; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: -5.0 ) ) using( var 透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) { status.文字列影のストーリーボード.AddTransition( status.文字列影の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列影のストーリーボード.AddTransition( status.文字列影の不透明度, 透明度の遷移 ); } // シーン2. 透明になりつつ上に消える 期間sec = 0.15; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: -10.0 ) ) using( var 透明度の遷移1 = Global.Animation.TrasitionLibrary.Linear( duration: 0.0, finalValue: 0.5 ) ) using( var 透明度の遷移2 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.0 ) ) { status.文字列影のストーリーボード.AddTransition( status.文字列影の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列影のストーリーボード.AddTransition( status.文字列影の不透明度, 透明度の遷移1 ); status.文字列影のストーリーボード.AddTransition( status.文字列影の不透明度, 透明度の遷移2 ); } // 開始 status.文字列影のストーリーボード.Schedule( Global.Animation.Timer.Time ); } //---------------- #endregion #region " (3) 判定文字(本体)アニメーションを構築 " //---------------- { // 初期状態 status.文字列本体の相対Y位置dpx = new Variable( Global.Animation.Manager, initialValue: +40.0 ); status.文字列本体のX方向拡大率 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); status.文字列本体のY方向拡大率 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); status.文字列本体の不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); status.文字列本体のストーリーボード = new Storyboard( Global.Animation.Manager ); double 期間sec; // シーン1. 透明から不透明になりつつ下から上に移動。 期間sec = 0.05; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: -5.0 ) ) using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: 期間sec, finalValue: 1.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) { status.文字列本体のストーリーボード.AddTransition( status.文字列本体の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のX方向拡大率, X方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のY方向拡大率, Y方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体の不透明度, 不透明度の遷移 ); } // シーン2. ちょっと下に跳ね返る 期間sec = 0.05; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: +5.0 ) ) using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) { status.文字列本体のストーリーボード.AddTransition( status.文字列本体の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のX方向拡大率, X方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のY方向拡大率, Y方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体の不透明度, 不透明度の遷移 ); } // シーン3. また上に戻る 期間sec = 0.05; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: +0.0 ) ) using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) { status.文字列本体のストーリーボード.AddTransition( status.文字列本体の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のX方向拡大率, X方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のY方向拡大率, Y方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体の不透明度, 不透明度の遷移 ); } // シーン4. 静止 期間sec = 0.15; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) { status.文字列本体のストーリーボード.AddTransition( status.文字列本体の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のX方向拡大率, X方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のY方向拡大率, Y方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体の不透明度, 不透明度の遷移 ); } // シーン5. 横に広がり縦につぶれつつ消える 期間sec = 0.05; using( var 相対Y位置の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: 期間sec ) ) using( var X方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 2.0 ) ) using( var Y方向拡大率の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.0 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 期間sec, finalValue: 0.0 ) ) { status.文字列本体のストーリーボード.AddTransition( status.文字列本体の相対Y位置dpx, 相対Y位置の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のX方向拡大率, X方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体のY方向拡大率, Y方向拡大率の遷移 ); status.文字列本体のストーリーボード.AddTransition( status.文字列本体の不透明度, 不透明度の遷移 ); } // 開始 status.文字列本体のストーリーボード.Schedule( Global.Animation.Timer.Time ); } //---------------- #endregion status.現在の状態 = 表示レーンステータス.状態.表示中; break; } case 表示レーンステータス.状態.表示中: { #region " (1) 光 の進行描画 " //---------------- if( null != status.光のストーリーボード ) { var 転送元矩形 = this._判定文字列の矩形リスト[ "PERFECT光" ]; var w = 転送元矩形!.Value.Width; var h = 転送元矩形!.Value.Height; var sx = (float)status.光のX方向拡大率.Value; var sy = (float)status.光のY方向拡大率.Value; var 変換行列2D = Matrix3x2.Scaling( sx, sy ) * Matrix3x2.Rotation( angle: MathUtil.DegreesToRadians( (float)status.光の回転角.Value ), center: new Vector2( w / 2f, h / 2f ) ) * Matrix3x2.Translation( status.表示中央位置dpx.X - w / 2f, status.表示中央位置dpx.Y - h / 2f ); this._判定文字列画像.描画する( d2ddc, 変換行列2D, 転送元矩形: 転送元矩形 ); } //---------------- #endregion #region " (2) 判定文字列(影)の進行描画" //---------------- if( null != status.文字列影のストーリーボード ) { var 転送元矩形 = this._判定文字列の矩形リスト[ status.判定種別.ToString() ]!; this._判定文字列画像.描画する( d2ddc, status.表示中央位置dpx.X - 転送元矩形.Value.Width / 2f, status.表示中央位置dpx.Y - 転送元矩形.Value.Height / 2f + (float)status.文字列影の相対Y位置dpx.Value, (float)status.文字列影の不透明度.Value, 転送元矩形: 転送元矩形 ); } //---------------- #endregion #region " (3) 判定文字列(本体)の進行描画 " //---------------- if( null != status.文字列本体のストーリーボード ) { var 転送元矩形 = this._判定文字列の矩形リスト[ status.判定種別.ToString() ]!; var sx = (float)status.文字列本体のX方向拡大率.Value; var sy = (float)status.文字列本体のY方向拡大率.Value; this._判定文字列画像.描画する( d2ddc, status.表示中央位置dpx.X - sx * 転送元矩形.Value.Width / 2f, status.表示中央位置dpx.Y - sy * 転送元矩形.Value.Height / 2f + (float)status.文字列本体の相対Y位置dpx.Value, X方向拡大率: sx, Y方向拡大率: sy, 不透明度0to1: (float)status.文字列本体の不透明度.Value, 転送元矩形: 転送元矩形 ); } //---------------- #endregion #region " (4) FAST/SLOW値の進行描画 " //---------------- if( Global.App.ログオン中のユーザ.演奏中に判定FastSlowを表示する ) { // FAST/SLOW値: // ・チップより入力が早いと青文字、チップより入力が遅いと赤文字、 //  チップと入力の時間差が 10ms 未満なら黄文字で表示する。 // ・MISS 時は表示しない。 // ・ミリ秒単位で表示する。 if( status.判定種別 != 判定種別.MISS ) { int FastSlow値 = (int)( status.FastSlow値sec * 1000.0 ); // ミリ秒、小数切り捨て int FastSlow値の絶対値 = Math.Abs( FastSlow値 ); var 接尾詞 = ( FastSlow値の絶対値 < 10 ) ? "_yellow" : ( 0 > FastSlow値 ) ? "_blue" : "_red"; var 文字列 = FastSlow値.ToString( "D" ); int 文字数 = 文字列.Length; float 拡大率 = 2f; var 拡大済み文字列サイズdpx = new Size2F( 0, 0 ); for( int i = 0; i < 文字数; i++ ) { var 文字矩形 = this._FastSlow数字の矩形リスト[ 文字列[ i ] + 接尾詞 ]!; 拡大済み文字列サイズdpx.Width += 文字矩形.Value.Width * 拡大率; 拡大済み文字列サイズdpx.Height = Math.Max( 拡大済み文字列サイズdpx.Height, 文字矩形.Value.Height * 拡大率 ); } float x = status.表示中央位置dpx.X - 拡大済み文字列サイズdpx.Width / 2f; float y = status.表示中央位置dpx.Y - 拡大済み文字列サイズdpx.Height / 2f + 45f; for( int i = 0; i < 文字数; i++ ) { var 文字矩形 = this._FastSlow数字の矩形リスト[ 文字列[ i ] + 接尾詞 ]!; this._FastSlow数字画像.描画する( d2ddc, x, y, X方向拡大率: 拡大率, Y方向拡大率: 拡大率, 転送元矩形: 文字矩形 ); x += 文字矩形.Value.Width * 拡大率; } } } //---------------- #endregion #region " 全部終わったら非表示へ。" //---------------- if( ( ( status.文字列影のストーリーボード is null ) || ( status.文字列影のストーリーボード.Status == StoryboardStatus.Ready ) ) && ( ( status.文字列本体のストーリーボード is null ) || ( status.文字列本体のストーリーボード.Status == StoryboardStatus.Ready ) ) && ( ( status.光のストーリーボード is null ) || ( status.光のストーリーボード.Status == StoryboardStatus.Ready ) ) ) { status.現在の状態 = 表示レーンステータス.状態.非表示; } //---------------- #endregion break; } default: { continue; // 非表示 } } } } // ローカル private readonly 画像D2D _判定文字列画像; private readonly 矩形リスト _判定文字列の矩形リスト; private readonly 画像D2D _FastSlow数字画像; private readonly 矩形リスト _FastSlow数字の矩形リスト; /// <summary> /// 以下の画像のアニメ&表示管理を行うクラス。 /// ・判定文字列(本体) /// ・判定文字列(影) /// ・光(今のところPERFECTのみ) /// </summary> private class 表示レーンステータス : IDisposable { public enum 状態 { 非表示, 表示開始, // 高速進行スレッドが設定 表示中, // 描画スレッドが設定 } public 状態 現在の状態 = 状態.非表示; public 判定種別 判定種別 = 判定種別.PERFECT; /// <summary> /// チップと入力のズレ時間[秒]。 /// チップより入力が早ければ負数、遅ければ正数。 /// </summary> public double FastSlow値sec = 0; public readonly Vector2 表示中央位置dpx; /// <summary> /// 判定文字列(本体)の表示されるY座標のオフセット。 /// 表示中央位置dpx.Y からの相対値[dpx]。 /// </summary> public Variable 文字列本体の相対Y位置dpx = null!; /// <summary> /// 判定文字列(本体)の不透明度。 /// 0 で完全透明、1 で完全不透明。 /// </summary> public Variable 文字列本体の不透明度 = null!; public Variable 文字列本体のX方向拡大率 = null!; public Variable 文字列本体のY方向拡大率 = null!; public Storyboard? 文字列本体のストーリーボード = null; /// <summary> /// 判定文字列(影)の表示されるY座標のオフセット。 /// 表示中央位置dpx.Y からの相対値[dpx]。 /// </summary> public Variable 文字列影の相対Y位置dpx = null!; /// <summary> /// 判定文字列(影)の不透明度。 /// 0 で完全透明、1 で完全不透明。 /// </summary> public Variable 文字列影の不透明度 = null!; public Storyboard? 文字列影のストーリーボード = null; /// <summary> /// 単位は度(degree)、時計回りを正とする。 /// </summary> public Variable 光の回転角 = null!; public Variable 光のX方向拡大率 = null!; public Variable 光のY方向拡大率 = null!; public Storyboard? 光のストーリーボード = null; public 表示レーンステータス( 表示レーン種別 lane ) { this.現在の状態 = 状態.非表示; float x = レーンフレーム.レーン中央位置X[ lane ]; this.表示中央位置dpx = lane switch { 表示レーン種別.LeftCymbal => new Vector2( x, 530f ), 表示レーン種別.HiHat => new Vector2( x, 597f ), 表示レーン種別.Foot => new Vector2( x, 636f ), 表示レーン種別.Snare => new Vector2( x, 597f ), 表示レーン種別.Bass => new Vector2( x, 635f ), 表示レーン種別.Tom1 => new Vector2( x, 561f ), 表示レーン種別.Tom2 => new Vector2( x, 561f ), 表示レーン種別.Tom3 => new Vector2( x, 600f ), 表示レーン種別.RightCymbal => new Vector2( x, 533f ), _ => new Vector2( x, -100f ), }; } public virtual void Dispose() { this.アニメ用メンバを解放する(); this.現在の状態 = 状態.非表示; } public void アニメ用メンバを解放する() { this.文字列本体のストーリーボード?.Dispose(); this.文字列本体の不透明度?.Dispose(); this.文字列本体のY方向拡大率?.Dispose(); this.文字列本体のX方向拡大率?.Dispose(); this.文字列本体の相対Y位置dpx?.Dispose(); this.文字列影のストーリーボード?.Dispose(); this.文字列影の不透明度?.Dispose(); this.文字列影の相対Y位置dpx?.Dispose(); this.光のストーリーボード?.Dispose(); this.光のY方向拡大率?.Dispose(); this.光のX方向拡大率?.Dispose(); this.光の回転角?.Dispose(); } } private readonly Dictionary<表示レーン種別, 表示レーンステータス> _レーンtoステータス; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/オプション設定ステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.オプション設定 { class オプション設定ステージ : IStage { // プロパティ public enum フェーズ { フェードイン, 表示, 入力割り当て, 曲読み込みフォルダ割り当て, 再起動, 再起動待ち, フェードアウト, 完了, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; // 生成と終了 public オプション設定ステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._舞台画像 = new 舞台画像(); this._システム情報 = new システム情報(); this._パネルリスト = new パネルリスト() { 入力割り当てフェーズへ移行する = () => { this.現在のフェーズ = フェーズ.入力割り当て; }, 曲読み込みフォルダ割り当てフェーズへ移行する = () => { this.現在のフェーズ = フェーズ.曲読み込みフォルダ割り当て; }, 再起動フェーズへ移行する = () => { this.現在のフェーズ = フェーズ.再起動; }, フェードアウトフェーズへ移行する = () => { this.現在のフェーズ = フェーズ.フェードアウト; }, }; this._再起動が必要 = false; // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.フェードイン; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パネルリスト.Dispose(); this._システム情報.Dispose(); this._舞台画像.Dispose(); } // 進行と描画 public void 進行する() { this._システム情報.FPSをカウントしプロパティを更新する(); var 入力 = Global.App.ドラム入力; 入力.すべての入力デバイスをポーリングする(); switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " フェードインを開始して表示フェーズへ。" //---------------- if( this._フェードインフェーズ完了 ) { // 表示フェーズへ。 this.現在のフェーズ = フェーズ.表示; } //---------------- #endregion break; } case フェーズ.表示: { #region " 入力処理。" //---------------- if( 入力.キャンセルキーが入力された() ) { #region " キャンセル " //---------------- if( this._パネルリスト.現在のパネルフォルダ.親パネル is null ) { #region " (A) 親ツリーがない → ステージをフェードアウトフェーズへ。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); this._パネルリスト.フェードアウトを開始する(); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( 半回転黒フェード ) ); this.現在のフェーズ = フェーズ.フェードアウト; //---------------- #endregion } else { #region " (B) 親ツリーがある → 親ツリーへ戻る。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); this._パネルリスト.親のパネルを選択する(); this._パネルリスト.フェードインを開始する(); //---------------- #endregion } //---------------- #endregion } else if( 入力.上移動キーが入力された() ) { #region " 上移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._パネルリスト.前のパネルを選択する(); //---------------- #endregion } else if( 入力.下移動キーが入力された() ) { #region " 下移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._パネルリスト.次のパネルを選択する(); //---------------- #endregion } else if( 入力.左移動キーが入力された() ) { #region " 左移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); this._パネルリスト.現在選択中のパネル!.左移動キーが入力された(); //---------------- #endregion } else if( 入力.右移動キーが入力された() ) { #region " 右移動 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); this._パネルリスト.現在選択中のパネル!.右移動キーが入力された(); //---------------- #endregion } else if( 入力.確定キーが入力された() ) { #region " 確定 " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); this._パネルリスト.現在選択中のパネル!.確定キーが入力された(); //---------------- #endregion } //---------------- #endregion break; } case フェーズ.入力割り当て: { #region " 入力割り当てダイアログを表示する。" //---------------- // 入力割り当てダイアログを表示。 var asycnResult = Global.App.BeginInvoke( new Action( () => { using var dlg = new 入力割り当てダイアログ(); Cursor.Show(); // いったんマウスカーソル表示 dlg.表示する(); if( Global.App.ScreenMode.IsFullscreenMode ) Cursor.Hide(); // 全画面ならマウスカーソルを消す。 } ) ); // 入力割り当てダイアログが閉じられるのを待つ。 asycnResult.AsyncWaitHandle.WaitOne(); // 閉じられたら表示フェーズへ。 this._パネルリスト.フェードインを開始する(); this.現在のフェーズ = フェーズ.表示; //---------------- #endregion break; } case フェーズ.曲読み込みフォルダ割り当て: { #region " 曲読み込みフォルダ割り当てダイアログを表示する。" //---------------- var asyncResult = Global.App.BeginInvoke( new Action( () => { using var dlg = new 曲読み込みフォルダ割り当てダイアログ( Global.App.システム設定.曲検索フォルダ ); Cursor.Show(); // いったんマウスカーソル表示 if( dlg.ShowDialog() == DialogResult.OK && dlg.新しい曲検索フォルダリストを取得する( out List<VariablePath> 新フォルダリスト ) ) { // 曲検索フォルダを新しいリストに更新。 Global.App.システム設定.曲検索フォルダ.Clear(); Global.App.システム設定.曲検索フォルダ.AddRange( 新フォルダリスト ); Global.App.システム設定.保存する(); // 再起動へ。 this._再起動が必要 = true; } else { this._再起動が必要 = false; } if( Global.App.ScreenMode.IsFullscreenMode ) Cursor.Hide(); // 全画面ならマウスカーソルを消す。 } ) ); // 曲読み込みフォルダ割り当てダイアログが閉じられるのを待つ。 asyncResult.AsyncWaitHandle.WaitOne(); // 閉じられたら次のフェーズへ。 this.現在のフェーズ = ( this._再起動が必要 ) ? フェーズ.再起動 : フェーズ.表示; //---------------- #endregion break; } case フェーズ.再起動: { #region " UIスレッドで再起動を実行する。" //---------------- Global.App.BeginInvoke( new Action( () => { Global.App.再起動する(); // UIスレッドで実行 } ) ); // 次のフェーズへ。 this.現在のフェーズ = フェーズ.再起動待ち; //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " フェードアウトが完了したら次のフェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) this.現在のフェーズ = フェーズ.完了; //---------------- #endregion break; } case フェーズ.再起動待ち: case フェーズ.完了: { #region " 遷移終了。Appによるステージ遷移を待つ。" //---------------- //---------------- #endregion break; } } #region " 画面モードが外部(F11キーなど)で変更されている場合には、それを「画面モード」パネルにも反映する。" //---------------- { var 画面モードパネル = this._パネルリスト.パネルツリーのルートノード.子パネルリスト .Find( ( p ) => ( p.パネル名 == Properties.Resources.TXT_画面モード ) ) as パネル_文字列リスト; if( 画面モードパネル is null ) // 念のため throw new Exception( "「画面モード」パネルが存在していません。" ); int システム設定上の現在の画面モード = ( Global.App.システム設定.全画面モードである ) ? 1 : 0; // 0:ウィンドウ, 1:全画面 if( 画面モードパネル.現在選択されている選択肢の番号 != システム設定上の現在の画面モード ) 画面モードパネル.現在選択されている選択肢の番号 = システム設定上の現在の画面モード; } //---------------- #endregion } public void 描画する() { this._システム情報.VPSをカウントする(); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = SharpDX.Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " 背景画面を描画し、フェードインを開始して表示フェーズへ。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.オプション設定ステージ_開始音 ); this._舞台画像.ぼかしと縮小を適用する( 0.5 ); this._パネルリスト.フェードインを開始する(); d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); d2ddc.EndDraw(); this._フェードインフェーズ完了 = true; //---------------- #endregion break; } case フェーズ.表示: case フェーズ.入力割り当て: case フェーズ.曲読み込みフォルダ割り当て: case フェーズ.再起動: case フェーズ.再起動待ち: { #region " 背景画面を描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " 背景画面&フェードアウトを描画する。" //---------------- d2ddc.BeginDraw(); this._舞台画像.進行描画する( d2ddc ); this._パネルリスト.進行描画する( d2ddc, 613f, 0f ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); this._システム情報.描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.完了: { break; } } } // ローカル private readonly 舞台画像 _舞台画像; private readonly システム情報 _システム情報; private readonly パネルリスト _パネルリスト; private bool _再起動が必要; private void _背景画面を描画する( DeviceContext d2ddc ) { this._舞台画像.進行描画する( d2ddc ); this._パネルリスト.進行描画する( d2ddc, 613f, 0f ); this._システム情報.描画する( d2ddc ); } private bool _フェードインフェーズ完了 = false; } } <|start_filename|>DTXMania2/ステージ/アイキャッチ/シャッター.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { class シャッター : アイキャッチ { // 生成と終了 public シャッター() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ロゴ = new 画像D2D( @"$(Images)\TitleLogo.png" ); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; this._明るいブラシ = new SolidColorBrush( d2ddc, new Color4( 83f / 255f, 210f / 255f, 255f / 255f, 1f ) ); this._ふつうのブラシ = new SolidColorBrush( d2ddc, new Color4( 46f / 255f, 117f / 255f, 182f / 255f, 1f ) ); this._濃いブラシ = new SolidColorBrush( d2ddc, new Color4( 0f / 255f, 32f / 255f, 96f / 255f, 1f ) ); this._黒ブラシ = new SolidColorBrush( d2ddc, Color4.Black ); this._白ブラシ = new SolidColorBrush( d2ddc, Color4.White ); this._シャッターアニメーション = new シャッター情報[ シャッター枚数 ] { #region " *** " //---------------- new シャッター情報() { // 1 ブラシ = this._明るいブラシ, 矩形サイズ = new Size2F( 910f, 908f ), 角度rad = (float) Math.PI / 4f, 閉じ中心位置 = new Vector2( 0f, 1080f ), 開き中心位置 = new Vector2( 0f-450, 1080f+450f ), 完全開き時刻sec = 0.0, 開閉時間sec = 0.2, }, new シャッター情報() { // 2 ブラシ = this._濃いブラシ, 矩形サイズ = new Size2F( 1000f, 992f ), 角度rad = (float) Math.PI / 4f, 閉じ中心位置 = new Vector2( 1920f, 0f ), 開き中心位置 = new Vector2( 1920f+500f, 0f-500f ), 完全開き時刻sec = 0.03, 開閉時間sec = 0.2, }, new シャッター情報() { // 3 ブラシ = this._黒ブラシ, 矩形サイズ = new Size2F( 915f, 911f ), 角度rad = (float) Math.PI / -4f, 閉じ中心位置 = new Vector2( 0f, 0f ), 開き中心位置 = new Vector2( 0f-450f, 0f-450f ), 完全開き時刻sec = 0.075, 開閉時間sec = 0.2, }, new シャッター情報() { // 4 ブラシ = this._ふつうのブラシ, 矩形サイズ = new Size2F( 884, 885f ), 角度rad = (float) Math.PI / -4f, 閉じ中心位置 = new Vector2( 1920f, 1080f ), 開き中心位置 = new Vector2( 1920f+450f, 1080f+450f ), 完全開き時刻sec = 0.06, 開閉時間sec = 0.2, }, new シャッター情報() { // 5 ブラシ = this._濃いブラシ, 矩形サイズ = new Size2F( 370f, 740f ), 角度rad = (float) 0f, 閉じ中心位置 = new Vector2( 104f+185f, 541f ), 開き中心位置 = new Vector2( 104f+185f-500f, 541f ), 完全開き時刻sec = 0.16, 開閉時間sec = 0.2, }, new シャッター情報() { // 6 ブラシ = this._黒ブラシ, 矩形サイズ = new Size2F( 280f, 560f ), 角度rad = (float) 0f, 閉じ中心位置 = new Vector2( 1519+140f, 570f ), 開き中心位置 = new Vector2( 1519+140f+400f, 570f ), 完全開き時刻sec = 0.2, 開閉時間sec = 0.2, }, new シャッター情報() { // 7 ブラシ = this._明るいブラシ, 矩形サイズ = new Size2F( 780f, 788f ), 角度rad = (float) Math.PI / 4f, 閉じ中心位置 = new Vector2( 1521f, 1080f ), 開き中心位置 = new Vector2( 1521f+390f, 1080f+390f ), 完全開き時刻sec = 0.2, 開閉時間sec = 0.2, }, new シャッター情報() { // 8 ブラシ = this._黒ブラシ, 矩形サイズ = new Size2F( 1114f, 495f ), 角度rad = (float) Math.PI / 4f, 閉じ中心位置 = new Vector2( 1236f, 178f ), 開き中心位置 = new Vector2( 1236f+400f, 178f-400f ), 完全開き時刻sec = 0.23, 開閉時間sec = 0.2, }, new シャッター情報() { // 9 ブラシ = this._黒ブラシ, 矩形サイズ = new Size2F( 652f, 312f ), 角度rad = (float) 0f, 閉じ中心位置 = new Vector2( 479f+323f, 1080f ), 開き中心位置 = new Vector2( 479f+323f, 1080f+160f ), 完全開き時刻sec = 0.3, 開閉時間sec = 0.2, }, new シャッター情報() { // 10 ブラシ = this._ふつうのブラシ, 矩形サイズ = new Size2F( 412f, 288f ), 角度rad = (float) 0f, 閉じ中心位置 = new Vector2( 666f, 0f ), 開き中心位置 = new Vector2( 666f, 0f-200f ), 完全開き時刻sec = 0.33, 開閉時間sec = 0.2, }, new シャッター情報() { // 11 ブラシ = this._黒ブラシ, 矩形サイズ = new Size2F( 630f, 630f ), 角度rad = (float) Math.PI / 4f, 閉じ中心位置 = new Vector2( 460f, 930f ), 開き中心位置 = new Vector2( 460f-330f, 930f+330f ), 完全開き時刻sec = 0.36, 開閉時間sec = 0.2, }, new シャッター情報() { // 12 ブラシ = this._明るいブラシ, 矩形サイズ = new Size2F( 875f, 884f ), 角度rad = (float) Math.PI / -4f, 閉じ中心位置 = new Vector2( 461f, 138f ), 開き中心位置 = new Vector2( 461f-438f, 138f-438f ), 完全開き時刻sec = 0.36, 開閉時間sec = 0.2, }, new シャッター情報() { // 13 ブラシ = this._濃いブラシ, 矩形サイズ = new Size2F( 460f, 690f ), 角度rad = (float) 0f, 閉じ中心位置 = new Vector2( 915f+230f, 253f+325f ), 開き中心位置 = new Vector2( 915f+230f+480f, 253f+325f ), 完全開き時刻sec = 0.4, 開閉時間sec = 0.2, }, new シャッター情報() { // 14 ブラシ = this._ふつうのブラシ, 矩形サイズ = new Size2F( 340f, 620f ), 角度rad = (float) 0f, 閉じ中心位置 = new Vector2( 614f+150f, 620f ), 開き中心位置 = new Vector2( 614f+150f-670f, 620f ), 完全開き時刻sec = 0.40, 開閉時間sec = 0.2, }, //---------------- #endregion }; //for( int i = 0; i < シャッター枚数; i++ ) // this._シャッター情報[ i ].開to閉割合 = new Variable( gd.Animation.Manager, initialValue: 0.0 ); //this._ロゴ不透明度 = new Variable( gd.Animation.Manager, initialValue: 0.0 ); // // --> クローズかオープンかで初期値が変わるので、ここでは設定しない。 this.現在のフェーズ = フェーズ.未定; } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._白ブラシ.Dispose(); this._黒ブラシ.Dispose(); this._濃いブラシ.Dispose(); this._ふつうのブラシ.Dispose(); this._明るいブラシ.Dispose(); foreach( var s in this._シャッターアニメーション ) s.Dispose(); this._ロゴボード?.Dispose(); this._ロゴ不透明度?.Dispose(); this._ロゴ.Dispose(); base.Dispose(); } // オープンとクローズ /// <summary> /// アイキャッチのクローズアニメーションを開始する。 /// </summary> public override void クローズする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; var start = animation.Timer.Time; for( int i = 0; i < シャッター枚数; i++ ) { using var 開閉遷移 = animation.TrasitionLibrary.SmoothStop( maximumDuration: 秒( this._シャッターアニメーション[ i ].開閉時間sec ), finalValue: 1.0 ); // 終了値 1.0(完全閉じ) this._シャッターアニメーション[ i ].開to閉割合?.Dispose(); this._シャッターアニメーション[ i ].開to閉割合 = new Variable( animation.Manager, initialValue: 0.0 ); // 初期値 0.0(完全開き) this._シャッターアニメーション[ i ].ストーリーボード?.Dispose(); this._シャッターアニメーション[ i ].ストーリーボード = new Storyboard( animation.Manager ); this._シャッターアニメーション[ i ].ストーリーボード.AddTransition( this._シャッターアニメーション[ i ].開to閉割合, 開閉遷移 ); this._シャッターアニメーション[ i ].ストーリーボード.Schedule( start + 秒( this._シャッターアニメーション[ i ].完全開き時刻sec ) ); // 開始時刻: 完全開き時刻 } using var _不透明度遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.75f ), finalValue: 1.0 ); // 終了値 1.0(完全不透明) this._ロゴ不透明度?.Dispose(); this._ロゴ不透明度 = new Variable( animation.Manager, initialValue: 0.0 ); // 初期値 0.0(完全透明) this._ロゴボード = new Storyboard( animation.Manager ); this._ロゴボード.AddTransition( this._ロゴ不透明度, _不透明度遷移 ); this._ロゴボード.Schedule( start ); this.現在のフェーズ = フェーズ.クローズ; } /// <summary> /// アイキャッチのオープンアニメーションを開始する。 /// </summary> public override void オープンする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; double 最も遅い時刻sec = 0.0; foreach( var s in this._シャッターアニメーション ) { if( 最も遅い時刻sec < s.完全閉じ時刻sec ) 最も遅い時刻sec = s.完全閉じ時刻sec; } var start = animation.Timer.Time; var end = start + 秒( 最も遅い時刻sec ); for( int i = 0; i < シャッター枚数; i++ ) { using var 開閉遷移 = animation.TrasitionLibrary.SmoothStop( maximumDuration: 秒( this._シャッターアニメーション[ i ].開閉時間sec ), finalValue: 0.0 ); // 終了値: 0.0(完全開き) this._シャッターアニメーション[ i ].開to閉割合?.Dispose(); this._シャッターアニメーション[ i ].開to閉割合 = new Variable( animation.Manager, initialValue: 1.0 ); // 初期値 1.0(完全閉じ) this._シャッターアニメーション[ i ].ストーリーボード?.Dispose(); this._シャッターアニメーション[ i ].ストーリーボード = new Storyboard( animation.Manager ); this._シャッターアニメーション[ i ].ストーリーボード.AddTransition( this._シャッターアニメーション[ i ].開to閉割合, 開閉遷移 ); this._シャッターアニメーション[ i ].ストーリーボード.Schedule( end - 秒( this._シャッターアニメーション[ i ].完全閉じ時刻sec ) ); // 開始時刻: 完全閉じ時刻 } this._ロゴ不透明度?.Dispose(); this._ロゴ不透明度 = new Variable( animation.Manager, initialValue: 1.0 ); // 初期値 0.0(完全不透明) using var _不透明度遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.75 ), finalValue: 0.0 ); // 終了値 0.0(完全透明) this._ロゴボード = new Storyboard( animation.Manager ); this._ロゴボード.AddTransition( this._ロゴ不透明度, _不透明度遷移 ); this._ロゴボード.Schedule( start ); this.現在のフェーズ = フェーズ.オープン; } // 進行と描画 /// <summary> /// アイキャッチのアニメーションを進行し、アイキャッチ画像を描画する。 /// </summary> protected override void 進行描画する( DeviceContext d2ddc, StoryboardStatus 描画しないStatus ) { bool すべて完了 = true; var preTrans = d2ddc.Transform; #region " シャッター " //---------------- for( int i = シャッター枚数 - 1; i >= 0; i-- ) { var context = this._シャッターアニメーション[ i ]; if( context.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード.Status == 描画しないStatus ) continue; d2ddc.Transform = Matrix3x2.Rotation( context.角度rad ) * Matrix3x2.Translation( context.開き中心位置 + ( context.閉じ中心位置 - context.開き中心位置 ) * new Vector2( (float)context.開to閉割合.Value ) ) * preTrans; float w = context.矩形サイズ.Width; float h = context.矩形サイズ.Height; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.FillRectangle( rc, context.ブラシ ); d2ddc.DrawRectangle( rc, this._白ブラシ, 3.0f ); } d2ddc.Transform = preTrans; //---------------- #endregion if( null != this._ロゴ不透明度 ) { #region " ロゴ " //---------------- if( this._ロゴボード.Status != StoryboardStatus.Ready ) すべて完了 = false; float 倍率 = this._ロゴ表示幅 / this._ロゴ.サイズ.Width; this._ロゴ.描画する( d2ddc, this._ロゴ表示位置.Width, this._ロゴ表示位置.Height, 不透明度0to1: (float)this._ロゴ不透明度.Value, X方向拡大率: 倍率, Y方向拡大率: 倍率 ); //---------------- #endregion } if( すべて完了 ) { if( this.現在のフェーズ == フェーズ.クローズ ) { this.現在のフェーズ = フェーズ.クローズ完了; } else if( this.現在のフェーズ == フェーズ.オープン ) { this.現在のフェーズ = フェーズ.オープン完了; } } } // ローカル private class シャッター情報 : IDisposable { public Brush ブラシ = null!; public Size2F 矩形サイズ; public float 角度rad; public Vector2 閉じ中心位置; public Vector2 開き中心位置; /// <summary> /// 開き: 0.0 → 1.0: 閉じ /// </summary> public Variable 開to閉割合 = null!; public double 完全開き時刻sec = 0.0; public double 開閉時間sec = 1.0; public double 完全閉じ時刻sec => this.完全開き時刻sec + 開閉時間sec; public Storyboard ストーリーボード = null!; public シャッター情報() { } public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.開to閉割合?.Dispose(); } } private const int シャッター枚数 = 14; private readonly シャッター情報[] _シャッターアニメーション; private readonly Brush _明るいブラシ; private readonly Brush _ふつうのブラシ; private readonly Brush _濃いブラシ; private readonly Brush _黒ブラシ; private readonly Brush _白ブラシ; private readonly 画像D2D _ロゴ; private Variable _ロゴ不透明度 = null!; private Storyboard _ロゴボード = null!; private readonly Size2F _ロゴ表示位置 = new Size2F( 1100f, 800f ); private readonly float _ロゴ表示幅 = 730f; } } <|start_filename|>DTXMania2/ステージ/01起動/起動ステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Forms; using FDK; namespace DTXMania2.起動 { class 起動ステージ : IStage { // プロパティ public enum フェーズ { 開始, グローバルリソース生成中, システムサウンド構築開始, システムサウンド構築完了待ち, 曲ツリー構築開始, 曲ツリー構築完了待ち, 曲ツリーDB反映開始, 曲ツリーDB反映完了待ち, 曲ツリー文字列画像生成開始, 曲ツリー文字列画像生成完了待ち, 開始音終了待ち開始, 開始音終了待ち, 完了, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; // 生成と終了 public 起動ステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); if( !Global.Options.ビュアーモードである ) { // この2つを先行読み込み。残りはシステムサウンド構築フェーズにて。 Global.App.システムサウンド.読み込む( Global.App.サウンドデバイス, システムサウンド種別.起動ステージ_開始音 ); Global.App.システムサウンド.読み込む( Global.App.サウンドデバイス, システムサウンド種別.起動ステージ_ループBGM ); // さっそく再生。 Global.App.システムサウンド.再生する( システムサウンド種別.起動ステージ_開始音 ); Global.App.システムサウンド.再生する( システムサウンド種別.起動ステージ_ループBGM, ループ再生する: true ); } else { // ビュアーモードならシステムサウンドなし。 } this._コンソールフォント = new フォント画像D2D( @"$(Images)\ConsoleFont20x32.png", @"$(Images)\ConsoleFont20x32.yaml", 文字幅補正dpx: -6f ); var copyrights = (AssemblyCopyrightAttribute[])Assembly.GetExecutingAssembly() .GetCustomAttributes( typeof( AssemblyCopyrightAttribute ), false ); this._コンソール表示内容 = new List<string>() { $"{Application.ProductName} Release {int.Parse( Application.ProductVersion.Split( '.' ).ElementAt( 0 ) ):000} - Beats with your heart.", $"{copyrights[ 0 ].Copyright}", $"", }; // 最初のフェーズへ。 this._コンソール表示内容.Add( "Boot..." ); this.現在のフェーズ = フェーズ.開始; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); Global.App.システムサウンド.停止する( システムサウンド種別.起動ステージ_開始音 ); Global.App.システムサウンド.停止する( システムサウンド種別.起動ステージ_ループBGM ); this._コンソールフォント.Dispose(); } // 進行と描画 public void 進行する() { switch( this.現在のフェーズ ) { case フェーズ.開始: { #region " 一度描画処理を通してから(画面を表示させてから)次のフェーズへ。" //---------------- this._コンソール表示内容[ ^1 ] += " done."; // 次のフェーズへ。 this._コンソール表示内容.Add( "Creating global resources..." ); this.現在のフェーズ = フェーズ.グローバルリソース生成中; break; //---------------- #endregion } case フェーズ.グローバルリソース生成中: { #region " グローバルリソースを生成して次のフェーズへ。" //---------------- //Global.App.グローバルリソースを作成する(); --> 今は何もしない。全部作成済み。 this._コンソール表示内容[ ^1 ] += " done."; // 次のフェーズへ。 this.現在のフェーズ = フェーズ.システムサウンド構築開始; break; //---------------- #endregion } case フェーズ.システムサウンド構築開始: { #region " システムサウンドの構築を開始して次のフェーズへ。" //---------------- // 次のフェーズへ。 this._コンソール表示内容.Add( "Creating system sounds..." ); this.現在のフェーズ = フェーズ.システムサウンド構築完了待ち; break; //---------------- #endregion } case フェーズ.システムサウンド構築完了待ち: { #region " システムサウンドを構築して次のフェーズへ。" //---------------- Global.App.システムサウンド.すべて生成する( Global.App.サウンドデバイス ); Log.Info( "システムサウンドの読み込みが完了しました。" ); Global.App.ドラムサウンド.すべて生成する( Global.App.サウンドデバイス ); Log.Info( "ドラムサウンドの読み込みが完了しました。" ); this._コンソール表示内容[ ^1 ] += " done."; // 次のフェーズへ。 this.現在のフェーズ = ( Global.Options.ビュアーモードである ) ? フェーズ.開始音終了待ち開始 : フェーズ.曲ツリー構築開始; break; //---------------- #endregion } case フェーズ.曲ツリー構築開始: { #region " 曲ツリーの構築を開始して次のフェーズへ。" //---------------- this._コンソール表示内容.Add( "Enumeration songs..." ); var allTree = new 曲.曲ツリー_全曲(); var ratingTree = new 曲.曲ツリー_評価順(); Global.App.曲ツリーリスト.Add( allTree ); Global.App.曲ツリーリスト.Add( ratingTree ); Global.App.曲ツリーリスト.SelectFirst(); 曲.Song.現在の難易度レベル = () => Global.App.曲ツリーリスト.SelectedItem!.フォーカス難易度レベル; // 全曲ツリーの構築を開始する。(現行化はまだ) this._曲ツリー構築タスク = allTree.構築するAsync( Global.App.システム設定.曲検索フォルダ ); // 評価順ツリーの構築は、ユーザのログオン時に行う。 // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲ツリー構築完了待ち; break; //---------------- #endregion } case フェーズ.曲ツリー構築完了待ち: { #region " 曲ツリーの構築の完了を待って、次のフェーズへ。" //---------------- if( !this._曲ツリー構築タスク.IsCompleted ) { // 進捗カウンタを表示。 var allTree = (曲.曲ツリー_全曲)Global.App.曲ツリーリスト[ 0 ]; this._コンソール表示内容[ ^1 ] = $"Enumeration songs... {allTree.進捗カウンタ}"; } else { this._コンソール表示内容[ ^1 ] += ", done."; // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲ツリーDB反映開始; } break; //---------------- #endregion } case フェーズ.曲ツリーDB反映開始: { #region " 曲ツリーへのDB反映を開始して次のフェーズへ。" //---------------- this._コンソール表示内容.Add( "Update songs..." ); var allTree = (曲.曲ツリー_全曲)Global.App.曲ツリーリスト[ 0 ]; this._曲ツリーDB反映タスク = allTree.ノードにDBを反映するAsync(); // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲ツリーDB反映完了待ち; break; //---------------- #endregion } case フェーズ.曲ツリーDB反映完了待ち: { #region " 曲ツリーのDB反映の完了を待って、次のフェーズへ。" //---------------- if( !this._曲ツリーDB反映タスク.IsCompleted ) { // 進捗カウンタを表示。 var allTree = (曲.曲ツリー_全曲)Global.App.曲ツリーリスト[ 0 ]; this._コンソール表示内容[ ^1 ] = $"Update songs... {allTree.進捗カウンタ}"; } else { this._コンソール表示内容[ ^1 ] += ", done."; // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲ツリー文字列画像生成開始; } break; //---------------- #endregion } case フェーズ.曲ツリー文字列画像生成開始: { #region " 曲ツリーの文字列画像の生成を開始して次のフェーズへ。" //---------------- this._コンソール表示内容.Add( "Building label images..." ); var allTree = (曲.曲ツリー_全曲)Global.App.曲ツリーリスト[ 0 ]; this._曲ツリー文字列画像生成タスク = allTree.文字列画像を生成するAsync(); // 次のフェーズへ。 this.現在のフェーズ = フェーズ.曲ツリー文字列画像生成完了待ち; break; //---------------- #endregion } case フェーズ.曲ツリー文字列画像生成完了待ち: { #region " 曲ツリーの文字列画像生成の完了を待って、次のフェーズへ。" //---------------- if( !this._曲ツリー文字列画像生成タスク.IsCompleted ) { // 進捗カウンタを表示。 var allTree = (曲.曲ツリー_全曲)Global.App.曲ツリーリスト[ 0 ]; this._コンソール表示内容[ ^1 ] = $"Building label images... {allTree.進捗カウンタ}"; } else { this._コンソール表示内容[ ^1 ] += ", done."; // 次のフェーズへ。 this.現在のフェーズ = フェーズ.開始音終了待ち開始; } break; //---------------- #endregion } case フェーズ.開始音終了待ち開始: { #region " 開始音の終了待ちを開始して次のフェーズへ。" //---------------- this._コンソール表示内容.Add( "All setup done." ); // 次のフェーズへ。 this.現在のフェーズ = フェーズ.開始音終了待ち; break; //---------------- #endregion } case フェーズ.開始音終了待ち: { #region " 開始音が鳴り止むのを待って、次のフェーズへ。" //---------------- // 開始音がまだ鳴っていれば、終了するまで待つ。 if( !Global.App.システムサウンド.再生中( システムサウンド種別.起動ステージ_開始音 ) ) { // 再生が終わったので次のフェーズへ。 this.現在のフェーズ = フェーズ.完了; } break; //---------------- #endregion } case フェーズ.完了: { #region " 遷移終了。Appによるステージ遷移を待つ。" //---------------- break; //---------------- #endregion } } } public void 描画する() { Global.App.画面をクリアする(); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = SharpDX.Matrix3x2.Identity; d2ddc.BeginDraw(); #region " 文字列表示 " //---------------- for( int i = 0; i < this._コンソール表示内容.Count; i++ ) this._コンソールフォント.描画する( d2ddc, 0f, i * 32f, this._コンソール表示内容[ i ] ); //---------------- #endregion d2ddc.EndDraw(); } // ローカル private readonly フォント画像D2D _コンソールフォント; private readonly List<string> _コンソール表示内容 = new List<string>(); private Task _曲ツリー構築タスク = null!; private Task _曲ツリーDB反映タスク = null!; private Task _曲ツリー文字列画像生成タスク = null!; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/曲読み込みフォルダ割り当てダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; using FDK; namespace DTXMania2.オプション設定 { partial class 曲読み込みフォルダ割り当てダイアログ : Form { // 生成と終了 public 曲読み込みフォルダ割り当てダイアログ( IReadOnlyList<VariablePath> 現在の曲検索フォルダリスト ) : base() { InitializeComponent(); foreach( var path in 現在の曲検索フォルダリスト ) this.listViewフォルダ一覧.Items.Add( new ListViewItem( $"{path.変数なしパス}" ) ); // ここでは変数なしでパスを表示する。 } private void 曲読み込みフォルダ割り当てダイアログ_FormClosing( object sender, FormClosingEventArgs e ) { if( this.DialogResult == DialogResult.Cancel ) // ウィンドウを閉じようとした時も Cancel になる。 { if( this._リストに変更がある ) { if( MessageBox.Show( Properties.Resources.TXT_変更を破棄していいですか, Properties.Resources.TXT_確認, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2 ) == DialogResult.No ) { e.Cancel = true; } } } } /// <summary> /// 結果取得。変更があったら true を返す。 /// </summary> public bool 新しい曲検索フォルダリストを取得する( out List<VariablePath> 新しいフォルダリスト ) { 新しいフォルダリスト = new List<VariablePath>(); foreach( ListViewItem? item in this.listViewフォルダ一覧.Items ) { if( null != item ) 新しいフォルダリスト.Add( new VariablePath( item.SubItems[ 0 ].Text ) ); } return this._リストに変更がある; } // その他GUIイベント private void listViewフォルダ一覧_SelectedIndexChanged( object sender, EventArgs e ) { if( 0 < this.listViewフォルダ一覧.SelectedItems.Count ) { // フォルダが選択されたので、削除ボタンを有効化。 this.button削除.Enabled = true; } else { // フォルダの選択が解除されたので、削除ボタンを無効化。 this.button削除.Enabled = false; } } private void button選択_Click( object sender, EventArgs e ) { // フォルダ選択ダイアログを生成する。 using( var folderBrowser = new FolderBrowserDialog() { Description = "追加するフォルダを選択してください。", } ) { // フォルダ選択ダイアログを表示する。 if( folderBrowser.ShowDialog( this ) == DialogResult.OK ) { // OK押下なら、選択されたフォルダを曲読み込みフォルダリストに追加して再表示する。 var vpath = new VariablePath( folderBrowser.SelectedPath ); this.listViewフォルダ一覧.Items.Add( new ListViewItem( $"{vpath.変数なしパス}" ) ); this.listViewフォルダ一覧.Refresh(); this._リストに変更がある = true; } } } private void button削除_Click( object sender, EventArgs e ) { // 選択されたフォルダを曲読み込みフォルダリストから削除して再表示する。 foreach( int? selectedIndex in this.listViewフォルダ一覧.SelectedIndices ) { if( selectedIndex.HasValue ) this.listViewフォルダ一覧.Items.RemoveAt( selectedIndex.Value ); } this.listViewフォルダ一覧.Refresh(); this._リストに変更がある = true; } // ローカル private bool _リストに変更がある = false; } } <|start_filename|>FDK/TraceValue.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Animation; namespace FDK { /// <summary> /// 一定速度(Linear遷移)で目標値へ近づく double 値。 /// </summary> public class TraceValue : IDisposable { // プロパティ public double 目標値 { get => this._目標値; set { this._目標値 = value; this._追従値アニメを再構築する(); } } public double 現在値 => this._現在値.Value; public double 切替時間sec { get; } public double 速度係数 { get; } // 生成と終了 public TraceValue( Animation animation, double 初期値, double 切替時間sec, double 速度係数 = 1.0 ) { this._Animation = animation; this._目標値 = 初期値; this._現在値 = new Variable( this._Animation.Manager, (double)初期値 ); this.切替時間sec = 切替時間sec; this.速度係数 = 速度係数; this._ストーリーボード = null!; } public virtual void Dispose() { this._ストーリーボード?.Dispose(); this._現在値?.Dispose(); } // ローカル private readonly Animation _Animation; private readonly Variable _現在値; private double _目標値; private Storyboard _ストーリーボード; private void _追従値アニメを再構築する() { this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( this._Animation.Manager ); using( var 遷移 = this._Animation.TrasitionLibrary.Linear( this.切替時間sec, finalValue: (double)this._目標値 ) ) this._ストーリーボード.AddTransition( this._現在値, 遷移 ); this._ストーリーボード.Schedule( this._Animation.Timer.Time ); } } } <|start_filename|>DTXMania2/ステージ/06曲読み込み/難易度.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using FDK; using DTXMania2.曲; namespace DTXMania2.曲読み込み { class 難易度 : IDisposable { // 生成と終了 public 難易度() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_Large.png", @"$(Images)\ParameterFont_Large.yaml", 文字幅補正dpx: 0f ); this._見出し用TextFormat = new TextFormat( Global.GraphicResources.DWriteFactory, "Century Gothic", 50f ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._見出し用TextFormat.Dispose(); this._数字画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { var 見出し描画領域 = new RectangleF( 783f, 117f, 414f, 63f ); var 数値描画領域 = new RectangleF( 783f, 180f, 414f, 213f ); // 難易度のラベルと値を描画する。 using var 見出し背景ブラシ = new SolidColorBrush( d2ddc, Song.難易度色リスト[ Global.App.曲ツリーリスト.SelectedItem!.フォーカス難易度レベル ] ); using var 黒ブラシ = new SolidColorBrush( d2ddc, Color4.Black ); using var 黒透過ブラシ = new SolidColorBrush( d2ddc, new Color4( Color3.Black, 0.5f ) ); using var 白ブラシ = new SolidColorBrush( d2ddc, Color4.White ); // 背景領域を塗りつぶす。 d2ddc.FillRectangle( 見出し描画領域, 見出し背景ブラシ ); d2ddc.FillRectangle( 数値描画領域, 黒ブラシ ); // 見出し文字列を描画する。 this._見出し用TextFormat.TextAlignment = TextAlignment.Trailing; var 見出し文字領域 = 見出し描画領域; 見出し文字領域.Width -= 8f; // 右マージン d2ddc.DrawText( Global.App.演奏譜面.難易度ラベル, this._見出し用TextFormat, 見出し文字領域, 白ブラシ ); // 小数部を描画する。 var 数値文字列 = Global.App.演奏譜面.譜面.Level.ToString( "0.00" ).PadLeft( 1 ); this._数字画像.描画する( d2ddc, 数値描画領域.X + 175f, 数値描画領域.Y, 数値文字列.Substring( 2 ), new Size2F( 2.2f, 2.2f ) ); // 整数部と小数点を描画する。 this._数字画像.描画する( d2ddc, 数値描画領域.X + 15f, 数値描画領域.Y, 数値文字列.Substring( 0, 2 ), new Size2F( 2.2f, 2.2f ) ); } // ローカル private readonly フォント画像D2D _数字画像; private readonly TextFormat _見出し用TextFormat; } } <|start_filename|>DTXMania2/保存データ/ユーザ設定.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2 { class ユーザ設定 { /// <summary> /// ユーザID。 /// null ならこのインスタンスはどのユーザにも割り当てられていないことを示す。 /// </summary> public string? ID => this._UserConfig.Id; public string 名前 => this._UserConfig.Name; public double 譜面スクロール速度 { get => this._UserConfig.ScrollSpeed; set => this._UserConfig.ScrollSpeed = value; } public bool シンバルフリーモードである { get => ( 0 != this._UserConfig.CymbalFree ); set => this._UserConfig.CymbalFree = value ? 1 : 0; } public bool AutoPlayがすべてONである => this.AutoPlay.All( ( kvp ) => kvp.Value ); public Dictionary<演奏.AutoPlay種別, bool> AutoPlay { get; protected set; } /// <summary> /// チップがヒット判定バーから(上または下に)どれだけ離れていると Perfect ~ Ok 判定になるのかの定義。秒単位。 /// </summary> public Dictionary<演奏.判定種別, double> 最大ヒット距離sec { get; set; } public 演奏.ドラムチッププロパティリスト ドラムチッププロパティリスト { get; protected set; } public 演奏.表示レーンの左右 表示レーンの左右 { get { return new 演奏.表示レーンの左右() { Rideは左 = ( this._UserConfig.RideLeft != 0 ), Chinaは左 = ( this._UserConfig.ChinaLeft != 0 ), Splashは左 = ( this._UserConfig.SplashLeft != 0 ), }; } set { this._UserConfig.RideLeft = ( value.Rideは左 ) ? 1 : 0; this._UserConfig.ChinaLeft = ( value.Chinaは左 ) ? 1 : 0; this._UserConfig.SplashLeft = ( value.Splashは左 ) ? 1 : 0; } } public bool ドラムの音を発声する { get => ( 0 != this._UserConfig.DrumSound ); set => this._UserConfig.DrumSound = value ? 1 : 0; } public int レーンの透明度 { get => this._UserConfig.LaneTrans; set => this._UserConfig.LaneTrans = value; } public bool 演奏中に動画を表示する { get => ( 0 != this._UserConfig.BackgroundMovie ); set => this._UserConfig.BackgroundMovie = value ? 1 : 0; } public double 再生速度 { get => this._UserConfig.PlaySpeed; set => this._UserConfig.PlaySpeed = value; } public bool 演奏中に小節線と拍線を表示する { get => ( 0 != this._UserConfig.ShowPartLine ); set => this._UserConfig.ShowPartLine = value ? 1 : 0; } public bool 演奏中に小節番号を表示する { get => ( 0 != this._UserConfig.ShowPartNumber ); set => this._UserConfig.ShowPartNumber = value ? 1 : 0; } public bool スコア指定の背景画像を表示する { get => ( 0 != this._UserConfig.ShowScoreWall ); set => this._UserConfig.ShowScoreWall = value ? 1 : 0; } public 演奏.動画の表示サイズ 動画の表示サイズ { get => (演奏.動画の表示サイズ)this._UserConfig.BackgroundMovieSize; set => this._UserConfig.BackgroundMovieSize = (int)value; } public bool 演奏中に判定FastSlowを表示する { get => ( 0 != this._UserConfig.ShowFastSlow ); set => this._UserConfig.ShowFastSlow = value ? 1 : 0; } public bool 音量に応じてチップサイズを変更する { get => ( 0 != this._UserConfig.NoteSizeByVolume ); set => this._UserConfig.NoteSizeByVolume = value ? 1 : 0; } public 演奏.ダーク種別 ダーク { get => (演奏.ダーク種別)this._UserConfig.Dark; set => this._UserConfig.Dark = (int)value; } // 生成と終了 public ユーザ設定() { this.AutoPlay = new Dictionary<演奏.AutoPlay種別, bool>() { { 演奏.AutoPlay種別.Unknown, true }, { 演奏.AutoPlay種別.LeftCrash, false }, { 演奏.AutoPlay種別.HiHat, false }, { 演奏.AutoPlay種別.Foot, false }, { 演奏.AutoPlay種別.Snare, false }, { 演奏.AutoPlay種別.Bass, false }, { 演奏.AutoPlay種別.Tom1, false }, { 演奏.AutoPlay種別.Tom2, false }, { 演奏.AutoPlay種別.Tom3, false }, { 演奏.AutoPlay種別.RightCrash, false }, }; this.最大ヒット距離sec = new Dictionary<演奏.判定種別, double>() { { 演奏.判定種別.PERFECT, 0.034 }, { 演奏.判定種別.GREAT, 0.067 }, { 演奏.判定種別.GOOD, 0.084 }, { 演奏.判定種別.OK, 0.117 }, }; this.ドラムチッププロパティリスト = new 演奏.ドラムチッププロパティリスト( new 演奏.表示レーンの左右() { Chinaは左 = false, Rideは左 = false, Splashは左 = true, }, 演奏.入力グループプリセット種別.基本形 ); this._UserConfig = new UserConfig(); this._UserConfigから反映する(); } public static ユーザ設定 読み込む( string user_id ) { var config = new ユーザ設定(); config._UserConfig = UserConfig.読み込む( user_id ); config._UserConfigから反映する(); return config; } public void 保存する() { this._UserConfigへ反映する(); this._UserConfig.保存する(); } // ローカル private UserConfig _UserConfig; private void _UserConfigから反映する() { this.AutoPlay = new Dictionary<演奏.AutoPlay種別, bool>() { { 演奏.AutoPlay種別.Unknown, true }, { 演奏.AutoPlay種別.LeftCrash, ( this._UserConfig.AutoPlay_LeftCymbal != 0 ) }, { 演奏.AutoPlay種別.HiHat, ( this._UserConfig.AutoPlay_HiHat != 0 ) }, { 演奏.AutoPlay種別.Foot, ( this._UserConfig.AutoPlay_LeftPedal != 0 ) }, { 演奏.AutoPlay種別.Snare, ( this._UserConfig.AutoPlay_Snare != 0 ) }, { 演奏.AutoPlay種別.Bass, ( this._UserConfig.AutoPlay_Bass != 0 ) }, { 演奏.AutoPlay種別.Tom1, ( this._UserConfig.AutoPlay_HighTom != 0 ) }, { 演奏.AutoPlay種別.Tom2, ( this._UserConfig.AutoPlay_LowTom != 0 ) }, { 演奏.AutoPlay種別.Tom3, ( this._UserConfig.AutoPlay_FloorTom != 0 ) }, { 演奏.AutoPlay種別.RightCrash, ( this._UserConfig.AutoPlay_RightCymbal != 0 ) }, }; this.最大ヒット距離sec = new HookedDictionary<演奏.判定種別, double>() { { 演奏.判定種別.PERFECT, this._UserConfig.MaxRange_Perfect }, { 演奏.判定種別.GREAT, this._UserConfig.MaxRange_Great }, { 演奏.判定種別.GOOD, this._UserConfig.MaxRange_Good }, { 演奏.判定種別.OK, this._UserConfig.MaxRange_Ok }, }; this.ドラムチッププロパティリスト.反映する( this.表示レーンの左右 ); this.ドラムチッププロパティリスト.反映する( ( this.シンバルフリーモードである ) ? 演奏.入力グループプリセット種別.シンバルフリー : 演奏.入力グループプリセット種別.基本形 ); } private void _UserConfigへ反映する() { this._UserConfig.AutoPlay_LeftCymbal = this.AutoPlay[ 演奏.AutoPlay種別.LeftCrash ] ? 1 : 0; this._UserConfig.AutoPlay_HiHat = this.AutoPlay[ 演奏.AutoPlay種別.HiHat ] ? 1 : 0; this._UserConfig.AutoPlay_LeftPedal = this.AutoPlay[ 演奏.AutoPlay種別.Foot ] ? 1 : 0; this._UserConfig.AutoPlay_Snare = this.AutoPlay[ 演奏.AutoPlay種別.Snare ] ? 1 : 0; this._UserConfig.AutoPlay_Bass = this.AutoPlay[ 演奏.AutoPlay種別.Bass ] ? 1 : 0; this._UserConfig.AutoPlay_HighTom = this.AutoPlay[ 演奏.AutoPlay種別.Tom1 ] ? 1 : 0; this._UserConfig.AutoPlay_LowTom = this.AutoPlay[ 演奏.AutoPlay種別.Tom2 ] ? 1 : 0; this._UserConfig.AutoPlay_FloorTom = this.AutoPlay[ 演奏.AutoPlay種別.Tom3 ] ? 1 : 0; this._UserConfig.AutoPlay_RightCymbal = this.AutoPlay[ 演奏.AutoPlay種別.RightCrash ] ? 1 : 0; this._UserConfig.MaxRange_Perfect = this.最大ヒット距離sec[ 演奏.判定種別.PERFECT ]; this._UserConfig.MaxRange_Great = this.最大ヒット距離sec[ 演奏.判定種別.GREAT ]; this._UserConfig.MaxRange_Good = this.最大ヒット距離sec[ 演奏.判定種別.GOOD ]; this._UserConfig.MaxRange_Ok = this.最大ヒット距離sec[ 演奏.判定種別.OK ]; this._UserConfig.CymbalFree = ( this.ドラムチッププロパティリスト.入力グループプリセット種別 == 演奏.入力グループプリセット種別.シンバルフリー ) ? 1 : 0; } } } <|start_filename|>DTXMania2/保存データ/ScorePropertiesDB/ScorePropertiesDB.Update.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2 { partial class ScorePropertiesDB { public static void 最新版にバージョンアップする() { using var _ = new LogBlock( Log.現在のメソッド名 ); // DBのバージョンを取得。 using var db = new ScorePropertiesDB(); int version = (int)db.UserVersion; while( version < ScorePropertiesDBRecord.VERSION ) { switch( version ) { case 0: case 1: { #region " 0, 1 → 最新版 " //---------------- // 最新バージョンのテーブルを作成する。内容は空。 using var cmdCreate = new SqliteCommand( ScorePropertiesDBRecord.GetCreateTableSQL(), db.Connection ); cmdCreate.ExecuteNonQuery(); version = ScorePropertiesDBRecord.VERSION; db.UserVersion = version; Log.Info( $"ScorePropertiesDB バージョン {version} を生成しました。" ); //---------------- #endregion break; } } } } } } <|start_filename|>DTXMania2/ステージ/08結果/演奏パラメータ結果.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; using DTXMania2.演奏; namespace DTXMania2.結果 { class 演奏パラメータ結果 : 判定パラメータ表示 { // 生成と終了 public 演奏パラメータ結果() : base() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._フルコンボ音声再生済み = false; // パラメータアニメを構築する。 this._パラメータアニメ = new パラメータアニメ( Global.Animation.Manager ); for( int i = 0; i < 6; i++ ) { const float 開始Xオフセット = +50f; this._パラメータアニメ.X位置オフセット[ i ] = new Variable( Global.Animation.Manager, initialValue: 開始Xオフセット ); this._パラメータアニメ.不透明度[ i ] = new Variable( Global.Animation.Manager, initialValue: 0.0 ); using( var 遅延 = Global.Animation.TrasitionLibrary.Constant( duration: i * 0.05 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: 0.8, finalValue: 1.0 ) ) { this._パラメータアニメ.ストーリーボード.AddTransition( this._パラメータアニメ.不透明度[ i ], 遅延 ); this._パラメータアニメ.ストーリーボード.AddTransition( this._パラメータアニメ.不透明度[ i ], 不透明度の遷移 ); } using( var 遅延 = Global.Animation.TrasitionLibrary.Constant( duration: i * 0.05 ) ) using( var 遷移1 = Global.Animation.TrasitionLibrary.Cubic( duration: 0.2, finalValue: +0.0, finalVelocity: -200.0 ) ) // 左へスライド using( var 遷移2 = Global.Animation.TrasitionLibrary.Reversal( duration: 0.2 ) ) // 方向転換 { this._パラメータアニメ.ストーリーボード.AddTransition( this._パラメータアニメ.X位置オフセット[ i ], 遅延 ); this._パラメータアニメ.ストーリーボード.AddTransition( this._パラメータアニメ.X位置オフセット[ i ], 遷移1 ); this._パラメータアニメ.ストーリーボード.AddTransition( this._パラメータアニメ.X位置オフセット[ i ], 遷移2 ); } } // 開始。 this._パラメータアニメ.ストーリーボード.Schedule( Global.Animation.Timer.Time ); } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パラメータアニメ.Dispose(); base.Dispose(); } // 進行と描画 public override void 進行描画する( DeviceContext d2ddc, float x, float y, 成績 現在の成績 ) { // パラメータアニメが完了してからフルコンボチェック。 if( this._パラメータアニメ.ストーリーボード.Status == StoryboardStatus.Ready && !this._フルコンボ音声再生済み ) { if( 現在の成績.MaxCombo == 現在の成績.総ノーツ数 ) Global.App.システムサウンド.再生する( システムサウンド種別.フルコンボ ); this._フルコンボ音声再生済み = true; // 再生してようがしてまいが true } var 拡大率 = new Size2F( 1.4f, 1.3f ); // 画像が小さいので少々拡大。 var 割合表 = 現在の成績.判定別ヒット割合; int 合計 = 0; float 基点X = x; x = 基点X + (float)this._パラメータアニメ.X位置オフセット[ 0 ].Value; this.パラメータを一行描画する( d2ddc, x, y, 拡大率, 判定種別.PERFECT, 現在の成績.判定別ヒット数[ 判定種別.PERFECT ], 割合表[ 判定種別.PERFECT ], (float)this._パラメータアニメ.不透明度[ 0 ].Value ); 合計 += 現在の成績.判定別ヒット数[ 判定種別.PERFECT ]; y += _改行幅dpx; x = 基点X + (float)this._パラメータアニメ.X位置オフセット[ 1 ].Value; this.パラメータを一行描画する( d2ddc, x, y, 拡大率, 判定種別.GREAT, 現在の成績.判定別ヒット数[ 判定種別.GREAT ], 割合表[ 判定種別.GREAT ], (float)this._パラメータアニメ.不透明度[ 1 ].Value ); 合計 += 現在の成績.判定別ヒット数[ 判定種別.GREAT ]; y += _改行幅dpx; x = 基点X + (float)this._パラメータアニメ.X位置オフセット[ 2 ].Value; this.パラメータを一行描画する( d2ddc, x, y, 拡大率, 判定種別.GOOD, 現在の成績.判定別ヒット数[ 判定種別.GOOD ], 割合表[ 判定種別.GOOD ], (float)this._パラメータアニメ.不透明度[ 2 ].Value ); 合計 += 現在の成績.判定別ヒット数[ 判定種別.GOOD ]; y += _改行幅dpx; x = 基点X + (float)this._パラメータアニメ.X位置オフセット[ 3 ].Value; this.パラメータを一行描画する( d2ddc, x, y, 拡大率, 判定種別.OK, 現在の成績.判定別ヒット数[ 判定種別.OK ], 割合表[ 判定種別.OK ], (float)this._パラメータアニメ.不透明度[ 3 ].Value ); 合計 += 現在の成績.判定別ヒット数[ 判定種別.OK ]; y += _改行幅dpx; x = 基点X + (float)this._パラメータアニメ.X位置オフセット[ 4 ].Value; this.パラメータを一行描画する( d2ddc, x, y, 拡大率, 判定種別.MISS, 現在の成績.判定別ヒット数[ 判定種別.MISS ], 割合表[ 判定種別.MISS ], (float)this._パラメータアニメ.不透明度[ 4 ].Value ); 合計 += 現在の成績.判定別ヒット数[ 判定種別.MISS ]; y += _改行幅dpx; x = 基点X + (float)this._パラメータアニメ.X位置オフセット[ 5 ].Value; var 矩形 = this.判定種別文字の矩形リスト[ "MaxCombo" ]!; this._判定種別文字.描画する( d2ddc, x, y, 転送元矩形: 矩形, 不透明度0to1: (float)this._パラメータアニメ.不透明度[ 5 ].Value ); x += 矩形.Value.Width + 16f; this.数値を描画する( d2ddc, x, y, 拡大率, 現在の成績.MaxCombo, 4, (float)this._パラメータアニメ.不透明度[ 5 ].Value ); this.数値を描画する( d2ddc, x + _dr * 拡大率.Width, y, 拡大率, (int)Math.Floor( 100.0 * 現在の成績.MaxCombo / 合計 ), 3, (float)this._パラメータアニメ.不透明度[ 5 ].Value ); // 切り捨てでいいやもう this.パラメータ文字.不透明度 = (float)this._パラメータアニメ.不透明度[ 5 ].Value; this.パラメータ文字.描画する( d2ddc, x + _dp * 拡大率.Width, y, "%", 拡大率 ); } // ローカル protected new const float _改行幅dpx = 36f; private class パラメータアニメ : IDisposable { public Variable[] X位置オフセット; public Variable[] 不透明度; public Storyboard ストーリーボード; public パラメータアニメ( Manager am ) { this.X位置オフセット = new Variable[ 6 ]; this.不透明度 = new Variable[ 6 ]; this.ストーリーボード = new Storyboard( am ); } public virtual void Dispose() { this.ストーリーボード.Dispose(); for( int i = 0; i < 6; i++ ) { this.X位置オフセット[ i ]?.Dispose(); this.不透明度[ i ]?.Dispose(); } } }; private readonly パラメータアニメ _パラメータアニメ; private bool _フルコンボ音声再生済み = false; } } <|start_filename|>DTXMania2/ステージ/08結果/難易度.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.結果 { partial class 難易度 : IDisposable { // プロパティ public bool アニメ完了 => this._アイコン.アニメ完了 && this._下線.アニメ完了 && this._数値.アニメ完了; // 生成と終了 public 難易度() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._アイコン = new 難易度.アイコン(); this._下線 = new 難易度.下線(); this._数値 = new 難易度.数値(); this._初めての進行描画 = true; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数値.Dispose(); this._下線.Dispose(); this._アイコン.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, float x, float y, double 難易度 ) { if( this._初めての進行描画 ) { // アニメーション開始 this._アイコン.開始する(); this._下線.開始する(); this._数値.開始する( 難易度 ); this._初めての進行描画 = false; } this._アイコン.進行描画する( d2ddc, x, y ); this._数値.進行描画する( d2ddc, x + 221f, y + 3f ); this._下線.進行描画する( d2ddc, x + 33f, y + 113f ); } public void アニメを完了する() { this._アイコン.アニメを完了する(); this._下線.アニメを完了する(); this._数値.アニメを完了する(); } // ローカル private const double _最初の待機時間sec = 0.5; private const double _アニメ時間sec = 0.25; private bool _初めての進行描画 = false; private readonly 難易度.アイコン _アイコン; private readonly 難易度.下線 _下線; private readonly 難易度.数値 _数値; } } <|start_filename|>FDK/サウンド/Sources/MediaFoundationOnStreamingWaveSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace FDK { /// <summary> /// 指定されたメディアファイル(動画, 音楽)をバックグラウンドで読み込む <see cref="CSCore.IWaveSource"/> オブジェクトを生成する。 /// </summary> public class MediaFoundationOnStreamingWaveSource : CSCore.IWaveSource { // プロパティ public virtual string Name { get; set; } /// <summary> /// シーク能力があるなら true 。 /// </summary> public virtual bool CanSeek => true; /// <summary> /// デコード後のオーディオデータのフォーマット。 /// </summary> public virtual CSCore.WaveFormat WaveFormat { get; protected set; } /// <summary> /// デコード後のオーディオデータのすべての長さ[byte]。 /// </summary> public virtual long Length => this._Disposed ? 0 : this._DecodedWaveDataQueue.書き込み位置; /// <summary> /// 現在の再生位置[byte]。 /// </summary> public virtual long Position { get => this._Disposed ? 0 : this._DecodedWaveDataQueue.読み出し位置; set { if( !( this._Disposed ) ) this._DecodedWaveDataQueue.読み出し位置 = this._位置をブロック境界単位にそろえて返す( value, this.WaveFormat.BlockAlign ); } } /// <summary> /// デコードタスクがデコードを完了したらセットされるイベント。 /// </summary> public ManualResetEventSlim DecodeComplete { get; } = new ManualResetEventSlim( false ); // 生成と終了 /// <summary> /// コンストラクタ。 /// 指定されたファイルを指定されたフォーマットでデコードし、内部にオンメモリで保管する。 /// </summary> public MediaFoundationOnStreamingWaveSource( VariablePath ファイルパス, CSCore.WaveFormat deviceFormat ) { this.Name = ファイルパス.変数付きパス; this.WaveFormat = new CSCore.WaveFormat( deviceFormat.SampleRate, 32, // bits deviceFormat.Channels, CSCore.AudioEncoding.IeeeFloat ); // ファイルから SourceReaderEx を生成する。 // //using( var sourceReader = new MFSourceReader( path ) ) // SourceReader は、SharpDX ではなく CSCore のものを使う。(WaveFormat から MediaType に一発で変換できるので。) // → CSCore.Win32.Comobject のファイナライザに不具合があるので、SourceReader には CSCore ではなく SharpDX のものを使う。 // _MFMediaType, WaveFormat フィールドは CSCore のものなので注意。 // using( var sourceReader = new SharpDX.MediaFoundation.SourceReader( ファイルパス.変数なしパス ) ) // パスは URI 扱い this._SourceReaderEx = sourceReader.QueryInterface<SharpDX.MediaFoundation.SourceReaderEx>(); this._SourceReaderの取得後の初期化(); } /// <summary> /// コンストラクタ。 /// 指定されたソースリーダーを指定されたフォーマットで、内部にオンメモリで保管する。 /// </summary> public MediaFoundationOnStreamingWaveSource( SharpDX.MediaFoundation.SourceReaderEx sourceReader, CSCore.WaveFormat deviceFormat ) { this.Name = ""; this.WaveFormat = new CSCore.WaveFormat( deviceFormat.SampleRate, 32, // bits deviceFormat.Channels, CSCore.AudioEncoding.IeeeFloat ); this._SourceReaderEx = sourceReader; this._SourceReaderの取得後の初期化(); } private void _SourceReaderの取得後の初期化() { // 最初のオーディオストリームを選択する。 //this._SourceReaderEx.SetStreamSelection( SharpDX.MediaFoundation.SourceReaderIndex.AllStreams, false ); --> その他についてはいじらない。 this._SourceReaderEx.SetStreamSelection( SharpDX.MediaFoundation.SourceReaderIndex.FirstAudioStream, true ); // 部分メディアタイプを作成。 // // ↓CSCore の場合。WaveFormatEx にも対応。 //using( var partialMediaType = MFMediaType.FromWaveFormat( this.WaveFormat ) ) // // ↓SharpDX の場合。 var wf = SharpDX.Multimedia.WaveFormat.CreateIeeeFloatWaveFormat( this.WaveFormat.SampleRate, this.WaveFormat.Channels ); SharpDX.MediaFoundation.MediaFactory.CreateAudioMediaType( ref wf, out SharpDX.MediaFoundation.AudioMediaType partialMediaType ); using( partialMediaType ) { // 作成した部分メディアタイプを SourceReader にセットする。必要なデコーダが見つからなかったら、ここで例外が発生する。 this._SourceReaderEx.SetCurrentMediaType( SharpDX.MediaFoundation.SourceReaderIndex.FirstAudioStream, partialMediaType ); // 完成されたメディアタイプを取得する。 this._AudioMediaType = this._SourceReaderEx.GetCurrentMediaType( SharpDX.MediaFoundation.SourceReaderIndex.FirstAudioStream ); this._MFAudioMediaType = new CSCore.MediaFoundation.MFMediaType( this._AudioMediaType.NativePointer ); // ネイティブポインタを使って、SharpDX → CSCore へ変換。SharpDX側オブジェクトは解放したらダメ。 } // メディアタイプから WaveFormat を取得する。 this.WaveFormat = this._MFAudioMediaType.ToWaveFormat( CSCore.MediaFoundation.MFWaveFormatExConvertFlags.Normal ); // デコード開始。 this._DecodedWaveDataQueue = new QueueMemoryStream(); this._デコードキャンセル = new CancellationTokenSource(); this._デコードタスク = Task.Factory.StartNew( this._デコードタスクエントリ, this._デコードキャンセル.Token ); } public virtual void Dispose() { if( !this._Disposed ) { #region " デコードタスクが稼働しているなら終了する。" //---------------- if( ( null != this._デコードタスク ) && !( this._デコードタスク.IsCompleted ) ) { this._デコードキャンセル.Cancel(); this._DecodedWaveDataQueue.Cancel(); this._デコードタスク.Wait( 5000 ); // 最大5秒までは待つ } //---------------- #endregion this._デコードキャンセル.Dispose(); this._DecodedWaveDataQueue.Dispose(); this._SourceReaderEx.Dispose(); //this._AudioMediaType.Dispose(); // _MFAudioMediaType と同じネイティブポインタを共有している。 this._MFAudioMediaType.Dispose(); // this._Disposed = true; } } // 出力 /// <summary> /// 連続したデータを読み込む。 /// データが不足していれば、その分は 0 で埋めて返す。 /// </summary> /// <param name="buffer">読み込んだデータを格納するための配列。</param> /// <param name="offset"><paramref name="buffer"/> に格納を始める位置。</param> /// <param name="count">読み込む最大のデータ数。</param> /// <returns><paramref name="buffer"/> に読み込んだデータの総数(常に <paramref name="count"/> に一致)。</returns> public virtual int Read( byte[] buffer, int offset, int count ) { // 前提条件チェック。音がめちゃくちゃになるとうざいので、このメソッド内では例外を出さないこと。 if( this._Disposed || null == this._SourceReaderEx || null == this._DecodedWaveDataQueue || null == buffer ) return 0; // ストリームから読み出す。データが不足していてもブロックせずすぐ戻る。 int readCount = this._DecodedWaveDataQueue.Read( buffer, offset, count, データが足りないならブロックする: false ); // データが不足しているなら、不足分を 0 で埋める。 if( readCount < count ) Array.Clear( buffer, ( offset + readCount ), ( count - readCount ) ); return count; } // ローカル protected SharpDX.MediaFoundation.SourceReaderEx _SourceReaderEx = null!; protected SharpDX.MediaFoundation.MediaType _AudioMediaType = null!; protected CSCore.MediaFoundation.MFMediaType _MFAudioMediaType = null!; protected QueueMemoryStream _DecodedWaveDataQueue = null!; protected Task _デコードタスク = null!; protected CancellationTokenSource _デコードキャンセル = null!; private bool _Disposed = false; private void _デコードタスクエントリ() { Log.現在のスレッドに名前をつける( "オーディオデコード" ); Log.Info( $"オーディオデコードタスクを起動しました。[{this.Name}]" ); while( true ) { // キャンセル通知が来てればループを抜ける。 if( this._デコードキャンセル.IsCancellationRequested ) { Log.Info( $"キャンセル通知を受信しました。[{this.Name}]" ); break; } // 次のサンプルをひとつデコードする。 using( var サンプル = this._SourceReaderEx.ReadSample( SharpDX.MediaFoundation.SourceReaderIndex.FirstAudioStream, SharpDX.MediaFoundation.SourceReaderControlFlags.None, out _, out var ストリームフラグ, out long サンプルの表示時刻100ns ) ) { // デコード結果を確認する。 if( ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.Endofstream ) ) { Log.Info( $"ストリームが終了しました。[{this.Name}]" ); break; } if( ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.Error ) || ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.AllEffectsremoved ) || ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.Currentmediatypechanged ) || ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.Nativemediatypechanged ) || ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.Newstream ) || ストリームフラグ.HasFlag( SharpDX.MediaFoundation.SourceReaderFlags.StreamTick ) ) { Log.ERROR( $"デコード中にエラーが発生、または未対応の状態変化が発生しました。[{this.Name}]" ); break; } // サンプルをロックし、オーディオデータへのポインタを取得して、オーディオデータをメモリストリームに書き込む。 using( var mediaBuffer = サンプル.ConvertToContiguousBuffer() ) { var audioData = mediaBuffer.Lock( out _, out int cbCurrentLength ); byte[] dstData = new byte[ cbCurrentLength ]; Marshal.Copy( audioData, dstData, 0, cbCurrentLength ); this._DecodedWaveDataQueue.Write( dstData, 0, cbCurrentLength ); mediaBuffer.Unlock(); } } } this.DecodeComplete.Set(); Log.Info( $"デコードタスクを終了しました。[{this.Name}]" ); } private long _位置をブロック境界単位にそろえて返す( long position, long blockAlign ) { return ( position - ( position % blockAlign ) ); } } } <|start_filename|>DTXMania2/イメージ/画像D2D.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { /// <summary> /// D2Dビットマップを使った画像表示。 /// </summary> class 画像D2D : FDK.画像D2D { public 画像D2D( VariablePath 画像ファイルパス, BitmapProperties1? bitmapProperties1 = null ) : base( Global.GraphicResources.WicImagingFactory2, Global.GraphicResources.既定のD2D1DeviceContext, Folder.カルチャを考慮した絶対パスを返す( 画像ファイルパス.変数なしパス ), bitmapProperties1 ) { } protected 画像D2D() : base() { } } } <|start_filename|>DTXMania2/ステージ/アイキャッチ/アイキャッチ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; using SharpDX.Animation; namespace DTXMania2 { /// <summary> /// アイキャッチの基本クラス。 /// </summary> /// <remarks> /// アイキャッチとは、画面の切り替え時に、つなぎとして表示される画面を指す。 /// 徐々に下画面を隠す「クローズ」と、徐々に下画面を表す「オープン」とがある。 /// </remarks> abstract class アイキャッチ : IDisposable { // プロパティ public enum フェーズ { 未定, クローズ, オープン, クローズ完了, オープン完了, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.未定; // 生成と終了 public アイキャッチ() { this.現在のフェーズ = フェーズ.未定; } public virtual void Dispose() { } // オープンとクローズ /// <summary> /// アイキャッチのクローズアニメーションを開始する。 /// </summary> public virtual void クローズする( float 速度倍率 = 1.0f ) { // 派生クラスでこのメソッドをオーバーライドし、 // クローズ用のストーリーボードと変数の生成、トラジションの追加、ストーリーボードの開始コードなどを記述すること。 this.現在のフェーズ = フェーズ.クローズ; } /// <summary> /// アイキャッチのオープンアニメーションを開始する。 /// </summary> public virtual void オープンする( float 速度倍率 = 1.0f ) { // 派生クラスでこのメソッドをオーバーライドし、 // オープン用のストーリーボードと変数の生成、トラジションの追加、ストーリーボードの開始コードなどを記述すること。 this.現在のフェーズ = フェーズ.オープン; } // 進行と描画 /// <summary> /// アイキャッチのアニメーションを進行し、アイキャッチ画像を描画する。 /// </summary> /// <returns>現在のフェーズ。</returns> public フェーズ 進行描画する( DeviceContext d2ddc ) { switch( this.現在のフェーズ ) { case フェーズ.未定: break; case フェーズ.クローズ: case フェーズ.クローズ完了: this.進行描画する( d2ddc, StoryboardStatus.Scheduled ); break; case フェーズ.オープン: case フェーズ.オープン完了: this.進行描画する( d2ddc, StoryboardStatus.Ready ); break; } return this.現在のフェーズ; } /// <summary> /// 派生クラスでこのメソッドをオーバーライドし、アイキャッチ画面の描画を行う。 /// </summary> protected virtual void 進行描画する( DeviceContext d2ddc, StoryboardStatus 描画しないStatus ) { bool すべて完了 = true; // 派生クラスでは、ここで以下の(1)~(3)を実装すること。 // (1) ストーリーボードが動作しているなら、すべて完了 フラグを false にする。 // 例: // if( context.ストーリーボード.Status != StoryboardStatus.Ready ) // すべて完了 = false; // (2) アイキャッチ画面を描画する。 // ただし、現在のストーリーボードのステータスが 描画しないStatus であるなら、描画はしないこと。 // 例: // if( context.ストーリーボード.Status != 描画しないStatus ) // { // // 描画処理 // } // (3) すべて完了したかどうかチェックする。 if( すべて完了 ) { if( this.現在のフェーズ == フェーズ.クローズ ) { this.現在のフェーズ = フェーズ.クローズ完了; } else if( this.現在のフェーズ == フェーズ.オープン ) { this.現在のフェーズ = フェーズ.オープン完了; } } } } } <|start_filename|>DTXMania2/保存データ/SystemConfig/old/v003_システム設定.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Windows.Forms; using YamlDotNet.Serialization; using SharpDX; using FDK; namespace DTXMania2.old.SystemConfig { using IdKey = DTXMania2.SystemConfig.IdKey; class v003_システム設定 { /// <summary> /// このクラスのバージョン。 /// </summary> [YamlMember] public int Version { get; set; } = 3; /// <summary> /// 曲ファイルを検索するフォルダのリスト。 /// </summary> [YamlMember( Alias = "SongSearchFolders" )] public List<VariablePath> 曲検索フォルダ { get; protected set; } [YamlMember( Alias = "WindowPositionOnViewerMode" )] public Point ビュアーモード時のウィンドウ表示位置 { get; set; } [YamlMember( Alias = "WindowSizeOnViewerMode" )] public Size2 ビュアーモード時のウィンドウサイズ { get; set; } /// <summary> /// チップヒットの判定位置を、判定バーからさらに上(負数)または下(正数)に調整する。 /// -99~+99[ms] 。 /// </summary> /// <remarks> /// 判定バーの見かけの位置は変わらず、判定位置のみ移動する。 /// 入力機器の遅延対策であるが、入力機器とのヒモづけは行わないので、 /// 入力機器が変われば再調整が必要になる場合がある。 /// </remarks> [YamlMember( Alias = "JudgePositionAdjustmentOnMilliseconds" )] public int 判定位置調整ms { get; set; } [YamlMember( Alias = "Fullscreen" )] public bool 全画面モードである { get; set; } [YamlIgnore] public bool ウィンドウモードである { get => !this.全画面モードである; set => this.全画面モードである = !value; } [YamlIgnore] public static readonly VariablePath 既定のシステム設定ファイルパス = @"$(AppData)Configuration.yaml"; // キーバインディング /// <summary> /// MIDI番号(0~7)とMIDIデバイス名のマッピング用 Dictionary。 /// </summary> [YamlMember( Alias = "MidiDeviceIDtoDeviceName" )] public Dictionary<int, string> MIDIデバイス番号toデバイス名 { get; protected set; } /// <summary> /// キーボードの入力(<see cref="System.Windows.Forms.Keys"/>)からドラム入力へのマッピング用 Dictionary 。 /// </summary> [YamlMember( Alias = "KeyboardToDrums" )] public Dictionary<IdKey, ドラム入力種別> キーボードtoドラム { get; protected set; } /// <summary> /// ゲームコントローラの入力(Extended Usage)からドラム入力へのマッピング用 Dictionary 。 /// </summary> [YamlMember( Alias = "GameControllerToDrums" )] public Dictionary<IdKey, ドラム入力種別> ゲームコントローラtoドラム { get; protected set; } /// <summary> /// MIDI入力の入力(MIDIノート番号)からドラム入力へのマッピング用 Dictionary 。 /// </summary> [YamlMember( Alias = "MidiInToDrums" )] public Dictionary<IdKey, ドラム入力種別> MIDItoドラム { get; protected set; } [YamlMember( Alias = "MinFoolPedalValue" )] public int FootPedal最小値 { get; set; } [YamlMember( Alias = "MaxFoolPedalValue" )] public int FootPedal最大値 { get; set; } // 生成と終了 public static v003_システム設定 読み込む( VariablePath path ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // (1) 読み込み or 新規作成 var yamlText = File.ReadAllText( path.変数なしパス ); var deserializer = new Deserializer(); var config = deserializer.Deserialize<v003_システム設定>( yamlText ); if( 3 != config.Version ) throw new Exception( "バージョンが違います。" ); // (2) 読み込み後の処理 // パスの指定がなければ、とりあえず exe のあるフォルダを検索対象にする。 if( 0 == config.曲検索フォルダ.Count ) config.曲検索フォルダ.Add( @"$(Exe)" ); return config; } public v003_システム設定() { this.曲検索フォルダ = new List<VariablePath>() { @"$(Exe)" }; this.ビュアーモード時のウィンドウ表示位置 = new Point( 100, 100 ); this.ビュアーモード時のウィンドウサイズ = new Size2( 640, 360 ); this.判定位置調整ms = 0; this.全画面モードである = false; this.FootPedal最小値 = 0; this.FootPedal最大値 = 90; // VH-11 の Normal Resolution での最大値 this.MIDIデバイス番号toデバイス名 = new Dictionary<int, string>(); this.キーボードtoドラム = new Dictionary<IdKey, ドラム入力種別>() { { new IdKey( 0, (int) Keys.Q ), ドラム入力種別.LeftCrash }, { new IdKey( 0, (int) Keys.Return ), ドラム入力種別.LeftCrash }, { new IdKey( 0, (int) Keys.A ), ドラム入力種別.HiHat_Open }, { new IdKey( 0, (int) Keys.Z ), ドラム入力種別.HiHat_Close }, { new IdKey( 0, (int) Keys.S ), ドラム入力種別.HiHat_Foot }, { new IdKey( 0, (int) Keys.X ), ドラム入力種別.Snare }, { new IdKey( 0, (int) Keys.C ), ドラム入力種別.Bass }, { new IdKey( 0, (int) Keys.Space ), ドラム入力種別.Bass }, { new IdKey( 0, (int) Keys.V ), ドラム入力種別.Tom1 }, { new IdKey( 0, (int) Keys.B ), ドラム入力種別.Tom2 }, { new IdKey( 0, (int) Keys.N ), ドラム入力種別.Tom3 }, { new IdKey( 0, (int) Keys.M ), ドラム入力種別.RightCrash }, { new IdKey( 0, (int) Keys.K ), ドラム入力種別.Ride }, }; this.ゲームコントローラtoドラム = new Dictionary<IdKey, ドラム入力種別>() { // 特になし }; this.MIDItoドラム = new Dictionary<IdKey, ドラム入力種別>() { // うちの環境(2017.6.11) { new IdKey( 0, 36 ), ドラム入力種別.Bass }, { new IdKey( 0, 30 ), ドラム入力種別.RightCrash }, { new IdKey( 0, 29 ), ドラム入力種別.RightCrash }, { new IdKey( 1, 51 ), ドラム入力種別.RightCrash }, { new IdKey( 1, 52 ), ドラム入力種別.RightCrash }, { new IdKey( 1, 57 ), ドラム入力種別.RightCrash }, { new IdKey( 0, 52 ), ドラム入力種別.RightCrash }, { new IdKey( 0, 43 ), ドラム入力種別.Tom3 }, { new IdKey( 0, 58 ), ドラム入力種別.Tom3 }, { new IdKey( 0, 42 ), ドラム入力種別.HiHat_Close }, { new IdKey( 0, 22 ), ドラム入力種別.HiHat_Close }, { new IdKey( 0, 26 ), ドラム入力種別.HiHat_Open }, { new IdKey( 0, 46 ), ドラム入力種別.HiHat_Open }, { new IdKey( 0, 44 ), ドラム入力種別.HiHat_Foot }, { new IdKey( 0, 255 ), ドラム入力種別.HiHat_Control }, // FDK の MidiIn クラスは、FootControl を ノート 255 として扱う。 { new IdKey( 0, 48 ), ドラム入力種別.Tom1 }, { new IdKey( 0, 50 ), ドラム入力種別.Tom1 }, { new IdKey( 0, 49 ), ドラム入力種別.LeftCrash }, { new IdKey( 0, 55 ), ドラム入力種別.LeftCrash }, { new IdKey( 1, 48 ), ドラム入力種別.LeftCrash }, { new IdKey( 1, 49 ), ドラム入力種別.LeftCrash }, { new IdKey( 1, 59 ), ドラム入力種別.LeftCrash }, { new IdKey( 0, 45 ), ドラム入力種別.Tom2 }, { new IdKey( 0, 47 ), ドラム入力種別.Tom2 }, { new IdKey( 0, 51 ), ドラム入力種別.Ride }, { new IdKey( 0, 59 ), ドラム入力種別.Ride }, { new IdKey( 0, 38 ), ドラム入力種別.Snare }, { new IdKey( 0, 40 ), ドラム入力種別.Snare }, { new IdKey( 0, 37 ), ドラム入力種別.Snare }, }; } public v003_システム設定( v002_システム設定 v2config ) : this() { this.曲検索フォルダ = v2config.曲検索フォルダ; this.ビュアーモード時のウィンドウサイズ = new Size2( v2config.ウィンドウサイズViewerモード用.Width, v2config.ウィンドウサイズViewerモード用.Height ); this.ビュアーモード時のウィンドウ表示位置 = new Point( v2config.ウィンドウ表示位置Viewerモード用.X, v2config.ウィンドウ表示位置Viewerモード用.Y ); this.判定位置調整ms = v2config.判定位置調整ms; this.FootPedal最小値 = v2config.キー割り当て.FootPedal最小値; this.FootPedal最大値 = v2config.キー割り当て.FootPedal最大値; this.MIDIデバイス番号toデバイス名 = v2config.キー割り当て.MIDIデバイス番号toデバイス名; this.キーボードtoドラム = v2config.キー割り当て.キーボードtoドラム; this.ゲームコントローラtoドラム = new Dictionary<IdKey, ドラム入力種別>(); this.MIDItoドラム = v2config.キー割り当て.MIDItoドラム; } public void 保存する( VariablePath path ) { using var _ = new LogBlock( Log.現在のメソッド名 ); var serializer = new SerializerBuilder() .WithTypeInspector( inner => new CommentGatheringTypeInspector( inner ) ) .WithEmissionPhaseObjectGraphVisitor( args => new CommentsObjectGraphVisitor( args.InnerVisitor ) ) .Build(); // ※ 値が既定値であるプロパティは出力されないので注意。 var yaml = serializer.Serialize( this ); File.WriteAllText( path.変数なしパス, yaml ); Log.Info( $"システム設定 を保存しました。[{path.変数付きパス}]" ); } public v003_システム設定 Clone() { return (v003_システム設定) this.MemberwiseClone(); } } } <|start_filename|>DTXMania2/ステージ/08結果/結果ステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using Microsoft.Data.Sqlite; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2.結果 { class 結果ステージ : IStage { // プロパティ public enum フェーズ { 表示, アニメ完了, フェードアウト, 完了, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; // 生成と終了 public 結果ステージ( 成績 result ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._結果 = result; Log.Info( $"曲名: {Global.App.演奏譜面.譜面.Title}" ); Log.Info( $"難易度: {Global.App.演奏譜面.譜面.Level}" ); Log.Info( $"ヒット数: Pf{this._結果.判定別ヒット数[演奏.判定種別.PERFECT]} / " + $"Gr{this._結果.判定別ヒット数[ 演奏.判定種別.GREAT]} / " + $"Gd{this._結果.判定別ヒット数[ 演奏.判定種別.GOOD]} / " + $"Ok{this._結果.判定別ヒット数[ 演奏.判定種別.OK ]} / " + $"Ms{this._結果.判定別ヒット数[ 演奏.判定種別.MISS]}" ); Log.Info( $"達成率: {this._結果.Achievement}" ); Log.Info( $"スキル: {this._結果.スキル}" ); Log.Info( $"ランク: {this._結果.ランク}" ); Global.App.システムサウンド.再生する( システムサウンド種別.ステージクリア ); #region " 成績をDBへ反映する。" //---------------- if( result.無効 ) { // 全Autoまたは無効の場合は反映しない。 this._最高成績である = false; } else { this._最高成績である = this._成績を反映する(); } //---------------- #endregion this._背景 = new 舞台画像(); this._既定のノード画像 = new 画像D2D( @"$(Images)\DefaultPreviewImage.png" ); this._現行化前のノード画像 = new 画像D2D( @"$(Images)\PreviewImageWaitForActivation.png" ); this._曲名パネル = new 画像D2D( @"$(Images)\ResultStage\ScoreTitlePanel.png" ); this._曲名画像 = new 文字列画像D2D() { フォント名 = "HGMaruGothicMPRO", フォントサイズpt = 40f, フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 6f, 前景色 = Color4.Black, 背景色 = Color4.White, }; this._サブタイトル画像 = new 文字列画像D2D() { フォント名 = "HGMaruGothicMPRO", フォントサイズpt = 25f, フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 5f, 前景色 = Color4.Black, 背景色 = Color4.White, }; this._演奏パラメータ結果 = new 演奏パラメータ結果(); this._ランク = new ランク(); this._難易度 = new 難易度(); this._曲別SKILL = new 曲別SKILL(); this._達成率 = ( this._最高成績である ) ? (達成率Base)new 達成率更新() : new 達成率(); this._システム情報 = new システム情報(); this._黒マスクブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( Color3.Black, 0.75f ) ); this._プレビュー枠ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0xFF209292 ) ); var 選択曲 = Global.App.演奏スコア; this._曲名画像.表示文字列 = 選択曲.曲名; this._サブタイトル画像.表示文字列 = 選択曲.アーティスト名; this._背景.ぼかしと縮小を適用する( 0.0 ); // 即時適用 // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.表示; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); Global.App.システムサウンド.停止する( システムサウンド種別.ステージクリア ); Global.App.WAV管理.すべての発声を停止する(); Global.App.WAV管理.Dispose(); this._プレビュー枠ブラシ.Dispose(); this._黒マスクブラシ.Dispose(); this._システム情報.Dispose(); this._達成率.Dispose(); this._曲別SKILL.Dispose(); this._難易度.Dispose(); this._ランク.Dispose(); this._演奏パラメータ結果.Dispose(); this._サブタイトル画像.Dispose(); this._曲名画像.Dispose(); this._曲名パネル.Dispose(); this._現行化前のノード画像.Dispose(); this._既定のノード画像.Dispose(); this._背景.Dispose(); } // 進行と描画 public void 進行する() { this._システム情報.FPSをカウントしプロパティを更新する(); Global.App.ドラム入力.すべての入力デバイスをポーリングする(); switch( this.現在のフェーズ ) { case フェーズ.表示: { if( this._曲別SKILL.アニメ完了 && this._難易度.アニメ完了 && this._達成率.アニメ完了 ) { #region " すべてのアニメが完了 → アニメ完了フェーズへ " //---------------- this.現在のフェーズ = フェーズ.アニメ完了; //---------------- #endregion } else if( Global.App.ドラム入力.確定キーが入力された() || Global.App.ドラム入力.キャンセルキーが入力された() ) { #region " 確定 or キャンセル → アニメを完了してアニメ完了フェーズへ " //---------------- this._曲別SKILL.アニメを完了する(); this._達成率.アニメを完了する(); this._難易度.アニメを完了する(); this._ランク.アニメを完了する(); this.現在のフェーズ = フェーズ.アニメ完了; //---------------- #endregion } else if( Global.App.ログオン中のユーザ.ドラムの音を発声する ) { #region " その他のキー → 空うちサウンドを再生する " //---------------- this._空うちサウンドを再生する(); //---------------- #endregion } break; } case フェーズ.アニメ完了: { if( Global.App.ドラム入力.確定キーが入力された() || Global.App.ドラム入力.キャンセルキーが入力された() ) { #region " 確定 or キャンセル → フェーズアウトへ " //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); // 確定だけど取消音 Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( シャッター ) ); this.現在のフェーズ = フェーズ.フェードアウト; //---------------- #endregion } else if( Global.App.ログオン中のユーザ.ドラムの音を発声する ) { #region " その他 → 空うちサウンドを再生 " //---------------- this._空うちサウンドを再生する(); //---------------- #endregion } break; } case フェーズ.フェードアウト: { #region " フェードアウトが完了したら完了フェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) this.現在のフェーズ = フェーズ.完了; //---------------- #endregion break; } case フェーズ.完了: { #region " 遷移終了。Appによるステージ遷移待ち。" //---------------- //---------------- #endregion break; } } } public void 描画する() { this._システム情報.VPSをカウントする(); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.表示: case フェーズ.アニメ完了: { #region " 背景画面を描画する。" //---------------- d2ddc.BeginDraw(); this._画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.フェードアウト: { #region " 背景画面&フェードアウト " //---------------- d2ddc.BeginDraw(); this._画面を描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.完了: { #region " フェードアウト " //---------------- d2ddc.BeginDraw(); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } } } private void _画面を描画する( DeviceContext d2ddc ) { this._背景.進行描画する( d2ddc ); d2ddc.FillRectangle( new RectangleF( 0f, 36f, Global.GraphicResources.設計画面サイズ.Width, Global.GraphicResources.設計画面サイズ.Height - 72f ), this._黒マスクブラシ ); this._プレビュー画像を描画する( d2ddc ); this._曲名パネル.描画する( d2ddc, 660f, 796f ); this._曲名を描画する( d2ddc ); this._サブタイトルを描画する( d2ddc ); this._演奏パラメータ結果.進行描画する( d2ddc, 1317f, 716f, this._結果 ); this._ランク.進行描画する( d2ddc, this._結果.ランク ); this._難易度.進行描画する( d2ddc, 1341f, 208f, Global.App.演奏スコア.難易度 ); this._曲別SKILL.進行描画する( d2ddc, 1329f, 327f, this._結果.スキル ); this._達成率.進行描画する( d2ddc, 1233f, 428f, this._結果.Achievement ); this._システム情報.描画する( d2ddc ); } private void _プレビュー画像を描画する( DeviceContext d2ddc ) { // 枠 const float 枠の太さdpx = 5f; d2ddc.FillRectangle( new RectangleF( this._プレビュー画像表示位置dpx.X - 枠の太さdpx, this._プレビュー画像表示位置dpx.Y - 枠の太さdpx, this._プレビュー画像表示サイズdpx.X + 枠の太さdpx * 2f, this._プレビュー画像表示サイズdpx.Y + 枠の太さdpx * 2f ), this._プレビュー枠ブラシ ); // プレビュー画像 var preimage = Global.App.演奏譜面.最高記録を現行化済み ? ( Global.App.演奏譜面.プレビュー画像 ?? this._既定のノード画像 ) : this._現行化前のノード画像; var 変換行列2D = Matrix3x2.Scaling( this._プレビュー画像表示サイズdpx.X / preimage.サイズ.Width, this._プレビュー画像表示サイズdpx.Y / preimage.サイズ.Height ) * Matrix3x2.Translation( this._プレビュー画像表示位置dpx.X, this._プレビュー画像表示位置dpx.Y ); preimage.描画する( d2ddc, 変換行列2D ); } private void _曲名を描画する( DeviceContext d2ddc ) { var 表示位置dpx = new Vector2( 690f, 820f ); // 拡大率を計算して描画する。 float 最大幅dpx = 545f; float X方向拡大率 = ( this._曲名画像.画像サイズdpx.Width <= 最大幅dpx ) ? 1f : 最大幅dpx / this._曲名画像.画像サイズdpx.Width; this._曲名画像.描画する( d2ddc, 表示位置dpx.X, 表示位置dpx.Y, X方向拡大率: X方向拡大率 ); } private void _サブタイトルを描画する( DeviceContext d2ddc ) { var 表示位置dpx = new Vector2( 690f, 820f + 60f ); // 拡大率を計算して描画する。 float 最大幅dpx = 545f; float X方向拡大率 = ( this._サブタイトル画像.画像サイズdpx.Width <= 最大幅dpx ) ? 1f : 最大幅dpx / this._サブタイトル画像.画像サイズdpx.Width; this._サブタイトル画像.描画する( d2ddc, 表示位置dpx.X, 表示位置dpx.Y, X方向拡大率: X方向拡大率 ); } // ローカル private readonly bool _最高成績である; private readonly 舞台画像 _背景; private readonly 画像D2D _既定のノード画像; private readonly 画像D2D _現行化前のノード画像; private readonly 画像D2D _曲名パネル; private readonly 文字列画像D2D _曲名画像; private readonly 文字列画像D2D _サブタイトル画像; private readonly 演奏パラメータ結果 _演奏パラメータ結果; private readonly ランク _ランク; private readonly 難易度 _難易度; private readonly 曲別SKILL _曲別SKILL; private readonly 達成率Base _達成率; private readonly システム情報 _システム情報; private readonly SolidColorBrush _黒マスクブラシ; private readonly SolidColorBrush _プレビュー枠ブラシ; private readonly 成績 _結果 = null!; private readonly Vector3 _プレビュー画像表示位置dpx = new Vector3( 668f, 194f, 0f ); private readonly Vector3 _プレビュー画像表示サイズdpx = new Vector3( 574f, 574f, 0f ); /// <summary> /// 成績を、RecordDB と演奏譜面へ追加または反映する。 /// </summary> /// <return>最高達成率を更新していればtrueを返す。</return> private bool _成績を反映する() { bool 最高成績である = false; using var recorddb = new RecordDB(); using var query = new SqliteCommand( "SELECT * FROM Records WHERE ScorePath = @ScorePath AND UserId = @UserId", recorddb.Connection ); query.Parameters.AddRange( new[] { new SqliteParameter( "@ScorePath", Global.App.演奏譜面.譜面.ScorePath ), new SqliteParameter( "@UserId", Global.App.ログオン中のユーザ.ID ), } ); var result = query.ExecuteReader(); if( result.Read() ) { #region " (A) レコードがすでに存在する → 記録を更新していれば、更新する。" //---------------- var record = new RecordDBRecord( result ); if( record.Achievement < this._結果.Achievement ) { record.Score = this._結果.Score; record.Achievement = this._結果.Achievement; record.CountMap = this._結果.CountMap; record.InsertTo( recorddb ); // 更新 最高成績である = true; Global.App.演奏譜面.最高記録 = record; Global.App.演奏譜面.最高記録を現行化済み = true; } else { 最高成績である = ( Global.App.演奏譜面.最高記録 is null ); // 初回なら最高記録。 Global.App.演奏譜面.最高記録 ??= record; // 初回なら代入。 Global.App.演奏譜面.最高記録を現行化済み = true; } //---------------- #endregion } else { #region " (B) レコードが存在しない → 新規追加する。" //---------------- var record = new RecordDBRecord() { ScorePath = Global.App.演奏譜面.譜面.ScorePath, UserId = Global.App.ログオン中のユーザ.ID!, Score = this._結果.Score, Achievement = this._結果.Achievement, CountMap = this._結果.CountMap, }; record.InsertTo( recorddb ); 最高成績である = true; Global.App.演奏譜面.最高記録 ??= record; Global.App.演奏譜面.最高記録を現行化済み = true; //---------------- #endregion } return 最高成績である; } private void _空うちサウンドを再生する() { // すべての押下入力(コントロールチェンジを除く)について…… foreach( var 入力 in Global.App.ドラム入力.ポーリング結果 .Where( ( e ) => e.InputEvent.押された && 0 == e.InputEvent.Control ) ) { // 結果ステージでは、一番最後に現れたチップを空打ち対象とする。 var chip = this._一番最後のチップを返す( 入力.Type ); if( null == chip ) continue; var prop = Global.App.ログオン中のユーザ.ドラムチッププロパティリスト[ chip.チップ種別 ]; if( 0 == chip.チップサブID ) // サブIDが 0 なら SSTF である { // (A) SSTF の場合 → プリセットドラムを鳴らす。(DTX他と同じく、チップがない入力については無音なので注意。) Global.App.ドラムサウンド.再生する( prop.チップ種別, 0, prop.発声前消音, prop.消音グループ種別 ); } else { // (B) DTX他の場合 → チップのWAVを再生する。 Global.App.WAV管理.発声する( chip.チップサブID, // zz 番号を示す prop.発声前消音, prop.消音グループ種別, BGM以外も再生する: Global.App.ログオン中のユーザ.ドラムの音を発声する, 音量: chip.音量 / (float)SSTF.チップ.最大音量 ); } } } /// <summary> /// 指定された <see cref="ドラム入力種別"/> のうちのいずれかに対応するチップのうち、一番最後に現れるものを返す。 /// </summary> /// <param name="drumType">チップに対応する <see cref="ドラム入力種別"/> の集合。</param> /// <returns>一番最後に現れたチップ。見つからなかったら null。</returns> private SSTF.チップ? _一番最後のチップを返す( ドラム入力種別 drumType ) { var チップtoプロパティ = Global.App.ログオン中のユーザ.ドラムチッププロパティリスト.チップtoプロパティ; // チップリストの後方から先頭に向かって検索。 for( int i = Global.App.演奏スコア.チップリスト.Count - 1; i >= 0; i-- ) { var chip = Global.App.演奏スコア.チップリスト[ i ]; if( チップtoプロパティ[ chip.チップ種別 ].ドラム入力種別 == drumType ) return chip; // 見つけた } return null; // 見つからなかった } } } <|start_filename|>DTXMania2/ステージ/アイキャッチ/回転幕.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; /* 回転幕の仕様(推定) * * ※ 画面A ... 切り替え元画面 *   画面B ... アイキャッチ遷移画面1(回転中) *   画面C ... アイキャッチ画面 *   画面D ... アイキャッチ遷移画面2(逆回転中) *   画面E ... 切り替え先画面 *   * <クローズ> * 1. 画面A切り替え元画面が表示されている。 * 2. 画面Aの上に、黒帯が上下から1本ずつ現れる。 * 3. 黒帯がそれぞれ画面中央にY方向移動する。 * → このとき、上下の黒帯間には画面Aが、黒帯の外側には画面Bが描画される。 * 4. 黒帯が、画面中央付近で回転を始める。 * → 回転開始直前に、画面Aの表示は終わり、すべて画面Bに置き換わる。 * 5. 黒帯が、270°回転したところで左右にX方向移動する。 * → このとき、左右の黒帯間には画面Cが、黒帯の外側には画面Bが描画される。 * 6. 黒帯が停止。 * → 停止直後、画面Bの表示は終わり、すべて画面Cに置き換わる。 * * <オープン> * 1. 画面Cの上に、黒帯が2つ左右に表示されている。 * 2. 黒帯がそれぞれ画面中央にX方向移動する。 * → このとき、左右の黒帯間には画面Cが、黒帯の外側には画面Dが描画される。 * 3. 黒帯が、画面中央付近で逆回転を始める。 * → 回転開始直前に、画面Cの表示は終わり、すべて画面Dに置き換わる。 * 4. 黒帯が、-270°回転したところで上下にY方向移動する。 * → このとき、上下の黒帯間には画面Eが、黒帯の外側には画面Dが描画される。 * 5. 黒帯が画面外へ消失。 * → 消失後、画面Dの表示は終わり、すべて画面Eに置き換わる。 */ namespace DTXMania2 { class 回転幕 : アイキャッチ { // 生成と終了 public 回転幕() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ロゴ = new 画像D2D( @"$(Images)\TitleLogo.png" ); this._画面BC_アイキャッチ遷移画面1_回転中 = new 舞台画像(); this._画面D_アイキャッチ遷移画面2_逆回転中 = new 舞台画像(); this._斜めジオメトリマスク = new PathGeometry( Global.GraphicResources.D2D1Factory1 ); using( var sink = this._斜めジオメトリマスク.Open() ) { // 長方形。これを、縮小&45°回転してマスクさせる。 const float w = 1920f; const float h = 1080f * 2.0f; // 斜めになるのでこのくらいいる。 sink.SetFillMode( FillMode.Winding ); sink.BeginFigure( new Vector2( -w / 2f, -h / 2f ), FigureBegin.Filled ); // (0,0) を長方形の中心とする。(スケーリング&回転させるのに都合がいい) sink.AddLine( new Vector2( -w / 2f, +h / 2f ) ); sink.AddLine( new Vector2( +w / 2f, +h / 2f ) ); sink.AddLine( new Vector2( +w / 2f, -h / 2f ) ); sink.EndFigure( FigureEnd.Closed ); sink.Close(); } this._斜めレイヤーパラメータ = new LayerParameters1 { ContentBounds = RectangleF.Infinite, GeometricMask = this._斜めジオメトリマスク, MaskAntialiasMode = AntialiasMode.PerPrimitive, MaskTransform = Matrix3x2.Identity, Opacity = 1.0f, OpacityBrush = null, LayerOptions = LayerOptions1.None, }; this.現在のフェーズ = フェーズ.未定; } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._斜めレイヤーパラメータ.GeometricMask = null; // 参照してるので先に手放す this._斜めジオメトリマスク.Dispose(); if( null != this._黒幕アニメーション ) { foreach( var b in this._黒幕アニメーション ) b.Dispose(); } this._画面D_アイキャッチ遷移画面2_逆回転中.Dispose(); this._画面BC_アイキャッチ遷移画面1_回転中.Dispose(); this._ロゴ.Dispose(); base.Dispose(); } // オープンとクローズ /// <summary> /// アイキャッチのクローズアニメーションを開始する。 /// </summary> public override void クローズする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this.現在のフェーズ = フェーズ.クローズ; if( null != this._黒幕アニメーション ) { foreach( var b in this._黒幕アニメーション ) b.Dispose(); } this._黒幕アニメーション = new 黒幕[ 2 ] { // 上&左 new 黒幕() { 中心位置X = new Variable( animation.Manager, initialValue: 1920.0/2.0 ), // クローズ初期位置、以下同 中心位置Y = new Variable( animation.Manager, initialValue: 0.0-500.0 ), 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 太さ = new Variable( animation.Manager, initialValue: 1000.0 ), 不透明度 = new Variable( animation.Manager, initialValue: 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }, // 下&右 new 黒幕() { 中心位置X = new Variable( animation.Manager, initialValue: 1920.0/2.0 ), 中心位置Y = new Variable( animation.Manager, initialValue: 1080.0+500.0 ), 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 太さ = new Variable( animation.Manager, initialValue: 1000.0 ), 不透明度 = new Variable( animation.Manager, initialValue: 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }, }; this._クローズ割合?.Dispose(); this._クローズ割合 = new Variable( animation.Manager, initialValue: 0.0 ); // 0.0 からスタート #region " ストーリーボードの構築(1) 上→左の黒幕, クローズ割合(便乗) " //---------------- var 幕 = this._黒幕アニメーション[ 0 ]; // シーン1 細くなりつつ画面中央へ移動。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン1期間 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 ), finalValue: 1080.0 / 2.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン1期間 - 0.1 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 ), finalValue: 100.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移1 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 * 0.75 ), finalValue: 0.9, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 * 0.25 ), finalValue: 0.5, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移1 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移2 ); // 便乗 using( var クローズ割合の遷移0to1 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 - 0.07/*他より短め*/), finalValue: 1.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { 幕.ストーリーボード.AddTransition( this._クローズ割合, クローズ割合の遷移0to1 ); } } // シーン2 270°回転。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン2期間 ), finalValue: Math.PI * 1.75, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); // 便乗 using( var クローズ割合の遷移1to2 = animation.TrasitionLibrary.Linear( duration: 秒( _シーン2期間 - 0.18 + 0.07/*他より長め*/), finalValue: 2.0 ) ) { 幕.ストーリーボード.AddTransition( this._クローズ割合, クローズ割合の遷移1to2 ); } } // シーン3 太くなりつつ画面左へ移動。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 0.0 - 200.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 + 0.05 ), finalValue: 800.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 * 0.25 ), finalValue: 1.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); // 便乗 using( var クローズ割合の遷移2to3 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 3.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) { 幕.ストーリーボード.AddTransition( this._クローズ割合, クローズ割合の遷移2to3 ); } } //---------------- #endregion #region " ストーリーボードの構築(2) 下→右の黒幕 " //---------------- 幕 = this._黒幕アニメーション[ 1 ]; double ずれ = 0.03; // シーン1 細くなりつつ画面中央へ移動。 double 期間 = _シーン1期間 - ずれ; using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 ), finalValue: 1080.0 / 2.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.1 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 ), finalValue: 100.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移1 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 * 0.75 ), finalValue: 0.9, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 * 0.25 ), finalValue: 0.5, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移1 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移2 ); } // シーン2 270°回転。 期間 = _シーン2期間 + ずれ; using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 ), finalValue: Math.PI * 1.75, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); } // シーン3 太くなりつつ画面右へ移動。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 1920.0 + 200.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 + 0.05 ), finalValue: 800.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 * 0.25 ), finalValue: 1.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); } //---------------- #endregion // 今すぐ開始。 var start = animation.Timer.Time; foreach( var bs in this._黒幕アニメーション ) bs.ストーリーボード.Schedule( start ); this._初めての進行描画 = true; } /// <summary> /// アイキャッチのオープンアニメーションを開始する。 /// </summary> public override void オープンする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this.現在のフェーズ = フェーズ.オープン; if( null != this._黒幕アニメーション ) { foreach( var b in this._黒幕アニメーション ) b.Dispose(); } this._黒幕アニメーション = new 黒幕[ 2 ] { // 上&左 new 黒幕() { 中心位置X = new Variable( animation.Manager, initialValue: 0.0 - 200.0 ), // オープン初期位置、以下同 中心位置Y = new Variable( animation.Manager, initialValue: 1080.0 / 2.0 ), 回転角rad = new Variable( animation.Manager, initialValue: Math.PI * 1.75 ), 太さ = new Variable( animation.Manager, initialValue: 800.0 ), 不透明度 = new Variable( animation.Manager, initialValue: 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }, // 下&右 new 黒幕() { 中心位置X = new Variable( animation.Manager, initialValue: 1920.0 + 200.0 ), 中心位置Y = new Variable( animation.Manager, initialValue: 1080.0 / 2.0 ), 回転角rad = new Variable( animation.Manager, initialValue: Math.PI * 1.75 ), 太さ = new Variable( animation.Manager, initialValue: 800.0 ), 不透明度 = new Variable( animation.Manager, initialValue: 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }, }; this._クローズ割合?.Dispose(); this._クローズ割合 = new Variable( animation.Manager, initialValue: 3.0 ); // 3.0 からスタート #region " ストーリーボードの構築(1) 上→左の黒幕, クローズ割合(便乗) " //---------------- var 幕 = this._黒幕アニメーション[ 0 ]; // シーン3 細くなりつつ画面中央へ移動。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 1920.0 / 2.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 - 0.08 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 100.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移1 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 * 0.75 ), finalValue: 0.9, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 * 0.25 ), finalValue: 0.5, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移1 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移2 ); // 便乗 using( var クローズ割合の遷移3to2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 2.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { 幕.ストーリーボード.AddTransition( this._クローズ割合, クローズ割合の遷移3to2 ); } } // シーン2 -270°回転。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン2期間 ), finalValue: 0.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン2期間 - 0.18 ) ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); // 便乗 using( var クローズ割合の遷移2to1 = animation.TrasitionLibrary.Linear( duration: 秒( _シーン2期間 - 0.18 + 0.07/*他より長め*/), finalValue: 1.0 ) ) { 幕.ストーリーボード.AddTransition( this._クローズ割合, クローズ割合の遷移2to1 ); } } // シーン1 太くなりつつ画面上方へ移動。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン1期間 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 ), finalValue: 0.0 - 500.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン1期間 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 ), finalValue: 1000.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 * 0.25 ), finalValue: 1.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var ロゴの不透明度の遷移 = animation.TrasitionLibrary.Discrete( delay: 秒( _シーン3期間 * ( 1.0 - 0.24 ) ), finalValue: 0.0, hold: ( _シーン3期間 ) / 速度倍率 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); // 便乗 using( var クローズ割合の遷移1to0 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン1期間 - 0.07/*他より短め*/), finalValue: 0.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { 幕.ストーリーボード.AddTransition( this._クローズ割合, クローズ割合の遷移1to0 ); } } //---------------- #endregion #region " ストーリーボードの構築(2) 下&右の黒幕 " //---------------- 幕 = this._黒幕アニメーション[ 1 ]; double ずれ = 0.03; // シーン3 細くなりつつ画面中央へ移動。 using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 1920.0 / 2.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( _シーン3期間 - 0.08 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 ), finalValue: 100.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移1 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 * 0.75 ), finalValue: 0.9, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( _シーン3期間 * 0.25 ), finalValue: 0.5, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移1 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移2 ); } // シーン2 -270°回転。 double 期間 = _シーン2期間 + ずれ; using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 ), finalValue: 0.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 - 0.18 ) ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); } // シーン1 太くなりつつ画面下方へ移動。 期間 = _シーン1期間 - ずれ; using( var 中心位置Xの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 ) ) ) using( var 中心位置Yの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 ), finalValue: 1080.0 + 500.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 回転radの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間 ) ) ) using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 ), finalValue: 1000.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間 * 0.25 ), finalValue: 1.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { 幕.ストーリーボード.AddTransition( 幕.中心位置X, 中心位置Xの遷移 ); 幕.ストーリーボード.AddTransition( 幕.中心位置Y, 中心位置Yの遷移 ); 幕.ストーリーボード.AddTransition( 幕.回転角rad, 回転radの遷移 ); 幕.ストーリーボード.AddTransition( 幕.太さ, 太さの遷移 ); 幕.ストーリーボード.AddTransition( 幕.不透明度, 不透明度の遷移 ); } //---------------- #endregion // 今すぐ開始。 var start = animation.Timer.Time; foreach( var bs in this._黒幕アニメーション ) bs.ストーリーボード.Schedule( start ); this._初めての進行描画 = true; } // 進行と描画 /// <summary> /// アイキャッチのアニメーションを進行し、アイキャッチ画像を描画する。 /// </summary> protected override void 進行描画する( DeviceContext d2ddc, StoryboardStatus 描画しないStatus ) { bool すべて完了 = true; var preTrans = d2ddc.Transform; #region " 背景の画像 " //---------------- switch( this.現在のフェーズ ) { case フェーズ.クローズ: { if( this._初めての進行描画 ) { this._画面BC_アイキャッチ遷移画面1_回転中.ぼかしと縮小を解除する( 0.0 ); // 全部解除してから this._画面BC_アイキャッチ遷移画面1_回転中.ぼかしと縮小を適用する(); // ゆっくり適用開始。 this._初めての進行描画 = false; } switch( this._クローズ割合.Value ) // 0 → 3.0 { // 画面A(切り替え元画面) // 画面B(アイキャッチ遷移画面1(回転中)) // 画面C(アイキャッチ画面) // ※ このメソッドの呼び出し前に、画面Aが全面描画済みであるものと想定する。 case double 割合 when( 1.0 > 割合 ): { #region " シーン1. 画面Aを下絵に、上下端から画面Bの描画領域が増えていく。(上下の黒帯の移動に伴って)" //---------------- Size2F 画面Bサイズ = this._画面BC_アイキャッチ遷移画面1_回転中.サイズ; float 画面B表示縦幅 = (float)( 画面Bサイズ.Height * 割合 / 2.0 ); // 0 → height/2 // 上から this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc, false, new Vector4( 0f, 0f, 画面Bサイズ.Width, 画面B表示縦幅 ) ); // 下から this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc, false, new Vector4( 0f, 画面Bサイズ.Height - 画面B表示縦幅, 画面Bサイズ.Width, 画面Bサイズ.Height ) ); //---------------- #endregion break; } case double 割合 when( 2.0 > 割合 ): { #region " シーン2. 画面Bを全表示。(黒帯は回転中)" //---------------- this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc ); //---------------- #endregion break; } case double 割合: // default { #region " シーン3. 画面Bを下絵に、中央から左右に向かって(黒帯の移動に従って)、画面Cの描画領域が広くなっていく。" //---------------- this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc ); // 下絵の画面B、全表示。 // 以下、画面Cを上に重ねて描画。 割合 = 割合 - 2.0; // 0 → 1.0 this._斜めレイヤーパラメータ.MaskTransform = Matrix3x2.Scaling( (float)( 割合 * 0.5 ), 1.0f ) * // x:0 → 0.5 ( ( 割合 < 0.5 ) ? Matrix3x2.Rotation( (float)( Math.PI / ( 5.85 - 1.85 * ( 割合 * 2 ) ) ) ) : Matrix3x2.Rotation( (float)( Math.PI / 4.0 ) ) // 45° ) * Matrix3x2.Translation( Global.GraphicResources.設計画面サイズ.Width / 2.0f, Global.GraphicResources.設計画面サイズ.Height / 2.0f ); // 画面中央固定。 this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc, layerParameters1: this._斜めレイヤーパラメータ ); this._ロゴを描画する( d2ddc ); //---------------- #endregion break; } } break; } case フェーズ.クローズ完了: { // 画面C(アイキャッチ画面(背景+ロゴ)) this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc ); this._ロゴを描画する( d2ddc ); break; } case フェーズ.オープン: { if( this._初めての進行描画 ) { this._画面BC_アイキャッチ遷移画面1_回転中.ぼかしと縮小を適用する( 0.0 ); // 0.0秒以内 → 最初から全部適用状態。 this._画面D_アイキャッチ遷移画面2_逆回転中.ぼかしと縮小を適用する( 0.0 ); // 全部適用してから this._画面D_アイキャッチ遷移画面2_逆回転中.ぼかしと縮小を解除する(); // ゆっくり解除開始。 this._初めての進行描画 = false; } switch( this._クローズ割合.Value ) // 3.0 → 0 { // 画面C(アイキャッチ画面) // 画面D(アイキャッチ遷移画面2(逆回転中)) // 画面E(切り替え先画面) // ※ このメソッドの呼び出し前に、画面Eが全面描画済みであるものと想定する。 case double 割合 when( 2.0 < 割合 ): { #region " シーン3. 画面Cを下絵に、左右から中央に向かって(黒帯の移動に従って)、画面Dの描画領域が広くなっていく。" //---------------- this._画面D_アイキャッチ遷移画面2_逆回転中.進行描画する( d2ddc ); // 画面D、全表示。(画面Cじゃないので注意) // 以下、画面C(画面Dじゃないので注意)を左右の黒帯の間に描画。 割合 = 割合 - 2.0; // 1.0 → 0 this._斜めレイヤーパラメータ.MaskTransform = Matrix3x2.Scaling( (float)( 割合 * 0.5 ), 1.0f ) * // x:0.5 → 0 ( ( 割合 < 0.5 ) ? Matrix3x2.Rotation( (float)( Math.PI / ( 5.85 - 1.85 * ( 割合 * 2 ) ) ) ) : Matrix3x2.Rotation( (float)( Math.PI / 4.0 ) ) // 45° ) * Matrix3x2.Translation( Global.GraphicResources.設計画面サイズ.Width / 2.0f, Global.GraphicResources.設計画面サイズ.Height / 2.0f ); // 画面中央固定。 this._画面BC_アイキャッチ遷移画面1_回転中.進行描画する( d2ddc, layerParameters1: this._斜めレイヤーパラメータ ); this._ロゴを描画する( d2ddc ); //---------------- #endregion break; } case double 割合 when( 1.0 < 割合 ): { #region " シーン2. 画面Dを全表示。(黒帯は逆回転中)" //---------------- this._画面D_アイキャッチ遷移画面2_逆回転中.進行描画する( d2ddc ); //---------------- #endregion break; } case double 割合: // default { #region " シーン1. 画面Dを下絵に、中央から上下端に向かって(黒帯の移動に従って)、画面Eの描画領域が減っていく。" //---------------- Size2F 画面Dサイズ = this._画面D_アイキャッチ遷移画面2_逆回転中.サイズ; float 画面D表示縦幅 = (float)( 画面Dサイズ.Height * 割合 / 2.0 ); // height/2 → 0 // 上から this._画面D_アイキャッチ遷移画面2_逆回転中.進行描画する( d2ddc, false, new Vector4( 0f, 0f, 画面Dサイズ.Width, 画面D表示縦幅 ) ); // 下から this._画面D_アイキャッチ遷移画面2_逆回転中.進行描画する( d2ddc, false, new Vector4( 0f, 画面Dサイズ.Height - 画面D表示縦幅, 画面Dサイズ.Width, 画面Dサイズ.Height ) ); //---------------- #endregion break; } } break; } case フェーズ.オープン完了: { // 画面E(切り替え先画面、すでに描画済みと想定) break; } } //---------------- #endregion #region " 黒帯(全シーンで共通)" //---------------- for( int i = 0; i < 2; i++ ) { var context = this._黒幕アニメーション[ i ]; if( context.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード.Status == 描画しないStatus ) continue; d2ddc.Transform = Matrix3x2.Rotation( (float)context.回転角rad.Value ) * Matrix3x2.Translation( (float)context.中心位置X.Value, (float)context.中心位置Y.Value ) * preTrans; using( var brush = new SolidColorBrush( d2ddc, new Color4( 0f, 0f, 0f, (float)context.不透明度.Value ) ) ) { float w = 2800.0f; float h = (float)context.太さ.Value; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.FillRectangle( rc, brush ); } } d2ddc.Transform = preTrans; //---------------- #endregion if( すべて完了 ) { if( this.現在のフェーズ == フェーズ.クローズ ) { this.現在のフェーズ = フェーズ.クローズ完了; } else if( this.現在のフェーズ == フェーズ.オープン ) { this.現在のフェーズ = フェーズ.オープン完了; } } } // private private bool _初めての進行描画 = false; private class 黒幕 : IDisposable { public Variable 中心位置X = null!; public Variable 中心位置Y = null!; public Variable 回転角rad = null!; public Variable 太さ = null!; public Variable 不透明度 = null!; public Storyboard ストーリーボード = null!; public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.不透明度?.Dispose(); this.太さ?.Dispose(); this.回転角rad?.Dispose(); this.中心位置Y?.Dispose(); this.中心位置X?.Dispose(); } } private 黒幕[] _黒幕アニメーション = null!; private readonly 画像D2D _ロゴ; private readonly RectangleF _ロゴ表示領域 = new RectangleF( ( 1920f - 730f ) / 2f, ( 1080f - 178f ) / 2f, 730f, 178f ); /// <summary> /// 1:全表示 ... 0:非表示 /// </summary> private Variable _クローズ割合 = null!; private readonly 舞台画像 _画面BC_アイキャッチ遷移画面1_回転中; // 画面BとCで共通。 private readonly 舞台画像 _画面D_アイキャッチ遷移画面2_逆回転中; private readonly PathGeometry _斜めジオメトリマスク; private LayerParameters1 _斜めレイヤーパラメータ; private const double _シーン1期間 = 0.3; private const double _シーン2期間 = 0.4; private const double _シーン3期間 = 0.2; private void _ロゴを描画する( DeviceContext d2ddc ) { this._ロゴ.描画する( d2ddc, this._ロゴ表示領域.Left, this._ロゴ表示領域.Top, 1.0f, X方向拡大率: ( this._ロゴ表示領域.Width / this._ロゴ.サイズ.Width ), Y方向拡大率: ( this._ロゴ表示領域.Height / this._ロゴ.サイズ.Height ), レイヤーパラメータ: this._斜めレイヤーパラメータ ); } } } <|start_filename|>SSTFormat/old/v002/スコア.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace SSTFormat.v002 { public class スコア : IDisposable, ISSTFScore { // ヘルパ /// <summary> /// 指定されたコマンド名が対象文字列内で使用されている場合に、パラメータ部分の文字列を返す。 /// </summary> /// <remarks> /// .dtx や box.def 等で使用されている "#<コマンド名>[:]<パラメータ>[;コメント]" 形式の文字列(対象文字列)について、 /// 指定されたコマンドを使用する行であるかどうかを判別し、使用する行であるなら、そのパラメータ部分の文字列を引数に格納し、true を返す。 /// 対象文字列のコマンド名が指定したコマンド名と異なる場合には、パラメータ文字列に null を格納して false を返す。 /// コマンド名は正しくてもパラメータが存在しない場合には、空文字列("") を格納して true を返す。 /// </remarks> /// <param name="対象文字列"> /// 調べる対象の文字列。(例: "#TITLE: 曲名 ;コメント") /// </param> /// <param name="コマンド名"> /// 調べるコマンドの名前(例:"TITLE")。#は不要、大文字小文字は区別されない。 /// </param> /// <returns> /// パラメータ文字列の取得に成功したら true、異なるコマンドだったなら false。 /// </returns> public static bool コマンドのパラメータ文字列部分を返す( string 対象文字列, string コマンド名, out string パラメータ文字列 ) { // コメント部分を除去し、両端をトリムする。なお、全角空白はトリムしない。 対象文字列 = 対象文字列.Split( ';' )[ 0 ].Trim( ' ', '\t' ); string 正規表現パターン = $@"^\s*#{コマンド名}(:|\s)+(.*)\s*$"; // \s は空白文字。 var m = Regex.Match( 対象文字列, 正規表現パターン, RegexOptions.IgnoreCase ); if( m.Success && ( 3 <= m.Groups.Count ) ) { パラメータ文字列 = m.Groups[ 2 ].Value; return true; } else { パラメータ文字列 = null; return false; } } // 定数プロパティ public SSTFVersion SSTFVersion { get; } = new SSTFVersion( 2, 0, 0, 0 ); public const double 初期BPM = 120.0; public const double 初期小節解像度 = 480.0; public const double BPM初期値固定での1小節4拍の時間ms = ( 60.0 * 1000 ) / ( スコア.初期BPM / 4.0 ); public const double BPM初期値固定での1小節4拍の時間sec = 60.0 / ( スコア.初期BPM / 4.0 ); /// <summary> /// 1ms あたりの設計ピクセル数 [dpx] 。 /// </summary> /// <remarks> /// BPM 150 のとき、1小節が 234 dpx になるように調整。 /// → 60秒で150拍のとき、1小節(4拍)が 234 dpx。 /// → 60秒の間に、150[拍]÷4[拍]=37.5[小節]。 /// → 60秒の間に、37.5[小節]×234[dpx/小節]= 8775[dpx]。 /// → 1ms の間に、8775[dpx]÷60000[ms]=0.14625[dpx/ms]。割り切れて良かった。 /// </remarks> public const double 基準譜面速度dpxms = 0.14625 * 2.25; // "* 2.25" は「x1.0はもう少し速くてもいいんではないか?」という感覚的な調整分。 /// <summary> /// 1秒あたりの設計ピクセル数 [dpx] 。 /// </summary> public const double 基準譜面速度dpxsec = 基準譜面速度dpxms * 1000.0; public static readonly Dictionary<レーン種別, List<チップ種別>> dicSSTFレーンチップ対応表 #region " *** " //----------------- = new Dictionary<レーン種別, List<チップ種別>>() { { レーン種別.Bass, new List<チップ種別>() { チップ種別.Bass } }, { レーン種別.BPM, new List<チップ種別>() { チップ種別.BPM } }, { レーン種別.China, new List<チップ種別>() { チップ種別.China } }, { レーン種別.HiHat, new List<チップ種別>() { チップ種別.HiHat_Close, チップ種別.HiHat_Foot, チップ種別.HiHat_HalfOpen, チップ種別.HiHat_Open } }, { レーン種別.LeftCrash, new List<チップ種別>() { チップ種別.LeftCrash, チップ種別.LeftCymbal_Mute } }, { レーン種別.Ride, new List<チップ種別>() { チップ種別.Ride, チップ種別.Ride_Cup } }, { レーン種別.RightCrash, new List<チップ種別>() { チップ種別.RightCrash, チップ種別.RightCymbal_Mute } }, { レーン種別.Snare, new List<チップ種別>() { チップ種別.Snare, チップ種別.Snare_ClosedRim, チップ種別.Snare_Ghost, チップ種別.Snare_OpenRim } }, { レーン種別.Song, new List<チップ種別>() { チップ種別.背景動画 } }, { レーン種別.Splash, new List<チップ種別>() { チップ種別.Splash } }, { レーン種別.Tom1, new List<チップ種別>() { チップ種別.Tom1, チップ種別.Tom1_Rim } }, { レーン種別.Tom2, new List<チップ種別>() { チップ種別.Tom2, チップ種別.Tom2_Rim } }, { レーン種別.Tom3, new List<チップ種別>() { チップ種別.Tom3, チップ種別.Tom3_Rim } }, }; //----------------- #endregion // 背景動画のデフォルト拡張子 public static readonly List<string> 背景動画のデフォルト拡張子s = new List<string>() { ".avi", ".flv", ".mp4", ".wmv", ".mpg", ".mpeg" }; // プロパティ;読み込み時または編集時に設定される /// <remarks> /// 背景動画ファイル名は、sstf ファイルには保存されず、必要時に sstf ファイルと同じフォルダを検索して取得する。 /// </remarks> public string 背景動画ファイル名 = ""; public class CHeader { public SSTFVersion SSTFバージョン = new SSTFVersion( 1, 0, 0, 0 ); // SSTFVersion 指定がない場合の既定値。 public string 曲名 = "(no title)"; public string 説明文 = ""; public float サウンドデバイス遅延ms = 0f; public string 譜面ファイルパス = ""; } public CHeader Header { get; protected set; } = new CHeader(); public List<チップ> チップリスト { get; protected set; } public List<double> 小節長倍率リスト { get; protected set; } public int 最大小節番号 { get { int 最大小節番号 = 0; foreach( チップ chip in this.チップリスト ) { if( chip.小節番号 > 最大小節番号 ) 最大小節番号 = chip.小節番号; } return 最大小節番号; } } public Dictionary<int, string> dicメモ { get; protected set; } = new Dictionary<int, string>(); // メソッド public スコア() { this.Header.SSTFバージョン = new SSTFVersion( 2, 0, 0, 0 ); // このソースで対応するバージョン this.チップリスト = new List<チップ>(); this.小節長倍率リスト = new List<double>(); } public スコア( string 曲データファイル名, bool ヘッダだけ = false ) : this() { if( ヘッダだけ ) this.曲データファイルを読み込む_ヘッダだけ( 曲データファイル名 ); else this.曲データファイルを読み込む( 曲データファイル名 ); } public スコア( v001_2.スコア v1_2score ) { this.Header = new CHeader() { 曲名 = v1_2score.Header.曲名, 説明文 = v1_2score.Header.説明文, サウンドデバイス遅延ms = v1_2score.Header.サウンドデバイス遅延ms, }; this.背景動画ファイル名 = v1_2score.背景動画ファイル名; this.dicメモ = v1_2score.dicメモ; this.小節長倍率リスト = v1_2score.小節長倍率リスト; this.チップリスト = new List<チップ>(); foreach( var chip in v1_2score.チップリスト ) this.チップリスト.Add( new チップ( chip ) ); } public void Dispose() { } /// <summary> /// 指定された曲データファイルを読み込む。 /// 失敗すれば何らかの例外を発出する。 /// </summary> public void 曲データファイルを読み込む( string 曲データファイル名 ) { #region " 初期化する。" //----------------- this.小節長倍率リスト = new List<double>(); this.dicメモ = new Dictionary<int, string>(); this.Header.譜面ファイルパス = 曲データファイル名; //----------------- #endregion #region " 背景動画ファイル名を更新する。" //---------------- this.背景動画ファイル名 = ( from file in Directory.GetFiles( Path.GetDirectoryName( 曲データファイル名 ) ) where スコア.背景動画のデフォルト拡張子s.Any( 拡張子名 => ( Path.GetExtension( file ).ToLower() == 拡張子名 ) ) select file ).FirstOrDefault(); //---------------- #endregion #region " 曲データファイルを読み込む。" //----------------- using( var sr = new StreamReader( 曲データファイル名, Encoding.UTF8 ) ) { int 行番号 = 0; int 現在の小節番号 = 0; int 現在の小節解像度 = 384; チップ種別 e現在のチップ = チップ種別.Unknown; while( false == sr.EndOfStream ) { // 1行ずつ読み込む。 行番号++; string 行 = this._行を読み込む( sr ); if( string.IsNullOrEmpty( 行 ) ) continue; // ヘッダコマンド処理。 #region " ヘッダコマンドの処理を行う。" //----------------- if( 行.StartsWith( "Title", StringComparison.OrdinalIgnoreCase ) ) { #region " Title コマンド " //----------------- string[] items = 行.Split( '=' ); if( items.Length != 2 ) { Trace.TraceError( $"Title の書式が不正です。スキップします。[{行番号}行目]" ); continue; } this.Header.曲名 = items[ 1 ].Trim(); //----------------- #endregion continue; } if( 行.StartsWith( "Description", StringComparison.OrdinalIgnoreCase ) ) { #region " Description コマンド " //----------------- string[] items = 行.Split( '=' ); if( items.Length != 2 ) { Trace.TraceError( $"Description の書式が不正です。スキップします。[{行番号}行目]" ); continue; } // 2文字のリテラル "\n" は改行に復号。 this.Header.説明文 = items[ 1 ].Trim().Replace( @"\n", Environment.NewLine ); //----------------- #endregion continue; } if( 行.StartsWith( "SoundDevice.Delay", StringComparison.OrdinalIgnoreCase ) ) { #region " SoundDevice.Delay コマンド " //----------------- string[] items = 行.Split( '=' ); if( items.Length != 2 ) { Trace.TraceError( $"SoundDevice.Delay の書式が不正です。スキップします。[{行番号}行目]" ); continue; } // 2文字のリテラル "\n" は改行に復号。 if( float.TryParse( items[ 1 ].Trim().Replace( @"\n", Environment.NewLine ), out float value ) ) this.Header.サウンドデバイス遅延ms = value; //----------------- #endregion continue; } //----------------- #endregion // メモ(小節単位)処理。 #region " メモ(小節単位)の処理を行う。" //----------------- if( 行.StartsWith( "PartMemo", StringComparison.OrdinalIgnoreCase ) ) { #region " '=' 以前を除去する。" //----------------- int 等号位置 = 行.IndexOf( '=' ); if( 0 >= 等号位置 ) { Trace.TraceError( $"PartMemo の書式が不正です。スキップします。[{行番号}]行目]" ); continue; } 行 = 行.Substring( 等号位置 + 1 ).Trim(); if( string.IsNullOrEmpty( 行 ) ) { Trace.TraceError( $"PartMemo の書式が不正です。スキップします。[{行番号}]行目]" ); continue; } //----------------- #endregion #region " カンマ位置を取得する。" //----------------- int カンマ位置 = 行.IndexOf( ',' ); if( 0 >= カンマ位置 ) { Trace.TraceError( $"PartMemo の書式が不正です。スキップします。[{行番号}]行目]" ); continue; } //----------------- #endregion #region " 小節番号を取得する。" //----------------- string 小節番号文字列 = 行.Substring( 0, カンマ位置 ); if( false == int.TryParse( 小節番号文字列, out int 小節番号 ) || ( 0 > 小節番号 ) ) { Trace.TraceError( $"PartMemo の小節番号が不正です。スキップします。[{行番号}]行目]" ); continue; } //----------------- #endregion #region " メモを取得する。" //----------------- string メモ = 行.Substring( カンマ位置 + 1 ); // 2文字のリテラル文字列 "\n" は改行に復号。 メモ = メモ.Replace( @"\n", Environment.NewLine ); //----------------- #endregion #region " メモが空文字列でないなら dicメモ に登録すると同時に、チップとしても追加する。" //----------------- if( !string.IsNullOrEmpty( メモ ) ) { this.dicメモ.Add( 小節番号, メモ ); this.チップリスト.Add( new チップ() { チップ種別 = チップ種別.小節メモ, 小節番号 = 小節番号, 小節内位置 = 0, 小節解像度 = 1, } ); } //----------------- #endregion continue; } //----------------- #endregion // 上記行頭コマンド以外は、チップ記述行だと見なす。 #region " チップ記述コマンドの処理を行う。" //----------------- // 行を区切り文字でトークンに分割。 string[] tokens = 行.Split( new char[] { ';', ':' } ); // すべてのトークンについて…… foreach( string token in tokens ) { // トークンを分割。 #region " トークンを区切り文字 '=' で strコマンド と strパラメータ に分割し、それぞれの先頭末尾の空白を削除する。" //----------------- string[] items = token.Split( '=' ); if( 2 != items.Length ) { if( 0 == token.Trim().Length ) // 空文字列(行末など)は不正じゃない。 continue; Trace.TraceError( $"コマンドとパラメータの記述書式が不正です。このコマンドをスキップします。[{行番号}行目]" ); continue; } string コマンド = items[ 0 ].Trim(); string パラメータ = items[ 1 ].Trim(); //----------------- #endregion // コマンド別に処理。 if( コマンド.Equals( "Part", StringComparison.OrdinalIgnoreCase ) ) { #region " Part(小節番号指定)コマンド " //----------------- #region " 小節番号を取得・設定。" //----------------- string 小節番号文字列 = this._指定された文字列の先頭から数字文字列を取り出す( ref パラメータ ); if( string.IsNullOrEmpty( 小節番号文字列 ) ) { Trace.TraceError( $"Part(小節番号)コマンドに小節番号の記述がありません。このコマンドをスキップします。[{行番号}行目]" ); continue; } if( false == int.TryParse( 小節番号文字列, out int 小節番号 ) ) { Trace.TraceError( $"Part(小節番号)コマンドの小節番号が不正です。このコマンドをスキップします。[{行番号}行目]" ); continue; } if( 0 > 小節番号 ) { Trace.TraceError( $"Part(小節番号)コマンドの小節番号が負数です。このコマンドをスキップします。[{行番号}行目]" ); continue; } 現在の小節番号 = 小節番号; //----------------- #endregion #region " Part 属性があれば取得する。" //----------------- while( 0 < パラメータ.Length ) { // 属性ID を取得。 char 属性ID = char.ToLower( パラメータ[ 0 ] ); // Part 属性があれば取得する。 if( 属性ID == 's' ) { #region " 小節長倍率(>0) → list小節長倍率 " //----------------- パラメータ = パラメータ.Substring( 1 ).Trim(); string 小節長倍率文字列 = this._指定された文字列の先頭から数字文字列を取り出す( ref パラメータ ); if( string.IsNullOrEmpty( 小節長倍率文字列 ) ) { Trace.TraceError( $"Part(小節番号)コマンドに小節長倍率の記述がありません。この属性をスキップします。[{行番号}行目]" ); continue; } パラメータ = パラメータ.Trim(); if( false == double.TryParse( 小節長倍率文字列, out double 小節長倍率 ) ) { Trace.TraceError( $"Part(小節番号)コマンドの小節長倍率が不正です。この属性をスキップします。[{行番号}行目]" ); continue; } if( 0.0 >= 小節長倍率 ) { Trace.TraceError( $"Part(小節番号)コマンドの小節長倍率が 0.0 または負数です。この属性をスキップします。[{行番号}行目]" ); continue; } // 小節長倍率辞書に追加 or 上書き更新。 this.小節長倍率を設定する( 現在の小節番号, 小節長倍率 ); //----------------- #endregion continue; } } //----------------- #endregion //----------------- #endregion continue; } if( コマンド.Equals( "Lane", StringComparison.OrdinalIgnoreCase ) ) { #region " Lane(レーン指定)コマンド(チップ種別の仮決め)" //----------------- if( パラメータ.Equals( "LeftCrash", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.LeftCrash; else if( パラメータ.Equals( "Ride", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Ride; else if( パラメータ.Equals( "China", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.China; else if( パラメータ.Equals( "Splash", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Splash; else if( パラメータ.Equals( "HiHat", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.HiHat_Close; else if( パラメータ.Equals( "Snare", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Snare; else if( パラメータ.Equals( "Bass", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Bass; else if( パラメータ.Equals( "Tom1", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Tom1; else if( パラメータ.Equals( "Tom2", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Tom2; else if( パラメータ.Equals( "Tom3", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.Tom3; else if( パラメータ.Equals( "RightCrash", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.RightCrash; else if( パラメータ.Equals( "BPM", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.BPM; else if( パラメータ.Equals( "Song", StringComparison.OrdinalIgnoreCase ) ) e現在のチップ = チップ種別.背景動画; else Trace.TraceError( $"Lane(レーン指定)コマンドのパラメータ記述 '{パラメータ}' が不正です。このコマンドをスキップします。[{行番号}行目]" ); //----------------- #endregion continue; } if( コマンド.Equals( "Resolution", StringComparison.OrdinalIgnoreCase ) ) { #region " Resolution(小節解像度指定)コマンド " //----------------- if( false == int.TryParse( パラメータ, out int 解像度 ) ) { Trace.TraceError( $"Resolution(小節解像度指定)コマンドの解像度が不正です。このコマンドをスキップします。[{行番号}行目]" ); continue; } if( 1 > 解像度 ) { Trace.TraceError( $"Resolution(小節解像度指定)コマンドの解像度は 1 以上でなければなりません。このコマンドをスキップします。[{行番号}行目]" ); continue; } 現在の小節解像度 = 解像度; //----------------- #endregion continue; } if( コマンド.Equals( "Chips", StringComparison.OrdinalIgnoreCase ) ) { #region " Chips(チップ指定)コマンド " //----------------- // パラメータを区切り文字 ',' でチップトークンに分割。 string[] chipTokens = パラメータ.Split( ',' ); // すべてのチップトークンについて…… for( int i = 0; i < chipTokens.Length; i++ ) { chipTokens[ i ].Trim(); #region " 空文字はスキップ。" //----------------- if( 0 == chipTokens[ i ].Length ) continue; //----------------- #endregion #region " チップを生成する。" //----------------- var chip = new チップ() { 小節番号 = 現在の小節番号, チップ種別 = e現在のチップ, 小節解像度 = 現在の小節解像度, 音量 = チップ.最大音量, }; chip.可視 = chip.可視の初期値; if( chip.チップ種別 == チップ種別.China ) chip.チップ内文字列 = "C N"; if( chip.チップ種別 == チップ種別.Splash ) chip.チップ内文字列 = "S P"; //----------------- #endregion #region " チップ位置を取得する。" //----------------- string 位置番号文字列 = this._指定された文字列の先頭から数字文字列を取り出す( ref chipTokens[ i ] ); chipTokens[ i ].Trim(); // 文法チェック。 if( string.IsNullOrEmpty( 位置番号文字列 ) ) { Trace.TraceError( $"チップの位置指定の記述がありません。このチップをスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } // 位置を取得。 if( false == int.TryParse( 位置番号文字列, out int チップ位置 ) ) { Trace.TraceError( $"チップの位置指定の記述が不正です。このチップをスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } // 値域チェック。 if( ( 0 > チップ位置 ) || ( チップ位置 >= 現在の小節解像度 ) ) { Trace.TraceError( $"チップの位置が負数であるか解像度(Resolution)以上の値になっています。このチップをスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } chip.小節内位置 = チップ位置; //----------------- #endregion #region " 共通属性・レーン別属性があれば取得する。" //----------------- while( chipTokens[ i ].Length > 0 ) { // 属性ID を取得。 char 属性ID = char.ToLower( chipTokens[ i ][ 0 ] ); // 共通属性があれば取得。 if( 属性ID == 'v' ) { #region " 音量 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); string 音量文字列 = this._指定された文字列の先頭から数字文字列を取り出す( ref chipTokens[ i ] ); chipTokens[ i ].Trim(); // 文法チェック。 if( string.IsNullOrEmpty( 音量文字列 ) ) { Trace.TraceError( $"チップの音量指定の記述がありません。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } // チップ音量の取得。 if( false == int.TryParse( 音量文字列, out int チップ音量 ) ) { Trace.TraceError( $"チップの音量指定の記述が不正です。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } // 値域チェック。 if( ( 1 > チップ音量 ) || ( チップ音量 > チップ.最大音量 ) ) { Trace.TraceError( $"チップの音量が適正範囲(1~{チップ.最大音量})を超えています。このチップをスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } chip.音量 = チップ音量; //----------------- #endregion continue; } // レーン別属性があれば取得。 switch( e現在のチップ ) { #region " case LeftCymbal " //----------------- case チップ種別.LeftCrash: if( 属性ID == 'm' ) { #region " Mute " //---------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.LeftCymbal_Mute; //---------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case Ride " //----------------- case チップ種別.Ride: case チップ種別.Ride_Cup: if( 属性ID == 'c' ) { #region " Ride.カップ " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Ride_Cup; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case China " //----------------- case チップ種別.China: #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion continue; //----------------- #endregion #region " case Splash " //----------------- case チップ種別.Splash: #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion continue; //----------------- #endregion #region " case HiHat " //----------------- case チップ種別.HiHat_Close: case チップ種別.HiHat_HalfOpen: case チップ種別.HiHat_Open: case チップ種別.HiHat_Foot: if( 属性ID == 'o' ) { #region " HiHat.オープン " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.HiHat_Open; //----------------- #endregion } else if( 属性ID == 'h' ) { #region " HiHat.ハーフオープン " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.HiHat_HalfOpen; //----------------- #endregion } else if( 属性ID == 'c' ) { #region " HiHat.クローズ " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.HiHat_Close; //----------------- #endregion } else if( 属性ID == 'f' ) { #region " HiHat.フットスプラッシュ " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.HiHat_Foot; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case Snare " //----------------- case チップ種別.Snare: case チップ種別.Snare_ClosedRim: case チップ種別.Snare_OpenRim: case チップ種別.Snare_Ghost: if( 属性ID == 'o' ) { #region " Snare.オープンリム " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Snare_OpenRim; //----------------- #endregion } else if( 属性ID == 'c' ) { #region " Snare.クローズドリム " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Snare_ClosedRim; //----------------- #endregion } else if( 属性ID == 'g' ) { #region " Snare.ゴースト " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Snare_Ghost; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case Bass " //----------------- case チップ種別.Bass: #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion continue; //----------------- #endregion #region " case Tom1 " //----------------- case チップ種別.Tom1: case チップ種別.Tom1_Rim: if( 属性ID == 'r' ) { #region " Tom1.リム " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Tom1_Rim; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case Tom2 " //----------------- case チップ種別.Tom2: case チップ種別.Tom2_Rim: if( 属性ID == 'r' ) { #region " Tom2.リム " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Tom2_Rim; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case Tom3 " //----------------- case チップ種別.Tom3: case チップ種別.Tom3_Rim: if( 属性ID == 'r' ) { #region " Tom3.リム " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.Tom3_Rim; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case RightCymbal " //----------------- case チップ種別.RightCrash: if( 属性ID == 'm' ) { #region " Mute " //---------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); chip.チップ種別 = チップ種別.RightCymbal_Mute; //---------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case BPM " //----------------- case チップ種別.BPM: if( 属性ID == 'b' ) { #region " BPM値 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); string BPM文字列 = this._指定された文字列の先頭から数字文字列を取り出す( ref chipTokens[ i ] ); chipTokens[ i ].Trim(); if( string.IsNullOrEmpty( BPM文字列 ) ) { Trace.TraceError( $"BPM数値の記述がありません。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } if( false == double.TryParse( BPM文字列, out double BPM ) || ( 0.0 >= BPM ) ) { Trace.TraceError( $"BPM数値の記述が不正です。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); continue; } chip.BPM = BPM; chip.チップ内文字列 = BPM.ToString( "###.##" ); //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; //----------------- #endregion #region " case Song " //----------------- case チップ種別.背景動画: #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion continue; //----------------- #endregion } #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ].Substring( 1 ).Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } //----------------- #endregion this.チップリスト.Add( chip ); } //----------------- #endregion continue; } Trace.TraceError( $"不正なコマンド「{コマンド}」が存在します。[{行番号}行目]" ); } //----------------- #endregion } sr.Close(); } //----------------- #endregion this.曲データファイルを読み込む_後処理だけ(); } public void 曲データファイルを読み込む_ヘッダだけ( string 曲データファイル名 ) { this.Header.譜面ファイルパス = 曲データファイル名; this.小節長倍率リスト = new List<double>(); // 曲データファイルのヘッダ部を読み込む。 using( var sr = new StreamReader( 曲データファイル名, Encoding.UTF8 ) ) { int 行番号 = 0; while( false == sr.EndOfStream ) { // 1行ずつ読み込む。 行番号++; string 行 = this._行を読み込む( sr ); if( string.IsNullOrEmpty( 行 ) ) continue; // ヘッダコマンド処理。 #region " ヘッダコマンドの処理を行う。" //----------------- if( 1 == 行番号 && // 先頭行に限る。 行.StartsWith( "SSTFVersion", StringComparison.OrdinalIgnoreCase ) ) { #region " SSTFバージョン " //---------------- string[] items = 行.Split( ' ' ); // SPACE 1文字 で統一するので注意 if( 2 != items.Length ) { Trace.TraceError( $"SSTFVersion の書式が不正です。スキップします(バージョンは1.0.0.0と見なされます)。[{行番号}行目]" ); continue; } try { this.Header.SSTFバージョン = new SSTFVersion( items[ 1 ].Trim() ); // string から Version へ変換できる書式であること。(例: "1.2.3.4") } catch { Trace.TraceError( $"SSTFVersion のバージョン書式が不正です。スキップします(バージョンは1.0.0.0と見なされます)。[{行番号}行目]" ); continue; } //---------------- #endregion continue; } if( 行.StartsWith( "Title", StringComparison.OrdinalIgnoreCase ) ) { #region " Title コマンド " //----------------- string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Title の書式が不正です。スキップします。[{行番号}行目]" ); continue; } this.Header.曲名 = items[ 1 ].Trim(); //----------------- #endregion continue; } if( 行.StartsWith( "Description", StringComparison.OrdinalIgnoreCase ) ) { #region " Description コマンド " //----------------- string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Description の書式が不正です。スキップします。[{行番号}行目]" ); continue; } // 2文字のリテラル "\n" は改行に復号。 this.Header.説明文 = items[ 1 ].Trim().Replace( @"\n", Environment.NewLine ); //----------------- #endregion continue; } //----------------- #endregion // 上記行頭コマンド以外は無視。 } } } /// <summary> /// すでにスコアの構築が完了しているものとして、後処理(小節線・拍線の追加、発声時刻の計算など)のみ行う。 /// </summary> public void 曲データファイルを読み込む_後処理だけ() { #region " 拍線の追加。小節線を先に追加すると小節が1つ増えるので、先に拍線から追加する。" //----------------- int 最大小節番号 = this.最大小節番号; // this.最大小節番号 プロパティはチップ数に依存して変化するので、for 文には組み込まないこと。 for( int i = 0; i <= 最大小節番号; i++ ) { double 小節長倍率 = this.小節長倍率を取得する( i ); for( int n = 1; n * 0.25 < 小節長倍率; n++ ) { this.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.拍線, 小節内位置 = (int) ( ( n * 0.25 ) * 100 ), 小節解像度 = (int) ( 小節長倍率 * 100 ), } ); } } //----------------- #endregion #region " 小節線の追加。" //----------------- 最大小節番号 = this.最大小節番号; for( int i = 0; i <= 最大小節番号 + 1; i++ ) { this.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.小節線, 小節内位置 = 0, 小節解像度 = 1, } ); } //----------------- #endregion #region " 小節の先頭 の追加。" //---------------- 最大小節番号 = this.最大小節番号; // 「小節の先頭」チップは、小節線と同じく、全小節の先頭位置に置かれる。 // 小節線には今後譜面作者によって位置をアレンジできる可能性を残したいが、 // ビュアーが小節の先頭位置を検索するためには、小節の先頭に置かれるチップが必要になる。 // よって、譜面作者の影響を受けない(ビュアー用の)チップを機械的に配置する。 for( int i = 0; i <= 最大小節番号; i++ ) { this.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.小節の先頭, 小節内位置 = 0, 小節解像度 = 1, } ); } //---------------- #endregion this.チップリスト.Sort(); #region " 全チップの発声/描画時刻と譜面内位置を計算する。" //----------------- // 1. BPMチップを無視し(初期BPMで固定)、dic小節長倍率, Cチップ.小節解像度, Cチップ.小節内位置 から両者を計算する。 // 以下、チップリストが小節番号順にソートされているという前提で。 double チップが存在する小節の先頭時刻ms = 0.0; int 現在の小節の番号 = 0; foreach( チップ chip in this.チップリスト ) { #region " チップの小節番号が現在の小節番号よりも大きい場合、チップが存在する小節に至るまで、「dbチップが存在する小節の先頭時刻ms」を更新する。" //----------------- while( 現在の小節の番号 < chip.小節番号 ) { double 現在の小節の小節長倍率 = this.小節長倍率を取得する( 現在の小節の番号 ); チップが存在する小節の先頭時刻ms += BPM初期値固定での1小節4拍の時間ms * 現在の小節の小節長倍率; 現在の小節の番号++; // 現在の小節番号 が chip.小節番号 に追いつくまでループする。 } //----------------- #endregion #region " チップの発声/描画時刻を求める。" //----------------- double チップが存在する小節の小節長倍率 = this.小節長倍率を取得する( 現在の小節の番号 ); chip.発声時刻ms = chip.描画時刻ms = (long) ( チップが存在する小節の先頭時刻ms + ( BPM初期値固定での1小節4拍の時間ms * チップが存在する小節の小節長倍率 * chip.小節内位置 ) / chip.小節解像度 ); //----------------- #endregion } // 2. BPMチップを考慮しながら調整する。(譜面内位置grid はBPMの影響を受けないので無視) double 現在のBPM = スコア.初期BPM; int チップ数 = this.チップリスト.Count; for( int i = 0; i < チップ数; i++ ) { // BPM チップ以外は無視。 var BPMチップ = this.チップリスト[ i ]; if( BPMチップ.チップ種別 != チップ種別.BPM ) continue; // BPMチップより後続の全チップの n発声/描画時刻ms を、新旧BPMの比率(加速率)で修正する。 double 加速率 = BPMチップ.BPM / 現在のBPM; // BPMチップ.dbBPM > 0.0 であることは読み込み時に保証済み。 for( int j = i + 1; j < チップ数; j++ ) { long 時刻ms = (long) ( BPMチップ.発声時刻ms + ( ( this.チップリスト[ j ].発声時刻ms - BPMチップ.発声時刻ms ) / 加速率 ) ); this.チップリスト[ j ].発声時刻ms = 時刻ms; this.チップリスト[ j ].描画時刻ms = 時刻ms; } 現在のBPM = BPMチップ.BPM; } //----------------- #endregion } /// <summary> /// 現在の スコア の内容をデータファイル(*.sstf)に書き出す。 /// </summary> /// <remarks> /// 小節線、拍線、Unknown チップは出力しない。 /// 失敗すれば何らかの例外を発出する。 /// </remarks> public void 曲データファイルを書き出す( string 曲データファイル名, string ヘッダ行 ) { using( var sw = new StreamWriter( 曲データファイル名, false, Encoding.UTF8 ) ) { // SSTFバージョンの出力 sw.WriteLine( $"# SSTFVersion {this.SSTFVersion.ToString()}" ); // ヘッダ行の出力 sw.WriteLine( $"{ヘッダ行}" ); // strヘッダ行に"{...}"が入ってても大丈夫なようにstring.Format()で囲む。 sw.WriteLine( "" ); // ヘッダコマンド行の出力 sw.WriteLine( "Title=" + ( ( string.IsNullOrEmpty( this.Header.曲名 ) ) ? "(no title)" : this.Header.曲名 ) ); if( !string.IsNullOrEmpty( this.Header.説明文 ) ) { // 改行コードは、2文字のリテラル "\n" に置換。 sw.WriteLine( "Description=" + this.Header.説明文.Replace( Environment.NewLine, @"\n" ) ); } sw.WriteLine( "SoundDevice.Delay={0}", this.Header.サウンドデバイス遅延ms ); sw.WriteLine( "" ); // 全チップの出力 #region " 全チップの最終小節番号を取得する。" //----------------- int 最終小節番号 = 0; foreach( var cc in this.チップリスト ) { if( cc.小節番号 > 最終小節番号 ) 最終小節番号 = cc.小節番号; } //----------------- #endregion for( int 小節番号 = 0; 小節番号 <= 最終小節番号; 小節番号++ ) { #region " dicレーン別チップリストの初期化。" //----------------- var dicレーン別チップリスト = new Dictionary<レーン種別, List<チップ>>(); foreach( レーン種別 laneType in Enum.GetValues( typeof( レーン種別 ) ) ) dicレーン別チップリスト[ laneType ] = new List<チップ>(); //----------------- #endregion #region " dicレーン別チップリストの構築; 小節番号 の小節に存在するチップのみをレーン別に振り分けて格納する。" //----------------- foreach( var cc in this.チップリスト ) { #region " 出力しないチップ種別は無視。" //---------------- if( cc.チップ種別 == チップ種別.小節線 || cc.チップ種別 == チップ種別.拍線 || cc.チップ種別 == チップ種別.小節メモ || cc.チップ種別 == チップ種別.小節の先頭 || cc.チップ種別 == チップ種別.Unknown ) { continue; } //---------------- #endregion if( cc.小節番号 > 小節番号 ) { // チップリストは昇順に並んでいるので、これ以上検索しても無駄。 break; } else if( cc.小節番号 == 小節番号 ) { var lane = レーン種別.Bass; // 対応するレーンがなかったら Bass でも返しておく。 foreach( var kvp in dicSSTFレーンチップ対応表 ) { if( kvp.Value.Contains( cc.チップ種別 ) ) { lane = kvp.Key; break; } } dicレーン別チップリスト[ lane ].Add( cc ); } } //----------------- #endregion #region " Part行 出力。" //----------------- sw.Write( $"Part = {小節番号.ToString()}" ); if( this.小節長倍率リスト[ 小節番号 ] != 1.0 ) sw.Write( $"s{this.小節長倍率リスト[ 小節番号 ].ToString()}" ); sw.WriteLine( ";" ); //----------------- #endregion #region " Lane, Resolution, Chip 行 出力。" //----------------- foreach( レーン種別 laneType in Enum.GetValues( typeof( レーン種別 ) ) ) { if( 0 < dicレーン別チップリスト[ laneType ].Count ) { sw.Write( $"Lane={laneType.ToString()}; " ); #region " 新しい解像度を求める。" //----------------- int 新しい解像度 = 1; foreach( var cc in dicレーン別チップリスト[ laneType ] ) 新しい解像度 = this._最小公倍数を返す( 新しい解像度, cc.小節解像度 ); //----------------- #endregion #region " dicレーン別チップリスト[ lane ] 要素の 小節解像度 と 小節内位置 を 新しい解像度 に合わせて修正する。 " //----------------- foreach( var cc in dicレーン別チップリスト[ laneType ] ) { int 倍率 = 新しい解像度 / cc.小節解像度; // 新しい解像度 は 小節解像度 の最小公倍数なので常に割り切れる。 cc.小節解像度 *= 倍率; cc.小節内位置 *= 倍率; } //----------------- #endregion sw.Write( $"Resolution = {新しい解像度}; " ); sw.Write( "Chips = " ); for( int i = 0; i < dicレーン別チップリスト[ laneType ].Count; i++ ) { チップ cc = dicレーン別チップリスト[ laneType ][ i ]; // 位置を出力。 sw.Write( cc.小節内位置.ToString() ); // 属性を出力(あれば)。 #region " (1) 共通属性 " //----------------- if( cc.音量 < チップ.最大音量 ) sw.Write( $"v{cc.音量.ToString()}" ); //----------------- #endregion #region " (2) 専用属性 " //----------------- switch( cc.チップ種別 ) { case チップ種別.Ride_Cup: sw.Write( 'c' ); break; case チップ種別.HiHat_Open: sw.Write( 'o' ); break; case チップ種別.HiHat_HalfOpen: sw.Write( 'h' ); break; case チップ種別.HiHat_Foot: sw.Write( 'f' ); break; case チップ種別.Snare_OpenRim: sw.Write( 'o' ); break; case チップ種別.Snare_ClosedRim: sw.Write( 'c' ); break; case チップ種別.Snare_Ghost: sw.Write( 'g' ); break; case チップ種別.Tom1_Rim: sw.Write( 'r' ); break; case チップ種別.Tom2_Rim: sw.Write( 'r' ); break; case チップ種別.Tom3_Rim: sw.Write( 'r' ); break; case チップ種別.LeftCymbal_Mute: sw.Write( 'm' ); break; case チップ種別.RightCymbal_Mute: sw.Write( 'm' ); break; case チップ種別.BPM: sw.Write( $"b{cc.BPM.ToString()}" ); break; } //----------------- #endregion // 区切り文字 または 終端文字 を出力 sw.Write( ( i == dicレーン別チップリスト[ laneType ].Count - 1 ) ? ";" : "," ); } sw.WriteLine( "" ); // 改行 } } //----------------- #endregion sw.WriteLine( "" ); // 次の Part 前に1行あける。 } // メモ(小節単位)の出力 #region " dicメモ を小節番号で昇順に出力する。" //----------------- var dic昇順メモ = new Dictionary<int, string>(); int 最大小節番号 = this.最大小節番号; for( int i = 0; i <= 最大小節番号; i++ ) { if( this.dicメモ.ContainsKey( i ) ) dic昇順メモ.Add( i, this.dicメモ[ i ] ); } foreach( var kvp in dic昇順メモ ) { int 小節番号 = kvp.Key; // 改行コードは、2文字のリテラル "\n" に置換。 string メモ = kvp.Value.Replace( Environment.NewLine, @"\n" ); sw.WriteLine( $"PartMemo={小節番号},{メモ}" ); } sw.WriteLine( "" ); //----------------- #endregion sw.Close(); } } /// <summary> /// 指定された Config.Speed を考慮し、指定された時間[ms]の間に流れるピクセル数[dpx]を算出して返す。</para> /// </summary> [Obsolete( "指定時間がミリ秒単位ではなく秒単位であるメソッドを使用してください。" )] public int 指定された時間msに対応する符号付きピクセル数を返す( double speed, long 指定時間ms ) { return (int) ( 指定時間ms * スコア.基準譜面速度dpxms * speed ); } /// <summary> /// 指定された Config.Speed を考慮し、指定された時間[秒]の間に流れるピクセル数[dpx]を算出して返す。 /// </summary> public double 指定された時間secに対応する符号付きピクセル数を返す( double speed, double 指定時間sec ) { return ( 指定時間sec * スコア.基準譜面速度dpxsec * speed ); } public double 小節長倍率を取得する( int 小節番号 ) { // 小節長倍率リスト が短ければ増設する。 if( 小節番号 >= this.小節長倍率リスト.Count ) { int 不足数 = 小節番号 - this.小節長倍率リスト.Count + 1; for( int i = 0; i < 不足数; i++ ) this.小節長倍率リスト.Add( 1.0 ); } // 小節番号に対応する倍率を返す。 return this.小節長倍率リスト[ 小節番号 ]; } public void 小節長倍率を設定する( int 小節番号, double 倍率 ) { // 小節長倍率リスト が短ければ増設する。 if( 小節番号 >= this.小節長倍率リスト.Count ) { int 不足数 = 小節番号 - this.小節長倍率リスト.Count + 1; for( int i = 0; i < 不足数; i++ ) this.小節長倍率リスト.Add( 1.0 ); } // 小節番号に対応付けて倍率を登録する。 this.小節長倍率リスト[ 小節番号 ] = 倍率; } // ローカル /// <summary> /// 取出文字列の先頭にある数字(小数点も有効)の連続した部分を取り出して、戻り値として返す。 /// また、取出文字列から取り出した数字文字列部分を除去した文字列を再度格納する。 /// </summary> private string _指定された文字列の先頭から数字文字列を取り出す( ref string 取出文字列 ) { int 桁数 = 0; while( ( 桁数 < 取出文字列.Length ) && ( char.IsDigit( 取出文字列[ 桁数 ] ) || 取出文字列[ 桁数 ] == '.' ) ) 桁数++; if( 0 == 桁数 ) return ""; string 数字文字列 = 取出文字列.Substring( 0, 桁数 ); 取出文字列 = ( 桁数 == 取出文字列.Length ) ? "" : 取出文字列.Substring( 桁数 ); return 数字文字列; } /// <summary> /// Stream から1行読み込み、コメントや改行等の前処理を行ってから返す。 /// </summary> /// <param name="reader"> /// 行の読み込み元。読み込んだ分、ポジションは進められる。 /// </param> /// <returns> /// 読み込んで、コメントや改行等の前処理を適用したあとの行を返す。 /// reader が EOF だった場合には null を返す。 /// </returns> private string _行を読み込む( StreamReader reader ) { if( reader.EndOfStream ) return null; // 1行読み込む。 string 行 = reader.ReadLine(); // (1) 改行とTABを空白文字に変換し、先頭末尾の空白を削除する。 行 = 行.Replace( Environment.NewLine, " " ); 行 = 行.Replace( '\t', ' ' ); 行 = 行.Trim(); // (2) 行中の '#' 以降はコメントとして除外する。 int 区切り位置 = 行.IndexOf( '#' ); if( 0 <= 区切り位置 ) { 行 = 行.Substring( 0, 区切り位置 ); 行 = 行.Trim(); } return 行; } private int _最小公倍数を返す( int m, int n ) { if( ( 0 >= m ) || ( 0 >= n ) ) throw new ArgumentOutOfRangeException( "引数に0以下の数は指定できません。" ); return ( m * n / this._最大公約数を返す( m, n ) ); } private int _最大公約数を返す( int m, int n ) { if( ( 0 >= m ) || ( 0 >= n ) ) throw new ArgumentOutOfRangeException( "引数に0以下の数は指定できません。" ); // ユーグリッドの互除法 int r; while( ( r = m % n ) != 0 ) { m = n; n = r; } return n; } } } <|start_filename|>DTXMania2/ステージ/07演奏/表示レーンの左右.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; namespace DTXMania2.演奏 { [DataContract( Name = "LanePosition", Namespace = "" )] struct 表示レーンの左右 { /// <summary> /// 演奏画面で、Ride/Ride_Cupチップを左シンバルレーン上に表示するなら true、 /// 右シンバルレーン上に表示するなら false。 /// </summary> [DataMember] public bool Rideは左 { get; set; } /// <summary> /// 演奏画面で、Chinaチップを左シンバルレーン上に表示するなら true、 /// 右シンバルレーン上に表示するなら false。 /// </summary> [DataMember] public bool Chinaは左 { get; set; } /// <summary> /// 演奏画面で、Splashチップを左シンバルレーン上に表示するなら true、 /// 右シンバルレーン上に表示するなら false。 /// </summary> [DataMember] public bool Splashは左 { get; set; } } } <|start_filename|>SSTFormat/old/v001_2/レーン種別.cs<|end_filename|> using System; namespace SSTFormat.v001_2 { public enum レーン種別 { LeftCrash, Ride, // 左右指定なし China, // 左右指定なし Splash, // 左右指定なし HiHat, Foot, Snare, Bass, Tom1, Tom2, Tom3, RightCrash, BPM, Song, } } <|start_filename|>SSTFormat/old/v003/スコア.DTX.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace SSTFormat.v003 { public partial class スコア { /// <summary> /// DTXフォーマットのファイルまたはテキストから <see cref="スコア"/> インスタンスを生成するためのクラス。 /// </summary> /// <remarks> /// テストプロジェクトに対しては InternalsVisibleTo 属性(AssemblyInfo.cs参照))により internal メソッドを可視としているため、 /// テスト対象のメソッドは、本来 private でも internal として宣言している。 /// </remarks> public static class DTX { public enum データ種別 { DTX, GDA, G2D, BMS, BME, 拡張子から判定 }; /// <summary> /// ファイルから指定された種別のデータを読み込み、スコアを生成して返す。 /// 読み込みに失敗した場合は、何らかの例外を発出する。 /// </summary> public static スコア ファイルから生成する( string ファイルパス, データ種別 データ種別 = データ種別.拡張子から判定, bool ヘッダだけ = false ) { if( データ種別 == データ種別.拡張子から判定 ) { #region " ファイルパスの拡張子からデータ種別を自動判別する。" //---------------- var 拡張子toデータ種別マップ = new Dictionary<string, データ種別>() { { ".dtx", データ種別.DTX }, { ".gda", データ種別.GDA }, { ".g2d", データ種別.G2D }, { ".bms", データ種別.BMS }, { ".bme", データ種別.BME }, }; string ファイルの拡張子 = Path.GetExtension( ファイルパス ).ToLower(); // マップから、拡張子に対応するデータ種別を取得する。 if( !( 拡張子toデータ種別マップ.TryGetValue( ファイルの拡張子, out データ種別 確定したデータ種別 ) ) ) { // マップにない拡張子はすべて DTX とみなす。 確定したデータ種別 = データ種別.DTX; } データ種別 = 確定したデータ種別; //---------------- #endregion } string 全入力文字列 = null; // ファイルの内容を一気読み。 using( var sr = new StreamReader( ファイルパス, Encoding.GetEncoding( 932/*Shift-JIS*/ ) ) ) 全入力文字列 = sr.ReadToEnd(); // 読み込んだ内容でスコアを生成する。 var score = 文字列から生成する( 全入力文字列, データ種別, ヘッダだけ ); // ファイルから読み込んだ場合のみ、このメンバが有効。 score.譜面ファイルパス = ファイルパス; return score; } /// <summary> /// 指定されたデータ種別のテキストデータを含んだ1つの文字列から、スコアを生成して返す。 /// 読み込みに失敗した場合は、何らかの例外を発出する。 /// </summary> public static スコア 文字列から生成する( string 全入力文字列, データ種別 データ種別 = データ種別.DTX, bool ヘッダだけ = false ) { if( データ種別 == データ種別.拡張子から判定 ) throw new Exception( "文字列から生成する場合には、拡張子からの自動判定は行えません。" ); 現在の.状態をリセットする(); 現在の.スコア = new スコア(); 現在の.スコア.譜面ファイルパス = null; // ファイルから読み込んだ場合のみ、このメンバが有効。 現在の.データ種別 = データ種別; 全入力文字列 = 全入力文字列.Replace( '\t', ' ' ); // TAB は空白に置換しておく。 // 読み込み using( var sr = new StringReader( 全入力文字列 ) ) { #region " すべての行について解析する。" //---------------- string 行; for( 現在の.行番号 = 1; ( 行 = sr.ReadLine() ) != null; 現在の.行番号++ ) { // 行を分割する。 if( !_行をコマンドとパラメータとコメントに分解する( 行, out 現在の.コマンド, out 現在の.コマンドzzなし, out 現在の.zz16進数, out 現在の.zz36進数, out 現在の.パラメータ, out 現在の.コメント ) ) { //Trace.TraceWarning( $"書式が不正です。無視します。[{現在の.行番号}行]" ); continue; } if( string.IsNullOrEmpty( 現在の.コマンド ) ) continue; // コマンド別に解析する。 if( _コマンドtoアクションマップ.TryGetValue( 現在の.コマンドzzなし.ToLower(), out var アクション ) || // zz付きコマンドとzzなしコマンドが重複する場合は、zzなしのほうが優先 _コマンドtoアクションマップ.TryGetValue( 現在の.コマンド.ToLower(), out アクション ) ) { if( !ヘッダだけ || アクション.ヘッダである ) アクション.解析アクション(); } else { // マップにあるコマンドに該当がなければ、オブジェクト配置として解析する。 if( !ヘッダだけ ) _コマンド_オブジェクト記述(); } } //---------------- #endregion } // 後処理 if( !ヘッダだけ ) { #region " チップリストの先頭に #BPM チップを追加する。" //---------------- { if( !( 現在の.BPM定義マップ.TryGetValue( 0, out double BPM値 ) ) ) BPM値 = スコア.初期BPM; // '#BPM:' が定義されてないなら初期BPMを使う 現在の.スコア.チップリスト.Add( new チップ() { BPM = BPM値, チップ種別 = チップ種別.BPM, 小節番号 = 0, 小節解像度 = 現在の.小節解像度, 小節内位置 = 0, 音量 = チップ.最大音量, 可視 = false, } ); } //---------------- #endregion #region " 拍線を追加する。" //----------------- { // 小節線を先に追加すると小節が1つ増えてしまうので、拍線から先に追加する。 int 最大小節番号 = 現在の.スコア.最大小節番号を返す(); // 最大小節番号はチップ数に依存して変化するので、次の for 文には組み込まないこと。 for( int i = 0; i <= 最大小節番号; i++ ) { double 小節長倍率 = 現在の.スコア.小節長倍率を取得する( i ); for( int n = 1; n * 0.25 < 小節長倍率; n++ ) { 現在の.スコア.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.拍線, 小節内位置 = (int) ( ( n * 0.25 ) * 100 ), 小節解像度 = (int) ( 小節長倍率 * 100 ), } ); } } } //----------------- #endregion #region " 小節線を追加する。" //----------------- { int 最大小節番号 = 現在の.スコア.最大小節番号を返す(); for( int i = 0; i <= 最大小節番号 + 1; i++ ) { 現在の.スコア.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.小節線, 小節内位置 = 0, 小節解像度 = 1, } ); } } //----------------- #endregion #region " 小節長倍率マップをもとに、スコアの小節長倍率リストを構築する。" //---------------- { double 現在の倍率 = 1.0; int 最大小節番号 = 現在の.スコア.最大小節番号を返す(); for( int i = 0; i <= 最大小節番号; i++ ) // すべての小節に対して設定。(SST仕様) { if( 現在の.小節長倍率マップ.ContainsKey( i ) ) 現在の倍率 = 現在の.小節長倍率マップ[ i ]; // 指定された倍率は、それが指定された小節以降の小節にも適用する。(DTX仕様) 現在の.スコア.小節長倍率を設定する( i, 現在の倍率 ); } } //---------------- #endregion #region " BPMチップの値を引き当てる。" //---------------- foreach( var kvp in 現在の.BPM参照マップ ) { // BPMチャンネルから作成された BPMチップには、BASEBPM を加算する。 // #BASEBPM が複数宣言されていた場合は、最後の値が使用される。 kvp.Key.BPM = 現在の.BASEBPM + 現在の.BPM定義マップ[ kvp.Value ]; } // 引き当てが終わったら、マップが持つチップへの参照を解放する。 現在の.BPM参照マップ.Clear(); //---------------- #endregion #region " WAVチップのPAN値, VOLUME値を引き当てる。" //---------------- foreach( var chip in 現在の.スコア.チップリスト ) { // このクラスで実装しているチャンネルで、 var query = _DTXチャンネルプロパティマップ.Where( ( kvp ) => ( kvp.Value.チップ種別 == chip.チップ種別 ) ); if( 1 == query.Count() ) { var kvp = query.Single(); // タプル型なので SingleOrDefault() は使えない。 // WAV を使うチャンネルで、 if( kvp.Value.WAVを使う ) { // PAN の指定があるなら、 if( 現在の.PAN定義マップ.ContainsKey( chip.チップサブID ) ) { // それをチップに設定する。 chip.左右位置 = 現在の.PAN定義マップ[ chip.チップサブID ]; } // VOLUME の指定があるなら、 if( 現在の.VOLUME定義マップ.ContainsKey( chip.チップサブID ) ) { // それをチップに設定する。 var DTX音量 = Math.Clamp( 現在の.VOLUME定義マップ[ chip.チップサブID ], min: 0, max: 100 ); // 無音:0 ~ 100:原音 chip.音量 = ( 100 == DTX音量 ) ? チップ.最大音量 : (int) ( DTX音量 * チップ.最大音量 / 100.0 ) + 1; } } } } //---------------- #endregion スコア._後処理を行う( 現在の.スコア ); } return 現在の.スコア; } /// <summary> /// 解析時の状態を保持するクラス。 /// static クラスなので、利用前には <see cref="状態をリセットする"/> を呼び出して前回の解析状態をクリアすること。 /// </summary> internal static class 現在の { public static スコア スコア; public static データ種別 データ種別; public static Random Random; public static int 行番号; public static string コマンド; public static string コマンドzzなし; // コマンドの末尾に、16進数2桁または36進数2桁と解釈できる文字列があるなら、それを除外したコマンド文。ないならコマンドと同じ。 public static int zz16進数; // コマンドの末尾に16進数2桁と解釈できる文字列があるならそれを10進数に変換した値。なければ -1。 public static int zz36進数; // コマンドの末尾に36進数2桁と解釈できる文字列があるならそれを10進数に変換した値。なければ -1。 public static string パラメータ; public static string コメント; public static int 小節番号; public static int チャンネル番号; public static チップ種別 チップ種別; public static int 小節解像度; public static int オブジェクト総数; public static int オブジェクト番号; /// <summary> /// [key: zz番号, value: PAN値(左:-100~中央:0~+100:右)] /// </summary> public static Dictionary<int, int> PAN定義マップ; /// <summary> /// [key: zz番号, key: VOLUME値(0:無音 ~ 100:原音)] /// </summary> public static Dictionary<int, int> VOLUME定義マップ; /* #BPM, #BPMzz の処理方法: * ・#BPMzz は、BPM定義マップ[1~3599] に登録する。 * ・#BPM は、#BPM00 とみなして BPM定義マップ[0] に登録する。 * ・ch.03 (整数BPM) はそのまま SSTチップ(BPM) としてチップリストに登録する。 * ・ch.08(拡張BPM)は、BPM値が 0 の SSTチップ(BPM) をチップリストに登録する。同時に、BPM参照マップ[チップ] にも登録する。 * ・DTXファイル読み込み後の後処理として、BPM参照マップ に掲載されているすべての SSTチップ(BPM) の BPM値を、BPM定義マップ から引き当てて設定する。 */ public static double BASEBPM = 0.0; /// <summary> /// [key: zz番号, value: BPM] /// </summary> public static Dictionary<int, double> BPM定義マップ; /// <summary> /// [key: BPMチップ, value: BPM定義のzz番号] /// </summary> public static Dictionary<チップ, int> BPM参照マップ; /* 小節長倍率の処理方法: * ・DTXでは指定した小節以降の小節長がすべて変わってしまうが、SSTでは指定した小節の小節長のみ変わる。 * ・そのため、解析時は 小節長倍率マップ に指定があった小節の情報のみ残しておき、 * 後処理でまとめて スコア.小節長倍率リスト に登録するものとする。 * ・なお、スコア.小節長倍率リスト には存在するすべての小節が登録されていなければならない。(スコアクラスの仕様) */ /// <summary> /// [key: 小節番号, value: 倍率] /// </summary> public static SortedDictionary<int, double> 小節長倍率マップ; // 初期化。 public static void 状態をリセットする() { スコア = null; データ種別 = データ種別.DTX; Random = new Random( (int) ( Stopwatch.GetTimestamp() % int.MaxValue ) ); 行番号 = 0; コマンド = ""; コマンドzzなし = ""; zz16進数 = -1; zz36進数 = -1; パラメータ = ""; コメント = ""; 小節番号 = 0; チャンネル番号 = 0; チップ種別 = チップ種別.Unknown; 小節解像度 = 384; // DTX の小節解像度は 384 固定 オブジェクト総数 = 0; オブジェクト番号 = 0; PAN定義マップ = new Dictionary<int, int>(); VOLUME定義マップ = new Dictionary<int, int>(); BASEBPM = 0.0; BPM定義マップ = new Dictionary<int, double>(); BPM参照マップ = new Dictionary<チップ, int>(); 小節長倍率マップ = new SortedDictionary<int, double>(); } } internal static bool _行をコマンドとパラメータとコメントに分解する( string 行, out string コマンド, out string コマンドzzなし, out int zz16進数, out int zz36進数, out string パラメータ, out string コメント ) { コマンド = null; コマンドzzなし = null; zz16進数 = -1; zz36進数 = -1; パラメータ = null; コメント = null; // コマンド, パラメータ, コメント の3つに分割する。 #if DEBUG string 行の正規表現 = @"^\s*(?:#\s*([^:;\s]*)[:\s]*([^;]*)?)?[;\s]*(.*)$"; // 仕様の詳細については、テストクラスを参照のこと。 var m = Regex.Match( 行, 行の正規表現 ); if( !m.Success || ( 4 != m.Groups.Count ) ) return false; コマンド = m.Groups[ 1 ].Value?.Trim(); パラメータ = m.Groups[ 2 ].Value?.Trim(); コメント = m.Groups[ 3 ].Value?.Trim(); #else // todo: Release 版はいずれ高速化したい…… string 行の正規表現 = @"^\s*(?:#\s*([^:;\s]*)[:\s]*([^;]*)?)?[;\s]*(.*)$"; // 仕様の詳細については、テストクラスを参照のこと。 var m = Regex.Match( 行, 行の正規表現 ); if( !m.Success || ( 4 != m.Groups.Count ) ) return false; コマンド = m.Groups[ 1 ].Value?.Trim(); パラメータ = m.Groups[ 2 ].Value?.Trim(); コメント = m.Groups[ 3 ].Value?.Trim(); #endif // 残りを決定する。 コマンドzzなし = コマンド; int len = コマンド.Length; if( 2 < len ) { if( !_16進数2桁の文字列を数値に変換して返す( コマンド.Substring( len - 2 ), out zz16進数 ) ) zz16進数 = -1; if( !_36進数2桁の文字列を数値に変換して返す( コマンド.Substring( len - 2 ), out zz36進数 ) ) zz36進数 = -1; if( -1 != zz16進数 || -1 != zz36進数 ) // どっちか取得できた コマンドzzなし = コマンド.Substring( 0, len - 2 ); } return true; } internal static void _コマンド_TITLE() { 現在の.スコア.曲名 = 現在の.パラメータ; } internal static void _コマンド_ARTIST() { 現在の.スコア.アーティスト名 = 現在の.パラメータ; } internal static void _コマンド_COMMENT() { 現在の.スコア.説明文 = 現在の.パラメータ; } internal static void _コマンド_DLEVEL_PLAYLEVEL() { if( !int.TryParse( 現在の.パラメータ, out int level ) ) { Trace.TraceError( $"#DLEVEL(PLAYLEVEL) の値の取得に失敗しました。[{現在の.行番号}行]" ); return; } 現在の.スコア.難易度 = Math.Clamp( level, min: 0, max: 99 ) / 10.0; // 0~99 → 0.0~9.90 } internal static void _コマンド_PREVIEW() { 現在の.スコア.プレビュー音声ファイル名 = 現在の.パラメータ; } internal static void _コマンド_PREIMAGE() { 現在の.スコア.プレビュー画像ファイル名 = 現在の.パラメータ; } internal static void _コマンド_PREMOVIE() { 現在の.スコア.プレビュー動画ファイル名 = 現在の.パラメータ; } internal static void _コマンド_PATH_WAV() { 現在の.スコア.PATH_WAV = 現在の.パラメータ; } internal static void _コマンド_WAVzz() { if( -1 == 現在の.zz36進数 ) { Trace.TraceError( $"#WAV のWAV番号の取得に失敗しました。[{現在の.行番号}行]" ); return; } if( 1 > 現在の.zz36進数 || 36 * 36 <= 現在の.zz36進数 ) { Trace.TraceError( $"#WAV のWAV番号に 01~ZZ 以外の値が指定されています。[{現在の.行番号}行]" ); return; } // ここでは、PATH_WAV はまだ反映しない。 現在の.スコア.WAVリスト[ 現在の.zz36進数 ] = (現在の.パラメータ, true); // あれば上書き、なければ追加 } internal static void _コマンド_PANzz_WAVPANzz() { if( -1 == 現在の.zz36進数 ) { Trace.TraceError( $"#PAN(WAVPAN) のWAV番号の取得に失敗しました。[{現在の.行番号}行]" ); return; } if( 1 > 現在の.zz36進数 || 36 * 36 <= 現在の.zz36進数 ) { Trace.TraceError( $"#PAN(WAVPAN) のWAV番号に 01~ZZ 以外の値が指定されています。[{現在の.行番号}行]" ); return; } if( !int.TryParse( 現在の.パラメータ, out int PAN値 ) ) { Trace.TraceError( $"#PAN(WAVPAN) のPAN値の取得に失敗しました。[{現在の.行番号}行]" ); return; } 現在の.PAN定義マップ[ 現在の.zz36進数 ] = Math.Clamp( PAN値, min: -100, max: +100 ); // あれば上書き、なければ追加 } internal static void _コマンド_VOLUMEzz_WAVVOLzz() { if( -1 == 現在の.zz36進数 ) { Trace.TraceError( $"#VOLUME(WAVVOL) のWAV番号の取得に失敗しました。[{現在の.行番号}行]" ); return; } if( 1 > 現在の.zz36進数 || 36 * 36 <= 現在の.zz36進数 ) { Trace.TraceError( $"#VOLUME(WAVVOL) のWAV番号に 01~ZZ 以外の値が指定されています。[{現在の.行番号}行]" ); return; } if( !int.TryParse( 現在の.パラメータ, out int VOLUME値 ) ) { Trace.TraceError( $"#VOLUME(WAVVOL) の値の取得に失敗しました。[{現在の.行番号}行]" ); return; } 現在の.VOLUME定義マップ[ 現在の.zz16進数 ] = Math.Clamp( VOLUME値, min: 0, max: 100 ); // あれば上書き、なければ追加 } internal static void _コマンド_BASEBPM() { if( !_DTX仕様の実数を取得する( 現在の.パラメータ, out double BPM値 ) ) { Trace.TraceWarning( $"#BASEBPM の値の取得に失敗しました。[{現在の.行番号}行]" ); return; } if( 0.0 > BPM値 ) { Trace.TraceWarning( $"#BASEBPM の値に負数が指定されています。[{現在の.行番号}行]" ); return; } 現在の.BASEBPM = BPM値; // 上書き可 } internal static void _コマンド_BPM_BPMzz() { if( "bpm" == 現在の.コマンド.ToLower() ) { 現在の.zz36進数 = 0; } if( 0 > 現在の.zz36進数 || 36 * 36 <= 現在の.zz36進数 ) { Trace.TraceError( $"#BPM のWAV番号に 00~ZZ 以外の値が指定されています。[{現在の.行番号}行]" ); return; } if( !_DTX仕様の実数を取得する( 現在の.パラメータ, out double BPM値 ) || ( 0.0 >= BPM値 ) || ( 1000.0 <= BPM値 ) ) // 値域制限(<1000)はDTX仕様 { Trace.TraceError( $"#BPM のBPM値が不正です。[{現在の.行番号}行]" ); return; } 現在の.BPM定義マップ[ 現在の.zz36進数 ] = BPM値; // あれば上書き、なければ追加 } internal static void _コマンド_AVIzz() { if( -1 == 現在の.zz36進数 ) { Trace.TraceError( $"#AVI のAVI番号の取得に失敗しました。[{現在の.行番号}行]" ); return; } if( 1 > 現在の.zz36進数 || 36 * 36 <= 現在の.zz36進数 ) { Trace.TraceError( $"#AVI のAVI番号に 01~ZZ 以外の値が指定されています。[{現在の.行番号}行]" ); return; } // ここでは、PATH_WAV はまだ反映しない。 現在の.スコア.AVIリスト[ 現在の.zz36進数 ] = 現在の.パラメータ; // あれば上書き、なければ追加 } internal static void _コマンド_オブジェクト記述() { #region " 小節番号とチャンネル番号を取得する。" //---------------- if( !_小節番号とチャンネル番号を取得する( 現在の.コマンド, out 現在の.小節番号, out 現在の.チャンネル番号 ) ) { //Trace.TraceWarning( $"小節番号またはチャンネル番号の取得に失敗しました。[{現在の.行番号}行]" ); return; } // 番号をずらして、先頭に空の小節を1つ設ける。(いきなり演奏が始まらないように。) 現在の.小節番号++; //---------------- #endregion if( 0x02 == 現在の.チャンネル番号 ) { #region " ch02 小節長倍率 はオブジェクト記述ではないので別途処理する。" //---------------- if( !_DTX仕様の実数を取得する( 現在の.パラメータ, out double 小節長倍率 ) ) { Trace.TraceWarning( $"ch02 のパラメータ(小節長倍率)の値の取得に失敗しました。[{現在の.行番号}行目]" ); return; } if( 0.0 >= 小節長倍率 ) { Debug.WriteLine( $"ch02 のパラメータ(小数長倍率)に 0 または負数を指定することはできません。[{現在の.行番号}行目]" ); return; } 現在の.小節長倍率マップ[ 現在の.小節番号 ] = 小節長倍率; // あれば上書き、なければ追加 //---------------- #endregion return; } 現在の.パラメータ = 現在の.パラメータ.Replace( "_", "" ); // 見やすさのために '_' を区切り文字として使用できる(DTX仕様) 現在の.パラメータ = 現在の.パラメータ.ToLower(); // すべて小文字化 現在の.オブジェクト総数 = 現在の.パラメータ.Length / 2; // 1オブジェクトは2文字;余った末尾は切り捨てる。(DTX仕様) // すべてのオブジェクトについて... for( 現在の.オブジェクト番号 = 0; 現在の.オブジェクト番号 < 現在の.オブジェクト総数; 現在の.オブジェクト番号++ ) { string オブジェクト記述 = 現在の.パラメータ.Substring( 現在の.オブジェクト番号 * 2, 2 ); if( "00" == オブジェクト記述 ) continue; // 00 はスキップ。 int オブジェクト値 = 0; #region " オブジェクト値を取得。" //---------------- if( 0x03 == 現在の.チャンネル番号 ) { // (A) ch03 (BPM) のみ 16進数2桁表記 if( !_16進数2桁の文字列を数値に変換して返す( オブジェクト記述, out オブジェクト値 ) ) { Debug.WriteLine( $"オブジェクトの記述に不正があります。[{現在の.行番号}行目]" ); return; } } else { // (B) その他は 36進数2桁表記 if( !_36進数2桁の文字列を数値に変換して返す( オブジェクト記述, out オブジェクト値 ) ) { Debug.WriteLine( $"オブジェクトの記述に不正があります。[{現在の.行番号}行目]" ); return; } } //---------------- #endregion チップ chip; #region " チップを作成する。" //---------------- { // チャンネルに対応するチャンネルプロパティを取得。 if( !_DTXチャンネルプロパティマップ.TryGetValue( 現在の.チャンネル番号, out var チャンネルプロパティ ) ) continue; // ないなら無視。 // チップを生成。 chip = new チップ() { チップ種別 = チャンネルプロパティ.チップ種別, チップサブID = オブジェクト値, 小節番号 = 現在の.小節番号, 小節解像度 = 現在の.小節解像度, 小節内位置 = (int) ( 現在の.小節解像度 * 現在の.オブジェクト番号 / 現在の.オブジェクト総数 ), 音量 = チップ.最大音量, // DTX の音量は既定で最大 可視 = チャンネルプロパティ.可視, }; // オプション処理があれば行う。 switch( 現在の.チャンネル番号 ) { // BPM case 0x03: chip.BPM = オブジェクト値 + 現在の.BASEBPM; // 引き当てないので、ここでBASEBPMを加算する。 break; // 拡張BPM case 0x08: chip.BPM = 0.0; // あとで引き当てる。BASEBPMは引き当て時に加算する。 現在の.BPM参照マップ.Add( chip, オブジェクト値 ); // 引き当てを予約。 break; // SE1~5 case int ch when( 0x61 <= ch && ch <= 0x65 ): _WAVの多重再生を無効にする( オブジェクト値 ); break; // チップ配置(ギター) case int ch when( 0x20 <= ch && ch <= 0x27 ): _WAVの多重再生を無効にする( オブジェクト値 ); break; // チップ配置(ベース) case int ch when( 0xA0 <= ch && ch <= 0xA7 ): _WAVの多重再生を無効にする( オブジェクト値 ); break; // 空打ち(ドラム) case 0xB1: 現在の.スコア.空打ちチップマップ[ レーン種別.HiHat ] = オブジェクト値; break; // HiHat Open と共有 case 0xB2: 現在の.スコア.空打ちチップマップ[ レーン種別.Snare ] = オブジェクト値; break; case 0xB3: 現在の.スコア.空打ちチップマップ[ レーン種別.Bass ] = オブジェクト値; break; case 0xB4: 現在の.スコア.空打ちチップマップ[ レーン種別.Tom1 ] = オブジェクト値; break; case 0xB5: 現在の.スコア.空打ちチップマップ[ レーン種別.Tom2 ] = オブジェクト値; break; case 0xB6: 現在の.スコア.空打ちチップマップ[ レーン種別.RightCrash ] = オブジェクト値; // ReftCrash と China は共有 現在の.スコア.空打ちチップマップ[ レーン種別.China ] = オブジェクト値; break; case 0xB7: 現在の.スコア.空打ちチップマップ[ レーン種別.Tom3 ] = オブジェクト値; break; case 0xB8: 現在の.スコア.空打ちチップマップ[ レーン種別.HiHat ] = オブジェクト値; break; // HiHat Close と共有 case 0xB9: 現在の.スコア.空打ちチップマップ[ レーン種別.Ride ] = オブジェクト値; break; case 0xBC: 現在の.スコア.空打ちチップマップ[ レーン種別.LeftCrash ] = オブジェクト値; // LeftCrash と Splash は共有 現在の.スコア.空打ちチップマップ[ レーン種別.Splash ] = オブジェクト値; break; } // ローカル関数 void _WAVの多重再生を無効にする( int WAV番号 ) { var dicWAV = 現在の.スコア.WAVリスト; if( dicWAV.ContainsKey( WAV番号 ) ) dicWAV[ WAV番号 ] = (dicWAV[ WAV番号 ].ファイルパス, 多重再生する: false); } } //---------------- #endregion 現在の.スコア.チップリスト.Add( chip ); } } internal static bool _DTX仕様の実数を取得する( string 文字列, out double 数値 ) { // DTX仕様の実数の定義(カルチャ非依存) // --> 仕様の詳細はテストメソッドを参照のこと。 const string 小数点文字s = ".,"; // '.' の他に ',' も使える。 const string 任意の桁区切り文字 = @"[\.,' ]"; // 小数点文字と被ってる文字もあるので注意。 int 小数点の位置 = 文字列.LastIndexOfAny( 小数点文字s.ToCharArray() ); // 小数点文字s のうち、一番最後に現れた箇所。(DTX仕様) string 整数部; string 小数部; // 整数部と小数部に分けて取得し、それぞれから桁区切り文字を除去する。 if( -1 == 小数点の位置 ) { // (A) 小数点がない場合 整数部 = Regex.Replace( 文字列, 任意の桁区切り文字, "" ); 小数部 = ""; } else { // (B) 小数点がある場合 整数部 = Regex.Replace( 文字列.Substring( 0, 小数点の位置 ), 任意の桁区切り文字, "" ); 小数部 = Regex.Replace( 文字列.Substring( 小数点の位置 + 1 ), 任意の桁区切り文字, "" ); } // 整数部+小数点+小数部 で CurrentCulture な実数文字列を作成し、double へ変換する。 return double.TryParse( $"{整数部}{CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator}{小数部}", out 数値 ); } internal static bool _16進数2桁の文字列を数値に変換して返す( string 文字列, out int 値 ) { 値 = 0; if( 2 > 文字列.Length ) return false; 文字列 = 文字列.ToLower(); int _10の位 = _16進数変換表.IndexOf( 文字列[ 0 ] ); int _1の位 = _16進数変換表.IndexOf( 文字列[ 1 ] ); if( -1 == _10の位 || -1 == _1の位 ) return false; 値 = ( _10の位 * 16 ) + _1の位; return true; } internal static bool _36進数2桁の文字列を数値に変換して返す( string 文字列, out int 値 ) { 値 = 0; if( 2 > 文字列.Length ) return false; 文字列 = 文字列.ToLower(); int _10の位 = _36進数変換表.IndexOf( 文字列[ 0 ] ); int _1の位 = _36進数変換表.IndexOf( 文字列[ 1 ] ); if( -1 == _10の位 || -1 == _1の位 ) return false; 値 = ( _10の位 * 36 ) + _1の位; return true; } internal static bool _小節番号とチャンネル番号を取得する( string コマンド, out int 小節番号, out int チャンネル番号 ) { 小節番号 = 0; チャンネル番号 = 0; if( 5 != コマンド.Length ) return false; // 必ず5文字ちょうどであること。 #region " 小節番号を取得する。" //---------------- { var 小節番号文字列 = コマンド.Substring( 0, 3 ).ToLower(); // 先頭 3 文字 int 百の位 = _36進数変換表.IndexOf( 小節番号文字列[ 0 ] ); // 0~Z(36進数1桁) int 十の位 = _16進数変換表.IndexOf( 小節番号文字列[ 1 ] ); // 0~9(10進数1桁) int 一の位 = _16進数変換表.IndexOf( 小節番号文字列[ 2 ] ); // 0~9(10進数1桁) if( -1 == 百の位 || -1 == 十の位 || -1 == 一の位 ) { //Trace.TraceWarning( $"小節番号が不正です。[{現在の.行番号}行]" ); return false; } 小節番号 = ( 百の位 * 100 ) + ( 十の位 * 10 ) + 一の位; } //---------------- #endregion #region " チャンネル番号を取得する。" //---------------- { var チャンネル文字列 = コマンド.Substring( 3, 2 ).ToLower(); // 後ろ 2 文字 switch( 現在の.データ種別 ) { case データ種別.GDA: case データ種別.G2D: // 英数字2桁 if( !_GDAtoDTXチャンネルマップ.TryGetValue( チャンネル文字列.ToUpper(), out チャンネル番号 ) ) { //Trace.TraceWarning( $"チャンネル番号が不正です。[{現在の.行番号}行]" ); return false; } break; default: // 16進数2桁 if( !_16進数2桁の文字列を数値に変換して返す( チャンネル文字列, out チャンネル番号 ) ) { //Trace.TraceWarning( $"チャンネル番号が不正です。[{現在の.行番号}行]" ); return false; } break; } } //---------------- #endregion return true; } private static readonly string _16進数変換表 = "0123456789abcdef"; // めんどいので大文字は考慮しない。利用先で小文字に変換のこと。 private static readonly string _36進数変換表 = "0123456789abcdefghijklmnopqrstuvwxyz"; // 同上。 private static readonly Dictionary<string, (bool ヘッダである, Action 解析アクション)> _コマンドtoアクションマップ = new Dictionary<string, (bool, Action)> { #region " *** " //---------------- // コマンド名, ヘッダである, 解析アクション { "title", ( true, _コマンド_TITLE ) }, { "artist", ( true, _コマンド_ARTIST ) }, { "comment", ( true, _コマンド_COMMENT ) }, { "path_wav", ( true, _コマンド_PATH_WAV ) }, { "wav", ( false, _コマンド_WAVzz ) }, { "pan", ( false, _コマンド_PANzz_WAVPANzz ) }, { "wavpan", ( false, _コマンド_PANzz_WAVPANzz ) }, { "volume", ( false, _コマンド_VOLUMEzz_WAVVOLzz ) }, { "wavvol", ( false, _コマンド_VOLUMEzz_WAVVOLzz ) }, { "basebpm", ( true, _コマンド_BASEBPM ) }, { "bpm", ( true, _コマンド_BPM_BPMzz ) }, { "dlevel", ( true, _コマンド_DLEVEL_PLAYLEVEL ) }, { "playlevel", ( true, _コマンド_DLEVEL_PLAYLEVEL ) }, { "preview", ( true, _コマンド_PREVIEW ) }, { "preimage", ( true, _コマンド_PREIMAGE ) }, { "premovie", ( true, _コマンド_PREMOVIE ) }, { "avi", ( true, _コマンド_AVIzz ) }, //---------------- #endregion }; // ここにないGDA/G2Dチャンネルは未対応。 private static readonly Dictionary<string, int> _GDAtoDTXチャンネルマップ = new Dictionary<string, int> { #region " *** " //---------------- //GDAチャンネル, DTXチャンネル { "TC", 0x03 }, // BPM { "BL", 0x02 }, // BarLength; 小節長 { "GS", 0x29 }, // ギター譜面スピード { "DS", 0x30 }, // ドラム譜面スピード { "FI", 0x53 }, // フィルイン { "HH", 0x11 }, // ハイハットクローズ { "SD", 0x12 }, // スネア { "BD", 0x13 }, // バスドラム { "HT", 0x14 }, // ハイタム { "LT", 0x15 }, // ロータム { "CY", 0x16 }, // 右シンバル { "G0", 0x20 }, // ギター OPEN { "G1", 0x21 }, // ギター --B { "G2", 0x22 }, // ギター -G- { "G3", 0x23 }, // ギター -GB { "G4", 0x24 }, // ギター R-- { "G5", 0x25 }, // ギター R-B { "G6", 0x26 }, // ギター RG- { "G7", 0x27 }, // ギター RGB { "GW", 0x28 }, // ギター Wailing { "01", 0x01 }, // BGM { "02", 0x62 }, // SE 02 { "03", 0x63 }, // SE 03 { "04", 0x64 }, // SE 04 { "05", 0x65 }, // SE 05 { "06", 0x66 }, // SE 06 { "07", 0x67 }, // SE 07 { "08", 0x68 }, // SE 08 { "09", 0x69 }, // SE 09 { "0A", 0x70 }, // SE 10 { "0B", 0x71 }, // SE 11 { "0C", 0x72 }, // SE 12 { "0D", 0x73 }, // SE 13 { "0E", 0x74 }, // SE 14 { "0F", 0x75 }, // SE 15 { "10", 0x76 }, // SE 16 { "11", 0x77 }, // SE 17 { "12", 0x78 }, // SE 18 { "13", 0x79 }, // SE 19 { "14", 0x80 }, // SE 20 { "15", 0x81 }, // SE 21 { "16", 0x82 }, // SE 22 { "17", 0x83 }, // SE 23 { "18", 0x84 }, // SE 24 { "19", 0x85 }, // SE 25 { "1A", 0x86 }, // SE 26 { "1B", 0x87 }, // SE 27 { "1C", 0x88 }, // SE 28 { "1D", 0x89 }, // SE 29 { "1E", 0x90 }, // SE 30 { "1F", 0x91 }, // SE 31 { "20", 0x92 }, // SE 32 { "B0", 0xA0 }, // ベース OPEN { "B1", 0xA1 }, // ベース --B { "B2", 0xA2 }, // ベース -G- { "B3", 0xA3 }, // ベース -GB { "B4", 0xA4 }, // ベース R-- { "B5", 0xA5 }, // ベース R-B { "B6", 0xA6 }, // ベース RG- { "B7", 0xA7 }, // ベース RGB { "BW", 0xA8 }, // ベース Wailing //---------------- #endregion }; // ここにないDTXチャンネルは未対応。 private static readonly Dictionary<int, (チップ種別 チップ種別, bool 可視, bool WAVを使う)> _DTXチャンネルプロパティマップ = new Dictionary<int, (チップ種別 チップ種別, bool 可視, bool WAVを使う)> { #region " *** " //---------------- { 0x01, ( チップ種別.BGM, false, true ) }, // バックコーラス(BGM) { 0x02, ( チップ種別.Unknown, false, false ) }, // 小節長倍率 ... SSTFではチップじゃない。 { 0x03, ( チップ種別.BPM, false, false ) }, // BPM { 0x08, ( チップ種別.BPM, false, false ) }, // 拡張BPM { 0x11, ( チップ種別.HiHat_Close,true, true ) }, // チップ配置(ドラム)・ハイハットクローズ { 0x12, ( チップ種別.Snare, true, true ) }, // チップ配置(ドラム)・スネア { 0x13, ( チップ種別.Bass, true, true ) }, // チップ配置(ドラム)・バス { 0x14, ( チップ種別.Tom1, true, true ) }, // チップ配置(ドラム)・ハイタム { 0x15, ( チップ種別.Tom2, true, true ) }, // チップ配置(ドラム)・ロータム { 0x16, ( チップ種別.RightCrash, true, true ) }, // チップ配置(ドラム)・右シンバル { 0x17, ( チップ種別.Tom3, true, true ) }, // チップ配置(ドラム)・フロアタム { 0x18, ( チップ種別.HiHat_Open, true, true ) }, // チップ配置(ドラム)・ハイハットオープン { 0x19, ( チップ種別.Ride, true, true ) }, // チップ配置(ドラム)・ライドシンバル { 0x1A, ( チップ種別.LeftCrash, true, true ) }, // チップ配置(ドラム)・左シンバル { 0x1B, ( チップ種別.HiHat_Foot, true, true ) }, // チップ配置(ドラム)・左ペダル { 0x1C, ( チップ種別.LeftBass, true, true ) }, // チップ配置(ドラム)・左バス { 0x20, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・OPEN { 0x21, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・xxB { 0x22, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・xGx { 0x23, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・xGB { 0x24, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・Rxx { 0x25, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・RxB { 0x26, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・RGx { 0x27, ( チップ種別.GuitarAuto, false, true ) }, // チップ配置(ギター)・RGB { 0x50, ( チップ種別.小節線, true, false ) }, // 小節線 { 0x51, ( チップ種別.拍線, true, false ) }, // 拍線 { 0x54, ( チップ種別.背景動画, false, false ) }, // 動画 { 0x5A, ( チップ種別.背景動画, false, false ) }, // 動画(全画面) { 0x61, ( チップ種別.SE1, false, true ) }, // SE1 { 0x62, ( チップ種別.SE2, false, true ) }, // SE2 { 0x63, ( チップ種別.SE3, false, true ) }, // SE3 { 0x64, ( チップ種別.SE4, false, true ) }, // SE4 { 0x65, ( チップ種別.SE5, false, true ) }, // SE5 { 0xA0, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・OPEN { 0xA1, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・xxB { 0xA2, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・xGx { 0xA3, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・xGB { 0xA4, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・Rxx { 0xA5, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・RxB { 0xA6, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・RGx { 0xA7, ( チップ種別.BassAuto, false, true ) }, // チップ配置(ベース)・RGB { 0xC2, ( チップ種別.Unknown, false, false ) }, // 拍線・小節線表示指定 ... SSTFではチップじゃないが、後処理で使用する。 //---------------- #endregion }; } } } <|start_filename|>DTXMania2/ステージ/07演奏/クリアメータ―.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { /// <summary> /// 曲の各区分をどの程度クリアできたかを示すメーター。 /// </summary> /// <remarks> /// 1曲を曲の長さによらず64等分し、それぞれの区間での成績を大雑把に示す。 /// 現状は、区間内で Ok, Miss 判定を出さなかったら黄色、出したら青色で示される。 /// この64等分された配列データをカウントマップと称する。 /// </remarks> class クリアメーター : IDisposable { /// <summary> /// カウント値の配列。 /// </summary> /// <remarks> /// インデックスが小さいほど曲の前方に位置する。 /// カウント値の値域は 0~12。今のところは 0 で非表示、1 で水色、2~12で黄色表示。 /// </remarks> public int[] カウントマップ { get; } /// <summary> /// カウント値の配列の最大要素数(定数)。 /// </summary> /// <remarks> /// 全曲の最大カウントを 768 とするので、 /// カウントマップリストの要素数は 768÷12 = 64 個が最大となる。 /// </remarks> public const int カウントマップの最大要素数 = 768 / 12; // 生成と終了 public クリアメーター() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.カウントマップ = new int[ カウントマップの最大要素数 ]; this.カウントマップをクリアする(); this._前回の設定位置 = 0f; this._前回設定したときの成績 = new Dictionary<判定種別, int>(); foreach( 判定種別? judge in Enum.GetValues( typeof( 判定種別 ) ) ) { if( judge.HasValue ) this._前回設定したときの成績.Add( judge.Value, 0 ); } } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); } // 設定登録 /// <summary> /// 初期化。 /// </summary> public void 最高成績のカウントマップを登録する( int[] カウントマップ ) { Debug.Assert( カウントマップの最大要素数 == カウントマップ.Length, "カウントマップの要素数が不正です。" ); this._最高成績のカウントマップ = new int[ カウントマップ.Length ]; カウントマップ.CopyTo( this._最高成績のカウントマップ, 0 ); } /// <summary> /// 指定された位置における現在の成績から、対応するカウント値を算出し、反映する。 /// </summary> /// <param name="現在位置">現在の位置を 開始点:0~1:終了点 で示す。</param> /// <param name="判定toヒット数">現在の位置における成績。</param> /// <returns>現在のカウントマップを文字列化したものを返す。</returns> public string カウント値を設定する( float 現在位置, IReadOnlyDictionary<判定種別, int> 判定toヒット数 ) { // 判定種別ごとに、前回からの成績の増加分を得る。 var 増加値 = new Dictionary<判定種別, int>(); foreach( 判定種別? judge in Enum.GetValues( typeof( 判定種別 ) ) ) { if( judge.HasValue ) 増加値.Add( judge.Value, 判定toヒット数[ judge.Value ] - this._前回設定したときの成績[ judge.Value ] ); } // カウント値を算出する。 int カウント値 = ( 0 < 増加値[ 判定種別.OK ] || 0 < 増加値[ 判定種別.MISS ] ) ? 1 : 12; // 今のところ 1 or 12 の二段階のみ // 前回の設定位置 から 現在位置 までの期間に対応するすべてのカウント値に反映する。 int 前回の位置 = (int)( this._前回の設定位置 * カウントマップの最大要素数 ); int 今回の位置 = (int)( 現在位置 * カウントマップの最大要素数 ); if( 1.0f > 現在位置 ) { for( int i = 前回の位置; i <= 今回の位置; i++ ) { // 同一区間では、成績の悪いほう(カウント値の小さいほう)を優先する。 this.カウントマップ[ i ] = ( 0 < this.カウントマップ[ i ] ) ? Math.Min( カウント値, this.カウントマップ[ i ] ) : カウント値; } } // 位置と成績を保存。 this._前回の設定位置 = 現在位置; foreach( 判定種別? judge in Enum.GetValues( typeof( 判定種別 ) ) ) { if( judge.HasValue ) this._前回設定したときの成績[ judge.Value ] = 判定toヒット数[ judge.Value ]; } // 現在のカウントマップを生成して返す。 var sb = new StringBuilder( カウントマップ.Length ); for( int i = 0; i < this.カウントマップ.Length; i++ ) sb.Append( this._カウントマップ文字列[ this.カウントマップ[ i ] ] ); return sb.ToString(); } public void カウントマップをクリアする() { for( int i = 0; i < this.カウントマップ.Length; i++ ) this.カウントマップ[ i ] = 0; } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { using var 水色ブラシ = new SolidColorBrush( d2ddc, new Color4( 0xffdd8e69 ) ); using var 黄色ブラシ = new SolidColorBrush( d2ddc, new Color4( 0xff17fffe ) ); const float 単位幅 = 12f; var 今回のライン全体の矩形 = new RectangleF( 1357f, 108f, 10f, 768f ); var 過去最高のライン全体の矩形 = new RectangleF( 1371f, 108f, 6f, 768f ); // (1) 今回のクリアメータ―を描画する。 for( int i = 0; i < this.カウントマップ.Length; i++ ) { if( 0 == this.カウントマップ[ i ] ) continue; d2ddc.FillRectangle( new RectangleF( 今回のライン全体の矩形.Left, 今回のライン全体の矩形.Bottom - 単位幅 * ( i + 1 ), 今回のライン全体の矩形.Width, 単位幅 ), ( 2 <= this.カウントマップ[ i ] ) ? 黄色ブラシ : 水色ブラシ ); } // (2) 過去の最高成績のクリアメータ―を描画する。 if( null != this._最高成績のカウントマップ ) { for( int i = 0; i < this._最高成績のカウントマップ.Length; i++ ) { if( 0 == this._最高成績のカウントマップ[ i ] ) continue; d2ddc.FillRectangle( new RectangleF( 過去最高のライン全体の矩形.Left, 過去最高のライン全体の矩形.Bottom - 単位幅 * ( i + 1 ), 過去最高のライン全体の矩形.Width, 単位幅 ), ( 2 <= this._最高成績のカウントマップ[ i ] ) ? 黄色ブラシ : 水色ブラシ ); } } } // ローカル private int[]? _最高成績のカウントマップ = null; private float _前回の設定位置 = 0f; private readonly Dictionary<判定種別, int> _前回設定したときの成績; private readonly char[] _カウントマップ文字列 = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C' }; } } <|start_filename|>DTXMania2/曲/Tree/Node/RandomSelectNode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2.曲 { class RandomSelectNode : Node { // プロパティ public override string タイトル => "< RANDOM SELECT >"; // ランダムセレクト /// <summary> /// このノードの属するノードリストからランダムに SongNode とフォーカス譜面を選択して返す。 /// 曲がなければ null を返す。 /// </summary> public (Score 譜面, SongNode 曲)? 譜面をランダムに選んで返す() { // RandomSelect がある階層以降すべての SongNode を取得。 var songNode配列 = this.親ノード!.Traverse().Where( ( node ) => node is SongNode ).ToArray(); int songNode数 = songNode配列.Length; if( 0 < songNode数 ) { for( int retry = 0; retry < 10; retry++ ) { // 乱数でノードを決定。 var songNode = songNode配列[ Global.App.乱数.Next( songNode数 ) ] as SongNode; // 非nullならOK、nullならretry if( null != songNode?.曲.フォーカス譜面 ) return (songNode.曲.フォーカス譜面, songNode); } } Log.ERROR( $"{nameof( SongNode )} が1つも見つかりません。" ); return null; } } } <|start_filename|>SSTFEditor/UndoRedo/UndoRedo管理.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace SSTFEditor.UndoRedo { class UndoRedo管理 { public static bool UndoRedoした直後である { get; set; } = false; public int Undo可能な回数 => this._ルート.Undo可能な回数; public int Redo可能な回数 => ( this.現在の総ノード数 - this.Undo可能な回数 ); public int 現在の総ノード数 => this._ルート.現在の総セル数; public UndoRedo管理() { this._現在のセル = this._ルート; } public セルBase Redoするセルを取得して返す() { this._現在のセル = this._ルート; if( 0 >= this._ルート.Redo可能な回数 ) return null; this._ルート.次にセルが追加される位置0to++; return this._ルート.セルs[ this._ルート.次にセルが追加される位置0to - 1 ]; } public セルBase Undoするセルを取得して返す() { this._現在のセル = this._ルート; if( 0 >= this._ルート.Undo可能な回数 ) return null; this._ルート.次にセルが追加される位置0to--; return this._ルート.セルs[ this._ルート.次にセルが追加される位置0to ]; } public セルBase Undoするセルを取得して返す_見るだけ() { this._現在のセル = this._ルート; if( 0 >= this._ルート.Undo可能な回数 ) return null; return this._ルート.セルs[ this._ルート.次にセルが追加される位置0to - 1 ]; } public void セルを追加する( セルBase 単独セル ) { // 追加するセルの後方にあるセルをすべて削除する。 int index = this._現在のセル.次にセルが追加される位置0to; int count = this._現在のセル.現在の総セル数 - this._現在のセル.次にセルが追加される位置0to; if( 0 < count ) this._現在のセル.セルs.RemoveRange( index, count ); // セルを追加する。 this._現在のセル.セルs.Add( 単独セル ); this._現在のセル.次にセルが追加される位置0to++; } public void トランザクション記録を開始する() { // 追加するセルの後方にあるセルをすべて削除する。 int index = this._現在のセル.次にセルが追加される位置0to; int count = this._現在のセル.現在の総セル数 - this._現在のセル.次にセルが追加される位置0to; if( 0 < count ) this._現在のセル.セルs.RemoveRange( index, count ); // リストセルを追加して開く。 var セルリスト = new Cセルリスト( this._現在のセル ); // 現在のセルが親セル。 this._現在のセル.セルs.Add( セルリスト ); this._現在のセル.次にセルが追加される位置0to++; this._現在のセル = セルリスト; } public void トランザクション記録を終了する() { // リストセルを閉じる。 if( null != this._現在のセル.親リスト ) { var list = this._現在のセル; this._現在のセル = this._現在のセル.親リスト; if( 0 == list.セルs.Count ) { this._現在のセル.セルs.Remove( list ); this._現在のセル.次にセルが追加される位置0to--; } } } public void UndoRedoリストをすべて空にする() { this._ルート = new Cセルリスト( null ); this._現在のセル = this._ルート; } private Cセルリスト _ルート = new Cセルリスト( null ); private Cセルリスト _現在のセル = null; } } <|start_filename|>DTXMania2/ステージ/08結果/達成率.数値.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; namespace DTXMania2.結果 { partial class 達成率 { class 数値 : IDisposable { // プロパティ public bool アニメ完了 => ( null != this._ストーリーボード && this._ストーリーボード.Status == StoryboardStatus.Ready ); // 生成と終了 public 数値() { this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_LargeBoldItalic.png", @"$(Images)\ParameterFont_LargeBoldItalic.yaml", 文字幅補正dpx: -2f ); this._MAX = new 画像D2D( @"$(Images)\ResultStage\MAX.png" ); this._MAXである = false; } public virtual void Dispose() { this._MAX用半径倍率?.Dispose(); this._MAX用拡大角度rad?.Dispose(); this._不透明度?.Dispose(); this._左位置dpx?.Dispose(); this._ストーリーボード?.Dispose(); this._MAX.Dispose(); this._数字画像.Dispose(); } // 進行と描画 public void 開始する( double 数値0to100 ) { if( 数値0to100 < 100.0 ) { this._MAXである = false; string v = 数値0to100.ToString( "0.00" ).PadLeft( 6 ) + '%'; // 左余白は ' '。例:" 19.00%", "100.00%" this._達成率文字列_整数部 = v[ 0..4 ]; // '.' 含む this._達成率文字列_小数部 = v[ 4.. ]; // '%' 含む } else { this._MAXである = true; this._達成率文字列_整数部 = ""; this._達成率文字列_小数部 = ""; } this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( Global.Animation.Manager ); #region " ストーリーボードの構築 " //---------------- { // 初期状態 this._左位置dpx?.Dispose(); this._不透明度?.Dispose(); this._MAX用拡大角度rad?.Dispose(); this._MAX用半径倍率?.Dispose(); this._左位置dpx = new Variable( Global.Animation.Manager, initialValue: +200.0 ); this._不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this._MAX用拡大角度rad = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this._MAX用半径倍率 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); // シーン1. 待つ { double シーン期間 = 達成率._最初の待機時間sec; using( var 左位置dpxの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var MAX用拡大角度radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var MAX用半径倍率の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { this._ストーリーボード.AddTransition( this._左位置dpx, 左位置dpxの遷移 ); this._ストーリーボード.AddTransition( this._不透明度, 不透明度の遷移 ); this._ストーリーボード.AddTransition( this._MAX用拡大角度rad, MAX用拡大角度radの遷移 ); this._ストーリーボード.AddTransition( this._MAX用半径倍率, MAX用半径倍率の遷移 ); } } // シーン2. アニメする { double シーン期間 = 達成率._アニメ時間sec; using( var 左位置dpxの遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: シーン期間 / 2, finalValue: 0.0, accelerationRatio: 0.2, decelerationRatio: 0.8 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1.0 ) ) using( var MAX用拡大角度radの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 2 * Math.PI ) ) using( var MAX用半径倍率の遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: シーン期間, finalValue: 0.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) { this._ストーリーボード.AddTransition( this._左位置dpx, 左位置dpxの遷移 ); this._ストーリーボード.AddTransition( this._不透明度, 不透明度の遷移 ); this._ストーリーボード.AddTransition( this._MAX用拡大角度rad, MAX用拡大角度radの遷移 ); this._ストーリーボード.AddTransition( this._MAX用半径倍率, MAX用半径倍率の遷移 ); } } } //---------------- #endregion // アニメーション開始 this._ストーリーボード.Schedule( Global.Animation.Timer.Time ); } public void アニメを完了する() { this._ストーリーボード?.Finish( 0.0 ); } public void 進行描画する( DeviceContext d2ddc, float x, float y ) { if( this._MAX用拡大角度rad is null || this._MAX用半径倍率 is null || this._不透明度 is null || this._左位置dpx is null ) return; if( this._MAXである ) { // MAX double 回転による拡大率 = Math.Abs( Math.Cos( this._MAX用拡大角度rad.Value ) ); // (0) 1 → 0 → 1(π) → 0 → 1 (2π) float 拡大率 = (float)( 1.0 + 回転による拡大率 * this._MAX用半径倍率.Value ); float 左位置dpx = x + 124f + ( ( 1.0f - 拡大率 ) * this._MAX.サイズ.Width ) / 2.0f; float 上位置dpx = y + 66f + ( ( 1.0f - 拡大率 ) * this._MAX.サイズ.Height ) / 2.0f; this._MAX.描画する( d2ddc, 左位置dpx, 上位置dpx, 不透明度0to1: (float)this._不透明度.Value, X方向拡大率: 拡大率, Y方向拡大率: 拡大率 ); } else { this._数字画像.不透明度 = (float)this._不透明度.Value; float 左位置dpx = x + (float)this._左位置dpx.Value; // 整数部を描画する('.'含む) this._数字画像.描画する( d2ddc, 左位置dpx, y, this._達成率文字列_整数部, new Size2F( 1.4f, 1.6f ) ); // 小数部を描画する this._数字画像.描画する( d2ddc, 左位置dpx + 246f, y + 50f, this._達成率文字列_小数部, new Size2F( 1.0f, 1.0f ) ); } } // ローカル private readonly フォント画像D2D _数字画像; private readonly 画像D2D _MAX; private bool _MAXである; private string _達成率文字列_小数部 = ""; private string _達成率文字列_整数部 = ""; // '.' 含む private Storyboard? _ストーリーボード = null; private Variable? _左位置dpx = null; private Variable? _不透明度 = null; private Variable? _MAX用拡大角度rad = null; private Variable? _MAX用半径倍率 = null; } } } <|start_filename|>DTXMania2/ステージ/05オプション設定/曲読み込みフォルダ割り当てダイアログ.Designer.cs<|end_filename|> namespace DTXMania2.オプション設定 { partial class 曲読み込みフォルダ割り当てダイアログ { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(曲読み込みフォルダ割り当てダイアログ)); this.buttonOk = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.listViewフォルダ一覧 = new System.Windows.Forms.ListView(); this.columnHeaderフォルダ名 = new System.Windows.Forms.ColumnHeader(); this.label1 = new System.Windows.Forms.Label(); this.button選択 = new System.Windows.Forms.Button(); this.button削除 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // buttonOk // resources.ApplyResources(this.buttonOk, "buttonOk"); this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Name = "buttonOk"; this.buttonOk.UseVisualStyleBackColor = true; // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // listViewフォルダ一覧 // resources.ApplyResources(this.listViewフォルダ一覧, "listViewフォルダ一覧"); this.listViewフォルダ一覧.AllowColumnReorder = true; this.listViewフォルダ一覧.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderフォルダ名}); this.listViewフォルダ一覧.GridLines = true; this.listViewフォルダ一覧.HideSelection = false; this.listViewフォルダ一覧.Name = "listViewフォルダ一覧"; this.listViewフォルダ一覧.UseCompatibleStateImageBehavior = false; this.listViewフォルダ一覧.View = System.Windows.Forms.View.Details; this.listViewフォルダ一覧.SelectedIndexChanged += new System.EventHandler(this.listViewフォルダ一覧_SelectedIndexChanged); // // columnHeaderフォルダ名 // resources.ApplyResources(this.columnHeaderフォルダ名, "columnHeaderフォルダ名"); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // button選択 // resources.ApplyResources(this.button選択, "button選択"); this.button選択.Name = "button選択"; this.button選択.UseVisualStyleBackColor = true; this.button選択.Click += new System.EventHandler(this.button選択_Click); // // button削除 // resources.ApplyResources(this.button削除, "button削除"); this.button削除.Name = "button削除"; this.button削除.UseVisualStyleBackColor = true; this.button削除.Click += new System.EventHandler(this.button削除_Click); // // 曲読み込みフォルダ割り当てダイアログ // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.Controls.Add(this.button削除); this.Controls.Add(this.button選択); this.Controls.Add(this.label1); this.Controls.Add(this.listViewフォルダ一覧); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOk); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "曲読み込みフォルダ割り当てダイアログ"; this.ShowIcon = false; this.ShowInTaskbar = false; this.TopMost = true; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.曲読み込みフォルダ割り当てダイアログ_FormClosing); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.ListView listViewフォルダ一覧; private System.Windows.Forms.Label label1; private System.Windows.Forms.ColumnHeader columnHeaderフォルダ名; private System.Windows.Forms.Button button選択; private System.Windows.Forms.Button button削除; } } <|start_filename|>DTXMania2/ステージ/07演奏/早送りアイコン.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class 早送りアイコン : IDisposable { // 生成と終了 public 早送りアイコン() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._上向きアイコン = new 画像D2D( @"$(Images)\PlayStage\FastForward.png" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._上向きアイコン.Dispose(); } // 進行と描画 public void 早送りする() { this._早送りカウンタ = new Counter( 0, 30, 10 ); this._早戻しカウンタ = null; } public void 早戻しする() { this._早送りカウンタ = null; this._早戻しカウンタ = new Counter( 0, 30, 10 ); } public void 進行描画する( DeviceContext d2ddc ) { if( this._早送りカウンタ != null ) { #region " 早送りアニメ " //---------------- if( this._早送りカウンタ.終了値に達していない ) { float 上移動量 = this._早送りカウンタ.現在値の割合 * 20f; #region " 影 " //---------------- { float 拡大率 = 2f + this._早送りカウンタ.現在値の割合 * 1f; var 変換行列2D = Matrix3x2.Scaling( 拡大率 ) * Matrix3x2.Translation( Global.GraphicResources.設計画面サイズ.Width / 2 - this._上向きアイコン.サイズ.Width * 拡大率 / 2, Global.GraphicResources.設計画面サイズ.Height / 2 - this._上向きアイコン.サイズ.Height * 拡大率 / 2 - 上移動量 ); float 不透明度 = ( 1f - this._早送りカウンタ.現在値の割合 ) * 0.25f; this._上向きアイコン.描画する( d2ddc, 変換行列2D, 不透明度0to1: 不透明度 ); } //---------------- #endregion #region " 本体 " //---------------- { float 拡大率 = 2f; var 変換行列2D = Matrix3x2.Scaling( 拡大率 ) * Matrix3x2.Translation( Global.GraphicResources.設計画面サイズ.Width / 2 - this._上向きアイコン.サイズ.Width * 拡大率 / 2, Global.GraphicResources.設計画面サイズ.Height / 2 - this._上向きアイコン.サイズ.Height * 拡大率 / 2 - 上移動量 ); float 不透明度 = 1f - this._早送りカウンタ.現在値の割合; this._上向きアイコン.描画する( d2ddc, 変換行列2D, 不透明度0to1: 不透明度 ); } //---------------- #endregion } else { this._早送りカウンタ = null; } //---------------- #endregion } else if( this._早戻しカウンタ != null ) { #region " 早戻しアニメ " //---------------- if( this._早戻しカウンタ.終了値に達していない ) { float 下移動量 = this._早戻しカウンタ.現在値の割合 * 20f; #region " 影 " //---------------- { float 拡大率 = 2f + this._早戻しカウンタ.現在値の割合 * 1f; float 不透明度 = ( 1f - this._早戻しカウンタ.現在値の割合 ) * 0.25f; var 回転中心 = new Vector2( this._上向きアイコン.サイズ.Width / 2f, this._上向きアイコン.サイズ.Height / 2f ); var 変換行列2D = Matrix3x2.Rotation( MathF.PI, 回転中心 ) * // 回転して下向きに Matrix3x2.Scaling( 拡大率 ) * Matrix3x2.Translation( Global.GraphicResources.設計画面サイズ.Width / 2 - this._上向きアイコン.サイズ.Width * 拡大率 / 2, Global.GraphicResources.設計画面サイズ.Height / 2 - this._上向きアイコン.サイズ.Height * 拡大率 / 2 + 下移動量 ); this._上向きアイコン.描画する( d2ddc, 変換行列2D, 不透明度0to1: 不透明度 ); } //---------------- #endregion #region " 本体 " //---------------- { float 拡大率 = 2f; float 不透明度 = 1f - this._早戻しカウンタ.現在値の割合; var 回転中心 = new Vector2( this._上向きアイコン.サイズ.Width / 2f, this._上向きアイコン.サイズ.Height / 2f ); var 変換行列2D = Matrix3x2.Rotation( MathF.PI, 回転中心 ) * // 回転して下向きに Matrix3x2.Scaling( 拡大率 ) * Matrix3x2.Translation( Global.GraphicResources.設計画面サイズ.Width / 2 - this._上向きアイコン.サイズ.Width * 拡大率 / 2, Global.GraphicResources.設計画面サイズ.Height / 2 - this._上向きアイコン.サイズ.Height * 拡大率 / 2 + 下移動量 ); this._上向きアイコン.描画する( d2ddc, 変換行列2D, 不透明度0to1: 不透明度 ); } //---------------- #endregion } else { this._早戻しカウンタ = null; } //---------------- #endregion } } // ローカル private readonly 画像D2D _上向きアイコン; private Counter? _早送りカウンタ = null; private Counter? _早戻しカウンタ = null; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/入力割り当てダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Data; using System.Linq; using System.Windows.Forms; using FDK; namespace DTXMania2.オプション設定 { partial class 入力割り当てダイアログ : Form { // 生成と終了 public 入力割り当てダイアログ() { InitializeComponent(); } public void 表示する() { using var _ = new LogBlock( Log.現在のメソッド名 ); using var timer = new Timer(); #region " 設定値で初期化。" //---------------- foreach( ドラム入力種別? drum in Enum.GetValues( typeof( ドラム入力種別 ) ) ) { if( !drum.HasValue || drum == ドラム入力種別.Unknown || drum == ドラム入力種別.HiHat_Control ) continue; // 除外(設定変更不可) this.comboBoxパッドリスト.Items.Add( drum.Value.ToString() ); } // 変更後のキーバインディングを、現在の設定値で初期化。 this._変更後のシステム設定 = Global.App.システム設定.Clone(); // 最初のパッドを選択し、割り当て済みリストを更新。 this.comboBoxパッドリスト.SelectedIndex = 0; // その他の初期化。 this._前回の入力リスト追加時刻 = QPCTimer.生カウント相対値を秒へ変換して返す( QPCTimer.生カウント ); this._FootPedal現在値 = 0; this.textBoxFootPedal現在値.Text = "0"; this.textBoxFootPedal最小値.Text = this._変更後のシステム設定.FootPedal最小値.ToString(); this.textBoxFootPedal最大値.Text = this._変更後のシステム設定.FootPedal最大値.ToString(); this._変更あり = false; // 初期メッセージを出力。 this.listView入力リスト.Items.Add( Properties.Resources.TXT_HIDKeyboardの受付を開始しました ); for( int i = 0; i < Global.App.ドラム入力.MidiIns.DeviceName.Count; i++ ) this.listView入力リスト.Items.Add( string.Format( Properties.Resources.TXT_MidiInの受付を開始しました, i, Global.App.ドラム入力.MidiIns.DeviceName[ i ] ) ); this.listView入力リスト.Items.Add( "" ); this.listView入力リスト.Items.Add( Properties.Resources.TXT_タイミングクロック信号_アクティブ信号は無視します ); this.listView入力リスト.Items.Add( Properties.Resources.TXT_入力と入力の間が500ミリ秒以上開いた場合は間に空行を表示します ); this.listView入力リスト.Items.Add( "" ); this.listView入力リスト.Items.Add( Properties.Resources.TXT_キーボードまたはMIDI信号を入力してください ); //---------------- #endregion // タイマーイベントを使って、定期的に、ゲームコントローラ/MIDI入力値の表示と、MIDIフットペダル開度ゲージの描画を行う。 timer.Interval = 100; timer.Tick += ( sender, arg ) => { #region " ゲームコントローラをポーリングし、入力値を入力リストへ出力。" //---------------- Global.App.ドラム入力.GameControllers.ポーリングする(); for( int i = 0; i < Global.App.ドラム入力.GameControllers.入力イベントリスト.Count; i++ ) { var inputEvent = Global.App.ドラム入力.GameControllers.入力イベントリスト[ i ]; if( inputEvent.押された ) { // 入力リストに表示。 var item = new ListViewItem入力リスト用( InputDeviceType.GameController, inputEvent ); // 既に割り当てられていたらそのドラム種別を表示。 var drumType = from kvp in this._変更後のシステム設定.ゲームコントローラtoドラム where ( kvp.Key.deviceId == item.inputEvent.DeviceID ) && ( kvp.Key.key == item.inputEvent.Key ) select kvp.Value; if( drumType.Any() ) item.Text += $" ({Properties.Resources.TXT_現在の割り当て}: {drumType.ElementAt( 0 )})"; this._一定時間が経っていれば空行を挿入する(); this.listView入力リスト.Items.Add( item ); this.listView入力リスト.EnsureVisible( this.listView入力リスト.Items.Count - 1 ); } } //---------------- #endregion #region " MIDI入力をポーリングし、入力値を入力リストへ出力。" //---------------- // MidiInChecker の機能もかねて、NoteOFF や ControlChange も表示する。(割り当てはできない。) Global.App.ドラム入力.MidiIns.ポーリングする(); for( int i = 0; i < Global.App.ドラム入力.MidiIns.入力イベントリスト.Count; i++ ) { var inputEvent = Global.App.ドラム入力.MidiIns.入力イベントリスト[ i ]; if( inputEvent.押された && ( 255 == inputEvent.Key ) && ( MidiIns.CTL_FOOTPEDAL == inputEvent.Control ) ) { #region " (A) フットペダルコントロールの場合 → 入力リストではなく専用のUIで表示。" //---------------- if( this._FootPedal現在値 != inputEvent.Velocity ) { // 現在値 this._FootPedal現在値 = inputEvent.Velocity; this.textBoxFootPedal現在値.Text = this._FootPedal現在値.ToString(); // 最大値 if( this._FootPedal現在値 > this._変更後のシステム設定.FootPedal最大値 ) { this._変更後のシステム設定.FootPedal最大値 = this._FootPedal現在値; this.textBoxFootPedal最大値.Text = this._変更後のシステム設定.FootPedal最大値.ToString(); } // 最小値 if( this._FootPedal現在値 <= this._変更後のシステム設定.FootPedal最小値 ) { this._変更後のシステム設定.FootPedal最小値 = this._FootPedal現在値; this.textBoxFootPedal最小値.Text = this._変更後のシステム設定.FootPedal最小値.ToString(); } } //---------------- #endregion } else { #region " (B) その他のMIDI入出力 → 入力リストに表示。" //---------------- var item = new ListViewItem入力リスト用( InputDeviceType.MidiIn, inputEvent ); // 既に割り当てられていたらそのドラム種別を表示。 if( 0 == item.inputEvent.Control ) // コントロールチェンジは除外。 { var drumType = from kvp in this._変更後のシステム設定.MIDItoドラム where ( kvp.Key.deviceId == item.inputEvent.DeviceID ) && ( kvp.Key.key == item.inputEvent.Key ) select kvp.Value; if( drumType.Any() ) item.Text += $" ({Properties.Resources.TXT_現在の割り当て}: {drumType.ElementAt( 0 )})"; } this._一定時間が経っていれば空行を挿入する(); this.listView入力リスト.Items.Add( item ); this.listView入力リスト.EnsureVisible( this.listView入力リスト.Items.Count - 1 ); //---------------- #endregion } } //---------------- #endregion #region " MIDIフットペダルの開度ゲージを描画。" //---------------- using( var g = pictureBoxFootPedal.CreateGraphics() ) { var 全体矩形 = pictureBoxFootPedal.ClientRectangle; var 背景色 = new System.Drawing.SolidBrush( pictureBoxFootPedal.BackColor ); var 最大値ゲージ色 = System.Drawing.Brushes.LightBlue; var ゲージ色 = System.Drawing.Brushes.Blue; g.FillRectangle( 背景色, 全体矩形 ); int 最大値用差分 = (int)( 全体矩形.Height * ( 1.0 - this._変更後のシステム設定.FootPedal最大値 / 127.0 ) ); var 最大値ゲージ矩形 = new System.Drawing.Rectangle( 全体矩形.X, 全体矩形.Y + 最大値用差分, 全体矩形.Width, 全体矩形.Height - 最大値用差分 ); g.FillRectangle( 最大値ゲージ色, 最大値ゲージ矩形 ); int 現在値用差分 = (int)( 全体矩形.Height * ( 1.0 - this._FootPedal現在値 / 127.0 ) ); var ゲージ矩形 = new System.Drawing.Rectangle( 全体矩形.X, 全体矩形.Y + 現在値用差分, 全体矩形.Width, 全体矩形.Height - 現在値用差分 ); g.FillRectangle( ゲージ色, ゲージ矩形 ); } //---------------- #endregion }; this.KeyPreview = true; // Control への入力を先に Form が受け取れるようにする。 this.KeyDown += ( sender, arg ) => { // ダイアログで RawInput を使う方法が分からないので KeyDown を使う #region " キーボードの入力値を入力リストへ出力。" //---------------- var inputEvent = new InputEvent() { DeviceID = 0, Key = (int)arg.KeyCode, TimeStamp = 0, Velocity = 100, 押された = true, Control = 0, }; var item = new ListViewItem入力リスト用( InputDeviceType.Keyboard, inputEvent ); if( inputEvent.Key == (int)Keys.Escape ) // 割り当てされてほしくないキーはここへ。 { item.割り当て可能 = false; } // 既に割り当てられていたらそのドラム種別を表示。 var drumType = from kvp in this._変更後のシステム設定.キーボードtoドラム where ( kvp.Key.deviceId == item.inputEvent.DeviceID ) && ( kvp.Key.key == item.inputEvent.Key ) select kvp.Value; if( drumType.Any() ) item.Text += $" ({Properties.Resources.TXT_現在の割り当て}: {drumType.ElementAt( 0 )})"; this._一定時間が経っていれば空行を挿入する(); this.listView入力リスト.Items.Add( item ); this.listView入力リスト.EnsureVisible( this.listView入力リスト.Items.Count - 1 ); //---------------- #endregion }; timer.Start(); #region " ダイアログを表示。" //---------------- Cursor.Show(); var dr = this.ShowDialog( Global.App ); if( Global.App.ScreenMode.IsFullscreenMode ) Cursor.Hide(); //---------------- #endregion timer.Stop(); if( dr == DialogResult.OK ) { // 設定値を反映する。 Global.App.システム設定 = this._変更後のシステム設定.Clone(); Global.App.システム設定.保存する(); } } // ローカル private enum InputDeviceType { Keyboard, Mouse, GameController, MidiIn, Unknown } /// <summary> /// <see cref="listView入力リスト"/> 用の ListViewItem 拡張クラス。 /// 表示テキストのほかに、入力情報も持つ。 /// </summary> private class ListViewItem入力リスト用 : ListViewItem { public bool 割り当て可能; public InputDeviceType deviceType; // Device種別 public InputEvent inputEvent; // DeviceID, key, velocity public ListViewItem入力リスト用( InputDeviceType deviceType, InputEvent inputEvent ) { this.割り当て可能 = true; this.deviceType = deviceType; this.inputEvent = inputEvent; switch( deviceType ) { case InputDeviceType.Keyboard: this.Text = $"Keyboard, {inputEvent.Key}, '{(Keys)inputEvent.Key}'"; break; case InputDeviceType.GameController: this.Text = $"GamePad, 0x{inputEvent.Key:X8}, '{HID.GetUsageName( (uint)inputEvent.Key )}'"; break; case InputDeviceType.MidiIn: if( inputEvent.押された ) { if( 255 != inputEvent.Key ) { this.Text = $"MidiIn[{inputEvent.DeviceID}], " + $"{inputEvent.Extra}, " + $"{Properties.Resources.TXT_ノートオン}, " + $"Note={inputEvent.Key}, " + $"Velocity={inputEvent.Velocity}"; this.割り当て可能 = true; // 割り当て可 this.ForeColor = System.Drawing.Color.Black; // 黒 } else { // フットペダル this.Text = $"MidiIn[{inputEvent.DeviceID}], " + $"{inputEvent.Extra}, " + $"{Properties.Resources.TXT_コントロールチェンジ}, " + $"Control={inputEvent.Control}(0x{inputEvent.Control:X2}), " + $"Value={inputEvent.Velocity}"; this.割り当て可能 = false; // 割り当て不可 this.ForeColor = System.Drawing.Color.Green; // 緑 } } else if( inputEvent.離された ) { this.Text = $"MidiIn[{inputEvent.DeviceID}], " + $"{inputEvent.Extra}, " + $"{Properties.Resources.TXT_ノートオフ}, " + $"Note={inputEvent.Key}, " + $"Velocity={inputEvent.Velocity}"; this.割り当て可能 = false; // 割り当て不可 this.ForeColor = System.Drawing.Color.Gray; // 灰 } break; default: throw new ArgumentException( "未対応のデバイスです。" ); } } } /// <summary> /// <see cref="listView割り当て済み入力リスト"/> 用の ListViewItem 拡張クラス。 /// 表示テキストのほかに、入力情報も持つ。 /// </summary> private class ListViewItem割り当て済み入力リスト用 : ListViewItem { public bool 割り当て可能; public InputDeviceType deviceType; // Device種別 public SystemConfig.IdKey idKey; // DeviceID, key public ListViewItem割り当て済み入力リスト用( InputDeviceType deviceType, SystemConfig.IdKey idKey ) { this.割り当て可能 = true; this.deviceType = deviceType; this.idKey = idKey; switch( deviceType ) { case InputDeviceType.Keyboard: this.Text = $"Keyboard, {idKey.key}, '{(Keys)idKey.key}'"; break; case InputDeviceType.GameController: this.Text = $"GamePad, 0x{idKey.key:X8}, '{HID.GetUsageName( (uint)idKey.key )}'"; break; case InputDeviceType.MidiIn: this.Text = $"MidiIn[{idKey.deviceId}], Note:{idKey.key}"; break; default: throw new ArgumentException( "未対応のデバイスです。" ); } } } /// <summary> /// ダイアログで編集した内容は、このメンバにいったん保存される。 /// </summary> private SystemConfig _変更後のシステム設定 = null!; private ドラム入力種別 _現在選択されているドラム入力種別 = ドラム入力種別.Unknown; private int _FootPedal現在値; /// <summary> /// <see cref="_現在選択されているドラム入力種別"/> について、 /// <see cref="_変更後のシステム設定"/> の内容を割り当て済みリストに反映する。 /// </summary> private void _割り当て済みリストを更新する( ListViewItem入力リスト用? 選択する項目 = null ) { this.listView割り当て済み入力リスト.Items.Clear(); // 現在選択されているドラム入力種別に割り当てられているキーボード入力をリストに追加。 this.listView割り当て済み入力リスト.Items.AddRange( ( from kvp in this._変更後のシステム設定.キーボードtoドラム where kvp.Value == this._現在選択されているドラム入力種別 select new ListViewItem割り当て済み入力リスト用( InputDeviceType.Keyboard, kvp.Key ) ) .ToArray() ); // 現在選択されているドラム入力種別に割り当てられているゲームコントローラ入力をリストに追加。 this.listView割り当て済み入力リスト.Items.AddRange( ( from kvp in this._変更後のシステム設定.ゲームコントローラtoドラム where kvp.Value == this._現在選択されているドラム入力種別 select new ListViewItem割り当て済み入力リスト用( InputDeviceType.GameController, kvp.Key ) ) .ToArray() ); // 現在選択されているドラム入力種別に割り当てられているMIDI入力をリストに追加。 this.listView割り当て済み入力リスト.Items.AddRange( ( from kvp in this._変更後のシステム設定.MIDItoドラム where kvp.Value == this._現在選択されているドラム入力種別 select new ListViewItem割り当て済み入力リスト用( InputDeviceType.MidiIn, kvp.Key ) ) .ToArray() ); // 指定された項目があればフォーカスを変更する。 if( null != 選択する項目 ) { foreach( ListViewItem割り当て済み入力リスト用? item in this.listView割り当て済み入力リスト.Items ) { if( null != item && item.deviceType == 選択する項目.deviceType && item.idKey.deviceId == 選択する項目.inputEvent.DeviceID && item.idKey.key == 選択する項目.inputEvent.Key ) { // MSDNより: // https://msdn.microsoft.com/ja-jp/library/y4x56c0b(v=vs.110).aspx // > 項目をプログラムで選択しても、フォーカスは自動的に ListView コントロールには変更されません。 // > そのため、項目を選択するときは、通常、その項目をフォーカスがある状態に設定します。 item.Focused = true; item.Selected = true; } } } } private void _現在選択されている入力リストの入力行を割り当て済み入力リストに追加する() { foreach( var itemobj in this.listView入力リスト.SelectedItems ) { if( ( itemobj is ListViewItem入力リスト用 item ) && // 選択されているのが ListViewItem入力リスト用 じゃなければ何もしない。 item.割り当て可能 ) // 割り当て可能のもののみ割り当てる。 { var idKey = new SystemConfig.IdKey( item.inputEvent ); switch( item.deviceType ) { case InputDeviceType.Keyboard: this._変更後のシステム設定.キーボードtoドラム[ idKey ] = this._現在選択されているドラム入力種別; // 追加または更新 this._割り当て済みリストを更新する( item ); this.listView割り当て済み入力リスト.Focus(); this._変更あり = true; break; case InputDeviceType.GameController: this._変更後のシステム設定.ゲームコントローラtoドラム[ idKey ] = this._現在選択されているドラム入力種別; // 追加または更新 this._割り当て済みリストを更新する( item ); this.listView割り当て済み入力リスト.Focus(); this._変更あり = true; break; case InputDeviceType.MidiIn: this._変更後のシステム設定.MIDItoドラム[ idKey ] = this._現在選択されているドラム入力種別; // 追加または更新 this._割り当て済みリストを更新する( item ); this.listView割り当て済み入力リスト.Focus(); this._変更あり = true; break; } } } } private double _前回の入力リスト追加時刻; private void _一定時間が経っていれば空行を挿入する() { double 今回の入力リスト追加時刻 = QPCTimer.生カウント相対値を秒へ変換して返す( QPCTimer.生カウント ); // 1秒以上経っていれば改行 if( 1.0 < ( 今回の入力リスト追加時刻 - this._前回の入力リスト追加時刻 ) ) this.listView入力リスト.Items.Add( "" ); this._前回の入力リスト追加時刻 = 今回の入力リスト追加時刻; } private void comboBoxパッドリスト_SelectedIndexChanged( object sender, EventArgs e ) { this._現在選択されているドラム入力種別 = (ドラム入力種別)Enum.Parse( typeof( ドラム入力種別 ), (string)this.comboBoxパッドリスト.SelectedItem ); this._割り当て済みリストを更新する(); } private void button追加_Click( object sender, EventArgs e ) { this._現在選択されている入力リストの入力行を割り当て済み入力リストに追加する(); } private void listView入力リスト_DoubleClick( object sender, EventArgs e ) { this._現在選択されている入力リストの入力行を割り当て済み入力リストに追加する(); } private void button割り当て解除_Click( object sender, EventArgs e ) { // 選択されている項目に対応する入力をキーバインディングから削除する。 foreach( ListViewItem割り当て済み入力リスト用? item in this.listView割り当て済み入力リスト.SelectedItems ) { if( item is null ) continue; switch( item.deviceType ) { case InputDeviceType.Keyboard: this._変更後のシステム設定.キーボードtoドラム.Remove( item.idKey ); this._変更あり = true; break; case InputDeviceType.GameController: this._変更後のシステム設定.ゲームコントローラtoドラム.Remove( item.idKey ); this._変更あり = true; break; case InputDeviceType.MidiIn: this._変更後のシステム設定.MIDItoドラム.Remove( item.idKey ); this._変更あり = true; break; } } this._割り当て済みリストを更新する(); } private bool _変更あり; private void 入力割り当てダイアログ_FormClosing( object sender, FormClosingEventArgs e ) { // ※ウィンドウを閉じようとした時も Cancel になる。 if( this.DialogResult == DialogResult.Cancel && this._変更あり ) { var dr = MessageBox.Show( Properties.Resources.TXT_変更を破棄していいですか, Properties.Resources.TXT_確認, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2 ); if( dr == DialogResult.No ) e.Cancel = true; } } } } <|start_filename|>DTXMania2/曲/Score.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using DTXMania2.演奏; namespace DTXMania2.曲 { /// <summary> /// 譜面を表すクラス。 /// </summary> class Score : IDisposable { // プロパティ /// <summary> /// 難易度レベルに対応する難易度文字列。 /// </summary> public string 難易度ラベル { get { lock( this._排他 ) return this._難易度ラベル; } set { lock( this._排他 ) this._難易度ラベル = value; } } /// <summary> /// 譜面の情報。 /// </summary> /// <remarks> /// <see cref="Score.譜面と画像を現行化済み"/>が false の場合、このプロパティと ScoreDB の対応レコードはまだ現行化されておらず、 /// 値は<see cref="ScoreDBRecord"/>の既定値(<see cref="ScoreDBRecord.ScorePath"/>と<see cref="ScoreDBRecord.Title"/>のみ設定済み; /// ただし<see cref="ScoreDBRecord.Title"/>は仮の値)である。 /// <see cref="Score.譜面と画像を現行化済み"/>が true の場合、このプロパティと ScoreDB の対応レコードは現行化済みである。 /// </remarks> public ScoreDBRecord 譜面 { get { lock( this._排他 ) return this._譜面; } set { lock( this._排他 ) this._譜面 = value; } } /// <summary> /// 譜面の属性情報。 /// </summary> /// <remarks> /// <see cref="Score.譜面の属性を現行化済み"/>が false の場合、このプロパティはまだ現行化されておらず、値は null である。 /// <see cref="Score.譜面の属性を現行化済み"/>が true の場合、このプロパティは現行化済みであり、値は、ScorePropertiesDB を反映したもの、あるいは null(ScorePropertiesDB 未記載)である。 /// </remarks> public ScorePropertiesDBRecord? 譜面の属性 { get { lock( this._排他 ) return this._譜面の属性; } set { lock( this._排他 ) this._譜面の属性 = value; } } /// <summary> /// この譜面の最高記録情報。 /// </summary> /// <remarks> /// <see cref="Score.最高記録を現行化済み"/>が false の場合、このプロパティはまだ現行化されておらず、値は null である。 /// <see cref="Score.最高記録を現行化済み"/>が true の場合、このプロパティは現行化済みであり、値は、RecordDB を反映したもの、あるいは null(RecordDB 未記載)である。 /// </remarks> public RecordDBRecord? 最高記録 { get { lock( this._排他 ) return this._最高記録; } set { lock( this._排他 ) this._最高記録 = value; } } /// <summary> /// <see cref="Score.譜面"/>と画像が現行化済みであれば true。 /// </summary> /// <remarks> /// 現行化とは、譜面ファイルと ScoreDB のレコードとの同期を取る作業である。 /// レコードが存在していない場合は、新規に追加される。 /// 譜面ファイルに更新があれば、ScoreDB の対応レコードが更新される。 /// </remarks> public bool 譜面と画像を現行化済み { get { lock( this._排他 ) return this._譜面と画像を現行化済み; } set { lock( this._排他 ) this._譜面と画像を現行化済み = value; } } /// <summary> /// <see cref="Score.譜面の属性"/>が現行化済みであれば true。 /// </summary> /// <remarks> /// 現行化とは、ScorePropertiesDB から曲属性を検索し、該当レコードがあればそれを<see cref="Score.譜面の属性"/>に上書きする作業を表す。 /// 結果、レコードがあろうがなかろうが、このメンバは true になる。 /// </remarks> public bool 譜面の属性を現行化済み { get { lock( this._排他 ) return this._譜面の属性を現行化済み; } set { lock( this._排他 ) this._譜面の属性を現行化済み = value; } } /// <summary> /// <see cref="Score.最高記録"/>が現行化済みであれば true。 /// </summary> /// <remarks> /// 現行化とは、RecordDB から最高記録を検索し、該当レコードがあればそれを<see cref="Score.最高記録"/>に上書きする作業を表す。 /// 結果、レコードがあろうがなかろうが、このメンバは true になる。 /// </remarks> public bool 最高記録を現行化済み { get { lock( this._排他 ) return this._最高記録を現行化済み; } set { lock( this._排他 ) this._最高記録を現行化済み = value; } } /// <summary> /// これまでの最高ランク。 /// 未取得なら null。 /// </summary> public 結果.ランク種別? 最高ランク { get { lock( this._排他 ) { return ( null != this.最高記録 ) ? 成績.ランクを算出する( this.最高記録.Achievement ) : (結果.ランク種別?)null; } } } /// <summary> /// この譜面に存在するノートの、レーン別の総数。 /// 現行化されていなければ null。 /// </summary> public IReadOnlyDictionary<表示レーン種別, int>? レーン別ノート数 { get { if( this.譜面と画像を現行化済み && this._レーン別ノート数 is null ) { #region " 現行化済みかつ未生成ならここで作成する。" //---------------- if( this._レーン別ノート数 is null ) { this._レーン別ノート数 = new Dictionary<表示レーン種別, int>() { [ 表示レーン種別.LeftCymbal ] = this.譜面.TotalNotes_LeftCymbal, [ 表示レーン種別.HiHat ] = this.譜面.TotalNotes_HiHat, [ 表示レーン種別.Foot ] = this.譜面.TotalNotes_LeftPedal, [ 表示レーン種別.Snare ] = this.譜面.TotalNotes_Snare, [ 表示レーン種別.Bass ] = this.譜面.TotalNotes_Bass, [ 表示レーン種別.Tom1 ] = this.譜面.TotalNotes_HighTom, [ 表示レーン種別.Tom2 ] = this.譜面.TotalNotes_LowTom, [ 表示レーン種別.Tom3 ] = this.譜面.TotalNotes_FloorTom, [ 表示レーン種別.RightCymbal ] = this.譜面.TotalNotes_RightCymbal, }; } //---------------- #endregion } return this._レーン別ノート数; } } /// <summary> /// <see cref="ScoreDBRecord.PreImage"/> に対応する、譜面のプレビュー画像。 /// </summary> public 画像D2D? プレビュー画像 { get { lock( this._排他 ) return this._プレビュー画像; } set { lock( this._排他 ) this._プレビュー画像 = value; } } /// <summary> /// <see cref="ScoreDBRecord.Title"/> を画像化したもの。 /// </summary> public 文字列画像D2D? タイトル文字列画像 { get { lock( this._排他 ) return this._タイトル文字列画像; } set { lock( this._排他 ) this._タイトル文字列画像 = value; } } /// <summary> /// <see cref="ScoreDBRecord.Artist"/> を画像化したもの。 /// </summary> public 文字列画像D2D? サブタイトル文字列画像 { get { lock( this._排他 ) return this._サブタイトル文字列画像; } set { lock( this._排他 ) this._サブタイトル文字列画像 = value; } } // 生成と終了 public Score() { } public virtual void Dispose() { this.プレビュー画像?.Dispose(); this.タイトル文字列画像?.Dispose(); this.サブタイトル文字列画像?.Dispose(); } // ローカル private string _難易度ラベル = "FREE"; private ScoreDBRecord _譜面 = new ScoreDBRecord(); private ScorePropertiesDBRecord? _譜面の属性 = null; private RecordDBRecord? _最高記録 = null; private bool _譜面と画像を現行化済み = false; private bool _譜面の属性を現行化済み = false; private bool _最高記録を現行化済み = false; private Dictionary<表示レーン種別, int> _レーン別ノート数 = null!; private 画像D2D? _プレビュー画像 = null; private 文字列画像D2D? _タイトル文字列画像 = null; private 文字列画像D2D? _サブタイトル文字列画像 = null; /// <summary> /// 現行化処理との排他用。 /// </summary> private readonly object _排他 = new object(); } } <|start_filename|>FDK/イメージ/画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpDX; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.Mathematics.Interop; namespace FDK { /// <summary> /// D3Dテクスチャを使った画像表示。 /// </summary> public class 画像 : IImage, IDisposable { // プロパティ /// <summary> /// 0:透明~1:不透明 /// </summary> public float 不透明度 { get; set; } = 1f; public bool 加算合成する { get; set; } = false; /// <summary> /// 画像の有効領域のサイズ。 /// 有効領域は画像の左上を原点とし、大きさは<see cref="画像.実サイズ"/>と同じかそれより小さい。 /// </summary> public Size2F サイズ { get; protected set; } /// <summary> /// Direct3D デバイス内で実際に生成された画像のサイズ。 /// このサイズは、(あるなら)Direct3D デバイスの制約を受ける。 /// </summary> public Size2F 実サイズ { get; protected set; } /// <summary> /// テクスチャ。 /// </summary> public Texture2D Texture { get; protected set; } = null!; /// <summary> /// テクスチャのシェーダーリソースビュー。 /// </summary> public ShaderResourceView ShaderResourceView { get; protected set; } = null!; // 生成と終了 /// <summary> /// 指定した画像ファイルから画像を作成する。 /// </summary> public 画像( Device1 d3dDevice1, VariablePath 画像ファイルパス, BindFlags bindFlags = BindFlags.ShaderResource ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); #region " 条件チェック " //---------------- if( string.IsNullOrEmpty( 画像ファイルパス.変数なしパス ) ) { Log.ERROR( $"画像ファイルパスの指定がありません。" ); return; } if( !File.Exists( 画像ファイルパス.変数なしパス ) ) { Log.ERROR( $"画像ファイルが存在しません。[{画像ファイルパス.変数付きパス}]" ); return; } //---------------- #endregion this._画像ファイルからシェーダリソースビューを作成して返す( d3dDevice1, bindFlags, 画像ファイルパス ); } /// <summary> /// 指定したサイズの、空の画像を作成する。 /// </summary> public 画像( Device1 d3dDevice1, Size2F サイズ, BindFlags bindFlags = BindFlags.ShaderResource ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); #region " 条件チェック " //---------------- if( 0f >= サイズ.Width || 0f >= サイズ.Height ) { Log.ERROR( $"テクスチャサイズが不正です。0 より大きい正の値を指定してください。[{サイズ}]" ); return; } //---------------- #endregion this._空のテクスチャとそのシェーダーリソースビューを作成して返す( d3dDevice1, bindFlags, サイズ ); } public virtual void Dispose() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this.ShaderResourceView?.Dispose(); // 画像の生成に失敗した場合、null のままである。 this.Texture?.Dispose(); // } // 進行と描画 /// <summary> /// 画像を描画する。 /// </summary> public void 描画する( DeviceContext d3dDeviceContext, Size2F 設計画面サイズdpx, RawViewportF[] viewports, DepthStencilView depthStencilView, RenderTargetView renderTargetView, DepthStencilState depthStencilState, float 左位置, float 上位置, float 不透明度0to1 = 1.0f, float X方向拡大率 = 1.0f, float Y方向拡大率 = 1.0f, RectangleF? 転送元矩形 = null ) { RectangleF srcRect = 転送元矩形 ?? new RectangleF( 0, 0, this.サイズ.Width, this.サイズ.Height ); var 画面左上dpx = new Vector3( -設計画面サイズdpx.Width / 2f, +設計画面サイズdpx.Height / 2f, 0f ); var 変換行列 = Matrix.Scaling( X方向拡大率, Y方向拡大率, 0f ) * Matrix.Translation( 画面左上dpx.X + ( 左位置 + X方向拡大率 * srcRect.Width / 2f ), 画面左上dpx.Y - ( 上位置 + Y方向拡大率 * srcRect.Height / 2f ), 0f ); this.描画する( d3dDeviceContext, 設計画面サイズdpx, viewports, depthStencilView, renderTargetView, depthStencilState, 変換行列, 不透明度0to1, 転送元矩形 ); } /// <summary> /// 画像を描画する。 /// </summary> /// <param name="ワールド行列変換">画像は原寸(<see cref="サイズ"/>)にスケーリングされており、その後にこのワールド行列が適用される。</param> /// <param name="転送元矩形">テクスチャ座標(値域0~1)で指定する。</param> public void 描画する( DeviceContext d3dDeviceContext, Size2F 設計画面サイズdpx, RawViewportF[] viewports, DepthStencilView depthStencilView, RenderTargetView renderTargetView, DepthStencilState depthStencilState, Matrix ワールド行列変換, float 不透明度0to1 = 1f, RectangleF? 転送元矩形 = null ) { if( this.Texture is null ) return; var d3ddc = d3dDeviceContext; this.不透明度 = MathUtil.Clamp( 不透明度0to1, 0f, 1f ); var srcRect = 転送元矩形 ?? new RectangleF( 0f, 0f, this.サイズ.Width, this.サイズ.Height ); #region " 定数バッファを更新する。" //---------------- { // 1x1のモデルサイズをテクスチャの描画矩形サイズへスケーリングする行列を前方に乗じる。 ワールド行列変換 = Matrix.Scaling( srcRect.Width, srcRect.Height, 0f ) * ワールド行列変換; // ワールド変換行列 ワールド行列変換.Transpose(); // 転置 this._定数バッファの転送元データ.World = ワールド行列変換; // ビュー変換行列と射影変換行列 this._等倍3D平面描画用の変換行列を取得する( 設計画面サイズdpx, out Matrix ビュー行列, out Matrix 射影行列 ); ビュー行列.Transpose(); // 転置(シェーダーにあわせる) 射影行列.Transpose(); // 転置(シェーダーにあわせる) this._定数バッファの転送元データ.View = ビュー行列; this._定数バッファの転送元データ.Projection = 射影行列; // 描画元矩形(x,y,zは0~1で指定する(UV座標)) this._定数バッファの転送元データ.TexLeft = srcRect.Left / this.サイズ.Width; this._定数バッファの転送元データ.TexTop = srcRect.Top / this.サイズ.Height; this._定数バッファの転送元データ.TexRight = srcRect.Right / this.サイズ.Width; this._定数バッファの転送元データ.TexBottom = srcRect.Bottom / this.サイズ.Height; // アルファ this._定数バッファの転送元データ.TexAlpha = this.不透明度; this._定数バッファの転送元データ.dummy1 = 0f; this._定数バッファの転送元データ.dummy2 = 0f; this._定数バッファの転送元データ.dummy3 = 0f; // 定数バッファへ書き込む。 var dataBox = d3ddc.MapSubresource( resourceRef: _ConstantBuffer, subresource: 0, mapType: MapMode.WriteDiscard, mapFlags: MapFlags.None ); SharpDX.Utilities.Write( dataBox.DataPointer, ref this._定数バッファの転送元データ ); d3ddc.UnmapSubresource( _ConstantBuffer, 0 ); } //---------------- #endregion #region " 3Dパイプラインを設定する。" //---------------- { // 入力アセンブラ d3ddc.InputAssembler.InputLayout = null; d3ddc.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; // 頂点シェーダ d3ddc.VertexShader.Set( _VertexShader ); d3ddc.VertexShader.SetConstantBuffers( 0, _ConstantBuffer ); // ハルシェーダ d3ddc.HullShader.Set( null ); // ドメインシェーダ d3ddc.DomainShader.Set( null ); // ジオメトリシェーダ d3ddc.GeometryShader.Set( null ); // ラスタライザ d3ddc.Rasterizer.SetViewports( viewports ); d3ddc.Rasterizer.State = _RasterizerState; // ピクセルシェーダ d3ddc.PixelShader.Set( _PixelShader ); d3ddc.PixelShader.SetConstantBuffers( 0, _ConstantBuffer ); d3ddc.PixelShader.SetShaderResources( 0, 1, this.ShaderResourceView ); d3ddc.PixelShader.SetSamplers( 0, 1, _SamplerState ); // 出力マージャ d3ddc.OutputMerger.SetTargets( depthStencilView, renderTargetView ); d3ddc.OutputMerger.SetBlendState( ( this.加算合成する ) ? _BlendState加算合成 : _BlendState通常合成, new Color4( 0f, 0f, 0f, 0f ), -1 ); d3ddc.OutputMerger.SetDepthStencilState( depthStencilState, 0 ); } //---------------- #endregion // 頂点バッファとインデックスバッファを使わずに 4 つの頂点を描画する。 d3ddc.Draw( vertexCount: 4, startVertexLocation: 0 ); } // ローカル private ST定数バッファの転送元データ _定数バッファの転送元データ; /// <seealso cref="http://qiita.com/oguna/items/c516e09ee57d931892b6"/> private void _画像ファイルからシェーダリソースビューを作成して返す( Device d3dDevice, BindFlags bindFlags, VariablePath 画像ファイルパス ) { // ファイルからビットマップを生成し、Clone() でフォーマットを A8R8G8B8 に変換する。 using var originalBitmap = new System.Drawing.Bitmap( 画像ファイルパス.変数なしパス ); var 画像の矩形 = new System.Drawing.Rectangle( 0, 0, originalBitmap.Width, originalBitmap.Height ); using var bitmap = originalBitmap.Clone( 画像の矩形, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); // ビットマップからテクスチャを生成する。 var ロック領域 = bitmap.LockBits( 画像の矩形, System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat ); try { var dataBox = new[] { new DataBox( ロック領域.Scan0, bitmap.Width * 4, bitmap.Height ) }; var textureDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = bindFlags, CpuAccessFlags = CpuAccessFlags.None, Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, Height = bitmap.Height, Width = bitmap.Width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription( 1, 0 ), Usage = ResourceUsage.Default, }; this.Texture = new Texture2D( d3dDevice, textureDesc, dataBox ); } finally { bitmap.UnlockBits( ロック領域 ); } // テクスチャのシェーダーリソースビューを生成する。 this.ShaderResourceView = new ShaderResourceView( d3dDevice, this.Texture ); this.サイズ = new Size2F( 画像の矩形.Width, 画像の矩形.Height ); this.実サイズ = new Size2F( this.Texture.Description.Width, this.Texture.Description.Height ); } private void _空のテクスチャとそのシェーダーリソースビューを作成して返す( Device d3dDevice, BindFlags bindFlags, Size2F サイズ ) { // 空のテクスチャを生成する。 var textureDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = bindFlags, CpuAccessFlags = CpuAccessFlags.None, Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, Height = (int)サイズ.Height, Width = (int)サイズ.Width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription( 1, 0 ), Usage = ResourceUsage.Default }; this.Texture = new Texture2D( d3dDevice, textureDesc ); // テクスチャのシェーダーリソースビューを生成する。 this.ShaderResourceView = new ShaderResourceView( d3dDevice, this.Texture ); this.サイズ = サイズ; this.実サイズ = new Size2F( this.Texture.Description.Width, this.Texture.Description.Height ); } /// <summary> /// 等倍3D平面描画用のビュー行列と射影行列を生成して返す。 /// </summary> /// <remarks> /// 「等倍3D平面」とは、Z = 0 におけるビューポートサイズが <paramref name="設計画面サイズdpx"/> に一致する平面である。 /// 例えば、設計画面サイズが 1024x720 の場合、等倍3D平面の表示可能な x, y の値域は (-512, -360)~(+512, +360) となる。 /// この平面を使うと、3Dモデルの配置やサイズ設定を設計画面サイズを基準に行うことができるようになる。 /// 本メソッドは、等倍3D平面を実現するためのビュー行列と射影行列を返す。 /// </remarks> public void _等倍3D平面描画用の変換行列を取得する( Size2F 設計画面サイズdpx, out Matrix ビュー行列, out Matrix 射影行列 ) { const float 視野角deg = 45.0f; var dz = (float)( 設計画面サイズdpx.Height / ( 4.0 * Math.Tan( MathUtil.DegreesToRadians( 視野角deg / 2.0f ) ) ) ); var カメラの位置 = new Vector3( 0f, 0f, -2f * dz ); var カメラの注視点 = new Vector3( 0f, 0f, 0f ); var カメラの上方向 = new Vector3( 0f, 1f, 0f ); ビュー行列 = Matrix.LookAtLH( カメラの位置, カメラの注視点, カメラの上方向 ); 射影行列 = Matrix.PerspectiveFovLH( MathUtil.DegreesToRadians( 視野角deg ), 設計画面サイズdpx.Width / 設計画面サイズdpx.Height, // アスペクト比 -dz, // 前方投影面までの距離 +dz ); // 後方投影面までの距離 } // 全インスタンス共通項目(static) #pragma warning disable 0649 // 「警告: ~は割り当てられません」 private struct ST定数バッファの転送元データ { public Matrix World; // ワールド変換行列 public Matrix View; // ビュー変換行列 public Matrix Projection; // 透視変換行列 public float TexLeft; // 描画元矩形の左u座標(0~1) public float TexTop; // 描画元矩形の上v座標(0~1) public float TexRight; // 描画元矩形の右u座標(0~1) public float TexBottom; // 描画元矩形の下v座標(0~1) public float TexAlpha; // テクスチャに乗じるアルファ値(0~1) public float dummy1; // float4境界に合わせるためのダミー public float dummy2; // float4境界に合わせるためのダミー public float dummy3; // float4境界に合わせるためのダミー }; #pragma warning restore 0649 private static VertexShader _VertexShader = null!; private static PixelShader _PixelShader = null!; private static BlendState _BlendState通常合成 = null!; private static BlendState _BlendState加算合成 = null!; private static RasterizerState _RasterizerState = null!; private static SamplerState _SamplerState = null!; private static SharpDX.Direct3D11.Buffer _ConstantBuffer = null!; public static void 全インスタンスで共有するリソースを作成する( Device1 d3dDevice1, VariablePath 頂点シェーダCSOパス, VariablePath ピクセルシェーダCSOパス ) { using var _ = new LogBlock( Log.現在のメソッド名 ); #region " 頂点シェーダを生成する。" //---------------- { var byteCode = File.ReadAllBytes( 頂点シェーダCSOパス.変数なしパス ); _VertexShader = new VertexShader( d3dDevice1, byteCode ); } //---------------- #endregion #region " ピクセルシェーダを生成する。" //---------------- { var byteCode = File.ReadAllBytes( ピクセルシェーダCSOパス.変数なしパス ); _PixelShader = new PixelShader( d3dDevice1, byteCode ); } //---------------- #endregion #region " ブレンドステート通常版を生成する。" //---------------- { var BlendStateNorm = new BlendStateDescription() { AlphaToCoverageEnable = false, // アルファマスクで透過する(するならZバッファ必須) IndependentBlendEnable = false, // 個別設定。false なら BendStateDescription.RenderTarget[0] だけが有効で、[1~7] は無視される。 }; BlendStateNorm.RenderTarget[ 0 ].IsBlendEnabled = true; // true ならブレンディングが有効。 BlendStateNorm.RenderTarget[ 0 ].RenderTargetWriteMask = ColorWriteMaskFlags.All; // RGBA の書き込みマスク。 // アルファ値のブレンディング設定 ... 特になし BlendStateNorm.RenderTarget[ 0 ].SourceAlphaBlend = BlendOption.One; BlendStateNorm.RenderTarget[ 0 ].DestinationAlphaBlend = BlendOption.Zero; BlendStateNorm.RenderTarget[ 0 ].AlphaBlendOperation = BlendOperation.Add; // 色値のブレンディング設定 ... アルファ強度に応じた透明合成(テクスチャのアルファ値は、テクスチャのアルファ×ピクセルシェーダでの全体アルファとする(HLSL参照)) BlendStateNorm.RenderTarget[ 0 ].SourceBlend = BlendOption.SourceAlpha; BlendStateNorm.RenderTarget[ 0 ].DestinationBlend = BlendOption.InverseSourceAlpha; BlendStateNorm.RenderTarget[ 0 ].BlendOperation = BlendOperation.Add; // ブレンドステートを作成する。 _BlendState通常合成 = new BlendState( d3dDevice1, BlendStateNorm ); } //---------------- #endregion #region " ブレンドステート加算合成版を生成する。" //---------------- { var BlendStateAdd = new BlendStateDescription() { AlphaToCoverageEnable = false, // アルファマスクで透過する(するならZバッファ必須) IndependentBlendEnable = false, // 個別設定。false なら BendStateDescription.RenderTarget[0] だけが有効で、[1~7] は無視される。 }; BlendStateAdd.RenderTarget[ 0 ].IsBlendEnabled = true; // true ならブレンディングが有効。 BlendStateAdd.RenderTarget[ 0 ].RenderTargetWriteMask = ColorWriteMaskFlags.All; // RGBA の書き込みマスク。 // アルファ値のブレンディング設定 ... 特になし BlendStateAdd.RenderTarget[ 0 ].SourceAlphaBlend = BlendOption.One; BlendStateAdd.RenderTarget[ 0 ].DestinationAlphaBlend = BlendOption.Zero; BlendStateAdd.RenderTarget[ 0 ].AlphaBlendOperation = BlendOperation.Add; // 色値のブレンディング設定 ... 加算合成 BlendStateAdd.RenderTarget[ 0 ].SourceBlend = BlendOption.SourceAlpha; BlendStateAdd.RenderTarget[ 0 ].DestinationBlend = BlendOption.One; BlendStateAdd.RenderTarget[ 0 ].BlendOperation = BlendOperation.Add; // ブレンドステートを作成する。 _BlendState加算合成 = new BlendState( d3dDevice1, BlendStateAdd ); } //---------------- #endregion #region " ラスタライザステートを生成する。" //---------------- _RasterizerState = new RasterizerState( d3dDevice1, new RasterizerStateDescription() { FillMode = FillMode.Solid, // 普通に描画する CullMode = CullMode.None, // 両面を描画する IsFrontCounterClockwise = false,// 時計回りが表面 DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, IsScissorEnabled = false, IsMultisampleEnabled = false, IsAntialiasedLineEnabled = false, } ); //---------------- #endregion #region " サンプラーステートを生成する。" //---------------- _SamplerState = new SamplerState( d3dDevice1, new SamplerStateDescription() { Filter = Filter.Anisotropic, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, MipLodBias = 0.0f, MaximumAnisotropy = 2, ComparisonFunction = Comparison.Never, BorderColor = new RawColor4( 0f, 0f, 0f, 0f ), MinimumLod = float.MinValue, MaximumLod = float.MaxValue, } ); //---------------- #endregion #region " 定数バッファを作成する。" //---------------- _ConstantBuffer = new SharpDX.Direct3D11.Buffer( d3dDevice1, new BufferDescription() { Usage = ResourceUsage.Dynamic, // 動的使用法 BindFlags = BindFlags.ConstantBuffer, // 定数バッファ CpuAccessFlags = CpuAccessFlags.Write, // CPUから書き込む OptionFlags = ResourceOptionFlags.None, SizeInBytes = SharpDX.Utilities.SizeOf<ST定数バッファの転送元データ>(), // バッファサイズ StructureByteStride = 0, } ); //---------------- #endregion } public static void 全インスタンスで共有するリソースを解放する() { using var _ = new LogBlock( Log.現在のメソッド名 ); _ConstantBuffer.Dispose(); _SamplerState.Dispose(); _RasterizerState.Dispose(); _BlendState加算合成.Dispose(); _BlendState通常合成.Dispose(); _PixelShader.Dispose(); _VertexShader.Dispose(); } } } <|start_filename|>DTXMania2/ステージ/07演奏/プレイヤー名表示.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using FDK; namespace DTXMania2.演奏 { /// <summary> /// プレイヤー名の表示。 /// </summary> class プレイヤー名表示 : IDisposable { // プロパティ public string 名前 { get; set; } = "(no nmae)"; // 生成と終了 public プレイヤー名表示() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._前回表示した名前 = ""; this._TextFormat = new TextFormat( Global.GraphicResources.DWriteFactory, "Meiryo", FontWeight.Regular, FontStyle.Normal, 22f ); this._TextLayout = null; this._文字色 = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Color4.White ); this._拡大率X = 1.0f; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._文字色.Dispose(); this._TextLayout?.Dispose(); this._TextFormat.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { var 描画矩形 = new RectangleF( 122f, 313f, 240f, 30f ); // 初回または名前が変更された場合に TextLayout を再構築する。 if( ( this._TextLayout is null ) || ( this._前回表示した名前 != this.名前 ) ) { const float 最大幅 = 1000f; this._TextLayout = new TextLayout( Global.GraphicResources.DWriteFactory, this.名前, this._TextFormat, 最大幅, 30f ) { TextAlignment = TextAlignment.Leading, WordWrapping = WordWrapping.NoWrap, // 最大幅を超えても改行しない(はみ出し分は切り捨て) }; float 文字列幅dpx = this._TextLayout.Metrics.WidthIncludingTrailingWhitespace; this._拡大率X = ( 文字列幅dpx <= 描画矩形.Width ) ? 1.0f : ( 描画矩形.Width / 文字列幅dpx ); } var preTrans = d2ddc.Transform; d2ddc.Transform = Matrix3x2.Scaling( this._拡大率X, 1.0f ) * // 拡大縮小 Matrix3x2.Translation( 描画矩形.X, 描画矩形.Y ) * // 平行移動 preTrans; // 座標(描画矩形)は拡大率の影響をうけるので、このメソッドではなく、Matrix3x2.Translation() で設定するほうが楽。 d2ddc.DrawTextLayout( Vector2.Zero, this._TextLayout, this._文字色 ); d2ddc.Transform = preTrans; // 更新 this._前回表示した名前 = this.名前; } // ローカル private string _前回表示した名前; private readonly TextFormat _TextFormat; private TextLayout? _TextLayout; private readonly SolidColorBrush _文字色; private float _拡大率X = 1.0f; } } <|start_filename|>FDK/イメージ/文字列画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Direct3D11; using SharpDX.DirectWrite; using SharpDX.DXGI; using SharpDX.Mathematics.Interop; namespace FDK { public class 文字列画像 : IImage, IDisposable { // プロパティ /// <summary> /// 表示する文字列。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public string 表示文字列 { get => this._表示文字列; set { if( value != this._表示文字列 ) { this._表示文字列 = value; this._TextLayoutを更新せよ = true; } } } /// <summary> /// 文字列描画に使うフォントの名前。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public string フォント名 { get => this._フォント名; set { if( value != this._フォント名 ) { this._フォント名 = value; this._TextFormatを更新せよ = true; } } } /// <summary> /// 文字列描画に使うフォントのサイズ。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public float フォントサイズpt { get => this._フォントサイズpt; set { if( value != this._フォントサイズpt ) { this._フォントサイズpt = value; this._TextFormatを更新せよ = true; } } } /// <summary> /// 文字列描画に使うフォントの太さ。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public FontWeight フォントの太さ { get => this._フォントの太さ; set { if( value != this._フォントの太さ ) { this._フォントの太さ = value; this._TextFormatを更新せよ = true; } } } /// <summary> /// 文字列描画に使うフォントのスタイル。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public FontStyle フォントスタイル { get => this._フォントスタイル; set { if( value != this._フォントスタイル ) { this._フォントスタイル = value; this._TextFormatを更新せよ = true; } } } /// <summary> /// 文字列の前景色。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public Color4 前景色 { get => this._前景色; set { if( value != this._前景色 ) { this._前景色 = value; this._ビットマップを更新せよ = true; } } } /// <summary> /// 文字列の背景色。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public Color4 背景色 { get => this._背景色; set { if( value != this._背景色 ) { this._背景色 = value; this._ビットマップを更新せよ = true; } } } public enum 効果 { /// <summary> /// 文字を前景色で描画する。 /// </summary> 通常, /// <summary> /// 文字は前景色で、影は背景色で描画する。 /// </summary> ドロップシャドウ, /// <summary> /// 文字は前景色で、縁は背景色で描画する。 /// </summary> 縁取り, } /// <summary> /// 文字列の描画効果。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public 効果 描画効果 { get => this._描画効果; set { if( value != this._描画効果 ) { this._描画効果 = value; this._ビットマップを更新せよ = true; } } } /// <summary> /// 縁取りのサイズ。<see cref="描画効果"/>が <see cref="効果.縁取り"/> のときのみ有効。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public float 縁のサイズdpx { get => this._縁のサイズdpx; set { if( value != this._縁のサイズdpx ) { this._縁のサイズdpx = value; this._ビットマップを更新せよ = true; } } } /// <summary> /// 文字列の改行処理。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public WordWrapping WordWrapping { get => this._WordWrapping; set { if( value != this._WordWrapping ) { this._WordWrapping = value; this._TextFormatを更新せよ = true; } } } /// <summary> /// 文字列の縦方向の位置そろえ。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public ParagraphAlignment ParagraphAlignment { get => this._ParagraphAlignment; set { if( value != this._ParagraphAlignment ) { this._ParagraphAlignment = value; this._TextFormatを更新せよ = true; } } } /// <summary> /// 文字列の横方向の位置そろえ。 /// このメンバを更新すると、次回の描画時に画像が更新される。 /// </summary> public TextAlignment TextAlignment { get => this._TextAlignment; set { if( value != this._TextAlignment ) { this._TextAlignment = value; this._TextFormatを更新せよ = true; } } } public float LineSpacing { get; protected set; } public float Baseline { get; protected set; } public bool 加算合成 { get; set; } = false; /// <summary> /// TextLayout を作る際に使われるレイアウトサイズ[dpx]。 /// 右揃えや下揃えなどを使う場合には、このサイズを基準にして、文字列の折り返しなどのレイアウトが行われる。 /// </summary> public Size2F レイアウトサイズdpx { get; set; } /// <summary> /// 実際に作成されたビットマップ画像のサイズ[dpx]。 /// 右揃えや下揃えなどを指定している場合は、このサイズは <see cref="レイアウトサイズdpx"/> に等しい。 /// 指定していない場合は、このサイズは <see cref="_表示文字列のサイズdpx"/> に等しい。 /// </summary> public Size2F 画像サイズdpx { get; protected set; } = Size2F.Zero; public RectangleF? 転送元矩形 { get; set; } = null; // 生成と終了 public 文字列画像( SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.DirectWrite.Factory dwFactory, SharpDX.Direct2D1.Factory1 d2dFactory1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, Size2F 設計画面サイズdpx ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); // 必要なプロパティは呼び出し元で設定すること。 this._画像 = null!; this._TextFormat = null!; this._TextLayout = null!; this._TextRenderer = new カスタムTextRenderer( d2dFactory1, d2dDeviceContext, Color.White, Color.Transparent ); // ビットマップの生成前に。 this._ビットマップを更新せよ = true; this._TextFormatを更新せよ = true; this._TextLayoutを更新せよ = true; if( this.レイアウトサイズdpx == Size2F.Zero ) this.レイアウトサイズdpx = 設計画面サイズdpx; // 初期サイズ } public virtual void Dispose() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this._TextRenderer.Dispose(); this._TextLayout?.Dispose(); this._TextFormat?.Dispose(); this._画像?.Dispose(); } public void ビットマップを生成または更新する( SharpDX.DirectWrite.Factory dwFactory, SharpDX.Direct2D1.Factory1 d2dFactory1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, SharpDX.Direct3D11.Device1 d3dDevice1 ) { float pt2px( float dpi, float pt ) => dpi * pt / 72f; if( this._TextFormatを更新せよ ) { #region " テキストフォーマットを更新する。" //---------------- this._TextFormat?.Dispose(); this._TextFormat = new TextFormat( dwFactory, this.フォント名, this.フォントの太さ, this.フォントスタイル, this.フォントサイズpt ) { TextAlignment = this.TextAlignment, ParagraphAlignment = this.ParagraphAlignment, WordWrapping = this.WordWrapping, FlowDirection = FlowDirection.TopToBottom, ReadingDirection = ReadingDirection.LeftToRight, }; // 行間は、プロパティではなくメソッドで設定する。 this.LineSpacing = pt2px( d2dDeviceContext.DotsPerInch.Width, this.フォントサイズpt ); // baseline の適切な比率は、lineSpacing の 80 %。(MSDNより) this.Baseline = this.LineSpacing * 0.8f; // TextFormat に、行間とベースラインを設定する。 this._TextFormat.SetLineSpacing( LineSpacingMethod.Uniform, this.LineSpacing, this.Baseline ); //---------------- #endregion } if( this._TextLayoutを更新せよ ) { #region " テキストレイアウトを更新する。" //---------------- this._TextLayout?.Dispose(); this._TextLayout = new TextLayout( dwFactory, this.表示文字列, this._TextFormat, this.レイアウトサイズdpx.Width, this.レイアウトサイズdpx.Height ); // レイアウトが変わったのでサイズも更新する。 this._表示文字列のサイズdpx = new Size2F( this._TextLayout.Metrics.WidthIncludingTrailingWhitespace, this._TextLayout.Metrics.Height ); //---------------- #endregion } if( this._ビットマップを更新せよ || this._TextFormatを更新せよ || this._TextLayoutを更新せよ ) { #region " 古いビットマップレンダーターゲットを解放し、新しく生成する。" //---------------- this.画像サイズdpx = ( this.ParagraphAlignment != ParagraphAlignment.Near || this.TextAlignment != TextAlignment.Leading ) ? this.レイアウトサイズdpx : // レイアウトにレイアウトサイズが必要 this._表示文字列のサイズdpx; // レイアウトサイズは不要 if( this.描画効果 == 効果.縁取り ) { // 縁取りを使うなら少し画像サイズを (+16, +16) 増やす。 this.画像サイズdpx = new Size2F( this.画像サイズdpx.Width + 16f, this.画像サイズdpx.Height + 16f ); this._表示文字列のサイズdpx = new Size2F( this._表示文字列のサイズdpx.Width + 16f, this._表示文字列のサイズdpx.Height + 16f ); } this._画像?.Dispose(); this._画像 = new 描画可能画像( d3dDevice1, d2dDeviceContext, this.画像サイズdpx, BindFlags.ShaderResource | BindFlags.RenderTarget ); //---------------- #endregion #region " ビットマップレンダーターゲットをクリアし、テキストを描画する。" //---------------- var surface = this._画像.Bitmap.Surface; // 要Release using var rt = new RenderTarget( d2dFactory1, surface, new RenderTargetProperties( new PixelFormat( Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied ) ) ); ( (IUnknown)surface ).Release(); rt.Transform = Matrix3x2.Identity; // 等倍 rt.AntialiasMode = AntialiasMode.PerPrimitive; rt.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Default; using var 前景色ブラシ = new SolidColorBrush( rt, this.前景色 ); using var 背景色ブラシ = new SolidColorBrush( rt, this.背景色 ); rt.BeginDraw(); rt.Clear( Color.Transparent ); switch( this.描画効果 ) { case 効果.通常: { using var de = new カスタムTextRenderer.DrawingEffect( rt ) { 文字の色 = this.前景色 }; this._TextLayout.Draw( de, this._TextRenderer, 0f, 0f ); break; } case 効果.ドロップシャドウ: { using var de = new カスタムTextRenderer.ドロップシャドウDrawingEffect( rt ) { 文字の色 = this.前景色, 影の色 = this.背景色, 影の距離 = 3.0f }; this._TextLayout.Draw( de, this._TextRenderer, 0f, 0f ); break; } case 効果.縁取り: { using var de = new カスタムTextRenderer.縁取りDrawingEffect( rt ) { 文字の色 = this.前景色, 縁の色 = this.背景色, 縁の太さ = this.縁のサイズdpx }; this._TextLayout.Draw( de, this._TextRenderer, 8f, 8f ); // 描画位置をずらす(+8,+8) break; } } rt.EndDraw(); //---------------- #endregion } this._ビットマップを更新せよ = false; this._TextFormatを更新せよ = false; this._TextLayoutを更新せよ = false; } // 進行と描画 public void 描画する( SharpDX.DirectWrite.Factory dwFactory, SharpDX.Direct2D1.Factory1 d2dFactory1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct3D11.DeviceContext d3dDeviceContext, Size2F 設計画面サイズdpx, RawViewportF[] viewports, DepthStencilView depthStencilView, RenderTargetView renderTargetView, DepthStencilState depthStencilState, float 左位置, float 上位置, float 不透明度0to1 = 1.0f, float X方向拡大率 = 1.0f, float Y方向拡大率 = 1.0f ) { if( string.IsNullOrEmpty( this.表示文字列 ) ) return; if( this._ビットマップを更新せよ || this._TextFormatを更新せよ || this._TextLayoutを更新せよ ) { this.ビットマップを生成または更新する( dwFactory, d2dFactory1, d2dDeviceContext, d3dDevice1 ); } var 画面左上dpx = new Vector3( -設計画面サイズdpx.Width / 2f, +設計画面サイズdpx.Height / 2f, 0f ); var 変換行列 = Matrix.Scaling( X方向拡大率, Y方向拡大率, 1f ) * Matrix.Translation( 画面左上dpx.X + ( 左位置 + X方向拡大率 * this._画像.サイズ.Width / 2f ), 画面左上dpx.Y - ( 上位置 + Y方向拡大率 * this._画像.サイズ.Height / 2f ), 0f ); this._画像.描画する( d3dDeviceContext, 設計画面サイズdpx, viewports, depthStencilView, renderTargetView, depthStencilState, 変換行列, 不透明度0to1 ); } public void 描画する( SharpDX.DirectWrite.Factory dwFactory, SharpDX.Direct2D1.Factory1 d2dFactory1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct3D11.DeviceContext d3dDeviceContext, Size2F 設計画面サイズdpx, RawViewportF[] viewports, DepthStencilView depthStencilView, RenderTargetView renderTargetView, DepthStencilState depthStencilState, Matrix? 変換行列3D = null, float 不透明度0to1 = 1.0f ) { if( string.IsNullOrEmpty( this.表示文字列 ) ) return; if( this._ビットマップを更新せよ || this._TextFormatを更新せよ || this._TextLayoutを更新せよ ) { this.ビットマップを生成または更新する( dwFactory, d2dFactory1, d2dDeviceContext, d3dDevice1 ); } this._画像.描画する( d3dDeviceContext, 設計画面サイズdpx, viewports, depthStencilView, renderTargetView, depthStencilState, 変換行列3D ?? Matrix.Identity, 不透明度0to1 ); } // ローカル private string _表示文字列 = ""; private string _フォント名 = "Meiryo"; private float _フォントサイズpt = 20f; private FontWeight _フォントの太さ = FontWeight.Normal; private FontStyle _フォントスタイル = FontStyle.Normal; private Color4 _前景色 = Color4.White; private Color4 _背景色 = Color4.Black; private 効果 _描画効果 = 効果.通常; private float _縁のサイズdpx = 6f; private WordWrapping _WordWrapping = WordWrapping.Wrap; private ParagraphAlignment _ParagraphAlignment = ParagraphAlignment.Near; private TextAlignment _TextAlignment = TextAlignment.Leading; private TextFormat _TextFormat = null!; private TextLayout _TextLayout = null!; private readonly カスタムTextRenderer _TextRenderer; /// <summary> /// TextLayout で作成された文字列のサイズ[dpx]。 /// <see cref="画像サイズ"/> と同じか、それより小さい。 /// </summary> private Size2F _表示文字列のサイズdpx = Size2F.Zero; private 描画可能画像 _画像; private bool _ビットマップを更新せよ; private bool _TextFormatを更新せよ; private bool _TextLayoutを更新せよ; } } <|start_filename|>FDK/イメージ/フォント画像D2D.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.WIC; namespace FDK { /// <summary> /// 文字盤(複数の文字を描いた1枚の画像)と、文字盤内での個々の文字の位置を表した矩形リストを使って、文字列を描画する。 /// 描画は Direct2D の Bitmap で行う。 /// </summary> public class フォント画像D2D : IImage, IDisposable { // プロパティ /// <summary> /// 文字と文字の間の(横方向の)間隔。拡大率の影響は受けない。負数もOK。 /// </summary> public float 文字幅補正dpx { get; set; } = 0f; /// <summary> /// 透明: 0 ~ 1 :不透明 /// </summary> public float 不透明度 { get; set; } = 1f; // 生成と終了 /// <summary> /// コンストラクタ。 /// 指定された画像ファイルと矩形リストyamlファイルを使って、フォント画像を生成する。 /// </summary> /// <param name="文字幅補正dpx">文字と文字の間の(横方向の)間隔。拡大率の影響は受けない。負数もOK。</param> /// <param name="不透明度">透明: 0 ~ 1 :不透明</param> public フォント画像D2D( ImagingFactory2 imagingFactory2, DeviceContext d2dDeviceContext, VariablePath 文字盤の画像ファイルパス, VariablePath 文字盤の矩形リストファイルパス, float 文字幅補正dpx = 0f, float 不透明度 = 1f ) { this._文字盤 = new 画像D2D( imagingFactory2, d2dDeviceContext, 文字盤の画像ファイルパス ); this._矩形リスト = new 矩形リスト( 文字盤の矩形リストファイルパス ); this.文字幅補正dpx = 文字幅補正dpx; this.不透明度 = 不透明度; } public virtual void Dispose() { this._文字盤.Dispose(); } // 進行と描画 /// <summary> /// 文字列を描画する。 /// </summary> /// <param name="基点のX位置">左揃えなら左端位置、右揃えなら右端位置のX座標。</param> /// <param name="拡大率">文字列の拡大率。null なら等倍。</param> /// <param name="右揃え">trueなら右揃え、falseなら左揃え。</param> public void 描画する( DeviceContext d2ddc, float 基点のX位置, float 上位置, string 表示文字列, Size2F? 拡大率 = null, bool 右揃え = false ) { if( string.IsNullOrEmpty( 表示文字列 ) ) return; 拡大率 ??= new Size2F( 1, 1 ); if( !this._有効文字の矩形と文字数を抽出し文字列全体のサイズを返す( 表示文字列, 拡大率.Value, out Size2F 文字列全体のサイズ, out int 有効文字数, out var 有効文字矩形リスト ) ) return; // 有効文字がない if( 右揃え ) 基点のX位置 -= 文字列全体のサイズ.Width; for( int i = 0; i < 有効文字数; i++ ) { var 文字矩形 = 有効文字矩形リスト.ElementAt( i ); this._文字盤.描画する( d2ddc, 基点のX位置, 上位置 + ( 文字列全体のサイズ.Height - 文字矩形!.Value.Height * 拡大率.Value.Height ), 転送元矩形: 文字矩形, X方向拡大率: 拡大率.Value.Width, Y方向拡大率: 拡大率.Value.Height, 不透明度0to1: this.不透明度 ); 基点のX位置 += ( 文字矩形!.Value.Width * 拡大率.Value.Width + this.文字幅補正dpx ); } } // ローカル private readonly 画像D2D _文字盤; private readonly 矩形リスト _矩形リスト; private bool _有効文字の矩形と文字数を抽出し文字列全体のサイズを返す( string 表示文字列, Size2F 拡大率, out Size2F 文字列全体のサイズ, out int 有効文字数, out IEnumerable<RectangleF?> 有効文字矩形リスト ) { 文字列全体のサイズ = Size2F.Empty; 有効文字矩形リスト = from ch in 表示文字列 where ( this._矩形リスト.文字列to矩形.ContainsKey( ch.ToString() ) ) select ( this._矩形リスト[ ch.ToString() ] ); 有効文字数 = 有効文字矩形リスト.Count(); if( 0 == 有効文字数 ) return false; foreach( var 文字矩形 in 有効文字矩形リスト ) { 文字列全体のサイズ.Width += ( 文字矩形!.Value.Width * 拡大率.Width + this.文字幅補正dpx ); if( 文字列全体のサイズ.Height < 文字矩形!.Value.Height * 拡大率.Height ) 文字列全体のサイズ.Height = 文字矩形!.Value.Height * 拡大率.Height; // 文字列全体の高さは、最大の文字高に一致。 } return true; } } } <|start_filename|>FDK/GameMode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace FDK { /// <summary> /// Game Mode API。 /// </summary> /// <seealso cref="https://docs.microsoft.com/en-us/previous-versions/windows/desktop/gamemode/game-mode-portal"/> public static class GameMode { /// <summary> /// ゲームモードが有効である場合はtrueを、そうでなければfalseを返す。 /// </summary> public static bool ゲームモードである { get { HasExpandedResources( out bool bHas ); return bHas; } } [DllImport( "gamemode.dll" )] public static extern int HasExpandedResources( out bool bHas ); } } <|start_filename|>DTXMania2/ステージ/06曲読み込み/プレビュー画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.曲読み込み { class プレビュー画像 : IDisposable { // 生成と終了 public プレビュー画像() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._既定のノード画像 = new 画像D2D( @"$(Images)\DefaultPreviewImage.png" ); this._現行化前のノード画像 = new 画像D2D( @"$(Images)\PreviewImageWaitForActivation.png" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._現行化前のノード画像.Dispose(); this._既定のノード画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { var ノード画像 = Global.App.演奏譜面.譜面と画像を現行化済み ? ( Global.App.演奏譜面.プレビュー画像 ?? this._既定のノード画像 ) : this._現行化前のノード画像; var 変換行列2D = Matrix3x2.Scaling( this._プレビュー画像表示サイズdpx.X / ノード画像.サイズ.Width, this._プレビュー画像表示サイズdpx.Y / ノード画像.サイズ.Height ) * Matrix3x2.Translation( this._プレビュー画像表示位置dpx.X, this._プレビュー画像表示位置dpx.Y ); ノード画像.描画する( d2ddc, 変換行列2D ); } // ローカル private readonly Vector3 _プレビュー画像表示位置dpx = new Vector3( 150f, 117f, 0f ); private readonly Vector3 _プレビュー画像表示サイズdpx = new Vector3( 576f, 576f, 0f ); private readonly 画像D2D _既定のノード画像; private readonly 画像D2D _現行化前のノード画像; } } <|start_filename|>DTXMania2/ステージ/舞台画像.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using SharpDX.Direct2D1.Effects; using FDK; namespace DTXMania2 { /// <summary> /// ステージの背景として使う画像。 /// </summary> /// <remarks> /// ぼかし&縮小アニメーションを適用したり、黒幕付き背景画像を表示したりすることもできる。 /// </remarks> class 舞台画像 : IDisposable { // プロパティ public Size2F サイズ => this._背景画像.サイズ; public bool ぼかしと縮小を適用中 { get; protected set; } = false; // 生成と終了 public 舞台画像( string? 背景画像ファイル名 = null, string? 背景黒幕付き画像ファイル名 = null ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._背景画像 = new 画像D2D( 背景画像ファイル名 ?? @"$(Images)\Background.jpg" ); this._背景黒幕付き画像 = new 画像D2D( 背景黒幕付き画像ファイル名 ?? @"$(Images)\BackgroundWithDarkCurtain.jpg" ); var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; this._ガウスぼかしエフェクト = new GaussianBlur( d2ddc ); this._ガウスぼかしエフェクト黒幕付き用 = new GaussianBlur( d2ddc ); this._拡大エフェクト = new Scale( d2ddc ) { CenterPoint = new Vector2( Global.GraphicResources.設計画面サイズ.Width / 2.0f, Global.GraphicResources.設計画面サイズ.Height / 2.0f ), }; this._拡大エフェクト黒幕付き用 = new Scale( d2ddc ) { CenterPoint = new Vector2( Global.GraphicResources.設計画面サイズ.Width / 2.0f, Global.GraphicResources.設計画面サイズ.Height / 2.0f ), }; this._クリッピングエフェクト = new Crop( d2ddc ); this._クリッピングエフェクト黒幕付き用 = new Crop( d2ddc ); this._ぼかしと縮小割合 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); this.ぼかしと縮小を適用中 = false; this._ストーリーボード = null; this._初めての進行描画 = true; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ストーリーボード?.Dispose(); this._ぼかしと縮小割合?.Dispose(); this._クリッピングエフェクト黒幕付き用.Dispose(); this._クリッピングエフェクト.Dispose(); this._拡大エフェクト黒幕付き用.Dispose(); this._拡大エフェクト.Dispose(); this._ガウスぼかしエフェクト黒幕付き用.Dispose(); this._ガウスぼかしエフェクト.Dispose(); this._背景黒幕付き画像.Dispose(); this._背景画像.Dispose(); } // 効果アニメーション public void ぼかしと縮小を適用する( double 完了までの最大時間sec = 1.0 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // 既に適用中なら無視。 if( this.ぼかしと縮小を適用中 ) return; if( 0.0 == 完了までの最大時間sec ) { // (A) アニメーションなしで即適用。 this._ストーリーボード?.Dispose(); this._ストーリーボード = null; this._ぼかしと縮小割合?.Dispose(); this._ぼかしと縮小割合 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); } else { // (B) アニメーションを付けて徐々に適用。 using( var 割合遷移 = Global.Animation.TrasitionLibrary.SmoothStop( 完了までの最大時間sec, finalValue: 1.0 ) ) { this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( Global.Animation.Manager ); this._ストーリーボード.AddTransition( this._ぼかしと縮小割合, 割合遷移 ); this._ストーリーボード.Schedule( Global.Animation.Timer.Time ); // 今すぐアニメーション開始 } } this.ぼかしと縮小を適用中 = true; } public void ぼかしと縮小を解除する( double 完了までの最大時間sec = 1.0 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); // 適用してないなら無視。 if( !this.ぼかしと縮小を適用中 ) return; if( 0.0 == 完了までの最大時間sec ) { // (A) アニメーションなしで即適用。 this._ストーリーボード?.Dispose(); this._ストーリーボード = null; this._ぼかしと縮小割合?.Dispose(); this._ぼかしと縮小割合 = new Variable( Global.Animation.Manager, initialValue: 0.0 ); } else { // (B) アニメーションを付けて徐々に適用。 using( var 割合遷移 = Global.Animation.TrasitionLibrary.SmoothStop( 完了までの最大時間sec, finalValue: 0.0 ) ) { this._ストーリーボード?.Dispose(); this._ストーリーボード = new Storyboard( Global.Animation.Manager ); this._ストーリーボード.AddTransition( this._ぼかしと縮小割合, 割合遷移 ); this._ストーリーボード.Schedule( Global.Animation.Timer.Time ); // 今すぐアニメーション開始 } } this.ぼかしと縮小を適用中 = false; } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, bool 黒幕付き = false, Vector4? 表示領域 = null, LayerParameters1? layerParameters1 = null ) { if( this._初めての進行描画 ) { #region " 背景画像と黒幕付き背景画像のそれぞれに対して、エフェクトチェーン(拡大 → ぼかし → クリッピング)を作成する。" //---------------- this._拡大エフェクト.SetInput( 0, this._背景画像.Bitmap, true ); this._ガウスぼかしエフェクト.SetInputEffect( 0, this._拡大エフェクト ); this._クリッピングエフェクト.SetInputEffect( 0, this._ガウスぼかしエフェクト ); this._拡大エフェクト黒幕付き用.SetInput( 0, this._背景黒幕付き画像.Bitmap, true ); this._ガウスぼかしエフェクト黒幕付き用.SetInputEffect( 0, this._拡大エフェクト黒幕付き用 ); this._クリッピングエフェクト黒幕付き用.SetInputEffect( 0, this._ガウスぼかしエフェクト黒幕付き用 ); //---------------- #endregion this._初めての進行描画 = false; } double 割合 = this._ぼかしと縮小割合?.Value ?? 0.0; var preBlend = d2ddc.PrimitiveBlend; d2ddc.PrimitiveBlend = PrimitiveBlend.SourceOver; if( 黒幕付き ) { #region " (A) 黒幕付き背景画像を描画する。" //---------------- this._拡大エフェクト黒幕付き用.ScaleAmount = new Vector2( (float)( 1f + ( 1.0 - 割合 ) * 0.04 ) ); // 1.04 ~ 1 this._ガウスぼかしエフェクト黒幕付き用.StandardDeviation = (float)( 割合 * 10.0 ); // 0~10 this._クリッピングエフェクト黒幕付き用.Rectangle = ( null != 表示領域 ) ? (Vector4)表示領域 : new Vector4( 0f, 0f, this._背景黒幕付き画像.サイズ.Width, this._背景黒幕付き画像.サイズ.Height ); if( layerParameters1.HasValue ) { // (A-a) レイヤーパラメータの指定あり using( var layer = new Layer( d2ddc ) ) { d2ddc.PushLayer( layerParameters1.Value, layer ); d2ddc.DrawImage( this._クリッピングエフェクト黒幕付き用 ); d2ddc.PopLayer(); } } else { // (A-b) レイヤーパラメータの指定なし d2ddc.DrawImage( this._クリッピングエフェクト黒幕付き用 ); } //---------------- #endregion } else { #region " (B) 背景画像を描画する。" //---------------- this._拡大エフェクト.ScaleAmount = new Vector2( (float)( 1f + ( 1.0 - 割合 ) * 0.04 ) ); // 1.04 ~ 1 this._ガウスぼかしエフェクト.StandardDeviation = (float)( 割合 * 10.0 ); // 0~10 this._クリッピングエフェクト.Rectangle = ( null != 表示領域 ) ? (Vector4)表示領域 : new Vector4( 0f, 0f, this._背景画像.サイズ.Width, this._背景画像.サイズ.Height ); if( layerParameters1.HasValue ) { // (B-a) レイヤーパラメータの指定あり using( var layer = new Layer( d2ddc ) ) { d2ddc.PushLayer( layerParameters1.Value, layer ); d2ddc.DrawImage( this._クリッピングエフェクト ); d2ddc.PopLayer(); } } else { // (B-b) レイヤーパラメータの指定なし d2ddc.DrawImage( this._クリッピングエフェクト ); } //---------------- #endregion } d2ddc.PrimitiveBlend = preBlend; } // ローカル private bool _初めての進行描画 = true; private readonly 画像D2D _背景画像; // D2D Effect を使う private readonly 画像D2D _背景黒幕付き画像; // D2D Effect を使う private readonly GaussianBlur _ガウスぼかしエフェクト; private readonly GaussianBlur _ガウスぼかしエフェクト黒幕付き用; private readonly Scale _拡大エフェクト; private readonly Scale _拡大エフェクト黒幕付き用; private readonly Crop _クリッピングエフェクト; private readonly Crop _クリッピングエフェクト黒幕付き用; /// <summary> /// くっきり&拡大: 0 ~ 1 :ぼかし&縮小 /// </summary> private Variable? _ぼかしと縮小割合 = null; private Storyboard? _ストーリーボード = null; } } <|start_filename|>FDK/StreamStringForNamedPipe.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace FDK { /// <summary> /// 名前付きパイプライン送受信用ストリームクラス。 /// </summary> /// <seealso cref="https://docs.microsoft.com/ja-jp/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication"/> public class StreamStringForNamedPipe { /// <summary> /// バイトストリーム用の送受信インスタンスを生成する。 /// </summary> /// <param name="ioStream">送受信に使用するバイトストリーム。</param> public StreamStringForNamedPipe( Stream ioStream ) { this._IoStream = ioStream; this._StreamEncoding = new UnicodeEncoding(); } /// <summary> /// バイトストリームから文字列を受信する。 /// </summary> public string ReadString() { // 最初に受信する2バイトをデータ長とする。 int b1 = this._IoStream.ReadByte(); if( -1 == b1 ) return ""; int b2 = this._IoStream.ReadByte(); if( -1 == b2 ) return ""; int len = ( b1 << 8 ) + b2; if( len < 0 ) return ""; // 念のため // 次いで、データ本体を受信。 var inBuffer = new byte[ len ]; this._IoStream.Read( inBuffer, 0, len ); // 受信した byte[] を string にして返す。 return this._StreamEncoding.GetString( inBuffer ); } /// <summary> /// バイトストリームへ文字列を送信する。 /// </summary> /// <param name="送信文字列"></param> /// <returns></returns> public int WriteString( string 送信文字列 ) { var outBuffer = _StreamEncoding.GetBytes( 送信文字列 ); // 最初にデータ長として2バイトを送信する。 int len = outBuffer.Length; if( len > UInt16.MaxValue ) throw new Exception( "送信文字列が長すぎます。" ); this._IoStream.WriteByte( (byte)( len >> 8 ) ); this._IoStream.WriteByte( (byte)( len & 0xFF ) ); // 次いで、データ本体を送信。 this._IoStream.Write( outBuffer, 0, len ); this._IoStream.Flush(); // 送信したデータ数[byte]を返す。 return outBuffer.Length + 2; } private readonly Stream _IoStream; private readonly UnicodeEncoding _StreamEncoding; } } <|start_filename|>SSTFEditor/オプションダイアログ.designer.cs<|end_filename|> namespace SSTFEditor { partial class オプションダイアログ { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(オプションダイアログ)); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.tabControlオプション = new System.Windows.Forms.TabControl(); this.tabPage全般 = new System.Windows.Forms.TabPage(); this.groupBoxSplashChips = new System.Windows.Forms.GroupBox(); this.radioButtonSplashRight = new System.Windows.Forms.RadioButton(); this.radioButtonSplashLeft = new System.Windows.Forms.RadioButton(); this.groupBoxChinaChips = new System.Windows.Forms.GroupBox(); this.radioButtonChinaRight = new System.Windows.Forms.RadioButton(); this.radioButtonChinaLeft = new System.Windows.Forms.RadioButton(); this.groupBoxRideChips = new System.Windows.Forms.GroupBox(); this.radioButtonRideRight = new System.Windows.Forms.RadioButton(); this.radioButtonRideLeft = new System.Windows.Forms.RadioButton(); this.checkBoxSSTF変換通知ダイアログ = new System.Windows.Forms.CheckBox(); this.buttonViewerPath参照 = new System.Windows.Forms.Button(); this.textBoxViewerPath = new System.Windows.Forms.TextBox(); this.labelViewerPath = new System.Windows.Forms.Label(); this.checkBoxオートフォーカス = new System.Windows.Forms.CheckBox(); this.label個まで表示する = new System.Windows.Forms.Label(); this.checkBox最近使用したファイル = new System.Windows.Forms.CheckBox(); this.numericUpDown最近使用したファイルの最大表示個数 = new System.Windows.Forms.NumericUpDown(); this.tabControlオプション.SuspendLayout(); this.tabPage全般.SuspendLayout(); this.groupBoxSplashChips.SuspendLayout(); this.groupBoxChinaChips.SuspendLayout(); this.groupBoxRideChips.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown最近使用したファイルの最大表示個数)).BeginInit(); this.SuspendLayout(); // // buttonOK // resources.ApplyResources(this.buttonOK, "buttonOK"); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Name = "buttonOK"; this.buttonOK.UseVisualStyleBackColor = true; // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // tabControlオプション // resources.ApplyResources(this.tabControlオプション, "tabControlオプション"); this.tabControlオプション.Controls.Add(this.tabPage全般); this.tabControlオプション.Name = "tabControlオプション"; this.tabControlオプション.SelectedIndex = 0; // // tabPage全般 // resources.ApplyResources(this.tabPage全般, "tabPage全般"); this.tabPage全般.Controls.Add(this.groupBoxSplashChips); this.tabPage全般.Controls.Add(this.groupBoxChinaChips); this.tabPage全般.Controls.Add(this.groupBoxRideChips); this.tabPage全般.Controls.Add(this.checkBoxSSTF変換通知ダイアログ); this.tabPage全般.Controls.Add(this.buttonViewerPath参照); this.tabPage全般.Controls.Add(this.textBoxViewerPath); this.tabPage全般.Controls.Add(this.labelViewerPath); this.tabPage全般.Controls.Add(this.checkBoxオートフォーカス); this.tabPage全般.Controls.Add(this.label個まで表示する); this.tabPage全般.Controls.Add(this.checkBox最近使用したファイル); this.tabPage全般.Controls.Add(this.numericUpDown最近使用したファイルの最大表示個数); this.tabPage全般.Name = "tabPage全般"; this.tabPage全般.UseVisualStyleBackColor = true; // // groupBoxSplashChips // resources.ApplyResources(this.groupBoxSplashChips, "groupBoxSplashChips"); this.groupBoxSplashChips.Controls.Add(this.radioButtonSplashRight); this.groupBoxSplashChips.Controls.Add(this.radioButtonSplashLeft); this.groupBoxSplashChips.Name = "groupBoxSplashChips"; this.groupBoxSplashChips.TabStop = false; // // radioButtonSplashRight // resources.ApplyResources(this.radioButtonSplashRight, "radioButtonSplashRight"); this.radioButtonSplashRight.Name = "radioButtonSplashRight"; this.radioButtonSplashRight.UseVisualStyleBackColor = true; // // radioButtonSplashLeft // resources.ApplyResources(this.radioButtonSplashLeft, "radioButtonSplashLeft"); this.radioButtonSplashLeft.Checked = true; this.radioButtonSplashLeft.Name = "radioButtonSplashLeft"; this.radioButtonSplashLeft.TabStop = true; this.radioButtonSplashLeft.UseVisualStyleBackColor = true; // // groupBoxChinaChips // resources.ApplyResources(this.groupBoxChinaChips, "groupBoxChinaChips"); this.groupBoxChinaChips.Controls.Add(this.radioButtonChinaRight); this.groupBoxChinaChips.Controls.Add(this.radioButtonChinaLeft); this.groupBoxChinaChips.Name = "groupBoxChinaChips"; this.groupBoxChinaChips.TabStop = false; // // radioButtonChinaRight // resources.ApplyResources(this.radioButtonChinaRight, "radioButtonChinaRight"); this.radioButtonChinaRight.Checked = true; this.radioButtonChinaRight.Name = "radioButtonChinaRight"; this.radioButtonChinaRight.TabStop = true; this.radioButtonChinaRight.UseVisualStyleBackColor = true; // // radioButtonChinaLeft // resources.ApplyResources(this.radioButtonChinaLeft, "radioButtonChinaLeft"); this.radioButtonChinaLeft.Name = "radioButtonChinaLeft"; this.radioButtonChinaLeft.UseVisualStyleBackColor = true; // // groupBoxRideChips // resources.ApplyResources(this.groupBoxRideChips, "groupBoxRideChips"); this.groupBoxRideChips.Controls.Add(this.radioButtonRideRight); this.groupBoxRideChips.Controls.Add(this.radioButtonRideLeft); this.groupBoxRideChips.Name = "groupBoxRideChips"; this.groupBoxRideChips.TabStop = false; // // radioButtonRideRight // resources.ApplyResources(this.radioButtonRideRight, "radioButtonRideRight"); this.radioButtonRideRight.Checked = true; this.radioButtonRideRight.Name = "radioButtonRideRight"; this.radioButtonRideRight.TabStop = true; this.radioButtonRideRight.UseVisualStyleBackColor = true; // // radioButtonRideLeft // resources.ApplyResources(this.radioButtonRideLeft, "radioButtonRideLeft"); this.radioButtonRideLeft.Name = "radioButtonRideLeft"; this.radioButtonRideLeft.UseVisualStyleBackColor = true; // // checkBoxSSTF変換通知ダイアログ // resources.ApplyResources(this.checkBoxSSTF変換通知ダイアログ, "checkBoxSSTF変換通知ダイアログ"); this.checkBoxSSTF変換通知ダイアログ.Name = "checkBoxSSTF変換通知ダイアログ"; this.checkBoxSSTF変換通知ダイアログ.UseVisualStyleBackColor = true; // // buttonViewerPath参照 // resources.ApplyResources(this.buttonViewerPath参照, "buttonViewerPath参照"); this.buttonViewerPath参照.Name = "buttonViewerPath参照"; this.buttonViewerPath参照.UseVisualStyleBackColor = true; this.buttonViewerPath参照.Click += new System.EventHandler(this.buttonViewerPath参照_Click); // // textBoxViewerPath // resources.ApplyResources(this.textBoxViewerPath, "textBoxViewerPath"); this.textBoxViewerPath.Name = "textBoxViewerPath"; // // labelViewerPath // resources.ApplyResources(this.labelViewerPath, "labelViewerPath"); this.labelViewerPath.Name = "labelViewerPath"; // // checkBoxオートフォーカス // resources.ApplyResources(this.checkBoxオートフォーカス, "checkBoxオートフォーカス"); this.checkBoxオートフォーカス.Name = "checkBoxオートフォーカス"; this.checkBoxオートフォーカス.UseVisualStyleBackColor = true; // // label個まで表示する // resources.ApplyResources(this.label個まで表示する, "label個まで表示する"); this.label個まで表示する.Name = "label個まで表示する"; // // checkBox最近使用したファイル // resources.ApplyResources(this.checkBox最近使用したファイル, "checkBox最近使用したファイル"); this.checkBox最近使用したファイル.Name = "checkBox最近使用したファイル"; this.checkBox最近使用したファイル.UseVisualStyleBackColor = true; // // numericUpDown最近使用したファイルの最大表示個数 // resources.ApplyResources(this.numericUpDown最近使用したファイルの最大表示個数, "numericUpDown最近使用したファイルの最大表示個数"); this.numericUpDown最近使用したファイルの最大表示個数.Maximum = new decimal(new int[] { 10, 0, 0, 0}); this.numericUpDown最近使用したファイルの最大表示個数.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numericUpDown最近使用したファイルの最大表示個数.Name = "numericUpDown最近使用したファイルの最大表示個数"; this.numericUpDown最近使用したファイルの最大表示個数.Value = new decimal(new int[] { 1, 0, 0, 0}); // // オプションダイアログ // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ControlBox = false; this.Controls.Add(this.buttonOK); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.tabControlオプション); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "オプションダイアログ"; this.tabControlオプション.ResumeLayout(false); this.tabPage全般.ResumeLayout(false); this.tabPage全般.PerformLayout(); this.groupBoxSplashChips.ResumeLayout(false); this.groupBoxSplashChips.PerformLayout(); this.groupBoxChinaChips.ResumeLayout(false); this.groupBoxChinaChips.PerformLayout(); this.groupBoxRideChips.ResumeLayout(false); this.groupBoxRideChips.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown最近使用したファイルの最大表示個数)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.TabControl tabControlオプション; private System.Windows.Forms.TabPage tabPage全般; internal System.Windows.Forms.CheckBox checkBoxオートフォーカス; private System.Windows.Forms.Label label個まで表示する; internal System.Windows.Forms.CheckBox checkBox最近使用したファイル; internal System.Windows.Forms.NumericUpDown numericUpDown最近使用したファイルの最大表示個数; private System.Windows.Forms.Button buttonViewerPath参照; private System.Windows.Forms.Label labelViewerPath; internal System.Windows.Forms.TextBox textBoxViewerPath; internal System.Windows.Forms.CheckBox checkBoxSSTF変換通知ダイアログ; private System.Windows.Forms.GroupBox groupBoxSplashChips; private System.Windows.Forms.GroupBox groupBoxChinaChips; private System.Windows.Forms.GroupBox groupBoxRideChips; internal System.Windows.Forms.RadioButton radioButtonSplashRight; internal System.Windows.Forms.RadioButton radioButtonSplashLeft; internal System.Windows.Forms.RadioButton radioButtonChinaRight; internal System.Windows.Forms.RadioButton radioButtonChinaLeft; internal System.Windows.Forms.RadioButton radioButtonRideRight; internal System.Windows.Forms.RadioButton radioButtonRideLeft; } } <|start_filename|>DTXMania2/ステージ/07演奏/ドラムチップ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2.演奏 { class ドラムチップ : IDisposable { // 生成と終了 public ドラムチップ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ドラムチップ画像 = new 画像D2D( @"$(Images)\PlayStage\DrumChip.png" ); this._ドラムチップの矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\DrumChip.yaml" ); this._ドラムチップアニメ = new LoopCounter( 0, 48, 10 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ドラムチップ画像.Dispose(); } // 進行と描画 public 演奏結果 進行描画する( DeviceContext d2ddc, ref int 描画開始チップ番号, チップの演奏状態 state, SSTF.チップ chip, int index, double ヒット判定バーとの距離dpx ) { float たて中央位置dpx = (float)( 演奏ステージ.ヒット判定位置Ydpx + ヒット判定バーとの距離dpx ); float 消滅割合 = 0f; const double チップが隠れるであろう適切なマージン = 40.0; #region " 消滅割合を算出; チップがヒット判定バーを通過したら徐々に消滅する。" //---------------- const float 消滅を開始するヒット判定バーからの距離dpx = 20f; const float 消滅開始から完全消滅するまでの距離dpx = 70f; if( 消滅を開始するヒット判定バーからの距離dpx < ヒット判定バーとの距離dpx ) // 通過した { // 通過距離に応じて 0→1の消滅割合を付与する。0で完全表示、1で完全消滅、通過してなければ 0。 消滅割合 = Math.Min( 1f, (float)( ( ヒット判定バーとの距離dpx - 消滅を開始するヒット判定バーからの距離dpx ) / 消滅開始から完全消滅するまでの距離dpx ) ); } //---------------- #endregion bool チップが描画開始チップである = ( index == 描画開始チップ番号 ); bool チップのY座標が画面下端を越えて隠れた = ( Global.GraphicResources.設計画面サイズ.Height + チップが隠れるであろう適切なマージン < たて中央位置dpx ); if( チップが描画開始チップである && チップのY座標が画面下端を越えて隠れた ) { #region " 描画開始チップ番号を更新し、演奏クリアのチェックを行う。" //---------------- 描画開始チップ番号++; // 描画開始チップがチップリストの末尾に到達したらクリア。 if( Global.App.演奏スコア.チップリスト.Count <= 描画開始チップ番号 ) { 描画開始チップ番号 = -1; return 演奏結果.クリア; } //---------------- #endregion } else if( !state.不可視 ) // 不可視チップは表示しない。 { #region " ドラムチップを描画する。" //---------------- var userConfig = Global.App.ログオン中のユーザ; // 音量からチップの大きさを計算する。 var 大きさ0to1 = new Size2F( 1f, 1f ); // 音量を反映した大きさ(縦横の倍率)。 var 等倍 = new Size2F( 1f, 1f ); // 音量を反映しない場合はこっちを使う。 if( userConfig.音量に応じてチップサイズを変更する && chip.チップ種別 != SSTF.チップ種別.Snare_Ghost ) // Snare Ghost は対象外 { // 既定音量未満は大きさを小さくするが、既定音量以上は大きさ1.0のままとする。最小は 0.3。 大きさ0to1 = new Size2F( 1f, MathUtil.Clamp( chip.音量 / (float)SSTF.チップ.既定音量, 0.3f, 1.0f ) ); // 現状、音量は縦方向にのみ影響する。 } var 表示レーン種別 = userConfig.ドラムチッププロパティリスト[ chip.チップ種別 ].表示レーン種別; var 表示チップ種別 = userConfig.ドラムチッププロパティリスト[ chip.チップ種別 ].表示チップ種別; if( 表示レーン種別 != 表示レーン種別.Unknown && 表示チップ種別 != 表示チップ種別.Unknown ) // Unknwon ならチップを表示しない。 { // チップを描画する。 switch( chip.チップ種別 ) { case SSTF.チップ種別.LeftCrash: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.LeftCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.LeftCymbal.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.HiHat_Close: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.HiHat, this._ドラムチップの矩形リスト[ 表示チップ種別.HiHat.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.HiHat_HalfOpen: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.HiHat, this._ドラムチップの矩形リスト[ 表示チップ種別.HiHat.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Foot, this._ドラムチップの矩形リスト[ 表示チップ種別.HiHat_HalfOpen.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.HiHat_Open: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.HiHat, this._ドラムチップの矩形リスト[ 表示チップ種別.HiHat.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Foot, this._ドラムチップの矩形リスト[ 表示チップ種別.HiHat_Open.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.HiHat_Foot: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Foot, this._ドラムチップの矩形リスト[ 表示チップ種別.Foot.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.Snare: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.Snare, this._ドラムチップの矩形リスト[ 表示チップ種別.Snare.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Snare_ClosedRim: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Snare, this._ドラムチップの矩形リスト[ 表示チップ種別.Snare_ClosedRim.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.Snare_OpenRim: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Snare, this._ドラムチップの矩形リスト[ 表示チップ種別.Snare_OpenRim.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); //this._単画チップを1つ描画する( dc,表示レーン種別.Snare, this._ドラムチップの矩形リスト[ 表示チップ種別.Snare.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); // → ないほうがいいかも。 break; case SSTF.チップ種別.Snare_Ghost: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Snare, this._ドラムチップの矩形リスト[ 表示チップ種別.Snare_Ghost.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.Bass: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.Bass, this._ドラムチップの矩形リスト[ 表示チップ種別.Bass.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.LeftBass: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.Bass, this._ドラムチップの矩形リスト[ 表示チップ種別.Bass.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Tom1: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.Tom1, this._ドラムチップの矩形リスト[ 表示チップ種別.Tom1.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Tom1_Rim: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Tom1, this._ドラムチップの矩形リスト[ 表示チップ種別.Tom1_Rim.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.Tom2: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.Tom2, this._ドラムチップの矩形リスト[ 表示チップ種別.Tom2.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Tom2_Rim: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Tom2, this._ドラムチップの矩形リスト[ 表示チップ種別.Tom2_Rim.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.Tom3: this._アニメチップを1つ描画する( d2ddc, 表示レーン種別.Tom3, this._ドラムチップの矩形リスト[ 表示チップ種別.Tom3.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Tom3_Rim: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.Tom3, this._ドラムチップの矩形リスト[ 表示チップ種別.Tom3_Rim.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.RightCrash: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.RightCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.RightCymbal.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.China: if( userConfig.表示レーンの左右.Chinaは左 ) this._単画チップを1つ描画する( d2ddc, 表示レーン種別.LeftCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.LeftChina.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); else this._単画チップを1つ描画する( d2ddc, 表示レーン種別.RightCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.RightChina.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Ride: if( userConfig.表示レーンの左右.Rideは左 ) this._単画チップを1つ描画する( d2ddc, 表示レーン種別.LeftCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.LeftRide.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); else this._単画チップを1つ描画する( d2ddc, 表示レーン種別.RightCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.RightRide.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Ride_Cup: if( userConfig.表示レーンの左右.Rideは左 ) this._単画チップを1つ描画する( d2ddc, 表示レーン種別.LeftCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.LeftRide_Cup.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); else this._単画チップを1つ描画する( d2ddc, 表示レーン種別.RightCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.RightRide_Cup.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.Splash: if( userConfig.表示レーンの左右.Splashは左 ) this._単画チップを1つ描画する( d2ddc, 表示レーン種別.LeftCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.LeftSplash.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); else this._単画チップを1つ描画する( d2ddc, 表示レーン種別.RightCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.RightSplash.ToString() ]!.Value, たて中央位置dpx, 大きさ0to1, 消滅割合 ); break; case SSTF.チップ種別.LeftCymbal_Mute: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.LeftCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.LeftCymbal_Mute.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; case SSTF.チップ種別.RightCymbal_Mute: this._単画チップを1つ描画する( d2ddc, 表示レーン種別.RightCymbal, this._ドラムチップの矩形リスト[ 表示チップ種別.RightCymbal_Mute.ToString() ]!.Value, たて中央位置dpx, 等倍, 消滅割合 ); break; } } //---------------- #endregion } return 演奏結果.演奏中; } // ローカル private readonly 画像D2D _ドラムチップ画像; private readonly 矩形リスト _ドラムチップの矩形リスト; private readonly LoopCounter _ドラムチップアニメ; private const float _チップの最終調整倍率 = 1.2f; // 見た感じで決めた主観的な値。 private void _単画チップを1つ描画する( DeviceContext d2ddc, 表示レーン種別 lane, RectangleF 転送元矩形, float 上位置, Size2F 大きさ0to1, float 消滅割合 ) { float X倍率 = 大きさ0to1.Width; float Y倍率 = 大きさ0to1.Height; // シンバルレーンは大きさの変化をより少なく、さらにX倍率もY倍率と同じにする。 if( lane == 表示レーン種別.LeftCymbal || lane == 表示レーン種別.RightCymbal ) { X倍率 = MathUtil.Clamp( 大きさ0to1.Width * 2f, min: 0f, max: 1f ); Y倍率 = MathUtil.Clamp( 大きさ0to1.Height * 2f, min: 0f, max: 1f ); } X倍率 *= ( 1f - 消滅割合 ) * _チップの最終調整倍率; Y倍率 *= ( 1f - 消滅割合 ) * _チップの最終調整倍率; this._ドラムチップ画像.描画する( d2ddc, 左位置: レーンフレーム.レーン中央位置X[ lane ] - ( 転送元矩形.Width * X倍率 / 2f ), 上位置: 上位置 - ( 転送元矩形.Height * Y倍率 / 2f ), 転送元矩形: 転送元矩形, X方向拡大率: X倍率, Y方向拡大率: Y倍率 ); } private void _アニメチップを1つ描画する( DeviceContext d2ddc, 表示レーン種別 lane, RectangleF 転送元矩形, float Y, Size2F 大きさ0to1, float 消滅割合 ) { float X倍率 = 大きさ0to1.Width; float Y倍率 = 大きさ0to1.Height; // Bass は縦方向に少し大きめに。 if( lane == 表示レーン種別.Bass ) Y倍率 *= 1.2f; X倍率 *= ( 1f - 消滅割合 ) * _チップの最終調整倍率; Y倍率 *= ( 1f - 消滅割合 ) * _チップの最終調整倍率; const float チップ1枚の高さ = 18f; 転送元矩形.Offset( 0f, this._ドラムチップアニメ.現在値 * 15f ); // 下端3pxは下のチップと共有する前提のデザインなので、18f-3f = 15f。 転送元矩形.Height = チップ1枚の高さ; this._ドラムチップ画像.描画する( d2ddc, 左位置: レーンフレーム.レーン中央位置X[ lane ] - ( 転送元矩形.Width * X倍率 / 2f ), 上位置: Y - ( チップ1枚の高さ * Y倍率 / 2f ), 転送元矩形: 転送元矩形, X方向拡大率: X倍率, Y方向拡大率: Y倍率 ); } } } <|start_filename|>SSTFormat/old/v002/チップ.cs<|end_filename|> using System; using System.Collections.Generic; namespace SSTFormat.v002 { public class チップ : IComparable { public const int 最大音量 = 8; #region " プロパティ(1)(増減したら CopyFrom() を修正のこと)" //---------------- public チップ種別 チップ種別 { get; set; } = チップ種別.Unknown; public int 小節番号 { get; set; } = -1; public int 小節内位置 { get; set; } = 0; public int 小節解像度 { get; set; } = 1; /// <summary> /// チップの描画時刻[ms]。 /// 譜面の先頭(小節番号 -1 の小節の先頭)からの時刻をミリ秒単位で表す。 /// 未使用なら -1 。 /// </summary> public long 描画時刻ms { get; set; } = -1; /// <summary> /// チップの描画時刻[sec]。 /// 譜面の先頭(小節番号 -1 の小節の先頭)からの時刻を秒単位で表す。 /// </summary> public double 描画時刻sec => this.描画時刻ms / 1000.0; /// <summary> /// チップの発声時刻[ms]。 /// 譜面の先頭(小節番号 -1 の小節の先頭)からの時刻をミリ秒単位で表す。 /// 未使用なら -1 。 /// </summary> /// <remarks> /// サウンドの発声遅延を考慮して、描画時刻よりも遅く設定すること。 /// </remarks> public long 発声時刻ms { get; set; } = -1; /// <summary> /// チップの発声時刻[sec]。 /// 譜面の先頭(小節番号 -1 の小節の先頭)からの時刻を秒単位で表す。 /// </summary> /// <remarks> /// サウンドの発声遅延を考慮して、描画時刻よりも遅く設定すること。 /// </remarks> public double 発声時刻sec => this.発声時刻ms / 1000.0; /// <summary> /// チップの音量(小:1~8:大)。 /// </summary> public int 音量 { get => this._音量; set => this._音量 = ( ( 1 > value ) || ( チップ.最大音量 < value ) ) ? throw new ArgumentException( $"音量の値域(1~{チップ.最大音量})を超える値 '{value}' が指定されました。" ) : value; } /// <summary> /// チップが BPM チップである場合は、その BPM 値。 /// それ以外の場合は無効。 /// </summary> public double BPM { get; set; } = 120.0; //---------------- #endregion #region " プロパティ(2) 演奏用(増減したら CopyFrom() を修正のこと)" //---------------- public bool 可視 { get; set; } = true; public bool 不可視 { get => !this.可視; set => this.可視 = !value; } public bool 可視の初期値 { get { return ( // ↓これらは不可視。 ( this.チップ種別 == チップ種別.BPM ) || ( this.チップ種別 == チップ種別.背景動画 ) || ( this.チップ種別 == チップ種別.小節メモ ) || ( this.チップ種別 == チップ種別.小節の先頭 ) || ( this.チップ種別 == チップ種別.Unknown ) ) ? false : true; } } public bool ヒット済みである { get; set; } = false; public bool ヒットされていない { get => !this.ヒット済みである; set => this.ヒット済みである = !value; } public bool 発声済みである { get; set; } = false; public bool 発声されていない { get => !this.発声済みである; set => this.発声済みである = !value; } //---------------- #endregion #region " プロパティ(3) SSTFEditor用(増減したら CopyFrom() を修正のこと)" //---------------- public int 譜面内絶対位置grid { get; set; } = 0; public bool ドラッグ操作により選択中である { get; set; } = false; public bool 選択が確定している { get; set; } = false; public bool 選択が確定していない { get => !this.選択が確定している; set => this.選択が確定している = !value; } public bool 移動済みである { get; set; } = true; public bool 移動されていない { get => !this.移動済みである; set => this.移動済みである = !value; } public string チップ内文字列 { get; set; } = null; public int 枠外レーン数 { get; set; } = 0; //---------------- #endregion public チップ() { } public チップ( チップ コピー元チップ ) { this.CopyFrom( コピー元チップ ); } public チップ( v001_2.チップ v1_2hip ) { // プロパティ(1) this.チップ種別 = (チップ種別) v1_2hip.チップ種別; this.小節番号 = v1_2hip.小節番号; this.小節内位置 = v1_2hip.小節内位置; this.小節解像度 = v1_2hip.小節解像度; this.描画時刻ms = v1_2hip.描画時刻ms; this.発声時刻ms = v1_2hip.発声時刻ms; this.音量 = v1_2hip.音量 * 2; // 1~4 → 1~8 this.BPM = v1_2hip.BPM; // プロパティ(2) this.可視 = v1_2hip.可視; this.ヒット済みである = v1_2hip.ヒット済みである; this.発声済みである = v1_2hip.発声済みである; // プロパティ(3) this.譜面内絶対位置grid = v1_2hip.譜面内絶対位置grid; this.ドラッグ操作により選択中である = v1_2hip.ドラッグ操作により選択中である; this.選択が確定している = v1_2hip.選択が確定している; this.移動済みである = v1_2hip.移動済みである; this.チップ内文字列 = v1_2hip.チップ内文字列; this.枠外レーン数 = v1_2hip.枠外レーン数; } public void CopyFrom( チップ srcChip ) { // プロパティ(1) this.チップ種別 = srcChip.チップ種別; this.小節番号 = srcChip.小節番号; this.小節内位置 = srcChip.小節内位置; this.小節解像度 = srcChip.小節解像度; this.描画時刻ms = srcChip.描画時刻ms; this.発声時刻ms = srcChip.発声時刻ms; this.音量 = srcChip.音量; this.BPM = srcChip.BPM; // プロパティ(2) this.可視 = srcChip.可視; this.ヒット済みである = srcChip.ヒット済みである; this.発声済みである = srcChip.発声済みである; // プロパティ(3) this.譜面内絶対位置grid = srcChip.譜面内絶対位置grid; this.ドラッグ操作により選択中である = srcChip.ドラッグ操作により選択中である; this.選択が確定している = srcChip.選択が確定している; this.移動済みである = srcChip.移動済みである; this.チップ内文字列 = srcChip.チップ内文字列; this.枠外レーン数 = srcChip.枠外レーン数; } public void ヒット前の状態にする() { // 演奏用プロパティについて設定する。 this.可視 = this.可視の初期値; this.ヒット済みである = false; this.発声済みである = false; } public void ヒット済みの状態にする() { // 演奏用プロパティについて設定する。 this.可視 = false; this.ヒット済みである = true; this.発声済みである = true; } #region " IComparable 実装 " //----------------- // 概要: // 現在のインスタンスを同じ型の別のオブジェクトと比較して、並べ替え順序において、現在のインスタンスの位置が同じ型の別のオブジェクトの前、後ろ、または同じのいずれであるかを示す整数を返します。 // // パラメータ: // obj: // このインスタンスと比較するオブジェクト。 // // 戻り値: // 比較対象オブジェクトの相対順序を示す 32 ビット符号付き整数。戻り値の意味は次のとおりです。 // // 値 説明 // -------------------- // 負数 this < obj // 0 this = obj // 正数 this > obj // // 例外: // System.ArgumentException: // obj の型がこのインスタンスの型と異なります。 // public int CompareTo( object obj ) { var other = obj as チップ; if( this.小節番号 < other.小節番号 ) { return -1; } if( this.小節番号 > other.小節番号 ) { return +1; } double dbThis = (double) this.小節内位置 / (double) this.小節解像度; double dbOther = (double) other.小節内位置 / (double) other.小節解像度; if( dbThis < dbOther ) { return -1; } if( dbThis > dbOther ) { return +1; } // グリッドが完全に等しいなら、チップの種類ごとに定義された深度で順序を決める。 if( チップ.チップの深さ[ this.チップ種別 ] > チップ.チップの深さ[ other.チップ種別 ] ) { return -1; } if( チップ.チップの深さ[ this.チップ種別 ] < チップ.チップの深さ[ other.チップ種別 ] ) { return +1; } return 0; } //----------------- #endregion protected readonly static Dictionary<チップ種別, int> チップの深さ #region " *** " //----------------- = new Dictionary<チップ種別, int>() { { チップ種別.Ride_Cup, 50 }, { チップ種別.HiHat_Open, 50 }, { チップ種別.HiHat_HalfOpen, 50 }, { チップ種別.HiHat_Close, 50 }, { チップ種別.HiHat_Foot, 50 }, { チップ種別.Snare, 50 }, { チップ種別.Snare_OpenRim, 50 }, { チップ種別.Snare_ClosedRim, 50 }, { チップ種別.Snare_Ghost, 50 }, { チップ種別.Tom1, 50 }, { チップ種別.Tom1_Rim, 50 }, { チップ種別.BPM, 50 }, { チップ種別.Ride, 60 }, { チップ種別.Splash, 60 }, { チップ種別.Tom2, 60 }, { チップ種別.Tom2_Rim, 60 }, { チップ種別.LeftCrash, 70 }, { チップ種別.China, 70 }, { チップ種別.Tom3, 70 }, { チップ種別.Tom3_Rim, 70 }, { チップ種別.RightCrash, 70 }, { チップ種別.Bass, 75 }, { チップ種別.LeftCymbal_Mute, 76 }, { チップ種別.RightCymbal_Mute, 76 }, { チップ種別.小節線, 80 }, { チップ種別.拍線, 85 }, { チップ種別.背景動画, 90 }, { チップ種別.小節メモ, 99 }, { チップ種別.小節の先頭, 99 }, { チップ種別.Unknown, 99 }, }; //----------------- #endregion private int _音量 = チップ.最大音量; } } <|start_filename|>DTXMania2/ステージ/04選曲/QuickConfig/リスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; namespace DTXMania2.選曲.QuickConfig { class リスト : ラベル, IDisposable { // プロパティ public int 現在の選択肢番号 { get; set; } = 0; public List<string> 選択肢リスト { get; protected set; } = new List<string>(); // 生成と終了 public リスト( string 名前, IEnumerable<string> 選択肢初期値リスト, int 初期選択肢番号 = 0, Action<リスト>? 値が変更された = null ) : base( 名前 ) { this.現在の選択肢番号 = 初期選択肢番号; if( null != 選択肢初期値リスト ) this.選択肢リスト.AddRange( 選択肢初期値リスト ); this._値が変更された = 値が変更された; this._選択肢文字列画像リスト = new Dictionary<string, 文字列画像D2D>(); for( int i = 0; i < this.選択肢リスト.Count; i++ ) { var image = new 文字列画像D2D() { 表示文字列 = this.選択肢リスト[ i ], フォント名 = Properties.Resources.TXT_評価記号用フォント, フォントサイズpt = 34f, 前景色 = Color.White, }; this._選択肢文字列画像リスト.Add( this.選択肢リスト[ i ], image ); } } public override void Dispose() { foreach( var kvp in this._選択肢文字列画像リスト ) kvp.Value.Dispose(); base.Dispose(); } // 進行と描画 public virtual void 前を選択する( bool Loop = true ) { if( Loop ) { // 前がなければ末尾に戻る。 this.現在の選択肢番号 = ( this.現在の選択肢番号 - 1 + this.選択肢リスト.Count ) % this.選択肢リスト.Count; this._値が変更された?.Invoke( this ); } else { if( this.現在の選択肢番号 > 0 ) { this.現在の選択肢番号--; this._値が変更された?.Invoke( this ); } } } public virtual void 次を選択する( bool Loop = true ) { if( Loop ) { // 次がなければ先頭に戻る。 this.現在の選択肢番号 = ( this.現在の選択肢番号 + 1 ) % this.選択肢リスト.Count; this._値が変更された?.Invoke( this ); } else { if( this.現在の選択肢番号 < this.選択肢リスト.Count - 1 ) { this.現在の選択肢番号++; this._値が変更された?.Invoke( this ); } } } public override void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置 ) { // ラベル base.進行描画する( d2ddc, 左位置, 上位置 ); // 項目 int 項目番号 = this.現在の選択肢番号; var 項目名 = this.選択肢リスト[ 項目番号 ]; var 項目画像 = this._選択肢文字列画像リスト[ 項目名 ]; 項目画像.描画する( d2ddc, 左位置 + 400f, 上位置 ); } // ローカル private readonly Dictionary<string, 文字列画像D2D> _選択肢文字列画像リスト; private Action<リスト>? _値が変更された; } } <|start_filename|>DTXMania2/曲/Tree/Node/Node.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using FDK; namespace DTXMania2.曲 { class Node : IDisposable { // ツリーノードプロパティ public virtual string タイトル { get; set; } = "(no title)"; public virtual string? サブタイトル { get; set; } = null; public virtual VariablePath? ノード画像ファイルの絶対パス { get; set; } = null; // 画像プロパティ public virtual 画像D2D? ノード画像 { get { lock( this._排他 ) return this._ノード画像; } set { lock( this._排他 ) this._ノード画像 = value; } } public virtual 文字列画像D2D? タイトル文字列画像 { get { lock( this._排他 ) return this._タイトル文字列画像; } set { lock( this._排他 ) this._タイトル文字列画像 = value; } } public virtual 文字列画像D2D? サブタイトル文字列画像 { get { lock( this._排他 ) return this._サブタイトル文字列画像; } set { lock( this._排他 ) this._サブタイトル文字列画像 = value; } } /// <summary> /// このノードの現行化が終了していれば true。 /// </summary> /// <remarks> /// 画像プロパティは、このフラグが true のときのみ有効。 /// <see cref="SongNode"/> については、このフラグが true であれば、 /// 対応する <see cref="Node"/> の現行化も完了している。 /// </remarks> public virtual bool 現行化済み { get { lock( this._排他 ) return this._現行化済み; } set { lock( this._排他 ) this._現行化済み = value; } } // ツリー構造プロパティ /// <summary> /// このノードの親ノード。 /// </summary> /// <remarks> /// null なら親ノードはルートノードである。 /// </remarks> public virtual BoxNode? 親ノード { get; set; } = null; /// <summary> /// このノードの1つ前に位置する兄弟ノードを示す。 /// </summary> /// <remarks> /// このノードが先頭である(このノードの親ノードの子ノードリストの先頭である)場合は、末尾に位置する兄弟ノードを示す。 /// </remarks> public virtual Node 前のノード { get { if( this.親ノード is null ) throw new Exception( "親ノードが登録されていません。" ); int index = this.親ノード.子ノードリスト.IndexOf( this ); if( 0 > index ) throw new Exception( "自身が親ノードの子として登録されていません。" ); index--; if( 0 > index ) index = this.親ノード.子ノードリスト.Count - 1; // 先頭だったなら、末尾へ。 return this.親ノード.子ノードリスト[ index ]; } } /// <summary> /// このノードの1つ後に位置する兄弟ノードを示す。 /// </summary> /// <remarks> /// このノードが末尾である(このノードの親ノードの子ノードリストの末尾である)場合は、先頭に位置する兄弟ノードを示す。 /// </remarks> public virtual Node 次のノード { get { if( this.親ノード is null ) throw new Exception( "親ノードが登録されていません。" ); int index = this.親ノード.子ノードリスト.IndexOf( this ); if( 0 > index ) throw new Exception( "自身が親ノードの子として登録されていません。" ); index++; if( this.親ノード.子ノードリスト.Count <= index ) index = 0; // 末尾だったなら、先頭へ。 return this.親ノード.子ノードリスト[ index ]; } } // 生成と終了 public Node() { } public virtual void Dispose() { this._サブタイトル文字列画像?.Dispose(); this._タイトル文字列画像?.Dispose(); this._ノード画像?.Dispose(); } // ローカル protected 画像D2D? _ノード画像 = null; protected 文字列画像D2D? _タイトル文字列画像 = null; protected 文字列画像D2D? _サブタイトル文字列画像 = null; protected bool _現行化済み = false; /// <summary> /// 現行化処理との排他用。 /// </summary> protected readonly object _排他 = new object(); } } <|start_filename|>DTXMania2/ステージ/04選曲/曲別スキルと達成率.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; using DTXMania2.曲; namespace DTXMania2.選曲 { class 曲別スキルと達成率 : IDisposable { // 生成と終了 public 曲別スキルと達成率() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数字画像 = new フォント画像D2D( @"$(Images)\ParameterFont_LargeBoldItalic.png", @"$(Images)\ParameterFont_LargeBoldItalic.yaml", 文字幅補正dpx: 0f ); this._スキルアイコン = new 画像D2D( @"$(Images)\SkillIcon.png" ); this._達成率アイコン = new 画像D2D( @"$(Images)\CompletionRateIcon.png" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._達成率アイコン.Dispose(); this._スキルアイコン.Dispose(); this._数字画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, Node フォーカスノード ) { if( !( フォーカスノード is SongNode snode ) || snode.曲.フォーカス譜面 is null ) return; // 現状、表示できるノードは SongNode のみ。 #region " フォーカスノードが変更されていれば情報を更新する。" //---------------- if( フォーカスノード != this._現在表示しているノード ) { this._現在表示しているノード = フォーカスノード; this._スキル値文字列 = null; this._達成率文字列 = null; if( snode.曲.フォーカス譜面.最高記録を現行化済み ) { var 最高記録 = snode.曲.フォーカス譜面.最高記録; if( null != 最高記録 ) { // 達成率。右詰め、余白は' '。 this._達成率文字列 = 最高記録.Achievement.ToString( "0.00" ).PadLeft( 6 ) + '%'; // スキル値。右詰め、余白は' '。 double skill = 成績.スキルを算出する( snode.曲.フォーカス譜面.譜面.Level, 最高記録.Achievement ); this._スキル値文字列 = skill.ToString( "0.00" ).PadLeft( 6 ); } } } //---------------- #endregion var スキル描画領域 = new RectangleF( 10f, 340f, 275f, 98f ); var 達成率描画領域 = new RectangleF( 10f, 240f, 275f, 98f ); #region " 達成率を描画する。" //---------------- if( null != this._達成率文字列 ) { // 達成率アイコンを描画する。 this._達成率アイコン.描画する( d2ddc, 達成率描画領域.X + 30f, 達成率描画領域.Y - 40f, X方向拡大率: 0.6f, Y方向拡大率: 0.6f ); // 小数部と '%' を描画する。 var 拡大率 = new Size2F( 0.8f, 0.8f ); this._数字画像.描画する( d2ddc, 達成率描画領域.X + 130f + 175f, 達成率描画領域.Y + ( 達成率描画領域.Height * ( 1.0f - 拡大率.Height ) ), this._達成率文字列[ 4.. ], 拡大率 ); // 整数部と '.' を描画する。 拡大率 = new Size2F( 1.0f, 1.0f ); this._数字画像.描画する( d2ddc, 達成率描画領域.X + 130f, 達成率描画領域.Y, this._達成率文字列[ 0..4 ], 拡大率 ); } //---------------- #endregion #region " スキル値を描画する。" //---------------- if( null != this._スキル値文字列 ) { // スキルアイコンを描画する。 this._スキルアイコン.描画する( d2ddc, スキル描画領域.X + 20f, スキル描画領域.Y + 10f, X方向拡大率: 0.5f, Y方向拡大率: 0.4f ); var 小数部 = this._スキル値文字列[ 4.. ]; var 整数部 = this._スキル値文字列[ ..4 ]; // 小数部を描画する。 var 拡大率 = new Size2F( 0.8f, 0.8f ); this._数字画像.描画する( d2ddc, スキル描画領域.X + 130f + 175f, スキル描画領域.Y + ( スキル描画領域.Height * ( 1.0f - 拡大率.Height ) ), 小数部, 拡大率 ); // 整数部を描画する('.'含む)。 拡大率 = new Size2F( 1.0f, 1.0f ); this._数字画像.描画する( d2ddc, スキル描画領域.X + 130f, スキル描画領域.Y, 整数部, 拡大率 ); } //---------------- #endregion } // ローカル private readonly フォント画像D2D _数字画像; private readonly 画像D2D _スキルアイコン; private readonly 画像D2D _達成率アイコン; private Node? _現在表示しているノード = null; private string? _スキル値文字列 = null; private string? _達成率文字列 = null; } } <|start_filename|>DTXMania2/ステージ/08結果/達成率Base.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; namespace DTXMania2.結果 { /// <summary> /// <see cref="達成率"/> と <see cref="達成率更新"/> の共通インターフェース。 /// </summary> abstract class 達成率Base : IDisposable { // プロパティ public virtual bool アニメ完了 { get; } // 生成と終了 public 達成率Base() { } public abstract void Dispose(); // 進行と描画 public abstract void 進行描画する( DeviceContext d2ddc, float x, float y, double 達成率0to100 ); public abstract void アニメを完了する(); } } <|start_filename|>SSTFEditor/検索条件入力ダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Forms; using FDK; using SSTF=SSTFormat.v004; namespace SSTFEditor { partial class 検索条件入力ダイアログ : Form { public bool 小節範囲指定CheckBoxがチェックされている => this.checkBox小節範囲指定.Checked; public int 小節範囲開始番号 { get { int 開始番号 = -1; if( this.textBox小節範囲開始.Text.Nullでも空でもない() ) { // (A) 開始番号に文字がある。 try { 開始番号 = int.Parse( this.textBox小節範囲開始.Text ); } catch { 開始番号 = -1; } } else if( this.textBox小節範囲終了.Text.Nullまたは空である() ) { // (B) 開始番号も終了番号も、空欄である。 開始番号 = -1; } else { // (C) 終了番号にだけ文字がある。 try { 開始番号 = int.Parse( this.textBox小節範囲終了.Text ); } catch { 開始番号 = -1; } } return 開始番号; } } public int 小節範囲終了番号 { get { int 終了番号 = -1; // (A) 終了番号に文字がある。 if( this.textBox小節範囲終了.Text.Nullでも空でもない() ) { try { 終了番号 = int.Parse( this.textBox小節範囲終了.Text ); } catch { 終了番号 = -1; } } else if( this.textBox小節範囲開始.Text.Nullまたは空である() ) { // (B) 開始番号も終了番号も、空欄である。 終了番号 = -1; } else { // (C) 開始場号にだけ文字がある。 try { 終了番号 = int.Parse( this.textBox小節範囲開始.Text ); } catch { 終了番号 = -1; } } return 終了番号; } } public 検索条件入力ダイアログ() { InitializeComponent(); #region " レーンリスト(チェックリストボックス)とそのチェックボックスに、前回の検索条件値を反映する。" //---------------- // 未初期化なら先に初期化する。 if( null == 前回の設定値.レーンを検索対象にする ) { 前回の設定値.レーンを検索対象にする = new bool[ this.dic行と編集レーン対応表.Count ]; for( int i = 0; i < 前回の設定値.レーンを検索対象にする.Length; i++ ) 前回の設定値.レーンを検索対象にする[ i ] = false; // 前回値をすべて false にする。 } // 前回の検索条件値を反映する。 foreach( var kvp in this.dic行と編集レーン対応表 ) this.checkedListBoxレーン選択リスト.Items.Add( this.編集レーン名[ kvp.Key ], 前回の設定値.レーンを検索対象にする[ kvp.Key ] ); //---------------- #endregion #region " チップリストとチップリストチェックに前回値を指定する。未初期化なら初期化する。" //---------------- // 未初期化なら先に初期化する。 if( null == 前回の設定値.チップを検索対象にする ) { 前回の設定値.チップを検索対象にする = new bool[ this.dic行とチップ種別対応表.Count ]; for( int i = 0; i < 前回の設定値.チップを検索対象にする.Length; i++ ) 前回の設定値.チップを検索対象にする[ i ] = false; // 前回値をすべて false にする。 } // 前回の検索条件値を反映する。 foreach( var kvp in this.dic行とチップ種別対応表 ) this.checkedListBoxチップ選択リスト.Items.Add( this.チップ種別名[ kvp.Key ], 前回の設定値.チップを検索対象にする[ kvp.Key ] ); //---------------- #endregion this.checkBox小節範囲指定.CheckState = 前回の設定値.検索する小節範囲を指定する; this.チェックに連動して有効無効が決まるパーツについてEnabledを設定する(); } public bool 選択されている( 編集レーン種別 laneType ) { // First() で要素が見つからなかったらバグなので、そのまま System.InvalidOperationException を放出させる。 var key = this.dic行と編集レーン対応表.First( ( kvp ) => ( kvp.Value == laneType ) ).Key; return ( this.checkedListBoxレーン選択リスト.GetItemCheckState( key ) == CheckState.Checked ); } public bool 選択されている( SSTF.チップ種別 chipType ) { // First() で要素が見つからなかったらバグなので、そのまま System.InvalidOperationException を放出させる。 var key = this.dic行とチップ種別対応表.First( ( kvp ) => ( kvp.Value == chipType ) ).Key; return ( this.checkedListBoxチップ選択リスト.GetItemCheckState( key ) == CheckState.Checked ); } protected static class 前回の設定値 { public static CheckState 検索する小節範囲を指定する = CheckState.Unchecked; public static bool[] レーンを検索対象にする = null; public static bool[] チップを検索対象にする = null; }; protected readonly Dictionary<int, 編集レーン種別> dic行と編集レーン対応表 = new Dictionary<int, 編集レーン種別>() { #region " *** " //----------------- { 0, 編集レーン種別.BPM }, { 1, 編集レーン種別.左シンバル }, { 2, 編集レーン種別.ハイハット }, { 3, 編集レーン種別.スネア }, { 4, 編集レーン種別.ハイタム }, { 5, 編集レーン種別.バス }, { 6, 編集レーン種別.ロータム }, { 7, 編集レーン種別.フロアタム }, { 8, 編集レーン種別.右シンバル }, { 9, 編集レーン種別.BGV }, { 10, 編集レーン種別.BGM }, //----------------- #endregion }; protected readonly string[] 編集レーン名 = new string[] { #region " *** " //----------------- "BPM", "Left Cymbal", "HiHat", "Snare", "High Tom", "Bass Drum", "Low Tom", "Floor Tom", "Right Cymbal", "BGV", "BGM", //----------------- #endregion }; protected readonly Dictionary<int, SSTF.チップ種別> dic行とチップ種別対応表 = new Dictionary<int, SSTF.チップ種別>() { #region " *** " //---------------- { 0, SSTF.チップ種別.BPM }, { 1, SSTF.チップ種別.LeftCrash }, { 2, SSTF.チップ種別.HiHat_Close }, { 3, SSTF.チップ種別.HiHat_HalfOpen }, { 4, SSTF.チップ種別.HiHat_Open }, { 5, SSTF.チップ種別.HiHat_Foot }, { 6, SSTF.チップ種別.Snare }, { 7, SSTF.チップ種別.Snare_Ghost }, { 8, SSTF.チップ種別.Snare_ClosedRim }, { 9, SSTF.チップ種別.Snare_OpenRim }, { 10, SSTF.チップ種別.Tom1 }, { 11, SSTF.チップ種別.Tom1_Rim }, { 12, SSTF.チップ種別.Bass }, { 13, SSTF.チップ種別.Tom2 }, { 14, SSTF.チップ種別.Tom2_Rim }, { 15, SSTF.チップ種別.Tom3 }, { 16, SSTF.チップ種別.Tom3_Rim }, { 17, SSTF.チップ種別.RightCrash }, { 18, SSTF.チップ種別.Ride }, { 19, SSTF.チップ種別.Ride_Cup }, { 20, SSTF.チップ種別.China }, { 21, SSTF.チップ種別.Splash }, { 22, SSTF.チップ種別.背景動画 }, { 23, SSTF.チップ種別.BGM }, //---------------- #endregion }; protected readonly string[] チップ種別名 = new string[] { #region " *** " //----------------- "BPM", "Left Crash", "HiHat Close", "HiHat HalfOpen", "HiHat Open", "Foot Pedal", "Snare", "Snare Ghost", "Snare Closed RimShot", "Snare Open RimShot", "High Tom", "High Tom RimShoft", "Bass Drum", "Low Tom", "Low Tom RimShot", "Floor Tom", "Floor Tom RimShoft", "Right Crash", "Ride", "Cup", "China Cymbal", "Splash Cymbal", "BGV", "BGM", //----------------- #endregion }; protected void チェックに連動して有効無効が決まるパーツについてEnabledを設定する() { bool flag = this.checkBox小節範囲指定.Checked; this.textBox小節範囲開始.Enabled = flag; this.textBox小節範囲終了.Enabled = flag; } // イベント protected void OnFormClosing( object sender, FormClosingEventArgs e ) { if( this.DialogResult == DialogResult.OK ) { // 入力値の妥当性を確認する。 #region " 小節範囲開始 " //---------------- { var text = this.textBox小節範囲開始.Text; if( text.Nullでも空でもない() && ( false == int.TryParse( text, out int num ) || ( 0 > num ) ) ) { MessageBox.Show( $"{Properties.Resources.MSG_小節番号に誤りがあります}{Environment.NewLine}'{text}'", Properties.Resources.MSG_エラーダイアログのタイトル, MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1 ); this.textBox小節範囲開始.Focus(); this.textBox小節範囲開始.SelectAll(); e.Cancel = true; return; } } //---------------- #endregion #region " 小節範囲終了 " //---------------- { var text = this.textBox小節範囲終了.Text; if( text.Nullでも空でもない() && ( false == int.TryParse( text, out int num ) || ( 0 > num ) ) ) { MessageBox.Show( $"{Properties.Resources.MSG_小節番号に誤りがあります}{Environment.NewLine}'{text}'", Properties.Resources.MSG_エラーダイアログのタイトル, MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1 ); this.textBox小節範囲終了.Focus(); this.textBox小節範囲終了.SelectAll(); e.Cancel = true; return; } } //---------------- #endregion // 入力値を前回値として保存する。 #region " 小節範囲指定 " //---------------- 前回の設定値.検索する小節範囲を指定する = this.checkBox小節範囲指定.CheckState; //---------------- #endregion #region " レーンを検索対象にする[] " //---------------- for( int i = 0; i < this.checkedListBoxレーン選択リスト.Items.Count; i++ ) 前回の設定値.レーンを検索対象にする[ i ] = ( this.checkedListBoxレーン選択リスト.GetItemCheckState( i ) == CheckState.Checked ); //---------------- #endregion #region " チップを選択対象にする[] " //---------------- for( int i = 0; i < this.checkedListBoxチップ選択リスト.Items.Count; i++ ) 前回の設定値.チップを検索対象にする[ i ] = this.checkedListBoxチップ選択リスト.GetItemCheckState( i ) == CheckState.Checked; //---------------- #endregion } } protected void OnKeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → キャンセル else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void textBox小節範囲開始_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → キャンセル else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void textBox小節範囲終了_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → キャンセル else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void checkBox小節範囲指定_CheckStateChanged( object sender, EventArgs e ) { this.チェックに連動して有効無効が決まるパーツについてEnabledを設定する(); } protected void checkBox小節範囲指定_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → キャンセル else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void checkedListBoxレーン選択リスト_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → キャンセル else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void buttonAllレーン_Click( object sender, EventArgs e ) { for( int i = 0; i < this.checkedListBoxレーン選択リスト.Items.Count; i++ ) this.checkedListBoxレーン選択リスト.SetItemChecked( i, true ); } protected void buttonAllレーン_KeyDown( object sender, KeyEventArgs e ) { // ESC → キャンセル if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void buttonClearレーン_Click( object sender, EventArgs e ) { for( int i = 0; i < this.checkedListBoxレーン選択リスト.Items.Count; i++ ) this.checkedListBoxレーン選択リスト.SetItemCheckState( i, CheckState.Unchecked ); } protected void buttonClearレーン_KeyDown( object sender, KeyEventArgs e ) { // ESC → キャンセル if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void buttonAllチップ_Click( object sender, EventArgs e ) { for( int i = 0; i < this.checkedListBoxチップ選択リスト.Items.Count; i++ ) this.checkedListBoxチップ選択リスト.SetItemChecked( i, true ); } protected void buttonAllチップ_KeyDown( object sender, KeyEventArgs e ) { // ESC → キャンセル if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void buttonClearチップ_Click( object sender, EventArgs e ) { for( int i = 0; i < this.checkedListBoxチップ選択リスト.Items.Count; i++ ) this.checkedListBoxチップ選択リスト.SetItemCheckState( i, CheckState.Unchecked ); } protected void buttonClearチップ_KeyDown( object sender, KeyEventArgs e ) { // ESC → キャンセル if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } } } <|start_filename|>FDK/サウンド/Sources/NVorbisOnStreamingSampleSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using CSCore; using NVorbis; namespace FDK { /// <summary> /// 指定されたメディアファイル(動画, 音楽)を Vorbis としてデコードして、<see cref="CSCore.ISampleSource"/> オブジェクトを生成する。 /// リサンプラーなし版。 /// </summary> /// <seealso cref="https://github.com/filoe/cscore/blob/master/Samples/NVorbisIntegration/Program.cs"/> public class NVorbisOnStreamingSampleSource : ISampleSource { // プロパティ public bool CanSeek => this._stream.CanSeek; public WaveFormat WaveFormat { get; } public long Position { get => ( this.CanSeek ) ? this._vorbisReader.SamplePosition : 0; set => this._vorbisReader.SamplePosition = ( this.CanSeek ) ? value : throw new InvalidOperationException( "DecodedNVorbisSource is not seekable." ); } public long Length { get => ( this.CanSeek ) ? this._vorbisReader.TotalSamples * this.WaveFormat.Channels : 0; // TotalSamples はフレーム数を返す。 } // 生成と終了 public NVorbisOnStreamingSampleSource( Stream stream, WaveFormat deviceFormat ) { if( stream is null ) throw new ArgumentException( "stream" ); if( !stream.CanRead ) throw new ArgumentException( "Stream is not readable.", "stream" ); this._stream = stream; this._vorbisReader = new VorbisReader( stream, true ); this.WaveFormat = new WaveFormat( this._vorbisReader.SampleRate, 32, // 32bit 固定 this._vorbisReader.Channels, AudioEncoding.IeeeFloat ); // IeeeFloat 固定 } public virtual void Dispose() { this._vorbisReader.Dispose(); } // 出力 public int Read( float[] buffer, int offset, int count ) { return this._vorbisReader.ReadSamples( buffer, offset, count ); } // ローカル private Stream _stream; private VorbisReader _vorbisReader; } } <|start_filename|>SSTFEditor/オプションダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace SSTFEditor { public partial class オプションダイアログ : Form { public オプションダイアログ() { InitializeComponent(); } private void buttonViewerPath参照_Click( object sender, EventArgs e ) { #region " ファイルを開くダイアログでファイルを選択する。" //----------------- var dialog = new OpenFileDialog() { Title = Properties.Resources.MSG_ファイル選択ダイアログのタイトル, Filter = Properties.Resources.MSG_ビュアー選択ダイアログのフィルタ, FilterIndex = 1, //InitialDirectory = "", }; var result = dialog.ShowDialog( this ); // メインフォームを再描画してダイアログを完全に消す。 this.Refresh(); // OKじゃないならここで中断。 if( DialogResult.OK != result ) return; //----------------- #endregion this.textBoxViewerPath.Text = dialog.FileName; } } } <|start_filename|>DTXMania2/保存データ/RecordDB/old/v007_RecordDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.old.RecordDBRecord { class v007_RecordDBRecord { public const int VERSION = 7; /// <summary> /// ユーザを一意に識別するID。 /// </summary> public string UserId { get; set; } /// <summary> /// 曲譜面ファイルのハッシュ値。 /// </summary> public string SongHashId { get; set; } /// <summary> /// スコア。 /// </summary> public int Score { get; set; } /// <summary> /// カウントマップラインのデータ。 /// 1ブロックを1文字('0':0~'C':12)で表し、<see cref="DTXMania.ステージ.演奏.カウントマップライン.カウントマップの最大要素数"/> 個の文字が並ぶ。 /// もし不足分があれば、'0' とみなされる。 /// </summary> public string CountMap { get; set; } /// <summary> /// 達成率。 /// </summary> public double Achievement { get; set; } /// <summary> /// テーブルのカラム部分を列挙したSQL。 /// </summary> public static readonly string ColumnList = @"( UserId NVARCHAR NOT NULL" + @", SongHashId NVARCHAR NOT NULL" + @", Score INTEGER NOT NULL" + @", CountMap NVARCHAR NOT NULL" + @", Achievement NUMERIC NOT NULL" + @", PRIMARY KEY(`UserId`,`SongHashId`)" + @")"; // 生成と終了 public v007_RecordDBRecord() { this.UserId = "Anonymous"; this.SongHashId = ""; this.Score = 0; this.CountMap = ""; this.Achievement = 0.0; } public v007_RecordDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "UserId": this.UserId = record.GetString( i ); break; case "SongHashId": this.SongHashId = record.GetString( i ); break; case "Score": this.Score = record.GetInt32( i ); break; case "CountMap": this.CountMap = record.GetString( i ); break; case "Achievement": this.Achievement = record.GetDouble( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public void InsertTo( SQLiteDB db ) { using var cmd = new SqliteCommand( "REPLACE INTO Records VALUES(" + $"'{this.UserId}'," + $"'{this.SongHashId}'," + $"{this.Score}," + $"'{this.CountMap}'," + $"{this.Achievement}" + ")", db.Connection ); cmd.ExecuteNonQuery(); } } } <|start_filename|>FDK/サウンド/PolySound.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using CSCore; namespace FDK { /// <summary> /// 多重再生ができるSound。 /// </summary> public class PolySound : IDisposable { // プロパティ /// <summary> /// 音量。0.0(無音)~1.0(原音)~...上限なし /// </summary> /// <remarks> /// このクラスではなく、<see cref="Mixer"/>クラスから参照して使用する。 /// </remarks> public float Volume { get => this.サウンドリスト[ 0 ].Volume; // 代表 set { float vol = Math.Max( value, 0f ); foreach( var sound in this.サウンドリスト ) // 全部同じ音量に sound.Volume = vol; } } public bool いずれかが再生中である => this.サウンドリスト.Any( ( sound ) => sound.再生中である ); // 生成と終了 public PolySound( SoundDevice device, ISampleSource sampleSource, int 多重度 = 4 ) { this.多重度 = 多重度; this.サウンドリスト = new Sound[ 多重度 ]; // 多重度数だけ Sound を同じソースで生成。 for( int i = 0; i < 多重度; i++ ) this.サウンドリスト[ i ] = new Sound( device, sampleSource ); } public virtual void Dispose() { foreach( var sound in this.サウンドリスト ) sound.Dispose(); } // 再生制御 public void Play( long 再生開始位置frame = 0, bool ループ再生する = false ) { // サウンドを再生する。 this.サウンドリスト[ this._次に再生するサウンドのインデックス ].Play( 再生開始位置frame, ループ再生する ); // サウンドローテーション。 if( !ループ再生する ) // ループ再生時はローテーションしない。 this._次に再生するサウンドのインデックス = ( this._次に再生するサウンドのインデックス + 1 ) % this.多重度; } public void Play( double 再生開始位置sec, bool ループ再生する = false ) => this.Play( this._秒ToFrame( 再生開始位置sec ), ループ再生する ); public void Stop() { foreach( var sound in this.サウンドリスト ) sound.Stop(); } // ローカル protected int 多重度; protected Sound[] サウンドリスト; private int _次に再生するサウンドのインデックス = 0; private long _秒ToFrame( double 時間sec ) => this.サウンドリスト[ 0 ].秒ToFrame( 時間sec ); } } <|start_filename|>DTXMania2/保存データ/ScoreDB/ScoreDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Data.Sqlite; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2 { class ScoreDBRecord { // プロパティ public const int VERSION = 7; /// <summary> /// 曲譜面ファイルへの絶対パス。主キー。 /// </summary> public string ScorePath { get; set; } /// <summary> /// 曲のタイトル。 /// </summary> public string Title { get; set; } /// <summary> /// 曲譜面ファイルの最終更新時刻の文字列表記。 /// 文字列の書式は、System.DateTime.ToString("G") と同じ。(例: "08/17/2000 16:32:32") /// カルチャはシステム既定のものとする。 /// </summary> public string LastWriteTime { get; set; } /// <summary> /// 曲の難易度。0.00~9.99。 /// </summary> public double Level { get; set; } /// <summary> /// 最小BPM。null なら未取得。 /// </summary> public double? MinBPM { get; set; } /// <summary> /// 最大BPM。null なら未取得。 /// </summary> public double? MaxBPM { get; set; } /// <summary> /// 左シンバルの総ノーツ数。 /// </summary> public int TotalNotes_LeftCymbal { get; set; } /// <summary> /// ハイハットの総ノーツ数。 /// </summary> public int TotalNotes_HiHat { get; set; } /// <summary> /// 左ペダルまたは左バスの総ノーツ数。 /// </summary> public int TotalNotes_LeftPedal { get; set; } /// <summary> /// スネアの総ノーツ数。 /// </summary> public int TotalNotes_Snare { get; set; } /// <summary> /// バスの総ノーツ数。 /// </summary> public int TotalNotes_Bass { get; set; } /// <summary> /// ハイタムの総ノーツ数。 /// </summary> public int TotalNotes_HighTom { get; set; } /// <summary> /// ロータムの総ノーツ数。 /// </summary> public int TotalNotes_LowTom { get; set; } /// <summary> /// フロアタムの総ノーツ数。 /// </summary> public int TotalNotes_FloorTom { get; set; } /// <summary> /// 右シンバルの総ノーツ数。 /// </summary> public int TotalNotes_RightCymbal { get; set; } /// <summary> /// 曲のプレビュー画像。 /// 曲譜面ファイル(<see cref="ScorePath"/>)からの相対パス。 /// </summary> public string PreImage { get; set; } /// <summary> /// 曲のアーティスト名。 /// </summary> public string Artist { get; set; } /// <summary> /// 曲のプレビュー音声ファイルのパス。 /// 曲譜面ファイル(<see cref="ScorePath"/>)からの相対パス。 /// </summary> public string PreSound { get; set; } /// <summary> /// この曲のBGMの再生タイミングを、この時間[ms]分だけ前後にずらす。(負数で早める、正数で遅める) /// </summary> public int BGMAdjust { get; set; } // 生成と終了 public ScoreDBRecord() { this.ScorePath = ""; this.Title = "(no title)"; this.LastWriteTime = DateTime.Now.ToString( "G" ); this.Level = 5.00; this.MinBPM = null; this.MaxBPM = null; this.TotalNotes_LeftCymbal = 0; this.TotalNotes_HiHat = 0; this.TotalNotes_LeftPedal = 0; this.TotalNotes_Snare = 0; this.TotalNotes_Bass = 0; this.TotalNotes_HighTom = 0; this.TotalNotes_LowTom = 0; this.TotalNotes_FloorTom = 0; this.TotalNotes_RightCymbal = 0; this.PreImage = ""; this.Artist = ""; this.PreSound = ""; this.BGMAdjust = 0; } public ScoreDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } public ScoreDBRecord( VariablePath 譜面ファイルの絶対パス, ユーザ設定 userConfig ) { // 譜面を読み込む。(ノーツ数やBPMを算出するため、ヘッダだけじゃなくすべてを読み込む。) var 譜面 = SSTF.スコア.ファイルから生成する( 譜面ファイルの絶対パス.変数なしパス ); var ノーツ数マップ = _ノーツ数を算出して返す( 譜面, userConfig ); var (最小BPM, 最大BPM) = _最小最大BPMを調べて返す( 譜面 ); // 読み込んだ譜面から反映する。 this.ScorePath = 譜面ファイルの絶対パス.変数なしパス; this.Title = 譜面.曲名; this.LastWriteTime = File.GetLastWriteTime( this.ScorePath ).ToString( "G" ); this.Level = 譜面.難易度; this.MinBPM = 最小BPM; this.MaxBPM = 最大BPM; this.TotalNotes_LeftCymbal = ノーツ数マップ[ 演奏.表示レーン種別.LeftCymbal ]; this.TotalNotes_HiHat = ノーツ数マップ[ 演奏.表示レーン種別.HiHat ]; this.TotalNotes_LeftPedal = ノーツ数マップ[ 演奏.表示レーン種別.Foot ]; this.TotalNotes_Snare = ノーツ数マップ[ 演奏.表示レーン種別.Snare ]; this.TotalNotes_Bass = ノーツ数マップ[ 演奏.表示レーン種別.Bass ]; this.TotalNotes_HighTom = ノーツ数マップ[ 演奏.表示レーン種別.Tom1 ]; this.TotalNotes_LowTom = ノーツ数マップ[ 演奏.表示レーン種別.Tom2 ]; this.TotalNotes_FloorTom = ノーツ数マップ[ 演奏.表示レーン種別.Tom3 ]; this.TotalNotes_RightCymbal = ノーツ数マップ[ 演奏.表示レーン種別.RightCymbal ]; this.PreImage = string.IsNullOrEmpty( 譜面.プレビュー画像ファイル名 ) ? "" : 譜面.プレビュー画像ファイル名; this.Artist = 譜面.アーティスト名; this.PreSound = string.IsNullOrEmpty( 譜面.プレビュー音声ファイル名 ) ? "" : 譜面.プレビュー音声ファイル名; this.BGMAdjust = 0; } /// <summary> /// 指定したインスタンスの内容を自身にコピーする。 /// </summary> /// <param name="record">コピー元インスタンス。</param> public void UpdateFrom( ScoreDBRecord record ) { this.ScorePath = record.ScorePath; this.Title = record.Title; this.LastWriteTime = record.LastWriteTime; this.Level = record.Level; this.MinBPM = record.MinBPM; this.MaxBPM = record.MaxBPM; this.TotalNotes_LeftCymbal = record.TotalNotes_LeftCymbal; this.TotalNotes_HiHat = record.TotalNotes_HiHat; this.TotalNotes_LeftPedal = record.TotalNotes_LeftPedal; this.TotalNotes_Snare = record.TotalNotes_Snare; this.TotalNotes_Bass = record.TotalNotes_Bass; this.TotalNotes_HighTom = record.TotalNotes_HighTom; this.TotalNotes_LowTom = record.TotalNotes_LowTom; this.TotalNotes_FloorTom = record.TotalNotes_FloorTom; this.PreImage = record.PreImage; this.Artist = record.Artist; this.PreSound = record.PreSound; this.BGMAdjust = record.BGMAdjust; } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "ScorePath": this.ScorePath = record.GetString( i ); break; case "Title": this.Title = record.GetString( i ); break; case "LastWriteTime": this.LastWriteTime = record.GetString( i ); break; case "Level": this.Level = record.GetDouble( i ); break; case "MinBPM": this.MinBPM = record.GetDouble( i ); break; case "MaxBPM": this.MaxBPM = record.GetDouble( i ); break; case "TotalNotes_LeftCymbal": this.TotalNotes_LeftCymbal = record.GetInt32( i ); break; case "TotalNotes_HiHat": this.TotalNotes_HiHat = record.GetInt32( i ); break; case "TotalNotes_LeftPedal": this.TotalNotes_LeftPedal = record.GetInt32( i ); break; case "TotalNotes_Snare": this.TotalNotes_Snare = record.GetInt32( i ); break; case "TotalNotes_Bass": this.TotalNotes_Bass = record.GetInt32( i ); break; case "TotalNotes_HighTom": this.TotalNotes_HighTom = record.GetInt32( i ); break; case "TotalNotes_LowTom": this.TotalNotes_LowTom = record.GetInt32( i ); break; case "TotalNotes_FloorTom": this.TotalNotes_FloorTom = record.GetInt32( i ); break; case "TotalNotes_RightCymbal": this.TotalNotes_RightCymbal = record.GetInt32( i ); break; case "PreImage": this.PreImage = record.GetString( i ); break; case "Artist": this.Artist = record.GetString( i ); break; case "PreSound": this.PreSound = record.GetString( i ); break; case "BGMAdjust": this.BGMAdjust = record.GetInt32( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public void ReplaceTo( SQLiteDB scoredb, string table = "Scores" ) { using var cmd = new SqliteCommand( $"REPLACE INTO {table} VALUES" + "( @ScorePath" + ", @Title" + ", @LastWriteTime" + ", @Level" + ", @MinBPM" + ", @MaxBPM" + ", @TotalNotes_LeftCymbal" + ", @TotalNotes_HiHat" + ", @TotalNotes_LeftPedal" + ", @TotalNotes_Snare" + ", @TotalNotes_Bass" + ", @TotalNotes_HighTom" + ", @TotalNotes_LowTom" + ", @TotalNotes_FloorTom" + ", @TotalNotes_RightCymbal" + ", @PreImage" + ", @Artist" + ", @PreSound" + ", @BGMAdjust" + ")", scoredb.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@ScorePath", this.ScorePath ), new SqliteParameter( "@Title", this.Title ), new SqliteParameter( "@LastWriteTime", this.LastWriteTime ), new SqliteParameter( "@Level", this.Level ), new SqliteParameter( "@MinBPM", this.MinBPM ), new SqliteParameter( "@MaxBPM", this.MaxBPM ), new SqliteParameter( "@TotalNotes_LeftCymbal", this.TotalNotes_LeftCymbal ), new SqliteParameter( "@TotalNotes_HiHat", this.TotalNotes_HiHat ), new SqliteParameter( "@TotalNotes_LeftPedal", this.TotalNotes_LeftPedal ), new SqliteParameter( "@TotalNotes_Snare", this.TotalNotes_Snare ), new SqliteParameter( "@TotalNotes_Bass", this.TotalNotes_Bass ), new SqliteParameter( "@TotalNotes_HighTom", this.TotalNotes_HighTom ), new SqliteParameter( "@TotalNotes_LowTom", this.TotalNotes_LowTom ), new SqliteParameter( "@TotalNotes_FloorTom", this.TotalNotes_FloorTom ), new SqliteParameter( "@TotalNotes_RightCymbal", this.TotalNotes_RightCymbal ), new SqliteParameter( "@PreImage", this.PreImage ), new SqliteParameter( "@Artist", this.Artist ), new SqliteParameter( "@PreSound", this.PreSound ), new SqliteParameter( "@BGMAdjust", this.BGMAdjust ), } ); cmd.ExecuteNonQuery(); } /// <summary> /// テーブルがなければ作成するSQLを返す。 /// </summary> public static string GetCreateTableSQL( string table = "Scores" ) => $"CREATE TABLE IF NOT EXISTS {table}" + @"( ScorePath NVARCHAR NOT NULL PRIMARY KEY" + @", Title NVARCHAR NOT NULL" + @", LastWriteTime NVARCHAR NOT NULL" + @", Level NUMERIC NOT NULL" + @", MinBPM NUMERIC" + @", MaxBPM NUMERIC" + @", TotalNotes_LeftCymbal INTEGER NOT NULL" + @", TotalNotes_HiHat INTEGER NOT NULL" + @", TotalNotes_LeftPedal INTEGER NOT NULL" + @", TotalNotes_Snare INTEGER NOT NULL" + @", TotalNotes_Bass INTEGER NOT NULL" + @", TotalNotes_HighTom INTEGER NOT NULL" + @", TotalNotes_LowTom INTEGER NOT NULL" + @", TotalNotes_FloorTom INTEGER NOT NULL" + @", TotalNotes_RightCymbal INTEGER NOT NULL" + @", PreImage NVARCHAR" + @", Artist NVARCHAR" + @", PreSound NVARCHAR" + @", BGMAdjust INTEGER NOT NULL" + @")"; // ローカル private Dictionary<演奏.表示レーン種別, int> _ノーツ数を算出して返す( SSTF.スコア score, ユーザ設定 userConfig ) { // ノーツ数マップを初期化。 var ノーツ数マップ = new Dictionary<演奏.表示レーン種別, int>(); foreach( 演奏.表示レーン種別? lane in Enum.GetValues( typeof( 演奏.表示レーン種別 ) ) ) { if( lane.HasValue ) ノーツ数マップ.Add( lane.Value, 0 ); } // 譜面内のすべてのチップについて…… foreach( var chip in score.チップリスト ) { var prop = userConfig.ドラムチッププロパティリスト[ chip.チップ種別 ]; // 1. AutoPlay ON のチップは、すべてが ON である場合を除いて、カウントしない。 if( userConfig.AutoPlay[ prop.AutoPlay種別 ] ) { if( !( userConfig.AutoPlayがすべてONである ) ) continue; } // 2. AutoPlay OFF 時でも、ユーザヒットの対象にならないチップはカウントしない。 if( !( prop.AutoPlayOFF_ユーザヒット ) ) continue; // カウント。 ノーツ数マップ[ prop.表示レーン種別 ]++; } return ノーツ数マップ; } private static (double 最小BPM, double 最大BPM) _最小最大BPMを調べて返す( SSTF.スコア score ) { var result = (最小BPM: double.MaxValue, 最大BPM: double.MinValue); foreach( var chip in score.チップリスト.Where( ( c ) => ( c.チップ種別 == SSTF.チップ種別.BPM ) ) ) { result.最小BPM = Math.Min( result.最小BPM, chip.BPM ); result.最大BPM = Math.Max( result.最大BPM, chip.BPM ); } if( result.最小BPM == double.MaxValue || result.最大BPM == double.MinValue ) { // BPMチップがひとつもなかった double 初期BPM = SSTF.スコア.初期BPM; result = (初期BPM, 初期BPM); } return result; } } } <|start_filename|>DTXMania2/ステージ/04選曲/プレビュー音声.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using CSCore; using FDK; namespace DTXMania2.選曲 { /// <summary> /// プレビュー音声の再生とライフサイクル管理。 /// </summary> /// <remarks> /// 指定された音声ファイルを、一定時間(500ミリ秒)後に生成して再生する機能を提供する。 /// 生成された音声データは、一定数までキャッシングされる。 /// </remarks> class プレビュー音声 : IDisposable { // 生成と終了 public プレビュー音声() { using var _ = new LogBlock( Log.現在のメソッド名 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); } // 再生と停止 /// <summary> /// サウンドファイルの再生を予約する。 /// </summary> /// <remarks> /// 予約されたサウンドは、500ミリ秒後に生成され、再生される。 /// </remarks> public void 再生を予約する( VariablePath 音声ファイルの絶対パス ) { CancellationTokenSource cancelTokenSource; CancellationToken cancelToken; lock( this._CancelTokenSources排他 ) { // 既存のすべてのタスクをキャンセルする。 foreach( var source in this._CanscellationTokenSources ) source.Cancel(); // 新しいタスク用のキャンセルトークンソースを生成する。 cancelTokenSource = new CancellationTokenSource(); cancelToken = cancelTokenSource.Token; this._CanscellationTokenSources.Add( cancelTokenSource ); } // 新しいタスクを開始する。 Task.Run( () => { // 500ミリ秒待つ。 Thread.Sleep( 500 ); if( cancelToken.IsCancellationRequested ) return; // キャンセルされた // ファイルからサウンドを生成する。 var sound = this._サウンドを生成する( 音声ファイルの絶対パス ); if( sound is null ) { Log.ERROR( $"サウンドの生成に失敗しました。[{音声ファイルの絶対パス}]" ); return; // 失敗した } if( cancelToken.IsCancellationRequested ) { sound.Dispose(); return; // キャンセルされた } // サウンドを再生する。 sound.Play( 0, ループ再生する: true ); // キャンセルされるまでブロック。 cancelToken.WaitHandle.WaitOne(); // サウンドを解放する。 sound.Dispose(); }, cancelToken ).ContinueWith( ( t ) => { // タスクが終了したらトークンソースを解放。 lock( this._CancelTokenSources排他 ) { this._CanscellationTokenSources.Remove( cancelTokenSource ); cancelTokenSource.Dispose(); } } ); } /// <summary> /// 現在再生されているサウンドを停止し、既存の予約があればキャンセルする。 /// </summary> public void 停止する() { lock( this._CancelTokenSources排他 ) { // 既存のすべてのタスクをキャンセルする。 foreach( var source in this._CanscellationTokenSources ) source.Cancel(); } } // ローカル private List<CancellationTokenSource> _CanscellationTokenSources = new List<CancellationTokenSource>(); private readonly object _CancelTokenSources排他 = new object(); private Sound? _サウンドを生成する( VariablePath 音声ファイルの絶対パス ) { // ファイルから ISampleSource を取得する。 var sampleSource = this._SampleSourceを生成する( 音声ファイルの絶対パス ); if( sampleSource is null ) { Log.ERROR( $"ISampleSourceの生成に失敗しました。[{音声ファイルの絶対パス}]" ); return null; } // ISampleSource からサウンドを生成して返す。 return new Sound( Global.App.サウンドデバイス, sampleSource ); } private ISampleSource? _SampleSourceを生成する( VariablePath 音声ファイルの絶対パス ) { ISampleSource? sampleSource = null; // キャッシュにある? lock( this._キャッシュ用排他 ) { if( this._サンプルソースキャッシュ.ContainsKey( 音声ファイルの絶対パス.変数なしパス ) ) { // あるなら、対応する ISampleSource を取得。 sampleSource = this._サンプルソースキャッシュ[ 音声ファイルの絶対パス.変数なしパス ]; } } if( sampleSource is null ) { // ファイルから ISampleSource を生成する。 sampleSource = SampleSourceFactory.Create( Global.App.サウンドデバイス, 音声ファイルの絶対パス ); if( sampleSource is null ) return null; // 失敗した // ISampleSource をキャッシュに登録する。 lock( this._キャッシュ用排他 ) { this._サンプルソースキャッシュ.Add( 音声ファイルの絶対パス.変数なしパス, sampleSource ); this._キャッシュ世代リスト.Add( 音声ファイルの絶対パス.変数なしパス ); } // キャッシュが一定数を超えたら、一番古いものから削除する。 if( _キャッシュする個数 < this._キャッシュ世代リスト.Count ) { lock( this._キャッシュ用排他 ) { var path = this._キャッシュ世代リスト.Last(); // リストの末尾の最後の this._サンプルソースキャッシュ[ path ].Dispose(); // ISampleSource を解放して this._キャッシュ世代リスト.Remove( path ); // キャッシュからも this._サンプルソースキャッシュ.Remove( path ); // 削除。 } } } else { // キャッシュの世代リストで、今取得したソースが一番若くなるように操作する。 lock( this._キャッシュ用排他 ) { this._キャッシュ世代リスト.Remove( 音声ファイルの絶対パス.変数なしパス ); // 冤罪の位置から除去して this._キャッシュ世代リスト.Add( 音声ファイルの絶対パス.変数なしパス ); // 一番最新の位置へ。 } } // ISampleSource を返す。 return sampleSource; } // キャッシュ private const int _キャッシュする個数 = 20; private readonly object _キャッシュ用排他 = new object(); private readonly Dictionary<string, ISampleSource> _サンプルソースキャッシュ = new Dictionary<string, ISampleSource>(); private readonly List<string> _キャッシュ世代リスト = new List<string>(); } } <|start_filename|>DTXMania2/保存データ/SystemConfig/SystemConfig.IdKey.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using YamlDotNet.Core; using YamlDotNet.Serialization; using FDK; namespace DTXMania2 { partial class SystemConfig { /// <summary> /// 入力のマッピング(Dictionary)のキーとなる型。 /// </summary> /// <remarks> /// 入力は、デバイスID(入力デバイスの内部識別用ID; <see cref="FDK.InputEvent.DeviceID"/>と同じ)と、 /// キー(キーコード、ノート番号などデバイスから得られる入力値)の組で定義される。 /// </remarks> public struct IdKey : IYamlConvertible { public int deviceId { get; set; } public int key { get; set; } public IdKey( int deviceId, int key ) { this.deviceId = deviceId; this.key = key; } public IdKey( InputEvent ie ) { this.deviceId = ie.DeviceID; this.key = ie.Key; } public IdKey( string 文字列 ) { // 変なの食わせたらそのまま例外発出する。 string[] v = 文字列.Split( new char[] { ',' } ); this.deviceId = int.Parse( v[ 0 ] ); this.key = int.Parse( v[ 1 ] ); } void IYamlConvertible.Read( IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer ) { var devkey = (string?)nestedObjectDeserializer( typeof( string ) ) ?? ""; string 正規表現パターン = $@"^(\d+),(\d+)$"; // \d は10進数数字 var m = Regex.Match( devkey, 正規表現パターン, RegexOptions.IgnoreCase ); if( m.Success && ( 3 <= m.Groups.Count ) ) { this.deviceId = int.Parse( m.Groups[ 1 ].Value ); this.key = int.Parse( m.Groups[ 2 ].Value ); } } void IYamlConvertible.Write( IEmitter emitter, ObjectSerializer nestedObjectSerializer ) { nestedObjectSerializer( $"{this.deviceId},{this.key}" ); } public override string ToString() => $"{this.deviceId},{this.key}"; } } } <|start_filename|>DTXMania2/ステージ/アイキャッチ/GO.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { class GO : アイキャッチ { // 生成と終了 public GO() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.現在のフェーズ = フェーズ.未定; this.文字画像 = new 画像D2D[ 3 ] { new 画像D2D( @"$(Images)\EyeCatch\G.png" ) { 加算合成する = true }, new 画像D2D( @"$(Images)\EyeCatch\O.png" ) { 加算合成する = true }, new 画像D2D( @"$(Images)\EyeCatch\!.png" ) { 加算合成する = true }, }; // Go! this._文字アニメーション = new 文字[ 3 ]; for( int i = 0; i < this._文字アニメーション.Length; i++ ) this._文字アニメーション[ i ] = new 文字(); // ぐるぐる棒 this._ぐるぐる棒アニメーション = new ぐるぐる棒[ 12 ]; for( int i = 0; i < this._ぐるぐる棒アニメーション.Length; i++ ) this._ぐるぐる棒アニメーション[ i ] = new ぐるぐる棒(); // フラッシュオーバー棒 this._フラッシュオーバー棒アニメーション = new フラッシュオーバー棒[ 6 ]; for( int i = 0; i < this._フラッシュオーバー棒アニメーション.Length; i++ ) this._フラッシュオーバー棒アニメーション[ i ] = new フラッシュオーバー棒(); // フェードイン this._フェードインアニメーション = new フェードイン(); } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); // Go! if( null != this._文字アニメーション ) { foreach( var s in this._文字アニメーション ) s.Dispose(); } // ぐるぐる棒 if( null != this._ぐるぐる棒アニメーション ) { foreach( var b in this._ぐるぐる棒アニメーション ) b.Dispose(); } // フラッシュオーバー棒 if( null != this._フラッシュオーバー棒アニメーション ) { foreach( var b in this._フラッシュオーバー棒アニメーション ) b.Dispose(); } // フェードイン this._フェードインアニメーション.Dispose(); // 文字画像 foreach( var image in this.文字画像 ) image.Dispose(); base.Dispose(); } // オープンとクローズ /// <summary> /// アイキャッチのクローズアニメーションを開始する。 /// </summary> public override void クローズする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this.現在のフェーズ = フェーズ.クローズ; // Go! var basetime = animation.Timer.Time; var start = basetime; #region " 「G」のアニメーション構築 " //---------------- { this._文字アニメーション[ (int)文字名.G ]?.Dispose(); this._文字アニメーション[ (int)文字名.G ] = new 文字() { 画像 = this.文字画像[ (int)文字名.G ], 中心位置X = new Variable( animation.Manager, 0.0 - 400.0 ), 中心位置Y = new Variable( animation.Manager, 1080.0 / 2.0 - 170.0 ), 拡大率 = new Variable( animation.Manager, 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }; var 文字 = this._文字アニメーション[ (int)文字名.G ]; using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.23 ), finalValue: 1920.0 / 2.0 - 260.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) 文字.ストーリーボード!.AddTransition( 文字!.中心位置X, 中心位置Xの遷移 ); using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.07 ), finalValue: 1920.0 / 2.0 - 320.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) 文字.ストーリーボード!.AddTransition( 文字.中心位置X, 中心位置Xの遷移 ); using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.07 ), finalValue: 1920.0 / 2.0 - 260.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) 文字.ストーリーボード!.AddTransition( 文字.中心位置X, 中心位置Xの遷移 ); 文字.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " 「O」のアニメーション構築 " //---------------- { this._文字アニメーション[ (int)文字名.O ]?.Dispose(); this._文字アニメーション[ (int)文字名.O ] = new 文字() { 画像 = this.文字画像[ (int)文字名.O ], 中心位置X = new Variable( animation.Manager, 1920.0 + 200.0 ), 中心位置Y = new Variable( animation.Manager, 1080.0 / 2.0 - 80.0 ), 拡大率 = new Variable( animation.Manager, 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }; var 文字 = this._文字アニメーション[ (int)文字名.O ]; using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.23 ), finalValue: 1920.0 / 2.0 - 20.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) 文字.ストーリーボード!.AddTransition( 文字.中心位置X, 中心位置Xの遷移 ); using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.07 ), finalValue: 1920.0 / 2.0 + 20.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) 文字.ストーリーボード!.AddTransition( 文字.中心位置X, 中心位置Xの遷移 ); using( var 中心位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.07 ), finalValue: 1920.0 / 2.0 - 20.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) 文字.ストーリーボード!.AddTransition( 文字.中心位置X, 中心位置Xの遷移 ); 文字.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " 「!」のアニメーション構築 " //---------------- { this._文字アニメーション[ (int)文字名.Exc ]?.Dispose(); this._文字アニメーション[ (int)文字名.Exc ] = new 文字() { 画像 = this.文字画像[ (int)文字名.Exc ], 中心位置X = new Variable( animation.Manager, 1920.0 / 2.0 + 140.0 ), 中心位置Y = new Variable( animation.Manager, 1080.0 / 2.0 + 100.0 ), 拡大率 = new Variable( animation.Manager, 0.1 ), ストーリーボード = new Storyboard( animation.Manager ), }; var 文字 = this._文字アニメーション[ (int)文字名.Exc ]; using( var 中心位置Yの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.14 ), finalValue: 1080.0 / 2.0 - 340.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) using( var 拡大率の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.14 ), finalValue: 1.5, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { 文字.ストーリーボード!.AddTransition( 文字.中心位置Y, 中心位置Yの遷移 ); 文字.ストーリーボード!.AddTransition( 文字.拡大率, 拡大率の遷移 ); } using( var 中心位置Yの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1 ), finalValue: 1080.0 / 2.0 - 200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) using( var 拡大率の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1 ), finalValue: 1.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { 文字.ストーリーボード!.AddTransition( 文字.中心位置Y, 中心位置Yの遷移 ); 文字.ストーリーボード!.AddTransition( 文字.拡大率, 拡大率の遷移 ); } 文字.ストーリーボード!.Schedule( start + 秒( 0.16 ) ); } //---------------- #endregion // ぐるぐる棒 start = basetime + 秒( 0.2 ); #region " [0] 上側1番目の青 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 0 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 0 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = 50.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.5f, 0.5f, 1f, 1f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 0 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 800.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " [1] 上側1番目の白 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 1 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 1 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 200.0 ), 棒の太さ = 20.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 1 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 1200.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.8824 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2600.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " [2] 上側2番目の青 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 2 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 2 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = 50.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.5f, 0.5f, 1f, 1f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 2 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 800.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0294 ) ); } //---------------- #endregion #region " [3] 上側2番目の白 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 3 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 3 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 200.0 ), 棒の太さ = 20.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 3 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 1200.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2600.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0294 ) ); } //---------------- #endregion #region " [4] 上側3番目の青 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 4 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 4 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = 50.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.1f, 0.1f, 0.5f, 0.5f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 4 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 800.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0471 ) ); } //---------------- #endregion #region " [5] 上側3番目の白 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 5 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 5 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 200.0 ), 棒の太さ = 10.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 0.5f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 5 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 1200.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2600.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0471 ) ); } //---------------- #endregion #region " [6] 下側1番目の青 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 6 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 6 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = 50.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.5f, 0.5f, 1f, 1f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 6 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 800.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " [7] 下側1番目の白 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 7 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 7 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 200.0 ), 棒の太さ = 20.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 7 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 1200.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2600.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " [8] 下側2番目の青 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 8 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 8 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = 50.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.5f, 0.5f, 1f, 1f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 8 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 800.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0294 ) ); } //---------------- #endregion #region " [9] 下側2番目の白 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 9 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 9 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 200.0 ), 棒の太さ = 20.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 9 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 1200.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2600.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0294 ) ); } //---------------- #endregion #region " [10] 下側3番目の青 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 10 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 10 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = 50.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.1f, 0.1f, 0.5f, 0.5f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 10 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 800.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2200.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0471 ) ); } //---------------- #endregion #region " [11] 下側3番目の白 のアニメーション構築 " //---------------- { this._ぐるぐる棒アニメーション[ 11 ]?.Dispose(); this._ぐるぐる棒アニメーション[ 11 ] = new ぐるぐる棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 200.0 ), 棒の太さ = 10.0, 回転角rad = new Variable( animation.Manager, initialValue: 0.0 ), 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 0.5f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._ぐるぐる棒アニメーション[ 11 ]; using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.1765 ), finalValue: 1200.0, accelerationRatio: 0.0, decelerationRatio: 1.0 ) ) using( var 回転の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.088 ) ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 0.1765 ) ) ) using( var 回転の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.294 ), finalValue: Math.PI * 1.25, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.AddTransition( bar.回転角rad, 回転の遷移 ); } using( var 太さの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.147 ), finalValue: 2600.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) { bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); } bar.ストーリーボード!.Schedule( start + 秒( 0.0471 ) ); } //---------------- #endregion // フラッシュオーバー棒 start = basetime + 秒( 0.55 ); #region " [0] 上側1番目の白 のアニメーション構築 " //---------------- { this._フラッシュオーバー棒アニメーション[ 0 ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ 0 ] = new フラッシュオーバー棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = new Variable( animation.Manager, initialValue: 50.0 ), 回転角rad = Math.PI * 0.25, 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._フラッシュオーバー棒アニメーション[ 0 ]; using( var 太さの遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.18 ), finalValue: 2200.0 ) ) bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " [1] 上側2番目の白 のアニメーション構築 " //---------------- { this._フラッシュオーバー棒アニメーション[ 1 ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ 1 ] = new フラッシュオーバー棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = new Variable( animation.Manager, initialValue: 50.0 ), 回転角rad = Math.PI * 0.25, 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._フラッシュオーバー棒アニメーション[ 1 ]; using( var 太さの遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.18 ), finalValue: 2200.0 ) ) bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.Schedule( start + 秒( 0.02 ) ); } //---------------- #endregion #region " [2] 下側1番目の白 のアニメーション構築 " //---------------- { this._フラッシュオーバー棒アニメーション[ 2 ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ 2 ] = new フラッシュオーバー棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = new Variable( animation.Manager, initialValue: 50.0 ), 回転角rad = Math.PI * 0.25, 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._フラッシュオーバー棒アニメーション[ 2 ]; using( var 太さの遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.18 ), finalValue: 2200.0 ) ) bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.Schedule( start ); } //---------------- #endregion #region " [3] 下側2番目の白 のアニメーション構築 " //---------------- { this._フラッシュオーバー棒アニメーション[ 3 ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ 3 ] = new フラッシュオーバー棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = new Variable( animation.Manager, initialValue: 50.0 ), 回転角rad = Math.PI * 0.25, 辺の種類 = 辺の種類.下辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._フラッシュオーバー棒アニメーション[ 3 ]; using( var 太さの遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.18 ), finalValue: 2200.0 ) ) bar.ストーリーボード!.AddTransition( bar.太さ, 太さの遷移 ); bar.ストーリーボード!.Schedule( start + 秒( 0.02 ) ); } //---------------- #endregion #region " [4] 真ん中の白 のアニメーション構築 " //---------------- { this._フラッシュオーバー棒アニメーション[ 4 ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ 4 ] = new フラッシュオーバー棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = new Variable( animation.Manager, initialValue: 0.0 ), 回転角rad = Math.PI * 0.25, 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 1f, 1f, 1f, 1f ) ), // 白 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._フラッシュオーバー棒アニメーション[ 4 ]; using( var 棒の太さの遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.18 ), finalValue: 2200.0 ) ) bar.ストーリーボード!.AddTransition( bar.棒の太さ, 棒の太さの遷移 ); bar.ストーリーボード!.Schedule( start + 秒( 0.033 ) ); } //---------------- #endregion #region " [5] 真ん中の青 のアニメーション構築 " //---------------- { this._フラッシュオーバー棒アニメーション[ 5 ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ 5 ] = new フラッシュオーバー棒() { 中心位置X = 1920.0 / 2.0, 中心位置Y = 1080.0 / 2.0, 太さ = new Variable( animation.Manager, initialValue: 0.0 ), 棒の太さ = new Variable( animation.Manager, initialValue: 0.0 ), 回転角rad = Math.PI * 0.25, 辺の種類 = 辺の種類.上辺, ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, new Color4( 0.5f, 0.5f, 1f, 1f ) ), // 青 ストーリーボード = new Storyboard( animation.Manager ), }; var bar = this._フラッシュオーバー棒アニメーション[ 5 ]; using( var 棒の太さの遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.18 ), finalValue: 2200.0 ) ) bar.ストーリーボード!.AddTransition( bar.棒の太さ, 棒の太さの遷移 ); bar.ストーリーボード!.Schedule( start + 秒( 0.1 ) ); } //---------------- #endregion // フェードイン → 使わない this._フェードインアニメーション?.Dispose(); this._フェードインアニメーション = new フェードイン(); } /// <summary> /// アイキャッチのオープンアニメーションを開始する。 /// </summary> public override void オープンする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this.現在のフェーズ = フェーズ.オープン; var basetime = animation.Timer.Time; // Go! → 使わない for( int i = 0; i < this._文字アニメーション.Length; i++ ) { this._文字アニメーション[ i ]?.Dispose(); this._文字アニメーション[ i ] = new 文字(); } // ぐるぐる棒 → 使わない for( int i = 0; i < this._ぐるぐる棒アニメーション.Length; i++ ) { this._ぐるぐる棒アニメーション[ i ]?.Dispose(); this._ぐるぐる棒アニメーション[ i ] = new ぐるぐる棒(); } // フラッシュオーバー棒 → 使わない for( int i = 0; i < this._フラッシュオーバー棒アニメーション.Length; i++ ) { this._フラッシュオーバー棒アニメーション[ i ]?.Dispose(); this._フラッシュオーバー棒アニメーション[ i ] = new フラッシュオーバー棒(); } // フェードイン var start = basetime; this._フェードインアニメーション?.Dispose(); this._フェードインアニメーション = new フェードイン() { 不透明度 = new Variable( animation.Manager, initialValue: 1.0 ), ストーリーボード = new Storyboard( animation.Manager ), }; using( var 不透明度の遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 0.8 ), finalValue: 0.0, accelerationRatio: 0.5, decelerationRatio: 0.5 ) ) this._フェードインアニメーション.ストーリーボード.AddTransition( this._フェードインアニメーション.不透明度, 不透明度の遷移 ); this._フェードインアニメーション.ストーリーボード.Schedule( start ); } // 進行と描画 /// <summary> /// アイキャッチのアニメーションを進行し、アイキャッチ画像を描画する。 /// </summary> protected override void 進行描画する( DeviceContext d2ddc, StoryboardStatus 描画しないStatus ) { bool すべて完了 = true; var preTrans = d2ddc.Transform; #region " ぐるぐる棒 " //---------------- for( int i = 0; i < this._ぐるぐる棒アニメーション.Length; i++ ) { var context = this._ぐるぐる棒アニメーション[ i ]; if( context.ストーリーボード is null ) continue; if( context.ストーリーボード!.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード!.Status == 描画しないStatus ) continue; d2ddc.Transform = Matrix3x2.Rotation( (float)context.回転角rad.Value ) * Matrix3x2.Translation( (float)context.中心位置X, (float)context.中心位置Y ) * preTrans; float contextの幅 = 2800.0f; float contextの高さ = (float)context.太さ.Value; var rc = ( context.辺の種類 == 辺の種類.上辺 ) ? new RectangleF( -contextの幅 / 2f, -( contextの高さ + (float)context.棒の太さ ) / 2f, contextの幅, (float)context.棒の太さ ) : // 上辺 new RectangleF( -contextの幅 / 2f, +( contextの高さ - (float)context.棒の太さ ) / 2f, contextの幅, (float)context.棒の太さ ); // 下辺 d2ddc.FillRectangle( rc, context.ブラシ ); } d2ddc.Transform = preTrans; //---------------- #endregion #region " フラッシュオーバー棒([0~4]の5本)" //---------------- for( int i = 0; i <= 4; i++ ) { var context = this._フラッシュオーバー棒アニメーション[ i ]; if( context.ストーリーボード is null ) continue; if( context.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード!.Status == 描画しないStatus ) continue; d2ddc.Transform = Matrix3x2.Rotation( (float)context.回転角rad ) * Matrix3x2.Translation( (float)context.中心位置X, (float)context.中心位置Y ) * preTrans; float contextの幅 = 2800.0f; float contextの高さ = (float)context.太さ.Value; var rc = ( context.辺の種類 == 辺の種類.上辺 ) ? new RectangleF( -contextの幅 / 2f, -( contextの高さ + (float)context.棒の太さ.Value ) / 2f, contextの幅, (float)context.棒の太さ.Value ) : // 上辺 new RectangleF( -contextの幅 / 2f, +( contextの高さ - (float)context.棒の太さ.Value ) / 2f, contextの幅, (float)context.棒の太さ.Value ); // 下辺 d2ddc.FillRectangle( rc, context.ブラシ ); } d2ddc.Transform = preTrans; //---------------- #endregion #region " Go! " //---------------- foreach( var context in this._文字アニメーション ) { if( context.ストーリーボード is null ) continue; if( context.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード!.Status == 描画しないStatus ) continue; var 変換行列2D = Matrix3x2.Scaling( (float)context.拡大率.Value ) * Matrix3x2.Translation( (float)context.中心位置X.Value, (float)context.中心位置Y.Value ); context.画像.描画する( d2ddc, 変換行列2D ); } //---------------- #endregion #region " フラッシュオーバー棒([5]の1本)... Go! の上にかぶせる" //---------------- { var context = this._フラッシュオーバー棒アニメーション[ 5 ]; if( null != context.ストーリーボード ) { if( context.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード.Status != 描画しないStatus ) { d2ddc.Transform = Matrix3x2.Rotation( (float)context.回転角rad ) * Matrix3x2.Translation( (float)context.中心位置X, (float)context.中心位置Y ) * preTrans; float contextの幅 = 2800.0f; float contextの高さ = (float)context.太さ.Value; var rc = ( context.辺の種類 == 辺の種類.上辺 ) ? new RectangleF( -contextの幅 / 2f, -( contextの高さ + (float)context.棒の太さ.Value ) / 2f, contextの幅, (float)context.棒の太さ.Value ) : // 上辺 new RectangleF( -contextの幅 / 2f, +( contextの高さ - (float)context.棒の太さ.Value ) / 2f, contextの幅, (float)context.棒の太さ.Value ); // 下辺 d2ddc.FillRectangle( rc, context.ブラシ ); d2ddc.Transform = preTrans; } } } //---------------- #endregion #region " フェードイン " //---------------- { var context = this._フェードインアニメーション; if( null != context.ストーリーボード ) { if( context.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( context.ストーリーボード.Status != 描画しないStatus ) { using( var ブラシ = new SolidColorBrush( d2ddc, new Color4( 0.5f, 0.5f, 1f, (float)context.不透明度.Value ) ) ) d2ddc.FillRectangle( new RectangleF( 0f, 0f, 1920f, 1080f ), ブラシ ); } } } //---------------- #endregion if( すべて完了 ) { if( this.現在のフェーズ == フェーズ.クローズ ) { this.現在のフェーズ = フェーズ.クローズ完了; } else if( this.現在のフェーズ == フェーズ.オープン ) { this.現在のフェーズ = フェーズ.オープン完了; } } } // ローカル private readonly 画像D2D[] 文字画像; /// <summary> /// G, O, ! のアニメーション情報 /// </summary> protected class 文字 : IDisposable { public 画像D2D 画像 = null!; public Variable 中心位置X = null!; public Variable 中心位置Y = null!; public Variable 拡大率 = null!; public Storyboard? ストーリーボード = null; // null ならこの文字は使用しない public virtual void Dispose() { this.画像 = null!; // Disposeしない this.ストーリーボード?.Dispose(); this.中心位置Y?.Dispose(); this.中心位置X?.Dispose(); this.拡大率?.Dispose(); } } private readonly 文字[] _文字アニメーション; private enum 文字名 { G = 0, O = 1, Exc = 2 }; /// <summary> /// ぐるぐる棒のアニメーション情報 /// </summary> private class ぐるぐる棒 : IDisposable { public double 中心位置X; public double 中心位置Y; public Variable 回転角rad = null!; public Variable 太さ = null!; public double 棒の太さ; public Storyboard? ストーリーボード = null; // null ならこのぐるぐる棒は使用しない public 辺の種類 辺の種類; public Brush ブラシ = null!; public virtual void Dispose() { this.ブラシ?.Dispose(); this.ストーリーボード?.Dispose(); this.太さ?.Dispose(); this.回転角rad?.Dispose(); } } private readonly ぐるぐる棒[] _ぐるぐる棒アニメーション; private enum 辺の種類 { 上辺, 下辺 } /// <summary> /// フラッシュオーバー棒のアニメーション情報 /// </summary> private class フラッシュオーバー棒 : IDisposable { public double 中心位置X; public double 中心位置Y; public double 回転角rad; public Variable 太さ = null!; public Variable 棒の太さ = null!; public Storyboard? ストーリーボード = null; // null ならこのフラッシュオーバー棒は使用しない public 辺の種類 辺の種類; public Brush ブラシ = null!; public virtual void Dispose() { this.ブラシ?.Dispose(); this.ストーリーボード?.Dispose(); this.棒の太さ?.Dispose(); this.太さ?.Dispose(); } } private readonly フラッシュオーバー棒[] _フラッシュオーバー棒アニメーション; /// <summary> /// フェードインのアニメーション情報 /// </summary> private class フェードイン : IDisposable { public Variable 不透明度 = null!; public Storyboard? ストーリーボード = null; // null ならフェードインは使用しない public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.不透明度?.Dispose(); } } private フェードイン _フェードインアニメーション; } } <|start_filename|>DTXMania2/ステージ/04選曲/QuickConfig/QuickConfigパネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Data.Sqlite; using SharpDX.Direct2D1; using FDK; using DTXMania2.曲; namespace DTXMania2.選曲.QuickConfig { class QuickConfigパネル : IDisposable { // プロパティ public enum フェーズ { 表示, 完了_戻る, 完了_オプション設定, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.表示; // 生成と終了 /// <summary> /// コンストラクタ。 /// </summary> /// <param name="song">現在選択中の曲。曲以外が選択されているなら null 。</param> /// <param name="userId">現在ログイン中のユーザ名。</param> public QuickConfigパネル( Song? song, string userId ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パネル = new 画像D2D( @"$(Images)\SelectStage\QuickConfigPanel.png" ); this._設定項目リスト = new SelectableList<ラベル>(); #region "「この曲の評価」" //---------------- var score = song?.譜面リスト?.FirstOrDefault( ( s ) => s != null ); if( null != score ) { this._設定項目リスト.Add( new リスト( 名前: Properties.Resources.TXT_この曲の評価, 選択肢初期値リスト: new[] { Properties.Resources.TXT_評価なし, Properties.Resources.TXT_評価1, Properties.Resources.TXT_評価2, Properties.Resources.TXT_評価3, Properties.Resources.TXT_評価4, Properties.Resources.TXT_評価5 }, 初期選択肢番号: score.譜面の属性?.Rating ?? 0, 値が変更された: ( list ) => { int 新Rating = list.現在の選択肢番号; #region " 属性DBの該当レコードを、更新または新規作成する。" //---------------- using var db = new ScorePropertiesDB(); for( int i = 0; i < song!.譜面リスト!.Length; i++ ) { var score = song.譜面リスト[ i ]!; if( null != score ) { using var cmd = new SqliteCommand( "SELECT * FROM ScoreProperties WHERE ScorePath = @ScorePath AND UserId = @UserId", db.Connection ); cmd.Parameters.AddRange( new[] { new SqliteParameter( "@ScorePath", score.譜面.ScorePath ), new SqliteParameter( "@UserId", Global.App.ログオン中のユーザ.ID ), } ); var result = cmd.ExecuteReader(); if( result.Read() ) { // (A) 属性DBにレコードがあった → Ratingを更新して書き戻し var prop = new ScorePropertiesDBRecord( result ); prop.Rating = 新Rating; prop.InsertTo( db ); } else { // (B) 属性DBにレコードがなかった → レコードを新規生成 var rc = new ScorePropertiesDBRecord() { ScorePath = score.譜面.ScorePath, UserId = userId, Rating = 新Rating, }; rc.InsertTo( db ); } } } //---------------- #endregion #region " DBから読み込み済みの属性も、更新または新規作成する。" //---------------- for( int i = 0; i < song!.譜面リスト!.Length; i++ ) { var score = song.譜面リスト[ i ]!; if( null != score ) { if( score.譜面の属性 is null ) { // (A) 新規作成 score.譜面の属性 = new ScorePropertiesDBRecord() { ScorePath = score.譜面.ScorePath, UserId = userId, Rating = list.現在の選択肢番号, }; } else { // (B) 更新 score.譜面の属性.Rating = list.現在の選択肢番号; } } } //---------------- #endregion } ) ); } //---------------- #endregion #region "「オプション設定へ」" //---------------- this._設定項目リスト.Add( new ラベル( Properties.Resources.TXT_オプション設定へ ) ); //---------------- #endregion #region "「戻る」" //---------------- this._設定項目リスト.Add( new ラベル( Properties.Resources.TXT_戻る ) ); //---------------- #endregion this._設定項目リスト.SelectItem( 0 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var item in this._設定項目リスト ) item.Dispose(); this._パネル.Dispose(); } // 進行と描画 public void 進行する() { var 入力 = Global.App.ドラム入力; // 呼び出し元でポーリング済み switch( this.現在のフェーズ ) { case フェーズ.表示: { #region " 入力処理。" //---------------- if( 入力.キャンセルキーが入力された() ) { #region " キャンセル → 完了_戻る フェーズへ。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); this.現在のフェーズ = フェーズ.完了_戻る; //---------------- #endregion } else if( 入力.上移動キーが入力された() ) { #region " 上 → 1つ前の項目へカーソルを移動する。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._設定項目リスト.SelectPrev( Loop: true ); //---------------- #endregion } else if( 入力.下移動キーが入力された() ) { #region " 下 → 1つ後の項目へカーソルを移動する。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.カーソル移動音 ); this._設定項目リスト.SelectNext( Loop: true ); //---------------- #endregion } else if( 入力.左移動キーが入力された() ) { #region " 左 → 項目の種類に応じて処理分岐。" //---------------- var item = this._設定項目リスト.SelectedItem; switch( item ) { case リスト list: Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); list.前を選択する( Loop: false ); break; case ラベル label: break; } //---------------- #endregion } else if( 入力.右移動キーが入力された() ) { #region " 右 → 項目の種類に応じて処理分岐。" //---------------- var item = this._設定項目リスト.SelectedItem; switch( item ) { case リスト list: Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); list.次を選択する( Loop: false ); break; case ラベル label: break; } //---------------- #endregion } else if( 入力.確定キーが入力された() ) { #region " 確定 → 項目の種類や名前に応じて処理分岐。" //---------------- var item = this._設定項目リスト.SelectedItem; switch( item ) { case リスト list: { Global.App.システムサウンド.再生する( システムサウンド種別.変更音 ); list.次を選択する( Loop: true ); break; } case ラベル label: { if( label.名前 == Properties.Resources.TXT_オプション設定へ ) { #region " 完了_オプション設定フェーズへ。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.決定音 ); this.現在のフェーズ = フェーズ.完了_オプション設定; //---------------- #endregion } else if( label.名前 == Properties.Resources.TXT_戻る ) { #region " 完了_戻る フェーズへ。" //---------------- Global.App.システムサウンド.再生する( システムサウンド種別.取消音 ); this.現在のフェーズ = フェーズ.完了_戻る; //---------------- #endregion } break; } } //---------------- #endregion } //---------------- #endregion break; } case フェーズ.完了_戻る: case フェーズ.完了_オプション設定: { #region " 遷移終了。呼び出し元による継続処理を待つ。" //---------------- //---------------- #endregion break; } } } public void 描画する( DeviceContext d2ddc, float 左位置, float 上位置 ) { var preTrans = d2ddc.Transform; switch( this.現在のフェーズ ) { case フェーズ.表示: { #region " QuickConfig パネルを描画する。" //---------------- this._パネル.描画する( d2ddc, 左位置, 上位置 ); for( int i = 0; i < this._設定項目リスト.Count; i++ ) { const float 左右マージン = 24.0f; const float 見出し行間 = 100.0f; const float 項目行間 = 60.0f; const float 項目ラベル上マージン = 6.0f; // 選択カーソルを描画する。 if( this._設定項目リスト.SelectedIndex == i ) { d2ddc.Transform = SharpDX.Matrix3x2.Identity; using var brush = new SolidColorBrush( d2ddc, new SharpDX.Color( 0.6f, 0.6f, 1f, 0.4f ) ); d2ddc.FillRectangle( new SharpDX.RectangleF( 左位置 + 左右マージン, 上位置 + 見出し行間 + 項目行間 * i, this._パネル.サイズ.Width - 左右マージン * 2, 項目行間 ), brush ); d2ddc.Transform = preTrans; } // 選択肢項目を描画する。 this._設定項目リスト[ i ].進行描画する( d2ddc, 左位置 + 左右マージン * 2, 上位置 + 見出し行間 + i * 項目行間 + 項目ラベル上マージン ); } //---------------- #endregion break; } case フェーズ.完了_戻る: case フェーズ.完了_オプション設定: { break; } } } // ローカル private readonly 画像D2D _パネル; private readonly SelectableList<ラベル> _設定項目リスト; } } <|start_filename|>DTXMania2/タスクメッセージ/TaskMessage.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace DTXMania2 { /// <summary> /// タスク(スレッド)間で送受信されるメッセージ。 /// </summary> /// <remarks> /// DTXMania2 では、GUIタスクと進行描画タスクが並列に動作している。 /// これらの間で送受信されるメッセージを定義する。 /// メッセージは、<see cref="TaskMessageQueue"/> を介して送受信される。 /// </remarks> class TaskMessage { /// <summary> /// メッセージの宛先となるタスク。 /// </summary> public enum タスク名 // 必要に応じて付け足すこと。 { GUIフォーム, 進行描画, } /// <summary> /// タスクメッセージの内容。 /// </summary> public enum 内容名 // 必要に応じて付け足すこと。 { 終了指示, サイズ変更, } /// <summary> /// このメッセージの宛先。 /// </summary> public タスク名 宛先 { get; } /// <summary> /// このメッセージの内容。 /// 書式は任意。 /// </summary> public 内容名 内容 { get; } /// <summary> /// メッセージの引数。 /// オプション。 /// </summary> public object[]? 引数 { get; } /// <summary> /// メッセージが受信され、対応する処理が完了した場合に Set されるイベント。 /// </summary> public ManualResetEventSlim 完了通知 { get; } /// <summary> /// コンストラクタ。 /// </summary> public TaskMessage( タスク名 宛先, 内容名 内容, object[]? 引数 = null ) { this.宛先 = 宛先; this.内容 = 内容; this.引数 = 引数; this.完了通知 = new ManualResetEventSlim( false ); } } } <|start_filename|>DTXMania2/ステージ/07演奏/入力グループプリセット種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.演奏 { enum 入力グループプリセット種別 { /// <summary> /// シンバル類のチップは、どのシンバル類を叩いても OK とするプリセット。 /// </summary> シンバルフリー, /// <summary> /// 類似したチップをグループ化したプリセット。 /// </summary> 基本形, } } <|start_filename|>FDK/イメージ/矩形リスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpDX; namespace FDK { /// <summary> /// 任意の文字列から任意の矩形を引き当てるための辞書。 /// 辞書の内容は、yamlファイルから読み込むことができる。 /// </summary> public class 矩形リスト { // プロパティ /// <summary> /// 文字列から矩形へのマッピング。 /// </summary> public Dictionary<string, RectangleF> 文字列to矩形 { get; } /// <summary> /// 文字列に対応する矩形を返す。 /// </summary> /// <param name="文字列">文字列。</param> /// <returns>文字列に対応する矩形。文字列がマッピングできなければ null を返す。</returns> public RectangleF? this[ string 文字列 ] => this.文字列to矩形.TryGetValue( 文字列, out var 矩形 ) ? 矩形 : (RectangleF?)null; // 生成と終了 public 矩形リスト() { this.文字列to矩形 = new Dictionary<string, RectangleF>(); } public 矩形リスト( VariablePath yamlファイルパス ) : this() { this.矩形リストをyamlファイルから読み込む( yamlファイルパス ); } public void 矩形リストをyamlファイルから読み込む( VariablePath yamlファイルパス ) { // yaml ファイルを読み込む。 var yamlText = File.ReadAllText( yamlファイルパス.変数なしパス ); var deserializer = new YamlDotNet.Serialization.Deserializer(); var yaml = deserializer.Deserialize<YAMLマップ>( yamlText ); // 内容から矩形リストを作成。 foreach( var kvp in yaml.RectangleList ) { if( 4 == kvp.Value.Length ) this.文字列to矩形[ kvp.Key ] = new RectangleF( kvp.Value[ 0 ], kvp.Value[ 1 ], kvp.Value[ 2 ], kvp.Value[ 3 ] ); else Log.ERROR( $"矩形リストの書式が不正です。[{yamlファイルパス.変数付きパス}]" ); } } // ローカル private class YAMLマップ { public Dictionary<string, float[]> RectangleList { get; set; } = new Dictionary<string, float[]>(); } } } <|start_filename|>SSTFormat/old/v003/スコア.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace SSTFormat.v003 { public partial class スコア : ISSTFScore { // 定数 /// <summary> /// このソースが実装するSSTFバージョン。 /// </summary> public static readonly Version SSTFVERSION = new Version( 3, 4, 0, 0 ); public const double 初期BPM = 120.0; public const double 初期小節解像度 = 480.0; public static readonly List<string> 背景動画のデフォルト拡張子リスト = new List<string>() { ".mp4", ".avi", ".wmv", ".mpg", ".mpeg" }; public static readonly Dictionary<チップ種別, レーン種別> チップtoレーンマップ = new Dictionary<チップ種別, レーン種別>() { #region " *** " //---------------- { チップ種別.Unknown, レーン種別.Unknown }, { チップ種別.LeftCrash, レーン種別.LeftCrash }, { チップ種別.Ride, レーン種別.Ride }, { チップ種別.Ride_Cup, レーン種別.Ride }, { チップ種別.China, レーン種別.China }, { チップ種別.Splash, レーン種別.Splash }, { チップ種別.HiHat_Open, レーン種別.HiHat }, { チップ種別.HiHat_HalfOpen, レーン種別.HiHat }, { チップ種別.HiHat_Close, レーン種別.HiHat }, { チップ種別.HiHat_Foot, レーン種別.Foot }, { チップ種別.Snare, レーン種別.Snare }, { チップ種別.Snare_OpenRim, レーン種別.Snare }, { チップ種別.Snare_ClosedRim, レーン種別.Snare }, { チップ種別.Snare_Ghost, レーン種別.Snare }, { チップ種別.Bass, レーン種別.Bass }, { チップ種別.LeftBass, レーン種別.Bass }, { チップ種別.Tom1, レーン種別.Tom1 }, { チップ種別.Tom1_Rim, レーン種別.Tom1 }, { チップ種別.Tom2, レーン種別.Tom2 }, { チップ種別.Tom2_Rim, レーン種別.Tom2 }, { チップ種別.Tom3, レーン種別.Tom3 }, { チップ種別.Tom3_Rim, レーン種別.Tom3 }, { チップ種別.RightCrash, レーン種別.RightCrash }, { チップ種別.BPM, レーン種別.BPM }, { チップ種別.小節線, レーン種別.Unknown }, { チップ種別.拍線, レーン種別.Unknown }, { チップ種別.背景動画, レーン種別.Song }, { チップ種別.小節メモ, レーン種別.Unknown }, { チップ種別.LeftCymbal_Mute, レーン種別.LeftCrash }, { チップ種別.RightCymbal_Mute, レーン種別.RightCrash }, { チップ種別.小節の先頭, レーン種別.Unknown }, { チップ種別.BGM, レーン種別.Song }, { チップ種別.SE1, レーン種別.Song }, { チップ種別.SE2, レーン種別.Song }, { チップ種別.SE3, レーン種別.Song }, { チップ種別.SE4, レーン種別.Song }, { チップ種別.SE5, レーン種別.Song }, { チップ種別.GuitarAuto, レーン種別.Song }, { チップ種別.BassAuto, レーン種別.Song }, //---------------- #endregion }; // ヘッダ /// <summary> /// SSTFバージョン。 /// ファイルから読み込んだ場合、ファイルにSSTFVersionの記述がなかった場合は v1.0.0.0 とみなす。 /// </summary> public Version SSTFバージョン { get; set; } /// <summary> /// このスコアの曲名。 /// </summary> public string 曲名 { get; set; } /// <summary> /// このスコアのアーティスト名。 /// 作曲者名、団体名、作品名、スコア作者名など、内容は任意。 /// </summary> public string アーティスト名 { get; set; } /// <summary> /// この曲の説明文。内容は任意。 /// </summary> public string 説明文 { get; set; } /// <summary> /// この曲の難易度。 /// 易:0.00~9.99:難 /// </summary> public double 難易度 { get; set; } /// <summary> /// プレビュー画像のファイル名。 /// </summary> public string プレビュー画像ファイル名 { get; set; } /// <summary> /// プレビュー音のファイル名。 /// </summary> public string プレビュー音声ファイル名 { get; set; } /// <summary> /// プレビュー動画のファイル名。 /// </summary> public string プレビュー動画ファイル名 { get; set; } /// <summary> /// このスコアが作成されたときのサウンドデバイスの遅延量[ミリ秒]。 /// </summary> public float サウンドデバイス遅延ms { get; set; } = 0f; /// <summary> /// 譜面ファイルの絶対パス。 /// </summary> public string 譜面ファイルパス { get; set; } = null; /// <summary> /// WAV, AVI, その他ファイルの基点となるフォルダの絶対パス。 /// 末尾は '\' 。(例: "D:\DTXData\DemoSong\Sounds\") /// </summary> public string PATH_WAV { get { if( null != this.譜面ファイルパス ) return Path.Combine( Path.GetDirectoryName( this.譜面ファイルパス ), this._PATH_WAV ); else return this._PATH_WAV; } set { this._PATH_WAV = value; if( this._PATH_WAV.Last() != '\\' ) this._PATH_WAV += '\\'; } } // チップリスト /// <summary> /// このスコアに存在するすべてのチップのリスト。 /// </summary> public List<チップ> チップリスト { get; protected set; } // 背景動画 /// <summary> /// スコアは、単一の動画または音楽(あるいはその両方)を持つことができる。 /// これは、<see cref="チップ種別.背景動画"/>の発声時に再生が開始される。 /// </summary> /// <remarks> /// 「プロトコル: 動画ID」という書式で指定する。大文字小文字は区別されない。 ///  例:"nicovideo: sm12345678" ... ニコ動 ///   "file: bgv.mp4" ... ローカルの mp4 ファイル ///   "bgv.mp4" ... プロトコルを省略してもローカルファイルとなる /// </remarks> public string 背景動画ID { get; set; } // 小節長倍率リスト /// <summary> /// 小節ごとの倍率。 /// インデックス番号が小節番号を表し、小節 0 から最大小節まで、すべての小節の倍率がこのリストに含まれる。 /// </summary> public List<double> 小節長倍率リスト { get; protected set; } public double 小節長倍率を取得する( int 小節番号 ) { // 小節長倍率リスト が短ければ増設する。 if( 小節番号 >= this.小節長倍率リスト.Count ) { int 不足数 = 小節番号 - this.小節長倍率リスト.Count + 1; for( int i = 0; i < 不足数; i++ ) this.小節長倍率リスト.Add( 1.0 ); } // 小節番号に対応する倍率を返す。 return this.小節長倍率リスト[ 小節番号 ]; } public void 小節長倍率を設定する( int 小節番号, double 倍率 ) { // 小節長倍率リスト が短ければ増設する。 if( 小節番号 >= this.小節長倍率リスト.Count ) { int 不足数 = 小節番号 - this.小節長倍率リスト.Count + 1; for( int i = 0; i < 不足数; i++ ) this.小節長倍率リスト.Add( 1.0 ); } // 小節番号に対応付けて倍率を登録する。 this.小節長倍率リスト[ 小節番号 ] = 倍率; } // 小節メモリスト /// <summary> /// メモリスト。 /// [key: 小節番号, value:メモ] /// </summary> public Dictionary<int, string> 小節メモリスト { get; protected set; } // 空うちチップマップ /// <summary> /// レーンごとの空うちチップ番号。 /// 空打ちチップが指定されている場合はそのWAVzzのzz番号を、指定されていないなら 0 を保持する。 /// [value: zz番号] /// </summary> public Dictionary<レーン種別, int> 空打ちチップマップ { get; protected set; } // WAVリスト /// <summary> /// #WAVzz で指定された、サウンドファイルへの相対パス他。 /// パスの基点は、#PATH_WAV があればそこ、なければ曲譜面ファイルと同じ場所。 /// [key: zz番号] /// </summary> public Dictionary<int, (string ファイルパス, bool 多重再生する)> WAVリスト { get; protected set; } // AVIリスト /// <summary> /// #AVIzz で指定された、動画ファイルへの相対パス。 /// パスの基点は、#PATH_WAV があればそこ、なければ曲譜面ファイルと同じ場所。 /// [key: zz番号] /// </summary> public Dictionary<int, string> AVIリスト { get; protected set; } // メソッド public スコア() { this.リセットする(); } public static スコア ファイルから生成する( string スコアファイルパス, bool ヘッダだけ = false ) { スコア score = null; var 拡張子 = Path.GetExtension( スコアファイルパス ).ToLower(); switch( 拡張子 ) { case ".sstf": score = SSTF.ファイルから生成する( スコアファイルパス, ヘッダだけ ); break; default: // dtx, gda, 他 score = DTX.ファイルから生成する( スコアファイルパス, DTX.データ種別.拡張子から判定, ヘッダだけ ); break; } //if( !( ヘッダだけ ) ) // _後処理を行う( score ); --> 生成メソッドの中で行っておくこと。 return score; } public スコア( v002.スコア v2score ) { this.SSTFバージョン = SSTFVERSION; this.曲名 = v2score.Header.曲名; this.アーティスト名 = ""; // v3で新設 this.説明文 = v2score.Header.説明文; this.難易度 = 5.0; // v3で新設 this.背景動画ID = v2score.背景動画ファイル名; // v3で仕様変更 this.プレビュー画像ファイル名 = null; // v3で新規追加 this.サウンドデバイス遅延ms = v2score.Header.サウンドデバイス遅延ms; this.譜面ファイルパス = v2score.Header.譜面ファイルパス; #region " 曲ファイルと同じ場所にあるプレビュー画像の検索(v3仕様)" //---------------- if( string.IsNullOrEmpty( this.プレビュー画像ファイル名 ) && !string.IsNullOrEmpty( v2score.Header.譜面ファイルパス ) ) { var _対応するサムネイル画像名 = new[] { "thumb.png", "thumb.bmp", "thumb.jpg", "thumb.jpeg" }; var 基点フォルダ = Path.GetDirectoryName( v2score.Header.譜面ファイルパス ) ?? @"\"; var path = ( from ファイル名 in Directory.GetFiles( 基点フォルダ ) where _対応するサムネイル画像名.Any( thumbファイル名 => ( Path.GetFileName( ファイル名 ).ToLower() == thumbファイル名 ) ) select ファイル名 ).FirstOrDefault(); if( default != path ) { this.プレビュー画像ファイル名 = ( Path.IsPathRooted( path ) ) ? _絶対パスを相対パスに変換する( 基点フォルダ, path ) : path; } } //---------------- #endregion this.チップリスト = new List<チップ>(); foreach( var v2chip in v2score.チップリスト ) this.チップリスト.Add( new チップ( v2chip ) ); this.小節長倍率リスト = v2score.小節長倍率リスト; this.小節メモリスト = v2score.dicメモ; this.空打ちチップマップ = new Dictionary<レーン種別, int>(); // v3で新規追加 this.WAVリスト = new Dictionary<int, (string ファイルパス, bool 多重再生する)>(); // v3で新規追加 this.AVIリスト = new Dictionary<int, string>(); // v3で新規追加 this.PATH_WAV = @"\"; // v3で新規追加 } public void リセットする() { this.SSTFバージョン = SSTFVERSION; this.曲名 = "(no title)"; this.アーティスト名 = ""; this.説明文 = ""; this.難易度 = 5.0; this.背景動画ID = null; this.プレビュー画像ファイル名 = null; this.プレビュー音声ファイル名 = null; this.プレビュー動画ファイル名 = null; this.サウンドデバイス遅延ms = 0f; this.譜面ファイルパス = null; this.チップリスト = new List<チップ>(); this.小節長倍率リスト = new List<double>(); this.小節メモリスト = new Dictionary<int, string>(); this.空打ちチップマップ = new Dictionary<レーン種別, int>(); foreach( レーン種別 lane in Enum.GetValues( typeof( レーン種別 ) ) ) this.空打ちチップマップ.Add( lane, 0 ); this.WAVリスト = new Dictionary<int, (string ファイルパス, bool 多重再生する)>(); this.AVIリスト = new Dictionary<int, string>(); this._PATH_WAV = ""; } /// <summary> /// この譜面における最後(最大)の小節番号。 /// </summary> public int 最大小節番号を返す() { if( 0 < this.チップリスト.Count ) return this.チップリスト.Max( ( chip ) => chip.小節番号 ); return -1; } // ローカル internal static void _後処理を行う( スコア score ) { #region " 小節の先頭チップを追加する。" //---------------- { int 最大小節番号 = score.最大小節番号を返す(); // 「小節の先頭」チップは、小節線と同じく、全小節の先頭位置に置かれる。 // 小節線には今後譜面作者によって位置をアレンジできる可能性を残したいが、 // ビュアーが小節の先頭位置を検索するためには、小節の先頭に置かれるチップが必要になる。 // よって、譜面作者の影響を受けない(ビュアー用の)チップを機械的に配置する。 for( int i = 0; i <= 最大小節番号; i++ ) { score.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.小節の先頭, 小節内位置 = 0, 小節解像度 = 1, } ); } } //---------------- #endregion #region " チップリストを並び替える。" //---------------- score.チップリスト.Sort(); //---------------- #endregion #region " 全チップの発声/描画時刻と譜面内位置を計算する。" //----------------- { // 1. BPMチップを無視し(初期BPMで固定)、小節長倍率, 小節解像度, 小節内位置 から 発声/描画時刻を計算する。 // 以下、チップリストが小節番号順にソートされているという前提で。 double チップが存在する小節の先頭時刻ms = 0.0; int 現在の小節の番号 = 0; foreach( チップ chip in score.チップリスト ) { // チップの小節番号が現在の小節の番号よりも大きい場合、チップが存在する小節に至るまで、チップが存在する小節の先頭時刻ms を更新する。 while( 現在の小節の番号 < chip.小節番号 ) // 現在の小節番号 が chip.小節番号 に追いつくまでループする。 { double 現在の小節の小節長倍率 = score.小節長倍率を取得する( 現在の小節の番号 ); チップが存在する小節の先頭時刻ms += _BPM初期値固定での1小節4拍の時間ms * 現在の小節の小節長倍率; 現在の小節の番号++; } // チップの発声/描画時刻を求める。 double チップが存在する小節の小節長倍率 = score.小節長倍率を取得する( 現在の小節の番号 ); double 時刻sec = ( チップが存在する小節の先頭時刻ms + ( _BPM初期値固定での1小節4拍の時間ms * チップが存在する小節の小節長倍率 * chip.小節内位置 ) / (double) chip.小節解像度 ) / 1000.0; chip.発声時刻sec = 時刻sec; chip.描画時刻sec = 時刻sec; } // 2. 次に、BPMチップを考慮しながら調整する。 double 現在のBPM = スコア.初期BPM; int チップ数 = score.チップリスト.Count; for( int i = 0; i < チップ数; i++ ) { var BPMチップ = score.チップリスト[ i ]; if( BPMチップ.チップ種別 != チップ種別.BPM ) continue; // BPM チップ以外は無視。 // BPMチップより後続の全チップの 発声/描画時刻ms を、新旧BPMの比率(加速率)で修正する。 double 加速率 = BPMチップ.BPM / 現在のBPM; // BPMチップ.dbBPM > 0.0 であることは読み込み時に保証済み。 for( int j = i + 1; j < チップ数; j++ ) { double 時刻sec = BPMチップ.発声時刻sec + ( score.チップリスト[ j ].発声時刻sec - BPMチップ.発声時刻sec ) / 加速率; score.チップリスト[ j ].発声時刻sec = 時刻sec; score.チップリスト[ j ].描画時刻sec = 時刻sec; } 現在のBPM = BPMチップ.BPM; } } //----------------- #endregion } /// <summary> /// 空文字、または絶対パス。 /// null は不可。 /// </summary> private string _PATH_WAV = ""; private const double _BPM初期値固定での1小節4拍の時間ms = ( 60.0 * 1000 ) / ( スコア.初期BPM / 4.0 ); private const double _BPM初期値固定での1小節4拍の時間sec = 60.0 / ( スコア.初期BPM / 4.0 ); private static string _絶対パスを相対パスに変換する( string 基点フォルダの絶対パス, string 変換したいフォルダの絶対パス ) { if( null == 変換したいフォルダの絶対パス ) return null; if( !( Path.IsPathRooted( 基点フォルダの絶対パス ) ) ) throw new Exception( $"基点フォルダは絶対パスで指定してください。[{基点フォルダの絶対パス}]" ); if( !( Path.IsPathRooted( 変換したいフォルダの絶対パス ) ) ) throw new Exception( $"変換対象フォルダは絶対パスで指定してください。[{変換したいフォルダの絶対パス}]" ); // 末尾は \ にしておく("+"でパスを連結する事態を想定。Path.Combine() を使う分には、末尾に \ があってもなくてもどっちでもいい。) if( '\\' != 基点フォルダの絶対パス[ 基点フォルダの絶対パス.Length - 1 ] ) 基点フォルダの絶対パス += @"\"; // 絶対-相対パス変換は、System.IO.Path クラスではなく System.IO.Uri クラスでしか行えない。 var 基点uri = new Uri( 基点フォルダの絶対パス ); var 変換前uri = new Uri( 変換したいフォルダの絶対パス ); var 変換後uri = 基点uri.MakeRelativeUri( 変換前uri ); // URI形式になっているので、パス形式に戻す。(具体的には、エスケープ文字を復元し、さらに '/' を '\' に置換する。) return Uri.UnescapeDataString( 変換後uri.ToString() ).Replace( oldChar: '/', newChar: '\\' ); } } } <|start_filename|>DTXMania2/保存データ/UserConfig/UserConfig.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Data.Sqlite; using YamlDotNet.Serialization; using FDK; namespace DTXMania2 { partial class UserConfig { // プロパティ public const int VERSION = 15; // このクラスのバージョン /// <summary> /// このクラスのバージョン。 /// </summary> [YamlMember] public int Version { get; set; } /// <summary> /// ユーザを一意に識別する文字列。主キーなので変更不可。 /// </summary> [YamlMember] public string Id { get; set; } /// <summary> /// ユーザ名。変更可。 /// </summary> [YamlMember] public string Name { get; set; } /// <summary> /// 譜面スクロール速度の倍率。1.0で等倍。 /// </summary> [YamlMember] public double ScrollSpeed { get; set; } /// <summary> /// 起動直後の表示モード。 /// 0: ウィンドウモード、その他: 全画面モード。 /// </summary> [YamlMember] public int Fullscreen { get; set; } /// <summary> /// シンバルフリーモード。 /// 0: OFF, その他: ON /// </summary> [YamlMember] public int CymbalFree { get; set; } /// <summary> /// Ride の表示位置。 /// 0: 右, 1: 左 /// </summary> [YamlMember] public int RideLeft { get; set; } /// <summary> /// China の表示位置。 /// 0: 右, 1: 左 /// </summary> [YamlMember] public int ChinaLeft { get; set; } /// <summary> /// Splash の表示位置。 /// 0: 右, 1: 左 /// </summary> [YamlMember] public int SplashLeft { get; set; } /// <summary> /// ユーザ入力時にドラム音を発声するか? /// 0: OFF, その他: ON /// </summary> [YamlMember] public int DrumSound { get; set; } /// <summary> /// レーンの透過度[%]。 /// 0:完全不透明 ~ 100:完全透明 /// </summary> [YamlMember] public int LaneTrans { get; set; } /// <summary> /// 演奏時に再生される背景動画を表示するか? /// 0: OFF, その他: ON /// </summary> [YamlMember] public int BackgroundMovie { get; set; } /// <summary> /// 演奏速度。 /// 1.0 で通常速度。 /// </summary> [YamlMember] public double PlaySpeed { get; set; } /// <summary> /// 小節線・拍線の表示 /// 0: OFF, その他: ON /// </summary> [YamlMember] public int ShowPartLine { get; set; } /// <summary> /// 小節番号の表示 /// 0: OFF, その他: ON /// </summary> [YamlMember] public int ShowPartNumber { get; set; } /// <summary> /// スコア指定の背景画像の表示 /// 0: OFF, その他: ON /// </summary> [YamlMember] public int ShowScoreWall { get; set; } /// <summary> /// 演奏中の背景動画の表示サイズ /// 0: 全画面, 1: 中央寄せ /// </summary> [YamlMember] public int BackgroundMovieSize { get; set; } /// <summary> /// 判定FAST/SLOWの表示 /// 0: OFF, その他: ON /// </summary> [YamlMember] public int ShowFastSlow { get; set; } /// <summary> /// 音量によるノーとサイズの変化 /// 0: OFF, その他: ON /// </summary> [YamlMember] public int NoteSizeByVolume { get; set; } /// <summary> /// ダークモード。 /// 0: OFF, 1:HALF, 2:FULL /// </summary> [YamlMember] public int Dark { get; set; } // AutoPlay /// <summary> /// 左シンバルレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_LeftCymbal { get; set; } /// <summary> /// ハイハットレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_HiHat { get; set; } /// <summary> /// 左ペダルレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_LeftPedal { get; set; } /// <summary> /// スネアレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_Snare { get; set; } /// <summary> /// バスレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_Bass { get; set; } /// <summary> /// ハイタムレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_HighTom { get; set; } /// <summary> /// ロータムレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_LowTom { get; set; } /// <summary> /// フロアタムレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_FloorTom { get; set; } /// <summary> /// 右シンバルレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> [YamlMember] public int AutoPlay_RightCymbal { get; set; } // 最大ヒット距離 /// <summary> /// Perfect の最大ヒット距離[秒]。 /// </summary> [YamlMember] public double MaxRange_Perfect { get; set; } /// <summary> /// Great の最大ヒット距離[秒]。 /// </summary> [YamlMember] public double MaxRange_Great { get; set; } /// <summary> /// Good の最大ヒット距離[秒]。 /// </summary> [YamlMember] public double MaxRange_Good { get; set; } /// <summary> /// Ok の最大ヒット距離[秒]。 /// </summary> [YamlMember] public double MaxRange_Ok { get; set; } // 生成と終了 public UserConfig() { this.Version = VERSION; this.Id = "Anonymous"; this.Name = "Anonymous"; this.ScrollSpeed = 1.0; this.Fullscreen = 0; this.CymbalFree = 1; this.RideLeft = 0; this.ChinaLeft = 0; this.SplashLeft = 1; this.DrumSound = 1; this.LaneTrans = 40; this.BackgroundMovie = 1; this.PlaySpeed = 1.0; this.ShowPartLine = 1; this.ShowPartNumber = 1; this.ShowScoreWall = 1; this.BackgroundMovieSize = 0; this.ShowFastSlow = 0; this.NoteSizeByVolume = 1; this.Dark = 0; this.AutoPlay_LeftCymbal = 1; this.AutoPlay_HiHat = 1; this.AutoPlay_LeftPedal = 1; this.AutoPlay_Snare = 1; this.AutoPlay_Bass = 1; this.AutoPlay_HighTom = 1; this.AutoPlay_LowTom = 1; this.AutoPlay_FloorTom = 1; this.AutoPlay_RightCymbal = 1; this.MaxRange_Perfect = 0.034; this.MaxRange_Great = 0.067; this.MaxRange_Good = 0.084; this.MaxRange_Ok = 0.117; } public UserConfig( SqliteDataReader user ) : this() { this.UpdateFrom( user ); } public static UserConfig 読み込む( string userId ) { using var _ = new LogBlock( Log.現在のメソッド名 ); var path = new VariablePath( @$"$(AppData)\User_{userId}.yaml" ); var yamlText = File.ReadAllText( path.変数なしパス ); var deserializer = new Deserializer(); var config = deserializer.Deserialize<UserConfig>( yamlText ); if( VERSION != config.Version ) { Log.Info( $"ユーザ設定ファイル[ID={userId}]を新規に作成します。" ); config = new UserConfig() { Id = userId, Name = userId, }; } return config; } /// <summary> /// ファイルに保存する。 /// </summary> public void 保存する() { using var _ = new LogBlock( Log.現在のメソッド名 ); var serializer = new SerializerBuilder() .WithTypeInspector( inner => new CommentGatheringTypeInspector( inner ) ) .WithEmissionPhaseObjectGraphVisitor( args => new CommentsObjectGraphVisitor( args.InnerVisitor ) ) .Build(); // ※ 値が既定値であるプロパティは出力されないので注意。 var path = new VariablePath( @$"$(AppData)\User_{this.Id}.yaml" ); var yaml = serializer.Serialize( this ); File.WriteAllText( path.変数なしパス, yaml ); Log.Info( $"ユーザ設定を保存しました。[{path.変数付きパス}]" ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="user">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader user ) { for( int i = 0; i < user.FieldCount; i++ ) { switch( user.GetName( i ) ) { case "Id": this.Id = user.GetString( i ); break; case "Name": this.Name = user.GetString( i ); break; case "ScrollSpeed": this.ScrollSpeed = user.GetDouble( i ); break; case "Fullscreen": this.Fullscreen = user.GetInt32( i ); break; case "CymbalFree": this.CymbalFree = user.GetInt32( i ); break; case "RideLeft": this.RideLeft = user.GetInt32( i ); break; // v004 case "ChinaLeft": this.ChinaLeft = user.GetInt32( i ); break; // v004 case "SplashLeft": this.SplashLeft = user.GetInt32( i ); break; // v004 case "DrumSound": this.DrumSound = user.GetInt32( i ); break; // v005 case "LaneTrans": this.LaneTrans = user.GetInt32( i ); break; // v007 case "BackgroundMovie": this.BackgroundMovie = user.GetInt32( i ); break; // v008 case "PlaySpeed": this.PlaySpeed = user.GetDouble( i ); break; // v009 case "ShowPartLine": this.ShowPartLine = user.GetInt32( i ); break; // v009 case "ShowPartNumber": this.ShowPartNumber = user.GetInt32( i ); break; // v009 case "ShowScoreWall": this.ShowScoreWall = user.GetInt32( i ); break; // v010 case "BackgroundMovieSize": this.BackgroundMovieSize = user.GetInt32( i ); break; // v010 case "ShowFastSlow": this.ShowFastSlow = user.GetInt32( i ); break; // v011 case "NoteSizeByVolume": this.NoteSizeByVolume = user.GetInt32( i ); break; // v013 case "Dark": this.Dark = user.GetInt32( i ); break; // v013 case "AutoPlay_LeftCymbal": this.AutoPlay_LeftCymbal = user.GetInt32( i ); break; case "AutoPlay_HiHat": this.AutoPlay_HiHat = user.GetInt32( i ); break; case "AutoPlay_LeftPedal": this.AutoPlay_LeftPedal = user.GetInt32( i ); break; case "AutoPlay_Snare": this.AutoPlay_Snare = user.GetInt32( i ); break; case "AutoPlay_Bass": this.AutoPlay_Bass = user.GetInt32( i ); break; case "AutoPlay_HighTom": this.AutoPlay_HighTom = user.GetInt32( i ); break; case "AutoPlay_LowTom": this.AutoPlay_LowTom = user.GetInt32( i ); break; case "AutoPlay_FloorTom": this.AutoPlay_FloorTom = user.GetInt32( i ); break; case "AutoPlay_RightCymbal": this.AutoPlay_RightCymbal = user.GetInt32( i ); break; case "MaxRange_Perfect": this.MaxRange_Perfect = user.GetDouble( i ); break; case "MaxRange_Great": this.MaxRange_Great = user.GetDouble( i ); break; case "MaxRange_Good": this.MaxRange_Good = user.GetDouble( i ); break; case "MaxRange_Ok": this.MaxRange_Ok = user.GetDouble( i ); break; } } } } } <|start_filename|>DTXMania2/ステージ/07演奏/フェーズパネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { class フェーズパネル : IDisposable { // プロパティ /// <summary> /// 現在の位置を 開始点:0~1:終了点 で示す。 /// </summary> public float 現在位置 { get => this._現在位置; set => this._現在位置 = Math.Clamp( value, min: 0.0f, max: 1.0f ); } // 生成と終了 public フェーズパネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._演奏位置カーソル画像 = new 画像D2D( @"$(Images)\PlayStage\PlayPositionCursor.png" ); this._演奏位置カーソルの矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\PlayPositionCursor.yaml" ); this._現在位置 = 0.0f; this._左右三角アニメ用カウンタ = new LoopCounter( 0, 100, 5 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._演奏位置カーソル画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { var 中央位置dpx = new Vector2( 1308f, 876f - this._現在位置 * 767f ); var バー矩形 = this._演奏位置カーソルの矩形リスト[ "Bar" ]!; this._演奏位置カーソル画像.描画する( d2ddc, 中央位置dpx.X - バー矩形.Value.Width / 2f, 中央位置dpx.Y - バー矩形.Value.Height / 2f, 転送元矩形: バー矩形 ); var 左三角矩形 = this._演奏位置カーソルの矩形リスト[ "Left" ]!; this._演奏位置カーソル画像.描画する( d2ddc, 中央位置dpx.X - 左三角矩形.Value.Width / 2f - this._左右三角アニメ用カウンタ.現在値の割合 * 40f, 中央位置dpx.Y - 左三角矩形.Value.Height / 2f, 転送元矩形: 左三角矩形 ); var 右三角矩形 = this._演奏位置カーソルの矩形リスト[ "Right" ]!; this._演奏位置カーソル画像.描画する( d2ddc, 中央位置dpx.X - 右三角矩形.Value.Width / 2f + this._左右三角アニメ用カウンタ.現在値の割合 * 40f, 中央位置dpx.Y - 右三角矩形.Value.Height / 2f, 転送元矩形: 右三角矩形 ); } // ローカル private float _現在位置 = 0.0f; private readonly 画像D2D _演奏位置カーソル画像; private readonly 矩形リスト _演奏位置カーソルの矩形リスト; private readonly LoopCounter _左右三角アニメ用カウンタ; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネル/パネル_システムボタン.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.オプション設定 { /// <summary> /// システム制御用のボタン。「設定完了」「戻る」など。 /// 描画が普通のパネルと違う。 /// </summary> class パネル_システムボタン : パネル { // 生成と終了 public パネル_システムボタン( string パネル名, Action<パネル>? 値の変更処理 = null ) : base( パネル名, 値の変更処理 ) { this._パネル名画像.前景色 = Color.Black; } public override void Dispose() { base.Dispose(); // 忘れずに } // 進行と描画 public override void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置, bool 選択中 ) { float 拡大率Y = (float)this._パネルの高さ割合.Value; float テキストの上下マージン = 72f * ( 1f - 拡大率Y ) / 2f; var テキスト矩形 = new RectangleF( 左位置 + 32f, 上位置 + 12f + テキストの上下マージン, 294f, 72f * 拡大率Y ); // (1) パネルの下地部分の描画。 using( var テキスト背景色 = new SolidColorBrush( d2ddc, Color.LightGray ) ) d2ddc.FillRectangle( テキスト矩形, テキスト背景色 ); // (2) パネル名の描画。 const float 左右マージンの最低値dpx = 20f; float 拡大率X = Math.Min( 1f, ( テキスト矩形.Width - 左右マージンの最低値dpx ) / this._パネル名画像.画像サイズdpx.Width ); this._パネル名画像.描画する( d2ddc, テキスト矩形.Left + ( テキスト矩形.Width - this._パネル名画像.画像サイズdpx.Width * 拡大率X ) / 2f, テキスト矩形.Top + ( テキスト矩形.Height - this._パネル名画像.画像サイズdpx.Height * 拡大率Y ) / 2f, X方向拡大率: 拡大率X, Y方向拡大率: 拡大率Y ); } } } <|start_filename|>FDK/サウンド/Sources/WavOnStreamingWaveSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using CSCore; using CSCore.Codecs.WAV; namespace FDK { /// <summary> /// 指定されたメディアファイルを PCM WAVE としてデコードして、<see cref="CSCore.IWaveSource"/> オブジェクトを生成する。 /// リサンプラーなし版。 /// </summary> public class WavOnStreamingWaveSource : IWaveSource { // プロパティ public bool CanSeek => this._WaveFileReader.CanSeek; public WaveFormat WaveFormat => this._WaveFileReader.WaveFormat; /// <summary> /// 現在の再生位置[byte]。 /// </summary> public long Position { get => this._WaveFileReader.Position; set => this._WaveFileReader.Position = this._位置をブロック境界単位にそろえて返す( value, this.WaveFormat.BlockAlign ); } /// <summary> /// デコード後のオーディオデータのすべての長さ[byte]。 /// </summary> public long Length => this._WaveFileReader.Length; // 生成と終了 public WavOnStreamingWaveSource( VariablePath ファイルパス, WaveFormat deviceFormat ) { this._WaveFileReader = new WaveFileReader( ファイルパス.変数なしパス ); } public virtual void Dispose() { this._WaveFileReader.Dispose(); } // 出力 /// <summary> /// 連続したデータを読み込み、<see cref="Position"/> を読み込んだ数だけ進める。 /// </summary> /// <param name="buffer">読み込んだデータを格納するための配列。</param> /// <param name="offset"><paramref name="buffer"/> に格納を始める位置。</param> /// <param name="count">読み込む最大のデータ数。</param> /// <returns><paramref name="buffer"/> に読み込んだデータの総数。</returns> public int Read( byte[] buffer, int offset, int count ) => this._WaveFileReader.Read( buffer, offset, count ); // ローカル private WaveFileReader _WaveFileReader; private long _位置をブロック境界単位にそろえて返す( long position, long blockAlign ) { return ( position - ( position % blockAlign ) ); } } } <|start_filename|>DTXMania2/ステージ/IStage.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2 { interface IStage : IDisposable { void 進行する(); void 描画する(); } } <|start_filename|>SSTFEditor/Popupメッセージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace SSTFEditor { public partial class Popupメッセージ : Form { public Popupメッセージ( string strメッセージ ) { InitializeComponent(); this.メッセージ = strメッセージ; this.フォント = new Font( "MS PGothic", 10f ); } protected string メッセージ; protected Font フォント; protected void Popupメッセージ_FormClosing( object sender, FormClosingEventArgs e ) { this.フォント?.Dispose(); this.フォント = null; } protected void Popupメッセージ_Load( object sender, EventArgs e ) { base.Location = new Point( base.Owner.Location.X + ( ( base.Owner.Width - base.Width ) / 2 ), base.Owner.Location.Y + ( ( base.Owner.Height - base.Height ) / 2 ) ); } protected void panelメッセージ本文_Paint( object sender, PaintEventArgs e ) { using( var brush = new SolidBrush( Color.Black ) ) { e.Graphics.DrawString( this.メッセージ, this.フォント, brush, new RectangleF( 0f, 0f, (float) this.panelメッセージ本文.ClientSize.Width, (float) this.panelメッセージ本文.ClientSize.Height ), new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Near, } ); } } } } <|start_filename|>DTXMania2/ステージ/07演奏/曲名パネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using FDK; namespace DTXMania2.演奏 { class 曲名パネル : IDisposable { // 生成と終了 public 曲名パネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パネル = new 画像D2D( @"$(Images)\PlayStage\ScoreTitlePanel.png" ); this._既定のノード画像 = new 画像D2D( @"$(Images)\DefaultPreviewImage.png" ); this._現行化前のノード画像 = new 画像D2D( @"$(Images)\PreviewImageWaitForActivation.png" ); this._曲名画像 = new 文字列画像D2D() { フォント名 = "HGMaruGothicMPRO", フォントサイズpt = 26f, フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 4f, 前景色 = Color4.Black, 背景色 = Color4.White, 表示文字列 = Global.App.演奏スコア?.曲名 ?? "", }; this._サブタイトル画像 = new 文字列画像D2D() { フォント名 = "HGMaruGothicMPRO", フォントサイズpt = 18f, フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 3f, 前景色 = Color4.Black, 背景色 = Color4.White, 表示文字列 = Global.App.演奏スコア?.アーティスト名 ?? "", }; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._サブタイトル画像.Dispose(); this._曲名画像.Dispose(); this._現行化前のノード画像.Dispose(); this._既定のノード画像.Dispose(); this._パネル.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { this._パネル.描画する( d2ddc, 1458f, 3f ); this._サムネイルを描画する( d2ddc ); this._曲名を描画する( d2ddc ); this._サブタイトルを描画する( d2ddc ); } // ローカル private readonly 画像D2D _パネル; private readonly 画像D2D _既定のノード画像; private readonly 画像D2D _現行化前のノード画像; private readonly 文字列画像D2D _曲名画像; private readonly 文字列画像D2D _サブタイトル画像; private readonly Vector3 _サムネイル画像表示位置dpx = new Vector3( 1477f, 19f, 0f ); private readonly Vector3 _サムネイル画像表示サイズdpx = new Vector3( 91f, 91f, 0f ); private readonly Vector2 _曲名表示位置dpx = new Vector2( 1576f + 4f, 43f + 0f ); private readonly Vector2 _曲名表示サイズdpx = new Vector2( 331f - 8f - 4f, 70f - 10f ); private void _サムネイルを描画する( DeviceContext d2ddc ) { var サムネイル画像 = Global.App.演奏譜面?.プレビュー画像 ?? this._既定のノード画像; var 変換行列2D = Matrix3x2.Scaling( this._サムネイル画像表示サイズdpx.X / サムネイル画像.サイズ.Width, this._サムネイル画像表示サイズdpx.Y / サムネイル画像.サイズ.Height ) * Matrix3x2.Translation( this._サムネイル画像表示位置dpx.X, this._サムネイル画像表示位置dpx.Y ); サムネイル画像.描画する( d2ddc, 変換行列2D ); } private void _曲名を描画する( DeviceContext d2ddc ) { // 拡大率を計算して描画する。 this._曲名画像.描画する( d2ddc, this._曲名表示位置dpx.X, this._曲名表示位置dpx.Y, X方向拡大率: ( this._曲名画像.画像サイズdpx.Width <= this._曲名表示サイズdpx.X ) ? 1f : this._曲名表示サイズdpx.X / this._曲名画像.画像サイズdpx.Width ); } private void _サブタイトルを描画する( DeviceContext d2ddc ) { // 拡大率を計算して描画する。 this._サブタイトル画像.描画する( d2ddc, this._曲名表示位置dpx.X, this._曲名表示位置dpx.Y + 30f, X方向拡大率: ( this._サブタイトル画像.画像サイズdpx.Width <= this._曲名表示サイズdpx.X ) ? 1f : this._曲名表示サイズdpx.X / this._サブタイトル画像.画像サイズdpx.Width ); } } } <|start_filename|>SSTFEditor/Popupメッセージ.designer.cs<|end_filename|> namespace SSTFEditor { partial class Popupメッセージ { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Popupメッセージ)); this.pictureBoxイラスト = new System.Windows.Forms.PictureBox(); this.panelメッセージ本文 = new System.Windows.Forms.Panel(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxイラスト)).BeginInit(); this.SuspendLayout(); // // pictureBoxイラスト // resources.ApplyResources(this.pictureBoxイラスト, "pictureBoxイラスト"); this.pictureBoxイラスト.Name = "pictureBoxイラスト"; this.pictureBoxイラスト.TabStop = false; // // panelメッセージ本文 // resources.ApplyResources(this.panelメッセージ本文, "panelメッセージ本文"); this.panelメッセージ本文.Name = "panelメッセージ本文"; this.panelメッセージ本文.Paint += new System.Windows.Forms.PaintEventHandler(this.panelメッセージ本文_Paint); // // Popupメッセージ // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.ControlBox = false; this.Controls.Add(this.panelメッセージ本文); this.Controls.Add(this.pictureBoxイラスト); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Name = "Popupメッセージ"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Popupメッセージ_FormClosing); this.Load += new System.EventHandler(this.Popupメッセージ_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxイラスト)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBoxイラスト; private System.Windows.Forms.Panel panelメッセージ本文; } } <|start_filename|>DTXMania2/曲/Tree/曲ツリー_評価順.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2.曲 { class 曲ツリー_評価順 : 曲ツリー { // 生成と終了 /// <summary> /// <see cref="App.全曲リスト"/> を元に、評価順曲ツリーを構築する。 /// </summary> public 曲ツリー_評価順() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.初期化する(); } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); // 全ノードを解放する。 foreach( var node in this.ルートノード.Traverse() ) node.Dispose(); base.Dispose(); } /// <summary> /// ツリーを初期状態に戻す。 /// </summary> public void 初期化する() { // 全ノードを解放する。 foreach( var node in this.ルートノード.Traverse() ) node.Dispose(); this.ルートノード.子ノードリスト.Clear(); // RANDOM SELECT を追加する。 this.ルートノード.子ノードリスト.Add( new RandomSelectNode() { 親ノード = this.ルートノード } ); // 評価BOX を追加する。 var ratingBoxLabel = new[] { Properties.Resources.TXT_評価なし, Properties.Resources.TXT_評価 + " " + Properties.Resources.TXT_評価1, Properties.Resources.TXT_評価 + " " + Properties.Resources.TXT_評価2, Properties.Resources.TXT_評価 + " " + Properties.Resources.TXT_評価3, Properties.Resources.TXT_評価 + " " + Properties.Resources.TXT_評価4, Properties.Resources.TXT_評価 + " " + Properties.Resources.TXT_評価5, }; this._評価BOX = new BoxNode[ 6 ]; // 0~5 for( int i = 0; i < this._評価BOX.Length; i++ ) { this._評価BOX[ i ] = new BoxNode( ratingBoxLabel[ i ] ) { 親ノード = this.ルートノード }; this._評価BOX[ i ].子ノードリスト.Add( new BackNode() { 親ノード = this._評価BOX[ i ] } ); this._評価BOX[ i ].子ノードリスト.Add( new RandomSelectNode() { 親ノード = this._評価BOX[ i ] } ); } for( int i = 0; i < this._評価BOX.Length; i++ ) this.ルートノード.子ノードリスト.Add( this._評価BOX[ this._評価BOX.Length - 1 - i ] ); // ここまで追加したすべてのノードの画像を生成する。(現行化待ち中に表示されるため) foreach( var node in this.ルートノード.Traverse() ) { node.タイトル文字列画像 = 現行化.タイトル文字列画像を生成する( node.タイトル ); node.サブタイトル文字列画像 = 現行化.サブタイトル文字列画像を生成する( node.サブタイトル ); node.ノード画像 = 現行化.ノード画像を生成する( node.ノード画像ファイルの絶対パス ); } // 最初のノードを選択する。 this.フォーカスリスト.SelectFirst(); } /// <summary> /// 現状の <see cref="App.全曲リスト"/> の内容に従って、評価順曲ツリーを再構築する。 /// </summary> public void 再構築する() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.初期化する(); foreach( var song in Global.App.全曲リスト ) { var score = song.譜面リスト?.FirstOrDefault( ( s ) => ( s != null && s.譜面の属性 != null ) ); int rating = score?.譜面の属性?.Rating ?? 0; this._評価BOX[ rating ].子ノードリスト.Add( new SongNode( song ) { 親ノード = this._評価BOX[ rating ] } ); } } protected BoxNode[] _評価BOX = null!; // [0~5] } } <|start_filename|>FDK/入力/HID.cs<|end_filename|> using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace FDK { /// <summary> /// HID (Human Interface Devices) 関連の API /// </summary> public class HID { public enum ReportType : int { Input = 0, Output = 1, Feature = 2, } public enum Status : int { Success = ( 0x0 << 28 ) | ( 0x11 << 16 ) | 0, Null = ( 0x8 << 28 ) | ( 0x11 << 16 ) | 1, InvalidPreparsedData = ( 0xC << 28 ) | ( 0x11 << 16 ) | 1, InvalidReportType = ( 0xC << 28 ) | ( 0x11 << 16 ) | 2, InvalidReportLength = ( 0xC << 28 ) | ( 0x11 << 16 ) | 3, UsageNotFound = ( 0xC << 28 ) | ( 0x11 << 16 ) | 4, ValueOutOfRange = ( 0xC << 28 ) | ( 0x11 << 16 ) | 5, BadLogPhyValues = ( 0xC << 28 ) | ( 0x11 << 16 ) | 6, BufferTooSmall = ( 0xC << 28 ) | ( 0x11 << 16 ) | 7, InternalError = ( 0xC << 28 ) | ( 0x11 << 16 ) | 8, I8042TransUnknown = ( 0xC << 28 ) | ( 0x11 << 16 ) | 9, IncompatibleReportID = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0xA, NotVablueArray = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0xB, IsValueArray = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0xC, DataIndexNotFound = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0xD, DataIndexOutOfRange = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0xE, ButtonNotPressed = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0xF, ReportDoesNotExist = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0x10, NotImplemented = ( 0xC << 28 ) | ( 0x11 << 16 ) | 0x20, } [StructLayout( LayoutKind.Sequential )] public struct Caps { public ushort Usage; public ushort UsagePage; public string UsageName => GetUsageName( this.UsagePage, this.Usage ); public ushort InputReportByteLength; public ushort OutputReportByteLength; public ushort FeatureReportByteLength; [MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U2, SizeConst = 17 )] public ushort[] Reserved; public ushort NumberLinkCollectionNodes; public ushort NumberInputButtonCaps; public ushort NumberInputValueCaps; public ushort NumberInputDataIndices; public ushort NumberOutputButtonCaps; public ushort NumberOutputValueCaps; public ushort NumberOutputDataIndices; public ushort NumberFeatureButtonCaps; public ushort NumberFeatureValueCaps; public ushort NumberFeatureDataIndices; } [StructLayout( LayoutKind.Explicit )] public struct Data { [FieldOffset( 0 )] public ushort DataIndex; [FieldOffset( 2 )] public ushort Reserved; [FieldOffset( 4 )] public uint RawValue; // for values [FieldOffset( 4 ), MarshalAs( UnmanagedType.U1 )] public bool On; // for buttons MUST BE TRUE for buttons. }; [StructLayout( LayoutKind.Explicit )] public struct ButtonCaps { [FieldOffset( 0 )] public ushort UsagePage; public string UsagePageName => GetUsagePageName( this.UsagePage ); [FieldOffset( 2 )] public byte ReportID; [FieldOffset( 3 ), MarshalAs( UnmanagedType.U1 )] public bool IsAlias; [FieldOffset( 4 )] public ushort BitField; [FieldOffset( 6 )] public ushort LinkCollection; [FieldOffset( 8 )] public ushort LinkUsage; [FieldOffset( 10 )] public ushort LinkUsagePage; public string LinkUsageName => GetUsageName( this.LinkUsagePage, this.LinkUsage ); [FieldOffset( 12 ), MarshalAs( UnmanagedType.U1 )] public bool IsRange; [FieldOffset( 13 ), MarshalAs( UnmanagedType.U1 )] public bool IsStringRange; [FieldOffset( 14 ), MarshalAs( UnmanagedType.U1 )] public bool IsDesignatorRange; [FieldOffset( 15 ), MarshalAs( UnmanagedType.U1 )] public bool IsAbsolute; [FieldOffset( 16 ), MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U4, SizeConst = 10 )] public uint[] Reserved; [FieldOffset( 56 )] public ButtonCapsRange Range; [FieldOffset( 56 )] public ButtonCapsNotRange NotRange; public string? NotRangeUsageName => this.IsRange ? null : GetUsageName( this.UsagePage, this.NotRange.Usage ); public ushort UsageMin => this.IsRange ? this.Range.UsageMin : this.NotRange.Usage; } [StructLayout( LayoutKind.Sequential )] public struct ButtonCapsRange { public ushort UsageMin; public ushort UsageMax; public ushort StringMin; public ushort StringMax; public ushort DesignatorMin; public ushort DesignatorMax; public ushort DataIndexMin; public ushort DataIndexMax; } [StructLayout( LayoutKind.Sequential )] public struct ButtonCapsNotRange { public ushort Usage; public ushort Reserved1; public ushort StringIndex; public ushort Reserved2; public ushort DesignatorIndex; public ushort Reserved3; public ushort DataIndex; public ushort Reserved4; } [StructLayout( LayoutKind.Explicit )] public struct ValueCaps { [FieldOffset( 0 )] public ushort UsagePage; public string UsagePageName => GetUsagePageName( this.UsagePage ); [FieldOffset( 2 )] public byte ReportID; [FieldOffset( 3 ), MarshalAs( UnmanagedType.U1 )] public bool IsAlias; [FieldOffset( 4 )] public ushort BitField; [FieldOffset( 6 )] public ushort LinkCollection; [FieldOffset( 8 )] public ushort LinkUsage; [FieldOffset( 10 )] public ushort LinkUsagePage; public string LinkUsageName => GetUsageName( this.LinkUsagePage, this.LinkUsage ); [FieldOffset( 12 ), MarshalAs( UnmanagedType.U1 )] public bool IsRange; [FieldOffset( 13 ), MarshalAs( UnmanagedType.U1 )] public bool IsStringRange; [FieldOffset( 14 ), MarshalAs( UnmanagedType.U1 )] public bool IsDesignatorRange; [FieldOffset( 15 ), MarshalAs( UnmanagedType.U1 )] public bool IsAbsolute; [FieldOffset( 16 ), MarshalAs( UnmanagedType.U1 )] public bool HasNull; [FieldOffset( 17 )] public byte Reserved; [FieldOffset( 18 )] public ushort BitSize; [FieldOffset( 20 )] public ushort ReportCount; [FieldOffset( 22 )] public ushort Reserved2_1; [FieldOffset( 24 )] public ushort Reserved2_2; [FieldOffset( 26 )] public ushort Reserved2_3; [FieldOffset( 28 )] public ushort Reserved2_4; [FieldOffset( 30 )] public ushort Reserved2_5; [FieldOffset( 32 )] public uint UnitsExp; [FieldOffset( 36 )] public uint Units; [FieldOffset( 40 )] public int LogicalMin; [FieldOffset( 44 )] public int LogicalMax; [FieldOffset( 48 )] public int PhysicalMin; [FieldOffset( 52 )] public int PhysicalMax; [FieldOffset( 56 )] public ValueCapsRange Range; [FieldOffset( 56 )] public ValueCapsNotRange NotRange; public string? NotRangeUsageName => this.IsRange ? null : GetUsageName( this.UsagePage, this.NotRange.Usage ); } [StructLayout( LayoutKind.Sequential )] public struct ValueCapsRange { public ushort UsageMin; public ushort UsageMax; public ushort StringMin; public ushort StringMax; public ushort DesignatorMin; public ushort DesignatorMax; public ushort DataIndexMin; public ushort DataIndexMax; } [StructLayout( LayoutKind.Sequential )] public struct ValueCapsNotRange { public ushort Usage; public ushort Reserved1; public ushort StringIndex; public ushort Reserved2; public ushort DesignatorIndex; public ushort Reserved3; public ushort DataIndex; public ushort Reserved4; } [StructLayout( LayoutKind.Sequential )] public struct LinkCollectionNode { public ushort LinkUsage; public ushort LinkUsagePage; public string LinkUsageName => GetUsageName( this.LinkUsagePage, this.LinkUsage ); public ushort Parent; public ushort NumberOfChildren; public ushort NextSibling; public ushort FirstChild; public byte CollectionType; public byte IsAlias; public byte Reserved_1; public byte Reserved_2; public IntPtr UserContext; } [StructLayout( LayoutKind.Sequential )] public struct UsageAndPage { public ushort Usage; public ushort UsagePage; } /// <summary> /// 事前解析データによって指定されるHIDデバイスの能力のリストを返す。 /// </summary> /// <param name="preparsedData"> /// HIDCLASSから返された事前解析データ。 /// </param> /// <param name="capabilities"> /// <see cref="Caps"/>構造体。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_PREPARSED_DATA /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetCaps( IntPtr preparsedData, out Caps capabilities ); /// <summary> /// 指定されたこのHIDデバイスのリンクコレクションツリーを記述する、<see cref="LinkCollectionNode"/> のリストを返す。 /// </summary> /// <param name="linkCollectionNodes"> /// 呼び出し元が割り当てた配列。このメソッドは、情報をそこに格納する。 /// </param> /// <param name="LinkCollectionNodesLength"> /// 呼び出し元は、この値に、配列の要素数を設定すること。このメソッドは、この値を、実際の要素数に設定して返す。 /// このHIDデバイスを記述するために必要とされるノードの総数は、<see cref="Caps.NumberLinkCollectionNodes"/> で確認することができる。 /// </param> /// <param name="preparsedData"> /// HIDCLASSから返された事前解析データ。 /// </param> /// <returns></returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetLinkCollectionNodes( [In, Out] LinkCollectionNode[] linkCollectionNodes, ref uint LinkCollectionNodesLength, IntPtr preparsedData ); /// <summary> /// 指定された制限に該当するすべてのボタン(のバイナリ値)を返す。 /// </summary> /// <param name="reportType"> /// <see cref="ReportType"/>のいずれか。 /// </param> /// <param name="usagePage"> /// 返されるボタン能力は、このUsagePageに制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="linkCollection"> /// 返されるボタン能力は、このリンクコレクション配列のインデックスに制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="usage"> /// 返されるボタン能力は、このUsageに制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="buttonCaps"> /// 指定されたレポート内のすべてのバイナリ値に関する情報を含んだ<see cref="ButtonCaps"/>の配列。 /// この配列は、呼び出し元によって割り当てられる。 /// </param> /// <param name="buttonCapsLength"> /// 入力としては、<paramref name="buttonCaps"/>(配列)の長さを要素単位で指定する。 /// 出力としては、実際に埋められた要素数が返される。 /// 最大数は、<see cref="Caps"/>で調べることができる。 /// <see cref="HID.Status.BufferTooSmall"/>が返された場合、このパラメータには必要とされる要素数が格納されている。 /// </param> /// <param name="preparseData"> /// HIDCLASSから返された事前解析データ。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_REPORT_TYPE /// HIDP_STATUS_INVALID_PREPARSED_DATA /// HIDP_STATUS_BUFFER_TOO_SMALL( all given entries however have been filled in) /// HIDP_STATUS_USAGE_NOT_FOUND /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetSpecificButtonCaps( ReportType reportType, ushort usagePage, ushort linkCollection, ushort usage, [In, Out] ButtonCaps[] buttonCaps, ref ushort buttonCapsLength, IntPtr preparseData ); /// <summary> /// すべてのボタン(のバイナリ値)を返す。 /// </summary> /// <param name="reportType"> /// <see cref="ReportType"/>のいずれか。 /// </param> /// <param name="buttonCaps"> /// 指定されたレポート内のすべてのバイナリ値に関する情報を含んだ<see cref="ButtonCaps"/>の配列。 /// この配列は、呼び出し元によって割り当てられる。 /// </param> /// <param name="buttonCapsLength"> /// 入力としては、<paramref name="buttonCaps"/>(配列)の長さを要素単位で指定する。 /// 出力としては、実際に埋められた要素数が返される。 /// 最大数は、<see cref="Caps"/>で調べることができる。 /// <see cref="HID.Status.BufferTooSmall"/>が返された場合、このパラメータには必要とされる要素数が格納されている。 /// </param> /// <param name="preparseData"> /// HIDCLASSから返された事前解析データ。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_REPORT_TYPE /// HIDP_STATUS_INVALID_PREPARSED_DATA /// HIDP_STATUS_BUFFER_TOO_SMALL( all given entries however have been filled in) /// HIDP_STATUS_USAGE_NOT_FOUND /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetButtonCaps( ReportType reportType, [In, Out] ButtonCaps[] buttonCaps, ref ushort buttonCapsLength, IntPtr preparseData ); /// <summary> /// 指定された制限に該当するすべての値(非バイナリ)を返す。 /// </summary> /// <param name="reportType"> /// <see cref="ReportType"/>のいずれか。 /// </param> /// <param name="usagePage"> /// 返される値能力は、このUsagePageに制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="linkCollection"> /// 返される値能力は、このリンクコレクション配列のインデックスに制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="usage"> /// 返される値能力は、このUsageに制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="valueCaps"> /// 指定されたレポート内のすべての非バイナリ値に関する情報を含んだ<see cref="ValueCaps"/>の配列。 /// この配列は、呼び出し元によって割り当てられる。 /// </param> /// <param name="valueCapsLength"> /// 入力としては、<paramref name="valueCaps"/>(配列)の長さを要素単位で指定する。 /// 出力としては、実際に埋められた要素数が返される。 /// 最大数は、<see cref="Caps"/>で調べることができる。 /// <see cref="HID.Status.BufferTooSmall"/>が返された場合、このパラメータには必要とされる要素数が格納されている。 /// </param> /// <param name="preparsedData"> /// HIDCLASSから返された事前解析データ。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_REPORT_TYPE /// HIDP_STATUS_INVALID_PREPARSED_DATA /// HIDP_STATUS_BUFFER_TOO_SMALL( all given entries however have been filled in) /// HIDP_STATUS_USAGE_NOT_FOUND /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetSpecificValueCaps( ReportType reportType, ushort usagePage, ushort linkCollection, ushort usage, [In, Out] ValueCaps[] valueCaps, ref uint valueCapsLength, IntPtr preparsedData ); /// <summary> /// すべての値(非バイナリ)を返す。 /// </summary> /// <param name="reportType"> /// <see cref="ReportType"/>のいずれか。 /// </param> /// <param name="valueCaps"> /// 指定されたレポート内のすべての非バイナリ値に関する情報を含んだ<see cref="ValueCaps"/>の配列。 /// この配列は、呼び出し元によって割り当てられる。 /// </param> /// <param name="valueCapsLength"> /// 入力としては、<paramref name="valueCaps"/>(配列)の長さを要素単位で指定する。 /// 出力としては、実際に埋められた要素数が返される。 /// 最大数は、<see cref="Caps"/>で調べることができる。 /// <see cref="HID.Status.BufferTooSmall"/>が返された場合、このパラメータには必要とされる要素数が格納されている。 /// </param> /// <param name="preparsedData"> /// HIDCLASSから返された事前解析データ。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_REPORT_TYPE /// HIDP_STATUS_INVALID_PREPARSED_DATA /// HIDP_STATUS_BUFFER_TOO_SMALL( all given entries however have been filled in) /// HIDP_STATUS_USAGE_NOT_FOUND /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetValueCaps( ReportType reportType, [In, Out] ValueCaps[] valueCaps, ref uint valueCapsLength, IntPtr preparsedData ); /// <summary> /// 注意:明確な理由のために、このメソッドは UsageValueArrays にはアクセスしません。 /// </summary> /// <param name="reportType"> /// <see cref="ReportType"/>のいずれか。 /// </param> /// <param name="dataList"> /// <see cref="Data"/>構造体の配列。指定されたレポートのデータ値がここに格納される。 /// </param> /// <param name="dataLength"> /// 入力としては、<paramref name="dataList"/>の要素数を指定する。 /// 出力としては、取得できた要素数が格納される。 /// 要素数の最大値は、<see cref="HidP_MaxDataListLength"/>で取得することができる。 /// </param> /// <param name="preparsedData"> /// HIDCLASSから得られた事前解析データ。 /// </param> /// <param name="report"> /// データが格納されているバッファ。 /// </param> /// <param name="reportLength"> /// レポートの長さ。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_REPORT_TYPE /// HIDP_STATUS_INVALID_PREPARSED_DATA /// HIDP_STATUS_INVALID_REPORT_LENGTH /// HIDP_STATUS_REPORT_DOES_NOT_EXIST /// HIDP_STATUS_BUFFER_TOO_SMALL /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetData( ReportType reportType, [In, Out] Data[] dataList, ref uint dataLength, IntPtr preparsedData, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 5 )] [In, Out] byte[] report, uint reportLength ); /// <summary> /// <see cref="HidP_GetData(ReportType, Data[], ref uint, IntPtr, ref byte[], uint)"/> で返される<see cref="Data"/>要素の最大の長さを返す。 /// </summary> /// <param name="reportType"></param> /// <param name="preparsedData"></param> /// <returns></returns> [DllImport( "hid.dll" )] public static extern uint HidP_MaxDataListLength( ReportType reportType, IntPtr preparsedData ); /// <summary> /// HIDレポート内に設定されているバイナリ値(ボタン)を返す。 /// </summary> /// <param name="reportType"> /// <see cref="ReportType"/>のいずれか。 /// </param> /// <param name="usagePage"> /// 返されるバイナリ値のUsagePage。 /// 複数のUsagePageを指定したい場合には、この関数を複数回呼び出すこと。 /// </param> /// <param name="linkCollection"> /// <paramref name="usageList"/>に返される値は、このリンクコレクション配列インデックス内に存在する値に制限される。 /// 0 を指定した場合、このパラメータは無視される。 /// </param> /// <param name="usageList"> /// レポート内に見つかったすべてのUsageを含む配列。 /// </param> /// <param name="usageLength"> /// 入力としては、<paramref name="usageList"/>の要素数を指定する。 /// 出力としては、見つかったUsageの数が格納される。 /// 最大の要素数は、<see cref="HidP_MaxUsageListLength(ReportType, ushort, IntPtr)"/>で取得することができる。 /// </param> /// <param name="preparsedData"> /// HIDCLASSから得られた事前解析データ。 /// </param> /// <param name="report"> /// レポートパケット。 /// </param> /// <param name="reportLength"> /// レポートパケットの長さ(バイト単位)。 /// </param> /// <returns> /// HIDP_STATUS_SUCCESS /// HIDP_STATUS_INVALID_REPORT_TYPE /// HIDP_STATUS_INVALID_PREPARSED_DATA /// HIDP_STATUS_INVALID_REPORT_LENGTH /// HIDP_STATUS_REPORT_DOES_NOT_EXIST /// HIDP_STATUS_BUFFER_TOO_SMALL /// HIDP_STATUS_INCOMPATIBLE_REPORT_ID /// HIDP_STATUS_USAGE_NOT_FOUND /// </returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetUsages( ReportType reportType, ushort usagePage, ushort linkCollection, [In, Out] ushort[] usageList, ref uint usageLength, IntPtr preparsedData, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 7 )] [In, Out] byte[] report, uint reportLength ); public static Status HidP_GetButtons( ReportType reportType, ushort usagePage, ushort linkCollection, ushort[] usageList, ref uint usageLength, IntPtr preparsedData, byte[] report, uint reportLength ) => HidP_GetUsages( reportType, usagePage, linkCollection, usageList, ref usageLength, preparsedData, report, reportLength ); /// <summary> /// HIDレポート内に設定されているバイナリ値(ボタン)を返す。 /// </summary> /// <param name="reportType"></param> /// <param name="linkCollection"></param> /// <param name="buttonList"></param> /// <param name="usageLength"></param> /// <param name="preparsedData"></param> /// <param name="report"></param> /// <param name="reportLength"></param> /// <returns></returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetUsagesEx( ReportType reportType, ushort linkCollection, [In, Out] UsageAndPage[] buttonList, ref uint usageLength, IntPtr preparsedData, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 6 )] [In] byte[] report, uint reportLength ); public static Status HidP_GetButtonsEx( ReportType reportType, ushort linkCollection, [In, Out] UsageAndPage[] buttonList, ref uint usageLength, IntPtr preparsedData, byte[] report, uint reportLength ) => HidP_GetUsagesEx( reportType, linkCollection, buttonList, ref usageLength, preparsedData, report, reportLength ); /// <summary> /// 指定されたタイプのHIDレポートおよび指定された最上位コレクションに対して、HidP_GetUsages 関数が返すことができるHID Usageの最大数を返します。 /// </summary> /// <param name="reportType"> /// </param> /// <param name="usagePage"> /// オプション。0 を指定すると、コレクション内のUsageの数が返される。 /// </param> /// <param name="preparsedData"> /// </param> /// <returns></returns> [DllImport( "hid.dll" )] public static extern uint HidP_MaxUsageListLength( ReportType reportType, ushort usagePage, IntPtr preparsedData ); /// <summary> /// HIDレポートの選択基準に一致するHID制御値を抽出します。 /// </summary> /// <param name="reportType"></param> /// <param name="usagePage"></param> /// <param name="linkCollection"></param> /// <param name="usage"></param> /// <param name="usageValue"></param> /// <param name="preparsedData"></param> /// <param name="report"></param> /// <param name="reportLength"></param> /// <returns></returns> [DllImport( "hid.dll" )] public static extern Status HidP_GetUsageValue( ReportType reportType, ushort usagePage, ushort linkCollection, ushort usage, out uint usageValue, IntPtr preparsedData, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 7 )] [In] byte[] report, uint reportLength ); /// <summary> /// HIDレポートから抽出された、スケーリング済みの符号付きHID制御値を返します。 /// </summary> /// <param name="reportType"> /// HIDのUsage値を含むHIDレポートのタイプを示す<see cref="ReportType"/>値を指定します。 /// </param> /// <param name="usagePage"> /// 抽出する値のUsagePageを指定します。 /// </param> /// <param name="linkCollection"> /// 抽出する値のリンクコレクション識別子を指定します。 /// 0の場合は、最上位コレクションを示します。 /// </param> /// <param name="usage"> /// 抽出する値のUsageを指定します。 /// </param> /// <param name="usageValue"> /// スケーリング済みの符号付き値が格納されます。 /// </param> /// <param name="preparsedData"> /// レポートを生成した最上位コレクションの事前解析済みデータを指定します。 /// </param> /// <param name="report"> /// Usageを含むレポートを指定します。 /// </param> /// <param name="reportLength"> /// <paramref name="report"/>の長さをバイト単位で指定します。 /// </param> /// <returns></returns> /// <remarks> /// <paramref name="preparsedData"/>, <paramref name="usageValue"/>, および <paramref name="report/> のバッファは、非ページプールから割り当てる必要があります。 /// ユーザーモードアプリケーションとカーネルモードドライバは、HidP_GetUsageValueArray を使用してUsage配列データを抽出する必要があります。 /// 戻り値が <see cref="HID.Status.BadLogPhyValues"/> であった場合、アプリケーションまたはドライバは HidP_GetUsageValue を呼び出して生のUsageデータを抽出できます。 /// 詳しくは <see cref="https://technet.microsoft.com/ru-ru/ff539861(v=vs.110)">HIDコレクション</see>を参照してください。 /// </remarks> [DllImport( "hid.dll" )] public static extern Status HidP_GetScaledUsageValue( ReportType reportType, ushort usagePage, ushort linkCollection, ushort usage, out int usageValue, IntPtr preparsedData, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 7 )] [In] byte[] report, uint reportLength ); [DllImport( "hid.dll" )] public static extern Status HidP_GetUsageValueArray( ReportType reportType, ushort usagePage, ushort linkCollection, ushort usage, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 5 )] [In, Out] byte[] usageValue, ushort usageValueByteLength, IntPtr preparsedData, [MarshalAs( UnmanagedType.LPArray, SizeParamIndex = 8 )] [In] byte[] report, uint reportLength ); /// <summary> /// 2つの HID Usage 配列を比較し、その差異を返す。 /// </summary> /// <param name="previousUsageList">前回のUsage配列。</param> /// <param name="currentUsageList">今回のUsage配列。</param> /// <param name="breakUsageList">前回にはあるけど今回にはないUsageの配列が格納される。</param> /// <param name="makeUsageList">今回にはあるけど前回にはないUsageの配列が格納される。</param> /// <param name="UsageListLength">配列の要素数。前回と今回で要素数が異なるなら、大きいほうを指定すること。</param> /// <returns></returns> /// <remarks> /// 配列中に 0 の Usage があると、それ以降は解釈されない。この場合、未解釈の出力 Usage は 0 に設定される。 /// </remarks> [DllImport( "hid.dll" )] public static extern Status HidP_UsageListDifference( [In] ushort[] previousUsageList, [In] ushort[] currentUsageList, [In, Out] ushort[] breakUsageList, [In, Out] ushort[] makeUsageList, uint UsageListLength ); [DllImport( "hid.dll" )] public static extern Status HidP_UsageAndPageListDifference( [In] UsageAndPage[] previousUsageList, [In] UsageAndPage[] currentUsageList, [In, Out] UsageAndPage[] breakUsageList, [In, Out] UsageAndPage[] makeUsageList, uint usageListLength ); public static string GetUsagePageName( ushort usagePage ) { return ( _UsagePageName.ContainsKey( usagePage ) ) ? _UsagePageName[ usagePage ] : $"{usagePage:X4}"; } public static string GetUsageName( uint extendedUsage ) => GetUsageName( (ushort)( ( extendedUsage >> 16 ) & 0xFFFF ), (ushort)( extendedUsage & 0xFFFF ) ); public static string GetUsageName( ushort usagePage, ushort usageId ) { uint extendedUsage = (uint)( usagePage << 16 ) | (ushort)usageId; return ( _UsageName.ContainsKey( extendedUsage ) ) ? _UsageName[ extendedUsage ] : $"{usagePage:X4} {usageId:X4}"; } private static readonly Dictionary<ushort, string> _UsagePageName = new Dictionary<ushort, string>() { #region " *** " //---------------- { 0x0001, "Generic Desktop Page" }, { 0x0002, "Simulation Controls Page" }, { 0x0003, "VR Controls Page" }, { 0x0004, "Sport Control Page" }, { 0x0005, "Game Control Page" }, { 0x0006, "Generic Device Controls Page" }, { 0x0007, "Keyboard/Keypad Page" }, { 0x0008, "LED Page" }, { 0x0009, "Button Page" }, { 0x000A, "Ordinal Page" }, { 0x000B, "Telephony Device Page" }, { 0x000C, "Consumer Page" }, { 0x000D, "Digitizers Page" }, { 0x0014, "Alphanumeric Display Page" }, { 0x0040, "Medical Instrument Page" }, //---------------- #endregion }; /// <summary> /// Extended Usage (上位2バイトがUsagePage, 下位2バイトがUsageID)と名前との対応表。 /// </summary> private static readonly Dictionary<uint, string> _UsageName = new Dictionary<uint, string>() { #region " 0x01: Generic Desktop Page " //---------------- { 0x0001_0000, "Undefined" }, { 0x0001_0001, "Pointer" }, { 0x0001_0002, "Mouse" }, { 0x0001_0004, "Joystick" }, { 0x0001_0005, "Game Pad" }, { 0x0001_0006, "Keyboard" }, { 0x0001_0007, "Keypad" }, { 0x0001_0008, "Multi-axis Controller" }, { 0x0001_0009, "Tablet PC System Controls" }, { 0x0001_0030, "X" }, { 0x0001_0031, "Y" }, { 0x0001_0032, "Z" }, { 0x0001_0033, "Rx" }, { 0x0001_0034, "Ry" }, { 0x0001_0035, "Rz" }, { 0x0001_0036, "Slider" }, { 0x0001_0037, "Dial" }, { 0x0001_0038, "Wheel" }, { 0x0001_0039, "Hat switch" }, { 0x0001_003A, "Counted Buffer" }, { 0x0001_003B, "Byte Count" }, { 0x0001_003C, "Motion Wakeup" }, { 0x0001_003D, "Start" }, { 0x0001_003E, "Select" }, { 0x0001_0040, "Vx" }, { 0x0001_0041, "Vy" }, { 0x0001_0042, "Vz" }, { 0x0001_0043, "Vbrx" }, { 0x0001_0044, "Vbry" }, { 0x0001_0045, "Vbrz" }, { 0x0001_0046, "Vno" }, { 0x0001_0047, "Feature Notification" }, { 0x0001_0048, "Resolution Multiplier" }, { 0x0001_0080, "System Control" }, { 0x0001_0081, "System Power Down" }, { 0x0001_0082, "System Sleep" }, { 0x0001_0083, "System Wake Up" }, { 0x0001_0084, "System Context Menu" }, { 0x0001_0085, "System Main Menu" }, { 0x0001_0086, "System App Menu" }, { 0x0001_0087, "System Menu Help" }, { 0x0001_0088, "System Menu Exit" }, { 0x0001_0089, "System Menu Select" }, { 0x0001_008A, "System Menu Right" }, { 0x0001_008B, "System Menu Left" }, { 0x0001_008C, "System Menu Up" }, { 0x0001_008D, "System Menu Down" }, { 0x0001_008E, "System Cold Restart" }, { 0x0001_008F, "System Warm Restart" }, { 0x0001_0090, "D-pad Up" }, { 0x0001_0091, "D-pad Down" }, { 0x0001_0092, "D-pad Right" }, { 0x0001_0093, "D-pad Left" }, { 0x0001_00A0, "System Dock" }, { 0x0001_00A1, "System Undock" }, { 0x0001_00A2, "System Setup" }, { 0x0001_00A3, "System Break" }, { 0x0001_00A4, "System Debugger Break" }, { 0x0001_00A5, "Application Break" }, { 0x0001_00A6, "Application Debugger Break" }, { 0x0001_00A7, "System Speaker Mute" }, { 0x0001_00A8, "System Hibernate" }, { 0x0001_00B0, "System Display Invert" }, { 0x0001_00B1, "System Display Internal" }, { 0x0001_00B2, "System Display External" }, { 0x0001_00B3, "System Display Both" }, { 0x0001_00B4, "System Display Dual" }, { 0x0001_00B5, "System Display Toggle Int/Ext" }, { 0x0001_00B6, "System Display Swap Primary/Secondary" }, { 0x0001_00B7, "System Display LCD Autoscale" }, //---------------- #endregion #region " 0x02: Simulation Controls Page " //---------------- { 0x0002_0000, "Undefined" }, { 0x0002_0001, "Flight Simulation Device" }, { 0x0002_0002, "Automobile Simulation Device" }, { 0x0002_0003, "Tank Simulation Device" }, { 0x0002_0004, "Spaceship Simulation Device" }, { 0x0002_0005, "Submarine Simulation Device" }, { 0x0002_0006, "Salling Simulation Device" }, { 0x0002_0007, "Motorcycle Simulation Device" }, { 0x0002_0008, "Sports Simulation Device" }, { 0x0002_0009, "Airplane Simulation Device" }, { 0x0002_000A, "Helicopter Simulation Device" }, { 0x0002_000B, "Magic Carpet Simulation Device" }, { 0x0002_000C, "Bicycle Simulation Device" }, { 0x0002_0020, "Flight Control Stick" }, { 0x0002_0021, "Flight Stick" }, { 0x0002_0022, "Cyclic Control" }, { 0x0002_0023, "Cyclic Trim" }, { 0x0002_0024, "Flight Yoke" }, { 0x0002_0025, "Track Control" }, { 0x0002_00B0, "Aileron" }, { 0x0002_00B1, "Aileron Trim" }, { 0x0002_00B2, "Anti-Torque Control" }, { 0x0002_00B3, "Autopilot Enable" }, { 0x0002_00B4, "Chaff Release" }, { 0x0002_00B5, "Collective Control" }, { 0x0002_00B6, "Dive Brake" }, { 0x0002_00B7, "Electronic Countermeasures" }, { 0x0002_00B8, "Elevator" }, { 0x0002_00B9, "Elevator Trim" }, { 0x0002_00BA, "Rudder" }, { 0x0002_00BB, "Throttle" }, { 0x0002_00BC, "Flight Communications" }, { 0x0002_00BD, "Flare Release" }, { 0x0002_00BE, "Landing Gear" }, { 0x0002_00BF, "Toe Break" }, { 0x0002_00C0, "Trigger" }, { 0x0002_00C1, "Weapons Arm" }, { 0x0002_00C2, "Weapons Select" }, { 0x0002_00C3, "Wing Flaps" }, { 0x0002_00C4, "Accelerator" }, { 0x0002_00C5, "Brake" }, { 0x0002_00C6, "Clutch" }, { 0x0002_00C7, "Shifter" }, { 0x0002_00C8, "Steering" }, { 0x0002_00C9, "Turret Direction" }, { 0x0002_00CA, "Barrel Elevation" }, { 0x0002_00CB, "Dive Plane" }, { 0x0002_00CC, "Ballast" }, { 0x0002_00CD, "Bicycle Crank" }, { 0x0002_00CE, "Handle Bars" }, { 0x0002_00CF, "Front Brake" }, { 0x0002_00D0, "Rear Brake" }, //---------------- #endregion #region " 0x03: VR Controls Page " //---------------- { 0x0003_0000, "Undefined" }, { 0x0003_0001, "Belt" }, { 0x0003_0002, "Body Suit" }, { 0x0003_0003, "Flexor" }, { 0x0003_0004, "Glove" }, { 0x0003_0005, "Head Tracker" }, { 0x0003_0006, "Head Mounted Display" }, { 0x0003_0007, "Hand Tracker" }, { 0x0003_0008, "Occulometer" }, { 0x0003_0009, "Vest" }, { 0x0003_000A, "Animatronic Device" }, { 0x0003_0020, "Stereo Enable" }, { 0x0003_0021, "Display Enable" }, //---------------- #endregion #region " 0x04: Sport Controls Page " //---------------- { 0x0004_0000, "Undefined" }, { 0x0004_0001, "Baseball Bat" }, { 0x0004_0002, "Golf Club" }, { 0x0004_0003, "Rowing Machine" }, { 0x0004_0004, "Treadmill" }, { 0x0004_0030, "Oar" }, { 0x0004_0031, "Slope" }, { 0x0004_0032, "Rate" }, { 0x0004_0033, "Stick Speed" }, { 0x0004_0034, "Stick Face Angle" }, { 0x0004_0035, "Stick Heel/Toe" }, { 0x0004_0036, "Stick Follow Through" }, { 0x0004_0037, "Stick Tempo" }, { 0x0004_0038, "Stick Type" }, { 0x0004_0039, "Stick Height" }, { 0x0004_0050, "Putter" }, { 0x0004_0051, "1 Iron" }, { 0x0004_0052, "2 Iron" }, { 0x0004_0053, "3 Iron" }, { 0x0004_0054, "4 Iron" }, { 0x0004_0055, "5 Iron" }, { 0x0004_0056, "6 Iron" }, { 0x0004_0057, "7 Iron" }, { 0x0004_0058, "8 Iron" }, { 0x0004_0059, "9 Iron" }, { 0x0004_005A, "10 Iron" }, { 0x0004_005B, "11 Iron" }, { 0x0004_005C, "Sand Wedge" }, { 0x0004_005D, "Loft Wedge" }, { 0x0004_005E, "Power Wedge" }, { 0x0004_005F, "1 Wood" }, { 0x0004_0060, "3 Wood" }, { 0x0004_0061, "5 Wood" }, { 0x0004_0062, "7 Wood" }, { 0x0004_0063, "9 Wood" }, //---------------- #endregion #region " 0x05: Game Control Page " //---------------- { 0x0005_0000, "Undefined" }, { 0x0005_0001, "3D Game Controller" }, { 0x0005_0002, "Pinball Device" }, { 0x0005_0003, "Gun Device" }, { 0x0005_0020, "Point of View" }, { 0x0005_0021, "Turn Right/Left" }, { 0x0005_0022, "Pitch Forward/Backward" }, { 0x0005_0023, "Roll Right/Left" }, { 0x0005_0024, "Move Right/Left" }, { 0x0005_0025, "Move Forward/Backward" }, { 0x0005_0026, "Move Up/Down" }, { 0x0005_0027, "Lean Right/Left" }, { 0x0005_0028, "Lean Forward/Backward" }, { 0x0005_0029, "Height of POV" }, { 0x0005_002A, "Flipper" }, { 0x0005_002B, "Secondary Flipper" }, { 0x0005_002C, "Bump" }, { 0x0005_002D, "New Game" }, { 0x0005_002E, "Shoot Ball" }, { 0x0005_002F, "Player" }, { 0x0005_0030, "Gun Bolt" }, { 0x0005_0031, "Gun Clip" }, { 0x0005_0032, "Gun Selector" }, { 0x0005_0033, "Gun Single Shot" }, { 0x0005_0034, "Gun Burst" }, { 0x0005_0035, "Gun Automatic" }, { 0x0005_0036, "Gun Safety" }, { 0x0005_0037, "Gamepad Fire/Jump" }, { 0x0005_0039, "Gamepad Trigger" }, //---------------- #endregion #region " 0x06: Generic Device Controls Page " //---------------- { 0x0006_0000, "Undefined" }, { 0x0006_0020, "Battery Strength" }, { 0x0006_0021, "Wireless Channel" }, { 0x0006_0022, "Wireless ID" }, { 0x0006_0023, "Discover Wireless Control" }, { 0x0006_0024, "Security Code Character Entered" }, { 0x0006_0025, "Security Code Character Erased" }, { 0x0006_0026, "Security Code Cleared" }, //---------------- #endregion #region " 0x07: Keyboard/Keypad Page " //---------------- { 0x0007_0000, "Reserved (no event indicated)" }, { 0x0007_0001, "Keyboard ErrorRollOver" }, { 0x0007_0002, "Keyboard POSTFail" }, { 0x0007_0003, "Keyboard ErrorUndefined" }, { 0x0007_0004, "Keyboard a and A" }, { 0x0007_0005, "Keyboard b and B" }, { 0x0007_0006, "Keyboard c and C" }, { 0x0007_0007, "Keyboard d and D" }, { 0x0007_0008, "Keyboard e and E" }, { 0x0007_0009, "Keyboard f and F" }, { 0x0007_000A, "Keyboard g and G" }, { 0x0007_000B, "Keyboard h and H" }, { 0x0007_000C, "Keyboard i and I" }, { 0x0007_000D, "Keyboard j and J" }, { 0x0007_000E, "Keyboard k and K" }, { 0x0007_000F, "Keyboard l and L" }, { 0x0007_0010, "Keyboard m and M" }, { 0x0007_0011, "Keyboard n and N" }, { 0x0007_0012, "Keyboard o and O" }, { 0x0007_0013, "Keyboard p and P" }, { 0x0007_0014, "Keyboard q and Q" }, { 0x0007_0015, "Keyboard r and R" }, { 0x0007_0016, "Keyboard s and S" }, { 0x0007_0017, "Keyboard t and T" }, { 0x0007_0018, "Keyboard u and U" }, { 0x0007_0019, "Keyboard v and V" }, { 0x0007_001A, "Keyboard w and W" }, { 0x0007_001B, "Keyboard x and X" }, { 0x0007_001C, "Keyboard y and Y" }, { 0x0007_001D, "Keyboard z and Z" }, { 0x0007_001E, "Keyboard 1 and !" }, { 0x0007_001F, "Keyboard 2 and @" }, { 0x0007_0020, "Keyboard 3 and #" }, { 0x0007_0021, "Keyboard 4 and $" }, { 0x0007_0022, "Keyboard 5 and %" }, { 0x0007_0023, "Keyboard 6 and ^" }, { 0x0007_0024, "Keyboard 7 and &" }, { 0x0007_0025, "Keyboard 8 and *" }, { 0x0007_0026, "Keyboard 9 and (" }, { 0x0007_0027, "Keyboard 0 and )" }, { 0x0007_0028, "Keyboard Return (ENTER)" }, { 0x0007_0029, "Keyboard ESCAPE" }, { 0x0007_002A, "Keyboard DELETE (Backspace)" }, { 0x0007_002B, "Keyboard Tab" }, { 0x0007_002C, "Keyboard Spacebar" }, { 0x0007_002D, "Keyboard - and (underscore)" }, { 0x0007_002E, "Keyboard = and +" }, { 0x0007_002F, "Keyboard [ and {" }, { 0x0007_0030, "Keyboard ] and }" }, { 0x0007_0031, "Keyboard \\ and |" }, { 0x0007_0032, "Keyboard Non-US # and ~" }, { 0x0007_0033, "Keyboard ; and :" }, { 0x0007_0034, "Keyboard ` and \"" }, { 0x0007_0035, "Keyboard Grave Accent and Tilde" }, { 0x0007_0036, "Keyboard , and <" }, { 0x0007_0037, "Keyboard . and >" }, { 0x0007_0038, "Keyboard / and ?" }, { 0x0007_0039, "Keyboard Caps Lock" }, { 0x0007_003A, "Keyboard F1" }, { 0x0007_003B, "Keyboard F2" }, { 0x0007_003C, "Keyboard F3" }, { 0x0007_003D, "Keyboard F4" }, { 0x0007_003E, "Keyboard F5" }, { 0x0007_003F, "Keyboard F6" }, { 0x0007_0040, "Keyboard F7" }, { 0x0007_0041, "Keyboard F8" }, { 0x0007_0042, "Keyboard F9" }, { 0x0007_0043, "Keyboard F10" }, { 0x0007_0044, "Keyboard F11" }, { 0x0007_0045, "Keyboard F12" }, { 0x0007_0046, "Keyboard PrintScreen" }, { 0x0007_0047, "Keyboard Scroll Lock" }, { 0x0007_0048, "Keyboard Pause" }, { 0x0007_0049, "Keyboard Insert" }, { 0x0007_004A, "Keyboard Home" }, { 0x0007_004B, "Keyboard PageUp" }, { 0x0007_004C, "Keyboard Delete Forward" }, { 0x0007_004D, "Keyboard End" }, { 0x0007_004E, "Keyboard PageDown" }, { 0x0007_004F, "Keyboard RightArrow" }, { 0x0007_0050, "Keyboard LeftArrow" }, { 0x0007_0051, "Keyboard DownArrow" }, { 0x0007_0052, "Keyboard UpArrow" }, { 0x0007_0053, "Keypad Num Lock and Clear" }, { 0x0007_0054, "Keypad /" }, { 0x0007_0055, "Keypad *" }, { 0x0007_0056, "Keypad -" }, { 0x0007_0057, "Keypad +" }, { 0x0007_0058, "Keypad ENTER" }, { 0x0007_0059, "Keypad 1 and End" }, { 0x0007_005A, "Keypad 2 and Down Arrow" }, { 0x0007_005B, "Keypad 3 and PageDn" }, { 0x0007_005C, "Keypad 4 and Left Arrow" }, { 0x0007_005D, "Keypad 5" }, { 0x0007_005E, "Keypad 6 and Right Arrow" }, { 0x0007_005F, "Keypad 7 and Home" }, { 0x0007_0060, "Keypad 8 and Up Arrow" }, { 0x0007_0061, "Keypad 9 and PageUp" }, { 0x0007_0062, "Keypad 0 and Insert" }, { 0x0007_0063, "Keypad . and Delete" }, { 0x0007_0064, "Keyboard Non-US \\ and |" }, { 0x0007_0065, "Keyboard Application" }, { 0x0007_0066, "Keyboard Power" }, { 0x0007_0067, "Keypad =" }, { 0x0007_0068, "Keyboard F13" }, { 0x0007_0069, "Keyboard F14" }, { 0x0007_006A, "Keyboard F15" }, { 0x0007_006B, "Keyboard F16" }, { 0x0007_006C, "Keyboard F17" }, { 0x0007_006D, "Keyboard F18" }, { 0x0007_006E, "Keyboard F19" }, { 0x0007_006F, "Keyboard F20" }, { 0x0007_0070, "Keyboard F21" }, { 0x0007_0071, "Keyboard F22" }, { 0x0007_0072, "Keyboard F23" }, { 0x0007_0073, "Keyboard F24" }, { 0x0007_0074, "Keyboard Execute" }, { 0x0007_0075, "Keyboard Help" }, { 0x0007_0076, "Keyboard Menu" }, { 0x0007_0077, "Keyboard Select" }, { 0x0007_0078, "Keyboard Stop" }, { 0x0007_0079, "Keyboard Again" }, { 0x0007_007A, "Keyboard Undo" }, { 0x0007_007B, "Keyboard Cut" }, { 0x0007_007C, "Keyboard Copy" }, { 0x0007_007D, "Keyboard Paste" }, { 0x0007_007E, "Keyboard Find" }, { 0x0007_007F, "Keyboard Mute" }, { 0x0007_0080, "Keyboard Volume Up" }, { 0x0007_0081, "Keyboard Volume Down" }, { 0x0007_0082, "Keyboard Locking Caps Lock" }, { 0x0007_0083, "Keyboard Locking Num Lock" }, { 0x0007_0084, "Keyboard Locking Scroll Lock" }, { 0x0007_0085, "Keyboard Comma" }, { 0x0007_0086, "Keyboard Equal Sign" }, { 0x0007_0087, "Keyboard International1" }, { 0x0007_0088, "Keyboard International2" }, { 0x0007_0089, "Keyboard International3" }, { 0x0007_008A, "Keyboard International4" }, { 0x0007_008B, "Keyboard International5" }, { 0x0007_008C, "Keyboard International6" }, { 0x0007_008D, "Keyboard International7" }, { 0x0007_008E, "Keyboard International8" }, { 0x0007_008F, "Keyboard International9" }, { 0x0007_0090, "Keyboard LANG1" }, { 0x0007_0091, "Keyboard LANG2" }, { 0x0007_0092, "Keyboard LANG3" }, { 0x0007_0093, "Keyboard LANG4" }, { 0x0007_0094, "Keyboard LANG5" }, { 0x0007_0095, "Keyboard LANG6" }, { 0x0007_0096, "Keyboard LANG7" }, { 0x0007_0097, "Keyboard LANG8" }, { 0x0007_0098, "Keyboard LANG9" }, { 0x0007_0099, "Keyboard Alternate Erase" }, { 0x0007_009A, "Keyboard SysReq/Attention" }, { 0x0007_009B, "Keyboard Cancel" }, { 0x0007_009C, "Keyboard Clear" }, { 0x0007_009D, "Keyboard Prior" }, { 0x0007_009E, "Keyboard Return" }, { 0x0007_009F, "Keyboard Separator" }, { 0x0007_00A0, "Keyboard Out" }, { 0x0007_00A1, "Keyboard Oper" }, { 0x0007_00A2, "Keyboard Clear/Again" }, { 0x0007_00A3, "Keyboard CrSel/Props" }, { 0x0007_00A4, "Keyboard ExSel" }, { 0x0007_00B0, "Keypad 00" }, { 0x0007_00B1, "Keypad 000" }, { 0x0007_00B2, "Thousands Separator" }, { 0x0007_00B3, "Decimal Separator" }, { 0x0007_00B4, "Currency Unit" }, { 0x0007_00B5, "Currency Sub-unit" }, { 0x0007_00B6, "Keypad (" }, { 0x0007_00B7, "Keypad )" }, { 0x0007_00B8, "Keypad {" }, { 0x0007_00B9, "Keypad }" }, { 0x0007_00BA, "Keypad Tab" }, { 0x0007_00BB, "Keypad Backspace" }, { 0x0007_00BC, "Keypad A" }, { 0x0007_00BD, "Keypad B" }, { 0x0007_00BE, "Keypad C" }, { 0x0007_00BF, "Keypad D" }, { 0x0007_00C0, "Keypad E" }, { 0x0007_00C1, "Keypad F" }, { 0x0007_00C2, "Keypad XOR" }, { 0x0007_00C3, "Keypad ^" }, { 0x0007_00C4, "Keypad %" }, { 0x0007_00C5, "Keypad <" }, { 0x0007_00C6, "Keypad >" }, { 0x0007_00C7, "Keypad &" }, { 0x0007_00C8, "Keypad &&" }, { 0x0007_00C9, "Keypad |" }, { 0x0007_00CA, "Keypad ||" }, { 0x0007_00CB, "Keypad :" }, { 0x0007_00CC, "Keypad #" }, { 0x0007_00CD, "Keypad Space" }, { 0x0007_00CE, "Keypad @" }, { 0x0007_00CF, "Keypad !" }, { 0x0007_00D0, "Keypad Memory Store" }, { 0x0007_00D1, "Keypad Memory Recall" }, { 0x0007_00D2, "Keypad Memory Clear" }, { 0x0007_00D3, "Keypad Memory Add" }, { 0x0007_00D4, "Keypad Memory Subtract" }, { 0x0007_00D5, "Keypad Memory Multiply" }, { 0x0007_00D6, "Keypad Memory Divide" }, { 0x0007_00D7, "Keypad +/-" }, { 0x0007_00D8, "Keypad Clear" }, { 0x0007_00D9, "Keypad Clear Entry" }, { 0x0007_00DA, "Keypad Binary" }, { 0x0007_00DB, "Keypad Octal" }, { 0x0007_00DC, "Keypad Decimal" }, { 0x0007_00DD, "Keypad Hexadecimal" }, { 0x0007_00E0, "Keyboard LeftControl" }, { 0x0007_00E1, "Keyboard LeftShift" }, { 0x0007_00E2, "Keyboard LeftAlt" }, { 0x0007_00E3, "Keyboard Left GUI" }, { 0x0007_00E4, "Keyboard RightControl" }, { 0x0007_00E5, "Keyboard RightShift" }, { 0x0007_00E6, "Keyboard RightAlt" }, { 0x0007_00E7, "Keyboard Right GUI" }, //---------------- #endregion #region " 0x08: LED Page " //---------------- { 0x0008_0000, "Undefined" }, { 0x0008_0001, "Num Lock" }, { 0x0008_0002, "Caps Lock" }, { 0x0008_0003, "Scroll Lock" }, { 0x0008_0004, "Compose" }, { 0x0008_0005, "Kana" }, { 0x0008_0006, "Power" }, { 0x0008_0007, "Shift" }, { 0x0008_0008, "Do Not Disturb" }, { 0x0008_0009, "Mute" }, { 0x0008_000A, "Tone Enable" }, { 0x0008_000B, "High Cut Filter" }, { 0x0008_000C, "Low Cut Filter" }, { 0x0008_000D, "Equalizer Enable" }, { 0x0008_000E, "Sound Field On" }, { 0x0008_000F, "Surround On" }, { 0x0008_0010, "Repear" }, { 0x0008_0011, "Stereo" }, { 0x0008_0012, "Sampling Rate Detect" }, { 0x0008_0013, "Spinning" }, { 0x0008_0014, "CAV" }, { 0x0008_0015, "CLV" }, { 0x0008_0016, "Recording Format Detect" }, { 0x0008_0017, "Off-Hook" }, { 0x0008_0018, "Ring" }, { 0x0008_0019, "Message Waiting" }, { 0x0008_001A, "Data Mode" }, { 0x0008_001B, "Battery Operation" }, { 0x0008_001C, "Battery OK" }, { 0x0008_001D, "Battery Low" }, { 0x0008_001E, "Speaker" }, { 0x0008_001F, "Head Set" }, { 0x0008_0020, "Hold" }, { 0x0008_0021, "Microphone" }, { 0x0008_0022, "Coverage" }, { 0x0008_0023, "Night Mode" }, { 0x0008_0024, "Send Calls" }, { 0x0008_0025, "Call Pickup" }, { 0x0008_0026, "Conference" }, { 0x0008_0027, "Stand-by" }, { 0x0008_0028, "Camera On" }, { 0x0008_0029, "Camera Off" }, { 0x0008_002A, "On-Line" }, { 0x0008_002B, "Off-Line" }, { 0x0008_002C, "Busy" }, { 0x0008_002D, "Ready" }, { 0x0008_002E, "Paper-Out" }, { 0x0008_002F, "Paper-Jam" }, { 0x0008_0030, "Remote" }, { 0x0008_0031, "Forward" }, { 0x0008_0032, "Reverse" }, { 0x0008_0033, "Stop" }, { 0x0008_0034, "Rewind" }, { 0x0008_0035, "Fast Forward" }, { 0x0008_0036, "Play" }, { 0x0008_0037, "Pause" }, { 0x0008_0038, "Record" }, { 0x0008_0039, "Error" }, { 0x0008_003A, "Usage Selected Indicator" }, { 0x0008_003B, "Usage In Use Indicator" }, { 0x0008_003C, "Usage Multi Mode Indicator" }, { 0x0008_003D, "Indicator On" }, { 0x0008_003E, "Indicator Flash" }, { 0x0008_003F, "Indicator Slow Blink" }, { 0x0008_0040, "Indicator Fast Blink" }, { 0x0008_0041, "Indicator Off" }, { 0x0008_0042, "Flash On Time" }, { 0x0008_0043, "Slow Blink On Time" }, { 0x0008_0044, "Slow Blink Off Time" }, { 0x0008_0045, "Fast Blink On Time" }, { 0x0008_0046, "Fast Blink Off Time" }, { 0x0008_0047, "Usage Indicator Color" }, { 0x0008_0048, "Indicator Red" }, { 0x0008_0049, "Indicator Green" }, { 0x0008_004A, "Indicator Amber" }, { 0x0008_004B, "Generic Indicator" }, { 0x0008_004C, "System Suspend" }, { 0x0008_004D, "External Power Connected" }, //---------------- #endregion #region " 0x09: Button Page " //---------------- { 0x0009_0000, "No Button pressed" }, { 0x0009_0001, "Button 1 (primary/trigger)" }, { 0x0009_0002, "Button 2 (secondary)" }, { 0x0009_0003, "Button 3 (tertiary)" }, { 0x0009_0004, "Button 4" }, { 0x0009_0005, "Button 5" }, { 0x0009_0006, "Button 6" }, { 0x0009_0007, "Button 7" }, { 0x0009_0008, "Button 8" }, { 0x0009_0009, "Button 9" }, { 0x0009_000A, "Button 10" }, { 0x0009_000B, "Button 11" }, { 0x0009_000C, "Button 12" }, { 0x0009_000D, "Button 13" }, { 0x0009_000E, "Button 14" }, { 0x0009_000F, "Button 15" }, { 0x0009_0010, "Button 16" }, { 0x0009_0011, "Button 17" }, { 0x0009_0012, "Button 18" }, { 0x0009_0013, "Button 19" }, { 0x0009_0014, "Button 20" }, { 0x0009_0015, "Button 21" }, { 0x0009_0016, "Button 22" }, { 0x0009_0017, "Button 23" }, { 0x0009_0018, "Button 24" }, { 0x0009_0019, "Button 25" }, { 0x0009_001A, "Button 26" }, { 0x0009_001B, "Button 27" }, { 0x0009_001C, "Button 28" }, { 0x0009_001D, "Button 29" }, { 0x0009_001E, "Button 30" }, { 0x0009_001F, "Button 31" }, { 0x0009_0020, "Button 32" }, //---------------- #endregion #region " 0x0A: Ordinal Page " //---------------- { 0x000A_0000, "Reserved" }, { 0x000A_0001, "Instance 1" }, { 0x000A_0002, "Instance 2" }, { 0x000A_0003, "Instance 3" }, { 0x000A_0004, "Instance 4" }, { 0x000A_0005, "Instance 5" }, { 0x000A_0006, "Instance 6" }, { 0x000A_0007, "Instance 7" }, { 0x000A_0008, "Instance 8" }, { 0x000A_0009, "Instance 9" }, { 0x000A_000A, "Instance 10" }, { 0x000A_000B, "Instance 11" }, { 0x000A_000C, "Instance 12" }, { 0x000A_000D, "Instance 13" }, { 0x000A_000E, "Instance 14" }, { 0x000A_000F, "Instance 15" }, { 0x000A_0010, "Instance 16" }, { 0x000A_0011, "Instance 17" }, { 0x000A_0012, "Instance 18" }, { 0x000A_0013, "Instance 19" }, { 0x000A_0014, "Instance 20" }, { 0x000A_0015, "Instance 21" }, { 0x000A_0016, "Instance 22" }, { 0x000A_0017, "Instance 23" }, { 0x000A_0018, "Instance 24" }, { 0x000A_0019, "Instance 25" }, { 0x000A_001A, "Instance 26" }, { 0x000A_001B, "Instance 27" }, { 0x000A_001C, "Instance 28" }, { 0x000A_001D, "Instance 29" }, { 0x000A_001E, "Instance 30" }, { 0x000A_001F, "Instance 31" }, { 0x000A_0020, "Instance 32" }, //---------------- #endregion #region " 0x0B: Telephony Device Page " //---------------- { 0x000B_0000, "Unassigned" }, { 0x000B_0001, "Phone" }, { 0x000B_0002, "Answering Machine" }, { 0x000B_0003, "Message Controls" }, { 0x000B_0004, "Handset" }, { 0x000B_0005, "Headset" }, { 0x000B_0006, "Telephony Key Pad" }, { 0x000B_0007, "Programmable Button" }, { 0x000B_0020, "Hook Switch" }, { 0x000B_0021, "Flash" }, { 0x000B_0022, "Feature" }, { 0x000B_0023, "Hold" }, { 0x000B_0024, "Redial" }, { 0x000B_0025, "Transfer" }, { 0x000B_0026, "Drop" }, { 0x000B_0027, "Park" }, { 0x000B_0028, "Forward Calls" }, { 0x000B_0029, "Alternate Function" }, { 0x000B_002A, "Line" }, { 0x000B_002B, "Speaker Phone" }, { 0x000B_002C, "Conference" }, { 0x000B_002D, "Ring Enable" }, { 0x000B_002E, "Ring Select" }, { 0x000B_002F, "Phone Mute" }, { 0x000B_0030, "Caller ID" }, { 0x000B_0031, "Send" }, { 0x000B_0050, "Speed Dial" }, { 0x000B_0051, "Store Number" }, { 0x000B_0052, "Recall Number" }, { 0x000B_0053, "Phone Directory" }, { 0x000B_0070, "Voice Mail" }, { 0x000B_0071, "Screen Calls" }, { 0x000B_0072, "Do Not Disturb" }, { 0x000B_0073, "Message" }, { 0x000B_0074, "Answer On/Off" }, { 0x000B_0090, "Inside Dial Tone" }, { 0x000B_0091, "Outside Dial Tone" }, { 0x000B_0092, "Inside Ring Tone" }, { 0x000B_0093, "Outside Ring Tone" }, { 0x000B_0094, "Priority Ring Tone" }, { 0x000B_0095, "Inside Ringback" }, { 0x000B_0096, "Priority Ringback" }, { 0x000B_0097, "Line Busy Tone" }, { 0x000B_0098, "Recorder Tone" }, { 0x000B_0099, "Call Waiting Tone" }, { 0x000B_009A, "Confirmation Tone 1" }, { 0x000B_009B, "Confirmation Tone 2" }, { 0x000B_009C, "Tones Off" }, { 0x000B_009D, "Outside Ringback" }, { 0x000B_009E, "Ringer" }, { 0x000B_00B0, "Phone Key 0" }, { 0x000B_00B1, "Phone Key 1" }, { 0x000B_00B2, "Phone Key 2" }, { 0x000B_00B3, "Phone Key 3" }, { 0x000B_00B4, "Phone Key 4" }, { 0x000B_00B5, "Phone Key 5" }, { 0x000B_00B6, "Phone Key 6" }, { 0x000B_00B7, "Phone Key 7" }, { 0x000B_00B8, "Phone Key 8" }, { 0x000B_00B9, "Phone Key 9" }, { 0x000B_00BA, "Phone Key Star" }, { 0x000B_00BB, "Phone Key Pound" }, { 0x000B_00BC, "Phone Key A" }, { 0x000B_00BD, "Phone Key B" }, { 0x000B_00BE, "Phone Key C" }, { 0x000B_00BF, "Phone Key D" }, //---------------- #endregion #region " 0x0C: Consumer Page " //---------------- { 0x000C_0000, "Unassigned" }, { 0x000C_0001, "Consumer Control" }, { 0x000C_0002, "Numeric Key Pad" }, { 0x000C_0003, "Programmable Buttons" }, { 0x000C_0004, "Microphone" }, { 0x000C_0005, "Headphone" }, { 0x000C_0006, "Graphic Equalizer" }, { 0x000C_0020, "+10" }, { 0x000C_0021, "+100" }, { 0x000C_0022, "AM/PM" }, { 0x000C_0030, "Power" }, { 0x000C_0031, "Reset" }, { 0x000C_0032, "Slepp" }, { 0x000C_0033, "Sleep After" }, { 0x000C_0034, "Sleep Mode" }, { 0x000C_0035, "Illumication" }, { 0x000C_0036, "Function Buttons" }, { 0x000C_0040, "Menu" }, { 0x000C_0041, "Menu Pick" }, { 0x000C_0042, "Menu Up" }, { 0x000C_0043, "Menu Down" }, { 0x000C_0044, "Menu Left" }, { 0x000C_0045, "Menu Right" }, { 0x000C_0046, "Menu Escape" }, { 0x000C_0047, "Menu Value Increase" }, { 0x000C_0048, "Menu Value Decrease" }, { 0x000C_0060, "Data On Screen" }, { 0x000C_0061, "Closed Caption" }, { 0x000C_0062, "Closed Caption Select" }, { 0x000C_0063, "VCR/TV" }, { 0x000C_0064, "Broadcast Mode" }, { 0x000C_0065, "Snapshot" }, { 0x000C_0066, "Still" }, { 0x000C_0080, "Selection" }, { 0x000C_0081, "Assign Selection" }, { 0x000C_0082, "Mode Step" }, { 0x000C_0083, "Recall Last" }, { 0x000C_0084, "Enter Channel" }, { 0x000C_0085, "Order Movie" }, { 0x000C_0086, "Channel" }, { 0x000C_0087, "Media Selection" }, { 0x000C_0088, "Media Select Computer" }, { 0x000C_0089, "Media Select TV" }, { 0x000C_008A, "Media Select WWW" }, { 0x000C_008B, "Media Select DVD" }, { 0x000C_008C, "Media Select Telephone" }, { 0x000C_008D, "Media Select Program Guide" }, { 0x000C_008E, "Media Select Video Phone" }, { 0x000C_008F, "Media Select Games" }, { 0x000C_0090, "Media Select Messages" }, { 0x000C_0091, "Media Select CD" }, { 0x000C_0092, "Media Select VCR" }, { 0x000C_0093, "Media Select Tuner" }, { 0x000C_0094, "Quit" }, { 0x000C_0095, "Help" }, { 0x000C_0096, "Media Select Tape" }, { 0x000C_0097, "Media Select Cable" }, { 0x000C_0098, "Media Select Satellite" }, { 0x000C_0099, "Media Select Security" }, { 0x000C_009A, "Media Select Home" }, { 0x000C_009B, "Media Select Call" }, { 0x000C_009C, "Channel Increment" }, { 0x000C_009D, "Channel Decrement" }, { 0x000C_009E, "Media Select SAP" }, { 0x000C_00A0, "VCR Plus" }, { 0x000C_00A1, "Once" }, { 0x000C_00A2, "Daily" }, { 0x000C_00A3, "Weekly" }, { 0x000C_00A4, "Monthly" }, { 0x000C_00B0, "Play" }, { 0x000C_00B1, "Pause" }, { 0x000C_00B2, "Record" }, { 0x000C_00B3, "Fast Forward" }, { 0x000C_00B4, "Rewind" }, { 0x000C_00B5, "Scan Nect Track" }, { 0x000C_00B6, "Scan Previous Track" }, { 0x000C_00B7, "Stop" }, { 0x000C_00B8, "Eject" }, { 0x000C_00B9, "Random Play" }, { 0x000C_00BA, "Select Disc" }, { 0x000C_00BB, "Enter Disc" }, { 0x000C_00BC, "Repeat" }, { 0x000C_00BD, "Tracking" }, { 0x000C_00BE, "Track Normal" }, { 0x000C_00BF, "Slow Tracking" }, { 0x000C_00C0, "Frame Forward" }, { 0x000C_00C1, "Frame Back" }, { 0x000C_00C2, "Mark" }, { 0x000C_00C3, "Clear Mark" }, { 0x000C_00C4, "Repeat From Mark" }, { 0x000C_00C5, "Return To Mark" }, { 0x000C_00C6, "Search Mark Forward" }, { 0x000C_00C7, "Search Mark Backwards" }, { 0x000C_00C8, "Counter Reset" }, { 0x000C_00C9, "Show Counter" }, { 0x000C_00CA, "Tracking Increment" }, { 0x000C_00CB, "Tracking Decrement" }, { 0x000C_00CC, "Stop/Eject" }, { 0x000C_00CD, "Play/Pause" }, { 0x000C_00E0, "Volume" }, { 0x000C_00E1, "Balance" }, { 0x000C_00E2, "Mute" }, { 0x000C_00E3, "Bass" }, { 0x000C_00E4, "Treble" }, { 0x000C_00E5, "Bass boost" }, { 0x000C_00E6, "Surround Mode" }, { 0x000C_00E7, "Loudness" }, { 0x000C_00E8, "MPX" }, { 0x000C_00E9, "Volume Increment" }, { 0x000C_00EA, "Volume Decrement" }, { 0x000C_00F0, "Speed Select" }, { 0x000C_00F1, "Playback Speed" }, { 0x000C_00F2, "Standard Play" }, { 0x000C_00F3, "Long Play" }, { 0x000C_00F4, "Extended Play" }, { 0x000C_00F5, "Slow" }, { 0x000C_0100, "Fan Enable" }, { 0x000C_0101, "Fan Speed" }, { 0x000C_0102, "Light Enable" }, { 0x000C_0103, "Light Illumication Level" }, { 0x000C_0104, "Climate Control Enable" }, { 0x000C_0105, "Room Temperature" }, { 0x000C_0106, "Security Enable" }, { 0x000C_0107, "Fire Alarm" }, { 0x000C_0108, "Police Alarm" }, { 0x000C_0109, "Proximity" }, { 0x000C_010A, "Motion" }, { 0x000C_010B, "Duress Alarm" }, { 0x000C_010C, "Holdup Alarm" }, { 0x000C_010D, "Medical Alarm" }, { 0x000C_0150, "Balance Right" }, { 0x000C_0151, "Balance Left" }, { 0x000C_0152, "Bass Increment" }, { 0x000C_0153, "Bass Decrement" }, { 0x000C_0154, "Treble Increment" }, { 0x000C_0155, "Treble Decrement" }, { 0x000C_0160, "Speaker System" }, { 0x000C_0161, "Channel Left" }, { 0x000C_0162, "Channel Right" }, { 0x000C_0163, "Channel Center" }, { 0x000C_0164, "Channel Front" }, { 0x000C_0165, "Channel Center Front" }, { 0x000C_0166, "Channel Side" }, { 0x000C_0167, "Channel Surround" }, { 0x000C_0168, "Channel Low Frequency Enhancement" }, { 0x000C_0169, "Channel Top" }, { 0x000C_016A, "Channel Unknown" }, { 0x000C_0170, "Sub-channel" }, { 0x000C_0171, "Sub-channel Increment" }, { 0x000C_0172, "Sub-channel Decrement" }, { 0x000C_0173, "Alternate Audio Increment" }, { 0x000C_0174, "Alternate Audio Decrement" }, { 0x000C_0180, "Application Launch Buttons" }, { 0x000C_0181, "AL Launch Button Configuration Tool" }, { 0x000C_0182, "AL Programmable Button Configuratin" }, { 0x000C_0183, "AL Consumer Control Configuration" }, { 0x000C_0184, "AL Word Processor" }, { 0x000C_0185, "AL Text Editor" }, { 0x000C_0186, "AL Spreadsheet" }, { 0x000C_0187, "AL Graphics Editor" }, { 0x000C_0188, "AL Presentation App" }, { 0x000C_0189, "AL Database App" }, { 0x000C_018A, "AL Email Reader" }, { 0x000C_018B, "AL Newsreader" }, { 0x000C_018C, "AL Voicemail" }, { 0x000C_018D, "AL Contacts/Address Book" }, { 0x000C_018E, "AL Calendar/Schedule" }, { 0x000C_018F, "AL Task/Project Manager" }, { 0x000C_0190, "AL Log/Journal/Timecard" }, { 0x000C_0191, "AL Checkbook/Finance" }, { 0x000C_0192, "AL Calculator" }, { 0x000C_0193, "AL A/V Capture/Playback" }, { 0x000C_0194, "AL Local Machine Browser" }, { 0x000C_0195, "AL LAN/WAN Browser" }, { 0x000C_0196, "AL Internet Browser" }, { 0x000C_0197, "AL Remote Networking/ISP Connect" }, { 0x000C_0198, "AL Network Conference" }, { 0x000C_0199, "AL Network Chat" }, { 0x000C_019A, "AL Telephony/Dialer" }, { 0x000C_019B, "AL Logon" }, { 0x000C_019C, "AL Logoff" }, { 0x000C_019D, "AL Logon/Logoff" }, { 0x000C_019E, "AL Terminal Lock/Screensaver" }, { 0x000C_019F, "AL Control Panel" }, { 0x000C_01A0, "AL Command Line Processor/Run" }, { 0x000C_01A1, "AL Process/Task Manager" }, { 0x000C_01A2, "AL Select Task/Application" }, { 0x000C_01A3, "AL Next Task/Application" }, { 0x000C_01A4, "AL Previous Task/Application" }, { 0x000C_01A5, "AL Preemptive Halt Task/Application" }, { 0x000C_01A6, "AL Integrated Help Center" }, { 0x000C_01A7, "AL Documents" }, { 0x000C_01A8, "AL Thesaurus" }, { 0x000C_01A9, "AL Dictionary" }, { 0x000C_01AA, "AL Desktop" }, { 0x000C_01AB, "AL Spell Check" }, { 0x000C_01AC, "AL Grammar Check" }, { 0x000C_01AD, "AL Wireless Status" }, { 0x000C_01AE, "AL Keybaord Layout" }, { 0x000C_01AF, "AL Virus Protection" }, { 0x000C_01B0, "AL Encryption" }, { 0x000C_01B1, "AL Screen Saver" }, { 0x000C_01B2, "AL Alarms" }, { 0x000C_01B3, "AL Cock" }, { 0x000C_01B4, "AL Fire Browser" }, { 0x000C_01B5, "AL Power Status" }, { 0x000C_01B6, "AL Image Browser" }, { 0x000C_01B7, "AL Audio Browser" }, { 0x000C_01B8, "AL Movie Browser" }, { 0x000C_01B9, "AL Digital rights Manager" }, { 0x000C_01BA, "AL Digital Wallet" }, { 0x000C_01BC, "AL Instant Messaging" }, { 0x000C_01BD, "AL OEM Features/Tips/Tutorial Browser" }, { 0x000C_01BE, "AL OEM Help" }, { 0x000C_01BF, "AL Online Community" }, { 0x000C_01C0, "AL Entertainment Content Browser" }, { 0x000C_01C1, "AL Online Shopping Browser" }, { 0x000C_01C2, "AL SmartCard Information/Help" }, { 0x000C_01C3, "AL Market Monitor/Finance Browser" }, { 0x000C_01C4, "AL Customized Corporate News Browser" }, { 0x000C_01C5, "AL Online Activity Browser" }, { 0x000C_01C6, "AL Research/Search Browser" }, { 0x000C_01C7, "AL Audio Player" }, { 0x000C_0200, "Generic GUI Application Controls" }, { 0x000C_0201, "AC New" }, { 0x000C_0202, "AC Open" }, { 0x000C_0203, "AC Close" }, { 0x000C_0204, "AC Exit" }, { 0x000C_0205, "AC Maximize" }, { 0x000C_0206, "AC Minimize" }, { 0x000C_0207, "AC Save" }, { 0x000C_0208, "AC Print" }, { 0x000C_0209, "AC Properties" }, { 0x000C_021A, "AC Undo" }, { 0x000C_021B, "AC Copy" }, { 0x000C_021C, "AC Cut" }, { 0x000C_021D, "AC Paster" }, { 0x000C_021E, "AC Select All" }, { 0x000C_021F, "AC Find" }, { 0x000C_0220, "AC Find and Replace" }, { 0x000C_0221, "AC Search" }, { 0x000C_0222, "AC Go To" }, { 0x000C_0223, "AC Home" }, { 0x000C_0224, "AC Back" }, { 0x000C_0225, "AC Forward" }, { 0x000C_0226, "AC Stop" }, { 0x000C_0227, "AC Refresh" }, { 0x000C_0228, "AC Previous Link" }, { 0x000C_0229, "AC Next Link" }, { 0x000C_022A, "AC Bookmarks" }, { 0x000C_022B, "AC History" }, { 0x000C_022C, "AC Subscriptions" }, { 0x000C_022D, "AC Zoom In" }, { 0x000C_022E, "AC Zoom Out" }, { 0x000C_022F, "AC Zoom" }, { 0x000C_0230, "AC Full Screen View" }, { 0x000C_0231, "AC Normal View" }, { 0x000C_0232, "AC View Toggle" }, { 0x000C_0233, "AC Scroll Up" }, { 0x000C_0234, "AC Scroll Down" }, { 0x000C_0235, "AC Scroll" }, { 0x000C_0236, "AC Pan Left" }, { 0x000C_0237, "AC Pan Right" }, { 0x000C_0238, "AC Pan" }, { 0x000C_0239, "AC New Window" }, { 0x000C_023A, "AC Tile Horizontally" }, { 0x000C_023B, "AC Tile Vertically" }, { 0x000C_023C, "AC Format" }, { 0x000C_023D, "AC Edit" }, { 0x000C_023E, "AC Bold" }, { 0x000C_023F, "AC Italics" }, { 0x000C_0240, "AC Underline" }, { 0x000C_0241, "AC Strikethrough" }, { 0x000C_0242, "AC Subscript" }, { 0x000C_0243, "AC Superscript" }, { 0x000C_0244, "AC All caps" }, { 0x000C_0245, "AC Rotate" }, { 0x000C_0246, "AC Resize" }, { 0x000C_0247, "AC Flip Horizontal" }, { 0x000C_0248, "AC Flip Vertical" }, { 0x000C_0249, "AC Mirror Horizontal" }, { 0x000C_024A, "AC Mirror Vertical" }, { 0x000C_024B, "AC Font select" }, { 0x000C_024C, "AC Font Color" }, { 0x000C_024D, "AC Font Size" }, { 0x000C_024E, "AC Justify Left" }, { 0x000C_024F, "AC Justify Center H" }, { 0x000C_0250, "AC Justify Right" }, { 0x000C_0251, "AC Justify Block H" }, { 0x000C_0252, "AC Justify Top" }, { 0x000C_0253, "AC Justify Center V" }, { 0x000C_0254, "AC Justify Bottom" }, { 0x000C_0255, "AC Justify Block V" }, { 0x000C_0256, "AC Indent Decrease" }, { 0x000C_0257, "AC Indent Increase" }, { 0x000C_0258, "AC Numbered List" }, { 0x000C_0259, "AC Restart Numbering" }, { 0x000C_025A, "AC Bulleted List" }, { 0x000C_025B, "AC Promote" }, { 0x000C_025C, "AC Demote" }, { 0x000C_025D, "AC Yes" }, { 0x000C_025E, "AC No" }, { 0x000C_025F, "AC Cancel" }, { 0x000C_0260, "AC Catalog" }, { 0x000C_0261, "AC Buy/Checkout" }, { 0x000C_0262, "AC Add to Card" }, { 0x000C_0263, "AC Expand" }, { 0x000C_0264, "AC Expand All" }, { 0x000C_0265, "AC Collapse" }, { 0x000C_0266, "AC Collapse All" }, { 0x000C_0267, "AC Print Preview" }, { 0x000C_0268, "AC Paste Special" }, { 0x000C_0269, "AC Insert Mode" }, { 0x000C_026A, "AC Delete" }, { 0x000C_026B, "AC Lock" }, { 0x000C_026C, "AC Unlock" }, { 0x000C_026D, "AC Protect" }, { 0x000C_026E, "AC Unprotect" }, { 0x000C_026F, "AC Attach Comment" }, { 0x000C_0270, "AC Delete Comment" }, { 0x000C_0271, "AC View Comment" }, { 0x000C_0272, "AC Select Word" }, { 0x000C_0273, "AC Select Sentence" }, { 0x000C_0274, "AC Select Paragraph" }, { 0x000C_0275, "AC Select Column" }, { 0x000C_0276, "AC Select Row" }, { 0x000C_0277, "AC Select Table" }, { 0x000C_0278, "AC Select Object" }, { 0x000C_0279, "AC Redo/Repeat" }, { 0x000C_027A, "AC Sort" }, { 0x000C_027B, "AC Sort Ascending" }, { 0x000C_027C, "AC Sort Descending" }, { 0x000C_027D, "AC Filter" }, { 0x000C_027E, "AC Set Clock" }, { 0x000C_027F, "AC View Clock" }, { 0x000C_0280, "AC Select Time Zone" }, { 0x000C_0281, "AC Edit Time Zone" }, { 0x000C_0282, "AC Set Alarm" }, { 0x000C_0283, "AC Clear Alarm" }, { 0x000C_0284, "AC Snooze Alarm" }, { 0x000C_0285, "AC Reset Alarm" }, { 0x000C_0286, "AC Synchronize" }, { 0x000C_0287, "AC Send/Receive" }, { 0x000C_0288, "AC Send To" }, { 0x000C_0289, "AC Reply" }, { 0x000C_028A, "AC Reply All" }, { 0x000C_028B, "AC Forward Msg" }, { 0x000C_028C, "AC Send" }, { 0x000C_028D, "AC Attach File" }, { 0x000C_028E, "AC Upload" }, { 0x000C_028F, "AC Download (Save Target As)" }, { 0x000C_0290, "AC Set Borders" }, { 0x000C_0291, "AC Insert Row" }, { 0x000C_0292, "AC Insert Column" }, { 0x000C_0293, "AC Insert File" }, { 0x000C_0294, "AC Insert Picture" }, { 0x000C_0295, "AC Insert Object" }, { 0x000C_0296, "AC Insert Symbol" }, { 0x000C_0297, "AC Save and Close" }, { 0x000C_0298, "AC Rename" }, { 0x000C_0299, "AC Merge" }, { 0x000C_029A, "AC Split" }, { 0x000C_029B, "AC Distribute Horizontally" }, { 0x000C_029C, "AC Distribute Vertically" }, //---------------- #endregion #region " 0x0D: Digitizers Page " //---------------- { 0x000D_0000, "Undefined" }, { 0x000D_0001, "Digitizer" }, { 0x000D_0002, "Pen" }, { 0x000D_0003, "Light Pen" }, { 0x000D_0004, "Touch Screen" }, { 0x000D_0005, "Touch Pad" }, { 0x000D_0006, "White Board" }, { 0x000D_0007, "Coordinate Measuring Machine" }, { 0x000D_0008, "3D Digitizer" }, { 0x000D_0009, "Stereo Plotter" }, { 0x000D_000A, "Articulated Arm" }, { 0x000D_000B, "Armature" }, { 0x000D_000C, "Multiple Point Digitizer" }, { 0x000D_000D, "Free Space Wand" }, { 0x000D_0020, "Sylus" }, { 0x000D_0021, "Puck" }, { 0x000D_0022, "Finger" }, { 0x000D_0030, "Tip Pressure" }, { 0x000D_0031, "Barrel Pressure" }, { 0x000D_0032, "In Range" }, { 0x000D_0033, "Touch" }, { 0x000D_0034, "Untouch" }, { 0x000D_0035, "Tap" }, { 0x000D_0036, "Quality" }, { 0x000D_0037, "Data Valid" }, { 0x000D_0038, "Transducer Index" }, { 0x000D_0039, "Tablet Function Keys" }, { 0x000D_003A, "Program Change Keys" }, { 0x000D_003B, "Battery Strength" }, { 0x000D_003C, "Invert" }, { 0x000D_003D, "X Tilt" }, { 0x000D_003E, "Y tilt" }, { 0x000D_003F, "Azimuth" }, { 0x000D_0040, "Altitude" }, { 0x000D_0041, "Twist" }, { 0x000D_0042, "Tip Switch" }, { 0x000D_0043, "Secondary Tip Switch" }, { 0x000D_0044, "Barrel Switch" }, { 0x000D_0045, "Eraser" }, { 0x000D_0046, "Tablet Pick" }, //---------------- #endregion #region " 0x14: Alphanumeric Display Page " //---------------- { 0x0014_0000, "Undefined" }, { 0x0014_0001, "Alphanumeric Display" }, { 0x0014_0002, "Bitmapped Display" }, { 0x0014_0020, "Display Attributes Report" }, { 0x0014_0021, "ASCII Character Set" }, { 0x0014_0022, "Data Read Back" }, { 0x0014_0023, "Font Read Back" }, { 0x0014_0024, "Display Control Report" }, { 0x0014_0025, "Clear Display" }, { 0x0014_0026, "Display Enable" }, { 0x0014_0027, "Screen Saver Delay" }, { 0x0014_0028, "Screen Saver Enable" }, { 0x0014_0029, "Vertical Scroll" }, { 0x0014_002A, "Horizontal Scroll" }, { 0x0014_002B, "Character Report" }, { 0x0014_002C, "Display Data" }, { 0x0014_002D, "Display Status" }, { 0x0014_002E, "Stat Not Ready" }, { 0x0014_002F, "Stat Ready" }, { 0x0014_0030, "Err Not a loadable character" }, { 0x0014_0031, "Err Font data cannot be read" }, { 0x0014_0032, "Cursor Position Report" }, { 0x0014_0033, "Row" }, { 0x0014_0034, "Column" }, { 0x0014_0035, "Rows" }, { 0x0014_0036, "Columns" }, { 0x0014_0037, "Cursor Pixel Positioning" }, { 0x0014_0038, "Cursor Mode" }, { 0x0014_0039, "Cursor Enable" }, { 0x0014_003A, "Cursor Blink" }, { 0x0014_003B, "Font Report" }, { 0x0014_003C, "Font Data" }, { 0x0014_003D, "Character Width" }, { 0x0014_003E, "Character Height" }, { 0x0014_003F, "Character Spacing Horizontal" }, { 0x0014_0040, "Character Spacing Vertical" }, { 0x0014_0041, "Unicode Character Set" }, { 0x0014_0042, "Font 7-Segment" }, { 0x0014_0043, "7-Segment Direct Map" }, { 0x0014_0044, "Font 14-Segment" }, { 0x0014_0045, "14-Segment Direct Map" }, { 0x0014_0046, "Display Brightness" }, { 0x0014_0047, "Display Contrast" }, { 0x0014_0048, "Character Attribute" }, { 0x0014_0049, "Attribute Readback" }, { 0x0014_004A, "Attribute data" }, { 0x0014_004B, "Char Attr Enhance" }, { 0x0014_004C, "Char Attr Underline" }, { 0x0014_004D, "Char Attr Blink" }, { 0x0014_0080, "Bitmap Size X" }, { 0x0014_0081, "Bitmap Size Y" }, { 0x0014_0083, "Bit Depth Format" }, { 0x0014_0084, "Display Orientation" }, { 0x0014_0085, "Palette Report" }, { 0x0014_0086, "Palette Data Size" }, { 0x0014_0087, "Palette Data Offset" }, { 0x0014_0088, "Palette Data" }, { 0x0014_008A, "Blit Report" }, { 0x0014_008B, "Blit Rectangle X1" }, { 0x0014_008C, "Blit Rectangle Y1" }, { 0x0014_008D, "Blit Rectangle X2" }, { 0x0014_008E, "Blit Rectangle Y2" }, { 0x0014_008F, "Blit Data" }, { 0x0014_0090, "Soft Button" }, { 0x0014_0091, "Soft Button ID" }, { 0x0014_0092, "Soft Button Side" }, { 0x0014_0093, "Soft Button Offset 1" }, { 0x0014_0094, "Soft Button Offset 2" }, { 0x0014_0095, "Soft Button Report" }, //---------------- #endregion #region " 0x40: Medical Instrument Page " //---------------- { 0x0040_0000, "Undefined" }, { 0x0040_0001, "Medical Ultrasound" }, { 0x0040_0020, "VCR/Acquisition" }, { 0x0040_0021, "Freeze/Thaw" }, { 0x0040_0022, "Clip Store" }, { 0x0040_0023, "Update" }, { 0x0040_0024, "Next" }, { 0x0040_0025, "Save" }, { 0x0040_0026, "Print" }, { 0x0040_0027, "Microphone Enable" }, { 0x0040_0040, "Cine" }, { 0x0040_0041, "Transmit Power" }, { 0x0040_0042, "Volume" }, { 0x0040_0043, "Focus" }, { 0x0040_0044, "Depth" }, { 0x0040_0060, "Soft Step - Primary" }, { 0x0040_0061, "Soft Step - Secondary" }, { 0x0040_0070, "Depth Gain Compensation" }, { 0x0040_0080, "Zoom Select" }, { 0x0040_0081, "Zoom Adjust" }, { 0x0040_0082, "Spectral Doppler Mode Select" }, { 0x0040_0083, "Spectral Doppler Adjust" }, { 0x0040_0084, "Color Doppler Mode Select" }, { 0x0040_0085, "Color Doppler Adjust" }, { 0x0040_0086, "Motion Mode Select" }, { 0x0040_0087, "Motion Mode Adjust" }, { 0x0040_0088, "2-D Mode Select" }, { 0x0040_0089, "2-D Mode Adjust" }, { 0x0040_00A0, "Soft Control Select" }, { 0x0040_00A1, "Soft Control Adjust" }, //---------------- #endregion }; } } <|start_filename|>DTXMania2/ステージ/07演奏/レーンフラッシュ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.演奏 { /// <summary> /// ドラム入力に対するレーンの反応。 /// </summary> class レーンフラッシュ : IDisposable { // 生成と終了 public レーンフラッシュ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._レーンフラッシュ画像 = new 画像D2D( @"$(Images)\PlayStage\LaneFlush.png" ) { 加算合成する = true }; this._レーンフラッシュの矩形リスト = new 矩形リスト( @"$(Images)\PlayStage\LaneFlush.yaml" ); this._フラッシュ情報 = new Dictionary<表示レーン種別, Counter>() { { 表示レーン種別.LeftCymbal, new Counter() }, { 表示レーン種別.HiHat, new Counter() }, { 表示レーン種別.Foot, new Counter() }, { 表示レーン種別.Snare, new Counter() }, { 表示レーン種別.Tom1, new Counter() }, { 表示レーン種別.Bass, new Counter() }, { 表示レーン種別.Tom2, new Counter() }, { 表示レーン種別.Tom3, new Counter() }, { 表示レーン種別.RightCymbal, new Counter() }, }; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._レーンフラッシュ画像.Dispose(); } // フラッシュ開始 public void 開始する( 表示レーン種別 laneType ) { this._フラッシュ情報[ laneType ].開始する( 0, 10, 15 ); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { foreach( var laneType in this._フラッシュ情報.Keys ) { if( this._フラッシュ情報[ laneType ].終了値に達した ) continue; var フラッシュ1枚のサイズ = new Size2F( this._レーンフラッシュの矩形リスト[ laneType.ToString() ]!.Value.Width, this._レーンフラッシュの矩形リスト[ laneType.ToString() ]!.Value.Height ); float 割合 = this._フラッシュ情報[ laneType ].現在値の割合; // 0 → 1 float 横拡大率 = 0.2f + 0.8f * 割合; // 0.2 → 1.0 割合 = MathF.Cos( 割合 * MathF.PI / 2f ); // 1 → 0(加速しながら) for( float y = ( レーンフレーム.領域.Bottom - フラッシュ1枚のサイズ.Height ); y > ( レーンフレーム.領域.Top - フラッシュ1枚のサイズ.Height ); y -= フラッシュ1枚のサイズ.Height ) { this._レーンフラッシュ画像.描画する( d2ddc, 左位置: レーンフレーム.レーン中央位置X[ laneType ] - フラッシュ1枚のサイズ.Width * 横拡大率 / 2f, 上位置: y, 不透明度0to1: 割合 * 0.75f, // ちょっと暗めに。 転送元矩形: this._レーンフラッシュの矩形リスト[ laneType.ToString() ]!.Value, X方向拡大率: 横拡大率 ); } } } // ローカル private readonly 画像D2D _レーンフラッシュ画像; private readonly 矩形リスト _レーンフラッシュの矩形リスト; private readonly Dictionary<表示レーン種別, Counter> _フラッシュ情報; } } <|start_filename|>SSTFEditor/数値入力ダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace SSTFEditor { public partial class 数値入力ダイアログ : Form { public decimal 数値 => this.numericUpDown数値.Value; public 数値入力ダイアログ() { InitializeComponent(); } public 数値入力ダイアログ( decimal 開始値, decimal 最小値, decimal 最大値, string 表示するメッセージ ) { this.InitializeComponent(); this.labelメッセージ.Text = 表示するメッセージ; this.numericUpDown数値.Value = 開始値; this.numericUpDown数値.Minimum = 最小値; this.numericUpDown数値.Maximum = 最大値; } // イベント protected void numericUpDown数値_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → キャンセル if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } } } <|start_filename|>DTXMania2/Effekseer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using FDK; namespace DTXMania2 { /// <summary> /// Effekseer.NET を使ってエフェクトを再生する。 /// </summary> class Effekseer : IDisposable { // プロパティ public EffekseerNET.Manager Manager { get; private set; } = null!; public EffekseerRendererDX11NET.Renderer Renderer { get; private set; } = null!; // 生成と終了 public Effekseer( SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct3D11.DeviceContext d3ddc, float width, float height ) { this.Renderer = EffekseerRendererDX11NET.Renderer.Create( d3dDevice1.NativePointer, d3ddc.NativePointer, squareMaxCount: 8000 ); this.Manager = EffekseerNET.Manager.Create( instance_max: 8000 ); this.Manager.SetSpriteRenderer( this.Renderer.CreateSpriteRenderer() ); this.Manager.SetRibbonRenderer( this.Renderer.CreateRibbonRenderer() ); this.Manager.SetRingRenderer( this.Renderer.CreateRingRenderer() ); this.Manager.SetTrackRenderer( this.Renderer.CreateTrackRenderer() ); this.Manager.SetModelRenderer( this.Renderer.CreateModelRenderer() ); this.Manager.SetTextureLoader( this.Renderer.CreateTextureLoader() ); this.Manager.SetModelLoader( this.Renderer.CreateModelLoader() ); this.Manager.SetMaterialLoader( this.Renderer.CreateMaterialLoader() ); this.Renderer.SetProjectionMatrix( new EffekseerNET.Matrix44().PerspectiveFovRH( 10.0f / 180.0f * MathF.PI, // 視野角10°;2Dにあわせるため、なるべく小さくして歪みを少なくする。 width / height, 1.0f, 500.0f ) ); this.Renderer.SetCameraMatrix( new EffekseerNET.Matrix44().LookAtRH( eye: new EffekseerNET.Vector3D( 0.0f, 0f, 50.0f ), at: new EffekseerNET.Vector3D( 0.0f, 0.0f, 0.0f ), up: new EffekseerNET.Vector3D( 0.0f, 1.0f, 0.0f ) ) ); this._前回の更新時刻 = QPCTimer.生カウント; } public virtual void Dispose() { this.Manager.Destroy(); // Dispose じゃないので注意 this.Renderer.Destroy(); // } // 進行と描画 public void 進行する() { long 現在時刻 = QPCTimer.生カウント; double 経過時間sec = QPCTimer.生カウント相対値を秒へ変換して返す( 現在時刻 - this._前回の更新時刻 ); this._前回の更新時刻 = 現在時刻; this.Manager.Update( (float)( 経過時間sec * 60.0 ) ); // Effekseerは毎秒60フレームで固定 } public void 描画する() { Global.GraphicResources.既定のD3D11DeviceContext.OutputMerger.SetRenderTargets( Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView ); Global.GraphicResources.既定のD3D11DeviceContext.Rasterizer.SetViewports( Global.GraphicResources.既定のD3D11ViewPort ); this.Renderer.BeginRendering(); this.Manager.Draw(); this.Renderer.EndRendering(); } public void 描画する( int effectHandle ) { Global.GraphicResources.既定のD3D11DeviceContext.OutputMerger.SetRenderTargets( Global.GraphicResources.既定のD3D11DepthStencilView, Global.GraphicResources.既定のD3D11RenderTargetView ); Global.GraphicResources.既定のD3D11DeviceContext.Rasterizer.SetViewports( Global.GraphicResources.既定のD3D11ViewPort ); this.Renderer.BeginRendering(); this.Manager.DrawHandle( effectHandle ); this.Renderer.EndRendering(); } // ローカル private long _前回の更新時刻 = 0; } } <|start_filename|>SSTFormat/v004/スコア.SSTFoverDTX.cs<|end_filename|> using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace SSTFormat.v004 { public partial class スコア { public static class SSTFoverDTX { /// <summary> /// 指定されたファイルが SSTF over DTX 形式のファイルであれば true を返す。 /// </summary> public static bool ファイルがSSTFoverDTXである( string ファイルの絶対パス ) { string 行; using( var sr = new StreamReader( ファイルの絶対パス, Encoding.GetEncoding( "shift-jis" ) ) ) // SSTFoverDTX は Shift-JIS 行 = sr.ReadLine().Trim(); int コメント識別子の位置 = 行.IndexOf( '#' ); // 見つからなければ -1 if( 0 > コメント識別子の位置 ) return false; // 先頭行がコメント行ではない var コメント文 = 行[ ( コメント識別子の位置 + 1 ).. ].Trim(); return コメント文.ToLower().StartsWith( "sstf over dtx" ); // コメント文が sstf over dtx で始まっていれば true } /// <summary> /// ファイルをSSTFoverDTXデータであるとみなして読み込み、スコアを生成して返す。 /// 読み込みに失敗した場合は、何らかの例外を発出する。 /// </summary> public static スコア ファイルから生成する( string SSTFoverDTXファイルの絶対パス, bool ヘッダだけ = false ) { // DTX ファイルとして読み込み、スコアを生成する。 var score = DTX.ファイルから生成する( SSTFoverDTXファイルの絶対パス, DTX.データ種別.DTX, ヘッダだけ ); // スコアを SSTFoverDTX 仕様に基づいて復元する。 _SSTFoverDTXからSSTFに復元する( score ); return score; } /// <summary> /// 文字列がSSTFoverDTXフォーマットのテキストデータを含むとみなして読み込み、スコアを生成して返す。 /// 読み込みに失敗した場合は、何らかの例外を発出する。 /// </summary> public static スコア 文字列から生成する( string 全入力文字列, bool ヘッダだけ = false ) { // DTX ファイルとして読み込み、スコアを生成する。 var score = DTX.文字列から生成する( 全入力文字列, DTX.データ種別.DTX, ヘッダだけ ); // スコアを SSTFoverDTX 仕様に基づいて復元する。 _SSTFoverDTXからSSTFに復元する( score ); return score; } /// <summary> /// 現在の スコア の内容をDTX互換形式ファイル(*.dtx)に書き出す。 /// 小節線、拍線、Unknown チップは出力しない。 /// 失敗時は何らかの例外を発出する。 /// </summary> public static void 出力する( スコア score, Stream 出力先, string 追加ヘッダ文 = null ) { using var sw = new StreamWriter( 出力先, Encoding.GetEncoding( "shift_jis" ) ); // バージョンの出力 sw.WriteLine( $"# SSTF over DTX, SSTFVersion {SSTFVERSION}" ); // 追加ヘッダの出力(あれば) if( !( string.IsNullOrEmpty( 追加ヘッダ文 ) ) ) { sw.WriteLine( $"{追加ヘッダ文}" ); // ヘッダ文に "{...}" が入ってても大丈夫なように、$"{...}" で囲む。 sw.WriteLine( "" ); } _ヘッダ行を出力する( score, sw ); _BPMを出力する( score, sw ); _小節長倍率を出力する( score, sw ); _WAVとVOLUMEを出力する( score, sw ); _オブジェクト記述を出力する( score, sw ); sw.Close(); } // 入力 /// <summary> /// 通常のDTXファイルとして読み込まれたスコアを、SSTFoverDTX の仕様に基づいて復元する。 /// </summary> private static void _SSTFoverDTXからSSTFに復元する( スコア score ) { foreach( var chip in score.チップリスト ) { switch( chip.チップ種別 ) { case チップ種別.SE1: { #region " SE1,18~1F → LeftCymbal_Mute " //---------------- int zz = chip.チップサブID - _zz( "18" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.LeftCymbal_Mute; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.HiHat_Open: { #region " HiHat_Open,2G~2N → HiHat_HalfOpen " //---------------- int zz = chip.チップサブID - _zz( "2G" ); if( 0 <= zz && zz < 8) { chip.チップ種別 = チップ種別.HiHat_HalfOpen; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.Snare: { #region " Snare,38~3F → Snare_OpenRim " //---------------- int zz = chip.チップサブID - _zz( "38" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.Snare_OpenRim; chip.音量 = zz + 1; } //---------------- #endregion #region " Snare,3G~3N → Snare_ClosedRim " //---------------- else if( 8 <= zz && zz < 16 ) { chip.チップ種別 = チップ種別.Snare_ClosedRim; chip.音量 = zz - 7; } //---------------- #endregion #region " Snare,3O~3V → Snare_Ghost " //---------------- if( 16 <= zz && zz < 24 ) { chip.チップ種別 = チップ種別.Snare_Ghost; chip.音量 = zz - 15; } //---------------- #endregion break; } case チップ種別.Tom1: { #region " Tom1,58~5F → Tom1_Rim " //---------------- int zz = chip.チップサブID - _zz( "58" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.Tom1_Rim; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.Tom2: { #region " Tom2,68~6F → Tom2_Rim " //---------------- int zz = chip.チップサブID - _zz( "68" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.Tom2_Rim; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.Tom3: { #region " Tom3,78~7F → Tom3_Rim " //---------------- int zz = chip.チップサブID - _zz( "78" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.Tom3_Rim; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.SE2: { #region " SE2,88~8F → RightCymbal_Mute " //---------------- int zz = chip.チップサブID - _zz( "88" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.RightCymbal_Mute; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.Ride: { #region " Ride,98~9F → Ride_Cup " //---------------- int zz = chip.チップサブID - _zz( "98" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.Ride_Cup; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.RightCrash: { #region " RightCrash,A0~A7 → China " //---------------- int zz = chip.チップサブID - _zz( "A0" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.China; chip.音量 = zz + 1; } //---------------- #endregion break; } case チップ種別.LeftCrash: { #region " LeftCrash,B0~B7 → Splash " //---------------- int zz = chip.チップサブID - _zz( "B0" ); if( 0 <= zz && zz < 8 ) { chip.チップ種別 = チップ種別.Splash; chip.音量 = zz + 1; } //---------------- #endregion break; } } } } // 出力 private static void _ヘッダ行を出力する( スコア score, StreamWriter sw ) { #region " 曲名 → #TITLE " //---------------- if( !string.IsNullOrEmpty( score.曲名 ) ) { sw.WriteLine( $"#TITLE: {score.曲名}" ); } else { sw.WriteLine( $"#TITLE: (no title)" ); } //---------------- #endregion #region " アーティスト名 → #ARTIST " //---------------- if( !string.IsNullOrEmpty( score.アーティスト名 ) ) { sw.WriteLine( $"#ARTIST: {score.アーティスト名}" ); } else { // 省略可。 } //---------------- #endregion #region " 説明文 → #COMMENT " //---------------- if( !string.IsNullOrEmpty( score.説明文 ) ) { sw.WriteLine( $"#COMMENT: {score.説明文}" ); } else { // 省略可。 } //---------------- #endregion #region " 難易度(0.00~9.99) → #DLEVEL(1~100) " //---------------- if( 0.0 < score.難易度 ) { sw.WriteLine( $"#DLEVEL: {Math.Clamp( (int) ( score.難易度 * 10 ), min: 1, max: 100 ) }" ); } else { sw.WriteLine( $"#DLEVEL: 1" ); // 0 や省略は不可。 } //---------------- #endregion #region " プレビュー音声 → #PREVIEW " //---------------- if( !string.IsNullOrEmpty( score.プレビュー音声ファイル名 ) ) { sw.WriteLine( $"#PREVIEW: {score.プレビュー音声ファイル名}" ); } else { // 省略可。 } //---------------- #endregion #region " プレビュー画像 → #PREIMAGE " //---------------- if( !string.IsNullOrEmpty( score.プレビュー画像ファイル名 ) ) { sw.WriteLine( $"#PREIMAGE: {score.プレビュー画像ファイル名}" ); } else { // 省略可。 } //---------------- #endregion #region " BGV → #VIDEO01 " //---------------- if( !string.IsNullOrEmpty( score.BGVファイル名 ) ) { sw.WriteLine( $"#VIDEO01: {score.BGVファイル名}" ); } else { // 省略可。 } //---------------- #endregion #region " BGM → #WAVC0 " //---------------- if( !string.IsNullOrEmpty( score.BGMファイル名 ) ) { sw.WriteLine( $"#WAVC0: {score.BGMファイル名}" ); sw.WriteLine( $"#BGMWAV: C0" ); } else { // 省略可。 } //---------------- #endregion #region " Viewerでの再生速度 → #DTXVPLAYSPEED " //---------------- if( score.Viewerでの再生速度 != 1.0 ) { sw.WriteLine( $"#DTXVPLAYSPEED: {score.Viewerでの再生速度}" ); } //---------------- #endregion sw.WriteLine( "" ); } private static void _WAVとVOLUMEを出力する( スコア score, StreamWriter sw ) { if( チップ.最大音量 != 8 ) throw new Exception( "チップの最大音量が 8 ではありません。" ); foreach( var kvp in _チップ種別マップ ) { for( int vol = 0; vol < チップ.最大音量; vol++ ) { var zz = _zz( kvp.Value.先頭wav番号 + vol ); sw.WriteLine( $"#WAV{zz}: {kvp.Value.ファイル名}" ); sw.WriteLine( $"#VOLUME{zz}: {(int) ( ( vol + 1 ) * 100.0 / チップ.最大音量 )}" ); } } sw.WriteLine( "" ); } private static void _BPMを出力する( スコア score, StreamWriter sw ) { int zz = 1; _BPMリスト = new List<double>(); foreach( var chip in score.チップリスト ) { if( chip.チップ種別 == チップ種別.BPM && !_BPMリスト.Contains( chip.BPM ) ) { sw.WriteLine( $"#BPM{_zz( zz )}: {chip.BPM}" ); zz++; _BPMリスト.Add( chip.BPM ); } } sw.WriteLine( "" ); } private static void _小節長倍率を出力する( スコア score, StreamWriter sw ) { int 最終小節番号 = score.最大小節番号を返す(); double 直前の小節の倍率 = 1.0; for( int 小節番号 = 0; 小節番号 <= 最終小節番号; 小節番号++ ) { // SSTF では、すべての小節番号に対して小節倍率が登録されている。 double 倍率 = score.小節長倍率リスト[ 小節番号 ]; // DTX では一度指定された倍率はそれ以降も有効だが、SSTF ではその小節限りとなる。 if( 倍率 != 直前の小節の倍率 ) { sw.WriteLine( $"#{_zxx( 小節番号 )}02: {倍率}" ); } 直前の小節の倍率 = 倍率; } sw.WriteLine( "" ); } private static void _オブジェクト記述を出力する( スコア score, StreamWriter sw ) { int 最終小節番号 = score.最大小節番号を返す(); // 小節単位で出力。 for( int 小節番号 = 0; 小節番号 <= 最終小節番号; 小節番号++ ) { var この小節に存在するチップのリスト = score.チップリスト.Where( ( c ) => c.小節番号 == 小節番号 ); // チップの複製をとりつつ、チップ種別ごとに分類する。 // 複製をとるのは、このあとメンバをいじるため。 var 種別ごとのチップリスト = new Dictionary<チップ種別, List<チップ>>(); foreach( var chip in この小節に存在するチップのリスト ) { if( 種別ごとのチップリスト.ContainsKey( chip.チップ種別 ) ) 種別ごとのチップリスト[ chip.チップ種別 ].Add( (チップ) chip.Clone() ); else 種別ごとのチップリスト.Add( chip.チップ種別, new List<チップ>() { (チップ) chip.Clone() } ); } // チップ種別ごとに処理し、出力する。 foreach( var chipType in 種別ごとのチップリスト.Keys ) { if( chipType != チップ種別.背景動画 && chipType != チップ種別.BGM && chipType != チップ種別.BPM && !_チップ種別マップ.ContainsKey( chipType ) ) continue; // オブジェクト記述の出力対象外 var chips = 種別ごとのチップリスト[ chipType ]; #region " 各チップの小節解像度を統一し、新しい小節内位置を算出する。" //---------------- { // 全チップの小節解像度の最小公倍数を計算する。 int 小節解像度の最小公倍数 = chips[ 0 ].小節解像度; for( int i = 1; i < chips.Count; i++ ) 小節解像度の最小公倍数 = _最小公倍数を返す( 小節解像度の最小公倍数, chips[ i ].小節解像度 ); // 小節解像度を最小公倍数で統一する。 for( int i = 0; i < chips.Count; i++ ) { chips[ i ].小節内位置 *= 小節解像度の最小公倍数 / chips[ i ].小節解像度; // 必ず割り切れる chips[ i ].小節解像度 = 小節解像度の最小公倍数; } // オブジェクト記述を短くするべく、ある程度までの素数で約分する。 for( int i = 0; i < _素数リスト.Length; i++ ) { while( true ) { bool すべて割り切れる = true; foreach( var chip in chips ) { if( 0 != ( chip.小節内位置 % _素数リスト[ i ] ) || 0 != ( chip.小節解像度 % _素数リスト[ i ] ) ) { すべて割り切れる = false; break; } } if( !すべて割り切れる ) break; foreach( var chip in chips ) { chip.小節内位置 /= _素数リスト[ i ]; chip.小節解像度 /= _素数リスト[ i ]; } } } } //---------------- #endregion // オブジェクト記述を作成する。 string DTXチャンネル番号 = "00"; var オブジェクト記述 = new int[ chips[ 0 ].小節解像度 ]; for( int i = 0; i < オブジェクト記述.Length; i++ ) オブジェクト記述[ i ] = 0; foreach( var chip in chips ) { switch( chipType ) { case チップ種別.背景動画: オブジェクト記述[ chip.小節内位置 ] = 1; // 背景動画は #VIDEO01 固定 DTXチャンネル番号 = "5A"; break; case チップ種別.BGM: オブジェクト記述[ chip.小節内位置 ] = 12 * 36 + 0; // BGM は #WAVC0 固定 DTXチャンネル番号 = "01"; break; case チップ種別.BPM: オブジェクト記述[ chip.小節内位置 ] = _BPMリスト.IndexOf( chip.BPM ) + 1; // #BPMzz: に対応する zz DTXチャンネル番号 = "08"; break; default: オブジェクト記述[ chip.小節内位置 ] = _チップ種別マップ[ chipType ].先頭wav番号 + ( chip.音量 - 1 ); DTXチャンネル番号 = _チップ種別マップ[ chipType ].DTXチャンネル番号.ToString( "X2" ); break; } } sw.Write( $"#{_zxx( 小節番号 )}{DTXチャンネル番号}: " ); for( int i = 0; i < オブジェクト記述.Length; i++ ) sw.Write( $"{_zz( オブジェクト記述[ i ] )}" ); sw.WriteLine(); } } sw.WriteLine( "" ); } // ローカル private static List<double> _BPMリスト = new List<double>(); private static readonly Dictionary<チップ種別, (string ファイル名, int 先頭wav番号, int DTXチャンネル番号)> _チップ種別マップ; private static string _xx( int 値 ) { if( 0 > 値 || 16 * 16 <= 値 ) throw new ArgumentOutOfRangeException( $"値が 0~{16 * 16 - 1} の範囲を越えています。" ); return 値.ToString( "X2" ); } private static string _zxx( int 値 ) { if( 0 > 値 || 36 * 100 <= 値 ) throw new ArgumentOutOfRangeException( $"値が 0~{36 * 100 - 1} の範囲を越えています。" ); int d3 = 値 / 100; int d21 = 値 % 100; return ( _36進数変換表[ d3 ] + d21.ToString( "D2" ) ); } private static string _zz( int 値 ) { if( 0 > 値 || 36 * 36 <= 値 ) throw new ArgumentOutOfRangeException( $"値が 0~{36 * 36 - 1} の範囲を越えています。" ); char ch2 = _36進数変換表[ 値 / 36 ]; char ch1 = _36進数変換表[ 値 % 36 ]; return ( ch2.ToString() + ch1.ToString() ); } private static int _zz( string zz ) { if( zz.Length < 2 ) return -1; int d2 = _36進数変換表.IndexOf( zz[ 0 ] ); if( d2 < 0 ) return -1; if( d2 >= 36 ) d2 -= ( 36 - 10 ); // 小文字の場合 int d1 = _36進数変換表.IndexOf( zz[ 1 ] ); if( d1 < 0 ) return -1; if( d1 >= 36 ) d1 -= ( 36 - 10 ); // 小文字の場合 return d2 * 36 + d1; } private static readonly string _36進数変換表; private static int _最大公約数を返す( int m, int n ) { if( ( 0 > m ) || ( 0 > n ) ) throw new Exception( "引数に負数は指定できません。" ); if( 0 == m ) return n; if( 0 == n ) return m; // ユーグリッドの互除法 int r; while( ( r = m % n ) != 0 ) { m = n; n = r; } return n; } private static int _最小公倍数を返す( int m, int n ) { if( ( 0 >= m ) || ( 0 >= n ) ) throw new Exception( "引数に0以下の数は指定できません。" ); return ( m * n / _最大公約数を返す( m, n ) ); } private static readonly int[] _素数リスト; // 静的コンストラクタ static SSTFoverDTX() { // 生成順序に依存関係がある(36進数変換表はチップ種別マップより先に初期化されている必要がある)ので、 // メンバ初期化子ではなく、静的コンストラクタで順序づけて生成する。 _36進数変換表 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; _チップ種別マップ = new Dictionary<チップ種別, (string ファイル名, int 先頭wav番号, int DTXチャンネル番号)>() { { チップ種別.LeftCrash, ( @"DrumSounds\LeftCrash.wav", _zz("10"), 0x1A ) }, { チップ種別.LeftCymbal_Mute, ( @"DrumSounds\LeftCymbalMute.wav", _zz("18"), 0x61 ) }, { チップ種別.HiHat_Close, ( @"DrumSounds\HiHatClose.wav", _zz("20"), 0x11 ) }, { チップ種別.HiHat_Open, ( @"DrumSounds\HiHatOpen.wav", _zz("28"), 0x18 ) }, { チップ種別.HiHat_HalfOpen, ( @"DrumSounds\HiHatHalfOpen.wav", _zz("2G"), 0x18 ) }, { チップ種別.HiHat_Foot, ( @"DrumSounds\HiHatFoot.wav", _zz("2O"), 0x1B ) }, { チップ種別.Snare, ( @"DrumSounds\Snare.wav", _zz("30"), 0x12 ) }, { チップ種別.Snare_OpenRim, ( @"DrumSounds\SnareOpenRim.wav", _zz("38"), 0x12 ) }, { チップ種別.Snare_ClosedRim, ( @"DrumSounds\SnareClosedRim.wav", _zz("3G"), 0x12 ) }, { チップ種別.Snare_Ghost, ( @"DrumSounds\SnareGhost.wav", _zz("3O"), 0x12 ) }, { チップ種別.Bass, ( @"DrumSounds\Bass.wav", _zz("40"), 0x13 ) }, { チップ種別.LeftBass, ( @"DrumSounds\Bass.wav", _zz("48"), 0x1C ) }, { チップ種別.Tom1, ( @"DrumSounds\Tom1.wav", _zz("50"), 0x14 ) }, { チップ種別.Tom1_Rim, ( @"DrumSounds\Tom1Rim.wav", _zz("58"), 0x14 ) }, { チップ種別.Tom2, ( @"DrumSounds\Tom2.wav", _zz("60"), 0x15 ) }, { チップ種別.Tom2_Rim, ( @"DrumSounds\Tom2Rim.wav", _zz("68"), 0x15 ) }, { チップ種別.Tom3, ( @"DrumSounds\Tom3.wav", _zz("70"), 0x17 ) }, { チップ種別.Tom3_Rim, ( @"DrumSounds\Tom3Rim.wav", _zz("78"), 0x17 ) }, { チップ種別.RightCrash, ( @"DrumSounds\RightCrash.wav", _zz("80"), 0x16 ) }, { チップ種別.RightCymbal_Mute, ( @"DrumSounds\RightCymbalMute.wav", _zz("88"), 0x62 ) }, { チップ種別.Ride, ( @"DrumSounds\Ride.wav", _zz("90"), 0x19 ) }, { チップ種別.Ride_Cup, ( @"DrumSounds\RideCup.wav", _zz("98"), 0x19 ) }, { チップ種別.China, ( @"DrumSounds\China.wav", _zz("A0"), 0x16 ) }, { チップ種別.Splash, ( @"DrumSounds\Splash.wav", _zz("B0"), 0x1A ) }, }; _素数リスト = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, }; } } } } <|start_filename|>FDK/定間隔進行.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { /// <summary> /// 一定間隔ごとの進行処理を実現するクラス。 /// </summary> /// <remarks> /// <para> 例えば、 /// <code> /// var cf = new C定間隔進行(); /// cf.経過時間の分だけ進行する( 400, 定間隔処理 ); /// </code> /// と記述した場合、400ms ごとに 定間隔処理() が実行されるようになる。 /// </para> /// <para> /// ただし、この動作は「経過時間の分だけ進行する()」メソッドを呼び出した時に、定間隔処理() を「必要な回数だけ反復実行」する仕様である。 /// 例えば、先述の例において、メソッドの呼び出し時点で、前回の同メソッド(またはコンストラクタ)の呼び出しから 900ms が経過していたとすると、 /// 定間隔処理() は 900÷400 = 2回実行され、残りの 100ms が経過時間として次回に繰り越される。 /// (一回の処理に時間がかかった場合にも定間隔処理が並列実行されるわけではない。) /// </para> /// <para> /// なお、定間隔処理にラムダ式を使用する場合は、キャプチャ変数のライフサイクル(実行される時点でまだ存在しているか否か)に留意し、弱い参照 の利用も検討すること。 /// </para> /// </remarks> public class 定間隔進行 { /// <summary> /// コンストラクタ。 /// 初期化し、同時に間隔の計測も開始する。 /// </summary> public 定間隔進行() { this.経過時間の計測を開始する(); } public void 経過時間の計測を開始する() { lock( this._スレッド間同期 ) { this._タイマ.リセットする(); } } public void 経過時間の計測を一時停止する() { lock( this._スレッド間同期 ) { this._タイマ.一時停止する(); } } public void 経過時間の計測を再開する() { lock( this._スレッド間同期 ) { this._タイマ.再開する(); } } public void 経過時間の分だけ進行する( long 間隔ms, Action 定間隔処理 ) { lock( this._スレッド間同期 ) { // 現在時刻を取得する。 this._タイマ.現在のカウントをキャプチャする(); long 現在時刻ms = this._タイマ.現在のキャプチャカウント100ns / 10_000; // 初めての進行の場合、前回時刻を初期化する。 if( this._前回の進行時刻ms == QPCTimer.未使用 ) this._前回の進行時刻ms = 現在時刻ms; // (ないと思うが)タイマが一回りしてしまった時のための保護。正常動作を保証するものではない。 if( this._前回の進行時刻ms > 現在時刻ms ) this._前回の進行時刻ms = 現在時刻ms; // 経過時間における回数だけ、処理を実行する。 while( ( 現在時刻ms - this._前回の進行時刻ms ) >= 間隔ms ) { 定間隔処理(); this._前回の進行時刻ms += 間隔ms; } } } private long _前回の進行時刻ms = QPCTimer.未使用; private readonly QPCTimer _タイマ = new QPCTimer(); private readonly object _スレッド間同期 = new object(); } } <|start_filename|>SSTFEditor/数値入力ダイアログ.designer.cs<|end_filename|> namespace SSTFEditor { partial class 数値入力ダイアログ { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( 数値入力ダイアログ ) ); this.labelメッセージ = new System.Windows.Forms.Label(); this.numericUpDown数値 = new System.Windows.Forms.NumericUpDown(); this.buttonOK = new System.Windows.Forms.Button(); this.buttonキャンセル = new System.Windows.Forms.Button(); ( (System.ComponentModel.ISupportInitialize) ( this.numericUpDown数値 ) ).BeginInit(); this.SuspendLayout(); // // labelメッセージ // resources.ApplyResources( this.labelメッセージ, "labelメッセージ" ); this.labelメッセージ.Name = "labelメッセージ"; // // numericUpDown数値 // this.numericUpDown数値.DecimalPlaces = 4; resources.ApplyResources( this.numericUpDown数値, "numericUpDown数値" ); this.numericUpDown数値.Maximum = new decimal( new int[] { 1000, 0, 0, 0} ); this.numericUpDown数値.Minimum = new decimal( new int[] { 1, 0, 0, 262144} ); this.numericUpDown数値.Name = "numericUpDown数値"; this.numericUpDown数値.Value = new decimal( new int[] { 1, 0, 0, 262144} ); this.numericUpDown数値.KeyDown += new System.Windows.Forms.KeyEventHandler( this.numericUpDown数値_KeyDown ); // // buttonOK // resources.ApplyResources( this.buttonOK, "buttonOK" ); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Name = "buttonOK"; this.buttonOK.UseVisualStyleBackColor = true; // // buttonキャンセル // resources.ApplyResources( this.buttonキャンセル, "buttonキャンセル" ); this.buttonキャンセル.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonキャンセル.Name = "buttonキャンセル"; this.buttonキャンセル.UseVisualStyleBackColor = true; // // C数値入力ダイアログ // resources.ApplyResources( this, "$this" ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ControlBox = false; this.Controls.Add( this.buttonOK ); this.Controls.Add( this.buttonキャンセル ); this.Controls.Add( this.numericUpDown数値 ); this.Controls.Add( this.labelメッセージ ); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "C数値入力ダイアログ"; this.ShowIcon = false; this.ShowInTaskbar = false; ( (System.ComponentModel.ISupportInitialize) ( this.numericUpDown数値 ) ).EndInit(); this.ResumeLayout( false ); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelメッセージ; private System.Windows.Forms.NumericUpDown numericUpDown数値; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonキャンセル; } } <|start_filename|>DTXMania2/ステージ/07演奏/ドラムチッププロパティ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SSTF=SSTFormat.v004; namespace DTXMania2.演奏 { /// <summary> /// 譜面のチップ(<see cref="チップ種別"/>)をキーとして、様々なコンフィグプロパティを定義する。 /// </summary> class ドラムチッププロパティ { // 主キー; SSTFにおけるチップの種別と、チップが属するレーンの種別。 public SSTF.チップ種別 チップ種別 { get; set; } public SSTF.レーン種別 レーン種別 { get; set; } // 表示 /// <summary> /// チップが表示される画面上のレーン。 /// オプション設定により変更可能な場合がある。 /// </summary> public 表示レーン種別 表示レーン種別 { get; set; } /// <summary> /// チップを描画形態(見た目)で分類したチップ種別。 /// </summary> public 表示チップ種別 表示チップ種別 { get; set; } // 入力 /// <summary> /// チップにヒット可能な入力の種別。 /// </summary> /// <remarks> /// チップと <see cref="ドラム入力種別"/> は N : 1 である。 /// これは、1つのドラム入力がヒット可能なチップが複数存在する場合があることを意味する。 /// 例えば、<see cref="ドラム入力種別.Ride"/> は、Ride チップと Ride_Cup チップをヒットすることができる。 /// </remarks> public ドラム入力種別 ドラム入力種別 { get; set; } /// <summary> /// チップが属する AutoPlay種別。 /// </summary> /// <remarks> /// AutoPlay は、(チップ単位でもレーン単位でも入力単位でもなく)<see cref="AutoPlay種別"/> 単位で ON / OFF される。 /// チップの属する <see cref="AutoPlay種別"/> が ON である場合、このチップの AutoPlay は ON である。OFF も同様。 /// </remarks> public AutoPlay種別 AutoPlay種別 { get; set; } /// <summary> /// チップの属する入力グループ種別。 /// </summary> /// <remarks> /// 同じ <see cref="入力グループ種別"/> に属するチップは、各チップの <see cref="ドラム入力種別"/> の /// いずれかでヒットすることができる。 /// 例えば、Ride チップと HHClose が同じ入力グループ種別に属している場合、 /// Ride 入力で HHClose チップをヒットすることができる。 /// </remarks> public 入力グループ種別 入力グループ種別 { get; set; } // ヒット /// <summary> /// このチップのサウンドの再生時に、同じ<see cref="消音グループ種別"/>に属するチップのサウンドの /// 消音が必要であるかどうかを示す。 /// </summary> public bool 発声前消音 { get; set; } /// <summary> /// チップのサウンドが属する消音グループ。 /// どこにも属さないなら <see cref="消音グループ種別.Unknown"/>。 /// </summary> /// <remarks> /// 同じ<see cref="消音グループ種別"/>に属するチップのサウンドは、同時に1つしか再生することができない。 /// </remarks> public 消音グループ種別 消音グループ種別 { get; set; } /// <summary> /// チップが AutoPlay ON のとき、ヒット判定バー上で何らかのヒット処理が自動で行われる場合は true。 /// </summary> public bool AutoPlayON_自動ヒット => ( this.AutoPlayON_自動ヒット_再生 || this.AutoPlayON_自動ヒット_非表示 || this.AutoPlayON_自動ヒット_判定 ); /// <summary> /// チップが AutoPlay ON のとき、ヒット判定バー上で再生処理が行われる場合は true。 /// </summary> public bool AutoPlayON_自動ヒット_再生 { get; set; } /// <summary> /// チップが AutoPlay ON のとき、ヒット判定バー上でチップが非表示になる場合は true。 /// </summary> public bool AutoPlayON_自動ヒット_非表示 { get; set; } /// <summary> /// チップが AutoPlay ON のとき、ヒット判定バー上でヒット判定処理が行われる場合は true。 /// </summary> public bool AutoPlayON_自動ヒット_判定 { get; set; } /// <summary> /// チップが AutoPlay ON のとき、ヒット判定バー通過後にMISS判定処理が行われる場合は true。 /// </summary> public bool AutoPlayON_Miss判定 { get; set; } /// <summary> /// チップが AutoPlay OFF のとき、ヒット判定バー上で何らかのヒット処理が自動で行われる場合は true。 /// </summary> public bool AutoPlayOFF_自動ヒット => ( this.AutoPlayOFF_自動ヒット_再生 || this.AutoPlayOFF_自動ヒット_非表示 || this.AutoPlayOFF_自動ヒット_判定 ); /// <summary> /// チップが AutoPlay OFF のとき、ヒット判定バー上で再生処理が行われる場合は true。 /// </summary> public bool AutoPlayOFF_自動ヒット_再生 { get; set; } /// <summary> /// チップが AutoPlay OFF のとき、ヒット判定バー上でチップが非表示になる場合は true。 /// </summary> public bool AutoPlayOFF_自動ヒット_非表示 { get; set; } /// <summary> /// チップが AutoPlay OFF のとき、ヒット判定バー上でヒット判定処理が行われる場合は true。 /// </summary> public bool AutoPlayOFF_自動ヒット_判定 { get; set; } /// <summary> /// チップが AutoPlay OFF かつユーザの入力がヒットした時に、何らかの処理が行われる場合は true。 /// </summary> public bool AutoPlayOFF_ユーザヒット => ( this.AutoPlayOFF_ユーザヒット_再生 || this.AutoPlayOFF_ユーザヒット_非表示 || this.AutoPlayOFF_ユーザヒット_判定 ); /// <summary> /// チップが AutoPlay OFF かつユーザの入力がヒットした時に、再生処理が行われる場合は true。 /// </summary> public bool AutoPlayOFF_ユーザヒット_再生 { get; set; } /// <summary> /// チップが AutoPlay OFF かつユーザの入力がヒットした時に、チップが非表示になる場合は true。 /// </summary> public bool AutoPlayOFF_ユーザヒット_非表示 { get; set; } /// <summary> /// チップが AutoPlay OFF かつユーザの入力がヒットした時に、ヒット判定処理が行われる場合は true。 /// </summary> public bool AutoPlayOFF_ユーザヒット_判定 { get; set; } /// <summary> /// チップが AutoPlay OFF のとき、ヒット判定バー通過後にMISS判定処理が行われる場合は true。 /// </summary> public bool AutoPlayOFF_Miss判定 { get; set; } } } <|start_filename|>FDK/Counter.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { /// <summary> /// ある int 型整数を、開始値から終了値まで、一定間隔で単純増加させるカウンタ。 /// 終了値に達したら、それ以降は終了値を維持する(不変)。 /// </summary> public class Counter { /// <summary> /// カウンタの開始値。 /// 常に終了値以下。 /// </summary> public int 開始値 { get { lock( this._スレッド間同期 ) { return this._開始値; } } } /// <summary> /// カウンタの終了値。 /// 常に開始値以上。 /// </summary> public int 終了値 { get { lock( this._スレッド間同期 ) { return this._終了値; } } } /// <summary> /// カウンタを進行し、現在の値を返す。 /// </summary> public int 現在値 { get { lock( this._スレッド間同期 ) { this.進行する(); return this._現在値; } } } /// <summary> /// カウンタを進行し、現在の値を 0.0~1.0 の割合値に変換して返す。 /// </summary> /// <return> /// 0.0 (開始値) ~ 1.0 (終了値) /// </return> public float 現在値の割合 { get { lock( this._スレッド間同期 ) { if( this._開始値 != this._終了値 ) { this.進行する(); return (float)( this._現在値 - this._開始値 ) / (float)( this._終了値 - this._開始値 ); } else { return 1.0f; // 開始値 = 終了値 なら常に 1.0 とする。 } } } } /// <summary> /// カウンタを進行し、その結果、カウンタの進行がまだ動作中なら true を返す。 /// (終了値に達しているかどうかは関係なく、開始前or一時停止中であるならfalseを返す。) /// </summary> public bool 動作中である { get { lock( this._スレッド間同期 ) { this.進行する(); // 終了してるかどうか判定する前に、溜まってる進行を全部消化する。 return this._動作中; } } } /// <summary> /// カウンタの進行が一時停止されているなら true を返す。 /// (終了値に達しているかどうかは関係なく、開始前or一時停止中であるならtrueを返す。) /// </summary> public bool 停止中である => !this.動作中である; /// <summary> /// カウンタを進行し、その結果、現在値が終了値に達していたら true を返す。 /// </summary> public bool 終了値に達した { get { lock( this._スレッド間同期 ) { this.進行する(); return ( this._現在値 >= this._終了値 ); } } } /// <summary> /// カウンタを進行し、その結果、まだ現在値が終了値に達していないら true を返す。 /// </summary> public bool 終了値に達していない => !this.終了値に達した; /// <summary> /// コンストラクタ。 /// 初期化のみ行い、カウンタは開始しない。 /// </summary> public Counter() { this._間隔ms = QPCTimer.未使用; this._定間隔進行 = null!; this._開始値 = 0; this._終了値 = 0; this._現在値 = 0; this._動作中 = false; } /// <summary> /// コンストラクタ。 /// 初期化し、同時にカウンタを開始する。 /// </summary> public Counter( int 最初の値, int 最後の値, long 値をひとつ増加させるのにかける時間ms = 1000 ) : this() { this.開始する( 最初の値, 最後の値, 値をひとつ増加させるのにかける時間ms ); } /// <summary> /// カウンタの現在値を最初の値に設定し、カウンタの進行を開始する。 /// </summary> public void 開始する( int 最初の値, int 最後の値, long 値をひとつ増加させるのにかける時間ms = 1000 ) { lock( this._スレッド間同期 ) { this._間隔ms = 値をひとつ増加させるのにかける時間ms; this._定間隔進行 = new 定間隔進行(); // 同時に開始する。 this._開始値 = 最初の値; this._終了値 = Math.Max( 最初の値, 最後の値 ); // 逆転しないことを保証。 this._現在値 = 最初の値; this._動作中 = true; } } /// <remarks> /// 一時停止中は、カウンタを進行させても、現在値が進まない。 /// </remarks> public void 一時停止する() { lock( this._スレッド間同期 ) { this._定間隔進行.経過時間の計測を一時停止する(); this._動作中 = false; } } /// <summary> /// 一時停止しているカウンタを、再び進行できるようにする。 /// </summary> public void 再開する() { lock( this._スレッド間同期 ) { this._定間隔進行.経過時間の計測を再開する(); this._動作中 = true; } } /// <summary> /// 前回のこのメソッドの呼び出しからの経過時間をもとに、必要なだけ現在値を増加させる。 /// カウント値が終了値に達している場合は、それ以上増加しない(終了値を維持する)。 /// </summary> public void 進行する() { if( this._間隔ms == QPCTimer.未使用 ) return; // 開始されていないなら無視。 lock( this._スレッド間同期 ) { this._定間隔進行?.経過時間の分だけ進行する( this._間隔ms, () => { if( this._動作中 ) { if( this._現在値 < this._終了値 ) { this._現在値++; } else { // 終了値以降、現在値は不変。 this._現在値 = this._終了値; } } } ); } } private int _開始値 = 0; private int _終了値 = 0; private int _現在値 = 0; private bool _動作中 = false; private long _間隔ms = QPCTimer.未使用; private 定間隔進行 _定間隔進行; private readonly object _スレッド間同期 = new object(); } } <|start_filename|>DTXMania2/サウンド/システムサウンド種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace DTXMania2 { enum システムサウンド種別 { [Alias( "CursorMove" )] カーソル移動音, [Alias( "Decide" )] 決定音, [Alias( "Cancel" )] 取消音, [Alias( "Change" )] 変更音, [Alias( "StageFailed" )] ステージ失敗, [Alias( "StageClear" )] ステージクリア, [Alias( "FullCombo" )] フルコンボ, [Alias( "Audience" )] 歓声, [Alias( "BootStage_Start" )] 起動ステージ_開始音, [Alias( "BootStage_LoopBGM" )] 起動ステージ_ループBGM, [Alias( "TitleStage_Start" )] タイトルステージ_開始音, [Alias( "TitleStage_LoopBGM" )] タイトルステージ_ループBGM, [Alias( "TitleStage_Decide" )] タイトルステージ_確定音, [Alias( "AuthStage_Start" )] 認証ステージ_開始音, [Alias( "AuthStage_LoopBGM" )] 認証ステージ_ループBGM, [Alias( "AuthStage_Decide" )] 認証ステージ_ログイン音, [Alias( "SelectStage_Start" )] 選曲ステージ_開始音, //[Alias( "SelectStage_LoopBGM" )] 選曲ステージ_ループBGM, --> 未対応 [Alias( "SelectStage_Decide" )] 選曲ステージ_曲決定音, [Alias( "OptionStage_Start" )] オプション設定ステージ_開始音, [Alias( "LoadingStage_Start" )] 曲読み込みステージ_開始音, [Alias( "LoadingStage_LoopBGM" )] 曲読み込みステージ_ループBGM, [Alias( "ExitStage_Start" )] 終了ステージ_開始音, } } <|start_filename|>DTXMania2/ステージ/04選曲/UpdatingSoglistパネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using FDK; using SharpDX.Direct2D1; namespace DTXMania2.選曲 { class UpdatingSoglistパネル : IDisposable { // 生成と終了 public UpdatingSoglistパネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パネル画像 = new 画像D2D( @"$(Images)\SelectStage\UpdatingSonglist.png" ); this._明滅カウンタ = new LoopCounter( 0, 99, 10 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._パネル画像.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, float x, float y ) { // 現行化タスクが稼働しているときのみ描画する。 if( Global.App.現行化.現行化中 ) { float 不透明度 = MathF.Sin( MathF.PI * this._明滅カウンタ.現在値 / 100f ); this._パネル画像.描画する( d2ddc, x, y, 不透明度0to1: 不透明度 ); } } // ローカル private readonly 画像D2D _パネル画像; private readonly LoopCounter _明滅カウンタ; } } <|start_filename|>SSTFormat/v004/スコア.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace SSTFormat.v004 { public partial class スコア : ISSTFScore { // 定数 /// <summary> /// このソースが実装するSSTFバージョン。 /// </summary> public static readonly Version SSTFVERSION = new Version( 4, 1, 0, 0 ); public const double 初期BPM = 120.0; public const double 初期小節解像度 = 480.0; // ヘッダ /// <summary> /// SSTFバージョン。 /// ファイルから読み込んだ場合、ファイルにSSTFVersionの記述がなかった場合は v1.0.0.0 とみなす。 /// </summary> public Version SSTFバージョン { get; set; } /// <summary> /// このスコアの曲名。 /// </summary> public string 曲名 { get; set; } /// <summary> /// このスコアのアーティスト名。 /// 作曲者名、団体名、作品名、スコア作者名など、内容は任意。 /// </summary> public string アーティスト名 { get; set; } /// <summary> /// この曲の説明文。内容は任意。 /// </summary> public string 説明文 { get; set; } /// <summary> /// この曲の難易度。 /// 易:0.00~9.99:難 /// </summary> public double 難易度 { get; set; } /// <summary> /// このスコアが作成されたときのサウンドデバイスの遅延量[ミリ秒]。 /// </summary> public float サウンドデバイス遅延ms { get; set; } = 0f; /// <summary> /// このスコアがビュアーで再生される時の再生速度。 /// </summary> public double Viewerでの再生速度 { get; set; } = 1.0; // ヘッダ:プレビュー /// <summary> /// プレビュー画像ファイルの、 /// <see cref="譜面ファイルのあるフォルダ"/> からの相対パス。 /// </summary> public string プレビュー画像ファイル名 { get; set; } /// <summary> /// プレビュー音声ファイルの、 /// <see cref="譜面ファイルのあるフォルダ"/> からの相対パス。 /// </summary> public string プレビュー音声ファイル名 { get; set; } /// <summary> /// プレビュー動画ファイルの、 /// <see cref="譜面ファイルのあるフォルダ"/> からの相対パス。 /// </summary> public string プレビュー動画ファイル名 { get; set; } // ヘッダ:ファイル・フォルダ情報 /// <summary> /// この曲の BGV として再生する動画ファイルの、 /// <see cref="譜面ファイルのあるフォルダ"/> からの相対パス。 /// </summary> /// <remarks> /// このファイルをソースとして、<see cref="チップ種別.背景動画"/> のチップで動画が再生される。 /// SSTFから変換された場合には、このフィールドに格納されたファイルは、#AVI01(固定)として <see cref="AVIリスト"/> にも登録される。 /// DTX他から変換された場合には、このフィールドは未使用(nullまたは空文字列)→ 動画は<see cref="AVIリスト"/>、音声は<see cref="WAVリスト"/>を使用する。 /// </remarks> public string BGVファイル名 { get; set; } /// <summary> /// この曲の BGM として再生する動画ファイルの、 /// <see cref="譜面ファイルのあるフォルダ"/> からの相対パス。 /// </summary> /// <remarks> /// このファイルをソースとして、<see cref="チップ種別.BGM"/> のチップで音声が再生される。 /// SSTFから変換された場合には、このフィールドに格納されたファイルは、#WAV01(固定)として <see cref="WAVリスト"/> にも登録される。 /// DTX他から変換された場合には、このフィールドは未使用(nullまたは空文字列)→ 動画は<see cref="AVIリスト"/>、音声は<see cref="WAVリスト"/>を使用する。 /// </remarks> public string BGMファイル名 { get; set; } /// <summary> /// この曲の背景画像として描画する画像ファイルの、<see cref="譜面ファイルのあるフォルダ"/> からの相対パス。 /// </summary> public string 背景画像ファイル名 { get; set; } /// <summary> /// 譜面ファイルの絶対パス。 /// </summary> public string 譜面ファイルの絶対パス { get; set; } = null; /// <summary> /// 譜面ファイルのあるフォルダの絶対パス。 /// </summary> /// <remarks> /// WAV, AVI ファイルへのパスには、このフィールドではなく <see cref="PATH_WAV"/> を使うこと。 /// </remarks> public string 譜面ファイルのあるフォルダ => ( string.IsNullOrEmpty( this.譜面ファイルの絶対パス ) ) ? "" : Path.GetDirectoryName( this.譜面ファイルの絶対パス ); /// <summary> /// WAV と AVI ファイルの基点となるフォルダの絶対パス。 /// </summary> /// <remarks> /// 譜面で指定された PATH_WAV が空文字列または相対パスの場合、譜面のあるフォルダからの相対パスとしてPATH_WAVを適用した絶対パスを返す。 ///  例:譜面ファイルが "D:\DTXData\DemoSong\score.sstf" であり、譜面内で PATH_WAV が未定義の場合、このプロパティは"D:\DTXData\DemoSong" を返す。 ///  例:譜面ファイルが "D:\DTXData\DemoSong\score.sstf" であり、譜面内で PATH_WAV=Sounds と指定されている場合、このプロパティは"D:\DTXData\DemoSong\Sounds" を返す。 /// 譜面で指定された PATH_WAV が絶対パスの場合、その PATH_WAV をそのまま返す。 ///  例:譜面ファイルが "D:\DTXData\DemoSong\score.sstf" であり、譜面内で PATH_WAV=E:\Sounds と指定されている場合、このプロパティは"E:\Sounds" を返す。 /// </remarks> public string PATH_WAV { get { if( string.IsNullOrEmpty( this._PATH_WAV ) ) { // (A) PATH_WAV が未指定の場合、譜面のあるフォルダの絶対パスを返す。 return this.譜面ファイルのあるフォルダ; } else if( !Path.IsPathRooted( this._PATH_WAV ) ) { // (B) 譜面で指定された PATH_WAV が空文字列または相対パスの場合、譜面のあるフォルダからの相対パスとしてPATH_WAVを適用した絶対パスを返す。 return Path.Combine( this.譜面ファイルのあるフォルダ, this._PATH_WAV ); } else { // (C) 譜面で指定された PATH_WAV が絶対パスの場合、その PATH_WAV をそのまま返す。 return this._PATH_WAV; } } } // チップリスト /// <summary> /// このスコアに存在するすべてのチップのリスト。 /// </summary> public List<チップ> チップリスト { get; protected set; } // 小節長倍率リスト /// <summary> /// 小節ごとの倍率。 /// インデックス番号が小節番号を表し、小節 0 から最大小節まで、すべての小節の倍率がこのリストに含まれる。 /// </summary> public List<double> 小節長倍率リスト { get; protected set; } public double 小節長倍率を取得する( int 小節番号 ) { // 小節長倍率リスト が短ければ増設する。 if( 小節番号 >= this.小節長倍率リスト.Count ) { int 不足数 = 小節番号 - this.小節長倍率リスト.Count + 1; for( int i = 0; i < 不足数; i++ ) this.小節長倍率リスト.Add( 1.0 ); } // 小節番号に対応する倍率を返す。 return this.小節長倍率リスト[ 小節番号 ]; } public void 小節長倍率を設定する( int 小節番号, double 倍率 ) { // 小節長倍率リスト が短ければ増設する。 if( 小節番号 >= this.小節長倍率リスト.Count ) { int 不足数 = 小節番号 - this.小節長倍率リスト.Count + 1; for( int i = 0; i < 不足数; i++ ) this.小節長倍率リスト.Add( 1.0 ); } // 小節番号に対応付けて倍率を登録する。 this.小節長倍率リスト[ 小節番号 ] = 倍率; } // 小節メモリスト /// <summary> /// メモリスト。 /// [key: 小節番号, value:メモ] /// </summary> public Dictionary<int, string> 小節メモリスト { get; protected set; } // WAVリスト /// <summary> /// #WAVzz で指定された、サウンドファイルへの相対パス他。 /// パスの基点は、#PATH_WAV があればそこ、なければ曲譜面ファイルと同じ場所。 /// [key: zz番号] /// </summary> public Dictionary<int, WAV情報> WAVリスト { get; protected set; } public class WAV情報 { public string ファイルパス { get; set; } public bool 多重再生する { get; set; } public bool BGMである { get; set; } } // AVIリスト /// <summary> /// #AVIzz で指定された、動画ファイルへの相対パス。 /// パスの基点は、#PATH_WAV があればそこ、なければ曲譜面ファイルと同じ場所。 /// [key: zz番号] /// </summary> public Dictionary<int, string> AVIリスト { get; protected set; } // メソッド public スコア() { this.リセットする(); } public static スコア ファイルから生成する( string スコアファイルの絶対パス, bool ヘッダだけ = false ) { ISSTFScore score = null; var 拡張子 = Path.GetExtension( スコアファイルの絶対パス ).ToLower(); switch( 拡張子 ) { case ".sstf": score = SSTFScoreFactory.CreateFromFile( スコアファイルの絶対パス, ヘッダだけ ); break; case ".dtx": if( SSTFoverDTX.ファイルがSSTFoverDTXである( スコアファイルの絶対パス ) ) score = SSTFoverDTX.ファイルから生成する( スコアファイルの絶対パス, ヘッダだけ ); else score = DTX.ファイルから生成する( スコアファイルの絶対パス, DTX.データ種別.DTX, ヘッダだけ ); break; default: // 通常dtx, gda, 他 score = DTX.ファイルから生成する( スコアファイルの絶対パス, DTX.データ種別.拡張子から判定, ヘッダだけ ); break; } //if( !( ヘッダだけ ) ) // _後処理を行う( score ); --> 生成メソッドの中で行っておくこと。 return (スコア) score; } public static スコア SSTFファイルから生成する( string スコアファイルの絶対パス, bool ヘッダだけ = false ) { return (スコア) SSTF.ファイルから生成する( スコアファイルの絶対パス, ヘッダだけ ); } public スコア( v003.スコア v3score ) { this.曲名 = v3score.曲名; this.アーティスト名 = v3score.アーティスト名; this.説明文 = v3score.説明文; this.難易度 = v3score.難易度; this.プレビュー画像ファイル名 = v3score.プレビュー画像ファイル名; this.プレビュー音声ファイル名 = v3score.プレビュー音声ファイル名; this.プレビュー動画ファイル名 = v3score.プレビュー動画ファイル名; this.サウンドデバイス遅延ms = v3score.サウンドデバイス遅延ms; var 基点フォルダ = Path.GetDirectoryName( v3score.譜面ファイルパス ); #region " 曲ファイルと同じ場所にあるプレビュー画像の検索(v3仕様)" //---------------- if( string.IsNullOrEmpty( this.プレビュー画像ファイル名 ) && !string.IsNullOrEmpty( v3score.譜面ファイルパス ) ) { var _対応するサムネイル画像名 = new[] { "thumb.png", "thumb.bmp", "thumb.jpg", "thumb.jpeg" }; var path = ( from ファイル名 in Directory.GetFiles( 基点フォルダ ) where _対応するサムネイル画像名.Any( thumbファイル名 => ( Path.GetFileName( ファイル名 ).ToLower() == thumbファイル名 ) ) select ファイル名 ).FirstOrDefault(); if( default != path ) { this.プレビュー画像ファイル名 = ( Path.IsPathRooted( path ) ) ? _絶対パスを相対パスに変換する( 基点フォルダ, path ) : path; } } //---------------- #endregion string 背景動画IDファイル = v3score.背景動画ID; this.BGVファイル名 = ( Path.IsPathRooted( 背景動画IDファイル ) ) ? _絶対パスを相対パスに変換する( 基点フォルダ, 背景動画IDファイル ) : 背景動画IDファイル; // v3では、BGV と this.BGMファイル名 = this.BGVファイル名; // BGM は同じファイル。 this.譜面ファイルの絶対パス = v3score.譜面ファイルパス; this._PATH_WAV = v3score.PATH_WAV; if( this._PATH_WAV == "\\" ) this._PATH_WAV = ""; this.チップリスト = new List<チップ>(); foreach( var v3chip in v3score.チップリスト ) this.チップリスト.Add( new チップ( v3chip ) ); this.小節長倍率リスト = v3score.小節長倍率リスト; this.小節メモリスト = v3score.小節メモリスト; //this.空打ちチップマップ = new Dictionary<レーン種別, int>(); //foreach( var v3kara in v3score.空打ちチップマップ ) // this.空打ちチップマップ.Add( (レーン種別) v3kara.Key, v3kara.Value ); this.WAVリスト = new Dictionary<int, WAV情報>(); foreach( var v3wav in v3score.WAVリスト ) { this.WAVリスト.Add( v3wav.Key, new WAV情報 { ファイルパス = v3wav.Value.ファイルパス, 多重再生する = v3wav.Value.多重再生する, BGMである = false, } ); } this.AVIリスト = v3score.AVIリスト; if( !string.IsNullOrEmpty( this.BGVファイル名 ) ) { #region " 背景動画が有効の場合に必要な追加処理。" //---------------- // avi01 に登録。 this.AVIリスト[ 1 ] = this.BGVファイル名; // wav01 にも登録。 if( !( this.WAVリスト.ContainsKey( 1 ) ) ) this.WAVリスト.Add( 1, new WAV情報() ); this.WAVリスト[ 1 ].ファイルパス = this.BGMファイル名; this.WAVリスト[ 1 ].多重再生する = false; this.WAVリスト[ 1 ].BGMである = true; // 背景動画チップと同じ場所にBGMチップを追加する。 var 作業前リスト = this.チップリスト; this.チップリスト = new List<チップ>(); // Clear() はNG foreach( var chip in 作業前リスト ) { // コピーしながら、 this.チップリスト.Add( chip ); // 必要あれば追加する。 if( chip.チップ種別 == チップ種別.背景動画 ) { chip.チップサブID = 1; // zz = 01 で固定。 var bgmChip = (チップ) chip.Clone(); bgmChip.チップ種別 = チップ種別.BGM; // チップ種別以外は共通 this.チップリスト.Add( bgmChip ); } } //---------------- #endregion } } public void リセットする() { this.SSTFバージョン = SSTFVERSION; this.曲名 = "(no title)"; this.アーティスト名 = ""; this.説明文 = ""; this.難易度 = 5.0; this.サウンドデバイス遅延ms = 0f; this.プレビュー画像ファイル名 = null; this.プレビュー音声ファイル名 = null; this.プレビュー動画ファイル名 = null; this.BGVファイル名 = null; this.BGMファイル名 = null; this.背景画像ファイル名 = null; this.譜面ファイルの絶対パス = null; this._PATH_WAV = ""; this.チップリスト = new List<チップ>(); this.小節長倍率リスト = new List<double>(); this.小節メモリスト = new Dictionary<int, string>(); this.WAVリスト = new Dictionary<int, WAV情報>(); this.AVIリスト = new Dictionary<int, string>(); } /// <summary> /// この譜面における最後(最大)の小節番号。 /// </summary> public int 最大小節番号を返す() { if( 0 < this.チップリスト.Count ) return this.チップリスト.Max( ( chip ) => chip.小節番号 ); return -1; } // ローカル internal static void _スコア読み込み時の後処理を行う( スコア score ) { #region " 小節の先頭チップを追加する。" //---------------- { int 最大小節番号 = score.最大小節番号を返す(); // 「小節の先頭」チップは、小節線と同じく、全小節の先頭位置に置かれる。 // 小節線には今後譜面作者によって位置をアレンジできる可能性を残したいが、 // ビュアーが小節の先頭位置を検索するためには、小節の先頭に置かれるチップが必要になる。 // よって、譜面作者の影響を受けない(ビュアー用の)チップを機械的に配置する。 for( int i = 0; i <= 最大小節番号; i++ ) { score.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.小節の先頭, 小節内位置 = 0, 小節解像度 = 1, } ); } } //---------------- #endregion #region " チップリストを並び替える。" //---------------- score.チップリスト.Sort(); //---------------- #endregion #region " 全チップの発声/描画時刻と譜面内位置を計算する。" //----------------- { // 1. BPMチップを無視し(初期BPMで固定)、小節長倍率, 小節解像度, 小節内位置 から 発声/描画時刻を計算する。 // 以下、チップリストが小節番号順にソートされているという前提で。 double チップが存在する小節の先頭時刻ms = 0.0; int 現在の小節の番号 = 0; foreach( チップ chip in score.チップリスト ) { // チップの小節番号が現在の小節の番号よりも大きい場合、チップが存在する小節に至るまで、チップが存在する小節の先頭時刻ms を更新する。 while( 現在の小節の番号 < chip.小節番号 ) // 現在の小節番号 が chip.小節番号 に追いつくまでループする。 { double 現在の小節の小節長倍率 = score.小節長倍率を取得する( 現在の小節の番号 ); チップが存在する小節の先頭時刻ms += _BPM初期値固定での1小節4拍の時間ms * 現在の小節の小節長倍率; 現在の小節の番号++; } // チップの発声/描画時刻を求める。 double チップが存在する小節の小節長倍率 = score.小節長倍率を取得する( 現在の小節の番号 ); double 時刻sec = ( チップが存在する小節の先頭時刻ms + ( _BPM初期値固定での1小節4拍の時間ms * チップが存在する小節の小節長倍率 * chip.小節内位置 ) / (double) chip.小節解像度 ) / 1000.0; chip.発声時刻sec = 時刻sec; chip.描画時刻sec = 時刻sec; } // 2. 次に、BPMチップを考慮しながら調整する。 double 現在のBPM = スコア.初期BPM; int チップ数 = score.チップリスト.Count; for( int i = 0; i < チップ数; i++ ) { var BPMチップ = score.チップリスト[ i ]; if( BPMチップ.チップ種別 != チップ種別.BPM ) continue; // BPM チップ以外は無視。 // BPMチップより後続の全チップの 発声/描画時刻ms を、新旧BPMの比率(加速率)で修正する。 double 加速率 = BPMチップ.BPM / 現在のBPM; // BPMチップ.dbBPM > 0.0 であることは読み込み時に保証済み。 for( int j = i + 1; j < チップ数; j++ ) { double 時刻sec = BPMチップ.発声時刻sec + ( score.チップリスト[ j ].発声時刻sec - BPMチップ.発声時刻sec ) / 加速率; score.チップリスト[ j ].発声時刻sec = 時刻sec; score.チップリスト[ j ].描画時刻sec = 時刻sec; } 現在のBPM = BPMチップ.BPM; } } //----------------- #endregion } /// <summary> /// WAV と AVI ファイルの基点となるフォルダの相対または絶対パス。 /// 譜面の PATH_WAV= の内容がそのまま入る。 /// </summary> /// <remarks> /// 例: "Sounds" /// </remarks> private string _PATH_WAV = ""; private const double _BPM初期値固定での1小節4拍の時間ms = ( 60.0 * 1000 ) / ( スコア.初期BPM / 4.0 ); private const double _BPM初期値固定での1小節4拍の時間sec = 60.0 / ( スコア.初期BPM / 4.0 ); private static string _絶対パスを相対パスに変換する( string 基点フォルダの絶対パス, string 変換したいフォルダの絶対パス ) { if( null == 変換したいフォルダの絶対パス ) return null; if( !( Path.IsPathRooted( 基点フォルダの絶対パス ) ) ) throw new Exception( $"基点フォルダは絶対パスで指定してください。[{基点フォルダの絶対パス}]" ); if( !( Path.IsPathRooted( 変換したいフォルダの絶対パス ) ) ) throw new Exception( $"変換対象フォルダは絶対パスで指定してください。[{変換したいフォルダの絶対パス}]" ); // 末尾は \ にしておく("+"でパスを連結する事態を想定。Path.Combine() を使う分には、末尾に \ があってもなくてもどっちでもいい。) if( '\\' != 基点フォルダの絶対パス[ 基点フォルダの絶対パス.Length - 1 ] ) 基点フォルダの絶対パス += @"\"; // 絶対-相対パス変換は、System.IO.Path クラスではなく System.IO.Uri クラスでしか行えない。 var 基点uri = new Uri( 基点フォルダの絶対パス ); var 変換前uri = new Uri( 変換したいフォルダの絶対パス ); var 変換後uri = 基点uri.MakeRelativeUri( 変換前uri ); // URI形式になっているので、パス形式に戻す。(具体的には、エスケープ文字を復元し、さらに '/' を '\' に置換する。) return Uri.UnescapeDataString( 変換後uri.ToString() ).Replace( oldChar: '/', newChar: '\\' ); } } } <|start_filename|>SSTFEditor/描画用チップ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SSTF=SSTFormat.v004; namespace SSTFEditor { /// <summary> /// SSTFormat.チップ の機能拡張。 /// </summary> class 描画用チップ : SSTF.チップ { public int 譜面内絶対位置grid { get; set; } = 0; public bool ドラッグ操作により選択中である { get; set; } = false; public bool 選択が確定している { get; set; } = false; public bool 選択が確定していない { get => !this.選択が確定している; set => this.選択が確定している = !value; } public bool 移動済みである { get; set; } = true; public bool 移動されていない { get => !this.移動済みである; set => this.移動済みである = !value; } public string チップ内文字列 { get; set; } = null; public int 枠外レーン数 { get; set; } = 0; public 描画用チップ( SSTF.チップ sstfChip = null ) { if( null != sstfChip ) this.CopyFrom( sstfChip ); this._特別なチップ内文字列を設定する(); } public 描画用チップ( 描画用チップ sstfChip ) { 描画用チップ.Copy( sstfChip, this ); this._特別なチップ内文字列を設定する(); } public static void Copy( 描画用チップ src, 描画用チップ dst ) { ( (SSTF.チップ) dst ).CopyFrom( src ); dst.譜面内絶対位置grid = src.譜面内絶対位置grid; dst.ドラッグ操作により選択中である = src.ドラッグ操作により選択中である; dst.選択が確定している = src.選択が確定している; dst.移動済みである = src.移動済みである; dst.チップ内文字列 = src.チップ内文字列; dst.枠外レーン数 = src.枠外レーン数; } public void CopyFrom( 描画用チップ コピー元チップ ) { 描画用チップ.Copy( コピー元チップ, this ); } private void _特別なチップ内文字列を設定する() { if( this.チップ種別 == SSTF.チップ種別.China ) this.チップ内文字列 = "C N"; if( this.チップ種別 == SSTF.チップ種別.Splash ) this.チップ内文字列 = "S P"; if( this.チップ種別 == SSTF.チップ種別.BPM ) this.チップ内文字列 = this.BPM.ToString( "###.##" ); } } } <|start_filename|>FDK/入力/GameControllerHIDProperty.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace FDK { /// <summary> /// HIDゲームコントローラのプロパティ。 /// </summary> public class GameControllerHIDProperty : IDisposable { public int DeviceID = 0; public string Name = ""; public IntPtr? PreparseData = null; public HID.Caps Caps; public HID.ButtonCaps[] ButtonCaps; public HID.ValueCaps[] ValueCaps; public HID.LinkCollectionNode[] CollectionNodes; /// <summary> /// ボタンの押下状態 /// [Capインデックス][ボタン番号(=UsageMixからの相対値)] /// </summary> public bool[][] ButtonState; // 生成と終了 public GameControllerHIDProperty() { this.Caps = new HID.Caps(); this.ButtonCaps = Array.Empty<HID.ButtonCaps>(); this.ValueCaps = Array.Empty<HID.ValueCaps>(); this.CollectionNodes = Array.Empty<HID.LinkCollectionNode>(); this.ButtonState = Array.Empty<bool[]>(); } public virtual void Dispose() { if( this.PreparseData.HasValue ) { //HID.HidD_FreePreparsedData( this.PreparseData.Value ); --> RawInput 経由で取得したものなので不要 Marshal.FreeHGlobal( this.PreparseData.Value ); this.PreparseData = null; } } } } <|start_filename|>FDK/ビデオ/Sources/VideoFrame.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX.Direct2D1; using SharpDX.MediaFoundation; namespace FDK { /// <summary> /// ビデオフレームの定義。 /// ビデオフレームとは、<see cref="IVideoSource.Read"/> で返されるオブジェクトのこと。 /// </summary> public class VideoFrame : IDisposable { /// <summary> /// このフレームの表示時刻。100ナノ秒単位。 /// </summary> public long 表示時刻100ns { get; set; } /// <summary> /// <see cref="Bitmap"/> の変換元となるサンプル。 /// </summary> public Sample Sample { get; set; } = null!; /// <summary> /// <see cref="Sample"/> からの変換後ビットマップ。 /// <see cref="Sample"/> とビデオメモリを共有しているので注意。 /// </summary> public Bitmap Bitmap { get; set; } = null!; public virtual void Dispose() { this.Bitmap?.Dispose(); this.Sample?.Dispose(); } } } <|start_filename|>DTXMania2/曲/Tree/Node/BackNode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.曲 { class BackNode : Node { public override string タイトル => "<< " + Properties.Resources.TXT_戻る; } } <|start_filename|>DTXMania2/曲/Def/SetDef.Block.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; namespace DTXMania2.曲 { partial class SetDef { /// <summary> /// 最大5曲をレベル別に保有できるブロック。 /// </summary> /// <remarks> /// set.def では任意個のブロックを宣言できる。(#TITLE行が登場するたび新しいブロックとみなされる) /// </remarks> public class Block { /// <summary> /// スコアのタイトル(#TITLE)を保持する。 /// </summary> public string Title { get; set; } = "(no title)"; /// <summary> /// スコアのフォント色(#FONTCOLOR)を保持する。 /// </summary> public Color FontColor { get; set; } = Color.White; /// <summary> /// スコアファイル名(#LxFILE)を保持する。 /// 配列は [0~4] で、存在しないレベルは null となる。 /// </summary> public string?[] File { get; } = new string[ 5 ]; /// <summary> /// スコアのラベル(#LxLABEL)を保持する。 /// 配列は[0~4] で、存在しないレベルは null となる。 /// </summary> public string?[] Label { get; } = new string[ 5 ]; } } } <|start_filename|>DTXMania2/保存データ/ScorePropertiesDB/old/v001_SongPropertiesDBRecord.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.old.ScorePropertiesDB { class v001_SongPropertiesDBRecord { // プロパティ public static int VERSION = 1; /// <summary> /// ユーザID。 /// </summary> public string UserId { get; set; } /// <summary> /// 曲譜面ファイルのハッシュ値。 /// 正確には一意じゃないけど、主キーとして扱う。 /// </summary> public string SongHashId { get; set; } /// <summary> /// 評価値。0~5。 /// </summary> public int Rating { get; set; } /// <summary> /// テーブルのカラム部分を列挙したSQL。 /// </summary> public static readonly string ColumnList = @"( UserId NVARCHAR NOT NULL" + @", SongHashId NVARCHAR NOT NULL" + @", Rating INTEGER NOT NULL" + @", PRIMARY KEY(`UserId`,`SongHashId`)" + @")"; // 生成と終了 public v001_SongPropertiesDBRecord() { this.UserId = "Anonymous"; this.SongHashId = ""; this.Rating = 0; } public v001_SongPropertiesDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "UserId": this.UserId = record.GetString( i ); break; case "SongHashId": this.SongHashId = record.GetString( i ); break; case "Rating": this.Rating = record.GetInt32( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public virtual void InsertTo( SQLiteDB db ) { using var cmd = new SqliteCommand( "REPLACE INTO SongProperties VALUES(" + $"'{this.UserId}'," + $"'{this.SongHashId}'" + $"{this.Rating}," + ")", db.Connection ); cmd.ExecuteNonQuery(); } } } <|start_filename|>DTXMania2/保存データ/ScoreDB/ScoreDB.Update.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2 { partial class ScoreDB { public static void 最新版にバージョンアップする() { using var _ = new LogBlock( Log.現在のメソッド名 ); using var db = new ScoreDB(); int version = (int)db.UserVersion; // v007 から、SongDB.sqlite3 が ScoreDB.sqlire3 に改名された。 var songdbPath = new VariablePath( @"$(AppData)\SongDB.sqlite3" ); using var songdb = File.Exists( songdbPath.変数なしパス ) ? new SQLiteDB( songdbPath.変数なしパス ) : null; // なければ null int songdb_version = (int)( songdb?.UserVersion ?? -1 ); // なければ負数 while( version < ScoreDBRecord.VERSION ) { switch( version ) { case 0: { #region " 0 → 最新版 " //---------------- // ScoreDB.sqlite3 に最新版のテーブルを新規に作成する。 foreach( var query in new[] { "PRAGMA foreign_keys = OFF", ScoreDBRecord.GetCreateTableSQL(), "PRAGMA foreign_keys = ON", } ) { using var cmd = new SqliteCommand( query, db.Connection ); cmd.ExecuteNonQuery(); } if( songdb is null ) // SongDB.sqlite3 がある? { version = ScoreDBRecord.VERSION; db.UserVersion = version; break; } // SongDB.sqlite3 が存在するので、データ移行する。 switch( songdb_version ) { case 0: case 1: case 2: case 3: case 4: case 5: // 何もしない。1~5 については、REAL 型の数値がすでにずれているため、データ移行しない。 break; case 6: { #region " 6 → 最新版 " //---------------- // ScoreDB 側に、最新バージョンのテーブルを作成する。 foreach( var query in new[] { "PRAGMA foreign_keys = OFF", ScoreDBRecord.GetCreateTableSQL(), } ) { using var cmd = new SqliteCommand( query, db.Connection ); cmd.ExecuteNonQuery(); } // v006 のレコードを読み込み、v007 テーブルに出力する。DBが違うので注意。 using( var cmdv007Begin = new SqliteCommand( "BEGIN", db.Connection ) ) cmdv007Begin.ExecuteNonQuery(); using var cmdv006query = new SqliteCommand( "SELECT * FROM Songs", songdb.Connection ); var v006result = cmdv006query.ExecuteReader(); while( v006result.Read() ) { var v006rc = new old.SongDBRecord.v006_SongDBRecord( v006result ); var v007rc = new ScoreDBRecord() { ScorePath = v006rc.Path, // 以下変更なし。 Title = v006rc.Title, LastWriteTime = v006rc.LastWriteTime, Level = v006rc.Level, MinBPM = v006rc.MinBPM, MaxBPM = v006rc.MaxBPM, TotalNotes_LeftCymbal = v006rc.TotalNotes_LeftCymbal, TotalNotes_HiHat = v006rc.TotalNotes_HiHat, TotalNotes_LeftPedal = v006rc.TotalNotes_LeftPedal, TotalNotes_Snare = v006rc.TotalNotes_Snare, TotalNotes_Bass = v006rc.TotalNotes_Bass, TotalNotes_HighTom = v006rc.TotalNotes_HighTom, TotalNotes_LowTom = v006rc.TotalNotes_LowTom, TotalNotes_FloorTom = v006rc.TotalNotes_FloorTom, TotalNotes_RightCymbal = v006rc.TotalNotes_RightCymbal, PreImage = v006rc.PreImage, Artist = v006rc.Artist, PreSound = v006rc.PreSound, BGMAdjust = v006rc.BGMAdjust, }; v007rc.ReplaceTo( db ); } using( var cmdv007End = new SqliteCommand( "END", db.Connection ) ) cmdv007End.ExecuteNonQuery(); using( var cmdKeysOn = new SqliteCommand( "PRAGMA foreign_keys = ON", db.Connection ) ) cmdKeysOn.ExecuteNonQuery(); version = ScoreDBRecord.VERSION; db.UserVersion = version; Log.Info( $"ScoreDB をバージョン {version} に更新しました。" ); //---------------- #endregion break; } } break; //---------------- #endregion } case 1: case 2: case 3: case 4: case 5: { #region " 1~5 → 6(BreakingChange)" //---------------- // テーブルを作り直す。REAL値が既にずれてるので、データ移行はしない。 foreach( var query in new[] { "PRAGMA foreign_keys = OFF", "DROP TABLE Songs", $"CREATE TABLE Songs {old.SongDBRecord.v006_SongDBRecord.ColumnList}", "PRAGMA foreign_keys = ON", } ) { using var cmd = new SqliteCommand( query, db.Connection ); cmd.ExecuteNonQuery(); } version = old.SongDBRecord.v006_SongDBRecord.VERSION; db.UserVersion = version; Log.Info( $"SongDB をバージョン {version} に更新しました。" ); //---------------- #endregion break; } } } } } } <|start_filename|>DTXMania2/曲/Tree/Node/RootNode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.曲 { class RootNode : BoxNode { public RootNode() : base( "(Root)" ) { } } } <|start_filename|>DTXMania2/ステージ/04選曲/選択曲枠ランナー.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.選曲 { /// <summary> /// 一定時間ごとに、選択曲を囲む枠の上下辺を右から左へすーっと走る光。 /// </summary> class 選択曲枠ランナー : IDisposable { // 生成と終了 public 選択曲枠ランナー() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ランナー画像 = new 画像D2D( @"$(Images)\SelectStage\FrameRunner.png" ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ランナー画像.Dispose(); } // 進行と描画 public void リセットする() { // 0~2000ms: 非表示、2000~2300ms: 表示 のループ this._カウンタ = new LoopCounter( 0, 2300, 1 ); } public void 進行描画する( DeviceContext d2ddc ) { if( this._カウンタ is null ) return; if( 2000 <= this._カウンタ.現在値 ) { float 割合 = ( this._カウンタ.現在値 - 2000 ) / 300f; // 0→1 // 上 this._ランナー画像.描画する( d2ddc, 1920f - 割合 * ( 1920f - 1044f ), 485f - this._ランナー画像.サイズ.Height / 2f ); // 下 this._ランナー画像.描画する( d2ddc, 1920f - 割合 * ( 1920f - 1044f ), 598f - this._ランナー画像.サイズ.Height / 2f ); } } // ローカル private readonly 画像D2D _ランナー画像; private LoopCounter? _カウンタ = null; } } <|start_filename|>FDK/ログ/Log.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace FDK { /// <summary> /// アプリケーションからのログ出力。 /// </summary> public static class Log { // プロパティ /// <summary> /// このメソッドの 呼び出し元のメソッド名 を返す。デバッグログ用。 /// </summary> public static string 現在のメソッド名 { get { // 1つ前のスタックフレームを取得。 var prevFrame = new StackFrame( skipFrames: 1, needFileInfo: false ); var クラス名 = prevFrame.GetMethod()?.ReflectedType?.ToString() ?? ""; var メソッド名 = prevFrame.GetMethod()?.Name ?? ""; return $"{クラス名}.{メソッド名}()"; } } // メソッド /// <summary> /// これを設定しておくと、スレッドID の横に (名前) と出力されるようになる。 /// </summary> public static void 現在のスレッドに名前をつける( string 名前 ) { lock( Log._スレッド間同期 ) { Thread.CurrentThread.Name = 名前; } } public static void Info( string 出力 ) { lock( Log._スレッド間同期 ) { Log._一定時間が経過していたら区切り線を表示する(); Trace.WriteLine( $"{tagINFO} {Log._日時とスレッドID} {Log._インデックスを返す( Log._スレッドの深さを返す() )}{出力}" ); } } public static void WARNING( string 出力 ) { lock( Log._スレッド間同期 ) { Log._一定時間が経過していたら区切り線を表示する(); Trace.WriteLine( $"{tagWARNING} {Log._日時とスレッドID} {Log._インデックスを返す( Log._スレッドの深さを返す() )}{出力}" ); } } public static void ERROR( string 出力 ) { lock( Log._スレッド間同期 ) { Log._一定時間が経過していたら区切り線を表示する(); Trace.WriteLine( $"{tagERROR} {Log._日時とスレッドID} {Log._インデックスを返す( Log._スレッドの深さを返す() )}{出力}" ); } } public static void WriteLine( string 出力 ) { lock( Log._スレッド間同期 ) { Trace.WriteLine( 出力 ); } } public static void Header( string ヘッダ出力 ) { lock( Log._スレッド間同期 ) { Log._一定時間が経過していたら区切り線を表示する(); Log.Info( "" ); Log.Info( $"======== {ヘッダ出力} ========" ); } } /// <summary> /// 連続して呼び出しても、前回の同一識別キーでの表示から一定時間が経たないと表示しないInfoメソッド。 /// </summary> /// <remarks> /// 毎秒60回の進行描画の進捗など、連続して呼び出すと膨大な数のログが出力されてしまう場合に使用する。 /// </remarks> /// <param name="識別キー"></param> /// <param name="出力"></param> public static void 定間隔Info( string 識別キー, string 出力, double 間隔sec = 0.25 ) { lock( Log._スレッド間同期 ) { if( Log._識別キー別最終表示時刻.ContainsKey( 識別キー ) ) { if( ( DateTime.Now - Log._識別キー別最終表示時刻[ 識別キー ] ).TotalSeconds >= 間隔sec ) { Log._識別キー別最終表示時刻[ 識別キー ] = DateTime.Now; Trace.WriteLine( $"{tagINFO} {Log._日時とスレッドID} {出力}" ); } } else { Log._識別キー別最終表示時刻.Add( 識別キー, DateTime.Now ); Trace.WriteLine( $"{tagINFO} {Log._日時とスレッドID} {出力}" ); } } } /// <summary> /// 指定されたフォルダ内に配置可能な、新しいログファイル名を生成して返す。 /// </summary> /// <param name="ログフォルダパス">ログファイルを配置するフォルダのパス。</param> /// <param name="ログファイルの接頭辞">ログファイル名に付与する接頭辞。</param> /// <param name="最大保存期間">フォルダ内に保存しておく最大の期間。</param> /// <returns>生成されたログファイル名。パス付き。</returns> /// <remarks> /// ログファイル名は、現在時刻をベースに名付けられる。 /// 同時に、フォルダ内に存在するすべてのファイルの更新時刻をチェックし、最大保存期間を超える古いファイルは、自動的に削除する。 /// </remarks> public static string ログファイル名を生成する( VariablePath ログフォルダパス, string ログファイルの接頭辞, TimeSpan 最大保存期間 ) { var 現在の日時 = DateTime.Now; if( Directory.Exists( ログフォルダパス.変数なしパス ) ) { // (A) フォルダがある場合 → 最大保存期間を超える古いファイルを削除する。 var 削除対象ファイルs = Directory.GetFiles( ログフォルダパス.変数なしパス ).Where( ( file ) => ( File.GetLastWriteTime( file ) < ( 現在の日時 - 最大保存期間 ) ) ); foreach( var path in 削除対象ファイルs ) File.Delete( path ); } else { // (B) フォルダがない場合 → 作成する。 Directory.CreateDirectory( ログフォルダパス.変数なしパス ); } // 現在の時刻をもとに、新しいログファイル名を生成して返す。 return Path.Combine( ログフォルダパス.変数なしパス, $"{ログファイルの接頭辞}{現在の日時.ToString( "yyyyMMdd-HHmmssffff" )}.txt" ); } public static void BeginInfo( string 開始ブロック名 ) { lock( Log._スレッド間同期 ) { Log._一定時間が経過していたら区切り線を表示する(); Trace.WriteLine( $"{tagINFO} {Log._日時とスレッドID} {Log._インデックスを返す( Log._スレッドの深さを返す() )}{開始ブロック名} --> 開始" ); Log._Info開始時刻.Push( DateTime.Now ); var NETスレッドID = Thread.CurrentThread.ManagedThreadId; Log._深さ[ NETスレッドID ]++; } } public static void EndInfo( string 終了ブロック名 ) { lock( Log._スレッド間同期 ) { var 経過時間ms = ( DateTime.Now - Log._Info開始時刻.Pop() ).TotalMilliseconds; var NETスレッドID = Thread.CurrentThread.ManagedThreadId; Log._深さ[ NETスレッドID ] = Math.Max( ( Log._深さ[ NETスレッドID ] - 1 ), 0 ); Log._一定時間が経過していたら区切り線を表示する(); Trace.WriteLine( $"{tagINFO} {Log._日時とスレッドID} {Log._インデックスを返す( Log._スレッドの深さを返す() )}{終了ブロック名} <-- 終了 ({経過時間ms}ms)" ); } } // ローカル private const double _最小区切り時間 = 2.0; // 区切り線を入れる最小の間隔[秒]。 private static string _日時とスレッドID { get { var NETスレッドID = Thread.CurrentThread.ManagedThreadId; var NETスレッド名 = Thread.CurrentThread.Name; return $"{DateTime.Now.ToString( "HH:mm:ss.fffffff" )} [" + ( string.IsNullOrEmpty( NETスレッド名 ) ? $"{NETスレッドID:00}" : NETスレッド名 ) + "]"; } } private static Dictionary<string, DateTime> _識別キー別最終表示時刻 = new Dictionary<string, DateTime>(); private static TimeSpan _経過時間 { get { var 現在時刻 = DateTime.Now; var 経過時間 = 現在時刻 - Log._最終表示時刻; Log._最終表示時刻 = 現在時刻; // 更新 return 経過時間; } } private static DateTime _最終表示時刻 = DateTime.Now; private static Stack<DateTime> _Info開始時刻 = new Stack<DateTime>(); private static readonly object _スレッド間同期 = new object(); private static readonly string tagINFO = "[INFORMATION]"; private static readonly string tagWARNING = "[ WARNING ]"; private static readonly string tagERROR = "[ ERROR ]"; private static readonly string tagINTERVAL = "[ INTERVAL ]"; private static Dictionary<int, int> _深さ = new Dictionary<int, int>(); private static int _スレッドの深さを返す() { var NETスレッドID = Thread.CurrentThread.ManagedThreadId; if( _深さ.TryGetValue( NETスレッドID, out int 深さ ) ) return 深さ; _深さ.Add( NETスレッドID, 0 ); return 0; } private static void _一定時間が経過していたら区切り線を表示する() { var span = Log._経過時間.TotalSeconds; if( Log._最小区切り時間 < span ) { #region " faces " //---------------- var faces = new[] { @" ^^) _旦~~", @"( ..)φ", @"( `ー´)ノ", @"(#^^#)", @"('ω')", @"(´・ω・`)", @"(*´ω`*)", @"( ・_・)ノΞ●~*", @"∠( ˙-˙ )/", @"(*/▽\*)", @"(ɔ ˘⌣˘)˘⌣˘ c)", @"((*◕ω◕)ノ", @"ㆆ﹏ㆆ", @"(゚Д゚;≡;゚д゚)", @"(゚дノ[壁]", @"ʅ(´-ω-`)ʃ", @"(*´﹃`*)", @"(>ω<)", @"٩(๑❛ᴗ❛๑)۶ ", @"(。・ω・。)", @"_(┐「ε:)_", @"(ノ-_-)ノ~┻━┻", @"_(ˇωˇ」∠)_ ", }; int faceNow = ( (int)( span * 1000.0 ) ) % faces.Length; //---------------- #endregion Trace.WriteLine( $"{tagINTERVAL} ...... {faces[ faceNow ]} ......" ); } } private static string _インデックスを返す( int 長さ ) { var sb = new StringBuilder(); for( int i = 0; i < 長さ; i++ ) sb.Append( "| " ); return sb.ToString(); } } } <|start_filename|>DTXMania2/保存データ/UserConfig/old/v007_UserConfig.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Sqlite; namespace DTXMania2.old.UserConfig { class v007_UserConfig { public const int VERSION = 7; // このクラスのバージョン // プロパティ /// <summary> /// このクラスのバージョン。 /// </summary> public int Version { get; set; } /// <summary> /// ユーザを一意に識別する文字列。主キーなので変更不可。 /// </summary> public string Id { get; set; } /// <summary> /// ユーザ名。変更可。 /// </summary> public string Name { get; set; } /// <summary> /// 譜面スクロール速度の倍率。1.0で等倍。 /// </summary> public double ScrollSpeed { get; set; } /// <summary> /// 起動直後の表示モード。 /// 0: ウィンドウモード、その他: 全画面モード。 /// </summary> public int Fullscreen { get; set; } /// <summary> /// シンバルフリーモード。 /// 0: OFF, その他: ON /// </summary> public int CymbalFree { get; set; } /// <summary> /// Ride の表示位置。 /// 0: 右, 1: 左 /// </summary> public int RideLeft { get; set; } /// <summary> /// China の表示位置。 /// 0: 右, 1: 左 /// </summary> public int ChinaLeft { get; set; } /// <summary> /// Splash の表示位置。 /// 0: 右, 1: 左 /// </summary> public int SplashLeft { get; set; } /// <summary> /// ユーザ入力時にドラム音を発声するか? /// 0: OFF, その他: ON /// </summary> public int DrumSound { get; set; } /// <summary> /// レーンの透過度[%]。 /// 0:完全不透明 ~ 100:完全透明 /// </summary> public int LaneTrans { get; set; } /// <summary> /// レーンタイプ名。 /// </summary> public string LaneType { get; set; } /// <summary> /// 演奏モード。 /// 0: Basic, 1: Expert /// Release 048 より Basic 廃止のため 1 で固定化。 /// </summary> public int PlayMode { get; set; } // AutoPlay /// <summary> /// 左シンバルレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_LeftCymbal { get; set; } /// <summary> /// ハイハットレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_HiHat { get; set; } /// <summary> /// 左ペダルレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_LeftPedal { get; set; } /// <summary> /// スネアレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_Snare { get; set; } /// <summary> /// バスレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_Bass { get; set; } /// <summary> /// ハイタムレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_HighTom { get; set; } /// <summary> /// ロータムレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_LowTom { get; set; } /// <summary> /// フロアタムレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_FloorTom { get; set; } /// <summary> /// 右シンバルレーンの AutoPlay 。 /// 0: OFF, その他: ON。 /// </summary> public int AutoPlay_RightCymbal { get; set; } // 最大ヒット距離 /// <summary> /// Perfect の最大ヒット距離[秒]。 /// </summary> public double MaxRange_Perfect { get; set; } /// <summary> /// Great の最大ヒット距離[秒]。 /// </summary> public double MaxRange_Great { get; set; } /// <summary> /// Good の最大ヒット距離[秒]。 /// </summary> public double MaxRange_Good { get; set; } /// <summary> /// Ok の最大ヒット距離[秒]。 /// </summary> public double MaxRange_Ok { get; set; } // 生成と終了 public v007_UserConfig() { this.Version = VERSION; this.Id = "Anonymous"; this.Name = "Anonymous"; this.ScrollSpeed = 1.0; this.Fullscreen = 0; this.CymbalFree = 1; this.RideLeft = 0; this.ChinaLeft = 0; this.SplashLeft = 1; this.DrumSound = 1; this.LaneTrans = 40; this.LaneType = "TypeA"; this.PlayMode = 1; this.AutoPlay_LeftCymbal = 1; this.AutoPlay_HiHat = 1; this.AutoPlay_LeftPedal = 1; this.AutoPlay_Snare = 1; this.AutoPlay_Bass = 1; this.AutoPlay_HighTom = 1; this.AutoPlay_LowTom = 1; this.AutoPlay_FloorTom = 1; this.AutoPlay_RightCymbal = 1; this.MaxRange_Perfect = 0.034; this.MaxRange_Great = 0.067; this.MaxRange_Good = 0.084; this.MaxRange_Ok = 0.117; } } } <|start_filename|>SSTFEditor/メインフォーム.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.IO.Pipes; using System.Linq; using System.Reflection; using System.Threading; using System.Windows.Forms; using FDK; using SSTF=SSTFormat.v004; namespace SSTFEditor { partial class メインフォーム : Form { public Config Config { get; set; } public 譜面 譜面 { get; set; } public 選択モード 選択モード { get; set; } public 編集モード 編集モード { get; set; } public クリップボード クリップボード { get; set; } public UndoRedo.UndoRedo管理 UndoRedo管理 { get; set; } public readonly int メジャーバージョン番号 = Assembly.GetExecutingAssembly().GetName().Version.Major; public readonly int マイナーバージョン番号 = Assembly.GetExecutingAssembly().GetName().Version.Minor; public readonly int リビジョン番号 = Assembly.GetExecutingAssembly().GetName().Version.Revision; public readonly int ビルド番号 = Assembly.GetExecutingAssembly().GetName().Version.Build; public const int 最大音量 = 8; public const int 最小音量 = 1; /// <summary> /// 1小節あたりのグリッド数。 /// 小節長倍率が 1.0 でない場合は、これを乗じることでグリッド数が変化する。 /// </summary> public readonly int GRID_PER_PART = int.Parse( Properties.Resources.GRID_PER_PART ); /// <summary> /// 1ピクセルあたりのグリッド数。 /// 現在の譜面拡大率によって変化する。 /// </summary> public int GRID_PER_PIXEL => (int)( int.Parse( Properties.Resources.GRID_PER_PIXEL ) / ( 1 + 0.25 * this.toolStripComboBox譜面拡大率.SelectedIndex ) ); public bool 選択モードである => ( CheckState.Checked == this.toolStripButton選択モード.CheckState ); public bool 編集モードである => ( CheckState.Checked == this.toolStripButton編集モード.CheckState ); public bool 未保存である { get => this._未保存である; set { // まず値を保存。 this._未保存である = value; // ウィンドウのタイトルバーの文字列を修正する。 string 表示するファイルの名前 = ( string.IsNullOrEmpty( this._編集中のファイル名 ) ) ? Properties.Resources.NEW_FILENAME : this._編集中のファイル名; if( this._未保存である ) { // 変更ありかつ未保存なら「*」を付ける。 this.Text = $"SSTFEditor {this.メジャーバージョン番号}.{this.マイナーバージョン番号}.{this.リビジョン番号}.{this.ビルド番号} *[{表示するファイルの名前}]"; this.toolStripMenuItem上書き保存.Enabled = true; this.toolStripButton上書き保存.Enabled = true; } else { // 保存後変更がないなら「*」は付けない。 this.Text = $"SSTFEditor {this.メジャーバージョン番号}.{this.マイナーバージョン番号}.{this.リビジョン番号}.{this.ビルド番号} [{表示するファイルの名前}]"; this.toolStripMenuItem上書き保存.Enabled = false; this.toolStripButton上書き保存.Enabled = false; } } } public bool 初期化完了 { get; set; } = false; public SSTF.チップ種別 現在のチップ種別 { get => this._現在のチップ種別; set { this._現在のチップ種別 = value; this.label現在のチップ種別.Text = this._チップto名前[ value ]; } } public int 現在のチップ音量 { get; set; } = メインフォーム.最大音量 - 1; public Size 譜面パネルサイズ => this.pictureBox譜面パネル.ClientSize; public Rectangle 譜面パネル領域 => this.pictureBox譜面パネル.ClientRectangle; public メインフォーム() { InitializeComponent(); this.Icon = Properties.Resources.Icon; this._アプリの起動処理を行う(); } public void 選択モードに切替えて関連GUIを設定する() { this.toolStripButton選択モード.CheckState = CheckState.Checked; this.toolStripButton編集モード.CheckState = CheckState.Unchecked; this.toolStripMenuItem選択モード.CheckState = CheckState.Checked; this.toolStripMenuItem編集モード.CheckState = CheckState.Unchecked; this.label現在のチップ種別.Text = "----"; this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); } public void 編集モードに切替えて関連GUIを設定する() { this.選択モード.全チップの選択を解除する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); this.toolStripButton選択モード.CheckState = CheckState.Unchecked; this.toolStripButton編集モード.CheckState = CheckState.Checked; this.toolStripMenuItem選択モード.CheckState = CheckState.Unchecked; this.toolStripMenuItem編集モード.CheckState = CheckState.Checked; } public void 選択チップの有無に応じて編集用GUIのEnabledを設定する() { bool 譜面上に選択チップがある = this._選択チップが1個以上ある; bool クリップボードに選択チップがある = ( null != this.クリップボード ) && ( 0 < this.クリップボード.アイテム数 ); // 編集メニューの Enabled 設定 this.toolStripMenuItemコピー.Enabled = 譜面上に選択チップがある; this.toolStripMenuItem切り取り.Enabled = 譜面上に選択チップがある; this.toolStripMenuItem貼り付け.Enabled = クリップボードに選択チップがある; this.toolStripMenuItem削除.Enabled = 譜面上に選択チップがある; // ツールバーの Enabled 設定 this.toolStripButtonコピー.Enabled = 譜面上に選択チップがある; this.toolStripButton切り取り.Enabled = 譜面上に選択チップがある; this.toolStripButton貼り付け.Enabled = クリップボードに選択チップがある; this.toolStripButton削除.Enabled = 譜面上に選択チップがある; // 右メニューの Enabled 設定 this.toolStripMenuItem選択チップのコピー.Enabled = 譜面上に選択チップがある; this.toolStripMenuItem選択チップの切り取り.Enabled = 譜面上に選択チップがある; this.toolStripMenuItem選択チップの貼り付け.Enabled = クリップボードに選択チップがある; this.toolStripMenuItem選択チップの削除.Enabled = 譜面上に選択チップがある; this.toolStripMenuItem音量指定.Enabled = 譜面上に選択チップがある; // 音量ラベル if( 譜面上に選択チップがある ) { toolStripLabel音量.Text = " - + "; // 選択中のチップ音量の相対操作モード } else { this._現在のチップ音量をツールバーに表示する(); } } public void 譜面をリフレッシュする() { this.pictureBox譜面パネル.Refresh(); } public void UndoRedo用GUIのEnabledを設定する() { bool Undo可 = ( 0 < this.UndoRedo管理.Undo可能な回数 ) ? true : false; bool Redo可 = ( 0 < this.UndoRedo管理.Redo可能な回数 ) ? true : false; this.toolStripMenuItem元に戻す.Enabled = Undo可; this.toolStripMenuItemやり直す.Enabled = Redo可; this.toolStripButton元に戻す.Enabled = Undo可; this.toolStripButtonやり直す.Enabled = Redo可; } public void 選択モードのコンテクストメニューを表示する( int x, int y ) { this.contextMenuStrip譜面右メニュー.Show( this.pictureBox譜面パネル, x, y ); // メニューを表示した時のマウス座標を控えておく。 this._選択モードでコンテクストメニューを開いたときのマウスの位置 = new Point( x, y ); } public void 譜面を縦スクロールする( int スクロール量grid ) { int 現在の位置grid = this.vScrollBar譜面用垂直スクロールバー.Value; int 最小値grid = this.vScrollBar譜面用垂直スクロールバー.Minimum; int 最大値grid = ( this.vScrollBar譜面用垂直スクロールバー.Maximum + 1 ) - this.vScrollBar譜面用垂直スクロールバー.LargeChange; int スクロール後の位置grid = 現在の位置grid + スクロール量grid; スクロール後の位置grid = Math.Clamp( スクロール後の位置grid, min: 最小値grid, max: 最大値grid ); this.vScrollBar譜面用垂直スクロールバー.Value = スクロール後の位置grid; } private bool _未保存である = false; private Font _メモ用フォント = new Font( FontFamily.GenericSansSerif, 9.0f ); private readonly Dictionary<SSTF.チップ種別, string> _チップto名前 = new Dictionary<SSTF.チップ種別, string>() { #region " *** " //----------------- { SSTF.チップ種別.Bass, "BassDrum" }, { SSTF.チップ種別.BPM, "BPM" }, { SSTF.チップ種別.China, "China" }, { SSTF.チップ種別.HiHat_Close, "HiHat(Close)" }, { SSTF.チップ種別.HiHat_Foot, "FootPedal" }, { SSTF.チップ種別.HiHat_HalfOpen, "HiHat(HalfOpen)" }, { SSTF.チップ種別.HiHat_Open, "HiHat(Open)" }, { SSTF.チップ種別.LeftCrash, "Crash" }, { SSTF.チップ種別.Ride, "Ride" }, { SSTF.チップ種別.Ride_Cup, "Ride(Cup)" }, { SSTF.チップ種別.RightCrash, "Crash" }, { SSTF.チップ種別.Snare, "Snare" }, { SSTF.チップ種別.Snare_ClosedRim, "Snare(CloseRimShot)" }, { SSTF.チップ種別.Snare_Ghost, "Snare(Ghost)" }, { SSTF.チップ種別.Snare_OpenRim, "Snare(OpenRimShot)" }, { SSTF.チップ種別.Splash, "Splash" }, { SSTF.チップ種別.Tom1, "HighTom" }, { SSTF.チップ種別.Tom1_Rim, "HighTom(RimShot)" }, { SSTF.チップ種別.Tom2, "LowTom" }, { SSTF.チップ種別.Tom2_Rim, "LowTom(RimShot)" }, { SSTF.チップ種別.Tom3, "FloorTom" }, { SSTF.チップ種別.Tom3_Rim, "FloorTom(RimShot)" }, { SSTF.チップ種別.LeftCymbal_Mute, "Mute" }, { SSTF.チップ種別.RightCymbal_Mute, "Mute" }, { SSTF.チップ種別.背景動画, "" }, { SSTF.チップ種別.BGM, "" }, { SSTF.チップ種別.Unknown, "" }, { SSTF.チップ種別.小節線, "" }, { SSTF.チップ種別.拍線, "" }, //----------------- #endregion }; private readonly Dictionary<int, string> _音量toラベル = new Dictionary<int, string>() { #region " *** " //---------------- { 1, "-6 *-----+-" }, { 2, "-5 **----+-" }, { 3, "-4 ***---+-" }, { 4, "-3 ****--+-" }, { 5, "-2 *****-+-" }, { 6, "-1 ******+-" }, { 7, " 0 *******-" }, { 8, "+1 ********" }, //---------------- #endregion }; private bool _選択チップが1個以上ある { get { if( ( null != this.譜面.スコア ) && ( null != this.譜面.スコア.チップリスト ) && ( 0 < this.譜面.スコア.チップリスト.Count ) ) { foreach( 描画用チップ chip in this.譜面.スコア.チップリスト ) { if( chip.選択が確定している ) return true; } } return false; } } /// <summary> /// 単位: [n分の1] (例: 間隔=16 なら、"1/16" を意味する。) /// </summary> private int _現在のガイド間隔 = 0; private Point _選択モードでコンテクストメニューを開いたときのマウスの位置; private SSTF.チップ種別 _現在のチップ種別 = SSTF.チップ種別.Unknown; #region " フォルダ、ファイルパス " //---------------- /// <summary> /// SSTFEditor.exe が格納されているフォルダへのパス。 /// </summary> private string _システムフォルダパス => ( Path.GetDirectoryName( Application.ExecutablePath ) ); /// <summary> /// Windowsログインユーザのアプリデータフォルダ。末尾は '\'。 /// </summary> /// <remarks> /// 例: "C:\Users\ログインユーザ名\AppData\Roaming\SSTFEditor\" /// </remarks> private string _ユーザフォルダパス { get { var path = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create ), @"SSTFEditor\" ); if( false == Directory.Exists( path ) ) Directory.CreateDirectory( path ); // なければ作成する。 return path; } } private string _作業フォルダパス = null; private string _編集中のファイル名 = null; private string _最後にプレイヤーに渡した一時ファイル名 = null; //---------------- #endregion #region " Viewer 用パイプライン " //---------------- private NamedPipeClientStream _Viewerに接続する() { var pipeToViewer = new NamedPipeClientStream( ".", Program._ビュアー用パイプライン名, PipeDirection.Out ); try { // パイプラインサーバへの接続を試みる。 pipeToViewer.Connect( 100 ); } catch( TimeoutException ) { // サーバが立ち上がっていないなら null を返す。 pipeToViewer?.Dispose(); pipeToViewer = null; } return pipeToViewer; // null じゃない場合は Dispose を忘れないこと。 } //---------------- #endregion // アクションメソッド #region " アクションメソッド(最上位の機能エントリ。メニューやコマンドバーなどから呼び出される。)" //---------------- private void _アプリの起動処理を行う() { // 作業フォルダの初期値は、Windowsユーザのマイドキュメントフォルダ。 this._作業フォルダパス = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments ); // Config.xml を読み込む。 this.Config = Config.読み込む( Path.Combine( this._ユーザフォルダパス, Properties.Resources.CONFIG_FILE_NAME ) ); if( this.Config.ViewerPath.Nullまたは空である() ) { // 既定のプレイヤーは、exe と同じ場所にあるものとする。 this.Config.ViewerPath = Path.Combine( this._システムフォルダパス, Properties.Resources.PLAYER_NAME ); if( false == File.Exists( this.Config.ViewerPath ) ) this.Config.ViewerPath = ""; // ビュアーが存在してない。 } // ウィンドウの位置とサイズ。 this.StartPosition = FormStartPosition.Manual; this.Location = this.Config.WindowLocation; this.ClientSize = this.Config.ClientSize; // デザイナでは追加できないイベントを手動で追加する。 this.splitContainer分割パネルコンテナ.MouseWheel += new MouseEventHandler( splitContainer分割パネルコンテナ_MouseWheel ); // 最近使ったファイル一覧を更新する。 this._ConfigのRecentUsedFilesをファイルメニューへ追加する(); // その他の初期化。 this._新規作成する(); this._ガイド間隔を変更する( 16 ); // 初期は 1/16 間隔。 this.toolStripComboBox再生速度.SelectedIndex = 7; // 初期は x1.0。 // 完了。 this.初期化完了 = true; // コマンドライン引数に、存在するファイルの指定があれば開く。 foreach( var arg in Environment.GetCommandLineArgs().Skip( 1 ) ) // 先頭は exe 名なのでスキップ。 { if( File.Exists( arg ) ) { this._指定されたファイルを開く( arg ); break; // 最初の1つだけ。 } } } private void _アプリの終了処理を行う() { // 一時ファイルが残っていれば、削除する。 if( File.Exists( this._最後にプレイヤーに渡した一時ファイル名 ) ) File.Delete( this._最後にプレイヤーに渡した一時ファイル名 ); // Config.xml を保存する。 this.Config.保存する( Path.Combine( this._ユーザフォルダパス, Properties.Resources.CONFIG_FILE_NAME ) ); // その他の終了処理。 this.譜面?.Dispose(); this.譜面 = null; this.選択モード?.Dispose(); this.選択モード = null; } private void _新規作成する() { if( DialogResult.Cancel == this._未保存なら保存する() ) return; // 保存がキャンセルされた場合はここで中断。 this._エディタを初期化する(); } private void _開く() { if( DialogResult.Cancel == this._未保存なら保存する() ) return; // 保存がキャンセルされた場合はここで中断。 #region " ファイルを開くダイアログでファイルを選択する。" //----------------- var dialog = new OpenFileDialog() { Title = Properties.Resources.MSG_ファイル選択ダイアログのタイトル, Filter = Properties.Resources.MSG_曲ファイル選択ダイアログのフィルタ, FilterIndex = 1, InitialDirectory = this._作業フォルダパス, }; var result = dialog.ShowDialog( this ); // メインフォームを再描画してダイアログを完全に消す。 this.Refresh(); // OKじゃないならここで中断。 if( DialogResult.OK != result ) return; //----------------- #endregion this._ファイルを読み込む( dialog.FileName ); } private void _指定されたファイルを開く( string ファイルパス ) { if( DialogResult.Cancel == this._未保存なら保存する() ) return; // 保存がキャンセルされた場合はここで中断。 this._ファイルを読み込む( ファイルパス ); } private void _上書き保存する() { #region " ファイル名が未設定なら、初めての保存と見なし、ファイル保存ダイアログで保存ファイル名を指定させる。" //----------------- if( this._編集中のファイル名.Nullまたは空である() ) { string 絶対パスファイル名 = this._ファイル保存ダイアログを開いてファイル名を取得する(); if( string.IsNullOrEmpty( 絶対パスファイル名 ) ) return; // ファイル保存ダイアログがキャンセルされたのならここで打ち切り。 this._作業フォルダパス = Path.GetDirectoryName( 絶対パスファイル名 ); // ダイアログでディレクトリを変更した場合、カレントディレクトリも変更されている。 this._編集中のファイル名 = Path.GetFileName( 絶対パスファイル名 ); } //----------------- #endregion this._上書き保存する( Path.Combine( this._作業フォルダパス, this._編集中のファイル名 ), 一時ファイルである: false ); } private void _上書き保存する( string ファイルの絶対パス, bool 一時ファイルである ) { #region " [保存中です] ポップアップを表示する。" //----------------- var msg = new Popupメッセージ( Properties.Resources.MSG_保存中です + Environment.NewLine + Properties.Resources.MSG_しばらくお待ち下さい ); msg.Owner = this; msg.Show(); msg.Refresh(); //----------------- #endregion try { // 選択モードだったら、全チップの選択を解除する。 if( this.選択モードである ) this.選択モード.全チップの選択を解除する(); // 一時ファイルじゃなければ再生速度を x1.0 に固定。 if( !一時ファイルである ) this.譜面.スコア.Viewerでの再生速度 = 1.0; // ファイルを出力する。 string ヘッダ行 = $"# Created by SSTFEditor {this.メジャーバージョン番号}.{this.マイナーバージョン番号}.{this.リビジョン番号}.{this.ビルド番号}"; switch( Path.GetExtension( ファイルの絶対パス ).ToLower() ) { case ".dtx": this.譜面.SSTFoverDTXファイルを書き出す( ファイルの絶対パス, ヘッダ行 ); break; case ".sstf": this.譜面.SSTFファイルを書き出す( ファイルの絶対パス, ヘッダ行 ); break; } // 出力したファイルのパスを、[ファイル]メニューの最近使ったファイル一覧に追加する。 if( false == 一時ファイルである ) { this.Config.ファイルを最近使ったファイルの一覧に追加する( ファイルの絶対パス ); this._ConfigのRecentUsedFilesをファイルメニューへ追加する(); } } finally { #region " [保存中です] ポップアップを閉じる。" //----------------- msg.Close(); //----------------- #endregion // 最後に、ダイアログのゴミなどを消すために再描画。 this.Refresh(); // 一時ファイルじゃないなら、保存完了。 if( false == 一時ファイルである ) this.未保存である = false; } } private void _名前を付けて保存する() { #region " ユーザに保存ファイル名を入力させる。" //----------------- string 絶対パスファイル名 = this._ファイル保存ダイアログを開いてファイル名を取得する(); if( 絶対パスファイル名.Nullまたは空である() ) return; // キャンセルされたらここで中断。 this._作業フォルダパス = Path.GetDirectoryName( 絶対パスファイル名 ); this._編集中のファイル名 = Path.GetFileName( 絶対パスファイル名 ); //----------------- #endregion this._上書き保存する(); this.未保存である = true; // ウィンドウタイトルに表示されているファイル名を変更するため、一度わざと true にする。 this.未保存である = false; } private void _終了する() { this.Close(); } private void _元に戻す() { // Undo する対象を UndoRedoリストから取得する。 var cell = this.UndoRedo管理.Undoするセルを取得して返す(); if( null == cell ) return; // なければ何もしない。 // Undo を実行する。 cell.Undoを実行する(); // GUIを再描画する。 this.UndoRedo用GUIのEnabledを設定する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); } private void _やり直す() { // Redo する対象を UndoRedoリストから取得する。 var cell = this.UndoRedo管理.Redoするセルを取得して返す(); if( null == cell ) return; // なければ何もしない。 // Redo を実行する。 cell.Redoを実行する(); // GUI を再描画する。 this.UndoRedo用GUIのEnabledを設定する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); } private void _切り取る() { // 譜面にフォーカスがないなら、何もしない。 if( false == this.pictureBox譜面パネル.Focused ) return; // 切り取り = コピー + 削除 this._コピーする(); this._削除する(); } private void _コピーする() { // 譜面にフォーカスがないなら何もしない。 if( false == this.pictureBox譜面パネル.Focused ) return; // コピーする。 this.クリップボード.現在選択されているチップをボードにコピーする(); // 画面を再描画する。 this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); } private void _貼り付ける( int 貼り付けを開始する譜面内絶対位置grid ) { // 譜面にフォーカスがないなら何もしない。 if( false == this.pictureBox譜面パネル.Focused ) return; this.クリップボード.チップを指定位置から貼り付ける( 貼り付けを開始する譜面内絶対位置grid ); } private void _削除する() { // 譜面にフォーカスがないなら何もしない。 if( false == this.pictureBox譜面パネル.Focused ) return; try { this.UndoRedo管理.トランザクション記録を開始する(); #region " 譜面が持つすべてのチップについて、選択されているチップがあれば削除する。" //---------------- for( int i = this.譜面.スコア.チップリスト.Count - 1; 0 <= i; i-- ) { var chip = (描画用チップ) this.譜面.スコア.チップリスト[ i ]; if( chip.選択が確定していない ) continue; var chip変更前 = new 描画用チップ( chip ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); this.譜面.スコア.チップリスト.Add( 変更対象 ); this.譜面.スコア.チップリスト.Sort(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this.譜面.スコア.チップリスト.Remove( 変更対象 ); this.未保存である = true; }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: null, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } //---------------- #endregion } finally { this.UndoRedo管理.トランザクション記録を終了する(); #region " GUI を再描画する。" //---------------- this.UndoRedo用GUIのEnabledを設定する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); //---------------- #endregion } } private void _すべて選択する() { // 編集モードなら強制的に選択モードにする。 if( this.編集モードである ) this.選択モードに切替えて関連GUIを設定する(); this.選択モード.全チップを選択する(); } private void _選択モードにする() { this.選択モードに切替えて関連GUIを設定する(); } private void _編集モードにする() { this.編集モードに切替えて関連GUIを設定する(); } private void _モードを切替える() { if( this.選択モードである ) { this.編集モードに切替えて関連GUIを設定する(); } else { this.選択モードに切替えて関連GUIを設定する(); } } private void _検索する() { this._選択モードにする(); this.選択モード.検索する(); } private void _ガイド間隔を変更する( int n分 ) { // 引数チェック。 if( !( new[] { 4, 6, 8, 12, 16, 24, 32, 36, 48, 64, 128, 0 }.Contains( n分 ) ) ) throw new ArgumentException( $"不正なガイド間隔({n分})が指定されました。" ); // 新しいガイド間隔を設定する。 this._現在のガイド間隔 = n分; this.譜面.現在のガイド間隔を変更する( n分 ); // 譜面オブジェクトとも共有する。 #region " ガイド間隔関連GUI(メニュー、コンボボックス)を更新する。" //----------------- // 一度、すべてのガイド間隔メニューのチェックをはずす。 this.toolStripMenuItemガイド間隔4分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔6分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔8分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔12分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔16分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔24分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔32分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔36分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔48分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔64分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔128分.CheckState = CheckState.Unchecked; this.toolStripMenuItemガイド間隔フリー.CheckState = CheckState.Unchecked; // で、制定された間隔に対応するメニューだけをチェックする。 switch( n分 ) { // Menu と ComboBox の2つを変更することでイベントが2つ発生し、最終的に // _ガイド間隔を変更する() を立て続けに2回呼び出してしまうことになるが……、まぁよしとする。 case 4: this.toolStripMenuItemガイド間隔4分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 0; break; case 6: this.toolStripMenuItemガイド間隔6分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 1; break; case 8: this.toolStripMenuItemガイド間隔8分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 2; break; case 12: this.toolStripMenuItemガイド間隔12分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 3; break; case 16: this.toolStripMenuItemガイド間隔16分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 4; break; case 24: this.toolStripMenuItemガイド間隔24分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 5; break; case 32: this.toolStripMenuItemガイド間隔32分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 6; break; case 36: this.toolStripMenuItemガイド間隔36分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 7; break; case 48: this.toolStripMenuItemガイド間隔48分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 8; break; case 64: this.toolStripMenuItemガイド間隔64分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 9; break; case 128: this.toolStripMenuItemガイド間隔128分.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 10; break; case 0: this.toolStripMenuItemガイド間隔フリー.CheckState = CheckState.Checked; this.toolStripComboBoxガイド間隔.SelectedIndex = 11; break; } //----------------- #endregion // 画面を再描画する。 this.pictureBox譜面パネル.Invalidate(); } private void _ガイド間隔を拡大する() { switch( this._現在のガイド間隔 ) { case 4: break; case 6: this._ガイド間隔を変更する( 4 ); break; case 8: this._ガイド間隔を変更する( 6 ); break; case 12: this._ガイド間隔を変更する( 8 ); break; case 16: this._ガイド間隔を変更する( 12 ); break; case 24: this._ガイド間隔を変更する( 16 ); break; case 32: this._ガイド間隔を変更する( 24 ); break; case 36: this._ガイド間隔を変更する( 32 ); break; case 48: this._ガイド間隔を変更する( 36 ); break; case 64: this._ガイド間隔を変更する( 48 ); break; case 128: this._ガイド間隔を変更する( 64 ); break; case 0: this._ガイド間隔を変更する( 128 ); break; } } private void _ガイド間隔を縮小する() { switch( this._現在のガイド間隔 ) { case 4: this._ガイド間隔を変更する( 6 ); break; case 6: this._ガイド間隔を変更する( 8 ); break; case 8: this._ガイド間隔を変更する( 12 ); break; case 12: this._ガイド間隔を変更する( 16 ); break; case 16: this._ガイド間隔を変更する( 24 ); break; case 24: this._ガイド間隔を変更する( 32 ); break; case 32: this._ガイド間隔を変更する( 36 ); break; case 36: this._ガイド間隔を変更する( 48 ); break; case 48: this._ガイド間隔を変更する( 64 ); break; case 64: this._ガイド間隔を変更する( 128 ); break; case 128: this._ガイド間隔を変更する( 0 ); break; case 0: break; } } private void _譜面拡大率を変更する( int n倍 ) { if( ( 1 > n倍 ) || ( this.toolStripComboBox譜面拡大率.Items.Count < n倍 ) ) throw new ArgumentException( $"不正な譜面拡大率({n倍})が指定されました。" ); this.toolStripComboBox譜面拡大率.SelectedIndex = ( n倍 - 1 ); this.譜面をリフレッシュする(); this.Config.ViewScale = n倍; } private void _最初から再生する() { this._指定された小節の先頭から再生する( 小節番号: 0 ); } private void _現在位置から再生する() { int 小節番号 = this.譜面.譜面内絶対位置gridに位置する小節の情報を返す( this.譜面.カレントラインの譜面内絶対位置grid ).小節番号; this._指定された小節の先頭から再生する( 小節番号 ); } private void _現在位置からBGMのみ再生する() { int 小節番号 = this.譜面.譜面内絶対位置gridに位置する小節の情報を返す( this.譜面.カレントラインの譜面内絶対位置grid ).小節番号; this._指定された小節の先頭から再生する( 小節番号, ドラム音を発声する: false ); } private void _指定された小節の先頭から再生する( int 小節番号, bool ドラム音を発声する = true ) { if( ( this.Config.ViewerPath.Nullまたは空である() ) || ( false == File.Exists( this.Config.ViewerPath ) ) ) return; // 前回の一時ファイルが存在していれば削除する。 if( File.Exists( this._最後にプレイヤーに渡した一時ファイル名 ) ) File.Delete( this._最後にプレイヤーに渡した一時ファイル名 ); // 新しい一時ファイルの名前をランダムに決める。 do { this._最後にプレイヤーに渡した一時ファイル名 = Path.Combine( this._作業フォルダパス, Path.GetRandomFileName() + @".sstf" ); } while( File.Exists( this._最後にプレイヤーに渡した一時ファイル名 ) ); // 同一名のファイルが存在してたらもう一度。(まずないだろうが) // 譜面を一時ファイルとして出力する。 this._上書き保存する( this._最後にプレイヤーに渡した一時ファイル名, 一時ファイルである: true ); // 一時ファイルである場合、「最近使ったファイル一覧」には残されない。 // ビュアーに演奏開始を指示する。 NamedPipeClientStream pipeStream = null; try { // ビュアーに接続を試みる。 pipeStream = this._Viewerに接続する(); if( pipeStream is null ) { #region " 接続に失敗したのでビュアーを起動する。" //---------------- if( this.Config.ViewerPath.Nullまたは空である() || !File.Exists( this.Config.ViewerPath ) ) return; // ビュアーの設定がないか、ビュアーファイルが存在していない。 // ビュアーオプション(-s)を付けてプロセスを起動。 Process.Start( this.Config.ViewerPath, "-s" ); // 再度ビュアーに接続を試みる。 for( int リトライ回数 = 0; リトライ回数 < 50; リトライ回数++ ) // 5秒相当 { pipeStream = this._Viewerに接続する(); if( null != pipeStream ) break; // つながった Thread.Sleep( 100 ); } if( pipeStream is null ) { // すべて接続に失敗した。諦める。 this._Viewer再生関連GUIのEnabledを設定する(); return; } //---------------- #endregion } // 演奏開始を指示する。 var options = new DTXMania2.CommandLineOptions() { Filename = this._最後にプレイヤーに渡した一時ファイル名, 再生開始 = true, 再生開始小節番号 = 小節番号, ドラム音を発声する = ドラム音を発声する, }; var ss = new StreamStringForNamedPipe( pipeStream ); var yamlText = options.ToYaml(); // YAML化 ss.WriteString( yamlText ); } catch { // 例外は無視。 } finally { pipeStream?.Dispose(); } } private void _再生を停止する() { if( ( this.Config.ViewerPath.Nullまたは空である() ) || ( false == File.Exists( this.Config.ViewerPath ) ) ) return; // プレイヤーの演奏を停止する。 NamedPipeClientStream pipeStream = null; try { // ビュアーに接続を試みる。 pipeStream = this._Viewerに接続する(); if( pipeStream is null ) return; // 失敗したら何もしない。 // 演奏停止を指示する。 var options = new DTXMania2.CommandLineOptions() { 再生停止 = true, }; var ss = new StreamStringForNamedPipe( pipeStream ); var yamlText = options.ToYaml(); // YAML化 ss.WriteString( yamlText ); } catch { // 例外は無視。 } finally { pipeStream?.Dispose(); } } private void _オプションを設定する() { using var dialog = new オプションダイアログ(); // Config の現在の値をダイアログへ設定する。 dialog.checkBoxオートフォーカス.CheckState = ( this.Config.AutoFocus ) ? CheckState.Checked : CheckState.Unchecked; dialog.checkBox最近使用したファイル.CheckState = ( this.Config.ShowRecentUsedFiles ) ? CheckState.Checked : CheckState.Unchecked; dialog.numericUpDown最近使用したファイルの最大表示個数.Value = this.Config.MaxOfUsedRecentFiles; dialog.textBoxViewerPath.Text = this.Config.ViewerPath; dialog.checkBoxSSTF変換通知ダイアログ.CheckState = ( this.Config.DisplaysConfirmOfSSTFConversion ) ? CheckState.Checked : CheckState.Unchecked; dialog.radioButtonRideLeft.Checked = this.Config.RideLeft; dialog.radioButtonRideRight.Checked = !this.Config.RideLeft; dialog.radioButtonChinaLeft.Checked = this.Config.ChinaLeft; dialog.radioButtonChinaRight.Checked = !this.Config.ChinaLeft; dialog.radioButtonSplashLeft.Checked = this.Config.SplashLeft; dialog.radioButtonSplashRight.Checked = !this.Config.SplashLeft; if( DialogResult.OK == dialog.ShowDialog( this ) ) { // 決定された値をダイアログから Config に反映する。 this.Config.AutoFocus = dialog.checkBoxオートフォーカス.Checked; this.Config.ShowRecentUsedFiles = dialog.checkBox最近使用したファイル.Checked; this.Config.MaxOfUsedRecentFiles = (int) dialog.numericUpDown最近使用したファイルの最大表示個数.Value; this.Config.ViewerPath = dialog.textBoxViewerPath.Text; this.Config.DisplaysConfirmOfSSTFConversion = dialog.checkBoxSSTF変換通知ダイアログ.Checked; this.Config.RideLeft = dialog.radioButtonRideLeft.Checked; this.Config.ChinaLeft = dialog.radioButtonChinaLeft.Checked; this.Config.SplashLeft = dialog.radioButtonSplashLeft.Checked; this._Viewer再生関連GUIのEnabledを設定する(); // [ファイル] メニューを修正。 this._ConfigのRecentUsedFilesをファイルメニューへ追加する(); // 譜面と編集モードに反映。 this.譜面.コンフィグを譜面に反映する( this.Config ); this.編集モード.レーン別チップ種別対応表を初期化する(); // Config.xml を保存する。 this.Config.保存する( Path.Combine( this._ユーザフォルダパス, Properties.Resources.CONFIG_FILE_NAME ) ); } // 画面を再描画してダイアログのゴミを消す。 this.Refresh(); } private void _バージョンを表示する() { using var dialog = new バージョン表示ダイアログ(); dialog.ShowDialog( this ); } private void _小節長倍率を変更する( int 小節番号 ) { double 変更後倍率 = 1.0; int 変更開始小節番号 = 小節番号; int 変更終了小節番号 = 小節番号; #region " 変更後の小節長倍率をユーザに入力させる。" //----------------- double 現在の小節長倍率 = this.譜面.スコア.小節長倍率を取得する( 小節番号 ); using( var dialog = new 小節長倍率入力ダイアログ( 小節番号 ) ) { dialog.倍率 = (float) 現在の小節長倍率; dialog.後続も全部変更する = false; if( DialogResult.OK != dialog.ShowDialog( this ) ) // キャンセルされたらここで中断。 return; 変更後倍率 = (double) dialog.倍率; 変更終了小節番号 = ( dialog.後続も全部変更する ) ? this.譜面.スコア.最大小節番号を返す() : 小節番号; } //----------------- #endregion try { this.UndoRedo管理.トランザクション記録を開始する(); for( int i = 変更開始小節番号; i <= 変更終了小節番号; i++ ) { var 変更前倍率 = this.譜面.スコア.小節長倍率を取得する( i ); #region " 新しい小節長倍率を設定する。" //----------------- var cell = new UndoRedo.セル<double>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 対象小節番号, 任意2 ) => { this.譜面.スコア.小節長倍率を設定する( (int) 対象小節番号, 変更前 ); this.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 対象小節番号, 任意2 ) => { this.譜面.スコア.小節長倍率を設定する( (int) 対象小節番号, 変更後 ); this.未保存である = true; }, 変更対象: 0.0, 変更前の値: 変更前倍率, 変更後の値: 変更後倍率, 任意1: i, 任意2: null ); this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); //----------------- #endregion #region " チップを移動または削除する。" //----------------- int 変化量grid = (int) ( ( 変更後倍率 - 変更前倍率 ) * this.GRID_PER_PART ); for( int j = this.譜面.スコア.チップリスト.Count - 1; j >= 0; j-- ) // 削除する場合があるので後ろからカウントする。 { var chip = (描画用チップ) this.譜面.スコア.チップリスト[ j ]; // (A) 変更対象の小節内のチップ → 移動なし。カウント変更あり。小節はみ出しチェックあり。 if( chip.小節番号 == i ) { #region " (A-a) 小節からはみ出したチップは、削除する。" //----------------- int 次小節の先頭位置grid = this.譜面.小節先頭の譜面内絶対位置gridを返す( i ) + (int) ( 変更後倍率 * this.GRID_PER_PART ); if( 次小節の先頭位置grid <= chip.譜面内絶対位置grid ) { var chip変更前 = new 描画用チップ( chip ); var cc = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); this.譜面.スコア.チップリスト.Add( 変更対象 ); this.譜面.スコア.チップリスト.Sort(); this.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this.譜面.スコア.チップリスト.Remove( 変更対象 ); this.未保存である = true; }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: null, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); cc.Redoを実行する(); } //----------------- #endregion #region " (A-b) 小節からはみ出さなかったチップは、パラメータを変更する。" //----------------- else { // 小節解像度を更新する。(小節内位置, 譜面内絶対位置grid は更新しない。) var cc = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.小節解像度 = (int) ( (double) 任意1 * this.GRID_PER_PART ); this.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.小節解像度 = (int) ( (double) 任意2 * this.GRID_PER_PART ); this.未保存である = true; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: 変更前倍率, 任意2: 変更後倍率 ); this.UndoRedo管理.セルを追加する( cc ); cc.Redoを実行する(); } //----------------- #endregion } // (B) 変更対象より先の小節内のチップ → 移動あり。カウントなし。小節はみ出しチェックなし。 else if( i < chip.小節番号 ) { #region " チップを 変化量grid ぶん移動する。" //----------------- var cc = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, _変化量grid, 任意2 ) => { 変更対象.譜面内絶対位置grid -= (int) _変化量grid; this.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, _変化量grid, 任意2 ) => { 変更対象.譜面内絶対位置grid += (int) _変化量grid; this.未保存である = true; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: 変化量grid, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); cc.Redoを実行する(); //----------------- #endregion } } //----------------- #endregion } } finally { this.UndoRedo管理.トランザクション記録を終了する(); // 画面を再描画する。 this.UndoRedo用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); this.未保存である = true; } } private void _小節を挿入する( int 挿入前小節番号 ) { // 挿入する新しい小節の小節長は、直前の(挿入前小節番号-1 の小節)と同じサイズとする。 double 小節長倍率 = ( 0 < 挿入前小節番号 ) ? this.譜面.スコア.小節長倍率を取得する( 挿入前小節番号 - 1 ) : 1.0; try { this.UndoRedo管理.トランザクション記録を開始する(); #region " 後方のチップを移動する。" //----------------- int 挿入に伴う増加量grid = (int) ( this.GRID_PER_PART * 小節長倍率 ); foreach( 描画用チップ chip in this.譜面.スコア.チップリスト ) { if( 挿入前小節番号 <= chip.小節番号 ) { var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, _挿入に伴う増加量grid, 任意2 ) => { 変更対象.小節番号--; 変更対象.譜面内絶対位置grid -= (int) _挿入に伴う増加量grid; }, Redoアクション: ( 変更対象, 変更前, 変更後, _挿入に伴う増加量grid, 任意2 ) => { 変更対象.小節番号++; 変更対象.譜面内絶対位置grid += (int) _挿入に伴う増加量grid; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: 挿入に伴う増加量grid, 任意2: null ); this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } //----------------- #endregion #region " 後方の小節長倍率を移動する。" //----------------- var cc = new UndoRedo.セル<double>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, _挿入前小節番号, 任意2 ) => { this.譜面.スコア.小節長倍率リスト.RemoveAt( (int) _挿入前小節番号 ); this.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, _挿入前小節番号, 任意2 ) => { this.譜面.スコア.小節長倍率リスト.Insert( (int) _挿入前小節番号, 小節長倍率 ); this.未保存である = true; }, 変更対象: 0.0, 変更前の値: 0.0, 変更後の値: 小節長倍率, 任意1: 挿入前小節番号, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); cc.Redoを実行する(); //----------------- #endregion } finally { this.UndoRedo管理.トランザクション記録を終了する(); // 画面を再描画する。 this.UndoRedo用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); this.未保存である = true; } } private void _小節を削除する( int 削除する小節番号 ) { double 削除する小節の小節長倍率 = this.譜面.スコア.小節長倍率を取得する( 削除する小節番号 ); // 削除する。 try { this.UndoRedo管理.トランザクション記録を開始する(); #region " 削除する小節内のチップをすべて削除する。" //----------------- for( int i = this.譜面.スコア.チップリスト.Count - 1; i >= 0; i-- ) { var chip = (描画用チップ) this.譜面.スコア.チップリスト[ i ]; if( 削除する小節番号 == chip.小節番号 ) { var chip変更前 = new 描画用チップ( chip ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); this.譜面.スコア.チップリスト.Add( 変更対象 ); this.譜面.スコア.チップリスト.Sort(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this.譜面.スコア.チップリスト.Remove( 変更対象 ); this.未保存である = true; }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: null, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } //----------------- #endregion #region " 削除した小節より後方のチップを、その小節分だけ前に移動する。" //----------------- int 削除に伴う減少量grid = (int) ( this.GRID_PER_PART * 削除する小節の小節長倍率 ); foreach( 描画用チップ chip in this.譜面.スコア.チップリスト ) { if( 削除する小節番号 < chip.小節番号 ) { var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, _削除に伴う減少量grid, 任意2 ) => { 変更対象.小節番号++; 変更対象.譜面内絶対位置grid += (int) _削除に伴う減少量grid; }, Redoアクション: ( 変更対象, 変更前, 変更後, _削除に伴う減少量grid, 任意2 ) => { 変更対象.小節番号--; 変更対象.譜面内絶対位置grid -= (int) _削除に伴う減少量grid; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: 削除に伴う減少量grid, 任意2: null ); this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } //----------------- #endregion #region " 削除した小節を、小節長倍率リストからも削除する。" //----------------- var cc = new UndoRedo.セル<double>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, _削除する小節番号, 任意2 ) => { this.譜面.スコア.小節長倍率リスト.Insert( (int) _削除する小節番号, 変更前 ); this.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, _削除する小節番号, 任意2 ) => { this.譜面.スコア.小節長倍率リスト.RemoveAt( (int) _削除する小節番号 ); this.未保存である = true; }, 変更対象: 0.0, 変更前の値: 削除する小節の小節長倍率, 変更後の値: 0.0, 任意1: 削除する小節番号, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); cc.Redoを実行する(); //----------------- #endregion } finally { this.UndoRedo管理.トランザクション記録を終了する(); // 画面を再描画する。 this.UndoRedo用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); this.未保存である = true; } } private void _小節の先頭へ移動する( int 小節番号 ) { // 小節番号をクリッピングする。 小節番号 = Math.Clamp( 小節番号, min: 0, max: this.譜面.スコア.最大小節番号を返す() ); // 垂直スクロールバーを移動させると、画面も自動的に移動する。 var bar = this.vScrollBar譜面用垂直スクロールバー; bar.Value = ( ( bar.Maximum + 1 ) - bar.LargeChange ) - this.譜面.小節先頭の譜面内絶対位置gridを返す( 小節番号 ); } /// <summary> /// 選択中のチップの音量を一括指定する。 /// </summary> /// <param name="音量">1~8。</param> private void _音量を一括設定する( int 音量 ) { // 譜面にフォーカスがないなら何もしない。 if( false == this.pictureBox譜面パネル.Focused ) return; try { this.UndoRedo管理.トランザクション記録を開始する(); #region " 譜面が持つすべてのチップについて、選択されているチップがあればその音量を変更する。" //---------------- for( int i = this.譜面.スコア.チップリスト.Count - 1; 0 <= i; i-- ) { var chip = (描画用チップ)this.譜面.スコア.チップリスト[ i ]; if( chip.選択が確定していない ) continue; var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.音量 = (int)任意1; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.音量 = (int)任意2; this.未保存である = true; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: chip.音量, // 変更前の音量 任意2: 音量 ); // 変更後の音量 this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } //---------------- #endregion } finally { this.UndoRedo管理.トランザクション記録を終了する(); #region " GUI を再描画する。" //---------------- this.UndoRedo用GUIのEnabledを設定する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); //---------------- #endregion } } //---------------- #endregion #region " アクション補佐メソッド(複数のアクションで共通する処理。) " //---------------- private void _エディタを初期化する() { this._編集中のファイル名 = null; #region " 各種オブジェクトを生成する。" //----------------- this.譜面?.Dispose(); this.譜面 = new 譜面( this ); // 譜面は、選択・編集モードよりも先に生成すること。 this.譜面.コンフィグを譜面に反映する( this.Config ); this.UndoRedo管理 = new UndoRedo.UndoRedo管理(); this.選択モード = new 選択モード( this ); this.編集モード = new 編集モード( this ); this.クリップボード = new クリップボード( this ); //----------------- #endregion // GUI の初期値を設定する。 #region " 基本情報タブ " //----------------- this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox曲名.Clear(); this.textBoxアーティスト名.Clear(); this.textBoxLevel.Text = "5.00"; this.trackBarLevel.Value = 500; this.textBox説明.Clear(); this.textBoxBGV.Clear(); this.textBoxBGM.Clear(); this.numericUpDownメモ用小節番号.Value = 0; this.textBoxメモ.Clear(); this.textBoxプレビュー音声.Clear(); this.textBoxプレビュー画像.Clear(); this.pictureBoxプレビュー画像.Image = Properties.Resources.既定のプレビュー画像; //----------------- #endregion #region " Viewer 再生 " //----------------- this._Viewer再生関連GUIのEnabledを設定する(); //----------------- #endregion #region " ガイド間隔 " //----------------- this._ガイド間隔を変更する( 16 ); // 初期値は 1/16。 //----------------- #endregion #region " 譜面拡大率 " //----------------- this._譜面拡大率を変更する( this.Config.ViewScale ); //----------------- #endregion #region " Undo/Redo " //----------------- this._次のプロパティ変更がUndoRedoリストに載るようにする(); this.UndoRedo用GUIのEnabledを設定する(); //----------------- #endregion #region " 垂直スクロールバー " //----------------- this.vScrollBar譜面用垂直スクロールバー.Minimum = 0; this.vScrollBar譜面用垂直スクロールバー.Maximum = ( this.譜面.全小節の高さgrid - 1 ); this.vScrollBar譜面用垂直スクロールバー.SmallChange = ( this.GRID_PER_PART / 16 ); this.vScrollBar譜面用垂直スクロールバー.LargeChange = this.GRID_PER_PART; this.vScrollBar譜面用垂直スクロールバー.Value = this.vScrollBar譜面用垂直スクロールバー.Maximum - this.vScrollBar譜面用垂直スクロールバー.LargeChange; //----------------- #endregion // 最初は編集モードで始める。 this.編集モードに切替えて関連GUIを設定する(); this.未保存である = false; } private DialogResult _未保存なら保存する() { // 既に保存済みなら何もしない。 if( false == this.未保存である ) return DialogResult.OK; // [編集中のデータを保存しますか?] ダイアログを表示。 var result = MessageBox.Show( Properties.Resources.MSG_編集中のデータを保存しますか, Properties.Resources.MSG_確認ダイアログのタイトル, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1 ); // Yes なら上書き保存する。 if( DialogResult.Yes == result ) this._上書き保存する(); // 画面を再描画してダイアログを消去する。 this.Refresh(); return result; // ダイアログの結果を返す。 } private string _ファイル保存ダイアログを開いてファイル名を取得する() { DialogResult result; string ファイル名; int filterIndex; // ダイアログでファイル名を取得する。 using( var dialog = new SaveFileDialog() { Title = "名前をつけて保存", Filter = "SSTFoverDTXファイル(*.dtx)|*.dtx|SSTFファイル(*.sstf)|*.sstf", FilterIndex = 1, InitialDirectory = this._作業フォルダパス, FileName = Path.GetFileNameWithoutExtension( this._編集中のファイル名 ), } ) { result = dialog.ShowDialog( this ); ファイル名 = dialog.FileName; filterIndex = dialog.FilterIndex; } // 画面を再描画してダイアログのゴミを消去する。 this.Refresh(); // キャンセルされたら ""(空文字列)を返す。 if( DialogResult.OK != result ) return ""; // ファイルの拡張子がなければ付与する。 if( 0 == Path.GetExtension( ファイル名 ).Length ) { string 既定の拡張子 = filterIndex switch { 1 => ".dtx", 2 => ".sstf", _ => throw new NotImplementedException(), }; ファイル名 = Path.ChangeExtension( ファイル名, 既定の拡張子 ); } return ファイル名; } private void _ファイルを読み込む( string ファイル名 ) { bool SSTFoverDTXである = SSTF.スコア.SSTFoverDTX.ファイルがSSTFoverDTXである( ファイル名 ); #region " .sstf 以外のファイルの場合(SSTFoverDTXを除く)、SSTF形式でインポートする旨を表示する。" //---------------- if( this.Config.DisplaysConfirmOfSSTFConversion ) { var 拡張子 = Path.GetExtension( ファイル名 ).ToLower(); if( 拡張子 != ".sstf" && !SSTFoverDTXである ) // SSTFoverDTX なら表示しない { // [SSTF形式に変換しますか?] ダイアログを表示。 var result = MessageBox.Show( Properties.Resources.MSG_SSTF形式に変換します, Properties.Resources.MSG_確認ダイアログのタイトル, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1 ); // No なら何もしない。 if( DialogResult.No == result ) return; } } //---------------- #endregion this._エディタを初期化する(); #region " [読み込み中です] ポップアップを表示する。" //----------------- var msg = new Popupメッセージ( Properties.Resources.MSG_読み込み中です + Environment.NewLine + Properties.Resources.MSG_しばらくお待ち下さい ); msg.Owner = this; msg.Show(); msg.Refresh(); //----------------- #endregion try { // 読み込む。 this.譜面.曲データファイルを読み込む( ファイル名 ); // 最低でも 10 小節は存在させる。 int 最大小節番号 = this.譜面.スコア.最大小節番号を返す(); for( int n = 最大小節番号 + 1; n < 9; n++ ) ; string 読み込み時の拡張子 = Path.GetExtension( ファイル名 ).ToLower(); if( !SSTFoverDTXである ) { // 読み込んだファイルの拡張子を .sstf に変換。(ファイルはすでに読み込み済み) this._編集中のファイル名 = Path.ChangeExtension( Path.GetFileName( ファイル名 ), ".sstf" ); } else this._編集中のファイル名 = Path.GetFileName( ファイル名 ); this._作業フォルダパス = Path.GetDirectoryName( ファイル名 ) + @"\"; // 読み込んだファイルを [ファイル]メニューの最近使ったファイル一覧に追加する。 this.Config.ファイルを最近使ったファイルの一覧に追加する( Path.Combine( this._作業フォルダパス, this._編集中のファイル名 ) ); this._ConfigのRecentUsedFilesをファイルメニューへ追加する(); // 基本情報タブを設定する。 this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox曲名.Text = 譜面.スコア.曲名; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxアーティスト名.Text = 譜面.スコア.アーティスト名; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxLevel.Text = 譜面.スコア.難易度.ToString( "0.00" ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.trackBarLevel.Value = Math.Clamp( (int) ( 譜面.スコア.難易度 * 100 ), min: 0, max: 999 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox説明.Text = 譜面.スコア.説明文; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxBGV.Text = 譜面.スコア.BGVファイル名; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxBGM.Text = 譜面.スコア.BGMファイル名; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxメモ.Text = ( this.譜面.スコア.小節メモリスト.ContainsKey( 0 ) ) ? this.譜面.スコア.AVIリスト[ 0 ] : ""; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxプレビュー音声.Text = 譜面.スコア.プレビュー音声ファイル名; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxプレビュー画像.Text = 譜面.スコア.プレビュー画像ファイル名; this._プレビュー画像を更新する(); // ウィンドウのタイトルバーの表示変更(str編集中のファイル名 が確定した後に) this.未保存である = true; // 以前の状態によらず、確実に更新するようにする。 // 読み込み時と拡張子が同一である場合は、保存済み状態としておく。 if( 読み込み時の拡張子.ToLower() == Path.GetExtension( this._編集中のファイル名 ).ToLower() ) this.未保存である = false; } catch( InvalidDataException ) { MessageBox.Show( Properties.Resources.MSG_対応していないファイルです, Properties.Resources.MSG_確認ダイアログのタイトル, MessageBoxButtons.OK ); } #region "「読み込み中です」ポップアップを閉じる。 " //----------------- msg.Close(); //----------------- #endregion // 最後に、ダイアログのゴミなどを消すために画面を再描画する。 this.Refresh(); } private enum タブ種別 : int { 基本情報 = 0 } private void _タブを選択する( タブ種別 eタブ種別 ) { this.tabControl情報タブコンテナ.SelectedIndex = (int) eタブ種別; } private void _次のプロパティ変更がUndoRedoリストに載らないようにする() { UndoRedo.UndoRedo管理.UndoRedoした直後である = true; } private void _次のプロパティ変更がUndoRedoリストに載るようにする() { UndoRedo.UndoRedo管理.UndoRedoした直後である = false; } private void _垂直スクロールバーと譜面の上下位置を調整する() { var bar = this.vScrollBar譜面用垂直スクロールバー; var box = this.pictureBox譜面パネル; var panel2 = this.splitContainer分割パネルコンテナ.Panel2; // 譜面パネルの長さをパネルに合わせて調整する。 box.ClientSize = new Size( box.ClientSize.Width, panel2.ClientSize.Height - box.Location.Y ); // 現在のバーの位置を割合で記憶する。 var bar率 = (double) bar.Value / (double) ( bar.Maximum - bar.Minimum ); // 新しい値域を設定した後、バーの位置を記憶しておいた割合で設定。 bar.Minimum = 0; bar.Maximum = this.譜面.全小節の高さgrid - 1; bar.Value = (int) ( ( bar.Maximum - bar.Minimum ) * bar率 ); // 譜面長さが画面長さより短いなら、スクロールバーを表示しない。 bar.Enabled = ( bar.Maximum > bar.LargeChange ) ? true : false; } private void _Viewer再生関連GUIのEnabledを設定する() { bool 各GUIは有効; using( var pipeStream = this._Viewerに接続する() ) { if( null != pipeStream ) { // (A) パイプラインサーバが起動しているなら、各GUIは有効。 各GUIは有効 = true; } else if( File.Exists( this.Config.ViewerPath ) ) { // (B) パイプラインサーバが起動していなくても、設定されている Viewer ファイルが存在するなら、各GUIは有効。 各GUIは有効 = true; } else { // (C) パイプラインサーバが起動しておらず、かつ Viewer ファイルも存在しないなら、各GUIは無効。 各GUIは有効 = false; } } this.toolStripButton先頭から再生.Enabled = 各GUIは有効; this.toolStripButton現在位置から再生.Enabled = 各GUIは有効; this.toolStripButton現在位置からBGMのみ再生.Enabled = 各GUIは有効; this.toolStripButton再生停止.Enabled = 各GUIは有効; this.toolStripMenuItem先頭から再生.Enabled = 各GUIは有効; this.toolStripMenuItem現在位置から再生.Enabled = 各GUIは有効; this.toolStripMenuItem現在位置からBGMのみ再生.Enabled = 各GUIは有効; this.toolStripMenuItem再生停止.Enabled = 各GUIは有効; } private void _ConfigのRecentUsedFilesをファイルメニューへ追加する() { #region " [ファイル] メニューから、[最近使ったファイルの一覧] をクリアする。" //----------------- for( int i = 0; i < this.toolStripMenuItemファイル.DropDownItems.Count; i++ ) { var item = this.toolStripMenuItemファイル.DropDownItems[ i ]; // ↓削除したくないサブメニューの一覧。これ以外のサブメニュー項目はすべて削除する。 if( item != this.toolStripMenuItem新規作成 && item != this.toolStripMenuItem開く && item != this.toolStripMenuItem上書き保存 && item != this.toolStripMenuItem名前を付けて保存 && item != this.toolStripSeparator1 && item != this.toolStripMenuItem終了 ) { this.toolStripMenuItemファイル.DropDownItems.Remove( item ); i = -1; // 要素数が変わったので列挙しなおし。RemoveAll() はないのか。 } } //----------------- #endregion if( ( false == this.Config.ShowRecentUsedFiles ) || // 表示しない or ( 0 == this.Config.RecentUsedFiles.Count ) ) // 履歴が 0 件 return; #region " Config が持つ履歴にそって、[ファイル] メニューにサブメニュー項目リストを追加する(ただし最大表示数まで)。" //----------------- // [File] のサブメニューリストに項目が1つでもある場合は、履歴サブメニュー項目を追加する前に、[終了] の下にセパレータを入れる。手動で。 bool セパレータの追加がまだ = true; // すべての [最近使ったファイル] について... for( int i = 0; i < this.Config.RecentUsedFiles.Count; i++ ) { // 最大表示数を越えたら中断。 if( this.Config.MaxOfUsedRecentFiles <= i ) return; // ファイルパスを、サブメニュー項目として [ファイル] メニューに追加する。 string ファイルパス = this.Config.RecentUsedFiles[ i ]; if( string.IsNullOrEmpty( ファイルパス ) ) continue; // セパレータの追加がまだなら追加する。 if( セパレータの追加がまだ ) { this.toolStripMenuItemファイル.DropDownItems.Add( new ToolStripSeparator() { Size = this.toolStripSeparator1.Size } ); セパレータの追加がまだ = false; } // ToolStripMenuItem を手動で作って [ファイル] のサブメニューリストに追加する。 var item = new ToolStripMenuItem() { Name = $"最近使ったファイル{i}", Size = this.toolStripMenuItem終了.Size, Text = $"&{i} {ファイルパス}", ToolTipText = ファイルパス, }; item.Click += new EventHandler( this.toolStripMenuItem最近使ったファイル_Click ); this.toolStripMenuItemファイル.DropDownItems.Add( item ); // 追加したファイルが既に存在していないなら項目を無効化(グレー表示)する。 if( false == File.Exists( ファイルパス ) ) item.Enabled = false; } //----------------- #endregion } private Point _現在のマウス位置を譜面パネル内座標pxに変換して返す() { return this.pictureBox譜面パネル.PointToClient( new Point( Cursor.Position.X, Cursor.Position.Y ) ); } private void _現在のチップ音量をツールバーに表示する() { this.toolStripLabel音量.Text = ( this._音量toラベル.ContainsKey( this.現在のチップ音量 ) ) ? this._音量toラベル[ this.現在のチップ音量 ] : @"???"; } private void _プレビュー画像を更新する() { try { string path = this.textBoxプレビュー画像.Text; if( !Path.IsPathRooted( path ) ) path = Path.Combine( this._作業フォルダパス, path ); this.pictureBoxプレビュー画像.Image = System.Drawing.Image.FromFile( path ); } catch { this.pictureBoxプレビュー画像.Image = Properties.Resources.既定のプレビュー画像; } } //---------------- #endregion // GUIイベントメソッド #region " メインフォーム イベント " //----------------- protected void メインフォーム_DragEnter( object sender, DragEventArgs e ) { if( e.Data.GetDataPresent( DataFormats.FileDrop ) ) { e.Effect = DragDropEffects.Copy; // ファイルならコピーと見なす(カーソルがコピー型になる) } else { e.Effect = DragDropEffects.None; // ファイルじゃないなら無視(カーソル変化なし) } } protected void メインフォーム_DragDrop( object sender, DragEventArgs e ) { string[] data = (string[]) e.Data.GetData( DataFormats.FileDrop ); if( 1 <= data.Length ) { // Dropされたファイルが複数あっても、先頭のファイルだけを有効とする。 this._指定されたファイルを開く( data[ 0 ] ); } } protected void メインフォーム_FormClosing( object sender, FormClosingEventArgs e ) { if( DialogResult.Cancel == this._未保存なら保存する() ) { e.Cancel = true; } else { this._アプリの終了処理を行う(); } } protected void メインフォーム_ResizeEnd( object sender, EventArgs e ) { // 新しい位置とサイズをコンフィグに記憶しておく。 this.Config.WindowLocation = this.Location; this.Config.ClientSize = this.ClientSize; } //----------------- #endregion #region " メニューバー イベント [File] " //----------------- protected void toolStripMenuItem新規作成_Click( object sender, EventArgs e ) { this._新規作成する(); } protected void toolStripMenuItem開く_Click( object sender, EventArgs e ) { this._開く(); } protected void toolStripMenuItem上書き保存_Click( object sender, EventArgs e ) { this._上書き保存する(); } protected void toolStripMenuItem名前を付けて保存_Click( object sender, EventArgs e ) { this._名前を付けて保存する(); } protected void toolStripMenuItem終了_Click( object sender, EventArgs e ) { this._終了する(); } protected void toolStripMenuItem最近使ったファイル_Click( object sender, EventArgs e ) { // ※このイベントハンドラに対応する「toolStripMenuItem最近使ったファイル」というアイテムはデザイナにはないので注意。 // 最近使ったファイルをFileメニューへ追加する際に、手動で作って追加したアイテムに対するハンドラである。 this._指定されたファイルを開く( ( (ToolStripMenuItem) sender ).ToolTipText ); } //----------------- #endregion #region " メニューバー イベント [Edit] " //---------------- protected void toolStripMenuItem元に戻す_Click( object sender, EventArgs e ) { this._元に戻す(); } protected void toolStripMenuItemやり直す_Click( object sender, EventArgs e ) { this._やり直す(); } protected void toolStripMenuItem切り取り_Click( object sender, EventArgs e ) { this._切り取る(); } protected void toolStripMenuItemコピー_Click( object sender, EventArgs e ) { this._コピーする(); } protected void toolStripMenuItem貼り付け_Click( object sender, EventArgs e ) { var マウスの位置 = this._現在のマウス位置を譜面パネル内座標pxに変換して返す(); // (A) マウスが譜面上になかった → 表示領域下辺から貼り付ける。 if( ( ( 0 > マウスの位置.X ) || ( 0 > マウスの位置.Y ) ) || ( ( マウスの位置.X > this.譜面パネルサイズ.Width ) || ( マウスの位置.Y > this.譜面パネルサイズ.Height ) ) ) { this._貼り付ける( this.譜面.譜面表示下辺の譜面内絶対位置grid ); } // (B) マウスが譜面上にある → そこから貼り付ける。 else { this._貼り付ける( this.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( マウスの位置.Y ) ); } } protected void toolStripMenuItem削除_Click( object sender, EventArgs e ) { this._削除する(); } protected void toolStripMenuItemすべて選択_Click( object sender, EventArgs e ) { this._すべて選択する(); } protected void toolStripMenuItem選択モード_Click( object sender, EventArgs e ) { this.選択モードに切替えて関連GUIを設定する(); } protected void toolStripMenuItem編集モード_Click( object sender, EventArgs e ) { this.編集モードに切替えて関連GUIを設定する(); } protected void toolStripMenuItemモード切替え_Click( object sender, EventArgs e ) { this._モードを切替える(); } protected void toolStripMenuItem検索_Click( object sender, EventArgs e ) { this._検索する(); } //---------------- #endregion #region " メニューバー イベント [View] " //---------------- protected void toolStripMenuItemガイド間隔4分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 4 ); } protected void toolStripMenuItemガイド間隔6分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 6 ); } protected void toolStripMenuItemガイド間隔8分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 8 ); } protected void toolStripMenuItemガイド間隔12分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 12 ); } protected void toolStripMenuItemガイド間隔16分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 16 ); } protected void toolStripMenuItemガイド間隔24分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 24 ); } protected void toolStripMenuItemガイド間隔32分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 32 ); } protected void toolStripMenuItemガイド間隔36分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 36 ); } protected void toolStripMenuItemガイド間隔48分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 48 ); } protected void toolStripMenuItemガイド間隔64分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 64 ); } protected void toolStripMenuItemガイド間隔128分_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 128 ); } protected void toolStripMenuItemガイド間隔フリー_Click( object sender, EventArgs e ) { this._ガイド間隔を変更する( 0 ); } protected void toolStripMenuItemガイド間隔拡大_Click( object sender, EventArgs e ) { this._ガイド間隔を拡大する(); } protected void toolStripMenuItemガイド間隔縮小_Click( object sender, EventArgs e ) { this._ガイド間隔を縮小する(); } //---------------- #endregion #region " メニューバー イベント [Play] " //---------------- protected void toolStripMenuItem先頭から再生_Click( object sender, EventArgs e ) { this._最初から再生する(); } protected void toolStripMenuItem現在位置から再生_Click( object sender, EventArgs e ) { this._現在位置から再生する(); } protected void toolStripMenuItem現在位置からBGMのみ再生_Click( object sender, EventArgs e ) { this._現在位置からBGMのみ再生する(); } protected void toolStripMenuItem再生停止_Click( object sender, EventArgs e ) { this._再生を停止する(); } //---------------- #endregion #region " メニューバー イベント [Tool] " //---------------- protected void toolStripMenuItemオプション_Click( object sender, EventArgs e ) { this._オプションを設定する(); } //---------------- #endregion #region " メニューバー イベント [Help] " //---------------- protected void toolStripMenuItemバージョン_Click( object sender, EventArgs e ) { this._バージョンを表示する(); } //---------------- #endregion #region " ツールバー イベント " //----------------- protected void toolStripButton新規作成_Click( object sender, EventArgs e ) { this._新規作成する(); } protected void toolStripButton開く_Click( object sender, EventArgs e ) { this._開く(); } protected void toolStripButton上書き保存_Click( object sender, EventArgs e ) { this._上書き保存する(); } protected void toolStripButton切り取り_Click( object sender, EventArgs e ) { this._切り取る(); } protected void toolStripButtonコピー_Click( object sender, EventArgs e ) { this._コピーする(); } protected void toolStripButton貼り付け_Click( object sender, EventArgs e ) { var マウスの位置 = this._現在のマウス位置を譜面パネル内座標pxに変換して返す(); // (A) マウスが譜面上になかった → 表示領域下辺から貼り付ける。 if( ( ( マウスの位置.X < 0 ) || ( マウスの位置.Y < 0 ) ) || ( ( マウスの位置.X > this.譜面パネルサイズ.Width ) || ( マウスの位置.Y > this.譜面パネルサイズ.Height ) ) ) { this._貼り付ける( this.譜面.譜面表示下辺の譜面内絶対位置grid ); } // (B) マウスが譜面上にある → そこから貼り付ける。 else { this._貼り付ける( this.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( マウスの位置.Y ) ); } } protected void toolStripButton削除_Click( object sender, EventArgs e ) { this._削除する(); } protected void toolStripButton元に戻す_Click( object sender, EventArgs e ) { this._元に戻す(); } protected void toolStripButtonやり直す_Click( object sender, EventArgs e ) { this._やり直す(); } protected void toolStripComboBox譜面拡大率_SelectedIndexChanged( object sender, EventArgs e ) { this._譜面拡大率を変更する( this.toolStripComboBox譜面拡大率.SelectedIndex + 1 ); } protected void toolStripComboBoxガイド間隔_SelectedIndexChanged( object sender, EventArgs e ) { switch( this.toolStripComboBoxガイド間隔.SelectedIndex ) { case 0: this._ガイド間隔を変更する( 4 ); return; case 1: this._ガイド間隔を変更する( 6 ); return; case 2: this._ガイド間隔を変更する( 8 ); return; case 3: this._ガイド間隔を変更する( 12 ); return; case 4: this._ガイド間隔を変更する( 16 ); return; case 5: this._ガイド間隔を変更する( 24 ); return; case 6: this._ガイド間隔を変更する( 32 ); return; case 7: this._ガイド間隔を変更する( 36 ); return; case 8: this._ガイド間隔を変更する( 48 ); return; case 9: this._ガイド間隔を変更する( 64 ); return; case 10: this._ガイド間隔を変更する( 128 ); return; case 11: this._ガイド間隔を変更する( 0 ); return; } } protected void toolStripButton選択モード_Click( object sender, EventArgs e ) { this._選択モードにする(); } protected void toolStripButton編集モード_Click( object sender, EventArgs e ) { this._編集モードにする(); } protected void toolStripButton先頭から再生_Click( object sender, EventArgs e ) { this._最初から再生する(); } protected void toolStripButton現在位置から再生_Click( object sender, EventArgs e ) { this._現在位置から再生する(); } protected void toolStripButton現在位置からBGMのみ再生_Click( object sender, EventArgs e ) { this._現在位置からBGMのみ再生する(); } protected void toolStripButton再生停止_Click( object sender, EventArgs e ) { this._再生を停止する(); } protected void toolStripComboBox再生速度_SelectedIndexChanged( object sender, EventArgs e ) { // 誤差回避のため、10倍したものを10で割る。 int v = 17 - this.toolStripComboBox再生速度.SelectedIndex; this.譜面.スコア.Viewerでの再生速度 = v / 10.0; } protected void toolStripButton音量Down_Click( object sender, EventArgs e ) { bool 譜面上に選択チップがある = this._選択チップが1個以上ある; // 選択中のチップの有無で挙動が異なる。 if( 譜面上に選択チップがある ) { #region " (A) 選択中のチップ音量の相対操作 " //---------------- try { this.UndoRedo管理.トランザクション記録を開始する(); #region " 選択されているすべてのチップについて、その音量をそれぞれ1つずつ下げる。" //---------------- foreach( 描画用チップ chip in this.譜面.スコア.チップリスト ) { if( chip.選択が確定している ) { int 新音量 = Math.Max( chip.音量 - 1, メインフォーム.最小音量 ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.音量 = (int)任意1; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.音量 = (int)任意2; this.未保存である = true; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: chip.音量, // 変更前の音量 任意2: 新音量 ); // 変更後の音量 this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } //---------------- #endregion } finally { this.UndoRedo管理.トランザクション記録を終了する(); #region " GUI を再描画する。" //---------------- this.UndoRedo用GUIのEnabledを設定する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); //---------------- #endregion } //---------------- #endregion } else { #region " (B) 現在のチップ音量の操作 " //---------------- int 新音量 = this.現在のチップ音量 - 1; this.現在のチップ音量 = ( 新音量 < メインフォーム.最小音量 ) ? メインフォーム.最小音量 : 新音量; this._現在のチップ音量をツールバーに表示する(); //---------------- #endregion } } protected void toolStripButton音量UP_Click( object sender, EventArgs e ) { bool 譜面上に選択チップがある = this._選択チップが1個以上ある; // 選択中のチップの有無で挙動が異なる。 if( 譜面上に選択チップがある ) { #region " (A) 選択中のチップ音量の相対操作 " //---------------- try { this.UndoRedo管理.トランザクション記録を開始する(); #region " 選択されているすべてのチップについて、その音量をそれぞれ1つずつ上げる。" //---------------- foreach( 描画用チップ chip in this.譜面.スコア.チップリスト ) { if( chip.選択が確定している ) { int 新音量 = Math.Min( chip.音量 + 1, メインフォーム.最大音量 ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.音量 = (int)任意1; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.音量 = (int)任意2; this.未保存である = true; }, 変更対象: chip, 変更前の値: null, 変更後の値: null, 任意1: chip.音量, // 変更前の音量 任意2: 新音量 ); // 変更後の音量 this.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } //---------------- #endregion } finally { this.UndoRedo管理.トランザクション記録を終了する(); #region " GUI を再描画する。" //---------------- this.UndoRedo用GUIのEnabledを設定する(); this.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.譜面をリフレッシュする(); //---------------- #endregion } //---------------- #endregion } else { #region " (B) 現在のチップ音量操作 " //---------------- int 新音量 = this.現在のチップ音量 + 1; this.現在のチップ音量 = ( 新音量 > メインフォーム.最大音量 ) ? メインフォーム.最大音量 : 新音量; this._現在のチップ音量をツールバーに表示する(); //---------------- #endregion } } //----------------- #endregion #region " 分割パネルコンテナ、譜面パネル、スクロールバー イベント " //----------------- protected void pictureBox譜面パネル_MouseClick( object sender, MouseEventArgs e ) { // フォーカスを得る。 this.pictureBox譜面パネル.Focus(); // 各モードに処理を引き継ぐ。 if( this.選択モードである ) { this.選択モード.MouseClick( e ); } else { this.編集モード.MouseClick( e ); } } protected void pictureBox譜面パネル_MouseDown( object sender, MouseEventArgs e ) { // 各モードに処理を引き継ぐ。 if( this.選択モードである ) this.選択モード.MouseDown( e ); } protected void pictureBox譜面パネル_MouseEnter( object sender, EventArgs e ) { // オートフォーカスが有効の場合、譜面にマウスが入ったら譜面がフォーカスを得る。 if( this.Config.AutoFocus ) this.pictureBox譜面パネル.Focus(); } protected void pictureBox譜面パネル_MouseLeave( object sender, EventArgs e ) { // 各モードに処理を引き継ぐ。 if( this.編集モードである ) this.編集モード.MouseLeave( e ); } protected void pictureBox譜面パネル_MouseMove( object sender, MouseEventArgs e ) { // 各モードに処理を引き継ぐ。 if( this.選択モードである ) { this.選択モード.MouseMove( e ); } else { this.編集モード.MouseMove( e ); } } protected void pictureBox譜面パネル_Paint( object sender, PaintEventArgs e ) { if( false == this.初期化完了 ) return; // 初期化が終わってないのに呼び出されることがあるので、その場合は無視。 #region " 小節数が変わってたら、スクロールバーの値域を調整する。" //----------------- int 全譜面の高さgrid = this.譜面.全小節の高さgrid; if( this.vScrollBar譜面用垂直スクロールバー.Maximum != 全譜面の高さgrid - 1 ) // 小節数が変わっている { // 譜面の高さ(grid)がどれだけ変わったか? int 増加分grid = ( 全譜面の高さgrid - 1 ) - this.vScrollBar譜面用垂直スクロールバー.Maximum; #region " スクロールバーの状態を新しい譜面の高さに合わせる。" //----------------- { int value = this.vScrollBar譜面用垂直スクロールバー.Value; // 次の式で Maximum が Value より小さくなると例外が発生するので、 this.vScrollBar譜面用垂直スクロールバー.Value = 0; // Value のバックアップを取っておいて、ひとまず 0 にする。 this.vScrollBar譜面用垂直スクロールバー.Maximum = 全譜面の高さgrid - 1; int newValue = value + 増加分grid; // オーバーフローしないようクリッピングする。 if( 0 > newValue ) { this.vScrollBar譜面用垂直スクロールバー.Value = 0; } else if( ( this.vScrollBar譜面用垂直スクロールバー.Maximum - this.vScrollBar譜面用垂直スクロールバー.LargeChange ) <= newValue ) { this.vScrollBar譜面用垂直スクロールバー.Value = this.vScrollBar譜面用垂直スクロールバー.Maximum - this.vScrollBar譜面用垂直スクロールバー.LargeChange; } else { this.vScrollBar譜面用垂直スクロールバー.Value = newValue; } } //----------------- #endregion #region " 譜面表示下辺の位置を更新する。" //----------------- this.譜面.譜面表示下辺の譜面内絶対位置grid = ( ( this.vScrollBar譜面用垂直スクロールバー.Maximum - this.vScrollBar譜面用垂直スクロールバー.LargeChange ) + 1 ) - this.vScrollBar譜面用垂直スクロールバー.Value; //----------------- #endregion } //----------------- #endregion #region " 譜面を描画する。" //----------------- this.譜面.描画する( e.Graphics, this.pictureBox譜面パネル ); //----------------- #endregion // 各モードに処理を引き継ぐ。 if( this.選択モードである ) { this.選択モード.Paint( e ); } else { this.編集モード.Paint( e ); } } protected void pictureBox譜面パネル_PreviewKeyDown( object sender, PreviewKeyDownEventArgs e ) { if( Keys.Prior == e.KeyCode ) { #region " PageUp → 垂直つまみを移動させる。あとはこの移動で生じる ChangedValue イベントで処理。" //----------------- int 移動すべき数grid = -this.GRID_PER_PART; int 新しい位置 = this.vScrollBar譜面用垂直スクロールバー.Value + 移動すべき数grid; int 最小値 = this.vScrollBar譜面用垂直スクロールバー.Minimum; int 最大値 = ( this.vScrollBar譜面用垂直スクロールバー.Maximum + 1 ) - this.vScrollBar譜面用垂直スクロールバー.LargeChange; if( 新しい位置 < 最小値 ) { 新しい位置 = 最小値; } else if( 新しい位置 > 最大値 ) { 新しい位置 = 最大値; } this.vScrollBar譜面用垂直スクロールバー.Value = 新しい位置; //----------------- #endregion } else if( Keys.Next == e.KeyCode ) { #region " PageDown → 垂直つまみを移動させる。あとはこの移動で生じる ChangedValue イベントで処理。" //----------------- int 移動すべき数grid = this.GRID_PER_PART; int 新しい位置 = this.vScrollBar譜面用垂直スクロールバー.Value + 移動すべき数grid; int 最小値 = this.vScrollBar譜面用垂直スクロールバー.Minimum; int 最大値 = ( this.vScrollBar譜面用垂直スクロールバー.Maximum + 1 ) - this.vScrollBar譜面用垂直スクロールバー.LargeChange; if( 新しい位置 < 最小値 ) { 新しい位置 = 最小値; } else if( 新しい位置 > 最大値 ) { 新しい位置 = 最大値; } this.vScrollBar譜面用垂直スクロールバー.Value = 新しい位置; //----------------- #endregion } else { // 各モードに処理を引き継ぐ。 if( this.編集モードである ) this.編集モード.PreviewKeyDown( e ); } } protected void splitContainer分割パネルコンテナ_MouseWheel( object sender, MouseEventArgs e ) { if( false == this.初期化完了 ) return; // 初期化が終わってないのに呼び出されることがあるので、その場合は無視。 #region " 移動量に対応する grid だけ垂直つまみを移動させる。あとはこの移動で生じる ChangedValue イベントで処理する。" //----------------- if( 0 == e.Delta ) return; // 移動量なし // 移動すべきグリッド数を計算する。 const int 拍の行数 = 32; // 1行=0.125拍とする。 int 移動すべき行数 = ( SystemInformation.MouseWheelScrollLines != -1 ) ? // e.Delta は MouseWheelScrollDelta の倍数であり、スクロールバーを下へ動かしたいときに負、上へ動かしたいときに正となる。 ( -e.Delta / SystemInformation.MouseWheelScrollDelta ) * SystemInformation.MouseWheelScrollLines : // MouseWheelScrollLines == -1 は「1画面単位」を意味する。 // ここでは、1画面=1小節とみなす。 Math.Sign( -e.Delta ) * 拍の行数; int 移動すべき数grid = 移動すべき行数 * ( this.GRID_PER_PART / 拍の行数 ); // スクロールバーのつまみを移動する。 int 新しい位置 = this.vScrollBar譜面用垂直スクロールバー.Value + 移動すべき数grid; int 最小値 = this.vScrollBar譜面用垂直スクロールバー.Minimum; int 最大値 = ( this.vScrollBar譜面用垂直スクロールバー.Maximum + 1 ) - this.vScrollBar譜面用垂直スクロールバー.LargeChange; this.vScrollBar譜面用垂直スクロールバー.Value = Math.Clamp( 新しい位置, 最小値, 最大値 ); //----------------- #endregion } protected void splitContainer分割パネルコンテナ_Panel2_SizeChanged( object sender, EventArgs e ) { if( false == this.初期化完了 ) return; // 初期化が終わってないのに呼び出されることがあるので、その場合は無視。 this._垂直スクロールバーと譜面の上下位置を調整する(); } protected void splitContainer分割パネルコンテナ_Panel2_Paint( object sender, PaintEventArgs e ) { if( false == this.初期化完了 ) return; // 初期化が終わってないのに呼び出されることがあるので、その場合は無視。 var g = e.Graphics; var メモ領域左上隅の位置 = new PointF() { X = this.譜面.レーンの合計幅px, Y = this.pictureBox譜面パネル.Location.Y, }; #region " [小節メモ] を描画する。" //----------------- g.DrawString( Properties.Resources.MSG_小節メモ, this._メモ用フォント, Brushes.White, PointF.Add( メモ領域左上隅の位置, new Size( 24, -24 )/*マージン*/ ) ); //----------------- #endregion #region " 小節メモの内容を描画する。" //----------------- // グリッド値は 上辺>下辺 なので注意。 int パネル下辺grid = this.譜面.譜面表示下辺の譜面内絶対位置grid; int パネル上辺grid = パネル下辺grid + ( this.pictureBox譜面パネル.ClientSize.Height * this.GRID_PER_PIXEL ); int 開始小節番号 = this.譜面.譜面表示下辺に位置する小節番号; int 最大小節番号 = this.譜面.スコア.最大小節番号を返す(); for( int 小節番号 = 開始小節番号; 小節番号 <= 最大小節番号; 小節番号++ ) { int 小節の下辺grid = this.譜面.小節先頭の譜面内絶対位置gridを返す( 小節番号 ); int 小節の上辺grid = 小節の下辺grid + this.譜面.小節長をグリッドで返す( 小節番号 ); if( 小節の下辺grid > パネル上辺grid ) break; // 小節が画面上方にはみ出し切ってしまったらそこで終了。 if( this.譜面.スコア.小節メモリスト.ContainsKey( 小節番号 ) ) { string メモ = this.譜面.スコア.小節メモリスト[ 小節番号 ]; string[] lines = メモ.Split( new string[] { Environment.NewLine }, StringSplitOptions.None ); int 行数 = lines.Length; var メモの位置 = new PointF() { X = メモ領域左上隅の位置.X + 4, // + 4 はマージン Y = メモ領域左上隅の位置.Y + ( パネル上辺grid - 小節の下辺grid ) / this.GRID_PER_PIXEL - ( 行数 * 16 ), // 9pt = だいたい16px }; g.DrawString( メモ, this._メモ用フォント, Brushes.White, メモの位置 ); } } //----------------- #endregion } protected void vScrollBar譜面用垂直スクロールバー_ValueChanged( object sender, EventArgs e ) { if( false == this.初期化完了 ) return; // 初期化が終わってないのに呼び出されることがあるので、その場合は無視。 var bar = vScrollBar譜面用垂直スクロールバー; if( bar.Enabled ) { // 下辺の位置を再計算。 this.譜面.譜面表示下辺の譜面内絶対位置grid = ( ( bar.Maximum + 1 ) - bar.LargeChange ) - bar.Value; // 編集モードの場合、カーソルのgrid位置を再計算。 if( this.編集モードである ) { var cp = this.pictureBox譜面パネル.PointToClient( Cursor.Position ); this.編集モード.MouseMove( new MouseEventArgs( MouseButtons.None, 0, cp.X, cp.Y, 0 ) ); } // メモ用小節番号を再計算。 this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.numericUpDownメモ用小節番号.Value = this.譜面.カレントラインに位置する小節番号; this._次のプロパティ変更がUndoRedoリストに載るようにする(); // 小節メモを再描画する。 this.splitContainer分割パネルコンテナ.Panel2.Refresh(); } } //----------------- #endregion #region " 譜面右メニュー イベント " //----------------- protected void toolStripMenuItem選択チップの切り取り_Click( object sender, EventArgs e ) { this._切り取る(); } protected void toolStripMenuItem選択チップのコピー_Click( object sender, EventArgs e ) { this._コピーする(); } protected void toolStripMenuItem選択チップの貼り付け_Click( object sender, EventArgs e ) { // メニューが開かれたときのマウスの座標を取得。 // ※メニューは必ずマウス位置を左上にして表示されるとは限らないため、メニューの表示位置からは取得しないこと。 var マウスの位置 = this._選択モードでコンテクストメニューを開いたときのマウスの位置; if( this.譜面.譜面パネル内X座標pxにある編集レーンを返す( マウスの位置.X ) == 編集レーン種別.Unknown ) return; // クリックされた場所にレーンがないなら無視。 // アクションを実行。 this._貼り付ける( this.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( マウスの位置.Y ) ); } protected void toolStripMenuItem選択チップの削除_Click( object sender, EventArgs e ) { this._削除する(); } protected void toolStripMenuItemすべてのチップの選択_Click( object sender, EventArgs e ) { // 編集モードなら強制的に選択モードにする。 if( this.編集モードである ) this.選択モードに切替えて関連GUIを設定する(); // 全チップを選択。 this.選択モード.全チップを選択する(); } protected void toolStripMenuItem小節長変更_Click( object sender, EventArgs e ) { // メニューが開かれたときのマウスの座標を取得。 // ※メニューは必ずマウス位置を左上にして表示されるとは限らないため、メニューの表示位置からは取得しないこと。 var マウスの位置 = this._選択モードでコンテクストメニューを開いたときのマウスの位置; if( this.譜面.譜面パネル内X座標pxにある編集レーンを返す( マウスの位置.X ) == 編集レーン種別.Unknown ) return; // クリックされた場所にレーンがないなら無視。 // アクションを実行。 this._小節長倍率を変更する( this.譜面.譜面パネル内Y座標pxにおける小節番号を返す( マウスの位置.Y ) ); } protected void toolStripMenuItem小節の挿入_Click( object sender, EventArgs e ) { // メニューが開かれたときのマウスの座標を取得。 // ※メニューは必ずマウス位置を左上にして表示されるとは限らないため、メニューの表示位置からは取得しないこと。 var マウスの位置 = this._選択モードでコンテクストメニューを開いたときのマウスの位置; if( this.譜面.譜面パネル内X座標pxにある編集レーンを返す( マウスの位置.X ) == 編集レーン種別.Unknown ) return; // クリックされた場所にレーンがないなら無視。 // アクションを実行。 this._小節を挿入する( this.譜面.譜面パネル内Y座標pxにおける小節番号を返す( マウスの位置.Y ) ); } protected void toolStripMenuItem小節の削除_Click( object sender, EventArgs e ) { // メニューが開かれたときのマウスの座標を取得。 // ※メニューは必ずマウス位置を左上にして表示されるとは限らないため、メニューの表示位置からは取得しないこと。 var マウスの位置 = this._選択モードでコンテクストメニューを開いたときのマウスの位置; if( this.譜面.譜面パネル内X座標pxにある編集レーンを返す( マウスの位置.X ) == 編集レーン種別.Unknown ) return; // クリックされた場所にレーンがないなら無視。 // アクションを実行。 this._小節を削除する( this.譜面.譜面パネル内Y座標pxにおける小節番号を返す( マウスの位置.Y ) ); } protected void toolStripMenuItem音量1_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 8 ); } protected void toolStripMenuItem音量2_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 7 ); } protected void toolStripMenuItem音量3_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 6 ); } protected void toolStripMenuItem音量4_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 5 ); } protected void toolStripMenuItem音量5_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 4 ); } protected void toolStripMenuItem音量6_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 3 ); } protected void toolStripMenuItem音量7_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 2 ); } protected void toolStripMenuItem音量8_Click( object sender, System.EventArgs e ) { this._音量を一括設定する( 1 ); } //----------------- #endregion #region " 基本情報タブ イベント " //----------------- protected void textBox曲名_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBox曲名 ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBox曲名.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBox曲名, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox曲名.Text = 変更前; this.textBox曲名.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox曲名.Text = 変更後; this.textBox曲名.Focus(); }, 変更対象: null, 変更前の値: this.textBox曲名_以前の値, 変更後の値: this.textBox曲名.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBox曲名_以前の値 = this.textBox曲名.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.曲名 = this.textBox曲名.Text; } protected void textBox曲名_Validated( object sender, EventArgs e ) { // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBox曲名 ); } private string textBox曲名_以前の値 = ""; protected void textBoxアーティスト名_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBoxアーティスト名 ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxアーティスト名.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxアーティスト名, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxアーティスト名.Text = 変更前; this.textBoxアーティスト名.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxアーティスト名.Text = 変更後; this.textBoxアーティスト名.Focus(); }, 変更対象: null, 変更前の値: this.textBoxアーティスト名_以前の値, 変更後の値: this.textBoxアーティスト名.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxアーティスト名_以前の値 = this.textBoxアーティスト名.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.アーティスト名 = this.textBoxアーティスト名.Text; } protected void textBoxアーティスト名_Validated( object sender, EventArgs e ) { // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxアーティスト名 ); } private string textBoxアーティスト名_以前の値 = ""; protected void textBox説明_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBox説明 ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBox説明.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBox説明, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox説明.Text = 変更前; this.textBox説明.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBox説明.Text = 変更後; this.textBox説明.Focus(); }, 変更対象: null, 変更前の値: this.textBox説明_以前の値, 変更後の値: this.textBox説明.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBox説明_以前の値 = this.textBox説明.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.説明文 = this.textBox説明.Text; } protected void textBox説明_Validated( object sender, EventArgs e ) { // 最新 UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBox説明 ); } private string textBox説明_以前の値 = ""; protected void textBoxメモ_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加or修正する。" //----------------- if( !UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? UndoRedo.セルBase cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( cell != null ) && cell.所有権がある( this.textBoxメモ ) ) { // (Yes) 最新のセルの "変更後の値" を <現在の値> に更新。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxメモ.Text; } else { // (No) セルを新規追加: // "変更前の値" = <以前の値> // "変更後の値" = <現在の値> // "所有者ID" = 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxメモ, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this.numericUpDownメモ用小節番号.Value = (decimal) 任意1; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxメモ.Text = 変更前; this.textBoxメモ.Focus(); int 小節番号 = (int) ( (decimal) 任意1 ); #region " dicメモ の更新 " //----------------- if( this.譜面.スコア.小節メモリスト.ContainsKey( 小節番号 ) ) { if( string.IsNullOrEmpty( 変更前 ) ) this.譜面.スコア.小節メモリスト.Remove( 小節番号 ); else this.譜面.スコア.小節メモリスト[ 小節番号 ] = 変更前; } else { if( !string.IsNullOrEmpty( 変更前 ) ) this.譜面.スコア.小節メモリスト.Add( 小節番号, 変更前 ); } //----------------- #endregion this._小節の先頭へ移動する( 小節番号 ); this.splitContainer分割パネルコンテナ.Panel2.Refresh(); // 小節メモをリフレッシュ。 }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this.numericUpDownメモ用小節番号.Value = (decimal) 任意1; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxメモ.Text = 変更後; this.textBoxメモ.Focus(); int 小節番号 = (int) ( (decimal) 任意1 ); #region " dicメモの更新 " //----------------- if( this.譜面.スコア.小節メモリスト.ContainsKey( 小節番号 ) ) { if( string.IsNullOrEmpty( 変更後 ) ) this.譜面.スコア.小節メモリスト.Remove( 小節番号 ); else this.譜面.スコア.小節メモリスト[ 小節番号 ] = 変更後; } else { if( !string.IsNullOrEmpty( 変更後 ) ) this.譜面.スコア.小節メモリスト.Add( 小節番号, 変更後 ); } //----------------- #endregion this._小節の先頭へ移動する( 小節番号 ); this.splitContainer分割パネルコンテナ.Panel2.Refresh(); // 小節メモをリフレッシュ。 }, 変更対象: null, 変更前の値: this.textBoxメモ_以前の値, 変更後の値: this.textBoxメモ.Text, 任意1: (object) this.numericUpDownメモ用小節番号.Value, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxメモ_以前の値 = this.textBoxメモ.Text; // <以前の値> = <現在の値> if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) this.未保存である = true; UndoRedo.UndoRedo管理.UndoRedoした直後である = false; #region " 小節番号に対応するメモを dicメモ に登録する。" //----------------- { int 小節番号 = (int) this.numericUpDownメモ用小節番号.Value; if( string.IsNullOrEmpty( this.textBoxメモ.Text ) ) { // (A) 空文字列の場合 if( this.譜面.スコア.小節メモリスト.ContainsKey( 小節番号 ) ) this.譜面.スコア.小節メモリスト.Remove( 小節番号 ); // 存在してたら削除。 // 存在してなかったら何もしない。 } else { // (B) その他の場合 if( this.譜面.スコア.小節メモリスト.ContainsKey( 小節番号 ) ) this.譜面.スコア.小節メモリスト[ 小節番号 ] = this.textBoxメモ.Text; // 存在してたら更新。 else this.譜面.スコア.小節メモリスト.Add( 小節番号, this.textBoxメモ.Text ); // 存在してなかったら追加。 } } //----------------- #endregion #region " もし最終小節だったなら、後ろに4つ小節を加える。" //----------------- { int 小節番号 = (int) this.numericUpDownメモ用小節番号.Value; if( 小節番号 == this.譜面.スコア.最大小節番号を返す() ) { this.譜面.最後の小節の後ろに小節を4つ追加する(); } } //----------------- #endregion } protected void textBoxメモ_Validated( object sender, EventArgs e ) { // 最新 UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxメモ ); // 小節メモをリフレッシュ。 this.splitContainer分割パネルコンテナ.Panel2.Refresh(); } private string textBoxメモ_以前の値 = ""; protected void numericUpDownメモ用小節番号_ValueChanged( object sender, EventArgs e ) { // 小節番号にあわせて、textBoxメモにメモを表示する。 int 小節番号 = (int) this.numericUpDownメモ用小節番号.Value; this._次のプロパティ変更がUndoRedoリストに載らないようにする(); if( this.譜面.スコア.小節メモリスト.ContainsKey( 小節番号 ) ) this.textBoxメモ.Text = this.譜面.スコア.小節メモリスト[ 小節番号 ]; else this.textBoxメモ.Text = ""; this._次のプロパティ変更がUndoRedoリストに載るようにする(); } protected void trackBarLevel_Scroll( object sender, EventArgs e ) { // テキストボックスに数値を反映。(0~999 → 0.00~9.99 に変換) this.textBoxLevel.Text = ( this.trackBarLevel.Value / 100.0 ).ToString( "0.00" ); // テキストボックスに Validation を起こさせる。 this.textBoxLevel.Focus(); this.trackBarLevel.Focus(); } protected void textBoxLevel_Validating( object sender, System.ComponentModel.CancelEventArgs e ) { // 入力値が 0.00 ~ 9.99 の小数であるか確認する。 if( float.TryParse( this.textBoxLevel.Text, out float val ) ) { // 値を丸める if( val < 0.0f ) { this.textBoxLevel.Text = "0.00"; val = 0.0f; } else if( val > 9.99f ) { this.textBoxLevel.Text = "9.99"; val = 9.99f; } #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBoxLevel ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxLevel.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxLevel, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxLevel.Text = 変更前; this.textBoxLevel.Focus(); this.trackBarLevel.Value = ( string.IsNullOrEmpty( 変更前 ) ) ? 0 : (int) ( float.Parse( 変更前 ) * 100 ); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxLevel.Text = 変更後; this.textBoxLevel.Focus(); this.trackBarLevel.Value = ( string.IsNullOrEmpty( 変更後 ) ) ? 0 : (int) ( float.Parse( 変更後 ) * 100 ); }, 変更対象: null, 変更前の値: this.textBoxLevel_以前の値, 変更後の値: this.textBoxLevel.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxLevel_以前の値 = this.textBoxLevel.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // トラックバーに反映する。 this.trackBarLevel.Value = (int) ( val * 100 ); // スコアに反映する。 譜面.スコア.難易度 = val; } else { e.Cancel = true; this.textBoxLevel.Text = ( this.trackBarLevel.Value / 100 ).ToString( "0.00" ); this.textBoxLevel.Select(); } } protected void textBoxLevel_Validated( object sender, EventArgs e ) { // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxLevel ); } private string textBoxLevel_以前の値 = "5.00"; protected void textBoxBGV_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBoxBGV ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxBGV.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxBGV, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxBGV.Text = 変更前; this.textBoxBGV.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxBGV.Text = 変更後; this.textBoxBGV.Focus(); }, 変更対象: null, 変更前の値: this.textBoxBGV_以前の値, 変更後の値: this.textBoxBGV.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxBGV_以前の値 = this.textBoxBGV.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.BGVファイル名 = this.textBoxBGV.Text; } protected void textBoxBGV_Validated( object sender, EventArgs e ) { // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxBGV ); } private string textBoxBGV_以前の値 = ""; protected void buttonBGV参照_Click( object sender, EventArgs e ) { #region " ファイルを開くダイアログでファイルを選択する。" //----------------- using var dialog = new OpenFileDialog() { Title = Properties.Resources.MSG_ファイル選択ダイアログのタイトル, Filter = Properties.Resources.MSG_背景動画ファイル選択ダイアログのフィルタ, FilterIndex = 1, InitialDirectory = this._作業フォルダパス, }; var result = dialog.ShowDialog( this ); // メインフォームを再描画してダイアログを完全に消す。 this.Refresh(); // OKじゃないならここで中断。 if( DialogResult.OK != result ) return; //----------------- #endregion this.textBoxBGV.Text = FDK.Folder.絶対パスを相対パスに変換する( this._作業フォルダパス, dialog.FileName ); } protected void textBoxBGM_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBoxBGM ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxBGM.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxBGM, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxBGM.Text = 変更前; this.textBoxBGM.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxBGM.Text = 変更後; this.textBoxBGM.Focus(); }, 変更対象: null, 変更前の値: this.textBoxBGM_以前の値, 変更後の値: this.textBoxBGM.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxBGM_以前の値 = this.textBoxBGM.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.BGMファイル名 = this.textBoxBGM.Text; } private void textBoxBGM_Validated( object sender, EventArgs e ) { // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxBGM ); } private string textBoxBGM_以前の値 = ""; protected void buttonBGM参照_Click( object sender, EventArgs e ) { #region " ファイルを開くダイアログでファイルを選択する。" //----------------- using var dialog = new OpenFileDialog() { Title = Properties.Resources.MSG_ファイル選択ダイアログのタイトル, Filter = Properties.Resources.MSG_背景動画ファイル選択ダイアログのフィルタ, FilterIndex = 1, InitialDirectory = this._作業フォルダパス, }; var result = dialog.ShowDialog( this ); // メインフォームを再描画してダイアログを完全に消す。 this.Refresh(); // OKじゃないならここで中断。 if( DialogResult.OK != result ) return; //----------------- #endregion this.textBoxBGM.Text = FDK.Folder.絶対パスを相対パスに変換する( this._作業フォルダパス, dialog.FileName ); } protected void textBoxプレビュー音声_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBoxプレビュー音声 ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxプレビュー音声.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxプレビュー音声, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxプレビュー音声.Text = 変更前; this.textBoxプレビュー音声.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxプレビュー音声.Text = 変更後; this.textBoxプレビュー音声.Focus(); }, 変更対象: null, 変更前の値: this.textBoxプレビュー音声_以前の値, 変更後の値: this.textBoxプレビュー音声.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxプレビュー音声_以前の値 = this.textBoxプレビュー音声.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.プレビュー音声ファイル名 = this.textBoxプレビュー音声.Text; } protected void textBoxプレビュー音声_Validated( object sender, EventArgs e ) { // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxプレビュー音声 ); } private string textBoxプレビュー音声_以前の値 = ""; private void buttonプレビュー音声_Click( object sender, EventArgs e ) { #region " ファイルを開くダイアログでファイルを選択する。" //----------------- using var dialog = new OpenFileDialog() { Title = Properties.Resources.MSG_ファイル選択ダイアログのタイトル, Filter = Properties.Resources.MSG_背景動画ファイル選択ダイアログのフィルタ, FilterIndex = 1, InitialDirectory = this._作業フォルダパス, }; var result = dialog.ShowDialog( this ); // メインフォームを再描画してダイアログを完全に消す。 this.Refresh(); // OKじゃないならここで中断。 if( DialogResult.OK != result ) return; //----------------- #endregion this.textBoxプレビュー音声.Text = FDK.Folder.絶対パスを相対パスに変換する( this._作業フォルダパス, dialog.FileName ); } private void textBoxプレビュー画像_TextChanged( object sender, EventArgs e ) { #region " この変更が Undo/Redo したことによるものではない場合、UndoRedoセルを追加 or 修正する。" //----------------- if( false == UndoRedo.UndoRedo管理.UndoRedoした直後である ) { // 最新のセルの所有者が自分? var cell = this.UndoRedo管理.Undoするセルを取得して返す_見るだけ(); if( ( null != cell ) && cell.所有権がある( this.textBoxプレビュー画像 ) ) { // (A) 所有者である → 最新のセルの "変更後の値" を現在のコントロールの値に更新する。 ( (UndoRedo.セル<string>) cell ).変更後の値 = this.textBoxプレビュー画像.Text; } else { // (B) 所有者ではない → 以下のようにセルを新規追加する。 // "変更前の値" ← 以前の値 // "変更後の値" ← 現在の値 // "所有者ID" ← 対象となるコンポーネントオブジェクト var cc = new UndoRedo.セル<string>( 所有者ID: this.textBoxプレビュー画像, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxプレビュー画像.Text = 変更前; this.textBoxプレビュー画像.Focus(); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this._タブを選択する( タブ種別.基本情報 ); this._次のプロパティ変更がUndoRedoリストに載らないようにする(); this.textBoxプレビュー画像.Text = 変更後; this.textBoxプレビュー画像.Focus(); }, 変更対象: null, 変更前の値: this.textBoxプレビュー画像_以前の値, 変更後の値: this.textBoxプレビュー画像.Text, 任意1: null, 任意2: null ); this.UndoRedo管理.セルを追加する( cc ); // Undo ボタンを有効にする。 this.UndoRedo用GUIのEnabledを設定する(); } } //----------------- #endregion this.textBoxプレビュー画像_以前の値 = this.textBoxプレビュー画像.Text; // 以前の値 ← 現在の値 UndoRedo.UndoRedo管理.UndoRedoした直後である = false; this.未保存である = true; // スコアには随時保存する。 譜面.スコア.プレビュー画像ファイル名 = this.textBoxプレビュー画像.Text; } private void textBoxプレビュー画像_Validated( object sender, EventArgs e ) { this._プレビュー画像を更新する(); // 最新の UndoRedoセル の所有権を放棄する。 this.UndoRedo管理.Undoするセルを取得して返す_見るだけ()?.所有権を放棄する( this.textBoxプレビュー画像 ); } private string textBoxプレビュー画像_以前の値 = ""; private void buttonプレビュー画像参照_Click( object sender, EventArgs e ) { #region " ファイルを開くダイアログでファイルを選択する。" //----------------- using var dialog = new OpenFileDialog() { Title = Properties.Resources.MSG_ファイル選択ダイアログのタイトル, Filter = Properties.Resources.MSG_画像ファイル選択ダイアログのフィルタ, FilterIndex = 1, InitialDirectory = this._作業フォルダパス, }; var result = dialog.ShowDialog( this ); // メインフォームを再描画してダイアログを完全に消す。 this.Refresh(); // OKじゃないならここで中断。 if( DialogResult.OK != result ) return; //----------------- #endregion this.textBoxプレビュー画像.Text = FDK.Folder.絶対パスを相対パスに変換する( this._作業フォルダパス, dialog.FileName ); this._プレビュー画像を更新する(); } //----------------- #endregion } } <|start_filename|>DTXMania2/タスクメッセージ/TaskMessageQueue.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; namespace DTXMania2 { /// <summary> /// <see cref="TaskMessage"/> の送受信に使用するキュー。 /// </summary> class TaskMessageQueue { // 生成と終了 public TaskMessageQueue() { this._TaskMessageList = new List<TaskMessage>(); } // メッセージの送信・取得 /// <summary> /// タスクメッセージをキューに格納し、完了通知待ち用のイベントを返す。 /// </summary> /// <returns> /// 返されるイベントは、引数で受け取ったメッセージの <see cref="TaskMessage.完了通知"/> と同一である。 /// </returns> public ManualResetEventSlim Post( TaskMessage msg ) { lock( this._TaskMessageList ) { this._TaskMessageList.Add( msg ); return msg.完了通知; } } /// <summary> /// 宛先に対するメッセージを1つ取得して返す。 /// </summary> /// <param name="宛先">取得するメッセージの宛先。</param> /// <returns>取得できたメッセージの列挙。1つも無ければ空の列挙を返す。</returns> public IEnumerable<TaskMessage> Get( TaskMessage.タスク名 宛先 ) { lock( this._TaskMessageList ) { var result = new List<TaskMessage>(); // 指定された宛先のメッセージをリストから抽出。 for( int i = 0; i < this._TaskMessageList.Count; i++ ) { var msg = this._TaskMessageList[ i ]; if( msg.宛先 == 宛先 ) { result.Add( msg ); } } // 抽出されたメッセージをリストから削除。 foreach( var msg in result ) this._TaskMessageList.Remove( msg ); // 結果を返す。 return result; } } // ローカル private readonly List<TaskMessage> _TaskMessageList; } } <|start_filename|>DTXMania2/ドラム入力/ドラム入力種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace DTXMania2 { /// <summary> /// 入力データの種別を、ドラム様式で定義したもの。 /// DTXMania2 では、演奏用の入力データは、すべてこのドラム入力種別へマッピングされる。 /// </summary> enum ドラム入力種別 { Unknown, LeftCrash, Ride, //Ride_Cup, --> Ride として扱う。(打ち分けない。) China, Splash, HiHat_Open, //HiHat_HalfOpen, --> HiHat_Open として扱う。(打ち分けない。) HiHat_Close, HiHat_Foot, // --> フットスプラッシュ HiHat_Control, // --> ハイハット開度 Snare, Snare_OpenRim, Snare_ClosedRim, //Snare_Ghost, --> ヒット判定しない。 Bass, Tom1, Tom1_Rim, Tom2, Tom2_Rim, Tom3, Tom3_Rim, RightCrash, //LeftCymbal_Mute, --> (YAMAHAでは)入力信号じゃない //RightCymbal_Mute, --> (YAMAHAでは)入力信号じゃない Pause_Resume, PlaySpeed_Up, PlaySpeed_Down, } } <|start_filename|>FDK/イメージ/画面キャプチャ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Direct3D11; using SharpDX.DXGI; namespace FDK { public static class 画面キャプチャ { /// <summary> /// 現在のバックバッファの内容を Bitmap に複写して返す。 /// すべての描画が終わったあと、Present() する前に呼び出すこと。 /// </summary> /// <returns>Bitmap。使用後は解放すること。</returns> public static Bitmap 取得する( SharpDX.Direct3D11.Device1 d3dDevice1, SwapChain1 swapchain1, RenderTargetView renderTargetView, SharpDX.Direct2D1.DeviceContext d2dDeviceContext ) { // バックバッファの情報を取得する。 Texture2DDescription backBufferDesc; using( var backBuffer = swapchain1.GetBackBuffer<Texture2D>( 0 ) ) backBufferDesc = backBuffer.Description; // CPUがアクセス可能な Texture2D バッファをGPU上に作成する。 using var captureTexture = new Texture2D( d3dDevice1, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, // CPUからアクセスできる。 Format = backBufferDesc.Format, Height = backBufferDesc.Height, Width = backBufferDesc.Width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription( 1, 0 ), Usage = ResourceUsage.Staging, // GPU から CPU への copy ができる。 } ); // RenderTarget から Texture2D バッファに、GPU上で画像データをコピーする。 using( var resource = renderTargetView.Resource ) d3dDevice1.ImmediateContext.CopyResource( resource, captureTexture ); // Texture2D の本体(DXGIサーフェス)から Bitmap を生成する。 using var dxgiSurface = captureTexture.QueryInterface<Surface>(); var dataRect = dxgiSurface.Map( SharpDX.DXGI.MapFlags.Read, out DataStream dataStream ); try { return new Bitmap( d2dDeviceContext, new Size2( captureTexture.Description.Width, captureTexture.Description.Height ), new DataPointer( dataStream.DataPointer, (int)dataStream.Length ), dataRect.Pitch, new BitmapProperties( new PixelFormat( Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore ), d2dDeviceContext.DotsPerInch.Width, d2dDeviceContext.DotsPerInch.Width ) ); } finally { dxgiSurface.Unmap(); } } } } <|start_filename|>FDK/サウンド/Sound.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using CSCore; namespace FDK { public class Sound : ISampleSource { // プロパティ public bool 再生中である => this._DeviceRef.TryGetTarget( out SoundDevice? device ) && device.Mixer.Contains( this ); public bool 再生中ではない => !( this.再生中である ); /// <summary> /// シークが可能なら true。 /// </summary> public bool CanSeek => this._BaseSampleSource?.CanSeek ?? false; /// <summary> /// このサウンドのフォーマット。 /// </summary> public WaveFormat WaveFormat => this._BaseSampleSource.WaveFormat; /// <remarks> /// 1つの <see cref="SampleSource"/>を複数の<see cref="Sound"/>インスタンスで共有できるように、 /// このプロパティは<see cref="Sound"/>インスタンスごとに独立して管理する。 /// </remarks> public long Position { get => this._Position; set => this._Position = Math.Clamp( value, min: 0, max: this.Length ); } public long Length => this._BaseSampleSource?.Length ?? 0; /// <summary> /// 音量。0.0(無音)~1.0(原音)~...上限なし /// </summary> /// <remarks> /// このクラスではなく、<see cref="Mixer"/>クラスから参照して使用する。 /// </remarks> public float Volume { get => this._Volume; set => this._Volume = Math.Max( value, 0 ); } public bool IsLoop { get; set; } = false; /// <summary> /// 一時停止中なら true /// </summary> public bool IsPaused { get; set; } = false; // 生成と終了 public Sound( SoundDevice device, ISampleSource sampleSource ) : this( device ) { this._BaseSampleSource = sampleSource; } protected Sound( SoundDevice device ) { if( device is null ) throw new ArgumentNullException(); this._BaseSampleSource = null!; this._DeviceRef = new WeakReference<SoundDevice>( device ); } public virtual void Dispose() { this.Stop(); //this._BaseSampleSource?.Dispose(); Dispose は行わない。(SampleSource は複数の Sound で共有されている可能性があるため。) } // 再生制御 public void Play( long 再生開始位置frame = 0, bool ループ再生する = false ) { if( this._BaseSampleSource is null ) throw new InvalidOperationException( "サンプルソースが null です。" ); if( this._DeviceRef.TryGetTarget( out SoundDevice? device ) ) { // BaseSampleSource の位置を、再生開始位置へ移動。 if( this._BaseSampleSource.CanSeek ) { this._Position = 再生開始位置frame * this.WaveFormat.Channels; //this._BaseSampleSource.Position = this._Position; --> ここではまだ設定しない。Read() で設定する。 } else { //Log.WARNING( $"このサンプルソースの再生位置を変更することができません。既定の位置から再生を開始します。" ); this._Position = 0; } this.IsLoop = ループ再生する; // ミキサーに追加(=再生開始)。 device.Mixer.AddSound( this ); } } public void Play( double 再生開始位置sec, bool ループ再生する = false ) => this.Play( this.秒ToFrame( 再生開始位置sec ), ループ再生する ); public void Stop() { if( ( null != this._DeviceRef ) && this._DeviceRef.TryGetTarget( out SoundDevice? device ) ) { device.Mixer.RemoveSound( this ); } } public void Pause() { if( this.再生中ではない ) return; // 停止。 this.Stop(); this.IsPaused = true; } public void Resume() { if( this.IsPaused ) { // 停止位置から再生。 this.Play( this.Position / this.WaveFormat.Channels, // position → frame this.IsLoop ); this.IsPaused = false; } } // 出力 public int Read( float[] buffer, int offset, int count ) { // ソースが未設定(null)なら即再生終了 if( this._BaseSampleSource is null ) return 0; if( this._BaseSampleSource.Length <= this._Position ) { // (A) 最後まで再生済んだ、または次のストリームデータが届いていない場合 if( this.IsLoop ) { // (A-a) ループする場合 this._Position = 0; // 再生位置を先頭に戻す。 Array.Clear( buffer, offset, count ); // 全部ゼロで埋めて返す。 return count; } else { // (A-b) ループしない場合 return 0; // 再生終了。 } } else { // (B) 読み込みできるストリームデータがある場合 // 1つの BaseSampleSource を複数の Sound で共有するために、Position は Sound ごとに管理している。 this._BaseSampleSource.Position = this._Position; var readCount = this._BaseSampleSource.Read( buffer, offset, count ); // 読み込み。 this._Position = this._BaseSampleSource.Position; if( 0 == readCount && this.IsLoop ) this._Position = 0; // 再生をループ。 return readCount; } } // その他 public long 秒ToFrame( double 時間sec ) { if( this._BaseSampleSource is null ) return 0; return (long)( 時間sec * this._BaseSampleSource.WaveFormat.SampleRate + 0.5 ); // +0.5 で四捨五入ができる } public double FrameTo秒( long 時間frame ) { if( this._BaseSampleSource is null ) return 0; return (double)時間frame / this._BaseSampleSource.WaveFormat.SampleRate; } // ローカル private WeakReference<SoundDevice> _DeviceRef; private ISampleSource _BaseSampleSource; private long _Position = 0; private float _Volume = 1.0f; } } <|start_filename|>FDK/入力/GameControllersHID.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using SharpDX.Multimedia; namespace FDK { public class GameControllersHID : IDisposable { // プロパティ /// <summary> /// 発生した入力イベントのリスト。 /// <see cref="ポーリングする()"/> を呼び出す度に更新される。 /// </summary> public List<InputEvent> 入力イベントリスト { get; protected set; } /// <summary> /// HIDデバイスリスト。 /// [key: HIDデバイスハンドル] /// </summary> /// <remarks> /// ゲームコントローラデバイスを Raw Input で取得する場合、実際に WM_INPUT が流れてくるまで /// どんなデバイスが接続されているかを確認しない。(リアルタイムで接続したデバイスも流れてくるので、 /// 最初に列挙しても意味が薄いため。) /// したがって、このデバイスリストも、WM_INPUTで新しいデバイスからの入力が届くたびに増やしていくことにする。 /// </remarks> public Dictionary<IntPtr, GameControllerHIDProperty> Devices { get; protected set; } // 生成と終了 /// <summary> /// コンストラクタ。 /// ゲームコントローラデバイスをRawInputに登録する。 /// </summary> /// <param name="hWindow"> /// 対象とするウィンドウのハンドル。<see cref="IntPtr.Zero"/> にすると、キーボードフォーカスに追従する。 /// </param> public GameControllersHID( IntPtr hWindow, SoundTimer soundTimer ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._SoundTimer = soundTimer; this.入力イベントリスト = new List<InputEvent>(); this.Devices = new Dictionary<IntPtr, GameControllerHIDProperty>(); // 登録したいデバイスの配列(ここでは2個)。 var devs = new RawInput.RawInputDevice[] { new RawInput.RawInputDevice { usUsagePage = UsagePage.Generic, // Genericページの usUsage = UsageId.GenericGamepad, // Genericゲームパッドと、 Flags = RawInput.DeviceFlags.None, hwndTarget = hWindow, }, new RawInput.RawInputDevice { usUsagePage = UsagePage.Generic, // Genericページの usUsage = UsageId.GenericJoystick, // Genericジョイスティック。 Flags = RawInput.DeviceFlags.None, hwndTarget = hWindow, } }; // デバイスを登録。 RawInput.RegisterRawInputDevices( devs, devs.Length, Marshal.SizeOf<RawInput.RawInputDevice>() ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); // デバイスプロパティを解放。 foreach( var kvp in this.Devices ) kvp.Value.Dispose(); this.Devices.Clear(); this._SoundTimer = null!; } // WM_INPUT /// <summary> /// ゲームコントローラHID からの WM_INPUT のコールバック。 /// </summary> /// <remarks> /// UIフォームのウィンドウメッセージループで WM_INPUT を受信した場合は、このコールバックを呼び出すこと。 /// </remarks> public void OnInput( in RawInput.RawInputData rawInputData ) { if( rawInputData.Header.Type != RawInput.DeviceType.HumanInputDevice || rawInputData.Hid is null ) return; // Keyboard, Mouse は無視 GameControllerHIDProperty deviceProperty; #region " デバイスプロパティを取得する。" //---------------- if( this.Devices.ContainsKey( rawInputData.Header.hDevice ) ) { // (A) すでに登録済みならデバイスリストから取得。 deviceProperty = this.Devices[ rawInputData.Header.hDevice ]; } else { // (B) データの発信元デバイスがデバイスリストにないなら、登録する。 string deviceName; #region " デバイス名を取得する。" //---------------- { int nameSize = 0; if( 0 > RawInput.GetRawInputDeviceInfo( rawInputData.Header.hDevice, RawInput.DeviceInfoType.DeviceName, IntPtr.Zero, ref nameSize ) ) { Log.ERROR( $"GetRawInputDeviceInfo(): error = { Marshal.GetLastWin32Error()}" ); return; } IntPtr deviceNamePtr = Marshal.AllocHGlobal( nameSize * sizeof( char ) ); if( 0 > RawInput.GetRawInputDeviceInfo( rawInputData.Header.hDevice, RawInput.DeviceInfoType.DeviceName, deviceNamePtr, ref nameSize ) ) { Marshal.FreeHGlobal( deviceNamePtr ); Log.ERROR( $"GetRawInputDeviceInfo(): error = { Marshal.GetLastWin32Error()}" ); return; } deviceName = Marshal.PtrToStringAuto( deviceNamePtr, nameSize ) ?? "Unknown"; Marshal.FreeHGlobal( deviceNamePtr ); } //---------------- #endregion IntPtr preparseData; #region " デバイスの事前解析データを取得する。" //---------------- { int pcbSize = 0; if( 0 != RawInput.GetRawInputDeviceInfo( rawInputData.Header.hDevice, RawInput.DeviceInfoType.PreparsedData, IntPtr.Zero, ref pcbSize ) ) { Log.ERROR( $"GetRawInputDeviceInfo(): error = { Marshal.GetLastWin32Error()}" ); return; } preparseData = Marshal.AllocHGlobal( pcbSize ); if( pcbSize != RawInput.GetRawInputDeviceInfo( rawInputData.Header.hDevice, RawInput.DeviceInfoType.PreparsedData, preparseData, ref pcbSize ) ) { Marshal.FreeHGlobal( preparseData ); Log.ERROR( $"GetRawInputDeviceInfo(): error = { Marshal.GetLastWin32Error()}" ); return; } } //---------------- #endregion HID.Caps caps; #region " デバイスの CAPS を取得する。" //---------------- { if( HID.Status.Success != HID.HidP_GetCaps( preparseData, out caps ) ) { Marshal.FreeHGlobal( preparseData ); Log.ERROR( $"HidP_GetCaps() error" ); return; } } //---------------- #endregion HID.ButtonCaps[] buttonCaps; bool[][] buttonState; #region " デバイスの ButtonCaps を取得し、ButtonState を作成する。" //---------------- { ushort buttonCapsLength = caps.NumberInputButtonCaps; buttonCaps = new HID.ButtonCaps[ buttonCapsLength ]; if( HID.Status.Success != HID.HidP_GetButtonCaps( HID.ReportType.Input, buttonCaps, ref buttonCapsLength, preparseData ) ) { Marshal.FreeHGlobal( preparseData ); Log.ERROR( $"HidP_GetButtonCaps() error" ); return; } buttonState = new bool[ buttonCaps.Length ][]; for( int b = 0; b < buttonCaps.Length; b++ ) { if( buttonCaps[ b ].IsRange ) { buttonState[ b ] = new bool[ buttonCaps[ b ].Range.UsageMax - buttonCaps[ b ].Range.UsageMin + 1 ]; for( int i = 0; i < buttonState[ b ].Length; i++ ) buttonState[ b ][ i ] = false; } else { buttonState[ b ] = new bool[ 1 ] { false }; } } } //---------------- #endregion HID.ValueCaps[] valueCaps; #region " デバイスの ValueCaps を取得する。" //---------------- { uint valueCapsLength = caps.NumberInputValueCaps; valueCaps = new HID.ValueCaps[ valueCapsLength ]; if( HID.Status.Success != HID.HidP_GetValueCaps( HID.ReportType.Input, valueCaps, ref valueCapsLength, preparseData ) ) { Marshal.FreeHGlobal( preparseData ); Log.ERROR( $"HidP_GetValueCaps() error" ); return; } } //---------------- #endregion HID.LinkCollectionNode[] collectionNodes; #region " デバイスのコレクションノードリストを取得する。" //---------------- { uint collectionNodesLength = caps.NumberLinkCollectionNodes; collectionNodes = new HID.LinkCollectionNode[ collectionNodesLength ]; if( HID.Status.Success != HID.HidP_GetLinkCollectionNodes( collectionNodes, ref collectionNodesLength, preparseData ) ) { Marshal.FreeHGlobal( preparseData ); Log.ERROR( $"HidP_GetCollectionNodes() error" ); return; } } //---------------- #endregion #region " プロパティインスタンスを生成して、デバイスリストに登録する。 " //---------------- deviceProperty = new GameControllerHIDProperty() { DeviceID = this.Devices.Count, // n 番目の DeviceID は n (n = 0...) Name = deviceName, PreparseData = preparseData, Caps = caps, ButtonCaps = buttonCaps, ButtonState = buttonState, ValueCaps = valueCaps, CollectionNodes = collectionNodes, }; this.Devices.Add( rawInputData.Header.hDevice, deviceProperty ); //---------------- #endregion Log.Info( $"新しいゲームコントローラ {deviceProperty.DeviceID} を認識しました。" ); } //---------------- #endregion byte[][] rawHidReports; #region " RawInput データからHIDレポートを取得する。" //---------------- { rawHidReports = new byte[ rawInputData.Hid.Count ][]; // インライン配列からバイト配列を取得。 int dataIndex = 0; for( int c = 0; c < rawInputData.Hid.Count; c++ ) { rawHidReports[ c ] = new byte[ rawInputData.Hid.SizeHid ]; for( int i = 0; i < rawInputData.Hid.SizeHid; i++ ) rawHidReports[ c ][ i ] = rawInputData.Hid.RawData[ dataIndex++ ]; } } //---------------- #endregion // すべての生HIDレポートについて、内容を解析し、入力として処理する。 for( int nReport = 0; nReport < rawHidReports.GetLength( 0 ); nReport++ ) { #region " (1) Button 入力を確認する。" //---------------- for( int nButtonCap = 0; nButtonCap < deviceProperty.Caps.NumberInputButtonCaps; nButtonCap++ ) { var buttonCap = deviceProperty.ButtonCaps[ nButtonCap ]; uint usageLength = HID.HidP_MaxUsageListLength( HID.ReportType.Input, buttonCap.UsagePage, deviceProperty.PreparseData ?? IntPtr.Zero ); var usageList = new ushort[ usageLength ]; var status = HID.HidP_GetButtons( HID.ReportType.Input, buttonCap.UsagePage, buttonCap.LinkCollection, usageList, ref usageLength, deviceProperty.PreparseData ?? IntPtr.Zero, rawHidReports[ nReport ], (uint)rawHidReports[ nReport ].Length ); if( status == HID.Status.Success ) { // current を prev にコピーしつつ current を false で初期化。 var currentButtonState = deviceProperty.ButtonState[ nButtonCap ]; var prevButtonState = new bool[ currentButtonState.Length ]; for( int usageIndex = 0; usageIndex < currentButtonState.Length; usageIndex++ ) { prevButtonState[ usageIndex ] = currentButtonState[ usageIndex ]; currentButtonState[ usageIndex ] = false; } // ON 通知のあった current を true にする。 for( int usageIndex = 0; usageIndex < usageLength; usageIndex++ ) currentButtonState[ usageList[ usageIndex ] - buttonCap.UsageMin ] = true; // prev から current で変化のあった usage に対して InputEvent を作成。 for( int usageIndex = 0; usageIndex < currentButtonState.Length; usageIndex++ ) { if( prevButtonState[ usageIndex ] != currentButtonState[ usageIndex ] ) { ushort usagePage = buttonCap.UsagePage; ushort usage = (ushort)( usageIndex + buttonCap.UsageMin ); var inputEvent = new InputEvent() { DeviceID = deviceProperty.DeviceID, Key = usagePage << 16 | usage, // ExtendUsage = 上位16bit:UsagePage, 下位16bit:Usage 押された = currentButtonState[ usageIndex ], Velocity = 255, // 固定 TimeStamp = this._SoundTimer.現在時刻sec, Extra = $"{buttonCap.UsagePageName} / {HID.GetUsageName( usagePage, usage )}", }; lock( this._一時入力イベントリスト ) { // 一時リストに追加。 this._一時入力イベントリスト.Add( inputEvent ); // キーの状態を更新。 this._現在のキーの押下状態[ inputEvent.Key ] = inputEvent.押された; } } } } } //---------------- #endregion // hack: (2) Value 入力を確認する。--> 現状、軸入力やアナログ入力には未対応。 } } // 入力 public void ポーリングする() { this.入力イベントリスト.Clear(); lock( this._一時入力イベントリスト ) { this.入力イベントリスト = this._一時入力イベントリスト; // 一時リストへの参照を直接渡して、 this._一時入力イベントリスト = new List<InputEvent>(); // 一時リストは新しく確保。 } } /// <summary> /// 最後のポーリングでキーが押されたならtrueを返す。 /// </summary> /// <param name="deviceID"></param> /// <param name="extendedUsage">上位16bit:UsagePage, 下位16bit:Usage</param> public bool キーが押された( int deviceID, int extendedUsage ) => this.キーが押された( deviceID, extendedUsage, out _ ); /// <summary> /// 最後のポーリングでキーが押されたならtrueを返す。 /// </summary> /// <param name="deviceID"></param> /// <param name="extendedUsage">上位16bit:UsagePage, 下位16bit:Usage</param> /// <param name="ev">対応する入力イベント。押されていないなら null 。</param> public bool キーが押された( int deviceID, int extendedUsage, out InputEvent? ev ) { lock( this._一時入力イベントリスト ) ev = this.入力イベントリスト.Find( ( item ) => ( item.Key == extendedUsage && item.押された ) ); return ( null != ev ); } /// <summary> /// 現在キーが押下状態ならtrueを返す。 /// </summary> /// <param name="deviceID"></param> /// <param name="extendedUsage">上位16bit:UsagePage, 下位16bit:Usage</param> public bool キーが押されている( int deviceID, int extendedUsage ) { lock( this._一時入力イベントリスト ) { return ( this._現在のキーの押下状態.TryGetValue( extendedUsage, out bool 押されている ) ) ? 押されている : false; } } /// <summary> /// 最後のポーリングでキーが離されたならtrueを返す。 /// </summary> /// <param name="deviceID"></param> /// <param name="extendedUsage">上位16bit:UsagePage, 下位16bit:Usage</param> public bool キーが離された( int deviceID, int extendedUsage ) => this.キーが離された( deviceID, extendedUsage, out _ ); /// <summary> /// 最後のポーリングでキーが離されたならtrueを返す。 /// </summary> /// <param name="deviceID"></param> /// <param name="extendedUsage">上位16bit:UsagePage, 下位16bit:Usage</param> /// <param name="ev">対応する入力イベント。押されていないなら null 。</param> public bool キーが離された( int deviceID, int extendedUsage, out InputEvent? ev ) { lock( this._一時入力イベントリスト ) { ev = this.入力イベントリスト.Find( ( item ) => ( item.Key == extendedUsage && item.離された ) ); } return ( null != ev ); } /// <summary> /// 現在キーが非押下状態ならtrueを返す。 /// </summary> /// <param name="deviceID"></param> /// <param name="extendedUsage">上位16bit:UsagePage, 下位16bit:Usage</param> public bool キーが離されている( int deviceID, int extendedUsage ) { lock( this._一時入力イベントリスト ) { return ( this._現在のキーの押下状態.TryGetValue( extendedUsage, out bool 押されている ) ) ? !( 押されている ) : true; } } // ローカル /// <summary> /// <see cref="OnInput(in RawInput.RawInputData)"/> で受け取ったイベントを一時的に蓄えておくリスト。 /// </summary> /// <remarks> /// <see cref="ポーリングする()"/> の実行で、内容を <see cref="入力イベントリスト"/> にコピーしたのち、クリアされる。 /// アクセス時には必ずこのインスタンス自身を lock すること。 /// </remarks> private List<InputEvent> _一時入力イベントリスト = new List<InputEvent>(); /// <summary> /// 現在のキーの押下状態。 /// [key: 仮想キーコードをintにしたもの] /// true なら押されている状態、false なら離されている状態。 /// </summary> private readonly Dictionary<int, bool> _現在のキーの押下状態 = new Dictionary<int, bool>(); private SoundTimer _SoundTimer; } } <|start_filename|>DTXMania2/ステージ/アイキャッチ/半回転黒フェード.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { class 半回転黒フェード : アイキャッチ { // 生成と終了 public 半回転黒フェード() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ロゴ画像 = new 画像D2D( @"$(Images)\TitleLogo.png" ); this._黒ブラシ = new SolidColorBrush( Global.GraphicResources.既定のD2D1DeviceContext, Color.Black ); this.現在のフェーズ = フェーズ.未定; } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._黒ブラシ.Dispose(); this._ロゴ画像.Dispose(); this._アニメーション?.Dispose(); base.Dispose(); } // オープンとクローズ /// <summary> /// アイキャッチのクローズアニメーションを開始する。 /// </summary> public override void クローズする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this._アニメーション?.Dispose(); this._アニメーション = new アニメ( animation.Manager ); const double 期間sec = 0.4; #region " (1) 背景マスク のアニメーション構築 " //---------------- this._アニメーション.背景_不透明度 = new Variable( animation.Manager, initialValue: 0.0 ); using( var 不透明度の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: 0.7 ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.背景_不透明度, 不透明度の遷移 ); } //---------------- #endregion #region " (2) 黒幕1(左下) のアニメーション構築 " //---------------- this._アニメーション.黒幕1左下_基点位置X = new Variable( animation.Manager, initialValue: -500.0 ); this._アニメーション.黒幕1左下_回転角rad = new Variable( animation.Manager, initialValue: Math.PI * 0.75 ); using( var 基点位置Xの遷移1 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec * 0.2 ), finalValue: 0.0 ) ) using( var 基点位置Xの遷移2 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec * 0.8 ), finalValue: Global.GraphicResources.設計画面サイズ.Width / 2.0 ) ) using( var 回転角の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: 0.0 ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕1左下_基点位置X, 基点位置Xの遷移1 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕1左下_基点位置X, 基点位置Xの遷移2 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕1左下_回転角rad, 回転角の遷移 ); } //---------------- #endregion #region " (3) 黒幕2(右上) のアニメーション構築 " //---------------- this._アニメーション.黒幕2右上_基点位置X = new Variable( animation.Manager, initialValue: Global.GraphicResources.設計画面サイズ.Width + 500.0 ); this._アニメーション.黒幕2右上_回転角rad = new Variable( animation.Manager, initialValue: Math.PI * 0.75f ); using( var 基点位置Xの遷移1 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec * 0.2 ), finalValue: Global.GraphicResources.設計画面サイズ.Width ) ) using( var 基点位置Xの遷移2 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec * 0.8 ), finalValue: Global.GraphicResources.設計画面サイズ.Width / 2.0 ) ) using( var 回転角の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: 0.0 ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕2右上_基点位置X, 基点位置Xの遷移1 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕2右上_基点位置X, 基点位置Xの遷移2 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕2右上_回転角rad, 回転角の遷移 ); } //---------------- #endregion #region " (4) ロゴ のアニメーション構築 " //---------------- this._アニメーション.ロゴ_位置X = new Variable( animation.Manager, initialValue: 1222.0 - 150.0 ); this._アニメーション.ロゴ_不透明度 = new Variable( animation.Manager, initialValue: 0.0 ); using( var 位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間sec ), finalValue: 1222.0, accelerationRatio: 0.1, decelerationRatio: 0.9 ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: 1.0 ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.ロゴ_位置X, 位置Xの遷移 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.ロゴ_不透明度, 不透明度の遷移 ); } //---------------- #endregion using( var 時間稼ぎ = animation.TrasitionLibrary.Constant( duration: 秒( 0.5 ) ) ) this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.ロゴ_位置X, 時間稼ぎ ); // 今すぐ開始。 this._アニメーション.ストーリーボード.Schedule( animation.Timer.Time ); this.現在のフェーズ = フェーズ.クローズ; } /// <summary> /// アイキャッチのオープンアニメーションを開始する。 /// </summary> public override void オープンする( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this._アニメーション?.Dispose(); this._アニメーション = new アニメ( animation.Manager ); const double 期間sec = 0.6; #region " (1) 背景マスク のアニメーション構築 " //---------------- this._アニメーション.背景_不透明度 = new Variable( animation.Manager, initialValue: 0.0 ); using( var 不透明度の遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 期間sec ) ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.背景_不透明度, 不透明度の遷移 ); } //---------------- #endregion #region " (2) 黒幕1(左下) のアニメーション構築 " //---------------- this._アニメーション.黒幕1左下_基点位置X = new Variable( animation.Manager, initialValue: Global.GraphicResources.設計画面サイズ.Width / 2.0 ); this._アニメーション.黒幕1左下_回転角rad = new Variable( animation.Manager, initialValue: 0.0 ); using( var 基点位置Xの遷移1 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec * 0.8 ), finalValue: 0.0 ) ) using( var 基点位置Xの遷移2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間sec * 0.2 ), finalValue: -500.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 回転角の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: Math.PI * 0.75f ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕1左下_基点位置X, 基点位置Xの遷移1 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕1左下_基点位置X, 基点位置Xの遷移2 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕1左下_回転角rad, 回転角の遷移 ); } //---------------- #endregion #region " (3) 黒幕2(右上) のアニメーション構築 " //---------------- this._アニメーション.黒幕2右上_基点位置X = new Variable( animation.Manager, initialValue: Global.GraphicResources.設計画面サイズ.Width / 2.0 ); this._アニメーション.黒幕2右上_回転角rad = new Variable( animation.Manager, initialValue: 0.0 ); using( var 基点位置Xの遷移1 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec * 0.8 ), finalValue: Global.GraphicResources.設計画面サイズ.Width ) ) using( var 基点位置Xの遷移2 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間sec * 0.2 ), finalValue: Global.GraphicResources.設計画面サイズ.Width + 500.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 回転角の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: Math.PI * 0.75f ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕2右上_基点位置X, 基点位置Xの遷移1 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕2右上_基点位置X, 基点位置Xの遷移2 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.黒幕2右上_回転角rad, 回転角の遷移 ); } //---------------- #endregion #region " (4) ロゴ のアニメーション構築 " //---------------- this._アニメーション.ロゴ_位置X = new Variable( animation.Manager, initialValue: 1222.0 ); this._アニメーション.ロゴ_不透明度 = new Variable( animation.Manager, initialValue: 1.0 ); using( var 位置Xの遷移 = animation.TrasitionLibrary.AccelerateDecelerate( duration: 秒( 期間sec ), finalValue: 1222.0 - 150.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 期間sec ), finalValue: 0.0 ) ) { this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.ロゴ_位置X, 位置Xの遷移 ); this._アニメーション.ストーリーボード.AddTransition( this._アニメーション.ロゴ_不透明度, 不透明度の遷移 ); } //---------------- #endregion // 今すぐ開始。 this._アニメーション.ストーリーボード.Schedule( animation.Timer.Time ); this.現在のフェーズ = フェーズ.オープン; } // 進行と描画 /// <summary> /// アイキャッチのアニメーションを進行し、アイキャッチ画像を描画する。 /// </summary> protected override void 進行描画する( DeviceContext d2ddc, StoryboardStatus 描画しないStatus ) { bool すべて完了 = true; switch( this.現在のフェーズ ) { case フェーズ.クローズ: { if( this._アニメーション.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( this._アニメーション.ストーリーボード.Status != 描画しないStatus ) { var preTrans = d2ddc.Transform; #region " 背景マスク " //---------------- using( var ブラシ = new SolidColorBrush( d2ddc, new Color4( Color3.Black, (float)this._アニメーション.背景_不透明度.Value ) ) ) { d2ddc.FillRectangle( new RectangleF( 0f, 0f, Global.GraphicResources.設計画面サイズ.Width, Global.GraphicResources.設計画面サイズ.Width ), ブラシ ); } //---------------- #endregion #region " (2) 黒幕1(左下)" //---------------- { float w = Global.GraphicResources.設計画面サイズ.Width * 1.5f; float h = Global.GraphicResources.設計画面サイズ.Height; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.Transform = Matrix3x2.Rotation( // 上辺中央を中心として回転 angle: (float)this._アニメーション.黒幕1左下_回転角rad.Value, center: new Vector2( 0f, -rc.Height / 2f ) ) * Matrix3x2.Translation( // (基点X, H×3/4) へ移動 x: (float)this._アニメーション.黒幕1左下_基点位置X.Value, y: Global.GraphicResources.設計画面サイズ.Height ) * preTrans; d2ddc.FillRectangle( rc, this._黒ブラシ ); d2ddc.Transform = preTrans; } //---------------- #endregion #region " (3) 黒幕2(右上)" //---------------- { float w = Global.GraphicResources.設計画面サイズ.Width * 1.5f; float h = Global.GraphicResources.設計画面サイズ.Height; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.Transform = Matrix3x2.Rotation( // 下辺中央を中心として回転 angle: (float)this._アニメーション.黒幕2右上_回転角rad.Value, center: new Vector2( 0f, rc.Height / 2f ) ) * Matrix3x2.Translation( // (基点X, H×1/4) へ移動 x: (float)this._アニメーション.黒幕2右上_基点位置X.Value, y: 0f ) * preTrans; d2ddc.FillRectangle( rc, this._黒ブラシ ); d2ddc.Transform = preTrans; } //---------------- #endregion #region " (4) ロゴ " //---------------- d2ddc.Transform = Matrix3x2.Scaling( 640f / this._ロゴ画像.サイズ.Width, 156f / this._ロゴ画像.サイズ.Height ) * Matrix3x2.Translation( (float)this._アニメーション.ロゴ_位置X.Value, 800f ) * preTrans; d2ddc.DrawBitmap( this._ロゴ画像.Bitmap, (float)this._アニメーション.ロゴ_不透明度.Value, BitmapInterpolationMode.Linear ); d2ddc.Transform = preTrans; //---------------- #endregion } break; } case フェーズ.クローズ完了: { break; } case フェーズ.オープン: { if( this._アニメーション.ストーリーボード.Status != StoryboardStatus.Ready ) すべて完了 = false; if( this._アニメーション.ストーリーボード.Status != 描画しないStatus ) { var preTrans = d2ddc.Transform; #region " (1) 背景マスク " //---------------- using( var ブラシ = new SolidColorBrush( d2ddc, new Color4( Color3.Black, (float)this._アニメーション.背景_不透明度.Value ) ) ) { d2ddc.FillRectangle( new RectangleF( 0f, 0f, Global.GraphicResources.設計画面サイズ.Width, Global.GraphicResources.設計画面サイズ.Width ), ブラシ ); } //---------------- #endregion #region " (2) 黒幕1(左下)" //---------------- { float w = Global.GraphicResources.設計画面サイズ.Width * 1.5f; float h = Global.GraphicResources.設計画面サイズ.Height; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.Transform = Matrix3x2.Rotation( // 上辺中央を中心として回転 angle: (float)this._アニメーション.黒幕1左下_回転角rad.Value, center: new Vector2( 0f, -rc.Height / 2f ) ) * Matrix3x2.Translation( // (基点X, H×3/4) へ移動 x: (float)this._アニメーション.黒幕1左下_基点位置X.Value, y: Global.GraphicResources.設計画面サイズ.Height ) * preTrans; d2ddc.FillRectangle( rc, this._黒ブラシ ); d2ddc.Transform = preTrans; } //---------------- #endregion #region " (3) 黒幕2(右上)" //---------------- { float w = Global.GraphicResources.設計画面サイズ.Width * 1.5f; float h = Global.GraphicResources.設計画面サイズ.Height; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.Transform = Matrix3x2.Rotation( // 下辺中央を中心として回転 angle: (float)this._アニメーション.黒幕2右上_回転角rad.Value, center: new Vector2( 0f, rc.Height / 2f ) ) * Matrix3x2.Translation( // (基点X, H×1/4) へ移動 x: (float)this._アニメーション.黒幕2右上_基点位置X.Value, y: 0f ) * preTrans; d2ddc.FillRectangle( rc, this._黒ブラシ ); d2ddc.Transform = preTrans; } //---------------- #endregion #region " (4) ロゴ " //---------------- d2ddc.Transform = Matrix3x2.Scaling( 640f / this._ロゴ画像.サイズ.Width, 156f / this._ロゴ画像.サイズ.Height ) * Matrix3x2.Translation( (float)this._アニメーション.ロゴ_位置X.Value, 800f ) * preTrans; d2ddc.DrawBitmap( this._ロゴ画像.Bitmap, (float)this._アニメーション.ロゴ_不透明度.Value, BitmapInterpolationMode.Linear ); d2ddc.Transform = preTrans; //---------------- #endregion } break; } case フェーズ.オープン完了: { break; } } if( すべて完了 ) { if( this.現在のフェーズ == フェーズ.クローズ ) { this.現在のフェーズ = フェーズ.クローズ完了; } else if( this.現在のフェーズ == フェーズ.オープン ) { this.現在のフェーズ = フェーズ.オープン完了; } } } // private private class アニメ : IDisposable { public Variable 背景_不透明度 = null!; public Variable 黒幕1左下_基点位置X = null!; public Variable 黒幕1左下_回転角rad = null!; public Variable 黒幕2右上_基点位置X = null!; public Variable 黒幕2右上_回転角rad = null!; public Variable ロゴ_位置X = null!; public Variable ロゴ_不透明度 = null!; public Storyboard ストーリーボード = null!; public アニメ( Manager am ) { this.ストーリーボード = new Storyboard( am ); } public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.背景_不透明度?.Dispose(); this.黒幕1左下_基点位置X?.Dispose(); this.黒幕1左下_回転角rad?.Dispose(); this.黒幕2右上_基点位置X?.Dispose(); this.黒幕2右上_回転角rad?.Dispose(); this.ロゴ_位置X?.Dispose(); this.ロゴ_不透明度?.Dispose(); } } private アニメ _アニメーション = null!; private readonly 画像D2D _ロゴ画像; private readonly SolidColorBrush _黒ブラシ; } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネル/パネル_フォルダ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.オプション設定 { /// <summary> /// 子パネルリストを持つフォルダ。 /// 子パネルリストの活性化・非活性化はこのクラスで行う。 /// </summary> class パネル_フォルダ : パネル { // プロパティ /// <summary> /// null ならルート階層。 /// </summary> public パネル_フォルダ? 親パネル { get; protected set; } = null; public SelectableList<パネル> 子パネルリスト { get => this._子パネルリスト; set { this._子パネルリスト = value; this._子パネルリスト.SelectFirst(); } } // 生成と終了 public パネル_フォルダ( string パネル名, パネル_フォルダ? 親パネル, IEnumerable<パネル>? 初期子パネルリスト = null, Action<パネル>? 値の変更処理 = null ) : base( パネル名, 値の変更処理, ヘッダ色種別.赤 ) { this.親パネル = 親パネル; this.子パネルリスト = new SelectableList<パネル>(); if( null != 初期子パネルリスト ) { foreach( var panel in 初期子パネルリスト ) this.子パネルリスト.Add( panel ); this._子パネルリスト.SelectFirst(); } } public override void Dispose() { base.Dispose(); // 忘れずに } // 進行と描画 public override void 進行描画する( DeviceContext d2ddc, float left, float top, bool 選択中 ) { // パネルの下地と名前を描画。 base.進行描画する( d2ddc, left, top, 選択中 ); // その他の描画があれば、ここに記述する。 } // ローカル protected SelectableList<パネル> _子パネルリスト = null!; } } <|start_filename|>DTXMania2/ステージ/青い線.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2 { /// <summary> /// 枠を形成する青い「線」を一本描画する。 /// </summary> class 青い線 : IDisposable { // プロパティ public float 太さdpx { get; protected set; } = 26f; // 生成と終了 public 青い線() { using var _ = new LogBlock( Log.現在のメソッド名 ); int 青色 = 0x61200a; int 水色 = 0xf95925; int 白色 = 0xffffff; this._線グラ頂点集合 = new GradientStopCollection( Global.GraphicResources.既定のD2D1DeviceContext, new GradientStop[] { new GradientStop() { Position = 0.00f, Color = new Color4( new Color3( 青色 ), 0f ) }, // 完全透明 new GradientStop() { Position = 0.35f, Color = new Color4( new Color3( 水色 ), 1f ) }, new GradientStop() { Position = 0.42f, Color = new Color4( new Color3( 青色 ), 0.7f ) }, new GradientStop() { Position = 0.48f, Color = new Color4( new Color3( 白色 ), 1f ) }, new GradientStop() { Position = 0.52f, Color = new Color4( new Color3( 白色 ), 1f ) }, new GradientStop() { Position = 0.58f, Color = new Color4( new Color3( 青色 ), 0.7f ) }, new GradientStop() { Position = 0.65f, Color = new Color4( new Color3( 水色 ), 1f ) }, new GradientStop() { Position = 1.00f, Color = new Color4( new Color3( 青色 ), 0f ) }, // 完全透明 } ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._線グラブラシ?.Dispose(); this._線グラ頂点集合.Dispose(); } // 進行と描画 /// <summary> /// よこ線(左→右)か、たて線(上→下)のいずれかを描画できる。 /// よこ線を描画したい場合は<paramref name="幅dpx"/>を指定し、 /// たて線を描画したい場合は<paramref name="高さdpx"/>を指定する。 /// <paramref name="幅dpx"/> と <paramref name="高さdpx"/> を同時に指定することはできない。 /// </summary> /// <param name="幅dpx">横方向(左→右)の長さ。<paramref name="高さdpx"/>と同時に指定してはならない。</param> /// <param name="高さdpx">縦方向(上→下)の長さ。<paramref name="幅dpx"/>と同時に指定してはならない。</param> public void 描画する( DeviceContext d2ddc, Vector2 開始位置dpx, float 幅dpx = -1f, float 高さdpx = -1f ) { var check = ( 幅dpx * 高さdpx ); Debug.Assert( 0f >= check, "幅か高さが両方指定されていないか、両方指定されています。どちらか一方だけを指定してください。" ); if( 0f == check ) return; // 面積ゼロ var preBlend = d2ddc.PrimitiveBlend; d2ddc.PrimitiveBlend = PrimitiveBlend.Add; // 加算合成 if( 0f < 幅dpx ) { // (A) 横方向(左→右)の枠 var 矩形 = new RectangleF( x: 開始位置dpx.X, y: 開始位置dpx.Y - this.太さdpx / 2f, width: 幅dpx, height: this.太さdpx ); this._線グラブラシ?.Dispose(); this._線グラブラシ = new LinearGradientBrush( d2ddc, new LinearGradientBrushProperties() { StartPoint = new Vector2( 矩形.Left, 矩形.Top ), EndPoint = new Vector2( 矩形.Left, 矩形.Bottom ), }, this._線グラ頂点集合 ); d2ddc.FillRectangle( 矩形, this._線グラブラシ ); } else { // (B) 縦方向(上→下)の枠 var 矩形 = new RectangleF( x: 開始位置dpx.X - this.太さdpx / 2f, y: 開始位置dpx.Y, width: this.太さdpx, height: 高さdpx ); this._線グラブラシ?.Dispose(); this._線グラブラシ = new LinearGradientBrush( d2ddc, new LinearGradientBrushProperties() { StartPoint = new Vector2( 矩形.Left, 矩形.Top ), EndPoint = new Vector2( 矩形.Right, 矩形.Top ), }, this._線グラ頂点集合 ); d2ddc.FillRectangle( 矩形, this._線グラブラシ ); } d2ddc.PrimitiveBlend = preBlend; } // ローカル private LinearGradientBrush? _線グラブラシ = null; private readonly GradientStopCollection _線グラ頂点集合; } } <|start_filename|>DTXMania2/ドラム入力/ドラム入力.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2 { class ドラム入力 : IDisposable { // プロパティ /// <summary> /// 全デバイスの入力イベントをドラム入力イベントに変換し、それを集めたリスト。 /// </summary> /// <remarks> /// <see cref="すべての入力デバイスをポーリングする(bool)"/> の呼び出し時にクリアされ、 /// その時点における、前回のポーリング以降の入力イベントで再構築される。 /// ただし、キーバインディングにキーとして登録されていない入力イベントは含まれない。 /// </remarks> public List<ドラム入力イベント> ポーリング結果 { get; } public KeyboardHID Keyboard { get; } public GameControllersHID GameControllers { get; } public MidiIns MidiIns { get; } // 生成と終了 /// <summary> /// 各入力デバイスを初期化する。 /// このコンストラクタは、GUI スレッドから呼び出すこと。 /// </summary> /// <param name="hWindow">ウィンドウハンドル。</param> /// <param name="soundTimer">サウンドタイマ。入力値のタイムスタンプの取得に使用される。</param> /// <param name="最大入力履歴数">入力履歴を使用する場合、その履歴の最大記憶数。</param> public ドラム入力( IntPtr hWindow, SoundTimer soundTimer, int 最大入力履歴数 = 32 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this.ポーリング結果 = new List<ドラム入力イベント>(); this.Keyboard = new KeyboardHID( soundTimer ); this.GameControllers = new GameControllersHID( hWindow, soundTimer ); this.MidiIns = new MidiIns( soundTimer ); this._最大入力履歴数 = 最大入力履歴数; this._入力履歴 = new List<ドラム入力イベント>( this._最大入力履歴数 ); #region " MIDI入力デバイスの可変IDへの対応を行う。" //---------------- if( 0 < this.MidiIns.DeviceName.Count ) { var config = Global.App.システム設定; var デバイスリスト = new Dictionary<int, string>(); // <デバイスID, デバイス名> #region " (1) 先に列挙された実際のデバイスに合わせて、デバイスリスト(配列番号がデバイス番号)を作成する。" //---------------- for( int i = 0; i < this.MidiIns.DeviceName.Count; i++ ) デバイスリスト.Add( i, this.MidiIns.DeviceName[ i ] ); //---------------- #endregion #region " (2) キーバインディングのデバイスリストとマージして、新しいデバイスリストを作成する。" //---------------- foreach( var kvp in config.MIDIデバイス番号toデバイス名 ) { var キーバインディング側のデバイス名 = kvp.Value; if( デバイスリスト.ContainsValue( キーバインディング側のデバイス名 ) ) { // (A) 今回も存在しているデバイスなら、何もしない。 } else { // (B) 今回は存在していないデバイスなら、末尾(=未使用ID)に登録する。 デバイスリスト.Add( デバイスリスト.Count, キーバインディング側のデバイス名 ); } } //---------------- #endregion #region " (3) キーバインディングのデバイスから新しいデバイスへ、キーのIDを付け直す。" //---------------- var 中間バッファ = new Dictionary<SystemConfig.IdKey, ドラム入力種別>(); foreach( var kvp in config.MIDItoドラム ) { var キーのデバイスID = kvp.Key.deviceId; // キーバインディングのデバイス番号 から、デバイスリストのデバイス番号 へ付け替える。 if( config.MIDIデバイス番号toデバイス名.TryGetValue( キーのデバイスID, out string? キーのデバイス名 ) ) { キーのデバイスID = デバイスリスト.First( ( kvp2 ) => ( kvp2.Value == キーのデバイス名 ) ).Key; // マージしたので、必ず存在する。 } 中間バッファ.Add( new SystemConfig.IdKey( キーのデバイスID, kvp.Key.key ), kvp.Value ); // デバイスID以外は変更なし。 } config.MIDItoドラム.Clear(); for( int i = 0; i < 中間バッファ.Count; i++ ) { var kvp = 中間バッファ.ElementAt( i ); config.MIDItoドラム.Add( new SystemConfig.IdKey( kvp.Key.deviceId, kvp.Key.key ), kvp.Value ); } //---------------- #endregion #region " (4) 新しいデバイスリストをキーバインディングに格納して、保存する。" //---------------- config.MIDIデバイス番号toデバイス名.Clear(); for( int i = 0; i < デバイスリスト.Count; i++ ) config.MIDIデバイス番号toデバイス名.Add( i, デバイスリスト[ i ] ); config.保存する(); //---------------- #endregion } else { // 列挙されたMIDI入力デバイスがまったくないなら、キーバインディングは何もいじらない。 } //---------------- #endregion } public virtual void Dispose() { this.MidiIns.Dispose(); this.GameControllers.Dispose(); this.Keyboard.Dispose(); } // WM_INPUT 処理 public void OnInput( RawInput.RawInputData rawInputData ) { this.Keyboard.OnInput( rawInputData ); this.GameControllers.OnInput( rawInputData ); } // 押下チェック /// <summary> /// 現在の<see cref="ポーリング結果"/>に、指定したドラム入力イベントが含まれているかを確認する。 /// </summary> /// <param name="イベント">調べるドラム入力イベント。</param> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool ドラムが入力された( ドラム入力種別 drumType ) { if( 0 == this.ポーリング結果.Count ) // 0 であることが大半だと思われるので、特別扱い。 { return false; } else { return ( 0 <= this.ポーリング結果.FindIndex( ( ev ) => ( ev.Type == drumType && ev.InputEvent.押された ) ) ); } } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、指定したドラム入力イベント集合のいずれか1つ以上が含まれているかを確認する。 /// </summary> /// <param name="drumTypes">調べるドラム入力イベントの集合。</param> /// <returns><see cref="ポーリング結果"/>に、指定したドラム入力イベントのいずれか1つ以上が含まれていれば true。</returns> public bool ドラムのいずれか1つが入力された( IEnumerable<ドラム入力種別> drumTypes ) { if( 0 == this.ポーリング結果.Count ) // 0 であることが大半だと思われるので、特別扱い。 { return false; } else { return ( 0 <= this.ポーリング結果.FindIndex( ( ev ) => ( ev.InputEvent.押された && drumTypes.Contains( ev.Type ) ) ) ); } } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、決定キーとみなせるドラム入力イベントが含まれているかを確認する。 /// </summary> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool 確定キーが入力された() { return this.ドラムのいずれか1つが入力された( this._確定ドラム入力リスト) ;// || this.Keyboard.キーが押された( 0, Key.Return ); Enter は、既定で LeftCrash に割り当てられている前提。 } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、キャンセルキーとみなせるドラム入力イベントが含まれているかを確認する。 /// </summary> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool キャンセルキーが入力された() { return this.Keyboard.キーが押された( 0, System.Windows.Forms.Keys.Escape ); } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、上移動キーとみなせるドラム入力イベントが含まれているかを確認する。 /// </summary> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool 上移動キーが入力された() { return this.Keyboard.キーが押された( 0, System.Windows.Forms.Keys.Up ) || this.ドラムのいずれか1つが入力された( this._上移動ドラム入力リスト ); } public bool 上移動キーが押されている() { return this.Keyboard.キーが押されている( 0, System.Windows.Forms.Keys.Up ); } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、下移動キーとみなせるドラム入力イベントが含まれているかを確認する。 /// </summary> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool 下移動キーが入力された() { return this.Keyboard.キーが押された( 0, System.Windows.Forms.Keys.Down ) || this.ドラムのいずれか1つが入力された( this._下移動ドラム入力リスト ); } public bool 下移動キーが押されている() { return this.Keyboard.キーが押されている( 0, System.Windows.Forms.Keys.Down ); } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、左移動キーとみなせるドラム入力イベントが含まれているかを確認する。 /// </summary> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool 左移動キーが入力された() { return this.Keyboard.キーが押された( 0, System.Windows.Forms.Keys.Left ) || this.ドラムのいずれか1つが入力された( this._左移動ドラム入力リスト ); } public bool 左移動キーが押されている() { return this.Keyboard.キーが押されている( 0, System.Windows.Forms.Keys.Left ); } /// <summary> /// 現在の<see cref="ポーリング結果"/>に、右移動キーとみなせるドラム入力イベントが含まれているかを確認する。 /// </summary> /// <returns><see cref="ポーリング結果"/>に含まれていれば true。</returns> public bool 右移動キーが入力された() { return this.Keyboard.キーが押された( 0, System.Windows.Forms.Keys.Right ) || this.ドラムのいずれか1つが入力された( this._右移動ドラム入力リスト ); } public bool 右移動キーが押されている() { return this.Keyboard.キーが押されている( 0, System.Windows.Forms.Keys.Right ); } /// <summary> /// 現在の履歴において、指定したシーケンスが成立しているかを確認する。 /// </summary> /// <param name="シーケンス"> 確認したいシーケンス。</param> /// <returns>シーケンスが成立しているなら true。</returns> /// <remarks> /// 指定したシーケンスが現在の履歴の一部に見られれば、成立しているとみなす。 /// 履歴内に複数存在している場合は、一番 古 い シーケンスが対象となる。 /// 成立した場合、そのシーケンスと、それより古い履歴はすべて削除される。 /// </remarks> public bool シーケンスが入力された( IEnumerable<ドラム入力イベント> シーケンス ) { int シーケンスのストローク数 = シーケンス.Count(); // ストローク = ドラム入力イベント(シーケンスの構成単位) if( 0 == シーケンスのストローク数 ) return false; // 空シーケンスは常に不成立。 if( this._入力履歴.Count < シーケンスのストローク数 ) return false; // 履歴数が足りない。 int 履歴の検索開始位置 = this._入力履歴.IndexOf( シーケンス.ElementAt( 0 ) ); if( -1 == 履歴の検索開始位置 ) return false; // 最初のストロークが見つからない。 if( ( this._入力履歴.Count - 履歴の検索開始位置 ) < シーケンスのストローク数 ) return false; // 履歴数が足りない。 // 検索開始位置から末尾へ、すべてのストロークが一致するか確認する。 for( int i = 1; i < シーケンスのストローク数; i++ ) { if( this._入力履歴[ 履歴の検索開始位置 + i ] != シーケンス.ElementAt( i ) ) return false; // 一致しなかった。 } // 見つけたシーケンスならびにそれより古い履歴を削除する。 this._入力履歴.RemoveRange( 0, 履歴の検索開始位置 + シーケンスのストローク数 ); return true; } /// <summary> /// 現在の履歴において、指定したシーケンスが成立しているかを確認する。 /// </summary> /// <param name="シーケンス">確認したいシーケンス。</param> /// <returns>シーケンスが成立しているなら true。</returns> /// <remarks> /// 指定したシーケンスが現在の履歴の一部に見られれば、成立しているとみなす。 /// 履歴内に複数存在している場合は、一番 古 い シーケンスが対象となる。 /// 成立した場合、そのシーケンスと、それより古い履歴はすべて削除される。 /// </remarks> public bool シーケンスが入力された( IEnumerable<ドラム入力種別> シーケンス ) { // ストロークはシーケンスの構成単位。ここでは「指定されたドラム入力種別に対応するドラム入力イベント」と同義である。 // ドラム入力種別 と ドラム入力イベント は、1 対 N の関係である。 static bool 適合する( ドラム入力種別 drumType, ドラム入力イベント drumEvent ) => ( drumEvent.Type == drumType && drumEvent.InputEvent.押された ); int シーケンスのストローク数 = シーケンス.Count(); if( 0 == シーケンスのストローク数 ) return false; // 空シーケンスは常に不成立。 if( this._入力履歴.Count < シーケンスのストローク数 ) return false; // 履歴数が足りない。 // 検索を開始する位置を特定する。 int 履歴の検索開始位置 = this._入力履歴.FindIndex( ( e ) => 適合する( シーケンス.ElementAt( 0 ), e ) ); if( -1 == 履歴の検索開始位置 ) return false; // 最初のストロークが見つからない。 if( シーケンスのストローク数 > ( this._入力履歴.Count - 履歴の検索開始位置 ) ) return false; // 履歴数が足りない。 // 検索開始位置から末尾へ向かって、すべてのストロークが一致するか確認する。 for( int i = 1; i < シーケンスのストローク数; i++ ) { if( !( 適合する( シーケンス.ElementAt( i ), this._入力履歴[ 履歴の検索開始位置 + i ] ) ) ) return false; // 一致しなかった。 } // すべて一致したので、そのシーケンスならびにそれより古い履歴を削除する。 this._入力履歴.RemoveRange( 0, 履歴の検索開始位置 + シーケンスのストローク数 ); return true; } /// <summary> /// 現在の履歴において、指定したシーケンスが成立しているかを確認する。 /// </summary> /// <param name="シーケンス">確認したいシーケンス。</param> /// <returns>シーケンスが成立しているなら true。</returns> /// <remarks> /// 指定したシーケンスが現在の履歴の一部に見られれば、成立しているとみなす。 /// 履歴内に複数存在している場合は、一番 古 い シーケンスが対象となる。 /// 成立した場合、そのシーケンスと、それより古い履歴はすべて削除される。 /// </remarks> public bool シーケンスが入力された( IEnumerable<SSTF.レーン種別> シーケンス, 演奏.ドラムチッププロパティリスト ドラムチッププロパティリスト ) { // ストロークはシーケンスの構成単位。ここでは、「指定されたレーン種別に対応するドラム入力種別に対応するドラム入力イベント」と同義。 // レーン種別 と ドラム入力種別 と ドラム入力イベント は、N 対 M 対 P の関係である。 bool 適合する( SSTF.レーン種別 laneType, ドラム入力イベント drumEvent ) => ( 0 < ドラムチッププロパティリスト.チップtoプロパティ.Count( ( kvp ) => ( kvp.Value.レーン種別 == laneType ) && ( kvp.Value.ドラム入力種別 == drumEvent.Type ) && ( drumEvent.InputEvent.押された ) ) ); int シーケンスのストローク数 = シーケンス.Count(); if( 0 == シーケンスのストローク数 ) return false; // 空シーケンスは常に不成立。 if( this._入力履歴.Count < シーケンスのストローク数 ) return false; // 履歴数が足りない。 // 検索を開始する位置を特定する。 int 履歴の検索開始位置 = this._入力履歴.FindIndex( ( e ) => 適合する( シーケンス.ElementAt( 0 ), e ) ); if( -1 == 履歴の検索開始位置 ) return false; // 最初のストロークが見つからない。 if( シーケンスのストローク数 > ( this._入力履歴.Count - 履歴の検索開始位置 ) ) return false; // 履歴数が足りない。 // 検索開始位置から末尾へ向かって、すべてのストロークが一致するか確認する。 for( int i = 1; i < シーケンスのストローク数; i++ ) { if( !( 適合する( シーケンス.ElementAt( i ), this._入力履歴[ 履歴の検索開始位置 + i ] ) ) ) return false; // 一致しなかった。 } // すべて一致したので、そのシーケンスならびにそれより古い履歴を削除する。 this._入力履歴.RemoveRange( 0, 履歴の検索開始位置 + シーケンスのストローク数 ); return true; } // ポーリング /// <summary> /// すべての入力デバイスをポーリングし、<see cref="ポーリング結果"/>のクリア&再構築と、入力履歴の更新を行う。 /// </summary> /// <param name="入力履歴を記録する">履歴に残す必要がないとき(演奏時の入力イベントなど)には false を指定する。</param> public void すべての入力デバイスをポーリングする( bool 入力履歴を記録する = true ) { // 入力履歴が OFF から ON に変わった場合には、入力履歴を全クリアする。 if( 入力履歴を記録する && this._入力履歴の記録を中断している ) { this._入力履歴.Clear(); this._前回の入力履歴の追加時刻sec = null; } this._入力履歴を記録中である = 入力履歴を記録する; // 全デバイスをポーリングする。 this.ポーリング結果.Clear(); var config = Global.App.システム設定; { this.Keyboard.ポーリングする(); this._入力イベントを取得する( this.Keyboard.入力イベントリスト, config.キーボードtoドラム, 入力履歴を記録する ); this.GameControllers.ポーリングする(); this._入力イベントを取得する( this.GameControllers.入力イベントリスト, config.ゲームコントローラtoドラム, 入力履歴を記録する ); this.MidiIns.ポーリングする(); this._入力イベントを取得する( this.MidiIns.入力イベントリスト, config.MIDItoドラム, 入力履歴を記録する ); } // タイムスタンプの小さい順にソートする。 this.ポーリング結果.Sort( ( x, y ) => (int)( x.InputEvent.TimeStamp - y.InputEvent.TimeStamp ) ); } /// <summary> /// これまでにポーリングで取得された入力の履歴。 /// </summary> /// <remarks> /// キーバインディングに従ってマッピングされた後の、ドラム入力イベントを対象とする。 /// リストのサイズには制限があり(<see cref="_最大入力履歴数"/>)、それを超える場合は、ポーリング時に古いイベントから削除されていく。 /// </remarks> private readonly List<ドラム入力イベント> _入力履歴; private int _最大入力履歴数 = 32; private bool _入力履歴を記録中である = true; private bool _入力履歴の記録を中断している { get => !this._入力履歴を記録中である; set => this._入力履歴を記録中である = !value; } /// <summary> /// null なら、入力履歴に追加された入力がまだないことを示す。 /// </summary> private double? _前回の入力履歴の追加時刻sec = null; // ローカル private const double _連続入力だとみなす最大の間隔sec = 0.5; private readonly ドラム入力種別[] _確定ドラム入力リスト = new[] { ドラム入力種別.LeftCrash, ドラム入力種別.RightCrash, ドラム入力種別.China, ドラム入力種別.Ride, ドラム入力種別.Splash, }; private readonly ドラム入力種別[] _上移動ドラム入力リスト = new[] { ドラム入力種別.Tom1, ドラム入力種別.Tom1_Rim, }; private readonly ドラム入力種別[] _下移動ドラム入力リスト = new[] { ドラム入力種別.Tom2, ドラム入力種別.Tom2_Rim, }; private readonly ドラム入力種別[] _左移動ドラム入力リスト = new[] { ドラム入力種別.Snare, ドラム入力種別.Snare_ClosedRim, ドラム入力種別.Snare_OpenRim, }; private readonly ドラム入力種別[] _右移動ドラム入力リスト = new[] { ドラム入力種別.Tom3, ドラム入力種別.Tom3_Rim, }; /// <summary> /// 単一の IInputDevice をポーリングし、対応表に従ってドラム入力へ変換して、ポーリング結果 に追加登録する。 /// </summary> private void _入力イベントを取得する( IReadOnlyList<InputEvent> 入力イベントリスト, IReadOnlyDictionary<SystemConfig.IdKey, ドラム入力種別> デバイスtoドラム対応表, bool 入力履歴を記録する ) { // ポーリングされた入力イベントのうち、キーバインディングに登録されているイベントだけを ポーリング結果 に追加する。 foreach( var ev in 入力イベントリスト ) { // キーバインディングを使って、入力イベント ev をドラム入力 evKey にマッピングする。 var evKey = new SystemConfig.IdKey( ev ); if( false == デバイスtoドラム対応表.ContainsKey( evKey ) ) continue; // 使われないならスキップ。 var drumType = デバイスtoドラム対応表[ evKey ]; // HHの場合、Velocityが最小値未満の場合は無視する。 if( drumType == ドラム入力種別.HiHat_Close || drumType == ドラム入力種別.HiHat_Open || drumType == ドラム入力種別.HiHat_Foot ) { if( ev.Velocity < Global.App.システム設定.HHVolocity最小値 ) continue; } // ドラム入力を、ポーリング結果に追加登録する。 var ドラム入力 = new ドラム入力イベント( ev, デバイスtoドラム対応表[ evKey ] ); this.ポーリング結果.Add( ドラム入力 ); #region " ドラム入力を入力履歴に追加登録する。 " //---------------- if( 入力履歴を記録する && ev.押された && // 押下入力だけを記録する。 ドラム入力.InputEvent.Control == 0 ) // コントロールチェンジは入力履歴の対象外とする。 { double 入力時刻sec = ev.TimeStamp; // 容量がいっぱいなら、古い履歴から削除する。 if( this._入力履歴.Count >= this._最大入力履歴数 ) this._入力履歴.RemoveRange( 0, ( this._入力履歴.Count - this._最大入力履歴数 + 1 ) ); // 前回の追加登録時刻からの経過時間がオーバーしているなら、履歴をすべて破棄する。 if( null != this._前回の入力履歴の追加時刻sec ) { var 前回の登録からの経過時間sec = 入力時刻sec - this._前回の入力履歴の追加時刻sec; if( _連続入力だとみなす最大の間隔sec < 前回の登録からの経過時間sec ) this._入力履歴.Clear(); } // 今回の入力を履歴に登録する。 this._入力履歴.Add( ドラム入力 ); this._前回の入力履歴の追加時刻sec = 入力時刻sec; } //---------------- #endregion } } } } <|start_filename|>DTXMania2/サウンド/消音グループ種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace DTXMania2 { /// <summary> /// 同じ消音グループ種別に属する場合、再生前消音の対象となる。 /// </summary> enum 消音グループ種別 { Unknown, LeftCymbal, RightCymbal, HiHat, Guitar, Bass, SE1, SE2, SE3, SE4, SE5, SE6, SE7, SE8, SE9, SE10, SE11, SE12, SE13, SE14, SE15, SE16, SE17, SE18, SE19, SE20, SE21, SE22, SE23, SE24, SE25, SE26, SE27, SE28, SE29, SE30, SE31, SE32, } } <|start_filename|>SSTFormat/v004/スコア.SSTF.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace SSTFormat.v004 { public partial class スコア { /// <summary> /// SSTFフォーマットのファイルまたはテキストから <see cref="スコア"/> インスタンスを生成するためのクラス。 /// </summary> /// <remarks> /// テストプロジェクトに対しては InternalsVisibleTo 属性(AssemblyInfo.cs参照))により internal メソッドを可視としているため、 /// テスト対象のメソッドは、本来 private でも internal として宣言している。 /// </remarks> public static class SSTF { /// <summary> /// ファイルからSSTFデータを読み込み、スコアを生成して返す。 /// 読み込みに失敗した場合は、何らかの例外を発出する。 /// </summary> public static スコア ファイルから生成する( string SSTFファイルの絶対パス, bool ヘッダだけ = false ) { // ファイルのSSTFバージョンを確認。 string 先頭行; using( var sr = new StreamReader( SSTFファイルの絶対パス, Encoding.UTF8 ) ) // SSTF は UTF-8 先頭行 = sr.ReadLine(); var SSTFバージョン = _行にSSTFVersionがあるなら解析して返す( 先頭行 ) ?? new Version( 1, 0, 0, 0 ); // 既定値 // ファイルのSSTFバージョンに応じた方法でスコアを生成する。 スコア score = null; // ファイルの内容を一気読み。 string 全入力文字列 = null; using( var sr = new StreamReader( SSTFファイルの絶対パス ) ) 全入力文字列 = sr.ReadToEnd(); // 読み込んだ内容でスコアを生成する。 score = _全行解析する( ref 全入力文字列, ヘッダだけ ); // ファイルから読み込んだ場合のみ、このメンバが有効。 score.譜面ファイルの絶対パス = SSTFファイルの絶対パス; // 後処理。 if( !( ヘッダだけ ) ) { スコア._スコア読み込み時の後処理を行う( score ); } return score; } /// <summary> /// SSTFフォーマットのテキストデータを含んだ1つの文字列から、スコアを生成して返す。 /// 読み込みに失敗した場合は、何らかの例外を発出する。 /// </summary> public static スコア 文字列から生成する( string 全入力文字列, bool ヘッダだけ = false ) { // データのSSTFバージョンを確認。 string 先頭行; using( var sr = new StringReader( 全入力文字列 ) ) 先頭行 = sr.ReadLine(); var SSTFバージョン = _行にSSTFVersionがあるなら解析して返す( 先頭行 ) ?? new Version( 1, 0, 0, 0 ); // 既定値 // データのSSTFバージョンに応じた方法でスコアを生成する。 スコア score = null; score = _全行解析する( ref 全入力文字列, ヘッダだけ ); score.譜面ファイルの絶対パス = null; // ファイルから読み込んだ場合のみ、このメンバが有効。 if( !( ヘッダだけ ) ) { スコア._スコア読み込み時の後処理を行う( score ); } return score; } /// <summary> /// 現在の スコア の内容をデータファイル(*.sstf)に書き出す。 /// 小節線、拍線、Unknown チップは出力しない。 /// 失敗時は何らかの例外を発出する。 /// </summary> public static void 出力する( スコア score, Stream 出力先, string 追加ヘッダ文 = null ) { using var sw = new StreamWriter( 出力先, Encoding.UTF8 ); // SSTFバージョンの出力 sw.WriteLine( $"# SSTFVersion {SSTFVERSION}" ); // 追加ヘッダの出力(あれば) if( !( string.IsNullOrEmpty( 追加ヘッダ文 ) ) ) { sw.WriteLine( $"{追加ヘッダ文}" ); // ヘッダ文に "{...}" が入ってても大丈夫なように、$"{...}" で囲む。 sw.WriteLine( "" ); } _ヘッダ行を出力する( score, sw ); _チップ記述行を出力する( score, sw ); _小節メモ行を出力する( score, sw ); sw.Close(); } // 行解析 #region " 解析に使う状態変数。(static) " //---------------- private static class 現在の { public static スコア スコア; public static int 行番号; public static int 小節番号; public static int 小節解像度; public static チップ種別 チップ種別; public static bool 可視; public static void 状態をリセットする() { スコア = null; 行番号 = 0; 小節番号 = 0; 小節解像度 = 384; チップ種別 = チップ種別.Unknown; 可視 = true; } } //---------------- #endregion internal static スコア _全行解析する( ref string 全入力文字列, bool ヘッダだけ = false ) { 現在の.状態をリセットする(); 現在の.スコア = new スコア(); using( var sr = new StringReader( 全入力文字列 ) ) { // すべての行について…… string 行; while( ( 行 = sr.ReadLine() ) != null ) // EOF なら null { 現在の.行番号++; // 行の前処理 #region " 改行とTABを空白文字に変換し、先頭末尾の空白を削除する。" //---------------- 行 = 行.Replace( Environment.NewLine, " " ); 行 = 行.Replace( '\t', ' ' ); 行 = 行.Trim(); //---------------- #endregion #region " 行中の '#' 以降はコメントとして除外する。" //---------------- { int 区切り位置 = 行.IndexOf( '#' ); if( 0 <= 区切り位置 ) { 行 = 行[ ..区切り位置 ]; 行 = 行.Trim(); } } //---------------- #endregion if( string.IsNullOrEmpty( 行 ) ) continue; // 空行 // 行の解析 if( _行をヘッダ行と想定して解析する( ref 行 ) ) continue; if( !( ヘッダだけ ) ) { if( _行を小節メモ行として解析する( ref 行 ) ) continue; if( _行をチップ記述行として解析する( ref 行 ) ) continue; } } } if( !( ヘッダだけ ) ) { #region " 拍線を追加する。" //----------------- // 小節線を先に追加すると小節が1つ増えてしまうので、拍線から先に追加する。 int 最大小節番号 = 現在の.スコア.最大小節番号を返す(); // 最大小節番号はチップ数に依存して変化するので、次の for 文には組み込まないこと。 for( int i = 0; i <= 最大小節番号; i++ ) { double 小節長倍率 = 現在の.スコア.小節長倍率を取得する( i ); for( int n = 1; n * 0.25 < 小節長倍率; n++ ) { 現在の.スコア.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.拍線, 小節内位置 = (int) ( ( n * 0.25 ) * 100 ), 小節解像度 = (int) ( 小節長倍率 * 100 ), } ); } } //----------------- #endregion #region " 小節線を追加する。" //----------------- 最大小節番号 = 現在の.スコア.最大小節番号を返す(); for( int i = 0; i <= 最大小節番号 + 1; i++ ) { 現在の.スコア.チップリスト.Add( new チップ() { 小節番号 = i, チップ種別 = チップ種別.小節線, 小節内位置 = 0, 小節解像度 = 1, } ); } //----------------- #endregion } var score = 現在の.スコア; 現在の.状態をリセットする(); return score; } /// <returns> /// 行をヘッダとして処理したなら true 、該当しないまたはエラーが発生したときは false を返す。 /// </returns> private static bool _行をヘッダ行と想定して解析する( ref string 行 ) { #region " Title " //----------------- if( 行.StartsWith( "title", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Title の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.曲名 = items[ 1 ].Trim(); return true; } //----------------- #endregion #region " Artist " //---------------- if( 行.StartsWith( "artist", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Artist の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.アーティスト名 = items[ 1 ].Trim(); return true; } //---------------- #endregion #region " Description " //----------------- if( 行.StartsWith( "description", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Description の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } // 2文字のリテラル "\n" は改行に復号。 現在の.スコア.説明文 = items[ 1 ].Trim().Replace( @"\n", Environment.NewLine ); return true; } //----------------- #endregion #region " SoundDevice.Delay " //----------------- if( 行.StartsWith( "sounddevice.delay", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"SoundDevice.Delay の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } // 2文字のリテラル "\n" は改行に復号。 if( float.TryParse( items[ 1 ].Trim().Replace( @"\n", Environment.NewLine ), out float value ) ) 現在の.スコア.サウンドデバイス遅延ms = value; return true; } //----------------- #endregion #region " Level " //---------------- if( 行.StartsWith( "level", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Level の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } if( double.TryParse( items[ 1 ].Trim(), out double level ) ) { 現在の.スコア.難易度 = Math.Clamp( level, min: 0.00, max: 9.99 ); return true; } else { Trace.TraceError( $"Level の右辺が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } } //---------------- #endregion #region " BGV " //---------------- if( 行.StartsWith( "BGV", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"BGV の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.BGVファイル名 = items[ 1 ].Trim(); 現在の.スコア.AVIリスト[ 1 ] = 現在の.スコア.BGVファイル名; // #AVI01 固定。あれば上書き、なければ追加 return true; } //---------------- #endregion #region " BGM " //---------------- if( 行.StartsWith( "BGM", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"BGM の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.BGMファイル名 = items[ 1 ].Trim(); 現在の.スコア.WAVリスト[ 1 ] = new WAV情報 { // #WAV01 固定。あれば上書き、なければ追加 ファイルパス = 現在の.スコア.BGMファイル名, 多重再生する = false, BGMである = true, }; return true; } //---------------- #endregion #region " Preview.Sound " //---------------- if( 行.StartsWith( "preview.sound", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Preview.Sound の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.プレビュー音声ファイル名 = items[ 1 ].Trim(); return true; } //---------------- #endregion #region " Preview.Image " //---------------- if( 行.StartsWith( "preview.image", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Preview.Image の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.プレビュー画像ファイル名 = items[ 1 ].Trim(); return true; } //---------------- #endregion #region " Preview.Movie " //---------------- if( 行.StartsWith( "preview.movie", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"Preview.Movie の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } 現在の.スコア.プレビュー動画ファイル名 = items[ 1 ].Trim(); return true; } //---------------- #endregion #region " ViewerPlaySpeed " //---------------- if( 行.StartsWith( "viewerplayspeed", StringComparison.OrdinalIgnoreCase ) ) { string[] items = 行.Split( '=' ); if( 2 != items.Length ) { Trace.TraceError( $"ViewerPlaySpeed の書式が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } if( double.TryParse( items[ 1 ].Trim(), out double speed ) ) { 現在の.スコア.Viewerでの再生速度 = double.Parse( items[ 1 ].Trim() ); return true; } else { Trace.TraceError( $"Level の右辺が不正です。スキップします。[{現在の.行番号}行目]" ); return false; } } //---------------- #endregion return false; // 該当なし } /// <returns> /// 行を小節メモ行として処理したなら true 、該当しないまたはエラーが発生したときは false を返す。 /// </returns> private static bool _行を小節メモ行として解析する( ref string 行 ) { if( 行.StartsWith( "partmemo", StringComparison.OrdinalIgnoreCase ) ) { #region " '=' 以前を除去する。" //----------------- int 等号位置 = 行.IndexOf( '=' ); if( 0 >= 等号位置 ) // 0 or -1 { Trace.TraceError( $"PartMemo の書式が不正です。スキップします。[{現在の.行番号}]行目]" ); return false; } 行 = 行[ ( 等号位置 + 1 ).. ].Trim(); if( string.IsNullOrEmpty( 行 ) ) { Trace.TraceError( $"PartMemo の書式が不正です。スキップします。[{現在の.行番号}]行目]" ); return false; } //----------------- #endregion #region " カンマ位置を取得する。" //----------------- int カンマ位置 = 行.IndexOf( ',' ); if( 0 >= カンマ位置 ) { Trace.TraceError( $"PartMemo の書式が不正です。スキップします。[{現在の.行番号}]行目]" ); return false; } //----------------- #endregion #region " 小節番号を取得する。" //----------------- string 小節番号文字列 = 行[ 0..カンマ位置 ]; if( !( int.TryParse( 小節番号文字列, out int 小節番号 ) || ( 0 > 小節番号 ) ) ) { Trace.TraceError( $"PartMemo の小節番号が不正です。スキップします。[{現在の.行番号}]行目]" ); return false; } //----------------- #endregion #region " メモを取得する。" //----------------- string メモ = 行[ ( カンマ位置 + 1 ).. ]; // 2文字のリテラル文字列 "\n" は改行に復号。 メモ = メモ.Replace( @"\n", Environment.NewLine ); //----------------- #endregion #region " メモが空文字列でないなら メモリスト に登録する。" //----------------- if( !( string.IsNullOrEmpty( メモ ) ) ) { 現在の.スコア.小節メモリスト.Add( 小節番号, メモ ); //現在の.スコア.チップリスト.Add( // new チップ() { // チップ種別 = チップ種別.小節メモ, // 小節番号 = 小節番号, // 小節内位置 = 0, // 小節解像度 = 1, // } ); // --> チップは廃止。(不要) } //----------------- #endregion return true; } return false; // 該当なし } /// <returns> /// 常に true を返す。 /// </returns> private static bool _行をチップ記述行として解析する( ref string 行 ) { // 行を区切り文字でトークンに分割。 string[] tokens = 行.Split( new char[] { ';', ':' } ); // すべてのトークンについて…… foreach( string token in tokens ) { string コマンド; string パラメータ; #region " トークンを区切り文字 '=' で コマンド と パラメータ に分割し、それぞれの先頭末尾の空白を削除する。" //----------------- string[] items = token.Split( '=' ); if( 2 != items.Length ) { if( 0 == token.Trim().Length ) // 空文字列(行末など)は不正じゃない。 continue; Trace.TraceError( $"コマンドとパラメータの記述書式が不正です。このコマンドをスキップします。[{現在の.行番号}行目]" ); continue; } コマンド = items[ 0 ].Trim(); パラメータ = items[ 1 ].Trim(); //----------------- #endregion switch( コマンド.ToLower() ) { case "part": #region " Part(小節番号指定)コマンド " //----------------- { // 小節番号を取得・設定。 string 小節番号文字列 = _指定された文字列の先頭から数字文字列を取り出す( ref パラメータ ); if( string.IsNullOrEmpty( 小節番号文字列 ) ) { Trace.TraceError( $"Part(小節番号)コマンドに小節番号の記述がありません。このコマンドをスキップします。[{現在の.行番号}行目]" ); continue; } if( !( int.TryParse( 小節番号文字列, out int 小節番号 ) ) ) { Trace.TraceError( $"Part(小節番号)コマンドの小節番号が不正です。このコマンドをスキップします。[{現在の.行番号}行目]" ); continue; } if( 0 > 小節番号 ) { Trace.TraceError( $"Part(小節番号)コマンドの小節番号が負数です。このコマンドをスキップします。[{現在の.行番号}行目]" ); continue; } 現在の.小節番号 = 小節番号; // Part の属性があれば取得する。 while( 0 < パラメータ.Length ) { char 属性ID = char.ToLower( パラメータ[ 0 ] ); if( 属性ID == 's' ) { #region " 小節長倍率(>0) → list小節長倍率 " //----------------- パラメータ = パラメータ[ 1.. ].Trim(); string 小節長倍率文字列 = _指定された文字列の先頭から数字文字列を取り出す( ref パラメータ ); if( string.IsNullOrEmpty( 小節長倍率文字列 ) ) { Trace.TraceError( $"Part(小節番号)コマンドに小節長倍率の記述がありません。この属性をスキップします。[{現在の.行番号}行目]" ); continue; } パラメータ = パラメータ.Trim(); if( !( double.TryParse( 小節長倍率文字列, out double 小節長倍率 ) ) ) { Trace.TraceError( $"Part(小節番号)コマンドの小節長倍率が不正です。この属性をスキップします。[{現在の.行番号}行目]" ); continue; } if( 0.0 >= 小節長倍率 ) { Trace.TraceError( $"Part(小節番号)コマンドの小節長倍率が 0.0 または負数です。この属性をスキップします。[{現在の.行番号}行目]" ); continue; } // 小節長倍率辞書に追加 or 上書き更新。 現在の.スコア.小節長倍率を設定する( 現在の.小節番号, 小節長倍率 ); continue; //----------------- #endregion } } } //----------------- #endregion break; case "lane": #region " Lane(レーン指定)コマンド(チップ種別の仮決め)" //----------------- { var lane = パラメータ.ToLower(); if( _レーンプロパティ.TryGetValue( lane, out var プロパティ ) ) { 現在の.チップ種別 = プロパティ.チップ種別; 現在の.可視 = プロパティ.可視; } else { Trace.TraceError( $"Lane(レーン指定)コマンドのパラメータ記述 '{パラメータ}' が不正です。このコマンドをスキップします。[{現在の.行番号}行目]" ); } } //----------------- #endregion break; case "resolution": #region " Resolution(小節解像度指定)コマンド " //----------------- { if( !( int.TryParse( パラメータ, out int 解像度 ) ) ) { Trace.TraceError( $"Resolution(小節解像度指定)コマンドの解像度が不正です。このコマンドをスキップします。[{現在の.行番号}行目]" ); continue; } if( 1 > 解像度 ) { Trace.TraceError( $"Resolution(小節解像度指定)コマンドの解像度は 1 以上でなければなりません。このコマンドをスキップします。[{現在の.行番号}行目]" ); continue; } 現在の.小節解像度 = 解像度; } //----------------- #endregion break; case "chips": #region " Chips(チップ指定)コマンド " //----------------- // パラメータを区切り文字 ',' でチップトークンに分割。 string[] chipTokens = パラメータ.Split( ',' ); // すべてのチップトークンについて…… for( int i = 0; i < chipTokens.Length; i++ ) { chipTokens[ i ].Trim(); if( 0 == chipTokens[ i ].Length ) continue; #region " チップを生成する。" //----------------- var chip = new チップ() { 小節番号 = 現在の.小節番号, チップ種別 = 現在の.チップ種別, チップサブID = ( 現在の.チップ種別 == チップ種別.背景動画 || 現在の.チップ種別 == チップ種別.BGM ) ? 1 : 0, // AVI, WAV なら 01 固定。 小節解像度 = 現在の.小節解像度, 音量 = チップ.既定音量, 可視 = 現在の.可視, }; //----------------- #endregion #region " チップ位置を取得する。" //----------------- { string 位置番号文字列 = _指定された文字列の先頭から数字文字列を取り出す( ref chipTokens[ i ] ); chipTokens[ i ].Trim(); // 文法チェック。 if( string.IsNullOrEmpty( 位置番号文字列 ) ) { Trace.TraceError( $"チップの位置指定の記述がありません。このチップをスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } // 位置を取得。 if( false == int.TryParse( 位置番号文字列, out int チップ位置 ) ) { Trace.TraceError( $"チップの位置指定の記述が不正です。このチップをスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } // 値域チェック。 if( ( 0 > チップ位置 ) || ( チップ位置 >= 現在の.小節解像度 ) ) { Trace.TraceError( $"チップの位置が負数であるか解像度(Resolution)以上の値になっています。このチップをスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } chip.小節内位置 = チップ位置; } //----------------- #endregion #region " 共通属性・レーン別属性があれば取得する。" //----------------- while( 0 < chipTokens[ i ].Length ) { var 属性ID = char.ToLower( chipTokens[ i ][ 0 ] ); // 共通属性 if( 'v' == 属性ID ) { #region " 音量 " //---------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); string 音量文字列 = _指定された文字列の先頭から数字文字列を取り出す( ref chipTokens[ i ] ); chipTokens[ i ].Trim(); // 文法チェック。 if( string.IsNullOrEmpty( 音量文字列 ) ) { Trace.TraceError( $"チップの音量指定の記述がありません。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } // チップ音量の取得。 if( !( int.TryParse( 音量文字列, out int チップ音量 ) ) ) { Trace.TraceError( $"チップの音量指定の記述が不正です。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } // 値域チェック。 if( ( 1 > チップ音量 ) || ( チップ音量 > チップ.最大音量 ) ) { Trace.TraceError( $"チップの音量が適正範囲(1~{チップ.最大音量})を超えています。このチップをスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } chip.音量 = チップ音量; continue; //---------------- #endregion } // レーン別属性 switch( 現在の.チップ種別 ) { case チップ種別.LeftCrash: if( 'm' == 属性ID ) { #region " ミュート " //---------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.LeftCymbal_Mute; //---------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Ride: case チップ種別.Ride_Cup: if( 'c' == 属性ID ) { #region " Ride.カップ " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Ride_Cup; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.China: { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Splash: { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.HiHat_Close: case チップ種別.HiHat_HalfOpen: case チップ種別.HiHat_Open: case チップ種別.HiHat_Foot: if( 'o' == 属性ID ) { #region " HiHat.オープン " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.HiHat_Open; //----------------- #endregion } else if( 'h' == 属性ID ) { #region " HiHat.ハーフオープン " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.HiHat_HalfOpen; //----------------- #endregion } else if( 'c' == 属性ID ) { #region " HiHat.クローズ " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.HiHat_Close; //----------------- #endregion } else if( 'f' == 属性ID ) { #region " HiHat.フットスプラッシュ " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.HiHat_Foot; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Snare: case チップ種別.Snare_ClosedRim: case チップ種別.Snare_OpenRim: case チップ種別.Snare_Ghost: if( 'o' == 属性ID ) { #region " Snare.オープンリム " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Snare_OpenRim; //----------------- #endregion } else if( 'c' == 属性ID ) { #region " Snare.クローズドリム " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Snare_ClosedRim; //----------------- #endregion } else if( 'g' == 属性ID ) { #region " Snare.ゴースト " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Snare_Ghost; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Bass: { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Tom1: case チップ種別.Tom1_Rim: if( 'r' == 属性ID ) { #region " Tom1.リム " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Tom1_Rim; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Tom2: case チップ種別.Tom2_Rim: if( 'r' == 属性ID ) { #region " Tom2.リム " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Tom2_Rim; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.Tom3: case チップ種別.Tom3_Rim: if( 'r' == 属性ID ) { #region " Tom3.リム " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.Tom3_Rim; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.RightCrash: if( 'm' == 属性ID ) { #region " ミュート " //---------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); chip.チップ種別 = チップ種別.RightCymbal_Mute; //---------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.BPM: if( 'b' == 属性ID ) { #region " BPM値 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); string BPM文字列 = _指定された文字列の先頭から数字文字列を取り出す( ref chipTokens[ i ] ); chipTokens[ i ].Trim(); if( string.IsNullOrEmpty( BPM文字列 ) ) { Trace.TraceError( $"BPM数値の記述がありません。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } if( false == double.TryParse( BPM文字列, out double BPM ) || ( 0.0 >= BPM ) ) { Trace.TraceError( $"BPM数値の記述が不正です。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); continue; } chip.BPM = BPM; //----------------- #endregion } else { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; case チップ種別.背景動画: { #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } continue; } #region " 未知の属性 " //----------------- chipTokens[ i ] = chipTokens[ i ][ 1.. ].Trim(); Trace.TraceError( $"未対応の属性「{属性ID}」が指定されています。この属性をスキップします。[{現在の.行番号}行目; {i + 1}個目のチップ]" ); //----------------- #endregion } //----------------- #endregion 現在の.スコア.チップリスト.Add( chip ); } //----------------- #endregion break; } } return true; } /// <remarks> /// 取出文字列の先頭にある数字(小数点も有効)の連続した部分を取り出して、戻り値として返す。 /// また、取出文字列から取り出した数字文字列部分を除去した文字列を再度格納する。 /// </remarks> private static string _指定された文字列の先頭から数字文字列を取り出す( ref string 取出文字列 ) { // 数字が何桁続くか数える。 int 桁数 = 0; while( ( 桁数 < 取出文字列.Length ) && ( char.IsDigit( 取出文字列[ 桁数 ] ) || 取出文字列[ 桁数 ] == '.' ) ) 桁数++; if( 0 == 桁数 ) return ""; // その桁数分を取り出して返す。 string 数字文字列 = 取出文字列[ ..桁数 ]; 取出文字列 = ( 桁数 == 取出文字列.Length ) ? "" : 取出文字列[ 桁数.. ]; return 数字文字列; } // 行出力 private static void _ヘッダ行を出力する( スコア score, StreamWriter sw ) { #region " Title " //---------------- sw.WriteLine( "Title=" + ( ( string.IsNullOrEmpty( score.曲名 ) ) ? "(no title)" : score.曲名 ) ); // Title は必須 //---------------- #endregion #region " Artist " //---------------- if( !string.IsNullOrEmpty( score.アーティスト名 ) ) // Artist は任意 sw.WriteLine( $"Artist=" + score.アーティスト名 ); //---------------- #endregion #region " Description " //---------------- if( !string.IsNullOrEmpty( score.説明文 ) ) // Description は任意 { // 改行コードは、2文字のリテラル "\n" に置換。 sw.WriteLine( $"Description=" + score.説明文.Replace( Environment.NewLine, @"\n" ) ); } //---------------- #endregion #region " SoundDevice.Delay " //---------------- sw.WriteLine( $"SoundDevice.Delay={score.サウンドデバイス遅延ms}" ); //---------------- #endregion #region " Level " //---------------- sw.WriteLine( $"Level={score.難易度.ToString( "0.00" )}" ); //---------------- #endregion #region " BGV " //---------------- if( !string.IsNullOrEmpty( score.BGVファイル名 ) ) sw.WriteLine( $"BGV=" + score.BGVファイル名 ); //---------------- #endregion #region " BGM " //---------------- if( !string.IsNullOrEmpty( score.BGMファイル名 ) ) sw.WriteLine( $"BGM=" + score.BGMファイル名 ); //---------------- #endregion #region " Preview.Sound " //---------------- if( !string.IsNullOrEmpty( score.プレビュー音声ファイル名 ) ) sw.WriteLine( $"Preview.Sound=" + score.プレビュー音声ファイル名 ); //---------------- #endregion #region " Preview.Image " //---------------- if( !string.IsNullOrEmpty( score.プレビュー画像ファイル名 ) ) sw.WriteLine( $"Preview.Image=" + score.プレビュー画像ファイル名 ); //---------------- #endregion #region " Preview.Movie " //---------------- if( !string.IsNullOrEmpty( score.プレビュー動画ファイル名 ) ) sw.WriteLine( $"Preview.Movie=" + score.プレビュー動画ファイル名 ); //---------------- #endregion #region " ViewerPlaySpeed " //---------------- if( score.Viewerでの再生速度 != 1.0 ) { sw.WriteLine( $"ViewerPlaySpeed=" + score.Viewerでの再生速度 ); } //---------------- #endregion sw.WriteLine( "" ); } private static void _小節メモ行を出力する( スコア score, StreamWriter sw ) { int 最大小節番号 = score.最大小節番号を返す(); // 小節番号昇順に出力。 for( int i = 0; i <= 最大小節番号; i++ ) { if( score.小節メモリスト.TryGetValue( i, out string メモ ) ) { メモ = メモ.Replace( Environment.NewLine, @"\n" ); // 改行コードは、2文字のリテラル "\n" に置換。 sw.WriteLine( $"PartMemo = {i},{メモ}" ); } } sw.WriteLine( "" ); } private static void _チップ記述行を出力する( スコア score, StreamWriter sw ) { if( 0 == score.チップリスト.Count ) return; int 最終小節番号 = score.最大小節番号を返す(); // すべての小節番号について…… for( int 小節番号 = 0; 小節番号 <= 最終小節番号; 小節番号++ ) { var 現在の小節に存在するチップのレーン別リスト = new Dictionary<レーン種別, チップ[]>(); #region " 現在の小節に存在するチップのレーン別リストを作成する。" //---------------- foreach( レーン種別 laneType in Enum.GetValues( typeof( レーン種別 ) ) ) { if( laneType == レーン種別.Unknown ) // チップ記述対象外レーン continue; var chips = score.チップリスト.Where( ( chip ) => ( chip.小節番号 == 小節番号 && SSTFプロパティ.チップtoレーンマップ[ chip.チップ種別 ] == laneType && // チップ記述対象外チップ chip.チップ種別 != チップ種別.SE1 && chip.チップ種別 != チップ種別.SE2 && chip.チップ種別 != チップ種別.SE3 && chip.チップ種別 != チップ種別.SE4 && chip.チップ種別 != チップ種別.SE5 && chip.チップ種別 != チップ種別.SE6 && chip.チップ種別 != チップ種別.SE7 && chip.チップ種別 != チップ種別.SE8 && chip.チップ種別 != チップ種別.SE9 && chip.チップ種別 != チップ種別.SE10 && chip.チップ種別 != チップ種別.SE11 && chip.チップ種別 != チップ種別.SE12 && chip.チップ種別 != チップ種別.SE13 && chip.チップ種別 != チップ種別.SE14 && chip.チップ種別 != チップ種別.SE15 && chip.チップ種別 != チップ種別.SE16 && chip.チップ種別 != チップ種別.SE17 && chip.チップ種別 != チップ種別.SE18 && chip.チップ種別 != チップ種別.SE19 && chip.チップ種別 != チップ種別.SE20 && chip.チップ種別 != チップ種別.SE21 && chip.チップ種別 != チップ種別.SE22 && chip.チップ種別 != チップ種別.SE23 && chip.チップ種別 != チップ種別.SE24 && chip.チップ種別 != チップ種別.SE25 && chip.チップ種別 != チップ種別.SE26 && chip.チップ種別 != チップ種別.SE27 && chip.チップ種別 != チップ種別.SE28 && chip.チップ種別 != チップ種別.SE29 && chip.チップ種別 != チップ種別.SE30 && chip.チップ種別 != チップ種別.SE31 && chip.チップ種別 != チップ種別.SE32 && chip.チップ種別 != チップ種別.GuitarAuto && chip.チップ種別 != チップ種別.BassAuto ) ); 現在の小節に存在するチップのレーン別リスト[ laneType ] = chips.ToArray(); } //---------------- #endregion #region " Part を出力する。" //----------------- { var options = ( score.小節長倍率リスト[ 小節番号 ] == 1.0 ) ? "" : $"s{score.小節長倍率リスト[ 小節番号 ]}"; // 小節長倍率指定 sw.WriteLine( $"Part = {小節番号}{options};" ); } //----------------- #endregion foreach( レーン種別 laneType in Enum.GetValues( typeof( レーン種別 ) ) ) { if( !( 現在の小節に存在するチップのレーン別リスト.ContainsKey( laneType ) ) || 0 == 現在の小節に存在するチップのレーン別リスト[ laneType ].Length ) continue; #region " Lane を出力する。" //---------------- sw.Write( $"Lane={laneType.ToString()}; " ); //---------------- #endregion #region " Resolution を出力する。" //---------------- { // チップの 位置 と 解像度 を約分する。 foreach( var chip in 現在の小節に存在するチップのレーン別リスト[ laneType ] ) { var 最大公約数 = _最大公約数を返す( chip.小節内位置, chip.小節解像度 ); chip.小節内位置 /= 最大公約数; chip.小節解像度 /= 最大公約数; } // この小節の解像度を、チップの解像度の最小公倍数から算出する。 int この小節の解像度 = 1; foreach( var chip in 現在の小節に存在するチップのレーン別リスト[ laneType ] ) この小節の解像度 = _最小公倍数を返す( この小節の解像度, chip.小節解像度 ); // 算出した解像度を、Resolution として出力する。 sw.Write( $"Resolution={この小節の解像度}; " ); // Resolution にあわせて、チップの位置と解像度を修正する。 foreach( var chip in 現在の小節に存在するチップのレーン別リスト[ laneType ] ) { int 倍率 = この小節の解像度 / chip.小節解像度; // 必ず割り切れる。(この小節の解像度はチップの小節解像度の最小公倍数なので) chip.小節内位置 *= 倍率; chip.小節解像度 *= 倍率; } } //---------------- #endregion #region " Chips を出力する。" //---------------- sw.Write( "Chips=" ); for( int i = 0; i < 現在の小節に存在するチップのレーン別リスト[ laneType ].Length; i++ ) { var chip = 現在の小節に存在するチップのレーン別リスト[ laneType ][ i ]; // 位置を出力。 sw.Write( chip.小節内位置.ToString() ); // 属性を出力(あれば)。 #region " (1) 共通属性 " //----------------- if( chip.音量 < チップ.最大音量 ) sw.Write( $"v{chip.音量.ToString()}" ); //----------------- #endregion #region " (2) 専用属性 " //----------------- switch( chip.チップ種別 ) { case チップ種別.Ride_Cup: sw.Write( 'c' ); break; case チップ種別.HiHat_Open: sw.Write( 'o' ); break; case チップ種別.HiHat_HalfOpen: sw.Write( 'h' ); break; case チップ種別.HiHat_Foot: sw.Write( 'f' ); break; case チップ種別.Snare_OpenRim: sw.Write( 'o' ); break; case チップ種別.Snare_ClosedRim: sw.Write( 'c' ); break; case チップ種別.Snare_Ghost: sw.Write( 'g' ); break; case チップ種別.Tom1_Rim: sw.Write( 'r' ); break; case チップ種別.Tom2_Rim: sw.Write( 'r' ); break; case チップ種別.Tom3_Rim: sw.Write( 'r' ); break; case チップ種別.LeftCymbal_Mute: sw.Write( 'm' ); break; case チップ種別.RightCymbal_Mute: sw.Write( 'm' ); break; case チップ種別.BPM: sw.Write( $"b{chip.BPM.ToString()}" ); break; } //----------------- #endregion // 区切り文字(,) または 終端文字(;) を出力。 bool 最後のチップである = ( i == 現在の小節に存在するチップのレーン別リスト[ laneType ].Length - 1 ); sw.Write( 最後のチップである ? ";" : "," ); } //---------------- #endregion sw.WriteLine( "" ); // ここまでが1行。 } sw.WriteLine( "" ); // 次の Part 前に1行あける。 } } private static Dictionary<string, (チップ種別 チップ種別, bool 可視)> _レーンプロパティ = new Dictionary<string, (チップ種別 チップ種別, bool 可視)> { #region " *** " //---------------- [ "leftcrash" ] = (チップ種別.LeftCrash, true), [ "ride" ] = (チップ種別.Ride, true), [ "china" ] = (チップ種別.China, true), [ "splash" ] = (チップ種別.Splash, true), [ "hihat" ] = (チップ種別.HiHat_Close, true), [ "foot" ] = (チップ種別.HiHat_Foot, true), [ "snare" ] = (チップ種別.Snare, true), [ "bass" ] = (チップ種別.Bass, true), [ "tom1" ] = (チップ種別.Tom1, true), [ "tom2" ] = (チップ種別.Tom2, true), [ "tom3" ] = (チップ種別.Tom3, true), [ "rightcrash" ] = (チップ種別.RightCrash, true), [ "bpm" ] = (チップ種別.BPM, false), [ "bgv" ] = (チップ種別.背景動画, false), [ "bgm" ] = (チップ種別.BGM, false), //---------------- #endregion }; // その他 private static int _最大公約数を返す( int m, int n ) { if( ( 0 > m ) || ( 0 > n ) ) throw new Exception( "引数に負数は指定できません。" ); if( 0 == m ) return n; if( 0 == n ) return m; // ユーグリッドの互除法 int r; while( ( r = m % n ) != 0 ) { m = n; n = r; } return n; } private static int _最小公倍数を返す( int m, int n ) { if( ( 0 >= m ) || ( 0 >= n ) ) throw new Exception( "引数に0以下の数は指定できません。" ); return ( m * n / _最大公約数を返す( m, n ) ); } /// <summary> /// 指定された行が SSTFVersion コメントであるかを判定し、そうであるならそのバージョンを解析して返す。 /// それ以外は null を返す。 /// </summary> internal static Version _行にSSTFVersionがあるなら解析して返す( string 行 ) { try { 行 = 行.Trim(); int コメント識別子の位置 = 行.IndexOf( '#' ); // 見つからなければ -1 if( 0 <= コメント識別子の位置 ) { var コメント文 = 行[ ( コメント識別子の位置 + 1 ).. ].Trim(); if( コメント文.ToLower().StartsWith( "sstfversion" ) ) { return new Version( コメント文[ ( "sstfversion".Length ).. ] ); // 生成失敗なら例外発生 } } } catch { } return null; } private static string _絶対パスを相対パスに変換する( string 基点フォルダの絶対パス, string 変換したいフォルダの絶対パス ) { if( null == 変換したいフォルダの絶対パス ) return null; if( !( Path.IsPathRooted( 基点フォルダの絶対パス ) ) ) throw new Exception( $"基点フォルダは絶対パスで指定してください。[{基点フォルダの絶対パス}]" ); if( !( Path.IsPathRooted( 変換したいフォルダの絶対パス ) ) ) throw new Exception( $"変換対象フォルダは絶対パスで指定してください。[{変換したいフォルダの絶対パス}]" ); // 末尾は \ にしておく("+"でパスを連結する事態を想定。Path.Combine() を使う分には、末尾に \ があってもなくてもどっちでもいい。) if( '\\' != 基点フォルダの絶対パス[ 基点フォルダの絶対パス.Length - 1 ] ) 基点フォルダの絶対パス += @"\"; // 絶対-相対パス変換は、System.IO.Path クラスではなく System.IO.Uri クラスでしか行えない。 var 基点uri = new Uri( 基点フォルダの絶対パス ); var 変換前uri = new Uri( 変換したいフォルダの絶対パス ); var 変換後uri = 基点uri.MakeRelativeUri( 変換前uri ); // URI形式になっているので、パス形式に戻す。(具体的には、エスケープ文字を復元し、さらに '/' を '\' に置換する。) return Uri.UnescapeDataString( 変換後uri.ToString() ).Replace( oldChar: '/', newChar: '\\' ); } } } } <|start_filename|>FDK/サウンド/Sources/MediaFoundationOnMemoryWaveSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace FDK { /// <summary> /// 指定されたメディアファイル(動画, 音楽)を最初に一括して読み込み&デコードする <see cref="CSCore.IWaveSource"/> オブジェクトを生成する。 /// </summary> public class MediaFoundationOnMemoryWaveSource : MediaFoundationOnStreamingWaveSource { /// <summary> /// コンストラクタ。 /// 指定されたファイルを指定されたフォーマットでデコードし、内部にオンメモリで保管する。 /// </summary> public MediaFoundationOnMemoryWaveSource( VariablePath ファイルパス, CSCore.WaveFormat deviceFormat ) : base( ファイルパス, deviceFormat ) { } } } <|start_filename|>DTXMania2/曲/Tree/曲ツリー.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FDK; namespace DTXMania2.曲 { abstract class 曲ツリー : IDisposable { // 曲ツリーは、1つのルートから成るノードの階層構造を持つ。 public virtual RootNode ルートノード { get; } // フォーカスについて: // // 【フォーカスホルダ】 //  ・曲ツリーは、ツリー内のいずれかの BoxNode を選択(フォーカス)することができる。 //  ・この BoxNode を「フォーカスホルダ」と称する。 // // 【フォーカスリスト】 //  ・フォーカスホルダの子ノードリストは「フォーカスリスト」とされ、選曲画面に表示される対象となる。 // // 【フォーカスノード(フォーカス曲)】 //  ・フォーカスリストは SelectableList<Node> 型であり、ゼロまたは1個のノードを選択(フォーカス)することができる。 //   これを「フォーカスノード」(または「フォーカス曲」)と称する。 // // 【フォーカス難易度レベル】 //  ・後述。 public virtual BoxNode フォーカスホルダ { get; set; } public virtual SelectableList<Node> フォーカスリスト => this.フォーカスホルダ.子ノードリスト; public virtual Node? フォーカスノード => this.フォーカスリスト.SelectedItem; /// <summary> /// 指定されたノードをフォーカス(選択)する。 /// </summary> /// <remarks> /// 必要に応じて、<see cref="フォーカスホルダ"/>, <see cref="フォーカスリスト"/> も変更される。 /// </remarks> /// <return>結果としてフォーカスノードが変わったら true 。</return> public bool フォーカスする( Node focusNode ) { var 変更前のノード = this.フォーカスノード; if( focusNode == 変更前のノード ) return false; // 同一 // ホルダを変更。 this.フォーカスホルダ = focusNode.親ノード ?? throw new Exception( "ルートノードをフォーカスすることはできません。" ); // チェック。 if( !this.フォーカスホルダ.子ノードリスト.SelectItem( focusNode ) || this.フォーカスホルダ.子ノードリスト.SelectedItem is null ) throw new Exception( "フォーカスノードの選択に失敗しました。" ); return true; } /// <summary> /// 現在のフォーカスノードの1つ後のノードをフォーカスする。 /// </summary> /// <remarks> /// 次のノードが存在しない場合は、フォーカスリストの先頭のノードをフォーカスする。 /// </remarks> /// <return>結果としてフォーカスノードが変わったら true 。</return> public bool 次のノードをフォーカスする() { var 変更前のノード = this.フォーカスノード; var focus_index = this.フォーカスリスト.SelectedIndex; var next_index = ( 0 > focus_index ) ? 0 : ( focus_index + 1 ) % this.フォーカスリスト.Count; this.フォーカスリスト.SelectItem( next_index ); return ( this.フォーカスノード != 変更前のノード ); } /// <summary> /// 現在のフォーカスノードの1つ前ノードをフォーカスする。 /// </summary> /// <remarks> /// 前のノードが存在しない場合は、フォーカスリストの末尾のノードをフォーカスする。 /// </remarks> /// <return>結果としてフォーカスノードが変わったら true 。</return> public bool 前のノードをフォーカスする() { var 変更前のノード = this.フォーカスノード; var focus_index = this.フォーカスリスト.SelectedIndex; var prev_index = ( 0 > focus_index ) ? 0 : ( focus_index - 1 + this.フォーカスリスト.Count ) % this.フォーカスリスト.Count; this.フォーカスリスト.SelectItem( prev_index ); return ( this.フォーカスノード != 変更前のノード ); } // 難易度レベルについて: // // 【難易度レベル】 //  ・set.def を使うと、1つの曲に対して最大5つの難易度の譜面を用意することができる。 //   慣例では 0:BASIC, 1:ADVANCED, 2:EXTREME, 3:MASTER, 4:ULTIMATE に相当する。(set.defのL1~L5に対応する。) // // 【ユーザ希望難易度レベル】 //  ・ユーザは、選曲画面で、希望の難易度レベルを選択することができる。 //   これを「ユーザ希望難易度レベル」と称する。 // // 【フォーカス難易度レベル】 //  ・ユーザ希望難易度レベルに「一番近い」フォーカスノードの難易度レベルを、「フォーカス難易度レベル」と称する。 //  ・すべてのノードは、必ずしも5つの難易度レベルすべてに対応している必要は無い。 //    - 例えば、EXTREME相当の譜面しか持たない曲も多く存在する。 //     この場合、この曲がフォーカスされた時点でのフォーカス難易度レベルは、2 にならざるを得ない。 //  ・従って、ユーザ希望難易度レベルとフォーカス難易度レベルは、必ずしも一致しない。 // // ※「難易度」「難易度レベル」「難易度ラベル」の違いに注意。 //  ・難易度 = 0.00 ~ 9.99 // ・難易度レベル = 0 ~ 4 // ・難易度ラベル = "BASIC", "ADVANCED" など public int ユーザ希望難易度レベル { get; protected set; } = 2; // 初期値は 2(MASTER 相当) public int フォーカス難易度レベル => this.フォーカスノード switch { // (A) 未選択の場合 null => this.ユーザ希望難易度レベル, // (B) 曲ノードの場合 SongNode snode => snode.曲.ユーザ希望難易度に最も近い難易度レベルを返す( this.ユーザ希望難易度レベル ), // (C) その他のノードの場合 _ => this.ユーザ希望難易度レベル, }; public void ユーザ希望難易度をひとつ増やす() { // ユーザ希望難易度を1つ増やす。(4を越えたら0に戻る。) // ただし、フォーカス難易度と一致しなかった(フォーカス曲がその難易度レベルの譜面を持っていなかった)場合は、 // 一致するまで増やし続ける。 for( int i = 0; i < 5; i++ ) // 最低5回で一周する { // 1つ増やす。 this.ユーザ希望難易度レベル = ( this.ユーザ希望難易度レベル + 1 ) % 5; // 4を越えたら0に戻る if( this.フォーカスノード is SongNode snode ) { // その難易度レベルに対応する譜面があればOK。 if( null != snode.曲.譜面リスト[ this.ユーザ希望難易度レベル ] ) return; } else { // SongNode 以外は特に条件なし。 return; } } } // 生成と終了 public 曲ツリー() { this.ルートノード = new RootNode(); this.フォーカスホルダ = this.ルートノード; } public virtual void Dispose() { foreach( var node in this.ルートノード.Traverse() ) node.Dispose(); Song.現在の難易度レベル = () => throw new NotImplementedException(); } } } <|start_filename|>DTXMania2/ステージ/08結果/達成率.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.結果 { partial class 達成率 : 達成率Base { // プロパティ /// <summary> /// アニメがすべて終わったら true。 /// </summary> public override bool アニメ完了 => this._アイコン.アニメ完了 && this._下線.アニメ完了 && this._数値.アニメ完了; // 生成と終了 public 達成率() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._アイコン = new アイコン(); this._下線 = new 下線(); this._数値 = new 数値(); this._初めての進行描画 = true; } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数値.Dispose(); this._下線.Dispose(); this._アイコン.Dispose(); } // 進行と描画 public override void アニメを完了する() { this._アイコン.アニメを完了する(); this._下線.アニメを完了する(); this._数値.アニメを完了する(); } public override void 進行描画する( DeviceContext d2ddc, float x, float y, double 達成率0to100 ) { if( this._初めての進行描画 ) { // アニメーション開始 this._アイコン.開始する(); this._下線.開始する(); this._数値.開始する( 達成率0to100 ); this._初めての進行描画 = false; } this._アイコン.進行描画する( d2ddc, x, y ); this._数値.進行描画する( d2ddc, x + 150f, y + 48f ); this._下線.進行描画する( d2ddc, x + 33f, y + 198f ); } // ローカル private bool _初めての進行描画; private const double _最初の待機時間sec = 1.0; private const double _アニメ時間sec = 0.25; private readonly 達成率.アイコン _アイコン; private readonly 達成率.下線 _下線; private readonly 達成率.数値 _数値; } } <|start_filename|>SSTFEditor/小節長倍率入力ダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace SSTFEditor { public partial class 小節長倍率入力ダイアログ : Form { public bool 後続も全部変更する { get => this.checkBox後続設定.Checked; set => this.checkBox後続設定.CheckState = value ? CheckState.Checked : CheckState.Unchecked; } public float 倍率 { get => (float) this.numericUpDown小節長の倍率.Value; set => this.numericUpDown小節長の倍率.Value = (decimal) value; } public 小節長倍率入力ダイアログ( int 小節番号 ) { InitializeComponent(); this.textBox小節番号.Text = 小節番号.ToString( "000" ); } protected void numericUpDown小節長の倍率_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → Cancel else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } protected void checkBox後続設定_KeyDown( object sender, KeyEventArgs e ) { // ENTER → OK if( e.KeyCode == Keys.Return ) this.buttonOK.PerformClick(); // ESC → Cancel else if( e.KeyCode == Keys.Escape ) this.buttonキャンセル.PerformClick(); } } } <|start_filename|>DTXMania2/ステージ/05オプション設定/入力割り当てダイアログ.Designer.cs<|end_filename|> namespace DTXMania2.オプション設定 { partial class 入力割り当てダイアログ { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(入力割り当てダイアログ)); this.listView入力リスト = new System.Windows.Forms.ListView(); this.columnHeaderMIDIノート情報 = new System.Windows.Forms.ColumnHeader(); this.buttonOk = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonFootPedalリセット = new System.Windows.Forms.Button(); this.labelFootPedal現在値 = new System.Windows.Forms.Label(); this.textBoxFootPedal現在値 = new System.Windows.Forms.TextBox(); this.labelFootPedal最大値 = new System.Windows.Forms.Label(); this.labelFootPedal最小値 = new System.Windows.Forms.Label(); this.pictureBoxFootPedal = new System.Windows.Forms.PictureBox(); this.textBoxFootPedal最小値 = new System.Windows.Forms.TextBox(); this.textBoxFootPedal最大値 = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.richTextBox3 = new System.Windows.Forms.RichTextBox(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.comboBoxパッドリスト = new System.Windows.Forms.ComboBox(); this.listView割り当て済み入力リスト = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.button割り当て解除 = new System.Windows.Forms.Button(); this.button追加 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.richTextBox2 = new System.Windows.Forms.RichTextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxFootPedal)).BeginInit(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // listView入力リスト // resources.ApplyResources(this.listView入力リスト, "listView入力リスト"); this.listView入力リスト.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderMIDIノート情報}); this.listView入力リスト.Cursor = System.Windows.Forms.Cursors.Arrow; this.listView入力リスト.FullRowSelect = true; this.listView入力リスト.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.listView入力リスト.HideSelection = false; this.listView入力リスト.Name = "listView入力リスト"; this.listView入力リスト.UseCompatibleStateImageBehavior = false; this.listView入力リスト.View = System.Windows.Forms.View.Details; this.listView入力リスト.DoubleClick += new System.EventHandler(this.listView入力リスト_DoubleClick); // // columnHeaderMIDIノート情報 // resources.ApplyResources(this.columnHeaderMIDIノート情報, "columnHeaderMIDIノート情報"); // // buttonOk // resources.ApplyResources(this.buttonOk, "buttonOk"); this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Name = "buttonOk"; this.buttonOk.UseVisualStyleBackColor = true; // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // buttonFootPedalリセット // resources.ApplyResources(this.buttonFootPedalリセット, "buttonFootPedalリセット"); this.buttonFootPedalリセット.Name = "buttonFootPedalリセット"; this.buttonFootPedalリセット.UseVisualStyleBackColor = true; // // labelFootPedal現在値 // resources.ApplyResources(this.labelFootPedal現在値, "labelFootPedal現在値"); this.labelFootPedal現在値.Name = "labelFootPedal現在値"; // // textBoxFootPedal現在値 // resources.ApplyResources(this.textBoxFootPedal現在値, "textBoxFootPedal現在値"); this.textBoxFootPedal現在値.Name = "textBoxFootPedal現在値"; this.textBoxFootPedal現在値.ReadOnly = true; // // labelFootPedal最大値 // resources.ApplyResources(this.labelFootPedal最大値, "labelFootPedal最大値"); this.labelFootPedal最大値.Name = "labelFootPedal最大値"; // // labelFootPedal最小値 // resources.ApplyResources(this.labelFootPedal最小値, "labelFootPedal最小値"); this.labelFootPedal最小値.Name = "labelFootPedal最小値"; // // pictureBoxFootPedal // resources.ApplyResources(this.pictureBoxFootPedal, "pictureBoxFootPedal"); this.pictureBoxFootPedal.BackColor = System.Drawing.SystemColors.Window; this.pictureBoxFootPedal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictureBoxFootPedal.Name = "pictureBoxFootPedal"; this.pictureBoxFootPedal.TabStop = false; // // textBoxFootPedal最小値 // resources.ApplyResources(this.textBoxFootPedal最小値, "textBoxFootPedal最小値"); this.textBoxFootPedal最小値.Name = "textBoxFootPedal最小値"; this.textBoxFootPedal最小値.ReadOnly = true; // // textBoxFootPedal最大値 // resources.ApplyResources(this.textBoxFootPedal最大値, "textBoxFootPedal最大値"); this.textBoxFootPedal最大値.Name = "textBoxFootPedal最大値"; this.textBoxFootPedal最大値.ReadOnly = true; // // groupBox2 // resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Controls.Add(this.richTextBox3); this.groupBox2.Controls.Add(this.pictureBoxFootPedal); this.groupBox2.Controls.Add(this.buttonFootPedalリセット); this.groupBox2.Controls.Add(this.textBoxFootPedal現在値); this.groupBox2.Controls.Add(this.labelFootPedal最小値); this.groupBox2.Controls.Add(this.labelFootPedal最大値); this.groupBox2.Controls.Add(this.labelFootPedal現在値); this.groupBox2.Controls.Add(this.textBoxFootPedal最大値); this.groupBox2.Controls.Add(this.textBoxFootPedal最小値); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // richTextBox3 // resources.ApplyResources(this.richTextBox3, "richTextBox3"); this.richTextBox3.BorderStyle = System.Windows.Forms.BorderStyle.None; this.richTextBox3.Cursor = System.Windows.Forms.Cursors.Arrow; this.richTextBox3.DetectUrls = false; this.richTextBox3.Name = "richTextBox3"; this.richTextBox3.ReadOnly = true; this.richTextBox3.ShortcutsEnabled = false; this.richTextBox3.TabStop = false; // // richTextBox1 // resources.ApplyResources(this.richTextBox1, "richTextBox1"); this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.richTextBox1.Cursor = System.Windows.Forms.Cursors.Arrow; this.richTextBox1.DetectUrls = false; this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.ReadOnly = true; this.richTextBox1.ShortcutsEnabled = false; this.richTextBox1.TabStop = false; // // comboBoxパッドリスト // resources.ApplyResources(this.comboBoxパッドリスト, "comboBoxパッドリスト"); this.comboBoxパッドリスト.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxパッドリスト.FormattingEnabled = true; this.comboBoxパッドリスト.Name = "comboBoxパッドリスト"; this.comboBoxパッドリスト.SelectedIndexChanged += new System.EventHandler(this.comboBoxパッドリスト_SelectedIndexChanged); // // listView割り当て済み入力リスト // resources.ApplyResources(this.listView割り当て済み入力リスト, "listView割り当て済み入力リスト"); this.listView割り当て済み入力リスト.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1}); this.listView割り当て済み入力リスト.FullRowSelect = true; this.listView割り当て済み入力リスト.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.listView割り当て済み入力リスト.HideSelection = false; this.listView割り当て済み入力リスト.Name = "listView割り当て済み入力リスト"; this.listView割り当て済み入力リスト.Scrollable = false; this.listView割り当て済み入力リスト.UseCompatibleStateImageBehavior = false; this.listView割り当て済み入力リスト.View = System.Windows.Forms.View.Details; // // columnHeader1 // resources.ApplyResources(this.columnHeader1, "columnHeader1"); // // button割り当て解除 // resources.ApplyResources(this.button割り当て解除, "button割り当て解除"); this.button割り当て解除.Name = "button割り当て解除"; this.button割り当て解除.UseVisualStyleBackColor = true; this.button割り当て解除.Click += new System.EventHandler(this.button割り当て解除_Click); // // button追加 // resources.ApplyResources(this.button追加, "button追加"); this.button追加.Name = "button追加"; this.button追加.UseVisualStyleBackColor = true; this.button追加.Click += new System.EventHandler(this.button追加_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // richTextBox2 // resources.ApplyResources(this.richTextBox2, "richTextBox2"); this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.richTextBox2.Cursor = System.Windows.Forms.Cursors.Arrow; this.richTextBox2.DetectUrls = false; this.richTextBox2.Name = "richTextBox2"; this.richTextBox2.ReadOnly = true; this.richTextBox2.ShortcutsEnabled = false; this.richTextBox2.TabStop = false; // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.richTextBox1); this.groupBox1.Controls.Add(this.listView入力リスト); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // groupBox3 // resources.ApplyResources(this.groupBox3, "groupBox3"); this.groupBox3.Controls.Add(this.richTextBox2); this.groupBox3.Controls.Add(this.label2); this.groupBox3.Controls.Add(this.comboBoxパッドリスト); this.groupBox3.Controls.Add(this.label3); this.groupBox3.Controls.Add(this.listView割り当て済み入力リスト); this.groupBox3.Name = "groupBox3"; this.groupBox3.TabStop = false; // // 入力割り当てダイアログ // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.button割り当て解除); this.Controls.Add(this.button追加); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox1); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOk); this.Controls.Add(this.groupBox2); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "入力割り当てダイアログ"; this.ShowIcon = false; this.ShowInTaskbar = false; this.TopMost = true; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.入力割り当てダイアログ_FormClosing); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxFootPedal)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListView listView入力リスト; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.ColumnHeader columnHeaderMIDIノート情報; private System.Windows.Forms.Button buttonFootPedalリセット; private System.Windows.Forms.Label labelFootPedal現在値; private System.Windows.Forms.TextBox textBoxFootPedal現在値; private System.Windows.Forms.Label labelFootPedal最大値; private System.Windows.Forms.Label labelFootPedal最小値; private System.Windows.Forms.PictureBox pictureBoxFootPedal; private System.Windows.Forms.TextBox textBoxFootPedal最小値; private System.Windows.Forms.TextBox textBoxFootPedal最大値; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.RichTextBox richTextBox3; private System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.ComboBox comboBoxパッドリスト; private System.Windows.Forms.ListView listView割り当て済み入力リスト; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.Button button割り当て解除; private System.Windows.Forms.Button button追加; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.RichTextBox richTextBox2; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox3; } } <|start_filename|>DTXMania2/保存データ/SystemConfig/SystemConfig.Update.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using YamlDotNet.RepresentationModel; using FDK; namespace DTXMania2 { partial class SystemConfig { public static void 最新版にバージョンアップする() { using var _ = new LogBlock( Log.現在のメソッド名 ); var path = new VariablePath( @"$(AppData)\Configuration.yaml" ); int version = 0; if( !File.Exists( path.変数なしパス ) ) return; #region " YAML階層のルートノード 'Version' を検索し、バージョン値を取得する。" //---------------- { var yamlText = File.ReadAllText( path.変数なしパス ); var yamlStream = new YamlStream(); yamlStream.Load( new StringReader( yamlText ) ); var rootMapping = (YamlMappingNode)yamlStream.Documents[ 0 ].RootNode; var versionNode = new YamlScalarNode( "Version" ); if( rootMapping.Children.ContainsKey( versionNode ) ) { var versionValue = rootMapping.Children[ versionNode ] as YamlScalarNode; version = int.Parse( versionValue?.Value ?? "1" ); // 取得 } } //---------------- #endregion while( version < SystemConfig.VERSION ) { switch( version ) { case 1: { break; // 存在しない } case 2: { #region " 2 → 3 " //---------------- var v2 = old.SystemConfig.v002_システム設定.読み込む( path ); var v3 = new old.SystemConfig.v003_システム設定( v2 ); v3.保存する( path ); version = v3.Version; break; //---------------- #endregion } case 3: { #region " 3 → 4 " //---------------- var v3 = old.SystemConfig.v003_システム設定.読み込む( path ); var v4 = new old.SystemConfig.v004_SystemConfig( v3 ); v4.保存する(); version = v4.Version; break; //---------------- #endregion } case 4: { #region " 4 → 5 " //---------------- var v4 = old.SystemConfig.v004_SystemConfig.読み込む( path ); var v5 = new old.SystemConfig.v005_SystemConfig( v4 ); v5.保存する(); version = v5.Version; break; //---------------- #endregion } case 5: { #region " 5 → 6 " //---------------- var v5 = old.SystemConfig.v005_SystemConfig.読み込む( path ); var v6 = new old.SystemConfig.v006_SystemConfig( v5 ); v6.保存する(); version = v6.Version; break; //---------------- #endregion } case 6: { #region " 6 → 最新版 " //---------------- var v6 = old.SystemConfig.v006_SystemConfig.読み込む( path ); var v7 = new SystemConfig( v6 ); v7.保存する(); version = v7.Version; break; //---------------- #endregion } } } } } } <|start_filename|>FDK/ログ/経過時間測定.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; namespace FDK { public class 経過時間測定 { public ConcurrentDictionary<string, double> スタック { get; } public double 現在のリアルタムカウントsec => this._Timer.現在のリアルタイムカウントsec; public 経過時間測定() { this.スタック = new ConcurrentDictionary<string, double>(); this.リセット(); } public void リセット() { lock( this._lock ) { this.スタック.Clear(); this._count = 0; this._Timer.リセットする(); this.経過ポイント( "開始" ); } } public void 経過ポイント( string ポイント名 ) { lock( this._lock ) { this.スタック.TryAdd( ポイント名, (float)( this._Timer.現在のリアルタイムカウントsec ) ); } } public void 経過ポイント() { lock( this._lock ) { this.スタック.TryAdd( $"{this._count}", (float)( this._Timer.現在のリアルタイムカウントsec ) ); this._count++; } } public void 表示() { lock( this._lock ) { double 直前の時刻 = 0.0; var sortedDic = this.スタック.OrderBy( ( kvp ) => ( kvp.Value ) ); for( int i = 0; i < sortedDic.Count(); i++ ) { var kvp = sortedDic.ElementAt( i ); Debug.Write( $"{kvp.Key}," ); } Debug.WriteLine( "区間計(ms)" ); for( int i = 0; i < sortedDic.Count(); i++ ) { var kvp = sortedDic.ElementAt( i ); Debug.Write( $"+{1000 * ( kvp.Value - 直前の時刻 ):0.00000}, " ); 直前の時刻 = kvp.Value; } Debug.WriteLine( $"{1000 * sortedDic.Last().Value:0.00000}" ); } } private QPCTimer _Timer = new QPCTimer(); private readonly object _lock = new object(); private long _count = 0; } } <|start_filename|>FDK/サウンド/Sources/ResampledOnMemoryWaveSource.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using CSCore; using CSCore.DSP; namespace FDK { /// <summary> /// 指定されたメディアファイルをデコードし、リサンプルして、 /// <see cref="CSCore.IWaveSource"/> オブジェクトを生成する。 /// </summary> public class ResampledOnMemoryWaveSource : IWaveSource { // プロパティ public bool CanSeek => true; // オンメモリなので常にサポートできる。 /// <summary> /// デコード&リサンプル後のオーディオデータのフォーマット。 /// </summary> public WaveFormat WaveFormat { get; } /// <summary> /// 現在の再生位置[byte]。 /// </summary> public long Position { get => this._Position; set => this._Position = this._位置をブロック境界単位にそろえて返す( value, this.WaveFormat.BlockAlign ); } /// <summary> /// デコード後のオーディオデータのすべての長さ[byte]。 /// </summary> public long Length => this._DecodedWaveData.Length; // 生成と終了 /// <summary> /// コンストラクタ。 /// 指定された <see cref="IWaveSource"/> をリサンプルする。 /// </summary> public ResampledOnMemoryWaveSource( IWaveSource waveSource, WaveFormat deviceFormat, double 再生速度 = 1.0 ) { // サウンドデバイスには、それに合わせたサンプルレートで報告する。 this.WaveFormat = new WaveFormat( deviceFormat.SampleRate, 32, // bits deviceFormat.Channels, AudioEncoding.IeeeFloat ); // しかしサウンドデータは、指定された再生速度を乗じたサンプルレートで生成する。 var waveFormtForResampling = new WaveFormat( (int)( this.WaveFormat.SampleRate / 再生速度 ), this.WaveFormat.BitsPerSample, this.WaveFormat.Channels, AudioEncoding.IeeeFloat ); // リサンプルを行う。 using( var resampler = new DmoResampler( waveSource, waveFormtForResampling ) ) { long サイズbyte = resampler.Length; this._DecodedWaveData = new MemoryTributary( (int)サイズbyte ); //resampler.Read( this._DecodedWaveData, 0, (int) サイズbyte ); // → 一気にReadすると、内部の Marshal.AllocCoTaskMem() に OutOfMemory例外を出されることがある。 //   よって、2秒ずつ分解しながら受け取る。 int sizeOf2秒 = (int)this._位置をブロック境界単位にそろえて返す( resampler.WaveFormat.BytesPerSecond * 2, resampler.WaveFormat.BlockAlign ); long 変換残サイズbyte = サイズbyte; while( 0 < 変換残サイズbyte ) { int 今回の変換サイズbyte = (int)this._位置をブロック境界単位にそろえて返す( Math.Min( sizeOf2秒, 変換残サイズbyte ), resampler.WaveFormat.BlockAlign ); var 中間バッファ = new byte[ 今回の変換サイズbyte ]; int 変換できたサイズbyte = resampler.Read( 中間バッファ, 0, 今回の変換サイズbyte ); if( 0 == 変換できたサイズbyte ) break; // 強制脱出 this._DecodedWaveData.Write( 中間バッファ, 0, 変換できたサイズbyte ); 変換残サイズbyte -= 変換できたサイズbyte; } } this._DecodedWaveData.Position = 0; } public virtual void Dispose() { this._DecodedWaveData.Dispose(); } // 出力 /// <summary> /// 連続したデータを読み込み、<see cref="Position"/> を読み込んだ数だけ進める。 /// </summary> /// <param name="buffer">読み込んだデータを格納するための配列。</param> /// <param name="offset"><paramref name="buffer"/> に格納を始める位置。</param> /// <param name="count">読み込む最大のデータ数。</param> /// <returns><paramref name="buffer"/> に読み込んだデータの総数。</returns> public int Read( byte[] buffer, int offset, int count ) { // ※ 音がめちゃくちゃになるとうざいので、このメソッド内では例外を出さないこと。 if( ( null == this._DecodedWaveData ) || ( null == buffer ) ) return 0; long 読み込み可能な最大count = ( this.Length - this._Position ); if( count > 読み込み可能な最大count ) count = (int)読み込み可能な最大count; if( 0 < count ) { this._DecodedWaveData.Position = this._Position; this._DecodedWaveData.Read( buffer, offset, count ); this._Position += count; } return count; } // ローカル private long _Position = 0; private MemoryTributary _DecodedWaveData; private long _位置をブロック境界単位にそろえて返す( long position, long blockAlign ) { return ( position - ( position % blockAlign ) ); } } } <|start_filename|>DTXMania2/Global.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using FDK; namespace DTXMania2 { /// <summary> /// グローバルリソース。すべて static。 /// </summary> static class Global { // グローバルプロパティ /// <summary> /// スワップチェーンなどのグラフィックリソース。 /// </summary> public static GraphicResources GraphicResources { get; } = new GraphicResources(); /// <summary> /// メインフォームインスタンスへの参照。 /// </summary> public static App App { get; set; } = null!; /// <summary> /// メインフォームインスタンスのウィンドウハンドル。 /// </summary> /// <remarks> /// <see cref="DTXMania2.App.Handle"/> メンバと同じ値であるが、GUIスレッド 以 外 のスレッドから参照する場合は、 /// <see cref="DTXMania2.App.Handle"/> ではなくこのメンバを参照すること。 /// (<see cref="DTXMania2.App"/> のメンバはすべて、必ずGUIスレッドから参照されなれければならないため。) /// </remarks> public static IntPtr Handle { get; set; } = IntPtr.Zero; /// <summary> /// アプリ起動時のコマンドラインオプション。 /// </summary> /// <remarks> /// <see cref="Program.Main(string[])"/> の引数から生成される。 /// YAML化することで、ビュアーモードで起動中の DTXMania2 のパイプラインサーバに送信する事が可能。 /// </remarks> public static CommandLineOptions Options { get; set; } = null!; /// <summary> /// タスク間メッセージングに使用するメッセージキュー。 /// </summary> public static TaskMessageQueue TaskMessageQueue { get; private set; } = new TaskMessageQueue(); /// <summary> /// Windows Animation API 関連。 /// </summary> public static Animation Animation { get; private set; } = null!; /// <summary> /// Effekseer 関連。 /// </summary> public static Effekseer Effekseer { get; private set; } = null!; // 生成と終了 /// <summary> /// 各種グローバルリソースを生成する。 /// </summary> public static void 生成する( App app, IntPtr hWindow, SharpDX.Size2F 設計画面サイズ, SharpDX.Size2F 物理画面サイズ ) { using var _ = new LogBlock( Log.現在のメソッド名 ); Global.App = app; Global.Handle = hWindow; Global.GraphicResources.スワップチェーンに依存しないグラフィックリソースの作成 += _スワップチェーンに依存しないグラフィックリソースの作成; Global.GraphicResources.スワップチェーンに依存しないグラフィックリソースの解放 += _スワップチェーンに依存しないグラフィックリソースの解放; Global.GraphicResources.スワップチェーンに依存するグラフィックリソースの作成 += _スワップチェーンに依存するグラフィックリソースの作成; Global.GraphicResources.スワップチェーンに依存するグラフィックリソースの解放 += _スワップチェーンに依存するグラフィックリソースの解放; Global.GraphicResources.生成する( Global.Handle, 設計画面サイズ, 物理画面サイズ ); Global._Dispose済み = false; } /// <summary> /// 各種グローバルリソースを開放する。 /// </summary> public static void 解放する() { using var _ = new LogBlock( Log.現在のメソッド名 ); #region " Dispose 済みなら何もしない。" //---------------- if( Global._Dispose済み ) return; Global._Dispose済み = true; //---------------- #endregion Global.GraphicResources.Dispose(); Global.Handle = IntPtr.Zero; } private static void _スワップチェーンに依存しないグラフィックリソースの作成( object? sender, EventArgs e ) { Global.Animation = new Animation(); } private static void _スワップチェーンに依存しないグラフィックリソースの解放( object? sender, EventArgs e ) { Global.Animation.Dispose(); } private static void _スワップチェーンに依存するグラフィックリソースの作成( object? sender, EventArgs e ) { Global.Effekseer = new Effekseer( Global.GraphicResources.D3D11Device1, Global.GraphicResources.既定のD3D11DeviceContext, Global.GraphicResources.設計画面サイズ.Width, Global.GraphicResources.設計画面サイズ.Height ); } private static void _スワップチェーンに依存するグラフィックリソースの解放( object? sender, EventArgs e ) { Global.Effekseer.Dispose(); } // その他 /// <summary> /// 指定されたコマンド名が対象文字列内で使用されている場合に、パラメータ部分の文字列を返す。 /// </summary> /// <remarks> /// .dtx や box.def 等で使用されている "#<コマンド名>[:]<パラメータ>[;コメント]" 形式の文字列(対象文字列)について、 /// 指定されたコマンドを使用する行であるかどうかを判別し、使用する行であるなら、そのパラメータ部分の文字列を引数に格納し、true を返す。 /// 対象文字列のコマンド名が指定したコマンド名と異なる場合には、パラメータ文字列に null を格納して false を返す。 /// コマンド名は正しくてもパラメータが存在しない場合には、空文字列("") を格納して true を返す。 /// </remarks> /// <param name="対象文字列">調べる対象の文字列。(例: "#TITLE: 曲名 ;コメント")</param> /// <param name="コマンド名">調べるコマンドの名前(例:"TITLE")。#は不要、大文字小文字は区別されない。</param> /// <returns>パラメータ文字列の取得に成功したら true、異なるコマンドだったなら false。</returns> public static bool コマンドのパラメータ文字列部分を返す( string 対象文字列, string コマンド名, out string パラメータ文字列 ) { // コメント部分を除去し、両端をトリムする。なお、全角空白はトリムしない。 対象文字列 = 対象文字列.Split( ';' )[ 0 ].Trim( ' ', '\t' ); string 正規表現パターン = $@"^\s*#\s*{コマンド名}(:|\s)+(.*)\s*$"; // \s は空白文字。 var m = Regex.Match( 対象文字列, 正規表現パターン, RegexOptions.IgnoreCase ); if( m.Success && ( 3 <= m.Groups.Count ) ) { パラメータ文字列 = m.Groups[ 2 ].Value; return true; } else { パラメータ文字列 = ""; return false; } } // ローカル private static bool _Dispose済み = true; } } <|start_filename|>FDK/PresentSwapChainVSync.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace FDK { /// <summary> /// 垂直帰線に合わせてスワップチェーンを表示するタスク。 /// </summary> public class PresentSwapChainVSync { /// <summary> /// スワップチェーンの表示待機中なら true。 /// </summary> public bool 表示待機中 { get => ( 0 != Interlocked.Read( ref this._ただいま表示中 ) ); protected set => Interlocked.Exchange( ref this._ただいま表示中, ( value ) ? 1 : 0 ); } /// <summary> /// 表示用の専用タスクを生成して、そこで垂直帰線同期とスワップチェーンの表示を行う。 /// </summary> public void 表示する( SharpDX.DXGI.SwapChain1 swapChain1 ) { this.表示待機中 = true; // 表示開始 // HACK: 毎回 Task.Run を実行しないような実装に変える。 Task.Run( () => { swapChain1.Present( 1, SharpDX.DXGI.PresentFlags.None ); this.表示待機中 = false; // 表示完了 } ); } /// <summary> /// 表示用の専用タスクを生成して、そこで垂直帰線同期とスワップチェーンの表示を行う。 /// </summary> [Obsolete] public void 表示する( SharpDX.DXGI.Output1 dxgiOutput1, SharpDX.DXGI.SwapChain1 swapChain1, int syncInterval ) { this.表示待機中 = true; // 表示開始 Task.Run( () => { // SwapChain.Present での垂直帰線待ちは広範囲のリソースを巻き込んで処理を停滞させるため、DXGIで行うようにする。 dxgiOutput1.WaitForVerticalBlank(); if( !swapChain1.IsDisposed ) // Wait中にDisposeされる場合がある swapChain1.Present( syncInterval, SharpDX.DXGI.PresentFlags.None ); this.表示待機中 = false; // 表示完了 } ); } /// <summary> /// 0 なら描画処理が可能、非 0 なら描画処理は不可(スワップチェーンの表示待機中のため)。 /// Interlocked クラスを使ってアクセスすること。 /// </summary> private long _ただいま表示中 = 0; } } <|start_filename|>FDK/入力/MidiIns.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace FDK { /// <summary> /// すべてのMIDI入力デバイス。 /// </summary> public class MidiIns : IDisposable { // 定数 public const int CTL_FOOTPEDAL = 4; // フットペダルのコントロールチェンジ番号 // プロパティ /// <summary> /// デバイス名のリスト。インデックスはデバイス番号。 /// </summary> public List<string> DeviceName { get; } = new List<string>(); /// <summary> /// FootPedal の MIDIコード。 /// </summary> /// <remarks> /// FootPedal 同時 HiHat キャンセル処理に使用される。 /// コードが判明次第、セットすること。 /// </remarks> public List<int> FootPedalNotes { get; } = new List<int>(); /// <summary> /// HiHat (Open, Close, etc,.) のMIDIコード。 /// </summary> /// <remarks> /// FootPedal 同時 HiHat キャンセル処理に使用される。 /// コードが判明次第、セットすること。 /// </remarks> public List<int> HiHatNotes { get; } = new List<int>(); /// <summary> /// 入力イベントのリスト。 /// ポーリング時に、前回のポーリング(またはコンストラクタ)以降に発生した入力イベントが格納される。 /// </summary> public List<InputEvent> 入力イベントリスト { get; protected set; } = new List<InputEvent>(); // 生成と終了 public MidiIns( SoundTimer soundTimer ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._SoundTimer = soundTimer; // コールバックをデリゲートとして生成し、そのデリゲートをGCの対象から外す。 this._midiInProc = new MidiInProc( this.MIDI入力コールバック ); this._midiInProcGCh = GCHandle.Alloc( this._midiInProc ); // デバイス数を取得。 uint MIDI入力デバイス数 = midiInGetNumDevs(); Log.Info( $"MIDI入力デバイス数 = {MIDI入力デバイス数}" ); // すべてのMIDI入力デバイスについて... for( uint id = 0; id < MIDI入力デバイス数; id++ ) { // デバイス名を取得。 var caps = new MIDIINCAPS(); midiInGetDevCaps( id, ref caps, Marshal.SizeOf( caps ) ); this.DeviceName.Add( caps.szPname ); Log.Info( $"MidiIn[{id}]: {caps.szPname}" ); // MIDI入力デバイスを開く。コールバックは全デバイスで共通。 IntPtr hMidiIn = default; if( ( 0 == midiInOpen( ref hMidiIn, id, this._midiInProc, default, CALLBACK_FUNCTION ) ) && ( default != hMidiIn ) ) { this._MIDI入力デバイスハンドルリスト.Add( hMidiIn ); midiInStart( hMidiIn ); } } } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); // すべてのMIDI入力デバイスの受信を停止し、デバイスを閉じる。 foreach( var hMidiIn in this._MIDI入力デバイスハンドルリスト ) { midiInStop( hMidiIn ); midiInReset( hMidiIn ); midiInClose( hMidiIn ); } this._MIDI入力デバイスハンドルリスト.Clear(); // コールバックデリゲートをGCの対象に戻し、デリゲートへの参照を破棄する。 lock( this._コールバック同期 ) // コールバックが実行中でないことを保証する。(不十分だが) { this._midiInProcGCh.Free(); this._midiInProcGCh = default; } } // 入力 public void ポーリングする() { // 前回のポーリングから今回までに蓄えたイベントをキャッシュへ参照渡し。 // 蓄積用リストを新しく確保する。 lock( this._コールバック同期 ) { this.入力イベントリスト = this._蓄積用入力イベントリスト; this._蓄積用入力イベントリスト = new List<InputEvent>(); } } public bool キーが押された( int deviceID, int key, out InputEvent? ev ) { ev = this.入力イベントリスト.Find( ( e ) => ( e.DeviceID == deviceID && e.Key == key && e.押された ) ); return ( null != ev ); } public bool キーが押された( int deviceID, int key ) => this.キーが押された( deviceID, key, out _ ); public bool キーが押されている( int deviceID, int key ) => false; // 常に false public bool キーが離された( int deviceID, int key, out InputEvent? ev ) { // MIDI入力では扱わない。 ev = null; return false; } public bool キーが離された( int deviceID, int key ) => this.キーが離された( deviceID, key, out _ ); public bool キーが離されている( int deviceID, int key ) => false; // 常に false // ローカル protected virtual void MIDI入力コールバック( IntPtr hMidiIn, uint wMsg, int dwInstance, int dwParam1, int dwParam2 ) { var timeStamp = this._SoundTimer.現在時刻sec; // できるだけ早く取得しておく。 if( MIM_DATA != wMsg ) return; int deviceID = this._MIDI入力デバイスハンドルリスト.FindIndex( ( h ) => ( h == hMidiIn ) ); if( 0 > deviceID ) return; byte ch = (byte)( dwParam1 & 0xFF ); byte ev = (byte)( dwParam1 & 0xF0 ); byte p1 = (byte)( ( dwParam1 >> 8 ) & 0xFF ); byte p2 = (byte)( ( dwParam1 >> 16 ) & 0xFF ); if( ( 0x90 == ev ) && ( 0 != p2 ) ) // Velocity(p2)==0 を NoteOFF 扱いとする機器があるのでそれに倣う { #region " (A) Note ON " //---------------- var ie = new InputEvent() { DeviceID = deviceID, Key = p1, 押された = true, TimeStamp = timeStamp, Control = 0, Velocity = p2, Extra = $"{ch:X2}{p1:X2}{p2:X2}", }; lock( this._コールバック同期 ) this._蓄積用入力イベントリスト.Add( ie ); //---------------- #endregion } else if( ( 0x80 == ev ) || ( 0x90 == ev && 0 == p2 ) ) // NoteOnかつVelocity(p2)==0 を NoteOFF 扱いとする機器があるのでそれに倣う { #region " (B) Note OFF " //---------------- var ie = new InputEvent() { DeviceID = deviceID, Key = p1, 押された = false, TimeStamp = timeStamp, Control = 0, Velocity = p2, Extra = $"{ch:X2}{p1:X2}{p2:X2}", }; lock( this._コールバック同期 ) this._蓄積用入力イベントリスト.Add( ie ); //---------------- #endregion } else if( 0xB0 == ev ) { #region " (C) コントロールチェンジ(フットペダル他) " //---------------- var ie = new InputEvent() { DeviceID = deviceID, Key = 255, // コントロールチェンジのキーは 255 とする。 押された = true, // 押された扱い。 TimeStamp = timeStamp, Control = p1, // コントロールチェンジの番号はこっち。 Velocity = p2, // コントロール値はこっち。 Extra = $"{ch:X2}{p1:X2}{p2:X2}", }; lock( this._コールバック同期 ) this._蓄積用入力イベントリスト.Add( ie ); //---------------- #endregion } } private List<IntPtr> _MIDI入力デバイスハンドルリスト = new List<IntPtr>(); /// <summary> /// コールバック関数で蓄積され、ポーリング時にキャッシュへコピー&クリアされる。 /// </summary> private List<InputEvent> _蓄積用入力イベントリスト = new List<InputEvent>(); /// <summary> /// すべてのMIDI入力デバイスで共通のコールバックのデリゲートとGCHandleと本体メソッド。 /// </summary> private MidiInProc _midiInProc; /// <summary> /// <see cref="MIDI入力コールバック(IntPtr, uint, int, int, int)"/> の固定用ハンドル。 /// </summary> private GCHandle _midiInProcGCh; private readonly object _コールバック同期 = new object(); private SoundTimer _SoundTimer; #region " Win32 " //----------------- private const int CALLBACK_FUNCTION = 0x00030000; private const uint MIM_DATA = 0x000003C3; private delegate void MidiInProc( IntPtr hMidiIn, uint wMsg, int dwInstance, int dwParam1, int dwParam2 ); [DllImport( "winmm.dll" )] private static extern uint midiInGetNumDevs(); [DllImport( "winmm.dll" )] private static extern uint midiInOpen( ref IntPtr phMidiIn, uint uDeviceID, MidiInProc dwCallback, IntPtr dwInstance, int fdwOpen ); [DllImport( "winmm.dll" )] private static extern uint midiInStart( IntPtr hMidiIn ); [DllImport( "winmm.dll" )] private static extern uint midiInStop( IntPtr hMidiIn ); [DllImport( "winmm.dll" )] private static extern uint midiInReset( IntPtr hMidiIn ); [DllImport( "winmm.dll" )] private static extern uint midiInClose( IntPtr hMidiIn ); public struct MIDIINCAPS { public short wMid; public short wPid; public int vDriverVersion; [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 32 )] public string szPname; public int dwSupport; } [DllImport( "winmm.dll" )] private static extern uint midiInGetDevCaps( uint uDeviceID, ref MIDIINCAPS caps, int cbMidiInCaps ); //----------------- #endregion } } <|start_filename|>SSTFEditor/譜面.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Windows.Forms; using FDK; using SSTF=SSTFormat.v004; namespace SSTFEditor { class 譜面 : IDisposable { // プロパティ /// <summary> /// 譜面に表示されるスコア。 /// </summary> public SSTF.スコア スコア { get; protected set; } public readonly Size チップサイズpx = new Size( 30, 8 ); public int 譜面表示下辺の譜面内絶対位置grid { get; set; } public int カレントラインの譜面内絶対位置grid { get => ( this.譜面表示下辺の譜面内絶対位置grid + ( 230 * this.Form.GRID_PER_PIXEL ) ); // 譜面拡大率によらず、大体下辺から -230 pixel くらいで。 } /// <summary> /// 現在の全小節の高さを計算してグリッド単位で返す。 /// </summary> public int 全小節の高さgrid { get { int 高さgrid = 0; int 最大小節番号 = this.スコア.最大小節番号を返す(); for( int i = 0; i <= 最大小節番号; i++ ) 高さgrid += this.小節長をグリッドで返す( i ); return 高さgrid; } } public int レーンの合計幅px { get { int レーン数 = Enum.GetValues( typeof( 編集レーン種別 ) ).Length; return ( レーン数 - 1 ) * this.チップサイズpx.Width; // -1 は Unknown をカウントしないため } } public int 譜面表示下辺に位置する小節番号 { get => this.譜面内絶対位置gridに位置する小節の情報を返す( this.譜面表示下辺の譜面内絶対位置grid ).小節番号; } public int カレントラインに位置する小節番号 { get => this.譜面内絶対位置gridに位置する小節の情報を返す( this.カレントラインの譜面内絶対位置grid ).小節番号; } /// <summary> /// チップの色。 /// </summary> protected readonly Dictionary<SSTF.チップ種別, Color> チップto色 = new Dictionary<SSTF.チップ種別, Color>() { #region " *** " //----------------- { SSTF.チップ種別.BPM, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, { SSTF.チップ種別.LeftCrash, Color.FromArgb( チップ背景色透明度, Color.WhiteSmoke ) }, { SSTF.チップ種別.LeftCymbal_Mute, Color.FromArgb( チップ背景色透明度, Color.Gray ) }, { SSTF.チップ種別.HiHat_Close, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, { SSTF.チップ種別.HiHat_Foot, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, { SSTF.チップ種別.HiHat_HalfOpen, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, { SSTF.チップ種別.HiHat_Open, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, { SSTF.チップ種別.Snare, Color.FromArgb( チップ背景色透明度, Color.Orange ) }, { SSTF.チップ種別.Snare_ClosedRim, Color.FromArgb( チップ背景色透明度, Color.OrangeRed ) }, { SSTF.チップ種別.Snare_Ghost, Color.FromArgb( チップ背景色透明度, Color.DeepPink ) }, { SSTF.チップ種別.Snare_OpenRim, Color.FromArgb( チップ背景色透明度, Color.Orange ) }, { SSTF.チップ種別.Tom1, Color.FromArgb( チップ背景色透明度, Color.Lime ) }, { SSTF.チップ種別.Tom1_Rim, Color.FromArgb( チップ背景色透明度, Color.Lime ) }, { SSTF.チップ種別.Bass, Color.FromArgb( チップ背景色透明度, Color.Gainsboro ) }, { SSTF.チップ種別.Tom2, Color.FromArgb( チップ背景色透明度, Color.Red ) }, { SSTF.チップ種別.Tom2_Rim, Color.FromArgb( チップ背景色透明度, Color.Red ) }, { SSTF.チップ種別.Tom3, Color.FromArgb( チップ背景色透明度, Color.Magenta ) }, { SSTF.チップ種別.Tom3_Rim, Color.FromArgb( チップ背景色透明度, Color.Magenta ) }, { SSTF.チップ種別.RightCrash, Color.FromArgb( チップ背景色透明度, Color.WhiteSmoke ) }, { SSTF.チップ種別.RightCymbal_Mute, Color.FromArgb( チップ背景色透明度, Color.Gray ) }, { SSTF.チップ種別.Ride, Color.FromArgb( チップ背景色透明度, Color.WhiteSmoke ) }, { SSTF.チップ種別.Ride_Cup, Color.FromArgb( チップ背景色透明度, Color.WhiteSmoke ) }, { SSTF.チップ種別.China, Color.FromArgb( チップ背景色透明度, Color.Tan ) }, { SSTF.チップ種別.Splash, Color.FromArgb( チップ背景色透明度, Color.LightGray ) }, { SSTF.チップ種別.背景動画, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, { SSTF.チップ種別.BGM, Color.FromArgb( チップ背景色透明度, Color.SkyBlue ) }, //----------------- #endregion }; // 生成と終了 public 譜面( メインフォーム form ) { this.Form = form; this.スコア = new SSTF.スコア(); this.譜面表示下辺の譜面内絶対位置grid = 0; // 最初は10小節ほど用意しておく → 10小節目の先頭に Unknown チップを置くことで実現 this.スコア.チップリスト.Add( new 描画用チップ() { チップ種別 = SSTF.チップ種別.Unknown, 小節番号 = 9, // 0から数えて10番目の小節 = 009 小節解像度 = 1, 小節内位置 = 0, 譜面内絶対位置grid = 9 * this.Form.GRID_PER_PART, // 小節009の先頭位置 } ); } public virtual void Dispose() { this.スコア = null; this.小節番号文字フォント?.Dispose(); this.小節番号文字フォント = null; this.小節番号文字ブラシ?.Dispose(); this.小節番号文字ブラシ = null; this.小節番号文字フォーマット?.Dispose(); this.小節番号文字フォーマット = null; this.ガイド線ペン?.Dispose(); this.ガイド線ペン = null; this.小節線ペン?.Dispose(); this.小節線ペン = null; this.拍線ペン?.Dispose(); this.拍線ペン = null; this.レーン区分線ペン?.Dispose(); this.レーン区分線ペン = null; this.レーン区分線太ペン?.Dispose(); this.レーン区分線太ペン = null; this.カレントラインペン?.Dispose(); this.カレントラインペン = null; this.レーン名文字フォント?.Dispose(); this.レーン名文字フォント = null; this.レーン名文字ブラシ?.Dispose(); this.レーン名文字ブラシ = null; this.レーン名文字影ブラシ?.Dispose(); this.レーン名文字影ブラシ = null; this.レーン名文字フォーマット?.Dispose(); this.レーン名文字フォーマット = null; this.チップの太枠ペン?.Dispose(); this.チップの太枠ペン = null; this.チップ内文字列フォーマット?.Dispose(); this.チップ内文字列フォーマット = null; this.チップ内文字列フォント?.Dispose(); this.チップ内文字列フォント = null; this.白丸白バツペン?.Dispose(); this.白丸白バツペン = null; this.Form = null; } public void コンフィグを譜面に反映する( Config config ) { // RideLeft, ChinaLeft, SplashLeft に従ってレーンの位置を決定する。 this.チップ種別to編集レーン[ SSTF.チップ種別.Ride ] = ( config.RideLeft ) ? 編集レーン種別.左シンバル : 編集レーン種別.右シンバル; this.チップ種別to編集レーン[ SSTF.チップ種別.Ride_Cup ] = ( config.RideLeft ) ? 編集レーン種別.左シンバル : 編集レーン種別.右シンバル; this.チップ種別to編集レーン[ SSTF.チップ種別.China ] = ( config.ChinaLeft ) ? 編集レーン種別.左シンバル : 編集レーン種別.右シンバル; this.チップ種別to編集レーン[ SSTF.チップ種別.Splash ] = ( config.SplashLeft ) ? 編集レーン種別.左シンバル : 編集レーン種別.右シンバル; } // ファイル入出力 public void 曲データファイルを読み込む( string ファイル名 ) { // 解放 this.スコア = null; // 読み込み this.スコア = SSTF.スコア.ファイルから生成する( ファイル名 ); // 後処理 #region " 小節線・拍線・Unknown チップをすべて削除する。" //----------------- this.スコア.チップリスト.RemoveAll( ( chip ) => ( chip.チップ種別 == SSTF.チップ種別.小節線 || chip.チップ種別 == SSTF.チップ種別.拍線 || chip.チップ種別 == SSTF.チップ種別.Unknown ) ); //----------------- #endregion #region " チップリストのすべてのチップを、描画用チップに変換する。" //---------------- { // バックアップを取って、 var 元のチップリスト = new SSTF.チップ[ this.スコア.チップリスト.Count ]; for( int i = 0; i < this.スコア.チップリスト.Count; i++ ) 元のチップリスト[ i ] = this.スコア.チップリスト[ i ]; // クリアして、 this.スコア.チップリスト.Clear(); // 再構築。 for( int i = 0; i < 元のチップリスト.Length; i++ ) this.スコア.チップリスト.Add( new 描画用チップ( 元のチップリスト[ i ] ) ); } //---------------- #endregion #region " 全チップに対して「譜面内絶対位置grid」を設定する。" //----------------- { int チップが存在する小節の先頭grid = 0; int 現在の小節番号 = 0; foreach( 描画用チップ chip in this.スコア.チップリスト ) { // チップの小節番号が現在の小節番号よりも大きい場合、チップが存在する小節に至るまで、「チップが存在する小節の先頭grid」を更新する。 while( 現在の小節番号 < chip.小節番号 ) { double 現在の小節の小節長倍率 = this.スコア.小節長倍率を取得する( 現在の小節番号 ); チップが存在する小節の先頭grid += (int) ( this.Form.GRID_PER_PART * 現在の小節の小節長倍率 ); 現在の小節番号++; // 現在の小節番号 が chip.小節番号 に追いつくまでループする。 } chip.譜面内絶対位置grid = チップが存在する小節の先頭grid + ( chip.小節内位置 * this.小節長をグリッドで返す( chip.小節番号 ) ) / chip.小節解像度; } } //----------------- #endregion } public void SSTFファイルを書き出す( string ファイル名, string ヘッダ行 ) { using( var fs = new FileStream( ファイル名, FileMode.Create, FileAccess.Write ) ) SSTF.スコア.SSTF.出力する( this.スコア, fs, $"{ヘッダ行}{Environment.NewLine}" ); } public void SSTFoverDTXファイルを書き出す( string ファイル名, string ヘッダ行 ) { using( var fs = new FileStream( ファイル名, FileMode.Create, FileAccess.Write ) ) SSTF.スコア.SSTFoverDTX.出力する( this.スコア, fs, $"{ヘッダ行}{Environment.NewLine}" ); } // 描画 /// <summary> /// コントロールに譜面を描画する。 /// </summary> /// <param name="g">描画に使用するグラフィックス</param> /// <param name="panel">描画先のコントロール</param> public void 描画する( Graphics g, Control panel ) { #region " panel のレーン背景画像が未作成なら作成する。" //----------------- if( null == this.譜面パネル背景 ) { this.譜面パネル背景 = new Bitmap( this.レーンの合計幅px, 1 ); using var graphics = Graphics.FromImage( this.譜面パネル背景 ); foreach( var laneProp in this.レーン属性.Values ) { using( var brush = new SolidBrush( laneProp.背景色 ) ) graphics.FillRectangle( brush, laneProp.位置 * this.チップサイズpx.Width, 0, this.チップサイズpx.Width, 1 ); } panel.Width = this.レーンの合計幅px; panel.BackgroundImage = this.譜面パネル背景; panel.BackgroundImageLayout = ImageLayout.Tile; } //----------------- #endregion int 小節先頭の譜面内絶対位置grid = 0; int パネル下辺の譜面内絶対位置grid = this.譜面表示下辺の譜面内絶対位置grid; int パネル上辺の譜面内絶対位置grid = パネル下辺の譜面内絶対位置grid + ( panel.ClientSize.Height * this.Form.GRID_PER_PIXEL ); #region " 小節番号・ガイド線・拍線・レーン区分線・小節線を描画。" //----------------- { int 最大小節番号 = this.スコア.最大小節番号を返す(); for( int 小節番号 = 0; 小節番号 <= 最大小節番号; 小節番号++ ) { int 小節長grid = this.小節長をグリッドで返す( 小節番号 ); int 次の小節の先頭位置grid = 小節先頭の譜面内絶対位置grid + 小節長grid; Rectangle 小節の描画領域px; // クリッピングと小節の描画領域の取得。小節が描画領域上端を超えたら終了。 #region " (A) 小節の描画領域が、パネルの領域外(下)にある場合。→ この小節は無視して次の小節へ。" //----------------- if( 次の小節の先頭位置grid < パネル下辺の譜面内絶対位置grid ) { 小節先頭の譜面内絶対位置grid = 次の小節の先頭位置grid; continue; } //----------------- #endregion #region " (B) 小節の描画領域が、パネルの領域外(上)にある場合。→ ここで描画終了。" //----------------- else if( 小節先頭の譜面内絶対位置grid >= パネル上辺の譜面内絶対位置grid ) { break; } //----------------- #endregion #region " (C) 小節の描画領域が、パネル内にすべて収まっている場合。" //----------------- else if( ( 小節先頭の譜面内絶対位置grid >= パネル下辺の譜面内絶対位置grid ) && ( 次の小節の先頭位置grid < パネル上辺の譜面内絶対位置grid ) ) { 小節の描画領域px = new Rectangle() { X = 0, Y = ( パネル上辺の譜面内絶対位置grid - 次の小節の先頭位置grid ) / this.Form.GRID_PER_PIXEL, Width = panel.ClientSize.Width, Height = ( 次の小節の先頭位置grid - 小節先頭の譜面内絶対位置grid ) / this.Form.GRID_PER_PIXEL, }; } //----------------- #endregion #region " (D) 小節の描画領域が、パネルをすべて包み込んでいる場合。" //----------------- else if( ( 小節先頭の譜面内絶対位置grid < パネル下辺の譜面内絶対位置grid ) && ( 次の小節の先頭位置grid >= パネル上辺の譜面内絶対位置grid ) ) { 小節の描画領域px = new Rectangle() { X = 0, Y = ( パネル上辺の譜面内絶対位置grid - 次の小節の先頭位置grid ) / this.Form.GRID_PER_PIXEL, Width = panel.ClientSize.Width, Height = ( 次の小節の先頭位置grid - 小節先頭の譜面内絶対位置grid ) / this.Form.GRID_PER_PIXEL, }; } //----------------- #endregion #region " (E) 小節の描画領域が、パネルの下側にはみだしている場合。" //----------------- else if( 小節先頭の譜面内絶対位置grid < パネル下辺の譜面内絶対位置grid ) { 小節の描画領域px = new Rectangle() { X = 0, Y = ( パネル上辺の譜面内絶対位置grid - 次の小節の先頭位置grid ) / this.Form.GRID_PER_PIXEL, Width = panel.ClientSize.Width, Height = ( 次の小節の先頭位置grid - 小節先頭の譜面内絶対位置grid ) / this.Form.GRID_PER_PIXEL, }; } //----------------- #endregion #region " (F) 小節の描画領域が、パネルの上側にはみだしている場合。" //----------------- else { 小節の描画領域px = new Rectangle() { X = 0, Y = ( パネル上辺の譜面内絶対位置grid - 次の小節の先頭位置grid ) / this.Form.GRID_PER_PIXEL, Width = panel.ClientSize.Width, Height = ( 次の小節の先頭位置grid - 小節先頭の譜面内絶対位置grid ) / this.Form.GRID_PER_PIXEL, }; } //----------------- #endregion #region " 小節番号を描画。" //----------------- g.DrawString( 小節番号.ToString( "000" ), this.小節番号文字フォント, this.小節番号文字ブラシ, 小節の描画領域px, this.小節番号文字フォーマット ); //----------------- #endregion #region " ガイド線を描画。" //----------------- this.譜面に定間隔で線を描画する( g, 小節番号, 小節の描画領域px, this.ガイド間隔grid, this.ガイド線ペン ); //----------------- #endregion #region " 拍線を描画。" //----------------- this.譜面に定間隔で線を描画する( g, 小節番号, 小節の描画領域px, this.Form.GRID_PER_PART / 4, this.拍線ペン ); //----------------- #endregion #region " レーン区分線を描画。" //----------------- { int x = 0; int num = Enum.GetValues( typeof( 編集レーン種別 ) ).Length - 1; // -1 は Unknown の分 for( int i = 0; i < num; i++ ) { x += this.チップサイズpx.Width; if( x >= 小節の描画領域px.Width ) x = 小節の描画領域px.Width - 1; g.DrawLine( ( i == 0 || i == num - 3 ) ? this.レーン区分線太ペン : this.レーン区分線ペン, x, 小節の描画領域px.Top, x, 小節の描画領域px.Bottom ); } } //----------------- #endregion #region " 小節線を描画。" //----------------- this.譜面に定間隔で線を描画する( g, 小節番号, 小節の描画領域px, 小節長grid, this.小節線ペン ); //----------------- #endregion // 次の小節へ。 小節先頭の譜面内絶対位置grid = 次の小節の先頭位置grid; } } //----------------- #endregion #region " チップを描画。" //----------------- var チップ描画領域 = new Rectangle(); foreach( 描画用チップ chip in this.スコア.チップリスト ) { #region " クリッピングと終了判定。" //----------------- if( chip.チップ種別 == SSTF.チップ種別.Unknown ) continue; // 描画対象外 if( 0 != chip.枠外レーン数 ) continue; // 描画範囲外 if( chip.譜面内絶対位置grid < パネル下辺の譜面内絶対位置grid ) continue; // 描画範囲外 if( chip.譜面内絶対位置grid >= パネル上辺の譜面内絶対位置grid ) break; // 描画範囲外(ここで終了) //----------------- #endregion var チップの編集レーン種別 = this.チップ種別to編集レーン[ chip.チップ種別 ]; if( チップの編集レーン種別 == 編集レーン種別.Unknown ) continue; int レーン位置 = this.レーン属性[ チップの編集レーン種別 ].位置; チップ描画領域.X = レーン位置 * this.チップサイズpx.Width; チップ描画領域.Y = panel.ClientSize.Height - ( chip.譜面内絶対位置grid - this.譜面表示下辺の譜面内絶対位置grid ) / this.Form.GRID_PER_PIXEL - this.チップサイズpx.Height; チップ描画領域.Width = this.チップサイズpx.Width; チップ描画領域.Height = this.チップサイズpx.Height; this.チップを指定領域へ描画する( g, chip, チップ描画領域 ); // 選択中なら太枠を付与。 if( chip.ドラッグ操作により選択中である || chip.選択が確定している ) this.チップの太枠を指定領域へ描画する( g, チップ描画領域 ); } //----------------- #endregion #region " レーン名を描画。" //----------------- var レーン名描画領域上側 = new Rectangle( 0, 0, panel.Width, 10 ); var レーン名描画領域下側 = new Rectangle( 0, 10, panel.Width, 譜面.レーン名表示高さpx ); // レーン名の背景のグラデーションを描画。 using( var brush = new LinearGradientBrush( レーン名描画領域下側, Color.FromArgb( 255, 50, 155, 50 ), Color.FromArgb( 0, 0, 255, 0 ), LinearGradientMode.Vertical ) ) g.FillRectangle( brush, レーン名描画領域下側 ); using( var brush = new LinearGradientBrush( レーン名描画領域上側, Color.FromArgb( 255, 0, 100, 0 ), Color.FromArgb( 255, 50, 155, 50 ), LinearGradientMode.Vertical ) ) g.FillRectangle( brush, レーン名描画領域上側 ); // 各レーン名を描画。 foreach( var laneProp in this.レーン属性.Values ) { var レーン名描画領域 = new Rectangle( x: レーン名描画領域下側.X + ( laneProp.位置 * this.チップサイズpx.Width ) + 2, y: レーン名描画領域下側.Y + 2, width: this.チップサイズpx.Width, height: 24 ); g.DrawString( laneProp.名前, this.レーン名文字フォント, this.レーン名文字影ブラシ, レーン名描画領域, this.レーン名文字フォーマット ); レーン名描画領域.X -= 2; レーン名描画領域.Y -= 2; g.DrawString( laneProp.名前, this.レーン名文字フォント, this.レーン名文字ブラシ, レーン名描画領域, this.レーン名文字フォーマット ); } //----------------- #endregion #region " カレントラインを描画。" //----------------- float y = panel.Size.Height - ( (float) ( this.カレントラインの譜面内絶対位置grid - this.譜面表示下辺の譜面内絶対位置grid ) / (float) this.Form.GRID_PER_PIXEL ); g.DrawLine( this.カレントラインペン, 0.0f, y, (float) ( panel.Size.Width - 1 ), y ); //----------------- #endregion } public void チップを指定領域へ描画する( Graphics g, 描画用チップ chip, Rectangle チップ描画領域 ) => this.チップを指定領域へ描画する( g, chip.チップ種別, chip.音量, チップ描画領域, chip.チップ内文字列 ); public void チップを指定領域へ描画する( Graphics g, SSTF.チップ種別 チップ種別, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { switch( チップ種別 ) { case SSTF.チップ種別.BPM: case SSTF.チップ種別.LeftCrash: case SSTF.チップ種別.HiHat_Close: case SSTF.チップ種別.Snare: case SSTF.チップ種別.Tom1: case SSTF.チップ種別.Bass: case SSTF.チップ種別.Tom2: case SSTF.チップ種別.Tom3: case SSTF.チップ種別.RightCrash: case SSTF.チップ種別.China: case SSTF.チップ種別.Splash: case SSTF.チップ種別.背景動画: case SSTF.チップ種別.BGM: this.チップを描画する_通常( g, チップ種別, 音量, チップ描画領域, チップ内文字列 ); break; case SSTF.チップ種別.Snare_Ghost: this.チップを描画する_小丸( g, チップ種別, 音量, チップ描画領域, チップ内文字列 ); break; case SSTF.チップ種別.Ride: this.チップを描画する_幅狭( g, チップ種別, 音量, チップ描画領域, チップ内文字列 ); break; case SSTF.チップ種別.Snare_OpenRim: case SSTF.チップ種別.HiHat_Open: this.チップを描画する_幅狭白丸( g, チップ種別, 音量, チップ描画領域, チップ内文字列 ); break; case SSTF.チップ種別.HiHat_HalfOpen: case SSTF.チップ種別.Ride_Cup: this.チップを描画する_幅狭白狭丸( g, チップ種別, 音量, チップ描画領域, チップ内文字列 ); break; case SSTF.チップ種別.HiHat_Foot: case SSTF.チップ種別.Snare_ClosedRim: case SSTF.チップ種別.Tom1_Rim: case SSTF.チップ種別.Tom2_Rim: case SSTF.チップ種別.Tom3_Rim: case SSTF.チップ種別.LeftCymbal_Mute: case SSTF.チップ種別.RightCymbal_Mute: this.チップを描画する_幅狭白バツ( g, チップ種別, 音量, チップ描画領域, チップ内文字列 ); break; } } public void チップの太枠を指定領域へ描画する( Graphics g, Rectangle チップ描画領域 ) { g.DrawRectangle( this.チップの太枠ペン, チップ描画領域 ); } // 譜面操作 public void 現在のガイド間隔を変更する( int n分 ) { this.ガイド間隔grid = ( n分 == 0 ) ? 1 : ( this.Form.GRID_PER_PART / n分 ); } public void チップを配置または置換する( 編集レーン種別 e編集レーン, SSTF.チップ種別 eチップ, int 譜面内絶対位置grid, string チップ文字列, int 音量, double BPM, bool 選択確定中 ) { try { this.Form.UndoRedo管理.トランザクション記録を開始する(); // 配置位置にチップがあれば削除する。 this.チップを削除する( e編集レーン, 譜面内絶対位置grid ); // そこにチップがなければ何もしない。 // 新しいチップを作成し配置する。 var 小節情報 = this.譜面内絶対位置gridに位置する小節の情報を返す( 譜面内絶対位置grid ); int 小節の長さgrid = this.小節長をグリッドで返す( 小節情報.小節番号 ); var chip = new 描画用チップ() { 選択が確定している = 選択確定中, BPM = BPM, 発声時刻sec = 0, // SSTFEditorでは使わない チップ種別 = eチップ, 音量 = 音量, 小節解像度 = 小節の長さgrid, 小節内位置 = 譜面内絶対位置grid - 小節情報.小節の先頭位置grid, 小節番号 = 小節情報.小節番号, 譜面内絶対位置grid = 譜面内絶対位置grid, チップ内文字列 = チップ文字列, }; // チップを譜面に追加。 var 変更前チップ = new 描画用チップ( chip ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this.スコア.チップリスト.Remove( 変更対象 ); this.Form.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); this.スコア.チップリスト.Add( 変更対象 ); this.スコア.チップリスト.Sort(); this.Form.未保存である = true; }, 変更対象: chip, 変更前の値: 変更前チップ, 変更後の値: null ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); // 配置した小節が現状最後の小節だったら、後ろに小節を4つ追加する。 if( chip.小節番号 == this.スコア.最大小節番号を返す() ) this.最後の小節の後ろに小節を4つ追加する(); } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.Form.未保存である = true; } } public void チップを削除する( 編集レーン種別 e編集レーン, int 譜面内絶対位置grid ) { var 削除チップ = (描画用チップ) ( from chip in this.スコア.チップリスト where ( ( this.チップ種別to編集レーン[ chip.チップ種別 ] == e編集レーン ) && ( ( (描画用チップ)chip ).譜面内絶対位置grid == 譜面内絶対位置grid ) ) select chip ).FirstOrDefault(); // チップが重なってたとしても、削除するのはひとつだけ。 if( null != 削除チップ ) { // UndoRedo セルを登録。 var 変更前チップ = new 描画用チップ( 削除チップ ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); this.スコア.チップリスト.Add( 変更対象 ); this.スコア.チップリスト.Sort(); this.Form.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this.スコア.チップリスト.Remove( 変更対象 ); this.Form.未保存である = true; }, 変更対象: 削除チップ, 変更前の値: 変更前チップ, 変更後の値: null ); this.Form.UndoRedo管理.セルを追加する( cell ); // 削除する。 cell.Redoを実行する(); // 削除完了。 this.Form.UndoRedo用GUIのEnabledを設定する(); } } public void 最後の小節の後ろに小節を4つ追加する() { int 最大小節番号 = this.スコア.最大小節番号を返す(); // 最終小節の小節先頭位置grid と 小節長倍率 を取得する。 int 小節先頭位置grid = this.小節先頭の譜面内絶対位置gridを返す( 最大小節番号 ); int 小節の長さgrid = this.小節長をグリッドで返す( 最大小節番号 ); double 最終小節の小節長倍率 = this.スコア.小節長倍率を取得する( 最大小節番号 ); // ダミーで置いた Unknown チップがあれば削除する。 this.チップを削除する( 編集レーン種別.Unknown, 小節先頭位置grid ); // 新しくダミーの Unknown チップを、最終小節番号の控え+4の小節の先頭に置く。 var dummyChip = new 描画用チップ() { チップ種別 = SSTF.チップ種別.Unknown, 小節番号 = 最大小節番号 + 4, 小節解像度 = 1, 小節内位置 = 0, 譜面内絶対位置grid = 小節先頭位置grid + 小節の長さgrid + ( this.Form.GRID_PER_PART * 3 ), }; var 変更後チップ = new 描画用チップ( dummyChip ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 小節長倍率, 任意2 ) => { this.スコア.チップリスト.Remove( 変更対象 ); for( int i = 0; i < 4; i++ ) this.スコア.小節長倍率リスト.RemoveAt( 変更後.小節番号 - 3 ); }, Redoアクション: ( 変更対象, 変更前, 変更後, 小節長倍率, 任意2 ) => { 変更対象.CopyFrom( 変更後 ); this.スコア.チップリスト.Add( 変更対象 ); this.スコア.チップリスト.Sort(); if( (double)小節長倍率 != 1.0 ) // 増設した4つの小節の小節長倍率を、最終小節の小節長倍率と同じにする。1.0 の場合は何もしない。 { for( int i = 0; i < 4; i++ ) this.スコア.小節長倍率を設定する( 変更後.小節番号 - i, (double)小節長倍率 ); } this.Form.未保存である = true; }, 変更対象: dummyChip, 変更前の値: null, 変更後の値: 変更後チップ, 任意1: 最終小節の小節長倍率, 任意2: null ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } // 各種変換 /// <summary> /// チップの属するレーンを定義する。 /// </summary> /// <remarks> /// <see cref="編集モード"/> のコンストラクタでも参照されるので、登録ルールに注意すること。 /// >登録ルール → 同一レーンについて、最初によく使うチップを、2番目にトグルで2番目によく使うチップを登録する。 /// </remarks> public readonly Dictionary<SSTF.チップ種別, 編集レーン種別> チップ種別to編集レーン = new Dictionary<SSTF.チップ種別, 編集レーン種別>() { #region " *** " //----------------- { SSTF.チップ種別.BPM, 編集レーン種別.BPM }, { SSTF.チップ種別.LeftCrash, 編集レーン種別.左シンバル }, { SSTF.チップ種別.HiHat_Close, 編集レーン種別.ハイハット }, { SSTF.チップ種別.HiHat_Open, 編集レーン種別.ハイハット }, { SSTF.チップ種別.HiHat_HalfOpen, 編集レーン種別.ハイハット }, { SSTF.チップ種別.HiHat_Foot, 編集レーン種別.ハイハット }, { SSTF.チップ種別.Snare, 編集レーン種別.スネア }, { SSTF.チップ種別.Snare_Ghost, 編集レーン種別.スネア }, { SSTF.チップ種別.Snare_ClosedRim, 編集レーン種別.スネア }, { SSTF.チップ種別.Snare_OpenRim, 編集レーン種別.スネア }, { SSTF.チップ種別.Tom1, 編集レーン種別.ハイタム }, { SSTF.チップ種別.Tom1_Rim, 編集レーン種別.ハイタム }, { SSTF.チップ種別.Bass, 編集レーン種別.バス }, { SSTF.チップ種別.Tom2, 編集レーン種別.ロータム }, { SSTF.チップ種別.Tom2_Rim, 編集レーン種別.ロータム }, { SSTF.チップ種別.Tom3, 編集レーン種別.フロアタム }, { SSTF.チップ種別.Tom3_Rim, 編集レーン種別.フロアタム }, { SSTF.チップ種別.RightCrash, 編集レーン種別.右シンバル }, { SSTF.チップ種別.Ride, 編集レーン種別.右シンバル }, // 右側で固定とする { SSTF.チップ種別.Ride_Cup, 編集レーン種別.右シンバル }, // { SSTF.チップ種別.China, 編集レーン種別.右シンバル }, // { SSTF.チップ種別.Splash, 編集レーン種別.右シンバル }, // { SSTF.チップ種別.LeftCymbal_Mute, 編集レーン種別.左シンバル }, { SSTF.チップ種別.RightCymbal_Mute, 編集レーン種別.右シンバル }, { SSTF.チップ種別.背景動画, 編集レーン種別.BGV }, { SSTF.チップ種別.BGM, 編集レーン種別.BGM }, { SSTF.チップ種別.小節線, 編集レーン種別.Unknown }, { SSTF.チップ種別.拍線, 編集レーン種別.Unknown }, { SSTF.チップ種別.小節の先頭, 編集レーン種別.Unknown }, { SSTF.チップ種別.小節メモ, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE1, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE2, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE3, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE4, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE5, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE6, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE7, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE8, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE9, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE10, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE11, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE12, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE13, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE14, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE15, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE16, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE17, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE18, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE19, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE20, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE21, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE22, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE23, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE24, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE25, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE26, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE27, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE28, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE29, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE30, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE31, 編集レーン種別.Unknown }, { SSTF.チップ種別.SE32, 編集レーン種別.Unknown }, { SSTF.チップ種別.GuitarAuto, 編集レーン種別.Unknown }, { SSTF.チップ種別.BassAuto, 編集レーン種別.Unknown }, { SSTF.チップ種別.Unknown, 編集レーン種別.Unknown }, //----------------- #endregion }; /// <summary> /// レーンの表示情報。 /// </summary> /// <remarks> /// <see cref="編集レーン種別.Unknown"/> の指定は不可。 /// </remarks> public readonly Dictionary<編集レーン種別, (int 位置, string 名前, Color 背景色, bool 区分線が太線)> レーン属性 = new Dictionary<編集レーン種別, (int 位置, string 名前, Color 背景色, bool 区分線が太線)>() { { 編集レーン種別.BPM, (位置: 0, 名前: "BPM", 背景色: Color.FromArgb( レーン背景色透明度, Color.SkyBlue ), 区分線が太線: true ) }, { 編集レーン種別.左シンバル, (位置: 1, 名前: "LC", 背景色: Color.FromArgb( レーン背景色透明度, Color.WhiteSmoke), 区分線が太線: false) }, { 編集レーン種別.ハイハット, (位置: 2, 名前: "HH", 背景色: Color.FromArgb( レーン背景色透明度, Color.SkyBlue), 区分線が太線: false) }, { 編集レーン種別.スネア, (位置: 3, 名前: "SD", 背景色: Color.FromArgb( レーン背景色透明度, Color.Orange), 区分線が太線: false) }, { 編集レーン種別.ハイタム, (位置: 4, 名前: "HT", 背景色: Color.FromArgb( レーン背景色透明度, Color.Lime), 区分線が太線: false) }, { 編集レーン種別.バス, (位置: 5, 名前: "BD", 背景色: Color.FromArgb( レーン背景色透明度, Color.Gainsboro), 区分線が太線: false) }, { 編集レーン種別.ロータム, (位置: 6, 名前: "LT", 背景色: Color.FromArgb( レーン背景色透明度, Color.Red), 区分線が太線: false) }, { 編集レーン種別.フロアタム, (位置: 7, 名前: "FT", 背景色: Color.FromArgb( レーン背景色透明度, Color.Magenta), 区分線が太線: false) }, { 編集レーン種別.右シンバル, (位置: 8, 名前: "RC", 背景色: Color.FromArgb( レーン背景色透明度, Color.WhiteSmoke), 区分線が太線: true ) }, { 編集レーン種別.BGV, (位置: 9, 名前: "BGV", 背景色: Color.FromArgb( レーン背景色透明度, Color.SkyBlue), 区分線が太線: false) }, { 編集レーン種別.BGM, (位置: 10, 名前: "BGM", 背景色: Color.FromArgb( レーン背景色透明度, Color.SkyBlue), 区分線が太線: false) }, }; // 小節番号 → grid public int 小節先頭の譜面内絶対位置gridを返す( int 小節番号 ) { if( 0 > 小節番号 ) throw new ArgumentOutOfRangeException( "小節番号に負数が指定されました。" ); int 高さgrid = 0; for( int i = 0; i < 小節番号; i++ ) 高さgrid += this.小節長をグリッドで返す( i ); return 高さgrid; } // grid → 小節番号, grid public (int 小節番号, int 小節の先頭位置grid) 譜面内絶対位置gridに位置する小節の情報を返す( int 譜面内絶対位置grid ) { if( 0 > 譜面内絶対位置grid ) throw new ArgumentOutOfRangeException( "位置に負数が指定されました。" ); var result = (小節番号: 0, 小節の先頭位置grid: -1); int 現在の小節長合計grid = 0; int 現在の小節番号 = 0; while( true ) // 最大小節番号を超えてどこまでもチェック。 { int 以前の値 = 現在の小節長合計grid; 現在の小節長合計grid += this.小節長をグリッドで返す( 現在の小節番号 ); if( 譜面内絶対位置grid < 現在の小節長合計grid ) { result.小節の先頭位置grid = 以前の値; result.小節番号 = 現在の小節番号; break; } 現在の小節番号++; } return result; } // Xpx → 編集レーン種別 public 編集レーン種別 譜面パネル内X座標pxにある編集レーンを返す( int 譜面パネル内X座標px ) { int レーン位置 = this.譜面パネル内X座標pxにある表示レーン位置を返す( 譜面パネル内X座標px ); var kvp = this.レーン属性.FirstOrDefault( ( kvp ) => kvp.Value.位置 == レーン位置 ); return ( kvp.Value.名前 != null ) ? kvp.Key : 編集レーン種別.Unknown; } // Xpx → 表示レーン位置 public int 譜面パネル内X座標pxにある表示レーン位置を返す( int 譜面パネル内X座標px ) { return 譜面パネル内X座標px / this.チップサイズpx.Width; } // 編集レーン → 表示レーン位置 public int 編集レーンの表示レーン位置を返す( 編集レーン種別 lane ) { return ( this.レーン属性.ContainsKey( lane ) ) ? this.レーン属性[ lane ].位置 : -1; } // 編集レーン → Xpx public int 編集レーンのX座標pxを返す( 編集レーン種別 lane ) { int レーン位置 = this.編集レーンの表示レーン位置を返す( lane ); return ( 0 <= レーン位置 ) ? レーン位置 * this.チップサイズpx.Width : 0; } // 表示レーン位置 → 編集レーン種別 public 編集レーン種別 表示レーン位置にある編集レーンを返す( int 表示レーン位置 ) { foreach( var kvp in this.レーン属性 ) { if( kvp.Value.位置 == 表示レーン位置 ) return kvp.Key; } return 編集レーン種別.Unknown; } // Ypx → 小節番号 public int 譜面パネル内Y座標pxにおける小節番号を返す( int 譜面パネル内Y座標px ) { return this.譜面パネル内Y座標pxにおける小節番号とその小節の譜面内絶対位置gridを返す( 譜面パネル内Y座標px ).小節番号; } // Ypx → grid public int 譜面パネル内Y座標pxにおける小節の譜面内絶対位置gridを返す( int 譜面パネル内Y座標px ) { return this.譜面パネル内Y座標pxにおける小節番号とその小節の譜面内絶対位置gridを返す( 譜面パネル内Y座標px ).小節の譜面内絶対位置grid; } // Ypx → 小節番号, grid public (int 小節番号, int 小節の譜面内絶対位置grid) 譜面パネル内Y座標pxにおける小節番号とその小節の譜面内絶対位置gridを返す( int 譜面パネル内Y座標px ) { int 譜面パネル内Y座標に対応する譜面内絶対位置grid = this.譜面表示下辺の譜面内絶対位置grid + ( this.Form.譜面パネルサイズ.Height - 譜面パネル内Y座標px ) * this.Form.GRID_PER_PIXEL; if( 譜面パネル内Y座標に対応する譜面内絶対位置grid < 0 ) { return (小節番号: -1, 小節の譜面内絶対位置grid: -1); } int 次の小節の先頭までの長さgrid = 0; int i = 0; while( true ) // 最大小節番号を超えてどこまでもチェック。 { double 小節長倍率 = this.スコア.小節長倍率を取得する( i ); int 現在の小節の先頭までの長さgrid = 次の小節の先頭までの長さgrid; 次の小節の先頭までの長さgrid += (int) ( this.Form.GRID_PER_PART * 小節長倍率 ); if( 譜面パネル内Y座標に対応する譜面内絶対位置grid < 次の小節の先頭までの長さgrid ) { return (小節番号: i, 小節の譜面内絶対位置grid: 現在の小節の先頭までの長さgrid); } i++; } } // Ypx → grid public int 譜面パネル内Y座標pxにおける譜面内絶対位置gridを返す( int 譜面パネル内Y座標px ) { int 譜面パネル底辺からの高さpx = this.Form.譜面パネルサイズ.Height - 譜面パネル内Y座標px; return this.譜面表示下辺の譜面内絶対位置grid + ( 譜面パネル底辺からの高さpx * this.Form.GRID_PER_PIXEL ); } // Ypx → grid public int 譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( int 譜面パネル内Y座標px ) { int 最高解像度での譜面内絶対位置grid = this.譜面パネル内Y座標pxにおける譜面内絶対位置gridを返す( 譜面パネル内Y座標px ); int 対応する小節の譜面内絶対位置grid = this.譜面パネル内Y座標pxにおける小節の譜面内絶対位置gridを返す( 譜面パネル内Y座標px ); int 対応する小節の小節先頭からの相対位置grid = ( ( 最高解像度での譜面内絶対位置grid - 対応する小節の譜面内絶対位置grid ) / this.ガイド間隔grid ) * this.ガイド間隔grid; return 対応する小節の譜面内絶対位置grid + 対応する小節の小節先頭からの相対位置grid; } // grid → Ypx public int 譜面内絶対位置gridにおける対象領域内のY座標pxを返す( int 譜面内絶対位置grid, Size 対象領域サイズpx ) { int 対象領域内の高さgrid = Math.Abs( 譜面内絶対位置grid - this.譜面表示下辺の譜面内絶対位置grid ); return ( 対象領域サイズpx.Height - ( 対象領域内の高さgrid / this.Form.GRID_PER_PIXEL ) ); } // grid → BPM public double 譜面内絶対位置gridにおけるBPMを返す( int 譜面内絶対位置grid ) { double bpm = SSTF.スコア.初期BPM; foreach( 描画用チップ chip in this.スコア.チップリスト ) { if( chip.譜面内絶対位置grid > 譜面内絶対位置grid ) break; if( chip.チップ種別 == SSTF.チップ種別.BPM ) bpm = chip.BPM; } return bpm; } // 小節長 → grid public int 小節長をグリッドで返す( int 小節番号 ) { double この小節の倍率 = this.スコア.小節長倍率を取得する( 小節番号 ); return (int) ( this.Form.GRID_PER_PART * この小節の倍率 ); } // x, y → チップ public 描画用チップ 譜面パネル内座標pxに存在するチップがあれば返す( int x, int y ) { var 座標の編集レーン = this.譜面パネル内X座標pxにある編集レーンを返す( x ); if( 座標の編集レーン == 編集レーン種別.Unknown ) return null; int 座標の譜面内絶対位置grid = this.譜面パネル内Y座標pxにおける譜面内絶対位置gridを返す( y ); int チップの厚さgrid = this.チップサイズpx.Height * this.Form.GRID_PER_PIXEL; foreach( 描画用チップ chip in this.スコア.チップリスト ) { if( ( this.チップ種別to編集レーン[ chip.チップ種別 ] == 座標の編集レーン ) && ( 座標の譜面内絶対位置grid >= chip.譜面内絶対位置grid ) && ( 座標の譜面内絶対位置grid < chip.譜面内絶対位置grid + チップの厚さgrid ) ) { return chip; } } return null; } // ローカル protected メインフォーム Form; protected int ガイド間隔grid = 0; protected const int レーン名表示高さpx = 32; protected const int チップ背景色透明度 = 192; protected const int チップ明影透明度 = 255; protected const int チップ暗影透明度 = 64; protected const int レーン背景色透明度 = 25; protected Bitmap 譜面パネル背景 = null; protected Font 小節番号文字フォント = new Font( "MS UI Gothic", 50f, FontStyle.Regular ); protected Brush 小節番号文字ブラシ = new SolidBrush( Color.FromArgb( 80, Color.White ) ); protected StringFormat 小節番号文字フォーマット = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }; protected Pen ガイド線ペン = new Pen( Color.FromArgb( 50, 50, 50 ) ); protected Pen 小節線ペン = new Pen( Color.White, 2.0f ); protected Pen 拍線ペン = new Pen( Color.Gray ); protected Pen レーン区分線ペン = new Pen( Color.Gray ); protected Pen レーン区分線太ペン = new Pen( Color.Gray, 3.0f ); protected Pen カレントラインペン = new Pen( Color.Red ); protected Font レーン名文字フォント = new Font( "MS US Gothic", 8.0f, FontStyle.Regular ); protected Brush レーン名文字ブラシ = new SolidBrush( Color.FromArgb( 0xff, 220, 220, 220 ) ); protected Brush レーン名文字影ブラシ = new SolidBrush( Color.Black ); protected StringFormat レーン名文字フォーマット = new StringFormat() { LineAlignment = StringAlignment.Near, Alignment = StringAlignment.Center }; protected Pen チップの太枠ペン = new Pen( Color.White, 2.0f ); protected StringFormat チップ内文字列フォーマット = new StringFormat() { LineAlignment = StringAlignment.Near, Alignment = StringAlignment.Center }; protected Font チップ内文字列フォント = new Font( "MS Gothic", 8f, FontStyle.Bold ); protected Pen 白丸白バツペン = new Pen( Color.White ); protected void 譜面に定間隔で線を描画する( Graphics g, int 小節番号, Rectangle 小節の描画領域, int 間隔grid, Pen 描画ペン ) { if( 描画ペン == this.ガイド線ペン ) Debug.Assert( 間隔grid != 0 ); // ガイド線なら間隔 0 はダメ。 if( 間隔grid >= this.Form.GRID_PER_PIXEL * 2 ) // 間隔 1px 以下は描画しない。最低2pxから。 { for( int i = 0; true; i++ ) { int y = 小節の描画領域.Bottom - ( ( i * 間隔grid ) / this.Form.GRID_PER_PIXEL ); if( y < 小節の描画領域.Top ) break; g.DrawLine( 描画ペン, 小節の描画領域.Left, y, 小節の描画領域.Right, y ); } } } protected void チップを描画する_通常( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列, Color 描画色 ) { using var 背景ブラシ = new SolidBrush( 描画色 ); using var 明るいペン = new Pen( Color.FromArgb( チップ明影透明度, 描画色 ) ); using var 暗いペン = new Pen( Color.FromArgb( チップ暗影透明度, 描画色 ) ); this.チップ音量に合わせてチップ描画領域を縮小する( 音量, ref チップ描画領域 ); // チップ本体 g.FillRectangle( 背景ブラシ, チップ描画領域 ); g.DrawLine( 明るいペン, チップ描画領域.X, チップ描画領域.Y, チップ描画領域.Right, チップ描画領域.Y ); g.DrawLine( 明るいペン, チップ描画領域.X, チップ描画領域.Y, チップ描画領域.X, チップ描画領域.Bottom ); g.DrawLine( 暗いペン, チップ描画領域.X, チップ描画領域.Bottom, チップ描画領域.Right, チップ描画領域.Bottom ); g.DrawLine( 暗いペン, チップ描画領域.Right, チップ描画領域.Bottom, チップ描画領域.Right, チップ描画領域.Y ); // チップ内文字列 if( チップ内文字列.Nullでも空でもない() ) { var layout = new RectangleF() { X = チップ描画領域.X, Y = チップ描画領域.Y, Width = チップ描画領域.Width, Height = チップ描画領域.Height, }; g.DrawString( チップ内文字列, this.チップ内文字列フォント, Brushes.Black, layout, this.チップ内文字列フォーマット ); layout.X--; layout.Y--; g.DrawString( チップ内文字列, チップ内文字列フォント, Brushes.White, layout, this.チップ内文字列フォーマット ); } } protected void チップを描画する_通常( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { this.チップを描画する_通常( g, eチップ, 音量, チップ描画領域, チップ内文字列, this.チップto色[ eチップ ] ); } protected void チップを描画する_幅狭( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列, Color 描画色 ) { // チップの幅を半分にする。 int w = チップ描画領域.Width; チップ描画領域.Width = w / 2; チップ描画領域.X += w / 4; this.チップを描画する_通常( g, eチップ, 音量, チップ描画領域, チップ内文字列, 描画色 ); } protected void チップを描画する_幅狭( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { this.チップを描画する_幅狭( g, eチップ, 音量, チップ描画領域, チップ内文字列, this.チップto色[ eチップ ] ); } protected void チップを描画する_幅狭白丸( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { // 幅狭チップを描画。 this.チップを描画する_幅狭( g, eチップ, 音量, チップ描画領域, チップ内文字列 ); // その上に丸を描く。 this.チップ音量に合わせてチップ描画領域を縮小する( 音量, ref チップ描画領域 ); g.DrawEllipse( this.白丸白バツペン, チップ描画領域 ); } protected void チップを描画する_幅狭白狭丸( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { // 幅狭チップを描画。 this.チップを描画する_幅狭( g, eチップ, 音量, チップ描画領域, チップ内文字列 ); // その上に狭い丸を描く。 this.チップ音量に合わせてチップ描画領域を縮小する( 音量, ref チップ描画領域 ); int w = チップ描画領域.Width; チップ描画領域.Width = w / 3; チップ描画領域.X += w / 3 - 1; // -1 は見た目のバランス(直感) g.DrawEllipse( this.白丸白バツペン, チップ描画領域 ); } protected void チップを描画する_幅狭白バツ( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { // 幅狭チップを描画。 this.チップを描画する_幅狭( g, eチップ, 音量, チップ描画領域, チップ内文字列 ); // その上にバツを描く。 this.チップ音量に合わせてチップ描画領域を縮小する( 音量, ref チップ描画領域 ); int w = チップ描画領域.Width; チップ描画領域.Width = w / 3; チップ描画領域.X += w / 3; g.DrawLine( this.白丸白バツペン, new Point( チップ描画領域.Left, チップ描画領域.Top ), new Point( チップ描画領域.Right, チップ描画領域.Bottom ) ); g.DrawLine( this.白丸白バツペン, new Point( チップ描画領域.Left, チップ描画領域.Bottom ), new Point( チップ描画領域.Right, チップ描画領域.Top ) ); } protected void チップを描画する_小丸( Graphics g, SSTF.チップ種別 eチップ, int 音量, Rectangle チップ描画領域, string チップ内文字列 ) { this.チップ音量に合わせてチップ描画領域を縮小する( 音量, ref チップ描画領域 ); Color 描画色 = this.チップto色[ eチップ ]; int w = チップ描画領域.Width; チップ描画領域.Width = w / 3; チップ描画領域.X += w / 3; using var 背景ブラシ = new SolidBrush( 描画色 ); using var 枠ペン = new Pen( Color.Orange ); g.FillEllipse( 背景ブラシ, チップ描画領域 ); g.DrawEllipse( 枠ペン, チップ描画領域 ); } protected void チップ音量に合わせてチップ描画領域を縮小する( int チップ音量, ref Rectangle 描画領域 ) { double 縮小率 = (double) チップ音量 * ( 1.0 / ( メインフォーム.最大音量 - メインフォーム.最小音量 + 1 ) ); 描画領域.Y += (int) ( 描画領域.Height * ( 1.0 - 縮小率 ) ); 描画領域.Height = (int) ( 描画領域.Height * 縮小率 ); } } } <|start_filename|>DTXMania2/ステージ/08結果/曲別SKILL.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.結果 { partial class 曲別SKILL : IDisposable { // プロパティ /// <summary> /// アニメがすべて終わったら true。 /// </summary> public bool アニメ完了 => this._アイコン.アニメ完了 && this._下線.アニメ完了 && this._数値.アニメ完了; // 生成と終了 public 曲別SKILL() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._アイコン = new アイコン(); this._下線 = new 下線(); this._数値 = new 数値(); this._初めての進行描画 = true; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._数値.Dispose(); this._下線.Dispose(); this._アイコン.Dispose(); } // 進行と描画 public void アニメを完了する() { this._アイコン.アニメを完了する(); this._下線.アニメを完了する(); this._数値.アニメを完了する(); } public void 進行描画する( DeviceContext d2ddc, float x, float y, double スキル値 ) { if( this._初めての進行描画 ) { // アニメーション開始 this._アイコン.開始する(); this._下線.開始する(); this._数値.開始する( スキル値 ); this._初めての進行描画 = false; } this._アイコン.進行描画する( d2ddc, x, y ); this._数値.進行描画する( d2ddc, x + 180f, y + 3f ); this._下線.進行描画する( d2ddc, x + 33f, y + 113f ); } // ローカル private const double _最初の待機時間sec = 0.75; private const double _アニメ時間sec = 0.25; private bool _初めての進行描画; private readonly 曲別SKILL.アイコン _アイコン; private readonly 曲別SKILL.下線 _下線; private readonly 曲別SKILL.数値 _数値; } } <|start_filename|>SSTFEditor/選択モード.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace SSTFEditor { class 選択モード : IDisposable { public 選択モード( メインフォーム form ) { this.Form = form; } public virtual void Dispose() { this.選択領域用のブラシ?.Dispose(); this.選択領域用のブラシ = null; this.選択領域用のペン?.Dispose(); this.選択領域用のペン = null; this.Form = null; } public void 個別選択を解除する( 描画用チップ chip ) { var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.選択が確定している = true; this.Form.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.選択が確定している = false; this.Form.未保存である = true; }, 変更対象: chip, 変更前の値: null, 変更後の値: null ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); this.Form.UndoRedo用GUIのEnabledを設定する(); } public void 全チップを選択する() { try { this.Form.UndoRedo管理.トランザクション記録を開始する(); foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { // 選択されていないすべてのチップを選択する。 if( chip.選択が確定していない ) { var 変更前のチップ = new 描画用チップ( chip ); var 変更後のチップ = new 描画用チップ( chip ) { ドラッグ操作により選択中である = false, 選択が確定している = true, }; var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); this.Form.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更後 ); this.Form.未保存である = true; }, 変更対象: chip, 変更前の値: 変更前のチップ, 変更後の値: 変更後のチップ ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.Form.選択チップの有無に応じて編集用GUIのEnabledを設定する(); this.Form.譜面をリフレッシュする(); } } public void 全チップの選択を解除する() { try { this.Form.UndoRedo管理.トランザクション記録を開始する(); foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { if( ( 0 != chip.枠外レーン数 ) || ( 0 > chip.譜面内絶対位置grid ) ) { #region " 譜面範囲外に出たチップがあれば削除する。" //----------------- var chip変更前 = this.移動開始時のチップ状態[ chip ]; var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( chip変更前 ); this.Form.譜面.スコア.チップリスト.Add( 変更対象 ); this.Form.譜面.スコア.チップリスト.Sort(); this.Form.未保存である = true; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { this.Form.譜面.スコア.チップリスト.Remove( 変更対象 ); this.Form.未保存である = true; }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: null ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); //----------------- #endregion } else if( chip.ドラッグ操作により選択中である || chip.選択が確定している ) { #region " チップの選択を解除する。" //----------------- var chip変更前 = new 描画用チップ( chip ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.選択が確定している = false; 変更対象.ドラッグ操作により選択中である = false; 変更対象.移動済みである = false; }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: null ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); //----------------- #endregion } } } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.Form.未保存である = true; } } public void 検索する() { using var dialog = new 検索条件入力ダイアログ(); if( dialog.ShowDialog( this.Form ) != DialogResult.OK ) return; // キャンセルされたら何もしない。 int 開始小節番号 = ( dialog.小節範囲指定CheckBoxがチェックされている ) ? dialog.小節範囲開始番号 : 0; int 終了小節番号 = ( dialog.小節範囲指定CheckBoxがチェックされている ) ? dialog.小節範囲終了番号 : this.Form.譜面.スコア.最大小節番号を返す(); if( 0 > 開始小節番号 ) 開始小節番号 = 0; // 省略時は 0 とみなす。 if( 0 > 終了小節番号 ) 終了小節番号 = this.Form.譜面.スコア.最大小節番号を返す(); // 省略時は 最大小節番号とする。 int 選択チップ数 = 0; try { this.Form.UndoRedo管理.トランザクション記録を開始する(); foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { var e編集レーン = this.Form.譜面.チップ種別to編集レーン[ chip.チップ種別 ]; // 編集レーンを持たないチップは無視する。 if( e編集レーン == 編集レーン種別.Unknown ) continue; if( ( chip.小節番号 >= 開始小節番号 ) && ( chip.小節番号 <= 終了小節番号 ) ) { if( dialog.選択されている( e編集レーン ) || dialog.選択されている( chip.チップ種別 ) ) { // チップを選択する。 var chip変更前 = new 描画用チップ( chip ); var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.選択が確定している = 変更前.選択が確定している; }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.選択が確定している = true; }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: null ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); 選択チップ数++; } } } } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.Form.譜面をリフレッシュする(); } #region " チップ数に応じて結果を表示する。" //----------------- if( 0 < 選択チップ数 ) { this.Form.選択チップの有無に応じて編集用GUIのEnabledを設定する(); MessageBox.Show( 選択チップ数 + Properties.Resources.MSG_個のチップが選択されました, Properties.Resources.MSG_検索結果ダイアログのタイトル, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1 ); } else { MessageBox.Show( Properties.Resources.MSG_該当するチップはありませんでした, Properties.Resources.MSG_検索結果ダイアログのタイトル, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1 ); } //----------------- #endregion } // イベント public void MouseClick( MouseEventArgs e ) { // 右クリック → コンテクストメニュー表示 if( e.Button == MouseButtons.Right ) this.Form.選択モードのコンテクストメニューを表示する( e.X, e.Y ); } public void MouseDown( MouseEventArgs e ) { // 左クリック if( e.Button == MouseButtons.Left ) { var chip = this.Form.譜面.譜面パネル内座標pxに存在するチップがあれば返す( e.X, e.Y ); // (A) チップがないか、未選択のチップがあった場合。 if( ( chip == null ) || ( false == chip.選択が確定している ) ) this.範囲選択の開始処理( e ); // (B) 選択状態のチップがあり、かつ、クリック時に CTRL が押されている場合。 else if( ( Control.ModifierKeys & Keys.Control ) == Keys.Control ) this.個別選択を解除する( chip ); // (C) 選択状態のチップがあり、かつ、クリック時に CTRL が押されていない場合。 else this.移動の開始処理( e ); } } public void MouseMove( MouseEventArgs e ) { // (A) 左ボタンが押されながら移動している場合 → 継続処理 if( e.Button == MouseButtons.Left ) { if( this.範囲選択のためにドラッグ中である ) this.範囲選択の継続処理( e ); else if( this.移動のためにドラッグ中である ) this.移動の継続処理( e ); } // (B) 左ボタンが押されずに移動した場合 → 終了処理 else { if( this.範囲選択のためにドラッグ中である ) this.範囲選択の終了処理( e ); else if( this.移動のためにドラッグ中である ) this.移動の終了処理( e ); } // 譜面を再描画する。 this.Form.譜面をリフレッシュする(); } public void Paint( PaintEventArgs e ) { if( this.範囲選択のためにドラッグ中である ) this.現在の選択範囲を描画する( e.Graphics ); } // 全般 protected メインフォーム Form = null; protected SolidBrush 選択領域用のブラシ = new SolidBrush( Color.FromArgb( 80, 55, 55, 255 ) ); protected Pen 選択領域用のペン = new Pen( Color.LightBlue ); protected void 現在の選択範囲を描画する( Graphics g ) { var 現在の選択領域px = new Rectangle() { X = Math.Min( this.現在の範囲選択用ドラッグ開始位置Xpx, this.現在の範囲選択用ドラッグ終了位置Xpx ), Y = this.Form.譜面.譜面内絶対位置gridにおける対象領域内のY座標pxを返す( Math.Max( // grid は上に行くほど大きくなる this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid, this.現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid ), this.Form.譜面パネルサイズ ), Width = Math.Abs( this.現在の範囲選択用ドラッグ開始位置Xpx - this.現在の範囲選択用ドラッグ終了位置Xpx ), Height = Math.Abs( this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid - this.現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid ) / this.Form.GRID_PER_PIXEL, }; // クリッピング 現在の選択領域px.Intersect( this.Form.譜面パネル領域 ); // 描画 if( ( 0 < 現在の選択領域px.Width ) && ( 0 < 現在の選択領域px.Height ) ) { g.FillRectangle( this.選択領域用のブラシ, 現在の選択領域px ); g.DrawRectangle( Pens.LightBlue, 現在の選択領域px ); } } protected void 譜面パネルの上下端にきたならスクロールする( MouseEventArgs e ) { const int 上端スクロール発動幅px = 70; const int 下端スクロール発動幅px = 50; if( e.Y <= 上端スクロール発動幅px ) { // (A) マウスが上端にいるので、上から下へスクロールする。 double 発動量 = Math.Min( Math.Max( 上端スクロール発動幅px - e.Y, 0 ) / (double) 上端スクロール発動幅px, 1.0 ); // 0~1 (Liner) double 速度係数 = ( 1.0 - Math.Cos( ( Math.PI / 2.0 ) * 発動量 ) ) * 2.0 + 1.0; // 発動量:0→1 のとき、速度係数:3→1 (Cos) int スクロール量grid = (int) ( -速度係数 * 180.0 ); // 速度係数:1→3 のとき、スクロール量grid:-180→-540; this.Form.譜面を縦スクロールする( スクロール量grid ); if( this.移動のためにドラッグ中である ) this.現在の移動用ドラッグ開始位置px.Y -= スクロール量grid / this.Form.GRID_PER_PIXEL; //if( this.範囲選択のためにドラッグ中である ) // this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid += スクロール量grid; // grid は上方向がプラス // → 譜面スクロール後のマウスイベントですぐに更新されるので、ここで位置を増減してしまうと2倍動いてしまう。なのでコメントアウト。 } else if( e.Y >= ( this.Form.譜面パネルサイズ.Height - 下端スクロール発動幅px ) && ( this.Form.譜面.譜面表示下辺の譜面内絶対位置grid > 0 ) ) // まだスクロールができる場合のみ { // (B) マウスが下端にいるので、下から上へスクロールする。 double 発動量 = Math.Min( Math.Max( e.Y - ( this.Form.譜面パネルサイズ.Height - 下端スクロール発動幅px ), 0 ) / (double) 下端スクロール発動幅px, 1.0 ); // 0~1 (Liner) double 速度係数 = ( 1.0 - Math.Cos( ( Math.PI / 2.0 ) * 発動量 ) ) * 2.0 + 1.0; // 発動量:0→1 のとき、速度係数:3→1 (Cos) int スクロール量grid = (int) ( 速度係数 * 180.0 ); // 速度係数:1→3 のとき、スクロール量grid:180→540; this.Form.譜面を縦スクロールする( スクロール量grid ); if( this.移動のためにドラッグ中である ) this.現在の移動用ドラッグ開始位置px.Y -= スクロール量grid / this.Form.GRID_PER_PIXEL; //if( this.範囲選択のためにドラッグ中である ) // this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid += スクロール量grid; // grid は上がプラス // → 譜面がスクロールしても開始位置は絶対grid指定なので、変更する必要がない。よって、コメントアウト。 } } // 移動関連 protected bool 移動のためにドラッグ中である = false; protected Point 現在の移動用ドラッグ開始位置px = new Point( 0, 0 ); protected Point 現在の移動用ドラッグ終了位置px = new Point( 0, 0 ); protected Dictionary<描画用チップ, 描画用チップ> 移動開始時のチップ状態 = new Dictionary<描画用チップ, 描画用チップ>(); protected struct レーングリッド座標 { public int 編集レーン位置; // X座標に相当。 public int 譜面内絶対位置grid; // Y座標に相当。 }; protected レーングリッド座標 前回のマウス位置LaneGrid = new レーングリッド座標(); protected void 移動の開始処理( MouseEventArgs e ) { this.移動のためにドラッグ中である = true; // ドラッグ範囲の初期化。 this.現在の移動用ドラッグ開始位置px.X = this.現在の移動用ドラッグ終了位置px.X = e.X; this.現在の移動用ドラッグ開始位置px.Y = this.現在の移動用ドラッグ終了位置px.Y = e.Y; // マウス位置(lane×grid)の初期化。 this.前回のマウス位置LaneGrid = new レーングリッド座標() { 編集レーン位置 = this.Form.譜面.譜面パネル内X座標pxにある表示レーン位置を返す( e.X ), 譜面内絶対位置grid = this.Form.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( e.Y ), }; // 移動対象チップ(現在選択が確定しているチップ)の「移動開始時のチップの全状態」を、ローカルの Dictionary に控えておく。 // これは 移動終了処理() で使用する。 this.移動開始時のチップ状態.Clear(); foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { if( chip.選択が確定している ) this.移動開始時のチップ状態.Add( chip, new 描画用チップ( chip ) ); } } protected void 移動の継続処理( MouseEventArgs e ) { // ドラッグ終了位置を現在のマウスの位置に更新。 this.現在の移動用ドラッグ終了位置px.X = e.X; this.現在の移動用ドラッグ終了位置px.Y = e.Y; // スクロールチェック。 this.譜面パネルの上下端にきたならスクロールする( e ); // チップの移動。 #region " 現在確定中のチップを移動する。" //----------------- // 現在の位置を算出。 var 現在のドラッグ終了位置LaneGrid = new レーングリッド座標() { 編集レーン位置 = this.Form.譜面.譜面パネル内X座標pxにある表示レーン位置を返す( this.現在の移動用ドラッグ終了位置px.X ), 譜面内絶対位置grid = this.Form.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( this.現在の移動用ドラッグ終了位置px.Y ), }; // 前回位置からの移動量を算出。 var 移動量LaneGrid = new レーングリッド座標() { 編集レーン位置 = 現在のドラッグ終了位置LaneGrid.編集レーン位置 - this.前回のマウス位置LaneGrid.編集レーン位置, 譜面内絶対位置grid = 現在のドラッグ終了位置LaneGrid.譜面内絶対位置grid - this.前回のマウス位置LaneGrid.譜面内絶対位置grid, }; // 前回位置から移動していれば、選択されているすべてのチップを移動させる。 if( ( 0 != 移動量LaneGrid.編集レーン位置 ) || ( 0 != 移動量LaneGrid.譜面内絶対位置grid ) ) { #region " 全チップの移動済フラグをリセットする。" //----------------- foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) chip.移動済みである = false; //----------------- #endregion foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { if( chip.選択が確定している && ( false == chip.移動済みである ) ) { if( 0 != 移動量LaneGrid.編集レーン位置 ) { #region " チップを横に移動する。" //----------------- int レーン数 = Enum.GetValues( typeof( 編集レーン種別 ) ).Length; int チップの現在のレーン位置 = this.Form.譜面.編集レーンの表示レーン位置を返す( this.Form.譜面.チップ種別to編集レーン[ chip.チップ種別 ] ); int チップの移動後のレーン位置; #region " チップの移動後のレーン位置 を算出。" //----------------- if( 0 > chip.枠外レーン数 ) { チップの移動後のレーン位置 = チップの現在のレーン位置 + 移動量LaneGrid.編集レーン位置; } else if( 0 < chip.枠外レーン数 ) { チップの移動後のレーン位置 = ( ( レーン数 - 1 ) + chip.枠外レーン数 ) + 移動量LaneGrid.編集レーン位置; } else { チップの移動後のレーン位置 = チップの現在のレーン位置; } //----------------- #endregion #region " チップの移動後のレーン位置 から、チップのチップ種別 or 枠外レーン数 を修正する。" //----------------- if( 0 > チップの移動後のレーン位置 ) // 左にはみ出している { chip.枠外レーン数 = チップの移動後のレーン位置; } else if( レーン数 <= チップの移動後のレーン位置 ) // 右にはみ出している { chip.枠外レーン数 = チップの移動後のレーン位置 - ( レーン数 - 1 ); } else { var eチップの移動後の編集レーン = this.Form.譜面.表示レーン位置にある編集レーンを返す( チップの移動後のレーン位置 ); foreach( var kvp in this.Form.譜面.チップ種別to編集レーン ) { if( kvp.Value == eチップの移動後の編集レーン ) // 対応表で最初に見つけた kvp のチップ種別を採択する。 { chip.チップ種別 = kvp.Key; break; } } chip.枠外レーン数 = 0; } //----------------- #endregion chip.移動済みである = true; this.Form.未保存である = true; //----------------- #endregion } if( 移動量LaneGrid.譜面内絶対位置grid != 0 ) { #region " チップを縦に移動する。" //----------------- int 移動後の譜面内絶対位置grid = chip.譜面内絶対位置grid + 移動量LaneGrid.譜面内絶対位置grid; if( 0 > 移動後の譜面内絶対位置grid ) { // 画面外なので何もしない。 } else if( 移動後の譜面内絶対位置grid >= this.Form.譜面.全小節の高さgrid ) { chip.譜面内絶対位置grid = 移動後の譜面内絶対位置grid; // そこに小節はないが、一応描画する。 } else { chip.譜面内絶対位置grid = 移動後の譜面内絶対位置grid; } chip.移動済みである = true; this.Form.未保存である = true; //----------------- #endregion } } } // 前回位置を現在の位置に更新。 this.前回のマウス位置LaneGrid = new レーングリッド座標() { 編集レーン位置 = 現在のドラッグ終了位置LaneGrid.編集レーン位置, 譜面内絶対位置grid = 現在のドラッグ終了位置LaneGrid.譜面内絶対位置grid, }; } //----------------- #endregion } protected void 移動の終了処理( MouseEventArgs e ) { try { this.Form.UndoRedo管理.トランザクション記録を開始する(); foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { // 選択が確定かつ初期位置から移動しているチップのみ対象とする。 if( chip.選択が確定している && ( chip.譜面内絶対位置grid != this.移動開始時のチップ状態[ chip ].譜面内絶対位置grid || chip.チップ種別 != this.移動開始時のチップ状態[ chip ].チップ種別 ) ) { // ここではまだ、譜面範囲外に出ている(=枠外レーン数がゼロでない)チップの削除は行わない。(その後再び移動される可能性があるため。) // これらの削除処理は「t全チップの選択を解除する()」で行う。 var chip変更前 = this.移動開始時のチップ状態[ chip ]; var 小節情報 = this.Form.譜面.譜面内絶対位置gridに位置する小節の情報を返す( chip.譜面内絶対位置grid ); var chip変更後 = new 描画用チップ( chip ) { 小節番号 = 小節情報.小節番号, 小節解像度 = (int) ( this.Form.GRID_PER_PART * this.Form.譜面.スコア.小節長倍率を取得する( 小節情報.小節番号 ) ), 小節内位置 = chip.譜面内絶対位置grid - 小節情報.小節の先頭位置grid, }; var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更後 ); }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: chip変更後 ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.移動のためにドラッグ中である = false; } } // 範囲選択関連 protected bool 範囲選択のためにドラッグ中である = false; protected int 現在の範囲選択用ドラッグ開始位置Xpx = 0; protected int 現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid = 0; protected int 現在の範囲選択用ドラッグ終了位置Xpx = 0; protected int 現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid = 0; protected void 範囲選択の開始処理( MouseEventArgs e ) { this.範囲選択のためにドラッグ中である = true; // ドラッグ範囲の初期化。 this.現在の範囲選択用ドラッグ開始位置Xpx = this.現在の範囲選択用ドラッグ終了位置Xpx = e.X; this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid = this.現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid = this.Form.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridを返す( e.Y ); // CTRL が押されていない場合、いったん全チップの選択を解除する。 if( ( Control.ModifierKeys & Keys.Control ) != Keys.Control ) this.全チップの選択を解除する(); // 全チップについて、選択・選択解除の取捨選択。 this.現在のドラッグ範囲中のチップをすべて選択状態にしそれ以外は選択を解除する(); } protected void 範囲選択の継続処理( MouseEventArgs e ) { // クリッピング。 int Xpt = Math.Clamp( e.X, min: 0, max: this.Form.譜面パネルサイズ.Width ); int Ypt = Math.Clamp( e.Y, min: 0, max: this.Form.譜面パネルサイズ.Height ); // ドラッグ終了位置を現在のマウスの位置に更新。 this.現在の範囲選択用ドラッグ終了位置Xpx = Xpt; this.現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid = this.Form.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridを返す( Ypt ); // スクロールチェック。 this.譜面パネルの上下端にきたならスクロールする( e ); // チップの選択 or 選択解除。 this.現在のドラッグ範囲中のチップをすべて選択状態にしそれ以外は選択を解除する(); } protected void 範囲選択の終了処理( MouseEventArgs e ) { this.範囲選択のためにドラッグ中である = false; try { this.Form.UndoRedo管理.トランザクション記録を開始する(); // ドラック選択範囲に入っているがまだ選択が確定していないチップを選択確定させる。 foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { // ドラッグ選択範囲内にあって既に選択が確定されているものについては何もしない。 if( chip.ドラッグ操作により選択中である && ( false == chip.選択が確定している ) ) { var chip変更前 = new 描画用チップ( chip ); var chip変更後 = new 描画用チップ( chip ) { ドラッグ操作により選択中である = false, 選択が確定している = true, }; var cell = new UndoRedo.セル<描画用チップ>( 所有者ID: null, Undoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更前 ); }, Redoアクション: ( 変更対象, 変更前, 変更後, 任意1, 任意2 ) => { 変更対象.CopyFrom( 変更後 ); }, 変更対象: chip, 変更前の値: chip変更前, 変更後の値: chip変更後 ); this.Form.UndoRedo管理.セルを追加する( cell ); cell.Redoを実行する(); } } } finally { this.Form.UndoRedo管理.トランザクション記録を終了する(); this.Form.UndoRedo用GUIのEnabledを設定する(); this.Form.選択チップの有無に応じて編集用GUIのEnabledを設定する(); } } protected void 現在のドラッグ範囲中のチップをすべて選択状態にしそれ以外は選択を解除する() { // 現在のドラッグ範囲を (px, grid) 座標で算出する。 // ※ px は上→下、grid は下→上に向かって増加するので注意! var 現在のドラッグ範囲pxGrid = new Rectangle() { X = Math.Min( this.現在の範囲選択用ドラッグ開始位置Xpx, this.現在の範囲選択用ドラッグ終了位置Xpx ), Y = Math.Min( this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid, this.現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid ), Width = Math.Abs( this.現在の範囲選択用ドラッグ開始位置Xpx - this.現在の範囲選択用ドラッグ終了位置Xpx ), Height = Math.Abs( this.現在の範囲選択用ドラッグ開始位置Ypxの譜面内絶対位置grid - this.現在の範囲選択用ドラッグ終了位置Ypxの譜面内絶対位置grid ), }; // 現在のドラッグ範囲を (lane, grid) 座標に変換する。 int ドラッグ範囲左のレーン位置 = this.Form.譜面.編集レーンの表示レーン位置を返す( this.Form.譜面.譜面パネル内X座標pxにある編集レーンを返す( 現在のドラッグ範囲pxGrid.Left ) ); int ドラッグ範囲右のレーン位置 = this.Form.譜面.編集レーンの表示レーン位置を返す( this.Form.譜面.譜面パネル内X座標pxにある編集レーンを返す( 現在のドラッグ範囲pxGrid.Right ) ); var 現在のドラッグ範囲LaneGrid = new Rectangle() { X = ドラッグ範囲左のレーン位置, Y = 現在のドラッグ範囲pxGrid.Y, Width = Math.Abs( ドラッグ範囲右のレーン位置 - ドラッグ範囲左のレーン位置 ) + 1, // +1 を忘れずに。 Height = 現在のドラッグ範囲pxGrid.Height + 1, // +1 を忘れずに。 }; // すべてのチップについて、現在のドラッグ範囲内に存在しているチップは「ドラッグ操作により選択中」フラグを立てる。 foreach( 描画用チップ chip in this.Form.譜面.スコア.チップリスト ) { int チップのレーン位置 = this.Form.譜面.編集レーンの表示レーン位置を返す( this.Form.譜面.チップ種別to編集レーン[ chip.チップ種別 ] ); int チップの厚さgrid = this.Form.譜面.チップサイズpx.Height * this.Form.GRID_PER_PIXEL; var チップの領域LaneGrid = new Rectangle() { X = チップのレーン位置, Y = chip.譜面内絶対位置grid, Width = 1, // +1 を忘れずに。 Height = チップの厚さgrid, }; chip.ドラッグ操作により選択中である = チップの領域LaneGrid.IntersectsWith( 現在のドラッグ範囲LaneGrid ); } } } } <|start_filename|>SSTFEditor/編集モード.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using SSTF=SSTFormat.v004; namespace SSTFEditor { class 編集モード { public Rectangle 現在のチップカーソル領域 { get; protected set; } public 編集モード( メインフォーム form ) { this.Form = form; this.現在のチップカーソル領域 = new Rectangle( 0, 0, 0, 0 ); // 現在のチップ種別番号の初期化。 this.dicレーン別現在のチップ種別番号 = new Dictionary<編集レーン種別, int>(); this.dicレーン別チップ種別バックアップ = new Dictionary<編集レーン種別, int>(); foreach( 編集レーン種別 editLaneType in Enum.GetValues( typeof( 編集レーン種別 ) ) ) { this.dicレーン別現在のチップ種別番号[ editLaneType ] = 0; this.dicレーン別チップ種別バックアップ[ editLaneType ] = 0; } this.レーン別チップ種別対応表を初期化する(); } public void レーン別チップ種別対応表を初期化する() { // 譜面.チップ種別to編集レーン プロパティを元にするので、譜面を先に生成してから編集モードを生成すること。 this.dicレーン別チップ種別対応表 = new Dictionary<編集レーン種別, List<SSTF.チップ種別>>(); foreach( 編集レーン種別 editLaneType in Enum.GetValues( typeof( 編集レーン種別 ) ) ) this.dicレーン別チップ種別対応表[ editLaneType ] = new List<SSTF.チップ種別>(); foreach( var kvp in this.Form.譜面.チップ種別to編集レーン ) { if( kvp.Key == SSTF.チップ種別.LeftBass ) continue; // SSTFEditorではLeftBassを扱わない this.dicレーン別チップ種別対応表[ kvp.Value ].Add( kvp.Key ); } } // イベント public void MouseClick( MouseEventArgs e ) { this.チップを配置または削除する( e ); this.Form.譜面をリフレッシュする(); } public void MouseLeave( EventArgs e ) { this.現在のチップカーソル領域 = new Rectangle( 0, 0, 0, 0 ); this.Form.譜面をリフレッシュする(); } public void MouseMove( MouseEventArgs e ) { #region " チップカーソルの領域を、現在の位置に合わせて更新する。" //----------------- var 以前のチップカーソル領域 = this.現在のチップカーソル領域; this.現在チップカーソルがある編集レーン = this.Form.譜面.譜面パネル内X座標pxにある編集レーンを返す( e.X ); this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid = this.Form.譜面.譜面パネル内Y座標pxにおける譜面内絶対位置gridをガイド幅単位で返す( e.Y ); // カーソルが譜面外にあるならここで終了。 if( this.現在チップカーソルがある編集レーン == 編集レーン種別.Unknown || ( 0 > this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid ) ) { this.現在チップカーソルがある編集レーン = 編集レーン種別.Unknown; this.Form.譜面をリフレッシュする(); // チップを消去する。 return; } // 新しい現在の領域を取得。 this.現在のチップカーソル領域 = new Rectangle( this.Form.譜面.編集レーンのX座標pxを返す( this.現在チップカーソルがある編集レーン ), this.Form.譜面.譜面内絶対位置gridにおける対象領域内のY座標pxを返す( this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid, this.Form.譜面パネルサイズ ) - this.Form.譜面.チップサイズpx.Height, this.Form.譜面.チップサイズpx.Width, this.Form.譜面.チップサイズpx.Height ); //----------------- #endregion this.チップカーソルのあるレーンに合わせて現在のチップ種別を変更する(); #region " 領域が変わってたら譜面を再描画する。" //----------------- if( false == this.現在のチップカーソル領域.Equals( 以前のチップカーソル領域 ) ) this.Form.譜面をリフレッシュする(); //----------------- #endregion } public void Paint( PaintEventArgs e ) { this.チップカーソルを描画する( e.Graphics, this.Form.現在のチップ種別 ); } public void PreviewKeyDown( PreviewKeyDownEventArgs e ) { // SPACE if( e.KeyCode == Keys.Space && !e.Shift ) { #region " 現在のレーン別チップ種別を、登録順にローテーションする。" //----------------- // インデックスを1つ増やす。インデックスが範囲を超えたら 0 に戻す。 int n = this.dicレーン別現在のチップ種別番号[ this.現在チップカーソルがある編集レーン ] + 1; if( n == this.dicレーン別チップ種別対応表[ this.現在チップカーソルがある編集レーン ].Count ) n = 0; this.dicレーン別現在のチップ種別番号[ this.現在チップカーソルがある編集レーン ] = n; // 画面へ反映する。 this.チップカーソルのあるレーンに合わせて現在のチップ種別を変更する(); this.Form.譜面をリフレッシュする(); this.強制種別使用中 = false; //----------------- #endregion } // SHIFT + SPACE else if( e.KeyCode == Keys.Space && e.Shift ) { #region " 現在のレーン別チップ種別を、特定の種別(2番目)とトグル切り替えする。" //----------------- if( this.dicレーン別チップ種別対応表[ this.現在チップカーソルがある編集レーン ].Count > 1 ) // 種別を2つ以上持たないレーンは関係ない。 { if( false == this.強制種別使用中 ) { // (A) 特定の種別(2番目)に切替える。 // 現在のインデックスをバックアップしておく。 this.dicレーン別チップ種別バックアップ[ this.現在チップカーソルがある編集レーン ] = this.dicレーン別現在のチップ種別番号[ this.現在チップカーソルがある編集レーン ]; // 現在のインデックスを強制的に「1」(2番目の要素)にする。 this.dicレーン別現在のチップ種別番号[ this.現在チップカーソルがある編集レーン ] = 1; this.強制種別使用中 = true; } else { // (B) 元の種別に戻す。 // 現在のインデックスをバックアップ値に戻す。 this.dicレーン別現在のチップ種別番号[ this.現在チップカーソルがある編集レーン ] = this.dicレーン別チップ種別バックアップ[ this.現在チップカーソルがある編集レーン ]; this.強制種別使用中 = false; } // 画面へ反映する。 this.チップカーソルのあるレーンに合わせて現在のチップ種別を変更する(); this.Form.譜面をリフレッシュする(); } //----------------- #endregion } } protected メインフォーム Form; protected 編集レーン種別 現在チップカーソルがある編集レーン; protected int 現在のチップカーソルの譜面先頭からのガイド単位の位置grid; protected bool 強制種別使用中 = false; protected Dictionary<編集レーン種別, int> dicレーン別チップ種別バックアップ; protected Dictionary<編集レーン種別, int> dicレーン別現在のチップ種別番号; protected Dictionary<編集レーン種別, List<SSTF.チップ種別>> dicレーン別チップ種別対応表; protected void チップカーソルを描画する( Graphics g, SSTF.チップ種別 チップ種別 ) { #region " 事前チェック。" //----------------- if( ( 0 >= this.現在のチップカーソル領域.Width ) || ( 0 >= this.現在のチップカーソル領域.Height ) || ( this.現在チップカーソルがある編集レーン == 編集レーン種別.Unknown ) || ( チップ種別 == SSTF.チップ種別.Unknown ) || ( チップ種別 == SSTF.チップ種別.小節線 ) || ( チップ種別 == SSTF.チップ種別.拍線 ) ) { return; // 描画しない。 } //----------------- #endregion // チップを描いて、 this.Form.譜面.チップを指定領域へ描画する( g, チップ種別, this.Form.現在のチップ音量, this.現在のチップカーソル領域, null ); // チップをカーソル枠で囲む。 this.Form.譜面.チップの太枠を指定領域へ描画する( g, this.現在のチップカーソル領域 ); } protected void チップカーソルのあるレーンに合わせて現在のチップ種別を変更する() { int index = this.dicレーン別現在のチップ種別番号[ this.現在チップカーソルがある編集レーン ]; this.Form.現在のチップ種別 = this.dicレーン別チップ種別対応表[ this.現在チップカーソルがある編集レーン ][ index ]; } protected void チップを配置または削除する( MouseEventArgs eClick ) { if( ( 0 >= this.現在のチップカーソル領域.Width ) || ( 0 >= this.現在のチップカーソル領域.Height ) ) return; // 左クリック if( eClick.Button == MouseButtons.Left ) { #region " チップを配置する。" //----------------- bool CTRL押下 = ( Control.ModifierKeys & Keys.Control ) == Keys.Control; if( this.現在チップカーソルがある編集レーン != 編集レーン種別.BPM ) { #region " (A) BPM レーン以外の場合 " //----------------- string チップ内文字列 = null; if( this.Form.現在のチップ種別 == SSTF.チップ種別.China ) チップ内文字列 = "C N"; if( this.Form.現在のチップ種別 == SSTF.チップ種別.Splash ) チップ内文字列 = "S P"; this.Form.譜面.チップを配置または置換する( e編集レーン: this.現在チップカーソルがある編集レーン, eチップ: this.Form.現在のチップ種別, 譜面内絶対位置grid: this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid, チップ文字列: チップ内文字列, 音量: this.Form.現在のチップ音量, // 音量変化は未実装 BPM: 0.0, 選択確定中: false ); //----------------- #endregion } else { #region " (B) BPM レーンの場合 " //----------------- using var dialog = new 数値入力ダイアログ( (decimal) this.Form.譜面.譜面内絶対位置gridにおけるBPMを返す( this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid ), 0.0001M, 1000M, Properties.Resources.MSG_BPM選択ダイアログの説明文 ); if( dialog.ShowDialog( this.Form ) != DialogResult.OK ) return; double bpm = (double) dialog.数値; this.Form.譜面.チップを配置または置換する( e編集レーン: 編集レーン種別.BPM, eチップ: SSTF.チップ種別.BPM, 譜面内絶対位置grid: this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid, チップ文字列: bpm.ToString( "###.##" ), 音量: メインフォーム.最大音量, // BPM チップは常に最大音量枠 BPM: bpm, 選択確定中: false ); //----------------- #endregion } //----------------- #endregion } else if( eClick.Button == MouseButtons.Right ) { #region " チップを削除する。" //----------------- this.Form.譜面.チップを削除する( this.現在チップカーソルがある編集レーン, this.現在のチップカーソルの譜面先頭からのガイド単位の位置grid ); //----------------- #endregion } } } } <|start_filename|>DTXMania2/ステージ/07演奏/右サイドクリアパネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using FDK; namespace DTXMania2.演奏 { class 右サイドクリアパネル : IDisposable { // プロパティ public 描画可能画像 クリアパネル { get; } public 画像D2D 背景 { get; } // 生成と終了 public 右サイドクリアパネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.背景 = new 画像D2D( @"$(Images)\PlayStage\RightSideClearPanel.png" ); this.クリアパネル = new 描画可能画像( new Size2F( 500, 990 ) ); // this._背景.サイズはまだ設定されていない。 } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this.クリアパネル.Dispose(); this.背景.Dispose(); } // 進行と描画 public void 進行描画する() { // テクスチャは画面中央が (0,0,0) で、Xは右がプラス方向, Yは上がプラス方向, Zは奥がプラス方向+。 var 変換行列 = Matrix.RotationY( MathUtil.DegreesToRadians( +48f ) ) * Matrix.Translation( Global.GraphicResources.画面左上dpx.X + 1630f, Global.GraphicResources.画面左上dpx.Y - 530f, 0f ); this.クリアパネル.描画する( 変換行列 ); } } } <|start_filename|>FDK/入力/RawInput.cs<|end_filename|> using System; using System.Runtime.InteropServices; using SharpDX.Multimedia; namespace FDK { /// <summary> /// Raw Input 関連のクラス、構造体、Win32APIの定義。 /// </summary> /// <remarks> /// RawInput はすべて GUI スレッドで実行すること。 /// </remarks> public class RawInput { [Flags] public enum DeviceFlags : uint { /// <summary> /// 既定のデバイス。 /// </summary> None = 0x00000000, /// <summary> /// アプリケーションキーを扱う。 /// </summary> /// <remarks> /// このフラグを設定すると、アプリケーションコマンドキーを扱うことができる。 /// このフラグは、キーボードデバイスに対して <see cref="NoLegacy"/> フラグが設定されている時のみ設定することができる。 /// </remarks> AppKeys = 0x00000400, /// <summary> /// マウスボタンをキャプチャする。 /// </summary> /// <remarks> /// このフラグを設定すると、マウスボタンをクリックしても、他のウィンドウをアクティブにしなくなる。 /// </remarks> CaptureMouse = 0x00000200, /// <summary> /// デバイスの接続・取り外しを通知する。 /// </summary> /// <remarks> /// このフラグを設定すると、デバイスが接続または取り外されたときに WM_INPUT_DEVICE_CHANGE メッセージが発行される。 /// このフラグは、Windows Vista 以降でのみサポートされる。 /// </remarks> DeviceNotify = 0x00002000, /// <summary> /// 特定の TLC を除外する。 /// </summary> /// <remarks> /// このフラグを設定すると、特定の Usage Page に属する Top Level Collection を除外することを示す。 /// このフラグは、<see cref="PageOnly"/> が指定された Usage Page の TLC に対してのみ有効。 /// </remarks> Exclude = 0x00000010, /// <summary> /// バックグラウンドで入力を排他的に取得する。 /// </summary> /// <remarks> /// このフラグを設定すると、フォアグラウンドアプリケーションが処理しなかった入力を、バックグラウンドで受け取ることができる。 /// 言い換えれば、フォアグラウンドアプリケーションが Raw Input に登録されておらず、バックグラウンドアプリケーションが登録されているなら、入力を受け取ることができる。 /// このフラグは、Windows Vista 以降でのみサポートされる。 /// </remarks> ExclusiveInputSink = 0x00001000, /// <summary> /// バックグラウンドで入力を取得する。 /// </summary> /// <remarks> /// このフラグを設定すると、フォアグラウンドにない状態でも入力を受け取ることができる。 /// <see cref="RawInputDevice.hwndTarget"/> が必ず設定されていること。 /// </remarks> InputSink = 0x00000100, /// <summary> /// アプリケーション定義のホットキーを無効化する。 /// </summary> /// <remarks> /// このフラグを設定すると、アプリケーション定義のキーボードデバイスホットキーが扱われなくなる。 /// ただし、システム定義のホットキー(例えば ALT+TAB や CTRL+ALT+DEL)は扱われる。 /// 既定では、すべてのキーボードホットキーが扱われる。 /// このフラグは、<see cref="NoLegacy"/> フラグが未設定で <see cref="RawInputDevice.hwndTarget"/> が <see cref="IntPtr.Zero"/> である場合でも設定することができる。 /// </remarks> NoHotKeys = 0x00000200, /// <summary> /// レガシーメッセージを抑制する。 /// </summary> /// <remarks> /// このフラグを設定すると、<see cref="RawInputDevice.usUsagePage"/> または <see cref="RawInputDevice.usUsage"/> で指定されたすべてのデバイスに対して、 /// レガシーメッセージを生成しなくなる。 /// これは、マウスとキーボードに対してのみ有効。 /// </remarks> NoLegacy = 0x00000030, /// <summary> /// 特定の Usage Page の全デバイスを使用する。 /// </summary> /// <remarks> /// このフラグを設定すると、指定された <see cref="RawInputDevice.usUsagePage"/> の Top Level Collection に属するすべてのデバイスが対象となる。 /// <see cref="RawInputDevice.usUsage"/> はゼロでなければならない。 /// 特定の TLC を除外するには、<see cref="Exclude"/> フラグを使用する。 /// </remarks> PageOnly = 0x00000020, /// <summary> /// デバイスを対象外にする。 /// </summary> /// <remarks> /// このフラグを設定すると、Top Level Collection が対象から外される。 /// このフラグは、OS に対して、その TLC に適合するデバイスからの読み込みを停止するよう通知する。 /// </remarks> Remove = 0x00000001, } public enum DataType : uint { /// <summary> /// <see cref="RawInputData"/> からヘッダ情報を取得する。 /// </summary> Header = 0x10000005, /// <summary> /// <see cref="RawInputData"/> から生データを取得する。 /// </summary> Input = 0x10000003, } public enum DeviceType : uint { /// <summary> /// マウスからの Raw Input を扱う。 /// </summary> Mouse = 0, /// <summary> /// キーボードからの Raw Input を扱う。 /// </summary> Keyboard = 1, /// <summary> /// マウスとキーボード以外の任意のデバイスからの Raw Input を扱う。 /// </summary> HumanInputDevice = 2, } [Flags] public enum ScanCodeFlags : short { /// <summary> /// キーは押されている。 /// </summary> Make = 0x0000, /// <summary> /// キーは離されている。 /// </summary> Break = 0x0001, /// <summary> /// スキャンコードは、E0 エスケープを持っている。 /// </summary> E0 = 0x0002, /// <summary> /// スキャンコードは、E1 エスケープを持っている。 /// </summary> E1 = 0x0004, } public enum DeviceInfoType : uint { /// <summary> /// デバイス名を表す文字列。 /// </summary> DeviceName = 0x20000007, /// <summary> /// <see cref="DeviceInfo"/> 構造体。 /// </summary> DeviceInfo = 0x2000000b, /// <summary> /// 事前解析されたデータ。 /// </summary> PreparsedData = 0x20000005, } [Flags] public enum MouseButtonFlags : short { None = 0x0000, /// <summary> /// 左ボタンが押された。 /// </summary> Button1Down = 0x0001, /// <summary> /// 左ボタンが離された。 /// </summary> Button1Up = 0x0002, /// <summary> /// 右ボタンが押された。 /// </summary> Button2Down = 0x0004, /// <summary> /// 右ボタンが離された。 /// </summary> Button2Up = 0x0008, /// <summary> /// 中ボタンが押された。 /// </summary> Button3Down = 0x0010, /// <summary> /// 中ボタンが離された。 /// </summary> Button3Up = 0x0020, /// <summary> /// XBUTTON1 が押された。 /// </summary> Button4Down = 0x0040, /// <summary> /// XBUTTON1 が離された。 /// </summary> Button4Up = 0x0080, /// <summary> /// XBUTTON2 が押された。 /// </summary> Button5Down = 0x0100, /// <summary> /// XBUTTON2 が離された。 /// </summary> Button5Up = 0x0200, /// <summary> /// マウスホイールが回転した。 /// <see cref="RawMouse.ButtonsData"/> にホイールの回転差分量が格納されている。 /// </summary> MouseWheel = 0x0400, /// <summary> /// マウスホイールが水平方向に移動された。 /// <see cref="RawMouse.ButtonsData"/> が正なら右、負なら左を示す。 /// </summary> Hwheel = 0x0800, // 以下別名 /// <summary> /// 左ボタンが押された。 /// </summary> LeftButtonDown = 0x0001, /// <summary> /// 左ボタンが離された。 /// </summary> LeftButtonUp = 0x0002, /// <summary> /// 右ボタンが押された。 /// </summary> RightButtonDown = 0x0004, /// <summary> /// 右ボタンが離された。 /// </summary> RightButtonUp = 0x0008, /// <summary> /// 中ボタンが押された。 /// </summary> MiddleButtonDown = 0x0010, /// <summary> /// 中ボタンが離された。 /// </summary> MiddleButtonUp = 0x0020, } [Flags] public enum MouseMode : short { /// <summary> /// マウスの移動データは、最後のマウス位置に対する相対位置である。 /// </summary> MoveRelative = 0x0000, /// <summary> /// マウスの移動データは、絶対位置である。 /// </summary> MoveAbsolute = 0x0001, /// <summary> /// マウス座標は、(マルチディスプレイシステム用の)仮想デスクトップにマップされる。 /// </summary> VirtualDesktop = 0x0002, /// <summary> /// マウスの属性が変化した。 /// </summary> /// <remarks> /// アプリケーションは、マウスの属性をクエリする必要がある。 /// </remarks> AttributesChanged = 0x0004, /// <summary> /// WM_MOUSEMOVE メッセージは合体されない。 /// </summary> /// <remarks> /// Windows Vista 以降でサポートされる。 /// 既定では、WM_MOUSEMOVE メッセージは合体される。 /// </remarks> MoveNoCoalesce = 0x0008, } [StructLayout( LayoutKind.Sequential )] public struct RawInputDevice { /// <summary> /// Raw Input デバイスの Top Level Collection Usage Page。 /// </summary> public UsagePage usUsagePage; /// <summary> /// Raw Input デバイスの Top Level Collection Usage。 /// </summary> public UsageId usUsage; /// <summary> /// 提供された <see cref="RawInputDevice.usUsagePage"/> と <see cref="RawInputDevice.usUsage"/> をどのように解釈するかを示すフラグ。 /// </summary> /// <remarks> /// このフラグはゼロにすることができる(既定値)。 /// 既定では、OS は、Top Level Collection (TLC) で指定された Raw Input を、登録されたアプリケーションに対して、そのウィンドウがフォーカスを得ている間、送信する。 /// </remarks> public DeviceFlags Flags; /// <summary> /// ターゲットウィンドウのハンドル。 /// </summary> /// <remarks> /// <see cref="IntPtr.Zero"/> の場合は、キーボードのフォーカスに従う。 /// </remarks> public IntPtr hwndTarget; }; public unsafe class RawInputData { [StructLayout( LayoutKind.Sequential )] public struct Native { public RawInputHeader.Native Header; public RawInputUnionData0 Data; [StructLayout( LayoutKind.Explicit )] public struct RawInputUnionData0 { [FieldOffset( 0 )] public RawMouse.Native Mouse; [FieldOffset( 0 )] public RawKeyboard.Native Keyboard; [FieldOffset( 0 )] public RawHid.Native Hid; } } /// <summary> /// Raw Input ヘッダ情報。 /// </summary> public RawInputHeader Header { get; set; } /// <summary> /// マウスの Raw Input データ。無効なら null。 /// </summary> public RawMouse? Mouse { get; set; } /// <summary> /// キーボードの Raw Input データ。無効なら null。 /// </summary> public RawKeyboard? Keyboard { get; set; } /// <summary> /// キーボードとマウス以外のデバイスの Raw Input データ。無効なら null。 /// </summary> public RawHid? Hid { get; set; } public RawInputData() { this.Header = new RawInputHeader(); this.Mouse = null; this.Keyboard = null; this.Hid = null; } public RawInputData( in Native native ) : this() { fixed( Native* pNative = &native ) this.RestoreFrom( pNative ); } public void MarshalTo( Native* pNative ) { this.Header.MarshalTo( &pNative->Header ); this.Mouse?.MarshalTo( &pNative->Data.Mouse ); this.Keyboard?.MarshalTo( &pNative->Data.Keyboard ); this.Hid?.MarshalTo( &pNative->Data.Hid ); } public void RestoreFrom( Native* pNative ) { this.Header = new RawInputHeader( pNative->Header ); switch( this.Header.Type ) { case DeviceType.Mouse: this.Mouse = new RawMouse( pNative->Data.Mouse ); break; case DeviceType.Keyboard: this.Keyboard = new RawKeyboard( pNative->Data.Keyboard ); break; case DeviceType.HumanInputDevice: this.Hid = new RawHid( pNative->Data.Hid ); break; default: throw new ArgumentException( $"未知のDeviceTypeです。[{this.Header.Type}]" ); } } } public unsafe class RawInputHeader { [StructLayout( LayoutKind.Sequential )] public struct Native { public DeviceType Type; public int Size; public IntPtr hDevice; public IntPtr wParam; } /// <summary> /// Raw Inpu デバイスの種別。 /// </summary> public DeviceType Type { get; set; } /// <summary> /// データの入力パケット全体のサイズ(バイト単位)。 /// </summary> /// <remarks> /// これには、<see cref="RawInputData"/> に加えて、<see cref="RawHid"/> 可変長配列の中の拡張入力レポートも(あるなら)含まれる。 /// </remarks> public int Size { get; set; } /// <summary> /// Raw Input データを生成するデバイスのハンドル。 /// </summary> public IntPtr hDevice { get; set; } /// <summary> /// WM_INPUT メッセージの <see cref="System.Windows.Forms.Message.WParam"/> で渡される値。 /// </summary> public IntPtr wParam { get; set; } public RawInputHeader() { } public RawInputHeader( in Native native ) : this() { fixed( Native* pNative = &native ) this.RestoreFrom( pNative ); } public void MarshalTo( Native* pNative ) { pNative->Type = this.Type; pNative->Size = this.Size; pNative->hDevice = this.hDevice; pNative->wParam = this.wParam; } public void RestoreFrom( Native* pNative ) { this.Type = pNative->Type; this.Size = pNative->Size; this.hDevice = pNative->hDevice; this.wParam = pNative->wParam; } } public unsafe class RawMouse { [StructLayout( LayoutKind.Sequential )] public struct Native { public MouseMode Flags; public RawMouseButtonsData.Native ButtonsData; public int RawButtons; public int LastX; public int LastY; public int ExtraInformation; } /// <summary> /// マウスの状態。 /// </summary> public MouseMode Flags { get; set; } public RawMouseButtonsData ButtonsData { get; set; } /// <summary> /// 生のボタンデータ。 /// </summary> public int RawButtons { get; set; } /// <summary> /// X軸方向の移動量。 /// </summary> /// <remarks> /// この値は、符号付き相対移動量または絶対移動量であり、それは <see cref="Flags"/> に依存する。 /// </remarks> public int LastX { get; set; } /// <summary> /// Y軸方向の移動量。 /// </summary> /// <remarks> /// この値は、符号付き相対移動量または絶対移動量であり、それは <see cref="Flags"/> に依存する。 /// </remarks> public int LastY { get; set; } /// <summary> /// デバイス定義の追加情報。 /// </summary> public int ExtraInformation { get; set; } public RawMouse() { this.ButtonsData = new RawMouseButtonsData(); } public RawMouse( in Native native ) : this() { fixed( Native* pNative = &native ) this.RestoreFrom( pNative ); } public void MarshalTo( Native* pNative ) { pNative->Flags = this.Flags; this.ButtonsData.MarshalTo( &pNative->ButtonsData ); pNative->RawButtons = this.RawButtons; pNative->LastX = this.LastX; pNative->LastY = this.LastY; pNative->ExtraInformation = this.ExtraInformation; } public void RestoreFrom( Native* pNative ) { this.Flags = pNative->Flags; this.ButtonsData = new RawMouseButtonsData( pNative->ButtonsData ); this.RawButtons = pNative->RawButtons; this.LastX = pNative->LastX; this.LastY = pNative->LastY; this.ExtraInformation = pNative->ExtraInformation; } } public unsafe class RawMouseButtonsData { [StructLayout( LayoutKind.Explicit )] public struct Native { [FieldOffset( 0 )] public int ulButtons; [FieldOffset( 0 )] public MouseButtonFlags usButtonFlags; [FieldOffset( 2 )] public short usButtonData; } /// <summary> /// Reserved. /// </summary> public int ulButtons { get; set; } /// <summary> /// マウスボタンの遷移状態。 /// </summary> public MouseButtonFlags usButtonFlags { get; set; } /// <summary> /// マウスホイールが水平または縦に移動すれば、ここに移動差分量が格納される。 /// </summary> public short usButtonData { get; set; } public RawMouseButtonsData() { } public RawMouseButtonsData( in Native native ) : this() { fixed( Native* pNative = &native ) this.RestoreFrom( pNative ); } public void MarshalTo( Native* pNative ) { pNative->usButtonFlags = this.usButtonFlags; pNative->usButtonData = this.usButtonData; } public void RestoreFrom( Native* pNative ) { this.usButtonFlags = pNative->usButtonFlags; this.usButtonData = pNative->usButtonData; } } public unsafe class RawKeyboard { [StructLayout( LayoutKind.Sequential, Pack = 1 )] public struct Native { public short MakeCode; public ScanCodeFlags Flags; public short Reserved; public short VKey; public uint Message; public int ExtraInformation; } /// <summary> /// スキャンコード。 /// </summary> /// <remarks> /// キーボードのオーバーランに対するスキャンコードは、KEYBOARD_OVERRUN_MAKE_CODE (0xFF) である。 /// </remarks> public short MakeCode; /// <summary> /// スキャンコード情報に関するフラグ。 /// </summary> public ScanCodeFlags Flags; /// <summary> /// 予約済み;ゼロであること。 /// </summary> public short Reserved; /// <summary> /// Windows メッセージ互換の仮想キーコード。 /// </summary> public short VKey; /// <summary> /// 対応するウィンドウメッセージ。 /// WM_KEYDOWN, WM_SYSKEYDOWN など。 /// </summary> public uint Message; /// <summary> /// デバイス定義の追加情報。 /// </summary> public int ExtraInformation; public RawKeyboard() { } public RawKeyboard( in Native native ) : this() { fixed( Native* pNative = &native ) this.RestoreFrom( pNative ); } public void MarshalTo( Native* pNative ) { pNative->MakeCode = this.MakeCode; pNative->Flags = this.Flags; pNative->Reserved = this.Reserved; pNative->VKey = this.VKey; pNative->Message = this.Message; pNative->ExtraInformation = this.ExtraInformation; } public void RestoreFrom( Native* pNative ) { this.MakeCode = pNative->MakeCode; this.Flags = pNative->Flags; this.Reserved = pNative->Reserved; this.VKey = pNative->VKey; this.Message = pNative->Message; this.ExtraInformation = pNative->ExtraInformation; } } public unsafe class RawHid { [StructLayout( LayoutKind.Sequential )] public struct Native { public int SizeHid; public int Count; public byte RawData; // 実際はBYTE[SizeHid*Count]。構造体のサイズ計算を行う場合には注意。 } /// <summary> /// <see cref="RawData"/> フィールド内のそれぞれの HID 入力のサイズ(バイト単位)。 /// </summary> public int SizeHid { get; set; } /// <summary> /// <see cref="RawData"/> フィールド内の HID 入力の数. /// </summary> public int Count { get; set; } /// <summary> /// Type: BYTE[1] /// Raw Input データ。バイトの配列。 /// </summary> public byte[] RawData { get; set; } = null!; public RawHid() { } public RawHid( in Native native ) : this() { fixed( Native* pNative = &native ) this.RestoreFrom( pNative ); } public void MarshalTo( Native* pNative ) { throw new NotImplementedException(); } public void RestoreFrom( Native* pNative ) { this.SizeHid = pNative->SizeHid; this.Count = pNative->Count; this.RawData = new byte[ this.SizeHid * this.Count ]; byte* p = &pNative->RawData; for( int i = 0; i < this.RawData.Length; i++ ) this.RawData[ i ] = *p++; } } [StructLayout( LayoutKind.Sequential )] public struct RawInputDevicelist { /// <summary> /// Raw Input デバイスのハンドル。 /// </summary> public IntPtr Device; /// <summary> /// デバイスの種別。 /// </summary> public DeviceType Type; } [StructLayout( LayoutKind.Explicit )] public struct DeviceInfo { [FieldOffset( 0 )] public int Size; [FieldOffset( 4 )] public DeviceType Type; // 以下、共用体。 [FieldOffset( 8 )] public DeviceInfoMouse Mouse; [FieldOffset( 8 )] public DeviceInfoKeyboard Keyboard; [FieldOffset( 8 )] public DeviceInfoHid Hid; } [StructLayout( LayoutKind.Sequential )] public struct DeviceInfoMouse { /// <summary> /// マウスデバイスの識別子。 /// </summary> public int Id; /// <summary> /// マウスのボタンの数。 /// </summary> public int NumberOfButtons; /// <summary> /// 1秒あたりのデータ位置の数。 /// </summary> /// <remarks> /// この情報は、必ずしもすべてのマウスデバイスに対して適用可能とは限らない。 /// </remarks> public int SampleRate; /// <summary> /// true なら、マウスは水平スクロール可能なホイールを持つ。そうでないなら false。 /// </summary> /// <remarks> /// このメンバは、Windows Vista 以降でのみサポートされる。 /// </remarks> [MarshalAs( UnmanagedType.Bool )] public bool HasHorizontalWheel; } [StructLayout( LayoutKind.Sequential )] public struct DeviceInfoKeyboard { /// <summary> /// キーボードの種別。 /// </summary> public int Type; /// <summary> /// キーボードのサブタイプ。 /// </summary> public int SubType; /// <summary> /// スキャンコードモード。 /// </summary> public int KeyboardMode; /// <summary> /// キーボード上のファンクションキーの数。 /// </summary> public int NumberOfFunctionKeys; /// <summary> /// キーボード上の LED インジケータの数。 /// </summary> public int NumberOfIndicators; /// <summary> /// キーボード上のキーの総数。 /// </summary> public int NumberOfKeysTotal; } [StructLayout( LayoutKind.Sequential )] public struct DeviceInfoHid { /// <summary> /// この HID の VendorID。 /// </summary> public int VendorId; /// <summary> /// この HID の ProductID。 /// </summary> public int ProductId; /// <summary> /// この HID のバージョン番号。 /// </summary> public int VersionNumber; /// <summary> /// デバイスに対する Top Level Collection Usage Page。 /// </summary> public UsagePage UsagePage; /// <summary> /// デバイスに対する Top Level Collection Usage。 /// </summary> public UsageId Usage; } /// <summary> /// Raw Input デバイスを登録する。 /// </summary> /// <param name="pRawInputDevices">Raw Input を供給するデバイスを表す <see cref="RawInputDevice"/> 構造体の配列。</param> /// <param name="uiNumDevices"><paramref name="pRawInputDevices"/> で示される <see cref="RawInputDevice"/> 構造体の数。</param> /// <param name="cbSize"><see cref="RawInputDevice"/> 構造体のサイズ(バイト単位)。</param> /// <returns>成功すれば true、失敗すれば false。</returns> [DllImport( "user32.dll", SetLastError = true )] [return: MarshalAs( UnmanagedType.Bool )] public static extern bool RegisterRawInputDevices( RawInputDevice[] pRawInputDevices, int uiNumDevices, int cbSize ); /// <summary> /// 指定したデバイスから Raw Input を取得する。 /// </summary> /// <param name="hDevice"><see cref="RawInputData"/> 構造体へのハンドル。WM_INPUT の lParam から取得される。</param> /// <param name="uiCommand">取得する内容を示すフラグ。</param> /// <param name="pData"><see cref="RawInputData"/> 構造体から得られるデータを示すポインタ。これは、<paramref name="uiCommand"/> の値に依存する。<see cref="IntPtr.Zero"/> を指定すると、必要なバッファのサイズが <paramref name="pcbSize"/> に格納される。</param> /// <param name="pcbSize"><paramref name="pData"/>メンバのサイズ(バイト単位)。</param> /// <param name="cbSizeHeader"><see cref="RawInputHeader"/> 構造体のサイズ(バイト単位)。</param> /// <returns> /// <paramref name="pData"/> が <see cref="IntPtr.Zero"/> かつ成功した場合、0 が返される。 /// <paramref name="pData"/> が有効でかつ成功した場合、<paramref name="pData"/> にコピーされたバイト数を返す。 /// エラーが発生した場合は -1 が返される。 /// </returns> [DllImport( "user32.dll", SetLastError = true )] public static extern int GetRawInputData( IntPtr hDevice, DataType uiCommand, out RawInputData pData, ref int pcbSize, int cbSizeHeader ); [DllImport( "user32.dll", SetLastError = true )] public static extern int GetRawInputData( IntPtr hDevice, DataType uiCommand, ref IntPtr pData, ref int pcbSize, int cbSizeHeader ); [DllImport( "user32.dll", SetLastError = true )] public static extern int GetRawInputData( IntPtr hDevice, DataType uiCommand, [In, Out] byte[]? pData, ref int pcbSize, int cbSizeHeader ); [DllImport( "user32.dll", SetLastError = true )] public static unsafe extern int GetRawInputData( IntPtr hDevice, DataType uiCommand, byte* pData, int* pcbSize, int cbSizeHeader ); /// <summary> /// システムに接続されている Raw Input デバイスを列挙する。 /// </summary> /// <param name="pRawInputDeviceList">システムに接続されあtデバイスの <see cref="RawInputDevicelist"/> 構造体の配列。null を指定すると、デバイスの数が <paramref name="uiNumDevices"/> に返される。</param> /// <param name="uiNumDevices"> /// <paramref name="pRawInputDeviceList"/> が null である場合、システムに接続されているデバイスの数がこの引数に格納される。 /// そうでない場合、<paramref name="pRawInputDeviceList"/> が示すバッファに含まれている <see cref="RawInputDevicelist"/> 構造体の数を指定する。 /// この値がシステムに接続されているデバイスの数よりも小さい場合、この引数には実際のデバイス数が返され、メソッドは ERROR_INSUFFICIENT_BUFFER エラーで失敗する。 /// </param> /// <param name="cbSize"><see cref="RawInputDevicelist"/> 構造体のサイズ(バイト単位)。</param> /// <returns>成功した場合は、<paramref name="pRawInputDeviceList"/> に格納されたデバイスの数が返される。エラーが発生した場合は -1 が返される。</returns> [DllImport( "user32.dll", SetLastError = true )] public static extern int GetRawInputDeviceList( [In, Out] RawInputDevicelist[] pRawInputDeviceList, ref int uiNumDevices, int cbSize ); /// <summary> /// Raw Input デバイスの情報を取得する。 /// </summary> /// <param name="hDevice">Raw Input デバイスのハンドル。この値は、<see cref="RawInputHeader.hDevice"/> または <see cref="GetRawInputDeviceList(RawInputDevicelist[], ref int, int)"/> から取得される。</param> /// <param name="uiCommand"><paramref name="pData"/> に何のデータが返されるかを示す。</param> /// <param name="pData"> /// <paramref name="uiCommand"/> で指定される情報を格納するバッファへのポインタ。 /// <paramref name="uiCommand"/> が <see cref="DeviceInfoType.DeviceInfo"/> である場合、このメソッドを呼び出す前に、<paramref name="pcbSize"/> に <see cref="DeviceInfo"/> 構造体のサイズ(バイト単位)を格納すること。 /// </param> /// <param name="pcbSize"><paramref name="pData"/> に含まれるデータのサイズ(バイト単位)。</param> /// <returns> /// 成功した場合、このメソッドは 0 以上の値を返す。これは、<paramref name="pData"/> にコピーされたバイト数を示している。 /// <paramref name="pData"/> がデータに対して十分に大きくない場合、-1 が返される。 /// <paramref name="pData"/> が <see cref="IntPtr.Zero"/> である場合、0 が返される。 /// いずれの場合も、<paramref name="pcbSize"/> には <paramref name="pData"/> バッファに必要となる最小のサイズが設定される。 /// </returns> [DllImport( "user32.dll", SetLastError = true, CharSet = CharSet.Auto )] public static extern uint GetRawInputDeviceInfo( IntPtr hDevice, DeviceInfoType uiCommand, [In, Out] IntPtr pData, ref int pcbSize ); [DllImport( "user32.dll", SetLastError = true )] public static extern uint GetRawInputBuffer( [In, Out] RawInputData[] pData, ref uint cbSize, uint csSizeHeader ); [DllImport( "user32.dll", SetLastError = true, EntryPoint = "GetRawInputBuffer" )] public static extern uint GetRawInputBufferB( ref IntPtr pData, ref uint cbSize, uint csSizeHeader ); } } <|start_filename|>SSTFEditor/Properties/Resources.Designer.cs<|end_filename|> //------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace SSTFEditor.Properties { using System; /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスが ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 /// </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("SSTFEditor.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Config.xml に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string CONFIG_FILE_NAME { get { return ResourceManager.GetString("CONFIG_FILE_NAME", resourceCulture); } } /// <summary> /// 6912 に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string GRID_PER_PART { get { return ResourceManager.GetString("GRID_PER_PART", resourceCulture); } } /// <summary> /// 27 に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string GRID_PER_PIXEL { get { return ResourceManager.GetString("GRID_PER_PIXEL", resourceCulture); } } /// <summary> /// (アイコン) に類似した型 System.Drawing.Icon のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Icon Icon { get { object obj = ResourceManager.GetObject("Icon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Set BPM value. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_BPM選択ダイアログの説明文 { get { return ResourceManager.GetString("MSG_BPM選択ダイアログの説明文", resourceCulture); } } /// <summary> /// Are you sure you want to load it and convert to SSTFormat? に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_SSTF形式に変換します { get { return ResourceManager.GetString("MSG_SSTF形式に変換します", resourceCulture); } } /// <summary> /// Error に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_エラーダイアログのタイトル { get { return ResourceManager.GetString("MSG_エラーダイアログのタイトル", resourceCulture); } } /// <summary> /// Please wait a minute. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_しばらくお待ち下さい { get { return ResourceManager.GetString("MSG_しばらくお待ち下さい", resourceCulture); } } /// <summary> /// exe files (*.exe)|*.exe に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_ビュアー選択ダイアログのフィルタ { get { return ResourceManager.GetString("MSG_ビュアー選択ダイアログのフィルタ", resourceCulture); } } /// <summary> /// Failed to save the file. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_ファイルの保存に失敗しました { get { return ResourceManager.GetString("MSG_ファイルの保存に失敗しました", resourceCulture); } } /// <summary> /// Select Song file に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_ファイル選択ダイアログのタイトル { get { return ResourceManager.GetString("MSG_ファイル選択ダイアログのタイトル", resourceCulture); } } /// <summary> /// Saving now... に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_保存中です { get { return ResourceManager.GetString("MSG_保存中です", resourceCulture); } } /// <summary> /// chips were selected. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_個のチップが選択されました { get { return ResourceManager.GetString("MSG_個のチップが選択されました", resourceCulture); } } /// <summary> /// Invalid file. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_対応していないファイルです { get { return ResourceManager.GetString("MSG_対応していないファイルです", resourceCulture); } } /// <summary> /// Part memo に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_小節メモ { get { return ResourceManager.GetString("MSG_小節メモ", resourceCulture); } } /// <summary> /// Invalid number in start part. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_小節番号に誤りがあります { get { return ResourceManager.GetString("MSG_小節番号に誤りがあります", resourceCulture); } } /// <summary> /// Song files (*.sstf;*.dtx;*.gda;*.g2d;*.bms;*.bme)|*.sstf;*.dtx;*.gda;*.g2d;*.bms;*.bme に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_曲ファイル選択ダイアログのフィルタ { get { return ResourceManager.GetString("MSG_曲ファイル選択ダイアログのフィルタ", resourceCulture); } } /// <summary> /// Search result に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_検索結果ダイアログのタイトル { get { return ResourceManager.GetString("MSG_検索結果ダイアログのタイトル", resourceCulture); } } /// <summary> /// Image files (*.png;*.jpg;*.jpeg;*.bmp)|*.png;*.jpg;*.jpeg;*.bmp に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_画像ファイル選択ダイアログのフィルタ { get { return ResourceManager.GetString("MSG_画像ファイル選択ダイアログのフィルタ", resourceCulture); } } /// <summary> /// Confirm に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_確認ダイアログのタイトル { get { return ResourceManager.GetString("MSG_確認ダイアログのタイトル", resourceCulture); } } /// <summary> /// Save changes to file ? に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_編集中のデータを保存しますか { get { return ResourceManager.GetString("MSG_編集中のデータを保存しますか", resourceCulture); } } /// <summary> /// Media files (*.mp4;*.avi;*.wmv;*.mpg;*.mpeg;*.wav;*.ogg;*.xa;*.mp3)|*.mp4;*.avi;*.wmv;*.mpg;*.mprg;*.wav;*.ogg;*.xa;*.mp3 に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_背景動画ファイル選択ダイアログのフィルタ { get { return ResourceManager.GetString("MSG_背景動画ファイル選択ダイアログのフィルタ", resourceCulture); } } /// <summary> /// Chips not found. に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_該当するチップはありませんでした { get { return ResourceManager.GetString("MSG_該当するチップはありませんでした", resourceCulture); } } /// <summary> /// Loading now... に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string MSG_読み込み中です { get { return ResourceManager.GetString("MSG_読み込み中です", resourceCulture); } } /// <summary> /// New に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string NEW_FILENAME { get { return ResourceManager.GetString("NEW_FILENAME", resourceCulture); } } /// <summary> /// DTXMania.exe に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string PLAYER_NAME { get { return ResourceManager.GetString("PLAYER_NAME", resourceCulture); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap りらちょー { get { object obj = ResourceManager.GetObject("りらちょー", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap 既定のプレビュー画像 { get { object obj = ResourceManager.GetObject("既定のプレビュー画像", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } } <|start_filename|>DTXMania2/曲/Tree/曲ツリー_全曲.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.曲 { class 曲ツリー_全曲 : 曲ツリー { // プロパティ public long 進捗カウンタ => Interlocked.Read( ref this._進捗カウンタ ); // 生成と終了 public 曲ツリー_全曲() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._進捗カウンタ = 0; } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); base.Dispose(); } // ツリーと全譜面リストの構築 /// <summary> /// 標準の曲ツリーを構築する。 /// </summary> /// <remarks> /// 曲ツリーは、曲検索フォルダを検索した結果に、現状の(現行前の)ScoreDB の内容を反映したものとなる。 /// 曲ツリーを構築すると同時に、全曲リスト/全譜面リストも構築する。 /// </remarks> public async Task 構築するAsync( IEnumerable<VariablePath> 曲検索フォルダパスリスト ) { //using var _ = new LogBlock( Log.現在のメソッド名 ); // 曲検索フォルダパスをスキャンして、曲ツリー(と全譜面リスト)を構築する。 await Task.Run( () => { // ルートノードの子ノードリストの先頭に「ランダムセレクト」を追加する。 this.ルートノード.子ノードリスト.Add( new RandomSelectNode() { 親ノード = this.ルートノード } ); // 曲検索パスに従って、ルートノード以降を構築する。 // 同時に、この中で、全曲リストと全譜面リストも構築する。 foreach( var path in 曲検索フォルダパスリスト ) this._構築する( path, this.ルートノード ); // 最初の子ノードをフォーカスする。 this.フォーカスリスト.SelectFirst(); } ); } /// <summary> /// 現状の ScoreDB と ScorePropertiesDB(ともに現行化前)を読み込んで反映する。 /// </summary> public async Task ノードにDBを反映するAsync() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this._進捗カウンタ = 0; await Task.Run( () => { // 全レコード抽出 using var scoredb = new ScoreDB(); using var scorePropertiesdb = new ScorePropertiesDB(); using var query = new SqliteCommand( "SELECT * FROM Scores", scoredb.Connection ); var result = query.ExecuteReader(); while( result.Read() ) { Interlocked.Increment( ref this._進捗カウンタ ); var record = new ScoreDBRecord( result ); // レコードに記載されているパスが全譜面リストに存在していれば、レコードの内容で更新する。 foreach( var score in Global.App.全譜面リスト.Where( ( s ) => s.譜面.ScorePath == record.ScorePath ) ) score.譜面.UpdateFrom( record ); } } ); } /// <summary> /// 文字列画像のみ生成する。(現行化待ち中に表示されるため) /// </summary> public async Task 文字列画像を生成するAsync() { //using var _ = new LogBlock( Log.現在のメソッド名 ); this._進捗カウンタ = 0; await Task.Run( () => { foreach( var score in Global.App.全譜面リスト ) { Interlocked.Increment( ref this._進捗カウンタ ); score.タイトル文字列画像 = 現行化.タイトル文字列画像を生成する( score.譜面.Title ); score.サブタイトル文字列画像 = 現行化.サブタイトル文字列画像を生成する( score.譜面.Artist ); } } ); } // ローカル private long _進捗カウンタ; // Interlocked でアクセスすること /// <summary> /// 1つのフォルダに対して検索と構築を行う。 /// 同時に、全譜面リストと全曲リストも構築する。 /// </summary> /// <param name="基点フォルダパス">検索フォルダの絶対パス。</param> /// <param name="親ノード">ノードは、このノードの子ノードとして構築される。</param> /// <param name="boxdefが有効">true にすると、フォルダ内の box.def が有効になる。false にすると box.def を無視する。</param> private void _構築する( VariablePath 基点フォルダパス, BoxNode 親ノード, bool boxdefが有効 = true ) { #region " 基点フォルダが存在しない場合やアクセスできない場合は無視。" //---------------- if( !( Directory.Exists( 基点フォルダパス.変数なしパス ) ) ) { Log.WARNING( $"指定されたフォルダが存在しません。無視します。[{基点フォルダパス.変数付きパス}]" ); return; } try { Directory.GetFiles( 基点フォルダパス.変数なしパス ); } catch( UnauthorizedAccessException ) { Log.ERROR( $"アクセスできないフォルダです。無視します。[{基点フォルダパス.変数付きパス}]" ); return; } //---------------- #endregion // 一時リスト。作成したノードをいったんこのノードリストに格納し、あとでまとめて曲ツリーに登録する。 var 追加ノードリスト = new List<Node>(); // (1) フォルダ内のファイルからノードを作成 // set.def/box.def ファイルの有無により処理分岐。 var dirInfo = new DirectoryInfo( 基点フォルダパス.変数なしパス ); var boxDefPath = new VariablePath( Path.Combine( 基点フォルダパス.変数なしパス, @"box.def" ) ); var setDefPath = new VariablePath( Path.Combine( 基点フォルダパス.変数なしパス, @"set.def" ) ); bool サブフォルダを検索する = true; if( boxdefが有効 && File.Exists( boxDefPath.変数なしパス ) ) { #region " (A) このフォルダに box.def がある → BOXノードを作成し、子ノードリストを再帰的に構築する。" //---------------- // box.defを読み込んでBOXノードを作成する。 var boxDef = new BoxDef( boxDefPath ); var boxNode = new BoxNode( boxDef ); 追加ノードリスト.Add( boxNode ); // BOXノードの子ノードリストの先頭に「戻る」と「ランダムセレクト」を追加する。 boxNode.子ノードリスト.Add( new BackNode() { 親ノード = boxNode } ); boxNode.子ノードリスト.Add( new RandomSelectNode() { 親ノード = boxNode } ); // このフォルダを対象として再帰的に構築する。ただし box.def は無効とする。 // 親ノードとしてBOXノードを指定しているので、構築結果のノードはBOXノードの子として付与される。 this._構築する( 基点フォルダパス, boxNode, boxdefが有効: false ); // box.def があった場合、サブフォルダは検索しない。 サブフォルダを検索する = false; //---------------- #endregion } else if( File.Exists( setDefPath.変数なしパス ) ) { #region " (B) このフォルダに set.def がある → その内容で任意個のノードを作成する。" //---------------- Interlocked.Increment( ref this._進捗カウンタ ); // set.def を読み込む。 var setDef = new SetDef( setDefPath ); // set.def 内のすべてのブロックについて、Song と SongNode を作成する。 var list = new List<Node>( 5 ); foreach( var block in setDef.Blocks ) { // set.def のブロックから Song を生成する。 var song = new Song( block, dirInfo.FullName ); // L1~L5が1つ以上有効なら、このブロックに対応する SongNode を生成する。 if( song.譜面リスト.Any( ( score ) => null != score ) ) list.Add( new SongNode( song ) ); } // 1つ以上の SongNode がある(1つ以上の有効なブロックがある)場合のみ登録する。 if( 0 < list.Count ) 追加ノードリスト.AddRange( list ); // set.def があった場合、サブフォルダは検索しない。 サブフォルダを検索する = false; //---------------- #endregion } else { #region " (C) box.def も set.def もない → このフォルダにあるすべての譜面ファイルを検索してノードを作成する。" //---------------- var 対応する拡張子 = new[] { ".sstf", ".dtx", ".gda", ".g2d", "bms", "bme" }; // 譜面ファイルを検索する。曲ファイルは、対応する拡張子を持つファイルである。 var fileInfos = dirInfo.GetFiles( "*.*", SearchOption.TopDirectoryOnly ) .Where( ( fileInfo ) => 対応する拡張子.Any( 拡張子名 => ( Path.GetExtension( fileInfo.Name ).ToLower() == 拡張子名 ) ) ); // 列挙されたすべての譜面ファイルについて…… foreach( var fileInfo in fileInfos ) { Interlocked.Increment( ref this._進捗カウンタ ); var path = new VariablePath( fileInfo.FullName ); try { // 1つの譜面を持つ Song を生成する。 var song = new Song( path ); 追加ノードリスト.Add( new SongNode( song ) ); } catch( Exception e ) { Log.ERROR( $"SongNode の生成に失敗しました。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); } // 続けて、サブフォルダも検索する。 サブフォルダを検索する = true; } //---------------- #endregion } #region " 作成した一時リストを親ノードの子として正式に追加する。" //---------------- foreach( var node in 追加ノードリスト ) { // 親ノードの子として登録する。 親ノード.子ノードリスト.Add( node ); node.親ノード = 親ノード; // SongNode なら、全曲リストと全譜面リストにも追加する。 if( node is SongNode snode ) { Global.App.全曲リスト.Add( snode.曲 ); for( int i = 0; i < 5; i++ ) { if( null != snode.曲.譜面リスト[ i ] ) Global.App.全譜面リスト.Add( snode.曲.譜面リスト[ i ]! ); } } } //---------------- #endregion // (2) サブフォルダを検索 if( サブフォルダを検索する ) { // すべてのサブフォルダについて…… foreach( var di in dirInfo.GetDirectories() ) { if( di.Name.StartsWith( "DTXFiles.", StringComparison.OrdinalIgnoreCase ) ) { #region " (A) サブフォルダが DTXFiles. で始まるBOXである → BOXノードを追加し、サブフォルダを再帰的に検索する。" //---------------- // BOXノードを作成し、ツリーに登録する。 var boxNode = new BoxNode( di.Name[ ( "DTXFiles.".Length ).. ] ) { 親ノード = 親ノード }; 親ノード.子ノードリスト.Add( boxNode ); // BOXノードの先頭に「戻る」と「ランダムセレクト」を追加する。 boxNode.子ノードリスト.Add( new BackNode() { 親ノード = boxNode } ); // 戻る boxNode.子ノードリスト.Add( new RandomSelectNode() { 親ノード = boxNode } ); // ランタムセレクト // BOXノードを親として、サブフォルダを検索する。 this._構築する( di.FullName, boxNode ); //---------------- #endregion } else { #region " (B) それ以外 → サブフォルダを再帰検索し、その内容を同じ親ノードに追加する。" //---------------- this._構築する( di.FullName, 親ノード ); //---------------- #endregion } } } } } } <|start_filename|>DTXMania2/曲/Tree/Node/SongNode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.曲 { class SongNode : Node { // プロパティ public override string タイトル => this.曲.フォーカス譜面?.譜面.Title ?? "(no title)"; public override string サブタイトル => this.曲.フォーカス譜面?.譜面.Artist ?? ""; public override 画像D2D? ノード画像 => this.曲.フォーカス譜面?.プレビュー画像; public override 文字列画像D2D? タイトル文字列画像 => this.曲.フォーカス譜面?.タイトル文字列画像; public override 文字列画像D2D? サブタイトル文字列画像 => this.曲.フォーカス譜面?.サブタイトル文字列画像; public Song 曲 { get; } = null!; // 生成と終了 public SongNode( Song 曲 ) { this.曲 = 曲; } } } <|start_filename|>DTXMania2/曲/AVI管理.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using FDK; namespace DTXMania2 { /// <summary> /// AVIリストの各動画インスタンスを管理する。 /// </summary> class AVI管理 : IDisposable { // プロパティ public IReadOnlyDictionary<int, Video> 動画リスト { get => new Dictionary<int, Video>( this._動画リスト.Select( ( kvp ) => new KeyValuePair<int, Video>( kvp.Key, kvp.Value.動画 ) ) ); } // 生成と終了 public AVI管理() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._動画リスト = new Dictionary<int, VideoContext>(); this._一時停止中の動画のリスト = new List<Video>(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._一時停止中の動画のリスト.Clear(); // 各要素はDisposeしない; 各要素の本体は動画リストにあるため。 foreach( var value in this._動画リスト.Values ) value.動画.Dispose(); this._動画リスト.Clear(); } // 登録、停止、再開 /// <summary> /// 指定したAVI番号に動画ファイルを登録する。 /// </summary> public void 登録する( int AVI番号, VariablePath 動画ファイルの絶対パス, double 再生速度 = 1.0 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( 0 > AVI番号 || 36 * 36 <= AVI番号 ) throw new ArgumentOutOfRangeException( $"AVI番号が範囲(0~1295)を超えています。[{AVI番号}]" ); if( !( File.Exists( 動画ファイルの絶対パス.変数なしパス ) ) ) { Log.ERROR( $"動画ファイルが存在しません。[{動画ファイルの絶対パス.変数付きパス}]" ); return; } // すでに登録済みなら解放する。 this._削除する( AVI番号 ); // 新しいVideoを生成して登録する。 this._登録する( AVI番号, 動画ファイルの絶対パス, 再生速度 ); } public void 再生中の動画をすべて一時停止する() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._一時停止中の動画のリスト.Clear(); foreach( var vc in this._動画リスト.Values ) { if( vc.動画.再生中 ) { vc.動画.一時停止する(); this._一時停止中の動画のリスト.Add( vc.動画 ); } } } public void 一時停止中の動画をすべて再開する() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var video in this._一時停止中の動画のリスト ) video.再開する(); this._一時停止中の動画のリスト.Clear(); } public void 削除する( int AVI番号 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._削除する( AVI番号 ); } /// <summary> /// 指定されたAVI番号の動画のみいったん解放し、新しく再構築する。 /// </summary> public void 再構築する( int AVI番号 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); if( this._動画リスト.ContainsKey( AVI番号 ) ) { var vc = this._動画リスト[ AVI番号 ]; // 動画のみ解放 vc.動画.Dispose(); // 動画のみ再構築 vc.動画 = new Video( Global.GraphicResources.MFDXGIDeviceManager, Global.GraphicResources.既定のD2D1DeviceContext, vc.動画ファイルの絶対パス, vc.再生速度 ); } } // ローカル private class VideoContext { public int AVI番号; public VariablePath 動画ファイルの絶対パス; public double 再生速度; public Video 動画; public VideoContext( int AVI番号, VariablePath 動画ファイルの絶対パス, double 再生速度, Video 動画 ) { this.AVI番号 = AVI番号; this.動画ファイルの絶対パス = 動画ファイルの絶対パス; this.再生速度 = 再生速度; this.動画 = 動画; } } /// <summary> /// 全AVIのリスト。[key: WAV番号] /// </summary> private readonly Dictionary<int, VideoContext> _動画リスト; private readonly List<Video> _一時停止中の動画のリスト; private void _登録する( int AVI番号, VariablePath 動画ファイルの絶対パス, double 再生速度 ) { this._動画リスト[ AVI番号 ] = new VideoContext( AVI番号, 動画ファイルの絶対パス, 再生速度, new Video( Global.GraphicResources.MFDXGIDeviceManager, Global.GraphicResources.既定のD2D1DeviceContext, 動画ファイルの絶対パス, 再生速度 ) ); } private void _削除する( int AVI番号 ) { if( this._動画リスト.ContainsKey( AVI番号 ) ) { this._動画リスト[ AVI番号 ].動画.Dispose(); this._動画リスト.Remove( AVI番号 ); } } } } <|start_filename|>FDK/VariablePath.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using YamlDotNet.Serialization; namespace FDK { /// <summary> /// フォルダ変数(<see cref="Folder"/>参照)の使えるパスを管理する。 /// </summary> /// <remarks> /// string の代わりにこの型を使えば、任意のパスを扱う際に、そのパスのフォルダ変数の有無を考慮することなく /// 好きなほうのメンバ(変数なし・変数付き)を使うことができるようになる。 /// <see cref="VariablePath"/> 型と string は、暗黙的に相互変換できる。 /// </remarks> public class VariablePath : IYamlConvertible { // プロパティ /// <summary> /// 管理しているパスにフォルダ変数が含まれている場合、それを展開して返す。 /// </summary> public string 変数なしパス { get; protected set; } = ""; /// <summary> /// 管理しているパスにフォルダ変数に置き換えられる場所があるなら、それを置き換えて返す。 /// </summary> public string 変数付きパス { get; protected set; } = ""; // 生成と終了 /// <summary> /// デフォルトコンストラクタ。 /// Yamlデシリアライズのために必要。 /// </summary> public VariablePath() { } /// <summary> /// コンストラクタ。 /// </summary> /// <param name="パス">管理したいパス文字列。変数付き・変数なしのどちらを指定してもいい。</param> public VariablePath( string パス ) { this._初期化( パス ); } private void _初期化( string パス ) { this.変数なしパス = Folder.絶対パスに含まれるフォルダ変数を展開して返す( パス ); this.変数付きパス = Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( this.変数なしパス ); } // string との相互変換 /// <summary> /// string から <see cref="VariablePath"/> への暗黙的変換。 /// </summary> public static implicit operator VariablePath( string パス ) => new VariablePath( パス ); /// <summary> /// <see cref="VariablePath"/> から string への暗黙的変換その1。 /// </summary> /// <param name="パス"></param> //public static implicit operator string( VariablePath パス ) --> なんかすごく間違いやすくなるので廃止。 // => パス?.変数付きパス ?? null; /// <summary> /// <see cref="VariablePath"/> から string への暗黙的変換その2。 /// </summary> public override string ToString() => this.変数付きパス; // ローカル(Yaml関連) #region " IYamlConvertible 実装 " //---------------- // Yaml から変換する void IYamlConvertible.Read( YamlDotNet.Core.IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer ) { var vpath = ( (string?)nestedObjectDeserializer( typeof( string ) ) ) ?? ""; this._初期化( vpath ); } // Yaml に変換する void IYamlConvertible.Write( YamlDotNet.Core.IEmitter emitter, ObjectSerializer nestedObjectSerializer ) { nestedObjectSerializer( this.変数付きパス ); } //---------------- #endregion } } <|start_filename|>DTXMania2/イメージ/文字列画像D2D.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2 { /// <summary> /// DirectWrite を使った Direct2D1ビットマップ。 /// </summary> /// <remarks> /// <see cref="表示文字列"/> メンバを更新すれば、次回の描画時に新しいビットマップが生成される。 /// </remarks> class 文字列画像D2D : FDK.文字列画像D2D { public 文字列画像D2D() : base( Global.GraphicResources.DWriteFactory, Global.GraphicResources.D2D1Factory1, Global.GraphicResources.既定のD2D1DeviceContext, Global.GraphicResources.設計画面サイズ ) { } } } <|start_filename|>SSTFEditor/バージョン表示ダイアログ.cs<|end_filename|> using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Reflection; using System.Windows.Forms; namespace SSTFEditor { partial class バージョン表示ダイアログ : Form { public バージョン表示ダイアログ() { InitializeComponent(); this.Text = $"{AssemblyTitle} のバージョン情報"; this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = $"バージョン {AssemblyVersion}"; this.labelCopyright.Text = AssemblyCopyright; this.textBoxDescription.Text = AssemblyDescription; } #region アセンブリ属性アクセサ public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyTitleAttribute ), false ); if( attributes.Length > 0 ) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute) attributes[ 0 ]; if( titleAttribute.Title != "" ) { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension( Assembly.GetExecutingAssembly().Location ); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyDescriptionAttribute ), false ); if( attributes.Length == 0 ) { return ""; } return ( (AssemblyDescriptionAttribute) attributes[ 0 ] ).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyProductAttribute ), false ); if( attributes.Length == 0 ) { return ""; } return ( (AssemblyProductAttribute) attributes[ 0 ] ).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyCopyrightAttribute ), false ); if( attributes.Length == 0 ) { return ""; } return ( (AssemblyCopyrightAttribute) attributes[ 0 ] ).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( AssemblyCompanyAttribute ), false ); if( attributes.Length == 0 ) { return ""; } return ( (AssemblyCompanyAttribute) attributes[ 0 ] ).Company; } } #endregion } } <|start_filename|>FDK/Folder.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; namespace FDK { /// <summary> /// フォルダ変数の変換機能を提供する。 /// </summary> /// <remarks> /// (1) システムから自動的に取得できるフォルダパス、(2) ユーザ名などが含まれていてログに出力するのがためらわれるフォルダパス などで /// 「フォルダ変数」を使うことにより、これらを隠蔽可能にする。 /// フォルダ変数は、"$("+名前+")" で自由に定義できる。 /// </remarks> public class Folder { // フォルダ変数関連 public static void フォルダ変数を追加または更新する( string 変数名, string 置換するパス文字列 ) { Folder._フォルダ変数toパス[ 変数名 ] = 置換するパス文字列; } public static void フォルダ変数を削除する( string 変数名 ) { if( Folder._フォルダ変数toパス.ContainsKey( 変数名 ) ) { Folder._フォルダ変数toパス.Remove( 変数名 ); } else { throw new Exception( $"指定されたフォルダ変数「{変数名}」は存在しません。" ); } } public static string フォルダ変数の内容を返す( string 変数名 ) { return ( Folder._フォルダ変数toパス.ContainsKey( 変数名 ) ) ? Folder._フォルダ変数toパス[ 変数名 ] : ""; } public static string 絶対パスに含まれるフォルダ変数を展開して返す( string 絶対パス ) { if( string.IsNullOrEmpty( 絶対パス ) ) return ""; foreach( var kvp in Folder._フォルダ変数toパス ) { if( !string.IsNullOrEmpty( kvp.Value ) ) 絶対パス = 絶対パス.Replace( "$(" + kvp.Key + ")", kvp.Value ); } return 絶対パス; } public static string 絶対パスをフォルダ変数付き絶対パスに変換して返す( string 絶対パス ) { if( string.IsNullOrEmpty( 絶対パス ) ) return ""; foreach( var kvp in Folder._フォルダ変数toパス ) { if( !string.IsNullOrEmpty( kvp.Value ) ) 絶対パス = 絶対パス.Replace( kvp.Value, "$(" + kvp.Key + ")" ); } return 絶対パス; } /// <summary> /// 指定された絶対パスで示されるファイルについて、カルチャフォルダ内に同名のファイルがあるなら /// そちらのファイルへの絶対パスを返す。 /// </summary> /// <param name="絶対パス">カルチャを考慮したいファイルへの絶対パス。</param> /// <returns>カルチャを考慮した、ファイルへの絶対パス。</returns> /// <remarks> /// 指定されたファイルと同じ場所に現在のカルチャを表すカルチャフォルダがあり、かつ、 /// そこに指定されたファイルと同名のファイルが存在しているなら、そのファイルへの絶対パスを返す。 /// カルチャフォルダがない、またはカルチャフォルダ内に同名のファイル存在していない場合には、 /// 引数に指定された絶対パスをそのまま返す。 /// カルチャフォルダは、ニュートラルカルチャよりも特定カルチャが優先される。 /// 例: /// 下記のようなファイルがあるとする。 /// d:\images\message.txt /// d:\images\ja-JP\message.txt /// d:\images\en\message.txt /// d:\images\en-US\message.txt /// このメソッドに "d:\images\message.txt" を渡すと、現在のカルチャに従って、以下のように返される。 /// 現在のカルチャ 戻り値 /// -------------------------------------------------------- /// ja-JP "d:\images\ja-JP\message.txt" /// en-US "d:\images\en-US\message.txt" /// en-CA "d:\images\en\message.txt" /// 上記以外 "d:\images\message.txt" /// -------------------------------------------------------- /// </remarks> public static string カルチャを考慮した絶対パスを返す( string 絶対パス ) { var culture = CultureInfo.CurrentUICulture; var folder_path = Path.GetDirectoryName( 絶対パス ) ?? @"\"; var file_name = Path.GetFileName( 絶対パス ); // 特定カルチャーでチェック var path = Path.Combine( folder_path, culture.Name, file_name ); if( File.Exists( path ) ) return path; // ニュートラルカルチャーでチェック path = Path.Combine( folder_path, culture.TwoLetterISOLanguageName, file_name ); if( File.Exists( path ) ) return path; // 既定のカルチャを使用する(無変更) return 絶対パス; } // ユーティリティ public static string 絶対パスを相対パスに変換する( string 基点フォルダの絶対パス, string 変換したいフォルダの絶対パス ) { if( string.IsNullOrEmpty( 変換したいフォルダの絶対パス ) ) return ""; if( !( Path.IsPathRooted( 基点フォルダの絶対パス ) ) ) throw new Exception( $"基点フォルダは絶対パスで指定してください。[{基点フォルダの絶対パス}]" ); if( !( Path.IsPathRooted( 変換したいフォルダの絶対パス ) ) ) throw new Exception( $"変換対象フォルダは絶対パスで指定してください。[{変換したいフォルダの絶対パス}]" ); // 末尾は \ にしておく("+"でパスを連結する事態を想定。Path.Combine() を使う分には、末尾に \ があってもなくてもどっちでもいい。) if( '\\' != 基点フォルダの絶対パス[ 基点フォルダの絶対パス.Length - 1 ] ) 基点フォルダの絶対パス += @"\"; // 絶対-相対パス変換は、System.IO.Path クラスではなく System.IO.Uri クラスでしか行えない。 var 基点uri = new Uri( 基点フォルダの絶対パス ); var 変換前uri = new Uri( 変換したいフォルダの絶対パス ); var 変換後uri = 基点uri.MakeRelativeUri( 変換前uri ); // URI形式になっているので、パス形式に戻す。(具体的には、エスケープ文字を復元し、さらに '/' を '\' に置換する。) return Uri.UnescapeDataString( 変換後uri.ToString() ).Replace( oldChar: '/', newChar: '\\' ); } // ローカル private static readonly Dictionary<string, string> _フォルダ変数toパス = new Dictionary<string, string>(); } } <|start_filename|>DTXMania2/ステージ/08結果/達成率更新.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Animation; using FDK; namespace DTXMania2.結果 { /// <summary> /// 最高達成率を更新した場合の達成率表示。 /// </summary> partial class 達成率更新 : 達成率Base { // プロパティ public override bool アニメ完了 { get { // 黒帯終了? foreach( var anim in this._黒帯アニメーション ) { if( anim.ストーリーボード.Status != StoryboardStatus.Ready ) return false; // まだ } // その他アニメ終了? return this._数値.アニメ完了 && this._アイコン.アニメ完了 && this._下線.アニメ完了; } } // 生成と終了 public 達成率更新( float 速度倍率 = 1.0f ) { using var _ = new LogBlock( Log.現在のメソッド名 ); double 秒( double v ) => ( v / 速度倍率 ); this._アイコン = new アイコン(); this._下線 = new 下線(); this._数値 = new 数値(); // ストーリーボードの構築・黒帯 this._黒帯アニメーション = new 黒帯[ 3 ]; #region " ストーリーボードの構築(1) 左→右へ移動する帯 " //---------------- { // 初期状態 var 黒帯 = this._黒帯アニメーション[ 0 ] = new 黒帯() { 中心位置X = new Variable( Global.Animation.Manager, initialValue: 1206.0 ), 中心位置Y = new Variable( Global.Animation.Manager, initialValue: 540.0 ), 回転角rad = new Variable( Global.Animation.Manager, initialValue: MathUtil.DegreesToRadians( 20.0f ) ), 太さ = new Variable( Global.Animation.Manager, initialValue: 198.0 ), 不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ), ストーリーボード = new Storyboard( Global.Animation.Manager ), }; // シーン1. 待つ { double シーン期間 = 秒( 達成率更新._最初の待機時間sec / 2 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン2. 左から真ん中へ、細く不透明になりつつ移動。 { double シーン期間 = 秒( 0.15 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1564.0 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: シーン期間, finalValue: 14.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.75 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン3. 真ん中から右へ移動。 { double シーン期間 = 秒( 0.1 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1922.0 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 20.0 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン4. 待つ { double シーン期間 = 秒( 達成率更新._登場後の待機時間sec ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン5. 右へ消えていく。 { double シーン期間 = 秒( 達成率更新._退場アニメ時間sec ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1922.0 + 66.0 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.0 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } } //---------------- #endregion #region " ストーリーボードの構築(2) 右→左へ移動する帯 " //---------------- { // 初期状態 var 黒帯 = this._黒帯アニメーション[ 1 ] = new 黒帯() { 中心位置X = new Variable( Global.Animation.Manager, initialValue: 1922.0 ), 中心位置Y = new Variable( Global.Animation.Manager, initialValue: 540.0 ), 回転角rad = new Variable( Global.Animation.Manager, initialValue: MathUtil.DegreesToRadians( 20.0f ) ), 太さ = new Variable( Global.Animation.Manager, initialValue: 198.0 ), 不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ), ストーリーボード = new Storyboard( Global.Animation.Manager ), }; // シーン1. 待つ { double シーン期間 = 秒( 達成率更新._最初の待機時間sec / 2 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン2. 右から真ん中へ、細く不透明になりつつ移動。 { double シーン期間 = 秒( 0.15 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1564.0 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: シーン期間, finalValue: 14.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.75 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン3. 真ん中から左へ移動。 { double シーン期間 = 秒( 0.1 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1214.0 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 20.0 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン4. 待つ { double シーン期間 = 秒( 達成率更新._登場後の待機時間sec ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン5. 左へ消えていく。 { double シーン期間 = 秒( 達成率更新._退場アニメ時間sec ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 1214.0 - 66.0 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.0 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } } //---------------- #endregion #region " ストーリーボードの構築(3) 真ん中の帯 " //---------------- { // 初期状態 var 黒帯 = this._黒帯アニメーション[ 2 ] = new 黒帯() { 中心位置X = new Variable( Global.Animation.Manager, initialValue: 1564.0 ), 中心位置Y = new Variable( Global.Animation.Manager, initialValue: 540.0 ), 回転角rad = new Variable( Global.Animation.Manager, initialValue: MathUtil.DegreesToRadians( 20.0f ) ), 太さ = new Variable( Global.Animation.Manager, initialValue: 0.0 ), 不透明度 = new Variable( Global.Animation.Manager, initialValue: 0.0 ), ストーリーボード = new Storyboard( Global.Animation.Manager ), }; // シーン1. 待つ { double シーン期間 = 秒( 達成率更新._最初の待機時間sec / 2 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン2. 何もしない { double シーン期間 = 秒( 0.15 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン3. 真ん中で太くなる。 { double シーン期間 = 秒( 0.1 ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.AccelerateDecelerate( duration: シーン期間, finalValue: 600.0, accelerationRatio: 0.9, decelerationRatio: 0.1 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.75 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン4. 待つ { double シーン期間 = 秒( 達成率更新._登場後の待機時間sec ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } // シーン5. 真ん中で細くなって消えていく。 { double シーン期間 = 秒( 達成率更新._退場アニメ時間sec ); using( var 中心位置Xの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 中心位置Yの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 回転角radの遷移 = Global.Animation.TrasitionLibrary.Constant( duration: シーン期間 ) ) using( var 太さの遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.0 ) ) using( var 不透明度の遷移 = Global.Animation.TrasitionLibrary.Linear( duration: シーン期間, finalValue: 0.0 ) ) { 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置X, 中心位置Xの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.中心位置Y, 中心位置Yの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.回転角rad, 回転角radの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.太さ, 太さの遷移 ); 黒帯.ストーリーボード.AddTransition( 黒帯.不透明度, 不透明度の遷移 ); } } } //---------------- #endregion } public override void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._アイコン.Dispose(); this._下線.Dispose(); this._数値.Dispose(); foreach( var anim in this._黒帯アニメーション ) anim.Dispose(); } // 進行と描画 public override void アニメを完了する() { foreach( var anim in this._黒帯アニメーション ) anim.ストーリーボード?.Finish( 0.0 ); this._アイコン.アニメを完了する(); this._下線.アニメを完了する(); this._数値.アニメを完了する(); } public override void 進行描画する( DeviceContext d2ddc, float x, float y, double 達成率0to100 ) { if( this._初めての進行描画 ) { this._初めての進行描画 = false; this._アイコン.開始する(); this._下線.開始する(); this._数値.開始する( 達成率0to100 ); var start = Global.Animation.Timer.Time; foreach( var anim in this._黒帯アニメーション ) anim.ストーリーボード?.Schedule( start ); } var preTrans = d2ddc.Transform; // 黒帯 foreach( var 黒帯 in this._黒帯アニメーション ) { d2ddc.Transform = Matrix3x2.Rotation( (float)黒帯.回転角rad.Value ) * Matrix3x2.Translation( (float)黒帯.中心位置X.Value, (float)黒帯.中心位置Y.Value ) * preTrans; using var brush = new SolidColorBrush( d2ddc, new Color4( 0f, 0f, 0f, (float)黒帯.不透明度.Value ) ); float w = (float)黒帯.太さ.Value; float h = 1600.0f; var rc = new RectangleF( -w / 2f, -h / 2f, w, h ); d2ddc.FillRectangle( rc, brush ); } d2ddc.Transform = preTrans; this._アイコン.進行描画する( d2ddc, x, y ); this._数値.進行描画する( d2ddc, x + 150f, y + 48f ); this._下線.進行描画する( d2ddc, x + 33f, y + 198f ); } // ローカル private bool _初めての進行描画 = true; private const double _最初の待機時間sec = 1.0; private const double _アニメ時間sec = 0.25; private const double _登場後の待機時間sec = 3.0; private const double _退場アニメ時間sec = 0.1; private class 黒帯 : IDisposable { public Variable 中心位置X = null!; public Variable 中心位置Y = null!; public Variable 回転角rad = null!; public Variable 太さ = null!; public Variable 不透明度 = null!; public Storyboard ストーリーボード = null!; public virtual void Dispose() { this.ストーリーボード?.Dispose(); this.不透明度?.Dispose(); this.太さ?.Dispose(); this.回転角rad?.Dispose(); this.中心位置Y?.Dispose(); this.中心位置X?.Dispose(); } } private readonly 黒帯[] _黒帯アニメーション; private readonly 達成率更新.アイコン _アイコン; private readonly 達成率更新.下線 _下線; private readonly 達成率更新.数値 _数値; } } <|start_filename|>FDK/ログ/LogBlock.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { /// <summary> /// コンストラクタでブロック開始ログ、Disposeでブロック終了ログを出力するインスタンス。 /// </summary> public class LogBlock : IDisposable { // "--> 開始" public LogBlock( string ブロック名 ) { this._ブロック名 = ブロック名; Log.BeginInfo( this._ブロック名 ); } // "<-- 終了" public virtual void Dispose() { Log.EndInfo( this._ブロック名 ); } private string _ブロック名; } } <|start_filename|>SSTFEditor/UndoRedo/セルリスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SSTFEditor.UndoRedo { class Cセルリスト : セルBase { public List<セルBase> セルs { get; set; } = null; public int 次にセルが追加される位置0to { get; set; } = 0; public Cセルリスト 親リスト { get; set; } = null; public int Undo可能な回数 => ( this.次にセルが追加される位置0to ); public int Redo可能な回数 => ( this.現在の総セル数 - this.Undo可能な回数 ); public int 現在の総セル数 => this.セルs.Count; public Cセルリスト( Cセルリスト 親リスト ) { this.親リスト = 親リスト; this.セルs = new List<セルBase>(); this.次にセルが追加される位置0to = 0; } public override void Redoを実行する() { // 前から順に実行する。 for( int i = 0; i < this.セルs.Count; i++ ) this.セルs[ i ].Redoを実行する(); } public override void Undoを実行する() { // 後ろから順に実行する。 for( int i = this.セルs.Count - 1; i >= 0; i-- ) this.セルs[ i ].Undoを実行する(); } } } <|start_filename|>DTXMania2/ステージ/07演奏/AutoPlay種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.演奏 { /// <summary> /// AutoPlay の指定単位。 /// AotoPlay が指定可能なチップは、この種別のいずれかに属する。 /// </summary> enum AutoPlay種別 { Unknown, LeftCrash, HiHat, Foot, // 左ペダル Snare, Bass, Tom1, Tom2, Tom3, RightCrash, } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネルリスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpDX; using SharpDX.Direct2D1; using FDK; using DTXMania2.演奏; namespace DTXMania2.オプション設定 { /// <summary> /// <see cref="パネル_フォルダ"/> の選択と表示。 /// </summary> class パネルリスト : IDisposable { // 外部依存アクション public Action 入力割り当てフェーズへ移行する = () => throw new NotImplementedException(); public Action 曲読み込みフォルダ割り当てフェーズへ移行する = () => throw new NotImplementedException(); public Action 再起動フェーズへ移行する = () => throw new NotImplementedException(); public Action フェードアウトフェーズへ移行する = () => throw new NotImplementedException(); // プロパティ public パネル_フォルダ パネルツリーのルートノード { get; } public パネル_フォルダ 現在のパネルフォルダ { get; private set; } public パネル? 現在選択中のパネル => this.現在のパネルフォルダ.子パネルリスト.SelectedItem; // 生成と終了 public パネルリスト() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._青い線 = new 青い線(); this._パッド矢印 = new パッド矢印(); this.パネルツリーのルートノード = new パネル_フォルダ( "root", 親パネル: null ); this.現在のパネルフォルダ = this.パネルツリーのルートノード; this._パネル_自動演奏_ONOFFトグルリスト = new List<パネル_ONOFFトグル>(); // ツリー構築・オプションパート(ユーザ別) var systemConfig = Global.App.システム設定; var userConfig = Global.App.ログオン中のユーザ; if( userConfig is null ) throw new Exception( "ユーザが選択されていません。" ); #region "「自動演奏」フォルダ" //---------------- { var 自動演奏フォルダ = new パネル_フォルダ( パネル名: Properties.Resources.TXT_自動演奏, 親パネル: this.パネルツリーのルートノード, 値の変更処理: ( panel ) => { this.子のパネルを選択する(); this.フェードインを開始する(); } ); this.パネルツリーのルートノード.子パネルリスト.Add( 自動演奏フォルダ ); // 子フォルダツリーの構築 #region "「すべてON/OFF」パネル " //---------------- 自動演奏フォルダ.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_すべてONOFF, 値の変更処理: ( panel ) => { bool 設定値 = !( this._パネル_自動演奏_ONOFFトグルリスト[ 0 ].ONである ); // 最初の項目値の反対にそろえる foreach( var typePanel in this._パネル_自動演奏_ONOFFトグルリスト ) { if( typePanel.ONである != 設定値 ) // 設定値と異なるなら typePanel.確定キーが入力された(); // ON/OFF反転 } } ) ); //---------------- #endregion #region " 各パッドのON/OFFパネル " //---------------- foreach( AutoPlay種別? autoPlayType in Enum.GetValues( typeof( AutoPlay種別 ) ) ) { if( !autoPlayType.HasValue || autoPlayType.Value == AutoPlay種別.Unknown ) continue; var typePanel = new パネル_ONOFFトグル( パネル名: autoPlayType.Value.ToString(), 初期状態はON: ( userConfig.AutoPlay[ autoPlayType.Value ] ), 値の変更処理: ( panel ) => { userConfig.AutoPlay[ autoPlayType.Value ] = ( (パネル_ONOFFトグル)panel ).ONである; } ); 自動演奏フォルダ.子パネルリスト.Add( typePanel ); this._パネル_自動演奏_ONOFFトグルリスト.Add( typePanel ); } //---------------- #endregion #region "「設定完了(戻る)」システムボタン //---------------- 自動演奏フォルダ.子パネルリスト.Add( new パネル_システムボタン( パネル名: Properties.Resources.TXT_設定完了_戻る, 値の変更処理: ( panel ) => { this.親のパネルを選択する(); this.フェードインを開始する(); } ) ); //---------------- #endregion 自動演奏フォルダ.子パネルリスト.SelectFirst(); } //---------------- #endregion #region "「画面モード」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_文字列リスト( パネル名: Properties.Resources.TXT_画面モード, 選択肢初期値リスト: new[] { Properties.Resources.TXT_ウィンドウ, Properties.Resources.TXT_全画面, }, 初期選択肢番号: ( systemConfig.全画面モードである ) ? 1 : 0, 値の変更処理: ( panel ) => { bool 全画面モードにする = ( 1 == ( (パネル_文字列リスト)panel ).現在選択されている選択肢の番号 ); if( 全画面モードにする ) Global.App.ScreenMode.ToFullscreenMode(); else Global.App.ScreenMode.ToWindowMode(); systemConfig.全画面モードである = 全画面モードにする; } ) ); //---------------- #endregion #region "「譜面スピード」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_倍率( パネル名: Properties.Resources.TXT_譜面スピード, 初期値: userConfig.譜面スクロール速度, 最小倍率: 0.5, 最大倍率: 8.0, 増減量: 0.5, 値の変更処理: ( panel ) => { userConfig.譜面スクロール速度 = ( (パネル_倍率)panel ).現在値; } ) ); //---------------- #endregion #region "「演奏中の壁紙表示」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_演奏中の壁紙表示, 初期状態はON: userConfig.スコア指定の背景画像を表示する, 値の変更処理: ( panel ) => { userConfig.スコア指定の背景画像を表示する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「演奏中の動画表示」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_演奏中の動画表示, 初期状態はON: userConfig.演奏中に動画を表示する, 値の変更処理: ( panel ) => { userConfig.演奏中に動画を表示する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「演奏中の動画サイズ」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_文字列リスト( パネル名: Properties.Resources.TXT_演奏中の動画サイズ, 選択肢初期値リスト: new[] { Properties.Resources.TXT_演奏中の動画サイズ_全画面, Properties.Resources.TXT_演奏中の動画サイズ_中央寄せ, }, 初期選択肢番号: (int)userConfig.動画の表示サイズ, 値の変更処理: ( panel ) => { userConfig.動画の表示サイズ = (動画の表示サイズ)( (パネル_文字列リスト)panel ).現在選択されている選択肢の番号; } ) ); //---------------- #endregion #region "「シンバルフリー」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_シンバルフリー, 初期状態はON: userConfig.シンバルフリーモードである, 値の変更処理: ( panel ) => { userConfig.シンバルフリーモードである = ( (パネル_ONOFFトグル)panel ).ONである; userConfig.ドラムチッププロパティリスト.反映する( ( userConfig.シンバルフリーモードである ) ? 入力グループプリセット種別.シンバルフリー : 入力グループプリセット種別.基本形 ); } ) ); //---------------- #endregion #region "「Rideの表示位置」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_文字列リスト( パネル名: Properties.Resources.TXT_Rideの表示位置, 選択肢初期値リスト: new[] { Properties.Resources.TXT_左, Properties.Resources.TXT_右, }, 初期選択肢番号: ( userConfig.表示レーンの左右.Rideは左 ) ? 0 : 1, 値の変更処理: ( panel ) => { userConfig.表示レーンの左右 = new 表示レーンの左右() { Rideは左 = ( ( (パネル_文字列リスト)panel ).現在選択されている選択肢の番号 == 0 ), Chinaは左 = userConfig.表示レーンの左右.Chinaは左, Splashは左 = userConfig.表示レーンの左右.Splashは左, }; } ) ); //---------------- #endregion #region "「Chinaの表示位置」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_文字列リスト( パネル名: Properties.Resources.TXT_Chinaの表示位置, 選択肢初期値リスト: new[] { Properties.Resources.TXT_左, Properties.Resources.TXT_右, }, 初期選択肢番号: ( userConfig.表示レーンの左右.Chinaは左 ) ? 0 : 1, 値の変更処理: ( panel ) => { userConfig.表示レーンの左右 = new 表示レーンの左右() { Rideは左 = userConfig.表示レーンの左右.Rideは左, Chinaは左 = ( ( (パネル_文字列リスト)panel ).現在選択されている選択肢の番号 == 0 ), Splashは左 = userConfig.表示レーンの左右.Splashは左, }; } ) ); //---------------- #endregion #region "「Splashの表示位置」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_文字列リスト( パネル名: Properties.Resources.TXT_Splashの表示位置, 選択肢初期値リスト: new[] { Properties.Resources.TXT_左, Properties.Resources.TXT_右, }, 初期選択肢番号: ( userConfig.表示レーンの左右.Splashは左 ) ? 0 : 1, 値の変更処理: ( panel ) => { userConfig.表示レーンの左右 = new 表示レーンの左右() { Rideは左 = userConfig.表示レーンの左右.Rideは左, Chinaは左 = userConfig.表示レーンの左右.Splashは左, Splashは左 = ( ( (パネル_文字列リスト)panel ).現在選択されている選択肢の番号 == 0 ), }; } ) ); //---------------- #endregion #region "「ドラムサウンド」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_ドラムサウンド, 初期状態はON: userConfig.ドラムの音を発声する, 値の変更処理: ( panel ) => { userConfig.ドラムの音を発声する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「レーンの透明度」数値ボックス " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_整数( パネル名: Properties.Resources.TXT_レーンの透明度, 最小値: 0, 最大値: 100, 初期値: userConfig.レーンの透明度, 増加減単位値: 5, 単位: "%", 値の変更処理: ( panel ) => { userConfig.レーンの透明度 = ( (パネル_整数)panel ).現在の値; } ) ); //---------------- #endregion #region "「演奏スピード」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_倍率( パネル名: Properties.Resources.TXT_演奏スピード, 初期値: userConfig.再生速度, 最小倍率: 0.1, 最大倍率: 2.0, 増減量: 0.1, 値の変更処理: ( panel ) => { userConfig.再生速度 = ( (パネル_倍率)panel ).現在値; // WAVキャッシュをすべて削除するために、世代を2つ進める。 Global.App.WAVキャッシュ.世代を進める(); Global.App.WAVキャッシュ.世代を進める(); } ) ); //---------------- #endregion #region "「小節線と拍線の表示」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_小節線と拍線の表示, 初期状態はON: userConfig.演奏中に小節線と拍線を表示する, 値の変更処理: ( panel ) => { userConfig.演奏中に小節線と拍線を表示する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「小節番号の表示」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_小節番号の表示, 初期状態はON: userConfig.演奏中に小節番号を表示する, 値の変更処理: ( panel ) => { userConfig.演奏中に小節番号を表示する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「判定FAST/SLOW値の表示」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_判定FASTSLOWの表示, 初期状態はON: userConfig.演奏中に判定FastSlowを表示する, 値の変更処理: ( panel ) => { userConfig.演奏中に判定FastSlowを表示する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「音量によるサイズ変化」ON/OFFトグル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_ONOFFトグル( パネル名: Properties.Resources.TXT_音量によるサイズ変化, 初期状態はON: userConfig.音量に応じてチップサイズを変更する, 値の変更処理: ( panel ) => { userConfig.音量に応じてチップサイズを変更する = ( (パネル_ONOFFトグル)panel ).ONである; } ) ); //---------------- #endregion #region "「ダークモード」リスト " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_文字列リスト( パネル名: Properties.Resources.TXT_ダークモード, 選択肢初期値リスト: new[] { ( Properties.Resources.TXT_OFF, Color.Red ), ( Properties.Resources.TXT_ダークモード_HALF, Color4.White ), ( Properties.Resources.TXT_ダークモード_FULL, Color4.White), }, 初期選択肢番号: (int)userConfig.ダーク, 値の変更処理: ( panel ) => { userConfig.ダーク = (ダーク種別)( (パネル_文字列リスト)panel ).現在選択されている選択肢の番号; } ) ); //---------------- #endregion // ツリー構築・システム設定パート(全ユーザ共通) #region "「判定位置調整」数値ボックス " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_整数( パネル名: Properties.Resources.TXT_判定位置調整, 最小値: -99, 最大値: +99, 初期値: systemConfig.判定位置調整ms, 増加減単位値: 1, 単位: "ms", 値の変更処理: ( panel ) => { systemConfig.判定位置調整ms = ( (パネル_整数)panel ).現在の値; } ) ); //---------------- #endregion #region "「入力割り当て」パネル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_入力割り当て, 値の変更処理: ( panel ) => { this.入力割り当てフェーズへ移行する(); }, ヘッダ色: パネル.ヘッダ色種別.赤 ) ); //---------------- #endregion #region "「曲読み込みフォルダ」パネル " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_曲読み込みフォルダ, 値の変更処理: ( panel ) => { this.曲読み込みフォルダ割り当てフェーズへ移行する(); }, ヘッダ色: パネル.ヘッダ色種別.赤 ) ); //---------------- #endregion #region "「初期化」フォルダ " //---------------- { var 初期化フォルダ = new パネル_フォルダ( パネル名: Properties.Resources.TXT_初期化, 親パネル: this.パネルツリーのルートノード, 値の変更処理: ( panel ) => { this.子のパネルを選択する(); this.フェードインを開始する(); } ); this.パネルツリーのルートノード.子パネルリスト.Add( 初期化フォルダ ); // 子フォルダツリーの構築 #region "「戻る」システムボタン " //---------------- 初期化フォルダ.子パネルリスト.Add( new パネル_システムボタン( パネル名: Properties.Resources.TXT_戻る, 値の変更処理: ( panel ) => { this.親のパネルを選択する(); this.フェードインを開始する(); } ) ); //---------------- #endregion #region "「設定を初期化」パネル" //---------------- 初期化フォルダ.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_設定を初期化, 値の変更処理: ( panel ) => { this._システム設定を初期化する(); this.再起動フェーズへ移行する(); } ) ); //---------------- #endregion #region "「曲DBを初期化」パネル" //---------------- 初期化フォルダ.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_曲DBを初期化, 値の変更処理: ( panel ) => { this._曲データベースを初期化する(); this.再起動フェーズへ移行する(); } ) ); //---------------- #endregion #region "「ユーザDBを初期化」パネル" //---------------- 初期化フォルダ.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_ユーザDBを初期化, 値の変更処理: ( panel ) => { this._ユーザデータベースを初期化する(); this.再起動フェーズへ移行する(); } ) ); //---------------- #endregion #region "「成績DBを初期化」パネル " //---------------- 初期化フォルダ.子パネルリスト.Add( new パネル( パネル名: Properties.Resources.TXT_成績DBを初期化, 値の変更処理: new Action<パネル>( ( panel ) => { this._成績データベースを初期化する(); this.再起動フェーズへ移行する(); } ) ) ); //---------------- #endregion 初期化フォルダ.子パネルリスト.SelectFirst(); } //---------------- #endregion #region "「設定完了」システムボタン " //---------------- this.パネルツリーのルートノード.子パネルリスト.Add( new パネル_システムボタン( パネル名: Properties.Resources.TXT_設定完了, 値の変更処理: ( panel ) => { this.フェードアウトを開始する(); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( シャッター ) ); this.フェードアウトフェーズへ移行する(); } ) ); //---------------- #endregion // 最後のパネルを選択。 this.パネルツリーのルートノード.子パネルリスト.SelectLast(); this.フェードインを開始する(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); Global.App.システム設定.保存する(); Global.App.ログオン中のユーザ.保存する(); foreach( var panel in this.パネルツリーのルートノード.Traverse() ) panel.Dispose(); this.パネルツリーのルートノード.Dispose(); this._パネル_自動演奏_ONOFFトグルリスト.Clear(); // 要素はツリーに含まれるのでDispose不要 this._パッド矢印.Dispose(); this._青い線.Dispose(); } // フェードイン・アウト public void フェードインを開始する( double 速度倍率 = 1.0 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); for( int i = 0; i < this.現在のパネルフォルダ.子パネルリスト.Count; i++ ) { this.現在のパネルフォルダ.子パネルリスト[ i ].フェードインを開始する( 0.02, 速度倍率 ); } } public void フェードアウトを開始する( double 速度倍率 = 1.0 ) { using var _ = new LogBlock( Log.現在のメソッド名 ); for( int i = 0; i < this.現在のパネルフォルダ.子パネルリスト.Count; i++ ) { this.現在のパネルフォルダ.子パネルリスト[ i ].フェードアウトを開始する( 0.02, 速度倍率 ); } } // 選択 public void 前のパネルを選択する() { this.現在のパネルフォルダ.子パネルリスト.SelectPrev( Loop: true ); } public void 次のパネルを選択する() { this.現在のパネルフォルダ.子パネルリスト.SelectNext( Loop: true ); } public void 親のパネルを選択する() { var 親パネル = this.現在のパネルフォルダ.親パネル; if( null != 親パネル ) this.現在のパネルフォルダ = 親パネル; } public void 子のパネルを選択する() { var 子パネル = this.現在のパネルフォルダ.子パネルリスト.SelectedItem as パネル_フォルダ; if( null != 子パネル ) this.現在のパネルフォルダ = 子パネル; } // 進行と描画 public void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置 ) { const float パネルの下マージン = 4f; float パネルの高さ = パネル.サイズ.Height + パネルの下マージン; // (1) フレーム1(たて線)を描画。 this._青い線.描画する( d2ddc, new Vector2( 左位置, 0f ), 高さdpx: Global.GraphicResources.設計画面サイズ.Height ); // (2) パネルを描画。(選択中のパネルの3つ上から7つ下までの計11枚。) var panels = this.現在のパネルフォルダ.子パネルリスト; if( panels.SelectedItem is null ) return; for( int i = 0; i < 11; i++ ) { int 描画パネル番号 = ( ( panels.SelectedIndex - 3 + i ) + panels.Count * 3 ) % panels.Count; // panels の末尾に達したら先頭に戻る。 var 描画パネル = panels[ 描画パネル番号 ]; 描画パネル.進行描画する( d2ddc, 左位置 + 22f, 上位置 + i * パネルの高さ, 選択中: ( i == 3 ) ); } // (3) フレーム2(選択パネル周囲)を描画。 float 幅 = パネル.サイズ.Width + 22f * 2f; this._青い線.描画する( d2ddc, new Vector2( 左位置, パネルの高さ * 3f ), 幅dpx: 幅 ); this._青い線.描画する( d2ddc, new Vector2( 左位置, パネルの高さ * 4f ), 幅dpx: 幅 ); this._青い線.描画する( d2ddc, new Vector2( 左位置 + 幅, パネルの高さ * 3f ), 高さdpx: パネルの高さ ); // (4) パッド矢印(上&下)を描画。 this._パッド矢印.描画する( d2ddc, パッド矢印.種類.上_Tom1, new Vector2( 左位置, パネルの高さ * 3f ) ); this._パッド矢印.描画する( d2ddc, パッド矢印.種類.下_Tom2, new Vector2( 左位置, パネルの高さ * 4f ) ); } // ローカル /// <summary> /// コード内で参照が必要になるパネルのホルダ。 /// </summary> private readonly List<パネル_ONOFFトグル> _パネル_自動演奏_ONOFFトグルリスト; private readonly 青い線 _青い線; private readonly パッド矢印 _パッド矢印; private void _システム設定を初期化する() { // 現行化中なら終了する。 Global.App.現行化.終了する(); // ファイルを削除する。 var path = SystemConfig.ConfigYamlPath; try { File.Delete( path.変数なしパス ); // ファイルがない場合には例外は出ない } catch( Exception e ) { Log.ERROR( $"システム設定ファイルの削除に失敗しました。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); } } private void _曲データベースを初期化する() { // 現行化中なら終了する。 Global.App.現行化.終了する(); // ファイルを削除する。 var path = ScoreDB.ScoreDBPath; try { File.Delete( path.変数なしパス ); // ファイルがない場合には例外は出ない } catch( Exception e ) { Log.ERROR( $"曲データベースファイルの削除に失敗しました。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); } } private void _ユーザデータベースを初期化する() { // 現行化中なら終了する。 Global.App.現行化.終了する(); // ファイルを削除する。 var path = new VariablePath( @$"$(AppData)\User_{Global.App.ログオン中のユーザ.ID}.yaml" ); try { File.Delete( path.変数なしパス ); // ファイルがない場合には例外は出ない } catch( Exception e ) { Log.ERROR( $"ユーザデータベースファイルの削除に失敗しました。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); } } private void _成績データベースを初期化する() { // 現行化中なら終了する。 Global.App.現行化.終了する(); // ファイルを削除する。 var path = RecordDB.RecordDBPath; try { File.Delete( path.変数なしパス ); // ファイルがない場合には例外は出ない } catch( Exception e ) { Log.ERROR( $"成績データベースファイルの削除に失敗しました。[{path.変数付きパス}][{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( e.Message )}]" ); } } } } <|start_filename|>SSTFormat/v004/チップ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SSTFormat.v004 { public class チップ : IComparable, ICloneable { // 定数 public const int 最大音量 = 8; public const int 既定音量 = 7; // チップの種類 public チップ種別 チップ種別 { get; set; } = チップ種別.Unknown; // チップの配置 /// <summary> /// このチップが存在する小節の番号。-1 以上の整数。 /// 小節番号 -1 の小節内には、発声可能なチップを配置しないこと。(小節線チップなどは可) /// </summary> public int 小節番号 { get; set; } = -1; /// <summary> /// このチップが存在する小節の解像度。 /// チップは 0~小節解像度-1 の範囲に配置できる。 /// </summary> /// <remarks> /// <see cref="小節内位置"/> と <see cref="小節解像度"/> の組でこのチップの位置を表す。 /// この組はチップごとに持つので、小節内のすべてのチップの解像度が等しいという必要はない。 /// </remarks> public int 小節解像度 { get; set; } = 1; /// <summary> /// このチップの位置。 /// チップの位置は、小節内の相対位置「小節内位置 ÷ 小節解像度」(= 0:小節先頭 ~ 1:小節末尾)で表される。 /// </summary> public int 小節内位置 { get; set; } = 0; // チップの描画/発声時刻 /// <summary> /// チップの描画時刻を、譜面の先頭(小節番号 -1 の小節の先頭)からの相対時間(秒単位)で表す。 /// 未使用(描画しないタイプのチップ)なら負数。 /// </summary> public double 描画時刻sec { get; set; } = -1; /// <summary> /// チップの発声時刻[sec]。 /// 譜面の先頭(小節番号 -1 の小節の先頭)からの時刻を秒単位で表す。 /// 未使用(発声しないタイプのチップ)なら負数。 /// </summary> /// <remarks> /// サウンドの発声遅延を考慮して、描画時刻よりも遅く設定すること。 /// </remarks> public double 発声時刻sec { get; set; } = -1; // チップのその他のプロパティ /// <summary> /// チップの種別をより詳細に示すためのユーザ定義ID。 /// </summary> /// <remarks> /// 今のところ、DTXから変換した場合に、ここにオブジェクト値が格納される。 /// </remarks> public int チップサブID { get; set; } = 0; /// <summary> /// チップの音量(小:1~<see cref="最大音量"/>:大)。 /// 最小値は 0 じゃなく 1 なので注意。 /// </summary> public int 音量 { get => this._音量; set => this._音量 = ( ( 1 > value ) || ( チップ.最大音量 < value ) ) ? throw new ArgumentException( $"音量の値域(1~{チップ.最大音量})を超える値 '{value}' が指定されました。" ) : value; } /// <summary> /// 左右の発声位置。PAN。 /// 左:-100 ~ 中央:0 ~ +100:右。 /// </summary> public int 左右位置 // hack: チップの左右位置の反映 { get => this._位置; set => this._位置 = ( -100 > value || +100 < value ) ? throw new ArgumentOutOfRangeException( $"位置の値域(-100~+100)を超える値 '{value}' が指定されました。" ) : value; } /// <summary> /// <see cref="チップ種別"/> が <see cref="チップ種別.BPM"/> である場合は、その BPM 値。 /// それ以外の場合は無効。 /// </summary> public double BPM { get; set; } = 120.0; /// <summary> /// true であればチップを表示してもよいが、false であれば表示してはならない。 /// ただし、チップが表示不可能なもの(小節の先頭など)である場合は、true/false のいずれであっても表示しなくていい。 /// </summary> public bool 可視 { get; set; } = true; // メソッド public チップ() { } public チップ( v003.チップ v3chip ) { this.チップ種別 = (チップ種別) v3chip.チップ種別; this.小節番号 = v3chip.小節番号; this.小節解像度 = v3chip.小節解像度; this.小節内位置 = v3chip.小節内位置; this.描画時刻sec = v3chip.描画時刻sec; this.発声時刻sec = v3chip.発声時刻sec; this.チップサブID = v3chip.チップサブID; this.音量 = v3chip.音量; this.左右位置 = v3chip.左右位置; this.BPM = v3chip.BPM; this.可視 = v3chip.可視; } /// <summary> /// チップの深いコピーを生成して返す。 /// </summary> public virtual object Clone() { // 浅いコピー var dst = this.MemberwiseClone(); // 参照型フィールドのコピー:必要ならここに記述すること。 return dst; } /// <summary> /// チップの内容を自身にコピーする。 /// </summary> public void CopyFrom( チップ src ) { this.チップ種別 = src.チップ種別; this.小節番号 = src.小節番号; this.小節解像度 = src.小節解像度; this.小節内位置 = src.小節内位置; this.描画時刻sec = src.描画時刻sec; this.発声時刻sec = src.発声時刻sec; this.チップサブID = src.チップサブID; this.音量 = src.音量; this.左右位置 = src.左右位置; this.BPM = src.BPM; this.可視 = src.可視; } // 概要: // 現在のインスタンスを同じ型の別のオブジェクトと比較して、並べ替え順序において、現在のインスタンスの位置が同じ型の別のオブジェクトの前、後ろ、または同じのいずれであるかを示す整数を返します。 // // パラメータ: // obj: // このインスタンスと比較するオブジェクト。 // // 戻り値: // 比較対象オブジェクトの相対順序を示す 32 ビット符号付き整数。戻り値の意味は次のとおりです。 // // 値 説明 // -------------------- // 負数 this < obj // 0 this = obj // 正数 this > obj // // 例外: // System.ArgumentException: // obj の型がこのインスタンスの型と異なります。 // public int CompareTo( object obj ) { var other = obj as チップ; if( this.小節番号 < other.小節番号 ) { return -1; } // 小さいほうが先 if( this.小節番号 > other.小節番号 ) { return +1; } // 大きいほうが後 double dbThis = (double) this.小節内位置 / (double) this.小節解像度; double dbOther = (double) other.小節内位置 / (double) other.小節解像度; if( dbThis < dbOther ) { return -1; } // 小さいほうが先 if( dbThis > dbOther ) { return +1; } // 大きいほうが後 // グリッドが完全に等しいなら、チップの種類ごとに定義された深度で順序を決める。 if( SSTFプロパティ.チップの深さ[ this.チップ種別 ] > SSTFプロパティ.チップの深さ[ other.チップ種別 ] ) { return -1; } // 大きいほうが先 ← 他と逆なので注意。 if( SSTFプロパティ.チップの深さ[ this.チップ種別 ] < SSTFプロパティ.チップの深さ[ other.チップ種別 ] ) { return +1; } // 小さいほうが後 ← return 0; } // ローカル private int _音量 = チップ.最大音量; private int _位置 = 0; } } <|start_filename|>DTXMania2/ステージ/03認証/ユーザリスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.認証 { /// <summary> /// ユーザリストパネルの表示とユーザの選択。 /// </summary> /// <remarks> /// ユーザリストは <see cref="App.ユーザリスト"/> が保持している。 /// </remarks> class ユーザリスト : IDisposable { // プロパティ /// <summary> /// 現在選択中のユーザ。 /// <see cref="App.ユーザリスト"/> のインデックス番号。(0~) /// </summary> public int 選択中のユーザ { get; protected set; } = 0; // 生成と終了 public ユーザリスト() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._ユーザパネル = new 画像D2D( @"$(Images)\AuthStage\UserPanel.png" ); this._ユーザパネル光彩付き = new 画像D2D( @"$(Images)\AuthStage\UserPanelWithFrame.png" ); this._ユーザ肩書きパネル = new 画像D2D( @"$(Images)\AuthStage\UserSubPanel.png" ); this._ユーザ名 = new 文字列画像D2D[ Global.App.ユーザリスト.Count ]; for( int i = 0; i < this._ユーザ名.Length; i++ ) { this._ユーザ名[ i ] = new 文字列画像D2D() { 表示文字列 = Global.App.ユーザリスト[ i ].名前, フォントサイズpt = 46f, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 6f, 前景色 = Color4.Black, 背景色 = Color4.White, }; } this._光彩アニメーションを開始する(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); foreach( var uname in this._ユーザ名 ) uname.Dispose(); this._ユーザ肩書きパネル.Dispose(); this._ユーザパネル光彩付き.Dispose(); this._ユーザパネル.Dispose(); } // 進行と描画 public void 進行描画する( DeviceContext d2ddc ) { #region " 選択中のパネルの光彩アニメーションの進行。" //---------------- var 割合 = this._光彩アニメカウンタ.現在値の割合; float 不透明度; if( 0.5f > 割合 ) { 不透明度 = 1.0f - ( 割合 * 2.0f ); // 1→0 } else { 不透明度 = ( 割合 - 0.5f ) * 2.0f; // 0→1 } //---------------- #endregion #region " ユーザリストを描画する。" //---------------- var 描画位置 = new Vector2( 569f, 188f ); const float リストの改行幅 = 160f; int 表示人数 = Math.Min( 5, Global.App.ユーザリスト.Count ); // hack: 現状は最大5人までとする。 for( int i = 0; i < 表示人数; i++ ) { // ユーザパネル;選択中のユーザにはパネルに光彩を追加。 if( i == this.選択中のユーザ ) this._ユーザパネル光彩付き.描画する( d2ddc, 描画位置.X, 描画位置.Y + リストの改行幅 * i, 不透明度0to1: 不透明度 ); this._ユーザパネル.描画する( d2ddc, 描画位置.X, 描画位置.Y + リストの改行幅 * i ); // ユーザ名 this._ユーザ名[ i ].描画する( d2ddc, 描画位置.X + 32f, 描画位置.Y + 40f + リストの改行幅 * i ); // 肩書き this._ユーザ肩書きパネル.描画する( d2ddc, 描画位置.X, 描画位置.Y + リストの改行幅 * i ); } //---------------- #endregion } // ユーザ選択 /// <summary> /// ユーザリスト上で、選択されているユーザのひとつ前のユーザを選択する。 /// </summary> public void 前のユーザを選択する() { this.選択中のユーザ = ( this.選択中のユーザ - 1 + Global.App.ユーザリスト.Count ) % Global.App.ユーザリスト.Count; // 前がないなら末尾へ this._光彩アニメーションを開始する(); } /// <summary> /// ユーザリスト上で、選択されているユーザのひとつ前のユーザを選択する。 /// </summary> public void 次のユーザを選択する() { this.選択中のユーザ = ( this.選択中のユーザ + 1 ) % Global.App.ユーザリスト.Count; // 次がないなら先頭へ this._光彩アニメーションを開始する(); } // ローカル private readonly 画像D2D _ユーザパネル; private readonly 画像D2D _ユーザパネル光彩付き; private readonly 画像D2D _ユーザ肩書きパネル; private readonly 文字列画像D2D[] _ユーザ名; private LoopCounter _光彩アニメカウンタ = null!; private void _光彩アニメーションを開始する() { this._光彩アニメカウンタ = new LoopCounter( 0, 200, 5 ); } } } <|start_filename|>FDK/サウンド/SoundTimer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace FDK { /// <summary> /// サウンドデバイスを基準にしたタイマ。 /// </summary> public class SoundTimer : IDisposable { // プロパティ /// <summary> /// コンストラクタまたはリセットの時点からの相対経過時間[sec]。 /// </summary> public double 現在時刻sec { get { lock( this._スレッド間同期 ) { if( 0 < this._停止回数 ) return ( this._停止位置sec - this._開始位置sec ); // 一時停止中。 if( this._SoundDevice.TryGetTarget( out SoundDevice? device ) ) return ( device.GetDevicePosition() - this._開始位置sec ); // 稼働中。 throw new InvalidOperationException( "サウンドデバイスが無効です。" ); } } } // 生成と終了 public SoundTimer( SoundDevice device ) { using var _ = new LogBlock( Log.現在のメソッド名 ); this._SoundDevice = new WeakReference<SoundDevice>( device ); this.リセットする(); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); } // 操作 public void リセットする( double 新しい現在時刻sec = 0.0 ) { lock( this._スレッド間同期 ) { if( this._SoundDevice.TryGetTarget( out SoundDevice? device ) ) { this._開始位置sec = device.GetDevicePosition() - 新しい現在時刻sec; this._停止回数 = 0; this._停止位置sec = 0; } } } public void 一時停止する() { lock( this._スレッド間同期 ) { if( this._SoundDevice.TryGetTarget( out SoundDevice? device ) ) { if( 0 == this._停止回数 ) this._停止位置sec = device.GetDevicePosition(); this._停止回数++; } } } public void 再開する() { lock( this._スレッド間同期 ) { this._停止回数--; if( 0 == this._停止回数 ) this.リセットする( this._停止位置sec - this._開始位置sec ); } } // ローカル private WeakReference<SoundDevice> _SoundDevice; private int _停止回数 = 0; private double _開始位置sec = 0.0; private double _停止位置sec = 0.0; private readonly object _スレッド間同期 = new object(); } } <|start_filename|>SSTFEditor/UndoRedo/セル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace SSTFEditor.UndoRedo { public delegate void DGRedoを実行する<T>( T 変更対象, T 変更前の値, T 変更後の値, object 任意1, object 任意2 ); public delegate void DGUndoを実行する<T>( T 変更対象, T 変更前の値, T 変更後の値, object 任意1, object 任意2 ); class セル<T> : セルBase { public T 変更対象; public T 変更前の値; public T 変更後の値; public object 任意1; // 任意に使えるパラメータ領域 public object 任意2; // public セル( object 所有者ID, DGUndoを実行する<T> Undoアクション, DGRedoを実行する<T> Redoアクション, T 変更対象, T 変更前の値, T 変更後の値, object 任意1 = null, object 任意2 = null ) { base.所有者ID = 所有者ID; this.undoアクション = Undoアクション; this.redoアクション = Redoアクション; this.変更対象 = 変更対象; this.変更前の値 = 変更前の値; this.変更後の値 = 変更後の値; this.任意1 = 任意1; this.任意2 = 任意2; } public override void Redoを実行する() { base.所有者ID = null; this.redoアクション( this.変更対象, this.変更前の値, this.変更後の値, this.任意1, this.任意2 ); } public override void Undoを実行する() { base.所有者ID = null; this.undoアクション( this.変更対象, this.変更前の値, this.変更後の値, this.任意1, this.任意2 ); } protected DGRedoを実行する<T> redoアクション; protected DGUndoを実行する<T> undoアクション; } } <|start_filename|>DTXMania2/ステージ/07演奏/表示チップ種別.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; namespace DTXMania2.演奏 { /// <summary> /// チップの描画形態。 /// </summary> enum 表示チップ種別 { Unknown, LeftCymbal, RightCymbal, HiHat, HiHat_Open, HiHat_HalfOpen, Foot, Snare, Snare_OpenRim, Snare_ClosedRim, Snare_Ghost, Bass, LeftBass, Tom1, Tom1_Rim, Tom2, Tom2_Rim, Tom3, Tom3_Rim, LeftRide, RightRide, LeftRide_Cup, RightRide_Cup, LeftChina, RightChina, LeftSplash, RightSplash, LeftCymbal_Mute, RightCymbal_Mute, } } <|start_filename|>DTXMania2/ステージ/06曲読み込み/曲読み込みステージ.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Windows.Forms; using SharpDX; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using FDK; using SSTF=SSTFormat.v004; namespace DTXMania2.曲読み込み { /// <summary> /// <see cref="App.演奏譜面"/> を読み込んで、<see cref="App.演奏スコア"/> を生成する。 /// </summary> class 曲読み込みステージ : IStage { // プロパティ public enum フェーズ { フェードイン, 表示, 完了, キャンセル時フェードアウト, キャンセル, } public フェーズ 現在のフェーズ { get; protected set; } = フェーズ.完了; // 生成と終了 public 曲読み込みステージ() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._舞台画像 = new 舞台画像(); this._注意文 = new 画像D2D( @"$(Images)\LoadingStage\Caution.png" ); this._曲名画像 = new 文字列画像D2D() { フォント名 = "HGMaruGothicMPRO", フォントサイズpt = 70f, フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 10f, 前景色 = Color4.Black, 背景色 = Color4.White, 表示文字列 = Global.App.演奏譜面.譜面.Title, }; this._サブタイトル画像 = new 文字列画像D2D() { フォント名 = "HGMaruGothicMPRO", フォントサイズpt = 45f, フォントの太さ = FontWeight.Regular, フォントスタイル = FontStyle.Normal, 描画効果 = 文字列画像D2D.効果.縁取り, 縁のサイズdpx = 7f, 前景色 = Color4.Black, 背景色 = Color4.White, 表示文字列 = Global.App.演奏譜面.譜面.Artist, }; this._プレビュー画像 = new プレビュー画像(); this._難易度 = new 難易度(); Global.App.システムサウンド.再生する( システムサウンド種別.曲読み込みステージ_開始音 ); Global.App.システムサウンド.再生する( システムサウンド種別.曲読み込みステージ_ループBGM, ループ再生する: true ); this._舞台画像.ぼかしと縮小を適用する( 0.0 ); Global.App.アイキャッチ管理.現在のアイキャッチ.オープンする(); // 最初のフェーズへ。 this.現在のフェーズ = フェーズ.フェードイン; } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); //Global.App.システムサウンド.停止する( システムサウンド種別.曲読み込みステージ_開始音 ); --> 鳴りっぱなしでいい Global.App.システムサウンド.停止する( システムサウンド種別.曲読み込みステージ_ループBGM ); this._難易度.Dispose(); this._プレビュー画像.Dispose(); this._サブタイトル画像.Dispose(); this._曲名画像.Dispose(); this._注意文.Dispose(); this._舞台画像.Dispose(); } // 進行と描画 public void 進行する() { switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " フェードインが完了したら表示フェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.オープン完了 ) this.現在のフェーズ = フェーズ.表示; //---------------- #endregion break; } case フェーズ.表示: { #region " スコアを読み込んで次のフェーズへ。" //---------------- if( スコアを読み込む() ) { // 成功 this.現在のフェーズ = フェーズ.完了; } else { // 失敗またはキャンセル Log.Info( "スコアの読み込みをキャンセルしました。" ); Global.App.アイキャッチ管理.アイキャッチを選択しクローズする( nameof( 半回転黒フェード ) ); this.現在のフェーズ = フェーズ.キャンセル時フェードアウト; } //---------------- #endregion break; } case フェーズ.完了: case フェーズ.キャンセル: { #region " 遷移終了。Appによるステージ遷移待ち。" //---------------- //---------------- #endregion break; } case フェーズ.キャンセル時フェードアウト: { #region " フェードアウトが完了したらキャンセルフェーズへ。" //---------------- if( Global.App.アイキャッチ管理.現在のアイキャッチ.現在のフェーズ == アイキャッチ.フェーズ.クローズ完了 ) this.現在のフェーズ = フェーズ.キャンセル; //---------------- #endregion break; } } } public void 描画する() { var d2ddc = Global.GraphicResources.既定のD2D1DeviceContext; d2ddc.Transform = Matrix3x2.Identity; switch( this.現在のフェーズ ) { case フェーズ.フェードイン: { #region " 背景画面&アイキャッチフェードインを描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.表示: { #region " スコアを読み込んで完了フェーズへ。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.完了: { #region " 遷移終了。Appによるステージ遷移待ち。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } case フェーズ.キャンセル時フェードアウト: { #region " 背景画面&アイキャッチフェードアウトを描画する。" //---------------- d2ddc.BeginDraw(); this._背景画面を描画する( d2ddc ); Global.App.アイキャッチ管理.現在のアイキャッチ.進行描画する( d2ddc ); d2ddc.EndDraw(); //---------------- #endregion break; } } } /// <summary> /// スコアを読み込む。 /// </summary> /// <returns>読み込みに成功すれば true, 失敗またはキャンセルされれば false。</returns> public static bool スコアを読み込む() { using var _ = new LogBlock( Log.現在のメソッド名 ); var keyboard = Global.App.ドラム入力.Keyboard; #region " キャンセルチェック " //---------------- keyboard.ポーリングする(); if( keyboard.キーが押された( 0, Keys.Escape ) ) return false; //---------------- #endregion // 曲ファイルを読み込む。 var 選択曲ファイルの絶対パス = Global.App.演奏譜面.譜面.ScorePath; Global.App.演奏スコア = SSTF.スコア.ファイルから生成する( 選択曲ファイルの絶対パス ); #region " キャンセルチェック " //---------------- keyboard.ポーリングする(); if( keyboard.キーが押された( 0, Keys.Escape ) ) return false; //---------------- #endregion // 全チップの発声時刻を修正する。 foreach( var chip in Global.App.演奏スコア.チップリスト ) { // Viewerでの再生速度は、ビュアーモード時のみ反映する。 double 再生速度 = Global.Options.ビュアーモードである ? Global.App.ログオン中のユーザ.再生速度 * Global.App.演奏スコア.Viewerでの再生速度 : Global.App.ログオン中のユーザ.再生速度; chip.発声時刻sec /= 再生速度; chip.描画時刻sec /= 再生速度; chip.発声時刻sec -= Global.App.サウンドデバイス.再生遅延sec; } #region " キャンセルチェック " //---------------- keyboard.ポーリングする(); if( keyboard.キーが押された( 0, Keys.Escape ) ) return false; //---------------- #endregion // WAVを生成する。 Global.App.WAVキャッシュ.世代を進める(); // ビュアーモードで再生速度が異なっている場合は、さらに世代を進めてキャッシュを無効にする。 if( _ビュアーモードでの前回の再生速度 != Global.App.演奏スコア.Viewerでの再生速度 ) { Global.App.WAVキャッシュ.世代を進める(); _ビュアーモードでの前回の再生速度 = Global.App.演奏スコア.Viewerでの再生速度; } Global.App.WAV管理?.Dispose(); Global.App.WAV管理 = new WAV管理(); foreach( var kvp in Global.App.演奏スコア.WAVリスト ) { #region " キャンセルチェック " //---------------- keyboard.ポーリングする(); if( keyboard.キーが押された( 0, Keys.Escape ) ) return false; //---------------- #endregion var wavInfo = kvp.Value; var path = Path.Combine( Global.App.演奏スコア.PATH_WAV, wavInfo.ファイルパス ); Global.App.WAV管理.登録する( kvp.Key, path, wavInfo.多重再生する, wavInfo.BGMである ); } // AVIを生成する。 Global.App.AVI管理?.Dispose(); Global.App.AVI管理 = new AVI管理(); if( Global.App.ログオン中のユーザ.演奏中に動画を表示する ) { foreach( var kvp in Global.App.演奏スコア.AVIリスト ) { #region " キャンセルチェック " //---------------- keyboard.ポーリングする(); if( keyboard.キーが押された( 0, Keys.Escape ) ) return false; //---------------- #endregion var path = Path.Combine( Global.App.演奏スコア.PATH_WAV, kvp.Value ); // Viewerでの再生速度は、ビュアーモード時のみ反映する。 double 再生速度 = Global.Options.ビュアーモードである ? Global.App.ログオン中のユーザ.再生速度 * Global.App.演奏スコア.Viewerでの再生速度 : Global.App.ログオン中のユーザ.再生速度; Global.App.AVI管理.登録する( kvp.Key, path, 再生速度 ); } } #region " キャンセルチェック " //---------------- keyboard.ポーリングする(); if( keyboard.キーが押された( 0, Keys.Escape ) ) return false; //---------------- #endregion // 完了。 Log.Info( $"曲ファイルを読み込みました。[{Folder.絶対パスをフォルダ変数付き絶対パスに変換して返す( 選択曲ファイルの絶対パス )}]" ); return true; } // ローカル private readonly 舞台画像 _舞台画像; private readonly 画像D2D _注意文; private readonly 文字列画像D2D _曲名画像; private readonly 文字列画像D2D _サブタイトル画像; private readonly プレビュー画像 _プレビュー画像; private readonly 難易度 _難易度; private static double _ビュアーモードでの前回の再生速度 = 1.0; private void _曲名を描画する( DeviceContext d2ddc ) { var 表示位置dpx = new Vector2( 782f, 409f ); // 拡大率を計算して描画する。 float 最大幅dpx = Global.GraphicResources.設計画面サイズ.Width - 表示位置dpx.X - 20f; // -20f はマージン float X方向拡大率 = ( this._曲名画像.画像サイズdpx.Width <= 最大幅dpx ) ? 1f : 最大幅dpx / this._曲名画像.画像サイズdpx.Width; this._曲名画像.描画する( d2ddc, 表示位置dpx.X, 表示位置dpx.Y, X方向拡大率: X方向拡大率 ); } private void _サブタイトルを描画する( DeviceContext d2ddc ) { var 表示位置dpx = new Vector2( 782f, 520f ); // 拡大率を計算して描画する。 float 最大幅dpx = Global.GraphicResources.設計画面サイズ.Width - 表示位置dpx.X; float X方向拡大率 = ( this._サブタイトル画像.画像サイズdpx.Width <= 最大幅dpx ) ? 1f : 最大幅dpx / this._サブタイトル画像.画像サイズdpx.Width; this._サブタイトル画像.描画する( d2ddc, 表示位置dpx.X, 表示位置dpx.Y, X方向拡大率: X方向拡大率 ); } private void _背景画面を描画する( DeviceContext d2ddc ) { this._舞台画像.進行描画する( d2ddc ); this._注意文.描画する( d2ddc, 0f, 760f ); this._プレビュー画像.進行描画する( d2ddc ); this._難易度.進行描画する( d2ddc ); this._曲名を描画する( d2ddc ); this._サブタイトルを描画する( d2ddc ); } } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネル/パネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Animation; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.オプション設定 { /// <summary> /// すべてのパネルのベースとなるクラス。 /// 名前だけのパネルとしても使う。 /// </summary> class パネル : IDisposable { // プロパティ public string パネル名 { get; protected set; } = ""; /// <summary> /// パネル全体のサイズ。static。 /// </summary> public static Size2F サイズ => new Size2F( 642f, 96f ); public class ヘッダ色種別 { public static readonly Color4 青 = new Color4( 0xff725031 ); // ABGR public static readonly Color4 赤 = new Color4( 0xff315072 ); } public Color4 ヘッダ色 { get; set; } = ヘッダ色種別.青; // 生成と終了 public パネル( string パネル名, Action<パネル>? 値の変更処理 = null, Color4? ヘッダ色 = null ) { this.パネル名 = パネル名; this.ヘッダ色 = ( ヘッダ色.HasValue ) ? ヘッダ色.Value : ヘッダ色種別.青; // 既定値は青 this._値の変更処理 = 値の変更処理; this._パネル名画像 = new 文字列画像D2D() { 表示文字列 = this.パネル名, フォントサイズpt = 34f, 前景色 = Color4.White }; this._パネルの高さ割合 = new Variable( Global.Animation.Manager, initialValue: 1.0 ); this._パネルのストーリーボード = null; } // ※派生クラスから呼び出すのを忘れないこと。 public virtual void Dispose() { this._パネルのストーリーボード?.Dispose(); this._パネルの高さ割合.Dispose(); this._パネル名画像.Dispose(); } public override string ToString() => this.パネル名; // フェードイン・アウト public void フェードインを開始する( double 遅延sec, double 速度倍率 = 1.0 ) { double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; this._パネルの高さ割合.Dispose(); this._パネルの高さ割合 = new Variable( animation.Manager, initialValue: 1.0 ); this._パネルのストーリーボード?.Dispose(); this._パネルのストーリーボード = new Storyboard( animation.Manager ); using( var 遅延遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 遅延sec ) ) ) using( var 縮む遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.1 ), finalValue: 0.0 ) ) using( var 膨らむ遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.1 ), finalValue: 1.0 ) ) { this._パネルのストーリーボード.AddTransition( this._パネルの高さ割合, 遅延遷移 ); this._パネルのストーリーボード.AddTransition( this._パネルの高さ割合, 縮む遷移 ); this._パネルのストーリーボード.AddTransition( this._パネルの高さ割合, 膨らむ遷移 ); } this._パネルのストーリーボード.Schedule( animation.Timer.Time ); } public void フェードアウトを開始する( double 遅延sec, double 速度倍率 = 1.0 ) { double 秒( double v ) => ( v / 速度倍率 ); var animation = Global.Animation; if( null == this._パネルの高さ割合 ) // 未生成のときだけ生成。生成済みなら、その現状を引き継ぐ。 this._パネルの高さ割合 = new Variable( animation.Manager, initialValue: 1.0 ); this._パネルのストーリーボード?.Dispose(); this._パネルのストーリーボード = new Storyboard( animation.Manager ); using( var 遅延遷移 = animation.TrasitionLibrary.Constant( duration: 秒( 遅延sec ) ) ) using( var 縮む遷移 = animation.TrasitionLibrary.Linear( duration: 秒( 0.1 ), finalValue: 0.0 ) ) { this._パネルのストーリーボード.AddTransition( this._パネルの高さ割合, 遅延遷移 ); this._パネルのストーリーボード.AddTransition( this._パネルの高さ割合, 縮む遷移 ); } this._パネルのストーリーボード.Schedule( animation.Timer.Time ); } // 進行と描画 public virtual void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置, bool 選択中 ) { float 拡大率Y = (float)this._パネルの高さ割合.Value; float パネルとヘッダの上下マージン = サイズ.Height * ( 1f - 拡大率Y ) / 2f; float テキストの上下マージン = 76f * ( 1f - 拡大率Y ) / 2f; var パネル矩形 = new RectangleF( 左位置, 上位置 + パネルとヘッダの上下マージン, サイズ.Width, サイズ.Height * 拡大率Y ); var ヘッダ矩形 = new RectangleF( 左位置, 上位置 + パネルとヘッダの上下マージン, 40f, サイズ.Height * 拡大率Y ); var テキスト矩形 = new RectangleF( 左位置 + 20f, 上位置 + 10f + テキストの上下マージン, 280f, 76f * 拡大率Y ); if( 選択中 ) { // 選択されているパネルは、パネル矩形を左右にちょっと大きくする。 パネル矩形.Left -= 38f; パネル矩形.Width += 38f * 2f; } // (1) パネルの下地部分の描画。 using( var パネル背景色 = new SolidColorBrush( d2ddc, new Color4( Color3.Black, 0.5f ) ) ) using( var ヘッダ背景色 = new SolidColorBrush( d2ddc, this.ヘッダ色 ) ) using( var テキスト背景色 = new SolidColorBrush( d2ddc, Color4.Black ) ) { d2ddc.FillRectangle( パネル矩形, パネル背景色 ); d2ddc.FillRectangle( ヘッダ矩形, ヘッダ背景色 ); d2ddc.FillRectangle( テキスト矩形, テキスト背景色 ); } // (2) パネル名の描画。 this._パネル名画像.ビットマップを生成または更新する( d2ddc ); // 先に画像を更新する。↓で画像サイズを取得するため。 float 拡大率X = Math.Min( 1f, ( テキスト矩形.Width - 20f ) / this._パネル名画像.画像サイズdpx.Width ); // -20 は左右マージンの最低値[dpx] this._パネル名画像.描画する( d2ddc, テキスト矩形.Left + ( テキスト矩形.Width - this._パネル名画像.画像サイズdpx.Width * 拡大率X ) / 2f, テキスト矩形.Top + ( テキスト矩形.Height - this._パネル名画像.画像サイズdpx.Height * 拡大率Y ) / 2f, X方向拡大率: 拡大率X, Y方向拡大率: 拡大率Y ); } // 入力 public virtual void 確定キーが入力された() { // 必要あれば、派生クラスで実装すること。 this._値の変更処理?.Invoke( this ); } public virtual void 左移動キーが入力された() { // 必要あれば、派生クラスで実装すること。 this._値の変更処理?.Invoke( this ); } public virtual void 右移動キーが入力された() { // 必要あれば、派生クラスで実装すること。 this._値の変更処理?.Invoke( this ); } // その他 /// <summary> /// 子孫を直列に列挙する。 /// </summary> public IEnumerable<パネル> Traverse() { // (1) 自分 yield return this; // (2) 子 if( this is パネル_フォルダ folder ) { foreach( var child in folder.子パネルリスト ) foreach( var coc in child.Traverse() ) yield return coc; } } // ローカル protected readonly 文字列画像D2D _パネル名画像; // パネル名は画像で保持。 protected Action<パネル>? _値の変更処理 = null; /// <summary> /// 項目部分のサイズ。 /// left と top は、パネルの left,top からの相対値。 /// </summary> protected RectangleF 項目領域 = new RectangleF( +322f, +0f, 342f, サイズ.Height ); /// <summary> /// 0.0:ゼロ ~ 1.0:原寸 /// </summary> protected Variable _パネルの高さ割合; /// <summary> /// フェードイン・アウトアニメーション用 /// </summary> protected Storyboard? _パネルのストーリーボード = null; } } <|start_filename|>FDK/サウンド/SampleSourceFactory.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using CSCore; namespace FDK { /// <summary> /// <see cref="ISampleSource"/> オブジェクトの生成を行う。 /// </summary> public static class SampleSourceFactory { /// <summary> /// 指定されたファイルの音声をデコードし、<see cref="ISampleSource"/> オブジェクトを返す。 /// 失敗すれば null 。 /// </summary> public static ISampleSource? Create( SoundDevice device, VariablePath path, double 再生速度 = 1.0 ) { if( !( File.Exists( path.変数なしパス ) ) ) { Log.ERROR( $"ファイルが存在しません。[{path.変数付きパス}]" ); return null; } var 拡張子 = Path.GetExtension( path.変数なしパス ).ToLower(); if( ".ogg" == 拡張子 ) { #region " OggVorvis " //---------------- try { // ファイルを読み込んで IWaveSource を生成。 using var audioStream = new FileStream( path.変数なしパス, FileMode.Open, FileAccess.Read ); using var waveSource = new NVorbisOnStreamingSampleSource( audioStream, device.WaveFormat ).ToWaveSource(); // IWaveSource をリサンプルして ISampleSource を生成。 return new ResampledOnMemoryWaveSource( waveSource, device.WaveFormat, 再生速度 ).ToSampleSource(); } catch { // ダメだったので次へ。 } //---------------- #endregion } if( ".wav" == 拡張子 ) { #region " WAV " //---------------- try { // ファイルを読み込んで IWaveSource を生成。 using var waveSource = new WavOnStreamingWaveSource( path, device.WaveFormat ); if( waveSource.WaveFormat.WaveFormatTag == AudioEncoding.Pcm ) // ここでは PCM WAV のみサポート { // IWaveSource をリサンプルして ISampleSource を生成。 return new ResampledOnMemoryWaveSource( waveSource, device.WaveFormat, 再生速度 ).ToSampleSource(); } // PCM WAV 以外は次へ。 } catch { // ダメだったので次へ。 } //---------------- #endregion } if( ".xa" == 拡張子 ) { #region " XA " //---------------- try { // ファイルを読み込んで IWaveSource を生成。 using var waveSource = new XAOnMemoryWaveSource( path, device.WaveFormat ); // IWaveSource をリサンプルして ISampleSource を生成。 return new ResampledOnMemoryWaveSource( waveSource, device.WaveFormat, 再生速度 ).ToSampleSource(); } catch { // ダメだったので次へ。 } //---------------- #endregion } #region " 全部ダメだったら MediaFoundation で試みる。" //---------------- try { // ファイルを読み込んで IWaveSource を生成。 using var waveSource = new MediaFoundationOnMemoryWaveSource( path, device.WaveFormat ); // デコード完了まで待機。 if( !waveSource.DecodeComplete.Wait( 60_1000 ) ) // 最大1分 throw new TimeoutException( $"デコードタスクがタイムアウトしました。[{path.変数付きパス}]" ); // IWaveSource をリサンプルして ISampleSource を生成。 return new ResampledOnMemoryWaveSource( waveSource, device.WaveFormat, 再生速度 ).ToSampleSource(); } catch { // ダメだった } //---------------- #endregion Log.ERROR( $"未対応のオーディオファイルです。{path.変数付きパス}" ); return null; } } } <|start_filename|>SSTFormat/v004/チップ種別.cs<|end_filename|> using System; namespace SSTFormat.v004 { /// <summary> /// チップの種別を表す整数値。 /// </summary> /// <remarks> /// 互換性を維持するために、将来にわたって不変な int 型の数値を、明確に定義する。 /// 同じ理由から、一度廃止した番号の再利用は禁止。新しいメンバには常に新しい値(最終値+1~)を割り当てること。 /// </remarks> public enum チップ種別 : int { /// <summary> /// 未知。 /// </summary> Unknown = 0, // パッド #region " シンバル " //---------------- /// <summary> /// クラッシュシンバル(左)。 /// </summary> LeftCrash = 1, /// <summary> /// クラッシュシンバル(右)。 /// </summary> RightCrash = 21, /// <summary> /// シンバルミュート(左)。v1.2以降。 /// </summary> LeftCymbal_Mute = 27, /// <summary> /// シンバルミュート(右)。v1.2以降。 /// </summary> RightCymbal_Mute = 28, /// <summary> /// ライドシンバル。 /// </summary> Ride = 2, /// <summary> /// ライドシンバルのカップ。 /// </summary> Ride_Cup = 3, /// <summary> /// チャイナシンバル。 /// </summary> China = 4, /// <summary> /// スプラッシュシンバル。 /// </summary> Splash = 5, //---------------- #endregion #region " ハイハット " //---------------- /// <summary> /// ハイハットオープン。 /// </summary> HiHat_Open = 6, /// <summary> /// ハイハットハーフオープン(半開き)。 /// </summary> HiHat_HalfOpen = 7, /// <summary> /// ハイハットクローズ。 /// </summary> HiHat_Close = 8, /// <summary> /// フットハイハット。フットスプラッシュではない。 /// </summary> HiHat_Foot = 9, //---------------- #endregion #region " スネア " //---------------- /// <summary> /// スネア。 /// </summary> Snare = 10, /// <summary> /// スネアのオープンリムショット。 /// </summary> Snare_OpenRim = 11, /// <summary> /// スネアのクローズドリムショット。 /// </summary> Snare_ClosedRim = 12, /// <summary> /// スネアのゴーストショット。 /// </summary> Snare_Ghost = 13, //---------------- #endregion #region " バス " //---------------- /// <summary> /// バスドラム(右)。 /// </summary> Bass = 14, /// <summary> /// バスドラム(左)。v3.1 以降。 /// </summary> LeftBass = 38, //---------------- #endregion #region " タム " //---------------- /// <summary> /// ハイタム。 /// </summary> Tom1 = 15, /// <summary> /// ハイタムのリムショット。 /// </summary> Tom1_Rim = 16, /// <summary> /// ロータム。 /// </summary> Tom2 = 17, /// <summary> /// ロータムのリムショット。 /// </summary> Tom2_Rim = 18, /// <summary> /// フロアタム。 /// </summary> Tom3 = 19, /// <summary> /// フロアタムのリムショット。 /// </summary> Tom3_Rim = 20, //---------------- #endregion // 自動再生 /// <summary> /// 動画の再生を開始する。 /// </summary> /// <remarks> /// 再生する動画のファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.AVIリスト"/> に格納される。 /// ファイルが音声も持つ場合でも、音声は再生されない。 /// </remarks> 背景動画 = 25, /// <summary> /// ギター音の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// </remarks> GuitarAuto = 36, /// <summary> /// ベース音の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// </remarks> BassAuto = 37, /// <summary> /// BGMの再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// SEとの違いは、多重再生されないこと。 /// </remarks> BGM = 30, #region " SE1~32 " //---------------- /// <summary> /// 効果音1の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE1 = 31, /// <summary> /// 効果音2の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE2 = 32, /// <summary> /// 効果音3の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE3 = 33, /// <summary> /// 効果音4の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE4 = 34, /// <summary> /// 効果音5の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE5 = 35, /// <summary> /// 効果音6の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE6 = 39, /// <summary> /// 効果音7の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE7 = 40, /// <summary> /// 効果音8の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE8 = 41, /// <summary> /// 効果音9の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE9 = 42, /// <summary> /// 効果音10の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE10 = 43, /// <summary> /// 効果音11の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE11 = 44, /// <summary> /// 効果音12の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE12 = 45, /// <summary> /// 効果音13の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE13 = 46, /// <summary> /// 効果音14の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE14 = 47, /// <summary> /// 効果音15の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE15 = 48, /// <summary> /// 効果音16の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE16 = 49, /// <summary> /// 効果音17の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE17 = 50, /// <summary> /// 効果音18の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE18 = 51, /// <summary> /// 効果音19の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE19 = 52, /// <summary> /// 効果音20の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE20 = 53, /// <summary> /// 効果音21の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE21 = 54, /// <summary> /// 効果音22の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE22 = 55, /// <summary> /// 効果音23の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE23 = 56, /// <summary> /// 効果音24の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE24 = 57, /// <summary> /// 効果音25の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE25 = 58, /// <summary> /// 効果音26の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE26 = 59, /// <summary> /// 効果音27の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE27 = 60, /// <summary> /// 効果音28の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE28 = 61, /// <summary> /// 効果音29の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE29 = 62, /// <summary> /// 効果音30の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE30 = 63, /// <summary> /// 効果音31の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE31 = 64, /// <summary> /// 効果音32の再生を開始する。v4.1以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// ファイルが動画も持つ場合でも、動画は再生されない。 /// BGM との違いは、多重再生されること。 /// </remarks> SE32 = 65, //---------------- #endregion // アクセサリ /// <summary> /// BPM(Beat per Minutes;1分間の拍数)を変更する。 /// </summary> /// <remarks> /// BPM 値は、<see cref="チップ.BPM"/> に格納される。 /// </remarks> BPM = 22, /// <summary> /// 小節の先頭に置かれることが保証される以外に意味はない。v1.2以降。 /// </summary> 小節の先頭 = 29, /// <summary> /// 小節線を配置する。 /// </summary> 小節線 = 23, /// <summary> /// 拍線を配置する。 /// </summary> 拍線 = 24, #region " 廃止 " //---------------- 小節メモ = 26, //---------------- #endregion // ※現時点の最終値: 65 → 次は 66 から! } } <|start_filename|>DTXMania2/ステージ/05オプション設定/パネル/パネル_文字列リスト.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpDX; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.オプション設定 { /// <summary> /// 任意個の文字列から1つを選択できるパネル項目(コンボボックス)。 /// コンストラクタから活性化までの間に、<see cref="選択肢リスト"/> に文字列を設定すること。 /// </summary> class パネル_文字列リスト : パネル { // プロパティ public int 現在選択されている選択肢の番号 { get; set; } = 0; public List<(string 文字列, Color4 色)> 選択肢リスト { get; } = new List<(string, Color4)>(); // 生成と終了 public パネル_文字列リスト( string パネル名, IEnumerable<string> 選択肢初期値リスト, int 初期選択肢番号 = 0, Action<パネル>? 値の変更処理 = null ) : base( パネル名, 値の変更処理 ) { this._初期化( 選択肢初期値リスト.Select( ( item ) => (item, Color4.White) ), // // 既定の色は白 初期選択肢番号 ); } // 色指定あり public パネル_文字列リスト( string パネル名, IEnumerable<(string 文字列, Color4 色)> 選択肢初期値リスト, int 初期選択肢番号 = 0, Action<パネル>? 値の変更処理 = null ) : base( パネル名, 値の変更処理 ) { this._初期化( 選択肢初期値リスト, 初期選択肢番号 ); } private void _初期化( IEnumerable<(string 文字列, Color4 色)> 選択肢初期値リスト, int 初期選択肢番号 = 0 ) { this.現在選択されている選択肢の番号 = 初期選択肢番号; // 初期値があるなら設定する。 if( null != 選択肢初期値リスト ) this.選択肢リスト.AddRange( 選択肢初期値リスト ); this._選択肢文字列画像リスト = new Dictionary<string, 文字列画像D2D>(); for( int i = 0; i < this.選択肢リスト.Count; i++ ) { var image = new 文字列画像D2D() { 表示文字列 = this.選択肢リスト[ i ].文字列, フォントサイズpt = 34f, 前景色 = this.選択肢リスト[ i ].色, }; this._選択肢文字列画像リスト.Add( this.選択肢リスト[ i ].文字列, image ); } } public override void Dispose() { foreach( var kvp in this._選択肢文字列画像リスト ) kvp.Value.Dispose(); base.Dispose(); // 忘れずに } public override string ToString() => $"{this.パネル名}, 選択肢: [{string.Join( ",", this.選択肢リスト )}]"; // 入力 public override void 左移動キーが入力された() { this.現在選択されている選択肢の番号 = ( this.現在選択されている選択肢の番号 - 1 + this.選択肢リスト.Count ) % this.選択肢リスト.Count; base.左移動キーが入力された(); } public override void 右移動キーが入力された() { this.現在選択されている選択肢の番号 = ( this.現在選択されている選択肢の番号 + 1 ) % this.選択肢リスト.Count; base.右移動キーが入力された(); } public override void 確定キーが入力された() => this.右移動キーが入力された(); // 進行と描画 public override void 進行描画する( DeviceContext d2ddc, float 左位置, float 上位置, bool 選択中 ) { // (1) パネルの下地と名前を描画。 base.進行描画する( d2ddc, 左位置, 上位置, 選択中 ); // (2) 選択肢文字列画像の描画。 float 拡大率Y = (float)this._パネルの高さ割合.Value; float 項目の上下マージン = this.項目領域.Height * ( 1f - 拡大率Y ) / 2f; var 項目矩形 = new RectangleF( x: this.項目領域.X + 左位置, y: this.項目領域.Y + 上位置 + 項目の上下マージン, width: this.項目領域.Width, height: this.項目領域.Height * 拡大率Y ); var 項目画像 = this._選択肢文字列画像リスト[ this.選択肢リスト[ this.現在選択されている選択肢の番号 ].文字列 ]; 項目画像.ビットマップを生成または更新する( d2ddc ); // 先に画像を更新する。↓で画像サイズを取得するため。 float 拡大率X = Math.Min( 1f, ( 項目矩形.Width - 20f ) / 項目画像.画像サイズdpx.Width ); // -20 は左右マージンの最低値[dpx] 項目画像.描画する( d2ddc, 項目矩形.Left + ( 項目矩形.Width - 項目画像.画像サイズdpx.Width * 拡大率X ) / 2f, 項目矩形.Top + ( 項目矩形.Height - 項目画像.画像サイズdpx.Height * 拡大率Y ) / 2f, X方向拡大率: 拡大率X, Y方向拡大率: 拡大率Y ); } // ローカル private Dictionary<string, 文字列画像D2D> _選択肢文字列画像リスト = null!; // 各文字列は画像で保持。 } } <|start_filename|>SSTFormat/old/v003/チップ種別.cs<|end_filename|> using System; namespace SSTFormat.v003 { /// <summary> /// チップの種別を表す整数値。 /// </summary> /// <remarks> /// 互換性を維持するために、将来にわたって不変な int 型の数値を、明確に定義する。 /// </remarks> public enum チップ種別 : int { /// <summary> /// 未知。 /// </summary> Unknown = 0, #region " シンバル類 " //---------------- /// <summary> /// クラッシュシンバル(左)。 /// </summary> LeftCrash = 1, /// <summary> /// クラッシュシンバル(右)。 /// </summary> RightCrash = 21, /// <summary> /// シンバルミュート(左)。v1.2以降。 /// </summary> LeftCymbal_Mute = 27, /// <summary> /// シンバルミュート(右)。v1.2以降。 /// </summary> RightCymbal_Mute = 28, /// <summary> /// ライドシンバル。 /// </summary> Ride = 2, /// <summary> /// ライドシンバルのカップ。 /// </summary> Ride_Cup = 3, /// <summary> /// チャイナシンバル。 /// </summary> China = 4, /// <summary> /// スプラッシュシンバル。 /// </summary> Splash = 5, //---------------- #endregion #region " ハイハット類 " //---------------- /// <summary> /// ハイハットオープン。 /// </summary> HiHat_Open = 6, /// <summary> /// ハイハットハーフオープン(半開き)。 /// </summary> HiHat_HalfOpen = 7, /// <summary> /// ハイハットクローズ。 /// </summary> HiHat_Close = 8, /// <summary> /// フットハイハット。フットスプラッシュではない。 /// </summary> HiHat_Foot = 9, //---------------- #endregion #region " パッド類 " //---------------- /// <summary> /// スネア。 /// </summary> Snare = 10, /// <summary> /// スネアのオープンリムショット。 /// </summary> Snare_OpenRim = 11, /// <summary> /// スネアのクローズドリムショット。 /// </summary> Snare_ClosedRim = 12, /// <summary> /// スネアのゴーストショット。 /// </summary> Snare_Ghost = 13, /// <summary> /// バスドラム(右)。 /// </summary> Bass = 14, /// <summary> /// バスドラム(左)。v3.1 以降。 /// </summary> LeftBass = 38, /// <summary> /// ハイタム。 /// </summary> Tom1 = 15, /// <summary> /// ハイタムのリムショット。 /// </summary> Tom1_Rim = 16, /// <summary> /// ロータム。 /// </summary> Tom2 = 17, /// <summary> /// ロータムのリムショット。 /// </summary> Tom2_Rim = 18, /// <summary> /// フロアタム。 /// </summary> Tom3 = 19, /// <summary> /// フロアタムのリムショット。 /// </summary> Tom3_Rim = 20, //---------------- #endregion #region " オートサウンド類 " //---------------- /// <summary> /// 動画の再生を開始する。 /// </summary> /// <remarks> /// 再生する動画の識別子は <see cref="スコア.背景動画ID"/> に格納される。 /// 背景動画が音声も持つ場合には、音声の再生も開始される。 /// </remarks> 背景動画 = 25, /// <summary> /// BGMの再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> BGM = 30, /// <summary> /// 効果音1の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> SE1 = 31, /// <summary> /// 効果音2の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> SE2 = 32, /// <summary> /// 効果音3の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> SE3 = 33, /// <summary> /// 効果音4の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> SE4 = 34, /// <summary> /// 効果音5の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> SE5 = 35, /// <summary> /// ギター音の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> GuitarAuto = 36, /// <summary> /// ベース音の再生を開始する。v3.0以降。 /// </summary> /// <remarks> /// 再生するサウンドのファイル名は、<see cref="チップ.チップサブID"/> をキーとする <see cref="スコア.WAVリスト"/> に格納される。 /// </remarks> BassAuto = 37, //---------------- #endregion #region " 制御類 " //---------------- /// <summary> /// BPM(Beat per Minutes;1分間の拍数)を変更する。 /// </summary> /// <remarks> /// BPM 値は、<see cref="チップ.BPM"/> に格納される。 /// </remarks> BPM = 22, /// <summary> /// 小節の先頭に置かれることが保証される以外に意味はない。v1.2以降。 /// </summary> 小節の先頭 = 29, //---------------- #endregion #region " アクセサリ類 " //---------------- /// <summary> /// 小節線を配置する。 /// </summary> 小節線 = 23, /// <summary> /// 拍線を配置する。 /// </summary> 拍線 = 24, /// <summary> /// 小節に対するメモ(文字列)を保持する。 /// </summary> /// <remarks> /// メモは、チップとは関係なく、<see cref="スコア.小節メモリスト"/> に格納される。 /// そのため、この種別は非推奨。 /// </remarks> 小節メモ = 26, //---------------- #endregion // ※現時点の最終値: 38 } } <|start_filename|>DTXMania2/ステージ/04選曲/表示方法選択パネル.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using SharpDX.Direct2D1; using FDK; namespace DTXMania2.選曲 { class 表示方法選択パネル : IDisposable { // 生成と終了 public 表示方法選択パネル() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._論理パネル番号 = new TraceValue( Global.Animation, 初期値: 0.0, 切替時間sec: 0.1 ); } public virtual void Dispose() { using var _ = new LogBlock( Log.現在のメソッド名 ); this._論理パネル番号.Dispose(); foreach( var p in this._パネルs ) p.Dispose(); } // 進行と描画 public void 次のパネルを選択する() { this._論理パネル番号.目標値++; Global.App.曲ツリーリスト.SelectNext( Loop: true ); 曲.Song.現在の難易度レベル = () => Global.App.曲ツリーリスト.SelectedItem!.フォーカス難易度レベル; } public void 前のパネルを選択する() { this._論理パネル番号.目標値--; Global.App.曲ツリーリスト.SelectPrev( Loop: true ); 曲.Song.現在の難易度レベル = () => Global.App.曲ツリーリスト.SelectedItem!.フォーカス難易度レベル; } public void 進行描画する( DeviceContext d2ddc ) { // パネルを合計8枚表示する。(左隠れ1枚 + 表示6枚 + 右隠れ1枚) int 論理パネル番号 = (int)Math.Truncate( this._論理パネル番号.現在値 ); double 差分 = this._論理パネル番号.現在値 - (double)論理パネル番号; // -1.0 < 差分 < 1.0 for( int i = 0; i < 8; i++ ) { int 実パネル番号 = this._論理パネル番号を実パネル番号に変換して返す( 論理パネル番号 + i - 3 ); // 現在のパネルの3つ前から表示開始。 var 画像 = this._パネルs[ 実パネル番号 ].画像; const float パネル幅 = 144f; 画像.描画する( d2ddc, 左位置: (float)( 768f + パネル幅 * ( i - 差分 ) ), 上位置: ( 3 == i ) ? 90f : 54f, // i==3 が現在の選択パネル。他より下に描画。 不透明度0to1: ( 3 == i ) ? 1f : 0.5f ); // 〃       他より明るく描画。 } } // ローカル private class Panel : IDisposable { public VariablePath 画像の絶対パス; public 画像D2D 画像; public Panel( VariablePath path ) { this.画像の絶対パス = path; this.画像 = new 画像D2D( path ); } public virtual void Dispose() { this.画像.Dispose(); } }; /// <summary> /// <see cref="App.曲ツリーリスト"/> と同じ並びであること。 /// </summary> private readonly List<Panel> _パネルs = new List<Panel>() { new Panel( @"$(Images)\SelectStage\Sorting_All.png" ), new Panel( @"$(Images)\SelectStage\Sorting_by_Rating.png" ), }; private readonly TraceValue _論理パネル番号; private int _論理パネル番号を実パネル番号に変換して返す( int 論理パネル番号 ) { return ( 0 <= 論理パネル番号 ) ? // 例:パネル数 3 で論理パネル番号が正の時: 0,1,2,3,4,5,... → 実パネル番号 = 0,1,2,0,1,2,... 論理パネル番号 % this._パネルs.Count : // 例:パネル数 3 で論理パネル番号が負の時: -1,-2,-3,-4,-5,... → 実パネル番号 = 2,1,0,2,1,0,... ( this._パネルs.Count - ( ( -論理パネル番号 ) % this._パネルs.Count ) ) % this._パネルs.Count; } } } <|start_filename|>SSTFEditor/メインフォーム.Designer.cs<|end_filename|> namespace SSTFEditor { partial class メインフォーム { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(メインフォーム)); this.splitContainer分割パネルコンテナ = new System.Windows.Forms.SplitContainer(); this.tabControl情報タブコンテナ = new System.Windows.Forms.TabControl(); this.tabPage基本情報 = new System.Windows.Forms.TabPage(); this.pictureBoxプレビュー画像 = new System.Windows.Forms.PictureBox(); this.buttonプレビュー画像参照 = new System.Windows.Forms.Button(); this.textBoxプレビュー画像 = new System.Windows.Forms.TextBox(); this.labelプレビュー画像 = new System.Windows.Forms.Label(); this.buttonプレビューサウンド参照 = new System.Windows.Forms.Button(); this.textBoxプレビュー音声 = new System.Windows.Forms.TextBox(); this.labelプレビュー音声 = new System.Windows.Forms.Label(); this.labelメモ用小節番号 = new System.Windows.Forms.Label(); this.labelアーティスト名 = new System.Windows.Forms.Label(); this.textBoxアーティスト名 = new System.Windows.Forms.TextBox(); this.buttonBGM参照 = new System.Windows.Forms.Button(); this.labelBGM = new System.Windows.Forms.Label(); this.textBoxBGM = new System.Windows.Forms.TextBox(); this.buttonBGV参照 = new System.Windows.Forms.Button(); this.textBoxLevel = new System.Windows.Forms.TextBox(); this.trackBarLevel = new System.Windows.Forms.TrackBar(); this.labelLevel = new System.Windows.Forms.Label(); this.textBoxメモ = new System.Windows.Forms.TextBox(); this.numericUpDownメモ用小節番号 = new System.Windows.Forms.NumericUpDown(); this.labelメモ小節単位 = new System.Windows.Forms.Label(); this.labelBGV = new System.Windows.Forms.Label(); this.textBoxBGV = new System.Windows.Forms.TextBox(); this.label説明 = new System.Windows.Forms.Label(); this.textBox説明 = new System.Windows.Forms.TextBox(); this.label曲名 = new System.Windows.Forms.Label(); this.textBox曲名 = new System.Windows.Forms.TextBox(); this.label現在のチップ種別 = new System.Windows.Forms.Label(); this.labelCurrentChipType = new System.Windows.Forms.Label(); this.pictureBox譜面パネル = new System.Windows.Forms.PictureBox(); this.statusStripステータスバー = new System.Windows.Forms.StatusStrip(); this.menuStripメニューバー = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItemファイル = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem新規作成 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem開く = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem上書き保存 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem名前を付けて保存 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem終了 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem編集 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem元に戻す = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemやり直す = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem切り取り = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemコピー = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem貼り付け = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem削除 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItemすべて選択 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem選択モード = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem編集モード = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemモード切替え = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem検索 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem表示 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔4分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔6分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔8分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔12分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔16分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔24分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔32分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔36分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔48分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔64分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔128分 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔フリー = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItemガイド間隔拡大 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemガイド間隔縮小 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem再生 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem先頭から再生 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem現在位置から再生 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem現在位置からBGMのみ再生 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem再生停止 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemツール = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemオプション = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemヘルプ = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemバージョン = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripツールバー = new System.Windows.Forms.ToolStrip(); this.toolStripButton新規作成 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton開く = new System.Windows.Forms.ToolStripButton(); this.toolStripButton上書き保存 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton切り取り = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonコピー = new System.Windows.Forms.ToolStripButton(); this.toolStripButton貼り付け = new System.Windows.Forms.ToolStripButton(); this.toolStripButton削除 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton元に戻す = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonやり直す = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripComboBox譜面拡大率 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripComboBoxガイド間隔 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripButton選択モード = new System.Windows.Forms.ToolStripButton(); this.toolStripButton編集モード = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton先頭から再生 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton現在位置から再生 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton現在位置からBGMのみ再生 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton再生停止 = new System.Windows.Forms.ToolStripButton(); this.toolStripComboBox再生速度 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton音量Down = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel音量 = new System.Windows.Forms.ToolStripLabel(); this.toolStripButton音量UP = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator(); this.vScrollBar譜面用垂直スクロールバー = new System.Windows.Forms.VScrollBar(); this.toolTipメインフォーム = new System.Windows.Forms.ToolTip(this.components); this.contextMenuStrip譜面右メニュー = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripMenuItem選択チップの切り取り = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem選択チップのコピー = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem選択チップの貼り付け = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem選択チップの削除 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItemすべてのチップの選択 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem小節長変更 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem小節の挿入 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem小節の削除 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem音量指定 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量2 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量3 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量4 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量5 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量6 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量7 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem音量8 = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer分割パネルコンテナ)).BeginInit(); this.splitContainer分割パネルコンテナ.Panel1.SuspendLayout(); this.splitContainer分割パネルコンテナ.Panel2.SuspendLayout(); this.splitContainer分割パネルコンテナ.SuspendLayout(); this.tabControl情報タブコンテナ.SuspendLayout(); this.tabPage基本情報.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxプレビュー画像)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarLevel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownメモ用小節番号)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox譜面パネル)).BeginInit(); this.menuStripメニューバー.SuspendLayout(); this.toolStripツールバー.SuspendLayout(); this.contextMenuStrip譜面右メニュー.SuspendLayout(); this.SuspendLayout(); // // splitContainer分割パネルコンテナ // resources.ApplyResources(this.splitContainer分割パネルコンテナ, "splitContainer分割パネルコンテナ"); this.splitContainer分割パネルコンテナ.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer分割パネルコンテナ.Name = "splitContainer分割パネルコンテナ"; // // splitContainer分割パネルコンテナ.Panel1 // resources.ApplyResources(this.splitContainer分割パネルコンテナ.Panel1, "splitContainer分割パネルコンテナ.Panel1"); this.splitContainer分割パネルコンテナ.Panel1.Controls.Add(this.tabControl情報タブコンテナ); this.toolTipメインフォーム.SetToolTip(this.splitContainer分割パネルコンテナ.Panel1, resources.GetString("splitContainer分割パネルコンテナ.Panel1.ToolTip")); // // splitContainer分割パネルコンテナ.Panel2 // resources.ApplyResources(this.splitContainer分割パネルコンテナ.Panel2, "splitContainer分割パネルコンテナ.Panel2"); this.splitContainer分割パネルコンテナ.Panel2.BackColor = System.Drawing.Color.Black; this.splitContainer分割パネルコンテナ.Panel2.Controls.Add(this.label現在のチップ種別); this.splitContainer分割パネルコンテナ.Panel2.Controls.Add(this.labelCurrentChipType); this.splitContainer分割パネルコンテナ.Panel2.Controls.Add(this.pictureBox譜面パネル); this.toolTipメインフォーム.SetToolTip(this.splitContainer分割パネルコンテナ.Panel2, resources.GetString("splitContainer分割パネルコンテナ.Panel2.ToolTip")); this.splitContainer分割パネルコンテナ.Panel2.SizeChanged += new System.EventHandler(this.splitContainer分割パネルコンテナ_Panel2_SizeChanged); this.splitContainer分割パネルコンテナ.Panel2.Paint += new System.Windows.Forms.PaintEventHandler(this.splitContainer分割パネルコンテナ_Panel2_Paint); this.toolTipメインフォーム.SetToolTip(this.splitContainer分割パネルコンテナ, resources.GetString("splitContainer分割パネルコンテナ.ToolTip")); // // tabControl情報タブコンテナ // resources.ApplyResources(this.tabControl情報タブコンテナ, "tabControl情報タブコンテナ"); this.tabControl情報タブコンテナ.Controls.Add(this.tabPage基本情報); this.tabControl情報タブコンテナ.Name = "tabControl情報タブコンテナ"; this.tabControl情報タブコンテナ.SelectedIndex = 0; this.toolTipメインフォーム.SetToolTip(this.tabControl情報タブコンテナ, resources.GetString("tabControl情報タブコンテナ.ToolTip")); // // tabPage基本情報 // resources.ApplyResources(this.tabPage基本情報, "tabPage基本情報"); this.tabPage基本情報.BackColor = System.Drawing.SystemColors.Window; this.tabPage基本情報.Controls.Add(this.pictureBoxプレビュー画像); this.tabPage基本情報.Controls.Add(this.buttonプレビュー画像参照); this.tabPage基本情報.Controls.Add(this.textBoxプレビュー画像); this.tabPage基本情報.Controls.Add(this.labelプレビュー画像); this.tabPage基本情報.Controls.Add(this.buttonプレビューサウンド参照); this.tabPage基本情報.Controls.Add(this.textBoxプレビュー音声); this.tabPage基本情報.Controls.Add(this.labelプレビュー音声); this.tabPage基本情報.Controls.Add(this.labelメモ用小節番号); this.tabPage基本情報.Controls.Add(this.labelアーティスト名); this.tabPage基本情報.Controls.Add(this.textBoxアーティスト名); this.tabPage基本情報.Controls.Add(this.buttonBGM参照); this.tabPage基本情報.Controls.Add(this.labelBGM); this.tabPage基本情報.Controls.Add(this.textBoxBGM); this.tabPage基本情報.Controls.Add(this.buttonBGV参照); this.tabPage基本情報.Controls.Add(this.textBoxLevel); this.tabPage基本情報.Controls.Add(this.trackBarLevel); this.tabPage基本情報.Controls.Add(this.labelLevel); this.tabPage基本情報.Controls.Add(this.textBoxメモ); this.tabPage基本情報.Controls.Add(this.numericUpDownメモ用小節番号); this.tabPage基本情報.Controls.Add(this.labelメモ小節単位); this.tabPage基本情報.Controls.Add(this.labelBGV); this.tabPage基本情報.Controls.Add(this.textBoxBGV); this.tabPage基本情報.Controls.Add(this.label説明); this.tabPage基本情報.Controls.Add(this.textBox説明); this.tabPage基本情報.Controls.Add(this.label曲名); this.tabPage基本情報.Controls.Add(this.textBox曲名); this.tabPage基本情報.Name = "tabPage基本情報"; this.toolTipメインフォーム.SetToolTip(this.tabPage基本情報, resources.GetString("tabPage基本情報.ToolTip")); // // pictureBoxプレビュー画像 // resources.ApplyResources(this.pictureBoxプレビュー画像, "pictureBoxプレビュー画像"); this.pictureBoxプレビュー画像.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictureBoxプレビュー画像.Name = "pictureBoxプレビュー画像"; this.pictureBoxプレビュー画像.TabStop = false; this.toolTipメインフォーム.SetToolTip(this.pictureBoxプレビュー画像, resources.GetString("pictureBoxプレビュー画像.ToolTip")); // // buttonプレビュー画像参照 // resources.ApplyResources(this.buttonプレビュー画像参照, "buttonプレビュー画像参照"); this.buttonプレビュー画像参照.Name = "buttonプレビュー画像参照"; this.toolTipメインフォーム.SetToolTip(this.buttonプレビュー画像参照, resources.GetString("buttonプレビュー画像参照.ToolTip")); this.buttonプレビュー画像参照.UseVisualStyleBackColor = true; this.buttonプレビュー画像参照.Click += new System.EventHandler(this.buttonプレビュー画像参照_Click); // // textBoxプレビュー画像 // resources.ApplyResources(this.textBoxプレビュー画像, "textBoxプレビュー画像"); this.textBoxプレビュー画像.Name = "textBoxプレビュー画像"; this.toolTipメインフォーム.SetToolTip(this.textBoxプレビュー画像, resources.GetString("textBoxプレビュー画像.ToolTip")); this.textBoxプレビュー画像.TextChanged += new System.EventHandler(this.textBoxプレビュー画像_TextChanged); this.textBoxプレビュー画像.Validated += new System.EventHandler(this.textBoxプレビュー画像_Validated); // // labelプレビュー画像 // resources.ApplyResources(this.labelプレビュー画像, "labelプレビュー画像"); this.labelプレビュー画像.Name = "labelプレビュー画像"; this.toolTipメインフォーム.SetToolTip(this.labelプレビュー画像, resources.GetString("labelプレビュー画像.ToolTip")); // // buttonプレビューサウンド参照 // resources.ApplyResources(this.buttonプレビューサウンド参照, "buttonプレビューサウンド参照"); this.buttonプレビューサウンド参照.Name = "buttonプレビューサウンド参照"; this.toolTipメインフォーム.SetToolTip(this.buttonプレビューサウンド参照, resources.GetString("buttonプレビューサウンド参照.ToolTip")); this.buttonプレビューサウンド参照.UseVisualStyleBackColor = true; this.buttonプレビューサウンド参照.Click += new System.EventHandler(this.buttonプレビュー音声_Click); // // textBoxプレビュー音声 // resources.ApplyResources(this.textBoxプレビュー音声, "textBoxプレビュー音声"); this.textBoxプレビュー音声.Name = "textBoxプレビュー音声"; this.toolTipメインフォーム.SetToolTip(this.textBoxプレビュー音声, resources.GetString("textBoxプレビュー音声.ToolTip")); this.textBoxプレビュー音声.TextChanged += new System.EventHandler(this.textBoxプレビュー音声_TextChanged); this.textBoxプレビュー音声.Validated += new System.EventHandler(this.textBoxプレビュー音声_Validated); // // labelプレビュー音声 // resources.ApplyResources(this.labelプレビュー音声, "labelプレビュー音声"); this.labelプレビュー音声.Name = "labelプレビュー音声"; this.toolTipメインフォーム.SetToolTip(this.labelプレビュー音声, resources.GetString("labelプレビュー音声.ToolTip")); // // labelメモ用小節番号 // resources.ApplyResources(this.labelメモ用小節番号, "labelメモ用小節番号"); this.labelメモ用小節番号.Name = "labelメモ用小節番号"; this.toolTipメインフォーム.SetToolTip(this.labelメモ用小節番号, resources.GetString("labelメモ用小節番号.ToolTip")); // // labelアーティスト名 // resources.ApplyResources(this.labelアーティスト名, "labelアーティスト名"); this.labelアーティスト名.Name = "labelアーティスト名"; this.toolTipメインフォーム.SetToolTip(this.labelアーティスト名, resources.GetString("labelアーティスト名.ToolTip")); // // textBoxアーティスト名 // resources.ApplyResources(this.textBoxアーティスト名, "textBoxアーティスト名"); this.textBoxアーティスト名.Name = "textBoxアーティスト名"; this.toolTipメインフォーム.SetToolTip(this.textBoxアーティスト名, resources.GetString("textBoxアーティスト名.ToolTip")); this.textBoxアーティスト名.TextChanged += new System.EventHandler(this.textBoxアーティスト名_TextChanged); this.textBoxアーティスト名.Validated += new System.EventHandler(this.textBoxアーティスト名_Validated); // // buttonBGM参照 // resources.ApplyResources(this.buttonBGM参照, "buttonBGM参照"); this.buttonBGM参照.Name = "buttonBGM参照"; this.toolTipメインフォーム.SetToolTip(this.buttonBGM参照, resources.GetString("buttonBGM参照.ToolTip")); this.buttonBGM参照.UseVisualStyleBackColor = true; this.buttonBGM参照.Click += new System.EventHandler(this.buttonBGM参照_Click); // // labelBGM // resources.ApplyResources(this.labelBGM, "labelBGM"); this.labelBGM.Name = "labelBGM"; this.toolTipメインフォーム.SetToolTip(this.labelBGM, resources.GetString("labelBGM.ToolTip")); // // textBoxBGM // resources.ApplyResources(this.textBoxBGM, "textBoxBGM"); this.textBoxBGM.Name = "textBoxBGM"; this.toolTipメインフォーム.SetToolTip(this.textBoxBGM, resources.GetString("textBoxBGM.ToolTip")); this.textBoxBGM.TextChanged += new System.EventHandler(this.textBoxBGM_TextChanged); this.textBoxBGM.Validated += new System.EventHandler(this.textBoxBGM_Validated); // // buttonBGV参照 // resources.ApplyResources(this.buttonBGV参照, "buttonBGV参照"); this.buttonBGV参照.Name = "buttonBGV参照"; this.toolTipメインフォーム.SetToolTip(this.buttonBGV参照, resources.GetString("buttonBGV参照.ToolTip")); this.buttonBGV参照.UseVisualStyleBackColor = true; this.buttonBGV参照.Click += new System.EventHandler(this.buttonBGV参照_Click); // // textBoxLevel // resources.ApplyResources(this.textBoxLevel, "textBoxLevel"); this.textBoxLevel.Name = "textBoxLevel"; this.toolTipメインフォーム.SetToolTip(this.textBoxLevel, resources.GetString("textBoxLevel.ToolTip")); this.textBoxLevel.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxLevel_Validating); this.textBoxLevel.Validated += new System.EventHandler(this.textBoxLevel_Validated); // // trackBarLevel // resources.ApplyResources(this.trackBarLevel, "trackBarLevel"); this.trackBarLevel.LargeChange = 50; this.trackBarLevel.Maximum = 999; this.trackBarLevel.Name = "trackBarLevel"; this.toolTipメインフォーム.SetToolTip(this.trackBarLevel, resources.GetString("trackBarLevel.ToolTip")); this.trackBarLevel.Value = 500; this.trackBarLevel.Scroll += new System.EventHandler(this.trackBarLevel_Scroll); // // labelLevel // resources.ApplyResources(this.labelLevel, "labelLevel"); this.labelLevel.Name = "labelLevel"; this.toolTipメインフォーム.SetToolTip(this.labelLevel, resources.GetString("labelLevel.ToolTip")); // // textBoxメモ // resources.ApplyResources(this.textBoxメモ, "textBoxメモ"); this.textBoxメモ.Name = "textBoxメモ"; this.toolTipメインフォーム.SetToolTip(this.textBoxメモ, resources.GetString("textBoxメモ.ToolTip")); this.textBoxメモ.TextChanged += new System.EventHandler(this.textBoxメモ_TextChanged); this.textBoxメモ.Validated += new System.EventHandler(this.textBoxメモ_Validated); // // numericUpDownメモ用小節番号 // resources.ApplyResources(this.numericUpDownメモ用小節番号, "numericUpDownメモ用小節番号"); this.numericUpDownメモ用小節番号.Maximum = new decimal(new int[] { 99999999, 0, 0, 0}); this.numericUpDownメモ用小節番号.Name = "numericUpDownメモ用小節番号"; this.toolTipメインフォーム.SetToolTip(this.numericUpDownメモ用小節番号, resources.GetString("numericUpDownメモ用小節番号.ToolTip")); this.numericUpDownメモ用小節番号.ValueChanged += new System.EventHandler(this.numericUpDownメモ用小節番号_ValueChanged); // // labelメモ小節単位 // resources.ApplyResources(this.labelメモ小節単位, "labelメモ小節単位"); this.labelメモ小節単位.Name = "labelメモ小節単位"; this.toolTipメインフォーム.SetToolTip(this.labelメモ小節単位, resources.GetString("labelメモ小節単位.ToolTip")); // // labelBGV // resources.ApplyResources(this.labelBGV, "labelBGV"); this.labelBGV.Name = "labelBGV"; this.toolTipメインフォーム.SetToolTip(this.labelBGV, resources.GetString("labelBGV.ToolTip")); // // textBoxBGV // resources.ApplyResources(this.textBoxBGV, "textBoxBGV"); this.textBoxBGV.Name = "textBoxBGV"; this.toolTipメインフォーム.SetToolTip(this.textBoxBGV, resources.GetString("textBoxBGV.ToolTip")); this.textBoxBGV.TextChanged += new System.EventHandler(this.textBoxBGV_TextChanged); this.textBoxBGV.Validated += new System.EventHandler(this.textBoxBGV_Validated); // // label説明 // resources.ApplyResources(this.label説明, "label説明"); this.label説明.Name = "label説明"; this.toolTipメインフォーム.SetToolTip(this.label説明, resources.GetString("label説明.ToolTip")); // // textBox説明 // resources.ApplyResources(this.textBox説明, "textBox説明"); this.textBox説明.Name = "textBox説明"; this.toolTipメインフォーム.SetToolTip(this.textBox説明, resources.GetString("textBox説明.ToolTip")); this.textBox説明.TextChanged += new System.EventHandler(this.textBox説明_TextChanged); this.textBox説明.Validated += new System.EventHandler(this.textBox説明_Validated); // // label曲名 // resources.ApplyResources(this.label曲名, "label曲名"); this.label曲名.Name = "label曲名"; this.toolTipメインフォーム.SetToolTip(this.label曲名, resources.GetString("label曲名.ToolTip")); // // textBox曲名 // resources.ApplyResources(this.textBox曲名, "textBox曲名"); this.textBox曲名.Name = "textBox曲名"; this.toolTipメインフォーム.SetToolTip(this.textBox曲名, resources.GetString("textBox曲名.ToolTip")); this.textBox曲名.TextChanged += new System.EventHandler(this.textBox曲名_TextChanged); this.textBox曲名.Validated += new System.EventHandler(this.textBox曲名_Validated); // // label現在のチップ種別 // resources.ApplyResources(this.label現在のチップ種別, "label現在のチップ種別"); this.label現在のチップ種別.ForeColor = System.Drawing.Color.Red; this.label現在のチップ種別.Name = "label現在のチップ種別"; this.toolTipメインフォーム.SetToolTip(this.label現在のチップ種別, resources.GetString("label現在のチップ種別.ToolTip")); // // labelCurrentChipType // resources.ApplyResources(this.labelCurrentChipType, "labelCurrentChipType"); this.labelCurrentChipType.ForeColor = System.Drawing.Color.White; this.labelCurrentChipType.Name = "labelCurrentChipType"; this.toolTipメインフォーム.SetToolTip(this.labelCurrentChipType, resources.GetString("labelCurrentChipType.ToolTip")); // // pictureBox譜面パネル // resources.ApplyResources(this.pictureBox譜面パネル, "pictureBox譜面パネル"); this.pictureBox譜面パネル.BackColor = System.Drawing.Color.Black; this.pictureBox譜面パネル.Name = "pictureBox譜面パネル"; this.pictureBox譜面パネル.TabStop = false; this.toolTipメインフォーム.SetToolTip(this.pictureBox譜面パネル, resources.GetString("pictureBox譜面パネル.ToolTip")); this.pictureBox譜面パネル.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox譜面パネル_Paint); this.pictureBox譜面パネル.MouseClick += new System.Windows.Forms.MouseEventHandler(this.pictureBox譜面パネル_MouseClick); this.pictureBox譜面パネル.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox譜面パネル_MouseDown); this.pictureBox譜面パネル.MouseEnter += new System.EventHandler(this.pictureBox譜面パネル_MouseEnter); this.pictureBox譜面パネル.MouseLeave += new System.EventHandler(this.pictureBox譜面パネル_MouseLeave); this.pictureBox譜面パネル.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox譜面パネル_MouseMove); this.pictureBox譜面パネル.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.pictureBox譜面パネル_PreviewKeyDown); // // statusStripステータスバー // resources.ApplyResources(this.statusStripステータスバー, "statusStripステータスバー"); this.statusStripステータスバー.Name = "statusStripステータスバー"; this.toolTipメインフォーム.SetToolTip(this.statusStripステータスバー, resources.GetString("statusStripステータスバー.ToolTip")); // // menuStripメニューバー // resources.ApplyResources(this.menuStripメニューバー, "menuStripメニューバー"); this.menuStripメニューバー.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemファイル, this.toolStripMenuItem編集, this.toolStripMenuItem表示, this.toolStripMenuItem再生, this.toolStripMenuItemツール, this.toolStripMenuItemヘルプ}); this.menuStripメニューバー.Name = "menuStripメニューバー"; this.toolTipメインフォーム.SetToolTip(this.menuStripメニューバー, resources.GetString("menuStripメニューバー.ToolTip")); // // toolStripMenuItemファイル // resources.ApplyResources(this.toolStripMenuItemファイル, "toolStripMenuItemファイル"); this.toolStripMenuItemファイル.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem新規作成, this.toolStripMenuItem開く, this.toolStripMenuItem上書き保存, this.toolStripMenuItem名前を付けて保存, this.toolStripSeparator1, this.toolStripMenuItem終了}); this.toolStripMenuItemファイル.Name = "toolStripMenuItemファイル"; // // toolStripMenuItem新規作成 // resources.ApplyResources(this.toolStripMenuItem新規作成, "toolStripMenuItem新規作成"); this.toolStripMenuItem新規作成.Name = "toolStripMenuItem新規作成"; this.toolStripMenuItem新規作成.Click += new System.EventHandler(this.toolStripMenuItem新規作成_Click); // // toolStripMenuItem開く // resources.ApplyResources(this.toolStripMenuItem開く, "toolStripMenuItem開く"); this.toolStripMenuItem開く.Name = "toolStripMenuItem開く"; this.toolStripMenuItem開く.Click += new System.EventHandler(this.toolStripMenuItem開く_Click); // // toolStripMenuItem上書き保存 // resources.ApplyResources(this.toolStripMenuItem上書き保存, "toolStripMenuItem上書き保存"); this.toolStripMenuItem上書き保存.Name = "toolStripMenuItem上書き保存"; this.toolStripMenuItem上書き保存.Click += new System.EventHandler(this.toolStripMenuItem上書き保存_Click); // // toolStripMenuItem名前を付けて保存 // resources.ApplyResources(this.toolStripMenuItem名前を付けて保存, "toolStripMenuItem名前を付けて保存"); this.toolStripMenuItem名前を付けて保存.Name = "toolStripMenuItem名前を付けて保存"; this.toolStripMenuItem名前を付けて保存.Click += new System.EventHandler(this.toolStripMenuItem名前を付けて保存_Click); // // toolStripSeparator1 // resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); this.toolStripSeparator1.Name = "toolStripSeparator1"; // // toolStripMenuItem終了 // resources.ApplyResources(this.toolStripMenuItem終了, "toolStripMenuItem終了"); this.toolStripMenuItem終了.Name = "toolStripMenuItem終了"; this.toolStripMenuItem終了.Click += new System.EventHandler(this.toolStripMenuItem終了_Click); // // toolStripMenuItem編集 // resources.ApplyResources(this.toolStripMenuItem編集, "toolStripMenuItem編集"); this.toolStripMenuItem編集.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem元に戻す, this.toolStripMenuItemやり直す, this.toolStripSeparator2, this.toolStripMenuItem切り取り, this.toolStripMenuItemコピー, this.toolStripMenuItem貼り付け, this.toolStripMenuItem削除, this.toolStripSeparator3, this.toolStripMenuItemすべて選択, this.toolStripSeparator4, this.toolStripMenuItem選択モード, this.toolStripMenuItem編集モード, this.toolStripMenuItemモード切替え, this.toolStripSeparator5, this.toolStripMenuItem検索}); this.toolStripMenuItem編集.Name = "toolStripMenuItem編集"; // // toolStripMenuItem元に戻す // resources.ApplyResources(this.toolStripMenuItem元に戻す, "toolStripMenuItem元に戻す"); this.toolStripMenuItem元に戻す.Name = "toolStripMenuItem元に戻す"; this.toolStripMenuItem元に戻す.Click += new System.EventHandler(this.toolStripMenuItem元に戻す_Click); // // toolStripMenuItemやり直す // resources.ApplyResources(this.toolStripMenuItemやり直す, "toolStripMenuItemやり直す"); this.toolStripMenuItemやり直す.Name = "toolStripMenuItemやり直す"; this.toolStripMenuItemやり直す.Click += new System.EventHandler(this.toolStripMenuItemやり直す_Click); // // toolStripSeparator2 // resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2"); this.toolStripSeparator2.Name = "toolStripSeparator2"; // // toolStripMenuItem切り取り // resources.ApplyResources(this.toolStripMenuItem切り取り, "toolStripMenuItem切り取り"); this.toolStripMenuItem切り取り.Name = "toolStripMenuItem切り取り"; this.toolStripMenuItem切り取り.Click += new System.EventHandler(this.toolStripMenuItem切り取り_Click); // // toolStripMenuItemコピー // resources.ApplyResources(this.toolStripMenuItemコピー, "toolStripMenuItemコピー"); this.toolStripMenuItemコピー.Name = "toolStripMenuItemコピー"; this.toolStripMenuItemコピー.Click += new System.EventHandler(this.toolStripMenuItemコピー_Click); // // toolStripMenuItem貼り付け // resources.ApplyResources(this.toolStripMenuItem貼り付け, "toolStripMenuItem貼り付け"); this.toolStripMenuItem貼り付け.Name = "toolStripMenuItem貼り付け"; this.toolStripMenuItem貼り付け.Click += new System.EventHandler(this.toolStripMenuItem貼り付け_Click); // // toolStripMenuItem削除 // resources.ApplyResources(this.toolStripMenuItem削除, "toolStripMenuItem削除"); this.toolStripMenuItem削除.Name = "toolStripMenuItem削除"; this.toolStripMenuItem削除.Click += new System.EventHandler(this.toolStripMenuItem削除_Click); // // toolStripSeparator3 // resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3"); this.toolStripSeparator3.Name = "toolStripSeparator3"; // // toolStripMenuItemすべて選択 // resources.ApplyResources(this.toolStripMenuItemすべて選択, "toolStripMenuItemすべて選択"); this.toolStripMenuItemすべて選択.Name = "toolStripMenuItemすべて選択"; this.toolStripMenuItemすべて選択.Click += new System.EventHandler(this.toolStripMenuItemすべて選択_Click); // // toolStripSeparator4 // resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4"); this.toolStripSeparator4.Name = "toolStripSeparator4"; // // toolStripMenuItem選択モード // resources.ApplyResources(this.toolStripMenuItem選択モード, "toolStripMenuItem選択モード"); this.toolStripMenuItem選択モード.Name = "toolStripMenuItem選択モード"; this.toolStripMenuItem選択モード.Click += new System.EventHandler(this.toolStripMenuItem選択モード_Click); // // toolStripMenuItem編集モード // resources.ApplyResources(this.toolStripMenuItem編集モード, "toolStripMenuItem編集モード"); this.toolStripMenuItem編集モード.Name = "toolStripMenuItem編集モード"; this.toolStripMenuItem編集モード.Click += new System.EventHandler(this.toolStripMenuItem編集モード_Click); // // toolStripMenuItemモード切替え // resources.ApplyResources(this.toolStripMenuItemモード切替え, "toolStripMenuItemモード切替え"); this.toolStripMenuItemモード切替え.Name = "toolStripMenuItemモード切替え"; this.toolStripMenuItemモード切替え.Click += new System.EventHandler(this.toolStripMenuItemモード切替え_Click); // // toolStripSeparator5 // resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5"); this.toolStripSeparator5.Name = "toolStripSeparator5"; // // toolStripMenuItem検索 // resources.ApplyResources(this.toolStripMenuItem検索, "toolStripMenuItem検索"); this.toolStripMenuItem検索.Name = "toolStripMenuItem検索"; this.toolStripMenuItem検索.Click += new System.EventHandler(this.toolStripMenuItem検索_Click); // // toolStripMenuItem表示 // resources.ApplyResources(this.toolStripMenuItem表示, "toolStripMenuItem表示"); this.toolStripMenuItem表示.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemガイド間隔}); this.toolStripMenuItem表示.Name = "toolStripMenuItem表示"; // // toolStripMenuItemガイド間隔 // resources.ApplyResources(this.toolStripMenuItemガイド間隔, "toolStripMenuItemガイド間隔"); this.toolStripMenuItemガイド間隔.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemガイド間隔4分, this.toolStripMenuItemガイド間隔6分, this.toolStripMenuItemガイド間隔8分, this.toolStripMenuItemガイド間隔12分, this.toolStripMenuItemガイド間隔16分, this.toolStripMenuItemガイド間隔24分, this.toolStripMenuItemガイド間隔32分, this.toolStripMenuItemガイド間隔36分, this.toolStripMenuItemガイド間隔48分, this.toolStripMenuItemガイド間隔64分, this.toolStripMenuItemガイド間隔128分, this.toolStripMenuItemガイド間隔フリー, this.toolStripSeparator6, this.toolStripMenuItemガイド間隔拡大, this.toolStripMenuItemガイド間隔縮小}); this.toolStripMenuItemガイド間隔.Name = "toolStripMenuItemガイド間隔"; // // toolStripMenuItemガイド間隔4分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔4分, "toolStripMenuItemガイド間隔4分"); this.toolStripMenuItemガイド間隔4分.Name = "toolStripMenuItemガイド間隔4分"; this.toolStripMenuItemガイド間隔4分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔4分_Click); // // toolStripMenuItemガイド間隔6分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔6分, "toolStripMenuItemガイド間隔6分"); this.toolStripMenuItemガイド間隔6分.Name = "toolStripMenuItemガイド間隔6分"; this.toolStripMenuItemガイド間隔6分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔6分_Click); // // toolStripMenuItemガイド間隔8分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔8分, "toolStripMenuItemガイド間隔8分"); this.toolStripMenuItemガイド間隔8分.Name = "toolStripMenuItemガイド間隔8分"; this.toolStripMenuItemガイド間隔8分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔8分_Click); // // toolStripMenuItemガイド間隔12分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔12分, "toolStripMenuItemガイド間隔12分"); this.toolStripMenuItemガイド間隔12分.Name = "toolStripMenuItemガイド間隔12分"; this.toolStripMenuItemガイド間隔12分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔12分_Click); // // toolStripMenuItemガイド間隔16分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔16分, "toolStripMenuItemガイド間隔16分"); this.toolStripMenuItemガイド間隔16分.Name = "toolStripMenuItemガイド間隔16分"; this.toolStripMenuItemガイド間隔16分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔16分_Click); // // toolStripMenuItemガイド間隔24分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔24分, "toolStripMenuItemガイド間隔24分"); this.toolStripMenuItemガイド間隔24分.Name = "toolStripMenuItemガイド間隔24分"; this.toolStripMenuItemガイド間隔24分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔24分_Click); // // toolStripMenuItemガイド間隔32分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔32分, "toolStripMenuItemガイド間隔32分"); this.toolStripMenuItemガイド間隔32分.Name = "toolStripMenuItemガイド間隔32分"; this.toolStripMenuItemガイド間隔32分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔32分_Click); // // toolStripMenuItemガイド間隔36分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔36分, "toolStripMenuItemガイド間隔36分"); this.toolStripMenuItemガイド間隔36分.Name = "toolStripMenuItemガイド間隔36分"; this.toolStripMenuItemガイド間隔36分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔36分_Click); // // toolStripMenuItemガイド間隔48分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔48分, "toolStripMenuItemガイド間隔48分"); this.toolStripMenuItemガイド間隔48分.Name = "toolStripMenuItemガイド間隔48分"; this.toolStripMenuItemガイド間隔48分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔48分_Click); // // toolStripMenuItemガイド間隔64分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔64分, "toolStripMenuItemガイド間隔64分"); this.toolStripMenuItemガイド間隔64分.Name = "toolStripMenuItemガイド間隔64分"; this.toolStripMenuItemガイド間隔64分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔64分_Click); // // toolStripMenuItemガイド間隔128分 // resources.ApplyResources(this.toolStripMenuItemガイド間隔128分, "toolStripMenuItemガイド間隔128分"); this.toolStripMenuItemガイド間隔128分.Name = "toolStripMenuItemガイド間隔128分"; this.toolStripMenuItemガイド間隔128分.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔128分_Click); // // toolStripMenuItemガイド間隔フリー // resources.ApplyResources(this.toolStripMenuItemガイド間隔フリー, "toolStripMenuItemガイド間隔フリー"); this.toolStripMenuItemガイド間隔フリー.Name = "toolStripMenuItemガイド間隔フリー"; this.toolStripMenuItemガイド間隔フリー.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔フリー_Click); // // toolStripSeparator6 // resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6"); this.toolStripSeparator6.Name = "toolStripSeparator6"; // // toolStripMenuItemガイド間隔拡大 // resources.ApplyResources(this.toolStripMenuItemガイド間隔拡大, "toolStripMenuItemガイド間隔拡大"); this.toolStripMenuItemガイド間隔拡大.Name = "toolStripMenuItemガイド間隔拡大"; this.toolStripMenuItemガイド間隔拡大.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔拡大_Click); // // toolStripMenuItemガイド間隔縮小 // resources.ApplyResources(this.toolStripMenuItemガイド間隔縮小, "toolStripMenuItemガイド間隔縮小"); this.toolStripMenuItemガイド間隔縮小.Name = "toolStripMenuItemガイド間隔縮小"; this.toolStripMenuItemガイド間隔縮小.Click += new System.EventHandler(this.toolStripMenuItemガイド間隔縮小_Click); // // toolStripMenuItem再生 // resources.ApplyResources(this.toolStripMenuItem再生, "toolStripMenuItem再生"); this.toolStripMenuItem再生.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem先頭から再生, this.toolStripMenuItem現在位置から再生, this.toolStripMenuItem現在位置からBGMのみ再生, this.toolStripMenuItem再生停止}); this.toolStripMenuItem再生.Name = "toolStripMenuItem再生"; // // toolStripMenuItem先頭から再生 // resources.ApplyResources(this.toolStripMenuItem先頭から再生, "toolStripMenuItem先頭から再生"); this.toolStripMenuItem先頭から再生.Name = "toolStripMenuItem先頭から再生"; this.toolStripMenuItem先頭から再生.Click += new System.EventHandler(this.toolStripMenuItem先頭から再生_Click); // // toolStripMenuItem現在位置から再生 // resources.ApplyResources(this.toolStripMenuItem現在位置から再生, "toolStripMenuItem現在位置から再生"); this.toolStripMenuItem現在位置から再生.Name = "toolStripMenuItem現在位置から再生"; this.toolStripMenuItem現在位置から再生.Click += new System.EventHandler(this.toolStripMenuItem現在位置から再生_Click); // // toolStripMenuItem現在位置からBGMのみ再生 // resources.ApplyResources(this.toolStripMenuItem現在位置からBGMのみ再生, "toolStripMenuItem現在位置からBGMのみ再生"); this.toolStripMenuItem現在位置からBGMのみ再生.Name = "toolStripMenuItem現在位置からBGMのみ再生"; this.toolStripMenuItem現在位置からBGMのみ再生.Click += new System.EventHandler(this.toolStripMenuItem現在位置からBGMのみ再生_Click); // // toolStripMenuItem再生停止 // resources.ApplyResources(this.toolStripMenuItem再生停止, "toolStripMenuItem再生停止"); this.toolStripMenuItem再生停止.Name = "toolStripMenuItem再生停止"; this.toolStripMenuItem再生停止.Click += new System.EventHandler(this.toolStripMenuItem再生停止_Click); // // toolStripMenuItemツール // resources.ApplyResources(this.toolStripMenuItemツール, "toolStripMenuItemツール"); this.toolStripMenuItemツール.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemオプション}); this.toolStripMenuItemツール.Name = "toolStripMenuItemツール"; // // toolStripMenuItemオプション // resources.ApplyResources(this.toolStripMenuItemオプション, "toolStripMenuItemオプション"); this.toolStripMenuItemオプション.Name = "toolStripMenuItemオプション"; this.toolStripMenuItemオプション.Click += new System.EventHandler(this.toolStripMenuItemオプション_Click); // // toolStripMenuItemヘルプ // resources.ApplyResources(this.toolStripMenuItemヘルプ, "toolStripMenuItemヘルプ"); this.toolStripMenuItemヘルプ.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemバージョン}); this.toolStripMenuItemヘルプ.Name = "toolStripMenuItemヘルプ"; // // toolStripMenuItemバージョン // resources.ApplyResources(this.toolStripMenuItemバージョン, "toolStripMenuItemバージョン"); this.toolStripMenuItemバージョン.Name = "toolStripMenuItemバージョン"; this.toolStripMenuItemバージョン.Click += new System.EventHandler(this.toolStripMenuItemバージョン_Click); // // toolStripツールバー // resources.ApplyResources(this.toolStripツールバー, "toolStripツールバー"); this.toolStripツールバー.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton新規作成, this.toolStripButton開く, this.toolStripButton上書き保存, this.toolStripSeparator7, this.toolStripButton切り取り, this.toolStripButtonコピー, this.toolStripButton貼り付け, this.toolStripButton削除, this.toolStripSeparator8, this.toolStripButton元に戻す, this.toolStripButtonやり直す, this.toolStripSeparator9, this.toolStripComboBox譜面拡大率, this.toolStripComboBoxガイド間隔, this.toolStripButton選択モード, this.toolStripButton編集モード, this.toolStripSeparator10, this.toolStripButton先頭から再生, this.toolStripButton現在位置から再生, this.toolStripButton現在位置からBGMのみ再生, this.toolStripButton再生停止, this.toolStripComboBox再生速度, this.toolStripSeparator11, this.toolStripButton音量Down, this.toolStripLabel音量, this.toolStripButton音量UP, this.toolStripSeparator15}); this.toolStripツールバー.Name = "toolStripツールバー"; this.toolTipメインフォーム.SetToolTip(this.toolStripツールバー, resources.GetString("toolStripツールバー.ToolTip")); // // toolStripButton新規作成 // resources.ApplyResources(this.toolStripButton新規作成, "toolStripButton新規作成"); this.toolStripButton新規作成.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton新規作成.Name = "toolStripButton新規作成"; this.toolStripButton新規作成.Click += new System.EventHandler(this.toolStripButton新規作成_Click); // // toolStripButton開く // resources.ApplyResources(this.toolStripButton開く, "toolStripButton開く"); this.toolStripButton開く.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton開く.Name = "toolStripButton開く"; this.toolStripButton開く.Click += new System.EventHandler(this.toolStripButton開く_Click); // // toolStripButton上書き保存 // resources.ApplyResources(this.toolStripButton上書き保存, "toolStripButton上書き保存"); this.toolStripButton上書き保存.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton上書き保存.Name = "toolStripButton上書き保存"; this.toolStripButton上書き保存.Click += new System.EventHandler(this.toolStripButton上書き保存_Click); // // toolStripSeparator7 // resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7"); this.toolStripSeparator7.Name = "toolStripSeparator7"; // // toolStripButton切り取り // resources.ApplyResources(this.toolStripButton切り取り, "toolStripButton切り取り"); this.toolStripButton切り取り.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton切り取り.Name = "toolStripButton切り取り"; this.toolStripButton切り取り.Click += new System.EventHandler(this.toolStripButton切り取り_Click); // // toolStripButtonコピー // resources.ApplyResources(this.toolStripButtonコピー, "toolStripButtonコピー"); this.toolStripButtonコピー.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonコピー.Name = "toolStripButtonコピー"; this.toolStripButtonコピー.Click += new System.EventHandler(this.toolStripButtonコピー_Click); // // toolStripButton貼り付け // resources.ApplyResources(this.toolStripButton貼り付け, "toolStripButton貼り付け"); this.toolStripButton貼り付け.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton貼り付け.Name = "toolStripButton貼り付け"; this.toolStripButton貼り付け.Click += new System.EventHandler(this.toolStripButton貼り付け_Click); // // toolStripButton削除 // resources.ApplyResources(this.toolStripButton削除, "toolStripButton削除"); this.toolStripButton削除.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton削除.Name = "toolStripButton削除"; this.toolStripButton削除.Click += new System.EventHandler(this.toolStripButton削除_Click); // // toolStripSeparator8 // resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8"); this.toolStripSeparator8.Name = "toolStripSeparator8"; // // toolStripButton元に戻す // resources.ApplyResources(this.toolStripButton元に戻す, "toolStripButton元に戻す"); this.toolStripButton元に戻す.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton元に戻す.Name = "toolStripButton元に戻す"; this.toolStripButton元に戻す.Click += new System.EventHandler(this.toolStripButton元に戻す_Click); // // toolStripButtonやり直す // resources.ApplyResources(this.toolStripButtonやり直す, "toolStripButtonやり直す"); this.toolStripButtonやり直す.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonやり直す.Name = "toolStripButtonやり直す"; this.toolStripButtonやり直す.Click += new System.EventHandler(this.toolStripButtonやり直す_Click); // // toolStripSeparator9 // resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9"); this.toolStripSeparator9.Name = "toolStripSeparator9"; // // toolStripComboBox譜面拡大率 // resources.ApplyResources(this.toolStripComboBox譜面拡大率, "toolStripComboBox譜面拡大率"); this.toolStripComboBox譜面拡大率.DropDownHeight = 200; this.toolStripComboBox譜面拡大率.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBox譜面拡大率.DropDownWidth = 75; this.toolStripComboBox譜面拡大率.Items.AddRange(new object[] { resources.GetString("toolStripComboBox譜面拡大率.Items"), resources.GetString("toolStripComboBox譜面拡大率.Items1"), resources.GetString("toolStripComboBox譜面拡大率.Items2"), resources.GetString("toolStripComboBox譜面拡大率.Items3"), resources.GetString("toolStripComboBox譜面拡大率.Items4"), resources.GetString("toolStripComboBox譜面拡大率.Items5"), resources.GetString("toolStripComboBox譜面拡大率.Items6"), resources.GetString("toolStripComboBox譜面拡大率.Items7"), resources.GetString("toolStripComboBox譜面拡大率.Items8"), resources.GetString("toolStripComboBox譜面拡大率.Items9"), resources.GetString("toolStripComboBox譜面拡大率.Items10"), resources.GetString("toolStripComboBox譜面拡大率.Items11"), resources.GetString("toolStripComboBox譜面拡大率.Items12")}); this.toolStripComboBox譜面拡大率.Name = "toolStripComboBox譜面拡大率"; this.toolStripComboBox譜面拡大率.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox譜面拡大率_SelectedIndexChanged); // // toolStripComboBoxガイド間隔 // resources.ApplyResources(this.toolStripComboBoxガイド間隔, "toolStripComboBoxガイド間隔"); this.toolStripComboBoxガイド間隔.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBoxガイド間隔.Items.AddRange(new object[] { resources.GetString("toolStripComboBoxガイド間隔.Items"), resources.GetString("toolStripComboBoxガイド間隔.Items1"), resources.GetString("toolStripComboBoxガイド間隔.Items2"), resources.GetString("toolStripComboBoxガイド間隔.Items3"), resources.GetString("toolStripComboBoxガイド間隔.Items4"), resources.GetString("toolStripComboBoxガイド間隔.Items5"), resources.GetString("toolStripComboBoxガイド間隔.Items6"), resources.GetString("toolStripComboBoxガイド間隔.Items7"), resources.GetString("toolStripComboBoxガイド間隔.Items8"), resources.GetString("toolStripComboBoxガイド間隔.Items9"), resources.GetString("toolStripComboBoxガイド間隔.Items10"), resources.GetString("toolStripComboBoxガイド間隔.Items11")}); this.toolStripComboBoxガイド間隔.Name = "toolStripComboBoxガイド間隔"; this.toolStripComboBoxガイド間隔.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBoxガイド間隔_SelectedIndexChanged); // // toolStripButton選択モード // resources.ApplyResources(this.toolStripButton選択モード, "toolStripButton選択モード"); this.toolStripButton選択モード.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton選択モード.Name = "toolStripButton選択モード"; this.toolStripButton選択モード.Click += new System.EventHandler(this.toolStripButton選択モード_Click); // // toolStripButton編集モード // resources.ApplyResources(this.toolStripButton編集モード, "toolStripButton編集モード"); this.toolStripButton編集モード.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton編集モード.Name = "toolStripButton編集モード"; this.toolStripButton編集モード.Click += new System.EventHandler(this.toolStripButton編集モード_Click); // // toolStripSeparator10 // resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10"); this.toolStripSeparator10.Name = "toolStripSeparator10"; // // toolStripButton先頭から再生 // resources.ApplyResources(this.toolStripButton先頭から再生, "toolStripButton先頭から再生"); this.toolStripButton先頭から再生.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton先頭から再生.Name = "toolStripButton先頭から再生"; this.toolStripButton先頭から再生.Click += new System.EventHandler(this.toolStripButton先頭から再生_Click); // // toolStripButton現在位置から再生 // resources.ApplyResources(this.toolStripButton現在位置から再生, "toolStripButton現在位置から再生"); this.toolStripButton現在位置から再生.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton現在位置から再生.Name = "toolStripButton現在位置から再生"; this.toolStripButton現在位置から再生.Click += new System.EventHandler(this.toolStripButton現在位置から再生_Click); // // toolStripButton現在位置からBGMのみ再生 // resources.ApplyResources(this.toolStripButton現在位置からBGMのみ再生, "toolStripButton現在位置からBGMのみ再生"); this.toolStripButton現在位置からBGMのみ再生.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton現在位置からBGMのみ再生.Name = "toolStripButton現在位置からBGMのみ再生"; this.toolStripButton現在位置からBGMのみ再生.Click += new System.EventHandler(this.toolStripButton現在位置からBGMのみ再生_Click); // // toolStripButton再生停止 // resources.ApplyResources(this.toolStripButton再生停止, "toolStripButton再生停止"); this.toolStripButton再生停止.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton再生停止.Name = "toolStripButton再生停止"; this.toolStripButton再生停止.Click += new System.EventHandler(this.toolStripButton再生停止_Click); // // toolStripComboBox再生速度 // resources.ApplyResources(this.toolStripComboBox再生速度, "toolStripComboBox再生速度"); this.toolStripComboBox再生速度.DropDownHeight = 150; this.toolStripComboBox再生速度.DropDownWidth = 35; this.toolStripComboBox再生速度.Items.AddRange(new object[] { resources.GetString("toolStripComboBox再生速度.Items"), resources.GetString("toolStripComboBox再生速度.Items1"), resources.GetString("toolStripComboBox再生速度.Items2"), resources.GetString("toolStripComboBox再生速度.Items3"), resources.GetString("toolStripComboBox再生速度.Items4"), resources.GetString("toolStripComboBox再生速度.Items5"), resources.GetString("toolStripComboBox再生速度.Items6"), resources.GetString("toolStripComboBox再生速度.Items7"), resources.GetString("toolStripComboBox再生速度.Items8"), resources.GetString("toolStripComboBox再生速度.Items9"), resources.GetString("toolStripComboBox再生速度.Items10"), resources.GetString("toolStripComboBox再生速度.Items11"), resources.GetString("toolStripComboBox再生速度.Items12"), resources.GetString("toolStripComboBox再生速度.Items13"), resources.GetString("toolStripComboBox再生速度.Items14")}); this.toolStripComboBox再生速度.Name = "toolStripComboBox再生速度"; this.toolStripComboBox再生速度.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox再生速度_SelectedIndexChanged); // // toolStripSeparator11 // resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11"); this.toolStripSeparator11.Name = "toolStripSeparator11"; // // toolStripButton音量Down // resources.ApplyResources(this.toolStripButton音量Down, "toolStripButton音量Down"); this.toolStripButton音量Down.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton音量Down.Name = "toolStripButton音量Down"; this.toolStripButton音量Down.Click += new System.EventHandler(this.toolStripButton音量Down_Click); // // toolStripLabel音量 // resources.ApplyResources(this.toolStripLabel音量, "toolStripLabel音量"); this.toolStripLabel音量.Name = "toolStripLabel音量"; // // toolStripButton音量UP // resources.ApplyResources(this.toolStripButton音量UP, "toolStripButton音量UP"); this.toolStripButton音量UP.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton音量UP.Name = "toolStripButton音量UP"; this.toolStripButton音量UP.Click += new System.EventHandler(this.toolStripButton音量UP_Click); // // toolStripSeparator15 // resources.ApplyResources(this.toolStripSeparator15, "toolStripSeparator15"); this.toolStripSeparator15.Name = "toolStripSeparator15"; // // vScrollBar譜面用垂直スクロールバー // resources.ApplyResources(this.vScrollBar譜面用垂直スクロールバー, "vScrollBar譜面用垂直スクロールバー"); this.vScrollBar譜面用垂直スクロールバー.Name = "vScrollBar譜面用垂直スクロールバー"; this.toolTipメインフォーム.SetToolTip(this.vScrollBar譜面用垂直スクロールバー, resources.GetString("vScrollBar譜面用垂直スクロールバー.ToolTip")); this.vScrollBar譜面用垂直スクロールバー.ValueChanged += new System.EventHandler(this.vScrollBar譜面用垂直スクロールバー_ValueChanged); // // contextMenuStrip譜面右メニュー // resources.ApplyResources(this.contextMenuStrip譜面右メニュー, "contextMenuStrip譜面右メニュー"); this.contextMenuStrip譜面右メニュー.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem選択チップの切り取り, this.toolStripMenuItem選択チップのコピー, this.toolStripMenuItem選択チップの貼り付け, this.toolStripMenuItem選択チップの削除, this.toolStripSeparator12, this.toolStripMenuItemすべてのチップの選択, this.toolStripSeparator13, this.toolStripMenuItem小節長変更, this.toolStripSeparator14, this.toolStripMenuItem小節の挿入, this.toolStripMenuItem小節の削除, this.toolStripSeparator16, this.toolStripMenuItem音量指定}); this.contextMenuStrip譜面右メニュー.Name = "contextMenuStrip譜面右メニュー"; this.toolTipメインフォーム.SetToolTip(this.contextMenuStrip譜面右メニュー, resources.GetString("contextMenuStrip譜面右メニュー.ToolTip")); // // toolStripMenuItem選択チップの切り取り // resources.ApplyResources(this.toolStripMenuItem選択チップの切り取り, "toolStripMenuItem選択チップの切り取り"); this.toolStripMenuItem選択チップの切り取り.Name = "toolStripMenuItem選択チップの切り取り"; this.toolStripMenuItem選択チップの切り取り.Click += new System.EventHandler(this.toolStripMenuItem選択チップの切り取り_Click); // // toolStripMenuItem選択チップのコピー // resources.ApplyResources(this.toolStripMenuItem選択チップのコピー, "toolStripMenuItem選択チップのコピー"); this.toolStripMenuItem選択チップのコピー.Name = "toolStripMenuItem選択チップのコピー"; this.toolStripMenuItem選択チップのコピー.Click += new System.EventHandler(this.toolStripMenuItem選択チップのコピー_Click); // // toolStripMenuItem選択チップの貼り付け // resources.ApplyResources(this.toolStripMenuItem選択チップの貼り付け, "toolStripMenuItem選択チップの貼り付け"); this.toolStripMenuItem選択チップの貼り付け.Name = "toolStripMenuItem選択チップの貼り付け"; this.toolStripMenuItem選択チップの貼り付け.Click += new System.EventHandler(this.toolStripMenuItem選択チップの貼り付け_Click); // // toolStripMenuItem選択チップの削除 // resources.ApplyResources(this.toolStripMenuItem選択チップの削除, "toolStripMenuItem選択チップの削除"); this.toolStripMenuItem選択チップの削除.Name = "toolStripMenuItem選択チップの削除"; this.toolStripMenuItem選択チップの削除.Click += new System.EventHandler(this.toolStripMenuItem選択チップの削除_Click); // // toolStripSeparator12 // resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12"); this.toolStripSeparator12.Name = "toolStripSeparator12"; // // toolStripMenuItemすべてのチップの選択 // resources.ApplyResources(this.toolStripMenuItemすべてのチップの選択, "toolStripMenuItemすべてのチップの選択"); this.toolStripMenuItemすべてのチップの選択.Name = "toolStripMenuItemすべてのチップの選択"; this.toolStripMenuItemすべてのチップの選択.Click += new System.EventHandler(this.toolStripMenuItemすべてのチップの選択_Click); // // toolStripSeparator13 // resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13"); this.toolStripSeparator13.Name = "toolStripSeparator13"; // // toolStripMenuItem小節長変更 // resources.ApplyResources(this.toolStripMenuItem小節長変更, "toolStripMenuItem小節長変更"); this.toolStripMenuItem小節長変更.Name = "toolStripMenuItem小節長変更"; this.toolStripMenuItem小節長変更.Click += new System.EventHandler(this.toolStripMenuItem小節長変更_Click); // // toolStripSeparator14 // resources.ApplyResources(this.toolStripSeparator14, "toolStripSeparator14"); this.toolStripSeparator14.Name = "toolStripSeparator14"; // // toolStripMenuItem小節の挿入 // resources.ApplyResources(this.toolStripMenuItem小節の挿入, "toolStripMenuItem小節の挿入"); this.toolStripMenuItem小節の挿入.Name = "toolStripMenuItem小節の挿入"; this.toolStripMenuItem小節の挿入.Click += new System.EventHandler(this.toolStripMenuItem小節の挿入_Click); // // toolStripMenuItem小節の削除 // resources.ApplyResources(this.toolStripMenuItem小節の削除, "toolStripMenuItem小節の削除"); this.toolStripMenuItem小節の削除.Name = "toolStripMenuItem小節の削除"; this.toolStripMenuItem小節の削除.Click += new System.EventHandler(this.toolStripMenuItem小節の削除_Click); // // toolStripSeparator16 // resources.ApplyResources(this.toolStripSeparator16, "toolStripSeparator16"); this.toolStripSeparator16.Name = "toolStripSeparator16"; // // toolStripMenuItem音量指定 // resources.ApplyResources(this.toolStripMenuItem音量指定, "toolStripMenuItem音量指定"); this.toolStripMenuItem音量指定.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem音量1, this.toolStripMenuItem音量2, this.toolStripMenuItem音量3, this.toolStripMenuItem音量4, this.toolStripMenuItem音量5, this.toolStripMenuItem音量6, this.toolStripMenuItem音量7, this.toolStripMenuItem音量8}); this.toolStripMenuItem音量指定.Name = "toolStripMenuItem音量指定"; // // toolStripMenuItem音量1 // resources.ApplyResources(this.toolStripMenuItem音量1, "toolStripMenuItem音量1"); this.toolStripMenuItem音量1.Name = "toolStripMenuItem音量1"; this.toolStripMenuItem音量1.Click += new System.EventHandler(this.toolStripMenuItem音量1_Click); // // toolStripMenuItem音量2 // resources.ApplyResources(this.toolStripMenuItem音量2, "toolStripMenuItem音量2"); this.toolStripMenuItem音量2.Name = "toolStripMenuItem音量2"; this.toolStripMenuItem音量2.Click += new System.EventHandler(this.toolStripMenuItem音量2_Click); // // toolStripMenuItem音量3 // resources.ApplyResources(this.toolStripMenuItem音量3, "toolStripMenuItem音量3"); this.toolStripMenuItem音量3.Name = "toolStripMenuItem音量3"; this.toolStripMenuItem音量3.Click += new System.EventHandler(this.toolStripMenuItem音量3_Click); // // toolStripMenuItem音量4 // resources.ApplyResources(this.toolStripMenuItem音量4, "toolStripMenuItem音量4"); this.toolStripMenuItem音量4.Name = "toolStripMenuItem音量4"; this.toolStripMenuItem音量4.Click += new System.EventHandler(this.toolStripMenuItem音量4_Click); // // toolStripMenuItem音量5 // resources.ApplyResources(this.toolStripMenuItem音量5, "toolStripMenuItem音量5"); this.toolStripMenuItem音量5.Name = "toolStripMenuItem音量5"; this.toolStripMenuItem音量5.Click += new System.EventHandler(this.toolStripMenuItem音量5_Click); // // toolStripMenuItem音量6 // resources.ApplyResources(this.toolStripMenuItem音量6, "toolStripMenuItem音量6"); this.toolStripMenuItem音量6.Name = "toolStripMenuItem音量6"; this.toolStripMenuItem音量6.Click += new System.EventHandler(this.toolStripMenuItem音量6_Click); // // toolStripMenuItem音量7 // resources.ApplyResources(this.toolStripMenuItem音量7, "toolStripMenuItem音量7"); this.toolStripMenuItem音量7.Name = "toolStripMenuItem音量7"; this.toolStripMenuItem音量7.Click += new System.EventHandler(this.toolStripMenuItem音量7_Click); // // toolStripMenuItem音量8 // resources.ApplyResources(this.toolStripMenuItem音量8, "toolStripMenuItem音量8"); this.toolStripMenuItem音量8.Name = "toolStripMenuItem音量8"; this.toolStripMenuItem音量8.Click += new System.EventHandler(this.toolStripMenuItem音量8_Click); // // メインフォーム // resources.ApplyResources(this, "$this"); this.AllowDrop = true; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer分割パネルコンテナ); this.Controls.Add(this.vScrollBar譜面用垂直スクロールバー); this.Controls.Add(this.toolStripツールバー); this.Controls.Add(this.statusStripステータスバー); this.Controls.Add(this.menuStripメニューバー); this.MainMenuStrip = this.menuStripメニューバー; this.Name = "メインフォーム"; this.toolTipメインフォーム.SetToolTip(this, resources.GetString("$this.ToolTip")); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.メインフォーム_FormClosing); this.ResizeEnd += new System.EventHandler(this.メインフォーム_ResizeEnd); this.DragDrop += new System.Windows.Forms.DragEventHandler(this.メインフォーム_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.メインフォーム_DragEnter); this.splitContainer分割パネルコンテナ.Panel1.ResumeLayout(false); this.splitContainer分割パネルコンテナ.Panel2.ResumeLayout(false); this.splitContainer分割パネルコンテナ.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer分割パネルコンテナ)).EndInit(); this.splitContainer分割パネルコンテナ.ResumeLayout(false); this.tabControl情報タブコンテナ.ResumeLayout(false); this.tabPage基本情報.ResumeLayout(false); this.tabPage基本情報.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxプレビュー画像)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackBarLevel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownメモ用小節番号)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox譜面パネル)).EndInit(); this.menuStripメニューバー.ResumeLayout(false); this.menuStripメニューバー.PerformLayout(); this.toolStripツールバー.ResumeLayout(false); this.toolStripツールバー.PerformLayout(); this.contextMenuStrip譜面右メニュー.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.StatusStrip statusStripステータスバー; private System.Windows.Forms.MenuStrip menuStripメニューバー; private System.Windows.Forms.ToolStrip toolStripツールバー; private System.Windows.Forms.VScrollBar vScrollBar譜面用垂直スクロールバー; private System.Windows.Forms.SplitContainer splitContainer分割パネルコンテナ; private System.Windows.Forms.PictureBox pictureBox譜面パネル; private System.Windows.Forms.TabControl tabControl情報タブコンテナ; private System.Windows.Forms.TabPage tabPage基本情報; private System.Windows.Forms.TextBox textBox曲名; private System.Windows.Forms.Label label説明; private System.Windows.Forms.TextBox textBox説明; private System.Windows.Forms.Label label曲名; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemファイル; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem新規作成; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem開く; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem上書き保存; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem名前を付けて保存; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem終了; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem編集; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem元に戻す; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemやり直す; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem切り取り; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemコピー; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem貼り付け; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem削除; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemすべて選択; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem選択モード; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem編集モード; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemモード切替え; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem検索; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem表示; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔4分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔8分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔12分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔16分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔24分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔32分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔48分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔64分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔128分; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔フリー; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔拡大; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔縮小; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem再生; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem先頭から再生; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem現在位置から再生; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem現在位置からBGMのみ再生; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem再生停止; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemツール; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemオプション; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemヘルプ; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemバージョン; private System.Windows.Forms.ToolStripButton toolStripButton新規作成; private System.Windows.Forms.ToolTip toolTipメインフォーム; private System.Windows.Forms.ToolStripButton toolStripButton開く; private System.Windows.Forms.ToolStripButton toolStripButton上書き保存; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripButton toolStripButton切り取り; private System.Windows.Forms.ToolStripButton toolStripButtonコピー; private System.Windows.Forms.ToolStripButton toolStripButton貼り付け; private System.Windows.Forms.ToolStripButton toolStripButton削除; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripButton toolStripButton元に戻す; private System.Windows.Forms.ToolStripButton toolStripButtonやり直す; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripComboBox toolStripComboBox譜面拡大率; private System.Windows.Forms.ToolStripComboBox toolStripComboBoxガイド間隔; private System.Windows.Forms.ToolStripButton toolStripButton選択モード; private System.Windows.Forms.ToolStripButton toolStripButton編集モード; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private System.Windows.Forms.ToolStripButton toolStripButton先頭から再生; private System.Windows.Forms.ToolStripButton toolStripButton現在位置から再生; private System.Windows.Forms.ToolStripButton toolStripButton現在位置からBGMのみ再生; private System.Windows.Forms.ToolStripButton toolStripButton再生停止; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; private System.Windows.Forms.Label labelBGV; private System.Windows.Forms.TextBox textBoxBGV; private System.Windows.Forms.ContextMenuStrip contextMenuStrip譜面右メニュー; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem選択チップの切り取り; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem選択チップのコピー; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem選択チップの貼り付け; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem選択チップの削除; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemすべてのチップの選択; private System.Windows.Forms.ToolStripSeparator toolStripSeparator13; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem小節長変更; private System.Windows.Forms.ToolStripSeparator toolStripSeparator14; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem小節の挿入; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem小節の削除; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔6分; private System.Windows.Forms.Label labelCurrentChipType; private System.Windows.Forms.Label label現在のチップ種別; private System.Windows.Forms.NumericUpDown numericUpDownメモ用小節番号; private System.Windows.Forms.Label labelメモ小節単位; private System.Windows.Forms.TextBox textBoxメモ; private System.Windows.Forms.ToolStripButton toolStripButton音量Down; private System.Windows.Forms.ToolStripButton toolStripButton音量UP; private System.Windows.Forms.ToolStripLabel toolStripLabel音量; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemガイド間隔36分; private System.Windows.Forms.TextBox textBoxLevel; private System.Windows.Forms.TrackBar trackBarLevel; private System.Windows.Forms.Label labelLevel; private System.Windows.Forms.Button buttonBGV参照; private System.Windows.Forms.Button buttonBGM参照; private System.Windows.Forms.Label labelBGM; private System.Windows.Forms.TextBox textBoxBGM; private System.Windows.Forms.Label labelアーティスト名; private System.Windows.Forms.TextBox textBoxアーティスト名; private System.Windows.Forms.Label labelメモ用小節番号; private System.Windows.Forms.TextBox textBoxプレビュー音声; private System.Windows.Forms.Label labelプレビュー音声; private System.Windows.Forms.Button buttonプレビューサウンド参照; private System.Windows.Forms.Label labelプレビュー画像; private System.Windows.Forms.Button buttonプレビュー画像参照; private System.Windows.Forms.TextBox textBoxプレビュー画像; private System.Windows.Forms.PictureBox pictureBoxプレビュー画像; private System.Windows.Forms.ToolStripComboBox toolStripComboBox再生速度; private System.Windows.Forms.ToolStripSeparator toolStripSeparator16; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量指定; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量2; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量3; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量5; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量6; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量7; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem音量8; } }
DTXMania/DTXMania2
<|start_filename|>Assets/_Project/Editor/BuildTools.cs<|end_filename|> /** * BuildTools.cs * Created by: <NAME> * Created on: 30/14/17 (dd/mm/yy) */ using UnityEditor; using UnityEngine; using Process = System.Diagnostics.Process; public static class BuildTools { [MenuItem("Tools/Run Server")] public static void RunServerMenu() { Process p = new Process(); p.StartInfo.FileName = GetFilePath("serverPath"); p.StartInfo.Arguments = "servermode"; p.Start(); } [MenuItem("Tools/Run Game")] public static void RunGameMenu() { Process p = new Process(); p.StartInfo.FileName = GetFilePath("gamePath"); p.StartInfo.Arguments = "gamemode"; p.Start(); } [MenuItem("Tools/Quick Build")] public static void QuickBuildMenu() { BuildPlayerOptions opts = new BuildPlayerOptions { options = BuildOptions.Development, locationPathName = GetSaveFile("buildPath"), target = BuildTarget.StandaloneWindows }; BuildPipeline.BuildPlayer(opts); } [MenuItem("Tools/Clear Editor Prefs", false, 22)] public static void ClearPrefsMenu() { EditorPrefs.DeleteKey("gamePath"); EditorPrefs.DeleteKey("serverPath"); EditorPrefs.DeleteKey("buildPath"); } public static string GetFilePath(string itemName) { var path = EditorPrefs.GetString(itemName); if (string.IsNullOrEmpty(path)) path = EditorUtility.OpenFilePanel("Select game executable", "C:/Users/Joao Borks/Desktop", "exe"); if (string.IsNullOrEmpty(path)) throw new System.Exception("Operation cancelled"); else EditorPrefs.SetString(itemName, path); return path; } public static string GetSaveFile(string itemName) { var path = EditorPrefs.GetString(itemName); if (string.IsNullOrEmpty(path)) path = EditorUtility.SaveFilePanel("Select folder to save", "C:/Users/Joao Borks/Desktop", "newTest", "exe"); if (string.IsNullOrEmpty(path)) throw new System.Exception("Operation cancelled"); else EditorPrefs.SetString(itemName, path); return path; } } <|start_filename|>Assets/_Project/Scripts/Networking/AuthCharPredictor.cs<|end_filename|> /** * AuthCharPredictor.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using System.Collections.Generic; using System.Linq; public class AuthCharPredictor : MonoBehaviour, IAuthCharStateHandler { LinkedList<CharacterInput> pendingInputs; AuthoritativeCharacter character; CharacterState predictedState; private CharacterState lastServerState = CharacterState.Zero; void Awake() { pendingInputs = new LinkedList<CharacterInput>(); character = GetComponent<AuthoritativeCharacter>(); } public void AddInput(CharacterInput input) { pendingInputs.AddLast(input); ApplyInput(input); character.SyncState(predictedState); } public void OnStateChange(CharacterState newState) { if (newState.timestamp <= lastServerState.timestamp) return; while (pendingInputs.Count > 0 && pendingInputs.First().inputNum <= newState.moveNum) { pendingInputs.RemoveFirst(); } predictedState = newState; lastServerState = newState; UpdatePredictedState(); } void UpdatePredictedState() { foreach (CharacterInput input in pendingInputs) { ApplyInput(input); } character.SyncState(predictedState); } void ApplyInput(CharacterInput input) { predictedState = CharacterState.Move(predictedState, input, character.Speed, 0); } } <|start_filename|>Assets/_Project/Scripts/Networking/AuthCharObserver.cs<|end_filename|> /** * AuthCharObserver.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using System.Collections.Generic; public class AuthCharObserver : MonoBehaviour, IAuthCharStateHandler { LinkedList<CharacterState> stateBuffer; AuthoritativeCharacter character; int clientTick = 0; void Awake() { character = GetComponent<AuthoritativeCharacter>(); stateBuffer = new LinkedList<CharacterState>(); SetObservedState(character.state); AddState(character.state); } void Update() { int pastTick = clientTick - character.interpolationDelay; var fromNode = stateBuffer.First; var toNode = fromNode.Next; while (toNode != null && toNode.Value.timestamp <= pastTick) { fromNode = toNode; toNode = fromNode.Next; stateBuffer.RemoveFirst(); } SetObservedState(toNode != null ? CharacterState.Interpolate(fromNode.Value, toNode.Value, pastTick) : fromNode.Value); } void FixedUpdate() { clientTick++; } public void OnStateChange(CharacterState newState) { clientTick = newState.timestamp; AddState(newState); } void AddState(CharacterState state) { if (stateBuffer.Count > 0 && stateBuffer.Last.Value.timestamp > state.timestamp) { return; } stateBuffer.AddLast(state); } void SetObservedState(CharacterState newState) { character.SyncState(newState); } } <|start_filename|>Assets/_Project/Scripts/Structs/CompressedInput.cs<|end_filename|> /** * CompressedInput.cs * Created by: <NAME> * Created on: 01/05/17 (dd/mm/yy) */ using UnityEngine; [System.Serializable] public struct CompressedInput { public sbyte x; public sbyte y; public CompressedInput(Vector2 inputVector) { x = (sbyte)Mathf.Clamp(inputVector.x * sbyte.MaxValue, sbyte.MinValue, sbyte.MaxValue); y = (sbyte)Mathf.Clamp(inputVector.y * sbyte.MaxValue, sbyte.MinValue, sbyte.MaxValue); } public Vector2 ToVector2 { get { return new Vector2((float)x / sbyte.MaxValue, (float)y / sbyte.MaxValue); } } } <|start_filename|>Assets/_Project/Scripts/Structs/CharacterInput.cs<|end_filename|> using UnityEngine; public struct CharacterInput { public CharacterInput(Vector2 _dir, int _inputNum) { dir = _dir; inputNum = _inputNum; } public Vector2 dir; public int inputNum; } <|start_filename|>Assets/_Project/Editor/Tools/ScriptKeywordProcessor.cs<|end_filename|> /** * ScriptKeywordProcessor.cs * Created by: <NAME> [<EMAIL>] * Created on: 03/04/17 (dd/mm/yy) */ // Tips from https://forum.unity3d.com/threads/c-script-template-how-to-make-custom-changes.273191/ using UnityEngine; using UnityEditor; internal sealed class ScriptKeywordProcessor : UnityEditor.AssetModificationProcessor { public static void OnWillCreateAsset(string path) { path = path.Replace(".meta", ""); int index = path.LastIndexOf("."); if (index < 0) return; string file = path.Substring(index); if (file != ".cs" && file != ".js") return; index = Application.dataPath.LastIndexOf("Assets"); path = Application.dataPath.Substring(0, index) + path; if (!System.IO.File.Exists(path)) return; string fileContent = System.IO.File.ReadAllText(path); string author = System.Security.Principal.WindowsIdentity.GetCurrent().Name; author = author.Contains("\\") ? author.Split('\\')[1] : author; fileContent = fileContent.Replace("#AUTHOR#", System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1]); fileContent = fileContent.Replace("#CREATIONDATE#", System.DateTime.Now.ToString("dd/MM/yy")); System.IO.File.WriteAllText(path, fileContent); AssetDatabase.Refresh(); } } <|start_filename|>Assets/_Project/Scripts/Utilities/LatencyMeasurer.cs<|end_filename|> /** * LatencyMeasurer.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class LatencyMeasurer : MonoBehaviour { public Gradient valueGradient; [Range(200, 500)] public int badLatency = 300; Text textValue; void Start() { textValue = GetComponent<Text>(); } void Update() { var ping = -1; if (NetworkManager.singleton.client != null) ping = NetworkManager.singleton.client.GetRTT(); if (ping >= 0) { textValue.text = ping.ToString(); textValue.color = valueGradient.Evaluate(ping / badLatency); } else { textValue.text = "Off"; textValue.color = valueGradient.Evaluate(1); } } } <|start_filename|>Assets/_Project/Scripts/Interfaces/IAuthCharStateHandler.cs<|end_filename|> /** * IAuthCharStateHandler.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ public interface IAuthCharStateHandler { void OnStateChange(CharacterState newState); } <|start_filename|>Assets/_Project/Scripts/Networking/AuthCharServer.cs<|end_filename|> /** * AuthCharServer.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using System.Collections.Generic; using System.Linq; public class AuthCharServer : MonoBehaviour { Queue<CharacterInput> inputBuffer; AuthoritativeCharacter character; int movesMade; int serverTick; CharacterController charCtrl; void Awake() { inputBuffer = new Queue<CharacterInput>(); character = GetComponent<AuthoritativeCharacter>(); character.state = CharacterState.Zero; charCtrl = GetComponent<CharacterController>(); } void Update() { if (movesMade > 0) movesMade--; if (movesMade == 0) { CharacterState state = character.state; while ((movesMade < character.InputBufferSize && inputBuffer.Count > 0)) { state = CharacterState.Move(state, inputBuffer.Dequeue(), character.Speed, serverTick); charCtrl.Move(state.position - charCtrl.transform.position); movesMade++; } if (movesMade > 0) { state.position = transform.position; character.state = state; character.OnServerStateChange(state); } } } void FixedUpdate() { serverTick++; } public void Move(CharacterInput[] inputs) { foreach (var input in inputs) inputBuffer.Enqueue(input); } } <|start_filename|>Assets/_Project/Scripts/Structs/CharacterState.cs<|end_filename|> /** * CharacterState.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using System.Collections; [System.Serializable] public struct CharacterState { public Vector3 position; public Vector3 eulerAngles; public Vector3 velocity; public Vector3 angularVelocity; public int moveNum; public int timestamp; public override string ToString() { return string.Format("CharacterState Pos:{0}|Rot:{1}|Vel:{2}|AngVel:{3}|MoveNum:{4}|Timestamp:{5}", position, eulerAngles, velocity, angularVelocity, moveNum, timestamp); } public static CharacterState Zero { get { return new CharacterState { position = Vector3.zero, eulerAngles = Vector3.zero, moveNum = 0, timestamp = 0 }; } } public static CharacterState Interpolate(CharacterState from, CharacterState to, int clientTick) { float t = ((float)(clientTick - from.timestamp)) / (to.timestamp - from.timestamp); return new CharacterState { position = Vector3.Lerp(from.position, to.position, t), eulerAngles = Vector3.Lerp(from.eulerAngles, to.eulerAngles, t), moveNum = 0, timestamp = 0 }; } public static CharacterState Extrapolate(CharacterState from, int clientTick) { int t = clientTick - from.timestamp; return new CharacterState { position = from.position + from.velocity * t, eulerAngles = from.eulerAngles + from.eulerAngles * t, moveNum = from.moveNum, timestamp = from.timestamp }; } public static CharacterState Move(CharacterState previous, CharacterInput input, float speed, int timestamp) { var state = new CharacterState { position = speed * Time.fixedDeltaTime * new Vector3(input.dir.x, 0, input.dir.y) + previous.position, eulerAngles = previous.eulerAngles, moveNum = previous.moveNum + 1, timestamp = timestamp }; var timestepInterval = timestamp - previous.timestamp + 1; state.velocity = (state.position - previous.position) / timestepInterval; state.angularVelocity = (state.eulerAngles - previous.eulerAngles) / timestepInterval; return state; } } <|start_filename|>Assets/_Project/Scripts/Utilities/DebugExtensions.cs<|end_filename|> /** * DebugExtensions.cs * Created by: <NAME> [<EMAIL>] * Created on: 18/03/18 (dd/mm//yy) */ using UnityEngine; using System.Collections.Generic; using System.Text; using System.Linq; public static class DebugExtensions { const int IdentSpaces = 2; public static void LogCollection<T>(IEnumerable<T> collection) { Debug.Log(CollectionToString(collection)); } public static void LogJaggedArray<T>(T[][] jaggedArray) { var sb = new StringBuilder(); var typeName = typeof(T).Name; sb.AppendFormat("{0} jagged array with {1} arrays:\n", typeName, jaggedArray.Length); for (int i = 0; i < jaggedArray.Length; i++) { sb.AppendFormat("- [{0}] {1} array with {2} elements:\n", i, typeName, jaggedArray[i].Length); for (int j = 0; j < jaggedArray[i].Length; j++) sb.AppendFormat(" - [{0}] {1}\n", j, jaggedArray[i][j].ToString()); } Debug.Log(sb); } static string CollectionToString<T>(IEnumerable<T> collection, int identLevel = 0) { var sb = new StringBuilder(); int count = collection.Count(); sb.AppendFormat("{0}{1} collection with {2} elements{3}\n", identLevel > 0 ? new string(' ', IdentSpaces * identLevel) : "", typeof(T).Name, count, count > 0 ? ":" : ""); for (int i = 0; i < count; i++) sb.AppendFormat("{0}[{1}] {2}\n", new string(' ', IdentSpaces * (identLevel + 1)), i, collection.ElementAt(i).ToString()); return sb.ToString(); } } <|start_filename|>Assets/_Project/Scripts/Networking/AuthoritativeCharacter.cs<|end_filename|> /** * AuthoritativeCharacter.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using UnityEngine.Networking; using System.Collections.Generic; [NetworkSettings(channel = 2)] public class AuthoritativeCharacter : NetworkBehaviour { public float Speed { get { return speed; } } /// <summary> /// Controls how many inputs are needed before sending update command /// </summary> public int InputBufferSize { get; private set; } /// <summary> /// Controls how many input updates are sent per second /// </summary> [SerializeField, Range(10, 50), Tooltip("In steps per second")] int inputUpdateRate = 10; [HideInInspector, SerializeField, Range(5f, 15f)] float speed = 6.25f; [SerializeField, Range(1, 60), Tooltip("In steps per second")] public int interpolationDelay = 12; [SyncVar(hook = "OnServerStateChange")] public CharacterState state = CharacterState.Zero; IAuthCharStateHandler stateHandler; AuthCharServer server; CharacterController charCtrl; void Awake() { InputBufferSize = (int)(1 / Time.fixedDeltaTime) / inputUpdateRate; } public override void OnStartServer() { base.OnStartServer(); server = gameObject.AddComponent<AuthCharServer>(); } void Start() { charCtrl = GetComponent<CharacterController>(); if (!isLocalPlayer) { stateHandler = gameObject.AddComponent<AuthCharObserver>(); return; } GetComponentInChildren<Renderer>().material.color = Color.green; stateHandler = gameObject.AddComponent<AuthCharPredictor>(); gameObject.AddComponent<AuthCharInput>(); } public void SyncState(CharacterState overrideState) { charCtrl.Move(overrideState.position - transform.position); } public void OnServerStateChange(CharacterState newState) { state = newState; if (stateHandler != null) stateHandler.OnStateChange(state); } [Command(channel = 0)] public void CmdMove(CharacterInput[] inputs) { server.Move(inputs); } } <|start_filename|>Assets/_Project/Scripts/Networking/AuthCharInput.cs<|end_filename|> /** * AuthCharInput.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using System.Collections.Generic; public class AuthCharInput : MonoBehaviour { public static bool simulated = false; List<CharacterInput> inputBuffer; AuthoritativeCharacter character; AuthCharPredictor predictor; int currentInput = 0; Vector2 simVector; void Awake() { inputBuffer = new List<CharacterInput>(); character = GetComponent<AuthoritativeCharacter>(); predictor = GetComponent<AuthCharPredictor>(); if (simulated) { simVector.x = Random.Range(0, 1) > 0 ? 1 : -1; simVector.y = Random.Range(-1f, 1f); } } void Update() { if (Input.GetKeyDown(KeyCode.F1)) simulated = !simulated; Vector2 input = simulated ? SimulatedVector() : new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); if (inputBuffer.Count == 0 && input == Vector2.zero) return; CharacterInput charInput = new CharacterInput(input, currentInput++); predictor.AddInput(charInput); inputBuffer.Add(charInput); } void FixedUpdate() { if (inputBuffer.Count < character.InputBufferSize) return; character.CmdMove(inputBuffer.ToArray()); inputBuffer.Clear(); } Vector2 SimulatedVector() { if (transform.position.x > 5) simVector.x = Random.Range(-1f, 0); else if (transform.position.x < -5) simVector.x = Random.Range(0, 1f); if (transform.position.z > 2 || transform.position.z < -2) simVector.y = 0; return simVector; } } <|start_filename|>Assets/_Project/Scripts/Utilities/ServerStarter.cs<|end_filename|> /** * ServerStarter.cs * Created by: <NAME> * Created on: 30/04/17 (dd/mm/yy) */ using UnityEngine; using UnityEngine.Networking; using System; using System.Linq; public class ServerStarter : MonoBehaviour { void Start() { var args = Environment.GetCommandLineArgs(); if (args.Any((arg) => arg == "servermode")) { Application.targetFrameRate = 60; NetworkManager.singleton.StartServer(); } else if (args.Any((arg) => arg == "gamemode")) { NetworkManager.singleton.StartClient(); AuthCharInput.simulated = true; } Time.fixedDeltaTime = 1 / 60f; Destroy(gameObject); } }
longde123/unity-fastpacedmultiplayer
<|start_filename|>tests/spec/fab/fabSpec.js<|end_filename|> describe("Fab", function () { var FAB; beforeEach(function() { loadFixtures('fab/fabFixture.html'); }); describe("Floating Action Button", function () { var normalFAB; beforeEach(function() { normalFAB = $('.fixed-action-btn').first(); normalFAB.floatingActionButton(); }); it("should open correctly", function (done) { var ul = normalFAB.find('> ul'); expect(ul.css('visibility')).toEqual('hidden', 'FAB menu div should be hidden initially'); setTimeout(function() { mouseenter(normalFAB[0]); setTimeout(function() { expect(ul.css('visibility')).toEqual('visible', 'FAB menu did not appear after mouseenter.'); done(); }, 400); }, 100); }); }); describe("FAB to toolbar", function () { var toolbarFAB; beforeEach(function() { toolbarFAB = $('.fixed-action-btn.toolbar'); toolbarFAB.floatingActionButton({ toolbarEnabled: true }); }); it("should open correctly", function (done) { var ul = toolbarFAB.find('> ul'); expect(ul.css('visibility')).toEqual('hidden', 'FAB menu div should be hidden initially'); setTimeout(function() { click(toolbarFAB[0]); setTimeout(function() { expect(ul.css('visibility')).toEqual('visible', 'FAB menu did not appear after mouseenter.'); click(document.body); setTimeout(function() { expect(ul.css('visibility')).toEqual('hidden', 'FAB menu div should be hidden after close'); done(); }, 400); }, 400); }, 100); }); }); }); <|start_filename|>jade/page-contents/waves_content.html<|end_filename|> <div class="container"> <div class="row"> <div class="col s12 m8 offset-m1 xl7 offset-xl1"> <div id="introduction" class="section scrollspy"> <h4>Introduction</h4> <p class="caption">Waves is an external library that we've included in Materialize to allow us to create the ink effect outlined in Material Design.</p> <a class="waves-effect waves-light btn" href="#!">Wave</a> </div> <div id="applying-waves" class="section scrollspy"> <h4>Applying Waves</h4> <p>The waves effect can be applied to any element. To put the waves effect on buttons, you just have to put the class <code class="language-markup">waves-effect</code> on to the buttons. If you want the waves effect to be white instead, add both <code class="language-markup">waves-effect waves-light</code> as classes.</p> <pre><code class="language-markup"> &lt;a class="waves-effect waves-light btn-large" href="#">Wave&lt;/a> </code></pre> </div> <div id="customization" class="section scrollspy"> <!-- Customization --> <h4>Customization</h4> <p>There are several ways to customize waves, you can either use pre-created classes, or you can define your own color by creating a new class.</p> <div class="row"> <div class="col s12 l6"> <h5 class="light">Available Colors</h5> <p>To use these, just add the corresponding class to your button. Play around with changing the background color of butons and the waves effect to create something cool!</p> <pre><code class="language-markup"> &lt;a href="#!" class="btn waves-effect waves-teal">Send&lt;/a> </code></pre> <div class="collection waves-color-demo"> <div class="collection-item">Default<a href="#!" class="waves-effect btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-light</code><a href="#!" class="waves-effect waves-light btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-red</code><a href="#!" class="waves-effect waves-red btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-yellow</code><a href="#!" class="waves-effect waves-yellow btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-orange</code><a href="#!" class="waves-effect waves-orange btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-purple</code><a href="#!" class="waves-effect waves-purple btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-green</code><a href="#!" class="waves-effect waves-green btn secondary-content">Send</a></div> <div class="collection-item"><code class="language-markup">waves-teal</code><a href="#!" class="waves-effect waves-teal btn secondary-content">Send</a></div> </div> </div> <div class="col s12 l6"> <h5 class="light">Custom Colors</h5> <p>If the color you want is not already available, you can easily make your own waves color by creating a custom CSS class. Take a look at the example below where we add a waves brown effect.</p> <pre><code class="language-css"> /* When creating your CSS selector, change "brown" to something of your choosing */ .waves-effect.waves-brown .waves-ripple { /* The alpha value allows the text and background color of the button to still show through. */ background-color: rgba(121, 85, 72, 0.65); } </code></pre> </div> </div> </div> <div id="circle" class="section scrollspy"> <!-- Circle --> <h4>Circle</h4> <p>If you want waves to form to a non rectangular shape, there is an option for circular waves. Just add the <code class="language-markup">waves-circle</code> in addition to <code class="language-markup">waves-effect</code>.</p> <div class="row"> <div class="col s12"> <h5 class="light">HTML Markup</h5> <pre><code class="language-markup"> &lt;a href="#!" class="waves-effect waves-circle waves-light btn-floating secondary-content"> &lt;i class="material-icons">add&lt;/i> &lt;/a> </code></pre> <div class="collection waves-color-demo"> <div class="collection-item">Default<a href="#!" class="waves-effect waves-circle btn-floating secondary-content"><i class="material-icons">add</i></a></div> <div class="collection-item"><code class="language-markup">waves-light</code><a href="#!" class="waves-effect waves-circle waves-light btn-floating secondary-content"><i class="material-icons">add</i></a></div> </div> </div> </div> </div> </div> <!-- Table of Contents --> <div class="col hide-on-small-only m3 xl3 offset-xl1"> <div class="toc-wrapper"> <div class="buysellads hide-on-small-only"> <!-- CarbonAds Zone Code --> <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CKYIK27J&placement=materializecss" id="_carbonads_js"></script> </div> <div style="height: 1px;"> <ul class="section table-of-contents"> <li><a href="#introduction">Introduction</a></li> <li><a href="#applying-waves">Applying Waves</a></li> <li><a href="#customization">Customization</a></li> <li><a href="#circle">Circle Waves</a></li> </ul> </div> </div> </div> </div> </div> <|start_filename|>jade/page-contents/pushpin_content.html<|end_filename|> <div class="container"> <div class="row"> <div class="col s12 m8 offset-m1 xl7 offset-xl1"> <div id="introduction" class="section scrollspy"> <p class="caption">Pushpin is our fixed positioning plugin. Use this to pin elements to your page during specific scroll ranges. You can check out our live example: the fixed table of contents on the right. </p> <a href="pushpin-demo.html" target="_blank" class="btn-large waves-effect waves-light">Open Demo</a> <br> <br> <h5>Demo Code</h5> <pre><code class="language-javascript"> $('.pushpin-demo-nav').each(function() { var $this = $(this); var $target = $('#' + $(this).attr('data-target')); $this.pushpin({ top: $target.offset().top, bottom: $target.offset().top + $target.outerHeight() - $this.height() }); }); </code></pre> <pre><code class="language-css"> // Only necessary for window height sized blocks. html, body { height: 100%; } </code></pre> </div> <div id="initialization" class="section scrollspy"> <h3 class="header">Initialization</h3> <p>Here is a sample initialization of pushpin. Take a look at what the options are and customize them to your needs.</p> <pre><code class="language-javascript col s12"> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.pushpin'); var instances = M.Pushpin.init(elems, options); }); // Or with jQuery $(document).ready(function(){ $('.pushpin').pushpin(); }); </code></pre> </div> <div id="options" class="section scrollspy"> <h3 class="header">Options</h3> <table class="striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>top</td> <td>Number</td> <td>0</td> <td>The distance in pixels from the top of the page where the element becomes fixed.</td> </tr> <tr> <td>bottom</td> <td>Number</td> <td>Infinity</td> <td>The distance in pixels from the top of the page where the elements stops being fixed.</td> </tr> <tr> <td>offset</td> <td>Number</td> <td>0</td> <td>The offset from the top the element will be fixed at.</td> </tr> <tr> <td>onPositionChange</td> <td>Function</td> <td>null</td> <td>Callback function called when pushpin position changes. You are provided with a position string.</td> </tr> </tbody> </table> </div> <div id="methods" class="scrollspy section"> <h3 class="header">Methods</h3> <blockquote> <p>Because jQuery is no longer a dependency, all the methods are called on the plugin instance. You can get the plugin instance like this: </p> <pre><code class="language-javascript col s12"> var instance = M.Pushpin.getInstance(elem); /* jQuery Method Calls You can still use the old jQuery plugin method calls. But you won't be able to access instance properties. $('.target').pushpin('methodName'); $('.target').pushpin('methodName', paramName); */ </code></pre> </blockquote> <h5 class="method-header"> .destroy(); </h5> <p>Destroy plugin instance and teardown</p> <pre><code class="language-javascript col s12"> instance.destroy(); </code></pre> </div> <div id="properties" class="scrollspy section"> <h3 class="header">Properties</h3> <table class="striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>el</td> <td>Element</td> <td>The DOM element the plugin was initialized with.</td> </tr> <tr> <td>options</td> <td>Object</td> <td>The options the instance was initialized with.</td> </tr> <tr> <td>originalOffset</td> <td>Number</td> <td>Original offsetTop of element.</td> </tr> </tbody> </table> </div> <div id="classes" class="section scrollspy"> <h3 class="header">CSS Classes</h3> <p class="caption">A pushpinned element has 3 states. One above and below the scrolling threshold, and the pinned state where the element becomes fixed. Because pushpin changes positioning, chances are your element will look different when the states change. Use these css classes to correctly style your 3 states.</p> <pre><code class="language-css col s12"> // Class for when element is above threshold .pin-top { position: relative; } // Class for when element is below threshold .pin-bottom { position: relative; } // Class for when element is pinned .pinned { position: fixed !important; } </code></pre> </div> </div> <!-- Table of Contents --> <div class="col hide-on-small-only m3 xl3 offset-xl1"> <div class="toc-wrapper"> <div class="buysellads hide-on-small-only"> <!-- CarbonAds Zone Code --> <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=materializecss" id="_carbonads_js"></script> </div> <div style="height: 1px;"> <ul class="section table-of-contents"> <li> <a href="#introduction">Introduction</a> </li> <li> <a href="#initialization">Initialization</a> </li> <li> <a href="#options">Options</a> </li> <li> <a href="#methods">Methods</a> </li> <li> <a href="#properties">Properties</a> </li> <li> <a href="#classes">CSS classes</a> </li> </ul> </div> </div> </div> </div> </div> <|start_filename|>jade/page-contents/modals_content.html<|end_filename|> <div class="container bsa"> <div class="row"> <div class="col s12 m8 offset-m1 xl7 offset-xl1"> <div id="introduction" class="section scrollspy"> <p class="caption">Use a modal for dialog boxes, confirmation messages, or other content that can be called up. In order for the modal to work you have to add the Modal ID to the link of the trigger. To add a close button, just add the class <code class="language-css">.modal-close</code> to your button.</p> <a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a> <div id="modal1" class="modal"> <div class="modal-content"> <h4>Modal Header</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect waves-red btn-flat">Disagree</a> <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a> </div> </div> <div id="modal2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Modal Header</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect waves-red btn-flat">Disagree</a> <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a> </div> </div> <div id="modal3" class="modal bottom-sheet"> <div class="modal-content"> <h3 class="header">Modal Header</h3> <ul class="collection"> <li class="collection-item avatar"> <img src="images/yuna.jpg" alt="" class="circle"> <span class="title">Title</span> <p>First Line <br> Second Line </p> <a href="#!" class="secondary-content"> <i class="material-icons">grade</i> </a> </li> <li class="collection-item avatar"> <i class="material-icons circle">folder</i> <span class="title">Title</span> <p>First Line <br> Second Line </p> <a href="#!" class="secondary-content"> <i class="material-icons">grade</i> </a> </li> <li class="collection-item avatar"> <i class="material-icons circle green">assessment</i> <span class="title">Title</span> <p>First Line <br> Second Line </p> <a href="#!" class="secondary-content"> <i class="material-icons">grade</i> </a> </li> <li class="collection-item avatar"> <i class="material-icons circle red">play_arrow</i> <span class="title">Title</span> <p>First Line <br> Second Line </p> <a href="#!" class="secondary-content"> <i class="material-icons">grade</i> </a> </li> </ul> </div> </div> </div> <pre><code class="language-markup"> &lt;!-- Modal Trigger --> &lt;a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal&lt;/a> &lt;!-- Modal Structure --> &lt;div id="modal1" class="modal"> &lt;div class="modal-content"> &lt;h4>Modal Header&lt;/h4> &lt;p>A bunch of text&lt;/p> &lt;/div> &lt;div class="modal-footer"> &lt;a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree&lt;/a> &lt;/div> &lt;/div> </code></pre> <div id="button-trigger" class="scrollspy section"> <h3 class="header">Modals with Button trigger</h3> <p>If you prefer to use a button to open a modal specify the Modal ID in <code class="language-markup">data-target</code> rather than the href attribute. </p> <pre><code class="language-markup"> &lt;!-- Modal Trigger --> &lt;button data-target="modal1" class="btn modal-trigger">Modal&lt;/button> </code></pre> </div> <div id="initialization" class="scrollspy section"> <h3 class="header">Initialization</h3> <p>To open a modal using a trigger:</p> <pre><code class="language-javascript"> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.modal'); var instances = M.Modal.init(elems, options); }); // Or with jQuery $(document).ready(function(){ $('.modal').modal(); }); </code></pre> </div> <div id="options" class="scrollspy section"> <h3 class="header">Options</h3> <p>You can customize the behavior of each modal using these options. For example, you can call a custom function to run when a modal is dismissed. To do this, just place your function in the intialization code as shown below.</p> <table class="striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>opacity</td> <td>Number</td> <td>0.5</td> <td>Opacity of the modal overlay.</td> </tr> <tr> <td>inDuration</td> <td>Number</td> <td>250</td> <td>Transition in duration in milliseconds.</td> </tr> <tr> <td>outDuration</td> <td>Number</td> <td>250</td> <td>Transition out duration in milliseconds.</td> </tr> <tr> <td>onOpenStart</td> <td>Function</td> <td>null</td> <td>Callback function called before modal is opened.</td> </tr> <tr> <td>onOpenEnd</td> <td>Function</td> <td>null</td> <td>Callback function called after modal is opened.</td> </tr> <tr> <td>onCloseStart</td> <td>Function</td> <td>null</td> <td>Callback function called before modal is closed.</td> </tr> <tr> <td>onCloseEnd</td> <td>Function</td> <td>null</td> <td>Callback function called after modal is closed.</td> </tr> <tr> <td>preventScrolling</td> <td>Boolean</td> <td>true</td> <td>Prevent page from scrolling while modal is open.</td> </tr> <tr> <td>dismissible</td> <td>Boolean</td> <td>true</td> <td>Allow modal to be dismissed by keyboard or overlay click.</td> </tr> <tr> <td>startingTop</td> <td>String</td> <td>'4%'</td> <td>Starting top offset</td> </tr> <tr> <td>endingTop</td> <td>String</td> <td>'10%'</td> <td>Ending top offset</td> </tr> </tbody> </table> <br> </div> <div id="methods" class="scrollspy section"> <h3 class="header">Methods</h3> <blockquote> <p>Because jQuery is no longer a dependency, all the methods are called on the plugin instance. You can get the plugin instance like this: </p> <pre><code class="language-javascript col s12"> var instance = M.Modal.getInstance(elem); /* jQuery Method Calls You can still use the old jQuery plugin method calls. But you won't be able to access instance properties. $('.modal').modal('methodName'); $('.modal').modal('methodName', paramName); */ </code></pre> </blockquote> <h5 class="method-header"> .open(); </h5> <p>Open modal</p> <pre><code class="language-javascript col s12"> instance.open(); </code></pre> <br> <h5 class="method-header"> .close(); </h5> <p>Close modal</p> <pre><code class="language-javascript col s12"> instance.close(); </code></pre> <br> <h5 class="method-header"> .destroy(); </h5> <p>Destroy plugin instance and teardown</p> <pre><code class="language-javascript col s12"> instance.destroy(); </code></pre> </div> <div id="properties" class="scrollspy section"> <h3 class="header">Properties</h3> <table class="striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>el</td> <td>Element</td> <td>The DOM element the plugin was initialized with.</td> </tr> <tr> <td>options</td> <td>Object</td> <td>The options the instance was initialized with.</td> </tr> <tr> <td>isOpen</td> <td>Boolean</td> <td>If the modal is open.</td> </tr> <tr> <td>id</td> <td>string</td> <td>ID of the modal element</td> </tr> </tbody> </table> </div> <div id="fixed-footer" class="scrollspy section"> <h3 class="header">Modals with Fixed Footer</h3> <a class="waves-effect waves-light btn modal-trigger" href="#modal2">Modal With Fixed Footer</a> <p>If you have content that is very long and you want the action buttons to be visible all the time, you can add the <code class="language-markup">modal-fixed-footer</code> class to the modal. </p> <pre><code class="language-markup"> &lt;!-- Modal Trigger --> &lt;a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal&lt;/a> &lt;!-- Modal Structure --> &lt;div id="modal1" class="modal modal-fixed-footer"> &lt;div class="modal-content"> &lt;h4>Modal Header&lt;/h4> &lt;p>A bunch of text&lt;/p> &lt;/div> &lt;div class="modal-footer"> &lt;a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree&lt;/a> &lt;/div> &lt;/div> </code></pre> </div> <div id="bottom-sheet" class="scrollspy section"> <h3 class="header">Bottom Sheet Modals</h3> <a class="waves-effect waves-light btn modal-trigger" href="#modal3">Modal Bottom Sheet Style</a> <p>Bottom Sheet Modals are good for displaying actions to the user on the bottom of a screen. They still act the same as regular modals.</p> <pre><code class="language-markup"> &lt;!-- Modal Trigger --> &lt;a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal&lt;/a> &lt;!-- Modal Structure --> &lt;div id="modal1" class="modal bottom-sheet"> &lt;div class="modal-content"> &lt;h4>Modal Header&lt;/h4> &lt;p>A bunch of text&lt;/p> &lt;/div> &lt;div class="modal-footer"> &lt;a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree&lt;/a> &lt;/div> &lt;/div> </code></pre> </div> </div> <!-- Table of Contents --> <div class="col hide-on-small-only m3 xl3 offset-xl1"> <div class="toc-wrapper"> <div class="buysellads hide-on-small-only"> <!-- CarbonAds Zone Code --> <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CKYIK27J&placement=materializecss" id="_carbonads_js"></script> </div> <div style="height: 1px;"> <ul class="section table-of-contents"> <li> <a href="#introduction">Introduction</a> </li> <li> <a href="#button-trigger">Button Trigger</a> </li> <li> <a href="#initialization">Intialization</a> </li> <li> <a href="#options">Options</a> </li> <li> <a href="#methods">Methods</a> </li> <li> <a href="#properties">Properties</a> </li> <li> <a href="#fixed-footer">Fixed Footer</a> </li> <li> <a href="#bottom-sheet">Bottom Sheet</a> </li> </ul> </div> </div> </div> </div> </div> <|start_filename|>tests/spec/cards/cardsFixture.html<|end_filename|> <div class="row"> <div class="col s12 m6"> <div class="card reveal"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="images/office.jpg"> </div> <div class="card-content"> <span class="card-title activator grey-text text-darken-4">Card Title<i class="material-icons right">more_vert</i></span> <p><a href="#">This is a link</a></p> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4">Card Title<i class="material-icons right">close</i></span> <p>Here is some more information about this product that is only revealed once clicked on.</p> </div> </div> <div class="col s12 m6"> <div class="card image"> <div class="card-image"> <img src="http://www.isaachernandez.com/wp-content/uploads/2012/02/Isaac-Hernandez-self-portrait-20701.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> </div> </div> </div> </div> <div class="row"> <div class="col s4"> <div class="card small"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s4"> <div class="card medium"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s4"> <div class="card large"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> </div> <|start_filename|>tests/spec/carousel/carouselSpec.js<|end_filename|> describe("Carousel", function () { beforeEach(function() { loadFixtures('carousel/carouselFixture.html'); }); describe("carousel plugin", function () { // beforeEach(function() { // }); it("No wrap next and prev should not overflow", function (done) { $noWrap = $('#slider-no-wrap').carousel({ noWrap: true }); $noWrap.carousel('prev'); expect($noWrap[0].M_Carousel.center).toEqual(0, 'Prev should do nothing'); $noWrap.carousel('set', 3); setTimeout(function() { $noWrap.carousel('next'); setTimeout(function() { expect($noWrap[0].M_Carousel.center).toEqual(3, 'Next should do nothing'); done(); }, 400); }, 400); }); }); }); <|start_filename|>templates/masonry-template/js/init.js<|end_filename|> (function($){ $(function(){ $('.sidenav').sidenav(); var $container = $('#masonry-grid'); // initialize $container.masonry({ columnWidth: '.col', itemSelector: '.col', }); }); // end of document ready })(jQuery); // end of jQuery name space <|start_filename|>tests/spec/modal/modalSpec.js<|end_filename|> describe( 'Modal:', function() { var transformMaterialbox; var trigger1, modal1, trigger2, modal2, trigger3, modal3; beforeEach(function() { loadFixtures('modal/modalFixture.html'); trigger1 = $('.btn[href="#modal1"]'); triggerIcon1 = $('.btn[data-target="modal1"] i'); trigger2 = $('.btn[href="#modal2"]'); trigger3 = $('.btn[href="#modal3"]'); modal1 = $('#modal1'); modal2 = $('#modal2'); modal3 = $('#modal3'); }); describe('Modals', function() { it('Should open and close correctly', function(done) { modal1.modal(); expect(modal1).toBeHidden('Modal should be hidden'); click(trigger1[0]); setTimeout(function() { expect(modal1).toBeVisible('Modal should be shown'); expect(modal1.hasClass('open')).toEqual(true, 'Modal should have class open'); // Check overlay is attached var overlay = M.Modal.getInstance(modal1[0]).$overlay; var overlayInDOM = $.contains(document, overlay[0]); expect(overlayInDOM).toEqual(true, 'Overlay should be attached on open'); click(overlay[0]); setTimeout(function() { expect(modal1.hasClass('open')).toEqual(false, 'Modal should have class open removed'); var overlayInDOM = $.contains(document, overlay[0]); expect(overlayInDOM).toEqual(false, 'Overlay should be removed on close'); done(); }, 500); }, 500); }); it('Should open and close correctly with children elements in trigger', function(done) { modal1.modal(); expect(modal1).toBeHidden('Modal should be hidden'); click(triggerIcon1[0]); setTimeout(function() { expect(modal1).toBeVisible('Modal should be shown'); expect(modal1.hasClass('open')).toEqual(true, 'Modal should have class open'); // Check overlay is attached var overlay = M.Modal.getInstance(modal1[0]).$overlay; var overlayInDOM = $.contains(document, overlay[0]); expect(overlayInDOM).toEqual(true, 'Overlay should be attached on open'); click(overlay[0]); setTimeout(function() { expect(modal1.hasClass('open')).toEqual(false, 'Modal should have class open removed'); var overlayInDOM = $.contains(document, overlay[0]); expect(overlayInDOM).toEqual(false, 'Overlay should be removed on close'); done(); }, 500); }, 500); }); it('Should have a dismissible option', function(done) { modal1.modal({ dismissible: false }); click(trigger1[0]); setTimeout(function() { expect(modal1).toBeVisible('Modal should be shown'); var overlay = M.Modal.getInstance(modal1[0]).$overlay; var overlayInDOM = $.contains(document, overlay[0]); expect(overlayInDOM).toEqual(true, 'Overlay should be attached on open'); click(overlay[0]); setTimeout(function() { expect(modal1).toBeVisible('Modal should be shown'); var overlayInDOM = $.contains(document, overlay[0]); expect(overlayInDOM).toEqual(true, 'modal should not be dismissable'); done(); }, 500); }, 500); }); it('Should have callbacks', function(done) { var readyTest = false; var completeTest = false; modal1.modal({ onOpenStart: function() { readyTest = true; }, onCloseStart: function() { completeTest = true; } }); expect(readyTest).toEqual(false, 'callback not yet fired'); expect(completeTest).toEqual(false, 'callback not yet fired'); click(trigger1[0]); setTimeout(function() { expect(readyTest).toEqual(true, 'callback fired'); expect(completeTest).toEqual(false, 'callback not yet fired'); var overlay = M.Modal.getInstance(modal1[0]).$overlay; click(overlay[0]); setTimeout(function() { expect(readyTest).toEqual(true, 'callback fired'); expect(completeTest).toEqual(true, 'callback fired'); done(); }, 500); }, 500); }); }); }); <|start_filename|>tests/spec/dropdown/dropdownSpec.js<|end_filename|> describe("Dropdown Plugin", function () { beforeEach(function() { loadFixtures('dropdown/dropdownFixture.html'); $('.dropdown-trigger').dropdown(); }); describe("Dropdown", function () { var normalDropdown; beforeEach(function() { // browserSelect = $('select.normal'); }); it("should open and close programmatically", function (done) { var dropdown1 = $('#dropdown1'); normalDropdown = $('#dropdownActivator'); expect(dropdown1).toBeHidden('Should be hidden before dropdown is opened.'); normalDropdown.dropdown('open'); setTimeout(function() { expect(dropdown1).toBeVisible('Should be shown after dropdown is opened.'); normalDropdown.dropdown('close'); setTimeout(function() { expect(dropdown1).toBeHidden('Should be hidden after dropdown is closed.'); done(); }, 400); }, 400); }); it("should close dropdown on document click if programmatically opened", function (done) { normalDropdown = $('#dropdownActivator'); expect(dropdown1).toBeHidden('Should be hidden before dropdown is opened.'); normalDropdown.dropdown('open'); setTimeout(function() { expect(dropdown1).toBeVisible('Should be shown after dropdown is opened.'); click(document.body); setTimeout(function() { expect(dropdown1).toBeHidden('Should be hidden after dropdown is closed.'); done(); }, 400); }, 400); }); it("should bubble events correctly", function (done) { var dropdown2 = $('#dropdown2'); normalDropdown = $('#dropdownBubble'); expect(dropdown2).toBeHidden('Should be hidden before dropdown is opened.'); normalDropdown.find('i').click(); setTimeout(function() { expect(dropdown2).toBeVisible('Should be shown after dropdown is opened.'); click(document.body); setTimeout(function() { expect(dropdown2).toBeHidden('Should be hidden after dropdown is closed.'); done(); }, 400); }, 400); }); it("hovered should destroy itself", function (done) { var dropdownTrigger = $('#dropdownDestroyTrigger'); $(dropdownTrigger).dropdown('destroy'); $(dropdownTrigger).dropdown({ hover: true }); expect(function() { $(dropdownTrigger).dropdown('destroy'); }).not.toThrow(); setTimeout(function() { done(); }, 400); }); }); }); <|start_filename|>jade/page-contents/cards_content.html<|end_filename|> <div class="container"> <div class="row"> <div class="col s12 m8 offset-m1 xl7 offset-xl1"> <!-- Cards Section--> <div id="basic" class="section scrollspy"> <p class="caption">Cards are a convenient means of displaying content composed of different types of objects. They’re also well-suited for presenting similar objects whose size or supported actions can vary considerably, like photos with captions of variable length.</p> <h3 class="header">Basic Card</h3> <div class="row"> <div class="col s12 m8"> <!-- Basic Card --> <div class="card blue-grey darken-1"> <div class="card-content white-text"> <span class="card-title">Card Title</span> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="row"> &lt;div class="col s12 m6"> &lt;div class="card blue-grey darken-1"> &lt;div class="card-content white-text"> &lt;span class="card-title">Card Title&lt;/span> &lt;p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.&lt;/p> &lt;/div> &lt;div class="card-action"> &lt;a href="#">This is a link&lt;/a> &lt;a href="#">This is a link&lt;/a> &lt;/div> &lt;/div> &lt;/div> &lt;/div> </code></pre> <br> </div> </div> </div> <div id="image" class="section scrollspy"> <div class="row"> <!-- Image Card --> <div class="col s12 m7"> <h3 class="header">Image Card</h3> <div class="card"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> </div> </div> </div> <div class="col s12 m5"> <br><br><br><br> <p class="caption"> Here is the standard card with an image thumbnail. </p> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="row"> &lt;div class="col s12 m7"> &lt;div class="card"> &lt;div class="card-image"> &lt;img src="images/sample-1.jpg"> &lt;span class="card-title">Card Title&lt;/span> &lt;/div> &lt;div class="card-content"> &lt;p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.&lt;/p> &lt;/div> &lt;div class="card-action"> &lt;a href="#">This is a link&lt;/a> &lt;/div> &lt;/div> &lt;/div> &lt;/div> </code></pre> <br> </div> </div> </div> <div id="fab" class="section scrollspy"> <div class="row"> <!-- Image Card --> <div class="col s12 m7"> <h3 class="header">FABs in Cards</h3> <div class="card"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> <a class="btn-floating halfway-fab waves-effect waves-light red"><i class="material-icons">add</i></a> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> </div> </div> <div class="col s12 m5"> <br><br><br><br> <p class="caption"> Here is an image card with a Floating Action Button. </p> </div> </div> <div class="row"> <div class="col s12 m7"> <div class="card"> <div class="card-image"> <img src="images/sample-1.jpg"> <a class="btn-floating btn-large halfway-fab waves-effect waves-light red"><i class="material-icons">add</i></a> </div> <div class="card-content"> <span class="card-title">Card Title</span> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> </div> </div> <div class="col s12 m5"> <p class="caption"> Here is an image card with a large Floating Action Button. </p> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="row"> &lt;div class="col s12 m6"> &lt;div class="card"> &lt;div class="card-image"> &lt;img src="images/sample-1.jpg"> &lt;span class="card-title">Card Title&lt;/span> &lt;a class="btn-floating halfway-fab waves-effect waves-light red">&lt;i class="material-icons">add&lt;/i>&lt;/a> &lt;/div> &lt;div class="card-content"> &lt;p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.&lt;/p> &lt;/div> &lt;/div> &lt;/div> &lt;/div> </code></pre> <br> </div> </div> </div> <div id="horizontal" class="section scrollspy"> <div class="row"> <!-- Horizontal Card --> <div class="col s12 m7"> <h3 class="header">Horizontal Card</h3> <div class="card horizontal"> <div class="card-image"> <img src="https://lorempixel.com/100/190/nature/6"> </div> <div class="card-stacked"> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information.</p> </div> <div class="card-action"> <a href="#">This is a link</a> </div> </div> </div> </div> <div class="col s12 m5"> <br><br><br><br> <p class="caption"> Here is the standard card with a horizontal image. </p> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="col s12 m7"> &lt;h2 class="header">Horizontal Card&lt;/h2> &lt;div class="card horizontal"> &lt;div class="card-image"> &lt;img src="https://lorempixel.com/100/190/nature/6"> &lt;/div> &lt;div class="card-stacked"> &lt;div class="card-content"> &lt;p>I am a very simple card. I am good at containing small bits of information.&lt;/p> &lt;/div> &lt;div class="card-action"> &lt;a href="#">This is a link&lt;/a> &lt;/div> &lt;/div> &lt;/div> &lt;/div> </code></pre> <br> </div> </div> </div> <div id="reveal" class="section scrollspy"> <div class="row"> <!-- Pullup Card --> <div class="col s12 m7"> <h3 class="header">Card Reveal</h3> <div class="card"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="images/office.jpg"> </div> <div class="card-content"> <span class="card-title activator grey-text text-darken-4">Card Title<i class="material-icons right">more_vert</i></span> <p><a href="#!">This is a link</a></p> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4">Card Title<i class="material-icons right">close</i></i></span> <p>Here is some more information about this product that is only revealed once clicked on.</p> </div> </div> </div> <div class="col s12 m5"> <br><br><br><br> <p class="caption"> Here you can add a card that reveals more information once clicked. Just add the <code class="language-markup">card-reveal</code> div with a <code class="language-markup">span.card-title</code> inside to make this work. Add the class <code class="language-markup">activator</code> to an element inside the card to allow it to open the card reveal. </p> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="card"> &lt;div class="card-image waves-effect waves-block waves-light"> &lt;img class="activator" src="images/office.jpg"> &lt;/div> &lt;div class="card-content"> &lt;span class="card-title activator grey-text text-darken-4">Card Title&lt;i class="material-icons right">more_vert</i>&lt;/i>&lt;/span> &lt;p>&lt;a href="#">This is a link&lt;/a>&lt;/p> &lt;/div> &lt;div class="card-reveal"> &lt;span class="card-title grey-text text-darken-4">Card Title&lt;i class="material-icons right">close</i>&lt;/i>&lt;/span> &lt;p>Here is some more information about this product that is only revealed once clicked on.&lt;/p> &lt;/div> &lt;/div> </code></pre> </div> </div> <div class="row"> <div class="col s12 m6"> <h5>Card Action Options</h5> <div class="card"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="images/office.jpg"> </div> <div class="card-content"> <span class="card-title activator grey-text text-darken-4">Card Title<i class="material-icons right">more_vert</i></span> <p><a href="#!">This is a link</a></p> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4">Card Title<i class="material-icons right">close</i></i></span> <p>Here is some more information about this product that is only revealed once clicked on.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s12 m6"> <br><br> <p class="caption"> The default state is having the card-reveal go over the card-action. </p> </div> </div> <div class="row"> <div class="col s12 m6"> <div class="card sticky-action"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="images/office.jpg"> </div> <div class="card-content"> <span class="card-title activator grey-text text-darken-4">Card Title<i class="material-icons right">more_vert</i></span> <p><a href="#!">This is a link</a></p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4">Card Title<i class="material-icons right">close</i></i></span> <p>Here is some more information about this product that is only revealed once clicked on.</p> </div> </div> </div> <div class="col s12 m6"> <p class="caption"> You can make your card-action always visible by adding the class <code class="language-markup">sticky-action</code> to the overall card. </p> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="card sticky-action"> ... &lt;div class="card-action">...&lt;/div> &lt;div class="card-reveal">...&lt;/div> &lt;/div> </code></pre> </div> </div> </div> <div id="tabs" class="section scrollspy"> <div class="row"> <!-- Small Card --> <div class="col s12"> <h3 class="header">Tabs in Cards</h3> <p class="caption"> You can add tabs to your cards by adding a dividing <code class="language-markup">cards-tabs</code> div inbetween your header content and your tab content. </p> <pre><code class="language-markup"> &lt;div class="card"> &lt;div class="card-content"> &lt;p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.&lt;/p> &lt;/div> &lt;div class="card-tabs"> &lt;ul class="tabs tabs-fixed-width"> &lt;li class="tab">&lt;a href="#test4">Test 1&lt;/a>&lt;/li> &lt;li class="tab">&lt;a class="active" href="#test5">Test 2&lt;/a>&lt;/li> &lt;li class="tab">&lt;a href="#test6">Test 3&lt;/a>&lt;/li> &lt;/ul> &lt;/div> &lt;div class="card-content grey lighten-4"> &lt;div id="test4">Test 1&lt;/div> &lt;div id="test5">Test 2&lt;/div> &lt;div id="test6">Test 3&lt;/div> &lt;/div> &lt;/div></code></pre> </div> </div> <div class="row"> <div class="col s12 m6"> <h5>White</h5> <div class="card"> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-tabs"> <ul class="tabs tabs-fixed-width"> <li class="tab"><a href="#test4">Test 1</a></li> <li class="tab"><a class="active" href="#test5">Test 2</a></li> <li class="tab"><a href="#test6">Test 3</a></li> </ul> </div> <div class="card-content grey lighten-4"> <div id="test4">Test 1</div> <div id="test5">Test 2</div> <div id="test6">Test 3</div> </div> </div> </div> <div class="col s12 m6"> <br><br> <p class="caption"> Basic white background card with tabs. </p> </div> </div> <div class="row"> <div class="col s12 m6"> <h5>Colored</h5> <div class="card blue"> <div class="card-content white-text"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-tabs"> <ul class="tabs tabs-fixed-width tabs-transparent"> <li class="tab"><a href="#test1">Test 1</a></li> <li class="tab"><a class="active" href="#test2">Test 2</a></li> <li class="tab"><a href="#test3">Test 3</a></li> </ul> </div> <div class="card-content blue lighten-5"> <div id="test1">Test 1</div> <div id="test2">Test 2</div> <div id="test3">Test 3</div> </div> </div> </div> <div class="col s12 m6"> <br><br> <p class="caption"> Colored or dark background card with tabs. </p> </div> </div> </div> <div id="sizes" class="section scrollspy"> <div class="row"> <!-- Small Card --> <div class="col s12"> <h3 class="header">Card Sizes</h3> <p class="caption">If you want to have uniformly sized cards, you can use our premade size classes. Just add the size class in addition to the card class. </p> <pre><code class="language-markup"> &lt;div class="card small"> &lt;!-- Card Content --> &lt;/div> </code></pre> </div> </div> <div class="row"> <div class="col s12 m6"> <h5>Small</h5> <div class="card small"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s12 m6"> <br><br> <p class="caption"> The Small Card limits the height of the card to 300px. </p> </div> </div> <div class="row"> <div class="col s12 m7"> <h5>Medium</h5> <div class="card medium"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s12 m5"> <br><br> <p class="caption"> The Medium Card limits the height of the card to 400px. </p> </div> </div> <div class="row"> <div class="col s12 m8"> <h5>Large</h5> <div class="card large"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title">Card Title</span> </div> <div class="card-content"> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> <div class="col s12 m4"> <br><br> <p class="caption"> The Large Card limits the height of the card to 500px. </p> </div> </div> </div> <div id="panel" class="section scrollspy"> <div class="row"> <!-- Card Panel --> <div class="col s12 m5"> <h3 class="header">Card Panel</h3> <div class="card-panel teal"> <span class="white-text">I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively. I am similar to what is called a panel in other frameworks.</span> </div> </div> <div class="col s12 m7"> <br><br><br><br> <p class="caption"> For a simpler card with less markup, try using a card panel which just has padding and a shadow effect </p> </div> <div class="col s12"> <br> <pre><code class="language-markup"> &lt;div class="row"> &lt;div class="col s12 m5"> &lt;div class="card-panel teal"> &lt;span class="white-text">I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively. I am similar to what is called a panel in other frameworks. &lt;/span> &lt;/div> &lt;/div> &lt;/div> </code></pre> </div> </div> </div> </div> <div class="col hide-on-small-only m3 xl3 offset-xl1"> <div class="toc-wrapper"> <div class="buysellads hide-on-small-only"> <!-- CarbonAds Zone Code --> <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CKYIK27J&placement=materializecss" id="_carbonads_js"></script> </div> <div style="height: 1px;"> <ul class="section table-of-contents"> <li><a href="#basic">Basic Card</a></li> <li><a href="#image">Image Card</a></li> <li><a href="#fab">FABs in Cards</a></li> <li><a href="#horizontal">Horizontal Card</a></li> <li><a href="#reveal">Card Reveal</a></li> <li><a href="#tabs">Tabs in Cards</a></li> <li><a href="#sizes">Card Sizes</a></li> <li><a href="#panel">Card Panel</a></li> </ul> </div> </div> </div> </div> </div> <|start_filename|>jade/mobile/mobile_content.html<|end_filename|> <div class="container"> <div class="row"> <div class="col s12 m8 offset-m1 xl7 offset-xl1"> <!-- Sidenav --> <div id="right" class="section scrollspy"> <h3 class="header">Navbar</h3> <p class="caption">The navbar is fully contained by an HTML5 Nav tag. Inside a recommended container div, there are 2 main parts of the navbar. A logo or brand link, and the navigations links. You can align these links to the left or right. </p> <h4>Drag Out Menu</h4> <p>This plugin includes several options for customizing the menu. See <a href="sidenav.html#options">Plugin Options</a> for details.</p> <img class="mobile-image" src="images/menu.gif"> </div> <!-- Toast --> <div id="toast-mobile" class="section scrollspy"> <h3 class="header">Toast</h3> <h4>Swipe to Dismiss</h4> <p>On all devices, you can swipe to dismiss toasts.</p> <img class="mobile-image" src="images/toast.gif"> </div> </div> <div class="col hide-on-small-only m3 xl3 offset-xl1"> <div class="toc-wrapper"> <div class="buysellads hide-on-small-only"> <!-- CarbonAds Zone Code --> <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CKYIK27J&placement=materializecss" id="_carbonads_js"></script> </div> <div style="height: 1px;"> <ul class="section table-of-contents"> <li><a href="#right">Sidebar</a></li> <li><a href="#toast-mobile">Toast</a></li> </ul> </div> </div> </div> </div> <!-- End Container -->
afzalsayed96/materialize
<|start_filename|>beats-output-http/resolver/resolver.go<|end_filename|> package resolver import ( "context" "net" "sync" "time" ) const MaxCacheSize = 512 //Must be greater then 16 func NewDNSResolver() *DNSResolver { tmp := DNSResolver{ resolver: net.DefaultResolver, cache: make(map[string]DNSRecord), } go func() { for range time.Tick(60 * time.Second) { tmp.refresh() } }() return &tmp } type DNSRecord struct { addr []string err error } type DNSResolver struct { resolver *net.Resolver cache map[string]DNSRecord sync.Mutex } func (dr *DNSResolver) LookupHost(ctx context.Context, host string) ([]string, error) { dr.Lock() defer dr.Unlock() if val, ok := dr.cache[host]; ok { return val.addr, val.err } addr, err := dr.resolver.LookupHost(ctx, host) dr.cache[host] = DNSRecord{ addr: addr, err: err, } return addr, err } func (dr *DNSResolver) refresh() { dr.Lock() defer dr.Unlock() //free cache space if len(dr.cache) > MaxCacheSize { for key := range dr.cache { delete(dr.cache, key) if len(dr.cache) <= MaxCacheSize-16 { break } } } for key, val := range dr.cache { addr, err := net.LookupHost(key) val.addr = addr val.err = err } } <|start_filename|>beats-output-http/http_test.go<|end_filename|> // +build !integration package http import "testing" func Test_maskPass(t *testing.T) { if maskPass("r") != "*" { t.Fail() } if maskPass("er") != "**" { t.Fail() } if maskPass("ert") != "***" { t.Fail() } if maskPass("hgfd") != "****" { t.Fail() } if maskPass("password") != "********" { t.Fail() } if maskPass("password1") != "<PASSWORD>" { t.Fail() } } <|start_filename|>beats-output-http/http.go<|end_filename|> package http import ( "bytes" "context" "errors" "fmt" "github.com/crazygreenpenguin/beats-output-http/resolver" "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/beats/v7/libbeat/common" "github.com/elastic/beats/v7/libbeat/logp" "github.com/elastic/beats/v7/libbeat/outputs" "github.com/elastic/beats/v7/libbeat/outputs/codec" "github.com/elastic/beats/v7/libbeat/publisher" "github.com/json-iterator/go" "io/ioutil" "net" "net/http" "sync" "time" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary var dnsCache = resolver.NewDNSResolver() func init() { outputs.RegisterType("http", makeHTTP) } type httpOutput struct { log *logp.Logger beat beat.Info observer outputs.Observer codec codec.Codec client *http.Client serialize func(event *publisher.Event) ([]byte, error) reqPool sync.Pool conf config } // makeHTTP instantiates a new http output instance. func makeHTTP( _ outputs.IndexManager, beat beat.Info, observer outputs.Observer, cfg *common.Config, ) (outputs.Group, error) { config := defaultConfig if err := cfg.Unpack(&config); err != nil { return outputs.Fail(err) } ho := &httpOutput{ log: logp.NewLogger("http"), beat: beat, observer: observer, conf: config, } // disable bulk support in publisher pipeline if err := cfg.SetInt("bulk_max_size", -1, -1); err != nil { ho.log.Error("Disable bulk error: ", err) } //select serializer ho.serialize = ho.serializeAll if config.OnlyFields { ho.serialize = ho.serializeOnlyFields } // init output if err := ho.init(beat, config); err != nil { return outputs.Fail(err) } return outputs.Success(-1, config.MaxRetries, ho) } func (out *httpOutput) init(beat beat.Info, c config) error { var err error out.codec, err = codec.CreateEncoder(beat, c.Codec) if err != nil { return err } tr := &http.Transport{ MaxIdleConns: out.conf.MaxIdleConns, ResponseHeaderTimeout: time.Duration(out.conf.ResponseHeaderTimeout) * time.Millisecond, IdleConnTimeout: time.Duration(out.conf.IdleConnTimeout) * time.Second, DisableCompression: !out.conf.Compression, DisableKeepAlives: !out.conf.KeepAlive, DialContext: func(ctx context.Context, network string, addr string) (conn net.Conn, err error) { host, port, err := net.SplitHostPort(addr) if err != nil { return nil, err } ips, err := dnsCache.LookupHost(ctx, host) if err != nil { return nil, err } for _, ip := range ips { var dialer net.Dialer conn, err = dialer.DialContext(ctx, network, net.JoinHostPort(ip, port)) if err == nil { break } } return }, } out.client = &http.Client{ Transport: tr, } out.reqPool = sync.Pool{ New: func() interface{} { req, err := http.NewRequest("POST", out.conf.URL, nil) if err != nil { return err } return req }, } out.log.Infof("Initialized http output:\n"+ "url=%v\n"+ "codec=%v\n"+ "only_fields=%v\n"+ "max_retries=%v\n"+ "compression=%v\n"+ "keep_alive=%v\n"+ "max_idle_conns=%v\n"+ "idle_conn_timeout=%vs\n"+ "response_header_timeout=%vms\n"+ "username=%v\n"+ "password=%<PASSWORD>", c.URL, c.Codec, c.OnlyFields, c.MaxRetries, c.Compression, c.KeepAlive, c.MaxIdleConns, c.IdleConnTimeout, c.ResponseHeaderTimeout, c.Username, maskPass(c.Password)) return nil } func maskPass(password string) string { result := "" if len(password) <= 8 { for i := 0; i < len(password); i++ { result += "*" } return result } for i, char := range password { if i > 1 && i < len(password)-2 { result += "*" } else { result += string(char) } } return result } // Implement Client func (out *httpOutput) Close() error { out.client.CloseIdleConnections() return nil } func (out *httpOutput) serializeOnlyFields(event *publisher.Event) ([]byte, error) { fields := event.Content.Fields fields["@timestamp"] = event.Content.Timestamp for key, val := range out.conf.AddFields { fields[key] = val } serializedEvent, err := json.Marshal(&fields) if err != nil { out.log.Error("Serialization error: ", err) return make([]byte, 0), err } return serializedEvent, nil } func (out *httpOutput) serializeAll(event *publisher.Event) ([]byte, error) { serializedEvent, err := out.codec.Encode(out.beat.Beat, &event.Content) if err != nil { out.log.Error("Serialization error: ", err) return make([]byte, 0), err } return serializedEvent, nil } func (out *httpOutput) Publish(_ context.Context, batch publisher.Batch) error { st := out.observer events := batch.Events() st.NewBatch(len(events)) if len(events) == 0 { batch.ACK() return nil } for i := range events { event := events[i] serializedEvent, err := out.serialize(&event) if err != nil { if event.Guaranteed() { out.log.Errorf("Failed to serialize the event: %+v", err) } else { out.log.Warnf("Failed to serialize the event: %+v", err) } out.log.Debugf("Failed event: %v", event) batch.RetryEvents(events) st.Failed(len(events)) return nil } if err = out.send(serializedEvent); err != nil { if event.Guaranteed() { out.log.Errorf("Writing event to http failed with: %+v", err) } else { out.log.Warnf("Writing event to http failed with: %+v", err) } batch.RetryEvents(events) st.Failed(len(events)) return nil } } batch.ACK() st.Acked(len(events)) return nil } func (out *httpOutput) String() string { return "http(" + out.conf.URL + ")" } func (out *httpOutput) send(data []byte) error { req, err := out.getReq(data) if err != nil { return err } defer out.putReq(req) resp, err := out.client.Do(req) if err != nil { return err } err = resp.Body.Close() if err != nil { out.log.Warn("Close response body error:", err) } if resp.StatusCode != http.StatusOK { return fmt.Errorf("bad response code: %d", resp.StatusCode) } return nil } func (out *httpOutput) getReq(data []byte) (*http.Request, error) { tmp := out.reqPool.Get() req, ok := tmp.(*http.Request) if ok { buf := bytes.NewBuffer(data) req.Body = ioutil.NopCloser(buf) req.Header.Set("User-Agent", "beat "+out.beat.Version) if out.conf.Username != "" { req.SetBasicAuth(out.conf.Username, out.conf.Password) } return req, nil } err, ok := tmp.(error) if ok { return nil, err } return nil, errors.New("pool assertion error") } func (out *httpOutput) putReq(req *http.Request) { out.reqPool.Put(req) } <|start_filename|>beats-output-http/config.go<|end_filename|> package http import ( "errors" "github.com/elastic/beats/v7/libbeat/outputs/codec" "net/http" ) type config struct { URL string `config:"url"` Codec codec.Config `config:"codec"` OnlyFields bool `config:"only_fields"` MaxRetries int `config:"max_retries"` Compression bool `config:"compression"` KeepAlive bool `config:"keep_alive"` MaxIdleConns int `config:"max_idle_conns"` IdleConnTimeout int `config:"idle_conn_timeout"` ResponseHeaderTimeout int `config:"response_header_timeout"` Username string `config:"username"` Password string `config:"password"` AddFields map[string]interface{} `config:"add_fields"` } var ( defaultConfig = config{ URL: "http://127.0.0.1:8090/message", OnlyFields: false, MaxRetries: -1, Compression: false, KeepAlive: true, MaxIdleConns: 1, IdleConnTimeout: 0, ResponseHeaderTimeout: 100, Username: "", Password: "", AddFields: make(map[string]interface{}, 0), } ) func (c *config) Validate() error { _, err := http.NewRequest("POST", c.URL, nil) if err != nil { return err } if c.MaxIdleConns < 1 { return errors.New("max_idle_conns can't be <1") } if c.IdleConnTimeout < 0 { return errors.New("idle_conn_timeout can't be <0") } if c.ResponseHeaderTimeout < 1 { return errors.New("response_header_timeout can't be <1") } if c.Username != "" && c.Password == "" { return errors.New("password can't be empty") } return nil }
ajain0811/elastic
<|start_filename|>3d-card-flip/styles.css<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ * { box-sizing: border-box; } html, body { margin: 0; padding: 0; width: 100%; height: 100%; font-family: Arial, Helvetica, sans-serif; } body { display: flex; align-items: center; justify-content: center; background: #E2E2E2; overflow-x: hidden; overflow-y: scroll; } sc-card { width: 260px; height: 380px; position: relative; perspective: 500px; will-change: transform; } sc-card .front, sc-card .back { backface-visibility: hidden; position: absolute; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; border-radius: 3px; overflow: hidden; } sc-card button { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: none; border: none; text-indent: -10000px; /*display: none;*/ } sc-card .front { background: #444; color: #FFF; } sc-card .front h1 { font-size: 24px; } sc-card .back { background: url(images/supercharged.jpg) center center no-repeat; color: #FFF; transform: rotateY(180deg); } sc-card .umbra, sc-card .penumbra { width: 100%; height: 100%; position: absolute; top: 0; left: 0; backface-visibility: visible; } sc-card .umbra { width: 270px; height: 390px; top: -5px; left: -5px; background: url(images/umbra.svg) center center no-repeat; transform: translateY(2px); opacity: 0.3; } sc-card .penumbra { width: 330px; height: 450px; top: -35px; left: -35px; background: url(images/penumbra.svg) center center no-repeat; transform: translateY(2px); opacity: 0; } <|start_filename|>accordion/index.html<|end_filename|> <!-- Copyright 2016 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!doctype html> <head> <meta charset="utf-8"> <meta name="author" content="<NAME>" /> <meta name="viewport" content="width=device-width"> <title>Accordionian</title> <link rel="stylesheet" href="styles.css"> </head> <body> <sc-accordion role="tablist"> <sc-pane aria-expanded="true" role="tabpanel"> <button role="tab">Panel 1</button> <div class="content"> This is some content. </div> </sc-pane> <sc-pane role="tabpanel"> <button role="tab">Panel 2</button> <div class="content"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis varius arcu vel metus sodales, non efficitur felis sodales. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc interdum ligula eu nibh commodo imperdiet a vehicula ipsum. Mauris ut ornare nunc. Phasellus eleifend tempor justo. Sed ante lectus, lobortis nec nisl vitae, posuere gravida lacus. Duis gravida, magna sit amet suscipit scelerisque, turpis ipsum condimentum orci, nec bibendum eros odio a erat. Nam vitae imperdiet magna. Ut venenatis consequat velit, vel consequat metus imperdiet vitae. Fusce bibendum dignissim mauris, a posuere urna facilisis eget. Praesent nec nisi arcu. Nam molestie, diam id congue lacinia, nibh urna cursus massa, sit amet dictum ex dui non dolor. Curabitur eget scelerisque mi. Nam varius, lacus nec ultricies convallis, dolor elit imperdiet lacus, in luctus elit nunc tempus felis. Mauris gravida scelerisque metus quis mattis.</p> <p>Pellentesque ut ultrices nibh, ut pharetra ex. Ut nibh odio, fermentum eu tempus nec, maximus et urna. Nunc viverra turpis ut purus ornare, quis sollicitudin tortor facilisis. Sed facilisis, diam vitae dictum vestibulum, magna risus vulputate dui, quis mollis tellus odio non erat. Fusce a commodo metus. Mauris consectetur ex a mi finibus bibendum. Pellentesque in laoreet ipsum, a feugiat ligula. Integer a feugiat ipsum.</p> </div> </sc-pane> <sc-pane role="tabpanel"> <button role="tab">Panel 3</button> <div class="content"> This is some more content. </div> </sc-pane> <sc-pane role="tabpanel"> <button role="tab">Panel 4</button> <div class="content"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis varius arcu vel metus sodales, non efficitur felis sodales. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc interdum ligula eu nibh commodo imperdiet a vehicula ipsum. Mauris ut ornare nunc. Phasellus eleifend tempor justo. Sed ante lectus, lobortis nec nisl vitae, posuere gravida lacus. Duis gravida, magna sit amet suscipit scelerisque, turpis ipsum condimentum orci, nec bibendum eros odio a erat. Nam vitae imperdiet magna. Ut venenatis consequat velit, vel consequat metus imperdiet vitae. Fusce bibendum dignissim mauris, a posuere urna facilisis eget. Praesent nec nisi arcu. Nam molestie, diam id congue lacinia, nibh urna cursus massa, sit amet dictum ex dui non dolor. Curabitur eget scelerisque mi. Nam varius, lacus nec ultricies convallis, dolor elit imperdiet lacus, in luctus elit nunc tempus felis. Mauris gravida scelerisque metus quis mattis.</p> <p>Pellentesque ut ultrices nibh, ut pharetra ex. Ut nibh odio, fermentum eu tempus nec, maximus et urna. Nunc viverra turpis ut purus ornare, quis sollicitudin tortor facilisis. Sed facilisis, diam vitae dictum vestibulum, magna risus vulputate dui, quis mollis tellus odio non erat. Fusce a commodo metus. Mauris consectetur ex a mi finibus bibendum. Pellentesque in laoreet ipsum, a feugiat ligula. Integer a feugiat ipsum.</p> </div> </sc-pane> </sc-accordion> <script> document.querySelector('sc-accordion').setAttribute('enhanced', ''); </script> <script src="sc-pane.js"></script> <script src="sc-accordion.js"></script> </body> </html> <|start_filename|>streaming-service-worker/server/error404.js<|end_filename|> class Error404 extends Error { constructor(message) { super(message); this.name = 'Error404'; } } module.exports = Error404; <|start_filename|>streaming-service-worker/posts/h2-push-tougher-than-i-thought/meta.json<|end_filename|> { "title": "HTTP/2 push is tougher than I thought", "posted": "2017-05-30", "summary": "\"HTTP/2 push will solve that\" is something I've heard a lot when it comes to page load performance problems, but I didn't know much about it, so I decided to dig in.\n HTTP/2 push is more complicated and low-level than I initially thought, but what really caught me off-guard is how inconsistent it is between browsers – I'd assumed it was a done deal & totally ready for production.", "description": "There are lots of edge cases I hadn't considered, and it's very inconsistent between browsers. Here's what I found…" } <|start_filename|>animated-clip/menu.js<|end_filename|> /** * * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class Menu { constructor () { this._menu = document.querySelector('.js-menu'); this._menuContents = this._menu.querySelector('.js-menu-contents'); this._menuToggleButton = this._menu.querySelector('.js-menu-toggle'); this._menuTitle = this._menu.querySelector('.js-menu-title'); this._expanded = true; this._animate = false; this._duration = 200; this._frameTime = 1000/60; this._nFrames = Math.round(this._duration / this._frameTime); this._collapsed; this.expand = this.expand.bind(this); this.collapse = this.collapse.bind(this); this.toggle = this.toggle.bind(this); this._calculateScales(); this._createEaseAnimations(); this._addEventListeners(); this.collapse(); this.activate(); } activate () { this._menu.classList.add('menu--active'); this._animate = true; } collapse () { if (!this._expanded) { return; } this._expanded = false; const {x, y} = this._collapsed; const invX = 1 / x; const invY = 1 / y; this._menu.style.transform = `scale(${x}, ${y})`; this._menuContents.style.transform = `scale(${invX}, ${invY})`; if (!this._animate) { return; } this._applyAnimation({expand: false}); } expand () { if (this._expanded) { return; } this._expanded = true; this._menu.style.transform = `scale(1, 1)`; this._menuContents.style.transform = `scale(1, 1)`; if (!this._animate) { return; } this._applyAnimation({expand: true}); } toggle () { if (this._expanded) { this.collapse(); return; } this.expand(); } _addEventListeners () { this._menuToggleButton.addEventListener('click', this.toggle); } _applyAnimation ({expand}=opts) { this._menu.classList.remove('menu--expanded'); this._menu.classList.remove('menu--collapsed'); this._menuContents.classList.remove('menu__contents--expanded'); this._menuContents.classList.remove('menu__contents--collapsed'); // Force a recalc styles here so the classes take hold. window.getComputedStyle(this._menu).transform; if (expand) { this._menu.classList.add('menu--expanded'); this._menuContents.classList.add('menu__contents--expanded'); return; } this._menu.classList.add('menu--collapsed'); this._menuContents.classList.add('menu__contents--collapsed'); } _calculateScales () { const collapsed = this._menuTitle.getBoundingClientRect(); const expanded = this._menu.getBoundingClientRect(); this._collapsed = { x: collapsed.width / expanded.width, y: collapsed.height / expanded.height } } _createEaseAnimations () { let menuEase = document.querySelector('.menu-ease'); if (menuEase) { return menuEase; } menuEase = document.createElement('style'); menuEase.classList.add('menu-ease'); const menuExpandAnimation = []; const menuExpandContentsAnimation = []; const menuCollapseAnimation = []; const menuCollapseContentsAnimation = []; const percentIncrement = 100 / this._nFrames; for (let i = 0; i <= this._nFrames; i++) { const step = this._ease(i / this._nFrames).toFixed(5); const percentage = (i * percentIncrement).toFixed(5); const startX = this._collapsed.x; const startY = this._collapsed.y; const endX = 1; const endY = 1; // Expand animation. this._append({ percentage, step, startX, startY, endX, endY, outerAnimation: menuExpandAnimation, innerAnimation: menuExpandContentsAnimation }); // Collapse animation. this._append({ percentage, step, startX: 1, startY: 1, endX: this._collapsed.x, endY: this._collapsed.y, outerAnimation: menuCollapseAnimation, innerAnimation: menuCollapseContentsAnimation }); } menuEase.textContent = ` @keyframes menuExpandAnimation { ${menuExpandAnimation.join('')} } @keyframes menuExpandContentsAnimation { ${menuExpandContentsAnimation.join('')} } @keyframes menuCollapseAnimation { ${menuCollapseAnimation.join('')} } @keyframes menuCollapseContentsAnimation { ${menuCollapseContentsAnimation.join('')} }`; document.head.appendChild(menuEase); return menuEase; } _append ({ percentage, step, startX, startY, endX, endY, outerAnimation, innerAnimation}=opts) { const xScale = (startX + (endX - startX) * step).toFixed(5); const yScale = (startY + (endY - startY) * step).toFixed(5); const invScaleX = (1 / xScale).toFixed(5); const invScaleY = (1 / yScale).toFixed(5); outerAnimation.push(` ${percentage}% { transform: scale(${xScale}, ${yScale}); }`); innerAnimation.push(` ${percentage}% { transform: scale(${invScaleX}, ${invScaleY}); }`); } _clamp (value, min, max) { return Math.max(min, Math.min(max, value)); } _ease (v, pow=4) { v = this._clamp(v, 0, 1); return 1 - Math.pow(1 - v, pow); } } new Menu() <|start_filename|>custom-scrollbar/scrollbar.js<|end_filename|> (function(scope) { var dragging = false; var lastY = 0; function dragStart(event) { dragging = true; this.style.pointerEvents = 'none'; this.style.userSelect = 'none'; lastY = (event.clientY || event.clientY === 0) ? event.clientY : event.touches[0].clientY; } function dragMove(event) { if (!dragging) return; var clientY = (event.clientY || event.clientY === 0) ? event.clientY : event.touches[0].clientY; this.scrollTop += (clientY - lastY)/this.thumb.scaling; lastY = clientY; event.preventDefault(); } function dragEnd(event) { dragging = false; this.style.pointerEvents = 'initial'; this.style.userSelect = 'initial'; } // The point of this function is to update the thumb's geometry to reflect // the amount of overflow. function updateSize(scrollable) { scrollable.style.width = ''; scrollable.style.width = `calc(${getComputedStyle(scrollable).width} + 200px)`; var thumb = scrollable.thumb; var viewport = scrollable.getBoundingClientRect(); var scrollHeight = scrollable.scrollHeight; var maxScrollTop = scrollHeight - viewport.height; var thumbHeight = Math.pow(viewport.height, 2)/scrollHeight; var maxTopOffset = viewport.height - thumbHeight; thumb.scaling = maxTopOffset / maxScrollTop; thumb.style.height = `${thumbHeight}px`; if(scrollable.isIOS) { thumb.nextElementSibling.style.marginTop = `-${thumbHeight}px`; var z = 1 - 1/(1+thumb.scaling); thumb.style.transform = ` translateZ(${z}px) scale(${1-z}) translateX(-200px) `; } else { thumb.style.transform = ` scale(${1/thumb.scaling}) matrix3d( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1 ) translateZ(${-2 + 1 - 1/thumb.scaling}px) translateX(-200px) `; } } function makeCustomScrollbar(scrollable) { // Edge requires a transform on the document body and a fixed position element // in order for it to properly render the parallax effect as you scroll. // See https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5084491/ if (getComputedStyle(document.body).transform == 'none') document.body.style.transform = 'translateZ(0)'; var fixedPos = document.createElement('div'); fixedPos.style.position = 'fixed'; fixedPos.style.top = '0'; fixedPos.style.width = '1px'; fixedPos.style.height = '1px'; fixedPos.style.zIndex = 1; document.body.insertBefore(fixedPos, document.body.firstChild); scrollable.style.perspectiveOrigin = 'top right'; scrollable.style.transformStyle = 'preserve-3d'; scrollable.style.perspective = '1px'; var perspectiveCtr = document.createElement('div'); perspectiveCtr.style.perspectiveOrigin = 'top right'; perspectiveCtr.style.transformStyle = 'preserve-3d'; perspectiveCtr.style.width = '100%'; perspectiveCtr.style.position = 'absolute'; perspectiveCtr.style.pointerEvents = 'none'; perspectiveCtr.classList.add('perspective-ctr') while(scrollable.firstChild) perspectiveCtr.appendChild(scrollable.firstChild); scrollable.insertBefore(perspectiveCtr, scrollable.firstChild); var thumb = document.createElement('div'); thumb.classList.add('thumb'); thumb.style.pointerEvents = 'initial'; thumb.style.position = 'absolute'; thumb.style.transformOrigin = 'top right'; thumb.style.top = '0'; thumb.style.right = '0'; perspectiveCtr.insertBefore(thumb, perspectiveCtr.firstChild); scrollable.thumb = thumb; scrollable.perspectiveCtr = perspectiveCtr; // We are on Safari, where we need to use the sticky trick! if (getComputedStyle(scrollable).webkitOverflowScrolling) { scrollable.isIOS = true; thumb.style.right = ''; thumb.style.left = '100%'; thumb.style.position = '-webkit-sticky'; perspectiveCtr.style.perspective = '1px'; perspectiveCtr.style.height = ''; perspectiveCtr.style.width = ''; perspectiveCtr.style.position = ''; Array.from(scrollable.children) .filter(function (e) {return e !== perspectiveCtr;}) .forEach(function (e) {perspectiveCtr.appendChild(e);}); } scrollable.thumb.addEventListener('mousedown', dragStart.bind(scrollable), {passive: true}); window.addEventListener('mousemove', dragMove.bind(scrollable)); window.addEventListener('mouseup', dragEnd.bind(scrollable), {passive: true}); scrollable.thumb.addEventListener('touchstart', dragStart.bind(scrollable), {passive: true}); window.addEventListener('touchmove', dragMove.bind(scrollable)); window.addEventListener('touchend', dragEnd.bind(scrollable), {passive: true}); var f = function () { updateSize(scrollable); }; requestAnimationFrame(f); window.addEventListener('resize', f); return f; } window.addEventListener('load', function () { Array.from(document.querySelectorAll('.overflow')).forEach(scrollable => { makeCustomScrollbar(scrollable); updateSize(scrollable); }); }); })(self); <|start_filename|>accordion/sc-accordion.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class SCAccordion extends HTMLElement { static get KEY_UP () { return 38; } static get KEY_LEFT () { return 37; } static get KEY_RIGHT () { return 39; } static get KEY_DOWN () { return 40; } createdCallback () { this._panes = null; } attachedCallback () { this._panes = this.querySelectorAll('sc-pane'); this._calculateGeometries(); this._movePanels(); this._addEventListeners(); requestAnimationFrame(_ => this.setAttribute('active', '')); } detachedCallback () { this._panes = null; } _addEventListeners () { this.addEventListener('panel-change', this._onPanelChange); this.addEventListener('keydown', evt => { const panesArray = Array.from(this._panes); const selectedItem = this.querySelector('sc-pane [role="tab"]:focus'); let index = panesArray.indexOf(selectedItem.parentNode); switch (evt.keyCode) { case SCAccordion.KEY_UP: case SCAccordion.KEY_LEFT: index--; break; case SCAccordion.KEY_RIGHT: case SCAccordion.KEY_DOWN: index++; break; default: break; } if (index < 0) { index = 0; } else if (index >= this._panes.length) { index = this._panes.length - 1; } panesArray[index].header.focus(); }); } _onPanelChange (evt) { const target = evt.target; this._panes.forEach(pane => { pane.removeAttribute('aria-expanded'); pane.setAttribute('aria-hidden', 'true'); }); target.setAttribute('aria-expanded', 'true'); target.removeAttribute('aria-hidden'); requestAnimationFrame(_ => this._movePanels()); } _calculateGeometries () { if (this._panes.length === 0) { return; } this._headerHeight = this._panes[0].header.offsetHeight; this._availableHeight = this.offsetHeight - (this._panes.length * this._headerHeight); } _movePanels () { let baseY = 0; this._panes.forEach((pane, index) => { pane.style.transform = `translateY(${baseY + (this._headerHeight * index)}px)`; pane.content.style.height = `${this._availableHeight}px`; if (pane.getAttribute('aria-expanded')) { baseY = this._availableHeight; } }); } } document.registerElement('sc-accordion', SCAccordion); <|start_filename|>firebase-firestore-comments/src/server/index.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const functions = require('firebase-functions'); const express = require('express'); const firebase = require('firebase/app'); const fs = require('fs'); require('firebase/firestore'); const router = express.Router(); const indexHtml = fs.readFileSync(`${__dirname}/index.html`, 'utf8'); const firebaseApp = firebase.initializeApp({ apiKey: "<KEY>", authDomain: "supercharged-comments.firebaseapp.com", databaseURL: "https://supercharged-comments.firebaseio.com", projectId: "supercharged-comments", storageBucket: "supercharged-comments.appspot.com", messagingSenderId: "116806762306" }); const { CommentForm } = require('./components/sc-comment-form'); const { CommentList } = require('./components/sc-comment-list'); const { Comment } = require('./components/sc-comment'); function pageBuilder(page) { return { page, replace(holder, replacement) { this.page = this.page.replace(holder, replacement); }, addCommentForm() { this.replace('<!-- ::COMMENT_FORM:: -->', CommentForm.component()); return this; }, addCommentList(state) { const comments = state.map(c => Comment.component(c, c.id)).join(''); this.replace('<!-- ::COMMENT_LIST:: -->', CommentList.component(comments)); return this; }, build() { return this.page; } } } router.get('/', (req, res) => { const commentsRef = firebase.firestore().collection('comments'); commentsRef.orderBy('timestamp').get().then(snap => { const state = snap.docs.map(d => Object.assign(d.data(), { id: d.id })); const page = pageBuilder(indexHtml) .addCommentForm() .addCommentList(state) .build(); res.send(page); }); }); exports.supercharged = functions.https.onRequest(router); <|start_filename|>expand-collapse/demo.js<|end_filename|> /** * * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* global FLIP */ 'use strict'; let item = document.querySelector('.item'); let close = document.querySelector('.close'); let headerImage = document.querySelector('.item__header-image'); let headerUnderlay = document.querySelector('.item__header-underlay'); let itemTitle = document.querySelector('.item__title'); let itemUnderlay = document.querySelector('.item__underlay'); let itemList = document.querySelector('.item__list'); // From Tween.js (MIT license) // @see https://github.com/tweenjs/tween.js/blob/master/src/Tween.js#L480-L484 let timingFunctionExpand = function (t) { return --t * t * t * t * t + 1; }; // From Tween.js (MIT license) // @see https://github.com/tweenjs/tween.js/blob/master/src/Tween.js#L480-L484 let timingFunctionCollapse = function (t) { if ((t *= 2) < 1) { return 0.5 * t * t * t * t * t; } return 0.5 * ((t -= 2) * t * t * t * t + 2); }; headerImage.addEventListener('click', () => { // Only expand if the item is collapsed. if (item.classList.contains('last')) return; let options = { timing: timingFunctionExpand, duration: 500 }; let flipGroup = FLIP.group([ Object.assign({}, options, { element: close, transform: false }), Object.assign({}, options, { element: headerImage }), Object.assign({}, options, { element: headerUnderlay }), Object.assign({}, options, { element: itemUnderlay }), Object.assign({}, options, { element: itemTitle, delay: 200 }), Object.assign({}, options, { element: itemList, duration: 800, delay: 200 }) ]); // First position & opacity. flipGroup.first(); // Set the item to the end position (it doesn't need to animate). item.classList.add('last'); // Apply the 'last' class and snapshot the last position & opacity. flipGroup.last('last'); // Move and fade the group back to the original position. flipGroup.invert(); // Play it forwards. flipGroup.play(); // The event to capture at the end of the animation let onFlipComplete = () => { itemList.removeEventListener('flipComplete', onFlipComplete); // Make the list scrollable itemList.style.overflow = 'auto'; } // When the image has finished FLIPing, remove the class from the item itself. itemList.addEventListener('flipComplete', onFlipComplete); }); close.addEventListener('click', () => { let options = { timing: timingFunctionCollapse, duration: 600, delay: 100 }; let flipGroup = FLIP.group([ Object.assign({}, options, { element: close, transform: false }), Object.assign({}, options, { element: headerImage, delay: 160 }), Object.assign({}, options, { element: headerUnderlay, delay: 160 }), Object.assign({}, options, { element: itemUnderlay, delay: 160 }), Object.assign({}, options, { element: itemTitle, duration: 420 }), Object.assign({}, options, { element: itemList, duration: 300 }) ]); // First position (item is expanded) & opacity. flipGroup.first(); // Set the item to the end position (it doesn't need to animate). flipGroup.removeClass('last'); // Apply the 'last' class and snapshot the last position & opacity. flipGroup.last(); // Move and fade the element back to the expanded position. flipGroup.invert(); // Because this paints while animating itemList.style.overflow = ''; // Play it. flipGroup.play(); // Remove the 'last' class item.classList.remove('last'); }); <|start_filename|>webgl-image-processing/app.js<|end_filename|> /* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const image = new Image(); image.src = 'image.jpg'; image.onload = function () { const canvas = document.createElement('canvas'); document.body.appendChild(canvas); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; const gl = canvas.getContext('webgl'); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.clearColor(1.0, 0.8, 0.1, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); const vertShaderSource = ` attribute vec2 position; varying vec2 texCoords; void main() { texCoords = (position + 1.0) / 2.0; texCoords.y = 1.0 - texCoords.y; gl_Position = vec4(position, 0, 1.0); } `; const fragShaderSource = ` precision highp float; varying vec2 texCoords; uniform sampler2D textureSampler; void main() { float warmth = -0.2; float brightness = 0.2; vec4 color = texture2D(textureSampler, texCoords); color.r += warmth; color.b -= warmth; color.rgb += brightness; gl_FragColor = color; } `; const vertShader = gl.createShader(gl.VERTEX_SHADER); const fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(vertShader, vertShaderSource); gl.shaderSource(fragShader, fragShaderSource); gl.compileShader(vertShader); gl.compileShader(fragShader); const program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); gl.linkProgram(program); gl.useProgram(program); const vertices = new Float32Array([ -1, -1, -1, 1, 1, 1, -1, -1, 1, 1, 1, -1, ]); const vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); const positionLocation = gl.getAttribLocation(program, 'position'); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(positionLocation); const texture = gl.createTexture(); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.drawArrays(gl.TRIANGLES, 0, 6); }; <|start_filename|>3d-card-flip/card-flip.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class SCFlipCard extends HTMLElement { static get SIDES () { return { FRONT: 1, BACK: 2 }; } flip () { if (this._locked) { return; } this._locked = true; const scale = (500 + 200) / 500; const sideOne = [ {transform: `translateZ(-200px) rotate${this._axis}(0deg) scale(${scale})`}, {transform: `translateZ(-100px) rotate${this._axis}(0deg) scale(${scale})`, offset: 0.15}, {transform: `translateZ(-100px) rotate${this._axis}(180deg) scale(${scale})`, offset: 0.65}, {transform: `translateZ(-200px) rotate${this._axis}(180deg) scale(${scale})`} ]; const sideTwo = [ {transform: `translateZ(-200px) rotate${this._axis}(180deg) scale(${scale})`}, {transform: `translateZ(-100px) rotate${this._axis}(180deg) scale(${scale})`, offset: 0.15}, {transform: `translateZ(-100px) rotate${this._axis}(360deg) scale(${scale})`, offset: 0.65}, {transform: `translateZ(-200px) rotate${this._axis}(360deg) scale(${scale})`} ]; const umbra = [ {opacity: 0.3, transform: `translateY(2px) rotate${this._axis}(0deg)`}, {opacity: 0.0, transform: `translateY(62px) rotate${this._axis}(0deg)`, offset: 0.15}, {opacity: 0.0, transform: `translateY(62px) rotate${this._axis}(180deg)`, offset: 0.65}, {opacity: 0.3, transform: `translateY(2px) rotate${this._axis}(180deg)`} ]; const penumbra = [ {opacity: 0.0, transform: `translateY(2px) rotate${this._axis}(0deg)`}, {opacity: 0.5, transform: `translateY(62px) rotate${this._axis}(0deg)`, offset: 0.15}, {opacity: 0.5, transform: `translateY(62px) rotate${this._axis}(180deg)`, offset: 0.65}, {opacity: 0.0, transform: `translateY(2px) rotate${this._axis}(180deg)`} ]; const timing = { duration: this._duration, iterations: 1, easing: 'ease-in-out', fill: 'forwards' }; switch (this._side) { case SCFlipCard.SIDES.FRONT: this._front.animate(sideOne, timing); this._back.animate(sideTwo, timing); this._back.focus(); this._front.inert = true; this._back.inert = false; break; case SCFlipCard.SIDES.BACK: this._front.animate(sideTwo, timing); this._back.animate(sideOne, timing); this._front.focus(); this._front.inert = false; this._back.inert = true; break; default: throw new Error('Unknown side'); } this._umbra.animate(umbra, timing); this._penumbra.animate(penumbra, timing) .onfinish = _ => { this._locked = false; this._side = (this._side === SCFlipCard.SIDES.FRONT) ? SCFlipCard.SIDES.BACK : SCFlipCard.SIDES.FRONT; }; } createdCallback () { this._locked = false; this._side = SCFlipCard.SIDES.FRONT; this._front = this.querySelector('.front'); this._back = this.querySelector('.back'); this._buttons = this.querySelectorAll('button'); this._umbra = this.querySelector('.umbra'); this._penumbra = this.querySelector('.penumbra'); this._front.inert = false; this._back.inert = true; this._duration = parseInt(this.getAttribute('duration'), 10); if (isNaN(this._duration)) { this._duration = 800; } this._axis = this.getAttribute('axis') || 'X'; if (this._axis.toUpperCase() === 'RANDOM') { this._axis = (Math.random() > 0.5 ? 'Y' : 'X'); } } attachedCallback () { Array.from(this._buttons) .forEach(b => { b.addEventListener('click', _ => this.flip()); }); } detachedCallback () { } } document.registerElement('sc-card', SCFlipCard); <|start_filename|>streaming-service-worker/server/rev.js<|end_filename|> const fs = require('fs'); const path = require('path'); const util = require('util'); const crypto = require('crypto'); const rename = util.promisify(fs.rename); const readFile = util.promisify(fs.readFile); const writeFile = util.promisify(fs.writeFile); const glob = util.promisify(require('glob')); const mkdirp = util.promisify(require('mkdirp')); const through2 = require('through2'); const escapeStringRegexp = require('escape-string-regexp'); const hashes = new Map(); function hashExtension(extension, hash) { return '.' + hash.digest('hex').slice(0, 10) + extension; } module.exports.copyAndRev = async function copyAndRev(cwd, from, to) { cwd = path.normalize(cwd); to = path.normalize(to); const paths = await glob(from, { cwd, nodir: true }); await Promise.all( paths.map(async p => { const parsedPath = path.parse(p); const parsedOutputPath = { dir: parsedPath.dir ? `${to}/${parsedPath.dir}` : to, name: parsedPath.name, ext: parsedPath.ext }; const hash = crypto.createHash('md5'); const input = fs.createReadStream(`${cwd}/${p}`); const initialOutputPath = path.format(parsedOutputPath); await mkdirp(parsedOutputPath.dir); await new Promise(resolve => { input.pipe(through2((chunk, enc, callback) => { hash.update(chunk); callback(null, chunk); })).pipe(fs.createWriteStream(initialOutputPath)).on('finish', resolve); }); parsedOutputPath.ext = hashExtension(parsedOutputPath.ext, hash); hashes.set(`/static/${p}`, `/static-rev/${parsedPath.dir ? parsedPath.dir + "/" : ""}${parsedOutputPath.name}${parsedOutputPath.ext}`); await rename(initialOutputPath, path.format(parsedOutputPath)); }) ); } module.exports.addAndRev = async function addAndRev(p, destination, content) { const parsedPath = path.parse(p); const newExtension = hashExtension(parsedPath.ext, crypto.createHash('md5').update(content) ); let outputPath = `${parsedPath.name}${newExtension}`; if (parsedPath.dir) outputPath = `${parsedPath.dir}/` + outputPath; hashes.set(`/static/${p}`, `/static-rev/${outputPath}`); await writeFile(`${destination}/${outputPath}`, content); }; module.exports.replaceInFiles = async function replaceInFiles(inGlob) { const paths = await glob(inGlob, { nodir: true }); await Promise.all( paths.map(async p => { const content = await readFile(p, 'utf8'); await writeFile(p, replace(content)); }) ); }; function replace(content) { const re = new RegExp( [...hashes.keys()].map(s => escapeStringRegexp(s)).join('|'), 'g' ); return content.replace(re, match => hashes.get(match)); }; module.exports.replace = replace; module.exports.get = function get(key) { return hashes.get(key); }; <|start_filename|>web-workers/main.css<|end_filename|> canvas { margin-top: 2em; } #input { height: 0; overflow: hidden; width: 0; } #input + label { background-color: #777; color: #f3f3f3; display: inline-block; font-family: sans-serif; font-size: 2em; padding: 5px; } #input:focus + label { outline: 5px solid teal; } <|start_filename|>lazy-image/static/sc-img.js<|end_filename|> /** * * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const template = document.createElement('template'); template.innerHTML = ` <style> :host{ display: block; background-color: red; position: relative; background-size: 100% 100%; /* image-rendering: pixelated; */ } img { width: 100%; position: absolute; top: 0; left: 0; animation-name: fade-in; animation-duration: 5s; } @keyframes fade-in { from {opacity: 0} } </style> `; const io = new IntersectionObserver(entries => { for(const entry of entries) { if(entry.isIntersecting) { entry.target.setAttribute('full', ''); } } }); class SCImg extends HTMLElement { static get observedAttributes() { return ['full']; } constructor() { super(); this.attachShadow({mode: 'open'}); this.shadowRoot.appendChild(template.content.cloneNode(true)); } connectedCallback() { io.observe(this); } disconnectedCallback() { io.unobserve(this); } get full() { return this.hasAttribute('full'); } get src() { return this.getAttribute('src'); } attributeChangedCallback() { if(this.loaded) return; const img = document.createElement('img'); img.src = this.src; img.onload = _ => { this.loaded = true; this.shadowRoot.appendChild(img); }; } } customElements.define('sc-img', SCImg); <|start_filename|>accordion/sc-pane.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class SCPane extends HTMLElement { get header () { if (!this._header) { this._header = this.querySelector('button[role="tab"]'); } return this._header; } get content () { if (!this._content) { this._content = this.querySelector('.content'); } return this._content; } attachedCallback () { this.header.addEventListener('click', _ => { const customEvent = new CustomEvent('panel-change', { bubbles: true }); this.dispatchEvent(customEvent); }); } } document.registerElement('sc-pane', SCPane); <|start_filename|>streaming-service-worker/static/css/all.css<|end_filename|> .content-n-side:before, .content-only:before, .page-width:before, .post-preview:before, .content-n-side:after, .content-only:after, .page-width:after, .post-preview:after { content: " "; display: table } .content-n-side:after, .content-only:after, .page-width:after, .post-preview:after { clear: both } /* vietnamese */ @font-face { font-family: 'Inconsolata'; font-style: normal; font-weight: 400; src: local('Inconsolata Regular'), local('Inconsolata-Regular'), url(https://fonts.gstatic.com/s/inconsolata/v15/BjAYBlHtW3CJxDcjzrnZCL6up8jxqWt8HVA3mDhkV_0.woff2) format('woff2'); unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB; } /* latin-ext */ @font-face { font-family: 'Inconsolata'; font-style: normal; font-weight: 400; src: local('Inconsolata Regular'), local('Inconsolata-Regular'), url(https://fonts.gstatic.com/s/inconsolata/v15/BjAYBlHtW3CJxDcjzrnZCCYE0-AqJ3nfInTTiDXDjU4.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Inconsolata'; font-style: normal; font-weight: 400; src: local('Inconsolata Regular'), local('Inconsolata-Regular'), url(https://fonts.gstatic.com/s/inconsolata/v15/BjAYBlHtW3CJxDcjzrnZCI4P5ICox8Kq3LLUNMylGO4.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } /* cyrillic-ext */ @font-face { font-family: 'PT Serif'; font-style: normal; font-weight: 400; src: local('PT Serif'), local('PTSerif-Regular'), url(https://fonts.gstatic.com/s/ptserif/v8/5hX15RUpPERmeybVlLQEWBTbgVql8nDJpwnrE27mub0.woff2) format('woff2'); unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F; } /* cyrillic */ @font-face { font-family: 'PT Serif'; font-style: normal; font-weight: 400; src: local('PT Serif'), local('PTSerif-Regular'), url(https://fonts.gstatic.com/s/ptserif/v8/fU0HAfLiPHGlZhZpY6M7dBTbgVql8nDJpwnrE27mub0.woff2) format('woff2'); unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; } /* latin-ext */ @font-face { font-family: 'PT Serif'; font-style: normal; font-weight: 400; src: local('PT Serif'), local('PTSerif-Regular'), url(https://fonts.gstatic.com/s/ptserif/v8/CPRt--GVMETgA6YEaoGitxTbgVql8nDJpwnrE27mub0.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'PT Serif'; font-style: normal; font-weight: 400; src: local('PT Serif'), local('PTSerif-Regular'), url(https://fonts.gstatic.com/s/ptserif/v8/I-OtoJZa3TeyH6D9oli3ifesZW2xOQ-xsNqO47m55DA.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } html { overflow-y: scroll; background: #f1f1f1; font-size: 15px; font-family: sans-serif; line-height: 1.9 } @media screen and (min-width: 530px) { html { font-size: 16px; color: #444 } } body { margin: 0; padding: 0; -webkit-text-size-adjust: 100% } figure { margin: 0 } img { max-width: 100% } p { margin: 1.2em 0 } a:link, a:visited { text-decoration: none; color: #CC2100 } a:active, a:hover, a:focus { color: #FF8F00 } a:active { text-decoration: underline } svg { overflow: hidden } .container { max-width: 1066px; background: #fff; margin: 0 auto } .content-n-side, .content-only, .page-width { position: relative; top: -31px; padding: 0 20px } @media screen and (min-width: 530px) { .content-n-side, .content-only, .page-width { padding: 0 64px 0 32px } } @media screen and (min-width: 800px) { .content-n-side, .content-only, .page-width { padding: 0 32px } } .content-n-side>.side { display: none; } @media screen and (min-width: 800px) { .content-n-side>.content { width: 75%; padding-right: 73px; float: left; -moz-box-sizing: border-box; box-sizing: border-box } .content-n-side>.side { width: 25%; float: right; display: block; } .site-header a.who { display: none; } } .page-width { -moz-box-sizing: border-box; box-sizing: border-box; max-width: 1066px; margin: 0 auto } @media screen and (min-width: 800px) { .content-only>.content { width: 68% } } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; cursor: pointer; background-color: #f5f5f5; background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(1, #e6e6e6)); background-image: -moz-linear-gradient(top, #fff, #e6e6e6); background-image: -o-linear-gradient(top, #fff, #e6e6e6); background-image: linear-gradient(to bottom, #fff, #e6e6e6); background-repeat: repeat-x; border: 1px solid #bbbbbb; border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); border-radius: 4px; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05) } .btn:hover { background-position: 0 -15px; background-color: #e6e6e6; -webkit-transition: background-position 0.1s linear; transition: background-position 0.1s linear } .btn:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px } .btn:active { background-image: none; outline: 0; box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05) } .btn-danger { color: #FFF; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #DA4F49; background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #EE5F5B), color-stop(1, #BD362F)); background-image: -moz-linear-gradient(top, #EE5F5B, #BD362F); background-image: -o-linear-gradient(top, #EE5F5B, #BD362F); background-image: linear-gradient(to bottom, #EE5F5B, #BD362F); background-repeat: repeat-x; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25) } .btn-danger:hover, .btn-danger:focus, .btn-danger:active, .btn-danger.active, .btn-danger.disabled, .btn-danger[disabled] { color: #FFF; background-color: #BD362F } .site-header { background: #2D2D2D; overflow: hidden } .site-header>.inner { padding-top: 75px; padding-left: 0 } @media screen and (min-width: 530px) { .site-header>.inner { padding-top: 135px } } .site-header a:link, .site-header a:visited { color: #fff } .site-header a:hover, .site-header a:active { color: #fff; text-decoration: underline } .site-header .title, .site-header .who { background: #009D81; line-height: 1; font-family: "PT Serif", georgia, serif; display: inline-block; font-size: 1.05rem; padding: 10px 45px 10px 20px } @media screen and (min-width: 530px) { .site-header .title, .site-header .who { padding: 10px 97px 10px 32px } } @media screen and (min-width: 1066px) { .site-header .title, .site-header .who { border-radius: 7px 7px 0 0 } } .site-header .who { float: right; padding: 10px 0; background: none; margin-right: 0 } @media screen and (min-width: 530px) { .site-header .who { margin-right: -32px } } @media screen and (min-width: 800px) { .site-header .who { position: absolute; right: 25%; padding-right: 90px } .js .site-header .who { display: none } } .h-1, .article-content h1, .who-page>h1 { background: #FF8400; color: #FFF; margin: 0; font-family: "PT Serif", georgia, serif; font-size: 2.5rem; font-weight: normal; line-height: 1.1; margin-left: -20px; padding: 7px 20px 13px 20px } @media screen and (min-width: 530px) { .h-1, .article-content h1, .who-page>h1 { font-size: 3.4rem; padding: 10px 36px 17px 62px; margin-left: -65px; margin-right: -32px } } @media screen and (min-width: 1066px) { .h-1, .article-content h1, .who-page>h1 { border-radius: 32px 0 0 32px } } .h-2, .article-content h2, .who-page>section>h1 { background: #009D81; color: #FFF; margin: 35px 0 0; font-family: "PT Serif", georgia, serif; font-size: 1.6rem; font-weight: normal; line-height: 1; padding: 7px 20px 10px 20px; margin-left: -20px } @media screen and (min-width: 530px) { .h-2, .article-content h2, .who-page>section>h1 { font-size: 1.9rem; padding: 10px 35px 13px 62px; margin-right: -32px; margin-left: -65px } } @media screen and (min-width: 1066px) { .h-2, .article-content h2, .who-page>section>h1 { border-radius: 32px 0 0 32px } } .h-3, .article-content h3 { margin: 27px 0 0; line-height: 1; font-family: sans-serif; font-weight: bold; font-size: 1rem; border-left: 14px solid #FF8400; padding-left: 8px } @media screen and (min-width: 530px) { .h-3, .article-content h3 { font-size: 1.2rem; border-left: 19px solid #FF8400; padding-left: 12px } } .h-4, .side>section>h1 { font-weight: normal; font-size: 0.9rem; border-bottom: 1px dotted #CCC; padding-bottom: 3px; margin: 1.4em 0 0; line-height: 1 } .article-date { font-size: 0.8rem; display: block; background: #FFE454; color: #000; padding: 6px 20px 5px 20px; margin: 0 0 0 -20px } @media screen and (min-width: 530px) { .article-date { padding: 6px 10px 5px 32px; margin-left: -32px; margin-right: -32px } } .article-content code { font-family: Inconsolata, courier, monospace; background: #EEE; padding: 3px 3px; margin: 0 2px; outline: 1px solid #E2E2E2; line-height: 1; white-space: normal; display: inline-block } .full-figure { margin: 1em -20px; overflow: hidden; background: #eee } @media screen and (min-width: 530px) { .full-figure { margin-left: 0; margin-right: 0 } } .full-figure.checked { background: url("/static/css/imgs/check.png") } .full-figure.blueprint { background: url("/static/css/imgs/graph-tile.png"), radial-gradient(circle farthest-corner, #08d, #002b46) center; background-size: 12%, cover } .full-figure img, .full-figure iframe, .full-figure video, .full-figure object { display: block; margin: 0 auto } .full-figure .video { position: relative; padding-top: 56.25% } .full-figure .video iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100% } .full-figure>figcaption { font-size: 0.8rem; line-height: 1.4; background: #FFE454; color: #000; padding: 6px 20px } @media screen and (min-width: 530px) { .full-figure>figcaption { padding: 6px 10px } } .side { font-size: 0.85rem; font-weight: normal } .side .icon-list { margin: 1em 0; display: flex; flex-flow: row wrap } .side .icon-list>li { flex: 0 0 50% } .my-big-face { margin-top: 10px } .my-big-face h1 { position: relative; margin: 0; padding: 76.27907% 0 0 0; outline: 10px solid #fff; background: #fff } .my-big-face img { position: absolute; top: 0; left: 0; width: 100%; height: 100% } .codehilite { background: #2D2D2D; color: #E4E4E4; margin: 1em -20px; padding: 16px 20px; line-height: 1.4; font-size: 1rem; overflow: auto } @media screen and (min-width: 530px) { .codehilite { margin-left: -32px; margin-right: 0; padding-left: 32px; padding-right: 0; font-size: 1.1rem } } .codehilite pre { font-family: Inconsolata, courier, monospace; margin: 0; display: inline-block; padding-right: 16px } .hljs-comment, .hljs-quote { color: #bc9458; font-style: italic } .hljs-keyword, .hljs-selector-tag { color: #c26230 } .hljs-string, .hljs-number, .hljs-regexp, .hljs-variable, .hljs-template-variable { color: #a5c261 } .hljs-subst { color: #519f50 } .hljs-tag, .hljs-name { color: #e8bf6a } .hljs-type { color: #da4939 } .hljs-symbol, .hljs-bullet, .hljs-built_in, .hljs-builtin-name, .hljs-attr, .hljs-link { color: #6d9cbe } .hljs-params { color: #d0d0ff } .hljs-attribute { color: #cda869 } .hljs-meta { color: #9b859d } .hljs-title, .hljs-section { color: #ffc66d } .hljs-addition { background-color: #144212; color: #e6e1dc; display: inline-block; width: 100% } .hljs-deletion { background-color: #600; color: #e6e1dc; display: inline-block; width: 100% } .hljs-selector-class { color: #9b703f } .hljs-selector-id { color: #8b98ab } .hljs-emphasis { font-style: italic } .hljs-strong { font-weight: bold } .hljs-link { text-decoration: underline } .i { display: inline-block; vertical-align: middle } .i-social { width: 16px; height: 16px; background: url("/static/css/imgs/social-icons.png") no-repeat; background-size: 106px } .i-social.flickr { background-position: 0 0 } .i-social.lanyrd { background-position: -18px 0 } .i-social.github { background-position: -36px 0 } .i-social.twitter { background-position: -54px 0 } .i-social.gplus { background-position: -72px 0 } .i-social.rss { background-position: -90px 0 } .icon-list { margin: 0; padding: 0; list-style: none } .icon-list>li { margin: 0 0 0.3em } .icon-list .i { margin-right: 4px } .link-list a { display: block } .comments { margin-top: 50px } .post-preview h1 { margin-top: 0 } .post-preview h1 a:link, .post-preview h1 a:visited { display: block; color: #fff } .post-preview h1 a:hover, .post-preview h1 a:active { color: #fff; text-decoration: underline } .post-preview .preview-image { margin: 20px 0 0 } @media screen and (min-width: 530px) { .post-preview .preview-image { float: left; width: 200px; margin: 5px 20px 20px 0 } } .post-preview .preview-image-sizer { position: relative } .post-preview .preview-image-sizer img { position: absolute; top: 0; left: 0; width: 100%; height: 100% } .pagination { overflow: hidden; margin: 2.1em 0; padding: 0 } .pagination li { display: inline } .pagination a:link, .pagination a:visited, .pagination .page, .pagination .next, .pagination .prev, .pagination .gap { float: left; padding: 0 8px; font-weight: bold; border-right: 1px dotted #a5a5a5 } .pagination .current, .pagination .disabled, .pagination .gap { color: #6e6e6e; font-weight: normal } .pagination .prev, .pagination a.prev:link, .pagination a.prev:visited { padding-left: 0 } .pagination .next, .pagination a.next:link, .pagination a.next:visited { border: none } .form-rows { margin: 1em -20px } .codehilite+.form-rows { margin-top: -1.1em } @media screen and (min-width: 530px) { .form-rows { margin-left: -32px; margin-right: 0 } } .form-rows .field { display: table-row } .form-rows .field:nth-child(even) .label { background: #3CB39D } .form-rows .field:nth-child(even) .input { background: #f7f7f7 } .form-rows .label { background: #009D81; color: #fff; vertical-align: middle; display: table-cell; width: 1px; white-space: nowrap; padding: 0.5em; padding-left: 20px } @media screen and (min-width: 530px) { .form-rows .label { padding-left: 32px } } .form-rows .input { background: #ECECEC; padding: 0 0.5em; vertical-align: middle; display: table-cell } .form-rows input[type=text], .form-rows input[type=range] { width: 100%; margin: 0; -moz-box-sizing: border-box; box-sizing: border-box } .form-rows-inner { display: table; width: 100% } .quote { margin: 0; border-left: 10px solid #D5D5D5; padding-left: 16px } .quote>p:last-of-type { margin-bottom: 0 } .warning { background: #BF0000; color: #fff; font-size: 0.8rem; font-weight: bold; padding: 6px 20px 5px 20px; margin: 0 0 0 -20px } @media screen and (min-width: 530px) { .warning { padding: 6px 10px 5px 32px; margin-left: -32px; margin-right: -32px } } .warning>:first-child { margin-top: 0 } .warning>:last-child { margin-bottom: 0 } .who-page figure img { display: block; margin: 0 auto } .who-page .icon-list { -webkit-columns: 100px; -moz-columns: 100px; columns: 100px; margin: 16px 0 } .blog-index .post-preview.first .h-2 { background: #FF8400 } <|start_filename|>streaming-service-worker/server/marked.js<|end_filename|> const marked = require('marked'); const highlight = require('highlight.js'); const renderer = new marked.Renderer(); marked.setOptions({ renderer, highlight(code, lang) { if (lang) { return highlight.highlight(lang, code).value; } return highlight.highlightAuto(code).value; } }); renderer.heading = function (text, level, raw) { return marked.Renderer.prototype.heading.call(this, text, level + 1, raw); }; renderer.code = function (code, lang, escaped) { if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out != null && out !== code) { escaped = true; code = out; } } if (!lang) { return '<div class="codehilite"><pre>' + (escaped ? code : escape(code, true)) + '\n</pre></div>'; } return '<div class="codehilite"><pre class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? code : escape(code, true)) + '\n</pre></div>\n'; }; module.exports = marked; <|start_filename|>service-worker/app/static/sc-router.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class SCRouter extends HTMLElement { _onChanged () { const path = window.location.pathname; const routes = Array.from(this._routes.keys()); const route = routes.find(r => r.test(path)); const data = route.exec(path); if (!route) { return; } // Store the new view. this._newView = this._routes.get(route); // We don't want to create more promises for the outgoing view animation, // because then we get a lot of hanging Promises, so we add a boolean gate // here to stop if there's already a transition running. if (this._isTransitioningBetweenViews) { return Promise.resolve(); } this._isTransitioningBetweenViews = true; // Assume that there's no outgoing animation required. let outViewPromise = Promise.resolve(); // If there is a current view... if (this._currentView) { // ...and it's the one we already have, just update it. if (this._currentView === this._newView) { // No transitions, so remove the boolean gate. this._isTransitioningBetweenViews = false; return this._currentView.update(data); } // Otherwise animate it out, and take the Promise made by the view as an // indicator that the view is done. outViewPromise = this._currentView.out(data); } // Whenever the outgoing animation is done (which may be immediately if // there isn't one), update the references to the current view, allow // outgoing animations to proceed. return outViewPromise .then(_ => { this._currentView = this._newView; this._isTransitioningBetweenViews = false; return this._newView.in(data); }); } go (url) { window.history.pushState(null, null, url); return this._onChanged(); } addRoute (route, view) { if (this._routes.has(route)) return console.warn(`Route already exists: ${route}`); this._routes.set(route, view); } _addRoutes () { let views = Array.from(document.querySelectorAll('sc-view')); views.forEach(view => { if (!view.route) return; this.addRoute(new RegExp(view.route, 'i'), view); }, this); } _removeRoute (route) { this._routes.delete(route); } _clearRoutes () { this._routes.clear(); } createdCallback () { this._onChanged = this._onChanged.bind(this); this._routes = new Map(); } attachedCallback () { window.addEventListener('popstate', this._onChanged); this._clearRoutes(); this._addRoutes(); this._onChanged(); } detachedCallback () { window.removeEventListener('popstate', this._onChanged); } } document.registerElement('sc-router', SCRouter); <|start_filename|>router-advanced/static/sc-view.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class SCView extends HTMLElement { createdCallback () { this._view = null; this._isRemote = (this.getAttribute('remote') !== null); } get route () { return this.getAttribute('route') || null; } _hideSpinner () { this.classList.remove('pending'); } _showSpinner () { this.classList.add('pending'); } _loadView (data) { // Wait for half a second then show the spinner. const spinnerTimeout = setTimeout(_ => this._showSpinner(), 500); this._view = new DocumentFragment(); const xhr = new XMLHttpRequest(); xhr.onload = evt => { const newDoc = evt.target.response; const newView = newDoc.querySelector('sc-view.visible'); // Copy in the child nodes from the parent. while(newView.firstChild) { this._view.appendChild(newView.firstChild); } // Add the fragment to the page. this.appendChild(this._view); // Clear the timeout and remove the spinner if needed. clearTimeout(spinnerTimeout); this._hideSpinner(); }; xhr.responseType = 'document'; xhr.open('GET', `${data[0]}`); xhr.send(); } in (data) { if (this._isRemote && !this._view) { this._loadView(data); } return new Promise((resolve, reject) => { const onTransitionEnd = () => { this.removeEventListener('transitionend', onTransitionEnd); resolve(); }; this.classList.add('visible'); this.addEventListener('transitionend', onTransitionEnd); }); } out () { return new Promise((resolve, reject) => { const onTransitionEnd = () => { this.removeEventListener('transitionend', onTransitionEnd); resolve(); }; this.classList.remove('visible'); this.addEventListener('transitionend', onTransitionEnd); }); } update () { return Promise.resolve(); } } document.registerElement('sc-view', SCView); <|start_filename|>accordion/styles.css<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ * { box-sizing: border-box; } html, body { margin: 0; padding: 0; height: 100vh; width: 100vw; font-family: Arial, Helvetica, sans-serif; } body { display: flex; flex-direction: column; align-items: center; justify-content: center; background: #EEE; } sc-accordion { width: 100%; max-width: 450px; box-shadow: 0 3px 4px rgba(0,0,0,0.4); background: #FFF; border-radius: 3px; } sc-accordion[enhanced] { visibility: hidden; height: 600px; overflow: hidden; position: relative; } sc-accordion[enhanced] sc-pane { position: absolute; top: 0; width: 100%; } sc-accordion[active] { visibility: visible; } sc-accordion[active] sc-pane { transition: transform 0.3s cubic-bezier(0, 0, 0.3, 1); } sc-pane button[role="tab"] { width: 100%; height: 48px; line-height: 48px; border: none; font-size: 16px; background: #666; color: #FFF; border-bottom: 1px solid #444; } sc-pane button[role="tab"]:focus { background: #333; } sc-pane .content { padding: 16px; overflow-y: scroll; background-color: #FFF; } <|start_filename|>image-zoomer/styles.css<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ * { box-sizing: border-box; } html, body { padding: 0; margin: 0; background-color: #FAFAFA; width: 100%; height: 100%; overflow: hidden; font-family: 'Roboto', Arial, sans-serif; } body { display: flex; flex-direction: column; } .header { width: 100%; height: 56px; color: #FFF; background: #607D8B; font-size: 20px; box-shadow: 0 4px 5px 0 rgba(0,0,0,.14), 0 2px 9px 1px rgba(0,0,0,.12), 0 4px 2px -2px rgba(0,0,0,.2); padding: 16px 16px 0; position: relative; z-index: 1; } .header__title { font-weight: 400; font-size: 20px; margin: 0; } .main { flex: 1; padding: 16px; overflow-x: hidden; overflow-y: scroll; position: relative; width: 100%; display: flex; justify-content: space-around; } .main img { width: 100%; max-width: 650px; cursor: zoom-in; } .zoomer { width: 1px; height: 1px; position: fixed; left: 0; top: 0; pointer-events: none; } .zoomer__canvas { position: absolute; left: -64px; top: -134px; } <|start_filename|>image-zoomer/image-zoomer.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class ImageZoomer { constructor () { this.element = document.querySelector('.zoomer'); this.target = document.querySelector('.target'); this.canvas = document.querySelector('.zoomer__canvas'); this.ctx = this.canvas.getContext('2d'); this.onStart = this.onStart.bind(this); this.onMove = this.onMove.bind(this); this.onEnd = this.onEnd.bind(this); this.update = this.update.bind(this); this.onResize = this.onResize.bind(this); this.targetBCR = null; this.zoomed = 0; this.targetZoomed = 0; this.x = 0; this.y = 0; this.trackingTouch = false; this.scheduledUpdate = false; this.initCanvas(); this.addEventListeners(); this.onResize(); requestAnimationFrame(this.update); } initCanvas () { const width = 128; const height = 128; const dPR = window.devicePixelRatio || 1; this.canvas.width = width * dPR; this.canvas.height = height * dPR; this.canvas.style.width = `${width}px`; this.canvas.style.height = `${height}px`; this.ctx.scale(dPR, dPR); } onResize () { this.targetBCR = this.target.getBoundingClientRect(); } onStart (evt) { if (evt.target !== this.target) return; this.x = evt.pageX || evt.touches[0].pageX; this.y = evt.pageY || evt.touches[0].pageY; evt.preventDefault(); this.trackingTouch = true; this.targetZoomed = 1; requestAnimationFrame(this.update); } onMove (evt) { if (!this.trackingTouch) return; this.x = evt.pageX || evt.touches[0].pageX; this.y = evt.pageY || evt.touches[0].pageY; } onEnd () { this.trackingTouch = false; this.targetZoomed = 0; } update () { const TAU = Math.PI * 2; const MAX_RADIUS = 46; const radius = this.zoomed * MAX_RADIUS; const targetX = (this.x - this.targetBCR.left) / this.targetBCR.width; const targetY = (this.y - this.targetBCR.top) / this.targetBCR.height; const imageScale = 3; const scaledTargetWidth = this.targetBCR.width * imageScale; const scaledTargetHeight = this.targetBCR.height * imageScale; const glassyGlow = this.ctx.createRadialGradient(64, 64, 64, 64, 64, 0); glassyGlow.addColorStop(0, 'rgba(255,255,255,0.8)'); glassyGlow.addColorStop(0.5, 'rgba(255,255,255,0)'); // Shadow. this.ctx.shadowColor = 'rgba(0,0,0,0.4)'; this.ctx.shadowBlur = 12; this.ctx.shadowOffsetY = 8; // Background. this.ctx.clearRect(0, 0, 128, 128); this.ctx.fillStyle = '#FFFFFF'; this.ctx.beginPath(); this.ctx.arc(64, 110 - radius, radius, 0, TAU); this.ctx.closePath(); this.ctx.fill(); // Zoomed image. this.ctx.save(); this.ctx.beginPath(); this.ctx.arc(64, 110 - (radius + 1), radius * 1.03, 0, TAU); this.ctx.clip(); this.ctx.closePath(); this.ctx.drawImage(this.target, -targetX * scaledTargetWidth + 64, -targetY * scaledTargetHeight + 64, scaledTargetWidth, scaledTargetHeight); this.ctx.restore(); // Glassy glow. this.ctx.fillStyle = glassyGlow; this.ctx.beginPath(); this.ctx.arc(64, 110 - radius, Math.max(0, radius - 2), 0, TAU); this.ctx.closePath(); this.ctx.fill(); // Position the parent element. this.element.style.transform = `translate(${this.x}px, ${this.y}px)`; // Update the zoom value. this.zoomed += (this.targetZoomed - this.zoomed) / 3; // Schedule another update if the zoom is fairly non-zero. if (this.zoomed > 0.001) { requestAnimationFrame(this.update); } else { this.zoomed = 0; } } addEventListeners () { document.addEventListener('touchstart', this.onStart); document.addEventListener('touchmove', this.onMove); document.addEventListener('touchend', this.onEnd); document.addEventListener('mousedown', this.onStart); document.addEventListener('mousemove', this.onMove); document.addEventListener('mouseup', this.onEnd); window.addEventListener('resize', this.onResize); } removeEventListeners () { document.removeEventListener('touchstart', this.onStart); document.removeEventListener('touchmove', this.onMove); document.removeEventListener('touchend', this.onEnd); document.removeEventListener('mousedown', this.onStart); document.removeEventListener('mousemove', this.onMove); document.removeEventListener('mouseup', this.onEnd); window.removeEventListener('resize', this.onResize); } } window.addEventListener('load', () => new ImageZoomer()); <|start_filename|>service-worker/package.json<|end_filename|> { "name": "server-side-rendering", "version": "1.0.0", "main": "index.js", "dependencies": { "dot": "^1.0.3", "express": "^4.14.0", "http2": "^3.3.5", "mz": "^2.4.0", "spdy": "^3.4.0" }, "devDependencies": {}, "scripts": { "chrome": "rm -rf /tmp/foo && open -a 'Google Chrome Canary' -n --args --user-data-dir=/tmp/foo --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https://localhost:8081 https://localhost:8081/" } } <|start_filename|>firebase-firestore-comments/src/components/sc-comment-form.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { SCElement } from './sc-element.js'; const html = String.raw; export class CommentForm extends SCElement { static template() { return html` <textarea></textarea> <button id="btnSend" class="sc-btn">Send</button> `; } static component() { return html` <sc-comment-form> ${this.template()} </sc-comment-form> `; } connectedCallback() { this.btnSend = this.querySelector('#btnSend'); this.textarea = this.querySelector('textarea'); this.btnSend.addEventListener('click', e => { const text = this.textarea.value; const detail = { text }; const event = new CustomEvent('comment-sent', { detail }); this.dispatchEvent(event); this.textarea.value = ''; }); } } <|start_filename|>firebase-firestore-comments/src/components/sc-element.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // are you node? // yah // umm... use this HTMLElement class I made // okay... sure? // are you browser? // yah // umm... use your HTMLElement class // okay... I was gonna do that anyways? thx? let _HTMLElement; if(typeof process !== 'undefined') { _HTMLElement = class HTMLElement { } } else { _HTMLElement = HTMLElement; } export class SCElement extends _HTMLElement { } <|start_filename|>web-workers/worker.js<|end_filename|> /* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Handles incoming messages in the web worker. * In this case: increases each pixel's red color by 20%. * @param {!Object} d Incoming data. */ addEventListener('message', (d) => { const imageData = d.data; const w = imageData.width; const h = imageData.height; const data = imageData.data; // Iterate pixel rows and columns to change red color of each. for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { let index = (x + (y * w)) * 4; data[index] = data[index] * 1.2; } } postMessage(imageData, [imageData.data.buffer]) }); <|start_filename|>stream-progress/third_party/transformstream.js<|end_filename|> // Methods on the transform stream controller object export function TransformStreamCloseReadable(transformStream) { // console.log('TransformStreamCloseReadable()'); if (transformStream._errored === true) { throw new TypeError('TransformStream is already errored'); } if (transformStream._readableClosed === true) { throw new TypeError('Readable side is already closed'); } TransformStreamCloseReadableInternal(transformStream); } export function TransformStreamEnqueueToReadable(transformStream, chunk) { // console.log('TransformStreamEnqueueToReadable()'); if (transformStream._errored === true) { throw new TypeError('TransformStream is already errored'); } if (transformStream._readableClosed === true) { throw new TypeError('Readable side is already closed'); } // We throttle transformer.transform invocation based on the backpressure of the ReadableStream, but we still // accept TransformStreamEnqueueToReadable() calls. const controller = transformStream._readableController; try { ReadableStreamDefaultControllerEnqueue(controller, chunk); } catch (e) { // This happens when readableStrategy.size() throws. // The ReadableStream has already errored itself. transformStream._readableClosed = true; TransformStreamErrorIfNeeded(transformStream, e); throw transformStream._storedError; } const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); const maybeBackpressure = desiredSize <= 0; if (maybeBackpressure === true && transformStream._backpressure === false) { // This allows pull() again. When desiredSize is 0, it's possible that a pull() will happen immediately (but // asynchronously) after this because of pending read()s and set _backpressure back to false. // // If pull() could be called from inside enqueue(), then this logic would be wrong. This cannot happen // because there is always a promise pending from start() or pull() when _backpressure is false. TransformStreamSetBackpressure(transformStream, true); } } export function TransformStreamError(transformStream, e) { if (transformStream._errored === true) { throw new TypeError('TransformStream is already errored'); } TransformStreamErrorInternal(transformStream, e); } // Abstract operations. export function TransformStreamCloseReadableInternal(transformStream) { assert(transformStream._errored === false); assert(transformStream._readableClosed === false); try { ReadableStreamDefaultControllerClose(transformStream._readableController); } catch (e) { assert(false); } transformStream._readableClosed = true; } export function TransformStreamErrorIfNeeded(transformStream, e) { if (transformStream._errored === false) { TransformStreamErrorInternal(transformStream, e); } } export function TransformStreamErrorInternal(transformStream, e) { // console.log('TransformStreamErrorInternal()'); assert(transformStream._errored === false); transformStream._errored = true; transformStream._storedError = e; if (transformStream._writableDone === false) { WritableStreamDefaultControllerError(transformStream._writableController, e); } if (transformStream._readableClosed === false) { ReadableStreamDefaultControllerError(transformStream._readableController, e); } } // Used for preventing the next write() call on TransformStreamSink until there // is no longer backpressure. export function TransformStreamReadableReadyPromise(transformStream) { assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized'); if (transformStream._backpressure === false) { return Promise.resolve(); } assert(transformStream._backpressure === true, '_backpressure should have been initialized'); return transformStream._backpressureChangePromise; } export function TransformStreamSetBackpressure(transformStream, backpressure) { // console.log(`TransformStreamSetBackpressure(${backpressure})`); // Passes also when called during construction. assert(transformStream._backpressure !== backpressure, 'TransformStreamSetBackpressure() should be called only when backpressure is changed'); if (transformStream._backpressureChangePromise !== undefined) { // The fulfillment value is just for a sanity check. transformStream._backpressureChangePromise_resolve(backpressure); } transformStream._backpressureChangePromise = new Promise(resolve => { transformStream._backpressureChangePromise_resolve = resolve; }); transformStream._backpressureChangePromise.then(resolution => { assert(resolution !== backpressure, '_backpressureChangePromise should be fulfilled only when backpressure is changed'); }); transformStream._backpressure = backpressure; } export function TransformStreamDefaultTransform(chunk, transformStreamController) { const transformStream = transformStreamController._controlledTransformStream; TransformStreamEnqueueToReadable(transformStream, chunk); return Promise.resolve(); } export function TransformStreamTransform(transformStream, chunk) { // console.log('TransformStreamTransform()'); assert(transformStream._errored === false); assert(transformStream._transforming === false); assert(transformStream._backpressure === false); transformStream._transforming = true; const transformer = transformStream._transformer; const controller = transformStream._transformStreamController; const transformPromise = PromiseInvokeOrPerformFallback(transformer, 'transform', [chunk, controller], TransformStreamDefaultTransform, [chunk, controller]); return transformPromise.then( () => { transformStream._transforming = false; return TransformStreamReadableReadyPromise(transformStream); }, e => { TransformStreamErrorIfNeeded(transformStream, e); return Promise.reject(e); }); } export function IsTransformStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { return false; } return true; } export function IsTransformStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { return false; } return true; } export class TransformStreamSink { constructor(transformStream, startPromise) { this._transformStream = transformStream; this._startPromise = startPromise; } start(c) { const transformStream = this._transformStream; transformStream._writableController = c; return this._startPromise.then(() => TransformStreamReadableReadyPromise(transformStream)); } write(chunk) { // console.log('TransformStreamSink.write()'); const transformStream = this._transformStream; return TransformStreamTransform(transformStream, chunk); } abort() { const transformStream = this._transformStream; transformStream._writableDone = true; TransformStreamErrorInternal(transformStream, new TypeError('Writable side aborted')); } close() { // console.log('TransformStreamSink.close()'); const transformStream = this._transformStream; assert(transformStream._transforming === false); transformStream._writableDone = true; const flushPromise = PromiseInvokeOrNoop(transformStream._transformer, 'flush', [transformStream._transformStreamController]); // Return a promise that is fulfilled with undefined on success. return flushPromise.then(() => { if (transformStream._errored === true) { return Promise.reject(transformStream._storedError); } if (transformStream._readableClosed === false) { TransformStreamCloseReadableInternal(transformStream); } return Promise.resolve(); }).catch(r => { TransformStreamErrorIfNeeded(transformStream, r); return Promise.reject(transformStream._storedError); }); } } export class TransformStreamSource { constructor(transformStream, startPromise) { this._transformStream = transformStream; this._startPromise = startPromise; } start(c) { const transformStream = this._transformStream; transformStream._readableController = c; return this._startPromise.then(() => { // Prevent the first pull() call until there is backpressure. assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized'); if (transformStream._backpressure === true) { return Promise.resolve(); } assert(transformStream._backpressure === false, '_backpressure should have been initialized'); return transformStream._backpressureChangePromise; }); } pull() { // console.log('TransformStreamSource.pull()'); const transformStream = this._transformStream; // Invariant. Enforced by the promises returned by start() and pull(). assert(transformStream._backpressure === true, 'pull() should be never called while _backpressure is false'); assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized'); TransformStreamSetBackpressure(transformStream, false); // Prevent the next pull() call until there is backpressure. return transformStream._backpressureChangePromise; } cancel() { const transformStream = this._transformStream; transformStream._readableClosed = true; TransformStreamErrorInternal(transformStream, new TypeError('Readable side canceled')); } } export class TransformStreamDefaultController { constructor(transformStream) { if (IsTransformStream(transformStream) === false) { throw new TypeError('TransformStreamDefaultController can only be ' + 'constructed with a TransformStream instance'); } if (transformStream._transformStreamController !== undefined) { throw new TypeError('TransformStreamDefaultController instances can ' + 'only be created by the TransformStream constructor'); } this._controlledTransformStream = transformStream; } get desiredSize() { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('desiredSize'); } const transformStream = this._controlledTransformStream; const readableController = transformStream._readableController; return ReadableStreamDefaultControllerGetDesiredSize(readableController); } enqueue(chunk) { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('enqueue'); } TransformStreamEnqueueToReadable(this._controlledTransformStream, chunk); } close() { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('close'); } TransformStreamCloseReadable(this._controlledTransformStream); } error(reason) { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('error'); } TransformStreamError(this._controlledTransformStream, reason); } } export class TransformStream { constructor(transformer = {}) { this._transformer = transformer; const { readableStrategy, writableStrategy } = transformer; this._transforming = false; this._errored = false; this._storedError = undefined; this._writableController = undefined; this._readableController = undefined; this._transformStreamController = undefined; this._writableDone = false; this._readableClosed = false; this._backpressure = undefined; this._backpressureChangePromise = undefined; this._backpressureChangePromise_resolve = undefined; this._transformStreamController = new TransformStreamDefaultController(this); let startPromise_resolve; const startPromise = new Promise(resolve => { startPromise_resolve = resolve; }); const source = new TransformStreamSource(this, startPromise); this._readable = new ReadableStream(source, readableStrategy); const sink = new TransformStreamSink(this, startPromise); this._writable = new WritableStream(sink, writableStrategy); assert(this._writableController !== undefined); assert(this._readableController !== undefined); const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(this._readableController); // Set _backpressure based on desiredSize. As there is no read() at this point, we can just interpret // desiredSize being non-positive as backpressure. TransformStreamSetBackpressure(this, desiredSize <= 0); const transformStream = this; const startResult = InvokeOrNoop(transformer, 'start', [transformStream._transformStreamController]); startPromise_resolve(startResult); startPromise.catch(e => { // The underlyingSink and underlyingSource will error the readable and writable ends on their own. if (transformStream._errored === false) { transformStream._errored = true; transformStream._storedError = e; } }); } get readable() { if (IsTransformStream(this) === false) { throw streamBrandCheckException('readable'); } return this._readable; } get writable() { if (IsTransformStream(this) === false) { throw streamBrandCheckException('writable'); } return this._writable; } } // Helper functions for the TransformStreamDefaultController. export function defaultControllerBrandCheckException(name) { return new TypeError( `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); } // Stubs for abstract operations used from ReadableStream and WritableStream. export function ReadableStreamDefaultControllerEnqueue(controller, chunk) { controller.enqueue(chunk); } export function ReadableStreamDefaultControllerGetDesiredSize(controller) { return controller.desiredSize; } export function ReadableStreamDefaultControllerClose(controller) { controller.close(); } export function ReadableStreamDefaultControllerError(controller, e) { controller.error(e); } export function WritableStreamDefaultControllerError(controller, e) { controller.error(e); } // Helper functions for the TransformStream. export function streamBrandCheckException(name) { return new TypeError( `TransformStream.prototype.${name} can only be used on a TransformStream`); } // Copied from helpers.js. export function IsPropertyKey(argument) { return typeof argument === 'string' || typeof argument === 'symbol'; } export function typeIsObject(x) { return (typeof x === 'object' && x !== null) || typeof x === 'function'; } export function Call(F, V, args) { if (typeof F !== 'function') { throw new TypeError('Argument is not a function'); } return Function.prototype.apply.call(F, V, args); } export function InvokeOrNoop(O, P, args) { assert(O !== undefined); assert(IsPropertyKey(P)); assert(Array.isArray(args)); const method = O[P]; if (method === undefined) { return undefined; } return Call(method, O, args); }; export function PromiseInvokeOrNoop(O, P, args) { assert(O !== undefined); assert(IsPropertyKey(P)); assert(Array.isArray(args)); try { return Promise.resolve(InvokeOrNoop(O, P, args)); } catch (returnValueE) { return Promise.reject(returnValueE); } }; export function PromiseInvokeOrPerformFallback(O, P, args, F, argsF) { assert(O !== undefined); assert(IsPropertyKey(P)); assert(Array.isArray(args)); assert(Array.isArray(argsF)); let method; try { method = O[P]; } catch (methodE) { return Promise.reject(methodE); } if (method === undefined) { return F(...argsF); } try { return Promise.resolve(Call(method, O, args)); } catch (e) { return Promise.reject(e); } }; // DIY assert() implementation export function assert(predicate, s) { class TransformStreamInternalLogicError extends Error { constructor(s) { super(s); } } if (!predicate) { console.log(`TransformStream internal logic error: assertion failed: s`); throw new TransformStreamInternalLogicError(s); } } <|start_filename|>lazy-image/static/styles.css<|end_filename|> /** * * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ body { padding: 50px; max-width: 720px; margin: 0 auto; } .spacer { height: 120vh; } img { display: block; width: 100%; } <|start_filename|>firebase-firestore-comments/src/components/sc-login.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const html = String.raw; export class LoginButton extends HTMLElement { static template() { return html` <button id="btnLogin" class="sc-btn">Login</button> `; } connectedCallback() { this.appendChild(template.content.cloneNode(true)); this.auth = firebase.auth(); this.btnLogin = this.querySelector('#btnLogin'); this.auth.onAuthStateChanged(user => { const event = new CustomEvent('on-auth', { detail: user }); this.user = user; this.dispatchEvent(event); }); this.btnLogin.addEventListener('click', e => { const google = new firebase.auth.GoogleAuthProvider(); this.auth.signInWithRedirect(google); }); } } let template = document.createElement('template'); template.innerHTML = LoginButton.template(); <|start_filename|>flip-switch/flip-switch.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* global customElements */ /* eslint-env es6 */ customElements.define('flip-switch', class extends HTMLElement { static get observedAttributes () { return ['color']; } constructor () { super(); const doc = document.currentScript.ownerDocument; const tmpl = doc.querySelector('#fs-tmpl'); this._root = this.attachShadow({mode: 'open'}); this._root.appendChild(tmpl.content.cloneNode(true)); this._elementProxy = document.createElement('div'); } set color (_color) { if (!_color) { return; } // Reset the styles of the element proxy. this._elementProxy.style.color = ''; // Now attempt to set it to the passed value. this._elementProxy.style.color = _color; // If it doesn't hold then the value passed is invalid. if (this._elementProxy.style.color === '') { console.warn(`${_color} is not a real color... WELL DONE.`); return; } this._color = _color; this.style.setProperty('--color', _color); } get color () { return this._color; } set value (_value) { this._value = _value; this._front.querySelector('button').textContent = _value; } get value () { return this._value; } connectedCallback () { this._container = this._root.querySelector('.container'); this._front = this._root.querySelector('.front'); this._back = this._root.querySelector('.back'); this._ripple = this._root.querySelector('.ripple'); this._shadow2px = this._root.querySelector('.shadow2px'); this._shadow12px = this._root.querySelector('.shadow12px'); this.flip = this.flip.bind(this); this._onResize = this._onResize.bind(this); this._onBackButtonClick = this._onBackButtonClick.bind(this); this._onTransitionEnd = this._onTransitionEnd.bind(this); this._onKeyPress = this._onKeyPress.bind(this); if (!this.value) { this.value = 1; } this.color = this.getAttribute('color'); this._addEventListeners(); this._front.inert = false; this._back.inert = true; requestAnimationFrame(_ => { this._onResize(); }); } disconnectedCallback () { this._removeEventListeners(); } attributeChangedCallback (name, oldValue, newValue) { if (name !== 'color') { return; } this.color = newValue; } flip () { this._container.classList.toggle('flipped'); this._ripple.classList.toggle('expanded'); this._shadow2px.classList.toggle('flipped'); this._shadow12px.classList.toggle('flipped'); this.classList.add('modal'); } _addEventListeners () { this._ripple.addEventListener('click', this.flip); this._front.addEventListener('click', this.flip); this._back.addEventListener('click', this._onBackButtonClick); this._container.addEventListener('transitionend', this._onTransitionEnd); this.addEventListener('keydown', this._onKeyPress); window.addEventListener('resize', this._onResize); } _removeEventListeners () { this._ripple.removeEventListener('click', this.flip); this._front.removeEventListener('click', this.flip); this._back.removeEventListener('click', this._onBackButtonClick); this._container.removeEventListener('transitionend', this._onTransitionEnd); this.removeEventListener('keydown', this._onKeyPress); window.removeEventListener('resize', this._onResize); } _onTransitionEnd () { if (this._container.classList.contains('flipped')) { this._front.inert = true; this._back.inert = false; this._back.querySelector(`button:nth-of-type(${this.value})`).focus(); return; } this._front.inert = false; this._back.inert = true; this._front.querySelector('button').focus(); this.classList.remove('modal'); } _onBackButtonClick (evt) { // if this is the back, BAIL. if (evt.target === evt.currentTarget) { return; } this.value = evt.target.textContent; this.flip(); } _onResize () { const position = this.getBoundingClientRect(); const midX = position.left + position.width * 0.5; const midY = position.top + position.height * 0.5; const rX = Math.max(midX, window.innerWidth - midX); const rY = Math.max(midY, window.innerHeight - midY); const radius = Math.sqrt(rX * rX + rY * rY); this._ripple.style.width = `${radius * 2}px`; this._ripple.style.height = `${radius * 2}px`; } _onKeyPress (evt) { if (this._back.hasAttribute('inert')) { return; } if (document.activeElement !== this) { return; } const firstTabStop = this._back.querySelector('button'); const lastTabStop = this._back.querySelector('button:last-of-type'); const deepActive = this._root.activeElement; // Check for TAB key press if (evt.keyCode === 9) { // SHIFT + TAB if (evt.shiftKey) { if (deepActive === firstTabStop) { evt.preventDefault(); lastTabStop.focus(); } // TAB } else if (deepActive === lastTabStop) { evt.preventDefault(); firstTabStop.focus(); } } // ESCAPE if (evt.keyCode === 27) { this.flip(); firstTabStop.focus(); } } }); <|start_filename|>streaming-service-worker/posts/es-modules-in-browsers/meta.json<|end_filename|> { "title": "ECMAScript modules in browsers", "posted": "2017-05-02", "summary": "ES modules are starting to land in browsers! Modules in general are [pretty well documented](https://ponyfoo.com/articles/es6-modules-in-depth), but here are some browser-specific differences…", "description": "ES modules are landing in browsers! Here are the HTML-specific differences you need to be aware of." } <|start_filename|>firebase-firestore-comments/src/components/sc-comment-list.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { SCElement } from './sc-element.js'; import { Comment } from './sc-comment.js'; const html = String.raw; export class CommentList extends SCElement { static component(state) { return html` <sc-comment-list> ${state} </sc-comment-list> `; } connectedCallback() { this.commentsRef = firebase.firestore().collection('comments'); this.commentsRef.orderBy('timestamp').onSnapshot(snap => { snap.docChanges.forEach(change => { const elInDOM = this.querySelector(`#_${change.doc.id}`); switch(change.type) { case 'added': if(elInDOM) { return; } this.addComment(change.doc); break; case 'removed': elInDOM.remove(); break; } }); }); } addComment(doc) { const element = document.createElement('sc-comment'); element.id = `_${doc.id}`; element.innerHTML = Comment.template(doc.data()); this.appendChild(element); } } <|start_filename|>firebase-firestore-comments/src/client/index.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LoginButton } from './components/sc-login.js'; import { CommentForm } from './components/sc-comment-form.js'; import { CommentList } from './components/sc-comment-list.js'; import { Comment } from './components/sc-comment.js'; customElements.define('sc-login', LoginButton); customElements.define('sc-comment-form', CommentForm); customElements.define('sc-comment-list', CommentList); customElements.define('sc-comment', Comment); const scLogin = document.querySelector('sc-login'); const scForm = document.querySelector('sc-comment-form'); scForm.addEventListener('comment-sent', e => { const commentsRef = firebase.firestore().collection('comments'); commentsRef.add({ text: e.detail.text, photoUrl: scLogin.user.photoURL, authorName: scLogin.user.displayName, timestamp: firebase.firestore.FieldValue.serverTimestamp() }); }); scLogin.addEventListener('on-auth', e => { if(e.detail) { scLogin.classList.add('sc-hidden'); } else { scLogin.classList.remove('sc-hidden'); } }); <|start_filename|>streaming-service-worker/server/routes.js<|end_filename|> const util = require('util'); const fs = require('fs'); const crypto = require('crypto'); const staticModule = require('static-module'); const readFile = util.promisify(fs.readFile); const readdir = util.promisify(fs.readdir); const stat = util.promisify(fs.stat); const marked = require('./marked'); const rev = require('./rev'); const Error404 = require('./error404'); const express = require('express'); const wrap = fn => (...args) => fn(...args).catch(args[2]); const readFileOr404 = (...args) => readFile(...args).catch(err => { if (err.code == 'ENOENT') throw new Error404; throw err; }); const router = express.Router(); router.use('/static-rev', express.static(__dirname + '/../static-rev', { maxAge: '1y' })); router.use('/favicon.ico', express.static(__dirname + '/../static/favicon.ico', { maxAge: '1y' })); // Set default caching headers router.use((req, res, next) => { res.set('Cache-Control', 'no-cache'); next(); }); router.get('/sw.js', (req, res) => { const input = fs.createReadStream(`${__dirname}/../client/sw.js`); const toCache = [ '/static/offline-inc.html', '/static/shell-start.html', '/static/shell-end.html', '/static/css/all.css', '/static/imgs/me.jpg', '/static/css/imgs/social-icons.png' ].map(u => rev.get(u)); const hash = crypto.createHash('md5'); for (const url in toCache) hash.update(url); const version = hash.digest('hex').slice(0, 10); res.set('Content-Type', 'application/javascript'); input.pipe( staticModule({ 'static-to-cache': () => JSON.stringify(toCache, null, ' '), 'static-rev-get': u => JSON.stringify(rev.get(u)), 'static-version': () => JSON.stringify(version) }) ).pipe(res); }); router.get('/', wrap(async(req, res) => { const dir = `${__dirname}/../posts`; const slugs = await readdir(dir); const posts = (await Promise.all( slugs.map(async slug => { const itemDir = `${dir}/${slug}`; if (!(await stat(itemDir)).isDirectory()) return null; const meta = JSON.parse(await readFile(`${itemDir}/meta.json`, 'utf-8')); return Object.assign({}, meta, { slug, summary: marked(meta.summary) }); }) )).filter(i => i).sort((a, b) => a.posted > b.posted ? -1 : 1); res.render('index', {posts}); })); router.get('/who/', (req, res) => res.render('who')); router.get('/:year(\\d{4})/:slug/:include(include)?', wrap(async (req, res) => { const dir = `${__dirname}/../posts/${req.params.slug}`; const contentPromise = readFileOr404(`${dir}/content.md`, 'utf-8'); const meta = JSON.parse(await readFileOr404(`${dir}/meta.json`, 'utf-8')); if (new Date(meta.posted).getFullYear() != Number(req.params.year)) { throw new Error404(); } const template = req.params.include ? 'post-inc' : 'post'; res.render(template, { meta, year: req.params.year, slug: req.params.slug, content: rev.replace(marked(await contentPromise)) }); })); // Handle errors router.use((err, req, res, next) => { if (!(err instanceof Error404)) { next(err) return; } res.status(404).render('404'); }); module.exports = router; <|start_filename|>stream-progress/stream.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {TransformStream} from './third_party/transformstream.js'; class JSONTransformer { constructor() { this.chunks = []; this.depth = 0; this.inString = false; this.skipNext = false; this.decoder = new TextDecoder(); } start() {} flush() {} transform(chunk, controller) { for(let i = 0; i < chunk.length; i++) { if(this.skipNext) { this.skipNext = false; continue; } const byte = chunk[i]; const char = String.fromCharCode(byte); switch(char) { case '{': if(this.inString) continue; this.depth++; break; case '}': if(this.inString) continue; this.depth--; if(this.depth === 0) { const tail = new Uint8Array(chunk.buffer, chunk.byteOffset, i + 1); chunk = new Uint8Array(chunk.buffer, chunk.byteOffset + i + 1); this.chunks.push(tail); const jsonStr = this.chunks.reduce((str, chunk) => str + this.decoder.decode(chunk, {stream: true}), ''); controller.enqueue(jsonStr); this.chunks.length = 0; i = -1; } break; case '"': this.inString = !this.inString; break; case '\\': this.skipNext = true; break; } } this.chunks.push(chunk); } } const dial = document.querySelector('sc-dial'); fetch('./tweets.json') .then(async resp => { if (resp.status != 200) { //Don't try to parse non JSON responses, such as a 404 error... return; } const bytesTotal = parseInt(resp.headers.get('Content-Length'), 10); const jsonStream = resp.body.pipeThrough(new TransformStream(new JSONTransformer())); const reader = jsonStream.getReader(); let bytesCounted = 0; while(true) { const {value, done} = await reader.read(); if(done) { dial.percentage = 1; return; } bytesCounted += value.length; dial.percentage = bytesCounted / bytesTotal; } }); <|start_filename|>stream-progress/dial.js<|end_filename|> /** * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class SCDial extends HTMLElement { static get SIZE () { return 256; } static get NINETY_DEGREES () { return Math.PI * 0.5; } static get TAU () { return Math.PI * 2; } constructor () { super(); this._canvas = document.createElement('canvas'); this._ctx = this._canvas.getContext('2d'); this._canvas.width = SCDial.SIZE; this._canvas.height = SCDial.SIZE; this._percentage = 0; } set percentage (_percentage) { if (Number.isNaN(_percentage) || _percentage < 0 || _percentage > 1) { throw new Error('Percentage must be a number between 0 and 1.'); } this._percentage = _percentage; this.draw(); } get percentage () { return this._percentage; } draw () { const mid = SCDial.SIZE * 0.5; // Since the coordinate system is about to get changed, // save the context (and restore it when we're done later). this._ctx.save(); // Clear everything. this._ctx.clearRect(0, 0, SCDial.SIZE, SCDial.SIZE); // Rotate the coordinate system. this._ctx.translate(mid, mid); this._ctx.rotate(-SCDial.NINETY_DEGREES); this._ctx.translate(-mid, -mid); // Outer arc. this._ctx.beginPath(); this._ctx.moveTo(mid, mid); this._ctx.arc(mid, mid, mid, 0, this._percentage * SCDial.TAU); this._ctx.closePath(); this._ctx.fillStyle = `rgb(${Math.round(this._percentage * 255)}, 0, 128)`; this._ctx.fill(); // Inner arc. this._ctx.beginPath(); this._ctx.moveTo(mid, mid); this._ctx.arc(mid, mid, mid * 0.8, 0, SCDial.TAU); this._ctx.closePath(); this._ctx.fillStyle = '#FFF'; this._ctx.fill(); this._ctx.restore(); // Number Label. this._ctx.fillStyle = '#333'; this._ctx.font = `${SCDial.SIZE * 0.25}px Arial`; this._ctx.textAlign = 'center'; this._ctx.textBaseline = 'middle'; this._ctx.fillText(Math.round(this._percentage * 100), mid, mid - 14); // Text label. this._ctx.fillStyle = '#777'; this._ctx.font = `${SCDial.SIZE * 0.06}px Arial`; this._ctx.fillText('PERCENT', mid, mid + 26); } connectedCallback () { this.appendChild(this._canvas); this.draw(); } } customElements.define('sc-dial', SCDial); <|start_filename|>lazy-image/index.js<|end_filename|> /** * * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const Express = require('express'); const fs = require('fs'); const {promisify} = require('util'); const readFile = promisify(fs.readFile); const im = require('gm').subClass({imageMagick: true}); const app = Express(); const thumbSize = 16; app.get('/', async (req, res) => { let filepath = req.url; if(filepath.endsWith('/')) filepath += 'index.html'; const buffer = await readFile('./static/'+filepath); const content = buffer.toString(); const newContent = await Promise.all( content .split(/(<sc-img[^>]+><\/sc-img>)/) .map(async item => { if(!item.startsWith('<sc-img')) return item; const src = /src="([^"]+)"/.exec(item)[1]; const img = im('./static/' + src); const sizeFunc = promisify(img.size.bind(img)); const {width, height} = await sizeFunc(); const thumbFunc = promisify(img.resize(thumbSize, thumbSize).toBuffer.bind(img)); const thumb = await thumbFunc('PNG'); const thumbURL = `data:image/png;base64,${thumb.toString('base64')}`; return item.replace('></sc-img>', `style="padding-top: ${height/width*100}%; background-image: url(${thumbURL});"></sc-img>`); }) ); res.send(newContent.join('')); }); app.use(Express.static('static')); app.listen(8080); <|start_filename|>service-worker/app/sw.js<|end_filename|> // Load our templating engine importScripts('/node_modules/dot/doT.min.js'); doT.templateSettings.strip = false; const VERSION = '1'; // All the assets that don’t change and our templates. // We are pretending that our actual page content is // dynamic and can’t be cached statically. const ASSETS = [ '/static/app.js', '/static/sc-view.js', '/static/sc-router.js', '/static/superstyles.css', '/static/images/spinner.png', '/header.partial.html', '/footer.partial.html' ]; // On install, load all our assets into a 'static' cache self.oninstall = event => event.waitUntil(async function () { const cache = await caches.open('static'); await cache.addAll(ASSETS); return self.skipWaiting(); }()); self.onactivate = event => event.waitUntil(self.clients.claim()); // Matches paths like `/`, `/index.html`, `/about/` or `/about/index.html`. // So when this regexp matches, we know we have to _build_ a response. const toplevelSection = /([^/]*)(\/|\/index.html)$/; self.onfetch = event => { // Parse the request URL so we can separate domain, path and query. event.parsedUrl = new URL(event.request.url); const matches = toplevelSection.exec(event.parsedUrl.pathname); // If this regexp matches, build a response if (matches) { event.request.item = matches[1]; return buildSite(event); // If it’s a request for /static/, just go to cache } else if (event.parsedUrl.pathname.startsWith('/static/')) { event.respondWith(caches.match(event.request)); return; } // Otherwise, use our dynamic caching strategy staleWhileRevalidate(event); }; function buildSite(event) { // Check if we are supposed to build a partial response or a full document const isPartial = event.parsedUrl.searchParams.get('partial') !== null; // But either case, only request the partial of the content, as we // already have header and footer in our cache. event.parsedUrl.searchParams.set('partial', ''); // This is a little hack as you can’t call waitUntil inside respondWith // or vice versa. let myWaitUntil; event.waitUntil(new Promise(resolve => { myWaitUntil = resolve; })); event.respondWith(async function () { // Get our 3 fragments for the response. Header, content and footer. const files = await Promise.all([ !isPartial ? caches.match('/header.partial.html') : new Response(null), staleWhileRevalidateWrapper(event.parsedUrl.toString(), myWaitUntil), !isPartial ? caches.match('/footer.partial.html') : new Response(null) ]); // All of those are Response objects. Grab the file contents as strings. const contents = await Promise.all(files.map(f => f.text())); // ... and concatenate them. const content = contents.join(''); // Compile the template const template = doT.template(content); // ... and execute the template as the body of the response return new Response(template(event.request), {headers: {'Content-Type': 'text/html'}}); }()); } // This function builds a temporary pseudo-event object so we can // grab the response as the value of the returned promise. function staleWhileRevalidateWrapper(request, waitUntil) { return new Promise(resolve => { staleWhileRevalidate({ request, respondWith: resolve, waitUntil }) }); } // staleWhileRevalidate is a caching strategy. It responds with // whatever it got cached (if anything), while updating the cache // in the background. function staleWhileRevalidate(event) { const fetchedVersion = fetch(event.request); // Since we _might_ be responding with the fetched response // and also using it to populate the cache, we need to make a copy. const fetchedCopy = fetchedVersion.then(response => response.clone()); const cachedVersion = caches.match(event.request); event.respondWith(async function () { try { // Respond with whatever is ready first, fetched or cached version. // Since fetch() will reject when offline, resolve to cachedVersion // on reject so we always resolve to something. const response = await Promise.race([ fetchedVersion.catch(_ => cachedVersion), cachedVersion ]); // However, caches.match() will resolve to `undefined` if there’s // nothing in cache. If that’s the case, wait for the network response. if (!response) { return await fetchedVersion; } return response; } catch(_) { // If nothing returns a valid response (rejects or is undefined), // we just return 404. return new Response(null, {status: 404}); } }()); event.waitUntil(async function () { try { const response = await fetchedCopy; const cache = await caches.open('dynamic'); return cache.put(event.request, response); } catch(_) {/* eat errors */} }()); } <|start_filename|>firebase-firestore-comments/package.json<|end_filename|> { "name": "supercharged", "version": "1.0.0", "main": "index.js", "license": "MIT", "scripts": { "build": "yarn build:client && yarn build:server && yarn build:components && yarn babel:components", "build:server": "cpx src/server/**/* functions", "build:client": "cpx src/client/**/* public", "build:components": "cpx src/components/**/* public/components", "babel:components": "babel src/components -d functions/components", "serve": "firebase serve --only functions,hosting" }, "dependencies": { "express": "^4.16.2", "firebase": "^4.9.0", "firebase-functions": "^0.8.1" }, "devDependencies": { "babel-cli": "^6.26.0", "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", "cpx": "^1.5.0", "firebase-tools": "~3.17.4" } } <|start_filename|>animated-blur/scripts/animated_blur.js<|end_filename|> /** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ class AnimatedBlur { constructor(name, element, params) { this.name = name; this.element = element; this.num = params.steps; this.duration = params.duration; this.initialized = false; element.classList.add('animated-blur'); } static get BLUR_MODE() { return { BLUR: 1, STANDBY: 0, UNBLUR: -1 }; } static getBlurStyle() { var html = 'html { ' + ' -webkit-text-size-adjust: none; /* Never autoresize text */ ' + ' -moz-text-size-adjust: none; ' + ' -ms-text-size-adjust: none; ' + '} '; var bodyStyle = '.bodyStyle { ' + // Necessary for all browers ' min-width: -webkit-min-content; ' + ' min-width: -moz-min-content; ' + ' min-width: min-content; ' + '} '; var animatedBlur = '.animated-blur { ' + ' position: relative; ' + '} '; var clonedElement = '.clonedElement { ' + ' position: absolute; ' + ' display: block; ' + ' margin: 0 auto; ' + ' pointer-events: none; ' + ' width: 100%; ' + ' height: 100%; ' + '} '; var composited = '.composited { ' + ' -webkit-transform: translateZ(0); ' + ' -moz-transform: translateZ(0); ' + ' -ms-transform: translateZ(0); ' + ' -o-transform: translateZ(0); ' + ' transform: translateZ(0); ' + '} '; return [html, bodyStyle, animatedBlur, composited, clonedElement]; } static addStyle() { var rules = AnimatedBlur.getBlurStyle(); if (document.styleSheets && document.styleSheets.length) { for (var i = 0; i < rules.length; ++i) { document.getElementsByTagName('style')[0].innerHTML = rules[i] + '\n' + document.getElementsByTagName('style')[0].innerHTML; } } else { var s = document.createElement('style'); for (var i = 0; i < rules.length; ++i) { s.innerHTML += rules[i]; } document.getElementsByTagName('head')[0].appendChild(s); } } calculateMargin() { this.marginTop = parseInt(window.getComputedStyle(this.element).marginTop); this.marginLeft = parseInt(window.getComputedStyle(this.element).marginLeft); if (this.marginTop == 0) { var header = 'p, pre, h1, h2, h3, h4, h5, h6'; var descendants = this.element.querySelectorAll(header); for (var i = 0; i < descendants.length; ++i) { if (window.getComputedStyle(descendants[i]).marginTop != '0px') { this.marginTop = parseInt(window.getComputedStyle(descendants[i]).marginTop); break; } } } } // Create template for shadow dom. It includes the element to be animated // and its style. createTemplate() { var template = document.createElement('Template'); template.id = this.name + '-template'; var styles = document.getElementsByTagName('style'); for (var i = 0; i < styles.length; ++i) { template.innerHTML = styles[i].outerHTML; } template.innerHTML += this.element.outerHTML; document.body.appendChild(template); } setupKeyFrames() { for (var id = 0; id < this.num; ++id) { var keyframes = '@keyframes ' + this.name + '-b' + (id + 1) + '-anim {'; for (var i = 0; i <= this.num; ++i) { // Use 0.99 otherwise Safari would have repainting // at the end of animation var opacity = (i == id || i == id + 1) ? 0.99 : 0.01; keyframes += (i * 100 / this.num) + '% { opacity: ' + opacity + '; }'; } keyframes += '}'; if (document.styleSheets && document.styleSheets.length) { document.styleSheets[0].insertRule(keyframes, 0); } else { var s = document.createElement('style'); s.innerHTML = keyframes; document.getElementsByTagName('head')[0].appendChild(s); } } } cloneElements() { var width = this.element.clientWidth; var height = this.element.clientHeight; var container = document.createElement('div'); container.id = this.name + '-clonedElement'; container.style.top = this.element.offsetTop - this.marginTop + 'px'; container.style.left = this.element.offsetLeft - this.marginLeft + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; container.classList.add('composited'); container.classList.add('clonedElement'); this.element.parentNode.insertBefore(container, this.element.nextSibling); var filterStdDev = 2; for (var i = 1; i <= this.num; ++i) { var div = document.createElement('div'); div.id = this.name + '-b' + i; div.classList.add('composited'); div.classList.add('clonedElement'); div.style.opacity = 0.01; var template = document.querySelector('#' + this.name + '-template'); var clone = document.importNode(template.content, true); if (i == 1) { clone.childNodes[1].style.filter = 'blur(0px)'; } else { clone.childNodes[1].style.filter = 'blur(' + filterStdDev + 'px)'; filterStdDev *= 2; } const supportsShadowDOMV1 = !!HTMLElement.prototype.attachShadow; if (supportsShadowDOMV1) { var shadowRoot = div.attachShadow({ mode: 'closed' }); shadowRoot.appendChild(clone); } else { div.appendChild(clone); } container.appendChild(div); } } update() { if (this.initialized) return; document.body.classList.add('bodyStyle'); this.calculateMargin(); this.setupKeyFrames(); this.createTemplate(); this.cloneElements(); // Create a compositing layer for the animated blur element after it // gets cloned. this.element.classList.add('composited'); this.initialized = true; } play(mode) { if (mode == AnimatedBlur.BLUR_MODE.STANDBY) return; for (var i = 0; i < this.num; ++i) { var div = mode > 0 ? document.body.querySelector('#' + this.name + '-b' + (i + 1)) : document.body.querySelector('#' + this.name + '-b' + (this.num - i)); div.style.animation = this.name + '-b' + (i + 1) + '-anim ' + this.duration + 'ms forwards linear'; // opacity 1 would cause delay on Safari. div.style.opacity = 0.99; } if (mode == AnimatedBlur.BLUR_MODE.UNBLUR) { this.element.style.animation = this.name + '-b' + this.num + '-anim ' + this.duration + 'ms forwards linear'; } else { this.element.style.animation = this.name + '-b1-anim ' + this.duration + 'ms forwards linear'; } } dispose() { document.getElementById(this.name + '-clonedElement').remove(); document.getElementById(this.name + '-template').remove(); this.element.classList.remove('composited'); this.element.style.removeProperty('animation'); if (this.element.style.length == 0) { this.element.removeAttribute('style'); } this.initialized = false; } resize() { var blur = 'div[id^="' + this.name + '"][id$="clonedElement"]'; var elements = document.body.querySelectorAll(blur); for (var i = 0; i < elements.length; ++i) { elements[i].style.top = this.element.offsetTop - this.marginTop + 'px'; elements[i].style.left = this.element.offsetLeft - this.marginLeft + 'px'; elements[i].style.width = this.element.clientWidth + 'px'; elements[i].style.height = this.element.clientHeight + 'px'; } } }; AnimatedBlur.addStyle(); <|start_filename|>firebase-firestore-comments/src/components/sc-comment.js<|end_filename|> /** * * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { SCElement } from './sc-element.js'; const html = String.raw; export class Comment extends SCElement { static template(state) { return html` <div class="sc-author"> <img class="sc-circle-avatar" src="${state.photoUrl}" alt="Profile Photo"> <div class="sc-author-name">${state.authorName}</div> </div> <div class="sc-comment-text">${state.text}</div> `; } static component(state, id) { return html` <sc-comment id="_${id}"> ${this.template(state)} </sc-comment> `; } } <|start_filename|>code-splitting/app/static/contact.js<|end_filename|> import '/static/sc-view.js'; import '/static/sc-router.js'; import '/static/app.js'; import '/static/database.js'; <|start_filename|>streaming-service-worker/server/index.js<|end_filename|> const express = require('express'); const del = require('del'); const nunjucks = require('nunjucks'); const app = express(); const rev = require('./rev'); app.set('view engine', 'njk'); const nunjucksEnv = nunjucks.configure(__dirname + '/../templates', { watch: true, express: app }); require('nunjucks-date-filter').install(nunjucksEnv); nunjucksEnv.addFilter('rev', str => rev.get(str)); app.use(require('./routes')); // Rev static files (async function() { const staticRevPath = `${__dirname}/../static-rev`; await del(staticRevPath); await rev.copyAndRev(`${__dirname}/../static`, '**', staticRevPath); await rev.addAndRev('offline-inc.html', staticRevPath, nunjucksEnv.render('offline-inc.njk')); const shell = nunjucksEnv.render('shell.njk'); const splitAt = '<!-- content go here -->'; await rev.addAndRev('shell-start.html', staticRevPath, shell.slice(0, shell.indexOf(splitAt))); await rev.addAndRev('shell-end.html', staticRevPath, shell.slice(shell.indexOf(splitAt) + splitAt.length)); await rev.replaceInFiles(`${__dirname}/../static-rev/**/*.css`); app.listen(3000, () => { console.log('Example app listening on port 3000!'); }); })(); <|start_filename|>code-splitting/build.js<|end_filename|> /** * * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const xml2js = require('xml2js'); const {promisify} = require('util'); // Versprechifizierung const {URL} = require('url'); const path = require('path'); const babel = require('babel-core'); const parseXML = promisify(xml2js.parseString); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); async function build() { const entryPoints = await extractEntryPoints(); const sections = entryPoints .map(entryPoint => path.basename(entryPoint, path.extname(entryPoint))) .map(entryPoint => entryPoint === '' ? 'index' : entryPoint); const depTrees = await Promise.all(sections.map(section => buildDependencyTree(`./app/static/${section}.js`))); const commonDependencies = findCommonDeps(depTrees); const sharedJs = await bundle( commonDependencies.map(dep => `import '${dep}';`).join('\n') ); await writeFile('./app/static/_shared.js', sharedJs); await Promise.all( sections .map(section => rewrite(section, commonDependencies)) ); } async function rewrite(section, commonDependencies) { let oldCode = await readFile(`./app/static/${section}.js`); oldCode = oldCode.toString('utf-8'); const plugin = { visitor: { ImportDeclaration(decl) { const importedFile = decl.node.source.value; if(commonDependencies.includes(importedFile)) decl.remove(); } } }; let {code} = babel.transform(oldCode, {plugins: [plugin]}); code = `import '/static/_shared.js';\n${code}`; await writeFile(`./app/static/_${section}.js`, code); } async function bundle(oldCode) { let newCode = []; const plugin = { visitor: { ImportDeclaration(decl) { const importedFile = decl.node.source.value; newCode.push((async function() { return await bundle(await readFile(`./app/${importedFile}`)); })()); decl.remove(); } } }; const {code} = babel.transform(oldCode, {plugins: [plugin]}); newCode.push(code); return flatten(await Promise.all(newCode)).join('\n'); } function findCommonDeps(depTrees) { const depSet = new Set(); depTrees.forEach(depTree => { depTree.forEach(dep => depSet.add(dep)); }); return Array.from(depSet) .filter(dep => { return depTrees.every(depTree => depTree.includes(dep)) }); } async function buildDependencyTree(file) { let code = await readFile(file); code = code.toString('utf-8'); let dep = []; const plugin = { visitor: { ImportDeclaration(decl) { const importedFile = decl.node.source.value; dep.push((async function() { return await buildDependencyTree(`./app/${importedFile}`); })()); dep.push(importedFile); } } } babel.transform(code, {plugins: [plugin]}); return flatten(await Promise.all(dep)); } async function extractEntryPoints() { let sitemapString = await readFile('./app/sitemap.xml'); sitemapString = sitemapString.toString('utf-8'); const sitemap = await parseXML(sitemapString); return sitemap.urlset.url .map(url => url.loc[0]) .map(url => new URL(url).pathname); } function flatten(arr) { return Array.prototype.concat.apply([], arr); } build() .catch(err => console.error(err.stack)); <|start_filename|>code-splitting/app/static/videoencoder.js<|end_filename|> import '/static/mp4.js'; <|start_filename|>streaming-service-worker/posts/combining-fonts/meta.json<|end_filename|> { "title": "Combining fonts", "posted": "2017-04-28", "summary": "I love the font [Just Another Hand](https://fonts.google.com/specimen/Just+Another+Hand), but I don't like the positioning of the hyphen & equals glyphs. Thankfully I can use CSS fonts to fix it!", "description": "Using @font-face to replace glyphs of one font with another." }
zjsuperman1987/ui-element-samples
<|start_filename|>MyGazeEstimation.cc<|end_filename|> #include <GazeEstimation.h> #include <RotationHelpers.h> #include <opencv2/core/core.hpp> #include <Eigen/Core> #include <Eigen/Geometry> #include <LandmarkDetectorFunc.h> #include <LandmarkDetectorModel.h> #include "MyGazeEstimation.h" using namespace Eigen; void MyGazeEstimation::EstimateGaze(const LandmarkDetector::CLNF& clnf, cv::Point3f& gaze, float fx, float fy, float cx, float cy, bool is_left) { cv::Vec6f head = LandmarkDetector::GetPose(clnf, fx, fy, cx, cy); cv::Matx33f rot = Utilities::Euler2RotationMatrix(cv::Vec3f(head(3), head(4), head(5))); int part = -1; for (size_t i = 0; i < clnf.hierarchical_models.size(); i++) { if (is_left) { if (clnf.hierarchical_model_names[i] == "left_eye_28") { part = i; } } else { if (clnf.hierarchical_model_names[i] == "right_eye_28") { part = i; } } } if (part == -1) { gaze = cv::Point3f(0, 0, 0); return; } cv::Mat eye_landmarks = clnf.hierarchical_models[part].GetShape(fx, fy, cx, cy); cv::Point3f pupil = GazeAnalysis::GetPupilPosition(eye_landmarks); cv::Point3f ray_dir = pupil / norm(pupil); cv::Mat face_landmarks = clnf.GetShape(fx, fy, cx, cy).t(); int eye_index = 1; if (is_left) { eye_index = 0; } cv::Mat offset_mat = (cv::Mat_<float>(3, 1) << 0.0, -3.5, 7.0); cv::Mat offset_mat_t = (cv::Mat(rot) * offset_mat ).t(); cv::Point3f eye_offset = cv::Point3f(offset_mat_t); cv::Mat mat_l = face_landmarks.row(36 + eye_index * 6); cv::Mat mat_r = face_landmarks.row(39 + eye_index * 6); cv::Point3f lid_l = cv::Point3f(mat_l); cv::Point3f lid_r = cv::Point3f(mat_r); cv::Point3f eye_center = (lid_l + lid_r) / 2.0; cv::Point3f eyeball_center = eye_center + eye_offset; // 2Dに再投影 float d = eye_center.z; float l2dx = lid_l.x * d / lid_l.z; float l2dy = lid_l.y * d / lid_l.z; float r2dx = lid_r.x * d / lid_r.z; float r2dy = lid_r.y * d / lid_r.z; float p2dx = pupil.x * d / pupil.z; float p2dy = pupil.y * d / pupil.z; float t = (p2dx - r2dx) / (l2dx - r2dx); if (t < 0.0) t = 0.0; else if (t > 1.0) t = 1.0; float newZ = lid_r.z + (lid_l.z - lid_r.z) * t; // 新しいzで、黒目の中心位置を再計算する。 pupil.x = pupil.x * newZ / pupil.z; pupil.y = pupil.y * newZ / pupil.z; pupil.z = newZ; ray_dir = pupil / norm(pupil); cv::Point3f gaze_axis = pupil - eyeball_center; gaze = gaze_axis / norm(gaze_axis); } <|start_filename|>MyGazeEstimation.h<|end_filename|> // -*- C++ -*- #ifndef MY_GAZE_ESTIMATION_H #define MY_GAZE_ESTIMATION_H #include <LandmarkDetectorModel.h> #include <opencv2/core/core.hpp> namespace MyGazeEstimation { void EstimateGaze(const LandmarkDetector::CLNF& clnf_model, cv::Point3f& gaze_absolute, float fx, float fy, float cx, float cy, bool left_eye); } #endif // ifndef MY_GAZE_ESTIMATION_H
errno-mmd/readfacevmd
<|start_filename|>src/test/java/org/elasticsearch/river/wikipedia/WikipediaRiverTest.java<|end_filename|> /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.river.wikipedia; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.common.base.Predicate; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.river.wikipedia.helper.HttpClient; import org.elasticsearch.river.wikipedia.helper.HttpClientResponse; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.junit.annotations.Network; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.concurrent.TimeUnit; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.CoreMatchers.equalTo; /** * This test requires internet connexion * If you want to run this test, use -Dtests.network=true */ @ElasticsearchIntegrationTest.ClusterScope( scope = ElasticsearchIntegrationTest.Scope.SUITE, transportClientRatio = 0.0) @Network public class WikipediaRiverTest extends ElasticsearchIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("plugins." + PluginsService.LOAD_PLUGIN_FROM_CLASSPATH, true) .build(); } @Before public void createEmptyRiverIndex() { // We want to force _river index to use 1 shard 1 replica client().admin().indices().prepareCreate("_river").setSettings(Settings.builder() .put(SETTING_NUMBER_OF_SHARDS, 1) .put(SETTING_NUMBER_OF_REPLICAS, 0)).get(); } @After public void deleteRiverAndWait() throws InterruptedException { logger.info(" --> remove all wikipedia rivers"); client().admin().indices().prepareDelete("_river").get(); // We just wait a few to make sure that all bulks has been processed awaitBusy(new Predicate<Object>() { @Override public boolean apply(Object o) { return false; } }, 2, TimeUnit.SECONDS); } private boolean isUrlAccessible(String server, String url) { HttpClientResponse response = new HttpClient(server, 80).request("HEAD", url); if (response.errorCode() == 200) { logger.info(" -> Internet working for [{}{}]", server, url); return true; } else { logger.info(" -> Internet not working for [{}{}]: {}", server, url, response.errorCode()); return false; } } @Test public void testWikipediaRiver() throws IOException, InterruptedException { if (isUrlAccessible("download.wikimedia.org", "/enwiki/latest/enwiki-latest-pages-articles.xml.bz2")) { logger.info(" --> create wikipedia river"); index("_river", "wikipedia", "_meta", jsonBuilder() .startObject() .field("type", "wikipedia") .startObject("index") .field("bulk_size", 100) .field("flush_interval", "100ms") .endObject() .endObject()); logger.info(" --> waiting for some documents"); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); CountResponse response = client().prepareCount("wikipedia").get(); logger.info(" -> got {} docs in {} index", response.getCount()); return response.getCount() > 0; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); } } /** * Testing another wikipedia source * http://dumps.wikimedia.org/frwiki/latest/frwiki-latest-pages-articles.xml.bz2 */ @Test public void testWikipediaRiverFrench() throws IOException, InterruptedException { if (isUrlAccessible("dumps.wikimedia.org", "/frwiki/latest/frwiki-latest-pages-articles.xml.bz2")) { logger.info(" --> create wikipedia river"); index("_river", "wikipedia", "_meta", jsonBuilder() .startObject() .field("type", "wikipedia") .startObject("wikipedia") .field("url", "http://dumps.wikimedia.org/frwiki/latest/frwiki-latest-pages-articles.xml.bz2") .endObject() .startObject("index") .field("bulk_size", 100) .field("flush_interval", "1s") .endObject() .endObject()); logger.info(" --> waiting for some documents"); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); CountResponse response = client().prepareCount("wikipedia").get(); logger.info(" -> got {} docs in {} index", response.getCount()); return response.getCount() > 0; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); } } } <|start_filename|>src/main/java/org/elasticsearch/river/wikipedia/support/WikiXMLParser.java<|end_filename|> /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.river.wikipedia.support; import org.elasticsearch.river.wikipedia.bzip2.CBZip2InputStream; import org.xml.sax.InputSource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.zip.GZIPInputStream; /** * @author <NAME> * @author <NAME> */ public abstract class WikiXMLParser { private URL wikiXMLFile = null; protected WikiPage currentPage = null; private BufferedReader br; public WikiXMLParser(URL fileName) { wikiXMLFile = fileName; } /** * Set a callback handler. The callback is executed every time a * page instance is detected in the stream. Custom handlers are * implementations of {@link PageCallbackHandler} * * @param handler * @throws Exception */ public abstract void setPageCallback(PageCallbackHandler handler) throws Exception; /** * The main parse method. * * @throws Exception */ public abstract void parse() throws Exception; /** * @return an iterator to the list of pages * @throws Exception */ public abstract WikiPageIterator getIterator() throws Exception; /** * @return An InputSource created from wikiXMLFile * @throws Exception */ protected InputSource getInputSource() throws Exception { if (wikiXMLFile.toExternalForm().endsWith(".gz")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(wikiXMLFile.openStream()), "UTF-8")); } else if (wikiXMLFile.toExternalForm().endsWith(".bz2")) { InputStream fis = wikiXMLFile.openStream(); byte[] ignoreBytes = new byte[2]; fis.read(ignoreBytes); //"B", "Z" bytes from commandline tools CBZip2InputStream cbZip2InputStream = new CBZip2InputStream(fis); br = new BufferedReader(new InputStreamReader(cbZip2InputStream, "UTF-8")); } else { br = new BufferedReader(new InputStreamReader(wikiXMLFile.openStream(), "UTF-8")); } return new InputSource(br); } protected void notifyPage(WikiPage page) { currentPage = page; } public void close() throws IOException { if (br != null) { br.close(); } } }
elastic/elasticsearch-river-wikipedia
<|start_filename|>TimeMachine.c<|end_filename|> #include <CoreFoundation/CoreFoundation.h> #include "utils.h" int main() { if (getuid() != 0) { setuid(0); } if (getuid() != 0) { printf("Can't set uid as 0.\n"); return 1; } run_system("/etc/rc.d/snapshotcheck"); CFDictionaryRef settings = loadPrefs(); if (settings == NULL) { settings = CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL); } if (!is_sealed("/") && (!CFDictionaryContainsKey(settings, CFSTR("rootfs_enabled")) || CFBooleanGetValue(CFDictionaryGetValue(settings, CFSTR("rootfs_enabled"))))) { int max_snapshot = 3; if (CFDictionaryContainsKey(settings, CFSTR("max_rootfs_snapshot"))) { CFTypeRef num = CFDictionaryGetValue(settings, CFSTR("max_rootfs_snapshot")); if (CFGetTypeID(num) == CFNumberGetTypeID()) { CFNumberGetValue(num, kCFNumberIntType, &max_snapshot); } else { CFPreferencesSetValue(CFSTR("max_rootfs_snapshot"), NULL, bundleID, CFSTR("mobile"), kCFPreferencesAnyHost); } CFRelease(num); } do_timemachine("/", true, max_snapshot); } if (!CFDictionaryContainsKey(settings, CFSTR("datafs_enabled")) || CFBooleanGetValue(CFDictionaryGetValue(settings, CFSTR("datafs_enabled")))) { int max_snapshot = 3; if (CFDictionaryContainsKey(settings, CFSTR("max_datafs_snapshot"))) { CFTypeRef num = CFDictionaryGetValue(settings, CFSTR("max_datafs_snapshot")); if (CFGetTypeID(num) == CFNumberGetTypeID()) { CFNumberGetValue(num, kCFNumberIntType, &max_snapshot); } else { CFPreferencesSetValue(CFSTR("max_datafs_snapshot"), NULL, bundleID, CFSTR("mobile"), kCFPreferencesAnyHost); } CFRelease(num); } do_timemachine("/private/var", true, max_snapshot); } CFRelease(settings); printf("TimeMachine on iOS's work is down, enjoy safety.\n\n"); return 0; } <|start_filename|>libTimeMachine.c<|end_filename|> #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <regex.h> #include <removefile.h> #include <sys/snapshot.h> #include "utils.h" __attribute__((aligned(4))) typedef struct val_attrs { uint32_t length; attribute_set_t returned; attrreference_t name_info; char name[MAXPATHLEN]; } val_attrs_t; bool is_number(const char *num) { if (strcmp(num, "0") == 0) { return true; } const char* p = num; if (*p < '1' || *p > '9') { return false; } else { p++; } while (*p) { if(*p < '0' || *p > '9') { return false; } else { p++; } } return true; } bool is_sealed(const char *mntpt) { io_registry_entry_t chosen = IORegistryEntryFromPath(kIOMasterPortDefault, "IODeviceTree:/chosen"); assert(MACH_PORT_VALID(chosen)); CFTypeRef firmware = IORegistryEntryCreateCFProperty(chosen, CFSTR("firmware-version"), kCFAllocatorDefault, 0); IOObjectRelease(chosen); assert(firmware != NULL); assert(CFGetTypeID(firmware) == CFDataGetTypeID()); CFStringRef bootloader = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, firmware, kCFStringEncodingUTF8); CFRelease(firmware); assert(bootloader != NULL); if (CFStringHasPrefix(bootloader, CFSTR("pongoOS-"))) { CFRelease(bootloader); return false; } CFRelease(bootloader); struct vol_attr { uint32_t len; vol_capabilities_attr_t vol_cap; } vol_attrs = {}; struct attrlist vol_attr_list = { .bitmapcount = ATTR_BIT_MAP_COUNT, .volattr = ATTR_VOL_CAPABILITIES }; if (!getattrlist(mntpt, &vol_attr_list, &vol_attrs, sizeof(vol_attrs), 0) && vol_attrs.vol_cap.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_SEALED) { return (vol_attrs.vol_cap.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_SEALED); } return false; } int snapshot_create(const char *vol, const char *snap) { int dirfd = open(vol, O_RDONLY, 0); if (dirfd < 0) { perror("open"); exit(1); } int ret = fs_snapshot_create(dirfd, snap, 0); close(dirfd); if (ret != 0) { perror("fs_snapshot_create"); printf("Failure\n"); } else { printf("Success\n"); } return ret; } bool snapshot_check(const char *vol, const char *snap) { int dirfd = open(vol, O_RDONLY, 0); if (dirfd < 0) { perror("open"); exit(1); } struct attrlist attr_list = { 0 }; attr_list.commonattr = ATTR_BULK_REQUIRED; val_attrs_t buf; bzero(&buf, sizeof(buf)); int retcount; while ((retcount = fs_snapshot_list(dirfd, &attr_list, &buf, sizeof(buf), 0))>0) { val_attrs_t *entry = &buf; for (int i = 0; i < retcount; i++) { if (entry->returned.commonattr & ATTR_CMN_NAME) { if (strcmp(entry->name, snap) == 0) { close(dirfd); return true; } } entry = (val_attrs_t *)((char *)entry + entry->length); } bzero(&buf, sizeof(buf)); } close(dirfd); if (retcount < 0) { perror("fs_snapshot_list"); exit(1); } return false; } int snapshot_delete(const char *vol, const char *snap) { int dirfd = open(vol, O_RDONLY, 0); if (dirfd < 0) { perror("open"); exit(1); } int ret = fs_snapshot_delete(dirfd, snap, 0); close(dirfd); if (ret != 0) { perror("fs_snapshot_delete"); printf("Failure\n"); } else { printf("Success\n"); } return ret; } int snapshot_rename(const char *vol, const char *snap, const char *nw) { int dirfd = open(vol, O_RDONLY, 0); if (dirfd < 0) { perror("open"); exit(1); } int ret = fs_snapshot_rename(dirfd, snap, nw, 0); close(dirfd); if (ret != 0) { perror("fs_snapshot_rename"); printf("Failure\n"); } else { printf("Success\n"); } return ret; } void run_system(const char *cmd) { int status = system(cmd); if (WEXITSTATUS(status) != 0) { perror(cmd); exit(WEXITSTATUS(status)); } } CFDictionaryRef loadPrefs() { CFArrayRef keyList = CFPreferencesCopyKeyList(bundleID, CFSTR("mobile"), kCFPreferencesAnyHost); if (keyList != NULL) { CFDictionaryRef prefs = CFPreferencesCopyMultiple(keyList, bundleID, CFSTR("mobile"), kCFPreferencesAnyHost); CFRelease(keyList); return prefs; } else { removefile("/private/var/mobile/Library/Preferences/com.michael.TimeMachine.plist", NULL, REMOVEFILE_RECURSIVE); CFPreferencesSynchronize(bundleID, CFSTR("mobile"), kCFPreferencesAnyHost); return NULL; } } CFNumberRef newInt(const int value) { return CFAutorelease(CFNumberCreate(NULL, kCFNumberIntType, &value)); } int do_timemachine(const char *vol, const bool create, const int max_snapshot) { if (create && max_snapshot != 0) { time_t time_T = time(NULL); struct tm *tmTime = localtime(&time_T); const char *format = "com.apple.TimeMachine.%Y-%m-%d-%H:%M:%S"; char *cre_snapshot = (char *)calloc(42, sizeof(char)); strftime(cre_snapshot, 42, format, tmTime); printf("Will create snapshot \"%s\" on fs \"%s\"...\n", cre_snapshot, vol); if (strcmp(vol, "/") == 0) { removefile("/.com.michael.TimeMachine", NULL, REMOVEFILE_RECURSIVE); FILE *fp = fopen("/.com.michael.TimeMachine", "w"); fprintf(fp, "%s", cre_snapshot); fclose(fp); snapshot_create(vol, cre_snapshot); removefile("/.com.michael.TimeMachine", NULL, REMOVEFILE_RECURSIVE); } else { snapshot_create(vol, cre_snapshot); } free(cre_snapshot); } int dirfd = open(vol, O_RDONLY, 0); if (dirfd < 0) { perror("open"); exit(1); } struct attrlist attr_list = { 0 }; attr_list.commonattr = ATTR_BULK_REQUIRED; val_attrs_t buf; bzero(&buf, sizeof(buf)); int number = 0; char **snapshots = (char**)malloc(number * sizeof(char*)); int retcount; while ((retcount = fs_snapshot_list(dirfd, &attr_list, &buf, sizeof(buf), 0))>0) { val_attrs_t *entry = &buf; for (int i = 0; i < retcount; i++) { if (entry->returned.commonattr & ATTR_CMN_NAME) { regex_t predicate; regcomp(&predicate, "^(com.apple.TimeMachine.)[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}:[0-9]{2}:[0-9]{2}$", REG_EXTENDED | REG_NEWLINE | REG_NOSUB); if (regexec(&predicate, entry->name, 0, NULL, 0) == 0) { snapshots = (char**)realloc(snapshots, ++number * sizeof(char*)); snapshots[number - 1] = (char*)calloc(42, sizeof(char)); strcpy(snapshots[number - 1], entry->name); } regfree(&predicate); } entry = (val_attrs_t *)((char *)entry + entry->length); } bzero(&buf, sizeof(buf)); } close(dirfd); if (retcount < 0) { perror("fs_snapshot_list"); exit(1); } int ret = 1; for (int no = 0; no < number - max_snapshot; no++) { printf("Will delete snapshot \"%s\" on fs \"%s\"...\n", snapshots[no], vol); snapshot_delete(vol, snapshots[no]); ret = 0; } for (int no = 0; no < number; no++) { free(snapshots[no]); } free(snapshots); return ret; } <|start_filename|>prerm.c<|end_filename|> #include <CoreFoundation/CoreFoundation.h> #include "utils.h" int main(const int argc, const char *argv[]) { if (getuid() != 0) { printf("Run this as root!\n"); return 1; } run_system("launchctl unload /Library/LaunchDaemons/com.michael.TimeMachine.plist"); if (argc > 1) { if (strcmp(argv[1], "upgrade") == 0) { return 0; } } if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_11_0) { printf("iOS11 or higher version detected, now checking orig snapshot...\n"); if (snapshot_check("/", "com.apple.TimeMachine.orig-fs")) { printf("Will rename snapshot \"com.apple.TimeMachine.orig-fs\" on fs / to \"orig-fs\"...\n"); snapshot_rename("/", "com.apple.TimeMachine.orig-fs", "orig-fs"); } if (snapshot_check("/", "com.apple.TimeMachine.electra-prejailbreak")) { printf("Will rename snapshot \"com.apple.TimeMachine.electra-prejailbreak\" on fs / to \"electra-prejailbreak\"...\n"); snapshot_rename("/", "com.apple.TimeMachine.electra-prejailbreak", "electra-prejailbreak"); } } else if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_10_3) { printf("iOS10 detected, skip orig snapshot check.\n"); } else { printf("Wrong iOS version detected, now exit.\n"); return 1; } return 0; } <|start_filename|>Makefile<|end_filename|> VERSION = 0.12.0 Package = com.michael.timemachine SDK = ${THEOS}/sdks/iPhoneOS14.3.sdk CC = xcrun -sdk $(SDK) clang -arch arm64 -arch arm64e -miphoneos-version-min=10.3 -Os LDID = ldid .PHONY: all clean all: clean libTimeMachine postinst prerm TimeMachineRootListController snapshotcheck setTimeMachine TimeMachine mkdir $(Package)_$(VERSION)_iphoneos-arm mkdir $(Package)_$(VERSION)_iphoneos-arm/DEBIAN cp control $(Package)_$(VERSION)_iphoneos-arm/DEBIAN mv postinst prerm $(Package)_$(VERSION)_iphoneos-arm/DEBIAN mkdir $(Package)_$(VERSION)_iphoneos-arm/etc mkdir $(Package)_$(VERSION)_iphoneos-arm/etc/rc.d mv snapshotcheck $(Package)_$(VERSION)_iphoneos-arm/etc/rc.d mkdir $(Package)_$(VERSION)_iphoneos-arm/Library mkdir $(Package)_$(VERSION)_iphoneos-arm/Library/LaunchDaemons cp com.michael.TimeMachine.plist $(Package)_$(VERSION)_iphoneos-arm/Library/LaunchDaemons mkdir $(Package)_$(VERSION)_iphoneos-arm/usr mkdir $(Package)_$(VERSION)_iphoneos-arm/usr/bin mv setTimeMachine $(Package)_$(VERSION)_iphoneos-arm/usr/bin mkdir $(Package)_$(VERSION)_iphoneos-arm/usr/lib mv libTimeMachine.dylib $(Package)_$(VERSION)_iphoneos-arm/usr/lib mkdir $(Package)_$(VERSION)_iphoneos-arm/Library/PreferenceBundles mkdir $(Package)_$(VERSION)_iphoneos-arm/Library/PreferenceLoader mkdir $(Package)_$(VERSION)_iphoneos-arm/Library/PreferenceLoader/Preferences cp -r Resources $(Package)_$(VERSION)_iphoneos-arm/Library/PreferenceBundles/TimeMachine.bundle mv TimeMachineRootListController $(Package)_$(VERSION)_iphoneos-arm/Library/PreferenceBundles/TimeMachine.bundle/TimeMachine cp entry.plist $(Package)_$(VERSION)_iphoneos-arm/Library/PreferenceLoader/Preferences/TimeMachine.plist mkdir $(Package)_$(VERSION)_iphoneos-arm/usr/libexec mv TimeMachine $(Package)_$(VERSION)_iphoneos-arm/usr/libexec dpkg -b $(Package)_$(VERSION)_iphoneos-arm libTimeMachine: clean $(CC) -dynamiclib -install_name /usr/lib/libTimeMachine.dylib -compatibility_version $(VERSION) -current_version $(VERSION) -framework CoreFoundation -framework IOKit libTimeMachine.c -o libTimeMachine.dylib strip -x libTimeMachine.dylib $(LDID) -S libTimeMachine.dylib postinst: libTimeMachine $(CC) -fobjc-arc -framework Foundation libTimeMachine.dylib postinst.m -o postinst strip postinst $(LDID) -Sentitlements-apfs.xml postinst prerm: libTimeMachine $(CC) -framework CoreFoundation libTimeMachine.dylib prerm.c -o prerm strip prerm $(LDID) -Sentitlements-apfs.xml prerm snapshotcheck: libTimeMachine $(CC) -fobjc-arc -framework Foundation libTimeMachine.dylib snapshotcheck.m -o snapshotcheck strip snapshotcheck $(LDID) -Sentitlements-apfs.xml snapshotcheck TimeMachineRootListController: libTimeMachine $(CC) -dynamiclib -fobjc-arc -install_name /Library/PreferenceBundles/TimeMachine.bundle/TimeMachine -I${THEOS}/vendor/include/ -framework Foundation -F $(SDK)/System/Library/PrivateFrameworks -framework Preferences libTimeMachine.dylib TimeMachineRootListController.m -o TimeMachineRootListController strip -x TimeMachineRootListController $(LDID) -S TimeMachineRootListController setTimeMachine: libTimeMachine $(CC) -fobjc-arc -framework Foundation libTimeMachine.dylib setTimeMachine.m -o setTimeMachine strip setTimeMachine $(LDID) -Sentitlements-apfs.xml setTimeMachine TimeMachine: libTimeMachine $(CC) -framework CoreFoundation libTimeMachine.dylib TimeMachine.c -o TimeMachine strip TimeMachine $(LDID) -Sentitlements-apfs.xml TimeMachine clean: rm -rf $(Package)_* libTimeMachine.dylib postinst prerm TimeMachineRootListController snapshotcheck setTimeMachine TimeMachine <|start_filename|>utils.h<|end_filename|> #ifndef _UTILS_H #define _UTILS_H #ifndef kCFCoreFoundationVersionNumber_iOS_10_3 # define kCFCoreFoundationVersionNumber_iOS_10_3 1349.56 #endif #ifndef kCFCoreFoundationVersionNumber_iOS_11_0 # define kCFCoreFoundationVersionNumber_iOS_11_0 1443.00 #endif #ifndef bundleID # define bundleID CFSTR("com.michael.TimeMachine") #endif CFDictionaryRef loadPrefs(); bool is_number(const char *num); bool is_sealed(const char *mntpt); CFNumberRef newInt(const int value); int do_timemachine(const char *vol, const bool create, const int max_snapshot); int snapshot_create(const char *vol, const char *snap); bool snapshot_check(const char *vol, const char *snap); int snapshot_delete(const char *vol, const char *snap); int snapshot_rename(const char *vol, const char *snap, const char *nw); void run_system(const char *cmd); #endif
Halo-Michael/TimeMachine-on-iOS
<|start_filename|>examples/libs/lv_example_libs.h<|end_filename|> /** * @file lv_example_libs.h * */ #ifndef LV_EXAMPLE_LIBS_H #define LV_EXAMPLE_LIBS_H #ifdef __cplusplus extern "C" { #endif /********************* * INCLUDES *********************/ #include "bmp/lv_example_bmp.h" #include "gif/lv_example_gif.h" #include "png/lv_example_png.h" #include "sjpg/lv_example_sjpg.h" #include "qrcode/lv_example_qrcode.h" #include "freetype/lv_example_freetype.h" /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /********************** * GLOBAL PROTOTYPES **********************/ /********************** * MACROS **********************/ #ifdef __cplusplus } /*extern "C"*/ #endif #endif /*LV_EXAMPLE_LIBS_H*/ <|start_filename|>examples/libs/freetype/lv_example_freetype_1.c<|end_filename|> #include "../../lv_examples.h" #if LV_USE_FREETYPE && LV_BUILD_EXAMPLES /** * Load a font with FreeType */ void lv_example_freetype_1(void) { /*Create a font*/ static lv_ft_info_t info; /*FreeType uses C standard file system, so no driver letter is required.*/ info.name = "./lvgl/examples/libs/freetype/arial.ttf"; info.weight = 24; info.style = FT_FONT_STYLE_NORMAL; lv_ft_font_init(&info); /*Create style with the new font*/ static lv_style_t style; lv_style_init(&style); lv_style_set_text_font(&style, info.font); lv_style_set_text_align(&style, LV_TEXT_ALIGN_CENTER); /*Create a label with the new style*/ lv_obj_t * label = lv_label_create(lv_scr_act()); lv_obj_add_style(label, &style, 0); lv_label_set_text(label, "Hello world\nI'm a font created with FreeType"); lv_obj_center(label); } #else void lv_example_freetype_1(void) { /*TODO *fallback for online examples*/ lv_obj_t * label = lv_label_create(lv_scr_act()); lv_label_set_text(label, "FreeType is not installed"); lv_obj_center(label); } #endif
qq49707555/lvgl
<|start_filename|>include/openpose/pose/wPoseExtractorNet.hpp<|end_filename|> #ifndef OPENPOSE_POSE_W_POSE_EXTRACTOR_NET_HPP #define OPENPOSE_POSE_W_POSE_EXTRACTOR_NET_HPP #include <openpose/core/common.hpp> #include <openpose/pose/poseExtractorNet.hpp> #include <openpose/thread/worker.hpp> namespace op { template<typename TDatums> class WPoseExtractorNet : public Worker<TDatums> { public: explicit WPoseExtractorNet(const std::shared_ptr<PoseExtractorNet>& poseExtractorSharedPtr); void initializationOnThread(); void work(TDatums& tDatums); private: std::shared_ptr<PoseExtractorNet> spPoseExtractorNet; DELETE_COPY(WPoseExtractorNet); }; } // Implementation #include <openpose/utilities/pointerContainer.hpp> namespace op { template<typename TDatums> WPoseExtractorNet<TDatums>::WPoseExtractorNet(const std::shared_ptr<PoseExtractorNet>& poseExtractorSharedPtr) : spPoseExtractorNet{poseExtractorSharedPtr} { } template<typename TDatums> void WPoseExtractorNet<TDatums>::initializationOnThread() { try { spPoseExtractorNet->initializationOnThread(); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums> void WPoseExtractorNet<TDatums>::work(TDatums& tDatums) { try { if (checkNoNullNorEmpty(tDatums)) { // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // Profiling speed const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // Extract people pose for (auto& tDatum : *tDatums) { spPoseExtractorNet->forwardPass(tDatum.inputNetData, Point<int>{tDatum.cvInputData.cols, tDatum.cvInputData.rows}, tDatum.scaleInputToNetInputs); tDatum.poseCandidates = spPoseExtractorNet->getCandidatesCopy(); tDatum.poseHeatMaps = spPoseExtractorNet->getHeatMapsCopy(); tDatum.poseKeypoints = spPoseExtractorNet->getPoseKeypoints().clone(); tDatum.poseScores = spPoseExtractorNet->getPoseScores().clone(); tDatum.scaleNetToOutput = spPoseExtractorNet->getScaleNetToOutput(); } // Profiling speed Profiler::timerEnd(profilerKey); Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__); // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } } catch (const std::exception& e) { this->stop(); tDatums = nullptr; error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } COMPILE_TEMPLATE_DATUM(WPoseExtractorNet); } #endif // OPENPOSE_POSE_W_POSE_EXTRACTOR_NET_HPP <|start_filename|>include/openpose/producer/wDatumProducer.hpp<|end_filename|> #ifndef OPENPOSE_PRODUCER_W_DATUM_PRODUCER_HPP #define OPENPOSE_PRODUCER_W_DATUM_PRODUCER_HPP #include <limits> // std::numeric_limits #include <queue> // std::queue #include <openpose/core/common.hpp> #include <openpose/producer/datumProducer.hpp> #include <openpose/thread/workerProducer.hpp> namespace op { template<typename TDatums, typename TDatumsNoPtr> class WDatumProducer : public WorkerProducer<TDatums> { public: explicit WDatumProducer(const std::shared_ptr<DatumProducer<TDatumsNoPtr>>& datumProducer); void initializationOnThread(); TDatums workProducer(); private: std::shared_ptr<DatumProducer<TDatumsNoPtr>> spDatumProducer; std::queue<TDatums> mQueuedElements; DELETE_COPY(WDatumProducer); }; } // Implementation #include <openpose/core/datum.hpp> namespace op { template<typename TDatums, typename TDatumsNoPtr> WDatumProducer<TDatums, TDatumsNoPtr>::WDatumProducer(const std::shared_ptr<DatumProducer<TDatumsNoPtr>>& datumProducer) : spDatumProducer{datumProducer} { } template<typename TDatums, typename TDatumsNoPtr> void WDatumProducer<TDatums, TDatumsNoPtr>::initializationOnThread() { } template<typename TDatums, typename TDatumsNoPtr> TDatums WDatumProducer<TDatums, TDatumsNoPtr>::workProducer() { try { // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // Profiling speed const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // Create and fill TDatums std::shared_ptr<TDatumsNoPtr> tDatums; // Producer if (mQueuedElements.empty()) { bool isRunning; std::tie(isRunning, tDatums) = spDatumProducer->checkIfRunningAndGetDatum(); // Stop Worker if producer finished if (!isRunning) this->stop(); // Profiling speed Profiler::timerEnd(profilerKey); Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__); // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } // Equivalent to WQueueSplitter // Queued elements - Multiple views --> Split views into different TDatums if (tDatums != nullptr && tDatums->size() > 1) { // Add tDatums to mQueuedElements for (auto i = 0u ; i < tDatums->size() ; i++) { auto& tDatum = (*tDatums)[i]; tDatum.subId = i; tDatum.subIdMax = tDatums->size()-1; mQueuedElements.emplace( std::make_shared<TDatumsNoPtr>(TDatumsNoPtr{tDatum})); } } // Queued elements - Multiple views --> Return oldest view if (!mQueuedElements.empty()) { tDatums = mQueuedElements.front(); mQueuedElements.pop(); } // Return TDatums return tDatums; } catch (const std::exception& e) { this->stop(); error(e.what(), __LINE__, __FUNCTION__, __FILE__); return TDatums{}; } } extern template class WDatumProducer<DATUM_BASE, DATUM_BASE_NO_PTR>; } #endif // OPENPOSE_PRODUCER_W_DATUM_PRODUCER_HPP <|start_filename|>include/openpose/thread/wQueueAssembler.hpp<|end_filename|> #ifndef OPENPOSE_THREAD_W_QUEUE_ASSEMBLER_HPP #define OPENPOSE_THREAD_W_QUEUE_ASSEMBLER_HPP #include <queue> // std::queue #include <openpose/core/common.hpp> #include <openpose/thread/worker.hpp> #include <openpose/utilities/pointerContainer.hpp> namespace op { // Note: The goal of WQueueAssembler and WQueueSplitter (integrated in wDatumProducer) is to reduce the latency // of OpenPose. E.g., if 4 cameras in stereo mode, without this, OpenPose would have to process all 4 cameras // with the same GPU. In this way, this work is parallelized over GPUs (1 view for each). // Pros: Latency highly recuded, same speed // Cons: Requires these extra 2 classes and proper threads for them template<typename TDatums, typename TDatumsNoPtr> class WQueueAssembler : public Worker<TDatums> { public: explicit WQueueAssembler(); void initializationOnThread(); void work(TDatums& tDatums); private: TDatums mNextTDatums; DELETE_COPY(WQueueAssembler); }; } // Implementation #include <chrono> #include <thread> namespace op { template<typename TDatums, typename TDatumsNoPtr> WQueueAssembler<TDatums, TDatumsNoPtr>::WQueueAssembler() { } template<typename TDatums, typename TDatumsNoPtr> void WQueueAssembler<TDatums, TDatumsNoPtr>::initializationOnThread() { } template<typename TDatums, typename TDatumsNoPtr> void WQueueAssembler<TDatums, TDatumsNoPtr>::work(TDatums& tDatums) { try { // Profiling speed const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // Input TDatums -> enqueue it if (checkNoNullNorEmpty(tDatums)) { // Security check if (tDatums->size() > 1) error("This function assumes that WQueueSplitter (inside WDatumProducer)" " was applied in the first place, i.e., that there is only 1 element" " per TDatums (size = " + std::to_string(tDatums->size()) + ").", __LINE__, __FUNCTION__, __FILE__); auto tDatum = (*tDatums)[0]; // Single view --> Return if (tDatum.subIdMax == 0) return; // Multiple view --> Merge views into different TDatums (1st frame) if (mNextTDatums == nullptr) mNextTDatums = std::make_shared<TDatumsNoPtr>(); // Multiple view --> Merge views into different TDatums mNextTDatums->emplace_back(tDatum); // Last view - Return frame if (mNextTDatums->back().subId == mNextTDatums->back().subIdMax) { tDatums = mNextTDatums; mNextTDatums = nullptr; // Profiling speed Profiler::timerEnd(profilerKey); Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__); // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } // Non-last view - Return nothing else tDatums = nullptr; } // Sleep if no new tDatums to either pop or push else std::this_thread::sleep_for(std::chrono::milliseconds{1}); } catch (const std::exception& e) { this->stop(); tDatums = nullptr; error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } extern template class WQueueAssembler<DATUM_BASE, DATUM_BASE_NO_PTR>; } #endif // OPENPOSE_THREAD_W_QUEUE_ASSEMBLER_HPP <|start_filename|>examples/calibration/calibration.cpp<|end_filename|> // ------------------------- OpenPose Calibration Toolbox ------------------------- // Check `doc/modules/calibration_module.md`. // Implemented on top of OpenCV. // It computes and saves the intrinsics parameters of the input images. // C++ std library dependencies #include <chrono> // `std::chrono::` functions and classes, e.g. std::chrono::milliseconds #include <thread> // std::this_thread // Other 3rdparty dependencies // GFlags: DEFINE_bool, _int32, _int64, _uint64, _double, _string #include <gflags/gflags.h> // Allow Google Flags in Ubuntu 14 #ifndef GFLAGS_GFLAGS_H_ namespace gflags = google; #endif // OpenPose dependencies #include <openpose/headers.hpp> // See all the available parameter options withe the `--help` flag. E.g. `build/examples/openpose/openpose.bin --help` // Note: This command will show you flags for other unnecessary 3rdparty files. Check only the flags for the OpenPose // executable. E.g. for `openpose.bin`, look for `Flags from examples/openpose/openpose.cpp:`. // Debugging/Other DEFINE_int32(logging_level, 3, "The logging level. Integer in the range [0, 255]. 0 will output any log() message, while" " 255 will not output any. Current OpenPose library messages are in the range 0-4: 1 for" " low priority messages and 4 for important ones."); // Calibration DEFINE_int32(mode, 1, "Select 1 for intrinsic camera parameter calibration, 2 for extrinsic calibration."); DEFINE_string(calibration_image_dir, "images/intrinsics/", "Directory where the images for camera parameter calibration are placed."); DEFINE_double(grid_square_size_mm, 127.0, "Chessboard square length (in millimeters)."); DEFINE_string(grid_number_inner_corners,"9x6", "Number of inner corners in width and height, i.e., number of total squares in width" " and height minus 1."); // Mode 1 - Intrinsics DEFINE_string(camera_serial_number, "18079958", "Camera serial number."); // Mode 2 - Extrinsics DEFINE_bool(omit_distortion, false, "Set to true if image views are already undistorted (e.g., if recorded from OpenPose" " after intrinsic parameter calibration)."); DEFINE_bool(combine_cam0_extrinsics, false, "Set to true if cam0 extrinsics are not [R=I, t=0]. I will make no effect if cam0 is" " already the origin. See doc/modules/calibration_module.md for an example."); DEFINE_int32(cam0, 1, "Baseline camera for extrinsic calibration, cam1 will be calibrated assuming cam0 the" " world coordinate origin."); DEFINE_int32(cam1, 0, "Target camera to estimate its extrinsic parameters, it will be calibrated assuming cam0" " as the world coordinate origin."); // // Mode 3 // DEFINE_int32(number_cameras, 4, "Number of cameras."); // Producer DEFINE_string(camera_parameter_folder, "models/cameraParameters/flir/", "String with the folder where the camera parameters are or will be" " located."); int openPoseDemo() { try { op::log("Starting OpenPose demo...", op::Priority::High); const auto timerBegin = std::chrono::high_resolution_clock::now(); // logging_level op::check(0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.", __LINE__, __FUNCTION__, __FILE__); op::ConfigureLog::setPriorityThreshold((op::Priority)FLAGS_logging_level); // Calibration - Intrinsics if (FLAGS_mode == 1) { op::log("Running calibration (intrinsic parameters)...", op::Priority::High); // Obtain & save intrinsics const auto gridInnerCorners = op::flagsToPoint(FLAGS_grid_number_inner_corners, "12x7"); // const auto flags = 0; // 5 parameters const auto flags = cv::CALIB_RATIONAL_MODEL; // 8 parameters // const auto flags = cv::CALIB_RATIONAL_MODEL | cv::CALIB_THIN_PRISM_MODEL; // 12 parameters // const auto flags = cv::CALIB_RATIONAL_MODEL | cv::CALIB_THIN_PRISM_MODEL | cv::CALIB_TILTED_MODEL; // 14 // const auto saveImagesWithCorners = false; const auto saveImagesWithCorners = true; // Run camera calibration code op::estimateAndSaveIntrinsics(gridInnerCorners, FLAGS_grid_square_size_mm, flags, op::formatAsDirectory(FLAGS_camera_parameter_folder), op::formatAsDirectory(FLAGS_calibration_image_dir), FLAGS_camera_serial_number, saveImagesWithCorners); op::log("Intrinsic calibration completed!", op::Priority::High); } // Calibration - Extrinsics else if (FLAGS_mode == 2) { op::log("Running calibration (extrinsic parameters)...", op::Priority::High); // Parameters op::estimateAndSaveExtrinsics(FLAGS_camera_parameter_folder, op::formatAsDirectory(FLAGS_calibration_image_dir), op::flagsToPoint(FLAGS_grid_number_inner_corners, "12x7"), FLAGS_grid_square_size_mm, FLAGS_cam0, FLAGS_cam1, FLAGS_omit_distortion, FLAGS_combine_cam0_extrinsics); op::log("Extrinsic calibration completed!", op::Priority::High); } // // Calibration - Extrinsics Refinement with Visual SFM // else if (FLAGS_mode == 3) // { // op::log("Running calibration (intrinsic parameters)...", op::Priority::High); // // Obtain & save intrinsics // const auto gridInnerCorners = op::flagsToPoint(FLAGS_grid_number_inner_corners, "12x7"); // const auto saveImagesWithCorners = false; // // const auto saveImagesWithCorners = true; // // Run camera calibration code // op::estimateAndSaveSiftFile(gridInnerCorners, // op::formatAsDirectory(FLAGS_calibration_image_dir), // FLAGS_number_cameras, // saveImagesWithCorners); // op::log("Intrinsic calibration completed!", op::Priority::High); // } else op::error("Unknown `--mode " + std::to_string(FLAGS_mode) + "`.", __LINE__, __FUNCTION__, __FILE__); // Measuring total time const auto now = std::chrono::high_resolution_clock::now(); const auto totalTimeSec = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(now-timerBegin).count() * 1e-9; const auto message = "OpenPose demo successfully finished. Total time: " + std::to_string(totalTimeSec) + " seconds."; op::log(message, op::Priority::High); return 0; } catch (const std::exception& e) { op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); return -1; } } int main(int argc, char *argv[]) { // Parsing command line flags gflags::ParseCommandLineFlags(&argc, &argv, true); // Running openPoseDemo return openPoseDemo(); } <|start_filename|>src/openpose/tracking/pyramidalLK.cpp<|end_filename|> // #include <iostream> #include <opencv2/core/core.hpp> // cv::Point2f, cv::Mat #include <opencv2/imgproc/imgproc.hpp> // cv::pyrDown #include <opencv2/video/video.hpp> // cv::buildOpticalFlowPyramid #include <openpose/utilities/profiler.hpp> #include <openpose/tracking/pyramidalLK.hpp> #if defined (WITH_SSE4) #include <emmintrin.h> #include "smmintrin.h" #endif #if defined (WITH_AVX) #include <immintrin.h> #endif #include <iostream> //#define DEBUG // #ifdef DEBUG // // When debugging is enabled, these form aliases to useful functions // #define dbg_printf(...) printf(__VA_ARGS__); // #else // // When debugging is disabled, no code gets generated for these // #define dbg_printf(...) // #endif #define SUCCESS 0 #define INVALID_PATCH_SIZE 1 #define OUT_OF_FRAME 2 #define ZERO_DENOMINATOR 3 #define UNDEFINED_ERROR 4 namespace op { #if defined (WITH_SSE4) float sse_dot_product(std::vector<float> &av, std::vector<float> &bv) { /* Get SIMD-vector pointers to the start of each vector */ unsigned int niters = av.size() / 4; float zeros[] = {0.0, 0.0, 0.0, 0.0}; float *a = (float *) aligned_alloc(16, av.size()*sizeof(float)); float *b = (float *) aligned_alloc(16, av.size()*sizeof(float)); memcpy(a,&av[0],av.size()*sizeof(float)); memcpy(b,&bv[0],bv.size()*sizeof(float)); __m128 *ptrA = (__m128*) &a[0], *ptrB = (__m128*) &b[0]; __m128 res = _mm_load_ps(zeros); /* Do SIMD dot product */ for (unsigned int i = 0; i < niters; i++, ptrA++,ptrB++) res = _mm_add_ps(_mm_dp_ps(*ptrA, *ptrB, 255), res); /* Get result back from the SIMD vector */ float fres[4]; _mm_store_ps (fres, res); int q = 4 * niters; for (unsigned int i = 0; i < av.size() % 4; i++) fres[0] += (a[i+q]*b[i+q]); free(a); free(b); return fres[0]; } #endif #if defined (WITH_AVX) float avx_dot_product(std::vector<float> &av, std::vector<float> &bv) { /* Get SIMD-vector pointers to the start of each vector */ unsigned int niters = av.size() / 8; float *a = (float *) aligned_alloc(32, av.size()*sizeof(float)); float *b = (float *) aligned_alloc(32, av.size()*sizeof(float)); memcpy(a,&av[0],av.size()*sizeof(float)); memcpy(b,&bv[0],bv.size()*sizeof(float)); __m256 *ptrA = (__m256*) &a[0], *ptrB = (__m256*) &b[0]; __m256 res = _mm256_set1_ps(0.0); for (unsigned int i = 0; i < niters; i++, ptrA++,ptrB++) res = _mm256_add_ps(_mm256_dp_ps(*ptrA, *ptrB, 255), res); /* Get result back from the SIMD vector */ float fres[8]; _mm256_storeu_ps (fres, res); int q = 8 * niters; for (unsigned int i = 0; i < av.size() % 8; i++) fres[0] += (a[i+q]*b[i+q]); free(a); free(b); return fres[0] + fres[4]; } #endif char computeLK(cv::Point2f& delta, std::vector<float>& ix, std::vector<float>& iy, std::vector<float>& it) { try { // Calculate sums auto sumXX = 0.f; auto sumYY = 0.f; auto sumXT = 0.f; auto sumYT = 0.f; auto sumXY = 0.f; #if defined (WITH_AVX) sumXX = avx_dot_product(ix,ix); sumYY = avx_dot_product(iy,iy); sumXY = avx_dot_product(ix,iy); sumXT = avx_dot_product(ix,it); sumYT = avx_dot_product(iy,it); #elif defined (WITH_SSE4) sumXX = sse_dot_product(ix,ix); sumYY = sse_dot_product(iy,iy); sumXY = sse_dot_product(ix,iy); sumXT = sse_dot_product(ix,it); sumYT = sse_dot_product(iy,it); #else for (auto i = 0u; i < ix.size(); i++) { sumXX += ix[i] * ix[i]; sumYY += iy[i] * iy[i]; sumXY += ix[i] * iy[i]; sumXT += ix[i] * it[i]; sumYT += iy[i] * it[i]; } #endif // Get numerator and denominator of u and v const auto den = (sumXX*sumYY) - (sumXY * sumXY); if (std::abs(den) < 1e-9f) return ZERO_DENOMINATOR; const auto numU = (-1.f * sumYY * sumXT) + (sumXY * sumYT); const auto numV = (-1.f * sumXX * sumYT) + (sumXT * sumXY); delta.x = numU / den; delta.y = numV / den; return SUCCESS; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return UNDEFINED_ERROR; } } void getVectors(std::vector<float>& ix, std::vector<float>& iy, std::vector<float>& it, const std::vector<std::vector<float>>& patch, const std::vector<std::vector<float>>& patchIt, const int patchSize) { try { // Performance: resize faster than emplace_back/push_back const auto numberElements = patchSize*patchSize; // Get `ix` and `iy` ix.resize(numberElements); iy.resize(numberElements); for (auto i = 1; i <= patchSize; i++) { const auto baseIndex = (i-1)*patchSize; for (auto j = 1; j <= patchSize; j++) { ix[baseIndex+j-1] = (patch[i][j+1] - patch[i][j-1])/2.0; iy[baseIndex+j-1] = (patch[i+1][j] - patch[i-1][j])/2.0; } } // Get `it` it.resize(numberElements); for (auto i = 0; i < patchSize; i++) { const auto baseIndex = i*patchSize; for (auto j = 0; j < patchSize; j++) it[baseIndex+j] = patchIt[i][j]; } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } char extractPatch(std::vector< std::vector<float>>& patch, const int x, const int y, const int patchSize, const cv::Mat& image) { try { int radix = patchSize / 2; if ( ((x - radix) < 0) || ((x + radix) >= image.cols) || ((y - radix) < 0) || ((y + radix) >= image.rows)) return OUT_OF_FRAME; for (auto i = -radix; i <= radix; i++) for (auto j = -radix; j <= radix; j++) patch[i+radix][j+radix] = image.at<float>(y+i,x+j); return SUCCESS; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return UNDEFINED_ERROR; } } char extractPatchIt(std::vector<std::vector<float>>& patch, const int xI, const int yI, const int xJ, const int yJ, const cv::Mat& I, const cv::Mat& J, const int patchSize) { try { const int radix = patchSize / 2; if (((xI - radix) < 0) || ((xI + radix) >= I.cols) || ((yI - radix) < 0) || ((yI + radix) >= I.rows)) return OUT_OF_FRAME; if (((xJ - radix) < 0) || ((xJ + radix) >= J.cols) || ((yJ - radix) < 0) || ((yJ + radix) >= J.rows)) return OUT_OF_FRAME; for (auto i = -radix; i <= radix; i++) for (auto j = -radix; j <= radix; j++) patch[i+radix][j+radix] = J.at<float>(yJ+i,xJ+j) - I.at<float>(yI+i,xI+j); return SUCCESS; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return UNDEFINED_ERROR; } } // Given an OpenCV image, build a gaussian pyramid of size 'levels' void buildGaussianPyramid(std::vector<cv::Mat>& pyramidImages, const cv::Mat& image, const int levels) { try { pyramidImages.clear(); pyramidImages.emplace_back(image); for (auto i = 0; i < levels - 1; i++) { cv::Mat pyredImage; cv::pyrDown(pyramidImages.back(), pyredImage); pyramidImages.emplace_back(pyredImage); } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } cv::Point2f pyramidIteration(char& status, const cv::Point2f& pointI, const cv::Point2f& pointJ, const cv::Mat& I, const cv::Mat& J, const int patchSize = 5) { try { cv::Point2f result; // Extract a patch around the image std::vector<std::vector<float>> patch(patchSize + 2, std::vector<float>(patchSize + 2)); std::vector<std::vector<float>> patchIt(patchSize, std::vector<float>(patchSize)); status = extractPatch(patch, (int)pointI.x,(int)pointI.y, patchSize + 2, I); // if (status) // return result; status = extractPatchIt(patchIt, pointI.x, pointI.y, pointJ.x, pointJ.y, I, J, patchSize); // if (status) // return result; // Get the Ix, Iy and It vectors std::vector<float> ix, iy, it; getVectors(ix, iy, it, patch, patchIt, patchSize); // Calculate optical flow cv::Point2f delta; status = computeLK(delta, ix, iy, it); // if (status) // return result; result = pointJ + delta; return result; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return cv::Point2f{}; } } void pyramidalLKCpu(std::vector<cv::Point2f>& coordI, std::vector<cv::Point2f>& coordJ, std::vector<cv::Mat>& pyramidImagesPrevious, std::vector<cv::Mat>& pyramidImagesCurrent, std::vector<char>& status, const cv::Mat& imagePrevious, const cv::Mat& imageCurrent, const int levels, const int patchSize) { try { // Empty coordinates if (coordI.size() == 0) return; std::vector<cv::Point2f> I; I.assign(coordI.begin(), coordI.end()); const auto rescaleScale = 1.0/(float)(1<<(levels-1)); for (auto& coordenate : I) coordenate *= rescaleScale; coordJ.clear(); coordJ.assign(I.begin(), I.end()); if (pyramidImagesPrevious.empty()) buildGaussianPyramid(pyramidImagesPrevious, imagePrevious, levels); if (pyramidImagesCurrent.empty()) buildGaussianPyramid(pyramidImagesCurrent, imageCurrent, levels); // Process all pixel requests for (auto i = 0u; i < coordI.size(); i++) { for (auto l = levels - 1; l >= 0; l--) { char status_point = 0; cv::Point2f result; result = pyramidIteration(status_point, I[i], coordJ[i],pyramidImagesPrevious[l], pyramidImagesCurrent[l], patchSize); if (status_point) status[i] = status_point; coordJ[i] = result; if (l == 0) break; I[i] *= 2.f; coordJ[i] *= 2.f; } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } // old, nwekp, pyramidPrev, pyramidCurr, status, imagePrev, imageCurr void pyramidalLKOcv(std::vector<cv::Point2f>& coordI, std::vector<cv::Point2f>& coordJ, std::vector<cv::Mat>& pyramidImagesPrevious, std::vector<cv::Mat>& pyramidImagesCurrent, std::vector<char>& status, const cv::Mat& imagePrevious, const cv::Mat& imageCurrent, const int levels, const int patchSize, const bool initFlow) { try { // Empty coordinates if (coordI.size() != 0) { // const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); std::vector<cv::Point2f> I; I.assign(coordI.begin(), coordI.end()); if (!initFlow) { coordJ.clear(); coordJ.assign(I.begin(), I.end()); } const cv::Mat& imagePrevGray = imagePrevious; const cv::Mat& imageCurrGray = imageCurrent; // Compute Pyramids if (pyramidImagesPrevious.empty()) cv::buildOpticalFlowPyramid(imagePrevGray, pyramidImagesPrevious, cv::Size{patchSize,patchSize}, levels); if (pyramidImagesCurrent.empty()) cv::buildOpticalFlowPyramid(imageCurrGray, pyramidImagesCurrent, cv::Size{patchSize,patchSize}, levels); // Compute Flow std::vector<uchar> st; std::vector<float> err; if (initFlow) cv::calcOpticalFlowPyrLK(pyramidImagesPrevious, pyramidImagesCurrent, coordI, coordJ, st, err, cv::Size{patchSize,patchSize},levels, cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS,30,0.01), cv::OPTFLOW_USE_INITIAL_FLOW); else cv::calcOpticalFlowPyrLK(pyramidImagesPrevious, pyramidImagesCurrent, coordI, coordJ, st, err, cv::Size{patchSize,patchSize},levels); // Check distance for (size_t i=0; i<status.size(); i++) { const float distance = std::sqrt( std::pow(coordI[i].x-coordJ[i].x,2) + std::pow(coordI[i].y-coordJ[i].y,2)); // Check if lk loss track, if distance is close keep it if (st[i] != (status[i])) if (distance <= patchSize*2) st[i] = 1; // If distance too far discard it if (distance > patchSize*2) st[i] = 0; } // Stupid hack because apparently in this tracker 0 means 1 and 1 is 0 wtf if (st.size() != status.size()) error("st.size() != status.size().", __LINE__, __FUNCTION__, __FILE__); for (size_t i=0; i<status.size(); i++) { // If its 0 to begin with (Because OP lost track?) if (status[i] != 0) { if (st[i] == 0) st[i] = 0; else if (st[i] == 1) st[i] = 1; else error("Wrong CV Type.", __LINE__, __FUNCTION__, __FILE__); status[i] = st[i]; } } // Profiler::timerEnd(profilerKey); // Profiler::printAveragedTimeMsEveryXIterations(profilerKey, __LINE__, __FUNCTION__, __FILE__, 5); // // Debug // std::cout << "LK: "; // for (int i=0; i<status.size(); i++) std::cout << !(int)status[i]; // std::cout << std::endl; } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } } <|start_filename|>include/openpose/gui/wGuiAdam.hpp<|end_filename|> #ifdef USE_3D_ADAM_MODEL #ifndef OPENPOSE_GUI_W_GUI_ADAM_HPP #define OPENPOSE_GUI_W_GUI_ADAM_HPP #include <openpose/core/common.hpp> #include <openpose/gui/guiAdam.hpp> #include <openpose/thread/workerConsumer.hpp> namespace op { template<typename TDatums> class WGuiAdam : public WorkerConsumer<TDatums> { public: explicit WGuiAdam(const std::shared_ptr<GuiAdam>& guiAdam); void initializationOnThread(); void workConsumer(const TDatums& tDatums); private: std::shared_ptr<GuiAdam> spGuiAdam; DELETE_COPY(WGuiAdam); }; } // Implementation #include <openpose/utilities/pointerContainer.hpp> namespace op { template<typename TDatums> WGuiAdam<TDatums>::WGuiAdam(const std::shared_ptr<GuiAdam>& guiAdam) : spGuiAdam{guiAdam} { } template<typename TDatums> void WGuiAdam<TDatums>::initializationOnThread() { try { spGuiAdam->initializationOnThread(); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums> void WGuiAdam<TDatums>::workConsumer(const TDatums& tDatums) { try { // tDatums might be empty but we still wanna update the GUI if (tDatums != nullptr) { // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // Profiling speed const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // Update cvMat & keypoints if (!tDatums->empty()) { // Update cvMat std::vector<cv::Mat> cvOutputDatas; for (auto& tDatum : *tDatums) cvOutputDatas.emplace_back(tDatum.cvOutputData); spGuiAdam->setImage(cvOutputDatas); // Update keypoints const auto& tDatum = (*tDatums)[0]; if (!tDatum.poseKeypoints3D.empty()) spGuiAdam->generateMesh(tDatum.poseKeypoints3D, tDatum.faceKeypoints3D, tDatum.handKeypoints3D, tDatum.adamPose.data(), tDatum.adamTranslation.data(), tDatum.vtVec.data(), tDatum.vtVec.rows(), tDatum.j0Vec.data(), tDatum.j0Vec.rows(), tDatum.adamFaceCoeffsExp.data()); } // Refresh/update GUI spGuiAdam->update(); // Profiling speed if (!tDatums->empty()) { Profiler::timerEnd(profilerKey); Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__); } // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } } catch (const std::exception& e) { this->stop(); error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } COMPILE_TEMPLATE_DATUM(WGuiAdam); } #endif // OPENPOSE_GUI_W_GUI_ADAM_HPP #endif <|start_filename|>src/openpose/pose/poseRenderer.cpp<|end_filename|> #include <openpose/pose/poseParameters.hpp> #include <openpose/pose/poseParametersRender.hpp> #include <openpose/pose/renderPose.hpp> #include <openpose/pose/poseRenderer.hpp> namespace op { std::map<unsigned int, std::string> createPartToName(const PoseModel poseModel) { try { auto partToName = getPoseBodyPartMapping(poseModel); const auto& bodyPartPairs = getPosePartPairs(poseModel); const auto& mapIdx = getPoseMapIndex(poseModel); const auto numberBodyPartsPlusBkg = getPoseNumberBodyParts(poseModel)+1; for (auto bodyPart = 0u; bodyPart < bodyPartPairs.size(); bodyPart+=2) { const auto bodyPartPairsA = bodyPartPairs.at(bodyPart); const auto bodyPartPairsB = bodyPartPairs.at(bodyPart+1); const auto mapIdxA = numberBodyPartsPlusBkg + mapIdx.at(bodyPart); const auto mapIdxB = numberBodyPartsPlusBkg + mapIdx.at(bodyPart+1); partToName[mapIdxA] = partToName.at(bodyPartPairsA) + "->" + partToName.at(bodyPartPairsB) + "(X)"; partToName[mapIdxB] = partToName.at(bodyPartPairsA) + "->" + partToName.at(bodyPartPairsB) + "(Y)"; } return partToName; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::map<unsigned int, std::string>(); } } PoseRenderer::PoseRenderer(const PoseModel poseModel) : mPoseModel{poseModel}, mPartIndexToName{createPartToName(poseModel)} { } } <|start_filename|>include/openpose/thread/thread.hpp<|end_filename|> #ifndef OPENPOSE_THREAD_THREAD_HPP #define OPENPOSE_THREAD_THREAD_HPP #include <atomic> #include <thread> #include <openpose/core/common.hpp> #include <openpose/thread/subThread.hpp> #include <openpose/thread/worker.hpp> namespace op { template<typename TDatums, typename TWorker = std::shared_ptr<Worker<TDatums>>> class Thread { public: explicit Thread(const std::shared_ptr<std::atomic<bool>>& isRunningSharedPtr = nullptr); // Move constructor Thread(Thread&& t); // Move assignment Thread& operator=(Thread&& t); // Destructor virtual ~Thread(); void add(const std::vector<std::shared_ptr<SubThread<TDatums, TWorker>>>& subThreads); void add(const std::shared_ptr<SubThread<TDatums, TWorker>>& subThread); void exec(const std::shared_ptr<std::atomic<bool>>& isRunningSharedPtr); void startInThread(); void stopAndJoin(); inline bool isRunning() const { return *spIsRunning; } private: std::shared_ptr<std::atomic<bool>> spIsRunning; std::vector<std::shared_ptr<SubThread<TDatums, TWorker>>> mSubThreads; std::thread mThread; void initializationOnThread(); void threadFunction(); void stop(); void join(); DELETE_COPY(Thread); }; } // Implementation namespace op { template<typename TDatums, typename TWorker> Thread<TDatums, TWorker>::Thread(const std::shared_ptr<std::atomic<bool>>& isRunningSharedPtr) : spIsRunning{(isRunningSharedPtr != nullptr ? isRunningSharedPtr : std::make_shared<std::atomic<bool>>(false))} { } template<typename TDatums, typename TWorker> Thread<TDatums, TWorker>::Thread(Thread<TDatums, TWorker>&& t) : spIsRunning{std::make_shared<std::atomic<bool>>(t.spIsRunning->load())} { std::swap(mSubThreads, t.mSubThreads); std::swap(mThread, t.mThread); } template<typename TDatums, typename TWorker> Thread<TDatums, TWorker>& Thread<TDatums, TWorker>::operator=(Thread<TDatums, TWorker>&& t) { std::swap(mSubThreads, t.mSubThreads); std::swap(mThread, t.mThread); spIsRunning = {std::make_shared<std::atomic<bool>>(t.spIsRunning->load())}; return *this; } template<typename TDatums, typename TWorker> Thread<TDatums, TWorker>::~Thread() { try { log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); stopAndJoin(); log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::add(const std::vector<std::shared_ptr<SubThread<TDatums, TWorker>>>& subThreads) { for (const auto& subThread : subThreads) mSubThreads.emplace_back(subThread); } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::add(const std::shared_ptr<SubThread<TDatums, TWorker>>& subThread) { add(std::vector<std::shared_ptr<SubThread<TDatums, TWorker>>>{subThread}); } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::exec(const std::shared_ptr<std::atomic<bool>>& isRunningSharedPtr) { try { stopAndJoin(); spIsRunning = isRunningSharedPtr; *spIsRunning = {true}; threadFunction(); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::startInThread() { try { log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); stopAndJoin(); *spIsRunning = {true}; mThread = {std::thread{&Thread::threadFunction, this}}; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::stopAndJoin() { try { stop(); join(); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::initializationOnThread() { try { log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); for (auto& subThread : mSubThreads) subThread->initializationOnThread(); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::threadFunction() { try { log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); initializationOnThread(); log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); while (isRunning()) { bool allSubThreadsClosed = true; for (auto& subThread : mSubThreads) allSubThreadsClosed &= !subThread->work(); if (allSubThreadsClosed) { log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); stop(); break; } } log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::stop() { try { *spIsRunning = {false}; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatums, typename TWorker> void Thread<TDatums, TWorker>::join() { try { if (mThread.joinable()) mThread.join(); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } COMPILE_TEMPLATE_DATUM(Thread); } #endif // OPENPOSE_THREAD_THREAD_HPP <|start_filename|>examples/tutorial_thread/2_user_processing_function.cpp<|end_filename|> // ------------------------- OpenPose Library Tutorial - Thread - Example 2 - User Processing Function ------------------------- // This fourth example shows the user how to: // 1. Read folder of images / video / webcam (`producer` module) // 2. Use the processing implemented by the user // 3. Display the rendered pose (`gui` module) // Everything in a multi-thread scenario (`thread` module) // In addition to the previous OpenPose modules, we also need to use: // 1. `core` module: for the Datum struct that the `thread` module sends between the queues // 2. `utilities` module: for the error & logging functions, i.e. op::error & op::log respectively // 3rdparty dependencies // GFlags: DEFINE_bool, _int32, _int64, _uint64, _double, _string #include <gflags/gflags.h> // Allow Google Flags in Ubuntu 14 #ifndef GFLAGS_GFLAGS_H_ namespace gflags = google; #endif // OpenPose dependencies #include <openpose/core/headers.hpp> #include <openpose/gui/headers.hpp> #include <openpose/producer/headers.hpp> #include <openpose/thread/headers.hpp> #include <openpose/utilities/headers.hpp> // See all the available parameter options withe the `--help` flag. E.g. `build/examples/openpose/openpose.bin --help` // Note: This command will show you flags for other unnecessary 3rdparty files. Check only the flags for the OpenPose // executable. E.g. for `openpose.bin`, look for `Flags from examples/openpose/openpose.cpp:`. // Debugging/Other DEFINE_int32(logging_level, 3, "The logging level. Integer in the range [0, 255]. 0 will output any log() message, while" " 255 will not output any. Current OpenPose library messages are in the range 0-4: 1 for" " low priority messages and 4 for important ones."); // Producer DEFINE_int32(camera, -1, "The camera index for cv::VideoCapture. Integer in the range [0, 9]. Select a negative" " number (by default), to auto-detect and open the first available camera."); DEFINE_string(camera_resolution, "-1x-1", "Set the camera resolution (either `--camera` or `--flir_camera`). `-1x-1` will use the" " default 1280x720 for `--camera`, or the maximum flir camera resolution available for" " `--flir_camera`"); DEFINE_double(camera_fps, 30.0, "Frame rate for the webcam (also used when saving video). Set this value to the minimum" " value between the OpenPose displayed speed and the webcam real frame rate."); DEFINE_string(video, "", "Use a video file instead of the camera. Use `examples/media/video.avi` for our default" " example video."); DEFINE_string(image_dir, "", "Process a directory of images. Use `examples/media/` for our default example folder with 20" " images. Read all standard formats (jpg, png, bmp, etc.)."); DEFINE_bool(flir_camera, false, "Whether to use FLIR (Point-Grey) stereo camera."); DEFINE_int32(flir_camera_index, -1, "Select -1 (default) to run on all detected flir cameras at once. Otherwise, select the flir" " camera index to run, where 0 corresponds to the detected flir camera with the lowest" " serial number, and `n` to the `n`-th lowest serial number camera."); DEFINE_string(ip_camera, "", "String with the IP camera URL. It supports protocols like RTSP and HTTP."); DEFINE_bool(process_real_time, false, "Enable to keep the original source frame rate (e.g. for video). If the processing time is" " too long, it will skip frames. If it is too fast, it will slow it down."); DEFINE_string(camera_parameter_folder, "models/cameraParameters/flir/", "String with the folder where the camera parameters are located."); DEFINE_bool(frame_keep_distortion, false, "If false (default), it will undistortionate the image based on the" " `camera_parameter_folder` camera parameters; if true, it will not undistortionate, i.e.," " it will leave it as it is."); // OpenPose DEFINE_string(output_resolution, "-1x-1", "The image resolution (display and output). Use \"-1x-1\" to force the program to use the" " input image resolution."); DEFINE_int32(3d_views, 1, "Complementary option to `--image_dir` or `--video`. OpenPose will read as many images per" " iteration, allowing tasks such as stereo camera processing (`--3d`). Note that" " `--camera_parameters_folder` must be set. OpenPose must find as many `xml` files in the" " parameter folder as this number indicates."); // Consumer DEFINE_bool(fullscreen, false, "Run in full-screen mode (press f during runtime to toggle)."); // This class can be implemented either as a template or as a simple class given // that the user usually knows which kind of data he will move between the queues, // in this case we assume a std::shared_ptr of a std::vector of op::Datum class WUserClass : public op::Worker<std::shared_ptr<std::vector<op::Datum>>> { public: WUserClass() { // User's constructor here } void initializationOnThread() {} void work(std::shared_ptr<std::vector<op::Datum>>& datumsPtr) { try { // User's processing here // datum.cvInputData: initial cv::Mat obtained from the frames producer (video, webcam, etc.) // datum.cvOutputData: final cv::Mat to be displayed if (datumsPtr != nullptr) for (auto& datum : *datumsPtr) cv::bitwise_not(datum.cvInputData, datum.cvOutputData); } catch (const std::exception& e) { op::log("Some kind of unexpected error happened."); this->stop(); op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } }; int openPoseTutorialThread2() { try { op::log("Starting OpenPose demo...", op::Priority::High); const auto timerBegin = std::chrono::high_resolution_clock::now(); // ------------------------- INITIALIZATION ------------------------- // Step 1 - Set logging level // - 0 will output all the logging messages // - 255 will output nothing op::check(0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.", __LINE__, __FUNCTION__, __FILE__); op::ConfigureLog::setPriorityThreshold((op::Priority)FLAGS_logging_level); // Step 2 - Read Google flags (user defined configuration) // outputSize const auto outputSize = op::flagsToPoint(FLAGS_output_resolution, "-1x-1"); // producerType const auto producerSharedPtr = op::flagsToProducer(FLAGS_image_dir, FLAGS_video, FLAGS_ip_camera, FLAGS_camera, FLAGS_flir_camera, FLAGS_camera_resolution, FLAGS_camera_fps, FLAGS_camera_parameter_folder, !FLAGS_frame_keep_distortion, (unsigned int) FLAGS_3d_views, FLAGS_flir_camera_index); const auto displayProducerFpsMode = (FLAGS_process_real_time ? op::ProducerFpsMode::OriginalFps : op::ProducerFpsMode::RetrievalFps); producerSharedPtr->setProducerFpsMode(displayProducerFpsMode); op::log("", op::Priority::Low, __LINE__, __FUNCTION__, __FILE__); // Step 3 - Setting producer auto videoSeekSharedPtr = std::make_shared<std::pair<std::atomic<bool>, std::atomic<int>>>(); videoSeekSharedPtr->first = false; videoSeekSharedPtr->second = 0; const op::Point<int> producerSize{(int)producerSharedPtr->get(CV_CAP_PROP_FRAME_WIDTH), (int)producerSharedPtr->get(CV_CAP_PROP_FRAME_HEIGHT)}; // Step 4 - Setting thread workers && manager typedef std::vector<op::Datum> TypedefDatumsNoPtr; typedef std::shared_ptr<TypedefDatumsNoPtr> TypedefDatums; op::ThreadManager<TypedefDatums> threadManager; // Step 5 - Initializing the worker classes // Frames producer (e.g. video, webcam, ...) auto DatumProducer = std::make_shared<op::DatumProducer<TypedefDatumsNoPtr>>(producerSharedPtr); auto wDatumProducer = std::make_shared<op::WDatumProducer<TypedefDatums, TypedefDatumsNoPtr>>(DatumProducer); // Specific WUserClass auto wUserClass = std::make_shared<WUserClass>(); // GUI (Display) auto gui = std::make_shared<op::Gui>(outputSize, FLAGS_fullscreen, threadManager.getIsRunningSharedPtr()); auto wGui = std::make_shared<op::WGui<TypedefDatums>>(gui); // ------------------------- CONFIGURING THREADING ------------------------- // In this simple multi-thread example, we will do the following: // 3 (virtual) queues: 0, 1, 2 // 1 real queue: 1. The first and last queue ids (in this case 0 and 2) are not actual queues, but the // beginning and end of the processing sequence // 2 threads: 0, 1 // wDatumProducer will generate frames (there is no real queue 0) and push them on queue 1 // wGui will pop frames from queue 1 and process them (there is no real queue 2) auto threadId = 0ull; auto queueIn = 0ull; auto queueOut = 1ull; threadManager.add(threadId++, wDatumProducer, queueIn++, queueOut++); // Thread 0, queues 0 -> 1 threadManager.add(threadId++, wUserClass, queueIn++, queueOut++); // Thread 1, queues 1 -> 2 threadManager.add(threadId++, wGui, queueIn++, queueOut++); // Thread 2, queues 2 -> 3 // Equivalent single-thread version // const auto threadId = 0ull; // auto queueIn = 0ull; // auto queueOut = 1ull; // threadManager.add(threadId, wDatumProducer, queueIn++, queueOut++); // Thread 0, queues 0 -> 1 // threadManager.add(threadId, wUserClass, queueIn++, queueOut++); // Thread 1, queues 1 -> 2 // threadManager.add(threadId, wGui, queueIn++, queueOut++); // Thread 2, queues 2 -> 3 // Smart multi-thread version // Assume wUser is the slowest process, and that wDatumProducer + wGui is faster than wGui itself, // then, we can group the last 2 in the same thread and keep wGui in a different thread: // const auto threadId = 0ull; // auto queueIn = 0ull; // auto queueOut = 1ull; // threadManager.add(threadId, wDatumProducer, queueIn++, queueOut++); // Thread 0, queues 0 -> 1 // threadManager.add(threadId+1, wUserClass, queueIn++, queueOut++); // Thread 1, queues 1 -> 2 // threadManager.add(threadId, wGui, queueIn++, queueOut++); // Thread 0, queues 2 -> 3 // ------------------------- STARTING AND STOPPING THREADING ------------------------- op::log("Starting thread(s)...", op::Priority::High); // Two different ways of running the program on multithread environment // Option a) Using the main thread (this thread) for processing (it saves 1 thread, recommended) threadManager.exec(); // Option b) Giving to the user the control of this thread // // VERY IMPORTANT NOTE: if OpenCV is compiled with Qt support, this option will not work. Qt needs the main // // thread to plot visual results, so the final GUI (which uses OpenCV) would return an exception similar to: // // `QMetaMethod::invoke: Unable to invoke methods with return values in queued connections` // // Start threads // threadManager.start(); // // Keep program alive while running threads. Here the user could perform any other desired function // while (threadManager.isRunning()) // std::this_thread::sleep_for(std::chrono::milliseconds{33}); // // Stop and join threads // op::log("Stopping thread(s)", op::Priority::High); // threadManager.stop(); // ------------------------- CLOSING ------------------------- // Measuring total time const auto now = std::chrono::high_resolution_clock::now(); const auto totalTimeSec = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(now-timerBegin).count() * 1e-9; const auto message = "OpenPose demo successfully finished. Total time: " + std::to_string(totalTimeSec) + " seconds."; op::log(message, op::Priority::High); // Return successful message return 0; } catch (const std::exception& e) { op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); return -1; } } int main(int argc, char *argv[]) { // Parsing command line flags gflags::ParseCommandLineFlags(&argc, &argv, true); // Running openPoseTutorialThread2 return openPoseTutorialThread2(); } <|start_filename|>src/openpose/tracking/personTracker.cpp<|end_filename|> #include <iostream> #include <thread> #include <opencv2/imgproc/imgproc.hpp> // cv::resize #include <openpose/tracking/personTracker.hpp> #include <openpose/utilities/fastMath.hpp> #include <openpose/tracking/pyramidalLK.hpp> namespace op { int roundUp(const int numToRound, const int multiple) { if (multiple == 0) return numToRound; const int remainder = numToRound % multiple; if (remainder == 0) return numToRound; return numToRound + multiple - remainder; } float computePersonScale(const PersonTrackerEntry& personEntry, const cv::Mat& imageCurrent) { int layerCount = 0; if (personEntry.status[0] || personEntry.status[14] || personEntry.status[15] || personEntry.status[16] || personEntry.status[17]) layerCount++; if (personEntry.status[2] || personEntry.status[3] || personEntry.status[4] || personEntry.status[5] || personEntry.status[6] || personEntry.status[7]) layerCount++; if (personEntry.status[8] || personEntry.status[11]) layerCount++; if (personEntry.status[9] || personEntry.status[10] || personEntry.status[12] || personEntry.status[13]) layerCount++; float minX = imageCurrent.size().width; float maxX = 0; float minY = imageCurrent.size().height; float maxY = 0; int totalKp = 0; for (size_t i=0; i<personEntry.keypoints.size(); i++) { if (personEntry.status[i]) { const auto kp = personEntry.keypoints[i]; if (kp.x < minX) minX = kp.x; if (kp.x > maxX) maxX = kp.x; if (kp.y < minY) minY = kp.y; if (kp.y > maxY) maxY = kp.y; totalKp++; } } const float xDist = (maxX - minX); const float yDist = (maxY - minY); float maxDist; if (xDist > yDist) maxDist = (xDist)*(4/layerCount); else maxDist = (yDist)*(4/layerCount); const float lkSize = roundUp(int(maxDist / 10.), 3); // std::cout << lkSize << std::endl; return lkSize; } void updateLK(std::unordered_map<int,PersonTrackerEntry>& personEntries, std::vector<cv::Mat>& pyramidImagesPrevious, std::vector<cv::Mat>& pyramidImagesCurrent, const cv::Mat& imagePrevious, const cv::Mat& imageCurrent, const int levels, const int patchSize, const bool trackVelocity, const bool scaleVarying) { try { // Inefficient version, do it per person for (auto& kv : personEntries) { PersonTrackerEntry newPersonEntry; PersonTrackerEntry& oldPersonEntry = kv.second; int lkSize = patchSize; if (scaleVarying) { pyramidImagesPrevious.clear(); lkSize = computePersonScale(oldPersonEntry, imageCurrent); } if (trackVelocity) { newPersonEntry.keypoints = oldPersonEntry.getPredicted(); pyramidalLKOcv(oldPersonEntry.keypoints, newPersonEntry.keypoints, pyramidImagesPrevious, pyramidImagesCurrent, oldPersonEntry.status, imagePrevious, imageCurrent, levels, patchSize, true); } else pyramidalLKOcv(oldPersonEntry.keypoints, newPersonEntry.keypoints, pyramidImagesPrevious, pyramidImagesCurrent, oldPersonEntry.status, imagePrevious, imageCurrent, levels, lkSize, false); newPersonEntry.lastKeypoints = oldPersonEntry.keypoints; newPersonEntry.status = oldPersonEntry.status; oldPersonEntry = newPersonEntry; } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } // void vizPersonEntries(cv::Mat& debugImage, const std::unordered_map<int, PersonTrackerEntry>& personEntries, // const bool mTrackVelocity) // { // try // { // for (auto& kv : personEntries) // { // const PersonTrackerEntry& pe = kv.second; // const std::vector<cv::Point2f> predictedKeypoints = pe.getPredicted(); // for (size_t i=0; i<pe.keypoints.size(); i++) // { // cv::circle(debugImage, pe.keypoints[i], 3, cv::Scalar(255,0,0),CV_FILLED); // cv::putText(debugImage, std::to_string((int)pe.status[i]), pe.keypoints[i], // cv::FONT_HERSHEY_DUPLEX, 0.4, cv::Scalar(0,0,255),1); // if (pe.lastKeypoints.size()) // { // cv::line(debugImage, pe.keypoints[i], pe.lastKeypoints[i],cv::Scalar(255,0,0)); // cv::circle(debugImage, pe.lastKeypoints[i], 3, cv::Scalar(255,255,0),CV_FILLED); // } // if (predictedKeypoints.size() && mTrackVelocity) // { // cv::line(debugImage, pe.keypoints[i], predictedKeypoints[i],cv::Scalar(255,0,0)); // cv::circle(debugImage, predictedKeypoints[i], 3, cv::Scalar(255,0,255),CV_FILLED); // } // } // } // } // catch (const std::exception& e) // { // error(e.what(), __LINE__, __FUNCTION__, __FILE__); // } // } void personEntriesFromOP(std::unordered_map<int, PersonTrackerEntry>& personEntries, const Array<float>& poseKeypoints, const Array<long long>& poseIds, float confidenceThreshold) { try { personEntries.clear(); for (int i=0; i<poseKeypoints.getSize(0); i++) { const auto id = poseIds[i]; personEntries[id] = PersonTrackerEntry(); personEntries[id].keypoints.resize(poseKeypoints.getSize(1)); personEntries[id].status.resize(poseKeypoints.getSize(1)); for (int j=0; j<poseKeypoints.getSize(1); j++) { personEntries[id].keypoints[j].x = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 0]; personEntries[id].keypoints[j].y = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 1]; const float prob = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 2]; if (prob < confidenceThreshold) personEntries[id].status[j] = 0; else personEntries[id].status[j] = 1; } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void syncPersonEntriesWithOP(std::unordered_map<int, PersonTrackerEntry>& personEntries, const Array<float>& poseKeypoints, const Array<long long>& poseIds, float confidenceThreshold, bool mergeResults) { try { if (!poseIds.empty()) { // Delete for (auto kv = personEntries.cbegin(); kv != personEntries.cend() /* not hoisted */; /* no increment */) { bool exists = false; for (int i=0; i<poseIds.getSize(0); i++) { const auto id = poseIds[i]; if (id == kv->first) exists = true; } if (!exists) personEntries.erase(kv++); else ++kv; } // Update or Add for (int i=0; i<poseIds.getSize(0); i++) { const auto id = poseIds[i]; // Update if (personEntries.count(id) && mergeResults) { PersonTrackerEntry& personEntry = personEntries[id]; for (int j=0; j<poseKeypoints.getSize(1); j++) { const float x = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 0]; const float y = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 1]; const float prob = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 2]; const cv::Point lkPoint = personEntry.keypoints[j]; const cv::Point opPoint = cv::Point(x,y); if (prob < confidenceThreshold) personEntries[id].status[j] = 0; else { personEntries[id].status[j] = 1; float distance = sqrt(pow(lkPoint.x-opPoint.x,2)+pow(lkPoint.y-opPoint.y,2)); if (distance < 5) personEntries[id].keypoints[j] = lkPoint; else if (distance < 10) personEntries[id].keypoints[j] = cv::Point{intRound((lkPoint.x+opPoint.x)/2.), intRound((lkPoint.y+opPoint.y)/2.)}; else personEntries[id].keypoints[j] = opPoint; } } } // Add else { personEntries[id] = PersonTrackerEntry(); personEntries[id].keypoints.resize(poseKeypoints.getSize(1)); personEntries[id].status.resize(poseKeypoints.getSize(1)); for (int j=0; j<poseKeypoints.getSize(1); j++) { personEntries[id].keypoints[j].x = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 0]; personEntries[id].keypoints[j].y = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 1]; const float prob = poseKeypoints[ i*poseKeypoints.getSize(1)*poseKeypoints.getSize(2) + j*poseKeypoints.getSize(2) + 2]; if (prob < confidenceThreshold) personEntries[id].status[j] = 0; else personEntries[id].status[j] = 1; } } } // Sanity Check Start if ((int)personEntries.size() != poseIds.getSize(0)) { // Print for (auto& kv : personEntries) std::cout << kv.first << " "; std::cout << std::endl; for (int i=0; i<poseIds.getSize(0); i++) std::cout << poseIds.at(i) << " "; std::cout << std::endl; std::cout << "---" << std::endl; error("Size Mismatch. THere is an error in your poseId formatting.", __LINE__, __FUNCTION__, __FILE__); } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void opFromPersonEntries(Array<float>& poseKeypoints, const std::unordered_map<int, PersonTrackerEntry>& personEntries, const Array<long long>& poseIds) { try { if (personEntries.size() && !poseIds.empty()) { int dims[] = { (int)personEntries.size(), (int)personEntries.begin()->second.keypoints.size(), 3 }; cv::Mat opArrayMat(3,dims,CV_32FC1); for (auto i=0; i<poseIds.getSize(0); i++) { const int id = poseIds[i]; const PersonTrackerEntry& pe = personEntries.at(id); for (int j=0; j<dims[1]; j++) { const auto baseIndex = i*dims[1]*dims[2] + j*dims[2]; opArrayMat.at<float>(baseIndex + 0) = pe.keypoints[j].x; opArrayMat.at<float>(baseIndex + 1) = pe.keypoints[j].y; opArrayMat.at<float>(baseIndex + 2) = (int)pe.status[j]; if (pe.keypoints[j].x == 0 && pe.keypoints[j].y == 0) opArrayMat.at<float>(baseIndex + 2) = 0; } } poseKeypoints.setFrom(opArrayMat); } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void scaleKeypoints(std::unordered_map<int, PersonTrackerEntry>& personEntries, const float xScale, const float yScale) { try { for (auto& kv : personEntries) { for (size_t i=0; i<kv.second.keypoints.size(); i++) { kv.second.keypoints[i].x *= xScale; kv.second.keypoints[i].y *= yScale; } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } PersonTracker::PersonTracker(const bool mergeResults, const int levels, const int patchSize, const float confidenceThreshold, const bool trackVelocity, const bool scaleVarying, const float rescale) : mMergeResults{mergeResults}, mLevels{levels}, mPatchSize{patchSize}, mTrackVelocity{trackVelocity}, mConfidenceThreshold{confidenceThreshold}, mScaleVarying{scaleVarying}, mRescale{rescale}, mLastFrameId{-1ll} { try { error("PersonTracker (`tracking` flag) buggy and not working yet, but we are working on it!" " Coming soon!", __LINE__, __FUNCTION__, __FILE__); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } PersonTracker::~PersonTracker() { } void PersonTracker::track(Array<float>& poseKeypoints, Array<long long>& poseIds, const cv::Mat& cvMatInput) { try { /* * 1. Get poseKeypoints for all people - Checks * 2. If last image is empty or mPersonEntries is empty (& poseKeypoints and poseIds has data or crash it) * Create mPersonEntries referencing poseIds * Initialize LK points * 3. If poseKeypoints is not empty and poseIds has data * 1. Update LK * 2. CRUD/Sync - Check mMergeResults flag to smooth or not * 4. If poseKeypoints is empty * 1. Update LK * 2. replace poseKeypoints */ // TODO: This case: if mMergeResults == false --> Run LK tracker ONLY IF poseKeypoints.empty() doesn't // consider the case of poseKeypoints being empty BECAUSE there were no people on the image // if mMergeResults == true --> Combine OP + LK tracker // if mMergeResults == false --> Run LK tracker ONLY IF poseKeypoints.empty() bool mergeResults = mMergeResults; mergeResults = true; // Sanity Checks if (poseKeypoints.getSize(0) != poseIds.getSize(0)) error("poseKeypoints and poseIds should have the same number of people", __LINE__, __FUNCTION__, __FILE__); // First frame if (mImagePrevious.empty()) { // Create mPersonEntries personEntriesFromOP(mPersonEntries, poseKeypoints, poseIds, mConfidenceThreshold); // Capture current frame as floating point cvMatInput.convertTo(mImagePrevious, CV_8UC3); // Rescale if (mRescale) { cv::Size rescaleSize(mRescale,mImagePrevious.size().height/(mImagePrevious.size().width/mRescale)); cv::resize(mImagePrevious, mImagePrevious, rescaleSize, 0, 0, cv::INTER_CUBIC); } // Save Last Ids mLastPoseIds = poseIds.clone(); } // Any other frame else { // Update LK const bool newOPData = !poseKeypoints.empty() && !poseIds.empty(); if ((newOPData && mergeResults) || (!newOPData)) { cv::Mat imageCurrent; std::vector<cv::Mat> pyramidImagesCurrent; cvMatInput.convertTo(imageCurrent, CV_8UC3); float xScale = 1., yScale = 1.; if (mRescale) { cv::Size rescaleSize(mRescale,imageCurrent.size().height/(imageCurrent.size().width/mRescale)); xScale = (float)imageCurrent.size().width / (float)rescaleSize.width; yScale = (float)imageCurrent.size().height / (float)rescaleSize.height; cv::resize(imageCurrent, imageCurrent, rescaleSize, 0, 0, cv::INTER_CUBIC); } scaleKeypoints(mPersonEntries, 1./xScale, 1./yScale); updateLK(mPersonEntries, mPyramidImagesPrevious, pyramidImagesCurrent, mImagePrevious, imageCurrent, mLevels, mPatchSize, mTrackVelocity, mScaleVarying); scaleKeypoints(mPersonEntries, xScale, yScale); mImagePrevious = imageCurrent; mPyramidImagesPrevious = pyramidImagesCurrent; } // There is new OP Data if (newOPData) { mLastPoseIds = poseIds.clone(); syncPersonEntriesWithOP(mPersonEntries, poseKeypoints, mLastPoseIds, mConfidenceThreshold, mergeResults); opFromPersonEntries(poseKeypoints, mPersonEntries, mLastPoseIds); } // There is no new OP Data else { opFromPersonEntries(poseKeypoints, mPersonEntries, mLastPoseIds); poseIds = mLastPoseIds.clone(); } } // cv::Mat debugImage = cvMatInput.clone(); // vizPersonEntries(debugImage, mPersonEntries, mTrackVelocity); // cv::imshow("win", debugImage); // cv::waitKey(15); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void PersonTracker::trackLockThread(Array<float>& poseKeypoints, Array<long long>& poseIds, const cv::Mat& cvMatInput, const long long frameId) { try { // Wait for desired order while (mLastFrameId < frameId - 1) std::this_thread::sleep_for(std::chrono::microseconds{100}); // Extract IDs track(poseKeypoints, poseIds, cvMatInput); // Update last frame id mLastFrameId = frameId; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } bool PersonTracker::getMergeResults() const { try { return mMergeResults; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return false; } } } <|start_filename|>src/openpose/pose/poseGpuRenderer.cpp<|end_filename|> #ifdef USE_CUDA #include <cuda.h> #include <cuda_runtime_api.h> #endif #include <openpose/pose/poseParameters.hpp> #include <openpose/pose/renderPose.hpp> #include <openpose/gpu/cuda.hpp> #include <openpose/utilities/keypoint.hpp> #include <openpose/pose/poseGpuRenderer.hpp> namespace op { PoseGpuRenderer::PoseGpuRenderer(const PoseModel poseModel, const std::shared_ptr<PoseExtractorNet>& poseExtractorNet, const float renderThreshold, const bool blendOriginalFrame, const float alphaKeypoint, const float alphaHeatMap, const unsigned int elementToRender) : // #body elements to render = #body parts (size()) + #body part pair connections // + 3 (+whole pose +whole heatmaps +PAFs) // POSE_BODY_PART_MAPPING crashes on Windows, replaced by getPoseBodyPartMapping GpuRenderer{renderThreshold, alphaKeypoint, alphaHeatMap, blendOriginalFrame, elementToRender, getNumberElementsToRender(poseModel)}, // mNumberElementsToRender PoseRenderer{poseModel}, spPoseExtractorNet{poseExtractorNet}, pGpuPose{nullptr} { } PoseGpuRenderer::~PoseGpuRenderer() { try { // Free CUDA pointers - Note that if pointers are 0 (i.e. nullptr), no operation is performed. #ifdef USE_CUDA cudaFree(pGpuPose); #endif } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void PoseGpuRenderer::initializationOnThread() { try { log("Starting initialization on thread.", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // GPU memory allocation for rendering #ifdef USE_CUDA cudaMalloc((void**)(&pGpuPose), POSE_MAX_PEOPLE * getPoseNumberBodyParts(mPoseModel) * 3 * sizeof(float)); cudaCheck(__LINE__, __FUNCTION__, __FILE__); #endif log("Finished initialization on thread.", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } std::pair<int, std::string> PoseGpuRenderer::renderPose(Array<float>& outputData, const Array<float>& poseKeypoints, const float scaleInputToOutput, const float scaleNetToOutput) { try { // Security checks if (outputData.empty()) error("Empty Array<float> outputData.", __LINE__, __FUNCTION__, __FILE__); // GPU rendering const auto elementRendered = spElementToRender->load(); std::string elementRenderedName; #ifdef USE_CUDA const auto numberPeople = poseKeypoints.getSize(0); if (numberPeople > 0 || elementRendered != 0 || !mBlendOriginalFrame) { cpuToGpuMemoryIfNotCopiedYet(outputData.getPtr(), outputData.getVolume()); cudaCheck(__LINE__, __FUNCTION__, __FILE__); const auto numberBodyParts = getPoseNumberBodyParts(mPoseModel); const auto numberBodyPartsPlusBkg = numberBodyParts+1; const Point<int> frameSize{outputData.getSize(1), outputData.getSize(0)}; // Draw poseKeypoints if (elementRendered == 0) { // Rescale keypoints to output size auto poseKeypointsRescaled = poseKeypoints.clone(); scaleKeypoints(poseKeypointsRescaled, scaleInputToOutput); // Render keypoints if (!poseKeypoints.empty()) cudaMemcpy(pGpuPose, poseKeypointsRescaled.getConstPtr(), numberPeople * numberBodyParts * 3 * sizeof(float), cudaMemcpyHostToDevice); renderPoseKeypointsGpu(*spGpuMemory, mPoseModel, numberPeople, frameSize, pGpuPose, mRenderThreshold, mShowGooglyEyes, mBlendOriginalFrame, getAlphaKeypoint()); } else { // If resized to input resolution: Replace scaleNetToOutput * scaleInputToOutput by // scaleInputToOutput, and comment the security checks. // Security checks if (scaleNetToOutput == -1.f) error("Non valid scaleNetToOutput.", __LINE__, __FUNCTION__, __FILE__); // Parameters const auto& heatMapSizes = spPoseExtractorNet->getHeatMapSize(); const Point<int> heatMapSize{heatMapSizes[3], heatMapSizes[2]}; // Add all heatmaps if (elementRendered == 2) // if (elementRendered == numberBodyPartsPlusBkg+1) { elementRenderedName = "Heatmaps"; renderPoseHeatMapsGpu(*spGpuMemory, mPoseModel, frameSize, spPoseExtractorNet->getHeatMapGpuConstPtr(), heatMapSize, scaleNetToOutput * scaleInputToOutput, (mBlendOriginalFrame ? getAlphaHeatMap() : 1.f)); } // Draw PAFs (Part Affinity Fields) else if (elementRendered == 3) // else if (elementRendered == numberBodyPartsPlusBkg+2) { elementRenderedName = "PAFs (Part Affinity Fields)"; renderPosePAFsGpu(*spGpuMemory, mPoseModel, frameSize, spPoseExtractorNet->getHeatMapGpuConstPtr(), heatMapSize, scaleNetToOutput * scaleInputToOutput, (mBlendOriginalFrame ? getAlphaHeatMap() : 1.f)); } // Draw specific body part or background else if (elementRendered <= numberBodyPartsPlusBkg+2) { const auto realElementRendered = (elementRendered == 1 ? numberBodyPartsPlusBkg : elementRendered - 3); elementRenderedName = mPartIndexToName.at(realElementRendered-1); renderPoseHeatMapGpu(*spGpuMemory, mPoseModel, frameSize, spPoseExtractorNet->getHeatMapGpuConstPtr(), heatMapSize, scaleNetToOutput * scaleInputToOutput, realElementRendered, (mBlendOriginalFrame ? getAlphaHeatMap() : 1.f)); } // Draw affinity between 2 body parts else { const auto affinityPart = (elementRendered-numberBodyPartsPlusBkg-3)*2; const auto affinityPartMapped = numberBodyPartsPlusBkg+getPoseMapIndex(mPoseModel).at(affinityPart); elementRenderedName = mPartIndexToName.at(affinityPartMapped); elementRenderedName = elementRenderedName.substr(0, elementRenderedName.find("(")); renderPosePAFGpu(*spGpuMemory, mPoseModel, frameSize, spPoseExtractorNet->getHeatMapGpuConstPtr(), heatMapSize, scaleNetToOutput * scaleInputToOutput, affinityPartMapped, (mBlendOriginalFrame ? getAlphaHeatMap() : 1.f)); } } } // GPU memory to CPU if last renderer gpuToCpuMemoryIfLastRenderer(outputData.getPtr(), outputData.getVolume()); cudaCheck(__LINE__, __FUNCTION__, __FILE__); #else UNUSED(outputData); UNUSED(poseKeypoints); UNUSED(scaleInputToOutput); UNUSED(scaleNetToOutput); error("OpenPose must be compiled with the `USE_CUDA` macro definitions in order to run this" " functionality. You can alternatively use CPU rendering (flag `--render_pose 1`).", __LINE__, __FUNCTION__, __FILE__); #endif // Return result return std::make_pair(elementRendered, elementRenderedName); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_pair(-1, ""); } } } <|start_filename|>src/openpose/wrapper/wrapperStructOutput.cpp<|end_filename|> #include <openpose/wrapper/wrapperStructOutput.hpp> namespace op { WrapperStructOutput::WrapperStructOutput(const DisplayMode displayMode_, const bool guiVerbose_, const bool fullScreen_, const std::string& writeKeypoint_, const DataFormat writeKeypointFormat_, const std::string& writeJson_, const std::string& writeCocoJson_, const std::string& writeCocoFootJson_, const std::string& writeImages_, const std::string& writeImagesFormat_, const std::string& writeVideo_, const double writeVideoFps_, const std::string& writeHeatMaps_, const std::string& writeHeatMapsFormat_, const std::string& writeVideoAdam_, const std::string& writeBvh_, const std::string& udpHost_, const std::string& udpPort_) : displayMode{displayMode_}, guiVerbose{guiVerbose_}, fullScreen{fullScreen_}, writeKeypoint{writeKeypoint_}, writeKeypointFormat{writeKeypointFormat_}, writeJson{writeJson_}, writeCocoJson{writeCocoJson_}, writeCocoFootJson{writeCocoFootJson_}, writeImages{writeImages_}, writeImagesFormat{writeImagesFormat_}, writeVideo{writeVideo_}, writeHeatMaps{writeHeatMaps_}, writeHeatMapsFormat{writeHeatMapsFormat_}, writeVideoFps{writeVideoFps_}, writeVideoAdam{writeVideoAdam_}, writeBvh{writeBvh_}, udpHost{udpHost_}, udpPort{udpPort_} { } } <|start_filename|>include/openpose/net/resizeAndMergeBase.hpp<|end_filename|> #ifndef OPENPOSE_NET_RESIZE_AND_MERGE_BASE_HPP #define OPENPOSE_NET_RESIZE_AND_MERGE_BASE_HPP #include <openpose/core/common.hpp> namespace op { template <typename T> OP_API void resizeAndMergeCpu(T* targetPtr, const std::vector<const T*>& sourcePtrs, const std::array<int, 4>& targetSize, const std::vector<std::array<int, 4>>& sourceSizes, const std::vector<T>& scaleInputToNetInputs = {1.f}); template <typename T> OP_API void resizeAndMergeGpu(T* targetPtr, const std::vector<const T*>& sourcePtrs, const std::array<int, 4>& targetSize, const std::vector<std::array<int, 4>>& sourceSizes, const std::vector<T>& scaleInputToNetInputs = {1.f}); template <typename T> OP_API void resizeAndMergeOcl(T* targetPtr, const std::vector<const T*>& sourcePtrs, std::vector<T*>& sourceTempPtrs, const std::array<int, 4>& targetSize, const std::vector<std::array<int, 4>>& sourceSizes, const std::vector<T>& scaleInputToNetInputs = {1.f}, const int gpuID = 0); } #endif // OPENPOSE_NET_RESIZE_AND_MERGE_BASE_HPP <|start_filename|>include/openpose/filestream/wUdpSender.hpp<|end_filename|> #ifndef OPENPOSE_FILESTREAM_W_UDP_SENDER_HPP #define OPENPOSE_FILESTREAM_W_UDP_SENDER_HPP #include <openpose/core/common.hpp> #include <openpose/filestream/udpSender.hpp> #include <openpose/thread/workerConsumer.hpp> namespace op { template<typename TDatums> class WUdpSender : public WorkerConsumer<TDatums> { public: explicit WUdpSender(const std::shared_ptr<UdpSender>& udpSender); void initializationOnThread(); void workConsumer(const TDatums& tDatums); private: const std::shared_ptr<UdpSender> spUdpSender; DELETE_COPY(WUdpSender); }; } // Implementation #include <openpose/utilities/pointerContainer.hpp> namespace op { template<typename TDatums> WUdpSender<TDatums>::WUdpSender(const std::shared_ptr<UdpSender>& udpSender) : spUdpSender{udpSender} { } template<typename TDatums> void WUdpSender<TDatums>::initializationOnThread() { } template<typename TDatums> void WUdpSender<TDatums>::workConsumer(const TDatums& tDatums) { try { if (checkNoNullNorEmpty(tDatums)) { // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // Profiling speed const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // Send though UDP communication #ifdef USE_3D_ADAM_MODEL const auto& tDatum = (*tDatums)[0]; if (!tDatum.poseKeypoints3D.empty()) { const auto& adamPose = tDatum.adamPose; // Eigen::Matrix<double, 62, 3, Eigen::RowMajor> const auto& adamTranslation = tDatum.adamTranslation; // Eigen::Vector3d(3, 1) const auto adamFaceCoeffsExp = tDatum.adamFaceCoeffsExp; // Eigen::VectorXd resized to (200, 1) //const float mouth_open = tDatum.mouthOpening; // tDatum.mouth_open; //const float leye_open = tDatum.rightEyeOpening; // tDatum.leye_open; //const float reye_open = tDatum.leftEyeOpening; // tDatum.reye_open; //const float dist_root_foot = Datum.distanceRootFoot; // tDatum.dist_root_foot; // m_adam_t: // 1. Total translation (centimeters) of the root in camera/global coordinate representation. // m_adam_pose: // 1. First row is global rotation, in AngleAxis representation. Radians (not degrees!) // 2. Rest are joint-angles in Euler-Angle representation. Degrees. spUdpSender->sendJointAngles(adamPose.data(), adamPose.rows(), adamTranslation.data(), adamFaceCoeffsExp.data(), adamFaceCoeffsExp.rows()); } #endif // Profiling speed Profiler::timerEnd(profilerKey); Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__); // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } } catch (const std::exception& e) { this->stop(); error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } COMPILE_TEMPLATE_DATUM(WUdpSender); } #endif // OPENPOSE_FILESTREAM_W_UDP_SENDER_HPP <|start_filename|>include/openpose/3d/jointAngleEstimation.hpp<|end_filename|> #ifdef USE_3D_ADAM_MODEL #ifndef OPENPOSE_3D_JOINT_ANGLE_ESTIMATION_HPP #define OPENPOSE_3D_JOINT_ANGLE_ESTIMATION_HPP #ifdef USE_EIGEN #include <Eigen/Core> #endif #ifdef USE_3D_ADAM_MODEL #include <adam/totalmodel.h> #endif #include <opencv2/core/core.hpp> #include <openpose/core/common.hpp> namespace op { OP_API int mapOPToAdam(const int oPPart); class OP_API JointAngleEstimation { public: static const std::shared_ptr<const TotalModel> getTotalModel(); JointAngleEstimation(const bool returnJacobian); void initializationOnThread(); void adamFastFit(Eigen::Matrix<double, 62, 3, Eigen::RowMajor>& adamPose, Eigen::Vector3d& adamTranslation, Eigen::Matrix<double, Eigen::Dynamic, 1>& vtVec, Eigen::Matrix<double, Eigen::Dynamic, 1>& j0Vec, Eigen::VectorXd& adamFacecoeffsExp, const Array<float>& poseKeypoints3D, const Array<float>& faceKeypoints3D, const std::array<Array<float>, 2>& handKeypoints3D); private: // PIMPL idiom // http://www.cppsamples.com/common-tasks/pimpl.html struct ImplJointAngleEstimation; std::shared_ptr<ImplJointAngleEstimation> spImpl; // PIMP requires DELETE_COPY & destructor, or extra code // http://oliora.github.io/2015/12/29/pimpl-and-rule-of-zero.html DELETE_COPY(JointAngleEstimation); }; } #endif // OPENPOSE_3D_JOINT_ANGLE_ESTIMATION_HPP #endif <|start_filename|>src/openpose/calibration/cameraParameterEstimation.cpp<|end_filename|> #include <fstream> #include <numeric> // std::accumulate #include <thread> #include <opencv2/core/core.hpp> #ifdef USE_EIGEN #include <Eigen/Dense> #include <opencv2/core/eigen.hpp> #endif #include <openpose/3d/cameraParameterReader.hpp> #include <openpose/calibration/gridPatternFunctions.hpp> #include <openpose/filestream/fileStream.hpp> #include <openpose/utilities/fileSystem.hpp> #include <openpose/calibration/cameraParameterEstimation.hpp> namespace op { // Private variables const long double PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844; // Private functions struct Intrinsics { cv::Mat cameraMatrix; cv::Mat distortionCoefficients; Intrinsics() : cameraMatrix(cv::Mat::eye(3, 3, CV_64F)), distortionCoefficients(cv::Mat::zeros(14, 1, CV_64F)) { } Intrinsics(const cv::Mat& cameraMatrix, const cv::Mat& distortionCoefficients) : cameraMatrix{cameraMatrix.clone()}, // cv::Mat::eye(3, 3, CV_64F) distortionCoefficients{distortionCoefficients.clone()} // cv::Mat::zeros(14||12||8||5, 1, CV_64F) { } bool empty() { return cameraMatrix.empty() || distortionCoefficients.empty(); } }; #ifdef USE_EIGEN struct Extrinsics { Eigen::Matrix3d Rotation; Eigen::Vector3d translationMm; std::vector<cv::Point2f> points2DVector; std::vector<cv::Point3f> objects3DVector; Extrinsics() { Rotation.setIdentity(); translationMm.setZero(); } }; #endif std::vector<std::string> getImagePaths(const std::string& imageDirectoryPath) { try { // Get files on directory with the desired extensions const std::vector<std::string> extensions{ // Completely supported by OpenCV "bmp", "dib", "pbm", "pgm", "ppm", "sr", "ras", // Most of them supported by OpenCV "jpg", "jpeg", "png"}; const auto imagePaths = getFilesOnDirectory(imageDirectoryPath, extensions); // Check #files > 0 if (imagePaths.empty()) error("No images were found on `" + imageDirectoryPath + "`.", __LINE__, __FUNCTION__, __FILE__); // Return result return imagePaths; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return {}; } } std::vector<std::pair<cv::Mat, std::string>> getImageAndPaths(const std::string& imageDirectoryPath) { try { // Get images on directory const auto imagePaths = getImagePaths(imageDirectoryPath); // Check #files > 0 if (imagePaths.empty()) error("No images were found on `" + imageDirectoryPath + "`.", __LINE__, __FUNCTION__, __FILE__); // Read images std::vector<std::pair<cv::Mat, std::string>> imageAndPaths; for (const auto& imagePath : imagePaths) { imageAndPaths.emplace_back(std::make_pair(cv::imread(imagePath, CV_LOAD_IMAGE_COLOR), imagePath)); if (imageAndPaths.back().first.empty()) error("Image could not be opened from path `" + imagePath + "`.", __LINE__, __FUNCTION__, __FILE__); } // Return result return imageAndPaths; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return {}; } } std::pair<double, std::vector<double>> calcReprojectionErrors(const std::vector<std::vector<cv::Point3f>>& objects3DVectors, const std::vector<std::vector<cv::Point2f>>& points2DVectors, const std::vector<cv::Mat>& rVecs, const std::vector<cv::Mat>& tVecs, const Intrinsics& intrinsics) { try { double reprojectionError; std::vector<double> perViewErrors(objects3DVectors.size()); std::vector<cv::Point2f> points2DVectors2; unsigned long long totalPoints = 0; double totalErr = 0; for (auto i = 0ull; i < objects3DVectors.size(); ++i ) { cv::projectPoints(cv::Mat(objects3DVectors.at(i)), rVecs.at(i), tVecs.at(i), intrinsics.cameraMatrix, intrinsics.distortionCoefficients, points2DVectors2); const auto err = cv::norm(cv::Mat(points2DVectors.at(i)), cv::Mat(points2DVectors2), CV_L2); const auto n = objects3DVectors.at(i).size(); perViewErrors.at(i) = {std::sqrt(err*err/n)}; totalErr += err*err; totalPoints += n; } reprojectionError = {std::sqrt(totalErr/totalPoints)}; return std::make_pair(reprojectionError, perViewErrors); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_pair(0., std::vector<double>{}); } } Intrinsics calcIntrinsicParameters(const cv::Size& imageSize, const std::vector<std::vector<cv::Point2f>>& points2DVectors, const std::vector<std::vector<cv::Point3f>>& objects3DVectors, const int calibrateCameraFlags) { try { log("\nCalibrating camera (intrinsics) with points from " + std::to_string(points2DVectors.size()) + " images...", Priority::High); //Find intrinsic and extrinsic camera parameters Intrinsics intrinsics; std::vector<cv::Mat> rVecs; std::vector<cv::Mat> tVecs; const auto rms = cv::calibrateCamera(objects3DVectors, points2DVectors, imageSize, intrinsics.cameraMatrix, intrinsics.distortionCoefficients, rVecs, tVecs, calibrateCameraFlags); // cv::checkRange checks that every array element is neither NaN nor infinite const auto calibrationIsCorrect = cv::checkRange(intrinsics.cameraMatrix) && cv::checkRange(intrinsics.distortionCoefficients); if (!calibrationIsCorrect) error("Unvalid cameraMatrix and/or distortionCoefficients.", __LINE__, __FUNCTION__, __FILE__); double totalAvgErr; std::vector<double> reprojectionErrors; std::tie(totalAvgErr, reprojectionErrors) = calcReprojectionErrors(objects3DVectors, points2DVectors, rVecs, tVecs, intrinsics); log("\nIntrinsics:", Priority::High); log("Re-projection error - cv::calibrateCamera vs. calcReprojectionErrors:\t" + std::to_string(rms) + " vs. " + std::to_string(totalAvgErr), Priority::High); log("Intrinsics_K:", Priority::High); log(intrinsics.cameraMatrix, Priority::High); log("Intrinsics_distCoeff:", Priority::High); log(intrinsics.distortionCoefficients, Priority::High); log(" ", Priority::High); return intrinsics; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return Intrinsics{}; } } double setAngleInRangeZeroTwoPi(const double angle) { try { // Return angle in range [0,2pi) return std::fmod(angle, 360); // floating-point remainder // double result{angle}; // Return angle in range [0,2pi) // const auto twoPi = 2 * PI; // while (result >= 2*PI) // result -= twoPi; // while (result < 0) // result += twoPi; // return result; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return 0; } } double setAngleInRangePlusMinusPi(const double angle) { try { auto result = setAngleInRangeZeroTwoPi(angle); // Return angle in range (-pi,pi] const auto twoPi = 2 * PI; if (result > PI) result -= twoPi; // // Return angle in range (-pi,pi] // const auto twoPi = 2 * PI; // while (result > PI) // result -= twoPi; // while (result <= -PI) // result += twoPi; return result; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return 0; } } #ifdef USE_EIGEN cv::Mat getRodriguesVector(const Eigen::Matrix3d& rotationMatrix) { try { // Rotation matrix as cv::Mat cv::Mat rotationMatrixCv; cv::eigen2cv(rotationMatrix, rotationMatrixCv); // Rotation as vector cv::Mat rotationVector; cv::Rodrigues(rotationMatrixCv, rotationVector); return rotationVector; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return cv::Mat(); } } std::pair<bool, double> estimateAverageAngle(const std::vector<double>& angles) { try { // Idea: // Average(-40, 40) = 0 // Average(-179, 179) = 180 (not 0!) // Average(90, 270) = 0 || 180??? We will assume outliers and return false // Security checks if (angles.empty()) error("Variables `angles` is empty.", __LINE__, __FUNCTION__, __FILE__); auto resultIsOK = true; double average = 0; // angles in range (-pi, pi] auto anglesNormalized = angles; for (auto& angle : anglesNormalized) angle = setAngleInRangePlusMinusPi(angle); // If the difference between them is > 180 degrees, then we turn them in the range [0, 360) (so // now the difference between them is < 180) and return the traditional average. Examples: // - If one in range [90, 180] and the other in range (-180, -90] // - If one is 179 degrees and the other one -179 degrees -> average should be 180 no 0! So: // [179 + (360-179)] / 2 = 180 // - Etc. // Math equivalent: // We want: ( maxAngle + (minAngle + 360) ) /2 // Equivalent to: ( maxAngle + minAngle + 360 ) /2 = (maxAngle + minAngle) / 2 + 180 // = (angleA + angleB) / 2 + 180, in radians: (angleA + angleB) / 2 + PI auto minElement = *std::min_element(anglesNormalized.begin(), anglesNormalized.end()); auto maxElement = *std::max_element(anglesNormalized.begin(), anglesNormalized.end()); if (maxElement - minElement >= PI) for (auto& angle : anglesNormalized) angle = setAngleInRangeZeroTwoPi(angle); // If after normalizing range between min and max is still >180 degrees --> there are outliers minElement = *std::min_element(anglesNormalized.begin(), anglesNormalized.end()); maxElement = *std::max_element(anglesNormalized.begin(), anglesNormalized.end()); if (maxElement - minElement >= PI) { resultIsOK = {false}; log("There are outliers in the angles.", Priority::High); } // If the difference between them is <= 180 degrees, then we just return the traditional average. // Examples: // - If both have the same signs, i.e. both in range [0, 180] or both in range (-180, 0) // - If one in range [0, 90] and the other in range [-90, 0] // - Etc. average = std::accumulate(anglesNormalized.begin(), anglesNormalized.end(), 0.) / (double)anglesNormalized.size(); average = setAngleInRangePlusMinusPi(average); return std::make_pair(resultIsOK, average); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_pair(false, 0.); } } Eigen::Matrix4d getMAverage(const std::vector<Eigen::Matrix4d>& MsToAverage, const Eigen::Matrix4d& noisyApproximatedM = Eigen::Matrix4d::Zero()) { try { auto MsToAverageRobust = MsToAverage; // Clean noisy outputs if (noisyApproximatedM.norm() > 0.1) { MsToAverageRobust.clear(); for (const auto& matrix : MsToAverage) { bool addElement = true; for (auto col = 0 ; col < 3 ; col++) { for (auto row = 0 ; row < 3 ; row++) { if (std::abs(matrix(col, row) - noisyApproximatedM(col, row)) > 0.25) { addElement = false; break; } } } if (addElement) MsToAverageRobust.push_back(matrix); } } // Projection matrix Eigen::Matrix4d averagedProjectionMatrix; averagedProjectionMatrix.setIdentity(); // Average translation for (const auto& matrix : MsToAverageRobust) averagedProjectionMatrix.block<3,1>(0,3) += matrix.block<3,1>(0,3); averagedProjectionMatrix.block<3,1>(0,3) /= (double)MsToAverageRobust.size(); // Average rotation std::array<std::vector<double>, 3> rotationVectors; for (const auto& matrix : MsToAverageRobust) { const auto rVec = getRodriguesVector(matrix.block<3,3>(0,0)); for (auto i = 0u ; i < rotationVectors.size() ; i++) rotationVectors.at(i).emplace_back(rVec.at<double>(i,0)); } cv::Mat rotationVector = cv::Mat::zeros(3, 1, CV_64F); for (auto i = 0u ; i < rotationVectors.size() ; i++) { const auto pairAverageAngle = estimateAverageAngle(rotationVectors.at(i)); if (!pairAverageAngle.first) log("Outlies in the result. Something went wrong when estimating the average of different" " projection matrices.", Priority::High); rotationVector.at<double>(i,0) = {pairAverageAngle.second}; } cv::Mat rotationMatrix; cv::Rodrigues(rotationVector, rotationMatrix); Eigen::Matrix3d rotEigen; cv::cv2eigen(rotationMatrix, rotEigen); averagedProjectionMatrix.block<3,3>(0,0) = rotEigen; // Result return averagedProjectionMatrix; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return Eigen::Matrix4d{}; } } Eigen::Matrix4d getMFromRt(const Eigen::Matrix3d& Rot, const Eigen::Vector3d& trans) { try { // projectionMatrix Eigen::Matrix4d projectionMatrix = Eigen::Matrix4d::Identity(); projectionMatrix.block<3,3>(0,0) = Rot; projectionMatrix.block<3,1>(0,3) = trans; return projectionMatrix; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return Eigen::Matrix4d{}; } } Eigen::Matrix4d getMFromRt(const cv::Mat& Rot, const cv::Mat& trans) { try { if (Rot.cols != 3 || Rot.rows != 3) error("Rotation matrix does not have 3 cols and/or 3 rows.", __LINE__, __FUNCTION__, __FILE__); if (trans.cols != 1 || trans.rows != 3) error("Translation vector does not have 1 col and/or 3 rows.", __LINE__, __FUNCTION__, __FILE__); Eigen::Matrix3d RotEigen; cv::cv2eigen(Rot, RotEigen); Eigen::Vector3d transEigen; cv::cv2eigen(trans, transEigen); // projectionMatrix return getMFromRt(RotEigen, transEigen); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return Eigen::Matrix4d{}; } } std::pair<cv::Mat, cv::Mat> solveCorrespondences2D3D(const cv::Mat& cameraMatrix, const cv::Mat& distortionCoefficients, const std::vector<cv::Point3f>& objects3DVector, const std::vector<cv::Point2f>& points2DVector) { try { // log("Solving 2D-3D correspondences (extrinsics)", Priority::High); cv::Mat rVec(3, 1, cv::DataType<double>::type); cv::Mat tVec(3, 1, cv::DataType<double>::type); // VERY IMPORTANT // So far, the only one that gives precise results is: cv::SOLVEPNP_DLS without RANSCAC // Non-RANSAC mode // It only can use 4 points // cv::solvePnP(fourObjects3DVector, fourPoints2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, cv::SOLVEPNP_P3P); // More robust against outliers // const auto found = cv::solvePnP(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, cv::SOLVEPNP_ITERATIVE); // Default cv::SOLVEPNP_ITERATIVE for OpenCV 3 const auto found = cv::solvePnP(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false); // More fragile against outliers // cv::solvePnP(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, cv::SOLVEPNP_EPNP); // More robust against outliers // cv::solvePnP(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, cv::SOLVEPNP_DLS); // More robust against outliers // cv::solvePnP(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, cv::SOLVEPNP_UPNP); // RANSAC mode // It gives really bad results // This one is the best, but it doest care about initial guesses // cv::solvePnPRansac(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, 1000, 8.0, 0.99, (int)objects3DVector.size() + 1, cv::noArray(), CV_EPNP); // This one is the best, but it doest care about initial guesses // cv::solvePnPRansac(objects3DVector, points2DVector, cameraMatrix, distortionCoefficients, rVec, tVec, false, 1000, 8.0, 0.99, cv::noArray(), cv::SOLVEPNP_ITERATIVE); if (!found) error("Correspondences could not be found.", __LINE__, __FUNCTION__, __FILE__); return std::make_pair(rVec, tVec); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_pair(cv::Mat(), cv::Mat()); } } std::tuple<cv::Mat, cv::Mat, std::vector<cv::Point2f>, std::vector<cv::Point3f>> calcExtrinsicParametersOpenCV(const cv::Mat& image, const cv::Mat& cameraMatrix, const cv::Mat& distortionCoefficients, const cv::Size& gridInnerCorners, const float gridSquareSizeMm) { try { // Finding accurate chessboard corner positions bool found{false}; std::vector<cv::Point2f> points2DVector; std::tie(found, points2DVector) = findAccurateGridCorners(image, gridInnerCorners); if (!found) return std::make_tuple(cv::Mat(), cv::Mat(), std::vector<cv::Point2f>(), std::vector<cv::Point3f>()); // Reordering points2DVector to have the first point at the top left position (top right in // case the chessboard is mirrored) reorderPoints(points2DVector, gridInnerCorners, Points2DOrigin::TopLeft); // Generate objects3DVector from gridSquareSizeMm const auto objects3DVector = getObjects3DVector(gridInnerCorners, gridSquareSizeMm); // Solving correspondences 2D-3D cv::Mat rVec; cv::Mat tVec; std::tie(rVec, tVec) = solveCorrespondences2D3D(cameraMatrix, distortionCoefficients, objects3DVector, points2DVector); return std::make_tuple(rVec, tVec, points2DVector, objects3DVector); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_tuple(cv::Mat(), cv::Mat(), std::vector<cv::Point2f>(), std::vector<cv::Point3f>()); } } std::tuple<bool, Extrinsics> calcExtrinsicParameters(const cv::Mat& image, const cv::Size& gridInnerCorners, const float gridSquareSizeMm, const cv::Mat& cameraMatrix, const cv::Mat& distortionCoefficients) { try { Extrinsics extrinsics; cv::Mat rVecOpenCV; cv::Mat RotOpenCV; cv::Mat tMmOpenCV; std::tie(rVecOpenCV, tMmOpenCV, extrinsics.points2DVector, extrinsics.objects3DVector) = calcExtrinsicParametersOpenCV( image, cameraMatrix, distortionCoefficients, gridInnerCorners, gridSquareSizeMm); if (rVecOpenCV.empty()) return std::make_tuple(false, Extrinsics{}); cv::Rodrigues(rVecOpenCV, RotOpenCV); cv::cv2eigen(RotOpenCV, extrinsics.Rotation); cv::cv2eigen(tMmOpenCV, extrinsics.translationMm); return std::make_tuple(true, extrinsics); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_tuple(false, Extrinsics{}); } } std::tuple<bool, Eigen::Matrix3d, Eigen::Vector3d, Eigen::Matrix3d, Eigen::Vector3d> getExtrinsicParameters(const std::vector<std::string>& cameraPaths, const cv::Size& gridInnerCorners, const float gridSquareSizeMm, const bool coutAndPlotGridCorners, const std::vector<cv::Mat>& intrinsics, const std::vector<cv::Mat>& distortions) { try { // Security checks if (intrinsics.size() != 2 || distortions.size() != 2 || cameraPaths.size() != 2) error("Found that (intrinsics.size() != 2 || distortions.size() != 2 || cameraPaths.size() != 2).", __LINE__, __FUNCTION__, __FILE__); std::vector<Extrinsics> extrinsicss(2); for (auto i = 0u ; i < cameraPaths.size() ; i++) { if (coutAndPlotGridCorners) log("getExtrinsicParameters(...), iteration with: " + cameraPaths[i], Priority::High); // Loading images const cv::Mat image = cv::imread(cameraPaths[i]); if (image.empty()) error("No image found in the path `" + cameraPaths[i] + "`.", __LINE__, __FUNCTION__, __FILE__); bool valid; std::tie(valid, extrinsicss[i]) = calcExtrinsicParameters( image, gridInnerCorners, gridSquareSizeMm, intrinsics.at(i), distortions.at(i)); if (!valid) return std::make_tuple(false, Eigen::Matrix3d{}, Eigen::Vector3d{}, Eigen::Matrix3d{}, Eigen::Vector3d{}); if (coutAndPlotGridCorners) { plotGridCorners(gridInnerCorners, extrinsicss[i].points2DVector, cameraPaths[i], image); } } return std::make_tuple( true, extrinsicss.at(0).Rotation, extrinsicss.at(0).translationMm, extrinsicss.at(1).Rotation, extrinsicss.at(1).translationMm ); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_tuple(false, Eigen::Matrix3d{}, Eigen::Vector3d{}, Eigen::Matrix3d{}, Eigen::Vector3d{}); } } Eigen::Matrix4d getMFrom2Ms(const Eigen::Matrix4d& MGridToCam0, const Eigen::Matrix4d& MGridToCam1) { try { // MCam1ToGrid // Non-efficient equivalent: // MCam1ToGrid = MGridToCam1.inverse() // Efficient version: // M * M.inverse() = I // [R t] [R -R't] = [I 0] // [0 1] [0 1 ] = [0 1] // Conclusion: // R_inv = R^-1 = R^T // t_inv = -R^T t Eigen::Matrix4d MCam1ToGrid = Eigen::Matrix4d::Identity(); MCam1ToGrid.block<3,3>(0,0) = MGridToCam1.block<3,3>(0,0).transpose(); MCam1ToGrid.block<3,1>(0,3) = - MCam1ToGrid.block<3,3>(0,0) * MGridToCam1.block<3,1>(0,3); // MCam1ToCam0 = MGridToCam0 * inv(MGridToCam1) // I.e., position of camera 1 w.r.t. camera 0 return Eigen::Matrix4d{MGridToCam0 * MCam1ToGrid}; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return Eigen::Matrix4d{}; } } Eigen::Matrix4d getMFromCam1ToCam0(const Eigen::Matrix3d& RGridToMainCam0, const Eigen::Vector3d& tGridToMainCam0, const Eigen::Matrix3d& RGridToMainCam1, const Eigen::Vector3d& tGridToMainCam1, const bool coutAndImshowVerbose) { const auto MGridToCam0 = getMFromRt(RGridToMainCam0, tGridToMainCam0); const auto MGridToCam1 = getMFromRt(RGridToMainCam1, tGridToMainCam1); // const auto MCam1ToCam0 = getMFrom2Ms(MGridToCam0, MGridToCam1); const auto MCam1ToCam0 = getMFrom2Ms(MGridToCam1, MGridToCam0); if (coutAndImshowVerbose) { const Eigen::Vector3d tCam1WrtCam0 = MCam1ToCam0.block<3,1>(0,3) / MCam1ToCam0(3,3); const Eigen::Matrix3d RCam1WrtCam0 = MCam1ToCam0.block<3,3>(0,0); log("M_gb:", Priority::High); log(MGridToCam1, Priority::High); log("M_gf:", Priority::High); log(MGridToCam0, Priority::High); log("M_bf:", Priority::High); log(MCam1ToCam0, Priority::High); log("########## Secondary camera position w.r.t. main camera ##########", Priority::High); log("tCam1WrtCam0:", Priority::High); log(tCam1WrtCam0, Priority::High); log("RCam1WrtCam0:", Priority::High); log(RCam1WrtCam0, Priority::High); log("MCam0WrtCam1:", Priority::High); log((- RCam1WrtCam0.transpose() * tCam1WrtCam0), Priority::High); } return MCam1ToCam0; } #endif const int SIFT_NAME = ('S' + ('I' << 8) + ('F' << 16) + ('T' << 24)); // const int MSER_NAME = ('M' + ('S' << 8) + ('E' << 16) + ('R' << 24)); // const int RECT_NAME = ('R' + ('E' << 8) + ('C' << 16) + ('T' << 24)); const int SIFT_VERSION_4 = ('V' + ('4' << 8) + ('.' << 16) + ('0' << 24)); const int SIFT_EOF = (0xff + ('E' << 8) + ('O' << 16) + ('F' << 24)); void writeVisualSFMSiftGPU(const std::string& fileName, const std::vector<cv::Point2f>& points2DVector) { const int siftName = SIFT_NAME; const int siftVersion = SIFT_VERSION_4; const int keyDimension = 5; const int descDimension = 128; const int siftEOF = SIFT_EOF; const int nSift = (int)points2DVector.size(); std::ofstream ofstreamSift; ofstreamSift.open(fileName, std::ios::binary); // Can write if (ofstreamSift.is_open()) { ofstreamSift.write(reinterpret_cast<const char*>(&siftName), sizeof(int)); ofstreamSift.write(reinterpret_cast<const char*>(&siftVersion), sizeof(int)); ofstreamSift.write(reinterpret_cast<const char*>(&nSift), sizeof(int)); ofstreamSift.write(reinterpret_cast<const char*>(&keyDimension), sizeof(int)); ofstreamSift.write(reinterpret_cast<const char*>(&descDimension), sizeof(int)); // for (int j = 0; j < nSift; ++j) for (auto i = 0u; i < points2DVector.size(); i++) { // const float x = KeyPts[4 * j]; // const float y = KeyPts[4 * j + 1]; const float x = points2DVector[i].x; const float y = points2DVector[i].y; const float dummy = 0.f; const float scale = 1.f; const float orientation = 0.f; ofstreamSift.write(reinterpret_cast<const char*>(&x), sizeof(float)); ofstreamSift.write(reinterpret_cast<const char*>(&y), sizeof(float)); ofstreamSift.write(reinterpret_cast<const char*>(&dummy), sizeof(float)); // ofstreamSift.write(reinterpret_cast<const char*>(&KeyPts[4 * j + 2]), sizeof(float)); // ofstreamSift.write(reinterpret_cast<const char*>(&KeyPts[4 * j + 3]), sizeof(float)); ofstreamSift.write(reinterpret_cast<const char*>(&scale), sizeof(float)); ofstreamSift.write(reinterpret_cast<const char*>(&orientation), sizeof(float)); } // // Extra argument: const unsigned char* const desc // for (int j = 0; j < nSift; ++j) // for (int i = 0; i < descDimension; i++) // ofstreamSift.write(reinterpret_cast<const char*>(&desc[j * descDimension + i]), // sizeof(unsigned char)); const unsigned char dummy = 0u; for (auto i = 0; i < nSift * descDimension; i++) ofstreamSift.write(reinterpret_cast<const char*>(&dummy), sizeof(unsigned char)); ofstreamSift.write(reinterpret_cast<const char*>(&siftEOF), sizeof(int)); ofstreamSift.close(); } // Couldn't write else log("Cannot write on " + fileName, Priority::High); } std::string getFileNameFromCameraIndex(const int cameraIndex) { try { // Security checks if (cameraIndex >= 100) error("Only implemented for up to 99 cameras.", __LINE__, __FUNCTION__, __FILE__); // Return result return (cameraIndex < 10 ? "00_0" : "00_") + std::to_string(cameraIndex); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return ""; } } void estimateAndSaveSiftFileSubThread(std::vector<cv::Point2f>* points2DExtrinsicPtr, std::vector<unsigned int>* matchIndexesCameraPtr, const int cameraIndex, const int numberCameras, const int numberCorners, const unsigned int numberViews, const bool saveImagesWithCorners, const std::string& imagesFolder, const cv::Size& gridInnerCornersCvSize, const cv::Size& imageSize, const std::vector<std::pair<cv::Mat, std::string>>& imageAndPaths) { try { // Security checks if (points2DExtrinsicPtr == nullptr || matchIndexesCameraPtr == nullptr) error("Make sure than points2DExtrinsicPtr != nullptr && matchIndexesCameraPtr != nullptr.", __LINE__, __FUNCTION__, __FILE__); std::vector<cv::Point2f>& points2DExtrinsic = *points2DExtrinsicPtr; std::vector<unsigned int>& matchIndexesCamera = *matchIndexesCameraPtr; std::vector<cv::Mat> imagesWithCorners; for (auto viewIndex = 0u ; viewIndex < numberViews ; viewIndex++) { // Get right image const auto& imageAndPath = imageAndPaths.at(viewIndex * numberCameras + cameraIndex); const auto& image = imageAndPath.first; if (viewIndex % std::max(1, int(numberViews/6)) == 0) log("Camera " + std::to_string(cameraIndex) + " - Image view " + std::to_string(viewIndex+1) + "/" + std::to_string(numberViews), Priority::High); // Security check if (imageSize.width != image.cols || imageSize.height != image.rows) error("Detected images with different sizes in `" + imagesFolder + "` All images" " must have the same resolution.", __LINE__, __FUNCTION__, __FILE__); // Find grid corners bool found; std::vector<cv::Point2f> points2DVector; std::tie(found, points2DVector) = findAccurateGridCorners(image, gridInnerCornersCvSize); // Reorder & save 2D pixels points if (found) { reorderPoints(points2DVector, gridInnerCornersCvSize, Points2DOrigin::TopLeft); for (auto i = 0 ; i < numberCorners ; i++) matchIndexesCamera.emplace_back(viewIndex * numberCorners + i); } else { points2DVector.clear(); points2DVector.resize(numberCorners, cv::Point2f{-1.f,-1.f}); log("Camera " + std::to_string(cameraIndex) + " - Image view " + std::to_string(viewIndex+1) + "/" + std::to_string(numberViews) + " - Chessboard not found.", Priority::High); } points2DExtrinsic.insert(points2DExtrinsic.end(), points2DVector.begin(), points2DVector.end()); // Show image (with chessboard corners if found) if (saveImagesWithCorners) { cv::Mat imageToPlot = image.clone(); if (found) drawGridCorners(imageToPlot, gridInnerCornersCvSize, points2DVector); imagesWithCorners.emplace_back(imageToPlot); } } // Save *.sift file for camera // const auto fileName = getFullFilePathNoExtension(imageAndPaths.at(cameraIndex).second) + ".sift"; const auto fileName = getFileParentFolderPath(imageAndPaths.at(cameraIndex).second) + getFileNameFromCameraIndex(cameraIndex) + ".sift"; writeVisualSFMSiftGPU(fileName, points2DExtrinsic); // Save images with corners if (saveImagesWithCorners) { const auto folderWhereSavingImages = imagesFolder + "images_with_corners/"; // Create directory in case it did not exist makeDirectory(folderWhereSavingImages); const auto pathWhereSavingImages = folderWhereSavingImages + std::to_string(cameraIndex) + "_"; // Save new images const std::string extension{".png"}; auto fileRemoved = true; for (auto i = 0u ; i < imagesWithCorners.size() || fileRemoved; i++) { const auto finalPath = pathWhereSavingImages + std::to_string(i+1) + extension; // remove leftovers/previous files // Note: If file is not deleted before cv::imwrite, Windows considers that the file // was "only" modified at that time, not created fileRemoved = {remove(finalPath.c_str()) == 0}; // save images on hhd in the desired place if (i < imagesWithCorners.size()) saveImage(imagesWithCorners.at(i), finalPath); } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } // Public functions void estimateAndSaveIntrinsics(const Point<int>& gridInnerCorners, const float gridSquareSizeMm, const int flags, const std::string& outputParameterFolder, const std::string& imagesFolder, const std::string& serialNumber, const bool saveImagesWithCorners) { try { // Point<int> --> cv::Size log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); const cv::Size gridInnerCornersCvSize{gridInnerCorners.x, gridInnerCorners.y}; // Read images in folder log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); std::vector<std::vector<cv::Point2f>> points2DVectors; const auto imageAndPaths = getImageAndPaths(imagesFolder); // Get 2D grid corners of each image log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); std::vector<cv::Mat> imagesWithCorners; const auto imageSize = imageAndPaths.at(0).first.size(); for (auto i = 0u ; i < imageAndPaths.size() ; i++) { log("\nImage " + std::to_string(i+1) + "/" + std::to_string(imageAndPaths.size()), Priority::High); const auto& image = imageAndPaths.at(i).first; // Security check if (imageSize.width != image.cols || imageSize.height != image.rows) error("Detected images with different sizes in `" + imagesFolder + "` All images" " must have the same resolution.", __LINE__, __FUNCTION__, __FILE__); // Find grid corners bool found; std::vector<cv::Point2f> points2DVector; std::tie(found, points2DVector) = findAccurateGridCorners(image, gridInnerCornersCvSize); // Reorder & save 2D pixels points if (found) { reorderPoints(points2DVector, gridInnerCornersCvSize, Points2DOrigin::TopLeft); points2DVectors.emplace_back(points2DVector); } else std::cerr << "Chessboard not found in this image." << std::endl; // Show image (with chessboard corners if found) if (saveImagesWithCorners) { cv::Mat imageToPlot = image.clone(); if (found) drawGridCorners(imageToPlot, gridInnerCornersCvSize, points2DVector); // cv::pyrDown(imageToPlot, imageToPlot); // cv::imshow("Image View", imageToPlot); // cv::waitKey(delayMilliseconds); imagesWithCorners.emplace_back(imageToPlot); } } // Run calibration log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // objects3DVector is the same one for each image const std::vector<std::vector<cv::Point3f>> objects3DVectors(points2DVectors.size(), getObjects3DVector(gridInnerCornersCvSize, gridSquareSizeMm)); const auto intrinsics = calcIntrinsicParameters(imageSize, points2DVectors, objects3DVectors, flags); // Save intrinsics/results log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); CameraParameterReader cameraParameterReader{serialNumber, intrinsics.cameraMatrix, intrinsics.distortionCoefficients}; cameraParameterReader.writeParameters(outputParameterFolder); // Save images with corners log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); if (saveImagesWithCorners) { const auto folderWhereSavingImages = imagesFolder + "images_with_corners/"; // Create directory in case it did not exist makeDirectory(folderWhereSavingImages); // Save new images const std::string extension{".png"}; auto fileRemoved = true; for (auto i = 0u ; i < imagesWithCorners.size() || fileRemoved; i++) { const auto finalPath = folderWhereSavingImages + std::to_string(i+1) + extension; // remove leftovers/previous files // Note: If file is not deleted before cv::imwrite, Windows considers that the file // was "only" modified at that time, not created fileRemoved = {remove(finalPath.c_str()) == 0}; // save images on hhd in the desired place if (i < imagesWithCorners.size()) saveImage(imagesWithCorners.at(i), finalPath); } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void estimateAndSaveExtrinsics(const std::string& intrinsicsFolder, const std::string& extrinsicsImagesFolder, const Point<int>& gridInnerCorners, const float gridSquareSizeMm, const int index0, const int index1, const bool imagesAreUndistorted, const bool combineCam0Extrinsics) { try { #ifdef USE_EIGEN // For debugging log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); const auto coutResults = false; // const auto coutResults = true; const bool coutAndImshowVerbose = false; // Point<int> --> cv::Size const cv::Size gridInnerCornersCvSize{gridInnerCorners.x, gridInnerCorners.y}; // Load intrinsic parameters log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); CameraParameterReader cameraParameterReader; cameraParameterReader.readParameters(intrinsicsFolder); const auto cameraSerialNumbers = cameraParameterReader.getCameraSerialNumbers(); const auto realCameraDistortions = cameraParameterReader.getCameraDistortions(); auto cameraIntrinsicsSubset = cameraParameterReader.getCameraIntrinsics(); auto cameraDistortionsSubset = (imagesAreUndistorted ? std::vector<cv::Mat>{realCameraDistortions.size()} : realCameraDistortions); // Only use the 2 desired ones log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); cameraIntrinsicsSubset = {cameraIntrinsicsSubset.at(index0), cameraIntrinsicsSubset.at(index1)}; cameraDistortionsSubset = {cameraDistortionsSubset.at(index0), cameraDistortionsSubset.at(index1)}; // Base extrinsics log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); cv::Mat extrinsicsCam0 = cv::Mat::eye(4, 4, realCameraDistortions.at(0).type()); bool cam0IsOrigin = true; if (combineCam0Extrinsics) { cameraParameterReader.getCameraExtrinsics().at(index0).copyTo(extrinsicsCam0(cv::Rect{0,0,4,3})); cam0IsOrigin = cv::norm(extrinsicsCam0 - cv::Mat::eye(4, 4, extrinsicsCam0.type())) < 1e-9; } // Number cameras and image paths log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); const auto numberCameras = cameraParameterReader.getNumberCameras(); log("\nDetected " + std::to_string(numberCameras) + " cameras from your XML files on:\n" + intrinsicsFolder + "\nRemove wrong/extra XML files if this number of cameras does not" + " correspond with the number of cameras recorded in:\n" + extrinsicsImagesFolder + "\n", Priority::High); const auto imagePaths = getImagePaths(extrinsicsImagesFolder); // Security check if (imagePaths.size() % numberCameras != 0) error("You indicated that there are " + std::to_string(numberCameras) + " cameras. However, we found a total of " + std::to_string(imagePaths.size()) + " images, which should be possible to divide into the number of cameras with no" " remainder.", __LINE__, __FUNCTION__, __FILE__); // Estimate extrinsic parameters per image log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); log("Calibrating camera " + cameraSerialNumbers.at(index1) + " with respect to camera " + cameraSerialNumbers.at(index0) + "...", Priority::High); const auto numberViews = imagePaths.size() / numberCameras; auto counterValidImages = 0u; std::vector<Eigen::Matrix4d> MCam1ToCam0s; for (auto i = 0u ; i < imagePaths.size() ; i+=numberCameras) { log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); const auto pathCam0 = imagePaths[i+index0]; const auto pathCam1 = imagePaths[i+index1]; if (coutResults || i/numberCameras % int(numberViews/10) == 0) log("It " + std::to_string(i/numberCameras+1) + "/" + std::to_string(numberViews) + ": " + getFileNameAndExtension(pathCam0) + " & " + getFileNameAndExtension(pathCam1) + "...", Priority::High); // Extrinsic parameters extractor Eigen::Matrix3d RGridToMainCam0; Eigen::Matrix3d RGridToMainCam1; Eigen::Vector3d tGridToMainCam0; Eigen::Vector3d tGridToMainCam1; bool valid = true; std::tie(valid, RGridToMainCam0, tGridToMainCam0, RGridToMainCam1, tGridToMainCam1) = getExtrinsicParameters({pathCam0, pathCam1}, gridInnerCornersCvSize, gridSquareSizeMm, false, // coutAndImshowVerbose, // It'd display all images with grid cameraIntrinsicsSubset, cameraDistortionsSubset); if (valid) { counterValidImages++; if (coutAndImshowVerbose) { log("########## Extrinsic parameters extractor ##########", Priority::High); log("R_gf", Priority::High); log(RGridToMainCam0, Priority::High); log("t_gf", Priority::High); log(tGridToMainCam0, Priority::High); log("R_gb", Priority::High); log(RGridToMainCam1, Priority::High); log("t_gb", Priority::High); log(tGridToMainCam1, Priority::High); log("\n", Priority::High); } // MCam1ToCam0 - Projection matrix estimator if (coutAndImshowVerbose) log("########## Projection Matrix from secondary camera to main camera ##########", Priority::High); MCam1ToCam0s.emplace_back(getMFromCam1ToCam0(RGridToMainCam0, tGridToMainCam0, RGridToMainCam1, tGridToMainCam1, coutAndImshowVerbose)); if (coutResults) { if (coutAndImshowVerbose) log("M_bg:", Priority::High); log(MCam1ToCam0s.back(), Priority::High); log(" ", Priority::High); } } else { if (coutResults) log("Invalid frame (chessboard not found).", Priority::High); } } log("Finished processing images.", Priority::High); // Pseudo RANSAC calibration log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); const auto MCam1ToCam0Noisy = getMAverage(MCam1ToCam0s); log("Estimated initial (noisy?) projection matrix.", Priority::High); auto MCam1ToCam0 = getMAverage(MCam1ToCam0s, MCam1ToCam0Noisy); while ((MCam1ToCam0 - getMAverage(MCam1ToCam0s, MCam1ToCam0)).norm() > 1e-3) { if (coutResults) log("Repeated robustness method...", Priority::High); MCam1ToCam0 = getMAverage(MCam1ToCam0s, MCam1ToCam0); } log("Estimated robust projection matrix.", Priority::High); log("norm(M_robust-M_noisy): " + std::to_string((MCam1ToCam0Noisy - MCam1ToCam0).norm()), Priority::High); // Show errors log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); if (coutAndImshowVerbose) { log("\n-----------------------------------------------------------------------------------" "-------------------\nErrors:", Priority::High); // Errors log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); for (auto i = 0u ; i < MCam1ToCam0s.size() ; i++) { log("tCam1WrtCam0:", Priority::High); log(MCam1ToCam0s.at(i).block<3,1>(0,3).transpose(), Priority::High); } log(" ", Priority::High); log("tCam1WrtCam0:", Priority::High); log(MCam1ToCam0.block<3,1>(0,3).transpose(), Priority::High); log(" ", Priority::High); // Rotation matrix in degrees Rodrigues(InputArray src, OutputArray dst log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); const auto rad2deg = 180 / PI; for (auto i = 0u ; i < MCam1ToCam0s.size() ; i++) { Eigen::Matrix3d R_secondaryToMain = MCam1ToCam0s.at(i).block<3,3>(0,0); log("rodrigues:", Priority::High); log((getRodriguesVector(R_secondaryToMain).t() * rad2deg), Priority::High); } Eigen::Matrix3d R_secondaryToMain = MCam1ToCam0.block<3,3>(0,0); log("rodrigues:", Priority::High); log((getRodriguesVector(R_secondaryToMain).t() * rad2deg), Priority::High); } // Show final result log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); if (coutResults) { log("\n\n\n---------------------------------------------------------------------------" "---------------------------", Priority::High); log(std::to_string(counterValidImages) + " valid images.", Priority::High); log("Initial (noisy?) projection matrix:", Priority::High); log(MCam1ToCam0Noisy, Priority::High); log("\nFinal projection matrix (mm):", Priority::High); log(MCam1ToCam0, Priority::High); log(" ", Priority::High); } // mm --> m log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); MCam1ToCam0.block<3,1>(0,3) *= 1e-3; // Eigen --> cv::Mat log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); cv::Mat cvMatExtrinsics; Eigen::MatrixXd eigenExtrinsics = MCam1ToCam0.block<3,4>(0,0); cv::eigen2cv(eigenExtrinsics, cvMatExtrinsics); // pos_target_origen = pos_target_cam1 * pos_cam1_origin // Example: pos_31 = pos_32 * pos_21 if (!cam0IsOrigin) cvMatExtrinsics *= extrinsicsCam0; // Final projection matrix log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); log("\nFinal projection matrix w.r.t. global origin (m):", Priority::High); log(cvMatExtrinsics, Priority::High); log(" ", Priority::High); // Save result log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); CameraParameterReader camera2ParameterReader{ cameraSerialNumbers.at(index1), cameraIntrinsicsSubset.at(1), realCameraDistortions.at(index1), cvMatExtrinsics}; camera2ParameterReader.writeParameters(intrinsicsFolder); // Let the rendered image to be displayed log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); if (coutAndImshowVerbose) cv::waitKey(0); #else UNUSED(intrinsicsFolder); UNUSED(extrinsicsImagesFolder); UNUSED(gridInnerCorners); UNUSED(gridSquareSizeMm); UNUSED(index0); UNUSED(index1); UNUSED(imagesAreUndistorted); UNUSED(combineCam0Extrinsics); error("CMake flag `USE_EIGEN` required when compiling OpenPose`.", __LINE__, __FUNCTION__, __FILE__); #endif } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void estimateAndSaveSiftFile(const Point<int>& gridInnerCorners, const std::string& imagesFolder, const int numberCameras, const bool saveImagesWithCorners) { try { log("Loading images...", Priority::High); const auto imageAndPaths = getImageAndPaths(imagesFolder); log("Images loaded.", Priority::High); // Point<int> --> cv::Size const cv::Size gridInnerCornersCvSize{gridInnerCorners.x, gridInnerCorners.y}; // Read images in folder const auto numberCorners = gridInnerCorners.area(); std::vector<std::vector<cv::Point2f>> points2DVectorsExtrinsic(numberCameras); // camera - keypoints std::vector<std::vector<unsigned int>> matchIndexes(numberCameras); // camera - indixes found if (imageAndPaths.empty()) error("imageAndPaths.empty()!.", __LINE__, __FUNCTION__, __FILE__); // Get 2D grid corners of each image std::vector<cv::Mat> imagesWithCorners; const auto imageSize = imageAndPaths.at(0).first.size(); const auto numberViews = imageAndPaths.size() / numberCameras; log("Processing cameras...", Priority::High); std::vector<std::thread> threads; for (auto cameraIndex = 0 ; cameraIndex < numberCameras ; cameraIndex++) { auto* points2DExtrinsic = &points2DVectorsExtrinsic[cameraIndex]; auto* matchIndexesCamera = &matchIndexes[cameraIndex]; // Threaded version threads.emplace_back(estimateAndSaveSiftFileSubThread, points2DExtrinsic, matchIndexesCamera, cameraIndex, numberCameras, numberCorners, numberViews, saveImagesWithCorners, imagesFolder, gridInnerCornersCvSize, imageSize, imageAndPaths); // // Non-threaded version // estimateAndSaveSiftFileSubThread(points2DExtrinsic, matchIndexesCamera, cameraIndex, numberCameras, // numberCorners, numberViews, saveImagesWithCorners, imagesFolder, // gridInnerCornersCvSize, imageSize, imageAndPaths); } // Threaded version for (auto& thread : threads) if (thread.joinable()) thread.join(); // Matching file std::ofstream ofstreamMatches{getFileParentFolderPath(imageAndPaths.at(0).second) + "FeatureMatches.txt"}; for (auto cameraIndex = 0 ; cameraIndex < numberCameras ; cameraIndex++) { for (auto cameraIndex2 = cameraIndex+1 ; cameraIndex2 < numberCameras ; cameraIndex2++) { std::vector<unsigned int> matchIndexesIntersection; std::set_intersection(matchIndexes[cameraIndex].begin(), matchIndexes[cameraIndex].end(), matchIndexes[cameraIndex2].begin(), matchIndexes[cameraIndex2].end(), std::back_inserter(matchIndexesIntersection)); ofstreamMatches << getFileNameFromCameraIndex(cameraIndex) << ".jpg" << " " << getFileNameFromCameraIndex(cameraIndex2) << ".jpg" // ofstreamMatches << getFileNameAndExtension(imageAndPaths.at(cameraIndex).second) // << " " << getFileNameAndExtension(imageAndPaths.at(cameraIndex2).second) << " " << matchIndexesIntersection.size() << "\n"; for (auto reps = 0 ; reps < 2 ; reps++) { for (auto i = 0u ; i < matchIndexesIntersection.size() ; i++) ofstreamMatches << matchIndexesIntersection[i] << " "; ofstreamMatches << "\n"; } ofstreamMatches << "\n"; } } ofstreamMatches.close(); // Security check log("Number points fully obtained: " + std::to_string(points2DVectorsExtrinsic[0].size()), Priority::High); log("Number views fully obtained: " + std::to_string(points2DVectorsExtrinsic[0].size() / numberCorners), Priority::High); for (auto i = 1 ; i < numberCameras ; i++) if (points2DVectorsExtrinsic[i].size() != points2DVectorsExtrinsic[0].size()) error("Something went wrong. Notify us.", __LINE__, __FUNCTION__, __FILE__); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } } <|start_filename|>include/openpose/thread/headers.hpp<|end_filename|> #ifndef OPENPOSE_THREAD_HEADERS_HPP #define OPENPOSE_THREAD_HEADERS_HPP // thread module #include <openpose/thread/enumClasses.hpp> #include <openpose/thread/priorityQueue.hpp> #include <openpose/thread/queue.hpp> #include <openpose/thread/queueBase.hpp> #include <openpose/thread/subThread.hpp> #include <openpose/thread/subThreadNoQueue.hpp> #include <openpose/thread/subThreadQueueIn.hpp> #include <openpose/thread/subThreadQueueInOut.hpp> #include <openpose/thread/subThreadQueueOut.hpp> #include <openpose/thread/thread.hpp> #include <openpose/thread/threadManager.hpp> #include <openpose/thread/worker.hpp> #include <openpose/thread/workerProducer.hpp> #include <openpose/thread/workerConsumer.hpp> #include <openpose/thread/wIdGenerator.hpp> #include <openpose/thread/wQueueAssembler.hpp> #include <openpose/thread/wQueueOrderer.hpp> #endif // OPENPOSE_THREAD_HEADERS_HPP <|start_filename|>include/openpose/pose/poseExtractor.hpp<|end_filename|> #ifndef OPENPOSE_POSE_POSE_EXTRACTOR_HPP #define OPENPOSE_POSE_POSE_EXTRACTOR_HPP #include <openpose/core/common.hpp> #include <openpose/core/enumClasses.hpp> #include <openpose/core/keepTopNPeople.hpp> #include <openpose/pose/poseParameters.hpp> #include <openpose/pose/poseExtractorNet.hpp> #include <openpose/tracking/personIdExtractor.hpp> #include <openpose/tracking/personTracker.hpp> namespace op { class OP_API PoseExtractor { public: PoseExtractor(const std::shared_ptr<PoseExtractorNet>& poseExtractorNet, const std::shared_ptr<KeepTopNPeople>& keepTopNPeople = nullptr, const std::shared_ptr<PersonIdExtractor>& personIdExtractor = nullptr, const std::shared_ptr<std::vector<std::shared_ptr<PersonTracker>>>& personTracker = {}, const int numberPeopleMax = -1, const int tracking = -1); virtual ~PoseExtractor(); void initializationOnThread(); void forwardPass(const std::vector<Array<float>>& inputNetData, const Point<int>& inputDataSize, const std::vector<double>& scaleRatios, const long long frameId = -1ll); // PoseExtractorNet functions Array<float> getHeatMapsCopy() const; std::vector<std::vector<std::array<float, 3>>> getCandidatesCopy() const; Array<float> getPoseKeypoints() const; Array<float> getPoseScores() const; float getScaleNetToOutput() const; // KeepTopNPeople functions void keepTopPeople(Array<float>& poseKeypoints, const Array<float>& poseScores) const; // PersonIdExtractor functions // Not thread-safe Array<long long> extractIds(const Array<float>& poseKeypoints, const cv::Mat& cvMatInput, const unsigned long long imageIndex = 0ull); // Same than extractIds but thread-safe Array<long long> extractIdsLockThread(const Array<float>& poseKeypoints, const cv::Mat& cvMatInput, const unsigned long long imageIndex, const long long frameId); // PersonTracker functions void track(Array<float>& poseKeypoints, Array<long long>& poseIds, const cv::Mat& cvMatInput, const unsigned long long imageViewIndex = 0ull); void trackLockThread(Array<float>& poseKeypoints, Array<long long>& poseIds, const cv::Mat& cvMatInput, const unsigned long long imageViewIndex, const long long frameId); private: const int mNumberPeopleMax; const int mTracking; const std::shared_ptr<PoseExtractorNet> spPoseExtractorNet; const std::shared_ptr<KeepTopNPeople> spKeepTopNPeople; const std::shared_ptr<PersonIdExtractor> spPersonIdExtractor; const std::shared_ptr<std::vector<std::shared_ptr<PersonTracker>>> spPersonTrackers; DELETE_COPY(PoseExtractor); }; } #endif // OPENPOSE_POSE_POSE_EXTRACTOR_HPP <|start_filename|>include/openpose/wrapper/wrapperStructExtra.hpp<|end_filename|> #ifndef OPENPOSE_WRAPPER_WRAPPER_STRUCT_EXTRA_HPP #define OPENPOSE_WRAPPER_WRAPPER_STRUCT_EXTRA_HPP #include <openpose/core/common.hpp> namespace op { /** * WrapperStructExtra: Pose estimation and rendering configuration struct. * WrapperStructExtra allows the user to set up the pose estimation and rendering parameters that will be used for * the OpenPose Wrapper class. */ struct OP_API WrapperStructExtra { /** * Whether to run the 3-D reconstruction demo, i.e., * 1) Reading from a stereo camera system. * 2) Performing 3-D reconstruction from the multiple views. * 3) Displaying 3-D reconstruction results. */ bool reconstruct3d; /** * Minimum number of views required to reconstruct each keypoint. * By default (-1), it will require all the cameras to see the keypoint in order to reconstruct it. */ int minViews3d; /** * Whether to return a person ID for each body skeleton, providing temporal consistency. */ bool identification; /** * Whether to enable people tracking across frames. The value indicates the number of frames where tracking * is run between each OpenPose keypoint detection. Select -1 (default) to disable it or 0 to run * simultaneously OpenPose keypoint detector and tracking for potentially higher accurary than only OpenPose. */ int tracking; /** * Whether to enable inverse kinematics (IK) from 3-D keypoints to obtain 3-D joint angles. By default * (0 threads), it is disabled. Increasing the number of threads will increase the speed but also the * global system latency. */ int ikThreads; /** * Constructor of the struct. * It has the recommended and default values we recommend for each element of the struct. * Since all the elements of the struct are public, they can also be manually filled. */ WrapperStructExtra(const bool reconstruct3d = false, const int minViews3d = -1, const bool identification = false, const int tracking = -1, const int ikThreads = 0); }; } #endif // OPENPOSE_WRAPPER_WRAPPER_STRUCT_EXTRA_HPP <|start_filename|>include/openpose/filestream/udpSender.hpp<|end_filename|> #ifndef OPENPOSE_FILESTREAM_UDP_SENDER_HPP #define OPENPOSE_FILESTREAM_UDP_SENDER_HPP #include <openpose/core/common.hpp> namespace op { class OP_API UdpSender { public: UdpSender(const std::string& udpHost, const std::string& udpPort); void sendJointAngles(const double* const adamPosePtr, const int adamPoseRows, const double* const adamTranslationPtr, const double* const adamFaceCoeffsExpPtr, const int faceCoeffRows); private: // PIMPL idiom // http://www.cppsamples.com/common-tasks/pimpl.html struct ImplUdpSender; std::shared_ptr<ImplUdpSender> spImpl; // PIMP requires DELETE_COPY & destructor, or extra code // http://oliora.github.io/2015/12/29/pimpl-and-rule-of-zero.html DELETE_COPY(UdpSender); }; } #endif // OPENPOSE_FILESTREAM_UDP_SENDER_HPP <|start_filename|>include/openpose/calibration/cameraParameterEstimation.hpp<|end_filename|> #ifndef OPENPOSE_CALIBRATION_CAMERA_PARAMETER_ESTIMATION_HPP #define OPENPOSE_CALIBRATION_CAMERA_PARAMETER_ESTIMATION_HPP #include <openpose/core/common.hpp> namespace op { /** * This function estimate and saves the intrinsic parameters (K and distortion coefficients). * @param gridInnerCorners The Point<int> of the board, i.e., the number of squares by width and height * @param gridSquareSizeMm Floating number with the size of a square in your defined unit (point, millimeter,etc). * @param flags Integer with the OpenCV flags for calibration (e.g., CALIB_RATIONAL_MODEL, * CALIB_THIN_PRISM_MODEL, or CALIB_TILTED_MODEL) * @param outputFilePath String with the name of the file where to write */ OP_API void estimateAndSaveIntrinsics(const Point<int>& gridInnerCorners, const float gridSquareSizeMm, const int flags, const std::string& outputParameterFolder, const std::string& imagesFolder, const std::string& serialNumber, const bool saveImagesWithCorners = false); OP_API void estimateAndSaveExtrinsics(const std::string& intrinsicsFolder, const std::string& extrinsicsImagesFolder, const Point<int>& gridInnerCorners, const float gridSquareSizeMm, const int index0, const int index1, const bool imagesAreUndistorted, const bool combineCam0Extrinsics); OP_API void estimateAndSaveSiftFile(const Point<int>& gridInnerCorners, const std::string& imagesFolder, const int numberCameras, const bool saveImagesWithCorners = false); } #endif // OPENPOSE_CALIBRATION_CAMERA_PARAMETER_ESTIMATION_HPP
purushothamgowthu/openpose
<|start_filename|>lib/sessions/corestore.js<|end_filename|> const { intoPeer } = require('../common') module.exports = class CorestoreSession { constructor (client, sessionState, corestore) { this._client = client this._corestore = corestore this._sessionState = sessionState const feedListener = (feed) => { this._client.corestore.onFeedNoReply({ key: feed.key }) } this._corestore.on('feed', feedListener) this._sessionState.addResource('@hypercore/feed', null, () => { this._corestore.removeListener('feed', feedListener) }) } // RPC Methods async open ({ id, key, name, weak }) { if (this._sessionState.hasCore(id)) throw new Error('Session already in use.') const core = this._corestore.get({ key, name: name }) this._sessionState.addCore(id, core, weak) // TODO: Delete session if ready fails. await new Promise((resolve, reject) => { core.ready(err => { if (err) return reject(err) return resolve() }) }) const appendListener = () => { this._client.hypercore.onAppendNoReply({ id, length: core.length, byteLength: core.byteLength }) } core.on('append', appendListener) this._sessionState.addResource('@hypercore/append-' + id, null, () => { core.removeListener('append', appendListener) }) const peerOpenListener = (peer) => { this._client.hypercore.onPeerOpenNoReply({ id, peer: intoPeer(peer) }) } core.on('peer-open', peerOpenListener) this._sessionState.addResource('@hypercore/peer-open-' + id, null, () => { core.removeListener('peer-open', peerOpenListener) }) const peerRemoveListener = (peer) => { if (!peer.remoteOpened) return this._client.hypercore.onPeerRemoveNoReply({ id, peer: intoPeer(peer) }) } core.on('peer-remove', peerRemoveListener) this._sessionState.addResource('@hypercore/peer-remove-' + id, null, () => { core.removeListener('peer-remove', peerRemoveListener) }) if (weak) { const closeListener = () => { this._client.hypercore.onCloseNoReply({ id }) } core.on('close', closeListener) this._sessionState.addResource('@hypercore/close-' + id, null, () => { core.removeListener('close', closeListener) }) } const peers = core.peers.filter(p => p.remoteOpened).map(intoPeer) return { key: core.key, discoveryKey: core.discoveryKey, length: core.length, byteLength: core.byteLength, writable: core.writable, peers } } }
tomasol/hyperspace
<|start_filename|>Sample.Model/Models/LowWorkloadObject.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.Model.Models { public interface ILowWorkloadObject : ISomeWorkloadObject { } internal class LowWorkloadObject : SomeWorkloadObject, ILowWorkloadObject { public LowWorkloadObject(int number) : base(number) { } } } <|start_filename|>Sample.ViewModel/Adapters/AllNumbersCollectionAdapter.cs<|end_filename|> using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters { internal interface IAllNumbersCollectionAdapter : IBackendAccessAdapter<int> { } internal class AllNumbersCollectionAdapter : IAllNumbersCollectionAdapter { private readonly IAllNumbersFakeBackendAccess _allNumbersFakeBackendAccess; public AllNumbersCollectionAdapter(IAllNumbersFakeBackendAccess allNumbersFakeBackendAccess) { _allNumbersFakeBackendAccess = allNumbersFakeBackendAccess; } public string Name => _allNumbersFakeBackendAccess.Name; public IBackendAccess<int> BackendAccess => _allNumbersFakeBackendAccess; public BackendAccessKind BackendAccessKind => BackendAccessKind.AllNumbers; } } <|start_filename|>BFF.DataVirtualizingCollection/DataVirtualizingCollection/DataVirtualizingCollectionBase.cs<|end_filename|> using System; using System.Reactive.Concurrency; using System.Reactive.Linq; using MrMeeseeks.Reactive.Extensions; namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection { internal abstract class DataVirtualizingCollectionBase<T> : VirtualizationBase<T>, IDataVirtualizingCollection<T> { private int _selectedIndex; protected DataVirtualizingCollectionBase( IObservable<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> observePageFetches, IDisposable disposeOnDisposal, IScheduler notificationScheduler) { disposeOnDisposal.CompositeDisposalWith(CompositeDisposable); observePageFetches .ObserveOn(notificationScheduler) .Subscribe(t => { var (offset, pageSize, previousPage, page) = t; for (var i = 0; i < pageSize; i++) { OnCollectionChangedReplace(page[i], previousPage[i], i + offset); } OnIndexerChanged(); }) .CompositeDisposalWith(CompositeDisposable); } protected override T IndexerInnerGet(int index) => index >= Count || index < 0 ? throw new IndexOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection.") : GetItemInner(index); protected abstract T GetItemInner(int index); private int _preResetSelectedIndex = -1; protected override void OnCollectionChangedReset() { _preResetSelectedIndex = _selectedIndex; SelectedIndex = -1; // deselection in order to workaround issue of Selectors base.OnCollectionChangedReset(); SelectedIndex = _preResetSelectedIndex; } protected override T GetItemForEnumerator(int i) => GetItemInner(i); public override int SelectedIndex { get => _selectedIndex; set { if (_selectedIndex == value) return; _selectedIndex = value; OnPropertyChanged(); } } } } <|start_filename|>BFF.DataVirtualizingCollection/DataVirtualizingCollection/AsyncDataVirtualizingCollection.cs<|end_filename|> using System; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using MrMeeseeks.Reactive.Extensions; namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection { internal sealed class AsyncDataVirtualizingCollection<T> : DataVirtualizingCollectionBase<T> { private readonly Func<CancellationToken, Task<int>> _countFetcher; private readonly IScheduler _notificationScheduler; private readonly IScheduler _countBackgroundScheduler; private readonly IPageStorage<T> _pageStorage; private readonly Subject<CancellationToken> _resetSubject = new (); private readonly SerialDisposable _pendingCountRequestCancellation = new (); private int _count; internal AsyncDataVirtualizingCollection( Func<int, IPageStorage<T>> pageStoreFactory, Func<CancellationToken, Task<int>> countFetcher, IObservable<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> observePageFetches, IDisposable disposeOnDisposal, IScheduler notificationScheduler, IScheduler countBackgroundScheduler) : base(observePageFetches, disposeOnDisposal, notificationScheduler) { _countFetcher = countFetcher; _notificationScheduler = notificationScheduler; _countBackgroundScheduler = countBackgroundScheduler; _count = 0; _resetSubject.CompositeDisposalWith(CompositeDisposable); _pageStorage = pageStoreFactory(0); InitializationCompleted = _resetSubject.FirstAsync().ToTask(); _resetSubject .SelectMany(async ct => { await ResetInner(ct).ConfigureAwait(false); return Unit.Default; }) .Subscribe(_ => {}) .CompositeDisposalWith(CompositeDisposable); Reset(); } public override int Count => _count; protected override T GetItemInner(int index) => _pageStorage[index]; private async Task ResetInner(CancellationToken ct) { try { await Observable.FromAsync(_countFetcher, _countBackgroundScheduler) .SelectMany(async count => { _count = count; await _pageStorage.Reset(_count).ConfigureAwait(false); return Unit.Default; }) .ObserveOn(_notificationScheduler) .Do(_ => { OnPropertyChanged(nameof(Count)); OnCollectionChangedReset(); OnIndexerChanged(); }) .ToTask(ct) .ConfigureAwait(false); } catch (OperationCanceledException) { // ignore cancellation from now on } } public override void Reset() { var cancellationDisposable = new CancellationDisposable(); _pendingCountRequestCancellation.Disposable = cancellationDisposable; _resetSubject.OnNext(cancellationDisposable.Token); } public override Task InitializationCompleted { get; } public override async ValueTask DisposeAsync() { _pendingCountRequestCancellation.Dispose(); await base.DisposeAsync().ConfigureAwait(false); await _pageStorage.DisposeAsync().ConfigureAwait(false); } } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/IAsyncPageFetchScheduler.cs<|end_filename|> using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.PageStorage { internal interface IAsyncPageFetchScheduler { Task Schedule(); } } <|start_filename|>Sample.ViewModel/Adapters/ProfileCollectionAdapter.cs<|end_filename|> using System.Linq; using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; using BFF.DataVirtualizingCollection.Sample.Model.Models; using BFF.DataVirtualizingCollection.Sample.ViewModel.Utility; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters { internal interface IProfileCollectionAdapter : IBackendAccessAdapter<IProfileViewModel> { } internal class ProfileCollectionAdapter : IProfileCollectionAdapter { private readonly IProfilesFakeBackendAccess _profilesFakeBackendAccess; public ProfileCollectionAdapter(IProfilesFakeBackendAccess profilesFakeBackendAccess) { _profilesFakeBackendAccess = profilesFakeBackendAccess; BackendAccess = TransformingBackendAccess<IProfile, IProfileViewModel>.CreateTransformingBackendAccess( _profilesFakeBackendAccess, TransformPage, TransformPlaceholder); } public string Name => _profilesFakeBackendAccess.Name; public IBackendAccess<IProfileViewModel> BackendAccess { get; } public BackendAccessKind BackendAccessKind => BackendAccessKind.Profiles; private IProfileViewModel[] TransformPage(IProfile[] page) { return page.Select(p => ProfileViewModelStatic.ProfileToViewModel[p]).ToArray(); } private IProfileViewModel TransformPlaceholder(IProfile item) { return ProfileViewModelStatic.ProfileToViewModel[item]; } } } <|start_filename|>BFF.DataVirtualizingCollection/DataVirtualizingCollection/IDataVirtualizingCollection.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection { // ReSharper disable once PossibleInterfaceMemberAmbiguity // Ambiguous Members should be implemented explicitly /// <summary> /// Marks a nongeneric data virtualizing collection. /// The data virtualizing collection represents the whole backend as a list. However, the items are not loaded all at once but page by page on demand. /// </summary> public interface IDataVirtualizingCollection : IVirtualizationBase { } // ReSharper disable once PossibleInterfaceMemberAmbiguity // Ambiguous Members should be implemented explicitly /// <summary> /// Marks a generic data virtualizing collection. /// The data virtualizing collection represents the whole backend as a list. However, the items are not loaded all at once but page by page on demand. /// </summary> /// <typeparam name="T">Item type.</typeparam> public interface IDataVirtualizingCollection<T> : IVirtualizationBase<T>, IDataVirtualizingCollection { } } <|start_filename|>Tests.Unit/DataVirtualizingCollection/AsyncDataVirtualizingCollectionTests.cs<|end_filename|> using System; using System.Reactive.Concurrency; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.DataVirtualizingCollection; using BFF.DataVirtualizingCollection.PageStorage; using NSubstitute; using Xunit; namespace BFF.DataVirtualizingCollection.Test.DataVirtualizingCollection { public class AsyncDataVirtualizingCollectionTests { [Fact] public async Task Reset_BeforeInitialCountFetchCompleted_CountFetchIsCanceled() { // Arrange var wasCanceled = false; var sut = new AsyncDataVirtualizingCollection<int>( _ => Substitute.For<IPageStorage<int>>(), async ct => { try { await Task.Delay(10, ct).ConfigureAwait(false); } catch (OperationCanceledException) { wasCanceled = true; } return 10; }, Substitute.For<IObservable<(int Offset, int PageSize, int[] PreviousPage, int[] Page)>>(), Substitute.For<IDisposable>(), new EventLoopScheduler(), TaskPoolScheduler.Default); // Act sut.Reset(); await Task.Delay(50).ConfigureAwait(false); // Assert Assert.True(wasCanceled); } } } <|start_filename|>Tests.Integration/DataVirtualizingCollectionFactory.cs<|end_filename|> using System; using System.Linq; using System.Reactive.Concurrency; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.DataVirtualizingCollection; namespace BFF.DataVirtualizingCollection.Tests.Integration { internal static class DataVirtualizingCollectionFactory { internal static IDataVirtualizingCollection<int> CreateCollectionWithIncrementalInteger( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = DataVirtualizingCollectionBuilder.Build<int>( pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => -1); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, (offset, pSize) => Enumerable .Range(offset, pSize) .ToArray(), () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => -1); return dataVirtualizingCollection; } internal static IDataVirtualizingCollection<int> CreateCollectionWithIncrementalIntegerWhereFetchersIgnorePageSize( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = DataVirtualizingCollectionBuilder.Build<int>( pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => -1); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, (offset, pSize) => Enumerable .Range(offset, pageSize) // <--- This is different! pageSize instead of pSize! .ToArray(), () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => -1); return dataVirtualizingCollection; } internal static IDataVirtualizingCollection<T> CreateCollectionWithCustomPageFetchingLogic<T>( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, Func<int, int, T[]> pageFetchingLogic, T placeholder, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = DataVirtualizingCollectionBuilder.Build<T>( pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => placeholder); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, pageFetchingLogic, () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => placeholder); return dataVirtualizingCollection; } internal static IDataVirtualizingCollection<T> CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed<T>( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, Func<int, int, T[]> pageFetchingLogic, T placeholder, int pageLimit, int removalCount, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = DataVirtualizingCollectionBuilder.Build<T>( pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => placeholder); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, pageLimit, removalCount); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, pageFetchingLogic, () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => placeholder); return dataVirtualizingCollection; } private static IPageHoldingBehaviorCollectionBuilder<T, IDataVirtualizingCollection<T>> StandardPageHoldingBehaviorCollectionBuilder<T>( IPageLoadingBehaviorCollectionBuilder<T, IDataVirtualizingCollection<T>> pageLoadingBehaviorCollectionBuilder, PageLoadingBehavior pageLoadingBehavior, Func<int, int, T> preloadingPlaceholderFactory) => pageLoadingBehavior switch { PageLoadingBehavior.NonPreloading => pageLoadingBehaviorCollectionBuilder.NonPreloading(), PageLoadingBehavior.Preloading => pageLoadingBehaviorCollectionBuilder.Preloading(preloadingPlaceholderFactory), _ => throw new Exception("Test configuration failed!") }; private static IFetchersKindCollectionBuilder<T, IDataVirtualizingCollection<T>> StandardFetcherKindCollectionBuilder<T>(IPageHoldingBehaviorCollectionBuilder<T, IDataVirtualizingCollection<T>> pageHoldingBehaviorCollectionBuilder, PageRemovalBehavior pageRemovalBehavior, int pageLimit, int removalCount) => pageRemovalBehavior switch { PageRemovalBehavior.Hoarding => pageHoldingBehaviorCollectionBuilder.Hoarding(), PageRemovalBehavior.LeastRecentlyUsed => pageHoldingBehaviorCollectionBuilder.LeastRecentlyUsed(pageLimit, removalCount), _ => throw new Exception("Test configuration failed!") }; private static IAsyncOnlyIndexAccessBehaviorCollectionBuilder<T, IDataVirtualizingCollection<T>> StandardIndexAccessBehaviorCollectionBuilder<T>(IFetchersKindCollectionBuilder<T, IDataVirtualizingCollection<T>> fetchersKindCollectionBuilder, FetchersKind fetchersKind, Func<int, int, T[]> pageFetcher, Func<int> countFetcher) => fetchersKind switch { FetchersKind.NonTaskBased => fetchersKindCollectionBuilder.NonTaskBasedFetchers( (offset, pSize, _) => { Thread.Sleep(25); return pageFetcher(offset, pSize); }, _ => { Thread.Sleep(25); return countFetcher(); }), FetchersKind.TaskBased => fetchersKindCollectionBuilder.TaskBasedFetchers( async (offset, pSize, _) => { await Task.Delay(TimeSpan.FromTicks(1)).ConfigureAwait(false); return pageFetcher(offset, pSize); }, async _ => { await Task.Delay(TimeSpan.FromTicks(1)).ConfigureAwait(false); return countFetcher(); }), _ => throw new Exception("Test configuration failed!") }; private static IDataVirtualizingCollection<T> StandardDataVirtualizingCollection<T>(IAsyncOnlyIndexAccessBehaviorCollectionBuilder<T, IDataVirtualizingCollection<T>> indexAccessBehaviorCollectionBuilder, IndexAccessBehavior indexAccessBehavior, Func<T> placeholderFactory) => indexAccessBehavior switch { IndexAccessBehavior.Synchronous => (indexAccessBehaviorCollectionBuilder as IIndexAccessBehaviorCollectionBuilder<T, IDataVirtualizingCollection<T>>)?.SyncIndexAccess() ?? throw new Exception("Task-based fetchers and synchronous access is not allowed."), IndexAccessBehavior.Asynchronous => indexAccessBehaviorCollectionBuilder.AsyncIndexAccess( (_, __) => placeholderFactory()), _ => throw new Exception("Test configuration failed!") }; } } <|start_filename|>Sample.View/ViewModelInterfaceImplementations/GetScheduler.cs<|end_filename|> using System.Reactive.Concurrency; using System.Windows; using BFF.DataVirtualizingCollection.Sample.ViewModel.Interfaces; namespace BFF.DataVirtualizingCollection.Sample.View.ViewModelInterfaceImplementations { internal class GetSchedulers : IGetSchedulers { public GetSchedulers() { NotificationScheduler = new DispatcherScheduler(Application.Current.Dispatcher); } public IScheduler NotificationScheduler { get; } public IScheduler BackgroundScheduler => TaskPoolScheduler.Default; } } <|start_filename|>Sample.ViewModel/Utility/RxRelayCommand.cs<|end_filename|> using System; using System.Reactive.Linq; using System.Threading.Tasks; using System.Windows.Input; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Utility { public interface IRxRelayCommand : ICommand, IDisposable { } internal class RxRelayCommand<T> : IRxRelayCommand { protected Action<T> ExecuteAction = obj => { }; private readonly IDisposable _canExecuteSubscription; private bool _canExecute; protected RxRelayCommand(IObservable<bool> canExecute, bool initialCanExecute = true) { _canExecute = initialCanExecute; _canExecuteSubscription = canExecute .Where(b => b != _canExecute) .Subscribe(b => { _canExecute = b; CanExecuteChanged?.Invoke(this, EventArgs.Empty); }); } public RxRelayCommand(Action<T> executeAction, bool initialCanExecute = true) : this(executeAction, Observable.Never<bool>(), initialCanExecute) { } public RxRelayCommand(Action<T> executeAction, IObservable<bool> canExecute, bool initialCanExecute = true) : this(canExecute, initialCanExecute) => ExecuteAction = executeAction; public bool CanExecute(object parameter) => _canExecute; public void Execute(object parameter) => ExecuteAction((T) parameter); public event EventHandler? CanExecuteChanged; public void Dispose() => _canExecuteSubscription.Dispose(); } internal sealed class RxRelayCommand : RxRelayCommand<object> { private RxRelayCommand(IObservable<bool> canExecute, bool initialCanExecute = true) : base(canExecute, initialCanExecute) { } public RxRelayCommand(Action executeAction, bool initialCanExecute = true) : this(Observable.Never<bool>(), initialCanExecute) => ExecuteAction = _ => executeAction(); public RxRelayCommand(Action executeAction, IObservable<bool> canExecute, bool initialCanExecute = true) : this(canExecute, initialCanExecute) => ExecuteAction = _ => executeAction(); } internal class AsyncRxRelayCommand<T> : IRxRelayCommand { private readonly Func<T, Task> _executeAction; private readonly IDisposable _canExecuteSubscription; private bool _canExecute; public AsyncRxRelayCommand(Func<T, Task> executeAction, bool initialCanExecute = true) : this(executeAction, Observable.Never<bool>(), initialCanExecute) { } public AsyncRxRelayCommand(Func<T, Task> executeAction, IObservable<bool> canExecute, bool initialCanExecute = true) { _executeAction = executeAction; _canExecute = initialCanExecute; _canExecuteSubscription = canExecute .Where(b => b != _canExecute) .Subscribe(b => { _canExecute = b; CanExecuteChanged?.Invoke(this, EventArgs.Empty); }); } public bool CanExecute(object parameter) => _canExecute; public void Execute(object parameter) => _executeAction((T) parameter); public event EventHandler? CanExecuteChanged; public void Dispose() => _canExecuteSubscription.Dispose(); } internal sealed class AsyncRxRelayCommand : RxRelayCommand<object> { private AsyncRxRelayCommand(IObservable<bool> canExecute, bool initialCanExecute = true) : base(canExecute, initialCanExecute) { } public AsyncRxRelayCommand(Func<Task> executeAction, bool initialCanExecute = true) : this(Observable.Never<bool>(), initialCanExecute) => ExecuteAction = _ => executeAction(); public AsyncRxRelayCommand(Func<Task> executeAction, IObservable<bool> canExecute, bool initialCanExecute = true) : this(canExecute, initialCanExecute) => ExecuteAction = _ => executeAction(); } } <|start_filename|>Sample.Model/Models/SomeWorkloadObject.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.Model.Models { public interface ISomeWorkloadObject { int Number { get; } } internal abstract class SomeWorkloadObject : ISomeWorkloadObject { public SomeWorkloadObject(int number) { Number = number; } public int Number { get; } } } <|start_filename|>Sample.ViewModel/ViewModels/Decisions/PageLoadingBehaviorViewModel.cs<|end_filename|> using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions { public enum PageLoadingBehavior { NonPreloading, Preloading } public interface IPageLoadingBehaviorViewModel { PageLoadingBehavior PageLoadingBehavior { get; set; } IPageHoldingBehaviorCollectionBuilder<T, TVirtualizationKind> Configure<T, TVirtualizationKind>( IPageLoadingBehaviorCollectionBuilder<T, TVirtualizationKind> builder, IBackendAccess<T> backendAccess) { return PageLoadingBehavior == PageLoadingBehavior.NonPreloading ? builder.NonPreloading() : builder.Preloading(backendAccess.PreloadingPlaceholderFetch); } } internal class PageLoadingBehaviorViewModel : ObservableObject, IPageLoadingBehaviorViewModel { private PageLoadingBehavior _pageLoadingBehavior = PageLoadingBehavior.NonPreloading; public PageLoadingBehavior PageLoadingBehavior { get => _pageLoadingBehavior; set { if (_pageLoadingBehavior == value) return; _pageLoadingBehavior = value; OnPropertyChanged(); } } } } <|start_filename|>BFF.DataVirtualizingCollection/PageRemoval/LeastRecentlyUsedPageRemoval.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using BFF.DataVirtualizingCollection.Utilities; namespace BFF.DataVirtualizingCollection.PageRemoval { internal static class LeastRecentlyUsedPageRemoval { internal static Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> Create( int pageLimit, int removalCount, bool isPreloading, ITimestampProvider timestampProvider) { IDictionary<int, DateTime> lastUsage = new Dictionary<int, DateTime>(); return pageRequests => { if (isPreloading) { // Make sure at least three pages (because of the preloading the two pages need to be // considered for the neighbor pages of the last fetched page) stay in the page store pageLimit = pageLimit < 4 ? 4 : pageLimit; removalCount = removalCount < 1 ? 1 : removalCount > pageLimit - 3 ? pageLimit - 3 : removalCount; } else { // Make sure at least one page stays in the page store pageLimit = pageLimit < 2 ? 2 : pageLimit; removalCount = removalCount < 1 ? 1 : removalCount > pageLimit - 1 ? pageLimit - 1 : removalCount; } return pageRequests.Select(tuple => { lastUsage[tuple.PageKey] = timestampProvider.Now; // Don't request any page removals if page limit isn't reached if (lastUsage.Count <= pageLimit) return new ReadOnlyCollection<int>(new List<int>()); // Remove at least one page but as much as required to get below page limit // The "-1" is necessary because the currently requested page is included in the count of the last usages var actualRemovalCount = lastUsage.Count - 1 - pageLimit + removalCount; var removalRequests = new ReadOnlyCollection<int>( lastUsage // Sort by least recent usage .OrderBy(kvp => kvp.Value) .Take(actualRemovalCount) .Select(kvp => kvp.Key) .ToList()); // Assuming the page will be removed, they need to be removed from the last-usage tracking here as well foreach (var removalRequest in removalRequests) { lastUsage.Remove(removalRequest); } return removalRequests; }) .Where(list => list.Any()); }; } } } <|start_filename|>BFF.DataVirtualizingCollection/DataVirtualizingCollection/DataVirtualizingCollectionBuilder.cs<|end_filename|> using System; using System.Collections.Specialized; using System.ComponentModel; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection { /// <summary> /// Initial entry point for creating a data virtualizing collection. /// </summary> public static class DataVirtualizingCollectionBuilder { /// <summary> /// Use to configure general virtualization settings. /// Further settings are applied via method chaining. /// Page size is set to the default value 100. /// The background scheduler is per default the <see cref="TaskPoolScheduler"/>. /// </summary> /// <param name="notificationScheduler">A scheduler for sending the notifications (<see cref="INotifyCollectionChanged"/>, <see cref="INotifyPropertyChanged"/>).</param> public static IPageLoadingBehaviorCollectionBuilder<TItem, IDataVirtualizingCollection<TItem>> Build<TItem>( IScheduler notificationScheduler) => Build<TItem>(DataVirtualizingCollectionBuilderBase.DefaultPageSize, notificationScheduler); /// <summary> /// Use to configure general virtualization settings. /// Further settings are applied via method chaining. /// The background scheduler is per default the <see cref="TaskPoolScheduler"/>. /// </summary> /// <param name="pageSize">Maximum size of a single page.</param> /// <param name="notificationScheduler">A scheduler for sending the notifications (<see cref="INotifyCollectionChanged"/>, <see cref="INotifyPropertyChanged"/>).</param> public static IPageLoadingBehaviorCollectionBuilder<TItem, IDataVirtualizingCollection<TItem>> Build<TItem>( int pageSize, IScheduler notificationScheduler) => new DataVirtualizingCollectionBuilder<TItem>(pageSize, notificationScheduler); /// <summary> /// Use to configure general virtualization settings. /// Further settings are applied via method chaining. /// </summary> /// <param name="pageSize">Maximum size of a single page.</param> /// <param name="notificationScheduler">A scheduler for sending the notifications (<see cref="INotifyCollectionChanged"/>, <see cref="INotifyPropertyChanged"/>).</param> /// <param name="backgroundScheduler">Per default this scheduler is used for all background operations (page and count fetches, preloading). In further settings you'll have the option to override this scheduler with another for specific background operations. </param> public static IPageLoadingBehaviorCollectionBuilder<TItem, IDataVirtualizingCollection<TItem>> Build<TItem>( int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) => new DataVirtualizingCollectionBuilder<TItem>(pageSize, notificationScheduler, backgroundScheduler); } internal sealed class DataVirtualizingCollectionBuilder<TItem> : DataVirtualizingCollectionBuilderBase<TItem, IDataVirtualizingCollection<TItem>> { internal DataVirtualizingCollectionBuilder(int pageSize, IScheduler notificationScheduler) : base(pageSize, notificationScheduler) { } internal DataVirtualizingCollectionBuilder(int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) : base(pageSize, notificationScheduler, backgroundScheduler) { } protected override IDataVirtualizingCollection<TItem> GenerateTaskBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var taskBasedCountFetcher = TaskBasedCountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); return new AsyncDataVirtualizingCollection<TItem>( GenerateTaskBasedAsynchronousPageStorage(pageFetchEvents), taskBasedCountFetcher, pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler, CountBackgroundScheduler); } protected override IDataVirtualizingCollection<TItem> GenerateAsyncEnumerableBasedAsynchronousCollection(Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var taskBasedCountFetcher = TaskBasedCountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); return new AsyncDataVirtualizingCollection<TItem>( GenerateAsyncEnumerableBasedAsynchronousPageStorage(pageFetchEvents), taskBasedCountFetcher, pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler, CountBackgroundScheduler); } protected override IDataVirtualizingCollection<TItem> GenerateNonTaskBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var countFetcher = CountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); return new AsyncDataVirtualizingCollection<TItem>( GenerateNonTaskBasedAsynchronousPageStorage(pageFetchEvents), ct => Task.FromResult(countFetcher(ct)), pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler, CountBackgroundScheduler); } protected override IDataVirtualizingCollection<TItem> GenerateNonTaskBasedSynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var countFetcher = CountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); return new SyncDataVirtualizingCollection<TItem>( GenerateNonTaskBasedSynchronousPageStorage(pageFetchEvents), countFetcher, pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler); } } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/ImmediateAsyncPageFetchScheduler.cs<|end_filename|> using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.PageStorage { internal class ImmediateAsyncPageFetchScheduler : IAsyncPageFetchScheduler { public Task Schedule() => Task.CompletedTask; } } <|start_filename|>Sample.ViewModel/ViewModels/ProfileViewModel.cs<|end_filename|> using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using BFF.DataVirtualizingCollection.Sample.Model.Models; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels { public interface IProfileViewModel { } internal static class ProfileViewModelStatic { internal static IReadOnlyDictionary<IProfile, IProfileViewModel> ProfileToViewModel { get; } = new ReadOnlyDictionary<IProfile, IProfileViewModel>( new Dictionary<IProfile, IProfileViewModel>( ProfileStatic .ProfilePool .Select(p => new KeyValuePair<IProfile, IProfileViewModel>(p, new ProfileViewModel(p))) .Concat(new [] { new KeyValuePair<IProfile, IProfileViewModel>(ProfileStatic.Empty, EmptyProfileViewModel.Instance), new KeyValuePair<IProfile, IProfileViewModel>(ProfileStatic.Preloading, PreloadingProfileViewModel.Instance) }))); } public class EmptyProfileViewModel : IProfileViewModel { public static EmptyProfileViewModel Instance { get; } = new(); private EmptyProfileViewModel(){} } public class PreloadingProfileViewModel : IProfileViewModel { public static PreloadingProfileViewModel Instance { get; } = new(); private PreloadingProfileViewModel(){} } public class ProfileViewModel : IProfileViewModel { private readonly IProfile _profile; public ProfileViewModel( IProfile profile) { _profile = profile; } public string Occupation => _profile.Occupation; public string Salary => _profile.Salary; public string Name => _profile.Name; public string Description => _profile.Description; public bool IsAvailable => _profile.IsAvailable; public bool IsFreelancer => _profile.IsFreelancer; public string? CompanyName => _profile.CompanyName; public IReadOnlyList<string> Abilities => _profile.Abilities; public int HiddenAbilitiesCount => _profile.HiddenAbilitiesCount; public string PicturePath => _profile.PicturePath; } } <|start_filename|>Tests.Integration/PageRemoval/AsyncHoardingTests.cs<|end_filename|> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Threading.Tasks; using Microsoft.Reactive.Testing; using MoreLinq.Extensions; using Xunit; namespace BFF.DataVirtualizingCollection.Tests.Integration.PageRemoval { public class AsyncHoardingTests { public static IEnumerable<object[]> Combinations => Enum.GetValues(typeof(PageLoadingBehavior)).OfType<PageLoadingBehavior>() .Cartesian( Enum.GetValues(typeof(FetchersKind)).OfType<FetchersKind>(), (first, second) => new object[] {first, PageRemovalBehavior.Hoarding, second, IndexAccessBehavior.Asynchronous}); [Theory] [MemberData(nameof(Combinations))] public async Task With6969ElementsAndPageSize1000_GetAnElementFromEachPage_NoneDisposed( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogic( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 6900; i += 100) { var _ = collection[i]; } await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); // Assert Assert.Empty(set); } [Theory] [MemberData(nameof(Combinations))] public async Task With69ElementsAndPageSize10_GetAnElementFromEachPageDisposeCollection_AllDisposed( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); const int expected = 69; var set = new ConcurrentBag<int>(); var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogic( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, expected, 10, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= expected; i += 10) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } await collection.DisposeAsync(); await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); // Assert Assert.Equal(expected, set.Count); } } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/LifoAsyncPageFetchScheduler.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.PageStorage { internal class LifoAsyncPageFetchScheduler : IAsyncPageFetchScheduler { private readonly Stack<TaskCompletionSource<Unit>> _stack = new(); private readonly Subject<TaskCompletionSource<Unit>> _subject = new(); public LifoAsyncPageFetchScheduler( TimeSpan throttleDueTime, IScheduler pageRequestBackgroundScheduler) => _subject .Synchronize() .Do(tcs => _stack.Push(tcs)) .Throttle(throttleDueTime, pageRequestBackgroundScheduler) .Subscribe(_ => { while (_stack.Any()) { var tcs = _stack.Pop(); tcs.SetResult(Unit.Default); } }); public Task Schedule() { var taskCompletionSource = new TaskCompletionSource<Unit>(); _subject.OnNext(taskCompletionSource); return taskCompletionSource.Task; } } } <|start_filename|>Sample.Model/Models/HighWorkloadObject.cs<|end_filename|> using System; namespace BFF.DataVirtualizingCollection.Sample.Model.Models { public interface IHighWorkloadObject : ISomeWorkloadObject { } internal class HighWorkloadObject : SomeWorkloadObject, IHighWorkloadObject, IDisposable { // Simulates workload // ReSharper disable once UnusedMember.Local private readonly byte[] _workload = new byte[12500]; public HighWorkloadObject(int number) : base(number) { } public void Dispose() { Console.WriteLine("Disposed"); } } } <|start_filename|>Sample.View/Utilities/Converters.cs<|end_filename|> using System.Windows; using System.Windows.Data; namespace BFF.DataVirtualizingCollection.Sample.View.Utilities { public static class Converters { public static IValueConverter BoolToVisibility = LambdaConverters.ValueConverter.Create<bool, Visibility>( e => e.Value ? Visibility.Visible : Visibility.Collapsed); public static IValueConverter ValueEqualsToParameter = LambdaConverters.ValueConverter.Create<object, bool, object>( e => Equals(e.Value, e.Parameter)); } } <|start_filename|>Sample.Model/BackendAccesses/MillionNumbersBackendAccess.cs<|end_filename|> using System; using BFF.DataVirtualizingCollection.Sample.Model.PersistenceLink; namespace BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses { public interface IMillionNumbersBackendAccess : IBackendAccess<long> { } internal class MillionNumbersBackendAccess : IMillionNumbersBackendAccess { private readonly IFetchMillionNumbersFromBackend _fetchMillionNumbersFromBackend; public MillionNumbersBackendAccess( IFetchMillionNumbersFromBackend fetchMillionNumbersFromBackend) { _fetchMillionNumbersFromBackend = fetchMillionNumbersFromBackend; } public string Name => "A Million Numbers Accessed Through Sqlite"; public long[] PageFetch(int pageOffset, int pageSize) => _fetchMillionNumbersFromBackend.FetchPage(pageOffset, pageSize); public long PlaceholderFetch(int _, int __) { return -11L; } public long PreloadingPlaceholderFetch(int _, int __) { return -21L; } public int CountFetch() { return _fetchMillionNumbersFromBackend.CountFetch(); } } } <|start_filename|>Sample.ViewModel/ViewModels/Functions/SpecificFunctionsViewModel.cs<|end_filename|> using System.Windows.Input; using BFF.DataVirtualizingCollection.Sample.ViewModel.Utility; using BFF.DataVirtualizingCollection.SlidingWindow; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Functions { public interface ISpecificFunctionsViewModel { } public class SpecificFunctionsViewModel : ObservableObject, ISpecificFunctionsViewModel { public static SpecificFunctionsViewModel Empty = new(); protected SpecificFunctionsViewModel() {} } public interface ISlidingWindowFunctionsViewModel : ISpecificFunctionsViewModel { ICommand SlideLeft { get; } ICommand SlideRight { get; } ICommand IncreaseWindowSize { get; } ICommand DecreaseWindowSize { get; } } public class SlidingWindowFunctionsViewModel : ISlidingWindowFunctionsViewModel { public ICommand SlideLeft { get; } = new RxRelayCommand<ISlidingWindow>(sw => sw.SlideLeft()); public ICommand SlideRight { get; } = new RxRelayCommand<ISlidingWindow>(sw => sw.SlideRight()); public ICommand IncreaseWindowSize { get; } = new RxRelayCommand<ISlidingWindow>(sw => sw.IncreaseWindowSize()); public ICommand DecreaseWindowSize { get; } = new RxRelayCommand<ISlidingWindow>(sw => sw.DecreaseWindowSize()); } } <|start_filename|>Sample.ViewModel/Adapters/HighWorkloadCollectionAdapter.cs<|end_filename|> using System; using System.Linq; using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; using BFF.DataVirtualizingCollection.Sample.Model.Models; using BFF.DataVirtualizingCollection.Sample.ViewModel.Utility; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters { internal interface IHighWorkloadCollectionAdapter : IBackendAccessAdapter<ISomeWorkloadObjectViewModel> { } internal class HighWorkloadCollectionAdapter : IHighWorkloadCollectionAdapter { private readonly IHighWorkloadFakeBackendAccess _highWorkloadFakeBackendAccess; private readonly Func<ISomeWorkloadObject, ISomeWorkloadObjectViewModel> _someWorkloadObjectViewModelFactory; public HighWorkloadCollectionAdapter( IHighWorkloadFakeBackendAccess highWorkloadFakeBackendAccess, Func<ISomeWorkloadObject, ISomeWorkloadObjectViewModel> someWorkloadObjectViewModelFactory) { _highWorkloadFakeBackendAccess = highWorkloadFakeBackendAccess; _someWorkloadObjectViewModelFactory = someWorkloadObjectViewModelFactory; BackendAccess = TransformingBackendAccess<ISomeWorkloadObject, ISomeWorkloadObjectViewModel> .CreateTransformingBackendAccess( _highWorkloadFakeBackendAccess, TransformPage, TransformPlaceholder); } public string Name => _highWorkloadFakeBackendAccess.Name; public IBackendAccess<ISomeWorkloadObjectViewModel> BackendAccess { get; } public BackendAccessKind BackendAccessKind => BackendAccessKind.HighWorkload; private ISomeWorkloadObjectViewModel[] TransformPage(ISomeWorkloadObject[] page) { return page.Select(_someWorkloadObjectViewModelFactory).ToArray(); } private ISomeWorkloadObjectViewModel TransformPlaceholder(ISomeWorkloadObject item) { return _someWorkloadObjectViewModelFactory(item); } } } <|start_filename|>Sample.ViewModel/ViewModels/Decisions/IndexAccessBehaviorViewModel.cs<|end_filename|> using System; using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions { public enum IndexAccessBehavior { Synchronous, Asynchronous } internal interface IIndexAccessBehaviorViewModelInternal : IIndexAccessBehaviorViewModel { void SetIsSyncEnabled(bool value); } public interface IIndexAccessBehaviorViewModel { IndexAccessBehavior IndexAccessBehavior { get; set; } bool IsSyncEnabled { get; } public TVirtualizationKind Configure<T, TVirtualizationKind>( IAsyncOnlyIndexAccessBehaviorCollectionBuilder<T, TVirtualizationKind> builder, IBackendAccess<T> backendAccess, FetcherKind fetcherDecision) { return IndexAccessBehavior == IndexAccessBehavior.Synchronous ? fetcherDecision == FetcherKind.NonTaskBased ? builder is IIndexAccessBehaviorCollectionBuilder<T, TVirtualizationKind> indexAccessBehaviorCollectionBuilder ? indexAccessBehaviorCollectionBuilder.SyncIndexAccess() : throw new ArgumentException("Builder should implement all builder interfaces", nameof(builder)) : throw new ArgumentException("Cannot choose sync index access when chosen to use task-based fetchers.") : builder.AsyncIndexAccess(backendAccess.PlaceholderFetch); } } internal class IndexAccessBehaviorViewModel : ObservableObject, IIndexAccessBehaviorViewModelInternal { private IndexAccessBehavior _indexAccessBehavior = IndexAccessBehavior.Asynchronous; private bool _isSyncEnabled; public IndexAccessBehavior IndexAccessBehavior { get => _indexAccessBehavior; set { if (_indexAccessBehavior == value) return; _indexAccessBehavior = value; OnPropertyChanged(); } } public bool IsSyncEnabled { get => _isSyncEnabled; private set { if (value == _isSyncEnabled) return; _isSyncEnabled = value; OnPropertyChanged(); if (!_isSyncEnabled) { IndexAccessBehavior = IndexAccessBehavior.Asynchronous; } } } public void SetIsSyncEnabled(bool value) { IsSyncEnabled = value; } } } <|start_filename|>BFF.DataVirtualizingCollection/DataVirtualizingCollection/SyncDataVirtualizingCollection.cs<|end_filename|> using System; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using MrMeeseeks.Reactive.Extensions; namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection { internal sealed class SyncDataVirtualizingCollection<T> : DataVirtualizingCollectionBase<T> { private readonly Func<CancellationToken, int> _countFetcher; private readonly IScheduler _notificationScheduler; private readonly IPageStorage<T> _pageStorage; private readonly Subject<Unit> _resetSubject = new(); private int _count; internal SyncDataVirtualizingCollection( Func<int, IPageStorage<T>> pageStoreFactory, Func<CancellationToken, int> countFetcher, IObservable<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> observePageFetches, IDisposable disposeOnDisposal, IScheduler notificationScheduler) : base (observePageFetches, disposeOnDisposal, notificationScheduler) { _countFetcher = countFetcher; _notificationScheduler = notificationScheduler; _count = _countFetcher(CancellationToken.None); _pageStorage = pageStoreFactory(_count); _resetSubject.CompositeDisposalWith(CompositeDisposable); _resetSubject .Subscribe(_ => ResetInner()) .CompositeDisposalWith(CompositeDisposable); } public override int Count => _count; protected override T GetItemInner(int index) { return _pageStorage[index]; } private void ResetInner() { _count = _countFetcher(CancellationToken.None); _pageStorage.Reset(_count); _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnPropertyChanged(nameof(Count)); OnCollectionChangedReset(); OnIndexerChanged(); }); } public override void Reset() => _resetSubject.OnNext(Unit.Default); public override Task InitializationCompleted { get; } = Task.CompletedTask; public override async ValueTask DisposeAsync() { await base.DisposeAsync().ConfigureAwait(false); await _pageStorage.DisposeAsync().ConfigureAwait(false); } } } <|start_filename|>Sample.Model/PersistenceLink/IFetchMillionNumbersFromBackend.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.Model.PersistenceLink { public interface IFetchMillionNumbersFromBackend { long[] FetchPage(int pageOffset, int pageSize); int CountFetch(); } } <|start_filename|>Tests.Unit/PageStorage/PageTestsBase.cs<|end_filename|> using System; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using Xunit; namespace BFF.DataVirtualizingCollection.Test.PageStorage { public abstract class PageTestsBase { internal abstract IPage<int> PageWithPageSizeOne { get; } [Fact] internal async Task Index_FetchNegativeIndex_ThrowsIndexOutOfRangeException() { // Arrange await using var sut = PageWithPageSizeOne; // Act + Assert Assert.Throws<IndexOutOfRangeException>(() => sut[-1]); } [Fact] internal async Task Index_FetchIndexEqualToPageSize_ThrowsIndexOutOfRangeException() { // Arrange await using var sut = PageWithPageSizeOne; // Act + Assert Assert.Throws<IndexOutOfRangeException>(() => sut[1]); } } } <|start_filename|>Sample.ViewModel/ViewModels/Options/SlidingWindowOptionsViewModel.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Options { public interface ISpecificOptionsViewModel { } public class SpecificOptionsViewModel : ObservableObject, ISpecificOptionsViewModel { public static SpecificOptionsViewModel Empty = new(); protected SpecificOptionsViewModel() {} } public interface ISlidingWindowOptionsViewModel : ISpecificOptionsViewModel { int WindowSize { get; set; } int WindowOffset { get; set; } } public class SlidingWindowOptionsViewModel : SpecificOptionsViewModel, ISlidingWindowOptionsViewModel { private int _windowSize = 4; private int _windowOffset; public int WindowSize { get => _windowSize; set { if (_windowSize == value) return; _windowSize = value; OnPropertyChanged(); } } public int WindowOffset { get => _windowOffset; set { if (_windowOffset == value) return; _windowOffset = value; OnPropertyChanged(); } } } } <|start_filename|>Sample.ViewModel/ViewModels/Options/GeneralOptionsViewModel.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Options { public interface IGeneralOptionsViewModel { int PageSize { get; set; } } internal class GeneralOptionsViewModel : ObservableObject, IGeneralOptionsViewModel { private int _pageSize = 100; public int PageSize { get => _pageSize; set { if (_pageSize == value) return; _pageSize = value; OnPropertyChanged(); } } } } <|start_filename|>BFF.DataVirtualizingCollection/Utilities/ErrorMessage.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Utilities { internal static class ErrorMessage { internal static string ImpossibleExceptionMessage => "Unfortunately, an error occured during data virtualization, which should have been prevented. Please open an issue on https://github.com/Yeah69/BFF.DataVirtualizingCollection."; } } <|start_filename|>Tests.Unit/PageStorage/PageStorageTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using NSubstitute; using NSubstitute.Extensions; using NSubstitute.ReceivedExtensions; using Xunit; // ReSharper disable UnusedVariable *** Necessary for some tests // ReSharper disable AccessToDisposedClosure *** Controlled disposal namespace BFF.DataVirtualizingCollection.Test.PageStorage { public class PageStorageTests { [Fact] public async Task Index_RequestSeventhPage_SeventhPageRequested() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); using var requests = new ReplaySubject<(int PageKey, int PageIndex)>(); await using var sut = new PageStorage<int>( 10, 10000, (_, __, ___, ____) => page, req => { req.Subscribe(requests); return Observable.Never<IReadOnlyList<int>>(); }); // Act var unused = sut[69]; requests.OnCompleted(); // Assert Assert.Collection(requests.ToEnumerable(), tuple => { var (pageKey, pageIndex) = tuple; Assert.Equal(6, pageKey); Assert.Equal(9, pageIndex); }); } [Fact] public async Task Dispose_ThreePagesRequested_AllThreePagesDisposed() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var sut = new PageStorage<int>( 10, 10000, (_, __, ___, ____) => page, _ => Observable.Never<IReadOnlyList<int>>()); // Act var i = sut[69]; var i1 = sut[23]; var i2 = sut[3]; await sut.DisposeAsync().ConfigureAwait(false); // Assert await page.Received(Quantity.Exactly(3)).DisposeAsync(); } [Fact] public async Task PageRemoval_RemoveAllExceptFirstRequestedPage_TwoPagesDisposed() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var subject = new Subject<IReadOnlyList<int>>(); await using var sut = new PageStorage<int>( 10, 10000, (_, __, ___, ____) => page, _ => subject); // Act var i = sut[69]; var i1 = sut[23]; var i2 = sut[3]; subject.OnNext(new []{ 0, 2 }); // Assert await page.Received(Quantity.Exactly(2)).DisposeAsync(); } [Fact] public async Task PageCount_Initially0_0() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var subject = new Subject<IReadOnlyList<int>>(); await using var sut = new PageStorageSpy( 10, 0, (_, __, ___, ____) => page, _ => subject); // Act var result = sut.PageCountDisclosure; // Assert Assert.Equal(0, result); } [Fact] public async Task PageCount_InitiallyCount10000_1000() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var subject = new Subject<IReadOnlyList<int>>(); await using var sut = new PageStorageSpy( 10, 10000, (_, __, ___, ____) => page, _ => subject); // Act var result = sut.PageCountDisclosure; // Assert Assert.Equal(1000, result); } [Fact] public async Task PageCount_InitiallyCount0ThenResetCountTo10000_1000() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var subject = new Subject<IReadOnlyList<int>>(); await using var sut = new PageStorageSpy( 10, 0, (_, __, ___, ____) => page, _ => subject); await sut.Reset(10000).ConfigureAwait(false); // Act var result = sut.PageCountDisclosure; // Assert Assert.Equal(1000, result); } [Fact] public async Task PageCount_InitiallyCount0ThenResetCountTo10001_1001() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var subject = new Subject<IReadOnlyList<int>>(); await using var sut = new PageStorageSpy( 10, 0, (_, __, ___, ____) => page, _ => subject); await sut.Reset(10001).ConfigureAwait(false); // Act var result = sut.PageCountDisclosure; // Assert Assert.Equal(1001, result); } private class PageStorageSpy : PageStorage<int> { internal PageStorageSpy( int pageSize, int count, Func<int, int, int, IDisposable, IPage<int>> nonPreloadingPageFactory, Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> pageReplacementStrategyFactory) : base(pageSize, count, nonPreloadingPageFactory, pageReplacementStrategyFactory) { } internal int PageCountDisclosure => PageCount; } } } <|start_filename|>Sample.View/Views/Options/SlidingWindowOptionsView.xaml.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.View.Views.Options { public partial class SlidingWindowOptionsView { public SlidingWindowOptionsView() { InitializeComponent(); } } } <|start_filename|>Sample.View/Utilities/DataTemplateSelectors.cs<|end_filename|> using System.Windows; using System.Windows.Controls; using BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels; namespace BFF.DataVirtualizingCollection.Sample.View.Utilities { public class BackendAccessDataTemplateSelector : DataTemplateSelector { public DataTemplate? AllNumbersTemplate { get; set; } public DataTemplate? HighWorkloadTemplate { get; set; } public DataTemplate? MillionNumbersTemplate { get; set; } public DataTemplate? ProfileTemplate { get; set; } public override DataTemplate? SelectTemplate(object item, DependencyObject container) { return item is IDataVirtualizingCollectionViewModelBase dataVirtualizingCollectionViewModel ? dataVirtualizingCollectionViewModel.BackendAccessKind switch { BackendAccessKind.AllNumbers => AllNumbersTemplate, BackendAccessKind.HighWorkload => HighWorkloadTemplate, BackendAccessKind.MillionNumbers => MillionNumbersTemplate, BackendAccessKind.Profiles => ProfileTemplate, _ => base.SelectTemplate(item, container) } : base.SelectTemplate(item, container); } } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/PageStorage.cs<|end_filename|> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageRemoval; using MrMeeseeks.Reactive.Extensions; namespace BFF.DataVirtualizingCollection.PageStorage { internal interface IPageStorage<out T> : IAsyncDisposable { T this[int index] { get; } Task Reset(int newCount); } internal class PageStorage<T> : IPageStorage<T> { private readonly int _pageSize; private readonly Func<int, int, int, IDisposable, IPage<T>> _nonPreloadingPageFactory; private readonly CompositeDisposable _compositeDisposable = new(); protected bool IsDisposed; protected readonly object IsDisposedLock = new(); protected readonly ConcurrentDictionary<int, IPage<T>> Pages = new(); protected readonly ISubject<(int PageKey, int PageIndex)> Requests; private int _count; internal PageStorage( int pageSize, int count, Func<int, int, int, IDisposable, IPage<T>> nonPreloadingPageFactory, Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> pageReplacementStrategyFactory) { _pageSize = pageSize; _count = count; PageCount = CalculateCurrentPageCount(); _nonPreloadingPageFactory = nonPreloadingPageFactory; Requests = new Subject<(int PageKey, int PageIndex)>().CompositeDisposalWith(_compositeDisposable); pageReplacementStrategyFactory(Requests) .SelectMany(async pageKeysToRemove => { var disposables = new List<Task>(); foreach (var pageKey in pageKeysToRemove) { if (Pages.TryGetValue(pageKey, out var page)) disposables.Add(page.DisposeAsync().AsTask()); } await Task.WhenAll(disposables); return Unit.Default; }) .Subscribe(_ => { }, exception => throw new PageReplacementStrategyException( "LeastRecentlyUsed strategy: Something unexpected happened during page removal! See inner exception.", exception)) .CompositeDisposalWith(_compositeDisposable); } protected int PageCount { get; private set; } public T this[int index] { get { var pageKey = index / _pageSize; var pageIndex = index % _pageSize; lock (IsDisposedLock) { if (!IsDisposed) Requests.OnNext((pageKey, pageIndex)); } var ret = Pages .GetOrAdd( pageKey, FetchNonPreloadingPage) [pageIndex]; Preloading(pageKey); return ret; IPage<T> FetchNonPreloadingPage(int key) => FetchPage(key, _nonPreloadingPageFactory); } } public Task Reset(int newCount) { _count = newCount; PageCount = CalculateCurrentPageCount(); return Task.WhenAll( Pages.Values.ToList().Select(p => p.DisposeAsync().AsTask())); } protected virtual void Preloading(int pageKey) { } protected IPage<T> FetchPage(int key, Func<int, int, int, IDisposable, IPage<T>> fetcher) { var offset = key * _pageSize; var actualPageSize = Math.Min(_pageSize, _count - offset); var disposable = Disposable.Create(() => Pages.TryRemove(key, out _)); return fetcher(key, offset, actualPageSize, disposable); } public async ValueTask DisposeAsync() { var pages = Pages.Values.ToList(); Pages.Clear(); await Task.WhenAll( pages.Select(p => p.DisposeAsync().AsTask())); lock (IsDisposedLock) { _compositeDisposable.Dispose(); IsDisposed = true; } } private int CalculateCurrentPageCount() => _count % _pageSize == 0 ? _count / _pageSize : _count / _pageSize + 1; } } <|start_filename|>Sample.ViewModel/Adapters/MillionNumbersCollectionAdapter.cs<|end_filename|> using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters { internal interface IMillionNumbersCollectionAdapter : IBackendAccessAdapter<long> { } internal class MillionNumbersCollectionAdapter : IMillionNumbersCollectionAdapter { private readonly IMillionNumbersBackendAccess _millionNumbersBackendAccess; public MillionNumbersCollectionAdapter(IMillionNumbersBackendAccess millionNumbersBackendAccess) { _millionNumbersBackendAccess = millionNumbersBackendAccess; } public string Name => _millionNumbersBackendAccess.Name; public IBackendAccess<long> BackendAccess => _millionNumbersBackendAccess; public BackendAccessKind BackendAccessKind => BackendAccessKind.MillionNumbers; } } <|start_filename|>Sample.Model/BackendAccesses/HighWorkloadFakeBackendAccess.cs<|end_filename|> using System; using System.Linq; using BFF.DataVirtualizingCollection.Sample.Model.Models; namespace BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses { public interface IHighWorkloadFakeBackendAccess : IBackendAccess<ISomeWorkloadObject> { } internal class HighWorkloadFakeBackendAccess : IHighWorkloadFakeBackendAccess { private ISomeWorkloadObject Placeholder { get; } = (ISomeWorkloadObject) new LowWorkloadObject(-11); private ISomeWorkloadObject PreloadingPlaceholder { get; } = (ISomeWorkloadObject) new LowWorkloadObject(-11); public string Name => "High Workload Simulation"; public ISomeWorkloadObject[] PageFetch(int pageOffset, int pageSize) => Enumerable .Range(pageOffset, pageSize) .Select(i => (ISomeWorkloadObject) new HighWorkloadObject(i)) .ToArray(); public ISomeWorkloadObject PlaceholderFetch(int _, int __) { return Placeholder; } public ISomeWorkloadObject PreloadingPlaceholderFetch(int _, int __) { return PreloadingPlaceholder; } public int CountFetch() { return int.MaxValue; } } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/IPage.cs<|end_filename|> using System; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.PageStorage { internal interface IPage : IAsyncDisposable { Task PageFetchCompletion { get; } } internal interface IPage<out T> : IPage { T this[int index] { get; } } } <|start_filename|>Sample.ViewModel/Adapters/IBackendAccessAdapter.cs<|end_filename|> using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters { public enum BackendAccessKind { AllNumbers, HighWorkload, MillionNumbers, Profiles } public interface IBackendAccessAdapter<TViewModel> { string Name { get; } IBackendAccess<TViewModel> BackendAccess { get; } BackendAccessKind BackendAccessKind { get; } } } <|start_filename|>Sample.ViewModel/ViewModels/Functions/GeneralFunctionsViewModel.cs<|end_filename|> using System.Windows.Input; using BFF.DataVirtualizingCollection.Sample.ViewModel.Utility; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Functions { public interface IGeneralFunctionsViewModel { ICommand Reset { get; } } public class GeneralFunctionsViewModel : ObservableObject, IGeneralFunctionsViewModel { public ICommand Reset { get; } = new RxRelayCommand<IVirtualizationBase>(dvc => dvc.Reset()); } } <|start_filename|>Tests.Unit/PageRemoval/HoardingPageNonRemovalTests.cs<|end_filename|> using System; using System.Reactive.Subjects; using BFF.DataVirtualizingCollection.PageRemoval; using Xunit; // ReSharper disable UnusedVariable *** Necessary for some tests namespace BFF.DataVirtualizingCollection.Test.PageRemoval { public class HoardingPageNonRemovalTests { [Fact] public void Create_RequestAllPagesWithPageSizeOne_NeverRequestsRemoval() { // Arrange var requestedRemoval = false; using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = HoardingPageNonRemoval .Create() (pageRequests) .Subscribe(_ => requestedRemoval = true); for (var i = 0; i < int.MaxValue; i++) { pageRequests.OnNext((i, 0)); } pageRequests.OnNext((int.MaxValue, 0)); // Assert Assert.False(requestedRemoval); } } } <|start_filename|>Sample.Model/BackendAccesses/ProfilesFakeBackendAccess.cs<|end_filename|> using System; using System.Linq; using BFF.DataVirtualizingCollection.Sample.Model.Models; namespace BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses { public interface IProfilesFakeBackendAccess : IBackendAccess<IProfile> { } internal class ProfilesFakeBackendAccess : IProfilesFakeBackendAccess { public string Name => "Profiles"; public IProfile[] PageFetch(int pageOffset, int pageSize) => Enumerable .Range(pageOffset, pageSize) .Select(i => ProfileStatic.ProfilePool[i % ProfileStatic.ProfilePool.Count]) .ToArray(); public IProfile PlaceholderFetch(int _, int __) { return ProfileStatic.Empty; } public IProfile PreloadingPlaceholderFetch(int pageOffset, int indexInsidePage) { return ProfileStatic.Preloading; } public int CountFetch() { return 420420; } } } <|start_filename|>BFF.DataVirtualizingCollection/IBuilderInterfaces.cs<|end_filename|> using System; using System.Collections.Generic; using System.Reactive.Concurrency; using System.Threading; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection { /// <summary> /// Lets you configure the page loading behavior. /// Here you can turn the preloading on or off. Preloading means that neighboring pages from requested pages are loaded as well, assuming that they'll be requested soon. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IPageLoadingBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// No preloading. Pages are loaded only as soon as an item of the page is requested. /// </summary> IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonPreloading(); /// <summary> /// Pages are loaded as soon as an item of the page is requested or as soon as a neighboring page is loaded. /// Per default the initially configured background scheduler is taken for the preloads. /// </summary> /// <param name="preloadingPlaceholderFactory">Initially preloaded pages are filled with placeholders.</param> IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> Preloading( Func<int, int, TItem> preloadingPlaceholderFactory); /// <summary> /// Pages are loaded as soon as an item of the page is requested or as soon as a neighboring page is loaded. /// </summary> /// <param name="preloadingPlaceholderFactory">Initially preloaded pages are filled with placeholders.</param> /// <param name="preloadingBackgroundScheduler">A scheduler exclusively for preloading pages.</param> IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> Preloading( Func<int, int, TItem> preloadingPlaceholderFactory, IScheduler preloadingBackgroundScheduler); } /// <summary> /// Lets you configure the page holding behavior. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// In this mode pages are loaded on demand. However, once loaded the pages are hold in memory until the data virtualizing collection is reset or disposed. /// </summary> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> Hoarding(); /// <summary> /// If the page limit is reached then the page which is least recently used will be chosen for removal. /// </summary> /// <param name="pageLimit">Has to be greater than zero (with preloading greater than two) in order to maintain at least one page in the page store (when preloading is active, then the neighbors of the most recently requested page are maintained as well).</param> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> LeastRecentlyUsed( int pageLimit); /// <summary> /// If the page limit is reached then the pages (amount: removal buffer plus one) which are least recently used will be chosen for removal. /// </summary> /// <param name="pageLimit">Has to be greater than zero (with preloading greater than two) in order to maintain at least one page in the page store (when preloading is active, then the neighbors of the most recently requested page are maintained as well).</param> /// <param name="removalCount">Has to be in between one and the page limit minus one (so at least one page remains). /// With active preloading the removal count cannot be greater than the page limit minus three.</param> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> LeastRecentlyUsed( int pageLimit, int removalCount); /// <summary> /// With this function you can provide a custom page-removal strategy. /// You'll get an observable which emits all element requests in form of a key to the page and the element's index inside of the page. /// You'll have to return an observable which emits page-removal requests. You can request to remove several pages at once. /// </summary> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> CustomPageRemovalStrategy( Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> pageReplacementStrategyFactory); } /// <summary> /// Lets you configure the fetcher (page and count) kind and lets you also provide appropriate fetchers as well. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// You have to provide non-task-based (synchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">You have to provide a lambda function which gets the count of all elements in the backend.</param> [Obsolete("Please use the overload with CancellationToken parameters (which can be ignored if not required). This function will be removed in next major release.")] IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonTaskBasedFetchers( Func<int, int, TItem[]> pageFetcher, Func<int> countFetcher); /// <summary> /// You have to provide task-based (asynchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">You have to provide a lambda function which gets the count of all elements in the backend.</param> [Obsolete("Please use the overload with CancellationToken parameters (which can be ignored if not required). This function will be removed in next major release.")] IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> TaskBasedFetchers( Func<int, int, Task<TItem[]>> pageFetcher, Func<Task<int>> countFetcher); /// <summary> /// You have to provide non-task-based (synchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size, third parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">The parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which gets the count of all elements in the backend.</param> IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonTaskBasedFetchers( Func<int, int, CancellationToken, TItem[]> pageFetcher, Func<CancellationToken, int> countFetcher); /// <summary> /// You have to provide task-based (asynchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size, third parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">The parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which gets the count of all elements in the backend.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> TaskBasedFetchers( Func<int, int, CancellationToken, Task<TItem[]>> pageFetcher, Func<CancellationToken, Task<int>> countFetcher); /// <summary> /// You have to provide a enumerable-based (asynchronous) page fetcher and a task-based (asynchronous) count fetcher. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size, third parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">The parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which gets the count of all elements in the backend.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> AsyncEnumerableBasedFetchers( Func<int, int, CancellationToken, IAsyncEnumerable<TItem>> pageFetcher, Func<CancellationToken, Task<int>> countFetcher); } /// <summary> /// Lets you configure the asynchronous index access options. /// Asynchronous meas the if the page still needs to be loaded a placeholder will be provided. As soon as the page is loaded a notification is emitted which states that the entry of the index arrived. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// Page request are triggered right after the generation of the page's placeholders. /// <para/> /// This is the default behavior. You won't need to call it explicitly. /// </summary> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ImmediatePageRequests(); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// <para/> /// Default throttling due time is set to 200 ms and default scheduler is the same as for the page requests. /// </summary> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// <para/> /// Default scheduler is the same as for the page requests. /// </summary> /// <param name="throttleDueTime">Time span which has to pass by without new page request until the collected page requests are triggered.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(TimeSpan throttleDueTime); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// <para/> /// Default throttling due time is set to 200 ms. /// </summary> /// <param name="pageRequestBackgroundScheduler">A scheduler exclusively for page request delaying.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(IScheduler pageRequestBackgroundScheduler); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// </summary> /// <param name="throttleDueTime">Time span which has to pass by without new page request until the collected page requests are triggered.</param> /// <param name="pageRequestBackgroundScheduler">A scheduler exclusively for page request delaying.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(TimeSpan throttleDueTime, IScheduler pageRequestBackgroundScheduler); /// <summary> /// If item of requested index isn't loaded yet the collections will return a placeholder instead and emit a notification as soon as it arrives. /// Per default the initially configured background scheduler is taken for page and count fetches. /// </summary> /// <param name="placeholderFactory">You have to provide a factory lambda function which returns a placeholder. /// The first parameter is the page key (index of pages) and the second is the page index (index of items inside the page).</param> TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory); /// <summary> /// If item of requested index isn't loaded yet the collections will return a placeholder instead and emit a notification as soon as it arrives. /// Per default the initially configured background scheduler is taken for count fetches. /// </summary> /// <param name="placeholderFactory">You have to provide a factory lambda function which returns a placeholder. /// The first parameter is the page key (index of pages) and the second is the page index (index of items inside the page).</param> /// <param name="pageBackgroundScheduler">A scheduler exclusively for page fetches.</param> TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory, IScheduler pageBackgroundScheduler); /// <summary> /// If item of requested index isn't loaded yet the collections will return a placeholder instead and emit a notification as soon as it arrives. /// </summary> /// <param name="placeholderFactory">You have to provide a factory lambda function which returns a placeholder. /// The first parameter is the page key (index of pages) and the second is the page index (index of items inside the page).</param> /// <param name="pageBackgroundScheduler">A scheduler exclusively for page fetches.</param> /// <param name="countBackgroundScheduler">A scheduler exclusively for count fetches.</param> TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory, IScheduler pageBackgroundScheduler, IScheduler countBackgroundScheduler); } /// <summary> /// Lets you configure whether the index access should be synchronous or asynchronous. /// Synchronous means that if the index access will wait actively until the entry is provided even if the page still has to be loaded. /// Asynchronous meas the if the page still needs to be loaded a placeholder will be provided. As soon as the page is loaded a notification is emitted which states that the entry of the index arrived. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> : IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// If item of requested index isn't loaded yet the collections will wait actively and return as soon as it arrives. /// Depending on the latency of the page fetcher it may result in freezes of the application. /// </summary> TVirtualizationKind SyncIndexAccess(); } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/PreloadingPageStorage.cs<|end_filename|> using System; using System.Collections.Generic; namespace BFF.DataVirtualizingCollection.PageStorage { internal class PreloadingPageStorage<T> : PageStorage<T> { private readonly Func<int, int, int, IDisposable, IPage<T>> _preloadingPageFactory; internal PreloadingPageStorage( int pageSize, int count, Func<int, int, int, IDisposable, IPage<T>> nonPreloadingPageFactory, Func<int, int, int, IDisposable, IPage<T>> preloadingPageFactory, Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> pageReplacementStrategyFactory) : base ( pageSize, count, nonPreloadingPageFactory, pageReplacementStrategyFactory) { _preloadingPageFactory = preloadingPageFactory; } protected override void Preloading(int pageKey) { var nextPageKey = pageKey + 1; if (nextPageKey < PageCount) Pages.GetOrAdd( nextPageKey, FetchPreloadingPage); var previousPageKey = pageKey - 1; if (previousPageKey >= 0) Pages.GetOrAdd( previousPageKey, FetchPreloadingPage); IPage<T> FetchPreloadingPage(int key) { lock (IsDisposedLock) { if (!IsDisposed) Requests.OnNext((key, -1)); } return FetchPage(key, _preloadingPageFactory); } } } } <|start_filename|>Sample.Persistence/PersistenceLink/FetchMillionNumbersFromBackend.cs<|end_filename|> using System.Collections.Generic; using System.IO; using System.Linq; using BFF.DataVirtualizingCollection.Sample.Model.PersistenceLink; using Microsoft.Data.Sqlite; namespace BFF.DataVirtualizingCollection.Sample.Persistence.PersistenceLink { internal class FetchMillionNumbersFromBackend : IFetchMillionNumbersFromBackend { private static readonly string PathToSimpleTestDb = $"{System.Reflection.Assembly.GetEntryAssembly()?.Location.Remove(System.Reflection.Assembly.GetEntryAssembly()?.Location.LastIndexOf(Path.DirectorySeparatorChar) ?? 0)}{Path.DirectorySeparatorChar}Databases{Path.DirectorySeparatorChar}BFF.DataVirtualizingCollection.MillionNumbers.sqlite"; public long[] FetchPage(int pageOffset, int pageSize) { using var sqliteConnection = new SqliteConnection( new SqliteConnectionStringBuilder { DataSource = PathToSimpleTestDb } .ToString()); sqliteConnection.Open(); sqliteConnection.BeginTransaction(); var sqliteCommand = sqliteConnection.CreateCommand(); sqliteCommand.CommandText = $"SELECT Number FROM Numbers LIMIT {pageSize} OFFSET {pageOffset};"; var sqliteDataReader = sqliteCommand.ExecuteReader(); IList<long> ret = new List<long>(); while (sqliteDataReader.Read()) ret.Add((long)sqliteDataReader["Number"]); return ret.ToArray(); } public int CountFetch() { using var sqliteConnection = new SqliteConnection( new SqliteConnectionStringBuilder { DataSource = PathToSimpleTestDb } .ToString()); sqliteConnection.Open(); var sqliteCommand = sqliteConnection.CreateCommand(); sqliteCommand.CommandText = "SELECT Count(*) FROM Numbers;"; return (int)(long)sqliteCommand.ExecuteScalar(); } } } <|start_filename|>BFF.DataVirtualizingCollection/IVirtualizationBase.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection { /// <summary> /// Root interface of all virtualizing collection types. Implements all necessary .Net interfaces (<c>IList</c>, <c>INotifyCollectionChanged</c>, <c>INotifyPropertyChanged</c>) in order to be usable by standard UI controls (like <c>ItemsControl</c> from WPF). <para/> /// Additionally, it has virtualization-specific members of its own. See documentation of the members for further details. <para/> /// </summary> /// <remarks> /// Implements IList in order to mock a standard .Net list. Controls like the <c>ItemsControl</c> from WPF in combination with the <c>VirtualizingStackPanel</c> use the indexer in order to load items on demand. Also the Count-property is used to arrange the scroll bar accordingly. <para/> /// The virtualized collections automatically changes its items. For example, if an async index access or preloading is set up, it will be eventually necessary to replace placeholders with the actually loaded items. In order to notify this changes to the UI the <c>INotifyCollectionChanged</c> interface is implemented. <para/> /// Also the properties of the collection itself may change, especially the Count-property. Hence notifications for such changes are send with <c>INotifyPropertyChanged</c>. <para/> /// Finally, each virtualizing collection has to be disposed after use, because it uses Rx subscriptions which have to be cleaned up. Also the currently active pages including their items which implement <c>IDisposable</c> are disposed as well. /// </remarks> public interface IVirtualizationBase : IList, INotifyCollectionChanged, INotifyPropertyChanged, IAsyncDisposable { /// <summary> /// Task is successfully completed when initialization is completed. <para/> /// </summary> /// <remarks> /// Initialization depends on the initial calculation of the Count-property. Because of the asynchronicity of task-based fetchers the Count-property might not be calculated at the end of construction of the virtualized collection. /// </remarks> Task InitializationCompleted { get; } /// <summary> /// Can be bound to SelectedIndexProperty on Selector controls in order to workaround issue with resets and selected items. <para/> /// </summary> /// <remarks> /// In WPF the Selector control will search for the previously selected item after each reset by iterating over all items until found. This behavior is the opposite of virtualization. Hence, the virtualizing collection would set this property to -1 (deselection) and notify the change before notifying any reset. /// </remarks> int SelectedIndex { get; set; } /// <summary> /// Disposes of all current pages and notifies that possibly everything changed. <para/> /// The Reset-function should be called any time when something in the virtualized backend has changed. <para/> /// </summary> /// <remarks> /// Consequently, the Count-property is recalculated. The UI will request all currently rendered items anew, so this items get reloaded. /// </remarks> void Reset(); } /// <summary> /// The generic version of <see cref="IVirtualizationBase"/>. Analogously, it implements <see cref="IList{T}"/> and <see cref="IReadOnlyList{T}"/>. /// </summary> /// <typeparam name="T">Item type.</typeparam> // ReSharper disable once PossibleInterfaceMemberAmbiguity *** the "new" members of this interface resolve the ambiguities public interface IVirtualizationBase<T> : IVirtualizationBase, IList<T>, IReadOnlyList<T> { /// <summary> /// The Count-property is newed here in order to resolve ambiguities cause by implementing <see cref="IList"/>, <see cref="IList{T}"/> and <see cref="IReadOnlyList{T}"/> at the same time. /// </summary> new int Count { get; } /// <summary> /// The indexer is newed here in order to resolve ambiguities cause by implementing <see cref="IList"/>, <see cref="IList{T}"/> and <see cref="IReadOnlyList{T}"/> at the same time. /// </summary> new T this[int index] { get; } } } <|start_filename|>Sample.Model/Models/Profile.cs<|end_filename|> using System.Collections.Generic; using System.Collections.ObjectModel; namespace BFF.DataVirtualizingCollection.Sample.Model.Models { public interface IProfile { string Occupation { get; } string Salary { get; } string Name { get; } string Description { get; } bool IsAvailable { get; } bool IsFreelancer { get; } string? CompanyName { get; } IReadOnlyList<string> Abilities { get; } int HiddenAbilitiesCount { get; } string PicturePath { get; } } public static class ProfileStatic { public static IReadOnlyList<IProfile> ProfilePool { get; } = new ReadOnlyCollection<IProfile>( new List<IProfile> { new Profile( "UI/UX designer", "$55/hr", "<NAME>", "Wade is a 32 year old UI/UX designer, with an impressive portfolio behind him.", true, false, "Epic Coders", new List<string>{ "UI", "UX", "photoshop" }, 4, "pack://application:,,,/ProfilePics/00_Wide.png"), new Profile( "mobile designer", "$32/hr", "<NAME>", "Paria is an android and iOS developer who worked at Apple for 6 years.", false, true, null, new List<string>{ "PHP", "android", "iOS"}, 2, "pack://application:,,,/ProfilePics/01_Paria.png"), new Profile( "mobile designer", "$42/hr", "<NAME>", "Morexandra is a dedicated developer for mobile platforms and is very good at it.", false, true, null, new List<string>{ "PHP", "android", "iOS"}, 12, "pack://application:,,,/ProfilePics/02_Morexandra.png"), new Profile( "interactive designer", "$44/hr", "<NAME>", "Smennifer is an interactive designer who is really awesome at what she does.", false, true, null, new List<string>{ "PHP", "android", "iOS"}, 2, "pack://application:,,,/ProfilePics/03_Smennifer.png"), new Profile( "mobile designer", "$40/hr", "<NAME>", "Anyetlana is an Android and iOS designer with advanced knowledge in coding.", true, true, null, new List<string>{ "PHP", "android", "iOS"}, 2, "pack://application:,,,/ProfilePics/04_Anyetlana.png"), new Profile( "UI/UX designer", "$30/hr", "<NAME>", "Korko is a 25 year old web designer with an impressive portfolio behind him.", false, false, "Visual Madness", new List<string>{ "UI", "UX", "photoshop"}, 4, "pack://application:,,,/ProfilePics/05_Korko.png"), new Profile( "UX designer", "$50/hr", "<NAME>", "Kowel is a 32 year old UX designer, with over 10 years of experience in what he does.", false, false, "Apple Inc", new List<string>{ "UI", "UX", "photoshop" }, 4, "pack://application:,,,/ProfilePics/06_Kowel.png"), new Profile( "mobile designer", "$32/hr", "<NAME>", "Sinia is an android and iOS developer who worked at Apple for 6 years.", false, true, null, new List<string>{ "PHP", "android", "iOS" }, 2, "pack://application:,,,/ProfilePics/07_Sinia.png"), new Profile( "photographer", "$40/hr", "<NAME>", "Wonathan is a 28 year old photographer from London with real talent for what he does.", false, false, "Epic Coders", new List<string>{ "UI", "UX", "photoshop" }, 4, "pack://application:,,,/ProfilePics/08_Wonathan.png"), new Profile( "Superhero", "free", "Matban", "I'm Matban!", false, true, null, new List<string>{ "tech", "IT", "martial arts" }, 69, "pack://application:,,,/ProfilePics/09_Matban.png"), new Profile( "mobile designer", "$39/hr", "<NAME>", "Surgiana is an android and iOS developer who worked at Apple for 6 years.", false, true, null, new List<string>{ "PHP", "android", "iOS" }, 2, "pack://application:,,,/ProfilePics/10_Surgiana.png"), new Profile( "UI/UX designer", "$45/hr", "<NAME>", "Jogory is a 32 year old UI/UX designer, with an impressive portfolio behind him.", false, false, "Epic Coders", new List<string>{ "UI", "UX", "photoshop" }, 4, "pack://application:,,,/ProfilePics/11_Jogory.png") }); public static IProfile Empty { get; } = new Profile(); public static IProfile Preloading { get; } = new Profile(); } internal class Profile : IProfile { public Profile( string occupation, string salary, string name, string description, bool isAvailable, bool isFreelancer, string? companyName, IReadOnlyList<string> abilities, int hiddenAbilitiesCount, string picturePath) { Occupation = occupation; Salary = salary; Name = name; Description = description; IsAvailable = isAvailable; IsFreelancer = isFreelancer; CompanyName = companyName; Abilities = abilities; HiddenAbilitiesCount = hiddenAbilitiesCount; PicturePath = picturePath; } internal Profile() { Occupation = string.Empty; Salary = string.Empty; Name = string.Empty; Description = string.Empty; Abilities = new string[0]; PicturePath = string.Empty; } public string Occupation { get; } public string Salary { get; } public string Name { get; } public string Description { get; } public bool IsAvailable { get; } public bool IsFreelancer { get; } public string? CompanyName { get; } public IReadOnlyList<string> Abilities { get; } public int HiddenAbilitiesCount { get; } public string PicturePath { get; } } } <|start_filename|>Sample.View/Views/Functions/SpecificFunctionsView.xaml.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.View.Views.Functions { public partial class SpecificFunctionsView { public SpecificFunctionsView() => InitializeComponent(); } } <|start_filename|>Sample.ViewModel/Interfaces/IGetSchedulers.cs<|end_filename|> using System.Reactive.Concurrency; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Interfaces { public interface IGetSchedulers { IScheduler NotificationScheduler { get; } IScheduler BackgroundScheduler { get; } } } <|start_filename|>BFF.DataVirtualizingCollection/SlidingWindow/SlidingWindowBuilder.cs<|end_filename|> using System; using System.Collections.Specialized; using System.ComponentModel; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.DataVirtualizingCollection; namespace BFF.DataVirtualizingCollection.SlidingWindow { /// <summary> /// Initial entry point for creating a sliding window. /// </summary> public static class SlidingWindowBuilder { /// <summary> /// Use to configure general virtualization and sliding-window-specific settings. /// Further settings are applied via method chaining. /// Page size is set to the default value 100. /// The background scheduler is per default the <see cref="TaskPoolScheduler"/>. /// </summary> /// <param name="windowSize">Initial count of items that the window should contain.</param> /// <param name="initialOffset">Initial starting item within the backend.</param> /// <param name="notificationScheduler">A scheduler for sending the notifications (<see cref="INotifyCollectionChanged"/>, <see cref="INotifyPropertyChanged"/>).</param> public static IPageLoadingBehaviorCollectionBuilder<TItem, ISlidingWindow<TItem>> Build<TItem>( int windowSize, int initialOffset, IScheduler notificationScheduler) => Build<TItem>(windowSize, initialOffset, DataVirtualizingCollectionBuilderBase.DefaultPageSize, notificationScheduler); /// <summary> /// Use to configure general virtualization and sliding-window-specific settings. /// Further settings are applied via method chaining. /// The background scheduler is per default the <see cref="TaskPoolScheduler"/>. /// </summary> /// <param name="windowSize">Initial count of items that the window should contain.</param> /// <param name="initialOffset">Initial starting item within the backend.</param> /// <param name="pageSize">Maximum size of a single page.</param> /// <param name="notificationScheduler">A scheduler for sending the notifications (<see cref="INotifyCollectionChanged"/>, <see cref="INotifyPropertyChanged"/>).</param> public static IPageLoadingBehaviorCollectionBuilder<TItem, ISlidingWindow<TItem>> Build<TItem>( int windowSize, int initialOffset, int pageSize, IScheduler notificationScheduler) => new SlidingWindowBuilder<TItem>(windowSize, initialOffset, pageSize, notificationScheduler); /// <summary> /// Use to configure general virtualization and sliding-window-specific settings. /// Further settings are applied via method chaining. /// </summary> /// <param name="windowSize">Initial count of items that the window should contain.</param> /// <param name="initialOffset">Initial starting item within the backend.</param> /// <param name="pageSize">Maximum size of a single page.</param> /// <param name="notificationScheduler">A scheduler for sending the notifications (<see cref="INotifyCollectionChanged"/>, <see cref="INotifyPropertyChanged"/>).</param> /// <param name="backgroundScheduler">Per default this scheduler is used for all background operations (page and count fetches, preloading). In further settings you'll have the option to override this scheduler with another for specific background operations. </param> public static IPageLoadingBehaviorCollectionBuilder<TItem, ISlidingWindow<TItem>> Build<TItem>( int windowSize, int initialOffset, int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) => new SlidingWindowBuilder<TItem>(windowSize, initialOffset, pageSize, notificationScheduler, backgroundScheduler); } internal class SlidingWindowBuilder<TItem> : DataVirtualizingCollectionBuilderBase<TItem, ISlidingWindow<TItem>> { private readonly int _windowSize; private readonly int _initialOffset; internal SlidingWindowBuilder(int windowSize, int initialOffset, int pageSize, IScheduler notificationScheduler) : base(pageSize, notificationScheduler) { _windowSize = windowSize; _initialOffset = initialOffset; } internal SlidingWindowBuilder(int windowSize, int initialOffset, int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) : base(pageSize, notificationScheduler, backgroundScheduler) { _windowSize = windowSize; _initialOffset = initialOffset; } protected override ISlidingWindow<TItem> GenerateTaskBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var taskBasedCountFetcher = TaskBasedCountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var dvc = new AsyncDataVirtualizingCollection<TItem>( GenerateTaskBasedAsynchronousPageStorage(pageFetchEvents), taskBasedCountFetcher, pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler, CountBackgroundScheduler); return new SlidingWindow<TItem>( _initialOffset, _windowSize, dvc, NotificationScheduler); } protected override ISlidingWindow<TItem> GenerateAsyncEnumerableBasedAsynchronousCollection(Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var taskBasedCountFetcher = TaskBasedCountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var dvc = new AsyncDataVirtualizingCollection<TItem>( GenerateAsyncEnumerableBasedAsynchronousPageStorage(pageFetchEvents), taskBasedCountFetcher, pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler, CountBackgroundScheduler); return new SlidingWindow<TItem>( _initialOffset, _windowSize, dvc, NotificationScheduler); } protected override ISlidingWindow<TItem> GenerateNonTaskBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var countFetcher = CountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var dvc = new AsyncDataVirtualizingCollection<TItem>( GenerateNonTaskBasedAsynchronousPageStorage(pageFetchEvents), ct => Task.FromResult(countFetcher(ct)), pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler, CountBackgroundScheduler); return new SlidingWindow<TItem>( _initialOffset, _windowSize, dvc, NotificationScheduler); } protected override ISlidingWindow<TItem> GenerateNonTaskBasedSynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var countFetcher = CountFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var dvc = new SyncDataVirtualizingCollection<TItem>( GenerateNonTaskBasedSynchronousPageStorage(pageFetchEvents), countFetcher, pageFetchEvents.AsObservable(), pageFetchEvents, NotificationScheduler); return new SlidingWindow<TItem>( _initialOffset, _windowSize, dvc, NotificationScheduler); } } } <|start_filename|>BFF.DataVirtualizingCollection/PageRemoval/PageReplacementStrategyException.cs<|end_filename|> using System; namespace BFF.DataVirtualizingCollection.PageRemoval { /// <summary> /// Thrown whenever an exception occurs during the process of page replacement. /// </summary> public class PageReplacementStrategyException : Exception { internal PageReplacementStrategyException(string message, Exception innerException) : base(message, innerException) { } } } <|start_filename|>Sample.ViewModel/ViewModels/Decisions/PageRemovalBehaviorViewModel.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions { public enum PageRemovalBehavior { LeastRecentlyUsed, Hoarding } public interface IPageRemovalBehaviorViewModel { PageRemovalBehavior PageRemovalBehavior { get; set; } public int LeastRecentlyUsedPageLimit { get; set; } public int LeastRecentlyUsedRemovalCount { get; set; } IFetchersKindCollectionBuilder<T, TVirtualizationKind> Configure<T, TVirtualizationKind>( IPageHoldingBehaviorCollectionBuilder<T, TVirtualizationKind> builder) => PageRemovalBehavior == PageRemovalBehavior.LeastRecentlyUsed ? builder.LeastRecentlyUsed(LeastRecentlyUsedPageLimit, LeastRecentlyUsedRemovalCount) : builder.Hoarding(); } internal class PageRemovalBehaviorViewModel : ObservableObject, IPageRemovalBehaviorViewModel { private PageRemovalBehavior _pageRemovalBehavior = PageRemovalBehavior.LeastRecentlyUsed; private int _leastRecentlyUsedPageLimit = 10; private int _leastRecentlyUsedRemovalCount = 1; public PageRemovalBehavior PageRemovalBehavior { get => _pageRemovalBehavior; set { if (_pageRemovalBehavior == value) return; _pageRemovalBehavior = value; OnPropertyChanged(); } } public int LeastRecentlyUsedPageLimit { get => _leastRecentlyUsedPageLimit; set { if (_leastRecentlyUsedPageLimit == value) return; _leastRecentlyUsedPageLimit = value; OnPropertyChanged(); } } public int LeastRecentlyUsedRemovalCount { get => _leastRecentlyUsedRemovalCount; set { if (_leastRecentlyUsedRemovalCount == value) return; _leastRecentlyUsedRemovalCount = value; OnPropertyChanged(); } } } } <|start_filename|>BFF.DataVirtualizingCollection/SlidingWindow/SlidingWindow.cs<|end_filename|> using System; using System.Collections.Specialized; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.DataVirtualizingCollection; using MrMeeseeks.Reactive.Extensions; namespace BFF.DataVirtualizingCollection.SlidingWindow { internal sealed class SlidingWindow<T> : VirtualizationBase<T>, ISlidingWindow<T> { private readonly IDataVirtualizingCollection<T> _dataVirtualizingCollection; private readonly IScheduler _notificationScheduler; private int _size; internal SlidingWindow( int offset, int windowSize, IDataVirtualizingCollection<T> dataVirtualizingCollection, IScheduler notificationScheduler) { _size = 0; Offset = 0; _dataVirtualizingCollection = dataVirtualizingCollection; _notificationScheduler = notificationScheduler; Observable .FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>( handler => handler.Invoke, h => _dataVirtualizingCollection.CollectionChanged += h, h => _dataVirtualizingCollection.CollectionChanged -= h) .ObserveOn(notificationScheduler) .Subscribe(e => { switch (e.EventArgs.Action) { case NotifyCollectionChangedAction.Replace: var index = e.EventArgs.NewStartingIndex - Offset; if (index < 0 || index >= _size) return; OnCollectionChangedReplace((T) e.EventArgs.NewItems[0], (T) e.EventArgs.OldItems[0], index); break; case NotifyCollectionChangedAction.Reset: OnCollectionChangedReset(); break; default: throw new Exception("Something unexpected happened."); } }); _dataVirtualizingCollection .ObservePropertyChanged(nameof(IDataVirtualizingCollection.Count)) .ObserveOn(notificationScheduler) .Subscribe(_ => { OnPropertyChanged(nameof(Count)); OnPropertyChanged(nameof(MaximumOffset)); }) .CompositeDisposalWith(CompositeDisposable); _dataVirtualizingCollection .ObservePropertyChanged("Item[]") .ObserveOn(notificationScheduler) .Subscribe(_ => OnIndexerChanged()) .CompositeDisposalWith(CompositeDisposable); InitializationCompleted = dataVirtualizingCollection .InitializationCompleted .ToObservable() .ObserveOn(notificationScheduler) .Do(_ => { _size = windowSize; JumpTo(offset); }) .FirstAsync() .ToTask(); } public int Offset { get; private set; } public int MaximumOffset => _dataVirtualizingCollection.Count - _size; public override int SelectedIndex { get; set; } public void SlideLeft() { if (Offset <= 0) return; Offset--; _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnCollectionChangedReset(); OnPropertyChanged(nameof(Offset)); OnIndexerChanged(); }); } public void SlideRight() { if (MaximumOffset <= Offset) return; Offset++; _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnCollectionChangedReset(); OnPropertyChanged(nameof(Offset)); OnIndexerChanged(); }); } public void JumpTo(int index) { Offset = Math.Max(0, Math.Min(_dataVirtualizingCollection.Count - _size, index)); _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnCollectionChangedReset(); OnPropertyChanged(nameof(Offset)); OnIndexerChanged(); }); } public void IncreaseWindowSize() { IncreaseWindowSizeBy(1); } public void DecreaseWindowSize() { DecreaseWindowSizeBy(1); } public void IncreaseWindowSizeBy(int sizeIncrement) { sizeIncrement = Math.Max(0, sizeIncrement); _size = Math.Min(_dataVirtualizingCollection.Count, _size + sizeIncrement); if (Offset > MaximumOffset) Offset = MaximumOffset; _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnCollectionChangedReset(); OnPropertyChanged(nameof(Offset)); OnPropertyChanged(nameof(MaximumOffset)); OnPropertyChanged(nameof(Count)); OnIndexerChanged(); }); } public void DecreaseWindowSizeBy(int sizeIncrement) { sizeIncrement = Math.Max(0, sizeIncrement); _size = Math.Max(0, _size - sizeIncrement); _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnCollectionChangedReset(); OnPropertyChanged(nameof(Offset)); OnPropertyChanged(nameof(MaximumOffset)); OnPropertyChanged(nameof(Count)); OnIndexerChanged(); }); } public void SetWindowSizeTo(int size) { if (size < 0) throw new ArgumentException("Given size may not be below zero.", nameof(size)); if (size == _size) return; var diff = size - _size; if (diff < 0) DecreaseWindowSizeBy(-diff); else IncreaseWindowSizeBy(diff); } protected override T GetItemForEnumerator(int i) => this[i]; public override int Count => _size; protected override T IndexerInnerGet(int index) => index < 0 || index >= Count ? throw new IndexOutOfRangeException() : _dataVirtualizingCollection[Offset + index]; public override void Reset() => _dataVirtualizingCollection.Reset(); public override Task InitializationCompleted { get; } public override async ValueTask DisposeAsync() { await base.DisposeAsync().ConfigureAwait(false); await _dataVirtualizingCollection.DisposeAsync().ConfigureAwait(false); } } } <|start_filename|>Sample.View/AutofacModule.cs<|end_filename|> using System.Reactive.Disposables; using System.Reflection; using Autofac; using BFF.DataVirtualizingCollection.Sample.View.ViewModelInterfaceImplementations; using BFF.DataVirtualizingCollection.Sample.View.Views; using Module = Autofac.Module; namespace BFF.DataVirtualizingCollection.Sample.View { public class AutofacModule : Module { public static MainWindowView Start() { var builder = new ContainerBuilder(); builder.RegisterModule(new AutofacModule()); return builder .Build() .BeginLifetimeScope() .Resolve<MainWindowView>(); } private AutofacModule() {} protected override void Load(ContainerBuilder builder) { var assemblies = new[] { Assembly.GetExecutingAssembly() }; builder.RegisterAssemblyTypes(assemblies) .AsImplementedInterfaces() .AsSelf(); builder.RegisterType<GetSchedulers>() .AsImplementedInterfaces() .AsSelf() .SingleInstance(); builder.RegisterType<CompositeDisposable>() .AsSelf() .UsingConstructor(() => new CompositeDisposable()) .InstancePerLifetimeScope(); builder.RegisterModule(new BFF.DataVirtualizingCollection.Sample.ViewModel.AutofacModule()); builder.RegisterModule(new BFF.DataVirtualizingCollection.Sample.Persistence.Proxy.AutofacModule()); } } } <|start_filename|>Sample.View/Views/Decisions/PageLoadingBehaviorView.xaml.cs<|end_filename|> using System.Windows; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions; namespace BFF.DataVirtualizingCollection.Sample.View.Views.Decisions { public partial class PageLoadingBehaviorView { public PageLoadingBehaviorView() { InitializeComponent(); } private void Preloading_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel) pageLoadingBehaviorViewModel.PageLoadingBehavior = PageLoadingBehavior.Preloading; } private void NonPreloading_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel) pageLoadingBehaviorViewModel.PageLoadingBehavior = PageLoadingBehavior.NonPreloading; } } } <|start_filename|>Tests.Integration/SlidingWindowDataAccess/SyncDataAccessTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Reactive.Testing; using MoreLinq.Extensions; using Xunit; namespace BFF.DataVirtualizingCollection.Tests.Integration.SlidingWindowDataAccess { public class SyncDataAccessTests { // ReSharper disable once MemberCanBePrivate.Global public static IEnumerable<object[]> Combinations => Enum.GetValues(typeof(PageLoadingBehavior)).OfType<PageLoadingBehavior>() .Cartesian( Enum.GetValues(typeof(PageRemovalBehavior)).OfType<PageRemovalBehavior>(), Enum.GetValues(typeof(FetchersKind)).OfType<FetchersKind>().Except(new [] { FetchersKind.TaskBased }), (first, second, third) => new object[] {first, second, third, IndexAccessBehavior.Synchronous}); [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_FirstEntry_0( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 0, scheduler); // Act + Assert Assert.Equal(0, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_70thEntry_69( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 60, scheduler); // Act + Assert Assert.Equal(69, collection[9]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_124thEntry_123( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 120, scheduler); // Act + Assert Assert.Equal(123, collection[3]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_6001thEntry_6000( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 6000, scheduler); // Act + Assert Assert.Equal(6000, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_6969thEntry_6968( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 6959, scheduler); // Act + Assert Assert.Equal(6968, collection[9]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_11thWindowEntry_ThrowsIndexOutOfRangeException( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 6959, scheduler); // Act + Assert Assert.Throws<IndexOutOfRangeException>(() => collection[10]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_MinusFirstEntry_ThrowsIndexOutOfRangeException( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, 10, 6959, scheduler); // Act + Assert Assert.Throws<IndexOutOfRangeException>(() => collection[-1]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWherePageFetcherIgnoresGivenPageSize23_70thEntry_69( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalIntegerWhereFetchersIgnorePageSize( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 23, 10, 60, scheduler); // Act + Assert Assert.Equal(69, collection[9]); } } } <|start_filename|>Tests.Integration/SlidingWindowFactory.cs<|end_filename|> using System; using System.Linq; using System.Reactive.Concurrency; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.SlidingWindow; namespace BFF.DataVirtualizingCollection.Tests.Integration { internal static class SlidingWindowFactory { internal static ISlidingWindow<int> CreateCollectionWithIncrementalInteger( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, int initialWindowSize, int initialWindowOffset, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = SlidingWindowBuilder.Build<int>( initialWindowSize, initialWindowOffset, pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => -1); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, (offset, pSize) => Enumerable .Range(offset, pSize) .ToArray(), () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => -1); return dataVirtualizingCollection; } internal static ISlidingWindow<int> CreateCollectionWithIncrementalIntegerWhereFetchersIgnorePageSize( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, int initialWindowSize, int initialWindowOffset, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = SlidingWindowBuilder.Build<int>( initialWindowSize, initialWindowOffset, pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => -1); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, (offset, pSize) => Enumerable .Range(offset, pageSize) // <--- This is different! pageSize instead of pSize! .ToArray(), () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => -1); return dataVirtualizingCollection; } internal static ISlidingWindow<T> CreateCollectionWithCustomPageFetchingLogic<T>( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, int initialWindowSize, int initialWindowOffset, Func<int, int, T[]> pageFetchingLogic, T placeholder, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = SlidingWindowBuilder.Build<T>( initialWindowSize, initialWindowOffset, pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => placeholder); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, pageFetchingLogic, () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => placeholder); return dataVirtualizingCollection; } internal static ISlidingWindow<T> CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed<T>( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, int count, int pageSize, int initialWindowSize, int initialWindowOffset, Func<int, int, T[]> pageFetchingLogic, T placeholder, int pageLimit, int removalCount, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = SlidingWindowBuilder.Build<T>( initialWindowSize, initialWindowOffset, pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => placeholder); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, pageLimit, removalCount); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, pageFetchingLogic, () => count); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => placeholder); return dataVirtualizingCollection; } internal static ISlidingWindow<int> CreateCollectionWithCustomCountFetcher( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior, Func<int> countFetcher, int pageSize, int initialWindowSize, int initialWindowOffset, IScheduler scheduler) { var pageLoadingBehaviorCollectionBuilder = SlidingWindowBuilder.Build<int>( initialWindowSize, initialWindowOffset, pageSize, new EventLoopScheduler(), scheduler); var pageHoldingBehaviorCollectionBuilder = StandardPageHoldingBehaviorCollectionBuilder( pageLoadingBehaviorCollectionBuilder, pageLoadingBehavior, (_, __) => -1); var fetchersKindCollectionBuilder = StandardFetcherKindCollectionBuilder( pageHoldingBehaviorCollectionBuilder, pageRemovalBehavior, 10, 1); var indexAccessBehaviorCollectionBuilder = StandardIndexAccessBehaviorCollectionBuilder( fetchersKindCollectionBuilder, fetchersKind, (offset, pSize) => Enumerable .Range(offset, pSize) .ToArray(), countFetcher); var dataVirtualizingCollection = StandardDataVirtualizingCollection( indexAccessBehaviorCollectionBuilder, indexAccessBehavior, () => -1); return dataVirtualizingCollection; } private static IPageHoldingBehaviorCollectionBuilder<T, ISlidingWindow<T>> StandardPageHoldingBehaviorCollectionBuilder<T>( IPageLoadingBehaviorCollectionBuilder<T, ISlidingWindow<T>> pageLoadingBehaviorCollectionBuilder, PageLoadingBehavior pageLoadingBehavior, Func<int, int, T> preloadingPlaceholderFactory) => pageLoadingBehavior switch { PageLoadingBehavior.NonPreloading => pageLoadingBehaviorCollectionBuilder.NonPreloading(), PageLoadingBehavior.Preloading => pageLoadingBehaviorCollectionBuilder.Preloading(preloadingPlaceholderFactory), _ => throw new Exception("Test configuration failed!") }; private static IFetchersKindCollectionBuilder<T, ISlidingWindow<T>> StandardFetcherKindCollectionBuilder<T>(IPageHoldingBehaviorCollectionBuilder<T, ISlidingWindow<T>> pageHoldingBehaviorCollectionBuilder, PageRemovalBehavior pageRemovalBehavior, int pageLimit, int removalCount) => pageRemovalBehavior switch { PageRemovalBehavior.Hoarding => pageHoldingBehaviorCollectionBuilder.Hoarding(), PageRemovalBehavior.LeastRecentlyUsed => pageHoldingBehaviorCollectionBuilder.LeastRecentlyUsed(pageLimit, removalCount), _ => throw new Exception("Test configuration failed!") }; private static IAsyncOnlyIndexAccessBehaviorCollectionBuilder<T, ISlidingWindow<T>> StandardIndexAccessBehaviorCollectionBuilder<T>(IFetchersKindCollectionBuilder<T, ISlidingWindow<T>> fetchersKindCollectionBuilder, FetchersKind fetchersKind, Func<int, int, T[]> pageFetcher, Func<int> countFetcher) => fetchersKind switch { FetchersKind.NonTaskBased => fetchersKindCollectionBuilder.NonTaskBasedFetchers( (offset, pSize, _) => { Thread.Sleep(25); return pageFetcher(offset, pSize); }, _ => { Thread.Sleep(25); return countFetcher(); }), FetchersKind.TaskBased => fetchersKindCollectionBuilder.TaskBasedFetchers( async (offset, pSize, _) => { await Task.Delay(TimeSpan.FromTicks(1)).ConfigureAwait(false); return pageFetcher(offset, pSize); }, async _ => { await Task.Delay(TimeSpan.FromTicks(1)).ConfigureAwait(false); return countFetcher(); }), _ => throw new Exception("Test configuration failed!") }; private static ISlidingWindow<T> StandardDataVirtualizingCollection<T>(IAsyncOnlyIndexAccessBehaviorCollectionBuilder<T, ISlidingWindow<T>> indexAccessBehaviorCollectionBuilder, IndexAccessBehavior indexAccessBehavior, Func<T> placeholderFactory) => indexAccessBehavior switch { IndexAccessBehavior.Synchronous => (indexAccessBehaviorCollectionBuilder as IIndexAccessBehaviorCollectionBuilder<T, ISlidingWindow<T>>) ?.SyncIndexAccess() ?? throw new Exception("Task-based fetchers and synchronous access is not allowed."), IndexAccessBehavior.Asynchronous => indexAccessBehaviorCollectionBuilder.AsyncIndexAccess( (_, __) => placeholderFactory()), _ => throw new Exception("Test configuration failed!") }; } } <|start_filename|>Tests.Unit/PageStorage/PreloadingPageStorageTests.cs<|end_filename|> using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using NSubstitute; using NSubstitute.Extensions; using NSubstitute.ReceivedExtensions; using Xunit; // ReSharper disable UnusedVariable *** Necessary for some tests // ReSharper disable AccessToDisposedClosure *** Controlled disposal namespace BFF.DataVirtualizingCollection.Test.PageStorage { public class PreloadingPageStorageTests { [Fact] public async Task Index_RequestSeventhPage_SeventhSixthAndEighthPageRequested() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); using var requests = new ReplaySubject<(int PageKey, int PageIndex)>(); await using var sut = new PreloadingPageStorage<int>( 10, 10000, (_, __, ___, ____) => page, (_, __, ___, ____) => page, req => { req.Subscribe(requests); return Observable.Never<IReadOnlyList<int>>(); }); // Act var unused = sut[69]; requests.OnCompleted(); // Assert Assert.Collection( requests.ToEnumerable(), tuple => { var (pageKey, pageIndex) = tuple; Assert.Equal(6, pageKey); Assert.Equal(9, pageIndex); }, tuple => { var (pageKey, pageIndex) = tuple; Assert.Equal(7, pageKey); Assert.Equal(-1, pageIndex); }, tuple => { var (pageKey, pageIndex) = tuple; Assert.Equal(5, pageKey); Assert.Equal(-1, pageIndex); }); } [Fact] public async Task Dispose_ThreePagesRequested_SevenPagesDisposed() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var sut = new PreloadingPageStorage<int>( 10, 10000, (_, __, ___, ____) => page, (_, __, ___, ____) => page, _ => Observable.Never<IReadOnlyList<int>>()); // Act var i = sut[69]; var i1 = sut[23]; var i2 = sut[3]; await sut.DisposeAsync().ConfigureAwait(false); // Assert await page.Received(Quantity.Exactly(7)).DisposeAsync(); } [Fact] public async Task PageRemoval_RemoveAllExceptFirstRequestedPage_SixPagesDisposed() { // Arrange var page = Substitute.For<IPage<int>>(); page.ReturnsForAll(69); var subject = new Subject<IReadOnlyList<int>>(); await using var sut = new PreloadingPageStorage<int>( 10, 10000, (_, __, ___, ____) => page, (_, __, ___, ____) => page, _ => subject); // Act var i = sut[69]; var i1 = sut[23]; var i2 = sut[3]; subject.OnNext(new[] { 0, 1, 2, 3, 5, 7 }); // Assert await page.Received(Quantity.Exactly(6)).DisposeAsync(); } } } <|start_filename|>Sample.ViewModel/Utility/TransformingBackendAccess.cs<|end_filename|> using System; using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.Utility { internal class TransformingBackendAccess<TModel, TViewModel> : IBackendAccess<TViewModel> { internal static IBackendAccess<TViewModel> CreateTransformingBackendAccess( IBackendAccess<TModel> modelBackendAccess, Func<TModel[], TViewModel[]> transformingPageFactory, Func<TModel, TViewModel> transformingPlaceholderFactory) { return new TransformingBackendAccess<TModel, TViewModel>( modelBackendAccess, transformingPageFactory, transformingPlaceholderFactory); } private readonly IBackendAccess<TModel> _modelBackendAccess; private readonly Func<TModel[], TViewModel[]> _transformingPageFactory; private readonly Func<TModel, TViewModel> _transformingPlaceholderFactory; private TransformingBackendAccess( IBackendAccess<TModel> modelBackendAccess, Func<TModel[], TViewModel[]> transformingPageFactory, Func<TModel, TViewModel> transformingPlaceholderFactory) { _modelBackendAccess = modelBackendAccess; _transformingPageFactory = transformingPageFactory; _transformingPlaceholderFactory = transformingPlaceholderFactory; } public string Name => _modelBackendAccess.Name; public TViewModel[] PageFetch(int pageOffset, int pageSize) { return _transformingPageFactory(_modelBackendAccess.PageFetch(pageOffset, pageSize)); } public TViewModel PlaceholderFetch(int pageOffset, int indexInsidePage) { return _transformingPlaceholderFactory(_modelBackendAccess.PlaceholderFetch(pageOffset, indexInsidePage)); } public TViewModel PreloadingPlaceholderFetch(int pageOffset, int indexInsidePage) { return _transformingPlaceholderFactory(_modelBackendAccess.PreloadingPlaceholderFetch(pageOffset, indexInsidePage)); } public int CountFetch() { return _modelBackendAccess.CountFetch(); } } } <|start_filename|>BFF.DataVirtualizingCollection/PageRemoval/HoardingPageNonRemoval.cs<|end_filename|> using System; using System.Collections.Generic; using System.Reactive.Linq; namespace BFF.DataVirtualizingCollection.PageRemoval { internal static class HoardingPageNonRemoval { internal static Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> Create() => _ => Observable.Never<IReadOnlyList<int>>(); } } <|start_filename|>Sample.Model/AutofacModule.cs<|end_filename|> using System.Reflection; using Autofac; using Module = Autofac.Module; namespace BFF.DataVirtualizingCollection.Sample.Model { public class AutofacModule : Module { protected override void Load(ContainerBuilder builder) { var assemblies = new[] { Assembly.GetExecutingAssembly() }; builder.RegisterAssemblyTypes(assemblies) .AsImplementedInterfaces() .AsSelf(); } } } <|start_filename|>BFF.DataVirtualizingCollection/Utilities/DateTimeTimestampProvider.cs<|end_filename|> using System; namespace BFF.DataVirtualizingCollection.Utilities { internal class DateTimeTimestampProvider : ITimestampProvider { public DateTime Now => DateTime.Now; } } <|start_filename|>Tests.Unit/PageRemoval/LeastRecentlyUsedPageRemovalTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Reactive.Subjects; using BFF.DataVirtualizingCollection.PageRemoval; using BFF.DataVirtualizingCollection.Utilities; using NSubstitute; using Xunit; // ReSharper disable UnusedVariable *** Necessary for some tests namespace BFF.DataVirtualizingCollection.Test.PageRemoval { public class LeastRecentlyUsedPageRemovalTests { [Theory] [InlineData(true)] [InlineData(false)] public void CreatePageLimit10RemovalCount1_Request10Pages_NeverRequestsRemoval(bool isPreloading) { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 10, 1, isPreloading, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 0; i < 10; i++) { pageRequests.OnNext((i, 0)); } // Assert Assert.Empty(requestedRemovals); } [Theory] [InlineData(true)] [InlineData(false)] public void CreatePageLimit10RemovalCount1_Request10PagesAndIterateThemAgain_NeverRequestsRemoval(bool isPreloading) { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 10, 1, isPreloading, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 0; i < 10; i++) { pageRequests.OnNext((i, 0)); } for (var i = 9; i >= 0; i--) { pageRequests.OnNext((i, 0)); } // Assert Assert.Empty(requestedRemovals); } [Theory] [InlineData(true)] [InlineData(false)] public void CreatePageLimit10RemovalCount1_Request11Pages_FirstPageRemovalRequest(bool isPreloading) { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 10, 1, isPreloading, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 0; i < 11; i++) { pageRequests.OnNext((i, 0)); } // Assert Assert.Collection( requestedRemovals, pageKey => Assert.Equal(0, pageKey)); } [Theory] [InlineData(true)] [InlineData(false)] public void CreatePageLimit10RemovalCount1_Request11PagesInReverse_FirstPageRemovalRequest(bool isPreloading) { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 10, 1, isPreloading, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 10; i >= 0; i--) { pageRequests.OnNext((i, 0)); } // Assert Assert.Collection( requestedRemovals, pageKey => Assert.Equal(10, pageKey)); } [Theory] [InlineData(true)] [InlineData(false)] public void CreatePageLimit10RemovalCount3_Request11Pages_FirstThreePagesRemovalRequest(bool isPreloading) { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 10, 3, isPreloading, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 0; i < 11; i++) { pageRequests.OnNext((i, 0)); } // Assert Assert.Collection( requestedRemovals, pageKey => Assert.Equal(0, pageKey), pageKey => Assert.Equal(1, pageKey), pageKey => Assert.Equal(2, pageKey)); } [Theory] [InlineData(true)] [InlineData(false)] public void CreatePageLimit10RemovalCount3_Request11PagesInReverse_FirstThreePagesRemovalRequest(bool isPreloading) { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 10, 3, isPreloading, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 10; i >= 0; i--) { pageRequests.OnNext((i, 0)); } // Assert Assert.Collection( requestedRemovals, pageKey => Assert.Equal(10, pageKey), pageKey => Assert.Equal(9, pageKey), pageKey => Assert.Equal(8, pageKey)); } [Fact] public void CreatePageLimit1RemovalCount1Preloading_Request5Pages_FirstPageRemovalRequest() { // Arrange var timestampCount = 0; var timestampProvider = Substitute.For<ITimestampProvider>(); timestampProvider.Now.Returns(_ => DateTime.MinValue + TimeSpan.FromTicks(1) * timestampCount++); var requestedRemovals = new List<int>(); using var pageRequests = new Subject<(int PageKey, int PageIndex)>(); // Act using var subscription = LeastRecentlyUsedPageRemoval .Create( 1, 1, true, timestampProvider) (pageRequests) .Subscribe(removals => requestedRemovals.AddRange(removals)); for (var i = 0; i < 5; i++) { pageRequests.OnNext((i, 0)); } // Assert Assert.Collection( requestedRemovals, pageKey => Assert.Equal(0, pageKey)); } } } <|start_filename|>Sample.Persistence.Proxy/AutofacModule.cs<|end_filename|> using Autofac; using Module = Autofac.Module; namespace BFF.DataVirtualizingCollection.Sample.Persistence.Proxy { public class AutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterModule(new BFF.DataVirtualizingCollection.Sample.Persistence.AutofacModule()); } } } <|start_filename|>BFF.DataVirtualizingCollection/SlidingWindow/ISlidingWindow.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.SlidingWindow { // ReSharper disable once PossibleInterfaceMemberAmbiguity // Ambiguous Members should be implemented explicitly /// <summary> /// Defines a nongeneric window to the backend (accessed by the page- and count-fetchers). /// A window is intended to be a much smaller section of the backend. It is specified by an offset and a size. /// Outwards it looks like a small list which contains only a few items of the whole backend. However, the sliding functionality /// makes it possible to go through the whole backend. /// </summary> public interface ISlidingWindow : IVirtualizationBase { /// <summary> /// Current offset of the window inside of the range of the items from the backend. The Offset marks the first item of the backend which is represented in the sliding window. /// </summary> int Offset { get; } /// <summary> /// Current maximum possible offset. Depends on the count of all backend items and the size of the window. /// </summary> int MaximumOffset { get; } /// <summary> /// Slides the window (<see cref="Offset"/>) to the backend one step to the start (left). /// </summary> void SlideLeft(); /// <summary> /// Slides the window (<see cref="Offset"/>) to the backend one step to the end (right). /// </summary> void SlideRight(); /// <summary> /// Sets the first entry of the window (<see cref="Offset"/>) to the given index of the backend. /// </summary> void JumpTo(int index); /// <summary> /// Increases windows size by one. /// </summary> void IncreaseWindowSize(); /// <summary> /// Decreases windows size by one. /// </summary> void DecreaseWindowSize(); /// <summary> /// Increases windows size by given increment. /// </summary> void IncreaseWindowSizeBy(int sizeIncrement); /// <summary> /// Decreases windows size by given increment. /// </summary> void DecreaseWindowSizeBy(int sizeIncrement); /// <summary> /// Sets windows size to given size. /// </summary> void SetWindowSizeTo(int size); } // ReSharper disable once PossibleInterfaceMemberAmbiguity // Ambiguous Members should be implemented explicitly /// <summary> /// Defines a generic window to the backend (accessed by the page- and count-fetchers). /// A window is intended to be a much smaller section of the backend. It is specified by an offset and a size. /// Outwards it looks like a small list which contains only a few items of the whole backend. However, the sliding functionality /// makes it possible to go through the whole backend. /// </summary> /// <typeparam name="T">Item type.</typeparam> public interface ISlidingWindow<T> : IVirtualizationBase<T>, ISlidingWindow { } } <|start_filename|>BFF.DataVirtualizingCollection/DataVirtualizingCollectionBuilderBase.cs<|end_filename|> using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageRemoval; using BFF.DataVirtualizingCollection.PageStorage; using BFF.DataVirtualizingCollection.Utilities; namespace BFF.DataVirtualizingCollection { internal enum PageLoadingBehavior { Preloading, NonPreloading } internal enum FetchersKind { NonTaskBased, TaskBased, AsyncEnumerableBased } internal enum IndexAccessBehavior { Asynchronous, Synchronous } internal static class DataVirtualizingCollectionBuilderBase { internal const int DefaultPageSize = 100; } internal abstract class DataVirtualizingCollectionBuilderBase<TItem, TVirtualizationKind> : IPageLoadingBehaviorCollectionBuilder<TItem, TVirtualizationKind>, IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind>, IFetchersKindCollectionBuilder<TItem, TVirtualizationKind>, IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> { protected const string UninitializedElementsExceptionMessage = "The builder used an uninitialized element. This should be impossible. Please open an issue on https://github.com/Yeah69/BFF.DataVirtualizingCollection."; protected readonly IScheduler NotificationScheduler; private readonly int _pageSize; private FetchersKind _fetchersKind = FetchersKind.NonTaskBased; private IndexAccessBehavior _indexAccessBehavior = IndexAccessBehavior.Synchronous; private Func<int, int, CancellationToken, TItem[]>? _pageFetcher; private Func<int, int, TItem>? _placeholderFactory; private Func<int, int, TItem>? _preloadingPlaceholderFactory; private IScheduler _preloadingBackgroundScheduler; private IScheduler _pageBackgroundScheduler; protected IScheduler CountBackgroundScheduler; private Func<int, int, CancellationToken, Task<TItem[]>>? _taskBasedPageFetcher; private Func<int, int, CancellationToken, IAsyncEnumerable<TItem>>? _asyncEnumerableBasedPageFetcher; protected Func<CancellationToken, int>? CountFetcher; private IAsyncPageFetchScheduler? _asyncPageFetchScheduler; private Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> _pageHoldingBehavior = HoardingPageNonRemoval.Create(); private PageLoadingBehavior _pageLoadingBehavior = PageLoadingBehavior.NonPreloading; protected Func<CancellationToken, Task<int>>? TaskBasedCountFetcher; protected DataVirtualizingCollectionBuilderBase( int pageSize, IScheduler notificationScheduler) : this( pageSize, notificationScheduler, TaskPoolScheduler.Default) { } protected DataVirtualizingCollectionBuilderBase( int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) { _pageSize = pageSize; NotificationScheduler = notificationScheduler; _preloadingBackgroundScheduler = backgroundScheduler; _pageBackgroundScheduler = backgroundScheduler; CountBackgroundScheduler = backgroundScheduler; } public IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonTaskBasedFetchers( Func<int, int, TItem[]> pageFetcher, Func<int> countFetcher) { _fetchersKind = FetchersKind.NonTaskBased; _pageFetcher = (offset, size, _) => pageFetcher(offset, size); CountFetcher = _ => countFetcher(); return this; } public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> TaskBasedFetchers( Func<int, int, Task<TItem[]>> pageFetcher, Func<Task<int>> countFetcher) { _fetchersKind = FetchersKind.TaskBased; _taskBasedPageFetcher = (offset, size, _) => pageFetcher(offset, size); TaskBasedCountFetcher = _ => countFetcher(); return this; } public IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonTaskBasedFetchers(Func<int, int, CancellationToken, TItem[]> pageFetcher, Func<CancellationToken, int> countFetcher) { _fetchersKind = FetchersKind.NonTaskBased; _pageFetcher = pageFetcher; CountFetcher = countFetcher; return this; } public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> TaskBasedFetchers(Func<int, int, CancellationToken, Task<TItem[]>> pageFetcher, Func<CancellationToken, Task<int>> countFetcher) { _fetchersKind = FetchersKind.TaskBased; _taskBasedPageFetcher = pageFetcher; TaskBasedCountFetcher = countFetcher; return this; } public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> AsyncEnumerableBasedFetchers(Func<int, int, CancellationToken, IAsyncEnumerable<TItem>> pageFetcher, Func<CancellationToken, Task<int>> countFetcher) { _fetchersKind = FetchersKind.AsyncEnumerableBased; _asyncEnumerableBasedPageFetcher = pageFetcher; TaskBasedCountFetcher = countFetcher; return this; } public TVirtualizationKind SyncIndexAccess() { _indexAccessBehavior = IndexAccessBehavior.Synchronous; return GenerateCollection(); } public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ImmediatePageRequests() { _asyncPageFetchScheduler = new ImmediateAsyncPageFetchScheduler(); return this; } public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests() => ThrottledLifoPageRequests(_pageBackgroundScheduler); public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests( TimeSpan throttleDueTime) => ThrottledLifoPageRequests(throttleDueTime, _pageBackgroundScheduler); public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests( IScheduler pageRequestBackgroundScheduler) => ThrottledLifoPageRequests(TimeSpan.FromMilliseconds(200), pageRequestBackgroundScheduler); public IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests( TimeSpan throttleDueTime, IScheduler pageRequestBackgroundScheduler) { _asyncPageFetchScheduler = new LifoAsyncPageFetchScheduler(throttleDueTime, pageRequestBackgroundScheduler); return this; } public TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory) { _indexAccessBehavior = IndexAccessBehavior.Asynchronous; _placeholderFactory = placeholderFactory; return GenerateCollection(); } public TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory, IScheduler pageBackgroundScheduler) { _pageBackgroundScheduler = pageBackgroundScheduler; return AsyncIndexAccess(placeholderFactory); } public TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory, IScheduler pageBackgroundScheduler, IScheduler countBackgroundScheduler) { _pageBackgroundScheduler = pageBackgroundScheduler; CountBackgroundScheduler = countBackgroundScheduler; return AsyncIndexAccess(placeholderFactory); } public IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> Hoarding() { return CustomPageRemovalStrategy(HoardingPageNonRemoval.Create()); } public IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> LeastRecentlyUsed( int pageLimit) { return LeastRecentlyUsed(pageLimit, 1); } public IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> LeastRecentlyUsed( int pageLimit, int removalCount) { return CustomPageRemovalStrategy(LeastRecentlyUsedPageRemoval.Create( pageLimit, removalCount, _pageLoadingBehavior == PageLoadingBehavior.Preloading, new DateTimeTimestampProvider())); } public IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> CustomPageRemovalStrategy( Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> pageReplacementStrategyFactory) { _pageHoldingBehavior = pageReplacementStrategyFactory; return this; } public IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonPreloading() { _pageLoadingBehavior = PageLoadingBehavior.NonPreloading; return this; } public IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> Preloading( Func<int, int, TItem> preloadingPlaceholderFactory) { _pageLoadingBehavior = PageLoadingBehavior.Preloading; _preloadingPlaceholderFactory = preloadingPlaceholderFactory; return this; } public IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> Preloading( Func<int, int, TItem> preloadingPlaceholderFactory, IScheduler preloadingBackgroundScheduler) { _preloadingBackgroundScheduler = preloadingBackgroundScheduler; return Preloading(preloadingPlaceholderFactory); } private TVirtualizationKind GenerateCollection() { var pageFetchEvents = new Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)>(); return (_indexAccessBehavior, _fetchersKind) switch { (IndexAccessBehavior.Synchronous, FetchersKind.NonTaskBased) => GenerateNonTaskBasedSynchronousCollection(pageFetchEvents), (IndexAccessBehavior.Asynchronous, FetchersKind.NonTaskBased) => GenerateNonTaskBasedAsynchronousCollection(pageFetchEvents), (IndexAccessBehavior.Asynchronous, FetchersKind.TaskBased) => GenerateTaskBasedAsynchronousCollection(pageFetchEvents), (IndexAccessBehavior.Asynchronous, FetchersKind.AsyncEnumerableBased) => GenerateAsyncEnumerableBasedAsynchronousCollection(pageFetchEvents), _ => throw new ArgumentException("Can't build data-virtualizing collection with given input.") }; } private IPageStorage<TItem> PageStoreFactory( int count, Func<int, int, int, IDisposable, IPage<TItem>> nonPreloadingPageFetcherFactory, Func<int, int, int, IDisposable, IPage<TItem>> preloadingPageFetcherFactory) { return _pageLoadingBehavior == PageLoadingBehavior.Preloading ? new PreloadingPageStorage<TItem>( _pageSize, count, nonPreloadingPageFetcherFactory, preloadingPageFetcherFactory, _pageHoldingBehavior) : new PageStorage<TItem>( _pageSize, count, nonPreloadingPageFetcherFactory, _pageHoldingBehavior); } internal Func<int, IPageStorage<TItem>> GenerateTaskBasedAsynchronousPageStorage( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { return PageStoreFactoryComposition; IPage<TItem> NonPreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var taskBasedPageFetcher = _taskBasedPageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var placeholderFactory = _placeholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var asyncPageFetchScheduler = _asyncPageFetchScheduler ?? new ImmediateAsyncPageFetchScheduler(); return new AsyncTaskBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, taskBasedPageFetcher, placeholderFactory, asyncPageFetchScheduler, _pageBackgroundScheduler, pageFetchEvents.AsObserver()); } IPage<TItem> PreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var taskBasedPageFetcher = _taskBasedPageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var preloadingPlaceholderFactory = _preloadingPlaceholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var asyncPageFetchScheduler = _asyncPageFetchScheduler ?? new ImmediateAsyncPageFetchScheduler(); return new AsyncTaskBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, taskBasedPageFetcher, preloadingPlaceholderFactory, asyncPageFetchScheduler, _preloadingBackgroundScheduler, pageFetchEvents.AsObserver()); } IPageStorage<TItem> PageStoreFactoryComposition(int count) { return PageStoreFactory(count, NonPreloadingPageFetcherFactory, PreloadingPageFetcherFactory); } } internal Func<int, IPageStorage<TItem>> GenerateAsyncEnumerableBasedAsynchronousPageStorage( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { return PageStoreFactoryComposition; IPage<TItem> NonPreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var asyncEnumerableBasedPageFetcher = _asyncEnumerableBasedPageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var placeholderFactory = _placeholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var asyncPageFetchScheduler = _asyncPageFetchScheduler ?? new ImmediateAsyncPageFetchScheduler(); return new AsyncEnumerableBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, asyncEnumerableBasedPageFetcher, placeholderFactory, asyncPageFetchScheduler, _pageBackgroundScheduler, pageFetchEvents.AsObserver()); } IPage<TItem> PreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var asyncEnumerableBasedPageFetcher = _asyncEnumerableBasedPageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var preloadingPlaceholderFactory = _preloadingPlaceholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var asyncPageFetchScheduler = _asyncPageFetchScheduler ?? new ImmediateAsyncPageFetchScheduler(); return new AsyncEnumerableBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, asyncEnumerableBasedPageFetcher, preloadingPlaceholderFactory, asyncPageFetchScheduler, _preloadingBackgroundScheduler, pageFetchEvents.AsObserver()); } IPageStorage<TItem> PageStoreFactoryComposition(int count) { return PageStoreFactory(count, NonPreloadingPageFetcherFactory, PreloadingPageFetcherFactory); } } internal Func<int, IPageStorage<TItem>> GenerateNonTaskBasedAsynchronousPageStorage( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { return PageStoreFactoryComposition; IPage<TItem> NonPreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var pageFetcher = _pageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var placeholderFactory = _placeholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var asyncPageFetchScheduler = _asyncPageFetchScheduler ?? new ImmediateAsyncPageFetchScheduler(); return new AsyncNonTaskBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, pageFetcher, placeholderFactory, asyncPageFetchScheduler, _pageBackgroundScheduler, pageFetchEvents.AsObserver()); } IPage<TItem> PreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var pageFetcher = _pageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var preloadingPlaceholderFactory = _preloadingPlaceholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var asyncPageFetchScheduler = _asyncPageFetchScheduler ?? new ImmediateAsyncPageFetchScheduler(); return new AsyncNonTaskBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, pageFetcher, preloadingPlaceholderFactory, asyncPageFetchScheduler, _preloadingBackgroundScheduler, pageFetchEvents.AsObserver()); } IPageStorage<TItem> PageStoreFactoryComposition(int count) { return PageStoreFactory(count, NonPreloadingPageFetcherFactory, PreloadingPageFetcherFactory); } } internal Func<int, IPageStorage<TItem>> GenerateNonTaskBasedSynchronousPageStorage( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents) { var immediateAsyncPageFetchScheduler = new ImmediateAsyncPageFetchScheduler(); return PageStoreFactoryComposition; IPage<TItem> NonPreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var pageFetcher = _pageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); return new SyncNonPreloadingNonTaskBasedPage<TItem>( offset, pageSize, onDisposalAfterFetchCompleted, pageFetcher); } IPage<TItem> PreloadingPageFetcherFactory( int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted) { var pageFetcher = _pageFetcher ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); var preloadingPlaceholderFactory = _preloadingPlaceholderFactory ?? throw new NullReferenceException(UninitializedElementsExceptionMessage); return new AsyncNonTaskBasedPage<TItem>( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, pageFetcher, preloadingPlaceholderFactory, immediateAsyncPageFetchScheduler, _preloadingBackgroundScheduler, pageFetchEvents.AsObserver()); } IPageStorage<TItem> PageStoreFactoryComposition(int count) { return PageStoreFactory(count, NonPreloadingPageFetcherFactory, PreloadingPageFetcherFactory); } } protected abstract TVirtualizationKind GenerateTaskBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents); protected abstract TVirtualizationKind GenerateAsyncEnumerableBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents); protected abstract TVirtualizationKind GenerateNonTaskBasedAsynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents); protected abstract TVirtualizationKind GenerateNonTaskBasedSynchronousCollection( Subject<(int Offset, int PageSize, TItem[] PreviousPage, TItem[] Page)> pageFetchEvents); } } <|start_filename|>Sample.ViewModel/ViewModels/ObservableObject.cs<|end_filename|> using System.ComponentModel; using System.Runtime.CompilerServices; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels { public interface IObservableObject : INotifyPropertyChanged {} public abstract class ObservableObject : IObservableObject { public event PropertyChangedEventHandler? PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <|start_filename|>Tests.Integration/PageRemoval/AsyncLeastRecentlyUsedTests.cs<|end_filename|> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Threading.Tasks; using Microsoft.Reactive.Testing; using MoreLinq.Extensions; using Xunit; namespace BFF.DataVirtualizingCollection.Tests.Integration.PageRemoval { public class AsyncLeastRecentlyUsedTests { // ReSharper disable once MemberCanBePrivate.Global public static IEnumerable<object[]> Combinations => Enum.GetValues(typeof(PageLoadingBehavior)).OfType<PageLoadingBehavior>() .Cartesian( Enum.GetValues(typeof(FetchersKind)).OfType<FetchersKind>(), (first, second) => new object[] {first, PageRemovalBehavior.LeastRecentlyUsed, second, IndexAccessBehavior.Asynchronous}); // ReSharper disable once MemberCanBePrivate.Global public static IEnumerable<object[]> CombinationsWherePreloading => Combinations.Where(objects => objects[0] is PageLoadingBehavior pageLoadingBehavior && pageLoadingBehavior == PageLoadingBehavior.Preloading); // ReSharper disable once MemberCanBePrivate.Global public static IEnumerable<object[]> CombinationsWhereNonPreloading => Combinations.Where(objects => objects[0] is PageLoadingBehavior pageLoadingBehavior && pageLoadingBehavior == PageLoadingBehavior.NonPreloading); [Theory] [MemberData(nameof(CombinationsWhereNonPreloading))] public async Task With6969ElementsPageSize100_NotMoreThanPageLimit_NoRemovals( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 900; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Empty(set); } [Theory] [MemberData(nameof(CombinationsWherePreloading))] public async Task With6969ElementsPageSize100Preloading_NotMoreThanPageLimit_NoRemovals( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 800; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Empty(set); } [Theory] [MemberData(nameof(CombinationsWhereNonPreloading))] public async Task With6969ElementsPageSize100_NotMoreThanPageLimitAndIterateSameElementsAgain_NoRemovals( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 900; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } for (var i = 0; i <= 900; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Empty(set); } [Theory] [MemberData(nameof(CombinationsWherePreloading))] public async Task With6969ElementsPageSize100Preloading_NotMoreThanPageLimitAndIterateSameElementsAgain_NoRemovals( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 800; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } for (var i = 0; i <= 800; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Empty(set); } [Theory] [MemberData(nameof(CombinationsWhereNonPreloading))] public async Task With6969ElementsPageSize100_OneMoreThanPageLimit_FirstPageRemoved( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); int[] expected = Enumerable.Range(0, 100).ToArray(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 1000; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Equal(set.Count, expected.Length); Assert.True(set.All(i => expected.Contains(i))); } [Theory] [MemberData(nameof(CombinationsWherePreloading))] public async Task With6969ElementsPageSize100Preloading_OneMoreThanPageLimit_FirstPageRemoved( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); int[] expected = Enumerable.Range(0, 100).ToArray(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 900; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Equal(set.Count, expected.Length); Assert.True(set.All(i => expected.Contains(i))); } [Theory] [MemberData(nameof(Combinations))] public async Task With6969ElementsPageSize100RemovalCount3_OneMoreThanPageLimit_FirstThreePagesRemoved( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); int[] expected = Enumerable.Range(0, 300).ToArray(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 10, 3, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 1000; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Equal(set.Count, expected.Length); Assert.True(set.All(i => expected.Contains(i))); } [Theory] [MemberData(nameof(CombinationsWherePreloading))] public async Task With6969ElementsPageSize100PageLimit1Preloading_FourPagesLoaded_FirstPageRemoved( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); int[] expected = Enumerable.Range(0, 100).ToArray(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 1, 1, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 300; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Equal(set.Count, expected.Length); Assert.True(set.All(i => expected.Contains(i))); } [Theory] [MemberData(nameof(CombinationsWherePreloading))] public async Task With6969ElementsPageSize100PageLimit4RemovalCount3Preloading_FourPagesLoaded_FirstPageRemoved( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); int[] expected = Enumerable.Range(0, 100).ToArray(); var set = new ConcurrentBag<int>(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithCustomPageFetchingLogicAndCustomLeastRecentlyUsed( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, (offset, pSize) => Enumerable .Range(offset, pSize) .Select(i => Disposable.Create(() => set.Add(i))) .ToArray(), Disposable.Empty, 4, 3, scheduler); scheduler.AdvanceBy(20); Assert.True(collection.InitializationCompleted.IsCompletedSuccessfully); // Act for (var i = 0; i <= 300; i += 100) { var _ = collection[i]; await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); scheduler.AdvanceBy(20); } // Assert Assert.Equal(set.Count, expected.Length); Assert.True(set.All(i => expected.Contains(i))); } } } <|start_filename|>Sample.ViewModel/ViewModels/Decisions/FetcherKindViewModel.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions { public enum FetcherKind { NonTaskBased, TaskBased, AsyncEnumerableBased } public interface IFetcherKindViewModelInternal : IFetcherKindViewModel { IIndexAccessBehaviorViewModel IndexAccessBehaviorViewModel { get; } } public interface IFetcherKindViewModel { FetcherKind FetcherKind { get; set; } public int DelayPageFetcherInMilliseconds { get; set; } public int DelayCountFetcherInMilliseconds { get; set; } IAsyncOnlyIndexAccessBehaviorCollectionBuilder<T, TVirtualizationKind> Configure<T, TVirtualizationKind>( IFetchersKindCollectionBuilder<T, TVirtualizationKind> builder, IBackendAccess<T> backendAccess) { return FetcherKind switch { FetcherKind.NonTaskBased => builder.NonTaskBasedFetchers( (offset, size, _) => { Console.WriteLine($"Client page fetch: {offset}"); Thread.Sleep(DelayPageFetcherInMilliseconds); return backendAccess.PageFetch(offset, size); }, _ => { Thread.Sleep(DelayCountFetcherInMilliseconds); return backendAccess.CountFetch(); }), FetcherKind.TaskBased => builder.TaskBasedFetchers( async (offset, size, ct) => { Console.WriteLine($"Client page fetch: {offset}"); await Task.Delay(DelayPageFetcherInMilliseconds, ct); return backendAccess.PageFetch(offset, size); }, async ct => { await Task.Delay(DelayCountFetcherInMilliseconds, ct); return backendAccess.CountFetch(); }), FetcherKind.AsyncEnumerableBased => builder.AsyncEnumerableBasedFetchers( (offset, size, ct) => { Console.WriteLine($"Client page fetch: {offset}"); var delay = DelayCountFetcherInMilliseconds / size - 1; return Fetch(); async IAsyncEnumerable<T> Fetch() { await foreach (var item in backendAccess.AsyncEnumerablePageFetch(offset, size).WithCancellation(ct).ConfigureAwait(false)) { await Task.Delay(delay, ct); yield return item; } } }, async _ => { await Task.Delay(DelayCountFetcherInMilliseconds); return backendAccess.CountFetch(); }), _ => throw new ArgumentOutOfRangeException() }; } } internal class FetcherKindViewModel : ObservableObject, IFetcherKindViewModelInternal { private readonly IIndexAccessBehaviorViewModelInternal _indexAccessBehaviorViewModelInternal; private FetcherKind _fetcherKind = FetcherKind.TaskBased; private int _delayPageFetcherInMilliseconds = 2000; private int _delayCountFetcherInMilliseconds = 2000; public FetcherKindViewModel( IIndexAccessBehaviorViewModelInternal indexAccessBehaviorViewModelInternal) { _indexAccessBehaviorViewModelInternal = indexAccessBehaviorViewModelInternal; } public FetcherKind FetcherKind { get => _fetcherKind; set { if (_fetcherKind == value) return; _fetcherKind = value; OnPropertyChanged(); _indexAccessBehaviorViewModelInternal.SetIsSyncEnabled(_fetcherKind == FetcherKind.NonTaskBased); } } public int DelayPageFetcherInMilliseconds { get => _delayPageFetcherInMilliseconds; set { if (_delayPageFetcherInMilliseconds == value) return; _delayPageFetcherInMilliseconds = value; OnPropertyChanged(); } } public int DelayCountFetcherInMilliseconds { get => _delayCountFetcherInMilliseconds; set { if (_delayCountFetcherInMilliseconds == value) return; _delayCountFetcherInMilliseconds = value; OnPropertyChanged(); } } public IIndexAccessBehaviorViewModel IndexAccessBehaviorViewModel => _indexAccessBehaviorViewModelInternal; } } <|start_filename|>Sample.ViewModel/ViewModels/DataVirtualizingCollectionViewModel.cs<|end_filename|> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Windows.Input; using BFF.DataVirtualizingCollection.DataVirtualizingCollection; using BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters; using BFF.DataVirtualizingCollection.Sample.ViewModel.Interfaces; using BFF.DataVirtualizingCollection.Sample.ViewModel.Utility; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Functions; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Options; using BFF.DataVirtualizingCollection.SlidingWindow; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels { public interface IDataVirtualizingCollectionViewModelBase { string Name { get; } IGeneralOptionsViewModel GeneralOptionsViewModel { get; } ISpecificOptionsViewModel SpecificOptionsViewModel { get; } IPageLoadingBehaviorViewModel PageLoadingBehaviorViewModel { get; } IPageRemovalBehaviorViewModel PageRemovalBehaviorViewModel { get; } IFetcherKindViewModel FetcherKindViewModel { get; } IIndexAccessBehaviorViewModel IndexAccessBehaviorViewModel { get; } ICommand CreateNew { get; } IGeneralFunctionsViewModel GeneralFunctionsViewModel { get; } ISpecificFunctionsViewModel SpecificFunctionsViewModel { get; } BackendAccessKind BackendAccessKind { get; } IVirtualizationBase? Items { get; } } public abstract class DataVirtualizingCollectionViewModelBaseBase<TViewModel, TVirtualizationKind> : ObservableObject, IDisposable, IDataVirtualizingCollectionViewModelBase where TVirtualizationKind : class, IVirtualizationBase<TViewModel> { private readonly IBackendAccessAdapter<TViewModel> _backendAccessAdapter; private readonly IGetSchedulers _getSchedulers; private IVirtualizationBase? _items; private readonly SerialDisposable _serialItems; private readonly CompositeDisposable _compositeDisposable = new(); protected DataVirtualizingCollectionViewModelBaseBase( // parameters IBackendAccessAdapter<TViewModel> backendAccessAdapter, // dependencies IGeneralOptionsViewModel generalOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, IGetSchedulers getSchedulers) { _backendAccessAdapter = backendAccessAdapter; _getSchedulers = getSchedulers; GeneralOptionsViewModel = generalOptionsViewModel; PageLoadingBehaviorViewModel = pageLoadingBehaviorViewModel; PageRemovalBehaviorViewModel = pageRemovalBehaviorViewModel; FetcherKindViewModel = fetcherKindViewModel; GeneralFunctionsViewModel = generalFunctionsViewModel; IndexAccessBehaviorViewModel = fetcherKindViewModel.IndexAccessBehaviorViewModel; _serialItems = new SerialDisposable(); _compositeDisposable.Add(_serialItems); var createNew = new RxRelayCommand(SetItems); CreateNew = createNew; _compositeDisposable.Add(createNew); } public string Name => _backendAccessAdapter.Name; public BackendAccessKind BackendAccessKind => _backendAccessAdapter.BackendAccessKind; public IVirtualizationBase? Items { get { if (_items is null) SetItems(); return _items; } private set { if (_items == value) return; _items = value; _serialItems.Disposable = _items as IDisposable; OnPropertyChanged(); } } public IGeneralOptionsViewModel GeneralOptionsViewModel { get; } public abstract ISpecificOptionsViewModel SpecificOptionsViewModel { get; } public IPageLoadingBehaviorViewModel PageLoadingBehaviorViewModel { get; } public IPageRemovalBehaviorViewModel PageRemovalBehaviorViewModel { get; } public IFetcherKindViewModel FetcherKindViewModel { get; } public IIndexAccessBehaviorViewModel IndexAccessBehaviorViewModel { get; } public ICommand CreateNew { get; } public IGeneralFunctionsViewModel GeneralFunctionsViewModel { get; } public abstract ISpecificFunctionsViewModel SpecificFunctionsViewModel { get; } protected abstract IPageLoadingBehaviorCollectionBuilder<TViewModel, TVirtualizationKind> CreateInitialBuilder(int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler); private void SetItems() { var builder = CreateInitialBuilder( GeneralOptionsViewModel.PageSize, _getSchedulers.NotificationScheduler, _getSchedulers.BackgroundScheduler); var afterPageLoadingDecision = PageLoadingBehaviorViewModel.Configure(builder, _backendAccessAdapter.BackendAccess); var afterPageRemovalDecision = PageRemovalBehaviorViewModel.Configure(afterPageLoadingDecision); var afterFetcherKindDecision = FetcherKindViewModel.Configure(afterPageRemovalDecision, _backendAccessAdapter.BackendAccess); var collection = IndexAccessBehaviorViewModel.Configure( afterFetcherKindDecision, _backendAccessAdapter.BackendAccess, FetcherKindViewModel.FetcherKind); Items = collection; } public void Dispose() { _compositeDisposable.Dispose(); } } public class DataVirtualizingCollectionViewModel<TViewModel> : DataVirtualizingCollectionViewModelBaseBase<TViewModel, IDataVirtualizingCollection<TViewModel>> { public DataVirtualizingCollectionViewModel( // parameters IBackendAccessAdapter<TViewModel> backendAccessAdapter, // dependencies IGeneralOptionsViewModel generalOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, IGetSchedulers getSchedulers) : base( backendAccessAdapter, generalOptionsViewModel, pageLoadingBehaviorViewModel, pageRemovalBehaviorViewModel, fetcherKindViewModel, generalFunctionsViewModel, getSchedulers) { } public override ISpecificOptionsViewModel SpecificOptionsViewModel => ViewModels.Options.SpecificOptionsViewModel.Empty; public override ISpecificFunctionsViewModel SpecificFunctionsViewModel => ViewModels.Functions.SpecificFunctionsViewModel.Empty; protected override IPageLoadingBehaviorCollectionBuilder<TViewModel, IDataVirtualizingCollection<TViewModel>> CreateInitialBuilder( int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) { return DataVirtualizingCollectionBuilder.Build<TViewModel>( pageSize, notificationScheduler, backgroundScheduler); } } public class SlidingWindowViewModel<TViewModel> : DataVirtualizingCollectionViewModelBaseBase<TViewModel, ISlidingWindow<TViewModel>> { private readonly ISlidingWindowOptionsViewModel _slidingWindowOptionsViewModel; public SlidingWindowViewModel( // parameters IBackendAccessAdapter<TViewModel> backendAccessAdapter, // dependencies IGeneralOptionsViewModel generalOptionsViewModel, ISlidingWindowOptionsViewModel slidingWindowOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, ISlidingWindowFunctionsViewModel slidingWindowFunctionsViewModel, IGetSchedulers getSchedulers) : base( backendAccessAdapter, generalOptionsViewModel, pageLoadingBehaviorViewModel, pageRemovalBehaviorViewModel, fetcherKindViewModel, generalFunctionsViewModel, getSchedulers) { _slidingWindowOptionsViewModel = slidingWindowOptionsViewModel; SpecificFunctionsViewModel = slidingWindowFunctionsViewModel; } public override ISpecificOptionsViewModel SpecificOptionsViewModel => _slidingWindowOptionsViewModel; public override ISpecificFunctionsViewModel SpecificFunctionsViewModel { get; } protected override IPageLoadingBehaviorCollectionBuilder<TViewModel, ISlidingWindow<TViewModel>> CreateInitialBuilder( int pageSize, IScheduler notificationScheduler, IScheduler backgroundScheduler) { return SlidingWindowBuilder.Build<TViewModel>( _slidingWindowOptionsViewModel.WindowSize, _slidingWindowOptionsViewModel.WindowOffset, pageSize, notificationScheduler, backgroundScheduler); } } internal interface IDataVirtualizingCollectionViewModelFactory { IDataVirtualizingCollectionViewModelBase CreateDataVirtualizingCollection<T>( IBackendAccessAdapter<T> backendAccessAdapter); IDataVirtualizingCollectionViewModelBase CreateSlidingWindow<T>( IBackendAccessAdapter<T> backendAccessAdapter); } internal class DataVirtualizingCollectionViewModelFactory : IDataVirtualizingCollectionViewModelFactory { private readonly IGeneralOptionsViewModel _generalOptionsViewModel; private readonly ISlidingWindowOptionsViewModel _slidingWindowOptionsViewModel; private readonly IPageLoadingBehaviorViewModel _pageLoadingBehaviorViewModel; private readonly IPageRemovalBehaviorViewModel _pageRemovalBehaviorViewModel; private readonly IFetcherKindViewModelInternal _fetcherKindViewModel; private readonly IGeneralFunctionsViewModel _generalFunctionsViewModel; private readonly ISlidingWindowFunctionsViewModel _slidingWindowFunctionsViewModel; private readonly IGetSchedulers _getSchedulers; private readonly CompositeDisposable _compositeDisposableOfLifetimeScope; public DataVirtualizingCollectionViewModelFactory( IGeneralOptionsViewModel generalOptionsViewModel, ISlidingWindowOptionsViewModel slidingWindowOptionsViewModel, IPageLoadingBehaviorViewModel pageLoadingBehaviorViewModel, IPageRemovalBehaviorViewModel pageRemovalBehaviorViewModel, IFetcherKindViewModelInternal fetcherKindViewModel, IGeneralFunctionsViewModel generalFunctionsViewModel, ISlidingWindowFunctionsViewModel slidingWindowFunctionsViewModel, IGetSchedulers getSchedulers, CompositeDisposable compositeDisposableOfLifetimeScope) { _generalOptionsViewModel = generalOptionsViewModel; _slidingWindowOptionsViewModel = slidingWindowOptionsViewModel; _pageLoadingBehaviorViewModel = pageLoadingBehaviorViewModel; _pageRemovalBehaviorViewModel = pageRemovalBehaviorViewModel; _fetcherKindViewModel = fetcherKindViewModel; _generalFunctionsViewModel = generalFunctionsViewModel; _slidingWindowFunctionsViewModel = slidingWindowFunctionsViewModel; _getSchedulers = getSchedulers; _compositeDisposableOfLifetimeScope = compositeDisposableOfLifetimeScope; } public IDataVirtualizingCollectionViewModelBase CreateDataVirtualizingCollection<T>(IBackendAccessAdapter<T> backendAccessAdapter) { var ret = new DataVirtualizingCollectionViewModel<T>( backendAccessAdapter, _generalOptionsViewModel, _pageLoadingBehaviorViewModel, _pageRemovalBehaviorViewModel, _fetcherKindViewModel, _generalFunctionsViewModel, _getSchedulers); _compositeDisposableOfLifetimeScope.Add(ret); return ret; } public IDataVirtualizingCollectionViewModelBase CreateSlidingWindow<T>(IBackendAccessAdapter<T> backendAccessAdapter) { var ret = new SlidingWindowViewModel<T>( backendAccessAdapter, _generalOptionsViewModel, _slidingWindowOptionsViewModel, _pageLoadingBehaviorViewModel, _pageRemovalBehaviorViewModel, _fetcherKindViewModel, _generalFunctionsViewModel, _slidingWindowFunctionsViewModel, _getSchedulers); _compositeDisposableOfLifetimeScope.Add(ret); return ret; } } } <|start_filename|>Sample.ViewModel/ViewModels/SomeWorkloadObjectViewModel.cs<|end_filename|> using BFF.DataVirtualizingCollection.Sample.Model.Models; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels { public interface ISomeWorkloadObjectViewModel { public int Number { get; } } public class SomeWorkloadObjectViewModel : ISomeWorkloadObjectViewModel { private readonly ISomeWorkloadObject _someWorkloadObject; public SomeWorkloadObjectViewModel( ISomeWorkloadObject someWorkloadObject) { _someWorkloadObject = someWorkloadObject; } public int Number => _someWorkloadObject.Number; } } <|start_filename|>Sample.ViewModel/ViewModels/MainWindowViewModel.cs<|end_filename|> using System.Collections.Generic; using System.Collections.ObjectModel; using BFF.DataVirtualizingCollection.Sample.ViewModel.Adapters; namespace BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels { public interface IMainWindowViewModel { IReadOnlyCollection<IDataVirtualizingCollectionViewModelBase> DataVirtualizingCollections { get; } IReadOnlyCollection<IDataVirtualizingCollectionViewModelBase> SlidingWindows { get; } } internal class MainWindowViewModel : ObservableObject, IMainWindowViewModel { public MainWindowViewModel( IAllNumbersCollectionAdapter allNumbersCollectionAdapter, IMillionNumbersCollectionAdapter millionNumbersCollectionAdapter, IHighWorkloadCollectionAdapter highWorkloadCollectionAdapter, IProfileCollectionAdapter profileCollectionAdapter, IDataVirtualizingCollectionViewModelFactory dataVirtualizingCollectionViewModelFactory) { DataVirtualizingCollections = new ReadOnlyCollection<IDataVirtualizingCollectionViewModelBase>( new List<IDataVirtualizingCollectionViewModelBase> { dataVirtualizingCollectionViewModelFactory.CreateDataVirtualizingCollection(allNumbersCollectionAdapter), dataVirtualizingCollectionViewModelFactory.CreateDataVirtualizingCollection(millionNumbersCollectionAdapter), dataVirtualizingCollectionViewModelFactory.CreateDataVirtualizingCollection(highWorkloadCollectionAdapter), dataVirtualizingCollectionViewModelFactory.CreateDataVirtualizingCollection(profileCollectionAdapter) }); SlidingWindows = new ReadOnlyCollection<IDataVirtualizingCollectionViewModelBase>( new List<IDataVirtualizingCollectionViewModelBase> { dataVirtualizingCollectionViewModelFactory.CreateSlidingWindow(allNumbersCollectionAdapter), dataVirtualizingCollectionViewModelFactory.CreateSlidingWindow(millionNumbersCollectionAdapter), dataVirtualizingCollectionViewModelFactory.CreateSlidingWindow(highWorkloadCollectionAdapter), dataVirtualizingCollectionViewModelFactory.CreateSlidingWindow(profileCollectionAdapter) }); } public IReadOnlyCollection<IDataVirtualizingCollectionViewModelBase> DataVirtualizingCollections { get; } public IReadOnlyCollection<IDataVirtualizingCollectionViewModelBase> SlidingWindows { get; } } } <|start_filename|>Tests.Integration/FactoryEnums.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Tests.Integration { public enum PageLoadingBehavior { Preloading, NonPreloading } public enum PageRemovalBehavior { Hoarding, LeastRecentlyUsed } public enum FetchersKind { NonTaskBased, TaskBased } public enum IndexAccessBehavior { Asynchronous, Synchronous } } <|start_filename|>Sample.View/App.xaml.cs<|end_filename|> using System.Windows; namespace BFF.DataVirtualizingCollection.Sample.View { public partial class App { public App() { var mainWindowView = AutofacModule.Start(); mainWindowView.Show(); } public static Visibility IsDebug { #if DEBUG get { return Visibility.Visible; } #else get { return Visibility.Collapsed; } #endif } } } <|start_filename|>Sample.View/Views/Options/GeneralOptionsView.xaml.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.View.Views.Options { public partial class GeneralOptionsView { public GeneralOptionsView() { InitializeComponent(); } } } <|start_filename|>Sample.View/Views/Decisions/PageRemovalBehaviorView.xaml.cs<|end_filename|> using System.Windows; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions; namespace BFF.DataVirtualizingCollection.Sample.View.Views.Decisions { public partial class PageRemovalBehaviorView { public PageRemovalBehaviorView() => InitializeComponent(); private void Hoarding_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IPageRemovalBehaviorViewModel pageLoadingBehaviorViewModel) pageLoadingBehaviorViewModel.PageRemovalBehavior = PageRemovalBehavior.Hoarding; } private void LeastRecentlyUsed_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IPageRemovalBehaviorViewModel pageLoadingBehaviorViewModel) pageLoadingBehaviorViewModel.PageRemovalBehavior = PageRemovalBehavior.LeastRecentlyUsed; } } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/SyncNonPreloadingPageBase.cs<|end_filename|> using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.PageStorage { internal class SyncNonPreloadingNonTaskBasedPage<T> : IPage<T> { private readonly int _pageSize; private readonly IDisposable _onDisposalAfterFetchCompleted; internal SyncNonPreloadingNonTaskBasedPage( // parameter int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted, // dependencies Func<int, int, CancellationToken, T[]> pageFetcher) { _pageSize = pageSize; _onDisposalAfterFetchCompleted = onDisposalAfterFetchCompleted; PageContent = pageFetcher(offset, pageSize, CancellationToken.None); } private T[] PageContent { get; } public T this[int index] => index >= _pageSize || index < 0 ? throw new IndexOutOfRangeException( "Index was out of range. Must be non-negative and less than the size of the collection.") : PageContent[index]; public Task PageFetchCompletion => Task.CompletedTask; public async ValueTask DisposeAsync() { await PageFetchCompletion.ConfigureAwait(false); _onDisposalAfterFetchCompleted.Dispose(); foreach (var disposable in PageContent.OfType<IDisposable>()) { disposable.Dispose(); } } } } <|start_filename|>BFF.DataVirtualizingCollection/VirtualizationBase.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Reactive.Disposables; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection { internal abstract class VirtualizationBase<T> : IVirtualizationBase<T> { int ICollection.Count => GetCountInner(); public bool IsSynchronized => false; public object SyncRoot { get; } = new(); public abstract int Count { get; } protected readonly CompositeDisposable CompositeDisposable = new(); int ICollection<T>.Count => GetCountInner(); int IReadOnlyCollection<T>.Count => GetCountInner(); bool ICollection<T>.IsReadOnly => true; object? IList.this[int index] { get => IndexerInnerGet(index); set => throw new NotSupportedException(); } protected abstract T IndexerInnerGet(int index); public bool IsReadOnly => true; public T this[int index] { get => IndexerInnerGet(index); set => throw new NotSupportedException(); } private int GetCountInner() => Count; public IEnumerator<T> GetEnumerator() { return Iterate().GetEnumerator(); IEnumerable<T> Iterate() { for (var i = 0; i < Count; i++) yield return GetItemForEnumerator(i); } } protected abstract T GetItemForEnumerator(int i); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private static int IndexOfInner() => -1; public int IndexOf(T item) => IndexOfInner(); private static bool ContainsInner() => IndexOfInner() != -1; public bool Contains(T item) => ContainsInner(); public bool IsFixedSize => true; public bool Contains(object value) => ContainsInner(); public int IndexOf(object value) => IndexOf((T) value); public abstract void Reset(); public event NotifyCollectionChangedEventHandler? CollectionChanged; public event PropertyChangedEventHandler? PropertyChanged; protected void OnCollectionChangedReplace(T newItem, T oldItem, int index) => CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, index)); protected virtual void OnCollectionChangedReset() => CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); // ReSharper disable once ExplicitCallerInfoArgument protected void OnIndexerChanged() => OnPropertyChanged("Item[]"); public abstract Task InitializationCompleted { get; } public abstract int SelectedIndex { get; set; } #region NotSupported public void CopyTo(Array array, int index) => throw new NotSupportedException(); public void Add(T item) => throw new NotSupportedException(); public void Insert(int index, T item) => throw new NotSupportedException(); public bool Remove(T item) => throw new NotSupportedException(); public void Remove(object value) => throw new NotSupportedException(); public void RemoveAt(int index) => throw new NotSupportedException(); void IList<T>.RemoveAt(int index) => throw new NotSupportedException(); public int Add(object value) => throw new NotSupportedException(); public void Clear() => throw new NotSupportedException(); public void Insert(int index, object value) => throw new NotSupportedException(); void ICollection<T>.Clear() => throw new NotSupportedException(); public void CopyTo(T[] array, int arrayIndex) => throw new NotSupportedException(); #endregion public virtual async ValueTask DisposeAsync() { try { await InitializationCompleted.ConfigureAwait(false); } catch (OperationCanceledException) { // Ignore cancellation } CompositeDisposable.Dispose(); } } } <|start_filename|>Tests.Integration/SlidingWindowSpecific/AsyncDataAccessTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Reactive.Testing; using MoreLinq.Extensions; using Xunit; namespace BFF.DataVirtualizingCollection.Tests.Integration.SlidingWindowSpecific { public class AsyncTests { // ReSharper disable once MemberCanBePrivate.Global public static IEnumerable<object[]> Combinations => Enum.GetValues(typeof(PageLoadingBehavior)).OfType<PageLoadingBehavior>() .Cartesian( Enum.GetValues(typeof(PageRemovalBehavior)).OfType<PageRemovalBehavior>(), Enum.GetValues(typeof(FetchersKind)).OfType<FetchersKind>(), (first, second, third) => new object[] {first, second, third, IndexAccessBehavior.Asynchronous}); [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69SlidingLeft_Offset68( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.SlideLeft(); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(68, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset0SlidingLeft_Offset0( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 0, scheduler); await collection.InitializationCompleted; // Act collection.SlideLeft(); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(0, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69SlidingRight_Offset70( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.SlideRight(); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(70, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset6959SlidingRight_Offset6959( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 6959, scheduler); await collection.InitializationCompleted; // Act collection.SlideRight(); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(6959, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69JumpTo169_Offset169( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.JumpTo(169); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(169, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69JumpToMinus1_Offset0( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.JumpTo(-1); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(0, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69JumpTo6970_Offset6959( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.JumpTo(6970); var _ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(6959, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69WindowSize10Increase_CountIncreasedLastElement79( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.IncreaseWindowSize(); var _ = collection[10]; await Task.Delay(50); // Assert Assert.Equal(11, collection.Count); Assert.Equal(79, collection[10]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69WindowSize10IncreaseBy2_CountIncreasedLastElement80( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.IncreaseWindowSizeBy(2); var _ = collection[11]; await Task.Delay(50); // Assert Assert.Equal(12, collection.Count); Assert.Equal(80, collection[11]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset6959WindowSize10Increase_CountIncreasedLastElement6968( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 6959, scheduler); await collection.InitializationCompleted; // Act collection.IncreaseWindowSize(); var _ = collection[10]; await Task.Delay(50); // Assert Assert.Equal(11, collection.Count); Assert.Equal(6968, collection[10]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69WindowSize10Decrease_CountDecreasedLastElement77( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.DecreaseWindowSize(); var _ = collection[8]; await Task.Delay(50); // Assert Assert.Equal(9, collection.Count); Assert.Equal(77, collection[8]); Assert.Throws<IndexOutOfRangeException>(() => collection[9]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Offset69WindowSize10DecreaseBy2_CountDecreasedLastElement76( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; // Act collection.DecreaseWindowSizeBy(2); var _ = collection[7]; await Task.Delay(50); // Assert Assert.Equal(8, collection.Count); Assert.Equal(76, collection[7]); Assert.Throws<IndexOutOfRangeException>(() => collection[8]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Reset_NothingChanged( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = SlidingWindowFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, scheduler); await collection.InitializationCompleted; var _ = collection[0]; await Task.Delay(50); // Act collection.Reset(); await Task.Delay(50); var __ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(69, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Reset_SwitchedPageFetching( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); bool switched = false; int[] PageFetcher(int offset, int size) => switched ? Enumerable.Range(offset + 1, size).ToArray() : Enumerable.Range(offset, size).ToArray(); await using var collection = SlidingWindowFactory.CreateCollectionWithCustomPageFetchingLogic( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 10, 10, 69, PageFetcher, -1, scheduler); await collection.InitializationCompleted; var _ = collection[0]; await Task.Delay(50); switched = true; // Act collection.Reset(); await Task.Delay(50); var __ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(70, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Reset_SwitchedCountFetchingOffsetAdjusted( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); bool switched = false; int CountFetcher() => switched ? 70 : 6969; await using var collection = SlidingWindowFactory.CreateCollectionWithCustomCountFetcher( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, CountFetcher, 10, 10, 69, scheduler); await collection.InitializationCompleted; var _ = collection[0]; await Task.Delay(50); switched = true; // Act collection.Reset(); await Task.Delay(50); var __ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(60, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_Reset_SwitchedCountFetchingCountAdjusted( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); bool switched = false; int CountFetcher() => switched ? 9 : 6969; await using var collection = SlidingWindowFactory.CreateCollectionWithCustomCountFetcher( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, CountFetcher, 10, 10, 69, scheduler); await collection.InitializationCompleted; var _ = collection[0]; await Task.Delay(50); switched = true; // Act collection.Reset(); await Task.Delay(50); var __ = collection[0]; await Task.Delay(50); // Assert Assert.Equal(0, collection[0]); Assert.Equal(9, collection.Count); } } } <|start_filename|>Tests.Unit/PageStorage/AsyncPageBaseTests.cs<|end_filename|> using System; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using Xunit; namespace BFF.DataVirtualizingCollection.Test.PageStorage { public abstract class AsyncPageBaseTestsBase : PageTestsBase { internal abstract AsyncPageBase<int> PageWithFirstEntry69AndPlaceholder23 { get; } internal abstract AsyncPageBase<IDisposable> PageWithDisposable(IDisposable disposable); internal abstract AsyncPageBase<IDisposable> PageWithDisposablePlaceholder(IDisposable disposable); [Fact] internal async Task Dispose_PageHasOneDisposable_Disposes() { // Arrange var isDisposed = new TaskCompletionSource<Unit>(); var disposable = Disposable.Create(() => isDisposed.SetResult(Unit.Default)); var sut = PageWithDisposable(disposable); await sut.PageFetchCompletion.ConfigureAwait(false); // Act await sut.DisposeAsync().ConfigureAwait(false); // Assert await isDisposed.Task.ToObservable().Timeout(TimeSpan.FromMinutes(5)).ToTask(); } [Fact] internal async Task Index_FetchFirstIndex_ReturnsPlaceholderImmediately() { // Arrange await using var sut = PageWithFirstEntry69AndPlaceholder23; // Act var value = sut[0]; // Assert Assert.Equal(23, value); } [Fact] internal async Task Index_FetchFirstIndex_ReturnsValueAfterWaiting() { // Arrange await using var sut = PageWithFirstEntry69AndPlaceholder23; // Act await sut.PageFetchCompletion.ConfigureAwait(false); var value = sut[0]; // Assert Assert.Equal(69, value); } [Fact] internal async Task Index_PlaceholderIsDisposable_DisposePlaceholderWhenActualPageArrives() { // Arrange var isDisposed = new TaskCompletionSource<Unit>(); var disposable = Disposable.Create(() => isDisposed.SetResult(Unit.Default)); await using var sut = PageWithDisposablePlaceholder(disposable); // Act var _ = sut[0]; // Assert await isDisposed.Task.ToObservable().Timeout(TimeSpan.FromSeconds(5)).ToTask(); } } // ReSharper disable once UnusedMember.Global public class AsyncNonTaskBasedPageTests : AsyncPageBaseTestsBase { internal override IPage<int> PageWithPageSizeOne => new AsyncNonTaskBasedPage<int>( 0, 0, 1, Disposable.Empty, (_, _, _) => { Thread.Sleep(10); return new[] { 69 }; }, (_, _) => 23, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, int[] PreviousPage, int[] Page)>(_ => { })); internal override AsyncPageBase<int> PageWithFirstEntry69AndPlaceholder23 => new AsyncNonTaskBasedPage<int>( 0, 0, 1, Disposable.Empty, (_, _, _) => { Thread.Sleep(1000); return new[] {69}; }, (_, _) => 23, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, int[] PreviousPage, int[] Page)>(_ => { })); internal override AsyncPageBase<IDisposable> PageWithDisposable(IDisposable disposable) { return new AsyncNonTaskBasedPage<IDisposable>( 0, 0, 1, Disposable.Empty, (_, _, _) => { Thread.Sleep(10); return new[] { disposable }; }, (_, _) => Disposable.Empty, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, IDisposable[] PreviousPage, IDisposable[] Page)>(_ => { })); } internal override AsyncPageBase<IDisposable> PageWithDisposablePlaceholder(IDisposable disposable) { return new AsyncNonTaskBasedPage<IDisposable>( 0, 0, 1, Disposable.Empty, (_, _, _) => { Thread.Sleep(10); return new []{ Disposable.Empty }; }, (_, _) => disposable, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, IDisposable[] PreviousPage, IDisposable[] Page)>(_ => { })); } } // ReSharper disable once UnusedMember.Global public class AsyncTaskBasedPageTests : AsyncPageBaseTestsBase { internal override IPage<int> PageWithPageSizeOne => new AsyncTaskBasedPage<int>( 0, 0, 1, Disposable.Empty, async (_, _, ct) => { await Task.Delay(10, ct).ConfigureAwait(false); return new[] { 69 }; }, (_, _) => 23, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, int[] PreviousPage, int[] Page)>(_ => { })); internal override AsyncPageBase<int> PageWithFirstEntry69AndPlaceholder23 => new AsyncTaskBasedPage<int>( 0, 0, 1, Disposable.Empty, async (_, _, ct) => { await Task.Delay(10, ct).ConfigureAwait(false); return new[] {69}; }, (_, _) => 23, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, int[] PreviousPage, int[] Page)>(_ => { })); internal override AsyncPageBase<IDisposable> PageWithDisposable(IDisposable disposable) { return new AsyncTaskBasedPage<IDisposable>( 0, 0, 1, Disposable.Empty, async (_, _, ct) => { await Task.Delay(10, ct).ConfigureAwait(false); return new[] { disposable }; }, (_, _) => Disposable.Empty, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, IDisposable[] PreviousPage, IDisposable[] Page)>(_ => { })); } internal override AsyncPageBase<IDisposable> PageWithDisposablePlaceholder(IDisposable disposable) { return new AsyncTaskBasedPage<IDisposable>( 0, 0, 1, Disposable.Empty, async (_, _, ct) => { await Task.Delay(10, ct).ConfigureAwait(false); return new[] { Disposable.Empty }; }, (_, _) => disposable, new ImmediateAsyncPageFetchScheduler(), DefaultScheduler.Instance, Observer.Create<(int Offset, int PageSize, IDisposable[] PreviousPage, IDisposable[] Page)>(_ => { })); } } } <|start_filename|>BFF.DataVirtualizingCollection/InternalsVisibleTo.cs<|end_filename|> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("BFF.DataVirtualizingCollection.Tests.Unit")] [assembly: InternalsVisibleTo("BFF.DataVirtualizingCollection.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] <|start_filename|>Sample.View/Views/Decisions/IndexAccessBehaviorViewModel.xaml.cs<|end_filename|> using System.Windows; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions; namespace BFF.DataVirtualizingCollection.Sample.View.Views.Decisions { public partial class IndexAccessBehaviorView { public IndexAccessBehaviorView() { InitializeComponent(); } private void Synchronous_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IIndexAccessBehaviorViewModel indexAccessBehaviorViewModel) indexAccessBehaviorViewModel.IndexAccessBehavior = IndexAccessBehavior.Synchronous; } private void Asynchronous_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IIndexAccessBehaviorViewModel indexAccessBehaviorViewModel) indexAccessBehaviorViewModel.IndexAccessBehavior = IndexAccessBehavior.Asynchronous; } } } <|start_filename|>Sample.View/Utilities/ProfileViewStatic.cs<|end_filename|> using System; using System.Windows.Data; using System.Windows.Media; using System.Windows.Media.Imaging; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels; using MahApps.Metro.IconPacks; namespace BFF.DataVirtualizingCollection.Sample.View.Utilities { public static class ProfileViewStatic { public static IValueConverter ToCompanyBrush = LambdaConverters.ValueConverter.Create<ProfileViewModel, Brush>( e => e.Value.IsFreelancer ? Brushes.Green : Brushes.Blue); public static IValueConverter ToCompanyText = LambdaConverters.ValueConverter.Create<ProfileViewModel, string>( e => e.Value.IsFreelancer ? "Freelancer" : e.Value.CompanyName ?? string.Empty); public static IValueConverter ToCompanyIcon = LambdaConverters.ValueConverter.Create<ProfileViewModel, PackIconMaterialKind>( e => e.Value.IsFreelancer ? PackIconMaterialKind.AccountOutline : PackIconMaterialKind.City); public static IValueConverter ToImageSource = LambdaConverters.ValueConverter.Create<ProfileViewModel, ImageSource>( e => new BitmapImage(new Uri(e.Value.PicturePath))); public static IValueConverter PrefixedHiddenAbilitiesCount = LambdaConverters.ValueConverter.Create<int, string>( e => $"+{e.Value}"); public static IValueConverter ProfilesTitle = LambdaConverters.ValueConverter.Create<int, string>( e => $"Profiles ({e.Value})"); } } <|start_filename|>BFF.DataVirtualizingCollection/PageStorage/AsyncPageBase.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using System.Threading; using System.Threading.Tasks; using MrMeeseeks.Extensions; namespace BFF.DataVirtualizingCollection.PageStorage { internal abstract class AsyncPageBase<T> : IPage<T> { protected readonly int Offset; protected readonly int PageSize; private readonly IDisposable _onDisposalAfterFetchCompleted; private readonly IAsyncPageFetchScheduler _asyncPageFetchScheduler; protected readonly IObserver<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> PageArrivalObservations; protected readonly CancellationTokenSource CancellationTokenSource = new(); protected T[] Page; protected bool IsDisposed; internal AsyncPageBase( // parameter int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted, // dependencies Func<int, int, T> placeholderFactory, IAsyncPageFetchScheduler asyncPageFetchScheduler, IObserver<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> pageArrivalObservations) { Offset = offset; PageSize = pageSize; _onDisposalAfterFetchCompleted = onDisposalAfterFetchCompleted; _asyncPageFetchScheduler = asyncPageFetchScheduler; PageArrivalObservations = pageArrivalObservations; Page = Enumerable .Range(0, pageSize) .Select(pageIndex => placeholderFactory(pageKey, pageIndex)) .ToArray(); } protected async Task FetchPage(CancellationToken ct) { await _asyncPageFetchScheduler.Schedule().ConfigureAwait(false); ct.ThrowIfCancellationRequested(); await FetchPageInner(ct).ConfigureAwait(false); } protected abstract Task FetchPageInner(CancellationToken ct); public abstract Task PageFetchCompletion { get; } public T this[int index] => index >= PageSize || index < 0 ? throw new IndexOutOfRangeException( "Index was out of range. Must be non-negative and less than the size of the collection.") : Page[index]; protected static async Task DisposePageItems(T[] page) { foreach (var disposable in page.OfType<IDisposable>()) disposable.Dispose(); foreach (var disposable in page.OfType<IAsyncDisposable>()) await disposable.DisposeAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { IsDisposed = true; try { CancellationTokenSource.Cancel(); await PageFetchCompletion.ConfigureAwait(false); } catch (OperationCanceledException) { // Ignore cancellation } finally { await DisposePageItems(Page).ConfigureAwait(false); PageFetchCompletion.Dispose(); _onDisposalAfterFetchCompleted.Dispose(); } } } internal sealed class AsyncNonTaskBasedPage<T> : AsyncPageBase<T> { private readonly Func<int, int, CancellationToken, T[]> _pageFetcher; internal AsyncNonTaskBasedPage( // parameter int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted, // dependencies Func<int, int, CancellationToken, T[]> pageFetcher, Func<int, int, T> placeholderFactory, IAsyncPageFetchScheduler asyncPageFetchScheduler, IScheduler pageBackgroundScheduler, IObserver<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> pageArrivalObservations) : base( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, placeholderFactory, asyncPageFetchScheduler, pageArrivalObservations) { _pageFetcher = pageFetcher; PageFetchCompletion = Observable .StartAsync(FetchPage, pageBackgroundScheduler) .ToTask(CancellationTokenSource.Token); } protected override async Task FetchPageInner(CancellationToken ct) { await Task.Delay(1, ct).ConfigureAwait(false); var previousPage = Page; Page = _pageFetcher(Offset, PageSize, ct); await DisposePageItems(previousPage).ConfigureAwait(false); if (!IsDisposed) PageArrivalObservations.OnNext((Offset, PageSize, previousPage, Page)); else await DisposePageItems(Page).ConfigureAwait(false); } public override Task PageFetchCompletion { get; } } internal sealed class AsyncTaskBasedPage<T> : AsyncPageBase<T> { private readonly Func<int, int, CancellationToken, Task<T[]>> _pageFetcher; internal AsyncTaskBasedPage( // parameter int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted, // dependencies Func<int, int, CancellationToken, Task<T[]>> pageFetcher, Func<int, int, T> placeholderFactory, IAsyncPageFetchScheduler asyncPageFetchScheduler, IScheduler pageBackgroundScheduler, IObserver<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> pageArrivalObservations) : base( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, placeholderFactory, asyncPageFetchScheduler, pageArrivalObservations) { _pageFetcher = pageFetcher; PageFetchCompletion = Observable .StartAsync(FetchPage, pageBackgroundScheduler) .ToTask(CancellationTokenSource.Token); } protected override async Task FetchPageInner(CancellationToken ct) { var previousPage = Page; Page = await _pageFetcher(Offset, PageSize, ct).ConfigureAwait(false); await DisposePageItems(previousPage).ConfigureAwait(false); if (!IsDisposed) PageArrivalObservations.OnNext((Offset, PageSize, previousPage, Page)); else await DisposePageItems(Page).ConfigureAwait(false); } public override Task PageFetchCompletion { get; } } internal sealed class AsyncEnumerableBasedPage<T> : AsyncPageBase<T> { private readonly Func<int, int, CancellationToken, IAsyncEnumerable<T>> _pageFetcher; internal AsyncEnumerableBasedPage( // parameter int pageKey, int offset, int pageSize, IDisposable onDisposalAfterFetchCompleted, // dependencies Func<int, int, CancellationToken, IAsyncEnumerable<T>> pageFetcher, Func<int, int, T> placeholderFactory, IAsyncPageFetchScheduler asyncPageFetchScheduler, IScheduler pageBackgroundScheduler, IObserver<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> pageArrivalObservations) : base( pageKey, offset, pageSize, onDisposalAfterFetchCompleted, placeholderFactory, asyncPageFetchScheduler, pageArrivalObservations) { _pageFetcher = pageFetcher; PageFetchCompletion = Observable .StartAsync(FetchPage, pageBackgroundScheduler) .ToTask(CancellationTokenSource.Token); } protected override async Task FetchPageInner(CancellationToken ct) { var i = 0; await foreach (var item in _pageFetcher(Offset, PageSize, ct)) { ct.ThrowIfCancellationRequested(); var temp = Page[i]; Page[i] = item; (temp as IDisposable)?.Dispose(); if (temp is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync().ConfigureAwait(false); if(IsDisposed.Not()) PageArrivalObservations.OnNext((Offset + i, 1, temp.ToEnumerable().ToArray(), item.ToEnumerable().ToArray())); i++; } } public override Task PageFetchCompletion { get; } } } <|start_filename|>Sample.View/Views/Decisions/FetcherKindView.xaml.cs<|end_filename|> using System.Windows; using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels.Decisions; namespace BFF.DataVirtualizingCollection.Sample.View.Views.Decisions { public partial class FetcherKindView { public FetcherKindView() => InitializeComponent(); private void NonTaskBased_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IFetcherKindViewModel fetcherKindViewModel) fetcherKindViewModel.FetcherKind = FetcherKind.NonTaskBased; } private void TaskBased_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IFetcherKindViewModel fetcherKindViewModel) fetcherKindViewModel.FetcherKind = FetcherKind.TaskBased; } private void AsyncEnumerableBased_OnChecked(object sender, RoutedEventArgs e) { if (DataContext is IFetcherKindViewModel fetcherKindViewModel) fetcherKindViewModel.FetcherKind = FetcherKind.AsyncEnumerableBased; } } } <|start_filename|>Sample.View/Views/Functions/GeneralFunctionsView.xaml.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.View.Views.Functions { public partial class GeneralFunctionsView { public GeneralFunctionsView() => InitializeComponent(); } } <|start_filename|>BFF.DataVirtualizingCollection/Utilities/ITimestampProvider.cs<|end_filename|> using System; namespace BFF.DataVirtualizingCollection.Utilities { internal interface ITimestampProvider { DateTime Now { get; } } } <|start_filename|>Sample.View/Views/MainWindowView.xaml.cs<|end_filename|> using BFF.DataVirtualizingCollection.Sample.ViewModel.ViewModels; namespace BFF.DataVirtualizingCollection.Sample.View.Views { public partial class MainWindowView { public MainWindowView(IMainWindowViewModel mainWindowViewModel) { InitializeComponent(); DataContext = mainWindowViewModel; } } } <|start_filename|>Sample.Model/BackendAccesses/AllNumbersFakeBackendAccess.cs<|end_filename|> using System; using System.Linq; namespace BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses { public interface IAllNumbersFakeBackendAccess : IBackendAccess<int> { } internal class AllNumbersFakeBackendAccess : IAllNumbersFakeBackendAccess { public string Name => "All Positive Numbers"; public int[] PageFetch(int pageOffset, int pageSize) => Enumerable.Range(pageOffset, pageSize).ToArray(); public int PlaceholderFetch(int _, int __) { return -11; } public int PreloadingPlaceholderFetch(int _, int __) { return -21; } public int CountFetch() { return int.MaxValue; } } } <|start_filename|>Sample.View/Views/DataVirtualizingCollectionView.xaml.cs<|end_filename|> namespace BFF.DataVirtualizingCollection.Sample.View.Views { public partial class DataVirtualizingCollectionView { public DataVirtualizingCollectionView() => InitializeComponent(); } } <|start_filename|>Sample.Model/BackendAccesses/IBackendAccess.cs<|end_filename|> using System.Collections.Generic; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection.Sample.Model.BackendAccesses { public interface IBackendAccess<T> { string Name { get; } T[] PageFetch(int pageOffset, int pageSize); async IAsyncEnumerable<T> AsyncEnumerablePageFetch(int pageOffset, int pageSize) { foreach (var item in PageFetch(pageOffset, pageSize)) { await Task.Delay(1); yield return item; } } T PlaceholderFetch(int pageOffset, int indexInsidePage); T PreloadingPlaceholderFetch(int pageOffset, int indexInsidePage); int CountFetch(); } } <|start_filename|>Tests.Unit/PageStorage/SyncNonPreloadingPageBaseTests.cs<|end_filename|> using System; using System.Reactive.Disposables; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using Xunit; namespace BFF.DataVirtualizingCollection.Test.PageStorage { public abstract class SyncNonPreloadingPageBaseTestsBase : PageTestsBase { internal abstract SyncNonPreloadingNonTaskBasedPage<int> PageWithFirstEntry69 { get; } internal abstract SyncNonPreloadingNonTaskBasedPage<IDisposable> PageWithDisposable(IDisposable disposable); [Fact] internal async Task Dispose_PageHasOneDisposable_DisposesImmediately() { // Arrange var isDisposed = false; var disposable = Disposable.Create(() => isDisposed = true); var sut = PageWithDisposable(disposable); // Act await sut.DisposeAsync(); // Assert Assert.True(isDisposed); } [Fact] internal async Task Index_FetchFirstIndex_ReturnsValue() { // Arrange await using var sut = PageWithFirstEntry69; // Act var value = sut[0]; // Assert Assert.Equal(69, value); } } // ReSharper disable once UnusedMember.Global public class SyncNonPreloadingNonTaskBasedPageTests : SyncNonPreloadingPageBaseTestsBase { internal override IPage<int> PageWithPageSizeOne => new SyncNonPreloadingNonTaskBasedPage<int>( 0, 1, Disposable.Empty, (offset, pageSize, _) => new[] { 69 }); internal override SyncNonPreloadingNonTaskBasedPage<int> PageWithFirstEntry69 => new( 0, 1, Disposable.Empty, (offset, pageSize, _) => new[] { 69 }); internal override SyncNonPreloadingNonTaskBasedPage<IDisposable> PageWithDisposable(IDisposable disposable) { return new( 0, 1, Disposable.Empty, (offset, pageSize, _) => new[] {disposable}); } } }
Yeah69/BFF.DataVirtualizingCollection
<|start_filename|>doc/adts_data.go<|end_filename|> package main import ( "fmt" "os" ) var f *os.File = nil func write(data []byte) { if f == nil { var err error f, err = os.Create("adts_data.aac") if err != nil { panic(err) } } f.Write(data) } func main() { fmt.Println("ffmpeg -i adts_data.aac -acodec pcm_s16le -y adts_data.pcm_s16le.wav") write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x35, 0xa1, 0x0c, 0x2f, 0x00, 0x00, 0x50, 0x23, 0xa6, 0x81, 0xbf, 0x9c, 0xbf, 0x13, 0x73, 0xa9, 0xb0, 0x41, 0xed, 0x60, 0x23, 0x48, 0xf7, 0x34, 0x07, 0x12, 0x53, 0xd8, 0xeb, 0x49, 0xf4, 0x1e, 0x73, 0xc9, 0x01, 0xfd, 0x16, 0x9f, 0x8e, 0xb5, 0xd5, 0x9b, 0xb6, 0x49, 0xdb, 0x35, 0x61, 0x3b, 0x54, 0xad, 0x5f, 0x9d, 0x34, 0x94, 0x88, 0x58, 0x89, 0x33, 0x54, 0x89, 0xc4, 0x09, 0x80, 0xa2, 0xa1, 0x28, 0x81, 0x42, 0x10, 0x48, 0x94, 0x05, 0xfb, 0x03, 0xc7, 0x64, 0xe1, 0x54, 0x17, 0xf6, 0x65, 0x15, 0x00, 0x48, 0xa9, 0x80, 0x00, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x19, 0x1a, 0x2a, 0x2d, 0x54, 0xce, 0x00, 0x58, 0x1a, 0x1e, 0x42, 0x0e, 0x1f, 0xd2, 0xd4, 0x9c, 0x15, 0x77, 0xf4, 0x07, 0x38, 0x3d, 0xc5, 0x04, 0x19, 0x64, 0x39, 0x98, 0x01, 0xae, 0x2e, 0xb1, 0xd0, 0x87, 0xca, 0x33, 0x17, 0xfb, 0x05, 0x00, 0x7a, 0x60, 0x47, 0x79, 0x6b, 0x9b, 0xdf, 0x2d, 0xfd, 0x32, 0xc6, 0x9f, 0x1f, 0x21, 0x4b, 0x04, 0x9b, 0xe2, 0x4d, 0x62, 0xc8, 0x01, 0xe0, 0x98, 0x0a, 0x37, 0x48, 0x44, 0x42, 0x02, 0x00, 0xd0, 0x7d, 0xae, 0xb4, 0x32, 0xf1, 0xcc, 0x76, 0x5f, 0x18, 0xac, 0xae, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x21, 0x12, 0xc2, 0x15, 0x04, 0x17, 0x94, 0x50, 0xb0, 0xaf, 0x3a, 0x34, 0x12, 0x7f, 0xee, 0x54, 0xac, 0xe2, 0x57, 0x57, 0xf7, 0x19, 0x18, 0xc5, 0x08, 0xc9, 0xaa, 0x21, 0x75, 0x2c, 0xc9, 0x4f, 0x6f, 0xc7, 0xe2, 0xfb, 0x44, 0x72, 0x47, 0x71, 0x4a, 0x88, 0x9b, 0xfe, 0x0c, 0x83, 0x02, 0x1a, 0xc9, 0x59, 0x7a, 0x48, 0x98, 0xac, 0x02, 0xab, 0x64, 0x22, 0x32, 0xcd, 0x50, 0x3d, 0x80, 0x16, 0x22, 0x70, 0xb0, 0x7b, 0x00, 0x53, 0xef, 0x7c, 0xbc}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x1d, 0x4d, 0x01, 0x42, 0x8a, 0x80, 0x19, 0x01, 0x8b, 0x0b, 0xe0, 0x02, 0x24, 0x7d, 0x8e, 0x08, 0xf2, 0x65, 0x64, 0xef, 0x02, 0x80, 0xf2, 0x72, 0xe4, 0xea, 0x19, 0x9c, 0xd6, 0x90, 0xb8, 0x6f, 0xd4, 0x28, 0x74, 0xb9, 0xdd, 0x80, 0x6a, 0xfe, 0x09, 0x0e, 0xa4, 0xb7, 0x83, 0x7f, 0xf8, 0x80, 0xa4, 0xa1, 0xd6, 0xb3, 0x6d, 0xbd, 0xe5, 0xe3, 0xc7, 0x00, 0xa0, 0x50, 0x17, 0x49, 0x96, 0x8b, 0x9a, 0x17, 0x40, 0x02, 0xa8, 0x50, 0x15, 0x03, 0x7a, 0x1c, 0x01, 0x5c, 0x9c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x18, 0x88, 0xc4, 0x37, 0x99, 0xa0, 0x2d, 0x44, 0x31, 0xa7, 0x04, 0x68, 0x10, 0x23, 0xe7, 0x01, 0x95, 0x20, 0xb6, 0x0e, 0xe8, 0x73, 0xb8, 0x64, 0xe9, 0x12, 0xe4, 0xa2, 0x35, 0xd1, 0x09, 0xf0, 0xd2, 0x36, 0xd6, 0x47, 0xaa, 0xd8, 0x9f, 0x41, 0xcb, 0xf0, 0xfa, 0xbf, 0x12, 0x62, 0x4c, 0xee, 0x89, 0x18, 0xf7, 0x29, 0x2a, 0xaa, 0x67, 0x09, 0x08, 0x5e, 0xac, 0xe9, 0x75, 0xfd, 0x3d, 0x30, 0x00, 0xac, 0x13, 0x85, 0x81, 0x61, 0x5d, 0x03, 0x2f, 0xfa, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x19, 0x64, 0x25, 0x12, 0xa6, 0x5a, 0xad, 0x48, 0x57, 0x02, 0xc2, 0xc2, 0x02, 0xfd, 0xe2, 0x99, 0x3c, 0xa6, 0x6f, 0x28, 0xe9, 0xed, 0x51, 0xc0, 0xe3, 0xfc, 0x35, 0x1b, 0xfd, 0x44, 0x7c, 0x26, 0xf1, 0xfe, 0xb7, 0x0e, 0x50, 0x6e, 0xc5, 0x97, 0x2b, 0xeb, 0xe8, 0xb3, 0xa4, 0xb9, 0xa3, 0x2c, 0x80, 0x9b, 0x19, 0x42, 0x3a, 0x4b, 0xdc, 0x1a, 0xb9, 0x68, 0x02, 0xc2, 0x2c, 0xd1, 0xd1, 0x8e, 0x40, 0x01, 0x58, 0x28, 0x0a, 0xa1, 0x0b, 0x1e, 0x6c, 0x26, 0xa6, 0x5d, 0x7c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x15, 0xe0, 0x28, 0x58, 0x61, 0xa0, 0x0b, 0x03, 0x59, 0x60, 0x80, 0xfd, 0xca, 0xc6, 0x86, 0xff, 0x7a, 0xd4, 0xd4, 0xd1, 0xcd, 0x9e, 0x82, 0xeb, 0xfb, 0x51, 0x3e, 0xab, 0x42, 0xef, 0xb9, 0xce, 0x2b, 0xc6, 0x8c, 0x2b, 0x5a, 0x15, 0xbb, 0x65, 0xdd, 0xc3, 0x3b, 0xd0, 0x46, 0x1d, 0xfe, 0xd6, 0x5c, 0x91, 0x84, 0x98, 0x0a, 0x95, 0x79, 0xca, 0x47, 0x93, 0x75, 0x20, 0xe4, 0x88, 0x59, 0x72, 0x75, 0xb3, 0xcb, 0x92, 0xb1, 0x00, 0x05, 0x39, 0xa0, 0x2a, 0x00, 0x37, 0xaf, 0x53, 0x0a, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x74, 0x11, 0xdc, 0x69, 0x01, 0x34, 0xac, 0xb4, 0xa2, 0x54, 0xd0, 0x17, 0x0b, 0x05, 0x65, 0x6d, 0x40, 0xd8, 0xa5, 0xc1, 0x69, 0xad, 0x78, 0x96, 0xb9, 0x7c, 0xd3, 0x31, 0xf0, 0x74, 0xe7, 0x0e, 0x46, 0x9a, 0xe7, 0x61, 0xbb, 0x41, 0x58, 0x68, 0xe0, 0x68, 0xdd, 0xc7, 0x06, 0x73, 0xc7, 0xd2, 0x43, 0xd7, 0x66, 0x21, 0x95, 0x3e, 0x83, 0xc3, 0xb9, 0x32, 0x74, 0xfe, 0xd2, 0x33, 0x8b, 0x64, 0x34, 0x95, 0x2f, 0x6c, 0x95, 0xcb, 0xa6, 0xad, 0x15, 0x84, 0x8b, 0xdd, 0x80, 0x36, 0xbe, 0x17, 0x88, 0x2e, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x7d, 0x11, 0xde, 0x2a, 0x74, 0xca, 0x49, 0x45, 0x48, 0x41, 0x0e, 0x2f, 0x28, 0x08, 0xcc, 0xf6, 0x30, 0x17, 0x20, 0x28, 0xfa, 0x46, 0x3b, 0xaf, 0x1b, 0xe4, 0x49, 0xd1, 0x06, 0xa7, 0x3c, 0xcf, 0x1b, 0xd5, 0xe6, 0xad, 0x1c, 0x2a, 0x74, 0xd4, 0x92, 0xb2, 0x85, 0x71, 0x0c, 0x3a, 0x3b, 0x41, 0x80, 0x6f, 0xad, 0xc5, 0x96, 0x69, 0xba, 0x32, 0xd1, 0xc4, 0x09, 0x8e, 0x1b, 0x66, 0x2c, 0x2c, 0x00, 0xad, 0x35, 0x84, 0x91, 0x40, 0x03, 0xc7, 0xc7, 0xa6, 0x05, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x24, 0x03, 0x04, 0x52, 0x9a, 0x89, 0x00, 0x02, 0xa5, 0x89, 0xa0, 0x0b, 0x99, 0xaa, 0x92, 0x9a, 0xd6, 0xba, 0x03, 0x3b, 0x58, 0x61, 0x59, 0xe7, 0xb9, 0x33, 0x0d, 0xd6, 0x4f, 0xac, 0x08, 0xdb, 0x09, 0xc9, 0x78, 0x65, 0x8e, 0xf8, 0xb6, 0x9b, 0x31, 0x06, 0x77, 0x4f, 0x67, 0x8c, 0x92, 0xaf, 0x3d, 0xab, 0xa3, 0xd2, 0x35, 0x74, 0x86, 0xdb, 0x4b, 0x06, 0xa8, 0x54, 0xa1, 0x49, 0x76, 0xef, 0xc0, 0xc3, 0x9f, 0x2d, 0x77, 0x3a, 0xa5, 0xe0, 0x01, 0x5a, 0x45, 0x0c, 0x21, 0x40, 0x36, 0x6e, 0xf2, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0xa1, 0x8b, 0x01, 0x53, 0x8a, 0x01, 0x01, 0x8a, 0xaa, 0x89, 0x0d, 0x34, 0xa0, 0x28, 0x68, 0x1c, 0xe2, 0xa8, 0xec, 0x5e, 0x63, 0x89, 0xec, 0x71, 0x84, 0x8e, 0x17, 0x00, 0x76, 0x50, 0x27, 0xa9, 0xdd, 0x12, 0x70, 0x83, 0xcd, 0x14, 0x7c, 0x9c, 0xa3, 0xd5, 0xee, 0x55, 0xa8, 0x3a, 0xe5, 0x5e, 0xee, 0x8b, 0xe7, 0xfd, 0xa8, 0xa9, 0x88, 0x40, 0xde, 0xb4, 0xd6, 0xd4, 0x19, 0xc5, 0xce, 0xda, 0xe5, 0x00, 0x6e, 0x6b, 0x6a, 0xfe, 0x5b, 0xd0, 0xf4, 0xcb, 0x6d, 0xc0, 0x05, 0x39, 0xa8, 0x26, 0x16, 0x01, 0xe7, 0xc3, 0xd1, 0xdc, 0x4f, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x20, 0x8a, 0xc7, 0x13, 0x80, 0x80, 0x80, 0x00, 0x59, 0x60, 0x75, 0x92, 0xe5, 0x60, 0xbb, 0x04, 0x62, 0x1b, 0x04, 0x13, 0xb6, 0xac, 0x4b, 0x06, 0x9a, 0xe3, 0xc7, 0xa5, 0xfa, 0x0f, 0x6d, 0x52, 0x00, 0x7e, 0x7e, 0xc4, 0x66, 0xc8, 0x00, 0xe2, 0x81, 0xd7, 0x45, 0xfc, 0xbb, 0x45, 0xcd, 0x0c, 0x1c, 0x55, 0x42, 0x51, 0x4d, 0xce, 0x93, 0x10, 0xb0, 0x90, 0xa0, 0x8e, 0x32, 0x8e, 0x85, 0x39, 0xa4, 0x28, 0x00, 0x1b, 0xc6, 0x8f, 0xc6, 0xcf, 0xf5, 0x28, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x95, 0x9b, 0x01, 0x22, 0x09, 0x80, 0x41, 0x85, 0x2a, 0x41, 0x6e, 0x8b, 0x09, 0xc4, 0x0f, 0xb9, 0x9c, 0x5b, 0x60, 0x92, 0x43, 0x1d, 0xb6, 0x80, 0x9e, 0xdd, 0x74, 0x45, 0x62, 0x63, 0xa1, 0x59, 0xc8, 0x40, 0x85, 0xd0, 0x2f, 0xb1, 0x52, 0xdb, 0xd7, 0x3a, 0x0e, 0xda, 0x00, 0xe5, 0x01, 0x20, 0xcd, 0x25, 0x87, 0x67, 0x38, 0x93, 0x81, 0xa9, 0x2e, 0x4a, 0xb0, 0xfd, 0xf6, 0x40, 0x7e, 0x26, 0x23, 0x90, 0x5a, 0x49, 0xa9, 0x14, 0x41, 0x54, 0x26, 0x12, 0xe2, 0x01, 0x54, 0x68, 0x0a, 0x88, 0x8c, 0x03, 0xe4, 0x53, 0xd3, 0x8f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x16, 0x5e, 0x82, 0x12, 0x80, 0x80, 0x0c, 0x8c, 0xb1, 0xa0, 0xd6, 0x80, 0x14, 0x7f, 0x08, 0xa1, 0xfc, 0x07, 0xa5, 0x9a, 0xcc, 0xbc, 0x6e, 0x39, 0x8a, 0xac, 0x15, 0x94, 0x2e, 0xf1, 0x2c, 0x32, 0x95, 0x37, 0xab, 0x2e, 0x47, 0xad, 0xe7, 0x87, 0x3a, 0xe3, 0x08, 0xe0, 0xb2, 0xaf, 0x4e, 0x9c, 0x71, 0xbe, 0x04, 0x5d, 0xea, 0x61, 0x4f, 0x44, 0x62, 0x92, 0x80, 0xeb, 0x9e, 0x91, 0x82, 0x4f, 0x88, 0xc0, 0xa4, 0x91, 0x55, 0xde, 0x11, 0x91, 0x50, 0xa8, 0x0a, 0x80, 0x0b, 0xf1, 0x3a, 0x5e, 0xfe, 0x9f, 0x6c, 0x17, 0xea, 0x87}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0x1c, 0x90, 0xa7, 0x13, 0x80, 0x82, 0x98, 0x02, 0xcf, 0x62, 0x04, 0x3b, 0x2c, 0x9d, 0xfb, 0xef, 0x8a, 0x27, 0x09, 0x4e, 0x74, 0x1a, 0x19, 0xea, 0x4f, 0x13, 0x15, 0xf5, 0x1c, 0x30, 0x45, 0x12, 0xfe, 0x59, 0x99, 0xfb, 0xb9, 0x2b, 0xce, 0x1b, 0xee, 0xfa, 0x21, 0x1e, 0xb8, 0x12, 0xba, 0xc0, 0xe7, 0x67, 0x39, 0x77, 0xcc, 0x0a, 0x2d, 0xce, 0x05, 0x41, 0x5c, 0x96, 0xb1, 0x40, 0x00, 0x53, 0x2a, 0xc2, 0x40, 0x48, 0x50, 0x3b, 0xfa, 0xfe, 0x4e, 0x1e, 0xaf, 0xaa, 0x4e, 0xbf, 0x6b, 0x2b, 0x8a, 0xd4, 0x9c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x15, 0x62, 0x27, 0x01, 0x62, 0x9d, 0xd1, 0x6a, 0xb6, 0x71, 0xd1, 0xd0, 0x41, 0xde, 0xbb, 0xb8, 0x15, 0x23, 0xa0, 0xdf, 0x7d, 0x9c, 0x73, 0xaf, 0x8d, 0x52, 0x22, 0xff, 0xc6, 0x26, 0x77, 0x98, 0xba, 0xd4, 0xca, 0x82, 0xe2, 0x8c, 0x27, 0x5f, 0x7f, 0x8d, 0xcf, 0x1f, 0x08, 0x8b, 0xf4, 0xe6, 0x9d, 0xfc, 0x21, 0x58, 0x4e, 0xb2, 0x31, 0xc0, 0xbe, 0x45, 0xc0, 0x82, 0x30, 0x8a, 0xc0, 0x37, 0x80, 0x58, 0x02, 0x90, 0x03, 0x04, 0x32, 0x84, 0xc0, 0x01, 0xf6, 0xcb, 0x2f, 0x57, 0x17, 0xc6, 0x37, 0xf8, 0x65, 0x78, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x1d, 0x56, 0x69, 0x01, 0x00, 0x5a, 0x94, 0x30, 0x0f, 0x2b, 0xd8, 0x27, 0x85, 0xdd, 0x1f, 0x2d, 0xae, 0xe0, 0x60, 0x70, 0x13, 0x02, 0x39, 0x5c, 0xfc, 0xb9, 0x4a, 0xbd, 0xd8, 0xb9, 0x88, 0x80, 0x8b, 0xbc, 0x49, 0x6b, 0x9a, 0xf8, 0x45, 0x6b, 0xf8, 0x76, 0xcd, 0xb3, 0x0c, 0xaf, 0xfc, 0x2c, 0x49, 0x75, 0xa9, 0x45, 0x5d, 0x5d, 0x10, 0x8c, 0xd0, 0xc0, 0xaa, 0xea, 0x93, 0x44, 0x29, 0xdc, 0xe2, 0x80, 0x70, 0x40, 0x00, 0x57, 0x86, 0x74, 0x47, 0x17, 0x7f, 0x92, 0x86, 0x90, 0x13, 0x44, 0x5b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x25, 0x1c, 0x26, 0x00, 0x00, 0x10, 0xb1, 0xa0, 0x24, 0x55, 0xe5, 0xb2, 0xfd, 0x75, 0x91, 0x2c, 0x38, 0x9c, 0xd0, 0x81, 0xd1, 0x5a, 0x41, 0x28, 0x81, 0x09, 0xd9, 0xeb, 0x05, 0x4f, 0x87, 0xb4, 0x64, 0x51, 0x6e, 0xbc, 0xa4, 0xd7, 0x13, 0xf7, 0xf0, 0xcf, 0x29, 0x9a, 0x14, 0x61, 0xee, 0x62, 0xb9, 0xd4, 0xf6, 0x08, 0xb1, 0x71, 0xeb, 0x42, 0xd6, 0xd3, 0xb4, 0x99, 0x75, 0xf2, 0xbf, 0xdd, 0x22, 0xe0, 0x26, 0xa8, 0x05, 0x33, 0x14, 0x4c, 0x05, 0x30, 0x83, 0x00, 0x00, 0x16, 0xdf, 0xc0, 0xf9, 0xe1, 0xe7, 0xee, 0xa8, 0x41, 0x03, 0xdf, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x21, 0x14, 0x6b, 0x55, 0xd1, 0x02, 0x37, 0xac, 0xba, 0x87, 0x00, 0xe8, 0x12, 0x7a, 0xa6, 0xa6, 0x0f, 0xc6, 0xa0, 0x42, 0xb7, 0xec, 0xf0, 0x84, 0x02, 0x79, 0x2c, 0xe6, 0xa9, 0x23, 0x00, 0x69, 0x2e, 0x2c, 0xba, 0xb2, 0x34, 0xce, 0x25, 0x3c, 0xbe, 0x1a, 0xdb, 0xb9, 0x7b, 0x42, 0x0a, 0x6d, 0xcf, 0x42, 0x7a, 0x91, 0xff, 0xbb, 0x70, 0x6d, 0x55, 0xc1, 0xc8, 0x8d, 0x2d, 0xb1, 0x20, 0xa5, 0x02, 0xe0, 0x80, 0x01, 0x4c, 0x01, 0x81, 0x9a, 0x02, 0x20, 0x00, 0x78, 0x71, 0xa4, 0x20, 0x83, 0xe7, 0xe6, 0x40, 0xbf}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x25, 0x1d, 0x86, 0x8b, 0x13, 0x00, 0x80, 0x00, 0x04, 0x05, 0x86, 0x6d, 0xdb, 0xff, 0xe2, 0x83, 0xfd, 0xb4, 0xfa, 0xed, 0xd3, 0x94, 0xed, 0xa4, 0x80, 0xef, 0x04, 0x86, 0xd0, 0xdb, 0x7e, 0x2c, 0xe2, 0xf3, 0xeb, 0xa9, 0xc2, 0x6e, 0x22, 0x7d, 0x16, 0x0b, 0x2b, 0x01, 0x14, 0x16, 0x9a, 0xfa, 0x84, 0xfa, 0x9e, 0x1a, 0xf4, 0x28, 0xe4, 0xfd, 0xfd, 0x8f, 0x27, 0xc9, 0x15, 0xe6, 0x82, 0xc4, 0x30, 0x94, 0xa3, 0x29, 0x49, 0x04, 0x36, 0x80, 0xc4, 0x20, 0x80, 0x00, 0x00, 0x2e, 0xeb, 0xde, 0x2b, 0xe9, 0x4a, 0x42, 0x67, 0xb5, 0x89, 0x8a, 0xaa, 0x56, 0x20, 0x25, 0x33, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x91, 0x8e, 0x44, 0x61, 0xa1, 0x44, 0xc5, 0x37, 0xc0, 0xb0, 0x2c, 0x03, 0x86, 0x82, 0x17, 0xb1, 0xba, 0x82, 0x8c, 0x7d, 0x8b, 0x8c, 0x4d, 0x42, 0x51, 0x78, 0xdc, 0x48, 0x08, 0xf1, 0xf4, 0x58, 0x3a, 0x7e, 0xdc, 0xcc, 0xe7, 0x8c, 0x40, 0xb3, 0x83, 0x8c, 0x5b, 0x5f, 0x05, 0x16, 0x82, 0x48, 0xa5, 0xfd, 0xd3, 0xb1, 0xbd, 0x7a, 0xbb, 0xd3, 0xd8, 0x6a, 0x58, 0x7f, 0x19, 0xb3, 0xc2, 0x94, 0x13, 0xcd, 0x30, 0x89, 0xc3, 0x27, 0xe1, 0xb2, 0xb9, 0x81, 0xa2, 0x20, 0x14, 0x70, 0x55, 0x40, 0x1c, 0x42, 0x08, 0x02, 0x18, 0x00, 0x1a, 0xcf, 0x02, 0x0f, 0xf2, 0x9e, 0xdd, 0x0d, 0x70, 0x4b, 0xfb, 0x22, 0x9a, 0xa9, 0xe9, 0x80, 0x32, 0x13, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x25, 0x89, 0x9e, 0x88, 0x11, 0x00, 0x80, 0x00, 0x02, 0xcd, 0x00, 0xd1, 0x6e, 0x87, 0xef, 0xa8, 0x25, 0xf4, 0xec, 0x1f, 0xff, 0xc6, 0x97, 0xe5, 0xea, 0x47, 0x20, 0x4b, 0x78, 0x1b, 0x83, 0x0d, 0x2e, 0xa2, 0x44, 0x98, 0xc8, 0x64, 0xe8, 0xd1, 0x50, 0x91, 0x20, 0xf6, 0xc2, 0xc9, 0x86, 0x5c, 0xf6, 0x95, 0xa9, 0x9d, 0x40, 0xea, 0x61, 0x48, 0x5a, 0xcf, 0xd3, 0xcd, 0xa4, 0xdc, 0x59, 0x7d, 0xa2, 0x45, 0x52, 0xe5, 0xd1, 0x15, 0x98, 0x28, 0xe1, 0xff, 0x3d, 0x38, 0x2e, 0xa4, 0x82, 0x09, 0x80, 0xa2, 0x10, 0x68, 0x04, 0x00, 0xb9, 0xdd, 0x1d, 0x45, 0x58, 0x60, 0x30, 0x57, 0x7e, 0x37}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x09, 0x8a, 0x92, 0x12, 0x00, 0x6a, 0x8a, 0x00, 0xb0, 0x70, 0x5c, 0x08, 0x79, 0xc0, 0xf1, 0xc1, 0xe6, 0x5a, 0xd0, 0x4b, 0x47, 0xa2, 0xa9, 0x8c, 0x52, 0xe8, 0x76, 0xa3, 0xd9, 0x33, 0x33, 0x95, 0xae, 0x7d, 0xaa, 0x17, 0xcf, 0x49, 0x80, 0x98, 0xca, 0xa1, 0x14, 0x9a, 0xde, 0x8a, 0x89, 0x77, 0x16, 0x8f, 0x63, 0x0e, 0xb7, 0xd1, 0x44, 0xa1, 0xcb, 0xca, 0xb0, 0x8d, 0x41, 0x01, 0x60, 0x49, 0xad, 0xa4, 0x99, 0xb7, 0xba, 0xab, 0x01, 0x48, 0x00, 0x53, 0x40, 0xc5, 0x60, 0xf4, 0x20, 0xb0, 0xc5, 0xc0, 0x87, 0x9c, 0x0f, 0x1c, 0xbb, 0x5e, 0xdc, 0xc4, 0x5a, 0xb4, 0x0e, 0xe0, 0x32, 0xc3, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x15, 0xcc, 0x8b, 0x22, 0x88, 0x80, 0x13, 0x24, 0x06, 0x40, 0x58, 0x02, 0x78, 0x95, 0x49, 0x5d, 0x8e, 0xfb, 0x2d, 0x99, 0x03, 0xda, 0x90, 0xbd, 0x89, 0x35, 0x52, 0xcc, 0x46, 0x95, 0xb6, 0xce, 0x64, 0x40, 0xb3, 0xda, 0x3b, 0xff, 0xdb, 0xe1, 0x37, 0xe6, 0xbf, 0x63, 0xe2, 0xf0, 0xad, 0x0b, 0xda, 0xeb, 0xa0, 0x36, 0x3a, 0x41, 0x5c, 0x82, 0x85, 0xbc, 0xb6, 0x84, 0x06, 0xbb, 0x08, 0x90, 0xde, 0x3e, 0x6e, 0x0e, 0x93, 0x7a, 0x22, 0x00, 0x14, 0x90, 0x31, 0x30, 0x50, 0x03, 0xa0, 0x9f, 0xbf, 0x40, 0xb0, 0x55, 0x02, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x20, 0x90, 0xa9, 0x00, 0x90, 0x40, 0x40, 0x0b, 0x14, 0x04, 0x50, 0x07, 0xd5, 0xc0, 0xcd, 0x79, 0x18, 0x26, 0x95, 0x59, 0xcd, 0x9e, 0x18, 0x73, 0xcb, 0x22, 0x05, 0xae, 0x3a, 0x7b, 0xb6, 0x50, 0x73, 0x61, 0xb3, 0xe4, 0xc5, 0x75, 0xe9, 0xd3, 0xbe, 0x3d, 0xf9, 0x57, 0x2f, 0xaa, 0x7b, 0xba, 0x72, 0x22, 0x12, 0x22, 0x71, 0xdc, 0xc5, 0x64, 0x6c, 0x6d, 0x03, 0x17, 0x5a, 0xbd, 0x5e, 0x64, 0x05, 0x53, 0xdc, 0x25, 0x2a, 0xd5, 0x18, 0x69, 0x40, 0xf6, 0xce, 0xb4, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x1d, 0x10, 0xc3, 0x42, 0x89, 0x00, 0x40, 0x00, 0x00, 0x00, 0x03, 0x36, 0x95, 0xae, 0xf9, 0x30, 0x42, 0xed, 0x1a, 0x54, 0x51, 0x09, 0xda, 0xf7, 0x7b, 0x88, 0x28, 0xf4, 0xf6, 0xc8, 0x7a, 0x30, 0x9b, 0x07, 0x8e, 0xf9, 0xce, 0x79, 0xcf, 0x7a, 0x82, 0x0e, 0x47, 0xcf, 0x86, 0x3d, 0x07, 0x4c, 0x21, 0x43, 0x6d, 0x7c, 0xac, 0x95, 0xfc, 0xf6, 0xb7, 0xdc, 0x9a, 0x55, 0x97, 0x57, 0x9e, 0x10, 0x04, 0xec, 0xc8, 0x9d, 0x62, 0x9c, 0x2c, 0xa6, 0x8c, 0x14, 0xe9, 0xe7, 0xd8, 0x89, 0x05, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x15, 0x5c, 0x68, 0x01, 0x31, 0x35, 0x59, 0x71, 0x52, 0x14, 0xae, 0x05, 0x9e, 0xdc, 0x83, 0xa2, 0x11, 0x26, 0x60, 0x1c, 0xbe, 0x72, 0x2f, 0x9f, 0xe3, 0x95, 0x53, 0x4b, 0x0e, 0xe1, 0x3d, 0xa5, 0x71, 0xd1, 0x3f, 0x3f, 0x03, 0x97, 0x89, 0xbf, 0x8e, 0x89, 0xed, 0x8b, 0xc6, 0xe7, 0xc0, 0xec, 0xd7, 0x5b, 0x79, 0xff, 0x73, 0xf7, 0x2e, 0x65, 0xf8, 0x2d, 0x41, 0x44, 0x50, 0x0e, 0x08, 0x5f, 0xa5, 0x68, 0xda, 0x95, 0xe4, 0x30, 0xd2, 0x58, 0x44, 0xb7, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x21, 0x06, 0xe8, 0x15, 0x01, 0x80, 0xef, 0x54, 0x91, 0x61, 0xc3, 0x50, 0x00, 0x33, 0xd3, 0xd7, 0x52, 0x1b, 0x2c, 0xed, 0x3b, 0x20, 0x4f, 0x71, 0xc0, 0x55, 0x8f, 0x28, 0x34, 0xcf, 0x76, 0x56, 0xa8, 0xa1, 0x3a, 0x50, 0x6a, 0x79, 0xf2, 0x39, 0x70, 0x6e, 0xf5, 0x64, 0x74, 0x52, 0x09, 0xf3, 0xeb, 0x80, 0x36, 0xe3, 0xa0, 0x4c, 0x5a, 0xe0, 0x17, 0x5f, 0xe8, 0x4c, 0x23, 0x30, 0x0a, 0x67, 0x38, 0x59, 0x61, 0x82, 0x3d, 0x7f, 0xdf, 0xd4, 0x35, 0x37, 0x91, 0x37, 0xc5, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x63, 0x19, 0xda, 0x2a, 0x37, 0xa5, 0x80, 0x20, 0xd0, 0x74, 0x6b, 0x81, 0x67, 0x93, 0xac, 0x66, 0x54, 0x7e, 0x52, 0xb8, 0xe5, 0xfc, 0x5a, 0x02, 0x54, 0x89, 0x27, 0x4a, 0x4c, 0xa0, 0xbd, 0x85, 0x78, 0x9e, 0x8a, 0x58, 0x76, 0xb3, 0x55, 0xb3, 0xbe, 0x98, 0x75, 0x76, 0x66, 0xa7, 0xcb, 0x57, 0xda, 0x69, 0xbf, 0xff, 0xed, 0x8b, 0xd8, 0xc5, 0x29, 0x83, 0x1c, 0x95, 0x48, 0x9b, 0x48, 0x42, 0x51, 0x94, 0x4d, 0x00, 0x54, 0xba, 0x82, 0x60, 0x0b, 0x17, 0xd9, 0xf2, 0x86, 0xb8, 0x1a, 0x3b, 0x44, 0xb8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0x1d, 0xd4, 0xc2, 0x15, 0x02, 0x56, 0x2c, 0x00, 0x59, 0xe4, 0x9a, 0x1b, 0xd6, 0xf9, 0xa1, 0xa9, 0x3c, 0x65, 0xef, 0xde, 0x30, 0x2c, 0x3e, 0xce, 0x22, 0x6a, 0x12, 0x37, 0xcc, 0xab, 0x15, 0xb2, 0x83, 0x3f, 0x95, 0x2c, 0xbb, 0x84, 0x5d, 0xdf, 0x0a, 0x0f, 0x6f, 0xf7, 0xe0, 0x81, 0x02, 0xd1, 0xf7, 0xa7, 0x06, 0x3e, 0xd8, 0x54, 0xaa, 0x88, 0x58, 0x2b, 0x25, 0x43, 0x86, 0x0e, 0x42, 0x9d, 0xa4, 0x92, 0x09, 0x81, 0x43, 0x64, 0x0c, 0x08, 0x43, 0xd8, 0x4e, 0x62, 0x9d, 0xe8, 0xe9, 0x00, 0x6d, 0xaa, 0xc0, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0xd8, 0x4a, 0x02, 0x00, 0x0d, 0xd8, 0xab, 0xb8, 0x3a, 0x04, 0xfc, 0x5b, 0x47, 0x4b, 0xc7, 0x4e, 0xf9, 0xe4, 0xdc, 0x4e, 0xb7, 0xb5, 0xed, 0xa1, 0x4b, 0xa2, 0xeb, 0x02, 0x8b, 0x68, 0xc2, 0x38, 0x1a, 0x4a, 0xe8, 0x38, 0xbb, 0x15, 0xc0, 0x4d, 0x78, 0x4c, 0xe9, 0x78, 0xc5, 0xb7, 0x0d, 0x46, 0x34, 0x0c, 0x32, 0x46, 0x0e, 0x7c, 0x4b, 0xa3, 0x16, 0x64, 0x81, 0x0a, 0x73, 0x9d, 0x6c, 0x2a, 0xd4, 0xe1, 0x61, 0x80, 0x3e, 0xdc, 0x0d, 0x01, 0xae}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x1d, 0x0e, 0xa3, 0x80, 0x9a, 0xc0, 0x68, 0x1b, 0x05, 0x8b, 0xe0, 0x80, 0x2c, 0x3b, 0xb0, 0x95, 0x82, 0x89, 0x52, 0x05, 0x22, 0x75, 0x0f, 0x0c, 0x50, 0x5a, 0xf6, 0x0c, 0x52, 0xf6, 0x36, 0x1a, 0x70, 0xd5, 0x7a, 0x63, 0x72, 0xfe, 0x96, 0xd7, 0xa1, 0xe0, 0x83, 0x49, 0x84, 0x36, 0xfc, 0x3c, 0xfd, 0x1b, 0xea, 0x39, 0x74, 0xd2, 0xcb, 0x93, 0x1c, 0xf6, 0x8b, 0x75, 0xb6, 0xd1, 0xd3, 0xaa, 0x40, 0xaa, 0xad, 0xb8, 0x02, 0x20, 0x02, 0xa8, 0xce, 0x16, 0x46, 0xc0, 0xf4, 0xad, 0x6f, 0x1a, 0xf4, 0x6f, 0xb8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x1d, 0xd8, 0x2a, 0x00, 0x0a, 0x00, 0x69, 0xd1, 0xc0, 0x3b, 0x6b, 0xbc, 0x05, 0x48, 0x7c, 0xd9, 0x75, 0x67, 0x07, 0x1c, 0xa7, 0x3f, 0x05, 0xb2, 0xc0, 0xdf, 0x80, 0x92, 0x34, 0x4a, 0xe3, 0x60, 0xcf, 0xa7, 0xdb, 0x9a, 0xc3, 0xcd, 0x36, 0xf8, 0xda, 0x13, 0x5a, 0x9c, 0x3b, 0x5e, 0x67, 0xa9, 0x77, 0x06, 0x22, 0x28, 0x12, 0xb8, 0x50, 0x26, 0x1b, 0x01, 0x07, 0x72, 0xe0, 0x52, 0xc1, 0xc2, 0xc1, 0x6a, 0x0a, 0x4f, 0x32, 0x23, 0x9c, 0xa7, 0xe7, 0x84, 0xc1, 0xdf, 0x99, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x1d, 0x5a, 0x29, 0x00, 0x86, 0xc0, 0xcb, 0x38, 0x70, 0x7b, 0x03, 0xdb, 0x6d, 0xe5, 0xcb, 0xf8, 0x27, 0x1a, 0xc4, 0x86, 0x19, 0x9c, 0xc1, 0x50, 0x8b, 0x99, 0xc6, 0x4b, 0x4a, 0xc5, 0x70, 0x1f, 0x2e, 0x52, 0xef, 0xfc, 0x62, 0xbd, 0x3d, 0x58, 0x6f, 0xfb, 0x62, 0x6b, 0xd3, 0xc2, 0x4e, 0xd9, 0x54, 0x90, 0x4d, 0x6b, 0xa3, 0x21, 0x23, 0x01, 0x20, 0x44, 0xbe, 0x1a, 0x01, 0x28, 0xb0, 0x81, 0x3f, 0x64, 0x34, 0x83, 0xc4, 0x20, 0x00, 0xb0, 0xcb, 0x9e, 0x3f, 0x72, 0x74, 0x01, 0x41, 0xe4, 0x27, 0xe2, 0x04, 0x7c, 0x49, 0x81, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x1c, 0xd1, 0x01, 0x52, 0x0a, 0x40, 0x0e, 0x78, 0x29, 0x4a, 0xd3, 0x81, 0xd7, 0x3e, 0xc0, 0x67, 0xb6, 0x56, 0x5d, 0xa5, 0x83, 0x03, 0x2b, 0xf4, 0xa2, 0x22, 0x65, 0x92, 0x4b, 0x8e, 0x50, 0xba, 0x46, 0xc4, 0xf9, 0xb3, 0xfd, 0x0a, 0xe9, 0xec, 0x9a, 0x57, 0x9e, 0x8a, 0xfb, 0xad, 0x5e, 0xc9, 0x3a, 0xbb, 0x70, 0xca, 0x57, 0x79, 0xaf, 0x64, 0x66, 0x30, 0xe7, 0xf0, 0xdf, 0x54, 0x00, 0x99, 0x06, 0xe8, 0x81, 0x2c, 0xe0, 0x15, 0x46, 0xd0, 0x83, 0x40, 0x16, 0x0f, 0x79, 0xfa, 0x23, 0xba, 0x0b, 0x55, 0x49, 0x43, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0x24, 0x8a, 0xc5, 0x35, 0x21, 0x62, 0xe0, 0xa8, 0x90, 0x03, 0x80, 0x58, 0x58, 0xc7, 0xd4, 0xf7, 0x44, 0x2f, 0xe1, 0xef, 0x92, 0x19, 0x77, 0x18, 0x0a, 0x73, 0x9e, 0xb5, 0xbf, 0x3e, 0x62, 0x88, 0xf6, 0x62, 0xee, 0xeb, 0xc2, 0xdc, 0x24, 0x9c, 0x4a, 0x85, 0x4a, 0x27, 0xa6, 0x90, 0xc1, 0x19, 0x1f, 0xc9, 0x4e, 0x7b, 0xbc, 0xda, 0xee, 0x8d, 0xb0, 0x9c, 0x2d, 0x4d, 0xc5, 0x65, 0xcc, 0xde, 0xc2, 0x80, 0x5c, 0x8d, 0x3b, 0x76, 0x88, 0x16, 0x88, 0x0a, 0x28, 0x28, 0xac, 0x1a, 0x00, 0x00, 0x05, 0xed, 0x7e, 0xfe, 0x0c, 0x71, 0xaa, 0xce, 0xd1, 0xc3, 0x6d, 0xf1, 0x9b, 0x2f, 0x10, 0xf9, 0x47, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x1d, 0xa1, 0x1c, 0x27, 0x00, 0x00, 0x16, 0x06, 0x81, 0x24, 0x70, 0x36, 0xf6, 0xd5, 0xcb, 0x2c, 0x95, 0x32, 0xee, 0x72, 0x29, 0x8e, 0x28, 0xe6, 0x8d, 0x95, 0x42, 0x63, 0xd4, 0xab, 0x66, 0xf5, 0x71, 0xb1, 0x9b, 0xe0, 0xe5, 0x57, 0xbf, 0xfd, 0x33, 0x0e, 0x3d, 0xd0, 0x39, 0xf7, 0xaf, 0x9c, 0x67, 0x5e, 0xe4, 0x7d, 0x63, 0x19, 0xf9, 0x0c, 0x5b, 0xca, 0x17, 0xbe, 0xc6, 0x4b, 0xb5, 0xf9, 0xc1, 0x4e, 0xf1, 0x7e, 0x1c, 0x3f, 0x9c, 0xea, 0xac, 0xa3, 0xb4, 0x00, 0xa8, 0x72, 0x0c, 0x01, 0x2d, 0x34, 0x10, 0x00, 0x0b, 0xd9, 0xd1, 0xeb, 0x97, 0xdd, 0x86, 0x58, 0xdb, 0x45, 0x2f, 0x80, 0x1f, 0x7e, 0x80, 0x1b, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x1d, 0x14, 0x4a, 0x11, 0x38, 0xa4, 0x20, 0xb2, 0x99, 0xaa, 0x96, 0x00, 0x15, 0x97, 0xe1, 0xf6, 0x9a, 0x8a, 0xfa, 0x8d, 0x12, 0x9a, 0x9e, 0xd4, 0xa9, 0x74, 0xd7, 0xe3, 0x4e, 0x8f, 0x8f, 0x6e, 0x06, 0x6b, 0xaf, 0x3a, 0x5e, 0xe1, 0x9d, 0xb4, 0x30, 0xc3, 0xfe, 0x2e, 0x72, 0xc1, 0x2c, 0xe5, 0x74, 0x3b, 0xda, 0xa8, 0xff, 0x81, 0xa8, 0x23, 0xcc, 0x77, 0x87, 0x92, 0xe2, 0x25, 0x71, 0x24, 0xe9, 0x3e, 0x65, 0x70, 0x69, 0xcc, 0x02, 0xc2, 0x75, 0x40, 0x0a, 0x29, 0x48, 0x2c, 0x42, 0x08, 0x00, 0x06, 0x7f, 0x37, 0xde, 0xf6, 0xe4, 0x70, 0x75, 0x30, 0xc7, 0x47, 0x7f, 0x45, 0x05, 0xd2, 0xee}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x2d, 0x1d, 0x16, 0x25, 0x42, 0x08, 0x82, 0xc0, 0x00, 0x04, 0xa2, 0xc6, 0x0f, 0xda, 0xb3, 0xa5, 0x1e, 0x0d, 0x4d, 0xe8, 0x1c, 0xdc, 0x44, 0x38, 0xc9, 0xa4, 0xb3, 0x11, 0x88, 0xb1, 0xd2, 0xda, 0xef, 0xe9, 0xcc, 0xe1, 0x41, 0x17, 0xbc, 0x07, 0xc6, 0xb9, 0xd9, 0x98, 0x13, 0xf0, 0xd6, 0x8b, 0xf7, 0xdb, 0x78, 0x2a, 0x7e, 0xfc, 0x53, 0xad, 0x38, 0xbf, 0xcf, 0xe7, 0xc7, 0x14, 0x85, 0x04, 0x11, 0xd5, 0x01, 0xf6, 0x32, 0x90, 0x4d, 0xda, 0x78, 0x99, 0x71, 0x11, 0xc1, 0xa0, 0x20, 0x05, 0x18, 0x06, 0x04, 0xa8, 0x04, 0x88, 0x41, 0x01, 0x2c, 0xa8, 0x1f, 0x6a, 0xd0, 0xb7, 0xc3, 0xbf, 0xdf, 0x3f, 0x42, 0xce, 0xa5, 0x46, 0x66, 0x10, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x1c, 0xa0, 0xc3, 0x51, 0x00, 0x40, 0x5b, 0x00, 0x00, 0xb0, 0x34, 0xf7, 0x93, 0x5e, 0x17, 0x18, 0xc1, 0x4c, 0x30, 0x09, 0x07, 0xc9, 0x04, 0x44, 0x1e, 0x2c, 0x51, 0xd1, 0x30, 0x07, 0x2f, 0x10, 0xde, 0x67, 0xdc, 0x39, 0xa4, 0x5b, 0x05, 0x09, 0x51, 0x29, 0xd0, 0x12, 0xf0, 0x06, 0xd2, 0x0a, 0x02, 0xa8, 0x48, 0x54, 0xd6, 0x12, 0xf6, 0x5c, 0x99, 0x57, 0x0d, 0xaa, 0x4b, 0xae, 0xb0, 0x0e, 0x82, 0x9c, 0x21, 0xc6, 0xf8, 0xf4, 0xdf, 0x42, 0x59, 0x65, 0x13, 0x4b, 0xb6, 0x42, 0xad, 0x5a, 0x10, 0x0f, 0x65, 0x80, 0x0a, 0x06, 0x69, 0xee, 0x9e, 0xa1, 0xa2, 0xe2, 0x2c, 0x2e, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x1c, 0x94, 0x65, 0x41, 0x89, 0x00, 0x96, 0x0a, 0x01, 0x80, 0x02, 0x32, 0x1a, 0x8b, 0x4e, 0x4d, 0x18, 0x57, 0x0e, 0xe5, 0x20, 0xfa, 0x01, 0x3c, 0xfe, 0xb1, 0x47, 0x38, 0xc5, 0x40, 0xe6, 0xd9, 0x7a, 0x3c, 0xf3, 0xdf, 0x3f, 0xd9, 0x96, 0x56, 0x57, 0x1a, 0x18, 0x19, 0xc9, 0xb9, 0x49, 0xaa, 0xa5, 0x35, 0x49, 0xec, 0xd2, 0x1c, 0xdd, 0x97, 0x26, 0xc3, 0xf4, 0x6d, 0x62, 0xca, 0x02, 0xa0, 0x05, 0x3c, 0x08, 0x50, 0x13, 0x40, 0x16, 0x1d, 0x23, 0xc0, 0x00, 0x0c, 0x7c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x1c, 0x4e, 0xab, 0x12, 0x12, 0xec, 0x14, 0xc1, 0x60, 0x05, 0x85, 0xc7, 0x37, 0x5a, 0xcd, 0x6d, 0x3d, 0x57, 0x67, 0x56, 0x4a, 0x58, 0xd2, 0x97, 0xc3, 0x64, 0xb1, 0xb1, 0xd3, 0xb9, 0x93, 0xe5, 0x9c, 0xc9, 0x3b, 0xc4, 0xd5, 0xaa, 0xe8, 0xfb, 0x4d, 0xcd, 0x95, 0x74, 0x24, 0x59, 0x51, 0x6b, 0xa8, 0xab, 0xc2, 0x97, 0x2a, 0xc7, 0x09, 0x9c, 0x6f, 0xb3, 0x37, 0x60, 0xa7, 0x8f, 0x7a, 0x94, 0x59, 0x10, 0xd7, 0xac, 0x00, 0xa2, 0x94, 0x85, 0x00, 0x00, 0xf7, 0xc8, 0x02, 0x3a, 0x12, 0x57, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x2d, 0x91, 0x14, 0xaa, 0x12, 0x80, 0x0a, 0x28, 0x48, 0x80, 0xb0, 0xaf, 0xba, 0x0d, 0xfb, 0x22, 0x65, 0xe6, 0xcc, 0xf7, 0x41, 0x07, 0xe3, 0x3f, 0xa5, 0xd2, 0x96, 0x52, 0x4a, 0x79, 0x2c, 0xf6, 0x83, 0x3b, 0xf0, 0x3f, 0xe6, 0x6f, 0x33, 0xbe, 0xbb, 0x5d, 0x0e, 0xc5, 0x79, 0xf9, 0x74, 0xee, 0x64, 0x35, 0x0b, 0x04, 0x14, 0xa2, 0xd9, 0x51, 0x30, 0xbd, 0xd7, 0x3c, 0x15, 0xce, 0xeb, 0xd5, 0xa4, 0xa0, 0xb8, 0x1b, 0x2d, 0x10, 0x0a, 0x05, 0x58, 0x3c, 0x42, 0x02, 0x02, 0x00, 0x01, 0xdf, 0xfd, 0x48, 0xf7, 0xf9, 0xfe, 0xec, 0xc8, 0x76, 0x5e, 0x82, 0x27}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x9e, 0x23, 0x41, 0x89, 0x0d, 0xde, 0xfa, 0xe0, 0x0c, 0x01, 0x02, 0xc0, 0x22, 0xa5, 0x76, 0x36, 0xa3, 0x61, 0x5f, 0x81, 0x7d, 0xa6, 0xd2, 0x82, 0xc5, 0xe4, 0xe6, 0x31, 0x08, 0x02, 0x67, 0x3c, 0x4a, 0x01, 0x8e, 0xbe, 0x76, 0x9a, 0x13, 0x18, 0x09, 0x5f, 0x5a, 0x1a, 0x8c, 0x8a, 0xac, 0xc1, 0x00, 0xb4, 0x65, 0x36, 0xd7, 0x4f, 0xb4, 0x7b, 0x47, 0x86, 0x30, 0x9c, 0x55, 0xe2, 0xc0, 0xca, 0xab, 0x61, 0x60, 0x09, 0xe9, 0x04, 0xa7, 0xbe, 0xe0, 0x14, 0x6a, 0xa0, 0x29, 0x84, 0x1a, 0x40, 0xb5, 0x01, 0xf2, 0xeb, 0xfb, 0xb0, 0x05, 0x62, 0x04, 0x27, 0xe4, 0x78}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x19, 0x0c, 0x4a, 0x60, 0xa0, 0x84, 0x81, 0x0e, 0x81, 0xb0, 0x00, 0x59, 0x70, 0x29, 0xc3, 0x8e, 0x48, 0x1c, 0xbf, 0x49, 0x73, 0xaa, 0x8c, 0x90, 0xd2, 0x9a, 0xc9, 0x00, 0x69, 0xb6, 0x29, 0x89, 0x09, 0xc6, 0xd0, 0x04, 0x17, 0x86, 0xfc, 0x89, 0x94, 0xb8, 0x13, 0xa4, 0x83, 0x0c, 0xea, 0x53, 0xd1, 0xd6, 0xbe, 0x10, 0x76, 0x26, 0x91, 0x47, 0xb6, 0xe2, 0x1f, 0x2f, 0x58, 0xa0, 0x8f, 0x11, 0x83, 0x99, 0xc0, 0x88, 0x24, 0x00, 0x29, 0x14, 0x82, 0xd0, 0x60, 0x81, 0x00, 0x17, 0x02, 0x9c, 0x38, 0xe4, 0x81, 0xcf, 0xa8, 0x3a, 0xfc, 0x03, 0xcb, 0xb0, 0x47, 0x7c, 0xe9, 0xaf, 0x4e, 0xe1, 0xfb, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x18, 0xa2, 0xc2, 0x32, 0x00, 0xe8, 0x06, 0x03, 0x22, 0x20, 0x37, 0xda, 0xe8, 0x11, 0x44, 0x26, 0x8e, 0x27, 0x29, 0x39, 0xdb, 0x6a, 0xbd, 0x79, 0xcc, 0xa1, 0xd5, 0x90, 0xde, 0x07, 0x9c, 0xd8, 0x31, 0x50, 0x28, 0xee, 0x4c, 0xb0, 0x24, 0xee, 0x7d, 0x01, 0xbe, 0x69, 0x32, 0xfc, 0x93, 0x3c, 0x90, 0x4c, 0xef, 0x8a, 0x80, 0x6b, 0xa9, 0x98, 0x4c, 0xe0, 0xb6, 0xef, 0xb7, 0xa1, 0x2e, 0x0f, 0xb0, 0xa9, 0xa5, 0x4c, 0x8d, 0xaa, 0x62, 0xa0, 0x02, 0x8d, 0xd4, 0x13, 0x00, 0x01, 0xec, 0x7a, 0xc0, 0xd4, 0xe4, 0xe1, 0xb1, 0x26, 0x2c, 0x9c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x5b, 0x1c, 0x9e, 0xa4, 0x11, 0x83, 0xa0, 0x10, 0x14, 0xe4, 0x00, 0xe5, 0xd9, 0x53, 0x73, 0x11, 0xd8, 0xcd, 0x6e, 0xcd, 0xe9, 0x55, 0x89, 0x87, 0x12, 0x35, 0xe9, 0x07, 0xe2, 0x0a, 0xe7, 0x83, 0x70, 0xda, 0x83, 0xe2, 0x9e, 0xa0, 0x78, 0x18, 0x97, 0x80, 0xcb, 0x3a, 0xbe, 0x58, 0xdc, 0xc6, 0x4b, 0x8b, 0xc7, 0x0e, 0x3e, 0xd4, 0x4e, 0xf3, 0xb1, 0xa3, 0x2d, 0x2e, 0x61, 0xba, 0x0c, 0xc2, 0x60, 0x01, 0x44, 0xab, 0x09, 0x00, 0x00, 0x7f, 0xb7, 0x8f, 0xfb, 0x0f, 0x3d, 0x5f, 0xd1, 0x1d, 0x25, 0xe0, 0xb4, 0xdf}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x09, 0x18, 0x28, 0x41, 0x89, 0x00, 0x79, 0x58, 0x39, 0xa8, 0x60, 0x00, 0x76, 0xb7, 0x5e, 0x0f, 0x1f, 0x98, 0xcb, 0xef, 0x59, 0xeb, 0x8c, 0xa0, 0xa2, 0x22, 0x28, 0x20, 0x34, 0x6c, 0x62, 0x14, 0x20, 0x56, 0x48, 0x50, 0xa6, 0xdb, 0xa9, 0xaa, 0x94, 0x62, 0x0e, 0xee, 0x07, 0x1a, 0x00, 0xe1, 0xae, 0x6a, 0x7a, 0x06, 0xed, 0x79, 0x39, 0xee, 0x92, 0xdf, 0xae, 0xb8, 0x88, 0xae, 0x00, 0x51, 0xb9, 0xc0, 0xe2, 0x10, 0x70, 0x1a, 0x09, 0xf7, 0xe7, 0x65, 0xa0, 0x72, 0x34, 0x8c, 0xf4, 0x22, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x11, 0x8a, 0x74, 0x00, 0x06, 0xc0, 0x01, 0xd0, 0x30, 0xdb, 0x7d, 0x89, 0xfe, 0x1c, 0xe8, 0xe6, 0x2c, 0xd9, 0xde, 0xb7, 0xd4, 0x44, 0xbc, 0x1b, 0x51, 0xad, 0xf1, 0x2b, 0x66, 0x39, 0x33, 0x93, 0xbe, 0xba, 0xf0, 0xd1, 0x4e, 0x64, 0xe1, 0xc5, 0x7d, 0x2b, 0xc6, 0xdc, 0x3d, 0x87, 0x17, 0xbb, 0xcd, 0xeb, 0x34, 0x60, 0xac, 0x02, 0x39, 0xf0, 0xd0, 0x58, 0x4e, 0x00, 0x29, 0x9c, 0xc1, 0x70, 0x6c, 0x6f, 0xec, 0xfe, 0x56, 0x5d, 0x32, 0x5c, 0xb1, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0xa1, 0x18, 0x22, 0x21, 0x09, 0x40, 0x00, 0xa0, 0x80, 0x34, 0x11, 0xc3, 0x5f, 0xbc, 0xd0, 0x8e, 0xb0, 0x1f, 0xd1, 0x16, 0x52, 0x0f, 0x3d, 0x9f, 0x46, 0x74, 0xf8, 0x0b, 0x27, 0x58, 0x9a, 0x52, 0x2c, 0x3e, 0x51, 0xf4, 0xfa, 0x29, 0x56, 0x3e, 0x4f, 0x31, 0x9d, 0x5e, 0xd9, 0x6a, 0xb9, 0xa8, 0x1d, 0xae, 0xf8, 0xe0, 0x87, 0x02, 0xfe, 0xbe, 0x9e, 0xf0, 0x41, 0x19, 0x0a, 0x90, 0x0b, 0x80, 0x2a, 0x0d, 0x21, 0x40, 0x00, 0x3c, 0x70, 0x5b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x19, 0x60, 0x65, 0x01, 0x00, 0x85, 0x00, 0x58, 0x71, 0xb0, 0x99, 0xa1, 0xe7, 0xb7, 0xd2, 0x44, 0xa3, 0xc3, 0xad, 0x25, 0x3f, 0x11, 0x57, 0xd7, 0x9a, 0x6c, 0xb8, 0x26, 0x15, 0x92, 0x62, 0x4f, 0x6e, 0xb7, 0xf1, 0xe1, 0x2c, 0x8d, 0x59, 0x8c, 0x4f, 0x3c, 0x54, 0x6e, 0x0c, 0x82, 0xe8, 0xde, 0xae, 0x3a, 0x37, 0x5f, 0xe8, 0x3a, 0xc2, 0xe6, 0x3a, 0xa6, 0x05, 0x22, 0x40, 0xba, 0x9d, 0xd2, 0x14, 0x00, 0xd0, 0x6b, 0x79, 0xba, 0x8d, 0x2d, 0x8e, 0x31, 0x7a, 0x41, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x20, 0x8c, 0xc2, 0x35, 0x80, 0x80, 0x10, 0x06, 0x5a, 0x10, 0xd0, 0x66, 0xca, 0x7c, 0xdb, 0xc9, 0xbc, 0x1d, 0xc9, 0x04, 0xf9, 0xdf, 0x2d, 0x24, 0x08, 0x73, 0x82, 0xfd, 0x6e, 0x41, 0xa1, 0x37, 0x0d, 0xe2, 0xfb, 0xff, 0xcd, 0x10, 0x49, 0xcb, 0x8c, 0xe1, 0xbc, 0xbf, 0x0f, 0x0a, 0xc6, 0x9d, 0x6f, 0xf5, 0xdb, 0xbf, 0xf2, 0x7f, 0xfc, 0x7e, 0xe0, 0x9e, 0x0a, 0xe0, 0x11, 0x04, 0x54, 0xd6, 0x63, 0xd7, 0x8d, 0x60, 0x98, 0x2e, 0x00, 0x7c, 0x46, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x19, 0x64, 0x25, 0x00, 0x00, 0x2c, 0x74, 0x4d, 0x80, 0x50, 0x57, 0x56, 0x28, 0x05, 0xd5, 0x53, 0x3a, 0x13, 0xae, 0x97, 0x37, 0xd8, 0xdd, 0xda, 0x94, 0xa1, 0x10, 0xdc, 0x12, 0x9f, 0xad, 0x7d, 0x5d, 0xd0, 0xb2, 0x3b, 0x4e, 0xae, 0xda, 0xeb, 0xf9, 0xee, 0x3a, 0x97, 0x10, 0x4c, 0x5c, 0x8b, 0xc5, 0x4f, 0x7d, 0xdf, 0xeb, 0xe9, 0x8e, 0x9e, 0x99, 0x05, 0x8e, 0xd9, 0x26, 0x08, 0x04, 0xd8, 0xd1, 0x44, 0xb8, 0x02, 0xac, 0x86, 0x1a, 0x50, 0x77, 0xb6, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x1d, 0x60, 0x26, 0x00, 0x28, 0xf1, 0xd1, 0x00, 0xd7, 0x5c, 0x82, 0xbf, 0xd1, 0x0c, 0x62, 0xf0, 0x60, 0xfe, 0x28, 0x40, 0x6c, 0xde, 0x4a, 0x4c, 0x33, 0x39, 0x3b, 0x17, 0x92, 0x24, 0x33, 0x50, 0x59, 0x3e, 0xcb, 0xaf, 0x9c, 0xed, 0x94, 0xeb, 0x0b, 0xc6, 0xb5, 0xe8, 0xdb, 0x1d, 0x91, 0x75, 0x00, 0xb9, 0x2a, 0x19, 0x8d, 0xf3, 0xe5, 0x17, 0xd1, 0x22, 0x88, 0x5d, 0x50, 0xea, 0x60, 0x09, 0x59, 0x7b, 0x0b, 0xa2, 0x02, 0xac, 0xd0, 0x15, 0x05, 0x83, 0xf2, 0xd4, 0x30, 0x23, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x1d, 0x18, 0x2a, 0x5c, 0x5b, 0x81, 0xc8, 0x00, 0x71, 0x76, 0xec, 0x1e, 0xa8, 0xb3, 0xac, 0xc4, 0x17, 0x61, 0x78, 0x5b, 0x2d, 0xd5, 0x43, 0xf4, 0x2e, 0x80, 0xc1, 0x2b, 0x4a, 0x5d, 0x05, 0xdb, 0x77, 0xae, 0x4d, 0x87, 0xbf, 0x6c, 0x56, 0x51, 0x07, 0xf2, 0xfa, 0xed, 0x34, 0x27, 0x68, 0xa5, 0x6b, 0x73, 0xbd, 0x8b, 0xe8, 0x29, 0x5c, 0xb1, 0x23, 0x7c, 0x35, 0x75, 0x5c, 0x09, 0x00, 0x14, 0xae, 0xb0, 0x90, 0x00, 0x13, 0xdf, 0x69, 0x78, 0x7d, 0x2d, 0x7d, 0xa6, 0x8d, 0xd6, 0x32, 0x50, 0xc6, 0x9c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x18, 0xd0, 0xc5, 0x35, 0x00, 0x08, 0x02, 0xc1, 0x6d, 0x05, 0x43, 0x62, 0x56, 0x9e, 0x3d, 0xda, 0x6d, 0x60, 0xe3, 0xe4, 0xdb, 0xfa, 0x7e, 0x3f, 0x60, 0xd0, 0xb6, 0xce, 0x9e, 0x8c, 0x55, 0x29, 0x48, 0xeb, 0xf9, 0x74, 0x58, 0x88, 0x18, 0x44, 0x10, 0x16, 0x97, 0xb7, 0xa7, 0xfe, 0xf8, 0xf4, 0xbf, 0xa7, 0x47, 0xf6, 0x32, 0x2d, 0x97, 0x4a, 0x99, 0x25, 0xec, 0xe6, 0xa4, 0x02, 0x43, 0x00, 0x16, 0x14, 0xa8, 0x98, 0x05, 0x3a, 0xb4, 0x20, 0x58, 0x58, 0x01, 0xec, 0xe9, 0xf8, 0xd0, 0xee, 0x08, 0x00, 0x04, 0xea, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x1d, 0x58, 0x28, 0x01, 0x09, 0x21, 0x7a, 0xa7, 0x26, 0x2c, 0x0f, 0x3a, 0x09, 0x1b, 0x7f, 0x48, 0xab, 0x47, 0x2b, 0x9a, 0xf0, 0xf4, 0x90, 0x29, 0x0e, 0x85, 0x25, 0x5b, 0xa9, 0xc5, 0xac, 0x49, 0x81, 0x08, 0xc9, 0x7f, 0x13, 0xe3, 0x96, 0xf8, 0x4b, 0xef, 0xc3, 0xd7, 0xdd, 0xca, 0x74, 0x7e, 0x6b, 0x13, 0x5e, 0xc5, 0xc7, 0x7a, 0x40, 0x5e, 0x09, 0xbb, 0x57, 0x81, 0x5a, 0xd5, 0x48, 0x51, 0xa6, 0x80, 0x2e, 0xff, 0x46, 0x89, 0xe0, 0x01, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x25, 0xd8, 0x26, 0x01, 0x37, 0xab, 0x2e, 0xd1, 0xd8, 0x02, 0x56, 0x9d, 0x05, 0x04, 0x99, 0x4b, 0x6a, 0xc5, 0x1b, 0xe6, 0xa2, 0xba, 0x81, 0x0d, 0xc2, 0x47, 0x27, 0x8c, 0x05, 0x34, 0x8b, 0x16, 0x94, 0x15, 0x6b, 0xab, 0xbe, 0x3c, 0xb3, 0xef, 0x62, 0xf6, 0xec, 0xb9, 0xe7, 0x61, 0xe0, 0x4b, 0x56, 0x8c, 0xc4, 0x94, 0x4f, 0x64, 0x3a, 0x2c, 0x21, 0x69, 0x9d, 0x53, 0x09, 0x9c, 0xab, 0xc1, 0x1a, 0x56, 0xa9, 0x82, 0xe0, 0x07, 0xd7, 0x51, 0x24, 0x10, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x19, 0x16, 0xa4, 0x14, 0x01, 0x5d, 0x00, 0x00, 0xd3, 0x4b, 0x05, 0x4b, 0xdb, 0x1a, 0xba, 0x4f, 0xb5, 0xf8, 0xc7, 0x0b, 0x1c, 0xf6, 0x99, 0x1d, 0x29, 0xb3, 0x32, 0xf8, 0x58, 0x66, 0xce, 0xf7, 0xfe, 0x90, 0x3f, 0xdd, 0x15, 0x4a, 0x6b, 0xf8, 0x4b, 0xec, 0xcb, 0xea, 0xd6, 0x09, 0xad, 0x34, 0xca, 0x33, 0x29, 0x73, 0x4a, 0x4a, 0xd9, 0x4f, 0x55, 0xf1, 0x7d, 0x88, 0x04, 0xd4, 0x54, 0xa7, 0xeb, 0x33, 0x49, 0x10, 0x15, 0x2c, 0x33, 0x30, 0x51, 0x2c, 0x01, 0x97, 0x92, 0xf9, 0x34, 0x31, 0xe2, 0x14, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x2d, 0x99, 0x1a, 0x6a, 0x00, 0x00, 0x0d, 0x08, 0x74, 0x1d, 0x2f, 0x05, 0x0d, 0x49, 0xa1, 0xa1, 0xbe, 0xc3, 0x97, 0xd8, 0x60, 0xb4, 0x84, 0x71, 0xcd, 0x04, 0x8f, 0x99, 0xee, 0xae, 0xb2, 0xa0, 0xb2, 0x61, 0xce, 0x65, 0xc1, 0xd3, 0x68, 0x2f, 0xfa, 0x57, 0xe3, 0x62, 0xa4, 0x14, 0xff, 0xe8, 0x52, 0xfe, 0x66, 0xb3, 0xb4, 0xd5, 0xb4, 0x34, 0x22, 0x48, 0xb9, 0x30, 0xeb, 0xd2, 0x31, 0x14, 0x45, 0x70, 0x29, 0xd5, 0x41, 0x30, 0x00, 0x1e, 0xaf, 0xbb, 0xd5, 0xac, 0xd1, 0xad, 0x28, 0x21, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x1d, 0x9d, 0x88, 0x86, 0x51, 0x0a, 0x80, 0x00, 0x00, 0xb0, 0x74, 0x16, 0x7d, 0x27, 0xef, 0x98, 0xbc, 0x46, 0xc0, 0x9f, 0x0d, 0x79, 0x31, 0x3b, 0x31, 0x57, 0x29, 0xd5, 0x35, 0x1b, 0x79, 0xa9, 0x80, 0xb6, 0xe5, 0x8b, 0x6a, 0x82, 0xaa, 0x8b, 0xb0, 0xa1, 0x00, 0xad, 0xcf, 0xd5, 0x5a, 0xff, 0x88, 0x79, 0x77, 0x59, 0x3c, 0xbd, 0x09, 0xf9, 0x8c, 0x05, 0x7a, 0xd9, 0x6c, 0x77, 0x03, 0x47, 0x02, 0x23, 0x38, 0x04, 0x09, 0x01, 0x47, 0x06, 0x07, 0x88, 0x80, 0xc0, 0x6a, 0xc6, 0xab, 0xd3, 0x89, 0x89, 0xe7, 0x4d, 0xad, 0x0b, 0x9c, 0x50, 0x29, 0x64, 0xac, 0xb5, 0xf8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x19, 0x5a, 0x2a, 0x64, 0x80, 0x54, 0x82, 0x12, 0x0e, 0x00, 0x72, 0xbe, 0x40, 0xf9, 0x44, 0xa1, 0xeb, 0xe7, 0xb8, 0x49, 0x06, 0x8d, 0xc6, 0x9a, 0x6f, 0x9e, 0x2e, 0x2c, 0xe7, 0xd8, 0x6c, 0xd6, 0x8d, 0x85, 0x66, 0x5a, 0xbb, 0xde, 0x3c, 0x6e, 0xfe, 0x70, 0xe7, 0xba, 0x7a, 0x66, 0xd3, 0x2a, 0x41, 0x1b, 0x5e, 0xc5, 0x26, 0x13, 0x61, 0xe2, 0x40, 0xe1, 0xb1, 0xe9, 0x32, 0x08, 0x80, 0x28, 0x00, 0x34, 0x33, 0x28, 0x30, 0x42, 0x07, 0x01, 0x03, 0x94, 0xd6, 0xf8, 0xca, 0xd9, 0x27, 0x06, 0x77, 0xf8, 0xa9, 0x73, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x25, 0x54, 0x28, 0x01, 0x00, 0x01, 0x63, 0x67, 0x02, 0xc2, 0xba, 0xcb, 0x45, 0x9d, 0xc0, 0xbc, 0xf8, 0x8d, 0x48, 0x22, 0x7a, 0xe2, 0xb0, 0x59, 0x52, 0x1c, 0x2b, 0x0d, 0xc7, 0xdd, 0xd3, 0x75, 0xc2, 0x5a, 0xd1, 0x08, 0xb1, 0x4b, 0xc2, 0xd1, 0x8a, 0x98, 0x71, 0x95, 0xf2, 0x57, 0xc3, 0x6b, 0xc9, 0x9c, 0x73, 0x1c, 0x87, 0x24, 0x91, 0xd6, 0x08, 0x83, 0x2d, 0xd5, 0x6c, 0x50, 0xc2, 0xa4, 0x0c, 0xfa, 0xde, 0x61, 0xbd, 0xaa, 0x40, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x25, 0xd6, 0x67, 0x01, 0x00, 0x16, 0x0a, 0x99, 0xa4, 0x00, 0x8a, 0x9b, 0x17, 0x2c, 0xb3, 0x5f, 0x69, 0xc8, 0xc7, 0xe3, 0xc5, 0x0d, 0xbf, 0x24, 0x72, 0x0c, 0x4f, 0xae, 0xba, 0xc8, 0xc2, 0x17, 0x25, 0x67, 0x49, 0xce, 0x62, 0x4c, 0xa2, 0xb5, 0xa5, 0x51, 0x0c, 0xa0, 0xe6, 0x56, 0x56, 0xcd, 0xf6, 0x0a, 0xc0, 0x44, 0xc7, 0x28, 0x75, 0xea, 0xcd, 0x71, 0x4a, 0x01, 0x49, 0x2a, 0x98, 0x81, 0x90, 0x14, 0xdf, 0xd5, 0x75, 0xa4, 0x21, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x25, 0x5c, 0x26, 0x77, 0xa5, 0x21, 0x68, 0x01, 0xa0, 0x16, 0x3c, 0x07, 0x14, 0xb5, 0xc9, 0xba, 0x96, 0x6c, 0x41, 0xc8, 0xc6, 0x3a, 0x0f, 0x37, 0x5a, 0x79, 0xf5, 0x6d, 0xeb, 0xa7, 0x85, 0x56, 0x29, 0x14, 0x52, 0xd4, 0x89, 0xb8, 0x17, 0x93, 0x48, 0x4b, 0x7c, 0xce, 0xbe, 0xd2, 0xe8, 0x1f, 0x7b, 0x32, 0x4a, 0xf0, 0xc8, 0x9d, 0x15, 0xed, 0x9d, 0xb9, 0x52, 0x6b, 0xda, 0xf6, 0xaa, 0xbf, 0xf4, 0x95, 0x0a, 0xc4, 0xb8, 0x15, 0x6a, 0x60, 0xb8, 0x03, 0x3e, 0xac, 0xee, 0x38, 0x06, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x8e, 0x14, 0x87, 0x14, 0x99, 0x56, 0x17, 0x0a, 0x90, 0xa2, 0xc0, 0x08, 0xe3, 0xc1, 0xa7, 0x94, 0xc0, 0x9b, 0xc5, 0xc4, 0x0b, 0x0e, 0xbb, 0x83, 0xad, 0x8e, 0x6a, 0x64, 0x48, 0x75, 0x83, 0x0e, 0x53, 0x86, 0x01, 0x50, 0x30, 0x0f, 0x6e, 0x25, 0xca, 0x1f, 0xe2, 0xe1, 0xc9, 0xdd, 0xa5, 0xf1, 0x92, 0xba, 0x37, 0x21, 0xf5, 0x1e, 0x04, 0xb5, 0x66, 0xdf, 0xf3, 0x68, 0xf5, 0x70, 0xfb, 0x69, 0x76, 0x99, 0xc2, 0xb2, 0x95, 0x20, 0xf2, 0xa7, 0x1a, 0xaf, 0x5c, 0x42, 0xee, 0xe0, 0x55, 0x50, 0x50, 0xa1, 0x76, 0x59, 0x60, 0x7d, 0xa3, 0xba, 0x1c, 0xb7, 0x6b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x25, 0x54, 0x47, 0x31, 0xb2, 0x4d, 0xc4, 0x96, 0x0b, 0x00, 0x2c, 0x1e, 0xa0, 0x9a, 0x91, 0x1a, 0x12, 0xa4, 0xa1, 0x01, 0x1f, 0x4a, 0x10, 0xe7, 0x82, 0x83, 0x37, 0x55, 0xae, 0x7f, 0x7a, 0x33, 0x98, 0x9d, 0x7c, 0xef, 0x39, 0x88, 0xa5, 0xaa, 0x51, 0x57, 0xc3, 0x38, 0x82, 0x32, 0xba, 0xce, 0x73, 0xe2, 0x6e, 0xbb, 0xa3, 0x65, 0x57, 0x51, 0x64, 0x7e, 0xd0, 0x9b, 0xcd, 0x43, 0x48, 0x27, 0x59, 0x13, 0x25, 0xf9, 0x93, 0xcc, 0x39, 0x93, 0xdf, 0x68, 0xf6, 0x5f, 0xea, 0x3e, 0xde, 0xba, 0x08, 0xa2, 0x88, 0x2a, 0x95, 0x41, 0x32, 0x00, 0x07, 0xf5, 0x9f, 0x77, 0x60, 0x0e, 0xf0, 0xdb, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x25, 0x14, 0x49, 0x00, 0xb2, 0x0c, 0xa9, 0x57, 0x60, 0x16, 0x00, 0x7d, 0x17, 0x9c, 0x67, 0x71, 0x99, 0x27, 0x97, 0xf8, 0xd7, 0x34, 0xbe, 0x60, 0x49, 0x85, 0x6e, 0x00, 0x11, 0x69, 0xda, 0xac, 0x9e, 0xe3, 0x7f, 0xc8, 0x55, 0xaa, 0xf8, 0x87, 0x62, 0x51, 0x9d, 0x08, 0xe3, 0x2c, 0x73, 0xbc, 0x9d, 0xb6, 0xf2, 0xf7, 0x51, 0xca, 0xbe, 0xbc, 0xd4, 0x02, 0x2b, 0xee, 0x54, 0x0c, 0x98, 0x82, 0x18, 0x49, 0x48, 0x62, 0x72, 0xf2, 0x2f, 0x05, 0x8e, 0x84, 0x30, 0x44, 0x65, 0x22, 0xb2, 0x04, 0x25, 0x0b, 0x26, 0x00, 0xcb, 0x06, 0xcd, 0xe8, 0x8a, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x19, 0x8e, 0xa6, 0x24, 0x80, 0x59, 0x0c, 0xb6, 0x70, 0xac, 0xbb, 0x04, 0x40, 0x0c, 0x88, 0xfb, 0x89, 0x10, 0x8f, 0x4e, 0x82, 0xec, 0xb2, 0x54, 0x5e, 0xf9, 0xd7, 0x99, 0x3b, 0xd3, 0x28, 0x3c, 0x32, 0xb6, 0xa5, 0x40, 0xb1, 0x96, 0xab, 0x60, 0xe4, 0x6a, 0xf2, 0x85, 0xc7, 0x57, 0x66, 0x4a, 0x88, 0xd3, 0x0e, 0x44, 0x16, 0x06, 0xbe, 0x25, 0x48, 0x59, 0xcc, 0x39, 0x81, 0xc2, 0x9d, 0xc3, 0x07, 0x58, 0x3f, 0x2b, 0xf1, 0x50, 0x77, 0x20, 0x50, 0x20, 0x11, 0x5d, 0x03, 0x12, 0x05, 0x9a, 0x00, 0x66, 0x0d, 0x23, 0x09, 0x2c, 0x62, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x25, 0x54, 0x43, 0x13, 0xaf, 0x70, 0xdd, 0xc6, 0x6a, 0xad, 0x60, 0x00, 0x19, 0x5c, 0x67, 0x96, 0x3f, 0xbc, 0x2e, 0xa8, 0xa6, 0x25, 0x97, 0x23, 0x8a, 0x26, 0x01, 0x05, 0x00, 0x59, 0xb4, 0xe5, 0x57, 0xbd, 0x5e, 0x02, 0x39, 0xcd, 0xaa, 0xad, 0x71, 0xd2, 0x5d, 0xe6, 0xa7, 0x31, 0x3e, 0x47, 0xdb, 0x5b, 0x9d, 0xac, 0xa2, 0x03, 0x28, 0x98, 0x11, 0x9f, 0xdd, 0x2e, 0x78, 0x5f, 0x75, 0xb3, 0x54, 0x8c, 0x43, 0x26, 0xc4, 0xe0, 0x5c, 0x02, 0xb5, 0xce, 0x16, 0x00, 0x39, 0x7a, 0x9e, 0xd2, 0xec, 0x05, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x09, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x19, 0x8a, 0x46, 0x36, 0x05, 0x08, 0x03, 0x86, 0xc0, 0xb5, 0x87, 0x73, 0xe3, 0x3a, 0x4e, 0x50, 0xdd, 0x9c, 0x82, 0xe1, 0xc5, 0x92, 0x24, 0xe6, 0x94, 0xf5, 0xf1, 0xaa, 0x4d, 0xe6, 0x67, 0x6a, 0x24, 0x6e, 0xe9, 0x4e, 0x22, 0x33, 0xdf, 0xa7, 0x54, 0x9c, 0xfc, 0x73, 0x12, 0xf0, 0xba, 0x88, 0x93, 0xdc, 0x12, 0x11, 0x08, 0xd0, 0x05, 0xf2, 0x80, 0x02, 0xc1, 0x84, 0x25, 0x0b, 0x20, 0x03, 0xcf, 0xa9, 0x42, 0xdc}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x9d, 0x88, 0x30, 0x01, 0x33, 0x20, 0x64, 0x90, 0x11, 0xa2, 0x9a, 0x06, 0xb3, 0xed, 0x28, 0x4a, 0xaa, 0x52, 0xe0, 0x48, 0x8e, 0x27, 0x90, 0x0f, 0x98, 0xa2, 0xc0, 0x1b, 0x27, 0x51, 0x83, 0x44, 0xf0, 0xf6, 0x87, 0x4e, 0xf4, 0x46, 0x49, 0x21, 0x36, 0x1c, 0x3b, 0xfe, 0x1e, 0x5f, 0x5e, 0x1c, 0xb3, 0x94, 0xf0, 0x1a, 0xac, 0x33, 0x11, 0xac, 0x92, 0xa7, 0x91, 0x68, 0xd9, 0x58, 0xe8, 0xad, 0xa1, 0x09, 0x42, 0xc0, 0x00, 0x94, 0x02, 0x91, 0xf1, 0x99, 0x8b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x19, 0x8a, 0x72, 0x28, 0x01, 0x02, 0xc0, 0x40, 0x3b, 0x9f, 0xbd, 0xf5, 0x45, 0x26, 0x42, 0xc0, 0x54, 0x07, 0xa0, 0xd8, 0xce, 0xae, 0xde, 0x35, 0x3c, 0x3d, 0x59, 0xa5, 0x19, 0xe8, 0xe7, 0xbd, 0xf5, 0x23, 0x9f, 0x8f, 0x68, 0xae, 0x7d, 0xbc, 0x7f, 0x5e, 0xed, 0xf3, 0x69, 0x45, 0x02, 0x33, 0x40, 0x54, 0x44, 0x31, 0xd9, 0x02, 0x00, 0x89, 0x5a, 0x91, 0x01, 0x5e, 0xc3, 0x13, 0x05, 0x0b, 0x00, 0x59, 0xea, 0xda, 0x0e, 0x80, 0xaf}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x24, 0xe8, 0xc1, 0x55, 0x14, 0xd0, 0x12, 0xe0, 0x00, 0xff, 0x1f, 0x48, 0x5d, 0xaa, 0x72, 0x2a, 0xaf, 0x33, 0x8f, 0xa2, 0x02, 0xe4, 0x2c, 0xa2, 0xde, 0xc3, 0xe8, 0xb4, 0xa5, 0xd1, 0x1d, 0xad, 0xc6, 0x04, 0x10, 0x6a, 0x7e, 0x01, 0x1e, 0xb6, 0x9a, 0xe8, 0xad, 0xb3, 0x8f, 0x8a, 0x0b, 0x15, 0xd4, 0xa2, 0x6a, 0x2b, 0xba, 0x30, 0x90, 0x17, 0x26, 0xb8, 0x01, 0x5b, 0x02, 0x14, 0x04, 0xd8, 0x16, 0x05, 0x83, 0x33, 0x46, 0x12, 0x21, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x25, 0x14, 0x2a, 0x4a, 0x64, 0xa8, 0xdf, 0x16, 0x05, 0x82, 0x50, 0x18, 0x4e, 0x57, 0xb0, 0xb2, 0x7e, 0x50, 0xf7, 0x48, 0x5b, 0x5a, 0xc0, 0x11, 0x4b, 0x25, 0xc1, 0xc4, 0xa9, 0xbf, 0x41, 0xbd, 0x77, 0x82, 0x41, 0x38, 0x14, 0xb9, 0x79, 0x82, 0x77, 0xed, 0x3f, 0x43, 0x9b, 0xeb, 0x3a, 0xbf, 0x64, 0xa3, 0xc2, 0x56, 0x7b, 0x83, 0x04, 0x23, 0xa1, 0xac, 0x83, 0x1d, 0xcc, 0x12, 0x80, 0x6a, 0x47, 0xaa, 0xe0, 0x05, 0x72, 0x9c, 0x2c, 0x80, 0x1d, 0x9d, 0x7f, 0x6c, 0x16, 0x06, 0xf8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x1d, 0x8a, 0x88, 0x14, 0xa7, 0x2b, 0xab, 0x43, 0x7a, 0x0b, 0x00, 0x02, 0xaf, 0xea, 0xfd, 0x53, 0x0c, 0x1c, 0x24, 0x0a, 0x23, 0x4c, 0xa5, 0x04, 0x49, 0xd2, 0xca, 0x62, 0x01, 0x7d, 0x94, 0x7e, 0xa6, 0x33, 0x4a, 0x19, 0xda, 0xd5, 0xd2, 0xf7, 0x14, 0xec, 0x95, 0x02, 0x4f, 0xeb, 0xc1, 0x9d, 0xb9, 0x58, 0x74, 0xb4, 0x9f, 0x1a, 0xb0, 0x5b, 0xda, 0x4e, 0x34, 0xf9, 0x25, 0xc9, 0xb9, 0x5e, 0x32, 0x15, 0x9f, 0xc4, 0x49, 0xeb, 0x00, 0x2a, 0x1d, 0x40, 0x51, 0x08, 0x34, 0x01, 0x00, 0xf0, 0x39, 0x1a, 0x5a, 0x1b, 0xc0, 0xd6, 0x08, 0x27, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x89, 0x94, 0x85, 0x16, 0x0c, 0x8a, 0xa5, 0xdd, 0x1a, 0x02, 0x00, 0x10, 0x9a, 0xa3, 0xf0, 0x62, 0xed, 0xee, 0xb0, 0x3e, 0x63, 0xe5, 0x4e, 0x74, 0x05, 0x37, 0x18, 0x42, 0xde, 0x8b, 0x1c, 0xf2, 0x4b, 0xc3, 0x16, 0x79, 0xce, 0x11, 0xbf, 0xc7, 0x6d, 0x97, 0x7a, 0x64, 0xe9, 0x4e, 0x67, 0xed, 0x3a, 0x49, 0xe1, 0x8c, 0xeb, 0x2e, 0xa4, 0xa3, 0x54, 0x65, 0x5a, 0xd9, 0x1b, 0x97, 0xa7, 0xbd, 0x15, 0xe0, 0x90, 0x01, 0x53, 0x43, 0x38, 0x82, 0x40, 0x00, 0x00, 0x18, 0xd9, 0xea, 0x61, 0x3b, 0x84, 0xd3, 0xf4, 0xf7, 0x86, 0x3a, 0x1e, 0xbf, 0x18, 0x95, 0x83, 0x38, 0x08, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x8a, 0x14, 0x86, 0x15, 0xb5, 0x40, 0x44, 0x00, 0x10, 0x01, 0x83, 0xc0, 0x3e, 0xac, 0xc4, 0xde, 0x2c, 0x4c, 0xf5, 0xe9, 0x92, 0x0c, 0x47, 0x99, 0x48, 0xa7, 0x11, 0x84, 0x40, 0x1c, 0x63, 0x3e, 0x92, 0x8a, 0x65, 0x04, 0x15, 0xf5, 0x4a, 0x12, 0x60, 0xd5, 0xad, 0x0b, 0x94, 0xcb, 0xab, 0xef, 0x5c, 0x5c, 0x3a, 0xca, 0xed, 0xb3, 0xa1, 0x83, 0x7e, 0x87, 0xc0, 0xa4, 0x75, 0x57, 0x10, 0x69, 0x23, 0x69, 0xd6, 0x22, 0x80, 0x15, 0xb4, 0x24, 0x28, 0xb4, 0x12, 0xd3, 0xbd, 0x5c, 0x08, 0x00, 0x1d, 0x29, 0xed, 0xc0, 0x09, 0xc8, 0x47, 0x4a, 0x88, 0x7d, 0xbb, 0x74, 0xc2, 0x2c, 0x4a, 0xfe, 0xe0, 0x25, 0x90, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x8e, 0x0a, 0x85, 0x24, 0x99, 0xd6, 0x00, 0x01, 0x60, 0x00, 0x89, 0x79, 0xef, 0x17, 0xbf, 0xe7, 0x11, 0x89, 0x93, 0xcb, 0x7e, 0xd0, 0xd4, 0xcb, 0x6a, 0x6d, 0xe4, 0x5b, 0xbf, 0x2a, 0x1b, 0x3a, 0x41, 0xa5, 0x23, 0x36, 0x9a, 0xfe, 0x69, 0x04, 0x38, 0x20, 0xd2, 0xdb, 0x02, 0x51, 0xd3, 0x70, 0x55, 0x43, 0xdd, 0xa7, 0x59, 0xcb, 0x92, 0x72, 0xd8, 0x99, 0x08, 0xc5, 0x21, 0x51, 0x74, 0x00, 0x01, 0x4f, 0x45, 0x02, 0xa0, 0x85, 0x40, 0x70, 0x00, 0x0b, 0x1b, 0xbf, 0xe9, 0xb4, 0x98, 0x87, 0x7d, 0x50, 0x6d, 0x39, 0xa0, 0xce, 0x61, 0x39, 0x20, 0x1c, 0x37, 0x00, 0xac, 0x41, 0x78, 0x53, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x89, 0x90, 0x8e, 0x12, 0xaf, 0x20, 0x90, 0x81, 0x0b, 0x00, 0x06, 0x16, 0x3e, 0xad, 0x4d, 0x97, 0x11, 0xec, 0x8b, 0xe5, 0xa9, 0xe1, 0x5c, 0x9a, 0x23, 0x3f, 0x3f, 0x0e, 0x9c, 0x5c, 0xeb, 0x06, 0xf6, 0x0f, 0xc4, 0x02, 0x35, 0xb3, 0x12, 0x9a, 0x94, 0x87, 0x69, 0x83, 0x0b, 0xab, 0x59, 0x0b, 0x87, 0x96, 0xc5, 0xb4, 0xab, 0x9f, 0x35, 0x16, 0xca, 0xb7, 0x52, 0xfc, 0xab, 0x5a, 0x93, 0x43, 0x45, 0x91, 0x08, 0xc0, 0x05, 0x3d, 0x0d, 0x18, 0x05, 0x11, 0x81, 0x80, 0x00, 0x58, 0x27, 0x78, 0xcf, 0xde, 0x18, 0x60, 0xc7, 0x9c, 0xef, 0xa6, 0x1e, 0x17, 0x9e, 0xb8, 0xaa, 0x75, 0x53, 0xb4, 0xe3, 0xac, 0x36, 0xd4, 0x0c, 0x17, 0xd6, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x0d, 0x90, 0x84, 0x24, 0x89, 0x52, 0x8c, 0xb8, 0x0a, 0x16, 0x22, 0xc0, 0x34, 0xdf, 0x1b, 0xdd, 0xf0, 0x46, 0x39, 0x3b, 0x8e, 0xb9, 0xa7, 0x77, 0xae, 0x7b, 0x7b, 0xe4, 0x33, 0x7b, 0xb4, 0x55, 0x84, 0xb6, 0x97, 0x70, 0xaf, 0x66, 0x55, 0x1b, 0x22, 0xab, 0x86, 0xbf, 0x03, 0xb1, 0x79, 0xd6, 0x47, 0x31, 0xc6, 0x74, 0x88, 0x66, 0x96, 0x56, 0x21, 0xb4, 0xf9, 0xee, 0xd6, 0xa2, 0x45, 0xe4, 0xb4, 0xe8, 0x70, 0x2c, 0x00, 0xaa, 0x81, 0x9d, 0x00, 0xc0, 0x1c, 0x00, 0x34, 0x00, 0xab, 0x7e, 0x4e, 0x68, 0xcb, 0xde, 0x63, 0xd8, 0xe8, 0xaf, 0x2c, 0xdf, 0xfd, 0xd0, 0x07, 0x17, 0x74, 0x06, 0x1c, 0x1d, 0x1f, 0x63, 0xa7, 0xd0, 0x03, 0x07, 0x42, 0x8f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x8d, 0x24, 0x28, 0x2a, 0x56, 0x4a, 0xb5, 0x6a, 0x01, 0x01, 0x16, 0x05, 0x7f, 0xbf, 0x9c, 0xc7, 0x38, 0xd0, 0xff, 0xa7, 0xf4, 0x3e, 0x04, 0x1c, 0x5a, 0x3b, 0x90, 0xec, 0x72, 0xdd, 0x27, 0xf1, 0x1a, 0xc9, 0xf6, 0x11, 0xf0, 0x19, 0xc5, 0xb8, 0x72, 0xb2, 0x9a, 0x47, 0x30, 0xed, 0xc5, 0x6d, 0x91, 0xac, 0x6b, 0x6d, 0x68, 0xf7, 0x92, 0xb2, 0x8a, 0xd7, 0x08, 0x94, 0x1d, 0xba, 0x45, 0x80, 0x00, 0x56, 0x40, 0xcd, 0xc0, 0x41, 0x08, 0x1c, 0xcb, 0x0b, 0x57, 0x40, 0xd8, 0x0d, 0x66, 0xc1, 0x25, 0x3f, 0x57, 0x2a, 0x6e, 0x38, 0x3d, 0x4f, 0x63, 0xb7, 0xd8, 0xe8, 0x20, 0x6b, 0x8a, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x95, 0x08, 0x34, 0x6e, 0x18, 0xd6, 0x5e, 0xed, 0x62, 0x01, 0x3a, 0xa7, 0x91, 0xbf, 0x3e, 0x1a, 0x20, 0x24, 0x35, 0xbc, 0x9d, 0x2a, 0xf3, 0xbb, 0x02, 0xf4, 0x80, 0x64, 0x50, 0x81, 0xdf, 0x57, 0x49, 0xc3, 0x04, 0xba, 0xc7, 0x16, 0x08, 0x63, 0x4f, 0xd7, 0x3f, 0x44, 0x6b, 0x32, 0x2b, 0x46, 0x6b, 0x11, 0x5c, 0x20, 0x16, 0x96, 0x04, 0x89, 0x10, 0x18, 0x40, 0xa8, 0x00, 0xc0, 0x8d, 0x40, 0x51, 0x38, 0x10, 0x00, 0x40, 0xb0, 0x76, 0xfe, 0xcd, 0x17, 0xcf, 0xf6, 0xdb, 0x1f, 0x3e, 0x77, 0xbb, 0x07, 0x0e, 0x4f, 0x8f, 0xaa, 0x01, 0x9c, 0x7f, 0x5a, 0x81, 0x05, 0x8e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x91, 0x1a, 0x2c, 0x41, 0x50, 0x01, 0x60, 0x2d, 0xa0, 0x43, 0xbe, 0xb9, 0xf6, 0x18, 0x2b, 0xf9, 0xd4, 0x72, 0x14, 0x09, 0xab, 0xf8, 0xbf, 0x9b, 0xf0, 0x82, 0x39, 0x36, 0xce, 0x4c, 0xcd, 0x63, 0xa8, 0xd3, 0x05, 0xbb, 0xf9, 0xb5, 0xc1, 0x79, 0x57, 0x76, 0x49, 0xda, 0x93, 0x4a, 0x05, 0xc9, 0xac, 0x48, 0x97, 0x32, 0x45, 0x83, 0x1b, 0x6a, 0x45, 0xc0, 0x2a, 0x20, 0x66, 0x94, 0x18, 0xa4, 0x0a, 0x00, 0x0b, 0x06, 0x0d, 0x0b, 0xb9, 0x5c, 0x01, 0x56, 0xb4, 0xf4, 0x9e, 0xd7, 0xb4, 0x12, 0xe2, 0x13, 0x75, 0xd5, 0x2c, 0x04, 0x05, 0x00, 0x92, 0x60, 0x20, 0xb2, 0x09, 0x23, 0x77}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x11, 0x8e, 0x32, 0x15, 0x41, 0x68, 0x80, 0x0b, 0x68, 0x0d, 0x83, 0xf3, 0x3d, 0x01, 0x6a, 0x0a, 0x57, 0xcd, 0x84, 0xa1, 0x02, 0x0a, 0x95, 0x22, 0x04, 0x1f, 0x94, 0x5b, 0x1b, 0x32, 0x36, 0xf1, 0x78, 0x9f, 0x97, 0xe5, 0xb5, 0x9e, 0x0c, 0xf0, 0xb1, 0x19, 0x97, 0x14, 0x54, 0xbb, 0x14, 0x55, 0xb6, 0xa6, 0x51, 0xe4, 0x16, 0x52, 0x12, 0x23, 0x2b, 0x81, 0x4d, 0x63, 0x56, 0x89, 0xc0, 0x42, 0x10, 0x18, 0x00, 0x00, 0x34, 0x08, 0xe7, 0xf7, 0xdc, 0xac, 0xfd, 0x8d, 0x9c, 0xc7, 0x67, 0x2f, 0xd5, 0xad, 0x58, 0x11, 0x3f, 0x68, 0x01, 0x72, 0x02, 0xc0, 0x1d, 0x01, 0x29, 0xe8, 0xe9, 0xbb, 0x0f, 0x69, 0x94, 0x2d, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x89, 0x8e, 0x88, 0x16, 0x28, 0x01, 0x2c, 0x00, 0x38, 0x03, 0x0e, 0xcf, 0x1e, 0x0e, 0xea, 0x1c, 0x71, 0xec, 0x9e, 0xd3, 0xa8, 0xd6, 0x49, 0x2a, 0x83, 0x03, 0xb4, 0x71, 0x83, 0x9d, 0x5e, 0xc8, 0x95, 0xdb, 0x25, 0x38, 0x8b, 0x49, 0xda, 0x68, 0x7e, 0x68, 0x59, 0xcd, 0xc2, 0x88, 0x5a, 0xf7, 0x99, 0x7d, 0xaa, 0x4a, 0x04, 0x77, 0x16, 0x4b, 0xeb, 0x71, 0x05, 0xca, 0x73, 0x00, 0xa8, 0x83, 0x99, 0x00, 0xc2, 0x60, 0x30, 0x00, 0xd0, 0x07, 0xaf, 0xb1, 0xe6, 0xe2, 0x82, 0x89, 0x70, 0x9c, 0x49, 0xa8, 0x2b, 0x15, 0xfb, 0xb0, 0xca, 0x23, 0x70, 0x52, 0xb2, 0x56, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x25, 0x08, 0x30, 0x00, 0x32, 0x0b, 0x40, 0x3a, 0x01, 0x97, 0x57, 0xd1, 0x87, 0x28, 0x03, 0xb8, 0x79, 0x17, 0x94, 0x65, 0x0f, 0x1c, 0x48, 0x9d, 0x72, 0x24, 0xdd, 0x7a, 0x06, 0x45, 0xf1, 0x42, 0xf1, 0xf0, 0x46, 0xb5, 0xb3, 0x19, 0xba, 0x5b, 0x0c, 0xf4, 0x50, 0x10, 0x68, 0x18, 0x46, 0xb5, 0x23, 0xf6, 0xb4, 0x19, 0x9b, 0x88, 0xab, 0x30, 0x2a, 0x28, 0x4a, 0x90, 0x38, 0x94, 0x04, 0x22, 0x01, 0x20, 0x02, 0xc3, 0x80, 0x7d, 0x80, 0xec, 0x52, 0x41, 0xc1, 0xe8, 0xb0, 0x36, 0x98, 0xe9, 0x47, 0xac, 0xa3, 0x70, 0x52, 0x9b, 0x5c, 0x6a, 0xe4, 0x54, 0x76, 0x11, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x8a, 0x0c, 0xe6, 0x17, 0x80, 0x00, 0x62, 0x03, 0x82, 0xc1, 0xd3, 0x92, 0x66, 0x61, 0x85, 0x16, 0xca, 0xcb, 0x8a, 0x6b, 0xc3, 0x19, 0xec, 0xfa, 0x83, 0x29, 0x9d, 0x3a, 0x9a, 0xdb, 0x9d, 0xea, 0x77, 0x24, 0x1d, 0xfe, 0x5d, 0xa2, 0x98, 0x88, 0x91, 0x1b, 0xa5, 0x64, 0xe0, 0x10, 0x02, 0xa3, 0xc8, 0xa6, 0x02, 0x2a, 0x0a, 0x74, 0x82, 0xe0, 0x53, 0xcb, 0x80, 0x82, 0xb0, 0x40, 0x00, 0x34, 0x58, 0x75, 0x5f, 0xd9, 0xcf, 0x7a, 0xd0, 0xdf, 0xe7, 0x1a, 0xba, 0x53, 0x34, 0x18, 0x4d, 0x67, 0xa7, 0xb8, 0x00, 0x92, 0xea, 0x10, 0xa5, 0xc0, 0x09, 0x4d, 0x11, 0x70, 0x27, 0x04, 0x06, 0xe5, 0x24, 0xa5, 0xc0, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x11, 0x52, 0x30, 0x01, 0xdb, 0x80, 0x0b, 0xd9, 0xc5, 0xa9, 0xc0, 0x6e, 0x58, 0x7d, 0x03, 0x1e, 0x91, 0x59, 0x2f, 0xba, 0x5c, 0xdb, 0x1f, 0x49, 0x89, 0xb7, 0x77, 0x6e, 0x20, 0x89, 0xfa, 0xa2, 0x89, 0xe3, 0xba, 0x90, 0x55, 0x75, 0x6c, 0x33, 0x8b, 0x92, 0x92, 0x92, 0xe5, 0x04, 0x45, 0x64, 0x02, 0x51, 0x5c, 0x31, 0x11, 0x02, 0xad, 0x8c, 0x04, 0x60, 0x83, 0x84, 0x82, 0xf4, 0xb3, 0xd8, 0x2e, 0x1f, 0x65, 0xf5, 0x82, 0x65, 0x25, 0xb7, 0x98, 0x6f, 0xbe, 0x40, 0x52, 0x31, 0x0a, 0x55, 0x4b, 0x42, 0x99, 0x80, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x89, 0x90, 0xe7, 0x16, 0x00, 0x00, 0x6d, 0xa0, 0x58, 0xf6, 0x1c, 0xff, 0xc0, 0xfb, 0xf1, 0xa2, 0xcf, 0x83, 0xfe, 0xec, 0xf3, 0x34, 0xe1, 0xb7, 0xd4, 0xd7, 0x88, 0xd3, 0xc7, 0x14, 0xc2, 0x7c, 0x19, 0x19, 0xd8, 0xa5, 0x95, 0x00, 0xbb, 0xe1, 0x13, 0xfd, 0xc6, 0xaa, 0xc1, 0x4e, 0x04, 0xae, 0x2e, 0x56, 0x85, 0xc1, 0x16, 0x68, 0x81, 0x10, 0x2a, 0x60, 0xca, 0x90, 0x48, 0x84, 0x06, 0x21, 0x00, 0x58, 0x74, 0x02, 0x73, 0x3e, 0x19, 0x78, 0x06, 0x62, 0x4e, 0x17, 0x96, 0x63, 0x91, 0x89, 0xab, 0xfd, 0x70, 0x11, 0xaf, 0xa4, 0x18, 0x62, 0x66, 0x38, 0x40, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x0d, 0x90, 0x72, 0x02, 0x1b, 0xb1, 0x65, 0x9b, 0x2d, 0xa6, 0x83, 0xbe, 0x6c, 0x7d, 0x06, 0x4d, 0x3b, 0x62, 0x9d, 0x46, 0xa5, 0x30, 0x8f, 0x53, 0xa0, 0x08, 0x16, 0xe6, 0x38, 0x7b, 0x66, 0xc4, 0xf8, 0x79, 0x94, 0xcd, 0xce, 0x8a, 0xd4, 0xd0, 0x78, 0x11, 0x45, 0x15, 0xa0, 0x65, 0x12, 0x91, 0xbd, 0x88, 0x9c, 0x50, 0x34, 0x42, 0xb0, 0x2b, 0x76, 0x80, 0x0a, 0x60, 0x0d, 0x09, 0x48, 0x05, 0x60, 0x81, 0xc8, 0x20, 0x51, 0x18, 0x0e, 0x1a, 0xb1, 0xe4, 0x53, 0x24, 0x5f, 0x5c, 0x4f, 0x92, 0x2c, 0x47, 0x40, 0xd5, 0xc6, 0x21, 0x14, 0x70, 0x02, 0x90, 0x03, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x0d, 0x94, 0x84, 0x16, 0x01, 0x8d, 0x2c, 0x00, 0x1d, 0x00, 0xfb, 0xae, 0x59, 0xe2, 0x1f, 0x84, 0x86, 0x8b, 0xd1, 0x5e, 0xe3, 0x0b, 0x58, 0x88, 0xea, 0x05, 0x8c, 0x06, 0xc1, 0x01, 0xbb, 0x84, 0x95, 0x16, 0x37, 0x68, 0xcd, 0xb4, 0xea, 0xee, 0xa2, 0x09, 0x90, 0x86, 0x0b, 0x5b, 0x8c, 0x69, 0x04, 0xd4, 0xb1, 0x08, 0x0e, 0x31, 0x05, 0xea, 0x20, 0x00, 0x0a, 0x68, 0x28, 0x09, 0x88, 0x08, 0x10, 0x81, 0x04, 0x40, 0x30, 0x04, 0xd0, 0x7f, 0x9e, 0x97, 0x77, 0x36, 0x5d, 0xb0, 0xa1, 0x30, 0xdb, 0x89, 0x19, 0xd4, 0x05, 0x8c, 0xf9, 0x4e, 0xc0, 0x88, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x11, 0x1a, 0x23, 0x41, 0x09, 0xc0, 0x01, 0xa0, 0x05, 0xad, 0x61, 0x6c, 0x86, 0xf4, 0x72, 0xd3, 0x88, 0xb8, 0xa3, 0x01, 0x46, 0xb4, 0xa5, 0xfe, 0x33, 0x74, 0x7d, 0x36, 0xad, 0x5a, 0xd8, 0x16, 0xce, 0x37, 0xf8, 0x8d, 0x1c, 0xc7, 0x73, 0xa1, 0x09, 0xf2, 0x35, 0x61, 0xeb, 0xed, 0xa6, 0x7e, 0x45, 0x74, 0x41, 0x70, 0x1e, 0xa2, 0x59, 0x85, 0xc0, 0xba, 0x20, 0xac, 0x61, 0x9b, 0x01, 0xc1, 0x2a, 0xc1, 0x8b, 0x1b, 0xac, 0x00, 0xb3, 0x8b, 0x57, 0x93, 0x83, 0xe6, 0xc9, 0x5c, 0x44, 0x43, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x11, 0x14, 0x6d, 0x01, 0x02, 0x33, 0x40, 0x00, 0x34, 0x0b, 0x9f, 0xf7, 0x39, 0x27, 0xe3, 0x46, 0xc2, 0x4f, 0x45, 0x64, 0xb5, 0x69, 0x9c, 0x6e, 0xe8, 0x2a, 0x89, 0x82, 0x36, 0x3b, 0xe1, 0x9c, 0xa6, 0x8b, 0x85, 0x44, 0xb0, 0x8d, 0x36, 0x7b, 0xd9, 0x6e, 0xe9, 0x93, 0xa4, 0x19, 0x4b, 0x58, 0x06, 0x90, 0xdb, 0x33, 0xaa, 0x20, 0xea, 0x40, 0x68, 0x84, 0x08, 0x1a, 0x80, 0xb1, 0x4e, 0x8f, 0x0a, 0x09, 0x26, 0x7c, 0xe4, 0x38, 0x4a, 0x00, 0x43, 0x97, 0x0a, 0x9f, 0xb6, 0xf6, 0x87}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x89, 0x90, 0xa5, 0x17, 0x00, 0x00, 0x01, 0xbe, 0x96, 0x07, 0x77, 0xf5, 0x07, 0x8b, 0x3f, 0x42, 0xed, 0x9d, 0xba, 0x05, 0xdd, 0x11, 0x64, 0x84, 0x70, 0x6b, 0xdf, 0xe8, 0xdc, 0xd9, 0x5e, 0xc3, 0x51, 0x0c, 0xed, 0x13, 0x45, 0xcc, 0xc7, 0xd2, 0x4b, 0x52, 0x0e, 0x90, 0xba, 0x45, 0xb6, 0x9c, 0x64, 0x16, 0xa2, 0x04, 0x89, 0x23, 0x1a, 0x89, 0xd8, 0x05, 0x38, 0x06, 0x86, 0xa4, 0x0a, 0x80, 0x1d, 0x0c, 0x96, 0x4a, 0xcb, 0x14, 0x2e, 0xbc, 0xb1, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x09, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x8b, 0x2c, 0x64, 0x86, 0x4b, 0xb0, 0xc0, 0x0b, 0x3c, 0x80, 0xf2, 0x6e, 0xfe, 0x25, 0xbe, 0x58, 0xd6, 0x24, 0x62, 0x6a, 0x72, 0x01, 0x88, 0x20, 0xe5, 0xe3, 0xfb, 0xf3, 0xcf, 0x36, 0xdb, 0x6e, 0xa4, 0x2d, 0x15, 0xc2, 0xc1, 0x65, 0xe6, 0x2e, 0x53, 0x68, 0x2a, 0xe9, 0x16, 0xb2, 0x91, 0x09, 0x5c, 0x8d, 0xf5, 0x58, 0x0a, 0xd8, 0x10, 0x9c, 0x28, 0xd0, 0x00, 0x84, 0x6c, 0x43, 0x81, 0x8b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x09, 0x92, 0x32, 0x00, 0x0a, 0x80, 0x34, 0x1a, 0x02, 0x1e, 0xf6, 0x54, 0x8e, 0xf6, 0x3e, 0xac, 0x15, 0xe0, 0xaa, 0xe6, 0x00, 0xa2, 0x26, 0xef, 0xf6, 0x81, 0xf9, 0xbc, 0xde, 0x1e, 0xac, 0x3e, 0xd6, 0xde, 0xea, 0x78, 0xcb, 0x5e, 0x28, 0x68, 0xf7, 0x5e, 0xb5, 0x8e, 0xef, 0x83, 0xf6, 0x6c, 0x61, 0x48, 0xdf, 0x20, 0x45, 0xd8, 0x65, 0x0e, 0x40, 0x2a, 0x40, 0x30, 0x31, 0x60, 0x10, 0x82, 0x08, 0x00, 0x00, 0x1a, 0xea, 0x07, 0x78, 0x54, 0x9f, 0xaf, 0xdd, 0xb4, 0x3b, 0x0c, 0xa6, 0xdc, 0xc8, 0x25, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x0d, 0x90, 0x72, 0x02, 0x59, 0x4d, 0x9d, 0x50, 0xda, 0xda, 0x69, 0x63, 0x7f, 0xda, 0xab, 0x72, 0x8c, 0x5f, 0xa6, 0xeb, 0x4c, 0x9e, 0xd7, 0x3f, 0xf4, 0x44, 0x88, 0x53, 0x5e, 0x9a, 0x69, 0x66, 0xfd, 0x3c, 0x55, 0x2b, 0xda, 0x68, 0xe8, 0xf2, 0xa1, 0x5d, 0x51, 0xd4, 0xc0, 0x4c, 0x9a, 0xc9, 0xa2, 0x4d, 0xc7, 0x60, 0xa0, 0x30, 0xad, 0x7c, 0xd5, 0xb0, 0x88, 0x14, 0xf0, 0x13, 0x6a, 0x08, 0x06, 0x81, 0x02, 0x88, 0x40, 0x60, 0x00, 0x34, 0x09, 0x79, 0x07, 0xfe, 0x5f, 0xe0, 0x87, 0x51, 0x60, 0x00, 0x65, 0x15, 0x4f, 0xdc, 0x2e, 0xb2, 0x41, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x99, 0xd8, 0x2b, 0x00, 0x00, 0x00, 0xd5, 0xac, 0x34, 0x6f, 0x5c, 0x75, 0x62, 0x81, 0x91, 0x8a, 0x06, 0x07, 0xb3, 0xe3, 0x26, 0x85, 0xfb, 0x2d, 0x92, 0xa5, 0x77, 0x1d, 0x4d, 0xcd, 0xe7, 0x58, 0xfc, 0x6a, 0x64, 0x2b, 0x63, 0x2b, 0x13, 0x82, 0xd0, 0xac, 0xa2, 0x9c, 0x22, 0xf8, 0x79, 0xc8, 0x14, 0xf5, 0xf5, 0x38, 0x16, 0xcd, 0x4e, 0x82, 0x8a, 0x0c, 0xe9, 0x43, 0x3d, 0x10, 0x94, 0x0c, 0x00, 0x54, 0x3a, 0x80, 0xa4, 0x50, 0x38, 0x88, 0x08, 0x01, 0xd0, 0x1f, 0xe4, 0xdc, 0x46, 0xad, 0xc6, 0xcc, 0xd6, 0x6c, 0x49, 0x8a, 0xc5, 0x86, 0x53, 0x41, 0x71, 0x88, 0xfb, 0x54, 0x00, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x0d, 0x94, 0x2e, 0x01, 0x01, 0x00, 0x46, 0x68, 0x05, 0xd8, 0xd9, 0xbe, 0x4b, 0xa0, 0x2c, 0x58, 0xbe, 0x52, 0x22, 0x37, 0x36, 0xae, 0xc3, 0x01, 0x30, 0x6f, 0x77, 0x00, 0x30, 0x42, 0xbf, 0xb4, 0x6e, 0xdd, 0xcd, 0x39, 0x5f, 0x2f, 0xaf, 0x2a, 0xd7, 0xc7, 0x0a, 0xa9, 0x6b, 0xc3, 0xdc, 0x79, 0x31, 0xab, 0xac, 0xac, 0x28, 0x45, 0x20, 0x12, 0xbd, 0xa9, 0xac, 0x2a, 0xc3, 0x40, 0x14, 0x42, 0x02, 0x00, 0x0c, 0x1a, 0x16, 0x11, 0x94, 0x98, 0x02, 0x7e, 0xb3, 0xab, 0x19, 0xe9, 0x2b, 0xd1, 0x20, 0x25, 0x16, 0xaf, 0xa4, 0x04, 0xfb, 0xa2, 0x13, 0xd9, 0x1b, 0xae, 0x64, 0x56, 0x20, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x0d, 0x16, 0x2b, 0x02, 0x00, 0x86, 0x2c, 0x05, 0x00, 0x25, 0x27, 0xee, 0x5e, 0x74, 0xcf, 0xda, 0x02, 0x24, 0x41, 0x3a, 0xc5, 0xb8, 0xc9, 0xfe, 0xb2, 0x49, 0xfc, 0xad, 0x10, 0x62, 0xcc, 0x6a, 0x66, 0x22, 0xb5, 0xea, 0xdc, 0x5b, 0x6e, 0x63, 0xa1, 0x3a, 0xa8, 0x1d, 0x08, 0xaa, 0x28, 0x4a, 0x93, 0x48, 0x24, 0x00, 0x31, 0x60, 0x02, 0xdb, 0x3e, 0x55, 0xfc, 0x9c, 0x73, 0xde, 0x74, 0x5f, 0x65, 0x56, 0x0d, 0x7a, 0xf9, 0x0f, 0x18, 0xdb, 0xa9, 0x23, 0x40, 0x2f, 0x4b, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x11, 0x8e, 0x85, 0x16, 0x89, 0x00, 0x8b, 0x00, 0x40, 0x08, 0x31, 0xbc, 0x45, 0x42, 0xdc, 0x51, 0x4a, 0x09, 0x20, 0x89, 0xd2, 0x22, 0x40, 0x0e, 0xfb, 0x06, 0xa9, 0x5b, 0x19, 0x40, 0x64, 0x0a, 0x2d, 0x92, 0x7d, 0xcd, 0x1d, 0xa4, 0x9c, 0x9c, 0x09, 0xc6, 0xee, 0xd5, 0x4a, 0xbe, 0x1a, 0x73, 0x16, 0x84, 0x94, 0xb1, 0x68, 0x24, 0x5b, 0x44, 0x0b, 0x80, 0x53, 0x4a, 0x85, 0x20, 0xa0, 0x00, 0x00, 0x39, 0x5f, 0x01, 0xff, 0x5a, 0x40, 0xad, 0x0a, 0xb0, 0xa9, 0x00, 0xdf, 0x04, 0xd4, 0x18, 0x6c, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x85, 0x09, 0x92, 0x85, 0x15, 0x80, 0x97, 0x16, 0x01, 0x60, 0x05, 0xac, 0x17, 0x71, 0x79, 0x56, 0x76, 0x16, 0xf7, 0x68, 0xa2, 0xd6, 0x3a, 0xd0, 0x8c, 0x04, 0x3d, 0x17, 0xdc, 0x53, 0x3a, 0x3c, 0xdd, 0xde, 0x8c, 0xa1, 0x59, 0x21, 0x62, 0x7b, 0xa1, 0xe0, 0xb1, 0x9b, 0x6c, 0x6f, 0x69, 0xc2, 0x8b, 0xdc, 0xb5, 0xea, 0x00, 0xc7, 0x48, 0x4a, 0xd5, 0x54, 0xba, 0x41, 0x22, 0x10, 0x50, 0x05, 0x81, 0xfb, 0xbb, 0x6f, 0x69, 0x00, 0x18, 0xc2, 0xae}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x8a, 0x12, 0x82, 0x18, 0x00, 0x5b, 0x6a, 0x81, 0x02, 0x38, 0xc0, 0x7f, 0xdf, 0x37, 0x6c, 0xc1, 0xac, 0x6c, 0x20, 0xb8, 0x7d, 0x65, 0xd0, 0x11, 0x8f, 0x39, 0xc3, 0x13, 0x8e, 0x7d, 0x3d, 0x60, 0x2d, 0x94, 0xf6, 0x1e, 0x17, 0xa4, 0x06, 0x04, 0x1c, 0x61, 0x0d, 0xe4, 0xff, 0x55, 0xeb, 0xda, 0x7e, 0x1d, 0x65, 0xed, 0x04, 0x2e, 0x0c, 0xe6, 0x70, 0x91, 0x20, 0x80, 0x05, 0x34, 0x04, 0xe0, 0x0c, 0x00, 0x00, 0xa1, 0xc5, 0xe2, 0x01, 0xc7, 0x80, 0x03, 0xbc, 0xb9, 0x1e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x11, 0x4e, 0x32, 0x10, 0x01, 0x68, 0x02, 0xf4, 0x40, 0x93, 0xdd, 0x68, 0x62, 0x0c, 0x6f, 0x5f, 0xe4, 0xae, 0x88, 0x6f, 0xbe, 0x13, 0x1b, 0x7b, 0xbf, 0xac, 0xa8, 0xc1, 0x1e, 0x9b, 0x54, 0x57, 0xe9, 0xef, 0x56, 0x31, 0x51, 0x0f, 0x1f, 0x29, 0xab, 0x13, 0x0a, 0xef, 0xde, 0xb5, 0xa7, 0xf0, 0x9c, 0x7c, 0x4d, 0x42, 0x4e, 0xe5, 0x62, 0xa0, 0x45, 0x40, 0x29, 0xa8, 0x61, 0x51, 0x08, 0x10, 0x06, 0xe5, 0x39, 0xc7, 0x56, 0xa5, 0x49, 0x60, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x11, 0x92, 0x70, 0x00, 0x91, 0x0a, 0xb0, 0x09, 0xe4, 0x06, 0x67, 0x6a, 0x40, 0x68, 0x43, 0x86, 0x00, 0x55, 0x84, 0xbd, 0x48, 0x6e, 0x90, 0x11, 0xa8, 0x54, 0x12, 0x2d, 0xa0, 0x93, 0x46, 0xbb, 0x89, 0x1a, 0xae, 0x3a, 0xde, 0x8a, 0x53, 0x77, 0x74, 0xf1, 0x5e, 0x16, 0xb1, 0xb7, 0xca, 0x81, 0x72, 0xd7, 0x2a, 0x76, 0x26, 0xb7, 0xdd, 0xcc, 0x21, 0x54, 0x80, 0xa3, 0x95, 0x02, 0xc4, 0x20, 0x31, 0x08, 0x0c, 0x00, 0x79, 0x1e, 0x73, 0xe8, 0x40, 0x70, 0x6b, 0x6f, 0x4c, 0x06, 0x8e, 0xd6, 0x7c, 0xcf, 0x60, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x2c, 0xe4, 0x05, 0x90, 0x00, 0x2d, 0xa2, 0xec, 0x76, 0x1e, 0xbf, 0x48, 0x63, 0x00, 0x89, 0x7d, 0x44, 0x26, 0x8a, 0xc8, 0xef, 0x39, 0xcb, 0x58, 0x01, 0x4d, 0xee, 0x4b, 0xac, 0xf5, 0x33, 0x57, 0xe1, 0xb4, 0xb8, 0x2d, 0x3a, 0x65, 0x84, 0x65, 0x72, 0x3a, 0x63, 0x1a, 0x12, 0x27, 0x3c, 0x31, 0xcb, 0x3d, 0x06, 0xd4, 0xe8, 0x9d, 0x09, 0x9b, 0x18, 0x51, 0x50, 0x24, 0x05, 0x45, 0x10, 0x4c, 0x0a, 0x11, 0x81, 0x84, 0x05, 0x90, 0x4c, 0xc9, 0xeb, 0x48, 0x38, 0x36, 0x4a, 0x70, 0x5d, 0xe5, 0x04, 0x2b, 0x37}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x7d, 0x21, 0xca, 0x30, 0x1e, 0xc0, 0x00, 0x02, 0x12, 0xc0, 0xd5, 0x59, 0xc1, 0xe8, 0x84, 0x0e, 0xe4, 0x02, 0x44, 0xe0, 0x38, 0x42, 0x65, 0x8c, 0xba, 0xd7, 0x3e, 0xec, 0x44, 0x56, 0x5a, 0xdf, 0x02, 0x6a, 0x9f, 0xc6, 0xde, 0x7a, 0x47, 0x4c, 0x29, 0x78, 0xb1, 0xf3, 0x75, 0x19, 0xe1, 0x55, 0xaa, 0x48, 0x2c, 0x67, 0x80, 0x26, 0x12, 0x56, 0xe0, 0x02, 0x98, 0x03, 0x42, 0x41, 0x82, 0x45, 0x00, 0x60, 0x08, 0x03, 0x6c, 0x15, 0x38, 0xaf, 0xb7, 0xf0, 0x52, 0xb9, 0x45, 0x23, 0x10, 0x70, 0x02, 0x47}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x11, 0x52, 0x30, 0x59, 0x9c, 0x02, 0x2c, 0x19, 0xa1, 0x60, 0x11, 0xd0, 0x4a, 0x21, 0x66, 0x35, 0x3c, 0x3c, 0x2b, 0xa5, 0xcf, 0xfc, 0x89, 0xab, 0xee, 0xf9, 0x42, 0xef, 0x3c, 0x7e, 0x13, 0x99, 0xef, 0xc3, 0x4c, 0x34, 0x89, 0x0e, 0x65, 0x87, 0xba, 0x08, 0xe9, 0x83, 0xb2, 0xcb, 0x61, 0x5a, 0x85, 0x68, 0x0a, 0x58, 0xa2, 0x24, 0x40, 0x05, 0x44, 0x18, 0x14, 0x24, 0x04, 0x88, 0x00, 0x67, 0x83, 0x4e, 0x2c, 0x2d, 0x1e, 0xc9, 0xce, 0x8a, 0x66, 0x01, 0x33, 0x79, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x21, 0x4a, 0x30, 0x00, 0x0d, 0x68, 0xa0, 0x0e, 0x28, 0x12, 0x22, 0xec, 0x42, 0xb2, 0x1e, 0xb5, 0x7c, 0x65, 0x40, 0x17, 0x43, 0x68, 0x4d, 0xde, 0xbc, 0xbd, 0x01, 0x53, 0xfe, 0x79, 0x60, 0xdf, 0xaf, 0xba, 0x9c, 0xe3, 0x95, 0x8b, 0x7c, 0x24, 0xbd, 0x9a, 0x2e, 0x9f, 0x4b, 0x3d, 0x3b, 0x92, 0xae, 0x03, 0xee, 0x24, 0xb2, 0xec, 0xb5, 0x0c, 0x25, 0x44, 0xc0, 0x53, 0x41, 0x81, 0x02, 0x70, 0x40, 0x40, 0x00, 0x96, 0xcb, 0xc1, 0x1e, 0x14, 0x1c, 0xe3, 0x20, 0x8a, 0xbe, 0x10, 0xa4, 0xa5, 0x0a, 0x20, 0x03, 0xfe, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x11, 0x52, 0x6e, 0x01, 0x00, 0x5a, 0xa5, 0x80, 0xab, 0x34, 0x06, 0xa8, 0xf5, 0x30, 0x3d, 0x10, 0x17, 0x53, 0x7c, 0xb7, 0xa9, 0xae, 0xdc, 0x19, 0x63, 0x97, 0xee, 0x81, 0xa8, 0xfc, 0xbb, 0x56, 0xc5, 0xcc, 0xd5, 0x4a, 0x06, 0x78, 0x0a, 0x1d, 0xa2, 0xb3, 0xf9, 0x34, 0xfa, 0x49, 0x1d, 0x6b, 0x2a, 0x1b, 0x03, 0x01, 0x61, 0x75, 0x35, 0x18, 0x1a, 0x21, 0x02, 0x08, 0x40, 0x80, 0xb0, 0x3d, 0x9b, 0xdf, 0x92, 0x19, 0x7c, 0x8a, 0x20, 0xc2, 0x56, 0x24, 0x56, 0x0a, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x21, 0x54, 0x2b, 0x02, 0xcb, 0x10, 0x28, 0x1d, 0x58, 0x1c, 0xbd, 0x65, 0x9a, 0x28, 0x45, 0x1b, 0x66, 0x30, 0x54, 0xf9, 0xd3, 0xae, 0x31, 0xb9, 0x7d, 0xdf, 0x14, 0x29, 0x5e, 0x89, 0xb8, 0x17, 0x89, 0xa5, 0x41, 0x64, 0x13, 0xce, 0x03, 0xa9, 0xe2, 0xb3, 0x14, 0x0a, 0x44, 0x5d, 0x2e, 0xab, 0x37, 0x49, 0x48, 0xd1, 0xf9, 0xe1, 0x4a, 0xc0, 0x8b, 0x18, 0x0a, 0xc6, 0x19, 0xb0, 0x0a, 0x21, 0x04, 0x00, 0x07, 0x0b, 0xa1, 0x59, 0x77, 0x20, 0xd5, 0x9a, 0x71, 0x07, 0x30, 0x78, 0xe2, 0x0f, 0x7b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x92, 0x2e, 0x01, 0x00, 0x04, 0x00, 0x0d, 0x03, 0xef, 0x60, 0xa0, 0x1a, 0xb8, 0x9d, 0x5a, 0x94, 0x3a, 0x39, 0x78, 0x16, 0xed, 0xa2, 0x0a, 0x28, 0x78, 0x56, 0x80, 0x07, 0x05, 0xc9, 0x2f, 0x1e, 0xfe, 0xfc, 0x9d, 0xbd, 0x11, 0xa5, 0x76, 0x66, 0xb2, 0x7a, 0x11, 0x89, 0x8a, 0xca, 0xc0, 0xc5, 0x31, 0x68, 0x89, 0x50, 0x95, 0x10, 0x2c, 0xa6, 0x82, 0xaa, 0x00, 0xa2, 0x30, 0x40, 0x00, 0x00, 0xb0, 0xdb, 0x6e, 0x9f, 0xa0, 0xc8, 0xd3, 0x30, 0x40, 0x50, 0x9f, 0x76, 0xa0, 0xa5, 0xfc, 0x62, 0x20, 0x72, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x21, 0x4a, 0x30, 0x09, 0x6d, 0xa0, 0x00, 0x38, 0x00, 0x8f, 0xf6, 0xee, 0x5e, 0x9e, 0xa0, 0xdd, 0xcc, 0xc4, 0x11, 0x19, 0x10, 0x90, 0x13, 0x92, 0x24, 0x8f, 0x4f, 0xab, 0x2a, 0x35, 0xdb, 0x9e, 0xbc, 0xe1, 0x6b, 0x29, 0x1b, 0xab, 0x80, 0xa5, 0x61, 0xae, 0x38, 0x8c, 0x1b, 0xa9, 0x4e, 0x70, 0xe9, 0xfd, 0xf1, 0xd9, 0x68, 0x10, 0x8f, 0xd0, 0x42, 0xb3, 0x02, 0x45, 0xc0, 0x2a, 0x00, 0x34, 0x25, 0x28, 0x1c, 0x44, 0x0c, 0x12, 0x00, 0xc7, 0x96, 0x90, 0x72, 0x1b, 0xd4, 0xaf, 0xc2, 0xcb, 0xc3, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x63, 0x20, 0xea, 0x82, 0x11, 0x9a, 0x14, 0x03, 0xa6, 0x80, 0xee, 0xf8, 0x72, 0x4a, 0x7e, 0x2d, 0x40, 0xbc, 0xb5, 0xb8, 0x5f, 0xd5, 0x09, 0x4b, 0xe4, 0x30, 0xcf, 0xa7, 0x72, 0xe1, 0x18, 0x18, 0xa9, 0x45, 0x65, 0x09, 0xad, 0x14, 0xe6, 0x53, 0x60, 0x45, 0xd7, 0xf3, 0x79, 0x3b, 0xc4, 0x92, 0x4a, 0x3a, 0x54, 0x2b, 0xcd, 0x8a, 0x53, 0x54, 0x34, 0x00, 0x2a, 0x58, 0x82, 0xb0, 0x70, 0x80, 0x00, 0x6d, 0xb3, 0x19, 0xef, 0xc9, 0xaf, 0x92, 0x00, 0x29, 0xec, 0x22, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0x20, 0xea, 0x00, 0x00, 0x00, 0xe1, 0xa0, 0x43, 0x61, 0xfb, 0x9e, 0x2f, 0xcf, 0x40, 0x80, 0x1d, 0x68, 0x3c, 0x64, 0xe7, 0x33, 0xee, 0x3f, 0x49, 0xda, 0x38, 0xf0, 0x35, 0x75, 0x32, 0xf2, 0x71, 0xd3, 0x09, 0x9a, 0x07, 0xaf, 0x43, 0x50, 0x96, 0x12, 0x76, 0x14, 0x20, 0x04, 0x0a, 0x5f, 0x51, 0x30, 0x16, 0x00, 0xaa, 0x81, 0x9a, 0x42, 0x22, 0xc0, 0xa0, 0x49, 0x1e, 0xfb, 0xc2, 0x8f, 0xcd, 0xd5, 0x03, 0xe7, 0xa2, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x11, 0x52, 0x30, 0x00, 0x00, 0x00, 0xf6, 0x01, 0xe2, 0xf0, 0x64, 0xb4, 0x8d, 0xb5, 0xc1, 0xb1, 0xbc, 0xb8, 0x31, 0xe3, 0xb6, 0xad, 0x3c, 0x58, 0xa1, 0x5e, 0xa9, 0xa6, 0x8d, 0xfd, 0x5f, 0xda, 0xfc, 0xa0, 0x97, 0x33, 0x8c, 0x14, 0x9c, 0x27, 0xf2, 0xd0, 0xe6, 0x98, 0x82, 0x54, 0xb0, 0xf3, 0xa0, 0x72, 0xb7, 0x12, 0x20, 0x60, 0x00, 0xa3, 0x00, 0xd0, 0x8d, 0x00, 0xd1, 0x18, 0x08, 0x00, 0xe0, 0x15, 0x58, 0xe0, 0xb5, 0x33, 0xfd, 0x80, 0x7d, 0x97, 0xfe, 0x82, 0xea, 0x28, 0x05, 0x2f, 0x01, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x15, 0x50, 0x48, 0x14, 0x00, 0x01, 0xb0, 0x34, 0xd2, 0x3a, 0x08, 0x2d, 0xe9, 0xd1, 0xa0, 0x92, 0x13, 0x9d, 0xab, 0x2a, 0x33, 0xa9, 0x77, 0xd9, 0x0b, 0x8a, 0x96, 0x98, 0xf7, 0xfc, 0x81, 0x27, 0x2d, 0xbd, 0x6f, 0x3e, 0x54, 0xd9, 0x42, 0x03, 0x01, 0xaa, 0xd4, 0xa6, 0xcc, 0xd4, 0x96, 0xce, 0x06, 0x6c, 0x89, 0x60, 0xa8, 0xd5, 0x20, 0x58, 0x01, 0x10, 0x0a, 0xa5, 0x70, 0x34, 0x44, 0x70, 0x21, 0x03, 0xd8, 0x0e, 0xce, 0xec, 0xfb, 0x03, 0x31, 0x9a, 0x08, 0x31, 0x7b, 0x00, 0x30, 0x06, 0x00, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x15, 0x1a, 0x68, 0x01, 0x80, 0x00, 0x14, 0x16, 0xe8, 0x07, 0x60, 0xf8, 0x41, 0x62, 0x28, 0x7e, 0xe3, 0xad, 0x02, 0x96, 0xea, 0xf0, 0x48, 0xcf, 0xed, 0x71, 0xa0, 0x3c, 0x2d, 0xd1, 0xd7, 0xfb, 0x4f, 0x21, 0xda, 0xc8, 0x69, 0x2e, 0x1f, 0x93, 0x8b, 0xcc, 0x69, 0x55, 0x8f, 0xcb, 0x54, 0x42, 0xc1, 0xa2, 0x20, 0x1c, 0x50, 0x0a, 0xd7, 0x68, 0x41, 0x67, 0x05, 0x05, 0x06, 0x1d, 0xe4, 0x07, 0x30, 0x9c, 0x58, 0x80, 0x03, 0x1a, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x15, 0x1a, 0x69, 0x01, 0x1b, 0xe0, 0x00, 0x15, 0x6a, 0xd2, 0xec, 0x07, 0x2f, 0xe4, 0x10, 0xae, 0xef, 0x8d, 0xb1, 0xfd, 0x4e, 0xb7, 0x47, 0x75, 0xff, 0x49, 0x73, 0x96, 0xff, 0x9a, 0x60, 0x03, 0x1a, 0x13, 0x1b, 0xd6, 0x13, 0x76, 0xaf, 0xc4, 0x54, 0x00, 0xe5, 0x95, 0x2b, 0xd5, 0x7d, 0xe3, 0x49, 0x4e, 0xd0, 0xcd, 0x8b, 0x93, 0x76, 0x84, 0x19, 0xf4, 0x84, 0xad, 0x05, 0xc5, 0x89, 0x2b, 0x94, 0xe1, 0x60, 0x2c, 0x3b, 0xbc, 0x65, 0x00, 0x23, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x21, 0x1c, 0x27, 0x2b, 0x34, 0xa8, 0x54, 0xab, 0xce, 0x01, 0x63, 0x56, 0x04, 0x18, 0x6d, 0xab, 0x5d, 0xbc, 0x2f, 0x1e, 0xa7, 0xcc, 0xa5, 0x02, 0x01, 0xc8, 0xcb, 0xbf, 0x56, 0xc4, 0x62, 0xa1, 0x7d, 0x82, 0x29, 0xac, 0x7c, 0x32, 0xb5, 0x66, 0xab, 0x0e, 0x0b, 0xf8, 0x84, 0xac, 0xe4, 0x57, 0x9f, 0xfa, 0x46, 0xac, 0x2f, 0x75, 0x52, 0xcc, 0x5f, 0x96, 0x86, 0x5c, 0x23, 0x0c, 0x40, 0x11, 0xe2, 0x84, 0x49, 0x00, 0x59, 0x09, 0xc2, 0xc7, 0x42, 0xc5, 0x1b, 0xc5, 0x78}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x19, 0x4a, 0x8a, 0x14, 0x21, 0xb3, 0x35, 0x5a, 0x4b, 0xb3, 0x03, 0x47, 0x58, 0x03, 0xcd, 0x59, 0x09, 0x3a, 0x11, 0xe9, 0xc0, 0x5f, 0x6d, 0x59, 0xf7, 0x2d, 0xc1, 0xaa, 0xbf, 0x4c, 0xae, 0xd5, 0x6c, 0xaf, 0x7b, 0x95, 0x07, 0x1e, 0x66, 0xd5, 0x66, 0x17, 0xce, 0xd1, 0x85, 0xfe, 0xa0, 0x48, 0x4e, 0x1f, 0x43, 0xa6, 0xe9, 0x12, 0xbd, 0x57, 0xfd, 0xf3, 0x7c, 0x27, 0x67, 0xcc, 0xd2, 0x05, 0x54, 0x87, 0x4a, 0x44, 0x00, 0x2a, 0x98, 0x80, 0xc2, 0x08, 0x30, 0x5f, 0xb0, 0x0d, 0x77, 0x89, 0x67, 0x39, 0x1e, 0x3e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x75, 0x19, 0x5e, 0x28, 0x52, 0x65, 0xe6, 0x8b, 0x34, 0x18, 0x07, 0x96, 0x80, 0x18, 0x24, 0xa8, 0xa1, 0x29, 0x8a, 0x63, 0xa1, 0x7e, 0x98, 0x58, 0xde, 0xfd, 0x74, 0x7a, 0x59, 0xf7, 0xf5, 0x42, 0xca, 0xe0, 0x21, 0x55, 0xa5, 0x85, 0x04, 0x97, 0x15, 0xb7, 0xaf, 0xa5, 0x89, 0x91, 0x9c, 0xc4, 0x3b, 0x58, 0x46, 0x2b, 0xd7, 0x9c, 0x43, 0x02, 0x20, 0x50, 0xe1, 0x4a, 0x48, 0x20, 0x02, 0x9a, 0x06, 0x1a, 0x00, 0x1a, 0x8b, 0x91, 0xbb, 0x41, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x85, 0x19, 0x8e, 0x70, 0x58, 0x64, 0x27, 0xb0, 0xa2, 0x80, 0xf2, 0xb0, 0x40, 0x3b, 0xa3, 0x4e, 0x89, 0x80, 0x36, 0x74, 0x07, 0x86, 0x50, 0x57, 0x18, 0xa0, 0x85, 0xfa, 0x46, 0xf9, 0xa8, 0x07, 0x42, 0xab, 0xe5, 0x0c, 0x1d, 0xec, 0x16, 0xaa, 0x08, 0x5f, 0x6f, 0x9d, 0xf7, 0xae, 0xc5, 0xa1, 0xd5, 0x50, 0x71, 0xb5, 0x1c, 0x07, 0x1e, 0xb4, 0x23, 0x22, 0x28, 0x2e, 0x59, 0xcc, 0x56, 0x70, 0xac, 0xb9, 0x08, 0xad, 0xc5, 0x00, 0x59, 0x08, 0xc3, 0x40, 0x51, 0x6e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x21, 0xc6, 0x6b, 0x41, 0x89, 0x02, 0xa5, 0x36, 0xd2, 0x40, 0x0d, 0x34, 0x01, 0x00, 0x2a, 0x2a, 0x13, 0x3b, 0x2a, 0xf2, 0x1a, 0x5e, 0xcc, 0x52, 0xec, 0x10, 0x2b, 0x6e, 0x19, 0x7a, 0x79, 0x64, 0x6b, 0x7c, 0x05, 0xec, 0x52, 0x50, 0x27, 0x83, 0x4a, 0xa9, 0x47, 0x46, 0x50, 0x50, 0xcd, 0x80, 0xc3, 0x42, 0x1f, 0x5f, 0xf0, 0x8e, 0x64, 0x2a, 0xb0, 0xf7, 0x02, 0x53, 0x07, 0x2e, 0x03, 0xb8, 0x0a, 0xb5, 0x38, 0x58, 0x00, 0xba, 0xf7, 0x6e, 0xbb, 0x40, 0x6b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x34, 0xe0, 0x00, 0x2c, 0xc5, 0x02, 0x0b, 0xb0, 0x5e, 0x88, 0x11, 0xd0, 0xa7, 0x2e, 0xc2, 0x26, 0xa7, 0xec, 0x18, 0xae, 0xdf, 0x40, 0x58, 0x5e, 0x01, 0xf6, 0x93, 0x9b, 0x40, 0x91, 0xac, 0x2b, 0x7e, 0x49, 0xd3, 0xe0, 0xe9, 0xe8, 0x40, 0xbe, 0xb7, 0x40, 0x44, 0x5e, 0x70, 0x4b, 0x88, 0xfb, 0x87, 0x55, 0xeb, 0x3b, 0x1a, 0x08, 0x80, 0x20, 0x00, 0x5c, 0x05, 0x52, 0x0c, 0x22, 0x21, 0x04, 0x00, 0xef, 0x3e, 0x11, 0x75, 0x27}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x2c, 0xe4, 0x00, 0x00, 0x02, 0x70, 0x02, 0x67, 0x0a, 0xfc, 0x44, 0x0c, 0xfd, 0x4e, 0x0c, 0x47, 0x78, 0x17, 0x68, 0xe0, 0x6f, 0x08, 0x44, 0x08, 0xe1, 0x51, 0x2c, 0x76, 0x47, 0xe9, 0xb2, 0x7a, 0x4f, 0x12, 0xb0, 0x1b, 0xbc, 0x45, 0x3c, 0x3b, 0x25, 0x54, 0x24, 0x56, 0xb0, 0x76, 0xab, 0x3a, 0xcf, 0xbe, 0xb4, 0xef, 0x09, 0xe9, 0x7a, 0xa7, 0x30, 0x04, 0x44, 0xa3, 0xad, 0x08, 0x00, 0x15, 0x2e, 0x60, 0x70, 0x84, 0x10, 0x09, 0x62, 0x7d, 0x3e, 0x9c, 0x81, 0xc2, 0x42, 0xce}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x35, 0x58, 0x24, 0x65, 0xc0, 0x86, 0x80, 0x00, 0xf6, 0x00, 0xae, 0xc0, 0x31, 0x17, 0x2d, 0x07, 0x2f, 0x54, 0x65, 0xcb, 0xad, 0x30, 0x60, 0x33, 0xb0, 0x32, 0x32, 0x6d, 0x1c, 0x78, 0x1f, 0x45, 0xe5, 0xc2, 0xf6, 0xa0, 0x99, 0x63, 0x46, 0x8d, 0x45, 0xfe, 0x1e, 0x10, 0xbb, 0x89, 0x2e, 0x80, 0x44, 0x20, 0x82, 0xf9, 0x31, 0xb4, 0xeb, 0xa5, 0x5d, 0xdb, 0x9b, 0x9a, 0x51, 0x7b, 0x9a, 0x01, 0x35, 0x84, 0x7e, 0xd0, 0x24, 0x02, 0xa1, 0x4a, 0x0f, 0x10, 0x82, 0x02, 0xc0, 0xff, 0xbb, 0xd7, 0x40, 0xc4, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x34, 0xe0, 0x00, 0x00, 0xc9, 0x5a, 0x2b, 0xa5, 0x82, 0xce, 0xc2, 0xb2, 0xa2, 0xcd, 0xa9, 0x6c, 0x20, 0x7f, 0x55, 0x93, 0x49, 0xe8, 0x44, 0x0c, 0x21, 0x54, 0x1a, 0x38, 0x45, 0x65, 0x78, 0xce, 0x3c, 0x27, 0x74, 0x6d, 0xc6, 0x74, 0xfb, 0x46, 0x53, 0xfd, 0x7f, 0x83, 0xe4, 0x51, 0x0a, 0x11, 0x8b, 0x86, 0xa4, 0xf9, 0x53, 0xc1, 0xbd, 0xc9, 0xdb, 0x65, 0x80, 0x0a, 0xaf, 0x2b, 0xde, 0xb2, 0x00, 0x14, 0xf0, 0x30, 0x3a, 0x84, 0x12, 0x21, 0x04, 0x00, 0x06, 0xb7, 0xa2, 0xe3, 0xbe, 0xf1, 0xb5, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x30, 0x88, 0xc2, 0x35, 0xa2, 0xc4, 0x02, 0xc0, 0x06, 0x80, 0x9d, 0x9c, 0xd1, 0x19, 0x88, 0x79, 0xa0, 0x67, 0xbd, 0xc6, 0xe7, 0x12, 0xcb, 0x91, 0x70, 0x15, 0x04, 0x83, 0xe0, 0xcb, 0x59, 0xbb, 0xb7, 0x18, 0xfe, 0xcd, 0x27, 0x7a, 0x5c, 0xc7, 0x57, 0x19, 0x1e, 0xb5, 0x7e, 0xb5, 0x7e, 0x25, 0xc3, 0x83, 0x11, 0xc2, 0x9a, 0xcb, 0xd1, 0x90, 0x00, 0x35, 0x58, 0xe6, 0x00, 0x15, 0x30, 0x20, 0x23, 0x08, 0x18, 0x21, 0x04, 0x07, 0x41, 0xd5, 0xdf, 0x83, 0x01, 0x6e, 0x95, 0x23, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x19, 0x56, 0x2c, 0x00, 0x9e, 0x34, 0x43, 0x50, 0x07, 0xb7, 0x3c, 0x83, 0x1b, 0x23, 0x63, 0x36, 0xd7, 0xd1, 0x2d, 0x01, 0xa5, 0xed, 0x4a, 0x0e, 0x10, 0xb8, 0x57, 0x45, 0x70, 0xdf, 0xdd, 0x17, 0xc1, 0xdf, 0xce, 0x0d, 0x14, 0x3e, 0x2b, 0xfa, 0xe6, 0xf2, 0xda, 0xb5, 0xe3, 0xb3, 0x09, 0x21, 0xe3, 0x99, 0x9f, 0x60, 0x52, 0x37, 0x0e, 0xd0, 0x02, 0x68, 0x41, 0x60, 0x00, 0xa7, 0x81, 0x81, 0x18, 0x41, 0x40, 0xb1, 0x43, 0x27, 0x46, 0x0a, 0xd3, 0x6a, 0x90, 0x0b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x6b, 0x16, 0xc2, 0xca, 0x36, 0x89, 0x27, 0x3a, 0x14, 0xd0, 0x0b, 0x25, 0x81, 0x7d, 0xa5, 0x1d, 0x9c, 0x3d, 0xd5, 0x60, 0x1d, 0x3e, 0xa2, 0x05, 0x0a, 0x16, 0x24, 0x13, 0x59, 0x3d, 0xe0, 0x83, 0xa4, 0xc6, 0xea, 0x15, 0x14, 0x80, 0xd0, 0x63, 0xf8, 0x22, 0xb6, 0xd1, 0xc1, 0x47, 0x22, 0x24, 0x34, 0xdd, 0xaf, 0xdc, 0x69, 0xec, 0x5a, 0x9a, 0x0a, 0x16, 0x74, 0x00, 0x50, 0x20, 0xba, 0xd6, 0x00, 0x0a, 0xc3, 0x40, 0x55, 0x00, 0x1f, 0xe9, 0xba, 0xf6, 0x90, 0x8f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x19, 0x96, 0x2c, 0x00, 0x00, 0x1c, 0x56, 0xda, 0x68, 0x04, 0x2d, 0xd9, 0x74, 0x8b, 0x73, 0x37, 0xd2, 0x6e, 0xdd, 0xeb, 0x17, 0xa0, 0x0b, 0x14, 0x26, 0x12, 0x2b, 0x28, 0xd1, 0x88, 0xad, 0xff, 0xb2, 0x1b, 0xd0, 0x00, 0x8c, 0x67, 0x00, 0x2b, 0xe0, 0xed, 0x98, 0xd3, 0x36, 0xdc, 0xd8, 0x69, 0x21, 0x38, 0xd3, 0x3f, 0xec, 0x44, 0xd9, 0x24, 0x17, 0x6f, 0x56, 0x80, 0xd0, 0x4b, 0x23, 0x5d, 0xd3, 0x00, 0x2c, 0x0c, 0x41, 0xb4, 0x16, 0xf8, 0x7c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6b, 0x15, 0xd8, 0xc3, 0x14, 0x80, 0x6f, 0x81, 0x50, 0xb0, 0x6f, 0xe8, 0x05, 0x98, 0xfb, 0x6c, 0xe7, 0x71, 0xec, 0x4b, 0x3f, 0xba, 0xa9, 0xdd, 0xe6, 0xb8, 0x86, 0xbd, 0xd6, 0xef, 0x34, 0x3a, 0x8d, 0x38, 0xba, 0x19, 0xaf, 0x22, 0x8a, 0xa9, 0x34, 0xdf, 0x54, 0xf7, 0xfd, 0x44, 0x70, 0xa0, 0x6e, 0xea, 0x40, 0x30, 0x0b, 0x3e, 0x35, 0x98, 0x67, 0x0c, 0xb9, 0xb2, 0xde, 0x02, 0xd7, 0x89, 0x81, 0xb7, 0x75, 0xe6, 0x00, 0x58, 0x90, 0x81, 0x42, 0x10, 0x82, 0xc0, 0xef, 0x5d, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x73, 0x25, 0x5e, 0x25, 0x01, 0x49, 0xbb, 0xf2, 0x18, 0x03, 0xd8, 0x0e, 0x69, 0x6b, 0x63, 0x6c, 0x4c, 0xc3, 0xd5, 0xc0, 0x6d, 0xeb, 0x40, 0xbb, 0x76, 0xdd, 0xb8, 0xf3, 0x3f, 0xeb, 0x95, 0x6f, 0xda, 0x4f, 0x0b, 0xec, 0xc2, 0x6f, 0x20, 0x15, 0xdd, 0x59, 0x9f, 0xdb, 0x55, 0xd5, 0xd3, 0x95, 0x6c, 0x99, 0x04, 0x43, 0x50, 0xd7, 0x51, 0xa9, 0xac, 0x74, 0x18, 0xec, 0x35, 0x42, 0x14, 0x98, 0x64, 0x60, 0x26, 0xf7, 0xc9, 0xbc, 0x00, 0xaa, 0x42, 0x03, 0x04, 0x20, 0xc7, 0x00, 0x73, 0xef, 0xe7, 0x1f, 0xe8, 0x2b, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x15, 0xca, 0xc3, 0x55, 0x09, 0x80, 0x01, 0x05, 0x0a, 0x38, 0x68, 0x01, 0x1b, 0xf0, 0xe6, 0x29, 0x72, 0xcd, 0xd0, 0x20, 0xf7, 0x28, 0xc3, 0xe2, 0x9e, 0x9c, 0x3c, 0x9c, 0xef, 0xf5, 0x31, 0x7a, 0x06, 0x2f, 0x8b, 0x9a, 0x10, 0x49, 0x52, 0x24, 0xcd, 0xb7, 0xdf, 0x2d, 0x4c, 0xac, 0x4d, 0x00, 0x75, 0x49, 0xc8, 0xf5, 0xdb, 0x6b, 0x41, 0x16, 0x77, 0xca, 0x02, 0x40, 0xc3, 0x2a, 0x15, 0x54, 0x02, 0xbc, 0x4c, 0x17, 0x00, 0x79, 0x98, 0x4b, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x11, 0xe0, 0x69, 0x41, 0x88, 0x2a, 0x2b, 0x50, 0x18, 0xf6, 0x00, 0x68, 0x9e, 0x14, 0x71, 0x15, 0x2f, 0x89, 0x1d, 0x46, 0x47, 0x5e, 0x8f, 0x83, 0xc3, 0x5e, 0xed, 0xf1, 0x86, 0x55, 0x7d, 0x08, 0xdc, 0x5e, 0x65, 0x8a, 0x2a, 0x4b, 0xcd, 0x71, 0x59, 0x6a, 0x70, 0x98, 0x6c, 0x30, 0xc9, 0x9f, 0x60, 0x46, 0x57, 0x87, 0x9e, 0x3e, 0x22, 0xc0, 0x6e, 0x1a, 0x68, 0x4f, 0x9e, 0x48, 0x06, 0x0a, 0xb3, 0x00, 0x15, 0x8a, 0x50, 0xc2, 0xf4, 0x07, 0xbb, 0xb2, 0xbb, 0x74, 0x65, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x18, 0x03, 0x06, 0x55, 0x89, 0x45, 0x15, 0x4f, 0x60, 0x4d, 0x82, 0x9a, 0xe8, 0x09, 0x49, 0xef, 0x54, 0xc9, 0x29, 0x76, 0x80, 0x14, 0x63, 0x46, 0x7d, 0xd4, 0x1f, 0x70, 0x34, 0x04, 0x06, 0xc8, 0xcb, 0x43, 0x72, 0x38, 0x2c, 0xb6, 0xbd, 0xdd, 0xe9, 0x85, 0x94, 0x2b, 0x29, 0x9c, 0xa8, 0xcf, 0xdf, 0xa7, 0x19, 0x2a, 0x57, 0x02, 0x48, 0x26, 0xce, 0xf2, 0xe4, 0xe4, 0x24, 0x09, 0x4c, 0x3d, 0x40, 0x4c, 0xb4, 0x40, 0x2b, 0xc5, 0x21, 0x45, 0x00, 0x1e, 0xdf, 0x00, 0x99, 0x2e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x32, 0x82, 0x87, 0x14, 0x80, 0x08, 0x16, 0xdd, 0x20, 0xe8, 0x04, 0xf2, 0x83, 0x3c, 0x72, 0xa4, 0x32, 0xf0, 0xb5, 0x23, 0x56, 0x14, 0xe0, 0x57, 0x28, 0x0e, 0x49, 0x33, 0x94, 0x53, 0xc1, 0x4f, 0x5a, 0x10, 0x54, 0xdd, 0x22, 0x67, 0xaf, 0x9b, 0x16, 0x65, 0x9c, 0xb5, 0x1d, 0xbd, 0x7f, 0xf6, 0x54, 0xcc, 0x59, 0xa5, 0x12, 0x9a, 0xad, 0xd1, 0x4d, 0x12, 0x54, 0x5d, 0x04, 0xc0, 0x02, 0x80, 0x0a, 0xf3, 0x48, 0x50, 0x00, 0x3e, 0xc1, 0xbd, 0xd3, 0x2a, 0x4f, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x73, 0xb8, 0x88, 0xe6, 0x12, 0x90, 0x36, 0x4b, 0xb1, 0x60, 0x1e, 0x70, 0x0d, 0xfe, 0x8f, 0x66, 0x9e, 0x87, 0x47, 0x04, 0xf1, 0x25, 0x78, 0xe2, 0xb8, 0x34, 0xb1, 0x9b, 0x86, 0x3f, 0xfa, 0xe9, 0xcd, 0x70, 0x09, 0xa7, 0x78, 0x8d, 0x25, 0xe7, 0x87, 0x7a, 0xb6, 0x1a, 0xbf, 0x41, 0x7a, 0xfa, 0x2a, 0xd3, 0x8a, 0xd4, 0x82, 0x89, 0x93, 0x66, 0x2e, 0x3c, 0x56, 0x14, 0x56, 0x56, 0xc2, 0x5e, 0x54, 0xe5, 0x18, 0x40, 0xba, 0x60, 0x0a, 0x2a, 0x02, 0xc0, 0xd4, 0x13, 0x68, 0x00, 0x68, 0xfd, 0x9f, 0x88, 0x12, 0x8f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x74, 0x11, 0x68, 0x25, 0x41, 0x59, 0xc0, 0x63, 0x45, 0x1a, 0x2c, 0xe8, 0x0a, 0xa3, 0xb8, 0x42, 0x69, 0x3b, 0xc4, 0x5e, 0xbe, 0x50, 0xea, 0xdc, 0xb5, 0x2e, 0x7b, 0xe3, 0xd8, 0x9a, 0xae, 0xc4, 0xf5, 0x7d, 0x92, 0x93, 0x10, 0x64, 0xa1, 0x05, 0x15, 0xd0, 0xaf, 0xd7, 0xcb, 0x0e, 0x99, 0xbe, 0x26, 0x74, 0x25, 0xa4, 0x06, 0x3e, 0x7a, 0x6f, 0x46, 0x65, 0x9a, 0x04, 0x64, 0x26, 0x67, 0x88, 0x25, 0x8a, 0x99, 0x66, 0x01, 0x58, 0x69, 0x0a, 0x2c, 0x00, 0xf3, 0xff, 0xd4, 0x01, 0x2e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x15, 0x92, 0x86, 0x34, 0x80, 0x25, 0x29, 0x52, 0x01, 0xa6, 0x96, 0x08, 0x6e, 0x1f, 0x02, 0x65, 0x75, 0xc7, 0xc5, 0x56, 0x18, 0xb1, 0xd9, 0x35, 0x7b, 0xa4, 0x60, 0xad, 0x1d, 0xec, 0xa4, 0x0d, 0xc0, 0xa9, 0x08, 0xfc, 0xf9, 0x1e, 0x1d, 0x67, 0x6d, 0x66, 0xc5, 0xa1, 0x89, 0xae, 0x25, 0xa2, 0xbe, 0x7b, 0xd2, 0xea, 0x56, 0x61, 0x44, 0xa7, 0x23, 0x6f, 0xda, 0xb9, 0xb6, 0xea, 0xf7, 0x6c, 0x77, 0x56, 0x9b, 0x66, 0x22, 0x40, 0x2c, 0xb4, 0x2d, 0x00, 0x29, 0x98, 0x6a, 0x70, 0x98, 0x00, 0x1e, 0x4c, 0x1b, 0x09, 0x03, 0xbe, 0x2f, 0xef, 0x99, 0x25, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x99, 0x90, 0x86, 0x14, 0x80, 0x10, 0x00, 0x1d, 0x00, 0x13, 0xf9, 0xbe, 0x3e, 0x1d, 0x14, 0x82, 0xea, 0xbd, 0x82, 0xca, 0x0a, 0xe4, 0x3a, 0xaf, 0xdf, 0x28, 0xd8, 0x89, 0x15, 0xd9, 0xb2, 0xf4, 0x07, 0xed, 0x8d, 0x97, 0xe2, 0xa4, 0x69, 0xf1, 0xc7, 0x3b, 0x69, 0x05, 0x27, 0x28, 0xf8, 0x51, 0xfb, 0x73, 0x0f, 0xbb, 0x85, 0xde, 0xff, 0x03, 0x7d, 0xfe, 0xde, 0x2c, 0x0d, 0x26, 0x8e, 0x72, 0xa7, 0x7d, 0xa4, 0x09, 0x09, 0x12, 0xdd, 0xdc, 0x5c, 0x0a, 0x75, 0x38, 0xb0, 0x14, 0x00, 0x00, 0x03, 0x5f, 0x0c, 0x70, 0xed, 0x02, 0xfe, 0xb1, 0x8b, 0x21, 0x16, 0x0b, 0xf5, 0xb4, 0x80, 0x29, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x58, 0x48, 0x12, 0xa6, 0xe9, 0x6d, 0xf0, 0x95, 0xa0, 0x08, 0x2f, 0xa0, 0x0e, 0xff, 0xf5, 0x55, 0x98, 0x22, 0xb1, 0xa0, 0xba, 0xbe, 0xbc, 0xf5, 0x26, 0x5c, 0x66, 0x7a, 0x58, 0xf0, 0xd4, 0x1f, 0x73, 0xb3, 0xbb, 0x0d, 0xee, 0xeb, 0x92, 0x91, 0xa1, 0x75, 0xf8, 0x27, 0x05, 0x56, 0xb3, 0x1f, 0xc0, 0xee, 0x3f, 0xeb, 0xcc, 0xdb, 0x4d, 0x46, 0xbb, 0xed, 0xa0, 0x1e, 0xea, 0x2a, 0x13, 0x5a, 0x00, 0x68, 0x0e, 0x00, 0x52, 0xb0, 0xcd, 0xc0, 0x31, 0x08, 0x20, 0x05, 0x80, 0x02, 0xcd, 0x36, 0xcd, 0x2e, 0x07, 0x77, 0xf1, 0x3f, 0x56, 0x34, 0xbe, 0xc2, 0x78, 0xbc, 0x18, 0xba, 0x90, 0x91, 0x78, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x95, 0x26, 0x25, 0x15, 0x90, 0x2b, 0x4b, 0x00, 0xb1, 0x6b, 0x07, 0x5c, 0x1d, 0x99, 0x14, 0x3d, 0x55, 0x4c, 0x33, 0x44, 0x86, 0x23, 0x11, 0xfa, 0x59, 0xc0, 0xf3, 0xfb, 0x08, 0xc9, 0xff, 0xab, 0xf9, 0x79, 0x18, 0x03, 0xfb, 0x00, 0x03, 0x28, 0x49, 0xdc, 0x00, 0xb2, 0xa6, 0xc3, 0xdb, 0xa0, 0xb6, 0xdc, 0x2a, 0x4f, 0x6c, 0x1c, 0xd9, 0xbc, 0x69, 0x55, 0x9e, 0xde, 0xf1, 0x8a, 0x0c, 0xdf, 0xea, 0x54, 0x4d, 0x1a, 0xaa, 0x09, 0xd0, 0x58, 0x0a, 0x75, 0x58, 0x24, 0x42, 0x08, 0x40, 0x00, 0x71, 0xd7, 0xa3, 0xa8, 0xe9, 0xe8, 0xae, 0x73, 0x98, 0x00, 0x75, 0xa7, 0x57}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x95, 0x94, 0x8b, 0x11, 0x80, 0x01, 0x44, 0xab, 0x68, 0x00, 0x4d, 0x25, 0x71, 0xfb, 0xdd, 0xcd, 0x21, 0xc5, 0x1d, 0x11, 0x8b, 0x20, 0x5c, 0xfc, 0x6b, 0xf5, 0x37, 0xa5, 0x6d, 0x97, 0x2e, 0xb4, 0x2a, 0x4c, 0xb1, 0xab, 0xda, 0xb5, 0x44, 0x43, 0x84, 0x87, 0x9d, 0xca, 0x59, 0x1c, 0x39, 0x8e, 0x57, 0xad, 0xb3, 0xb3, 0xbb, 0x83, 0x2b, 0x20, 0x53, 0xdc, 0x2a, 0x64, 0xa0, 0x2c, 0x66, 0xb8, 0x95, 0x62, 0x79, 0x11, 0x34, 0xe4, 0x60, 0xf1, 0x6e, 0xdf, 0x29, 0x66, 0x1e, 0x3a, 0xd8, 0xc0, 0x9d, 0xc4, 0x7b, 0x01, 0x4c, 0xc4, 0x12, 0x82, 0xc4, 0x20, 0x80, 0x04, 0x11, 0xd6, 0xb8, 0x86, 0x32, 0x18, 0xc9, 0x45, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x15, 0x90, 0x88, 0x14, 0x02, 0x02, 0x04, 0x02, 0x06, 0x84, 0x0f, 0x05, 0xe4, 0xd5, 0x5d, 0x16, 0xbc, 0x85, 0x73, 0x08, 0x4c, 0xad, 0xa5, 0x94, 0xc2, 0x9a, 0x2c, 0x91, 0xa4, 0x46, 0xf7, 0x9c, 0xc6, 0x3c, 0x2c, 0x00, 0xd6, 0x46, 0x88, 0x8b, 0x92, 0xad, 0xe9, 0x12, 0xe1, 0x77, 0x3c, 0x29, 0xef, 0xb8, 0x6e, 0xa4, 0xed, 0x9c, 0xe7, 0xa7, 0x6e, 0x05, 0x75, 0xa5, 0x59, 0x6a, 0x8d, 0x25, 0x7a, 0x0e, 0xf6, 0x84, 0x6c, 0xa8, 0x88, 0x14, 0xb4, 0x42, 0x38, 0x18, 0x42, 0x0b, 0x02, 0xb3, 0x40, 0x30, 0xb8, 0xef, 0x41, 0xc9, 0x4b, 0x24, 0x01, 0x2f, 0xb2, 0x28, 0x17, 0xc2, 0xe0, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x89, 0x96, 0x47, 0x40, 0x91, 0xc0, 0x26, 0x10, 0xb2, 0x00, 0xb0, 0x1a, 0x0c, 0x13, 0xcf, 0x82, 0x1b, 0xd5, 0x9a, 0xae, 0xc5, 0x56, 0x32, 0xa4, 0x25, 0x9c, 0x8c, 0x09, 0xb8, 0x03, 0x8c, 0x59, 0x3d, 0x37, 0xc0, 0xa8, 0xb5, 0xa9, 0x48, 0x6e, 0x78, 0xef, 0x25, 0x41, 0x24, 0x73, 0xd5, 0xe3, 0xf9, 0xe6, 0x5d, 0x7d, 0x3c, 0x70, 0xca, 0xb4, 0xd1, 0xd6, 0x26, 0x26, 0x4e, 0xbc, 0x71, 0x03, 0xd4, 0xdb, 0xfa, 0xb0, 0x16, 0x29, 0x4a, 0x58, 0x00, 0xd6, 0xd5, 0x9a, 0xc2, 0x4a, 0x10, 0x03, 0xe9, 0x5f, 0xa0, 0x6b, 0xa1, 0x79, 0x0a, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x15, 0x18, 0x6c, 0x24, 0x00, 0x54, 0x81, 0x68, 0x1a, 0x04, 0x2c, 0x5e, 0x70, 0x0d, 0xd3, 0xa3, 0x0d, 0x4b, 0x77, 0x7b, 0x76, 0x97, 0xad, 0xa5, 0x14, 0x2e, 0x6b, 0x3c, 0x16, 0xe7, 0xd4, 0x23, 0x22, 0xf7, 0x67, 0x45, 0xe8, 0x42, 0x5a, 0xff, 0x63, 0x58, 0x61, 0x8f, 0x51, 0x7e, 0x3a, 0xcd, 0x58, 0xd0, 0x5f, 0x40, 0x21, 0x33, 0x8d, 0x42, 0x40, 0x05, 0x54, 0x08, 0x52, 0x12, 0x00, 0x28, 0x3a, 0xc3, 0x34, 0x20, 0xc2, 0x2f, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x0d, 0x5e, 0x2b, 0x53, 0x9b, 0xba, 0x90, 0x54, 0x4a, 0x96, 0x0b, 0x1d, 0x01, 0x27, 0x30, 0xaf, 0xc7, 0xb0, 0xa9, 0x9b, 0xcf, 0x28, 0x96, 0x75, 0x4c, 0x95, 0xea, 0x26, 0xdb, 0x94, 0x8c, 0xf4, 0x46, 0xb3, 0xce, 0xee, 0xe2, 0xe6, 0x1a, 0x2f, 0x71, 0x81, 0xcf, 0x9b, 0xed, 0xd3, 0x59, 0xfa, 0xb2, 0xee, 0x3d, 0x56, 0xa0, 0x83, 0x54, 0xf5, 0xdd, 0x9e, 0x3b, 0x08, 0x00, 0x63, 0x02, 0xb8, 0xd2, 0x14, 0x3a, 0x00, 0x7b, 0xcf, 0x27, 0xfb, 0x9d, 0x14, 0xb2, 0xbc}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x21, 0x08, 0xc5, 0x33, 0x09, 0x00, 0x40, 0x00, 0x6e, 0x43, 0x41, 0xa0, 0x3a, 0xf2, 0xaa, 0x45, 0x31, 0xa0, 0x97, 0xe3, 0x4a, 0x17, 0x57, 0x08, 0x33, 0x5a, 0x00, 0xbe, 0xf2, 0xa5, 0xf4, 0x95, 0x75, 0xed, 0x25, 0xbe, 0x0a, 0xbc, 0x44, 0xb6, 0x8b, 0x2d, 0x2e, 0x45, 0x97, 0x73, 0xa4, 0xb4, 0x1a, 0xb4, 0x6f, 0xd4, 0x67, 0x8e, 0xe1, 0x93, 0x70, 0x69, 0xc1, 0xab, 0xd3, 0xcf, 0xa1, 0xa9, 0xb9, 0x8c, 0xf4, 0xe6, 0xe4, 0x74, 0xd1, 0x5a, 0xa9, 0x0a, 0x2c, 0x00, 0x7e, 0x9c, 0xd6, 0x36, 0x00, 0x27, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x21, 0x0a, 0xc5, 0x15, 0x80, 0x21, 0xca, 0xac, 0x16, 0x3a, 0x9d, 0x00, 0x1b, 0xa7, 0x65, 0xb1, 0x30, 0x30, 0xca, 0xa8, 0xe1, 0x0d, 0x86, 0x5a, 0x18, 0x08, 0xf0, 0xe3, 0xb9, 0x9f, 0xc8, 0x6b, 0x5a, 0xe2, 0x11, 0x1a, 0xe9, 0x24, 0xdf, 0xee, 0x27, 0xe3, 0x2a, 0xdf, 0xa8, 0x86, 0x59, 0x80, 0xc0, 0xa1, 0x51, 0xb7, 0xc9, 0xc6, 0x12, 0xb1, 0x86, 0x90, 0xb5, 0x24, 0x15, 0x4c, 0x6f, 0x16, 0xc2, 0x0e, 0x1b, 0xc0, 0x52, 0xd0, 0xc4, 0xe1, 0x30, 0x00, 0x0d, 0xeb, 0xb5, 0xdb, 0xa5, 0xa0, 0x81, 0xa3, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x20, 0x4b, 0x05, 0x14, 0x80, 0x90, 0x16, 0x14, 0xb2, 0x01, 0x60, 0x83, 0x7a, 0xd5, 0x94, 0x4e, 0x91, 0x0e, 0x4f, 0x28, 0x40, 0xd2, 0x14, 0xfe, 0x6d, 0x31, 0xc6, 0xe8, 0xa9, 0xd4, 0x40, 0x86, 0xec, 0xd9, 0xa8, 0xfe, 0x78, 0xa7, 0xa1, 0x0a, 0xc7, 0xbc, 0x23, 0x26, 0x53, 0xbf, 0xb3, 0xff, 0xe6, 0x49, 0x17, 0x83, 0x3c, 0x60, 0xb7, 0x5c, 0x39, 0x83, 0x28, 0x01, 0x82, 0x41, 0x5a, 0xc3, 0x13, 0x05, 0x1c, 0x00, 0x01, 0xee, 0xef, 0xa6, 0x51, 0x05, 0x78}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x8c, 0x21, 0x0f, 0x03, 0x14, 0x80, 0x9a, 0x2a, 0x42, 0xca, 0x26, 0x58, 0x1e, 0xc0, 0x54, 0xa0, 0xce, 0x10, 0xdb, 0x20, 0x70, 0xf1, 0x05, 0x7b, 0xa7, 0x84, 0xbb, 0x28, 0xf3, 0xf6, 0x33, 0x7b, 0xbc, 0x41, 0x5f, 0xf4, 0x80, 0x6b, 0x2d, 0x92, 0x90, 0xe1, 0x2a, 0x4a, 0x2e, 0x26, 0xf9, 0xdd, 0xe1, 0xeb, 0x0b, 0x0a, 0xd6, 0xd7, 0x76, 0x52, 0x36, 0x9c, 0x84, 0x8a, 0x3d, 0xf0, 0x24, 0xdd, 0xbe, 0x0c, 0xb9, 0xaa, 0xa0, 0x62, 0x70, 0x9a, 0xc0, 0x58, 0x76, 0xa2, 0x7b, 0x2c, 0x9c, 0x0d, 0x3c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x1d, 0x06, 0xe8, 0x35, 0x80, 0x02, 0x80, 0x2c, 0xb7, 0xd0, 0x44, 0xbb, 0x1e, 0xd0, 0x00, 0xeb, 0xb1, 0x4b, 0x37, 0x54, 0x38, 0x8e, 0x17, 0x72, 0x07, 0x2d, 0x72, 0x66, 0xc4, 0x68, 0x19, 0xcb, 0x8d, 0x55, 0xf5, 0x25, 0x5d, 0xbc, 0xcf, 0x46, 0x53, 0x1d, 0xf6, 0xdb, 0xd6, 0x9f, 0x26, 0x70, 0x5b, 0x6a, 0x57, 0x34, 0x5f, 0x0e, 0x7c, 0x1b, 0x7a, 0x39, 0x71, 0x80, 0x24, 0x16, 0x0b, 0xc0, 0x35, 0x68, 0x05, 0x4c, 0x0c, 0x34, 0x03, 0x92, 0xcf, 0x48, 0x43, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x1d, 0x60, 0x26, 0x00, 0x02, 0x83, 0x40, 0xe1, 0xd0, 0x21, 0x93, 0xdf, 0x1b, 0x8a, 0xc8, 0xab, 0x7c, 0x15, 0x86, 0x2b, 0xd2, 0x24, 0x44, 0xb1, 0x4a, 0x82, 0x4d, 0xe5, 0x9f, 0x53, 0xe1, 0xfd, 0x13, 0x8e, 0x0e, 0x3a, 0xac, 0x7a, 0x62, 0xf9, 0xfa, 0x91, 0x07, 0x7d, 0xc1, 0x09, 0x21, 0x62, 0x32, 0x84, 0x2a, 0x87, 0x9b, 0x53, 0x35, 0x66, 0x04, 0x8b, 0xd6, 0xa7, 0x36, 0x51, 0x32, 0x00, 0x58, 0x2a, 0x42, 0x8f, 0x68, 0x0b, 0x0e, 0x7f, 0xe7, 0x7b, 0xb1, 0xcc, 0x0b, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x1c, 0x8a, 0xa3, 0x62, 0x8a, 0x40, 0x11, 0x5b, 0x2e, 0xc0, 0x74, 0x80, 0x16, 0x73, 0xf7, 0xef, 0x97, 0x9f, 0xa7, 0x82, 0x4d, 0x4a, 0xd1, 0x7b, 0x6d, 0xc9, 0xcd, 0x79, 0x38, 0x41, 0x91, 0xda, 0xc6, 0x30, 0x14, 0xd0, 0x8d, 0x19, 0x1d, 0x00, 0x3e, 0x7c, 0x0e, 0x4a, 0x01, 0x66, 0x03, 0x99, 0x03, 0x20, 0x25, 0x3c, 0xe4, 0xff, 0x0b, 0x1d, 0x83, 0x40, 0xa6, 0x5a, 0xd8, 0x28, 0x2e, 0x98, 0x0a, 0xd1, 0x38, 0x58, 0x00, 0x78, 0x42, 0x9c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x11, 0x68, 0x25, 0x5c, 0x99, 0x60, 0x0a, 0xb2, 0x2c, 0x00, 0x38, 0x47, 0xf8, 0x49, 0x6e, 0xf7, 0xdc, 0x7f, 0x2c, 0x7f, 0xde, 0xb8, 0xf6, 0xcb, 0xf5, 0x49, 0x35, 0xc6, 0x74, 0x95, 0x29, 0x03, 0x59, 0xae, 0x73, 0x72, 0x55, 0x4e, 0x1d, 0x68, 0x76, 0x6e, 0x3b, 0x89, 0x46, 0x49, 0x9b, 0x31, 0x66, 0x0a, 0x87, 0x2c, 0x29, 0x54, 0x9e, 0xa9, 0xe3, 0x49, 0x57, 0xbc, 0x5c, 0x91, 0xeb, 0x98, 0x24, 0x00, 0x0a, 0xa5, 0x40, 0x55, 0x08, 0xb0, 0xae, 0xff, 0xa0, 0x13, 0xde, 0x3e, 0x73, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x11, 0x8a, 0x85, 0x63, 0x00, 0x50, 0x62, 0x55, 0x99, 0x20, 0x88, 0x0b, 0x58, 0x58, 0x00, 0x5c, 0x6f, 0x26, 0x53, 0xaf, 0x50, 0xbb, 0xe0, 0xbf, 0x67, 0x96, 0x85, 0x6b, 0x40, 0xfa, 0x1f, 0xcf, 0xf8, 0xb8, 0xe7, 0xf6, 0x22, 0x0e, 0xfa, 0x50, 0x6f, 0x45, 0x26, 0x60, 0x6a, 0xc1, 0xc1, 0x1c, 0x4a, 0x6c, 0x08, 0xe1, 0xc5, 0x48, 0x17, 0xe7, 0x0b, 0x3c, 0x22, 0x92, 0x2b, 0x82, 0x18, 0xde, 0x23, 0xb5, 0x65, 0xe7, 0x8d, 0x61, 0x0c, 0xaa, 0x16, 0x26, 0x50, 0x05, 0x2b, 0x0c, 0xcc, 0x0b, 0x10, 0x82, 0x00, 0x16, 0x2c, 0xf1, 0xf3, 0x4b, 0x44, 0x0d, 0xdb, 0xc5, 0x4d, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x15, 0x4c, 0x8e, 0x12, 0x1b, 0xb8, 0xa9, 0x00, 0x34, 0x09, 0x60, 0x07, 0x2b, 0x6f, 0xce, 0x93, 0xcc, 0xf0, 0x57, 0x82, 0x48, 0xdc, 0x72, 0xed, 0xbe, 0xff, 0x61, 0x19, 0x58, 0x50, 0x7b, 0x40, 0x35, 0x32, 0xbf, 0x43, 0xb0, 0xa0, 0xf9, 0x85, 0xed, 0x90, 0x0c, 0x0b, 0xb8, 0xac, 0xfe, 0x31, 0x09, 0xcc, 0x73, 0x28, 0x2a, 0x14, 0xae, 0x52, 0xe2, 0x1d, 0x67, 0x06, 0xad, 0xdb, 0x55, 0x83, 0x91, 0x6e, 0xaa, 0x2b, 0x4c, 0x96, 0x0a, 0x82, 0x40, 0x29, 0xd5, 0x41, 0x30, 0x05, 0x88, 0xfa, 0xfd, 0x9d, 0x45, 0xc2, 0xf6, 0x64, 0x21, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x98, 0x96, 0x83, 0x14, 0x90, 0x66, 0xe7, 0x03, 0x2d, 0x65, 0x82, 0xde, 0x40, 0x49, 0xe3, 0x6d, 0x9a, 0x4c, 0x63, 0xf9, 0xbc, 0x14, 0xfb, 0x25, 0x81, 0x36, 0x26, 0xef, 0x29, 0x8f, 0xb2, 0xe1, 0x3c, 0x65, 0x52, 0x27, 0x62, 0x3b, 0xb5, 0xfe, 0xc0, 0x2d, 0x8a, 0x4e, 0x24, 0x6e, 0x88, 0x9f, 0x1e, 0xfb, 0xe3, 0x04, 0xe1, 0x68, 0xdb, 0x2f, 0x79, 0x7c, 0x31, 0x99, 0xd5, 0x03, 0x6a, 0x58, 0x66, 0x35, 0x0d, 0x00, 0x51, 0x50, 0xc0, 0x6c, 0x11, 0x40, 0x14, 0x42, 0x04, 0x12, 0x00, 0x03, 0xaa, 0xe8, 0x0f, 0xf4, 0x39, 0xfb, 0xc2, 0x70, 0x17, 0xb8, 0x74, 0xc6, 0x06, 0x29, 0x2e, 0x11, 0x53, 0xd5, 0xe8, 0x9a, 0x2a, 0x9f, 0x70, 0x03, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x19, 0x4e, 0x46, 0x35, 0x00, 0x00, 0x08, 0x1d, 0x0d, 0x0b, 0xed, 0xd3, 0xdf, 0xb6, 0xb5, 0xec, 0x79, 0x45, 0xae, 0x64, 0xcb, 0xc8, 0x10, 0xdf, 0x7d, 0xe1, 0x54, 0xae, 0x1e, 0xc5, 0x55, 0x23, 0xa7, 0xf7, 0x7b, 0x12, 0x22, 0x76, 0xb9, 0xc9, 0xf0, 0xd2, 0x78, 0xab, 0xe8, 0xf3, 0x46, 0x57, 0x8d, 0x67, 0xc5, 0x82, 0x4d, 0xdd, 0x8a, 0x6a, 0x12, 0xbe, 0x88, 0x66, 0xd6, 0x18, 0xea, 0x02, 0x00, 0x51, 0x00, 0x68, 0x46, 0x70, 0x80, 0x84, 0x04, 0x02, 0x03, 0xc9, 0xbe, 0xc7, 0x84, 0x3d, 0xf3, 0xee, 0x1d, 0xb5, 0x60, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x25, 0x12, 0x6b, 0x0b, 0x11, 0x40, 0x00, 0x70, 0xb0, 0x0b, 0x7e, 0xab, 0x58, 0xe5, 0x48, 0x6b, 0x8c, 0xbc, 0x26, 0x82, 0x8e, 0x12, 0x28, 0x33, 0x35, 0x14, 0x93, 0x19, 0xd0, 0xa0, 0x04, 0xf8, 0xbf, 0x2d, 0xa9, 0xdd, 0xdd, 0x07, 0x51, 0xab, 0xdc, 0x79, 0xa0, 0x1d, 0xd1, 0x27, 0x66, 0x6a, 0xf5, 0xdc, 0x7b, 0x19, 0xcd, 0x25, 0xfb, 0xfa, 0xc9, 0x67, 0x80, 0xa0, 0x34, 0xc2, 0x21, 0x05, 0x71, 0x81, 0x41, 0x62, 0x74, 0x04, 0x04, 0x20, 0x20, 0x00, 0x0e, 0xf4, 0x0f, 0x67, 0x59, 0x67, 0xd8, 0x72, 0x0e, 0xb3, 0x00, 0x22, 0x22, 0x84, 0x8e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x18, 0x8c, 0xc6, 0x12, 0x20, 0x84, 0xab, 0x48, 0x29, 0x01, 0x01, 0x7c, 0x0d, 0x03, 0x91, 0x8f, 0x4d, 0x48, 0xd5, 0xd8, 0x74, 0x17, 0x3d, 0x5d, 0xdd, 0x47, 0x21, 0x59, 0x81, 0x00, 0xd9, 0x9b, 0xaf, 0x66, 0x98, 0x45, 0x54, 0x31, 0x05, 0x04, 0x4b, 0xb2, 0xa0, 0x63, 0xf5, 0x9d, 0x95, 0xc2, 0x5a, 0xe5, 0xf0, 0xb6, 0x14, 0x81, 0xe7, 0x8b, 0xe4, 0x4e, 0x68, 0x40, 0x3a, 0xa9, 0x00, 0x1b, 0x50, 0x4e, 0x00, 0x54, 0xaa, 0x02, 0xa0, 0x2c, 0x5f, 0xe3, 0xae, 0x53, 0xb0, 0x06, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x19, 0x4d, 0x02, 0x42, 0x0a, 0x40, 0x41, 0x02, 0xb2, 0x58, 0xde, 0xa1, 0x65, 0xe8, 0x11, 0x1e, 0x18, 0x91, 0x11, 0x4b, 0x48, 0x49, 0xdc, 0xef, 0xc8, 0xf8, 0xbd, 0x51, 0x5c, 0x70, 0x51, 0x25, 0xdd, 0x96, 0xdc, 0xea, 0xd1, 0x26, 0xca, 0x31, 0x31, 0x64, 0xf9, 0x0d, 0xfd, 0x63, 0x5d, 0x46, 0xcb, 0x48, 0xce, 0xaa, 0x92, 0xa9, 0x6b, 0x92, 0x87, 0x34, 0x08, 0x94, 0x69, 0xac, 0x04, 0x2c, 0x48, 0x41, 0xb5, 0x84, 0xff, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x34, 0x88, 0xa1, 0x42, 0x09, 0xc0, 0x6d, 0xa8, 0x00, 0x68, 0x79, 0x01, 0x72, 0xe0, 0x29, 0x07, 0xf0, 0x36, 0x30, 0xea, 0x73, 0x1e, 0x17, 0x88, 0x2e, 0x50, 0xc6, 0xe1, 0x10, 0x05, 0x4d, 0x9f, 0x26, 0xe3, 0x8d, 0x6c, 0xe8, 0xaf, 0x89, 0x9b, 0xf8, 0xa2, 0xdd, 0xb1, 0xed, 0xd3, 0x2b, 0x94, 0x9c, 0x1e, 0xb5, 0xfb, 0x53, 0x70, 0x63, 0x06, 0x5a, 0x6d, 0x4b, 0x40, 0xb0, 0x5c, 0x63, 0xc6, 0x98, 0xcd, 0x26, 0xdf, 0x4e, 0xde, 0xa0, 0x16, 0x44, 0x20, 0xda, 0x04, 0xcb, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x8c, 0xc8, 0xd6, 0xd5, 0x4a, 0x5b, 0x2e, 0x2a, 0xc0, 0x1d, 0x00, 0x23, 0x81, 0xaf, 0x8e, 0x79, 0x76, 0xd9, 0x56, 0xa7, 0x91, 0xba, 0xf4, 0xce, 0xce, 0x55, 0xb5, 0x97, 0x5f, 0xb1, 0xd9, 0x7b, 0x14, 0xb3, 0xd0, 0x19, 0x96, 0x32, 0x82, 0x09, 0xbc, 0xb2, 0xdd, 0xc3, 0x72, 0xa4, 0x75, 0xf9, 0x7d, 0x5f, 0xcf, 0x63, 0xb0, 0xde, 0x60, 0x1c, 0x6d, 0x0d, 0xfa, 0x73, 0x21, 0x74, 0xb1, 0xdc, 0x04, 0x89, 0xe8, 0x4c, 0x02, 0xad, 0x56, 0x12, 0x50, 0x00, 0x55, 0xfe, 0x51, 0xb8, 0x00, 0xb0, 0x1a, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x10, 0x03, 0x43, 0x73, 0xa1, 0x8d, 0x00, 0x51, 0x29, 0x65, 0x80, 0xbb, 0x01, 0x42, 0xac, 0x92, 0xa4, 0xb0, 0xf6, 0x66, 0xb5, 0xa2, 0x02, 0x65, 0xfc, 0xbb, 0x66, 0xea, 0x1d, 0xcf, 0xa0, 0xd1, 0xc6, 0xca, 0x63, 0x8b, 0x58, 0x9a, 0x1c, 0x67, 0x14, 0xc5, 0x96, 0x5b, 0xd7, 0x0b, 0xe0, 0xfa, 0x9a, 0x9c, 0x95, 0xed, 0x9b, 0xda, 0x5e, 0x22, 0x09, 0xfe, 0x36, 0x85, 0x54, 0xd1, 0x4b, 0x10, 0xd2, 0x1b, 0x34, 0xaa, 0x54, 0xa8, 0x05, 0x7a, 0xac, 0x24, 0xb8, 0x18, 0x03, 0x8f, 0xb7, 0x9c, 0xc0, 0x05, 0xec, 0x0b, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x1e, 0x48, 0x72, 0x05, 0x0a, 0xb6, 0x4d, 0x01, 0x5e, 0xc0, 0x07, 0x2a, 0xb4, 0x86, 0xd4, 0x0d, 0xcf, 0x18, 0x81, 0xb9, 0x1b, 0xb1, 0xf8, 0xe6, 0x96, 0x6d, 0x90, 0x9f, 0x03, 0xa5, 0x9d, 0x8e, 0x91, 0x9a, 0x69, 0xda, 0x6b, 0x47, 0xab, 0x1b, 0x31, 0xfa, 0xde, 0x66, 0x07, 0xb8, 0xf4, 0x08, 0x3d, 0x13, 0x8f, 0xa0, 0xf7, 0x10, 0xec, 0x5a, 0x34, 0x69, 0xd4, 0x02, 0x84, 0xf1, 0x00, 0x2b, 0xd5, 0x01, 0x54, 0x05, 0x07, 0x1f, 0x6d, 0x80, 0x0c, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x29, 0xc8, 0x47, 0x12, 0x80, 0xc0, 0x15, 0x53, 0x2c, 0x59, 0xb9, 0xab, 0x02, 0x03, 0x72, 0x4f, 0x01, 0xa1, 0x2f, 0x0c, 0x51, 0xe6, 0xf9, 0x70, 0x51, 0x77, 0x0b, 0x6a, 0xd0, 0xcd, 0x82, 0xbf, 0x87, 0xb2, 0x30, 0xf0, 0x17, 0x65, 0xef, 0x84, 0x93, 0x1a, 0x08, 0xd7, 0xd1, 0x8f, 0xf8, 0x7c, 0x30, 0x1d, 0xb3, 0xb7, 0xb1, 0xff, 0xe0, 0x2e, 0xdf, 0x0b, 0xda, 0xee, 0xb4, 0x77, 0x2f, 0x12, 0xb9, 0x56, 0x12, 0x20, 0x0c, 0x0f, 0x3f, 0x1d, 0xe8, 0x00, 0xc8, 0x16, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x35, 0x8a, 0x2b, 0x00, 0x01, 0x53, 0x4d, 0xd1, 0x6e, 0x0e, 0x82, 0xb5, 0x5d, 0x18, 0x07, 0x0b, 0xf9, 0x23, 0x5f, 0x5e, 0x3a, 0xd3, 0xf0, 0xaf, 0xb9, 0x38, 0x8a, 0x53, 0x27, 0x73, 0x7b, 0xbd, 0x0c, 0x34, 0xcc, 0xb0, 0x58, 0x04, 0x4d, 0x10, 0x82, 0xbd, 0x9c, 0x26, 0x05, 0x6c, 0x90, 0x84, 0x11, 0x79, 0x99, 0xf0, 0x6f, 0xe5, 0x3b, 0x41, 0x35, 0xc8, 0x01, 0xbd, 0x59, 0x57, 0x18, 0x01, 0x55, 0xac, 0x98, 0x15, 0xea, 0x20, 0xda, 0x83, 0xcf, 0x95, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x40, 0x5a, 0xcc, 0xb8, 0x48, 0x4e, 0x78, 0x0e, 0xbb, 0x07, 0x5a, 0x58, 0x55, 0x95, 0xe2, 0x4e, 0xb4, 0x99, 0x12, 0x78, 0x12, 0x54, 0x9a, 0xa5, 0x3e, 0x48, 0x4d, 0x03, 0xeb, 0x5c, 0x58, 0x9b, 0x8c, 0x57, 0x1c, 0x03, 0x03, 0x8c, 0x00, 0x42, 0x10, 0x31, 0x5d, 0x8a, 0x8f, 0xdb, 0x5d, 0x1e, 0xf5, 0x8b, 0x66, 0x92, 0xdc, 0x32, 0x39, 0xd8, 0x12, 0x09, 0x55, 0xf0, 0x93, 0x19, 0x50, 0x12, 0x89, 0x3b, 0x81, 0x5a, 0xaa, 0x09, 0x80, 0x02, 0xbf, 0x6e, 0x00, 0x00, 0x4b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x21, 0x0c, 0xc3, 0x16, 0x39, 0xbb, 0x0a, 0x85, 0x48, 0xd0, 0x04, 0xe8, 0x0a, 0xf1, 0x3c, 0xb2, 0x8c, 0xcb, 0x98, 0x9a, 0x41, 0x28, 0x46, 0x4e, 0x9b, 0x30, 0xb1, 0x07, 0xf2, 0x5b, 0xf5, 0xe9, 0xe9, 0xd5, 0x20, 0x4a, 0x9e, 0xbf, 0x72, 0xf1, 0xef, 0x6b, 0xe1, 0xcf, 0x46, 0x10, 0xd1, 0x1f, 0x9e, 0x8e, 0xac, 0x98, 0x8f, 0xcd, 0x1b, 0xa2, 0x39, 0x8d, 0x21, 0x51, 0xbc, 0x2d, 0x48, 0x80, 0x56, 0x30, 0x45, 0x41, 0x20, 0x00, 0x0f, 0xf4, 0x1b, 0x02, 0x6e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x11, 0x4b, 0x03, 0x63, 0x11, 0x84, 0xa1, 0x50, 0x68, 0xc8, 0xb0, 0x2c, 0x68, 0x0a, 0xfd, 0x34, 0x01, 0x2c, 0xa2, 0x11, 0xc3, 0x59, 0xb7, 0x9f, 0x88, 0x52, 0xcc, 0x78, 0x60, 0x15, 0x1d, 0x9d, 0x4d, 0x2a, 0x08, 0xa8, 0x6c, 0x16, 0x03, 0x85, 0x75, 0x5a, 0x45, 0x9f, 0x5d, 0x7a, 0x08, 0xdc, 0x3a, 0xa1, 0x02, 0x46, 0x47, 0x87, 0xf3, 0x8c, 0x47, 0x1f, 0xd3, 0xa1, 0xc6, 0xb5, 0x30, 0xc8, 0x53, 0x65, 0x4b, 0x80, 0x50, 0x14, 0x22, 0x05, 0x6a, 0x98, 0x2e, 0x56, 0x81, 0x5f, 0xa6, 0x62, 0x13, 0x9c, 0x4e, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x11, 0x94, 0x8a, 0x12, 0xa9, 0x86, 0x91, 0x00, 0x58, 0x87, 0x90, 0x1d, 0xf1, 0x51, 0x4f, 0x7c, 0x80, 0x20, 0x28, 0x46, 0xb1, 0xb7, 0x2f, 0xa8, 0xec, 0x53, 0x0a, 0x4c, 0xf6, 0xea, 0xfd, 0xea, 0x21, 0x2b, 0x0e, 0x94, 0x7a, 0x01, 0xa4, 0xcf, 0xf5, 0x7a, 0x9b, 0xeb, 0xa3, 0xc2, 0xa3, 0xcd, 0xa8, 0x67, 0x77, 0xa0, 0x4f, 0x90, 0xdf, 0x79, 0x8f, 0xe7, 0x01, 0x19, 0x2e, 0x3b, 0xa1, 0x5a, 0xad, 0x06, 0xda, 0x39, 0x8a, 0x84, 0x90, 0x96, 0x10, 0x29, 0x6c, 0xc1, 0x61, 0x08, 0x3a, 0x06, 0x5f, 0xf4, 0xa5, 0xd8, 0xd8, 0xcf, 0x00, 0x0c, 0x3b, 0x09, 0xe8, 0x01, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x09, 0x98, 0x43, 0x60, 0xa0, 0xc5, 0x00, 0xc8, 0x44, 0x29, 0x9d, 0x02, 0x16, 0x01, 0x3d, 0xb2, 0xd4, 0xe6, 0xad, 0x15, 0x53, 0x9b, 0x92, 0x3c, 0xc5, 0xc6, 0xea, 0xd2, 0xa1, 0x04, 0xb0, 0x81, 0xb2, 0x69, 0x89, 0x67, 0x64, 0x1a, 0x50, 0xa8, 0xc1, 0x56, 0xed, 0x57, 0x5a, 0x8a, 0xd1, 0xd6, 0x8d, 0xc0, 0x0d, 0x56, 0x6b, 0x2c, 0x7d, 0xe9, 0xcb, 0x9b, 0xc3, 0x5f, 0xc6, 0xc8, 0x5d, 0x11, 0x40, 0x50, 0xce, 0x0b, 0x80, 0x15, 0x8e, 0xa0, 0x9b, 0x08, 0x2c, 0x2b, 0xb0, 0xf3, 0xcd, 0x98, 0x48, 0x08, 0xb9, 0x8e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x0d, 0x9e, 0x45, 0x33, 0x15, 0xbd, 0x2b, 0x35, 0x22, 0x8a, 0xd0, 0x22, 0xd6, 0xe8, 0x26, 0xf4, 0xeb, 0xdb, 0xb8, 0xa1, 0xd4, 0xce, 0x87, 0x73, 0x02, 0x97, 0x44, 0x54, 0xac, 0x95, 0x53, 0x6b, 0x57, 0x19, 0x88, 0xcd, 0x38, 0x41, 0x8b, 0xc2, 0x08, 0x0a, 0x21, 0x81, 0x10, 0x3a, 0x16, 0xaa, 0x7c, 0x92, 0xb2, 0x78, 0xca, 0xf4, 0xfd, 0xd8, 0xc1, 0x13, 0x2a, 0xa7, 0xd2, 0xac, 0xe0, 0xed, 0x25, 0x89, 0x44, 0x49, 0x94, 0x5e, 0xc1, 0x38, 0x40, 0xce, 0x05, 0x35, 0x09, 0x10, 0x13, 0x00, 0x60, 0x43, 0x72, 0xd4, 0xcb, 0xf8, 0x16, 0x84, 0xe9, 0xc7, 0x0c, 0x77, 0x93, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x86, 0x18, 0x85, 0x50, 0xa1, 0x44, 0xa0, 0x01, 0x00, 0xab, 0x40, 0x74, 0x06, 0x93, 0x0e, 0x9d, 0xe9, 0xb9, 0x46, 0xa1, 0x4d, 0xa4, 0x74, 0x31, 0x00, 0x57, 0x15, 0x23, 0x84, 0x0b, 0x33, 0xe1, 0x1a, 0x53, 0x94, 0x9a, 0x0f, 0x9b, 0x40, 0x4f, 0xe0, 0xd1, 0xf8, 0xe6, 0x33, 0xcf, 0x5d, 0x09, 0xa9, 0xaf, 0x46, 0x4c, 0x2d, 0x18, 0x56, 0xc8, 0x52, 0x54, 0x5c, 0xe7, 0x10, 0xa0, 0xf2, 0xf6, 0xc2, 0xd7, 0x85, 0x4d, 0x44, 0xef, 0x6e, 0x72, 0xc2, 0x76, 0x9c, 0xae, 0x05, 0xc5, 0x80, 0xaa, 0x81, 0x91, 0xc2, 0x68, 0x65, 0x8c, 0x0a, 0xd2, 0x71, 0x8d, 0x51, 0xd9, 0xe5, 0xd0, 0x41, 0xb2, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0e, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x09, 0x18, 0xa5, 0x22, 0x30, 0x44, 0xa5, 0x45, 0x5c, 0x1b, 0xd3, 0x2e, 0xc1, 0xa0, 0x00, 0xc9, 0xb6, 0xf1, 0x8f, 0x7c, 0x33, 0x5e, 0x53, 0x27, 0xff, 0x49, 0x1a, 0x85, 0x6b, 0x2c, 0xf3, 0x39, 0x23, 0xcc, 0x6e, 0xd9, 0x36, 0x26, 0x4d, 0xaf, 0xe2, 0xa2, 0xbc, 0xe0, 0x25, 0xd3, 0x9a, 0x8b, 0x9d, 0xac, 0xd3, 0xb9, 0xa8, 0x8c, 0xec, 0x44, 0x50, 0x4a, 0x54, 0x0c, 0xd5, 0x5a, 0x40, 0x09, 0x40, 0x05, 0x2d, 0x18, 0x66, 0x04, 0x00, 0x00, 0xb1, 0x4e, 0x9a, 0x01, 0x71, 0x5c, 0xbc, 0x27, 0x06, 0x85, 0x0c, 0xa7, 0x2e, 0x25, 0x41, 0xc5, 0x0a, 0x00, 0x64, 0x85, 0x14, 0x01, 0xfd, 0x4a, 0x06, 0xcf, 0xc1, 0xd4, 0x1d, 0x11, 0xbe, 0x9e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x8d, 0x96, 0x43, 0x61, 0x0a, 0x80, 0x80, 0x00, 0x11, 0xd0, 0x08, 0x67, 0xc1, 0x4b, 0xc4, 0x62, 0x80, 0xa0, 0xaa, 0x39, 0x4a, 0xd7, 0xc2, 0x37, 0xfb, 0x06, 0x6e, 0x6b, 0x6a, 0x9b, 0xa3, 0x81, 0x54, 0x1a, 0xe4, 0x04, 0xfe, 0xf9, 0x3d, 0x5c, 0xe3, 0x7a, 0x41, 0x2a, 0x9a, 0x4c, 0xe0, 0x59, 0x29, 0x38, 0xbe, 0x50, 0x29, 0x76, 0xbf, 0xc3, 0xe1, 0xb2, 0xbc, 0x31, 0x92, 0xa8, 0xa5, 0xf4, 0xb3, 0xc8, 0x10, 0x7f, 0xdd, 0x5c, 0xee, 0x02, 0x8e, 0xc4, 0xaa, 0x03, 0x88, 0xc0, 0xe0, 0x00, 0x00, 0x91, 0xe5, 0xac, 0x37, 0x51, 0xeb, 0xeb, 0x39, 0x08, 0xed, 0x36, 0x5d, 0xe9, 0x15, 0x27, 0x40, 0xfd, 0x8e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x15, 0x26, 0x25, 0x11, 0x57, 0x55, 0x65, 0x68, 0x10, 0x0e, 0x80, 0xea, 0x73, 0xec, 0x8a, 0x1e, 0x10, 0xc1, 0x0a, 0xe5, 0x18, 0xcf, 0x53, 0xfa, 0xe9, 0x23, 0xe7, 0xba, 0x2a, 0xfc, 0x45, 0xb4, 0x30, 0x2a, 0x62, 0xfb, 0x96, 0xe7, 0x15, 0x1f, 0xed, 0xf3, 0x40, 0xba, 0x80, 0x78, 0xb4, 0xfe, 0x13, 0xdf, 0x04, 0x10, 0xf5, 0x31, 0xad, 0x22, 0x77, 0xa4, 0x60, 0x68, 0xea, 0x90, 0x28, 0x88, 0x2d, 0x22, 0x41, 0xfd, 0x29, 0x28, 0x00, 0xa6, 0xa1, 0xa9, 0xc0, 0xa2, 0x40, 0x50, 0xd1, 0x6e, 0x40, 0x0f, 0x73, 0xd3, 0x97, 0x25, 0x34, 0xfb, 0xf8, 0x6c, 0x61, 0xe5, 0x08, 0x61, 0x88, 0x1a, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x95, 0x66, 0x25, 0x00, 0x40, 0x01, 0x60, 0xe0, 0x03, 0x23, 0x4a, 0xc5, 0x7f, 0xcd, 0x66, 0x85, 0x1d, 0xdb, 0x44, 0xdc, 0xdc, 0x7a, 0xfb, 0xf2, 0x63, 0xc2, 0xfa, 0xb1, 0xf9, 0x5d, 0xda, 0xb1, 0xdf, 0xc1, 0x6e, 0xf5, 0x44, 0xe6, 0x91, 0x6b, 0xea, 0xee, 0x4d, 0x4b, 0x15, 0x52, 0x95, 0xca, 0x65, 0x24, 0xf0, 0x9c, 0x6a, 0x2a, 0xb2, 0x41, 0x39, 0x54, 0x6c, 0x9e, 0xe4, 0x66, 0xfd, 0xdc, 0x91, 0x02, 0xc5, 0x62, 0x3b, 0x90, 0x01, 0x49, 0x62, 0x62, 0x09, 0x02, 0x60, 0x0b, 0x06, 0xc4, 0x6d, 0x60, 0x4d, 0x77, 0xd4, 0xfc, 0xa6, 0x95, 0x84, 0x61, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x09, 0x8e, 0x8b, 0x14, 0xb2, 0xa4, 0x58, 0x2b, 0x40, 0x81, 0x76, 0xb0, 0x06, 0x07, 0xe9, 0x95, 0xc6, 0x57, 0xb7, 0x41, 0x51, 0x13, 0x21, 0x4a, 0xe5, 0x74, 0xc0, 0x35, 0xec, 0x95, 0x05, 0xa2, 0xcc, 0xc3, 0xf6, 0x85, 0x1b, 0xa2, 0xa6, 0x6b, 0x0f, 0xe9, 0x5f, 0x0a, 0xe6, 0x8f, 0x34, 0x30, 0x66, 0x78, 0x28, 0xad, 0x16, 0xa6, 0x9b, 0xd6, 0x91, 0x5a, 0x81, 0x2a, 0x93, 0x0a, 0x58, 0x44, 0x15, 0x4e, 0x60, 0xb8, 0x02, 0xfc, 0xbe, 0xcb, 0x48, 0xbb, 0xa4, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x95, 0x10, 0x29, 0x21, 0x09, 0x40, 0x02, 0x95, 0x2a, 0xf2, 0xec, 0xd2, 0x38, 0xb0, 0x6d, 0xcb, 0x2d, 0x81, 0xfd, 0x4d, 0x1c, 0x39, 0x8d, 0x62, 0x57, 0x0a, 0xa9, 0xf2, 0x4f, 0x5d, 0x8e, 0x31, 0x4b, 0x68, 0x7a, 0x93, 0xa7, 0x9a, 0x32, 0x4e, 0xda, 0xd9, 0x8b, 0xce, 0xb1, 0xbc, 0x09, 0x22, 0xda, 0x71, 0xab, 0xc9, 0xef, 0xe2, 0x29, 0x79, 0x0a, 0x24, 0x69, 0x5d, 0x0e, 0x02, 0xb9, 0xc4, 0x01, 0x55, 0x06, 0x12, 0x04, 0xdb, 0xe1, 0xa0, 0xe8, 0x2f, 0x53, 0xc6, 0x22, 0xc8, 0x5a, 0xc8, 0x02, 0xc6, 0x27, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x6d, 0x19, 0x18, 0x2b, 0x1c, 0x64, 0x08, 0x42, 0xb4, 0x11, 0x68, 0xf8, 0x08, 0xea, 0xfd, 0x99, 0x7a, 0xa2, 0x8f, 0x76, 0x53, 0x92, 0x0e, 0xb6, 0x8b, 0x0c, 0x39, 0x74, 0xd9, 0x28, 0x65, 0x24, 0xd5, 0x04, 0x5d, 0x6d, 0xed, 0x39, 0xd4, 0x52, 0xad, 0xe5, 0x0e, 0x9b, 0xa7, 0xd6, 0x78, 0xdc, 0xf6, 0xea, 0xd6, 0xa7, 0x6f, 0xc9, 0x5c, 0x5e, 0x4b, 0xd8, 0x33, 0xe2, 0x2e, 0x44, 0x16, 0x08, 0x02, 0x96, 0xd0, 0x0a, 0x11, 0x02, 0x40, 0x16, 0x19, 0xf8, 0x1f, 0x02, 0x5a, 0x75, 0x36, 0x41, 0x44, 0xe9, 0xe3, 0xc0, 0x00, 0x28, 0x8d, 0xc8, 0xcb, 0x1f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x11, 0x1e, 0x2a, 0x54, 0x52, 0x20, 0xad, 0x00, 0x45, 0x9a, 0x01, 0x7b, 0x4f, 0xcd, 0x2b, 0x54, 0xa8, 0xf6, 0x7b, 0x57, 0x62, 0x57, 0xf2, 0x85, 0xb3, 0xb4, 0x07, 0x4a, 0xd9, 0x66, 0xa0, 0x60, 0xb8, 0x19, 0x9e, 0x48, 0xa7, 0x99, 0x22, 0xd7, 0x69, 0x17, 0xe0, 0xee, 0xbc, 0x7d, 0x34, 0x47, 0xf4, 0xf8, 0x25, 0xdc, 0xb2, 0xa5, 0x05, 0x04, 0xd2, 0x62, 0x09, 0x00, 0x14, 0x96, 0x53, 0x28, 0x18, 0x42, 0x03, 0x10, 0x82, 0x00, 0x00, 0x33, 0xf3, 0xd0, 0x08, 0x72, 0xf2, 0xd7, 0x4d, 0x15, 0xda, 0x67, 0x71, 0x44, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x09, 0x20, 0x2b, 0x66, 0x13, 0x85, 0xe3, 0x2e, 0x00, 0xb3, 0x85, 0x80, 0xff, 0x4d, 0xa7, 0x4e, 0x7e, 0xd4, 0x16, 0x6f, 0x5d, 0x00, 0x43, 0x52, 0xae, 0x93, 0xe2, 0x52, 0xcf, 0x6e, 0x31, 0x2d, 0x56, 0xa7, 0xc2, 0x5a, 0x0d, 0x8a, 0xb1, 0x2a, 0x91, 0xba, 0xb9, 0x54, 0xbf, 0xf9, 0xaf, 0x3a, 0xb0, 0x93, 0x25, 0x98, 0x8c, 0xff, 0x0b, 0x49, 0x19, 0x61, 0xa0, 0x01, 0x4b, 0x43, 0x53, 0x81, 0x44, 0x20, 0xa1, 0x08, 0x08, 0x01, 0x6f, 0x21, 0x3f, 0xbd, 0x80, 0x1b, 0x63, 0x47, 0xd3, 0x8e, 0x98, 0x08, 0xae, 0x0f, 0xf4, 0x5e, 0x51, 0xca, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x1d, 0x18, 0x2a, 0x00, 0x08, 0x00, 0x3a, 0x34, 0x0e, 0xfd, 0xe6, 0xe4, 0xdc, 0xca, 0xe1, 0xe2, 0x20, 0xc0, 0xe8, 0x2d, 0x41, 0x31, 0xe9, 0x06, 0x5a, 0x03, 0x8f, 0xbb, 0xbd, 0x8a, 0x02, 0x4f, 0x79, 0x95, 0xc9, 0x7a, 0x7a, 0xb9, 0xa0, 0x53, 0xf3, 0x76, 0xc0, 0x5e, 0x78, 0x52, 0x85, 0x5b, 0xee, 0x21, 0x72, 0x2b, 0xdb, 0x0b, 0x12, 0x40, 0x95, 0xc5, 0x90, 0x05, 0x43, 0xa8, 0x26, 0x00, 0x0d, 0xff, 0x57, 0x76, 0x3a, 0x57, 0x4d, 0x1d, 0x0c, 0x60, 0x51, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0xa5, 0x12, 0x6b, 0x42, 0x0b, 0x05, 0x80, 0x70, 0x58, 0x37, 0xfb, 0x6f, 0x82, 0x9e, 0x0d, 0x44, 0xe8, 0x5f, 0x37, 0x5b, 0x38, 0xb8, 0xdc, 0x51, 0x4b, 0xfd, 0x88, 0x8e, 0x29, 0x5e, 0xb8, 0xaa, 0xd9, 0x8a, 0x6a, 0x74, 0x57, 0xae, 0xaf, 0xbd, 0x3a, 0x46, 0xdd, 0x5c, 0x37, 0x32, 0x1b, 0x08, 0xaf, 0xf5, 0xbb, 0x7b, 0x3a, 0x38, 0x82, 0xa5, 0xc9, 0xa6, 0x56, 0xb4, 0x09, 0x11, 0x05, 0x45, 0x05, 0x0a, 0x24, 0x03, 0x08, 0x81, 0x60, 0x82, 0xc0, 0xef, 0x73, 0x43, 0xc1, 0xf3, 0xe4, 0x1b, 0x18, 0xb7, 0xca, 0xac, 0x6e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x86, 0x10, 0x74, 0x00, 0x46, 0x19, 0x62, 0x07, 0x92, 0xc1, 0x0c, 0x9a, 0x3c, 0x42, 0xfd, 0xde, 0x28, 0xc2, 0x0b, 0x76, 0xc8, 0xe8, 0xce, 0xe8, 0x84, 0x11, 0xab, 0x6d, 0xaf, 0x96, 0xc1, 0xad, 0xcc, 0xad, 0x6c, 0xbf, 0x89, 0xa1, 0xc3, 0xa8, 0x4b, 0x0a, 0x3b, 0x11, 0x34, 0x95, 0x4c, 0x94, 0x6a, 0x08, 0xde, 0x50, 0x33, 0x11, 0xdb, 0x4a, 0x5c, 0xb8, 0x03, 0x2a, 0x40, 0x52, 0x51, 0x44, 0xc0, 0x71, 0x08, 0x28, 0x00, 0x04, 0xdf, 0xcf, 0xf4, 0x42, 0x44, 0x54, 0x61, 0xd0, 0xce, 0x81, 0x7a, 0x50, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x0d, 0x8e, 0x86, 0x16, 0x80, 0x48, 0x00, 0x0e, 0x94, 0xf2, 0x0e, 0xfd, 0xed, 0xf0, 0xc5, 0xe7, 0x2d, 0xde, 0xbc, 0x72, 0xcf, 0x76, 0xb4, 0xa6, 0x5c, 0x06, 0x1f, 0x0b, 0x36, 0x67, 0x3b, 0x4f, 0x3c, 0x02, 0xf0, 0x4a, 0xdc, 0xa5, 0x9a, 0x4b, 0xcd, 0x8d, 0xc6, 0x04, 0xd8, 0xad, 0x7a, 0x98, 0xa5, 0x68, 0x56, 0xc3, 0x81, 0xe3, 0x21, 0xd8, 0x6e, 0x99, 0x30, 0xa0, 0x15, 0x4c, 0x63, 0x60, 0x14, 0x42, 0x05, 0x06, 0x80, 0x1c, 0x00, 0x01, 0xf8, 0x77, 0x98, 0xe1, 0x1b, 0x8b, 0x81, 0x78, 0xf6, 0x70, 0x09, 0xfa, 0x01, 0x8a, 0xf7, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x18, 0x6e, 0x11, 0xbd, 0x17, 0x50, 0xce, 0x0e, 0x14, 0x69, 0x60, 0x5e, 0x97, 0x88, 0x11, 0x22, 0xbe, 0x02, 0xc4, 0xc8, 0xf3, 0x7e, 0x9b, 0x23, 0x36, 0x02, 0xaf, 0x6d, 0xd7, 0x77, 0xd9, 0x3b, 0x3f, 0x2e, 0xc9, 0x66, 0xf5, 0x54, 0xe7, 0x48, 0x5a, 0xd6, 0x62, 0xb8, 0xda, 0x1d, 0x8e, 0x25, 0x7b, 0x84, 0x4a, 0xbc, 0xc2, 0x20, 0xa8, 0x75, 0x01, 0x84, 0xa0, 0x31, 0x18, 0x08, 0x04, 0x70, 0x0e, 0x16, 0x1c, 0x7e, 0xf3, 0x1d, 0x58, 0xd9, 0xae, 0x6d, 0xcc, 0x60, 0x6d, 0x52, 0x80, 0x6f, 0x71, 0x80, 0x17, 0x02, 0xc0, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x1d, 0x0c, 0x70, 0x00, 0x00, 0xb0, 0x1c, 0x0e, 0x82, 0x3e, 0x9f, 0xc8, 0x08, 0x50, 0xee, 0xae, 0xae, 0x1c, 0xd2, 0xb1, 0x21, 0x01, 0x97, 0x46, 0x80, 0xaa, 0xc4, 0x8f, 0x21, 0x98, 0xb5, 0x1a, 0x30, 0xcf, 0xa9, 0xe8, 0x2e, 0xa6, 0x15, 0x27, 0x87, 0x97, 0x15, 0x24, 0x10, 0x80, 0x85, 0x27, 0x06, 0x4d, 0x88, 0xac, 0xbb, 0x30, 0xa0, 0x2a, 0x20, 0x0a, 0x77, 0x48, 0x10, 0x84, 0x04, 0x20, 0x80, 0xc4, 0x40, 0x31, 0x08, 0x03, 0xa0, 0xfa, 0x07, 0x79, 0x8e, 0x8e, 0xcd, 0x90, 0x61, 0x90, 0x4e, 0x28, 0xf7, 0x78, 0xe8, 0x36, 0xbb, 0x24, 0xb0, 0x49, 0x10, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x8a, 0x47, 0x16, 0x80, 0x00, 0x05, 0x88, 0x80, 0x07, 0xfb, 0x74, 0x8a, 0x55, 0xd6, 0x3c, 0xbf, 0x33, 0xa0, 0xbc, 0x31, 0xc1, 0xea, 0xed, 0xbd, 0x76, 0xbb, 0x1f, 0x39, 0x61, 0x52, 0x8e, 0xb4, 0x5f, 0x12, 0xf9, 0x2d, 0x2e, 0x82, 0x9b, 0xb5, 0x5a, 0x57, 0xac, 0xef, 0x04, 0x43, 0x78, 0x2f, 0x1b, 0x56, 0x85, 0x4a, 0x12, 0x20, 0xa8, 0x05, 0x43, 0xc4, 0x06, 0x25, 0x02, 0x00, 0x07, 0x41, 0x46, 0x81, 0x9f, 0xb5, 0x01, 0xa1, 0x86, 0xc8, 0x27, 0x32, 0x00, 0x15, 0x85, 0x80, 0x00, 0x95, 0xc0, 0x0b, 0x25, 0x1c, 0x61, 0xcb, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x19, 0x0e, 0x30, 0x48, 0x8c, 0x2b, 0x4b, 0x5f, 0x7c, 0x04, 0x05, 0x82, 0xfa, 0xfa, 0xd2, 0x27, 0x83, 0x45, 0x27, 0x43, 0x45, 0x6c, 0x14, 0xb5, 0x1e, 0x36, 0xcc, 0x59, 0xcd, 0xf1, 0x2c, 0x74, 0x62, 0xf9, 0xc2, 0x7d, 0x3a, 0x6f, 0xdc, 0xbc, 0x70, 0x63, 0xfe, 0xdb, 0xd5, 0x57, 0x3a, 0xdb, 0x26, 0xa4, 0x11, 0xbd, 0xa2, 0x29, 0xc8, 0x24, 0x48, 0xca, 0x29, 0x66, 0xd8, 0x82, 0x99, 0xd0, 0x06, 0x10, 0x81, 0x44, 0x20, 0x31, 0x08, 0x10, 0x02, 0xd6, 0x0f, 0xc8, 0x8c, 0xbd, 0xf9, 0xda, 0xe1, 0xa7, 0x95, 0xdc, 0x45, 0x50, 0x29, 0x32, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x1d, 0x16, 0x2b, 0x28, 0x26, 0x80, 0x10, 0x2d, 0x00, 0x56, 0x6f, 0xc9, 0x69, 0x19, 0xd1, 0xc5, 0x5a, 0x88, 0x02, 0xf1, 0xb0, 0xde, 0xbb, 0x00, 0x4b, 0x79, 0xcc, 0xf7, 0x0c, 0xb3, 0x7a, 0xac, 0xdc, 0x5b, 0x3c, 0x86, 0x19, 0x3c, 0xfe, 0xc9, 0xa9, 0x0f, 0x1a, 0xd1, 0x46, 0x33, 0x2f, 0x1e, 0xb0, 0x4b, 0xbf, 0xfe, 0x4d, 0x0a, 0x0b, 0x44, 0x50, 0xa5, 0x05, 0x48, 0x82, 0x95, 0x56, 0x2c, 0x02, 0x88, 0x40, 0x00, 0x01, 0x6b, 0x07, 0xf5, 0xf8, 0x9f, 0xe7, 0xcc, 0xe8, 0xdf, 0x76, 0x66, 0xe7, 0x84, 0xf0, 0x5d, 0xd8, 0x07, 0x8e, 0x00, 0x11, 0xca, 0x0c, 0x72, 0x59, 0xce, 0x14, 0x03, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x24, 0x64, 0x02, 0x04, 0x58, 0x02, 0xc6, 0x88, 0xb1, 0x04, 0xbf, 0xc0, 0x92, 0xd1, 0x8c, 0xa9, 0xae, 0x32, 0x04, 0x99, 0x41, 0x09, 0xef, 0x16, 0x43, 0x85, 0x69, 0xbd, 0x0a, 0xb9, 0xdb, 0x52, 0xba, 0x8a, 0x26, 0x9c, 0xa5, 0x5f, 0x75, 0xab, 0x29, 0xeb, 0xc7, 0xa2, 0x56, 0x08, 0x1e, 0x62, 0x42, 0x99, 0x94, 0xce, 0xc3, 0x58, 0x18, 0x00, 0x40, 0x00, 0x2f, 0xc6, 0xfe, 0xcd, 0x42, 0x7b, 0x23, 0x4a, 0xcb, 0xca, 0x2a, 0x01, 0x79, 0xe1, 0x20, 0x69, 0xfa, 0x98, 0x05, 0x94, 0x04, 0x22, 0x45, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x7d, 0x09, 0x8e, 0x89, 0x15, 0xb4, 0x59, 0x60, 0x00, 0x59, 0xa2, 0xc4, 0x43, 0x79, 0x05, 0xb1, 0x2d, 0x36, 0x7b, 0xd2, 0x35, 0x89, 0xe6, 0x96, 0xb4, 0xa6, 0x12, 0x94, 0x5e, 0x72, 0x65, 0x8a, 0xb1, 0x39, 0xe3, 0xdd, 0x4d, 0x9e, 0x2d, 0x2e, 0xc3, 0x67, 0x8c, 0x9d, 0x43, 0x75, 0x21, 0x42, 0x05, 0xe0, 0x24, 0x52, 0x29, 0x26, 0xcb, 0x60, 0x22, 0x0a, 0xd5, 0x50, 0x4c, 0xe0, 0x4a, 0xb0, 0x75, 0xfa, 0x9a, 0xea, 0xe1, 0xdd, 0xd1, 0x66, 0x2f, 0x52, 0xce, 0x9c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x15, 0x1a, 0x2b, 0x00, 0x68, 0x08, 0x05, 0xb4, 0x03, 0xa5, 0x9e, 0x5a, 0x65, 0x03, 0x27, 0xdf, 0x3f, 0x8a, 0x15, 0x4b, 0x10, 0x98, 0x81, 0x17, 0x6a, 0xf3, 0x05, 0xc3, 0x1e, 0x92, 0xf9, 0x43, 0x0d, 0x8c, 0x54, 0x38, 0xe2, 0x98, 0x98, 0xb7, 0x4e, 0x6b, 0x40, 0xa4, 0x44, 0xaa, 0x0e, 0x02, 0x2a, 0x20, 0xb2, 0xe0, 0x02, 0xa1, 0xcc, 0xc4, 0x04, 0x88, 0x40, 0x62, 0x20, 0x20, 0x1c, 0x4b, 0x00, 0xf8, 0x5e, 0xa6, 0x33, 0xc0, 0xe7, 0x29, 0xdb, 0xb2, 0xab, 0x76, 0xc9, 0x1a, 0xb7, 0xba, 0xf4, 0x28, 0xa2, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x19, 0x0a, 0x32, 0x4a, 0xe5, 0xd4, 0xc9, 0x00, 0x20, 0x6a, 0xc0, 0x3a, 0x7a, 0xee, 0x8f, 0xa3, 0x3b, 0x40, 0x25, 0xc8, 0xa8, 0x17, 0x2a, 0x5b, 0x66, 0x27, 0xe2, 0xf4, 0x1f, 0x17, 0x7d, 0x0a, 0xc2, 0x48, 0xd6, 0x39, 0x19, 0x8c, 0xbb, 0xdb, 0xb3, 0x89, 0x85, 0xea, 0x10, 0x24, 0xcb, 0x02, 0xc0, 0x27, 0x62, 0xa0, 0x29, 0x9d, 0x42, 0x50, 0x70, 0x00, 0x14, 0x2f, 0xea, 0x6f, 0xce, 0xf4, 0x6f, 0x57, 0x85, 0x04, 0xd4, 0x62, 0xdf, 0x00, 0x0d, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x15, 0x8c, 0x72, 0x00, 0x2d, 0x40, 0x07, 0x57, 0x40, 0x3a, 0xa0, 0xdb, 0x67, 0x19, 0x0c, 0xb4, 0x9a, 0xd4, 0x5d, 0xb7, 0x66, 0x27, 0x82, 0x29, 0x15, 0xe2, 0x2a, 0x8c, 0x3f, 0x90, 0xec, 0xec, 0xdf, 0x77, 0x7b, 0x5d, 0xdd, 0x64, 0xad, 0x05, 0xfb, 0x32, 0x51, 0xc0, 0xe6, 0x36, 0x93, 0xed, 0xae, 0xb4, 0xa5, 0x29, 0x38, 0xa3, 0xac, 0x28, 0x42, 0x28, 0x10, 0x2c, 0x02, 0x95, 0xd2, 0x05, 0x12, 0x82, 0x80, 0x2c, 0x02, 0xfe, 0xca, 0xfa, 0xb3, 0x2e, 0x38, 0x06, 0x58, 0x66, 0x88, 0x05, 0xf0, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x1d, 0x12, 0x2b, 0x01, 0x25, 0x5d, 0xc0, 0x20, 0x82, 0xa3, 0x80, 0x15, 0x06, 0x60, 0x20, 0x3b, 0xf0, 0xc8, 0x69, 0x76, 0x76, 0x8c, 0xbf, 0x96, 0x52, 0xda, 0x45, 0x94, 0x49, 0x3e, 0x4c, 0xb3, 0x97, 0x9f, 0x56, 0x6c, 0x6c, 0x74, 0x53, 0x72, 0x79, 0xa8, 0x58, 0x43, 0x31, 0xa2, 0xce, 0x89, 0x4a, 0x8e, 0xcb, 0x66, 0x07, 0x22, 0xad, 0x84, 0x08, 0x20, 0x82, 0x84, 0x40, 0x66, 0xb8, 0x01, 0x73, 0xf0, 0xbe, 0x8a, 0xe4, 0xd0, 0xb2, 0x6e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x29, 0x0e, 0x2c, 0x00, 0x86, 0xee, 0xd0, 0x03, 0x4b, 0x02, 0x9b, 0xfc, 0x2d, 0x17, 0x8d, 0xa3, 0x1a, 0xe3, 0x46, 0x74, 0x53, 0xac, 0x03, 0x09, 0x0b, 0xab, 0x8b, 0x4f, 0x93, 0x59, 0x20, 0x66, 0x97, 0xc7, 0x98, 0xcc, 0x85, 0xdb, 0x23, 0x75, 0xfd, 0xb4, 0x94, 0x68, 0x36, 0xcd, 0xa7, 0x37, 0xe4, 0x32, 0x46, 0x04, 0x22, 0x7a, 0xa2, 0xe0, 0x75, 0x98, 0x0a, 0xcc, 0x0a, 0x4a, 0x18, 0x15, 0x04, 0x07, 0x12, 0x81, 0xc1, 0x00, 0x3b, 0xd9, 0x94, 0xcb, 0x48, 0x9d, 0x3f, 0x70, 0x7f, 0xe3, 0x38, 0xcc, 0x2d, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x21, 0x0a, 0x30, 0x3a, 0x08, 0x01, 0x08, 0x06, 0x80, 0xa8, 0x26, 0x10, 0x8d, 0x3d, 0x10, 0xc7, 0x3c, 0x4a, 0xcf, 0x12, 0x50, 0xd9, 0x50, 0xc3, 0x92, 0x46, 0xad, 0x8e, 0xff, 0x1d, 0x1a, 0x7d, 0xb7, 0x8f, 0x34, 0xae, 0x3b, 0xa9, 0xf8, 0xf6, 0x7e, 0x2c, 0x35, 0xfc, 0xb0, 0x52, 0xeb, 0x26, 0xff, 0x0a, 0xf5, 0xd0, 0x1a, 0x21, 0x7c, 0xef, 0x58, 0x06, 0xd8, 0x81, 0x4c, 0xaa, 0x02, 0x99, 0x41, 0x20, 0x0a, 0xb0, 0x13, 0xf6, 0x87, 0x84, 0x5f, 0x65, 0x81, 0x7d, 0xaf, 0xa9, 0x44, 0x35, 0x20, 0xae, 0xa2, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x0d, 0x8e, 0x73, 0x20, 0x00, 0x04, 0x16, 0x3a, 0x01, 0xb7, 0x77, 0xf1, 0x2f, 0x75, 0x36, 0x5e, 0x42, 0x53, 0x7a, 0x83, 0x36, 0x92, 0x70, 0x9b, 0xb3, 0x63, 0x8f, 0x69, 0xbe, 0x74, 0x4d, 0x55, 0xbb, 0xbc, 0x30, 0x2f, 0xb1, 0x38, 0x63, 0xb4, 0xef, 0xa9, 0x96, 0x11, 0x08, 0x1b, 0xaa, 0x16, 0x34, 0x02, 0x51, 0x2c, 0x40, 0x4d, 0x73, 0xab, 0x02, 0xa4, 0x06, 0xc4, 0x02, 0x20, 0x81, 0x04, 0x40, 0x23, 0x43, 0x40, 0x18, 0x2d, 0x4a, 0x27, 0xe2, 0x38, 0xd3, 0x37, 0xa3, 0x23, 0x61, 0x63, 0x74, 0x85, 0x08, 0xf2, 0x60, 0x41, 0xc3, 0x01, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x11, 0x90, 0x44, 0x16, 0x80, 0x8b, 0x02, 0x20, 0x68, 0x58, 0x23, 0xa6, 0xa1, 0x81, 0xad, 0x4a, 0x14, 0x44, 0x5c, 0x38, 0xa5, 0x0a, 0x05, 0xa1, 0x28, 0x51, 0x6b, 0x58, 0x45, 0x79, 0x8b, 0x5f, 0xf0, 0xcd, 0x5b, 0xcd, 0x72, 0xdf, 0xa0, 0x9f, 0xb6, 0xf3, 0x84, 0x61, 0xb2, 0x61, 0x32, 0x7d, 0x24, 0x94, 0x03, 0xb2, 0x59, 0xa9, 0xdf, 0x72, 0x6d, 0xad, 0x65, 0x80, 0xa5, 0x00, 0xd0, 0x8c, 0xc0, 0x82, 0x10, 0x10, 0x44, 0x04, 0x00, 0x34, 0x16, 0xcc, 0x35, 0xa9, 0x2b, 0xe8, 0x9c, 0xf3, 0xdb, 0x99, 0x49, 0x32, 0xc9, 0x21, 0x68, 0x38, 0x38}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x29, 0x0c, 0x2d, 0x07, 0x02, 0xc0, 0x06, 0x85, 0x80, 0x85, 0x66, 0x81, 0x6f, 0xe4, 0xd6, 0x22, 0x33, 0x2e, 0x5c, 0xe7, 0x29, 0x6b, 0x45, 0x83, 0xf4, 0x11, 0x85, 0x17, 0x3b, 0xe7, 0x7f, 0xae, 0x6e, 0x16, 0x94, 0xe4, 0x68, 0x11, 0x64, 0x46, 0x3b, 0xca, 0xf4, 0xa5, 0xef, 0x11, 0x31, 0x09, 0xda, 0xa2, 0x43, 0x72, 0xe9, 0xaa, 0x50, 0x0a, 0x35, 0x40, 0x1c, 0xce, 0x02, 0x10, 0x81, 0x00, 0x16, 0x00, 0x00, 0xfa, 0x7d, 0xa1, 0xd1, 0x3e, 0x06, 0xeb, 0xb3, 0xe1, 0x03, 0x4b, 0x06, 0x88, 0x9a, 0x35, 0xad, 0xa3, 0x58, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x1d, 0x14, 0x2c, 0x6e, 0xf3, 0x43, 0xaa, 0x96, 0x00, 0x68, 0x00, 0x2f, 0x6b, 0x40, 0xe2, 0xc9, 0xbc, 0x88, 0x16, 0xa8, 0x48, 0x05, 0x91, 0x74, 0xb7, 0xe1, 0xd1, 0x37, 0x54, 0xe6, 0x70, 0xeb, 0x63, 0x33, 0xee, 0x19, 0x93, 0xce, 0x6e, 0x2a, 0x9e, 0xe8, 0x4d, 0x1d, 0x1a, 0xbd, 0xd0, 0xdf, 0xc8, 0x2f, 0xb4, 0x81, 0x4b, 0x04, 0x25, 0x25, 0xd0, 0xb8, 0x00, 0xac, 0x71, 0x0a, 0xc0, 0xa2, 0x10, 0x52, 0x01, 0xae, 0x4f, 0x60, 0x3c, 0xc0, 0x25, 0x00, 0x8b, 0x1c, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x21, 0x14, 0x29, 0x01, 0x00, 0x22, 0xc5, 0x05, 0x0b, 0xe0, 0x18, 0x76, 0x5c, 0x2c, 0x4f, 0xd1, 0xf5, 0x91, 0xe3, 0x14, 0x38, 0x4e, 0x48, 0x63, 0x40, 0xeb, 0x4f, 0xc7, 0x62, 0x2e, 0x84, 0xcc, 0xd0, 0xc5, 0xfe, 0xdb, 0x68, 0x9b, 0x3a, 0x03, 0x76, 0xc1, 0x3f, 0x76, 0xa8, 0xcd, 0x68, 0xfe, 0xb7, 0x24, 0x0d, 0xe8, 0x28, 0x23, 0x3a, 0xd4, 0x18, 0x85, 0x2b, 0x88, 0x16, 0x27, 0x04, 0x80, 0x01, 0xf0, 0x6a, 0x72, 0x3c, 0x98, 0x40, 0x2e, 0x9f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x74, 0x28, 0x94, 0x29, 0x54, 0x99, 0x12, 0x58, 0x16, 0x03, 0x4b, 0x02, 0x5b, 0xa9, 0x82, 0x74, 0xa9, 0xa6, 0x8a, 0xa7, 0x18, 0x2c, 0xb4, 0x51, 0xd6, 0x21, 0x03, 0xc2, 0x11, 0x1a, 0x0e, 0x8a, 0xd0, 0xcb, 0x37, 0x59, 0x8d, 0x5d, 0x8a, 0x36, 0x95, 0x35, 0x55, 0xec, 0xb6, 0xf6, 0x2d, 0x4b, 0x80, 0x46, 0x53, 0x02, 0xc2, 0x95, 0xad, 0x40, 0x0a, 0x68, 0x19, 0xa0, 0x0a, 0x41, 0x01, 0x88, 0x41, 0x00, 0x00, 0x0b, 0xe4, 0x60, 0x81, 0xa6, 0xcd, 0x41, 0xe3, 0xac, 0x96, 0xa4, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x1c, 0x92, 0x6d, 0x00, 0x00, 0x15, 0x16, 0x71, 0xd0, 0x00, 0xe3, 0x9d, 0x85, 0x9a, 0x38, 0x6b, 0xb5, 0x14, 0xa8, 0x84, 0x34, 0x22, 0x23, 0x84, 0x31, 0x52, 0xdb, 0x2c, 0xc5, 0x04, 0x83, 0x3c, 0xc3, 0xae, 0x86, 0x7c, 0x01, 0x3c, 0x45, 0x44, 0x88, 0x98, 0x6a, 0x4a, 0x24, 0x84, 0x84, 0x55, 0x66, 0xcd, 0x96, 0xf8, 0x3b, 0xb2, 0x01, 0x4c, 0xaa, 0x03, 0x08, 0x40, 0xa2, 0x10, 0x30, 0x00, 0x0a, 0xfd, 0x3f, 0xfc, 0xb0, 0x39, 0x60, 0x35, 0xad, 0xbe, 0xc4, 0xae, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x1d, 0x0a, 0x31, 0x01, 0x00, 0xdc, 0x03, 0x54, 0xf2, 0x04, 0x06, 0x4b, 0xd2, 0x1a, 0x97, 0x25, 0xa9, 0xbd, 0x29, 0x1c, 0xa1, 0x94, 0x9e, 0x85, 0x54, 0x2f, 0x5f, 0xd9, 0xf2, 0xef, 0x4c, 0x1b, 0xb0, 0xd3, 0x1a, 0xbe, 0xae, 0x18, 0x90, 0xba, 0xd4, 0xa1, 0x28, 0x90, 0xba, 0xe8, 0x22, 0xad, 0x44, 0x92, 0x10, 0x30, 0x2c, 0xc5, 0x64, 0xa1, 0x0c, 0xe0, 0x2a, 0x98, 0x42, 0xe0, 0x6b, 0xc8, 0x00, 0x00, 0x3d, 0xd8, 0xe0, 0x06, 0xdb, 0x86, 0xdd, 0x01, 0xfd, 0xa3, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x1c, 0x90, 0x6e, 0x00, 0x02, 0x01, 0x66, 0xac, 0x01, 0x9b, 0x77, 0x59, 0x1a, 0x39, 0x28, 0x67, 0xe5, 0x49, 0x59, 0x28, 0x87, 0x80, 0xc7, 0xa1, 0x55, 0x28, 0x86, 0xba, 0x59, 0x23, 0x68, 0xe6, 0x78, 0x84, 0xc2, 0x4b, 0xf5, 0x95, 0x9d, 0xfa, 0xc6, 0xc6, 0xb5, 0xef, 0xd8, 0x5e, 0x68, 0xed, 0x29, 0x8e, 0xb5, 0x9a, 0xa6, 0xd4, 0xfb, 0x66, 0x8e, 0x85, 0x56, 0x8c, 0xd3, 0x00, 0x59, 0x11, 0x03, 0x2e, 0x00, 0x7f, 0x70, 0x6e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0x28, 0x90, 0x29, 0x01, 0x00, 0x00, 0x00, 0x2c, 0x14, 0x5e, 0xde, 0xd7, 0x5b, 0xb1, 0xe9, 0x65, 0x57, 0xd1, 0x81, 0x0e, 0x7b, 0x84, 0xe3, 0x0e, 0xb9, 0x5d, 0xdb, 0xec, 0x7f, 0xff, 0x62, 0x57, 0xde, 0x27, 0xed, 0x52, 0x51, 0xc3, 0xb9, 0xe0, 0x4e, 0xca, 0x4d, 0xa2, 0x77, 0x9a, 0x99, 0xd3, 0xba, 0x48, 0x10, 0x16, 0x14, 0x85, 0xec, 0x53, 0xaa, 0x04, 0xe0, 0x51, 0x08, 0x20, 0x00, 0x00, 0x3d, 0xe7, 0x57, 0xc0, 0x3b, 0x27, 0x87, 0xc6, 0x40, 0x0a, 0x60, 0x5c, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x1c, 0x90, 0x2e, 0x00, 0x04, 0x01, 0xa0, 0x58, 0x48, 0xff, 0x11, 0xcb, 0x42, 0xee, 0x32, 0x55, 0xcd, 0x81, 0xc9, 0x15, 0xc2, 0xfd, 0x2b, 0x72, 0x45, 0x36, 0x22, 0x3f, 0xd7, 0x17, 0xc2, 0xf2, 0xe0, 0x56, 0xb3, 0x26, 0x3b, 0xfb, 0xdf, 0xa5, 0xd0, 0xe9, 0x1d, 0x72, 0xac, 0x94, 0x8f, 0xef, 0x85, 0x8e, 0xc2, 0xb1, 0x54, 0x91, 0x88, 0xb8, 0x0a, 0x95, 0x50, 0x98, 0x08, 0x21, 0x04, 0x00, 0x04, 0x10, 0x3f, 0xd3, 0xdf, 0xa0, 0xec, 0x65, 0xd9, 0x91, 0xac, 0x83, 0x50, 0x19, 0xac, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x5c, 0x25, 0x0e, 0x47, 0x13, 0x00, 0xb0, 0x10, 0x01, 0xc1, 0xd0, 0x17, 0x75, 0xd1, 0x2e, 0x6e, 0xae, 0x40, 0x5f, 0x3a, 0x2e, 0x11, 0x4a, 0x32, 0x8b, 0xcc, 0x5a, 0x88, 0x21, 0x33, 0x5d, 0xed, 0xce, 0xa7, 0x1b, 0xee, 0xec, 0x57, 0xe9, 0xd3, 0xfe, 0xa2, 0x3e, 0x51, 0x36, 0xf8, 0xc1, 0x05, 0xa1, 0x5c, 0x9c, 0x33, 0x45, 0x84, 0x01, 0x59, 0x5d, 0xba, 0x0b, 0xf7, 0x2c, 0x39, 0x5d, 0x00, 0x54, 0xa8, 0xc5, 0xa0, 0xd2, 0x00, 0x00, 0x1e, 0xab, 0xdf, 0x53, 0xfe, 0x1c, 0xbc, 0x70, 0x01, 0x94, 0xfc, 0x7e, 0x3c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x75, 0x0d, 0x8e, 0x2c, 0x21, 0x09, 0x4b, 0x00, 0x81, 0x01, 0xc3, 0x58, 0x01, 0xcd, 0x2a, 0x84, 0xd0, 0x67, 0x37, 0xb9, 0x62, 0x48, 0xd9, 0x1d, 0x07, 0x0a, 0x11, 0x7b, 0x27, 0xb2, 0x6b, 0xce, 0x4c, 0x36, 0x79, 0xe1, 0x48, 0xac, 0x5f, 0xf5, 0xb2, 0xc4, 0x63, 0x74, 0xa0, 0xea, 0x76, 0x8d, 0x6b, 0x43, 0x4d, 0x95, 0x2a, 0x79, 0xda, 0xae, 0x2e, 0xad, 0x74, 0xf4, 0x01, 0x4e, 0xc2, 0x06, 0x89, 0x01, 0x40, 0x03, 0xd7, 0xda, 0xfa, 0x70, 0x50, 0x20, 0x97}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x11, 0x86, 0x85, 0x18, 0x80, 0x00, 0x02, 0xc5, 0x80, 0x93, 0x82, 0xde, 0x5d, 0x46, 0x30, 0xaa, 0x8b, 0xad, 0xc6, 0x31, 0x25, 0x51, 0x62, 0x49, 0xfc, 0x4c, 0x25, 0x87, 0x74, 0xa9, 0x2e, 0x7a, 0x34, 0xf4, 0x8c, 0x51, 0x83, 0xa1, 0x36, 0x2f, 0x62, 0xd6, 0xbe, 0xd4, 0x2b, 0x6f, 0xce, 0xb8, 0xa7, 0x11, 0x32, 0xa6, 0x68, 0x63, 0xb5, 0x3a, 0x5a, 0x6c, 0xff, 0x75, 0x00, 0x53, 0xba, 0xc5, 0x00, 0xa0, 0x00, 0x00, 0x1f, 0x53, 0x57, 0x1e, 0x27, 0x82, 0x18, 0x8c, 0x8c, 0xa1, 0x9d, 0x80, 0x1b, 0xe2, 0x08, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x44, 0x25, 0x14, 0x6a, 0x00, 0x00, 0x00, 0xb0, 0x12, 0x3e, 0xa2, 0xec, 0x28, 0x69, 0xb4, 0x30, 0xb3, 0x68, 0x8e, 0xfd, 0x42, 0x82, 0xe0, 0xc8, 0xa4, 0xb9, 0x3a, 0xd4, 0x76, 0xb6, 0xec, 0xb2, 0xfd, 0xaa, 0x2f, 0x20, 0x15, 0x56, 0x53, 0x79, 0xa4, 0xb3, 0xc1, 0xfd, 0xe2, 0x70, 0x90, 0x5d, 0x4b, 0x71, 0x10, 0xb1, 0x55, 0x00, 0x5e, 0x01, 0x6a, 0x42, 0x40, 0x52, 0x40, 0x95, 0x20, 0x52, 0x08, 0x30, 0x00, 0x00, 0xb9, 0x1c, 0xf6, 0x83, 0xc7, 0x98, 0x20, 0x95, 0x6d, 0x7f, 0xa6, 0xb8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x64, 0x1c, 0xa2, 0x25, 0x14, 0xa4, 0x70, 0x00, 0x1a, 0x00, 0x03, 0x90, 0xe6, 0x19, 0xa1, 0x10, 0x00, 0x08, 0xd7, 0x15, 0x67, 0x3f, 0x69, 0x90, 0x79, 0x84, 0x25, 0x08, 0x7b, 0x09, 0x58, 0xa5, 0xb2, 0xb7, 0x43, 0x3c, 0x49, 0x8c, 0x58, 0x01, 0x26, 0xc9, 0xab, 0xea, 0xe1, 0xf7, 0xd4, 0xe7, 0x17, 0xe5, 0x01, 0x5b, 0x85, 0x5d, 0x32, 0xa8, 0x2a, 0x87, 0x68, 0x82, 0xa1, 0x46, 0x2e, 0x06, 0x00, 0x05, 0x80, 0x3c, 0x33, 0x3c, 0x40, 0x88, 0x26, 0x12, 0xed, 0xd3, 0x9f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x0d, 0x8e, 0x4b, 0x14, 0x00, 0x00, 0x01, 0x29, 0xa3, 0x42, 0xfb, 0xa9, 0x2b, 0x1a, 0xa1, 0x8e, 0xee, 0xab, 0xd3, 0x86, 0xef, 0x66, 0xfc, 0x74, 0x10, 0x5e, 0xd0, 0x8f, 0x1b, 0x56, 0x5a, 0x3e, 0x17, 0x6b, 0x4f, 0xac, 0xf6, 0xf4, 0x1c, 0xd2, 0x3c, 0x20, 0x0b, 0x94, 0xc6, 0xaa, 0x4e, 0x42, 0xf7, 0xb5, 0xca, 0xc4, 0x79, 0x00, 0x3c, 0x49, 0x05, 0xdb, 0x00, 0xaa, 0x55, 0x01, 0x84, 0x20, 0xc5, 0x80, 0x03, 0x8f, 0x86, 0x40, 0x00, 0x85, 0x5c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x8c, 0x33, 0x00, 0x14, 0x00, 0x0d, 0x01, 0x33, 0xee, 0x9f, 0xd3, 0x35, 0xae, 0x78, 0xe9, 0x93, 0xd5, 0xc5, 0xa8, 0x36, 0x29, 0x0e, 0x1a, 0xf1, 0xc2, 0x84, 0x69, 0xe0, 0x60, 0x97, 0x68, 0xdb, 0xc2, 0x9f, 0x1f, 0x79, 0xa3, 0xc5, 0x7b, 0xa7, 0x87, 0x6e, 0x41, 0x15, 0x5d, 0x20, 0x88, 0x8f, 0x14, 0xd3, 0x12, 0xb6, 0x51, 0x3f, 0xd0, 0x8c, 0x41, 0x4b, 0x02, 0x02, 0x21, 0x40, 0x84, 0x10, 0x68, 0x00, 0x76, 0xd3, 0x46, 0x57, 0xfd, 0x9b, 0x33, 0x9d, 0x4f, 0x7d, 0x05, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x44, 0x1d, 0x18, 0x2a, 0x00, 0x00, 0x00, 0x58, 0x18, 0x39, 0x1d, 0xbc, 0xac, 0xed, 0x45, 0xb9, 0xcc, 0xfa, 0x90, 0xbc, 0xa4, 0xcc, 0x99, 0x6a, 0xd2, 0x15, 0x2a, 0x63, 0x63, 0x3d, 0xd6, 0x64, 0xfb, 0x36, 0x81, 0x74, 0x85, 0x94, 0x49, 0xcf, 0x8c, 0x15, 0xfd, 0x28, 0xbe, 0x39, 0xb1, 0xab, 0x39, 0x25, 0x86, 0x53, 0x2a, 0x59, 0x53, 0x9f, 0x73, 0x84, 0xb2, 0xc1, 0x75, 0xa4, 0x02, 0x8e, 0x56, 0x12, 0x00, 0x03, 0x3e, 0xcb, 0xdf, 0xf5, 0x8e, 0xbf, 0x2c, 0xb8, 0x46, 0x94, 0x65, 0x01, 0x85, 0xc3, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x09, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x20, 0x92, 0x6c, 0x00, 0x00, 0x40, 0x05, 0x82, 0xb5, 0x5b, 0x4b, 0x7d, 0x4c, 0x7f, 0x4e, 0x0b, 0x44, 0x4b, 0x80, 0xcc, 0x08, 0x8c, 0x3f, 0x50, 0x94, 0xb0, 0x5f, 0xae, 0x35, 0xd4, 0xca, 0x93, 0xe6, 0x4f, 0x3f, 0xe5, 0x5e, 0xb1, 0xbb, 0x35, 0x69, 0x15, 0x5b, 0x4b, 0x5d, 0xca, 0xeb, 0x47, 0x2d, 0x25, 0x09, 0x15, 0x24, 0x96, 0x1a, 0xaf, 0x82, 0x1b, 0xfe, 0xa4, 0x05, 0x72, 0x08, 0x36, 0x08, 0x0a, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x1d, 0x18, 0x2a, 0x00, 0x00, 0x00, 0xb5, 0x2c, 0x54, 0x39, 0xa7, 0xc4, 0xb1, 0xae, 0xbe, 0xbf, 0x94, 0x04, 0x4e, 0x8b, 0x9f, 0x25, 0x19, 0xa3, 0x5d, 0x1e, 0xa3, 0x0e, 0x48, 0xdb, 0xd7, 0xbf, 0x1d, 0xfe, 0xb1, 0xd3, 0x3e, 0x38, 0x66, 0xac, 0x3a, 0x45, 0x19, 0x69, 0xd1, 0x2a, 0xdc, 0xec, 0x0b, 0x95, 0xc5, 0xdd, 0x49, 0xc0, 0x6c, 0xba, 0xfb, 0x33, 0x6c, 0x02, 0x00, 0xa9, 0x62, 0x8a, 0x02, 0x01, 0x00, 0x00, 0x07, 0xb6, 0x2b, 0xa1, 0x0c, 0x94, 0xed, 0x6d, 0x83, 0x5c, 0xe1, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x21, 0x4a, 0x48, 0x34, 0x00, 0x06, 0xf4, 0x0b, 0x14, 0x01, 0x82, 0xc3, 0xef, 0x46, 0x3a, 0xdd, 0x4e, 0x3a, 0xec, 0xe2, 0x08, 0x81, 0x8e, 0x76, 0x01, 0x86, 0x2f, 0x71, 0xd7, 0x6c, 0x1d, 0x84, 0x1a, 0x67, 0x90, 0x57, 0xd1, 0xc3, 0x9f, 0x3f, 0xa3, 0x80, 0x54, 0xdb, 0xd8, 0x46, 0xaf, 0x47, 0xb1, 0x6c, 0xb2, 0x88, 0x30, 0xa0, 0x92, 0x2b, 0x34, 0x45, 0xc9, 0xf4, 0x25, 0x10, 0x00, 0x29, 0x20, 0x66, 0x94, 0x20, 0x8c, 0x06, 0x21, 0x03, 0x00, 0x00, 0xb0, 0x1b, 0xf9, 0x5f, 0xcf, 0x5a, 0xcb, 0xcf, 0x3a, 0x7f, 0x29, 0x6d, 0x20, 0x05, 0x5d, 0xc6, 0x6e, 0xc9, 0x0f, 0x5c, 0x0e, 0x13, 0xc4, 0x94, 0xdc}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x8a, 0x0e, 0x87, 0x16, 0x80, 0x01, 0xa1, 0x40, 0x1c, 0x58, 0x76, 0x54, 0x41, 0xd0, 0x8b, 0x90, 0x9e, 0xc4, 0xe2, 0x40, 0x8e, 0xa6, 0x63, 0x94, 0xf2, 0x8b, 0xb9, 0x75, 0xdb, 0x7c, 0x77, 0x89, 0xef, 0x18, 0x2c, 0x87, 0x90, 0x51, 0xb7, 0xa7, 0x6a, 0xc7, 0x67, 0x2b, 0x45, 0x9a, 0xb5, 0x95, 0x99, 0x2f, 0x79, 0x0c, 0x2b, 0x80, 0xa1, 0xa0, 0x23, 0xb6, 0x7d, 0xe5, 0x42, 0x60, 0x52, 0xd0, 0xc1, 0xa2, 0xa0, 0x19, 0x00, 0x38, 0x00, 0x37, 0x88, 0xc0, 0xa9, 0xd1, 0x84, 0xa4, 0xb5, 0x92, 0x5f, 0x5e, 0xb9, 0xf9, 0x16, 0xbc, 0x80, 0x4c, 0x73, 0x8d, 0xef, 0x68, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x8a, 0x0e, 0x86, 0x17, 0x00, 0x0d, 0x2c, 0xe4, 0x16, 0x5b, 0x40, 0x9e, 0x8b, 0x17, 0x11, 0x52, 0xe9, 0xeb, 0x32, 0x63, 0xd0, 0x3c, 0xcc, 0xb8, 0x13, 0x8c, 0xe8, 0x13, 0x5a, 0xd6, 0x60, 0x2f, 0x88, 0x53, 0x57, 0xd4, 0x7d, 0xad, 0x20, 0x9c, 0x6c, 0x2f, 0x2b, 0x42, 0x7b, 0x88, 0x41, 0x42, 0xc5, 0x30, 0x22, 0xa2, 0x2b, 0xa9, 0x19, 0x60, 0xeb, 0x82, 0xd2, 0xc7, 0x59, 0xf9, 0xa8, 0x22, 0x05, 0x1c, 0x9c, 0x10, 0x2a, 0x02, 0x00, 0x00, 0x01, 0xfc, 0x0a, 0x70, 0xc0, 0xd1, 0x96, 0x13, 0x2f, 0x5c, 0x71, 0x4f, 0x02, 0x31, 0xd1, 0x8c, 0x08, 0x92, 0xa4, 0x51, 0x0e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x75, 0x0d, 0x1c, 0x2c, 0x48, 0x93, 0x23, 0x80, 0x00, 0x5d, 0x8e, 0x00, 0xbd, 0x02, 0x3c, 0xcb, 0xec, 0xd0, 0x21, 0xdf, 0x03, 0x69, 0x74, 0x74, 0x41, 0x52, 0xc7, 0x2c, 0x94, 0xed, 0x3b, 0xb2, 0xe1, 0x7b, 0x0a, 0xd6, 0x9c, 0xa8, 0x70, 0x82, 0x70, 0xee, 0xa2, 0x2a, 0x21, 0x3a, 0x25, 0xdd, 0x98, 0x02, 0x50, 0xb8, 0xf8, 0x2b, 0x6f, 0x60, 0x84, 0x41, 0x4d, 0x08, 0x04, 0x8a, 0x40, 0x60, 0x2e, 0x01, 0xa0, 0xc1, 0xf0, 0xe5, 0xa0, 0x51, 0x0e, 0x70, 0x53, 0x40, 0xb0, 0x96, 0xf9, 0xa9, 0x6b, 0x59, 0x1d, 0xf7, 0x80, 0x67, 0x88, 0x44, 0x91, 0x9a, 0xd8, 0x90, 0xb8, 0x83, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x1c, 0xce, 0x49, 0x13, 0x00, 0x02, 0xc2, 0xc2, 0xc2, 0xc2, 0xbf, 0xdb, 0x68, 0x33, 0x4c, 0xb5, 0x60, 0x64, 0x65, 0xc1, 0xcd, 0x48, 0x27, 0x1f, 0x3f, 0x51, 0xe5, 0xed, 0x77, 0x57, 0xd0, 0x5f, 0x8b, 0x15, 0x70, 0xa8, 0x89, 0x3b, 0x49, 0x20, 0x19, 0x3d, 0x32, 0x92, 0x84, 0xcd, 0x8f, 0x91, 0x30, 0x51, 0x04, 0xb2, 0x27, 0x30, 0xfc, 0x1b, 0x04, 0xa5, 0x54, 0xc2, 0x00, 0xa2, 0xb1, 0x99, 0x41, 0x42, 0x70, 0x10, 0x88, 0x00, 0x0d, 0x01, 0x05, 0x70, 0x0c, 0xfc, 0xed, 0x90, 0x59, 0x87, 0x77, 0x18, 0xd8, 0x11, 0x88, 0x0b, 0x08, 0x7c, 0x2e, 0x08, 0x00, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0d, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x35, 0x9d, 0x0c, 0x48, 0x14, 0x00, 0x00, 0x40, 0x16, 0xb6, 0x83, 0xa2, 0x59, 0x17, 0x29, 0xc1, 0xe1, 0x30, 0x76, 0x70, 0x15, 0x76, 0xd1, 0x66, 0x36, 0x44, 0xbb, 0x6d, 0x55, 0x50, 0xbe, 0x93, 0xb7, 0xd1, 0x47, 0x69, 0xc4, 0x43, 0xd7, 0x3c, 0x54, 0x35, 0x31, 0x21, 0x81, 0x5c, 0x4d, 0xd6, 0x88, 0xbf, 0x14, 0xc0, 0x67, 0xfb, 0xa6, 0x9d, 0xc3, 0x33, 0x19, 0x1b, 0xd6, 0xad, 0xe1, 0x10, 0x50, 0x49, 0x81, 0x22, 0x80, 0x18, 0x8c, 0x00, 0x05, 0x81, 0xff, 0xd7, 0xe1, 0xc0, 0xe0, 0xe7, 0xfa, 0xfc, 0xc1, 0x7a, 0x7e, 0x00, 0x3b, 0xa9, 0xea, 0xcb, 0xfd, 0xe0, 0xa8, 0x0c, 0x80, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x7c, 0x34, 0x8a, 0x2b, 0x44, 0x83, 0xc8, 0x8a, 0x01, 0xc0, 0x02, 0x0c, 0xf2, 0x52, 0x42, 0x9d, 0x42, 0x50, 0x92, 0x52, 0x53, 0x44, 0x61, 0x32, 0x85, 0x12, 0xc0, 0x66, 0xde, 0x39, 0xdc, 0xe0, 0x9e, 0x2c, 0x01, 0x12, 0x2a, 0x28, 0xb5, 0x5d, 0x57, 0x93, 0xbe, 0xa2, 0x11, 0xad, 0xbc, 0xa8, 0x8a, 0x22, 0xe5, 0x77, 0x3d, 0x8f, 0x9d, 0x51, 0x92, 0x4b, 0x66, 0xa5, 0xc4, 0xf5, 0xd5, 0x90, 0x4a, 0x20, 0xa1, 0x81, 0x05, 0x04, 0xe0, 0x2c, 0x3c, 0x7f, 0xd3, 0xe0, 0xa5, 0x35, 0x09, 0x97, 0x80, 0x02, 0x60, 0x4c, 0xa8, 0x01, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x19, 0x0c, 0xa2, 0x17, 0x80, 0x41, 0x42, 0xa4, 0x20, 0xb5, 0x80, 0x1e, 0x2e, 0xce, 0xe2, 0x64, 0x62, 0xd7, 0x2b, 0x49, 0x14, 0x61, 0xf3, 0x68, 0xeb, 0xc5, 0x2a, 0x28, 0xe9, 0xeb, 0x21, 0x37, 0xc7, 0x4b, 0x52, 0x15, 0xdb, 0xc6, 0x61, 0x49, 0x91, 0xe8, 0x34, 0x52, 0x0a, 0x8c, 0x30, 0x1b, 0x44, 0x83, 0x86, 0xf7, 0x1a, 0x82, 0x51, 0x05, 0x43, 0x2c, 0x20, 0x22, 0x05, 0x8f, 0x66, 0x80, 0xbc, 0xfd, 0xdd, 0x16, 0xeb, 0x2c, 0x0b, 0x32, 0x38, 0x51, 0x00, 0x0d, 0xe8, 0x72, 0x0a, 0x78, 0xf4, 0xaa, 0x00, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x91, 0x8e, 0x4d, 0x12, 0x80, 0x40, 0x20, 0x00, 0x58, 0x91, 0xf1, 0xf8, 0x70, 0xb7, 0x33, 0xad, 0x41, 0xf0, 0xe5, 0xd4, 0x2d, 0xb6, 0x59, 0xea, 0x68, 0x08, 0xbc, 0x60, 0x51, 0x49, 0x85, 0x48, 0x0b, 0xcf, 0xed, 0x65, 0xef, 0x50, 0xef, 0x64, 0x6e, 0xb9, 0x1a, 0x0e, 0x64, 0x42, 0xb9, 0xe8, 0x0a, 0x36, 0x17, 0x67, 0xa6, 0x15, 0x32, 0x2c, 0xbc, 0x12, 0xad, 0x0a, 0xbd, 0x20, 0xdd, 0x60, 0xa8, 0x14, 0xcf, 0x10, 0x60, 0x40, 0x00, 0x17, 0xe9, 0x6b, 0x40, 0xd1, 0xad, 0x18, 0x01, 0x40, 0x01, 0x40, 0x00, 0x59, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x09, 0xc0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x99, 0x1c, 0x29, 0x00, 0x10, 0x14, 0x0b, 0x16, 0x11, 0xcf, 0xb8, 0x2b, 0x43, 0x4f, 0x42, 0x1d, 0x6c, 0x0d, 0x0a, 0x88, 0x18, 0x34, 0x1f, 0xcb, 0x3a, 0xc6, 0x81, 0xab, 0x89, 0x02, 0x22, 0x11, 0x23, 0xbd, 0x7a, 0xf7, 0xe1, 0x61, 0x59, 0x93, 0x7b, 0xa9, 0x19, 0x95, 0xb2, 0xcd, 0xad, 0xd0, 0x94, 0xe9, 0x34, 0x51, 0x9c, 0xd6, 0xaf, 0xb4, 0x01, 0x77, 0x10, 0x00, 0x56, 0xb8, 0x83, 0x60, 0x76, 0x31, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x24, 0xe8, 0x00, 0x10, 0x00, 0x69, 0xa0, 0x1f, 0xd7, 0xf3, 0x1d, 0x12, 0x8b, 0x95, 0x6d, 0xe2, 0xe9, 0x51, 0xa4, 0xa3, 0x99, 0x9a, 0x80, 0x40, 0xeb, 0xee, 0xca, 0xf0, 0xee, 0x76, 0x3d, 0xc9, 0x6a, 0xde, 0x9a, 0x2c, 0xd2, 0xdc, 0xec, 0x5a, 0xcb, 0xd2, 0xd8, 0xe1, 0xb5, 0x16, 0xf5, 0x4e, 0x3d, 0x9c, 0x10, 0x09, 0x5e, 0xd6, 0xcb, 0x01, 0x69, 0x4c, 0x85, 0x20, 0x99, 0x16, 0xea, 0x20, 0xa7, 0x83, 0x05, 0xc0, 0x0e, 0xd4, 0x13, 0x34, 0x44, 0x0d, 0x4e, 0x72, 0x04, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x14, 0x47, 0x14, 0x00, 0x04, 0x00, 0x43, 0xa0, 0x04, 0xff, 0x6e, 0x36, 0xd3, 0x78, 0x30, 0x4e, 0x04, 0x95, 0x39, 0x87, 0x8f, 0x0a, 0xb6, 0xb6, 0x58, 0xe5, 0xd2, 0xbe, 0x0f, 0x6c, 0x2a, 0x34, 0x84, 0x52, 0x15, 0x35, 0xe9, 0x8d, 0x95, 0x97, 0x21, 0x02, 0xcc, 0xd7, 0x13, 0x95, 0x8d, 0x69, 0xad, 0x50, 0x2d, 0xfd, 0xc4, 0x00, 0x29, 0xa1, 0x01, 0x50, 0x01, 0x4f, 0xd3, 0xf6, 0x2b, 0x48, 0xb6, 0x9f, 0x94, 0xa7, 0xcc, 0xb1, 0x23, 0x09, 0xf8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x4c, 0x15, 0x0c, 0x32, 0x01, 0x60, 0xa7, 0x20, 0x68, 0xd0, 0x5c, 0x07, 0x68, 0xe4, 0x0e, 0x83, 0xfe, 0x59, 0x70, 0x67, 0x42, 0xd8, 0xcb, 0x35, 0xfb, 0x2c, 0x09, 0xec, 0x80, 0x83, 0x21, 0x5e, 0xfc, 0xb0, 0xb4, 0x6e, 0xa4, 0x33, 0x15, 0x5b, 0x4b, 0xb4, 0xe3, 0xb6, 0xb9, 0x09, 0x09, 0xd6, 0xb3, 0xac, 0xd7, 0x4e, 0x66, 0x72, 0xd2, 0x6b, 0x2f, 0x18, 0xd1, 0x26, 0x50, 0x0a, 0x86, 0x28, 0x8c, 0x2a, 0x16, 0x5a, 0xe0, 0x3b, 0x47, 0x20, 0x75, 0x7f, 0xfd, 0x3c, 0x95, 0x2a, 0xd7, 0x23, 0x19, 0xf8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x15, 0x10, 0x25, 0x42, 0x09, 0xc3, 0x83, 0x02, 0xb9, 0x01, 0x07, 0x0d, 0x80, 0xdf, 0xfb, 0x8c, 0x5a, 0x22, 0xe6, 0x8b, 0x15, 0xa7, 0xd5, 0x95, 0x43, 0x87, 0xa7, 0x5d, 0xcb, 0xf5, 0xec, 0x0f, 0x4d, 0x54, 0x67, 0x35, 0xa4, 0xa5, 0x26, 0x71, 0x48, 0xf7, 0xdc, 0x64, 0xf3, 0x63, 0x0d, 0x72, 0x76, 0xa2, 0x89, 0x72, 0x4c, 0x5b, 0xf1, 0x11, 0x94, 0x88, 0xcb, 0xf1, 0xb8, 0x90, 0x0a, 0x88, 0x21, 0x0c, 0x2c, 0x38, 0x02, 0x1d, 0x76, 0x42, 0x65, 0x06, 0x7d, 0x58, 0xe3, 0x37}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x0d, 0x0e, 0x26, 0x43, 0x89, 0x80, 0xcb, 0x80, 0x00, 0xa0, 0x04, 0xdd, 0x88, 0x8a, 0x48, 0x56, 0xba, 0x1b, 0x4c, 0x8a, 0x0a, 0x3b, 0x81, 0x44, 0xd9, 0x71, 0xf5, 0xbe, 0xf8, 0xb2, 0x99, 0x66, 0x52, 0x45, 0xda, 0xce, 0xc8, 0x99, 0xc3, 0xc8, 0xa1, 0xd3, 0xc4, 0x57, 0x0c, 0x88, 0xdc, 0x5f, 0x9b, 0xf4, 0xe7, 0xfb, 0xd9, 0x5a, 0xfc, 0x50, 0xbd, 0x17, 0x40, 0xaf, 0x72, 0x94, 0x98, 0xc5, 0x00, 0x2a, 0x94, 0xc1, 0x70, 0x58, 0xdf, 0xfa, 0xf8, 0xb7, 0x9a, 0x93, 0x57, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x11, 0x60, 0x45, 0x12, 0x00, 0x06, 0xec, 0x0c, 0xb0, 0x02, 0x6f, 0x53, 0x0d, 0x45, 0xd1, 0x94, 0x05, 0x89, 0xab, 0x9b, 0xbd, 0x31, 0xb1, 0x55, 0x80, 0x52, 0x69, 0x23, 0x64, 0x2d, 0x84, 0xd3, 0xa6, 0x17, 0x6a, 0x2f, 0x2a, 0xbe, 0xfd, 0x9d, 0x16, 0x28, 0x69, 0x71, 0x8d, 0xd2, 0x53, 0x8d, 0xde, 0x6c, 0xf3, 0x53, 0x0e, 0x59, 0x15, 0x8d, 0x6c, 0xcf, 0x74, 0x52, 0xdb, 0x9a, 0x0c, 0x7a, 0x74, 0x81, 0x58, 0x6b, 0x09, 0x03, 0x40, 0x0f, 0xa8, 0x7f, 0x53, 0x06, 0x29, 0x44, 0x5b, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x89, 0x8c, 0x91, 0x12, 0x00, 0xb5, 0x05, 0x03, 0x00, 0x50, 0x51, 0xf8, 0x09, 0x1a, 0x1a, 0x53, 0x6a, 0xe7, 0x9a, 0x88, 0xba, 0xbd, 0x96, 0x32, 0x61, 0xdf, 0x15, 0x6c, 0xd4, 0xdd, 0x76, 0xbb, 0x02, 0xb2, 0xc6, 0x93, 0x44, 0x2d, 0xb4, 0xa5, 0x80, 0xa0, 0xbd, 0x8f, 0x30, 0x81, 0xf3, 0x62, 0xb6, 0x6e, 0x14, 0xcd, 0x60, 0xe2, 0x4a, 0x66, 0xb3, 0x39, 0xbd, 0x6f, 0x74, 0x89, 0x75, 0xa2, 0x68, 0x27, 0x67, 0xa2, 0xe0, 0x56, 0x30, 0xc3, 0x49, 0x60, 0xeb, 0xc6, 0x1d, 0xf8}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x1c, 0x9c, 0x28, 0x00, 0xcb, 0x00, 0x00, 0x01, 0x36, 0x6b, 0x62, 0x6a, 0xdd, 0x44, 0x98, 0x58, 0x8b, 0xc3, 0x79, 0x00, 0x5c, 0xd9, 0xab, 0x64, 0x4d, 0xb1, 0xd0, 0x41, 0xe8, 0xd8, 0x23, 0x38, 0xff, 0x98, 0x30, 0xe2, 0x71, 0x17, 0xf3, 0xa7, 0xe9, 0x8b, 0x39, 0x42, 0x32, 0xfa, 0xd0, 0x5a, 0x05, 0x6e, 0x31, 0x80, 0x06, 0x20, 0x14, 0xf0, 0x21, 0x58, 0x40, 0x00, 0x28, 0x0f, 0x75, 0x8c, 0x98, 0x06, 0x5e, 0xc2, 0x7c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x74, 0x1d, 0x22, 0x25, 0x39, 0xe2, 0xb4, 0x40, 0x00, 0x0e, 0x2f, 0x01, 0x0e, 0x42, 0x56, 0x62, 0x31, 0x15, 0x12, 0x59, 0x45, 0x3e, 0xf8, 0xaa, 0x78, 0x43, 0x95, 0x3e, 0x4f, 0x85, 0x76, 0x6a, 0x98, 0xa3, 0x35, 0x00, 0x6f, 0xaf, 0xf2, 0x1e, 0x70, 0x8a, 0x9d, 0x16, 0x66, 0x80, 0xff, 0x17, 0xfb, 0x26, 0x55, 0xdd, 0x4f, 0x05, 0xb2, 0xaa, 0x1c, 0xe2, 0x8b, 0x0b, 0x7b, 0x60, 0x69, 0xb8, 0x9d, 0x44, 0x63, 0x40, 0x52, 0xe0, 0x57, 0xa0, 0xc3, 0x40, 0x42, 0x2d, 0x7c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x6c, 0x1d, 0x64, 0x24, 0x65, 0x4b, 0x21, 0x00, 0x12, 0x2c, 0x5e, 0x09, 0x5f, 0x5c, 0xed, 0x29, 0xdc, 0x1c, 0x68, 0x15, 0x0e, 0x21, 0x4a, 0x7b, 0x32, 0x61, 0x28, 0x14, 0x4d, 0xca, 0xcb, 0x84, 0x56, 0x6b, 0x7c, 0xe5, 0xaf, 0x85, 0xda, 0xe6, 0x6d, 0x17, 0x45, 0x46, 0x2f, 0xab, 0x78, 0xb3, 0x12, 0xb0, 0x26, 0xe6, 0x0e, 0x1b, 0x5f, 0x4e, 0xb7, 0x1c, 0x37, 0xac, 0x72, 0x9a, 0x0c, 0x18, 0x00, 0x1b, 0x08, 0x17, 0xb4, 0xc0, 0xac, 0x42, 0x06, 0x48, 0x1c, 0x33, 0xb5, 0xc0, 0xf0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x19, 0x16, 0x2c, 0x51, 0x04, 0x40, 0x00, 0x2d, 0xc0, 0x0b, 0xde, 0xb0, 0x59, 0x06, 0x41, 0x5f, 0xc6, 0xa1, 0x13, 0x38, 0xd1, 0xfd, 0xf7, 0x0e, 0xcf, 0x87, 0x3e, 0x71, 0x1d, 0x4d, 0x46, 0xd1, 0x56, 0xd1, 0x9e, 0xae, 0x9a, 0xf9, 0xa1, 0xdb, 0xc7, 0x2c, 0x88, 0xec, 0xad, 0x9f, 0xb5, 0x95, 0x4a, 0x14, 0xed, 0x2b, 0x5b, 0xc4, 0x19, 0x33, 0x54, 0x95, 0x43, 0x1a, 0x80, 0xf5, 0x01, 0x54, 0xa7, 0x0b, 0x01, 0x61, 0xf4, 0xd7, 0x54, 0x01, 0xbc, 0xd7}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x3d, 0x92, 0x0a, 0x34, 0x00, 0x01, 0xbd, 0x40, 0x17, 0x60, 0x1f, 0xee, 0xf4, 0xc5, 0x2b, 0x36, 0xc8, 0x56, 0x4a, 0x01, 0x5f, 0x09, 0x27, 0x24, 0xad, 0x69, 0x93, 0xcd, 0xfd, 0x67, 0x3b, 0xea, 0xc0, 0x5d, 0x81, 0x24, 0x71, 0xfe, 0x11, 0x4f, 0xa2, 0xd9, 0x78, 0xaf, 0x5c, 0xca, 0xcb, 0xce, 0x15, 0x74, 0xa4, 0x62, 0x92, 0xa2, 0x70, 0x1f, 0x27, 0x18, 0x9a, 0x50, 0x02, 0xa1, 0x88, 0x71, 0x04, 0x16, 0x01, 0x60, 0x00, 0x13, 0x55, 0xae, 0x97, 0xa2, 0xe7, 0x92, 0x79, 0xa3, 0x39, 0xa2, 0x1b, 0x13, 0x13, 0x9d, 0x78, 0x00, 0xd0, 0xd8, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x00, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x91, 0x8a, 0x89, 0x35, 0xa8, 0x56, 0x92, 0xcc, 0x00, 0x1c, 0x00, 0x3b, 0xf6, 0xc9, 0x2a, 0xfe, 0x08, 0x55, 0x90, 0x22, 0x11, 0xd4, 0x6b, 0xf1, 0x73, 0xcc, 0x46, 0x99, 0x32, 0x22, 0xb9, 0x47, 0xa8, 0x0a, 0x7a, 0x8e, 0x66, 0x54, 0x6e, 0x27, 0x89, 0x1b, 0xc2, 0x73, 0x8b, 0x3f, 0x5a, 0x4f, 0xdc, 0xc0, 0x40, 0x86, 0x00, 0x56, 0xc7, 0x04, 0x07, 0x05, 0x2c, 0x56, 0xf2, 0x88, 0x14, 0xac, 0xa0, 0x38, 0x84, 0x16, 0x00, 0xab, 0x07, 0xdc, 0x01, 0x5f, 0x9b, 0xd3, 0x09, 0x44, 0x11, 0xd7, 0x3e, 0x91, 0x41, 0x02, 0x7c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x3c, 0x11, 0x18, 0x6b, 0x20, 0x80, 0x40, 0x01, 0x02, 0x02, 0x01, 0x75, 0xf7, 0xbd, 0x8f, 0x4c, 0x74, 0x9f, 0x32, 0x6a, 0x55, 0xf8, 0xa0, 0x4a, 0xe8, 0xa4, 0xc7, 0x1b, 0xdb, 0x92, 0x95, 0x5f, 0xa5, 0xc9, 0xad, 0xa5, 0xed, 0xaf, 0xe2, 0x25, 0xd8, 0xf5, 0x2d, 0x5e, 0x5b, 0x0c, 0x37, 0x24, 0x70, 0xc4, 0xda, 0x10, 0x06, 0x5e, 0x59, 0x9f, 0x24, 0x52, 0xa4, 0x1d, 0x5e, 0x97, 0x5f, 0x4e, 0xda, 0x47, 0x13, 0x18, 0x46, 0x06, 0x10, 0x82, 0xc0, 0x80, 0x17, 0xfa, 0xc1, 0xef, 0xc8, 0xd1, 0x9c, 0xc1, 0x6c, 0xde, 0x68, 0xbd, 0x6b, 0x4e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x11, 0x12, 0x70, 0x02, 0x02, 0xa1, 0x60, 0x00, 0x18, 0x7a, 0xa5, 0x62, 0x7e, 0x68, 0xa6, 0xc2, 0x9d, 0x64, 0xb9, 0x2c, 0x72, 0x2a, 0x65, 0xb8, 0xdf, 0xc6, 0x2f, 0xce, 0xc6, 0xd2, 0xeb, 0x7a, 0x75, 0x25, 0xad, 0xb1, 0x66, 0x1d, 0x72, 0x6b, 0x24, 0x76, 0xf0, 0x38, 0xa2, 0x4e, 0x20, 0xbe, 0xd9, 0x2c, 0xc6, 0x78, 0xec, 0x6c, 0xd2, 0xb9, 0xaf, 0xe5, 0x7e, 0x25, 0x10, 0x53, 0x2a, 0xc0, 0xe2, 0x10, 0x50, 0x5c, 0x00, 0x1e, 0xef, 0x44, 0x77, 0x31, 0x15, 0x7b, 0x1d, 0x99, 0xb1, 0x76, 0xd0, 0x70}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x74, 0x21, 0x58, 0x27, 0x40, 0x98, 0x57, 0x62, 0xc0, 0x0b, 0x01, 0x78, 0x01, 0x74, 0xab, 0x63, 0x51, 0x2a, 0xa8, 0xa2, 0xc5, 0x4a, 0x33, 0xe9, 0x29, 0xe5, 0x5a, 0x65, 0x74, 0x59, 0xe3, 0x10, 0xbc, 0x9a, 0x9d, 0x1b, 0x6c, 0x80, 0xb5, 0x87, 0x1a, 0xdd, 0xc1, 0x92, 0x2c, 0x97, 0x15, 0x29, 0x69, 0x25, 0x30, 0x57, 0xb1, 0x45, 0x76, 0xca, 0x14, 0x8a, 0x69, 0x45, 0xd3, 0x83, 0xb3, 0xfb, 0xd4, 0x0a, 0x39, 0x50, 0x1c, 0x44, 0x03, 0x10, 0x81, 0x80, 0x02, 0xc6, 0x7f, 0x9e, 0x07, 0x17, 0xa5, 0x03, 0x1b, 0x4e, 0xc8, 0x56, 0x51, 0x19, 0xae, 0xe0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x09, 0x8c, 0x87, 0x17, 0x2c, 0x20, 0x18, 0x00, 0x35, 0xb0, 0x18, 0xfa, 0x58, 0xf5, 0xfe, 0x46, 0xc2, 0xc9, 0xdd, 0x61, 0xa7, 0xb1, 0x33, 0x17, 0x4b, 0xe4, 0x77, 0x20, 0x0d, 0xb8, 0xdb, 0xb7, 0x1d, 0x22, 0xd5, 0x06, 0x7f, 0xcc, 0x9e, 0xd9, 0x39, 0x9c, 0x20, 0x62, 0x09, 0xd2, 0x79, 0xc1, 0x65, 0x8e, 0xcb, 0x4e, 0x5c, 0x5a, 0x1a, 0xa3, 0x9b, 0x67, 0xc6, 0x20, 0xa6, 0x82, 0x12, 0x42, 0x00, 0x00, 0x02, 0xbb, 0xd9, 0xa4, 0x4b, 0xf3, 0x93, 0xe1, 0x6d, 0x78, 0x08, 0xd6, 0x40, 0x32, 0x3e}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0c, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x05, 0x8e, 0x48, 0x52, 0x8a, 0x00, 0x02, 0xc0, 0x03, 0x59, 0xb0, 0x5d, 0xfe, 0xbe, 0xbc, 0xf0, 0xef, 0x4e, 0x6e, 0x2d, 0x58, 0x3d, 0x00, 0xe2, 0x5f, 0xe4, 0xe9, 0xcb, 0x44, 0x8a, 0xf8, 0x52, 0xd8, 0xe4, 0x51, 0x31, 0xbb, 0x98, 0xd2, 0x72, 0xd5, 0x87, 0x8c, 0x0b, 0x26, 0xaa, 0x2d, 0x50, 0x27, 0x79, 0x8a, 0xde, 0x67, 0xba, 0x0d, 0x57, 0x70, 0xad, 0x2f, 0x16, 0xaf, 0x48, 0x14, 0x90, 0x33, 0x40, 0x28, 0x44, 0x06, 0x00, 0x37, 0xd0, 0x43, 0xb0, 0xd1, 0xde, 0x8a, 0x77, 0xab, 0x3a, 0xa3, 0x46, 0x54, 0x6e, 0x1a, 0xf6, 0x43, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x11, 0x1e, 0x6a, 0x09, 0x52, 0x00, 0x00, 0xb2, 0x81, 0x03, 0xbe, 0x55, 0x45, 0x12, 0x49, 0x22, 0x2d, 0xf8, 0x3c, 0x93, 0xa1, 0x46, 0x39, 0x6c, 0x64, 0x52, 0xc8, 0xe6, 0x87, 0x3c, 0x31, 0x50, 0xc5, 0xb7, 0x1a, 0x8d, 0xd9, 0x15, 0x75, 0x93, 0xc4, 0x59, 0x54, 0xe6, 0x6d, 0x16, 0x9b, 0x8c, 0x2d, 0xc2, 0x76, 0xa4, 0x72, 0xce, 0xd5, 0xff, 0xa6, 0x63, 0x9d, 0xf9, 0x00, 0x55, 0x29, 0x40, 0xe2, 0x30, 0x72, 0xd1, 0x60, 0xae, 0x5e, 0xae, 0xd3, 0x5c, 0x61, 0x0c, 0x24, 0x1c}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x60, 0xfc, 0x21, 0x17, 0x55, 0x54, 0x15, 0x1c, 0x6a, 0x0a, 0x48, 0x16, 0x4c, 0x01, 0x6a, 0x02, 0x7c, 0xaa, 0x9b, 0x5d, 0xd3, 0x23, 0x5e, 0xcc, 0xed, 0x68, 0x23, 0x3f, 0xcc, 0xa9, 0xc4, 0xde, 0x70, 0xb0, 0xeb, 0xb4, 0xdc, 0x9b, 0xe7, 0x6b, 0x0a, 0xb0, 0xb8, 0xf2, 0xf6, 0xea, 0xe5, 0x65, 0xd8, 0x67, 0x4c, 0xbf, 0x4f, 0x9d, 0x25, 0x74, 0xe0, 0x8b, 0x08, 0x91, 0x05, 0xdb, 0xfe, 0x3d, 0xac, 0xbc, 0xac, 0x58, 0xad, 0xe9, 0x5a, 0xd0, 0x05, 0x33, 0xa0, 0x2a, 0x02, 0xc5, 0x7a, 0x63, 0x5b, 0x5a, 0xb1, 0x02, 0xa7, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x15, 0x8a, 0x47, 0x42, 0x1a, 0x00, 0x00, 0x00, 0x6a, 0xd8, 0x06, 0x1a, 0x8c, 0x6a, 0xde, 0x98, 0x1b, 0x81, 0x38, 0x89, 0x62, 0x1a, 0xed, 0x14, 0x4d, 0xf3, 0x0f, 0xad, 0xe0, 0x9a, 0x22, 0x2f, 0x6a, 0xd8, 0x02, 0x83, 0xe3, 0xd4, 0xd9, 0x7e, 0x8c, 0x85, 0x4c, 0xb2, 0xfb, 0x40, 0x3d, 0x4e, 0x10, 0x9c, 0x98, 0x9a, 0x10, 0x99, 0xf7, 0x79, 0xc5, 0x10, 0x6d, 0x72, 0xad, 0xd5, 0x75, 0x9b, 0xae, 0xb2, 0xc6, 0xea, 0x9a, 0x00, 0x55, 0x89, 0x03, 0x20, 0x1f, 0xfd, 0xdf, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x15, 0x90, 0xe8, 0x14, 0x00, 0xb4, 0xb1, 0x5c, 0x81, 0x64, 0x68, 0x2a, 0x15, 0x65, 0xa4, 0x70, 0xe8, 0x0a, 0x87, 0x9a, 0x28, 0x13, 0x8d, 0x07, 0x03, 0xc2, 0x09, 0x4e, 0x49, 0xe0, 0x18, 0xd6, 0xd6, 0x68, 0x18, 0xda, 0x97, 0x29, 0x11, 0x90, 0x8a, 0x4f, 0x77, 0xa3, 0x11, 0x84, 0x17, 0xa5, 0x53, 0x11, 0x2f, 0x68, 0xa6, 0xb4, 0x5e, 0x05, 0x99, 0x7f, 0x88, 0xb8, 0x13, 0x28, 0x95, 0x46, 0x40, 0x14, 0x6e, 0x31, 0x58, 0x3c, 0x00, 0x16, 0x37, 0xfd, 0x43, 0xd4, 0xd8, 0x19, 0x80, 0x83, 0x07}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xe0, 0xfc, 0x21, 0x17, 0x55, 0x55, 0x15, 0x88, 0x49, 0x52, 0x99, 0x80, 0x08, 0x68, 0x6c, 0x14, 0x7c, 0x01, 0xd0, 0x97, 0x71, 0xbe, 0xa8, 0x72, 0xb6, 0x94, 0xd7, 0x9a, 0x34, 0xdb, 0x2c, 0x30, 0x63, 0x7f, 0x0f, 0x93, 0x21, 0x5d, 0xb8, 0x39, 0xcf, 0xd9, 0x9d, 0x26, 0x0d, 0xc1, 0x44, 0xcf, 0x96, 0x61, 0x9d, 0x49, 0xd5, 0xb9, 0x94, 0x32, 0xea, 0x9a, 0x5c, 0x59, 0x11, 0x0d, 0x11, 0x46, 0x5f, 0x36, 0x32, 0x44, 0x03, 0x56, 0xd1, 0xae, 0x21, 0xa6, 0x02, 0xb8, 0x4a, 0x18, 0x00, 0x46, 0x35, 0xbf}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x15, 0x8c, 0xaf, 0x11, 0x80, 0x00, 0x82, 0x80, 0x68, 0x03, 0xe1, 0x86, 0x90, 0xf3, 0x52, 0x48, 0x47, 0xe7, 0xc9, 0x23, 0xaf, 0xf0, 0xfa, 0x53, 0xcf, 0x06, 0xcd, 0x60, 0xd9, 0x89, 0xa1, 0x51, 0x04, 0x95, 0x78, 0x09, 0x98, 0x63, 0x18, 0xbf, 0x77, 0x4c, 0xaf, 0xe3, 0x46, 0x34, 0x8e, 0x7b, 0x98, 0x76, 0xea, 0xdc, 0xf8, 0x0d, 0xc9, 0x70, 0x5d, 0x09, 0x84, 0x75, 0xf8, 0x00, 0xc8, 0x00, 0x00, 0x15, 0x01, 0x50, 0xc5, 0x13, 0x84, 0x40, 0x05, 0x80, 0xe7, 0x49, 0x69, 0x1b, 0x82, 0xd4, 0x00, 0x8f}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x80, 0xfc, 0x21, 0x17, 0x55, 0x45, 0x25, 0x62, 0x23, 0x00, 0x0b, 0x0d, 0x94, 0xb5, 0x1e, 0xc1, 0x7f, 0x80, 0x28, 0x5e, 0xbd, 0x30, 0x08, 0xb6, 0x9d, 0x2c, 0xf0, 0x04, 0x7d, 0x40, 0x14, 0x60, 0x86, 0xae, 0x65, 0x95, 0x3a, 0xb5, 0x17, 0x71, 0x1a, 0x5a, 0x0a, 0x4a, 0x45, 0x5c, 0x3a, 0xb9, 0x5a, 0xb0, 0x37, 0x02, 0x46, 0x52, 0xe7, 0x10, 0xac, 0x68, 0xdc, 0x17, 0x22, 0x07, 0xa7, 0x30, 0x48, 0xb0, 0x00, 0x00, 0x38, 0x80, 0xa3, 0x81, 0x9a, 0x02, 0x40, 0x00, 0x41, 0x42, 0x71, 0x58, 0xe6, 0x7f, 0xb9, 0x06, 0xa7, 0xbb, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0a, 0xa0, 0xfc, 0x21, 0x17, 0x55, 0x65, 0x0c, 0x03, 0x05, 0x55, 0x21, 0x0c, 0xc1, 0x60, 0x58, 0x00, 0x1f, 0x00, 0x26, 0x24, 0x42, 0x75, 0x04, 0x7a, 0x85, 0x18, 0x4d, 0x37, 0x00, 0xd7, 0x86, 0x60, 0xc5, 0x92, 0x37, 0xa1, 0x34, 0x54, 0x2e, 0x23, 0x64, 0x41, 0x53, 0x12, 0xfe, 0xb5, 0x3c, 0x52, 0x9d, 0x8b, 0x9d, 0xba, 0x9c, 0x21, 0x8d, 0x68, 0x01, 0x66, 0x37, 0x0f, 0x75, 0xf2, 0xdd, 0x67, 0xc6, 0xdd, 0x5b, 0x86, 0x20, 0x01, 0x02, 0x40, 0x16, 0x04, 0x30, 0xd2, 0xc2, 0x46, 0x5d, 0xc0}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x1c, 0x96, 0x6b, 0x26, 0xf8, 0x00, 0x05, 0x40, 0x70, 0xe0, 0x1d, 0x1a, 0x78, 0x3b, 0xad, 0x9a, 0x24, 0x0e, 0xe5, 0x54, 0x38, 0x92, 0x95, 0x6f, 0xba, 0x0d, 0x9a, 0x01, 0x92, 0x68, 0xdd, 0x51, 0xc2, 0x29, 0x15, 0x0a, 0x5e, 0x77, 0xc1, 0xda, 0x55, 0xba, 0xea, 0xb4, 0xe9, 0x96, 0xfa, 0xbf, 0x70, 0x66, 0xad, 0x29, 0xa7, 0x77, 0x9e, 0x71, 0xd2, 0x2e, 0x5d, 0x7c, 0x58, 0x00, 0x13, 0x44, 0x80, 0x0a, 0x76, 0x18, 0x30, 0x44, 0x0c, 0x48, 0x02, 0x97, 0x30, 0xe4, 0x4a, 0xeb, 0x87}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x20, 0xfc, 0x21, 0x17, 0x55, 0x4d, 0x15, 0x68, 0x24, 0x00, 0x00, 0x4a, 0x90, 0x38, 0x00, 0xf0, 0x42, 0x71, 0xbc, 0x3f, 0x91, 0x01, 0xef, 0x19, 0x4c, 0x4e, 0x3f, 0x55, 0x74, 0xab, 0xc1, 0x6d, 0x44, 0x93, 0x6a, 0xc4, 0x17, 0x02, 0x10, 0x49, 0xbe, 0x95, 0x6f, 0xed, 0x9b, 0x9e, 0x7f, 0x92, 0xdb, 0xe1, 0x57, 0xc7, 0xe4, 0xc3, 0xdd, 0x24, 0x51, 0x39, 0xe5, 0x66, 0x10, 0xe3, 0x72, 0xc4, 0xa1, 0x5c, 0x13, 0x78, 0x45, 0xbd, 0x48, 0x00, 0x6d, 0x18, 0x12, 0x00, 0xa7, 0x41, 0x86, 0x8d, 0x83, 0xfa, 0x5d, 0xae}) write([]byte{0xff, 0xf1, 0x50, 0x80, 0x0b, 0x40, 0xfc, 0x21, 0x17, 0x55, 0x5d, 0x20, 0xd1, 0x03, 0x43, 0x09, 0x16, 0xa0, 0x03, 0x2f, 0x42, 0xc1, 0xa0, 0x45, 0xb3, 0xd6, 0x97, 0x6b, 0x68, 0xa0, 0x37, 0x38, 0xe8, 0xe5, 0xba, 0x8a, 0x3c, 0xf2, 0xf2, 0x78, 0xef, 0x83, 0x5b, 0x35, 0x93, 0x8a, 0x02, 0xde, 0x72, 0x1b, 0x06, 0x4c, 0xb1, 0x5f, 0x45, 0x6b, 0x60, 0xb3, 0x54, 0x3b, 0x3f, 0x2e, 0x18, 0x9d, 0xe0, 0xc9, 0xcf, 0x25, 0x31, 0x34, 0x76, 0xc4, 0xb7, 0x95, 0xd3, 0x2d, 0xbc, 0x20, 0xb5, 0x84, 0xc6, 0x14, 0x90, 0x88, 0x2a, 0xd8, 0x21, 0xc0, 0x2e, 0xfe}) }
ylcrow/go-fdkaac
<|start_filename|>range-slider.js<|end_filename|> /*! * * ======================================================================= * THE SIMPLEST JAVASCRIPT CUSTOM RANGE SLIDER * Author: <NAME> <https://github.com/tovic> * ======================================================================= * * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org> * */ function rangeSlider(elem, config) { var html = document.documentElement, range = document.createElement('div'), dragger = document.createElement('span'), down = false, rangeWidth, rangeOffset, draggerWidth, cachePosition; var defaults = { value: 0, // set default value on initiation from `0` to `100` (percentage based) vertical: false, // vertical or horizontal? rangeClass: "", // add extra custom class for the range slider track draggerClass: "", // add extra custom class for the range slider dragger drag: function(v) { /* console.log(v); */ } // function to return the range slider value into something }; for (var i in defaults) { if (typeof config[i] == "undefined") config[i] = defaults[i]; } function addEventTo(el, ev, fn) { if (el.addEventListener) { el.addEventListener(ev, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + ev, fn); } else { el['on' + ev] = fn; } } var isVertical = config.vertical; elem.className = (elem.className + ' range-slider ' + (isVertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, ""); range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, ""); dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, ""); addEventTo(range, "mousedown", function(e) { html.className = (html.className + ' no-select').replace(/^ +/, ""); rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight']; rangeOffset = range.getBoundingClientRect().left; // rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop']; draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight']; down = true; updateDragger(e); return false; }); addEventTo(document, "mousemove", function(e) { updateDragger(e); }); addEventTo(document, "mouseup", function(e) { html.className = html.className.replace(/(^| )no-select( |$)/g, ""); down = false; }); addEventTo(window, "resize", function(e) { var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight']; dragger.style[!isVertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px'; down = false; }); function updateDragger(e) { e = e || window.event; var pos = !isVertical ? e.pageX : e.pageY; if (!pos) { pos = !isVertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) { dragger.style[!isVertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px'; cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100); config.drag(cachePosition); } } function initDragger() { var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight']; cachePosition = ((config.value / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']); dragger.style[!isVertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px'; config.drag(config.value); } range.appendChild(dragger); elem.appendChild(range); initDragger(); } <|start_filename|>kmeans.js<|end_filename|> // Initial inspiration was from: http://www.bytemuse.com/post/k-means-clustering-visualization/ $(function() { // Number of points to be used in the K-Means Visualization var NUM_POINTS = 500; var $numClusters = $('#num-clusters'); var numClusters = parseInt($numClusters.val(), 10); var $numCentroids = $('#num-centroids'); var numCentroids = parseInt($numClusters.val(), 10); var $rangeSlider = $('#range-slider'); var $meanSquareValue = $('.mean-square-value'); var width = $('#kmeans-vis').width(); var height = width; // Create SVG for d3 var svg = d3.select('#kmeans-vis').append('svg') .attr('width', width) .attr('height', height); pointsGroup = svg.append('g').attr('id', 'points'); var centroidsGroup = svg.append('g').attr('id', 'centroids'); var voronoiGroup = svg.append('g').attr('id', 'voronoi'); var triangle = d3.svg.symbol().type('triangle-up').size(function(d) { return 200; }); var colors = d3.scale.category10(); // Array of (x, y) points that will be classified var points = []; // Array of (x, y) centroids var centroids = []; var centroidBins = []; // Initial randomness. This is what the slider is set to. // 0 means data is very clustered, 100 means completely random var randomness = 25; var $step = $('.step'); rangeSlider($rangeSlider[0], { value: randomness, drag: function(value) { // Update the randomness after the user drags the slider // and reset the points to be clustered randomness = value; resetPoints(); } }); // Resets the text on the centroid button function resetCentroidUpdateText() { $step.addClass('find'); $step.html('Find closest centroid'); $('.active').removeClass('active'); $('.closest').addClass('active'); } // Every time the step button is clicked, we alternate between finding the closest // centroid and updating the centroid $step.click(function() { if ($step.hasClass('find')) { findClosestCentroid(); findClosestCentroidAnimation(); $step.removeClass('find'); $step.html('Update centroid'); $('.active').removeClass('active'); $('.update').addClass('active'); } else { updateCentroid(); updateCentroidAnimation(); resetCentroidUpdateText(); } }); $('.closest').on('click', function() { if ($('.closest').hasClass('active')) { $step.click(); } }); $('.update').on('click', function() { if ($('.update').hasClass('active')) { $step.click(); } }); $('.new-points').click(function() { resetPoints(); }); $numClusters.blur(function() { var numClustersNew = parseInt($numClusters.val(), 10); if (!isNaN(numClustersNew) && numClustersNew != numClusters) { resetPoints(); } }); $numCentroids.blur(function() { var numCentroidsNew = parseInt($numCentroids.val(), 10); if (!isNaN(numCentroidsNew) && numCentroidsNew != numCentroids) { generateClusters(); } }); $('.new-centroids').click(function() { generateClusters(); }); $numClusters.blur(function() { var numClustersNew = parseInt($numClusters.val(), 10); if (!isNaN(numClustersNew) && numClustersNew != numClusters) { resetPoints(); } }); $numCentroids.blur(function() { var numCentroidsNew = parseInt($numCentroids.val(), 10); if (!isNaN(numCentroidsNew) && numCentroidsNew != numCentroids) { generateClusters(); } }); function uncolorPoints() { pointsGroup.selectAll('*').remove(); pointsGroup.selectAll('circle') .data(points).enter() .append('circle') .attr('cx', function(d) { return d[0]; }).attr('cy', function(d) { return d[1]; }).attr('r', 3); } function resetPoints() { resetCentroidUpdateText(); points = []; // Arbitrarily chosen variance and percentageClusteredPoints // There is no signficance behind the constants except that they looked good // with the slider. var variance = randomness / 2 + 5; var percentageClusteredPoints = (100 - 0.8 * randomness) / 100; numClusters = parseInt($numClusters.val(), 10); for (var i = 0; i < numClusters; i++) { // Creates a normal distribution with mean randomCenter(parameter) // and variance var xNorm = d3.random.normal(randomCenter(width), variance); var yNorm = d3.random.normal(randomCenter(height), variance); for (var j = 0; j < percentageClusteredPoints * NUM_POINTS / numClusters; j++) { points.push([normalPt(xNorm), normalPt(yNorm)]); } } // Scatter the remaining points randomly var length = points.length; for (var i = 0; i < NUM_POINTS - length; i++) { points.push([randomCenter(width), randomCenter(height)]); } uncolorPoints(); resetCentroidUpdateText(); voronoiGroup.selectAll('*').remove(); $meanSquareValue.html('not yet calculated'); } // Randomly generates the clusters and initializes the d3 animation function generateClusters() { centroids = []; numCentroids = parseInt($numCentroids.val(), 10); uncolorPoints(); resetCentroidUpdateText(); // Generate completely random centroids for (var k = 0; k < numCentroids; k++) { var randomX = randomCenter(width); var randomY = randomCenter(height); centroids.push([randomX, randomY]); } // Render initial centroid display centroidsGroup.selectAll('*').remove(); voronoiGroup.selectAll('*').remove(); centroidsGroup.selectAll('path') .data(centroids).enter() .append('path') .attr('d', triangle) .attr('fill', function(d, ndx){ return colors(ndx); }) .style('stroke', 'black') .style('stroke-width', '0.7') .attr('transform', function(d){ return 'translate(' + d[0] + ',' + d[1] + ')'; }); $meanSquareValue.html('not yet calculated'); } // For each point, we find the centroid it is the closest to. function findClosestCentroid() { centroidBins = []; for (var i = 0; i < numCentroids; i++) { centroidBins.push([]); } for (var i = 0; i < points.length; i++) { var point = points[i]; var minDist = Infinity; var minIndex = 0; for (var j = 0; j < centroids.length; j++) { centroid = centroids[j]; var d = distance(point, centroid); if (d < minDist) { minDist = d; minIndex = j; } } centroidBins[minIndex].push(point); } var meanSquaredDistance = 0; for (var i = 0; i < centroidBins.length; i++) { bin = centroidBins[i]; for (var j = 0; j < bin.length; j++) { var dist = distance(centroids[i], bin[j]); meanSquaredDistance += dist * dist; } } meanSquaredDistance /= NUM_POINTS; $meanSquareValue.html(meanSquaredDistance.toFixed(2)); } function findClosestCentroidAnimation() { // TODO: This is terribly inefficient, fix later // Color the points according to the centroid to which they belong pointsGroup.selectAll('*') .data(points) .transition() .attr('fill', function(d, ndx){ for (var i = 0; i < centroidBins.length; i++) { if (centroidBins[i].indexOf(d) != -1) { return colors(i); } } }); // Render voronoi voronoiGroup.selectAll('*').remove(); // Comment these lines out to get rid of Voronoi voronoiGroup.selectAll('path') .data(d3.geom.voronoi(centroids)) .enter().append('path') .style('fill', function(d, ndx) { return colors(ndx); }).attr('d', function(d) { return 'M' + (d.join('L')) + 'Z'; }); } // Once the points have been assigned to the centroids, updates the // centroid to be the mean of all points assigned to it function updateCentroid() { var meanSquaredDistance = 0; // Find new centroids for (var i = 0; i < centroidBins.length; i++) { bin = centroidBins[i]; newCentroid = avgXY(bin); for (var j = 0; j < bin.length; j++) { var dist = distance(newCentroid, bin[j]); meanSquaredDistance += dist * dist; } // If there are no points in the bin, newCentroid may be NaN // In this case, we don't update the centroid location if (!isNaN(newCentroid[0]) && !isNaN(newCentroid[1])) { centroids[i] = newCentroid; } } meanSquaredDistance /= NUM_POINTS; $meanSquareValue.html(meanSquaredDistance.toFixed(2)); } function updateCentroidAnimation() { centroidsGroup.selectAll('path') .data(centroids) .transition() .attr('transform',function(d){ return 'translate(' + d[0] + ',' + d[1] + ')'; }); } // Initial generation of clusters generateClusters(); // Helper functions // Generate centers for dist centers and centroids function randomCenter(n) { return Math.random() * n; }; // Euclidean distance between points a and b function distance(a, b) { return Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2)); } // Finds the average x value and average y value of all the points in arr function avgXY(arr) { var avgX = d3.sum(arr, function(d) { return d[0]; }) / arr.length; var avgY = d3.sum(arr, function(d) { return d[1]; }) / arr.length; return [avgX, avgY]; } // Given a function normalFn, uses it to generate a value. If the value // is not within the range (0, width), continues to do so. function normalPt(normalFn) { var val = normalFn(); if (val > 0 && val < width) { return val; } else { return normalPt(normalFn); } } }); <|start_filename|>range-slider.css<|end_filename|> .range-slider { margin: 5px; display: inline; } .range-slider-track { width: 150px; height: 15px; display: inline-block; position: relative; } .range-slider-track:before { content: ""; /*display: block;*/ position: absolute; top: 7px; left: 0; width: 100%; height: 2px; background-color: black; } .range-slider-track .dragger { display: block; width: 15px; height: 15px; border-radius: 15px; position: absolute; z-index: 2; background-color: #428bca; } .no-select { -webkit-touch-callout:none; -webkit-user-select:none; -khtml-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; } <|start_filename|>kmeans.css<|end_filename|> html { height: 100%; } body { font-size: 16px; background-color: #fcfcfc; position: relative; min-height: 100%; } .container { min-width: 1100px; min-height: 760px; } .k-means-header { padding-left: 0px; } .kmeans-div { width: 600px; } #kmeans-vis { margin-top: 5px; margin-bottom: 5px; height: 600px; width: 600px; border: 1px solid black; } #kmeans-vis #voronoi path { fill-opacity: 0.2; } #num-clusters, #num-centroids { border: 0px; border-bottom: 1px solid black; padding-left: 8px; width: 30px; padding-top: 0px; padding-bottom: 0px; background-color: #fcfcfc; } a { margin-top: 5px; cursor: pointer; } .step { width: 160px; } .algorithm-start { padding-top: 10px; padding-bottom: 10px; } .step-title { padding-left: 10px; padding-top: 10px; font-size: 20px; } .step-description { padding-left: 10px; padding-bottom: 15px; } .active { /*color: #428bca;*/ background-color: #fcf9ce; /*font-weight: bold;*/ cursor: pointer; padding-right: 5px; } hr { margin-top: 30px; border-top: 1px solid #ccc; } .data-header { margin-top: 0px; } div.input { width: 148px; display: inline-block; } a.generate { margin-left: 2px; } footer { position: absolute; font-size: 13px; margin-bottom: 5px; bottom: 0; border-top: 1px solid #ccc;; width: inherit; }
lutzhamel/kmeans
<|start_filename|>Sources/Program.cs<|end_filename|> using HtmlAgilityPack; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CVE_2020_0688_Scanner { class Program { static string getRawVersion(string url) { try { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var web = new HtmlWeb(); var doc = web.Load(url); var value = doc.DocumentNode .SelectNodes("//link") .First() .Attributes["href"].Value; string rawVersion = ""; Regex regex = new Regex(@"/[0-9.]+/"); rawVersion = regex.Match(value).ToString(); if (rawVersion == "") return "[ERROR] Unable to retrieve the version number."; else return rawVersion.Replace("/", ""); } catch (Exception ex) { return "[ERROR] Unable to connect to the server : " + ex.ToString(); } } static string getServerVersion(string rawVersion) { if (rawVersion.StartsWith("6.5.")) { return "2003"; } if (rawVersion.StartsWith("8.")) { return "2007"; } if (rawVersion.StartsWith("14.")) { return "2010"; } if (rawVersion.StartsWith("15.0.")) { return "2013"; } if (rawVersion.StartsWith("15.1.")) { return "2016"; } if (rawVersion.StartsWith("15.2.")) { return "2019"; } return "[ERROR] Unable to identify server version."; } static void Main(string[] args) { // Args if (args.Length < 1) { Console.WriteLine("[ERROR] Missing argument 1 : File to process." + Environment.NewLine); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(Properties.Resources.helpText); Console.ForegroundColor = ConsoleColor.White; Environment.Exit(0); } string input = args[0]; if (!File.Exists(@input)) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("[ERROR] File " + input + " not found." + Environment.NewLine); Environment.Exit(0); } // Display banner Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(Properties.Resources.bannerText); // Init System.IO.StreamReader file = new System.IO.StreamReader(@input); string host; int processed = 0; List<String> lstFailed = new List<string>(); List<String> lstSafe = new List<string>(); List<String> lstVulnerable = new List<string>(); List<String> lstMaybeSafe = new List<string>(); // Process each line while ((host = file.ReadLine()) != null) { // Process one item Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(Environment.NewLine + "[DEBUG] Processing " + host); // Check input format if (!host.Contains("http://") && !host.Contains("https://")) { host = "https://" + host; } if (!Uri.IsWellFormedUriString(host, UriKind.Absolute)) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("[ERROR] Malformed URL " + host); lstFailed.Add(host); goto end; } // Get raw version string rawVersion = getRawVersion(host); if (rawVersion.Contains("[ERROR]")) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(rawVersion); lstFailed.Add(host); goto end; } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[INFO] Identified version " + rawVersion); } // Get exchange version string serverVersion = getServerVersion(rawVersion); if (serverVersion.Contains("[ERROR]")) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(serverVersion); lstFailed.Add(host); goto end; } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[INFO] Server version is Exchange " + serverVersion); } string vulnerable = "unknow"; try { // Check if vulnerable if (serverVersion == "2007" || serverVersion == "2003") { // 2003 & 2007 can't be patched against CVE-2020-0688 vulnerable = "yes"; } else if (serverVersion == "2010") { // If version is equal or greather than 14.3.496 then server is patched if (Convert.ToInt32(rawVersion.Split('.')[2]) >= 496) vulnerable = "no"; else vulnerable = "yes"; } else if (serverVersion == "2013") { /* If version starts with 15.0.1497 then it may be vulnerable (only 15.0.1497.6 is patched) If version is greater than 15.0.1497 then server is patched */ if (Convert.ToInt32(rawVersion.Split('.')[2]) == 1497) vulnerable = "maybe"; else if (Convert.ToInt32(rawVersion.Split('.')[2]) > 1497) vulnerable = "no"; else vulnerable = "yes"; } else if (serverVersion == "2016") { /* If version starts with 15.1.1913 or 15.1.1847 then it may be vulnerable (only 15.1.1913.7 and 15.1.1847.7 are patched) If version is greater than 15.1.1913 then server is patched */ if (Convert.ToInt32(rawVersion.Split('.')[2]) == 1913 || Convert.ToInt32(rawVersion.Split('.')[2]) == 1847) vulnerable = "maybe"; else if (Convert.ToInt32(rawVersion.Split('.')[2]) > 1913) vulnerable = "no"; else vulnerable = "yes"; } else if (serverVersion == "2019") { /* If version starts with 15.2.529 or 15.2.464 then it may be vulnerable (only 15.2.529.8 and 15.2.464.11 are patched) If version is greater than 15.1.1913 then server is patched */ if (Convert.ToInt32(rawVersion.Split('.')[2]) == 529 || Convert.ToInt32(rawVersion.Split('.')[2]) == 464) vulnerable = "maybe"; else if (Convert.ToInt32(rawVersion.Split('.')[2]) > 529) vulnerable = "no"; else vulnerable = "yes"; } } catch { } if (vulnerable == "yes") { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[CRITICAL] Server is vulnerable to CVE-2020-0688 !"); lstVulnerable.Add(host); } else if (vulnerable == "maybe") { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[WARNING] Server may be patched for CVE-2020-0688."); lstMaybeSafe.Add(host); } else if (vulnerable == "no") { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[OK] Server is patched for CVE-2020-0688."); lstSafe.Add(host); } else { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("[ERROR] Uknown error."); lstFailed.Add(host); } // End item end: Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("[DEBUG] Item processed." + Environment.NewLine); processed++; } // Display stats Console.WriteLine("=====> STATS"); Console.WriteLine("> Processed: " + processed.ToString()); ; Console.WriteLine("> Error: " + lstFailed.Count); Console.WriteLine("> Vulnerable: " + lstVulnerable.Count); Console.WriteLine("> (Maybe) Patched: " + lstMaybeSafe.Count); Console.WriteLine("> Patched: " + lstSafe.Count); // Write to output file string outfile = "CVE_2020_0688_Scan_" + DateTime.Now.ToString().Replace(":", "").Replace("/", "").Replace(" ", "_") + ".txt"; Console.WriteLine(Environment.NewLine + "=====> Writing results in " + outfile); using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(@outfile)) { file2.WriteLine("---------- Patched servers ----------"); file2.WriteLine(""); foreach (string line in lstSafe) { file2.WriteLine(line); } file2.WriteLine("---------- (Maybe) Patched servers ----------"); file2.WriteLine(""); foreach (string line in lstMaybeSafe) { file2.WriteLine(line); } file2.WriteLine("---------- Vulnerable servers ----------"); file2.WriteLine(""); foreach (string line in lstVulnerable) { file2.WriteLine(line); } file2.WriteLine("---------- Errors ----------"); file2.WriteLine(""); foreach (string line in lstFailed) { file2.WriteLine(line); } } // Exit file file.Close(); // Exit program Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(Environment.NewLine + "Press any key to exit..."); Console.ReadKey(); } } }
onSec-fr/CVE-2020-0688-Scanner
<|start_filename|>DetectorDescription/Core/src/DDSolid.cc<|end_filename|> #include "DetectorDescription/Core/interface/DDSolid.h" #include "DetectorDescription/Core/interface/DDSolidShapes.h" #include <ostream> #include <string> #include <array> #include "DetectorDescription/Core/src/Assembly.h" #include "DetectorDescription/Core/src/Boolean.h" #include "DetectorDescription/Core/src/Box.h" #include "DetectorDescription/Core/src/Cons.h" #include "DetectorDescription/Core/src/EllipticalTube.h" #include "DetectorDescription/Core/src/ExtrudedPolygon.h" #include "DetectorDescription/Core/src/Polycone.h" #include "DetectorDescription/Core/src/Polyhedra.h" #include "DetectorDescription/Core/src/PseudoTrap.h" #include "DetectorDescription/Core/src/Shapeless.h" #include "DetectorDescription/Core/src/Solid.h" #include "DetectorDescription/Core/src/Sphere.h" #include "DetectorDescription/Core/src/Torus.h" #include "DetectorDescription/Core/src/Trap.h" #include "DetectorDescription/Core/src/TruncTubs.h" #include "DetectorDescription/Core/src/Tubs.h" #include "DetectorDescription/Core/src/CutTubs.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/Exception.h" using DDI::Solid; std::ostream& operator<<(std::ostream& os, const DDSolidShape s) { return os << "DDSolidShape index:" << static_cast<int>(s) << ", name: " << DDSolidShapesName::name(s); } std::ostream& operator<<(std::ostream& os, const DDSolid& solid) { DDBase<DDName, DDI::Solid*>::def_type defined(solid.isDefined()); if (defined.first) { os << *(defined.first) << " "; if (defined.second) { os << " " << DDSolidShapesName::name(solid.shape()) << ": "; solid.rep().stream(os); } else { os << "* solid not defined * "; } } else { os << "* solid not declared * "; } return os; } DDSolid::DDSolid() : DDBase<DDName, std::unique_ptr<Solid>>() {} DDSolid::DDSolid(const DDName& name) : DDBase<DDName, std::unique_ptr<Solid>>() { create(name); } DDSolid::DDSolid(const DDName& name, std::unique_ptr<Solid> solid) : DDBase<DDName, std::unique_ptr<Solid>>() { create(name, std::move(solid)); } DDSolid::DDSolid(const DDName& name, DDSolidShape shape, const std::vector<double>& pars) { std::unique_ptr<DDI::Solid> solid(nullptr); std::vector<double> dummy; switch (shape) { case DDSolidShape::ddbox: solid = std::make_unique<DDI::Box>(0, 0, 0); break; case DDSolidShape::ddtubs: solid = std::make_unique<DDI::Tubs>(0, 0, 0, 0, 0); break; case DDSolidShape::ddcons: solid = std::make_unique<DDI::Cons>(0, 0, 0, 0, 0, 0, 0); break; case DDSolidShape::ddpseudotrap: solid = std::make_unique<DDI::PseudoTrap>(0, 0, 0, 0, 0, 0, false); break; case DDSolidShape::ddshapeless: solid = std::make_unique<DDI::Shapeless>(); break; case DDSolidShape::ddtrap: solid = std::make_unique<DDI::Trap>(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); break; case DDSolidShape::ddpolyhedra_rz: solid = std::make_unique<DDI::Polyhedra>(0, 0, 0, dummy, dummy); break; case DDSolidShape::ddpolyhedra_rrz: solid = std::make_unique<DDI::Polyhedra>(0, 0, 0, dummy, dummy, dummy); break; case DDSolidShape::ddpolycone_rz: solid = std::make_unique<DDI::Polycone>(0, 0, dummy, dummy); break; case DDSolidShape::ddpolycone_rrz: solid = std::make_unique<DDI::Polycone>(0, 0, dummy, dummy, dummy); break; case DDSolidShape::ddtrunctubs: solid = std::make_unique<DDI::TruncTubs>(0, 0, 0, 0, 0, 0, 0, false); break; case DDSolidShape::ddtorus: solid = std::make_unique<DDI::Torus>(0, 0, 0, 0, 0); break; case DDSolidShape::ddsphere: solid = std::make_unique<DDI::Sphere>(0, 0, 0, 0, 0, 0); break; case DDSolidShape::ddellipticaltube: solid = std::make_unique<DDI::EllipticalTube>(0, 0, 0); break; case DDSolidShape::ddcuttubs: solid = std::make_unique<DDI::CutTubs>(0., 0., 0., 0., 0., 0., 0., 1., 0., 0., -1.); break; case DDSolidShape::ddextrudedpolygon: solid = std::make_unique<DDI::ExtrudedPolygon>(dummy, dummy, dummy, dummy, dummy, dummy); break; case DDSolidShape::ddassembly: solid = std::make_unique<DDI::Assembly>(); break; default: throw cms::Exception("DDException") << "DDSolid::DDSolid( DDName, DDSolidShape, std::vector<double> ): wrong shape."; } solid->setParameters(pars); create(name, std::move(solid)); } double DDSolid::volume() const { return rep().volume(); } DDSolidShape DDSolid::shape() const { return rep().shape(); } const std::vector<double>& DDSolid::parameters() const { return rep().parameters(); } DDTrap::DDTrap(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddtrap) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is no DDTrap.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDTrap::halfZ() const { return rep().parameters()[0]; } double DDTrap::theta() const { return rep().parameters()[1]; } double DDTrap::phi() const { return rep().parameters()[2]; } double DDTrap::y1() const { return rep().parameters()[3]; } double DDTrap::x1() const { return rep().parameters()[4]; } double DDTrap::x2() const { return rep().parameters()[5]; } double DDTrap::alpha1() const { return rep().parameters()[6]; } double DDTrap::y2() const { return rep().parameters()[7]; } double DDTrap::x3() const { return rep().parameters()[8]; } double DDTrap::x4() const { return rep().parameters()[9]; } double DDTrap::alpha2() const { return rep().parameters()[10]; } DDTruncTubs::DDTruncTubs(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddtrunctubs) { edm::LogError("DDSolid") << "s.shape()=" << s.shape() << " " << s.name() << std::endl; std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is no DDTruncTubs\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDTruncTubs::zHalf() const { return rep().parameters()[0]; } double DDTruncTubs::rIn() const { return rep().parameters()[1]; } double DDTruncTubs::rOut() const { return rep().parameters()[2]; } double DDTruncTubs::startPhi() const { return rep().parameters()[3]; } double DDTruncTubs::deltaPhi() const { return rep().parameters()[4]; } double DDTruncTubs::cutAtStart() const { return rep().parameters()[5]; } double DDTruncTubs::cutAtDelta() const { return rep().parameters()[6]; } bool DDTruncTubs::cutInside() const { return bool(rep().parameters()[7]); } DDPseudoTrap::DDPseudoTrap(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddpseudotrap) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is no DDPseudoTrap\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDPseudoTrap::halfZ() const { return rep().parameters()[4]; } double DDPseudoTrap::x1() const { return rep().parameters()[0]; } double DDPseudoTrap::x2() const { return rep().parameters()[1]; } double DDPseudoTrap::y1() const { return rep().parameters()[2]; } double DDPseudoTrap::y2() const { return rep().parameters()[3]; } double DDPseudoTrap::radius() const { return rep().parameters()[5]; } bool DDPseudoTrap::atMinusZ() const { return rep().parameters()[6]; } DDBox::DDBox(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddbox) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDBox.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDBox::halfX() const { return rep().parameters()[0]; } double DDBox::halfY() const { return rep().parameters()[1]; } double DDBox::halfZ() const { return rep().parameters()[2]; } DDShapelessSolid::DDShapelessSolid(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddshapeless) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDShapelessSolid.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } DDUnion::DDUnion(const DDSolid& s) : DDBooleanSolid(s) { if (s.shape() != DDSolidShape::ddunion) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDUnion.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } DDIntersection::DDIntersection(const DDSolid& s) : DDBooleanSolid(s) { if (s.shape() != DDSolidShape::ddunion) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDIntersection.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } DDSubtraction::DDSubtraction(const DDSolid& s) : DDBooleanSolid(s) { if (s.shape() != DDSolidShape::ddsubtraction) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is no DDSubtraction.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } DDPolySolid::DDPolySolid(const DDSolid& s) : DDSolid(s) {} std::vector<double> DDPolySolid::getVec(const size_t& which, const size_t& offset, const size_t& numVecs) const { // which: first second or third std::vector // offset: number of non-std::vector components before std::vectors start if ((rep().parameters().size() - offset) % numVecs != 0) { edm::LogError("DDSolid") << "Could not find equal sized components of std::vectors in a PolySolid description." << "rep().parameters().size()=" << rep().parameters().size() << " numVecs=" << numVecs << " offset=" << offset << std::endl; } std::vector<double> tvec; for (size_t i = offset + which; i < rep().parameters().size(); i = i + numVecs) { tvec.emplace_back(rep().parameters()[i]); } return tvec; } DDPolycone::DDPolycone(const DDSolid& s) : DDPolySolid(s) { if (s.shape() != DDSolidShape::ddpolycone_rz && s.shape() != DDSolidShape::ddpolycone_rrz) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDPolycone.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDPolycone::startPhi() const { return rep().parameters()[0]; } double DDPolycone::deltaPhi() const { return rep().parameters()[1]; } std::vector<double> DDPolycone::rVec() const { std::vector<double> tvec; if (shape() == DDSolidShape::ddpolycone_rz) tvec = getVec(1, 2, 2); return tvec; } std::vector<double> DDPolycone::zVec() const { if (shape() == DDSolidShape::ddpolycone_rz) return getVec(0, 2, 2); else // (shape() == DDSolidShape::ddpolycone_rrz) return getVec(0, 2, 3); } std::vector<double> DDPolycone::rMinVec() const { std::vector<double> tvec; if (shape() == DDSolidShape::ddpolycone_rrz) tvec = getVec(1, 2, 3); return tvec; } std::vector<double> DDPolycone::rMaxVec() const { std::vector<double> tvec; if (shape() == DDSolidShape::ddpolycone_rrz) tvec = getVec(2, 2, 3); return tvec; } DDPolyhedra::DDPolyhedra(const DDSolid& s) : DDPolySolid(s) { if (s.shape() != DDSolidShape::ddpolyhedra_rz && s.shape() != DDSolidShape::ddpolyhedra_rrz) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDPolyhedra.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } int DDPolyhedra::sides() const { return int(rep().parameters()[0]); } double DDPolyhedra::startPhi() const { return rep().parameters()[1]; } double DDPolyhedra::deltaPhi() const { return rep().parameters()[2]; } std::vector<double> DDPolyhedra::rVec() const { std::vector<double> tvec; if (shape() == DDSolidShape::ddpolyhedra_rz) tvec = getVec(1, 3, 2); return tvec; } std::vector<double> DDPolyhedra::zVec() const { if (shape() == DDSolidShape::ddpolyhedra_rz) return getVec(0, 3, 2); else // (shape() == ddpolycone_rrz) return getVec(0, 3, 3); } std::vector<double> DDPolyhedra::rMinVec() const { std::vector<double> tvec; if (shape() == DDSolidShape::ddpolyhedra_rrz) tvec = getVec(1, 3, 3); return tvec; } std::vector<double> DDPolyhedra::rMaxVec() const { std::vector<double> tvec; if (shape() == DDSolidShape::ddpolyhedra_rrz) tvec = getVec(2, 3, 3); return tvec; } DDExtrudedPolygon::DDExtrudedPolygon(const DDSolid& s) : DDPolySolid(s) { if (s.shape() != DDSolidShape::ddextrudedpolygon) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDExtrudedPolygon.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } auto DDExtrudedPolygon::xyPointsSize(void) const -> std::size_t { // Compute the size of the X and Y coordinate vectors // which define the vertices of the outlined polygon // defined in clock-wise order return (rep().parameters().size() - 4 * zSectionsSize()) * 0.5; } auto DDExtrudedPolygon::zSectionsSize(void) const -> std::size_t { // The first parameters element stores a size of the four equal size vectors // which form the ExtrudedPolygon shape Z sections: // // * first: Z coordinate of the XY polygone plane, // * second and third: x and y offset of the polygone in the XY plane, // * fourth: the polygone scale in each XY plane // // The Z sections defined by the z position in an increasing order. return rep().parameters()[0]; } std::vector<double> DDExtrudedPolygon::xVec(void) const { return std::vector<double>(rep().parameters().begin() + 1, rep().parameters().begin() + 1 + xyPointsSize()); } std::vector<double> DDExtrudedPolygon::yVec(void) const { return std::vector<double>(rep().parameters().begin() + 1 + xyPointsSize(), rep().parameters().begin() + 1 + 2 * xyPointsSize()); } std::vector<double> DDExtrudedPolygon::zVec(void) const { return std::vector<double>(rep().parameters().end() - 4 * zSectionsSize(), rep().parameters().end() - 3 * zSectionsSize()); } std::vector<double> DDExtrudedPolygon::zxVec(void) const { return std::vector<double>(rep().parameters().end() - 3 * zSectionsSize(), rep().parameters().end() - 2 * zSectionsSize()); } std::vector<double> DDExtrudedPolygon::zyVec(void) const { return std::vector<double>(rep().parameters().end() - 2 * zSectionsSize(), rep().parameters().end() - zSectionsSize()); } std::vector<double> DDExtrudedPolygon::zscaleVec(void) const { return std::vector<double>(rep().parameters().end() - zSectionsSize(), rep().parameters().end()); } DDCons::DDCons(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddcons) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDCons.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDCons::zhalf() const { return rep().parameters()[0]; } double DDCons::rInMinusZ() const { return rep().parameters()[1]; } double DDCons::rOutMinusZ() const { return rep().parameters()[2]; } double DDCons::rInPlusZ() const { return rep().parameters()[3]; } double DDCons::rOutPlusZ() const { return rep().parameters()[4]; } double DDCons::phiFrom() const { return rep().parameters()[5]; } double DDCons::deltaPhi() const { return rep().parameters()[6]; } DDTorus::DDTorus(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddtorus) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDTorus.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDTorus::rMin() const { return rep().parameters()[0]; } double DDTorus::rMax() const { return rep().parameters()[1]; } double DDTorus::rTorus() const { return rep().parameters()[2]; } double DDTorus::startPhi() const { return rep().parameters()[3]; } double DDTorus::deltaPhi() const { return rep().parameters()[4]; } DDTubs::DDTubs(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddtubs) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDTubs.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDTubs::zhalf() const { return rep().parameters()[0]; } double DDTubs::rIn() const { return rep().parameters()[1]; } double DDTubs::rOut() const { return rep().parameters()[2]; } double DDTubs::startPhi() const { return rep().parameters()[3]; } double DDTubs::deltaPhi() const { return rep().parameters()[4]; } DDBooleanSolid::DDBooleanSolid(const DDSolid& s) : DDSolid(s), boolean_(static_cast<DDI::BooleanSolid&>(s.rep())) {} DDRotation DDBooleanSolid::rotation() const { return boolean_.r(); } DDTranslation DDBooleanSolid::translation() const { return boolean_.t(); } DDSolid DDBooleanSolid::solidA() const { return boolean_.a(); } DDSolid DDBooleanSolid::solidB() const { return boolean_.b(); } DDSphere::DDSphere(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddsphere) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDSphere (or sphere section).\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDSphere::innerRadius() const { return rep().parameters()[0]; } double DDSphere::outerRadius() const { return rep().parameters()[1]; } double DDSphere::startPhi() const { return rep().parameters()[2]; } double DDSphere::deltaPhi() const { return rep().parameters()[3]; } double DDSphere::startTheta() const { return rep().parameters()[4]; } double DDSphere::deltaTheta() const { return rep().parameters()[5]; } DDEllipticalTube::DDEllipticalTube(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddellipticaltube) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDEllipticalTube.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDEllipticalTube::xSemiAxis() const { return rep().parameters()[0]; } double DDEllipticalTube::ySemiAxis() const { return rep().parameters()[1]; } double DDEllipticalTube::zHeight() const { return rep().parameters()[2]; } DDCutTubs::DDCutTubs(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddcuttubs) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDCutTubs.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } double DDCutTubs::zhalf() const { return rep().parameters()[0]; } double DDCutTubs::rIn() const { return rep().parameters()[1]; } double DDCutTubs::rOut() const { return rep().parameters()[2]; } double DDCutTubs::startPhi() const { return rep().parameters()[3]; } double DDCutTubs::deltaPhi() const { return rep().parameters()[4]; } std::array<double, 3> DDCutTubs::lowNorm(void) const { return std::array<double, 3>{{rep().parameters()[5], rep().parameters()[6], rep().parameters()[7]}}; } std::array<double, 3> DDCutTubs::highNorm(void) const { return std::array<double, 3>{{rep().parameters()[8], rep().parameters()[9], rep().parameters()[10]}}; } DDAssembly::DDAssembly(const DDSolid& s) : DDSolid(s) { if (s.shape() != DDSolidShape::ddassembly) { std::string ex = "Solid [" + s.name().ns() + ":" + s.name().name() + "] is not a DDAssembly.\n"; ex = ex + "Use a different solid interface!"; throw cms::Exception("DDException") << ex; } } // ================================================================================= // =========================SolidFactory============================================ DDSolid DDSolidFactory::assembly(const DDName& name) { return DDSolid(name, std::make_unique<DDI::Assembly>()); } DDSolid DDSolidFactory::box(const DDName& name, double xHalf, double yHalf, double zHalf) { return DDSolid(name, std::make_unique<DDI::Box>(xHalf, yHalf, zHalf)); } DDSolid DDSolidFactory::polycone(const DDName& name, double startPhi, double deltaPhi, const std::vector<double>& z, const std::vector<double>& rmin, const std::vector<double>& rmax) { return DDSolid(name, std::make_unique<DDI::Polycone>(startPhi, deltaPhi, z, rmin, rmax)); } DDSolid DDSolidFactory::polycone( const DDName& name, double startPhi, double deltaPhi, const std::vector<double>& z, const std::vector<double>& r) { return DDSolid(name, std::make_unique<DDI::Polycone>(startPhi, deltaPhi, z, r)); } DDSolid DDSolidFactory::polyhedra(const DDName& name, int sides, double startPhi, double deltaPhi, const std::vector<double>& z, const std::vector<double>& rmin, const std::vector<double>& rmax) { return DDSolid(name, std::make_unique<DDI::Polyhedra>(sides, startPhi, deltaPhi, z, rmin, rmax)); } DDSolid DDSolidFactory::polyhedra(const DDName& name, int sides, double startPhi, double deltaPhi, const std::vector<double>& z, const std::vector<double>& r) { return DDSolid(name, std::make_unique<DDI::Polyhedra>(sides, startPhi, deltaPhi, z, r)); } DDSolid DDSolidFactory::extrudedpolygon(const DDName& name, const std::vector<double>& x, const std::vector<double>& y, const std::vector<double>& z, const std::vector<double>& zx, const std::vector<double>& zy, const std::vector<double>& zscale) { return DDSolid(name, std::make_unique<DDI::ExtrudedPolygon>(x, y, z, zx, zy, zscale)); } DDSolid DDSolidFactory::unionSolid( const DDName& name, const DDSolid& a, const DDSolid& b, const DDTranslation& t, const DDRotation& r) { return DDSolid(name, std::make_unique<DDI::Union>(a, b, t, r)); } DDSolid DDSolidFactory::subtraction( const DDName& name, const DDSolid& a, const DDSolid& b, const DDTranslation& t, const DDRotation& r) { return DDSolid(name, std::make_unique<DDI::Subtraction>(a, b, t, r)); } DDSolid DDSolidFactory::intersection( const DDName& name, const DDSolid& a, const DDSolid& b, const DDTranslation& t, const DDRotation& r) { return DDSolid(name, std::make_unique<DDI::Intersection>(a, b, t, r)); } DDSolid DDSolidFactory::trap(const DDName& name, double pDz, double pTheta, double pPhi, double pDy1, double pDx1, double pDx2, double pAlp1, double pDy2, double pDx3, double pDx4, double pAlp2) { return DDSolid(name, std::make_unique<DDI::Trap>(pDz, pTheta, pPhi, pDy1, pDx1, pDx2, pAlp1, pDy2, pDx3, pDx4, pAlp2)); } DDSolid DDSolidFactory::pseudoTrap(const DDName& name, double pDx1, /**< Half-length along x at the surface positioned at -dz */ double pDx2, /**< Half-length along x at the surface positioned at +dz */ double pDy1, /**< Half-length along y at the surface positioned at -dz */ double pDy2, /**< Half-length along y at the surface positioned at +dz */ double pDz, /**< Half of the height of the pseudo trapezoid along z */ double radius, /**< radius of the cut-out (negative sign) or rounding (pos. sign) */ bool atMinusZ /**< if true, the cut-out or rounding is applied at -dz, else at +dz */ ) { return DDSolid(name, std::make_unique<DDI::PseudoTrap>(pDx1, pDx2, pDy1, pDy2, pDz, radius, atMinusZ)); } DDSolid DDSolidFactory::truncTubs(const DDName& name, double zHalf, /**< half-length of the z-axis */ double rIn, /**< inner radius of the tube-section */ double rOut, /**< outer radius of the tube-section */ double startPhi, /**< starting angle of the tube-section */ double deltaPhi, /**< spanning angle of the tube-section */ double cutAtStart, /**< tructation at startPhi side */ double cutAtDelta, /**< truncation at deltaPhi side */ bool cutInside) { return DDSolid( name, std::make_unique<DDI::TruncTubs>(zHalf, rIn, rOut, startPhi, deltaPhi, cutAtStart, cutAtDelta, cutInside)); } DDSolid DDSolidFactory::cons(const DDName& name, double zhalf, double rInMinusZ, double rOutMinusZ, double rInPlusZ, double rOutPlusZ, double phiFrom, double deltaPhi) { return DDSolid(name, std::make_unique<DDI::Cons>(zhalf, rInMinusZ, rOutMinusZ, rInPlusZ, rOutPlusZ, phiFrom, deltaPhi)); } DDSolid DDSolidFactory::torus( const DDName& name, double rMin, double rMax, double rTorus, double startPhi, double deltaPhi) { return DDSolid(name, std::make_unique<DDI::Torus>(rMin, rMax, rTorus, startPhi, deltaPhi)); } DDSolid DDSolidFactory::tubs( const DDName& name, double zhalf, double rIn, double rOut, double phiFrom, double deltaPhi) { return DDSolid(name, std::make_unique<DDI::Tubs>(zhalf, rIn, rOut, phiFrom, deltaPhi)); } DDSolid DDSolidFactory::cuttubs(const DDName& name, double zhalf, double rIn, double rOut, double phiFrom, double deltaPhi, double lx, double ly, double lz, double tx, double ty, double tz) { return DDSolid(name, std::make_unique<DDI::CutTubs>(zhalf, rIn, rOut, phiFrom, deltaPhi, lx, ly, lz, tx, ty, tz)); } DDSolid DDSolidFactory::sphere(const DDName& name, double innerRadius, double outerRadius, double startPhi, double deltaPhi, double startTheta, double deltaTheta) { return DDSolid(name, std::make_unique<DDI::Sphere>(innerRadius, outerRadius, startPhi, deltaPhi, startTheta, deltaTheta)); } DDSolid DDSolidFactory::ellipticalTube(const DDName& name, double xSemiAxis, double ySemiAxis, double zHeight) { return DDSolid(name, std::make_unique<DDI::EllipticalTube>(xSemiAxis, ySemiAxis, zHeight)); } DDSolid DDSolidFactory::shapeless(const DDName& name) { return DDSolid(name, std::make_unique<DDI::Shapeless>()); } <|start_filename|>SimDataFormats/Associations/interface/TracksterToSimTracksterAssociator.h<|end_filename|> #ifndef SimDataFormats_Associations_TracksterToSimTracksterAssociator_h #define SimDataFormats_Associations_TracksterToSimTracksterAssociator_h // Original Author: <NAME> // system include files #include <memory> // user include files #include "SimDataFormats/Associations/interface/TracksterToSimTracksterAssociatorBaseImpl.h" // forward declarations namespace hgcal { class TracksterToSimTracksterAssociator { public: TracksterToSimTracksterAssociator(std::unique_ptr<hgcal::TracksterToSimTracksterAssociatorBaseImpl>); TracksterToSimTracksterAssociator() = default; TracksterToSimTracksterAssociator(TracksterToSimTracksterAssociator &&) = default; TracksterToSimTracksterAssociator &operator=(TracksterToSimTracksterAssociator &&) = default; ~TracksterToSimTracksterAssociator() = default; // ---------- const member functions --------------------- /// Associate a Trackster to SimClusters hgcal::RecoToSimCollectionSimTracksters associateRecoToSim( const edm::Handle<ticl::TracksterCollection> &tCH, const edm::Handle<reco::CaloClusterCollection> &lCCH, const edm::Handle<ticl::TracksterCollection> &sTCH) const { return m_impl->associateRecoToSim(tCH, lCCH, sTCH); }; /// Associate a SimCluster to Tracksters hgcal::SimToRecoCollectionSimTracksters associateSimToReco( const edm::Handle<ticl::TracksterCollection> &tCH, const edm::Handle<reco::CaloClusterCollection> &lCCH, const edm::Handle<ticl::TracksterCollection> &sTCH) const { return m_impl->associateSimToReco(tCH, lCCH, sTCH); } private: TracksterToSimTracksterAssociator(const TracksterToSimTracksterAssociator &) = delete; // stop default const TracksterToSimTracksterAssociator &operator=(const TracksterToSimTracksterAssociator &) = delete; // stop default // ---------- member data -------------------------------- std::unique_ptr<TracksterToSimTracksterAssociatorBaseImpl> m_impl; }; } // namespace hgcal #endif <|start_filename|>IOPool/Common/bin/EdmProvDump.cc<|end_filename|> #include "DataFormats/Common/interface/setIsMergeable.h" #include "DataFormats/Provenance/interface/BranchType.h" #include "DataFormats/Provenance/interface/EventSelectionID.h" #include "DataFormats/Provenance/interface/History.h" #include "DataFormats/Provenance/interface/ParameterSetBlob.h" #include "DataFormats/Provenance/interface/ParameterSetID.h" #include "DataFormats/Provenance/interface/ProcessHistoryRegistry.h" #include "DataFormats/Provenance/interface/ProductRegistry.h" #include "DataFormats/Provenance/interface/Parentage.h" #include "DataFormats/Provenance/interface/ProductProvenance.h" #include "DataFormats/Provenance/interface/StoredProductProvenance.h" #include "DataFormats/Provenance/interface/ParentageRegistry.h" #include "FWCore/Catalog/interface/InputFileCatalog.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/Registry.h" #include "FWCore/ServiceRegistry/interface/ServiceRegistry.h" #include "FWCore/Services/src/SiteLocalConfigService.h" #include "FWCore/Utilities/interface/Algorithms.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Utilities/interface/propagate_const.h" #include "TError.h" #include "TFile.h" #include "TTree.h" #include "boost/program_options.hpp" #include <cassert> #include <iostream> #include <memory> #include <map> #include <set> #include <sstream> #include <vector> typedef std::map<std::string, std::vector<edm::BranchDescription>> IdToBranches; typedef std::map<std::pair<std::string, std::string>, IdToBranches> ModuleToIdBranches; static std::ostream& prettyPrint(std::ostream& oStream, edm::ParameterSet const& iPSet, std::string const& iIndent, std::string const& iIndentDelta); static std::string const triggerResults = std::string("TriggerResults"); static std::string const triggerPaths = std::string("@trigger_paths"); static std::string const source = std::string("source"); static std::string const input = std::string("@main_input"); namespace { typedef std::map<edm::ParameterSetID, edm::ParameterSetBlob> ParameterSetMap; class HistoryNode { public: HistoryNode() : config_(), simpleId_(0) {} HistoryNode(edm::ProcessConfiguration const& iConfig, unsigned int iSimpleId) : config_(iConfig), simpleId_(iSimpleId) {} void addChild(HistoryNode const& child) { children_.push_back(child); } edm::ParameterSetID const& parameterSetID() const { return config_.parameterSetID(); } std::string const& processName() const { return config_.processName(); } std::size_t size() const { return children_.size(); } HistoryNode* lastChildAddress() { return &children_.back(); } typedef std::vector<HistoryNode>::const_iterator const_iterator; typedef std::vector<HistoryNode>::iterator iterator; iterator begin() { return children_.begin(); } iterator end() { return children_.end(); } const_iterator begin() const { return children_.begin(); } const_iterator end() const { return children_.end(); } void print(std::ostream& os) const { os << config_.processName() << " '" << config_.passID() << "' '" << config_.releaseVersion() << "' [" << simpleId_ << "] (" << config_.parameterSetID() << ")" << std::endl; } void printHistory(std::string const& iIndent = std::string(" ")) const; void printEventSetupHistory(ParameterSetMap const& iPSM, std::vector<std::string> const& iFindMatch, std::ostream& oErrorLog) const; void printOtherModulesHistory(ParameterSetMap const& iPSM, ModuleToIdBranches const&, std::vector<std::string> const& iFindMatch, std::ostream& oErrorLog) const; void printTopLevelPSetsHistory(ParameterSetMap const& iPSM, std::vector<std::string> const& iFindMatch, std::ostream& oErrorLog) const; edm::ProcessConfigurationID configurationID() const { return config_.id(); } static bool sort_; private: edm::ProcessConfiguration config_; std::vector<HistoryNode> children_; unsigned int simpleId_; }; std::ostream& operator<<(std::ostream& os, HistoryNode const& node) { node.print(os); return os; } bool HistoryNode::sort_ = false; } // namespace std::ostream& operator<<(std::ostream& os, edm::ProcessHistory& iHist) { std::string const indentDelta(" "); std::string indent = indentDelta; for (auto const& process : iHist) { os << indent << process.processName() << " '" << process.passID() << "' '" << process.releaseVersion() << "' (" << process.parameterSetID() << ")" << std::endl; indent += indentDelta; } return os; } void HistoryNode::printHistory(std::string const& iIndent) const { std::string const indentDelta(" "); const std::string& indent = iIndent; for (auto const& item : *this) { std::cout << indent << item; item.printHistory(indent + indentDelta); } } std::string eventSetupComponent(char const* iType, std::string const& iCompName, edm::ParameterSet const& iProcessConfig, std::string const& iProcessName) { std::ostringstream result; edm::ParameterSet const& pset = iProcessConfig.getParameterSet(iCompName); std::string name(pset.getParameter<std::string>("@module_label")); if (name.empty()) { name = pset.getParameter<std::string>("@module_type"); } result << iType << ": " << name << " " << iProcessName << "\n" << " parameters: "; prettyPrint(result, pset, " ", " "); return result.str(); } void HistoryNode::printEventSetupHistory(ParameterSetMap const& iPSM, std::vector<std::string> const& iFindMatch, std::ostream& oErrorLog) const { for (auto const& itH : *this) { //Get ParameterSet for process ParameterSetMap::const_iterator itFind = iPSM.find(itH.parameterSetID()); if (itFind == iPSM.end()) { oErrorLog << "No ParameterSetID for " << itH.parameterSetID() << std::endl; } else { edm::ParameterSet processConfig(itFind->second.pset()); std::vector<std::string> sourceStrings, moduleStrings; //get the sources std::vector<std::string> sources = processConfig.getParameter<std::vector<std::string>>("@all_essources"); for (auto& itM : sources) { std::string retValue = eventSetupComponent("ESSource", itM, processConfig, itH.processName()); bool foundMatch = true; if (!iFindMatch.empty()) { for (auto const& stringToFind : iFindMatch) { if (retValue.find(stringToFind) == std::string::npos) { foundMatch = false; break; } } } if (foundMatch) { sourceStrings.push_back(std::move(retValue)); } } //get the modules std::vector<std::string> modules = processConfig.getParameter<std::vector<std::string>>("@all_esmodules"); for (auto& itM : modules) { std::string retValue = eventSetupComponent("ESModule", itM, processConfig, itH.processName()); bool foundMatch = true; if (!iFindMatch.empty()) { for (auto const& stringToFind : iFindMatch) { if (retValue.find(stringToFind) == std::string::npos) { foundMatch = false; break; } } } if (foundMatch) { moduleStrings.push_back(std::move(retValue)); } } if (sort_) { std::sort(sourceStrings.begin(), sourceStrings.end()); std::sort(moduleStrings.begin(), moduleStrings.end()); } std::copy(sourceStrings.begin(), sourceStrings.end(), std::ostream_iterator<std::string>(std::cout, "\n")); std::copy(moduleStrings.begin(), moduleStrings.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } itH.printEventSetupHistory(iPSM, iFindMatch, oErrorLog); } } std::string nonProducerComponent(std::string const& iCompName, edm::ParameterSet const& iProcessConfig, std::string const& iProcessName) { std::ostringstream result; edm::ParameterSet const& pset = iProcessConfig.getParameterSet(iCompName); std::string label(pset.getParameter<std::string>("@module_label")); result << "Module: " << label << " " << iProcessName << "\n" << " parameters: "; prettyPrint(result, pset, " ", " "); return result.str(); } void HistoryNode::printOtherModulesHistory(ParameterSetMap const& iPSM, ModuleToIdBranches const& iModules, std::vector<std::string> const& iFindMatch, std::ostream& oErrorLog) const { for (auto const& itH : *this) { //Get ParameterSet for process ParameterSetMap::const_iterator itFind = iPSM.find(itH.parameterSetID()); if (itFind == iPSM.end()) { oErrorLog << "No ParameterSetID for " << itH.parameterSetID() << std::endl; } else { edm::ParameterSet processConfig(itFind->second.pset()); std::vector<std::string> moduleStrings; //get all modules std::vector<std::string> modules = processConfig.getParameter<std::vector<std::string>>("@all_modules"); for (auto& itM : modules) { //if we didn't already handle this from the branches if (iModules.end() == iModules.find(std::make_pair(itH.processName(), itM))) { std::string retValue(nonProducerComponent(itM, processConfig, itH.processName())); bool foundMatch = true; if (!iFindMatch.empty()) { for (auto const& stringToFind : iFindMatch) { if (retValue.find(stringToFind) == std::string::npos) { foundMatch = false; break; } } } if (foundMatch) { moduleStrings.push_back(std::move(retValue)); } } } if (sort_) { std::sort(moduleStrings.begin(), moduleStrings.end()); } std::copy(moduleStrings.begin(), moduleStrings.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } itH.printOtherModulesHistory(iPSM, iModules, iFindMatch, oErrorLog); } } static void appendToSet(std::set<std::string>& iSet, std::vector<std::string> const& iFrom) { for (auto const& n : iFrom) { iSet.insert(n); } } static std::string topLevelPSet(std::string const& iName, edm::ParameterSet const& iProcessConfig, std::string const& iProcessName) { std::ostringstream result; edm::ParameterSet const& pset = iProcessConfig.getParameterSet(iName); result << "PSet: " << iName << " " << iProcessName << "\n" << " parameters: "; prettyPrint(result, pset, " ", " "); return result.str(); } void HistoryNode::printTopLevelPSetsHistory(ParameterSetMap const& iPSM, std::vector<std::string> const& iFindMatch, std::ostream& oErrorLog) const { for (auto const& itH : *this) { //Get ParameterSet for process ParameterSetMap::const_iterator itFind = iPSM.find(itH.parameterSetID()); if (itFind == iPSM.end()) { oErrorLog << "No ParameterSetID for " << itH.parameterSetID() << std::endl; } else { edm::ParameterSet processConfig(itFind->second.pset()); //Need to get the names of PSets which are used by the framework (e.g. names of modules) std::set<std::string> namesToExclude; appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_modules")); appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_sources")); appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_loopers")); //appendToSet(namesToExclude,processConfig.getParameter<std::vector<std::string> >("@all_subprocesses"));//untracked appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_esmodules")); appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_essources")); appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_esprefers")); if (processConfig.existsAs<std::vector<std::string>>("all_aliases")) { appendToSet(namesToExclude, processConfig.getParameter<std::vector<std::string>>("@all_aliases")); } std::vector<std::string> allNames{}; processConfig.getParameterSetNames(allNames); std::vector<std::string> results; for (auto const& name : allNames) { if (name.empty() || '@' == name[0] || namesToExclude.find(name) != namesToExclude.end()) { continue; } std::string retValue = topLevelPSet(name, processConfig, itH.processName()); bool foundMatch = true; if (!iFindMatch.empty()) { for (auto const& stringToFind : iFindMatch) { if (retValue.find(stringToFind) == std::string::npos) { foundMatch = false; break; } } } if (foundMatch) { results.push_back(std::move(retValue)); } } if (sort_) { std::sort(results.begin(), results.end()); } std::copy(results.begin(), results.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } itH.printTopLevelPSetsHistory(iPSM, iFindMatch, oErrorLog); } } namespace { std::unique_ptr<TFile> makeTFileWithLookup(std::string const& filename) { // See if it is a logical file name. std::unique_ptr<edm::SiteLocalConfig> slcptr = std::make_unique<edm::service::SiteLocalConfigService>(edm::ParameterSet()); auto slc = std::make_shared<edm::serviceregistry::ServiceWrapper<edm::SiteLocalConfig>>(std::move(slcptr)); edm::ServiceToken slcToken = edm::ServiceRegistry::createContaining(slc); edm::ServiceRegistry::Operate operate(slcToken); std::string override; std::vector<std::string> fileNames; fileNames.push_back(filename); edm::InputFileCatalog catalog(fileNames, override, true); if (catalog.fileNames(0)[0] == filename) { throw cms::Exception("FileNotFound", "RootFile::RootFile()") << "File " << filename << " was not found or could not be opened.\n"; } // filename is a valid LFN. std::unique_ptr<TFile> result(TFile::Open(catalog.fileNames(0)[0].c_str())); if (!result.get()) { throw cms::Exception("FileNotFound", "RootFile::RootFile()") << "File " << fileNames[0] << " was not found or could not be opened.\n"; } return result; } // Open the input file, returning the TFile object that represents it. // The returned unique_ptr will not be null. The argument must not be null. // We first try the file name as a PFN, so that the catalog and related // services are not loaded unless needed. std::unique_ptr<TFile> makeTFile(std::string const& filename) { gErrorIgnoreLevel = kFatal; std::unique_ptr<TFile> result(TFile::Open(filename.c_str())); gErrorIgnoreLevel = kError; if (!result.get()) { // Try again with catalog. return makeTFileWithLookup(filename); } return result; } } // namespace static std::ostream& prettyPrint(std::ostream& os, edm::ParameterSetEntry const& psetEntry, std::string const& iIndent, std::string const& iIndentDelta) { char const* trackiness = (psetEntry.isTracked() ? "tracked" : "untracked"); os << "PSet " << trackiness << " = ("; prettyPrint(os, psetEntry.pset(), iIndent + iIndentDelta, iIndentDelta); os << ")"; return os; } static std::ostream& prettyPrint(std::ostream& os, edm::VParameterSetEntry const& vpsetEntry, std::string const& iIndent, std::string const& iIndentDelta) { std::vector<edm::ParameterSet> const& vps = vpsetEntry.vpset(); os << "VPSet " << (vpsetEntry.isTracked() ? "tracked" : "untracked") << " = ({" << std::endl; std::string newIndent = iIndent + iIndentDelta; std::string start; std::string const between(",\n"); for (auto const& item : vps) { os << start << newIndent; prettyPrint(os, item, newIndent, iIndentDelta); start = between; } if (!vps.empty()) { os << std::endl; } os << iIndent << "})"; return os; } static std::ostream& prettyPrint(std::ostream& oStream, edm::ParameterSet const& iPSet, std::string const& iIndent, std::string const& iIndentDelta) { std::string newIndent = iIndent + iIndentDelta; oStream << "{" << std::endl; for (auto const& item : iPSet.tbl()) { // indent a bit oStream << newIndent << item.first << ": " << item.second << std::endl; } for (auto const& item : iPSet.psetTable()) { // indent a bit edm::ParameterSetEntry const& pe = item.second; oStream << newIndent << item.first << ": "; prettyPrint(oStream, pe, iIndent, iIndentDelta); oStream << std::endl; } for (auto const& item : iPSet.vpsetTable()) { // indent a bit edm::VParameterSetEntry const& pe = item.second; oStream << newIndent << item.first << ": "; prettyPrint(oStream, pe, newIndent, iIndentDelta); oStream << std::endl; } oStream << iIndent << "}"; return oStream; } class ProvenanceDumper { public: // It is illegal to call this constructor with a null pointer; a // legal C-style string is required. ProvenanceDumper(std::string const& filename, bool showDependencies, bool extendedAncestors, bool extendedDescendants, bool excludeESModules, bool showAllModules, bool showTopLevelPSets, std::vector<std::string> const& findMatch, bool dontPrintProducts, std::string const& dumpPSetID); ProvenanceDumper(ProvenanceDumper const&) = delete; // Disallow copying and moving ProvenanceDumper& operator=(ProvenanceDumper const&) = delete; // Disallow copying and moving // Write the provenenace information to the given stream. void dump(); void printErrors(std::ostream& os); int exitCode() const; private: void addAncestors(edm::BranchID const& branchID, std::set<edm::BranchID>& ancestorBranchIDs, std::ostringstream& sout, std::map<edm::BranchID, std::set<edm::ParentageID>>& perProductParentage) const; void addDescendants(edm::BranchID const& branchID, std::set<edm::BranchID>& descendantBranchIDs, std::ostringstream& sout, std::map<edm::BranchID, std::set<edm::BranchID>>& parentToChildren) const; std::string filename_; edm::propagate_const<std::unique_ptr<TFile>> inputFile_; int exitCode_; std::stringstream errorLog_; int errorCount_; edm::ProductRegistry reg_; edm::ProcessConfigurationVector phc_; edm::ProcessHistoryVector phv_; ParameterSetMap psm_; HistoryNode historyGraph_; bool showDependencies_; bool extendedAncestors_; bool extendedDescendants_; bool excludeESModules_; bool showOtherModules_; bool productRegistryPresent_; bool showTopLevelPSets_; std::vector<std::string> findMatch_; bool dontPrintProducts_; std::string dumpPSetID_; void work_(); void dumpProcessHistory_(); void dumpEventFilteringParameterSets_(TFile* file); void dumpEventFilteringParameterSets(edm::EventSelectionIDVector const& ids); void dumpParameterSetForID_(edm::ParameterSetID const& id); }; ProvenanceDumper::ProvenanceDumper(std::string const& filename, bool showDependencies, bool extendedAncestors, bool extendedDescendants, bool excludeESModules, bool showOtherModules, bool showTopLevelPSets, std::vector<std::string> const& findMatch, bool dontPrintProducts, std::string const& dumpPSetID) : filename_(filename), inputFile_(makeTFile(filename)), exitCode_(0), errorLog_(), errorCount_(0), showDependencies_(showDependencies), extendedAncestors_(extendedAncestors), extendedDescendants_(extendedDescendants), excludeESModules_(excludeESModules), showOtherModules_(showOtherModules), productRegistryPresent_(true), showTopLevelPSets_(showTopLevelPSets), findMatch_(findMatch), dontPrintProducts_(dontPrintProducts), dumpPSetID_(dumpPSetID) {} void ProvenanceDumper::dump() { work_(); } void ProvenanceDumper::printErrors(std::ostream& os) { if (errorCount_ > 0) os << errorLog_.str() << std::endl; } int ProvenanceDumper::exitCode() const { return exitCode_; } void ProvenanceDumper::dumpEventFilteringParameterSets(edm::EventSelectionIDVector const& ids) { edm::EventSelectionIDVector::size_type num_ids = ids.size(); if (num_ids == 0) { std::cout << "No event filtering information is available.\n"; std::cout << "------------------------------\n"; } else { std::cout << "Event filtering information for " << num_ids << " processing steps is available.\n" << "The ParameterSets will be printed out, " << "with the oldest printed first.\n"; for (edm::EventSelectionIDVector::size_type i = 0; i != num_ids; ++i) { dumpParameterSetForID_(ids[i]); } } } void ProvenanceDumper::dumpEventFilteringParameterSets_(TFile* file) { TTree* history = dynamic_cast<TTree*>(file->Get(edm::poolNames::eventHistoryTreeName().c_str())); if (history != nullptr) { edm::History h; edm::History* ph = &h; history->SetBranchAddress(edm::poolNames::eventHistoryBranchName().c_str(), &ph); if (history->GetEntry(0) <= 0) { std::cout << "No event filtering information is available; the event history tree has no entries\n"; } else { dumpEventFilteringParameterSets(h.eventSelectionIDs()); } } else { TTree* events = dynamic_cast<TTree*>(file->Get(edm::poolNames::eventTreeName().c_str())); assert(events != nullptr); TBranch* eventSelectionsBranch = events->GetBranch(edm::poolNames::eventSelectionsBranchName().c_str()); if (eventSelectionsBranch == nullptr) return; edm::EventSelectionIDVector ids; edm::EventSelectionIDVector* pids = &ids; eventSelectionsBranch->SetAddress(&pids); if (eventSelectionsBranch->GetEntry(0) <= 0) { std::cout << "No event filtering information is available; the event selections branch has no entries\n"; } else { dumpEventFilteringParameterSets(ids); } } } void ProvenanceDumper::dumpParameterSetForID_(edm::ParameterSetID const& id) { std::cout << "ParameterSetID: " << id << '\n'; if (id.isValid()) { ParameterSetMap::const_iterator i = psm_.find(id); if (i == psm_.end()) { std::cout << "We are unable to find the corresponding ParameterSet\n"; edm::ParameterSet empty; empty.registerIt(); if (id == empty.id()) { std::cout << "But it would have been empty anyway\n"; } } else { edm::ParameterSet ps(i->second.pset()); prettyPrint(std::cout, ps, " ", " "); std::cout << '\n'; } } else { std::cout << "This ID is not valid\n"; } std::cout << " -------------------------\n"; } void ProvenanceDumper::dumpProcessHistory_() { std::cout << "Processing History:" << std::endl; std::map<edm::ProcessConfigurationID, unsigned int> simpleIDs; for (auto const& ph : phv_) { //loop over the history entries looking for matches HistoryNode* parent = &historyGraph_; for (auto const& pc : ph) { if (parent->size() == 0) { unsigned int id = simpleIDs[pc.id()]; if (0 == id) { id = 1; simpleIDs[pc.id()] = id; } parent->addChild(HistoryNode(pc, id)); parent = parent->lastChildAddress(); } else { //see if this is unique bool isUnique = true; for (auto& child : *parent) { if (child.configurationID() == pc.id()) { isUnique = false; parent = &child; break; } } if (isUnique) { simpleIDs[pc.id()] = parent->size() + 1; parent->addChild(HistoryNode(pc, simpleIDs[pc.id()])); parent = parent->lastChildAddress(); } } } } historyGraph_.printHistory(); } void ProvenanceDumper::work_() { TTree* meta = dynamic_cast<TTree*>(inputFile_->Get(edm::poolNames::metaDataTreeName().c_str())); assert(nullptr != meta); edm::ProductRegistry* pReg = &reg_; if (meta->FindBranch(edm::poolNames::productDescriptionBranchName().c_str()) != nullptr) { meta->SetBranchAddress(edm::poolNames::productDescriptionBranchName().c_str(), &pReg); } else { productRegistryPresent_ = false; } ParameterSetMap* pPsm = &psm_; if (meta->FindBranch(edm::poolNames::parameterSetMapBranchName().c_str()) != nullptr) { meta->SetBranchAddress(edm::poolNames::parameterSetMapBranchName().c_str(), &pPsm); } else { TTree* psetTree = dynamic_cast<TTree*>(inputFile_->Get(edm::poolNames::parameterSetsTreeName().c_str())); assert(nullptr != psetTree); typedef std::pair<edm::ParameterSetID, edm::ParameterSetBlob> IdToBlobs; IdToBlobs idToBlob; IdToBlobs* pIdToBlob = &idToBlob; psetTree->SetBranchAddress(edm::poolNames::idToParameterSetBlobsBranchName().c_str(), &pIdToBlob); for (long long i = 0; i != psetTree->GetEntries(); ++i) { psetTree->GetEntry(i); psm_.insert(idToBlob); } } edm::ProcessHistoryVector* pPhv = &phv_; if (meta->FindBranch(edm::poolNames::processHistoryBranchName().c_str()) != nullptr) { meta->SetBranchAddress(edm::poolNames::processHistoryBranchName().c_str(), &pPhv); } edm::ProcessHistoryMap phm; edm::ProcessHistoryMap* pPhm = &phm; if (meta->FindBranch(edm::poolNames::processHistoryMapBranchName().c_str()) != nullptr) { meta->SetBranchAddress(edm::poolNames::processHistoryMapBranchName().c_str(), &pPhm); } if (meta->FindBranch(edm::poolNames::moduleDescriptionMapBranchName().c_str()) != nullptr) { if (meta->GetBranch(edm::poolNames::moduleDescriptionMapBranchName().c_str())->GetSplitLevel() != 0) { meta->SetBranchStatus((edm::poolNames::moduleDescriptionMapBranchName() + ".*").c_str(), false); } else { meta->SetBranchStatus(edm::poolNames::moduleDescriptionMapBranchName().c_str(), false); } } meta->GetEntry(0); assert(nullptr != pReg); edm::pset::Registry& psetRegistry = *edm::pset::Registry::instance(); for (auto const& item : psm_) { edm::ParameterSet pset(item.second.pset()); pset.setID(item.first); psetRegistry.insertMapped(pset); } if (!phv_.empty()) { for (auto const& history : phv_) { for (auto const& process : history) { phc_.push_back(process); } } edm::sort_all(phc_); phc_.erase(std::unique(phc_.begin(), phc_.end()), phc_.end()); } // backward compatibility else if (!phm.empty()) { for (auto const& history : phm) { phv_.push_back(history.second); for (auto const& process : history.second) { phc_.push_back(process); } } edm::sort_all(phc_); phc_.erase(std::unique(phc_.begin(), phc_.end()), phc_.end()); } if (!dumpPSetID_.empty()) { edm::ParameterSetID psetID; try { psetID = edm::ParameterSetID(dumpPSetID_); } catch (cms::Exception const& x) { throw cms::Exception("Command Line Argument") << "Illegal ParameterSetID string. It should contain 32 hexadecimal characters"; } dumpParameterSetForID_(psetID); return; } //Prepare the parentage information if requested std::map<edm::BranchID, std::set<edm::ParentageID>> perProductParentage; if (showDependencies_ || extendedAncestors_ || extendedDescendants_) { TTree* parentageTree = dynamic_cast<TTree*>(inputFile_->Get(edm::poolNames::parentageTreeName().c_str())); if (nullptr == parentageTree) { std::cerr << "ERROR, no Parentage tree available so cannot show dependencies, ancestors, or descendants.\n"; std::cerr << "Possibly this is not a standard EDM format file. For example, dependency, ancestor, and\n"; std::cerr << "descendant options to edmProvDump will not work with nanoAOD format files.\n\n"; showDependencies_ = false; extendedAncestors_ = false; extendedDescendants_ = false; } else { edm::ParentageRegistry& registry = *edm::ParentageRegistry::instance(); std::vector<edm::ParentageID> orderedParentageIDs; orderedParentageIDs.reserve(parentageTree->GetEntries()); for (Long64_t i = 0, numEntries = parentageTree->GetEntries(); i < numEntries; ++i) { edm::Parentage parentageBuffer; edm::Parentage* pParentageBuffer = &parentageBuffer; parentageTree->SetBranchAddress(edm::poolNames::parentageBranchName().c_str(), &pParentageBuffer); parentageTree->GetEntry(i); registry.insertMapped(parentageBuffer); orderedParentageIDs.push_back(parentageBuffer.id()); } parentageTree->SetBranchAddress(edm::poolNames::parentageBranchName().c_str(), nullptr); TTree* eventMetaTree = dynamic_cast<TTree*>(inputFile_->Get(edm::BranchTypeToMetaDataTreeName(edm::InEvent).c_str())); if (nullptr == eventMetaTree) { eventMetaTree = dynamic_cast<TTree*>(inputFile_->Get(edm::BranchTypeToProductTreeName(edm::InEvent).c_str())); } if (nullptr == eventMetaTree) { std::cerr << "ERROR, no '" << edm::BranchTypeToProductTreeName(edm::InEvent) << "' Tree in file so can not show dependencies\n"; showDependencies_ = false; extendedAncestors_ = false; extendedDescendants_ = false; } else { TBranch* storedProvBranch = eventMetaTree->GetBranch(edm::BranchTypeToProductProvenanceBranchName(edm::InEvent).c_str()); if (nullptr != storedProvBranch) { std::vector<edm::StoredProductProvenance> info; std::vector<edm::StoredProductProvenance>* pInfo = &info; storedProvBranch->SetAddress(&pInfo); for (Long64_t i = 0, numEntries = eventMetaTree->GetEntries(); i < numEntries; ++i) { storedProvBranch->GetEntry(i); for (auto const& item : info) { edm::BranchID bid(item.branchID_); perProductParentage[bid].insert(orderedParentageIDs.at(item.parentageIDIndex_)); } } } else { //backwards compatible check TBranch* productProvBranch = eventMetaTree->GetBranch(edm::BranchTypeToBranchEntryInfoBranchName(edm::InEvent).c_str()); if (nullptr != productProvBranch) { std::vector<edm::ProductProvenance> info; std::vector<edm::ProductProvenance>* pInfo = &info; productProvBranch->SetAddress(&pInfo); for (Long64_t i = 0, numEntries = eventMetaTree->GetEntries(); i < numEntries; ++i) { productProvBranch->GetEntry(i); for (auto const& item : info) { perProductParentage[item.branchID()].insert(item.parentageID()); } } } else { std::cerr << " ERROR, could not find provenance information so can not show dependencies\n"; showDependencies_ = false; extendedAncestors_ = false; extendedDescendants_ = false; } } } } } std::map<edm::BranchID, std::set<edm::BranchID>> parentToChildren; edm::ParentageRegistry& registry = *edm::ParentageRegistry::instance(); if (extendedDescendants_) { for (auto const& itParentageSet : perProductParentage) { edm::BranchID childBranchID = itParentageSet.first; for (auto const& itParentageID : itParentageSet.second) { edm::Parentage const* parentage = registry.getMapped(itParentageID); if (nullptr != parentage) { for (auto const& branch : parentage->parents()) { parentToChildren[branch].insert(childBranchID); } } else { std::cerr << " ERROR:parentage info not in registry ParentageID=" << itParentageID << std::endl; } } } } dumpEventFilteringParameterSets_(inputFile_.get()); dumpProcessHistory_(); if (productRegistryPresent_) { std::cout << "---------Producers with data in file---------" << std::endl; } //using edm::ParameterSetID as the key does not work // typedef std::map<edm::ParameterSetID, std::vector<edm::BranchDescription> > IdToBranches ModuleToIdBranches moduleToIdBranches; //IdToBranches idToBranches; std::map<edm::BranchID, std::string> branchIDToBranchName; for (auto const& processConfig : phc_) { edm::ParameterSet const* processParameterSet = edm::pset::Registry::instance()->getMapped(processConfig.parameterSetID()); if (nullptr == processParameterSet || processParameterSet->empty()) { continue; } for (auto& item : reg_.productListUpdator()) { auto& product = item.second; if (product.processName() != processConfig.processName()) { continue; } //force it to rebuild the branch name product.init(); setIsMergeable(product); if (showDependencies_ || extendedAncestors_ || extendedDescendants_) { branchIDToBranchName[product.branchID()] = product.branchName(); } /* std::cout << product.branchName() << " id " << product.productID() << std::endl; */ std::string moduleLabel = product.moduleLabel(); if (moduleLabel == source) { moduleLabel = input; } else if (moduleLabel == triggerResults) { moduleLabel = triggerPaths; } std::stringstream s; if (processParameterSet->existsAs<edm::ParameterSet>(moduleLabel)) { edm::ParameterSet const& moduleParameterSet = processParameterSet->getParameterSet(moduleLabel); if (!moduleParameterSet.isRegistered()) { edm::ParameterSet moduleParameterSetCopy = processParameterSet->getParameterSet(moduleLabel); moduleParameterSetCopy.registerIt(); s << moduleParameterSetCopy.id(); } else { s << moduleParameterSet.id(); } moduleToIdBranches[std::make_pair(product.processName(), product.moduleLabel())][s.str()].push_back(product); } } } for (auto const& item : moduleToIdBranches) { std::ostringstream sout; sout << "Module: " << item.first.second << " " << item.first.first << std::endl; std::set<edm::BranchID> allBranchIDsForLabelAndProcess; IdToBranches const& idToBranches = item.second; for (auto const& idBranch : idToBranches) { sout << " PSet id:" << idBranch.first << std::endl; if (!dontPrintProducts_) { sout << " products: {" << std::endl; } std::set<edm::BranchID> branchIDs; for (auto const& branch : idBranch.second) { if (!dontPrintProducts_) { sout << " " << branch.branchName() << std::endl; } branchIDs.insert(branch.branchID()); allBranchIDsForLabelAndProcess.insert(branch.branchID()); } sout << " }" << std::endl; edm::ParameterSetID psid(idBranch.first); ParameterSetMap::const_iterator itpsm = psm_.find(psid); if (psm_.end() == itpsm) { ++errorCount_; errorLog_ << "No ParameterSetID for " << psid << std::endl; exitCode_ = 1; } else { sout << " parameters: "; prettyPrint(sout, edm::ParameterSet((*itpsm).second.pset()), " ", " "); sout << std::endl; } if (showDependencies_) { sout << " dependencies: {" << std::endl; std::set<edm::ParentageID> parentageIDs; for (auto const& branch : branchIDs) { //Save these BranchIDs std::set<edm::ParentageID> const& temp = perProductParentage[branch]; parentageIDs.insert(temp.begin(), temp.end()); } for (auto const& parentID : parentageIDs) { edm::Parentage const* parentage = registry.getMapped(parentID); if (nullptr != parentage) { for (auto const& branch : parentage->parents()) { sout << " " << branchIDToBranchName[branch] << std::endl; } } else { sout << " ERROR:parentage info not in registry ParentageID=" << parentID << std::endl; } } if (parentageIDs.empty()) { sout << " no dependencies recorded (event may not contain data from this module)" << std::endl; } sout << " }" << std::endl; } } // end loop over PSetIDs if (extendedAncestors_) { sout << " extendedAncestors: {" << std::endl; std::set<edm::BranchID> ancestorBranchIDs; for (auto const& branchID : allBranchIDsForLabelAndProcess) { addAncestors(branchID, ancestorBranchIDs, sout, perProductParentage); } for (auto const& ancestorBranchID : ancestorBranchIDs) { sout << " " << branchIDToBranchName[ancestorBranchID] << "\n"; } sout << " }" << std::endl; } if (extendedDescendants_) { sout << " extendedDescendants: {" << std::endl; std::set<edm::BranchID> descendantBranchIDs; for (auto const& branchID : allBranchIDsForLabelAndProcess) { addDescendants(branchID, descendantBranchIDs, sout, parentToChildren); } for (auto const& descendantBranchID : descendantBranchIDs) { sout << " " << branchIDToBranchName[descendantBranchID] << "\n"; } sout << " }" << std::endl; } bool foundMatch = true; if (!findMatch_.empty()) { for (auto const& stringToFind : findMatch_) { if (sout.str().find(stringToFind) == std::string::npos) { foundMatch = false; break; } } } if (foundMatch) { std::cout << sout.str() << std::endl; } } // end loop over module label/process if (productRegistryPresent_ && showOtherModules_) { std::cout << "---------Other Modules---------" << std::endl; historyGraph_.printOtherModulesHistory(psm_, moduleToIdBranches, findMatch_, errorLog_); } else if (!productRegistryPresent_) { std::cout << "---------All Modules---------" << std::endl; historyGraph_.printOtherModulesHistory(psm_, moduleToIdBranches, findMatch_, errorLog_); } if (!excludeESModules_) { std::cout << "---------EventSetup---------" << std::endl; historyGraph_.printEventSetupHistory(psm_, findMatch_, errorLog_); } if (showTopLevelPSets_) { std::cout << "---------Top Level PSets---------" << std::endl; historyGraph_.printTopLevelPSetsHistory(psm_, findMatch_, errorLog_); } if (errorCount_ != 0) { exitCode_ = 1; } } void ProvenanceDumper::addAncestors(edm::BranchID const& branchID, std::set<edm::BranchID>& ancestorBranchIDs, std::ostringstream& sout, std::map<edm::BranchID, std::set<edm::ParentageID>>& perProductParentage) const { edm::ParentageRegistry& registry = *edm::ParentageRegistry::instance(); std::set<edm::ParentageID> const& parentIDs = perProductParentage[branchID]; for (auto const& parentageID : parentIDs) { edm::Parentage const* parentage = registry.getMapped(parentageID); if (nullptr != parentage) { for (auto const& branch : parentage->parents()) { if (ancestorBranchIDs.insert(branch).second) { addAncestors(branch, ancestorBranchIDs, sout, perProductParentage); } } } else { sout << " ERROR:parentage info not in registry ParentageID=" << parentageID << std::endl; } } } void ProvenanceDumper::addDescendants(edm::BranchID const& branchID, std::set<edm::BranchID>& descendantBranchIDs, std::ostringstream& sout, std::map<edm::BranchID, std::set<edm::BranchID>>& parentToChildren) const { for (auto const& childBranchID : parentToChildren[branchID]) { if (descendantBranchIDs.insert(childBranchID).second) { addDescendants(childBranchID, descendantBranchIDs, sout, parentToChildren); } } } static char const* const kSortOpt = "sort"; static char const* const kSortCommandOpt = "sort,s"; static char const* const kDependenciesOpt = "dependencies"; static char const* const kDependenciesCommandOpt = "dependencies,d"; static char const* const kExtendedAncestorsOpt = "extendedAncestors"; static char const* const kExtendedAncestorsCommandOpt = "extendedAncestors,x"; static char const* const kExtendedDescendantsOpt = "extendedDescendants"; static char const* const kExtendedDescendantsCommandOpt = "extendedDescendants,c"; static char const* const kExcludeESModulesOpt = "excludeESModules"; static char const* const kExcludeESModulesCommandOpt = "excludeESModules,e"; static char const* const kShowAllModulesOpt = "showAllModules"; static char const* const kShowAllModulesCommandOpt = "showAllModules,a"; static char const* const kFindMatchOpt = "findMatch"; static char const* const kFindMatchCommandOpt = "findMatch,f"; static char const* const kDontPrintProductsOpt = "dontPrintProducts"; static char const* const kDontPrintProductsCommandOpt = "dontPrintProducts,p"; static char const* const kShowTopLevelPSetsOpt = "showTopLevelPSets"; static char const* const kShowTopLevelPSetsCommandOpt = "showTopLevelPSets,t"; static char const* const kHelpOpt = "help"; static char const* const kHelpCommandOpt = "help,h"; static char const* const kFileNameOpt = "input-file"; static char const* const kDumpPSetIDOpt = "dumpPSetID"; static char const* const kDumpPSetIDCommandOpt = "dumpPSetID,i"; int main(int argc, char* argv[]) { using namespace boost::program_options; std::string descString(argv[0]); descString += " [options] <filename>"; descString += "\nAllowed options"; options_description desc(descString); // clang-format off desc.add_options()(kHelpCommandOpt, "show help message")(kSortCommandOpt, "alphabetially sort EventSetup components")( kDependenciesCommandOpt, "print what data each EDProducer is directly dependent upon")( kExtendedAncestorsCommandOpt, "print what data each EDProducer is dependent upon including indirect dependences")( kExtendedDescendantsCommandOpt, "print what data depends on the data each EDProducer produces including indirect dependences")( kExcludeESModulesCommandOpt, "do not print ES module information")( kShowAllModulesCommandOpt, "show all modules (not just those that created data in the file)")( kShowTopLevelPSetsCommandOpt, "show all top level PSets")( kFindMatchCommandOpt, boost::program_options::value<std::vector<std::string>>(), "show only modules whose information contains the matching string (or all the matching strings, this option can " "be repeated with different strings)")(kDontPrintProductsCommandOpt, "do not print products produced by module")( kDumpPSetIDCommandOpt, value<std::string>(), "print the parameter set associated with the parameter set ID string (and print nothing else)"); // clang-format on //we don't want users to see these in the help messages since this // name only exists since the parser needs it options_description hidden; hidden.add_options()(kFileNameOpt, value<std::string>(), "file name"); //full list of options for the parser options_description cmdline_options; cmdline_options.add(desc).add(hidden); positional_options_description p; p.add(kFileNameOpt, -1); variables_map vm; try { store(command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm); notify(vm); } catch (error const& iException) { std::cerr << iException.what(); return 1; } if (vm.count(kHelpOpt)) { std::cout << desc << std::endl; return 0; } if (vm.count(kSortOpt)) { HistoryNode::sort_ = true; } bool showDependencies = false; if (vm.count(kDependenciesOpt)) { showDependencies = true; } bool extendedAncestors = false; if (vm.count(kExtendedAncestorsOpt)) { extendedAncestors = true; } bool extendedDescendants = false; if (vm.count(kExtendedDescendantsOpt)) { extendedDescendants = true; } bool excludeESModules = false; if (vm.count(kExcludeESModulesOpt)) { excludeESModules = true; } bool showAllModules = false; if (vm.count(kShowAllModulesOpt)) { showAllModules = true; } bool showTopLevelPSets = false; if (vm.count(kShowTopLevelPSetsOpt)) { showTopLevelPSets = true; } std::string fileName; if (vm.count(kFileNameOpt)) { try { fileName = vm[kFileNameOpt].as<std::string>(); } catch (boost::bad_any_cast const& e) { std::cout << e.what() << std::endl; return 2; } } else { std::cout << "Data file not specified." << std::endl; std::cout << desc << std::endl; return 2; } std::string dumpPSetID; if (vm.count(kDumpPSetIDOpt)) { try { dumpPSetID = vm[kDumpPSetIDOpt].as<std::string>(); } catch (boost::bad_any_cast const& e) { std::cout << e.what() << std::endl; return 2; } } std::vector<std::string> findMatch; if (vm.count(kFindMatchOpt)) { try { findMatch = vm[kFindMatchOpt].as<std::vector<std::string>>(); } catch (boost::bad_any_cast const& e) { std::cout << e.what() << std::endl; return 2; } } bool dontPrintProducts = false; if (vm.count(kDontPrintProductsOpt)) { dontPrintProducts = true; } //silence ROOT warnings about missing dictionaries gErrorIgnoreLevel = kError; ProvenanceDumper dumper(fileName, showDependencies, extendedAncestors, extendedDescendants, excludeESModules, showAllModules, showTopLevelPSets, findMatch, dontPrintProducts, dumpPSetID); int exitCode(0); try { dumper.dump(); exitCode = dumper.exitCode(); } catch (cms::Exception const& x) { std::cerr << "cms::Exception caught\n"; std::cerr << x.what() << '\n'; exitCode = 2; } catch (std::exception& x) { std::cerr << "std::exception caught\n"; std::cerr << x.what() << '\n'; exitCode = 3; } catch (...) { std::cerr << "Unknown exception caught\n"; exitCode = 4; } dumper.printErrors(std::cerr); return exitCode; } <|start_filename|>CondCore/EcalPlugins/plugins/EcalTPGStripStatus_PayloadInspector.cc<|end_filename|> #include "CondCore/Utilities/interface/PayloadInspectorModule.h" #include "CondCore/Utilities/interface/PayloadInspector.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "CondCore/EcalPlugins/plugins/EcalDrawUtils.h" #include "FWCore/ParameterSet/interface/FileInPath.h" // the data format of the condition to be inspected #include "CondFormats/EcalObjects/interface/EcalTPGStripStatus.h" #include "TH2F.h" #include "TCanvas.h" #include "TStyle.h" #include "TLine.h" #include "TLatex.h" #include <string> namespace { enum { NTCC = 108, NTower = 28, NStrip = 5, NXtal = 5 }; enum { IX_MIN = 1, IY_MIN = 1, IX_MAX = 100, IY_MAX = 100 }; // endcaps lower and upper bounds on x and y /*********************************************** 2d plot of ECAL TPGStripStatus of 1 IOV ************************************************/ class EcalTPGStripStatusPlot : public cond::payloadInspector::PlotImage<EcalTPGStripStatus> { public: EcalTPGStripStatusPlot() : cond::payloadInspector::PlotImage<EcalTPGStripStatus>("ECAL TPGStripStatus - map ") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> >& iovs) override { TH2F* endc_p = new TH2F("EE+", "EE+ TPG Strip Status", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); TH2F* endc_m = new TH2F("EE-", "EE- TPG Strip Status", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); int EEstat[2] = {0, 0}; std::string mappingFile = "Geometry/EcalMapping/data/EEMap.txt"; std::ifstream f(edm::FileInPath(mappingFile).fullPath().c_str()); if (!f.good()) { std::cout << "EcalTPGStripStatus File EEMap.txt not found" << std::endl; throw cms::Exception("FileNotFound"); } uint32_t rawEE[NTCC][NTower][NStrip][NXtal]; int NbrawEE[NTCC][NTower][NStrip]; for (int TCC = 0; TCC < NTCC; TCC++) for (int TT = 0; TT < NTower; TT++) for (int ST = 0; ST < NStrip; ST++) NbrawEE[TCC][TT][ST] = 0; while (!f.eof()) { int ix, iy, iz, CL; int dccid, towerid, pseudostrip_in_SC, xtal_in_pseudostrip; int tccid, tower, pseudostrip_in_TCC, pseudostrip_in_TT; f >> ix >> iy >> iz >> CL >> dccid >> towerid >> pseudostrip_in_SC >> xtal_in_pseudostrip >> tccid >> tower >> pseudostrip_in_TCC >> pseudostrip_in_TT; EEDetId detid(ix, iy, iz, EEDetId::XYMODE); uint32_t rawId = detid.denseIndex(); if (tccid > NTCC || tower > NTower || pseudostrip_in_TT > NStrip || xtal_in_pseudostrip > NXtal) std::cout << " tccid " << tccid << " tower " << tower << " pseudostrip_in_TT " << pseudostrip_in_TT << " xtal_in_pseudostrip " << xtal_in_pseudostrip << std::endl; else { rawEE[tccid - 1][tower - 1][pseudostrip_in_TT - 1][xtal_in_pseudostrip - 1] = rawId; NbrawEE[tccid - 1][tower - 1][pseudostrip_in_TT - 1]++; } } // read EEMap file f.close(); double wei[2] = {0., 0.}; auto iov = iovs.front(); std::shared_ptr<EcalTPGStripStatus> payload = fetchPayload(std::get<1>(iov)); unsigned int run = std::get<0>(iov); if (payload.get()) { const EcalTPGStripStatusMap& stripMap = (*payload).getMap(); // std::cout << " tower map size " << stripMap.size() << std::endl; EcalTPGStripStatusMapIterator itSt; for (itSt = stripMap.begin(); itSt != stripMap.end(); ++itSt) { if (itSt->second > 0) { // let's decode the ID int strip = itSt->first / 8; int pseudostrip = strip & 0x7; strip /= 8; int tt = strip & 0x7F; strip /= 128; int tccid = strip & 0x7F; int NbXtalInStrip = NbrawEE[tccid - 1][tt - 1][pseudostrip - 1]; if (NbXtalInStrip != NXtal) std::cout << " Strip TCC " << tccid << " TT " << tt << " ST " << pseudostrip << " Nx Xtals " << NbXtalInStrip << std::endl; // std::cout << " Strip TCC " << tccid << " TT " << tt << " ST " << pseudostrip // << " Nx Xtals " << NbXtalInStrip << std::endl; for (int Xtal = 0; Xtal < NbXtalInStrip; Xtal++) { uint32_t rawId = rawEE[tccid - 1][tt - 1][pseudostrip - 1][Xtal]; // std::cout << " rawid " << rawId << std::endl; EEDetId detid = EEDetId::detIdFromDenseIndex(rawId); float x = (float)detid.ix(); float y = (float)detid.iy(); int iz = detid.zside(); if (iz == -1) iz++; if (Xtal == 0) wei[iz] += 1.; if (iz == 0) { endc_m->Fill(x + 0.5, y + 0.5, wei[iz]); EEstat[0]++; } else { endc_p->Fill(x + 0.5, y + 0.5, wei[iz]); EEstat[1]++; } // std::cout << " x " << x << " y " << y << " z " << iz << std::endl; } } } } // payload // std::cout << " nb strip EE- " << wei[0] << " EE+ " << wei[1] << std::endl; gStyle->SetPalette(1); gStyle->SetOptStat(0); const Int_t NRGBs = 5; const Int_t NCont = 255; Double_t stops[NRGBs] = {0.00, 0.34, 0.61, 0.84, 1.00}; Double_t red[NRGBs] = {0.00, 0.00, 0.87, 1.00, 0.51}; Double_t green[NRGBs] = {0.00, 0.81, 1.00, 0.20, 0.00}; Double_t blue[NRGBs] = {0.51, 1.00, 0.12, 0.00, 0.00}; TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont); gStyle->SetNumberContours(NCont); // TCanvas canvas("CC map","CC map", 1600, 450); Double_t w = 1200; Double_t h = 650; TCanvas canvas("c", "c", w, h); // canvas.SetWindowSize(w + (w - canvas.GetWw()), h + (h - canvas.GetWh())); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("Ecal TPGStripStatus, IOV %i", run)); float xmi[2] = {0.0, 0.5}; float xma[2] = {0.5, 1.0}; TPad** pad = new TPad*; for (int obj = 0; obj < 2; obj++) { pad[obj] = new TPad(Form("p_%i", obj), Form("p_%i", obj), xmi[obj], 0.0, xma[obj], 0.94); pad[obj]->Draw(); } pad[0]->cd(); DrawEE(endc_m, 0., wei[0]); t1.SetTextSize(0.03); t1.DrawLatex(0.15, 0.92, Form("%i crystals", EEstat[0])); pad[1]->cd(); DrawEE(endc_p, 0., wei[1]); t1.DrawLatex(0.15, 0.92, Form("%i crystals", EEstat[1])); std::string ImageName(m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; /*************************************************************** 2d plot of ECAL TPGStripStatus difference between 2 IOVs ****************************************************************/ template <cond::payloadInspector::IOVMultiplicity nIOVs, int ntags> class EcalTPGStripStatusDiffBase : public cond::payloadInspector::PlotImage<EcalTPGStripStatus, nIOVs, ntags> { public: EcalTPGStripStatusDiffBase() : cond::payloadInspector::PlotImage<EcalTPGStripStatus, nIOVs, ntags>("ECAL TPGStripStatus difference") {} bool fill() override { TH2F* endc_p = new TH2F("EE+", "EE+ TPG Strip Status", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); TH2F* endc_m = new TH2F("EE-", "EE- TPG Strip Status", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); int EEstat[2][2] = {{0, 0}, {0, 0}}; std::string mappingFile = "Geometry/EcalMapping/data/EEMap.txt"; std::ifstream f(edm::FileInPath(mappingFile).fullPath().c_str()); if (!f.good()) { std::cout << "EcalTPGStripStatus File EEMap.txt not found" << std::endl; throw cms::Exception("FileNotFound"); } uint32_t rawEE[NTCC][NTower][NStrip][NXtal]; int NbrawEE[NTCC][NTower][NStrip]; for (int TCC = 0; TCC < NTCC; TCC++) for (int TT = 0; TT < NTower; TT++) for (int ST = 0; ST < NStrip; ST++) NbrawEE[TCC][TT][ST] = 0; while (!f.eof()) { int ix, iy, iz, CL; int dccid, towerid, pseudostrip_in_SC, xtal_in_pseudostrip; int tccid, tower, pseudostrip_in_TCC, pseudostrip_in_TT; f >> ix >> iy >> iz >> CL >> dccid >> towerid >> pseudostrip_in_SC >> xtal_in_pseudostrip >> tccid >> tower >> pseudostrip_in_TCC >> pseudostrip_in_TT; EEDetId detid(ix, iy, iz, EEDetId::XYMODE); uint32_t rawId = detid.denseIndex(); if (tccid > NTCC || tower > NTower || pseudostrip_in_TT > NStrip || xtal_in_pseudostrip > NXtal) std::cout << " tccid " << tccid << " tower " << tower << " pseudostrip_in_TT " << pseudostrip_in_TT << " xtal_in_pseudostrip " << xtal_in_pseudostrip << std::endl; else { rawEE[tccid - 1][tower - 1][pseudostrip_in_TT - 1][xtal_in_pseudostrip - 1] = rawId; NbrawEE[tccid - 1][tower - 1][pseudostrip_in_TT - 1]++; } } // read EEMap file f.close(); unsigned int run[2] = {0, 0}; int vEE[100]; int istat = 0; std::string l_tagname[2]; auto iovs = cond::payloadInspector::PlotBase::getTag<0>().iovs; l_tagname[0] = cond::payloadInspector::PlotBase::getTag<0>().name; auto firstiov = iovs.front(); run[0] = std::get<0>(firstiov); std::tuple<cond::Time_t, cond::Hash> lastiov; if (ntags == 2) { auto tag2iovs = cond::payloadInspector::PlotBase::getTag<1>().iovs; l_tagname[1] = cond::payloadInspector::PlotBase::getTag<1>().name; lastiov = tag2iovs.front(); } else { lastiov = iovs.back(); l_tagname[1] = l_tagname[0]; } run[1] = std::get<0>(lastiov); for (int irun = 0; irun < nIOVs; irun++) { std::shared_ptr<EcalTPGStripStatus> payload; if (irun == 0) { payload = this->fetchPayload(std::get<1>(firstiov)); } else { payload = this->fetchPayload(std::get<1>(lastiov)); } if (payload.get()) { const EcalTPGStripStatusMap& stripMap = (*payload).getMap(); // std::cout << " tower map size " << stripMap.size() << std::endl; EcalTPGStripStatusMapIterator itSt; for (itSt = stripMap.begin(); itSt != stripMap.end(); ++itSt) { if (itSt->second > 0) { int ID = itSt->first / 8; if (irun == 0 && istat < 100) { vEE[istat] = ID; // std::cout << " strip " << ID << " found in run 1" << std::endl; istat++; if (istat == 100) std::cout << " limit on number of strips reached, stop keeping others" << std::endl; } else { bool found = false; for (int is = 0; is < istat; is++) { // std::cout << " checking " << ID << " against " << vEE[is] << std::endl; if (vEE[is] == ID) { // std::cout << " strip " << ID << " already in run 1" << std::endl; found = true; vEE[is] = -1; break; } } if (!found) { // std::cout << " strip " << ID << " new, plot it" << std::endl; // let's decode the ID int strip = ID; int pseudostrip = strip & 0x7; strip /= 8; int tt = strip & 0x7F; strip /= 128; int tccid = strip & 0x7F; int NbXtalInStrip = NbrawEE[tccid - 1][tt - 1][pseudostrip - 1]; if (NbXtalInStrip != NXtal) std::cout << " Strip TCC " << tccid << " TT " << tt << " ST " << pseudostrip << " Nx Xtals " << NbXtalInStrip << std::endl; for (int Xtal = 0; Xtal < NbXtalInStrip; Xtal++) { uint32_t rawId = rawEE[tccid - 1][tt - 1][pseudostrip - 1][Xtal]; // std::cout << " rawid " << rawId << std::endl; EEDetId detid = EEDetId::detIdFromDenseIndex(rawId); float x = (float)detid.ix(); float y = (float)detid.iy(); int iz = detid.zside(); if (iz == -1) iz++; if (iz == 0) { endc_m->Fill(x + 0.5, y + 0.5, 1.); EEstat[0][0]++; } else { endc_p->Fill(x + 0.5, y + 0.5, 1.); EEstat[1][0]++; } // std::cout << " x " << x << " y " << y << " z " << iz << std::endl; } // loop over crystals in strip } // new strip } // second run } } // loop over strips } // payload else return false; // std::cout << " nb of strips " << istat << std::endl; } // loop over IOVs // now check if strips have disappered for (int is = 0; is < istat; is++) { if (vEE[is] != -1) { // std::cout << " strip " << vEE[is] << " not found in run 2, plot it" << std::endl; // let's decode the ID int strip = vEE[is]; int pseudostrip = strip & 0x7; strip /= 8; int tt = strip & 0x7F; strip /= 128; int tccid = strip & 0x7F; int NbXtalInStrip = NbrawEE[tccid - 1][tt - 1][pseudostrip - 1]; if (NbXtalInStrip != NXtal) std::cout << " Strip TCC " << tccid << " TT " << tt << " ST " << pseudostrip << " Nx Xtals " << NbXtalInStrip << std::endl; for (int Xtal = 0; Xtal < NbXtalInStrip; Xtal++) { uint32_t rawId = rawEE[tccid - 1][tt - 1][pseudostrip - 1][Xtal]; // std::cout << " rawid " << rawId << std::endl; EEDetId detid = EEDetId::detIdFromDenseIndex(rawId); float x = (float)detid.ix(); float y = (float)detid.iy(); int iz = detid.zside(); if (iz == -1) iz++; if (iz == 0) { endc_m->Fill(x + 0.5, y + 0.5, -1.); EEstat[0][1]++; } else { endc_p->Fill(x + 0.5, y + 0.5, -1.); EEstat[1][1]++; } // std::cout << " x " << x << " y " << y << " z " << iz << std::endl; } // loop over crystals in strip } // new strip } // loop over run 1 strips gStyle->SetPalette(1); gStyle->SetOptStat(0); const Int_t NRGBs = 5; const Int_t NCont = 255; Double_t stops[NRGBs] = {0.00, 0.34, 0.61, 0.84, 1.00}; Double_t red[NRGBs] = {0.00, 0.00, 0.87, 1.00, 0.51}; Double_t green[NRGBs] = {0.00, 0.81, 1.00, 0.20, 0.00}; Double_t blue[NRGBs] = {0.51, 1.00, 0.12, 0.00, 0.00}; TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont); gStyle->SetNumberContours(NCont); // TCanvas canvas("CC map","CC map", 1600, 450); Double_t w = 1200; Double_t h = 650; TCanvas canvas("c", "c", w, h); // canvas.SetWindowSize(w + (w - canvas.GetWw()), h + (h - canvas.GetWh())); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); int len = l_tagname[0].length() + l_tagname[1].length(); if (ntags == 2) { if (len < 180) { t1.SetTextSize(0.03); t1.DrawLatex(0.5, 0.96, Form("%s %i - %s %i", l_tagname[1].c_str(), run[1], l_tagname[0].c_str(), run[0])); } else { t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("Ecal TPGStripStatus, IOV %i - %i", run[1], run[0])); } } else { t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("%s, IOV %i - %i", l_tagname[0].c_str(), run[1], run[0])); } float xmi[2] = {0.0, 0.5}; float xma[2] = {0.5, 1.0}; TPad** pad = new TPad*; for (int obj = 0; obj < 2; obj++) { pad[obj] = new TPad(Form("p_%i", obj), Form("p_%i", obj), xmi[obj], 0.0, xma[obj], 0.94); pad[obj]->Draw(); } pad[0]->cd(); DrawEE(endc_m, -1.0, 1.0); t1.SetTextSize(0.03); t1.DrawLatex(0.15, 0.92, Form("new %i old %i", EEstat[0][0], EEstat[0][1])); pad[1]->cd(); DrawEE(endc_p, -1.0, 1.0); t1.DrawLatex(0.15, 0.92, Form("new %i old %i", EEstat[1][0], EEstat[1][1])); std::string ImageName(this->m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; // class EcalTPGStripStatusDiffBase using EcalTPGStripStatusDiffOneTag = EcalTPGStripStatusDiffBase<cond::payloadInspector::SINGLE_IOV, 1>; using EcalTPGStripStatusDiffTwoTags = EcalTPGStripStatusDiffBase<cond::payloadInspector::SINGLE_IOV, 2>; /***************************************** 2d plot of EcalTPGStripStatus Error Summary of 1 IOV ******************************************/ class EcalTPGStripStatusSummaryPlot : public cond::payloadInspector::PlotImage<EcalTPGStripStatus> { public: EcalTPGStripStatusSummaryPlot() : cond::payloadInspector::PlotImage<EcalTPGStripStatus>("Ecal TPGStrip Status Summary - map ") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> >& iovs) override { auto iov = iovs.front(); //get reference to 1st element in the vector iovs std::shared_ptr<EcalTPGStripStatus> payload = fetchPayload(std::get<1>(iov)); //std::get<1>(iov) refers to the Hash in the tuple iov unsigned int run = std::get<0>(iov); //referes to Time_t in iov. TH2F* align; //pointer to align which is a 2D histogram int NbRows = 1; int NbColumns = 2; if (payload.get()) { //payload is an iov retrieved from payload using hash. const EcalTPGStripStatusMap& stripMap = (*payload).getMap(); align = new TH2F("Ecal TPGStrip Status Summary", "Total NumberOfMasked", NbColumns, 0, NbColumns, NbRows, 0, NbRows); int NbMaskedTT = 0; for (EcalTPGStripStatusMapIterator it = stripMap.begin(); it != stripMap.end(); ++it) if ((*it).second > 0) NbMaskedTT++; align->Fill(0.5, 0.5, stripMap.size()); align->Fill(1.5, 0.5, NbMaskedTT); } // if payload.get() else return false; gStyle->SetPalette(1); gStyle->SetOptStat(0); TCanvas canvas("CC map", "CC map", 1000, 1000); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); t1.SetTextSize(0.04); t1.SetTextColor(2); t1.DrawLatex(0.5, 0.96, Form("Endcap:Number of masked Trigger Strips, IOV %i", run)); TPad* pad = new TPad("pad", "pad", 0.0, 0.0, 1.0, 0.94); pad->Draw(); pad->cd(); align->Draw("TEXT"); drawTable(NbRows, NbColumns); align->GetXaxis()->SetTickLength(0.); align->GetXaxis()->SetLabelSize(0.); align->GetYaxis()->SetTickLength(0.); align->GetYaxis()->SetLabelSize(0.); std::string ImageName(m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; } // namespace // Register the classes as boost python plugin PAYLOAD_INSPECTOR_MODULE(EcalTPGStripStatus) { PAYLOAD_INSPECTOR_CLASS(EcalTPGStripStatusPlot); PAYLOAD_INSPECTOR_CLASS(EcalTPGStripStatusDiffOneTag); PAYLOAD_INSPECTOR_CLASS(EcalTPGStripStatusDiffTwoTags); PAYLOAD_INSPECTOR_CLASS(EcalTPGStripStatusSummaryPlot); } <|start_filename|>CondCore/EcalPlugins/plugins/EcalFloatCondObjectContainer_PayloadInspector.cc<|end_filename|> #include "CondCore/Utilities/interface/PayloadInspectorModule.h" #include "CondCore/Utilities/interface/PayloadInspector.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "CondCore/EcalPlugins/plugins/EcalDrawUtils.h" // the data format of the condition to be inspected #include "CondFormats/EcalObjects/interface/EcalCondObjectContainer.h" #include "TH2F.h" #include "TCanvas.h" #include "TStyle.h" #include "TLine.h" #include "TLatex.h" #include <string> namespace { enum { kEBChannels = 61200, kEEChannels = 14648, kSides = 2, kRMS = 5 }; enum { MIN_IETA = 1, MIN_IPHI = 1, MAX_IETA = 85, MAX_IPHI = 360 }; // barrel lower and upper bounds on eta and phi enum { IX_MIN = 1, IY_MIN = 1, IX_MAX = 100, IY_MAX = 100 }; // endcaps lower and upper bounds on x and y /***************************************************** 2d plot of ECAL FloatCondObjectContainer of 1 IOV *****************************************************/ class EcalFloatCondObjectContainerPlot : public cond::payloadInspector::PlotImage<EcalFloatCondObjectContainer> { public: EcalFloatCondObjectContainerPlot() : cond::payloadInspector::PlotImage<EcalFloatCondObjectContainer>("ECAL FloatCondObjectContainer - map ") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> >& iovs) override { TH2F* barrel = new TH2F("EB", "EB", MAX_IPHI, 0, MAX_IPHI, 2 * MAX_IETA, -MAX_IETA, MAX_IETA); TH2F* endc_p = new TH2F("EE+", "EE+", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); TH2F* endc_m = new TH2F("EE-", "EE-", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); double EBmean = 0., EBrms = 0., EEmean = 0., EErms = 0.; int EBtot = 0, EEtot = 0; auto iov = iovs.front(); std::shared_ptr<EcalFloatCondObjectContainer> payload = fetchPayload(std::get<1>(iov)); unsigned int run = std::get<0>(iov); if (payload.get()) { for (int ieta = -MAX_IETA; ieta <= MAX_IETA; ieta++) { Double_t eta = (Double_t)ieta; if (ieta == 0) continue; else if (ieta > 0.) eta = eta - 0.5; // 0.5 to 84.5 else eta = eta + 0.5; // -84.5 to -0.5 for (int iphi = 1; iphi <= MAX_IPHI; iphi++) { Double_t phi = (Double_t)iphi - 0.5; EBDetId id(ieta, iphi); double val = (*payload)[id.rawId()]; barrel->Fill(phi, eta, val); EBmean = EBmean + val; EBrms = EBrms + val * val; EBtot++; } } for (int sign = 0; sign < kSides; sign++) { int thesign = sign == 1 ? 1 : -1; for (int ix = 1; ix <= IX_MAX; ix++) { for (int iy = 1; iy <= IY_MAX; iy++) { if (!EEDetId::validDetId(ix, iy, thesign)) continue; EEDetId id(ix, iy, thesign); double val = (*payload)[id.rawId()]; EEmean = EEmean + val; EErms = EErms + val * val; EEtot++; if (thesign == 1) endc_p->Fill(ix, iy, val); else endc_m->Fill(ix, iy, val); } // iy } // ix } // side } // payload double vt = (double)EBtot; EBmean = EBmean / vt; EBrms = EBrms / vt - (EBmean * EBmean); EBrms = sqrt(EBrms); if (EBrms == 0.) EBrms = 0.001; double pEBmin = EBmean - kRMS * EBrms; double pEBmax = EBmean + kRMS * EBrms; // std::cout << " mean " << EBmean << " rms " << EBrms << " entries " << EBtot << " min " << pEBmin << " max " << pEBmax << std::endl; vt = (double)EEtot; EEmean = EEmean / vt; EErms = EErms / vt - (EEmean * EEmean); EErms = sqrt(EErms); if (EErms == 0.) EErms = 0.001; double pEEmin = EEmean - kRMS * EErms; double pEEmax = EEmean + kRMS * EErms; // std::cout << " mean " << EEmean << " rms " << EErms << " entries " << EEtot << " min " << pEEmin << " max " << pEEmax << std::endl; gStyle->SetPalette(1); gStyle->SetOptStat(0); TCanvas canvas("CC map", "CC map", 1600, 450); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("Ecal FloatCondObjectContainer, IOV %i", run)); float xmi[3] = {0.0, 0.24, 0.76}; float xma[3] = {0.24, 0.76, 1.00}; TPad** pad = new TPad*; for (int obj = 0; obj < 3; obj++) { pad[obj] = new TPad(Form("p_%i", obj), Form("p_%i", obj), xmi[obj], 0.0, xma[obj], 0.94); pad[obj]->Draw(); } pad[0]->cd(); DrawEE(endc_m, pEEmin, pEEmax); pad[1]->cd(); DrawEB(barrel, pEBmin, pEBmax); pad[2]->cd(); DrawEE(endc_p, pEEmin, pEEmax); std::string ImageName(m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; /************************************************************************ 2d plot of ECAL FloatCondObjectContainer difference between 2 IOVs ************************************************************************/ template <cond::payloadInspector::IOVMultiplicity nIOVs, int ntags> class EcalFloatCondObjectContainerDiffBase : public cond::payloadInspector::PlotImage<EcalFloatCondObjectContainer, nIOVs, ntags> { public: EcalFloatCondObjectContainerDiffBase() : cond::payloadInspector::PlotImage<EcalFloatCondObjectContainer, nIOVs, ntags>( "ECAL FloatCondObjectContainer difference") {} bool fill() override { TH2F* barrel = new TH2F("EB", "EB difference", MAX_IPHI, 0, MAX_IPHI, 2 * MAX_IETA, -MAX_IETA, MAX_IETA); TH2F* endc_p = new TH2F("EE+", "EE+ difference", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); TH2F* endc_m = new TH2F("EE-", "EE- difference", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); double EBmean = 0., EBrms = 0., EEmean = 0., EErms = 0.; int EBtot = 0, EEtot = 0; unsigned int run[2]; float vEB[kEBChannels], vEE[kEEChannels]; std::string l_tagname[2]; auto iovs = cond::payloadInspector::PlotBase::getTag<0>().iovs; l_tagname[0] = cond::payloadInspector::PlotBase::getTag<0>().name; auto firstiov = iovs.front(); run[0] = std::get<0>(firstiov); std::tuple<cond::Time_t, cond::Hash> lastiov; if (ntags == 2) { auto tag2iovs = cond::payloadInspector::PlotBase::getTag<1>().iovs; l_tagname[1] = cond::payloadInspector::PlotBase::getTag<1>().name; lastiov = tag2iovs.front(); } else { lastiov = iovs.back(); l_tagname[1] = l_tagname[0]; } run[1] = std::get<0>(lastiov); for (int irun = 0; irun < nIOVs; irun++) { std::shared_ptr<EcalFloatCondObjectContainer> payload; if (irun == 0) { payload = this->fetchPayload(std::get<1>(firstiov)); } else { payload = this->fetchPayload(std::get<1>(lastiov)); } if (payload.get()) { for (int ieta = -MAX_IETA; ieta <= MAX_IETA; ieta++) { Double_t eta = (Double_t)ieta; if (ieta == 0) continue; else if (ieta > 0.) eta = eta - 0.5; // 0.5 to 84.5 else eta = eta + 0.5; // -84.5 to -0.5 for (int iphi = 1; iphi <= MAX_IPHI; iphi++) { Double_t phi = (Double_t)iphi - 0.5; EBDetId id(ieta, iphi); int channel = id.hashedIndex(); double val = (*payload)[id.rawId()]; if (irun == 0) vEB[channel] = val; else { double diff = val - vEB[channel]; barrel->Fill(phi, eta, diff); EBmean = EBmean + diff; EBrms = EBrms + diff * diff; EBtot++; // std::cout << " entry " << EBtot << " mean " << EBmean << " rms " << EBrms << std::endl; } } } for (int sign = 0; sign < kSides; sign++) { int thesign = sign == 1 ? 1 : -1; for (int ix = 1; ix <= IX_MAX; ix++) { for (int iy = 1; iy <= IY_MAX; iy++) { if (!EEDetId::validDetId(ix, iy, thesign)) continue; EEDetId id(ix, iy, thesign); int channel = id.hashedIndex(); double val = (*payload)[id.rawId()]; if (irun == 0) vEE[channel] = val; else { double diff = val - vEE[channel]; EEmean = EEmean + diff; EErms = EErms + diff * diff; EEtot++; if (thesign == 1) endc_p->Fill(ix, iy, diff); else endc_m->Fill(ix, iy, diff); } } // iy } // ix } // side } // payload else return false; } // loop over IOVs double vt = (double)EBtot; EBmean = EBmean / vt; EBrms = EBrms / vt - (EBmean * EBmean); EBrms = sqrt(EBrms); if (EBrms == 0.) EBrms = 0.001; double pEBmin = EBmean - kRMS * EBrms; double pEBmax = EBmean + kRMS * EBrms; // std::cout << " mean " << EBmean << " rms " << EBrms << " entries " << EBtot << " min " << pEBmin << " max " << pEBmax << std::endl; vt = (double)EEtot; EEmean = EEmean / vt; EErms = EErms / vt - (EEmean * EEmean); EErms = sqrt(EErms); if (EErms == 0.) EErms = 0.001; double pEEmin = EEmean - kRMS * EErms; double pEEmax = EEmean + kRMS * EErms; // std::cout << " mean " << EEmean << " rms " << EErms << " entries " << EEtot << " min " << pEEmin << " max " << pEEmax << std::endl; gStyle->SetPalette(1); gStyle->SetOptStat(0); TCanvas canvas("CC map", "CC map", 1600, 450); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); int len = l_tagname[0].length() + l_tagname[1].length(); if (ntags == 2 && len < 150) { t1.SetTextSize(0.04); t1.DrawLatex( 0.5, 0.96, Form("%s IOV %i - %s IOV %i", l_tagname[1].c_str(), run[1], l_tagname[0].c_str(), run[0])); } else { t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("%s, IOV %i - %i", l_tagname[0].c_str(), run[1], run[0])); } float xmi[3] = {0.0, 0.24, 0.76}; float xma[3] = {0.24, 0.76, 1.00}; TPad** pad = new TPad*; for (int obj = 0; obj < 3; obj++) { pad[obj] = new TPad(Form("p_%i", obj), Form("p_%i", obj), xmi[obj], 0.0, xma[obj], 0.94); pad[obj]->Draw(); } pad[0]->cd(); DrawEE(endc_m, pEEmin, pEEmax); pad[1]->cd(); DrawEB(barrel, pEBmin, pEBmax); pad[2]->cd(); DrawEE(endc_p, pEEmin, pEEmax); std::string ImageName(this->m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; // class EcalFloatCondObjectContainerDiffBase using EcalFloatCondObjectContainerDiffOneTag = EcalFloatCondObjectContainerDiffBase<cond::payloadInspector::SINGLE_IOV, 1>; using EcalFloatCondObjectContainerDiffTwoTags = EcalFloatCondObjectContainerDiffBase<cond::payloadInspector::SINGLE_IOV, 2>; } // namespace // Register the classes as boost python plugin PAYLOAD_INSPECTOR_MODULE(EcalFloatCondObjectContainer) { PAYLOAD_INSPECTOR_CLASS(EcalFloatCondObjectContainerPlot); PAYLOAD_INSPECTOR_CLASS(EcalFloatCondObjectContainerDiffOneTag); PAYLOAD_INSPECTOR_CLASS(EcalFloatCondObjectContainerDiffTwoTags); } <|start_filename|>DetectorDescription/Core/src/Assembly.cc<|end_filename|> #include "DetectorDescription/Core/src/Assembly.h" #include "DetectorDescription/Core/interface/DDSolidShapes.h" #include "DetectorDescription/Core/src/Solid.h" DDI::Assembly::Assembly() : Solid(DDSolidShape::ddassembly) {} void DDI::Assembly::stream(std::ostream& os) const {} <|start_filename|>RecoPixelVertexing/PixelTriplets/src/CACut.h<|end_filename|> // -*- C++ -*- // // // // Package: RecoPixelVertexing/PixelTriplets // // Class: CACut // // // // Original Author: <NAME> // // Created: Wed, 14 Feb 2019 10:30:00 GMT // // #ifndef RecoPixelVertexing_PixelTriplets_src_CACut_h #define RecoPixelVertexing_PixelTriplets_src_CACut_h #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "CAGraph.h" class CACut { public: explicit CACut(const double defaultCut, const std::vector<edm::ParameterSet> &tripletCuts) : useCACuts_(true), foundAllLayerIds_(false), defaultCut_(defaultCut) { if (tripletCuts.size() == 1 && tripletCuts[0].getParameter<double>("cut") == -1.) { useCACuts_ = false; LogDebug("Configuration") << "No CACut VPSet. Using default cut value of " << defaultCut << " for all layer triplets"; return; } valuesByTripletNames_.reserve(tripletCuts.size()); valuesByLayerIds_.reserve(tripletCuts.size()); setCutValuesByTripletNames(tripletCuts); } void setCutValuesByTripletNames(const std::vector<edm::ParameterSet> &tripletCuts) { for (const auto &thisTriplet : tripletCuts) { valuesByTripletNames_.emplace_back(); auto &thisCACut = valuesByTripletNames_.back(); thisCACut.tripletName_ = thisTriplet.getParameter<std::string>("seedingLayers"); thisCACut.cutValue_ = thisTriplet.getParameter<double>("cut"); } } void setCutValuesByLayerIds(CAGraph &caLayers) { if (!useCACuts_ || foundAllLayerIds_) return; foundAllLayerIds_ = true; valuesByLayerIds_.clear(); for (const auto &thisTriplet : valuesByTripletNames_) { valuesByLayerIds_.emplace_back(); auto &thisCACut = valuesByLayerIds_.back(); // Triplet name, e.g. 'BPix1+BPix2+BPix3' std::string layersToSet = thisTriplet.tripletName_; for (int thisLayer = 0; thisLayer < 3; thisLayer++) { // Get layer name std::size_t layerPos = layersToSet.find('+'); if ((thisLayer < 2 && layerPos == std::string::npos) || (thisLayer == 2 && layerPos != std::string::npos)) { throw cms::Exception("Configuration") << "Please enter a valid triplet name in the CACuts parameter set; e.g. 'BPix1+BPix2+BPix3'"; } std::string layerName = layersToSet.substr(0, layerPos); layersToSet = layersToSet.substr(layerPos + 1); // Get layer ID thisCACut.layerIds_.emplace_back(caLayers.getLayerId(layerName)); if (thisCACut.layerIds_.back() == -1) { foundAllLayerIds_ = false; edm::LogWarning("Configuration") << "Layer name '" << layerName << "' not found in the CAGraph. Please check CACuts parameter set if this " "warning is present for all events"; } } // Cut thisCACut.cutValue_ = thisTriplet.cutValue_; thisCACut.hasValueByInnerLayerId_ = false; } setCutValuesByInnerLayerIds(); } void setCutValuesByInnerLayerIds() { for (auto &thisTriplet : valuesByLayerIds_) { if (thisTriplet.hasValueByInnerLayerId_) continue; auto it = std::find(thisTriplet.layerIds_.begin(), thisTriplet.layerIds_.end(), -1); if (it != thisTriplet.layerIds_.end()) continue; bool foundOuterDoublet = false; for (auto &thisOuterDoublet : valuesByInnerLayerIds_) { if (thisOuterDoublet.outerDoubletIds_[0] == thisTriplet.layerIds_[1] && thisOuterDoublet.outerDoubletIds_[1] == thisTriplet.layerIds_[2]) { thisOuterDoublet.innerLayerIds_.emplace_back(thisTriplet.layerIds_[0]); thisOuterDoublet.cutValues_.emplace_back(thisTriplet.cutValue_); foundOuterDoublet = true; break; } } if (!foundOuterDoublet) { valuesByInnerLayerIds_.emplace_back(defaultCut_); auto &newOuterDoublet = valuesByInnerLayerIds_.back(); newOuterDoublet.outerDoubletIds_.emplace_back(thisTriplet.layerIds_[1]); newOuterDoublet.outerDoubletIds_.emplace_back(thisTriplet.layerIds_[2]); newOuterDoublet.innerLayerIds_.emplace_back(thisTriplet.layerIds_[0]); newOuterDoublet.cutValues_.emplace_back(thisTriplet.cutValue_); } thisTriplet.hasValueByInnerLayerId_ = true; } } struct CAValuesByInnerLayerIds { explicit CAValuesByInnerLayerIds(float cut) : defaultCut_(cut) {} float at(int layerId) const { for (size_t thisLayer = 0; thisLayer < innerLayerIds_.size(); thisLayer++) { if (innerLayerIds_.at(thisLayer) == layerId) return cutValues_.at(thisLayer); } return defaultCut_; } std::vector<int> outerDoubletIds_; std::vector<int> innerLayerIds_; std::vector<float> cutValues_; private: double defaultCut_; }; CAValuesByInnerLayerIds getCutsByInnerLayer(int layerIds1, int layerIds2) const { for (const auto &thisCut : valuesByInnerLayerIds_) { if (thisCut.outerDoubletIds_[0] == layerIds1 && thisCut.outerDoubletIds_[1] == layerIds2) { return thisCut; } } CAValuesByInnerLayerIds emptyCutsByInnerLayer(defaultCut_); return emptyCutsByInnerLayer; } private: struct CAValueByTripletName { std::string tripletName_; float cutValue_; }; struct CAValueByLayerIds { std::vector<int> layerIds_; float cutValue_; bool hasValueByInnerLayerId_; }; private: std::vector<CAValueByTripletName> valuesByTripletNames_; std::vector<CAValueByLayerIds> valuesByLayerIds_; std::vector<CAValuesByInnerLayerIds> valuesByInnerLayerIds_; bool useCACuts_; bool foundAllLayerIds_; const float defaultCut_; }; #endif <|start_filename|>CondCore/EcalPlugins/plugins/EcalTPGCrystalStatus_PayloadInspector.cc<|end_filename|> #include "CondCore/Utilities/interface/PayloadInspectorModule.h" #include "CondCore/Utilities/interface/PayloadInspector.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "CondCore/EcalPlugins/plugins/EcalDrawUtils.h" #include "CondCore/EcalPlugins/plugins/EcalBadCrystalsCount.h" // the data format of the condition to be inspected #include "CondFormats/EcalObjects/interface/EcalTPGCrystalStatus.h" #include "TH2F.h" #include "TCanvas.h" #include "TStyle.h" #include "TLine.h" #include "TLatex.h" #include <string> namespace { enum { kEBChannels = 61200, kEEChannels = 14648, kSides = 2 }; enum { MIN_IETA = 1, MIN_IPHI = 1, MAX_IETA = 85, MAX_IPHI = 360 }; // barrel lower and upper bounds on eta and phi enum { IX_MIN = 1, IY_MIN = 1, IX_MAX = 100, IY_MAX = 100 }; // endcaps lower and upper bounds on x and y /*********************************************** 2d plot of ECAL TPGCrystalStatus of 1 IOV ************************************************/ class EcalTPGCrystalStatusPlot : public cond::payloadInspector::PlotImage<EcalTPGCrystalStatus> { public: EcalTPGCrystalStatusPlot() : cond::payloadInspector::PlotImage<EcalTPGCrystalStatus>("ECAL TPGCrystalStatus - map ") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> >& iovs) override { TH2F* barrel = new TH2F("EB", "EB TPG Crystal Status", MAX_IPHI, 0, MAX_IPHI, 2 * MAX_IETA, -MAX_IETA, MAX_IETA); TH2F* endc_p = new TH2F("EE+", "EE+ TPG Crystal Status", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); TH2F* endc_m = new TH2F("EE-", "EE- TPG Crystal Status", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); int EBstat = 0, EEstat[2] = {0, 0}; auto iov = iovs.front(); std::shared_ptr<EcalTPGCrystalStatus> payload = fetchPayload(std::get<1>(iov)); unsigned int run = std::get<0>(iov); if (payload.get()) { for (int ieta = -MAX_IETA; ieta <= MAX_IETA; ieta++) { Double_t eta = (Double_t)ieta; if (ieta == 0) continue; else if (ieta > 0.) eta = eta - 0.5; // 0.5 to 84.5 else eta = eta + 0.5; // -84.5 to -0.5 for (int iphi = 1; iphi <= MAX_IPHI; iphi++) { Double_t phi = (Double_t)iphi - 0.5; EBDetId id(ieta, iphi); double val = (*payload)[id.rawId()].getStatusCode(); barrel->Fill(phi, eta, val); if (val > 0) EBstat++; } } for (int sign = 0; sign < kSides; sign++) { int thesign = sign == 1 ? 1 : -1; for (int ix = 1; ix <= IX_MAX; ix++) { for (int iy = 1; iy <= IY_MAX; iy++) { if (!EEDetId::validDetId(ix, iy, thesign)) continue; EEDetId id(ix, iy, thesign); double val = (*payload)[id.rawId()].getStatusCode(); if (thesign == 1) { endc_p->Fill(ix, iy, val); if (val > 0) EEstat[1]++; } else { endc_m->Fill(ix, iy, val); if (val > 0) EEstat[0]++; } } // iy } // ix } // side } // payload gStyle->SetPalette(1); gStyle->SetOptStat(0); // TCanvas canvas("CC map","CC map", 1600, 450); Double_t w = 1200; Double_t h = 1400; TCanvas canvas("c", "c", w, h); canvas.SetWindowSize(w + (w - canvas.GetWw()), h + (h - canvas.GetWh())); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("Ecal TPGCrystalStatus, IOV %i", run)); // float xmi[3] = {0.0 , 0.24, 0.76}; // float xma[3] = {0.24, 0.76, 1.00}; float xmi[3] = {0.0, 0.0, 0.5}; float xma[3] = {1.0, 0.5, 1.0}; float ymi[3] = {0.47, 0.0, 0.0}; float yma[3] = {0.94, 0.47, 0.47}; TPad** pad = new TPad*; for (int obj = 0; obj < 3; obj++) { pad[obj] = new TPad(Form("p_%i", obj), Form("p_%i", obj), xmi[obj], ymi[obj], xma[obj], yma[obj]); pad[obj]->Draw(); } pad[0]->cd(); DrawEB(barrel, 0., 1.); t1.DrawLatex(0.2, 0.94, Form("%i crystals", EBstat)); pad[1]->cd(); DrawEE(endc_m, 0., 1.); t1.DrawLatex(0.15, 0.92, Form("%i crystals", EEstat[0])); pad[2]->cd(); DrawEE(endc_p, 0., 1.); t1.DrawLatex(0.15, 0.92, Form("%i crystals", EEstat[1])); std::string ImageName(m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; /************************************************************************ 2d plot of ECAL TPGCrystalStatus difference between 2 IOVs ************************************************************************/ template <cond::payloadInspector::IOVMultiplicity nIOVs, int ntags> class EcalTPGCrystalStatusDiffBase : public cond::payloadInspector::PlotImage<EcalTPGCrystalStatus, nIOVs, ntags> { public: EcalTPGCrystalStatusDiffBase() : cond::payloadInspector::PlotImage<EcalTPGCrystalStatus, nIOVs, ntags>("ECAL TPGCrystalStatus difference") {} bool fill() override { TH2F* barrel = new TH2F("EB", "EB difference", MAX_IPHI, 0, MAX_IPHI, 2 * MAX_IETA, -MAX_IETA, MAX_IETA); TH2F* endc_p = new TH2F("EE+", "EE+ difference", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); TH2F* endc_m = new TH2F("EE-", "EE- difference", IX_MAX, IX_MIN, IX_MAX + 1, IY_MAX, IY_MIN, IY_MAX + 1); int EBstat = 0, EEstat[2] = {0, 0}; unsigned int run[2] = {0, 0}; float vEB[kEBChannels], vEE[kEEChannels]; std::string l_tagname[2]; auto iovs = cond::payloadInspector::PlotBase::getTag<0>().iovs; l_tagname[0] = cond::payloadInspector::PlotBase::getTag<0>().name; auto firstiov = iovs.front(); run[0] = std::get<0>(firstiov); std::tuple<cond::Time_t, cond::Hash> lastiov; if (ntags == 2) { auto tag2iovs = cond::payloadInspector::PlotBase::getTag<1>().iovs; l_tagname[1] = cond::payloadInspector::PlotBase::getTag<1>().name; lastiov = tag2iovs.front(); } else { lastiov = iovs.back(); l_tagname[1] = l_tagname[0]; } run[1] = std::get<0>(lastiov); for (int irun = 0; irun < nIOVs; irun++) { std::shared_ptr<EcalTPGCrystalStatus> payload; if (irun == 0) { payload = this->fetchPayload(std::get<1>(firstiov)); } else { payload = this->fetchPayload(std::get<1>(lastiov)); } if (payload.get()) { for (int ieta = -MAX_IETA; ieta <= MAX_IETA; ieta++) { Double_t eta = (Double_t)ieta; if (ieta == 0) continue; else if (ieta > 0.) eta = eta - 0.5; // 0.5 to 84.5 else eta = eta + 0.5; // -84.5 to -0.5 for (int iphi = 1; iphi <= MAX_IPHI; iphi++) { Double_t phi = (Double_t)iphi - 0.5; EBDetId id(ieta, iphi); int channel = id.hashedIndex(); double val = (*payload)[id.rawId()].getStatusCode(); if (irun == 0) vEB[channel] = val; else { double diff = val - vEB[channel]; barrel->Fill(phi, eta, diff); if (diff != 0) EBstat++; // std::cout << " entry " << EBtot << " mean " << EBmean << " rms " << EBrms << std::endl; } } } for (int sign = 0; sign < kSides; sign++) { int thesign = sign == 1 ? 1 : -1; for (int ix = 1; ix <= IX_MAX; ix++) { for (int iy = 1; iy <= IY_MAX; iy++) { if (!EEDetId::validDetId(ix, iy, thesign)) continue; EEDetId id(ix, iy, thesign); int channel = id.hashedIndex(); double val = (*payload)[id.rawId()].getStatusCode(); if (irun == 0) vEE[channel] = val; else { double diff = val - vEE[channel]; if (thesign == 1) { endc_p->Fill(ix, iy, diff); if (diff != 0) EEstat[1]++; } else { endc_m->Fill(ix, iy, diff); if (diff != 0) EEstat[0]++; } } } // iy } // ix } // side } // payload else return false; } // loop over IOVs gStyle->SetPalette(1); gStyle->SetOptStat(0); Double_t w = 1200; Double_t h = 1400; TCanvas canvas("c", "c", w, h); canvas.SetWindowSize(w + (w - canvas.GetWw()), h + (h - canvas.GetWh())); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); int len = l_tagname[0].length() + l_tagname[1].length(); if (ntags == 2) { if (len < 80) { t1.SetTextSize(0.03); t1.DrawLatex(0.5, 0.96, Form("%s %i - %s %i", l_tagname[1].c_str(), run[1], l_tagname[0].c_str(), run[0])); } else { t1.SetTextSize(0.05); t1.DrawLatex(0.5, 0.96, Form("Ecal TPGCrystalStatus, IOV %i - %i", run[1], run[0])); } } else { t1.SetTextSize(0.03); t1.DrawLatex(0.5, 0.96, Form("%s, IOV %i - %i", l_tagname[0].c_str(), run[1], run[0])); } // float xmi[3] = {0.0 , 0.24, 0.76}; // float xma[3] = {0.24, 0.76, 1.00}; float xmi[3] = {0.0, 0.0, 0.5}; float xma[3] = {1.0, 0.5, 1.0}; float ymi[3] = {0.47, 0.0, 0.0}; float yma[3] = {0.94, 0.47, 0.47}; std::vector<TPad*> pad; for (int obj = 0; obj < 3; obj++) { pad.push_back(new TPad(Form("p_%i", obj), Form("p_%i", obj), xmi[obj], ymi[obj], xma[obj], yma[obj])); pad[obj]->Draw(); } pad[0]->cd(); DrawEB(barrel, -1., 1.); t1.DrawLatex(0.2, 0.94, Form("%i differences", EBstat)); pad[1]->cd(); DrawEE(endc_m, -1., 1.); t1.DrawLatex(0.15, 0.92, Form("%i differences", EEstat[0])); pad[2]->cd(); DrawEE(endc_p, -1., 1.); t1.DrawLatex(0.15, 0.92, Form("%i differences", EEstat[1])); std::string ImageName(this->m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; // class EcalTPGCrystalStatusDiffBase using EcalTPGCrystalStatusDiffOneTag = EcalTPGCrystalStatusDiffBase<cond::payloadInspector::SINGLE_IOV, 1>; using EcalTPGCrystalStatusDiffTwoTags = EcalTPGCrystalStatusDiffBase<cond::payloadInspector::SINGLE_IOV, 2>; /********************************************************* 2d plot of EcalTPGCrystalStatus Error Summary of 1 IOV *********************************************************/ class EcalTPGCrystalStatusSummaryPlot : public cond::payloadInspector::PlotImage<EcalTPGCrystalStatus> { public: EcalTPGCrystalStatusSummaryPlot() : cond::payloadInspector::PlotImage<EcalTPGCrystalStatus>("Ecal TPGCrystal Status Error Summary - map ") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> >& iovs) override { auto iov = iovs.front(); //get reference to 1st element in the vector iovs std::shared_ptr<EcalTPGCrystalStatus> payload = fetchPayload(std::get<1>(iov)); //std::get<1>(iov) refers to the Hash in the tuple iov unsigned int run = std::get<0>(iov); //referes to Time_t in iov. TH2F* align; //pointer to align which is a 2D histogram int NbRows = 3; int NbColumns = 3; if (payload.get()) { //payload is an iov retrieved from payload using hash. align = new TH2F("Ecal TPGCrystal Status Error Summary", "EB/EE-/EE+ ErrorCount Total Number", NbColumns, 0, NbColumns, NbRows, 0, NbRows); long unsigned int ebErrorCount = 0; long unsigned int ee1ErrorCount = 0; long unsigned int ee2ErrorCount = 0; long unsigned int ebTotal = (payload->barrelItems()).size(); long unsigned int ee1Total = 0; long unsigned int ee2Total = 0; getBarrelErrorSummary<EcalTPGCrystalStatusCode>(payload->barrelItems(), ebErrorCount); getEndCapErrorSummary<EcalTPGCrystalStatusCode>( payload->endcapItems(), ee1ErrorCount, ee2ErrorCount, ee1Total, ee2Total); double row = NbRows - 0.5; //EB summary values align->Fill(0.5, row, 1); align->Fill(1.5, row, ebErrorCount); align->Fill(2.5, row, ebTotal); row--; //EE- summary values align->Fill(0.5, row, 2); align->Fill(1.5, row, ee1ErrorCount); align->Fill(2.5, row, ee1Total); row--; //EE+ summary values align->Fill(0.5, row, 3); align->Fill(1.5, row, ee2ErrorCount); align->Fill(2.5, row, ee2Total); } // if payload.get() else return false; gStyle->SetPalette(1); gStyle->SetOptStat(0); TCanvas canvas("CC map", "CC map", 1000, 1000); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); t1.SetTextSize(0.04); t1.SetTextColor(2); t1.DrawLatex(0.5, 0.96, Form("EcalTPGCrystalStatus Error Summary, IOV %i", run)); TPad* pad = new TPad("pad", "pad", 0.0, 0.0, 1.0, 0.94); pad->Draw(); pad->cd(); align->Draw("TEXT"); drawTable(NbRows, NbColumns); align->GetXaxis()->SetTickLength(0.); align->GetXaxis()->SetLabelSize(0.); align->GetYaxis()->SetTickLength(0.); align->GetYaxis()->SetLabelSize(0.); std::string ImageName(m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } // fill method }; } // namespace // Register the classes as boost python plugin PAYLOAD_INSPECTOR_MODULE(EcalTPGCrystalStatus) { PAYLOAD_INSPECTOR_CLASS(EcalTPGCrystalStatusPlot); PAYLOAD_INSPECTOR_CLASS(EcalTPGCrystalStatusDiffOneTag); PAYLOAD_INSPECTOR_CLASS(EcalTPGCrystalStatusDiffTwoTags); PAYLOAD_INSPECTOR_CLASS(EcalTPGCrystalStatusSummaryPlot); }
soumyadipbarman/cmssw
<|start_filename|>app/backend/ServerRequester.js<|end_filename|> "use strict"; const http = require('http'); const host = 'cromberg.blweb.ru'; function ServerRequester() { } ServerRequester.prototype.notify = function (oldSettings, newSettings) { let requestData = null; let doRequest = false; if (newSettings.remind === true && oldSettings.remind === false) { requestData = { action: 'add', email: newSettings.email, language: newSettings.language, }; doRequest = true; } else if (newSettings.remind === false && oldSettings.remind === true) { // todo: if we disable notifications and change email, we send only delete request requestData = { action: 'delete', email: oldSettings.email, language: newSettings.language, }; doRequest = true; } else if (oldSettings.email && (oldSettings.email !== newSettings.email || oldSettings.language !== newSettings.language)) { requestData = { action: 'update', email: newSettings.email, oldEmail: oldSettings.email, language: newSettings.language, }; doRequest = true; } if (!doRequest) { return; } requestData = 'data=' + encodeURIComponent(JSON.stringify(requestData)); // todo: if error, try later request('POST', '/email', {'Content-Type': 'application/x-www-form-urlencoded'}, requestData); }; ServerRequester.prototype.getServerVersion = function (callback) { request('GET', '/version', null, null, function (response) { if (response.statusCode !== 200) { return; } response.on('data', function (data) { const versionData = JSON.parse(data); if (versionData.data == undefined) { return; } callback(versionData.data); }); }); }; function request(method, path, headers, requestData, callback) { let req = http.request({ method: method, host: host, path: path, headers: headers }, function (response) { if (callback) { callback(response); } }); req.on('error', function (error) { }); if (requestData !== null) { req.write(requestData); } req.end(); } module.exports = ServerRequester; <|start_filename|>app/scripts/renderer.js<|end_filename|> const ipcRenderer = require('electron').ipcRenderer; const shell = require('electron').shell; const moment = require('moment'); const settingsView = require('../view/SettingsView'); const balanceView = require('../view/BalanceView'); const incomeView = require('../view/IncomeView'); const languages = require('../scripts/languages'); const renderFunctions = require('../scripts/renderFunctions'); let resizeTimeout; window.onclick = clicksHandler; window.onresize = resizeThrottler; if (typeof google === 'undefined') { alert(languages.getText('no-internet')); throw new Error('no internet'); } google.charts.load('45', {packages: ['corechart']}); ipcRenderer.on('error', function (event, data) { alert(data); }); ipcRenderer.on('new-version', function (event, oldVersion, newVersion) { alert(languages.getTextWithPlaceholders('new-version', [oldVersion, newVersion])); }); ipcRenderer.on('income-data', function (event, data) { incomeView.setData(data); balanceView.setIncomeData(data); }); ipcRenderer.on('income-data-inserted', function (event, incomeItem) { incomeView.insertIncome(incomeItem); }); ipcRenderer.on('income-data-deleted', function (event, incomeId) { incomeView.deleteIncome(incomeId); }); ipcRenderer.on('income-edited', function (event, income) { incomeView.updateIncome(income); }); ipcRenderer.on('balance-inserted', function (event, source) { balanceView.addBalanceSource(source); }); ipcRenderer.on('balance-updated', function (event, id, month, sum) { balanceView.addBalance(id, month, sum); }); ipcRenderer.on('balance-reupdated', function (event, id, month) { balanceView.deleteBalance(id, month); }); ipcRenderer.on('balance-types', function (event, types) { balanceView.setBalance(types); }); ipcRenderer.on('settings-saved', function (event, data) { settingsView.updateData(data); }); ipcRenderer.on('settings', function (event, data) { languages.setLanguage(data.language); settingsView.setData(data); init(); }); function init() { document.documentElement.innerHTML = languages.replacePlaceholders(document.documentElement.innerHTML); $('.js-tab').click(function () { renderFunctions.makeActive($(this).data('name'), incomeView, balanceView); }); renderFunctions.makeActive('income', incomeView, balanceView); incomeView.preparePage((incomeItem) => { ipcRenderer.send('income-add', incomeItem); }); balanceView.preparePage( (source) => { ipcRenderer.send('balance-add', source); }, (id, month, value) => { ipcRenderer.send('balance-update', id, month, value); }, (id, month) => { ipcRenderer.send('balance-month-remove', id, month); }, (id, newName) => { ipcRenderer.send('rename-balance-source', id, newName); } ); settingsView.preparePage((settings) => { ipcRenderer.send('update-settings', settings); }); } function clicksHandler(e) { if (e.target.classList.contains('js-income-edit')) { incomeView.editClickHandler(e); return; } if (e.target.classList.contains('js-income-save')) { ipcRenderer.send('income-edit', incomeView.saveClickHandler(e)); return; } if (e.target.classList.contains('js-income-delete')) { const row = event.target.closest('.js-income-row'); const id = row.dataset.id.toString(); ipcRenderer.send('income-delete', id); } if (e.target.tagName == 'A') { renderFunctions.onLinkClick(e, shell); } } function resizeThrottler() { if (!resizeTimeout) { resizeTimeout = setTimeout(function () { resizeTimeout = null; renderFunctions.actualResizeHandler(incomeView, balanceView); }, 250); } } <|start_filename|>server/www/resources/template/page-stats.html<|end_filename|> <h1>Статистика</h1> <h2>Запуски приложения по дням</h2> <div class="js-stats-launch-by-day stats-launch"></div> <h2>Запуски приложения по месяцам</h2> <div class="js-stats-launch-by-month stats-launch"></div> <div class="hidden js-data-day"> [[data-day]] </div> <div class="hidden js-data-month"> [[data-month]] </div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type='text/javascript' src='/resources/js/stats.js'></script> <|start_filename|>server/www/resources/js/stats.js<|end_filename|> google.charts.load('current', {packages: ['annotatedtimeline']}); document.addEventListener("DOMContentLoaded", function () { let data_day = document.getElementsByClassName("js-data-day")[0].textContent; data_day = JSON.parse(data_day); let chart_element_day = document.getElementsByClassName("js-stats-launch-by-day")[0]; draw(data_day, chart_element_day); let data_month = document.getElementsByClassName("js-data-month")[0].textContent; data_month = JSON.parse(data_month); let chart_element_month = document.getElementsByClassName("js-stats-launch-by-month")[0]; draw(data_month, chart_element_month); }); function draw(data, chart_element) { google.charts.setOnLoadCallback(drawLaunchStats); function drawLaunchStats() { let dataForTable = data.map(function (element) { return [new Date(element[0]), parseInt(element[1]), parseInt(element[2])]; }); let labels = [['Count', 'Launches', 'Uniques launches by ip']]; let test = labels.concat(dataForTable); let dataTable = google.visualization.arrayToDataTable(test); let options = { displayAnnotations: true }; let chart = new google.visualization.AnnotatedTimeLine(chart_element); chart.draw(dataTable, options); } } <|start_filename|>server/www/resources/style.css<|end_filename|> * { margin: 0; padding: 0; font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6 } body { background-color: #f1f1f1; } .wrapper { background-color: #ffffff; padding: 20px 20px; width: 1000px; margin: 0 auto; } .wrapper:after { content: ''; display: block; clear: both; } h1 { margin: 20px 0; font-size: 150%; } h2 { margin: 15px 0; font-size: 120%; } p { margin: 10px 0; } .logo { float: left; margin: 0 20px 0 0; } .screenshots { text-align: center; } .screenshots a { display: inline-block; margin: 0 20px; vertical-align: middle; } .screenshots img { width: 450px; } .clear { clear: both; } .hidden { display: none; } .stats-launch { width:100%; height: 500px; } <|start_filename|>app/backend/Dao.js<|end_filename|> const Database = require('../backend/Database').Database; const Settings = require('../models/settings'); let Tables = { INCOME: 'income', SETTINGS: 'settings', BALANCE: 'balance' }; function Dao(path) { this.database = new Database(path); } Dao.prototype.getDatabasePath = function () { return this.database.filename; }; // Incomes Dao.prototype.getIncomes = function (callback) { this.database.getByType(Tables.INCOME, callback); }; Dao.prototype.insertIncome = function (income, callback) { this.database.insert(income, Tables.INCOME, callback); }; Dao.prototype.updateIncome = function (income, callback) { this.database.updateFullData(income.id, Tables.INCOME, income, callback); }; Dao.prototype.deleteIncome = function (incomeId, callback) { this.database.delete(Tables.INCOME, incomeId, callback); }; //Balance Dao.prototype.getBalances = function (callback) { this.database.getByType(Tables.BALANCE, callback); }; Dao.prototype.addBalanceSource = function (source, callback) { this.database.insert(source, Tables.BALANCE, callback); }; Dao.prototype.addBalance = function (id, month, sum, callback) { let key = 'data.value.' + month; this.database.addProperty({'_id': id, 'type': Tables.BALANCE}, key, sum, callback); }; Dao.prototype.deleteBalance = function (id, month, callback) { let key = 'data.value.' + month; this.database.deleteProperty({'_id': id, 'type': Tables.BALANCE}, key, callback); }; Dao.prototype.renameBalance = function (id, newName) { this.database.update( {type: Tables.BALANCE, _id: id}, {$set: {"data.name": newName}} ); }; // Settings Dao.prototype.getSettings = function (callback) { this.database.getByType(Tables.SETTINGS, (data) => { if (data.length > 1) { throw new Error("Settings error"); } if (data.length === 0) { callback(new Settings(false, '')); // default settings return; } callback(data[0]); }); }; Dao.prototype.updateSettings = function (settings, callback) { this.database.deleteAll(Tables.SETTINGS); this.database.insert(settings, Tables.SETTINGS, callback); }; // Other Dao.prototype.drop = function () { this.database.drop(); }; module.exports = Dao; <|start_filename|>app/scripts/renderFunctions.js<|end_filename|> function onLinkClick(e, shell) { if (e.target.getAttribute('href') !== null) { e.preventDefault(); shell.openExternal(e.target.getAttribute('href')); } } function reloadGraph(tabName, incomeView, balanceView) { switch (tabName) { case 'income': incomeView.reloadGraph(); break; case 'balance': balanceView.reloadGraph(); break; default: alert('Unknown tab name: ' + name); } } function makeActive(tabName, incomeView, balanceView) { $('.js-page').removeClass('active'); $('.js-tab').removeClass('active'); $('.js-tab[data-name=' + tabName + ']').addClass('active'); $('.js-page[data-name="' + tabName + '"]').addClass('active'); reloadGraph(tabName, incomeView, balanceView); } function actualResizeHandler(incomeView, balanceView) { let name = $('.js-tab.active').data('name'); reloadGraph(name, incomeView, balanceView); } module.exports = {onLinkClick, makeActive, actualResizeHandler}; <|start_filename|>app/view/SettingsView.js<|end_filename|> "use strict"; const functions = require('../scripts/functions'); const Settings = require('../models/settings'); function SettingsView() { this.data = {}; } SettingsView.prototype.setData = function (data) { this.data = data; }; SettingsView.prototype.updateData = function (data) { this.data = data; updateData(this.data); $('.js-settings-response').text("ok"); }; SettingsView.prototype.preparePage = function(sendSettingsFunction) { updateData(this.data); $('.settings-close-button').click(() => { toggleSettingsWindow(); }); $(".js-settings-button").click(() => { toggleSettingsWindow(); }); $('.js-settings-backup').change(function (e) { let path = e.target.files[0].path; $('.js-settings-backup-text').val(path); }); $('.js-settings-database').change(function (e) { let path = e.target.files[0].path; $('.js-settings-database-text').val(path); }); $(".js-settings-form").on('submit', function (e) { e.preventDefault(); let response = $('.js-settings-response'); let remindFlag = $('.js-settings-remind').is(":checked"); let remindEmail = $('.js-settings-email').val(); let databaseFolder = $('.js-settings-database-text').val(); let backupFolder = $('.js-settings-backup-text').val(); let language = $('.js-settings-language').val(); if (remindFlag === true && remindEmail.length === 0) { response.text("Empty email"); response.addClass("error"); return; } let settings = new Settings(remindFlag, remindEmail, databaseFolder, backupFolder, language); sendSettingsFunction(settings); response.removeClass("error"); response.text(""); }); }; function updateData(data) { $('.js-settings-remind').prop("checked", data.remind); $('.js-settings-email').val(data.email); $('.js-settings-backup-text').val(data.backupFolder); $('.js-settings-database-text').val(data.databaseFolder); $('.js-settings-language').val(data.language); } function toggleSettingsWindow() { $(".js-settings-button").toggleClass("active"); $(".js-settings-window").toggleClass("active"); } module.exports = new SettingsView(); <|start_filename|>app/backend/Backup.js<|end_filename|> const fs = require('fs'); const moment = require('moment'); const path = require('path'); function Backup(databasePath, folder) { this.folder = folder; this.databasePath = databasePath; } Backup.prototype.makeBackup = function (lastBackupTimestamp) { if (!this.folder) { console.log('cant find a folder for backup'); return undefined; } let currentDayTimestamp = moment().startOf('day').unix(); if (currentDayTimestamp === lastBackupTimestamp) { console.log('backup already was made today'); return undefined; } fs.createReadStream(this.databasePath).pipe(fs.createWriteStream(this.folder + generateBackupName())); return currentDayTimestamp; }; function generateBackupName() { return path.sep + 'database_' + moment().format('YYYY-MM-DD hh-mm') + '.db'; } module.exports = Backup; <|start_filename|>app/view/BalanceView.js<|end_filename|> 'use strict'; const functions = require('../scripts/functions'); const moment = require('moment'); let balanceView = null; const languages = require('../scripts/languages'); function BalanceView() { this.data = {}; this.dataByMonth = []; this.addBalanceFunction = undefined; this.removeBalanceFunction = undefined; this.incomeByMonth = {}; balanceView = this; return this; } BalanceView.prototype.addBalanceSource = function (source) { this.data[source.id] = { 'name': source.name, 'value': source.value, }; this.addBalanceSourceToDOM(source.id, source.name, []); }; BalanceView.prototype.addBalance = function (id, month, sum) { if (typeof this.data[id] === 'undefined') { this.data[id] = {'value': []}; } if (isMonthInDOM(id, month)) { this.updateSumDOM(id, month, sum); } else { this.addMonthDOM(id, month, sum); } this.data[id]['value'][month] = sum; this.dataByMonth = convertData(this.data); this.reloadGraph(); }; BalanceView.prototype.deleteBalance = function (id, month) { if (typeof this.data[id] === 'undefined') { throw new Error('this id does not exist'); } this.data[id]['value'][month] = 0; this.updateSumDOM(id, month, 0); this.dataByMonth = convertData(this.data); this.reloadGraph(); }; BalanceView.prototype.addBalanceSourceToDOM = function (sourceId, sourceName, dataByMonth) { let section = document.createElement('SECTION'); section.className = 'balance-source'; let h2 = document.createElement('H2'); let form = document.createElement('FORM'); let monthInput = document.createElement('INPUT'); let sumInput = document.createElement('INPUT'); let submit = document.createElement('BUTTON'); h2.dataset.id = sourceId; h2.className = 'balance-source-name js-balance-source-name'; fillSourceName(sourceId, h2, sourceName); section.appendChild(h2); form.className = 'addBalance'; form.dataset.id = sourceId; form.onsubmit = (e) => { onBalanceSubmit(e, this.addBalanceFunction); }; monthInput.type = 'month'; monthInput.name = 'month'; monthInput.required = 'required'; monthInput.className = 'js-balance-form-month month'; monthInput.min = '1900-01'; monthInput.max = '2100-01'; monthInput.value = moment().format('YYYY-MM'); form.appendChild(monthInput); sumInput.type = 'number'; sumInput.name = 'balanceValue'; sumInput.placeholder = 'Enter balance'; sumInput.required = 'required'; sumInput.className = 'js-balance-form-sum sum'; form.appendChild(sumInput); submit.type = 'submit'; submit.textContent = '+'; form.appendChild(submit); section.appendChild(form); document.querySelector('.balance-items').appendChild(section); dataByMonth.forEach((month) => { this.addMonthDOM(sourceId, month.month.format('MMYYYY'), month.sum); }); }; BalanceView.prototype.addMonthDOM = function (id, month, sum) { let form = document.querySelector('form[data-id="' + id + '"'); let section = form.parentNode; let p = document.createElement('P'); p.className = 'balance-item'; let monthTag = document.createElement('span'); monthTag.className = 'month'; monthTag.textContent = moment(month, "MMYYYY").format("MMM YYYY") + ':'; let sumTag = document.createElement('span'); sumTag.className = ' sum'; sumTag.textContent = functions.numberWithSpaces(sum); p.dataset.month = month; p.appendChild(monthTag); let deleteIcon = document.createElement('span'); deleteIcon.className = 'delete-month-balance'; deleteIcon.onclick = (e) => { onDeleteClick(e, this.removeBalanceFunction); }; p.appendChild(deleteIcon); p.appendChild(sumTag); section.insertBefore(p, form); }; BalanceView.prototype.updateSumDOM = function (id, month, sum) { let block = document.querySelector('h2[data-id="' + id + '"').parentNode; block.querySelector('p[data-month="' + month + '"] span.sum').textContent = functions.numberWithSpaces(sum); }; BalanceView.prototype.setBalance = function (balanceSources) { balanceSources.forEach(balanceSource => { this.data[balanceSource.id] = { name: balanceSource.name, value: balanceSource.value }; }); this.dataByMonth = convertData(this.data); let sourceIndex = 0; balanceSources.forEach(balanceSource => { let dataByMonthForCurrentSource = []; this.dataByMonth.forEach(month => { dataByMonthForCurrentSource.push( { month: month.month, sum: month.value[sourceIndex] } ); }); this.addBalanceSourceToDOM(balanceSource.id, balanceSource.name, dataByMonthForCurrentSource); sourceIndex++; }); }; BalanceView.prototype.reloadGraph = function () { let chartData = prepareDataForBalanceChart(this.data, this.dataByMonth); drawChart(chartData, 'js-balance-chart', {legend: {position: 'top'}}); let chartDiffData = prepareDataForBalanceDiffChart(this.dataByMonth); drawChart(chartDiffData, 'js-balance-diff-chart'); let costsChartData = prepareDataForCostsChart(this.dataByMonth, this.incomeByMonth); drawChart(costsChartData, 'js-costs-chart'); let [pieData, lastMonth] = prepareDataForPieChart(this.data, this.dataByMonth); drawPieChart(pieData, lastMonth, 'js-balance-pie-chart'); let lastMonthSum = pieData.reduce(function f(a, b) { return a + b[1]; }, 0); document.getElementsByClassName('js-balance-sum')[0].innerHTML = functions.numberWithSpaces(lastMonthSum); }; BalanceView.prototype.preparePage = function (addBalanceSourceFunction, addBalanceFunction, removeBalanceFunction, renameBalanceSourceFunction) { $('.js-balance-source-form').on('submit', (e) => { e.preventDefault(); const source = { name: document.getElementById('balancesource').value, value: {}, }; addBalanceSourceFunction(source); }); this.addBalanceFunction = addBalanceFunction; this.removeBalanceFunction = removeBalanceFunction; this.renameBalanceSourceFunction = renameBalanceSourceFunction; }; BalanceView.prototype.setIncomeData = function (data) { let incomeByMonth = []; data.forEach((value) => { let monthStr = moment.unix(value.date).format("YYYY-MM"); if (!incomeByMonth.hasOwnProperty(monthStr)) { incomeByMonth[monthStr] = value.sum; } else { incomeByMonth[monthStr] += value.sum; } }); this.incomeByMonth = incomeByMonth; }; function onBalanceSubmit(e, addBalanceFunction) { e.preventDefault(); let id = e.target.dataset.id; let month = moment(e.target.querySelector('.js-balance-form-month').value).format("MMYYYY"); let value = parseFloat(e.target.querySelector('.js-balance-form-sum').value); if (addBalanceFunction === undefined) { alert("error"); return; } addBalanceFunction(id, month, value); } function onDeleteClick(e, removeBalanceFunction) { e.preventDefault(); let element = e.target.parentNode.parentNode.getElementsByTagName('h2')[0]; let id = element.dataset.id; let month = e.target.parentNode.dataset.month; if (removeBalanceFunction === undefined) { alert("error"); return; } removeBalanceFunction(id, month); } function drawChart(chartData, chartId, options = {}) { google.charts.setOnLoadCallback(chart); let chart_options = { width: '100%', height: 400, legend: options.legend ? options.legend : 'none', bar: {groupWidth: '75%'}, isStacked: true, vAxis: { minValue: 0 } }; function chart() { let data = google.visualization.arrayToDataTable(chartData); let view = new google.visualization.DataView(data); let chart = new google.visualization.ColumnChart(document.getElementById(chartId)); chart.draw(view, chart_options); } } function drawPieChart(pieData, lastMonth, chartId) { google.charts.setOnLoadCallback(chart); function chart() { let data = google.visualization.arrayToDataTable([['','']].concat(pieData)); let options = { width: '100%', height: 350, title: languages.getTextWithPlaceholders('balance-pie-chart-title', [lastMonth.format('MMM YYYY')]), pieSliceText: 'label', }; let chart = new google.visualization.PieChart(document.getElementById(chartId)); chart.draw(data, options); } } function prepareDataForCostsChart(balanceByMonth, incomeByMonth) { let prevBalance = undefined; let costsData = [ [languages.getText('month'), languages.getText('cost')] ]; for (let i = 0; i < balanceByMonth.length; i++) { let currentMonth = balanceByMonth[i]; let currentBalance = currentMonth.value.reduce(function (total, val) { return total + val; }); let monthStr = currentMonth.month.format('YYYY-MM'); let currentIncome = incomeByMonth.hasOwnProperty(monthStr) ? incomeByMonth[monthStr] : 0; let currentCosts = prevBalance != undefined ? currentIncome - (currentBalance - prevBalance) : 0; costsData.push( [currentMonth.month.format('MMM YYYY'), currentCosts] ); prevBalance = currentBalance; } costsData.push( [moment().format('MMM YYYY'), 0] ); return costsData; } function prepareDataForBalanceChart(balanceData, dataByMonth) { let chartPartNames = ['month']; for (let source in balanceData) { if (!balanceData.hasOwnProperty(source)) { continue; } chartPartNames.push(balanceData[source].name); } chartPartNames.push({role: 'annotation'}); let dataChart = []; dataByMonth.forEach((month) => { let chartMonthData = [month.month.format('MMM YYYY')]; chartMonthData = chartMonthData.concat(month.value); chartMonthData.push(''); dataChart.push(chartMonthData); }); return [chartPartNames].concat(dataChart); } function prepareDataForBalanceDiffChart(dataByMonth) { let chartPartNames = ['month', 'diff']; let chartData = []; let prevMonthSum = undefined; for (let i = 0; i < dataByMonth.length; i++) { let currentMonthSum = dataByMonth[i].value.reduce((x, y) => x + y); let diff = 0; if (prevMonthSum !== undefined) { diff = currentMonthSum - prevMonthSum; } let monthName = dataByMonth[i].month.format('MMM YYYY'); chartData.push([monthName, diff]); prevMonthSum = currentMonthSum; } return [chartPartNames].concat(chartData); } function prepareDataForPieChart(balanceData, dataByMonth) { let lastAddedMonth = null; for (let i = dataByMonth.length - 1; i >= 0; i--) { let monthData = dataByMonth[i]; let isNotEmpty = true; isNotEmpty = monthData['value'].some(function (balance) { return balance != 0; }); if (isNotEmpty) { lastAddedMonth = monthData; break; } } let data = []; let index = 0; for (let source in balanceData) { if (!balanceData.hasOwnProperty(source)) { continue; } data.push([balanceData[source].name, lastAddedMonth['value'][index]]); index++; } return [data, lastAddedMonth.month]; } function convertData(balanceSources) { // todo: refactor this, to another return format: array of (month(string), values) instead of array(month(object), values) let firstMonth = moment().startOf('month'); let lastMonth = moment().startOf('month'); let currentMonth = moment().startOf('month'); for (let balanceId in balanceSources) { if (!balanceSources.hasOwnProperty(balanceId)) { continue; } let currentSource = balanceSources[balanceId]; let months = Object.keys(currentSource.value); let monthData = []; for (let i = 0; i < months.length; i++) { monthData.push(moment(months[i], "MMYYYY")); } [firstMonth, lastMonth] = functions.calcStartEndDates(firstMonth, lastMonth, monthData); } let data = []; let countMonths = lastMonth.diff(firstMonth, 'months', false) + 1; let month = firstMonth; for (let i = 0; i < countMonths; i++) { let monthData = { month: month.clone(), value: [] }; let addedAnuValue = false; for (let balanceId in balanceSources) { if (!balanceSources.hasOwnProperty(balanceId)) { continue; } let currentSource = balanceSources[balanceId]; if (currentSource.value[month.format("MMYYYY")] !== undefined) { monthData.value.push(currentSource.value[month.format("MMYYYY")]); addedAnuValue = true; } else { monthData.value.push(0); } } if (addedAnuValue === false && currentMonth.format("MMYYYY") === month.format("MMYYYY")) { continue; } data.push(monthData); month.add(1, 'M'); } return data; } function isMonthInDOM(sourceId, monthStr) { let block = document.querySelector('h2[data-id="' + sourceId + '"').parentNode; return block.querySelector('p[data-month="' + monthStr + '"] span.sum') !== null } function fillSourceName(id, element, sourceName) { element.textContent = sourceName; let editBalance = document.createElement('span'); editBalance.className = 'balance-edit js-balance-edit'; editBalance.onclick = () => { let input = document.createElement('input'); input.value = sourceName; input.className = 'balance-edit-input'; let save = document.createElement('span'); save.className = 'balance-edit-save'; save.onclick = () => { if (sourceName !== input.value) { balanceView.renameBalanceSourceFunction(id, input.value); balanceView.data[id].name = input.value; balanceView.reloadGraph(); } fillSourceName(id, element, input.value); }; element.innerHTML = ''; element.appendChild(input); element.appendChild(save); }; element.appendChild(editBalance); } module.exports = new BalanceView(); <|start_filename|>app/backend/Database.js<|end_filename|> const Datastore = require('nedb'); function Database(path) { this.db = new Datastore({filename: path}); this.db.loadDatabase( function (err) { if (err) { // todo: this. Can happens, when database in dropbox folder, for example. console.log("DATABASE ERROR"); console.log(err); throw new Error("Database load error: " + err); } } ); this.filename = this.db.filename; } Database.prototype.insert = function (data, type, callback) { this.db.insert({ type: type, data: data }, function (err, doc) { if (err) { throw new Error(err); } if (callback === undefined) { return; } callback(mapDataFromDB(doc)); }); }; Database.prototype.updateFullData = function (id, type, data, callback) { this.db.update({ _id: id, type: type, }, { type: type, data: data }, {}, callback ); }; Database.prototype.update = function (find, update, callback) { this.db.update(find, update, {}, callback); }; Database.prototype.addProperty = function (query, key, value, callback) { let obj = {}; obj[key] = value; this.db.update(query, { $set: obj }, {upsert: true}, function () { callback(); }); }; Database.prototype.deleteProperty = function (query, key, callback) { let obj = {}; obj[key] = true; this.db.update(query, {$unset: obj}, {}, () => { callback(); }); }; Database.prototype.getByType = function (type, callback) { this.db.find({type: type}, function (err, data) { let result = data.map(mapDataFromDB); callback(result); }); }; Database.prototype.delete = function (type, id, callback) { this.db.remove({ type: type, _id: id }, {}, function (err) { if (err) { throw new Error(err); } if (callback === undefined) { return; } callback(id); }); }; Database.prototype.deleteAll = function (type) { this.db.remove({ type: type, }, true); }; Database.prototype.drop = function () { this.db.remove({}, { multi: true }, function (err, numRemoved) { }); }; function mapDataFromDB(item) { let data = item.data; data.id = item._id; return data; } module.exports.Database = Database; <|start_filename|>app/view/IncomeView.js<|end_filename|> const functions = require('../scripts/functions'); const Income = require('../models/income'); const moment = require('moment'); const languages = require('../scripts/languages'); function IncomeView() { this.data = {}; this.dataByMonth = { cols: ["Month", "Sum"], data: null, chart: null, chartData: null, chartOptions: null, }; this.dataByYear = { cols: ["Year", "Sum"], data: null, chart: null, chartData: null, chartOptions: null, }; this.dataAverage = { cols: ["Year", "Middle sum"], data: null, chart: null, chartData: null, chartOptions: null, }; this.sum = 0; this.average = 0; this.topMonth = { name: '', value: 0 }; this.worstMonth = { name: '', value: 0 }; this.paymentTypes = []; this.contacts = []; this.ready = false; } IncomeView.prototype.setData = function (data) { data.sort((a, b) => { return a.date - b.date; }); this.data = data; insertIncomeData(data); updateGraphData(this); let paymentTypes = data.map(function (e) { return e.paymentType; }); this.paymentTypes = paymentTypes.filter(functions.uniqueArrayFilter); let contacts = data.map(function (e) { return e.contact; }); this.contacts = contacts.filter(functions.uniqueArrayFilter); if (this.ready) { setFieldsAutocomplete(this.paymentTypes, this.contacts); } this.reloadGraph(); }; IncomeView.prototype.insertIncome = function (item) { this.data.push(item); updateGraphData(this); this.reloadGraph(); insertIncomeToPage(item); }; IncomeView.prototype.deleteIncome = function (id) { let index = getIndexById(id, this.data); this.data.splice(index, 1); document.querySelector('tr[data-id="' + id + '"]').remove(); updateGraphData(this); this.reloadGraph(); }; IncomeView.prototype.updateIncome = function (income) { let index = getIndexById(income.id, this.data); this.data[index] = income; let row = document.querySelector('.js-income-row[data-id="' + income.id + '"]'); this.setRowFromItem(income, row); updateGraphData(this); this.reloadGraph(); }; IncomeView.prototype.reloadGraph = function () { if (this.dataByMonth.data === null || this.dataByYear === null || this.dataAverage === null || this.data === null) { return; } drawByMonth(this.dataByMonth); drawByYear(this.dataByYear); drawAverage(this.dataAverage); drawByType(this.data); drawByContact(this.data); }; IncomeView.prototype.setRowFromItem = function (item, row) { setupIncomeRow(item, row); }; IncomeView.prototype.preparePage = function (addIncomeFunction) { $('.js-add-month').val(moment().format("YYYY-MM")); $('.js-add-date').val(moment().format("YYYY-MM-DD")); $(".js-income-page .js-income-add").on('submit', (e) => { e.preventDefault(); const incomeItem = getItemFromForm(document.querySelector('.js-income-page .form')); addIncomeFunction(incomeItem); }); this.ready = true; setFieldsAutocomplete(this.paymentTypes, this.contacts); }; IncomeView.prototype.editClickHandler = function (event) { const row = event.target.closest('.js-income-row'); const fields = [ [row, ".js-date", ".js-add-date", {format: "YYYY-MM-DD"} ], [ row, ".js-month", ".js-add-month", {format: "YYYY-MM"} ], [row, ".js-sum", ".js-add-sum"], [row, ".js-payment-type", ".js-add-payment-type"], [row, ".js-contact", ".js-add-contact"], [row, ".js-description", ".js-add-description"] ]; fields.forEach(copyField); row.className += ' update'; setFieldsAutocomplete(this.paymentTypes, this.contacts); }; IncomeView.prototype.saveClickHandler = function (event) { const row = event.target.closest('.js-income-row'); return getItemFromForm(row); }; function drawByMonth(dataByMonth) { draw(dataByMonth, '100%', 400, "js-income-month-chart"); } function drawByYear(dataByYear) { draw(dataByYear, '100%', 300, "js-income-year-chart"); } function drawAverage(dataAverage) { draw(dataAverage, '100%', 300, "js-income-average-chart"); } function drawByType(data){ let chartData = preparePieChartDataByField(data, 'paymentType'); drawPie(chartData, 'js-income-by-types-chart') } function drawByContact(data) { let chartData = preparePieChartDataByField(data, 'contact'); drawPie(chartData, 'js-income-by-contacts-chart') } function preparePieChartDataByField(data, field) { let map = data.reduce( (accumulator, item) => { if (accumulator.hasOwnProperty(item[field])) { accumulator[item[field]] += item.sum; } else { accumulator[item[field]] = item.sum; } return accumulator; }, {} ); let result = []; for (let type in map) { if (map.hasOwnProperty(type)) { result.push([type, map[type]]); } } return result; } function draw(chartData, width, height, chartId) { google.charts.setOnLoadCallback(drawChart); function drawChart() { let dataTable = prepareChartData(chartData); if (chartData.chart !== null) { chartData.chart.draw(dataTable, chartData.chartOptions); chartData.chartData = dataTable; return } let view = new google.visualization.DataView(dataTable); let options = { width: width, height: height, bar: {groupWidth: "95%"}, legend: {position: "none"}, animation: { duration: 500, easing: 'out', }, vAxis: { minValue: 0 } // chartArea: { // width: '80%', // height: '80%' // } }; let chart = new google.visualization.ColumnChart(document.getElementById(chartId)); chart.draw(view, options); chartData.chart = chart; chartData.chartData = dataTable; chartData.chartOptions = options; } } function drawPie(pieData, chartId) { google.charts.setOnLoadCallback(chart); function chart() { let data = google.visualization.arrayToDataTable([['','']].concat(pieData)); let sliceVisibilityThreshold = 0; if (pieData.length > 8) { sliceVisibilityThreshold = 0.05 } let options = { width: '100%', height: 350, pieSliceText: 'label', sliceVisibilityThreshold: sliceVisibilityThreshold, }; let chart = new google.visualization.PieChart(document.getElementById(chartId)); chart.draw(data, options); } } function insertIncomeData(data) { data.forEach(insertIncomeToPage); } function updateGraphData(incomeItem) { let data = incomeItem.data; let firstMonth = moment().startOf('month'); let firstYear = moment().startOf('year'); let lastMonth = moment().startOf('month'); let lastYear = moment().startOf('year'); if (data.length !== 0) { firstMonth = moment.unix(data[0]['month']).startOf('month'); firstYear = moment.unix(data[0]['month']).startOf('year'); lastMonth = moment.unix(data[data.length - 1]['month']).startOf('month'); lastYear = moment.unix(data[data.length - 1]['month']).startOf('year'); } let firstYearStr = firstYear.format('YYYY'); let firstYearMonthCount = 12 - firstMonth.month(); let countMonths = lastMonth.diff(firstMonth, 'months', false) + 1; let countYears = lastYear.diff(firstYear, 'years', false) + 1; let dataByMonth = {}; let dataByYear = {}; let dataAverage = {}; for (let i = 0; i < countMonths; i++) { dataByMonth[firstMonth.format("MMM YYYY")] = 0; firstMonth.add(1, 'M'); } for (let i = 0; i < countYears; i++) { dataByYear[firstYear.format("YYYY")] = 0; dataAverage[firstYear.format("YYYY")] = 0; firstYear.add(1, 'Y'); } incomeItem.sum = 0; data.forEach(function (element) { incomeItem.sum += element.sum; let month = moment.unix(element.month).format("MMM YYYY"); dataByMonth[month] += element.sum; let year = moment.unix(element.month).format("YYYY"); dataByYear[year] += element.sum; // если разница меньше нуля, значит анализируется месяц за прошлые годы let monthDiff = 12; let isPreviousYear = moment().format("YYYY") !== year; if (!isPreviousYear) { monthDiff = moment().month() + 1; } else if (year === firstYearStr) { monthDiff = firstYearMonthCount; } dataAverage[year] += element.sum / monthDiff; }); incomeItem.dataByMonth.data = []; for (let property in dataByMonth) { if (dataByMonth.hasOwnProperty(property)) { if (incomeItem.topMonth.value < dataByMonth[property] || incomeItem.topMonth.name === '') { incomeItem.topMonth.value = dataByMonth[property]; incomeItem.topMonth.name = property; } if (incomeItem.worstMonth.value > dataByMonth[property] || incomeItem.worstMonth.name === '') { incomeItem.worstMonth.value = dataByMonth[property]; incomeItem.worstMonth.name = property; } incomeItem.dataByMonth.data.push({ name: property, value: dataByMonth[property], time: moment(property, "MMM YYYY").unix() }); } } incomeItem.dataByYear.data = []; for (let property in dataByYear) { if (dataByYear.hasOwnProperty(property)) { incomeItem.dataByYear.data.push({ name: property, value: dataByYear[property], time: moment(property, "YYYY").unix() }); } } incomeItem.dataAverage.data = []; for (let property in dataAverage) { if (dataAverage.hasOwnProperty(property)) { incomeItem.dataAverage.data.push({ name: property, value: dataAverage[property], time: moment(property, "YYYY").unix() }); } } incomeItem.dataByMonth.data.sort(function (a, b) { return a.time - b.time; }); incomeItem.dataByYear.data.sort(function (a, b) { return a.time - b.time; }); incomeItem.dataAverage.data.sort(function (a, b) { return a.time - b.time; }); incomeItem.average = Math.round(incomeItem.sum / Object.keys(incomeItem.dataByMonth.data).length); document.getElementsByClassName('js-income-sum')[0].innerHTML = functions.numberWithSpaces(incomeItem.sum); document.getElementsByClassName('js-income-average')[0].innerHTML = functions.numberWithSpaces(incomeItem.average); document.getElementsByClassName('js-income-top')[0].innerHTML = functions.numberWithSpaces(incomeItem.topMonth.value); document.getElementsByClassName('js-income-worst')[0].innerHTML = functions.numberWithSpaces(incomeItem.worstMonth.value); } function prepareChartData(chartData) { let data = [chartData.cols]; data = data.concat(chartData.data.map(function (element) { return [element.name, element.value]; })); return google.visualization.arrayToDataTable(data); } function insertIncomeToPage(item) { let rowExample = document.querySelector('.js-income-page .js-row'); let row = rowExample.cloneNode(true); setupIncomeRow(item, row); let rowParent = rowExample.parentNode; rowParent.insertBefore(row, rowExample); } function setupIncomeRow(item, row) { let id = item.id.toString(); row.classList.remove('js-row'); row.classList.remove('update'); row.dataset.id = id; row.querySelector('.js-date').textContent = moment.unix(item.date).format("DD.MM.YYYY"); row.querySelector('.js-date').dataset.time = item.date; row.querySelector('.js-month').textContent = moment.unix(item.month).format("MMM YYYY"); row.querySelector('.js-month').dataset.time = item.month; row.querySelector('.js-sum').textContent = functions.numberWithSpaces(item.sum); row.querySelector('.js-payment-type').textContent = item.paymentType; row.querySelector('.js-contact').textContent = item.contact; row.querySelector('.js-description').textContent = item.description; } function getIndexById(id, data) { for (let i = 0; i < data.length; i++) { if (data[i]['id'] === id) { return i; } } return null; } function copyField([row, elementClass, fieldClass, options = {}]) { const {format} = options; const element = row.querySelector(elementClass); const field = document.querySelector(fieldClass).cloneNode(true); let val = element.innerHTML; if (field.type == 'number') { val = parseFloat(val.replace(' ', '')); } field.value = val; if (format !== undefined) { const time = element.dataset.time; field.value = moment.unix(time).format(format); } element.innerHTML = ''; element.appendChild(field); } function getItemFromForm(row) { let date = row.querySelector('input.js-add-date').value; let month = row.querySelector('input.js-add-month').value; let sum = row.querySelector('input.js-add-sum').value; let type = row.querySelector('input.js-add-payment-type').value; let contact = row.querySelector('input.js-add-contact').value; let description = row.querySelector('input.js-add-description').value; if (date.length === 0 || month.length === 0 || sum.length === 0) { alert("Error"); return; } let income = new Income(moment(date), moment(month), parseInt(sum), type, contact, description); let id = row.dataset.id; if (id !== undefined) { income.id = id; } return income; } function setFieldsAutocomplete(types, contacts) { if (contacts.length > 0) { setAutocomplete('.js-add-contact', contacts); } if (types.length > 0) { setAutocomplete('.js-add-payment-type', types); } } function setAutocomplete(jsClass, data) { $(".js-income-page " + jsClass).autocomplete({ source: data, minLength: 0, }); } module.exports = new IncomeView(); <|start_filename|>app/models/income.js<|end_filename|> module.exports = function(date, month, sum, paymentType, contact, description) { this.id = null; this.date = date.unix(); this.month = month.unix(); this.sum = sum; this.paymentType = paymentType; this.contact = contact; this.description = description; }; <|start_filename|>app/models/settings.js<|end_filename|> module.exports = function(remind, email, databaseFolder, backupFolder, language) { this.remind = remind; this.email = email; this.databaseFolder = databaseFolder; this.backupFolder = backupFolder; this.language = language; this.lastBackupDateTimestamp = 0; }; <|start_filename|>app/scripts/languages.js<|end_filename|> const legend = { title: { ru: 'Cromberg - система личного учёта', en: 'Cromberg - personal finance accounting system', fr: 'Cromberg - système de comptabilité financière personnelle' }, income: { ru: 'Доход', en: 'Income', fr: 'Revenu' }, balance: { ru: 'Баланс', en: 'Balance', fr: 'Balance' }, settings: { ru: 'Настройки', en: 'Settings', fr: 'Paramètres' }, remind: { ru: 'Присылать мне уведомления каждый месяц', en: 'Remind me every month about balance', fr: 'Rappelez-moi chaque mois la balance' }, 'remind-email': { ru: 'E-mail для уведомлений', en: 'E-mail for reminds', fr: 'E-mail de rappel' }, sum: { ru: 'Сумма', en: 'Sum', fr: 'Somme' }, average: { ru: 'Средний', en: 'Average', fr: 'Moyenne' }, 'top-month': { ru: 'Лучший месяц', en: 'Best month', fr: 'Meilleur mois' }, 'worst-month': { ru: 'Худший месяц', en: 'Worst month', fr: 'Pire mois' }, date: { ru: 'Дата поступления средств', en: 'Date of receive money', fr: 'Date de réception de l\'argent' }, month: { ru: 'Месяц', en: 'Month', fr: 'Mois' }, type: { ru: 'Тип', en: 'Type', fr: 'Type' }, contact: { ru: 'Контакт', en: 'Contact', fr: 'Contact' }, description: { ru: 'Описание', en: 'Description', fr: 'Description' }, 'balance-source-input': { ru: 'Введите место для хранения средств', en: 'Enter a place to storage money', fr: 'Entrer un endroit pour ranger de l\'argent' }, save: { ru: 'Сохранить', en: 'Save', fr: 'Enregister' }, 'income-month': { ru: 'Доход по месяцам', en: 'Income by month', fr: 'Revenu mensuel' }, 'income-year': { ru: 'Доход по годам', en: 'Income by year', fr: 'Revenu annuel' }, 'income-average': { ru: 'Средний доход по годам', en: 'Average income by year', fr: 'Revenu moyen annuel' }, 'income-by-type': { ru: 'По типам', en: 'By types', fr: 'Par types' }, 'income-by-contact': { ru: 'По контактам', en: 'By contacts', fr: 'Par des contacts' }, 'backup-folder': { ru: 'Папка для бекапов', en: 'Backup folder', fr: 'Dossier de sauvegarde' }, 'database-folder': { ru: 'Папка для базы данных', en: 'Database folder', fr: 'Dossier de la base de données ' }, 'choose-folder': { ru: 'Выберите папку', en: 'Choose folder', fr: 'Choisissez dossier' }, 'balance-chart-title': { ru: 'Баланс по месяцам', en: 'Balance by months', fr: 'Balance par mois' }, 'balance-chart-diff-title': { ru: 'Разница с предыдущим месяцем', en: 'Diff with previous month', fr: 'Balance par mois' }, 'balance-pie-chart-title': { ru: 'За последний месяц: ?', en: 'Last month: ?', fr: 'Le mois dernier: ?' }, 'costs-chart-title': { ru: 'Расход по месяцам', en: 'Costs by months', fr: 'Coûts par mois' }, 'cost': { ru: 'Расход', en: 'Spending', fr: 'Déchets' }, 'no-internet': { ru: 'Без подключения к интернету работа программы невозможна', en: 'Its need internet connection for correct work', fr: 'Connexion internet nécessaire pour fonctionné correctement' }, 'language': { ru: 'Язык', en: 'Language', fr: 'Langue' }, 'statistic': { ru: 'Статистика', en: 'Statistic', fr: 'Statistique' }, 'new-version': { ru: 'Вышла новая версия приложения. Текущая версия: ?, новая версия: ?.', en: 'A new version of the application has been released. Current: ?, new: ?.', fr: 'Une nouvelle version de l\'application a été publiée. Actuel:?, nouveau:?.' }, }; function Languages() { this.setLanguage(navigator.language); } Languages.prototype.getText = function (word) { const lang = this.lang; if (!legend.hasOwnProperty(word)) { return word; } if (legend[word].hasOwnProperty(lang)) { return legend[word][lang]; } return word; }; Languages.prototype.getTextWithPlaceholders = function (word, array) { let text = this.getText(word); array.forEach(function (element) { text = text.replace('?', element); }); return text; }; Languages.prototype.setLanguage = function (lang) { if (!lang) { lang = navigator.language; } switch (lang) { case 'ru': this.lang = 'ru'; break; case 'fr': this.lang = 'fr'; break; default: this.lang = 'en'; } }; Languages.prototype.replacePlaceholders = function (pageText) { let regex = /\[\[([\w-]*?)\]\]/g; let words = pageText.match(regex); words.forEach((value) => { let word = value.substr(2, value.length - 4); let text = this.getText(word); pageText = pageText.replace(value, text); }); return pageText; }; module.exports = new Languages(); <|start_filename|>app/scripts/functions.js<|end_filename|> function uniqueArrayFilter(value, index, self) { return self.indexOf(value) === index; } function numberWithSpaces(x) { let parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " "); return parts.join("."); } function calcStartEndDates(startDate, endDate, dateArray) { if (dateArray.length === 0) { return [startDate, endDate]; } dateArray.sort((a, b) => { return a.unix() - b.unix(); }); if (endDate.isBefore(dateArray[dateArray.length - 1])) { endDate = dateArray[dateArray.length - 1]; } if (startDate.isAfter(dateArray[0])) { startDate = dateArray[0]; } return [startDate, endDate]; } module.exports = {uniqueArrayFilter, numberWithSpaces, calcStartEndDates}; <|start_filename|>app/css/style.css<|end_filename|> html, body { margin: 0; } .wrapper { padding: 20px 40px; } * { box-sizing: border-box; } .content { box-sizing: border-box; min-height: 100%; } .js-row { display: none; } table.data-table { width: 100%; text-align: left; border-collapse: collapse; margin-bottom: 35px; } table.data-table tr:hover td, table.data-table tr.row.update { background: #f1f1f1; } table.data-table td { position: relative; } table.data-table input, table.data-table select { width: 100%; border: 0; } table.data-table input.submit { position: absolute; right: 0; width: 80px; top: 40px; } table.data-table td, table.data-table th { padding: 7px 10px 7px 10px; border: 1px dashed #e1e1e1; border-right: 0; border-left: 0; } table.data-table tr.form td { padding: 0; } table.data-table tr.form input { padding: 7px 10px 7px 10px; } table.data-table tr.form:hover td { background: #fff; } table.data-table td:last-child, table.data-table th:last-child { border-right: 0; } table.data-table td:first-child, table.data-table th:first-child { border-left: 0; } table.data-table tr.row span { display: inline-block; } table.data-table tr.row { position: relative; } table.data-table tr.row .income-button { position: absolute; cursor: pointer; display: none; width: 25px; height: 25px; } table.data-table tr.row .save { right: 35px; top:4px; background: url('../img/ok.svg') no-repeat; } table.data-table tr.row.update .save { display: block; } table.data-table tr.row .delete { right: 10px; top:3px; background: url('../img/delete.svg') no-repeat; } table.data-table tr.row:hover .delete { display: block; } table.data-table tr.row .edit { right: 35px; top:3px; background: url('../img/edit.svg') no-repeat; } table.data-table tr.row:hover .edit { display: block; } table.data-table tr.row.update .edit { display: none; } .page { display: none; } .page.active { display: block; } .page:after { display: block; content: ''; clear: both; } .tabs { display: inline-block; } .tabs .tab.active { cursor: default; } .tabs .tab, .settings-button { padding: 5px 10px; cursor: pointer; background: #ffffff; border: 1px solid #f1f1f1; display: inline-block; } .tabs .tab.active, .settings-button.active { background: #f1f1f1; } .buttons { position: absolute; top: 0; right: 0; margin: 20px 20px 0 0; } .settings-button { position: relative; display: inline-block; cursor: pointer; z-index: 100; } .income-statistic { text-align: center; } .income-month-chart { height: 400px; } .income-year-chart, .income-average-chart { height: 300px; } .income-by-types-chart, .income-by-contacts-chart { height: 350px; } .inline-blocks .income-chart, .inline-blocks .income-data { display: inline-block; padding: 0 20px; vertical-align: top; min-width: 300px; width: 30%; text-align: left; } .data-line { margin: 0; padding: 10px; border-bottom: 1px dashed #e1e1e1; } .data-line:hover { background: #f1f1f1; } .income-data-name { font-weight: bold; } .data-value { float: right; } .settings-window { display: none; position: fixed; width: 500px; border: 5px solid #e1e1e1; background: #fff; z-index: 50; padding: 20px 40px; margin-left: -250px; margin-top: -100px; top: 30%; left: 50%; } .settings-window.active { display: block; } .settings-window .settings-close-button { position: absolute; top: 15px; right: 15px; font-size: 20px; cursor: pointer; } .settings-form label { display: block; margin: 15px 0; } .settings-form .settings-folder { position: absolute; z-index: 100; opacity: 0; width: 410px; margin: 10px 0; } .settings-form .settings-folder-text { position: relative; width: 100%; margin: 10px 0; } .settings-response.error { color: #ff0000; } .balance-source { margin: 15px 30px 15px 0; float: left; width: 320px; } .balance-source-name { padding: 10px 5px; margin: 10px 0; position: relative; } .balance-source-name:hover { background: #f1f1f1; } .balance-source-name .balance-edit { position: absolute; top: 10px; right: 15px; display: none; cursor: pointer; width: 30px; height: 30px; background: url('../img/edit.svg') no-repeat; } .balance-source-name .balance-edit-save { position: absolute; top: 10px; right: 15px; cursor: pointer; width: 30px; height: 30px; background: url('../img/ok.svg') no-repeat; } .balance-source-name .balance-edit-input { width: 240px; } .balance-source-name:hover .balance-edit { display: block; } .balance-items .balance-item { padding: 7px 10px 7px 10px; margin: 0; border-bottom: 1px dashed #e1e1e1; } .balance-items .balance-item:hover { background: #f1f1f1; } .balance-items .balance-item:hover .delete-month-balance { display: inline-block; } .balance-items .balance-item:hover .sum { margin-right: 20px; } .delete-month-balance { float: right; cursor: pointer; width: 20px; height: 20px; display: none; vertical-align: middle; background: url('../img/delete.svg') no-repeat; } .balance-items .balance-item .month { display: inline-block; width: 120px; } .balance-items .balance-item .sum { display: inline-block; width: 70px; float: right; text-align: right; margin-right: 40px; } form.addBalance { margin-top: 15px; } form.addBalance input.month { width: 160px; } form.addBalance input.sum { padding: 2px; width: 110px; margin-left: 5px; } form.addBalance button.submit { padding: 2px 6px; margin-left: 5px; } .balance-statistic { text-align: center; margin-bottom: 40px; } .inline-blocks .balance-chart, .inline-blocks .balance-data { display: inline-block; padding: 0 10px; vertical-align: top; min-width: 300px; width: 49%; text-align: left; } <|start_filename|>app/main.js<|end_filename|> const electron = require('electron'); const compareVersions = require('compare-versions'); const Dao = require('./backend/Dao'); const Backup = require('./backend/Backup'); const functions = require('./scripts/functions'); const argv = require('minimist')(process.argv); const ServerRequester = require('./backend/ServerRequester'); const path = require('path'); const Config = require('electron-config'); const fs = require('fs'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; const serverRequester = new ServerRequester(); const DATABASE_FOLDER_KEY = 'database-folder'; const DATABASE_NAME = 'database'; // require('./tmp/converter').exportBalanceData(); // require('./tmp/converter').exportIncomeData(); // Определение глобальной ссылки , если мы не определим, окно // окно будет закрыто автоматически когда JavaScript объект будет очищен сборщиком мусора. let mainWindow = null; // Проверяем что все окна закрыты и закрываем приложение. app.on('window-all-closed', function () { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('ready', function () { // Создаем окно браузера. mainWindow = new BrowserWindow( { minWidth: 800, minHeight: 600, width: 1024, height: 600, icon: path.join(__dirname, 'build/icon.ico') } ); const config = new Config(); let dbPath = config.get(DATABASE_FOLDER_KEY); if (dbPath === undefined) { dbPath = app.getPath('userData') + path.sep + 'db' + path.sep; config.set(DATABASE_FOLDER_KEY, dbPath); } dbPath = dbPath + DATABASE_NAME; if (argv.dev) { mainWindow.webContents.openDevTools(); dbPath = "database-dev"; } else { mainWindow.setMenu(null); } const dao = new Dao(dbPath); // mainWindow.maximize(); mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.webContents.on('dom-ready', function () { serverRequester.getServerVersion((version) => { if (compareVersions(version, app.getVersion()) > 0) { mainWindow.webContents.send('new-version', app.getVersion(), version); } }); dao.getSettings(function (settings) { settings.databaseFolder = config.get(DATABASE_FOLDER_KEY); mainWindow.webContents.send('settings', settings); let backup = new Backup(dao.getDatabasePath(), settings.backupFolder); let backupTimestamp = backup.makeBackup(settings.lastBackupDateTimestamp); if (backupTimestamp !== undefined) { settings.lastBackupDateTimestamp = backupTimestamp; dao.updateSettings(settings, () => { }); } }); dao.getIncomes(function (data) { mainWindow.webContents.send('income-data', data); }); dao.getBalances(function (types) { mainWindow.webContents.send('balance-types', types); }); }); // Этот метод будет выполнен когда генерируется событие закрытия окна. mainWindow.on('closed', function () { // Удаляем ссылку на окно, если ваше приложение будет поддерживать несколько // окон вы будете хранить их в массиве, это время // когда нужно удалить соответствующий элемент. mainWindow = null; }); ipcMain.on('income-add', (event, income) => { dao.insertIncome(income, function (inserted) { mainWindow.webContents.send('income-data-inserted', inserted); }); }); ipcMain.on('income-delete', (event, incomeId) => { dao.deleteIncome(incomeId, () => { mainWindow.webContents.send('income-data-deleted', incomeId); }); }); ipcMain.on('income-edit', (event, income) => { dao.updateIncome(income, (err) => { if (err !== null) { throw new Error("Update error"); } mainWindow.webContents.send('income-edited', income); }); }); ipcMain.on('balance-add', (event, source) => { dao.addBalanceSource(source, insertedSource => { mainWindow.webContents.send('balance-inserted', insertedSource); }); }); ipcMain.on('balance-update', (event, id, month, sum) => { dao.addBalance(id, month, sum, () => { mainWindow.webContents.send('balance-updated', id, month, sum); }); }); ipcMain.on('balance-month-remove', (event, id, month) => { dao.deleteBalance(id, month, () => { mainWindow.webContents.send('balance-reupdated', id, month); }); }); ipcMain.on('rename-balance-source', (event, id, newName) => { dao.renameBalance(id, newName); }); ipcMain.on('update-settings', (event, newClientSettings) => { let currentFolder = config.get(DATABASE_FOLDER_KEY); let newFolder = newClientSettings.databaseFolder; if (newFolder !== currentFolder) { config.set(DATABASE_FOLDER_KEY, newFolder + path.sep); if (argv.dev) { mainWindow.webContents.send('error', 'You cant move database file in dev mod'); return; } let is = fs.createReadStream(currentFolder + DATABASE_NAME); let os = fs.createWriteStream(newFolder + path.sep + DATABASE_NAME); is.pipe(os); is.on('end', function () { fs.unlinkSync(currentFolder + DATABASE_NAME); app.relaunch(); app.exit(0); }); } let newSettings = Object.assign({}, newClientSettings); delete newSettings.databaseFolder; // we wont to save this as a settings in database; dao.getSettings((oldSettings) => { serverRequester.notify(oldSettings, newSettings); dao.updateSettings(newSettings, () => { mainWindow.webContents.send('settings-saved', newClientSettings); }); }); }); });
Profins/IncomeAssess
<|start_filename|>test/url_parser.test.js<|end_filename|> const expect = require("chai").expect; const UrlParser = require("../url_parser").UrlParser; let urlAddress = "https://test.address.com:2603/route/to/page/?climate=change&sea-level=rising"; let urlPattern = ""; describe("UrlParser", () => { it("should return the hostname", () => { expect(UrlParser(urlAddress, urlPattern).host).to.equal( "test.address.com:2603" ); }); it("should return the hostname", () => { expect(UrlParser(urlAddress, urlPattern).hostname).to.equal( "test.address.com" ); }); it("should return the port", () => { expect(UrlParser(urlAddress, urlPattern).port).to.equal("2603"); }); it("should return the path name", () => { expect(UrlParser(urlAddress, urlPattern).pathname).to.equal( "/route/to/page/" ); }); it("should return the path name", () => { expect(UrlParser(urlAddress, urlPattern).protocol).to.equal("https:"); }); it("should return the search queries", () => { expect(UrlParser(urlAddress, urlPattern).search).to.equal( "?climate=change&sea-level=rising" ); }); it("should return the search queries as an object", () => { expect(UrlParser(urlAddress, urlPattern).queryParams).to.deep.equal({ climate: "change", "sea-level": "rising", }); }); it("should return the search queries as an array with all keys", () => { expect(UrlParser(urlAddress, urlPattern).queryParamsKeys).to.deep.equal([ "climate", "sea-level", ]); }); it("should return the search queries as an array with all values", () => { expect(UrlParser(urlAddress, urlPattern).queryParamsValues).to.deep.equal([ "change", "rising", ]); }); it("should return the path name as an array of elements", () => { expect(UrlParser(urlAddress, urlPattern).pathNames).to.deep.equal([ "route", "to", "page", ]); }); describe("A url with a hash", () => { beforeEach(() => { urlAddress = "https://test.address.com:2603/1234/developer?climate=change&sea-level=rising#main"; urlPattern = "/:id/:title"; }); it("should return the hash part of the query", () => { expect(UrlParser(urlAddress, urlPattern).hash).to.equal("#main"); }); }); describe("A url with named params", () => { describe("In root path", () => { beforeEach(() => { urlAddress = "https://test.address.com:2603/1234/developer/?climate=change&sea-level=rising"; urlPattern = "/:id/:title"; }); it("should return the named params keys", () => { expect( UrlParser(urlAddress, urlPattern).namedParamsKeys ).to.deep.equal(["id", "title"]); }); it("should return the named params values", () => { expect( UrlParser(urlAddress, urlPattern).namedParamsValues ).to.deep.equal(["1234", "developer"]); }); it("should return the named params as an object", () => { expect(UrlParser(urlAddress, urlPattern).namedParams).to.deep.equal({ id: "1234", title: "developer", }); }); }); describe("In a first level path", () => { beforeEach(() => { urlAddress = "https://test.address.com:2603/employee/1234/developer/?climate=change&sea-level=rising"; urlPattern = "/employee/:id/:title"; }); it("should return the named params keys", () => { expect( UrlParser(urlAddress, urlPattern).namedParamsKeys ).to.deep.equal(["id", "title"]); }); it("should return the named params values", () => { expect( UrlParser(urlAddress, urlPattern).namedParamsValues ).to.deep.equal(["1234", "developer"]); }); it("should return the named params as an object", () => { expect(UrlParser(urlAddress, urlPattern).namedParams).to.deep.equal({ id: "1234", title: "developer", }); }); }); describe("In a multilevel level path", () => { beforeEach(() => { urlAddress = "https://test.address.com:2603/employees/show/1234/developer/reports/asc/?climate=change&sea-level=rising"; urlPattern = "/employees/show/:id/:title/reports/:order"; }); it("should return the named params keys", () => { expect( UrlParser(urlAddress, urlPattern).namedParamsKeys ).to.deep.equal(["id", "title", "order"]); }); it("should return the named params values", () => { expect( UrlParser(urlAddress, urlPattern).namedParamsValues ).to.deep.equal(["1234", "developer", "asc"]); }); it("should return the named params as an object", () => { expect(UrlParser(urlAddress, urlPattern).namedParams).to.deep.equal({ id: "1234", title: "developer", order: "asc", }); }); it("should return the path name as an array of elements", () => { expect(UrlParser(urlAddress, urlPattern).pathNames).to.deep.equal([ "employees", "show", "1234", "developer", "reports", "asc", ]); }); }); }); }); <|start_filename|>index.js<|end_filename|> const UrlParser = require("./url_parser").UrlParser; module.exports = { UrlParser };
jorgegorka/url-params-parser
<|start_filename|>compassservant/src/main/java/com/dyzs/compassservant/ColorUtil.java<|end_filename|> package com.dyzs.compassservant; import android.graphics.Color; import java.util.Random; public class ColorUtil { /** * 随机生成漂亮的颜色 * @return */ public static int randomColor() { Random random = new Random(); int red = random.nextInt(150) + 50; int green = random.nextInt(150) + 50; int blue = random.nextInt(150) + 50; return Color.rgb(red, green, blue); // 根据rgb混合生成一种新的颜色 } /** * 随机生成漂亮的颜色,带透明度的 * @return */ public static int randomColorArgb() { Random random = new Random(); int alpha = random.nextInt(70) + 30; int red = random.nextInt(150) + 50; int green = random.nextInt(150) + 50; int blue = random.nextInt(150) + 50; return Color.argb(alpha, red, green, blue); // 根据argb混合生成一种新的颜色 } /** * 颜色与上一个十六进制数ARGB,得到一个颜色加深的效果,效果从 0-F 深 * @param color * @return */ public static int getColorDeeply(int color) { // | 0xF0000000 & 0xFFF5F5F5 return color & 0xFFDDDDDD; } /** * 颜色值取反 * @param color * @return */ public static int getColorReverse(int color) { // String string = String.format("#%x", color); // string reverse int red = 255 - Color.red(color); int green = 255 - Color.green(color); int blue = 255 - Color.blue(color); return Color.argb(255, red, green, blue); } /** * 获取两个颜色值之间渐变的某个点的颜色值 * @param resSColor * @param resEColor * @param rangeColorRate * @return */ public static int getCompositeColor(int resSColor, int resEColor, float rangeColorRate) { int sc = resSColor; int ec = resEColor; int rS = Color.red(sc); int gS = Color.green(sc); int bS = Color.blue(sc); int rE = Color.red(ec); int gE = Color.green(ec); int bE = Color.blue(ec); int r = (int) (rS + (rE - rS) * 1f * rangeColorRate); int g = (int) (gS + (gE - gS) * 1f * rangeColorRate); int b = (int) (bS + (bE - bS) * 1f * rangeColorRate); return Color.argb(255, r, g, b); } } <|start_filename|>app/src/main/java/com/dyzs/app/activity/MainActivity.java<|end_filename|> package com.dyzs.app.activity; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.Process; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.dyzs.app.compassservant.R; import com.dyzs.compassservant.CompassServant; public class MainActivity extends AppCompatActivity implements CompassServant.ServantListener { private HandlerThread mHandlerThread; private String mHtName = "compass_servant"; private Handler mLooper; private Handler mUIHandler; private static int MESSAGE = 0x110; CompassServant compass_servant; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initHandlerThread(); compass_servant = (CompassServant) findViewById(R.id.compass_servant); compass_servant.setServantListener(this); compass_servant.setPointerDecibel(118); } private void initHandlerThread() { mUIHandler = new Handler(); mHandlerThread = new HandlerThread(mHtName, Process.THREAD_PRIORITY_DEFAULT); mHandlerThread.start(); mLooper = new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == MESSAGE && i > 0) { doWithMainUI(); i--; } } }; } private int i = 1000; private void doWithMainUI() { try { mUIHandler.post(new Runnable() { @Override public void run() { Double d = Math.random() * 89; int iRandom = d.intValue() + 30; compass_servant.setPointerDecibel(iRandom); } }); } catch (Exception e) { } } @Override public void onDestroy() { mHandlerThread.quit(); super.onDestroy(); } @Override public void startTension() { mLooper.sendEmptyMessage(MESSAGE); } } <|start_filename|>compassservant/src/main/java/com/dyzs/compassservant/CompassServant.java<|end_filename|> package com.dyzs.compassservant; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.SweepGradient; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.animation.DecelerateInterpolator; /** * @author dyzs * Created on 2018/1/9. * 自定义命名空间 * xmlns:dyzs="http://schemas.android.com/apk/res/com.dyzs.common.ui.CompassServant" */ public class CompassServant extends View{ private static final String TAG = CompassServant.class.getSimpleName(); private Context mCtx;// god of the universal private float mWidth, mHeight; private float mPadding;// 外圆相对于 view 的间距 private float mSpacing;// 刻度与外圆, 刻度与内弧之间的间隔 the abyss between tick mark and outer circle private float[] mCircleCenter = new float[2];// view 的圆心点center of the universal private float mOuterCircleRadius;// 圆半径 private float mPointerRadius;// 指针半径 private float mTickRadius;// 刻度半径 private float mInnerArcRadius;// 内弧半径 private float mInnerArcDegree;// 内弧的度数 private float mPerDegree;// 刻度值的平均度数 private float mPointerDegree;// 当前指针刻度 private RectF mPointerRectF, mTickRectF, mInnerArcRectF, mTextRectF; private float mCircleWidth;// 外圆的宽度 outer circle width private float mTickLength;// 刻度线的长度 tick mark pointer length private float mTickWidth;// 刻度线的宽度 tick mark pointer width private float mInnerArcWidth;// 内弧的宽度 color gradient width private float mPointerWidth;// 当前指针宽度 pointer width private Paint mOuterCirclePaint;// outer circle paint private Paint mTickPaint;// tick mark paint private Paint mInnerArcPaint;// color gradient paint private Paint mPointerPaint;// pointer paint private Paint mTextPaint, mTrianglePaint; private float mStartAngle;// 画布绘圆的开始角度 private int mDecibel;// 总刻度数 tick mark total count private int[] mInnerArcGradientColors;// 内圆弧的渐变颜色值 private float[] mGalaxyPositions;// could't be authorized private int mC1, mC2, mC3, mC4;// 内圆弧的颜色1,2,3,4 private int mCCommander;// xml设置属性时,控制显示的颜色个数 command display colors, value limits[2~4] private int mBackgroundColor;// 默认获取背景颜色 private float mLeapTextSize;// 当前显示刻度的文本的大小 private static final int[] SYS_ATTRS = new int[]{ android.R.attr.background, android.R.attr.padding };// got new skill @Deprecated private Path mTrianglePath; public CompassServant(Context context) { this(context, null); } public CompassServant(Context context, AttributeSet attrs) { this(context, attrs, -1); } public CompassServant(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, -1); } public CompassServant(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs, defStyleAttr, defStyleRes); // startPointerAnim(); } private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { mCtx = context; /* get system attr */ TypedArray ta = context.obtainStyledAttributes(attrs, SYS_ATTRS); mBackgroundColor = ta.getColor(0, ContextCompat.getColor(context, R.color.black)); mPadding = ta.getDimension(1, dp2Px(10)); ta.recycle(); setBackgroundColor(mBackgroundColor); ta = context.obtainStyledAttributes(attrs, R.styleable.CompassServant, defStyleAttr, defStyleRes); mCCommander = ta.getInt(R.styleable.CompassServant_cs_color_commander, 3); mC1 = ta.getColor(R.styleable.CompassServant_cs_color1, ContextCompat.getColor(context, R.color.white)); mC2 = ta.getColor(R.styleable.CompassServant_cs_color2, ContextCompat.getColor(context, R.color.oxygen_green)); mC3 = ta.getColor(R.styleable.CompassServant_cs_color3, ContextCompat.getColor(context, R.color.cinnabar_red)); mC4 = ta.getColor(R.styleable.CompassServant_cs_color4, ContextCompat.getColor(context, R.color.pale_blue)); mDecibel = ta.getInteger(R.styleable.CompassServant_cs_decibel, 119); mTickLength = ta.getDimension(R.styleable.CompassServant_cs_tick_mark_length, 80f); mCircleWidth = ta.getDimension(R.styleable.CompassServant_cs_outer_circle, 20f); mInnerArcDegree = ta.getFloat(R.styleable.CompassServant_cs_galaxy_degree, 280f); mLeapTextSize = ta.getDimension(R.styleable.CompassServant_cs_text_size, 50f); ta.recycle(); mSpacing = 15f; mInnerArcDegree = mInnerArcDegree % 361f; mPerDegree = mInnerArcDegree / mDecibel; mStartAngle = (360f - mInnerArcDegree) / 2 + 90f; mPointerDegree = 280f; // def degree value mInnerArcWidth = mCircleWidth * 1.5f; mTickWidth = (float) (mPerDegree / 4.5f * 2 * Math.PI); mPointerWidth = mTickWidth * 2; setInnerArcColors(calcInitColors()); mOuterCirclePaint = new Paint(); mOuterCirclePaint.setAntiAlias(true); mOuterCirclePaint.setStyle(Paint.Style.STROKE); mOuterCirclePaint.setStrokeWidth(mCircleWidth); mOuterCirclePaint.setColor(ContextCompat.getColor(context, R.color.tension_grey)); mTickPaint = new Paint(); mTickPaint.setAntiAlias(true); mTickPaint.setStyle(Paint.Style.STROKE); mTickPaint.setStrokeWidth(mTickWidth); mTickPaint.setColor(ContextCompat.getColor(context, R.color.tension_grey)); mInnerArcPaint = new Paint(); mInnerArcPaint.setAntiAlias(true); mInnerArcPaint.setStyle(Paint.Style.STROKE); mInnerArcPaint.setStrokeWidth(mInnerArcWidth); mInnerArcPaint.setColor(ContextCompat.getColor(context, R.color.girl_pink)); mPointerPaint = new Paint(); mPointerPaint.setAntiAlias(true); mPointerPaint.setStyle(Paint.Style.STROKE); mPointerPaint.setStrokeWidth(mPointerWidth); mPointerPaint.setColor(ContextCompat.getColor(context, R.color.alice_blue)); mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setColor(mBackgroundColor); mTextPaint.setStrokeWidth(4f); mTextPaint.setTextSize(mLeapTextSize); mTrianglePaint = new Paint(); mTrianglePaint.setAntiAlias(true); mTrianglePaint.setColor(ContextCompat.getColor(context, R.color.tension_grey)); } private int[] calcInitColors() { mCCommander = mCCommander % 5; if (mCCommander < 2) {mCCommander = 2;} int[] retColors = new int[mCCommander], colors = new int[]{mC1, mC2, mC3, mC4}; // System.arraycopy(colors, 0, retColors, 0, mCCommander); for (int i = 0; i < mCCommander; i++) { retColors[i] = colors[i]; } return retColors; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); System.out.println("on measure"); mWidth = getMeasuredWidth();mHeight = getMeasuredHeight(); if (mWidth >= mHeight) { mOuterCircleRadius = mHeight / 2 - mPadding; } else { mOuterCircleRadius = mWidth / 2 - mPadding; } mCircleCenter[0] = mWidth / 2; mCircleCenter[1] = mHeight / 2; mPointerRadius = mOuterCircleRadius - mCircleWidth / 2; float l, t, r, b; l = mCircleCenter[0] - mPointerRadius; t = mCircleCenter[1] - mPointerRadius; r = mCircleCenter[0] + mPointerRadius; b = mCircleCenter[1] + mPointerRadius; mPointerRectF = new RectF(l, t, r, b); mTickRadius = mOuterCircleRadius - mCircleWidth - mTickLength / 2 - mSpacing; l = mCircleCenter[0] - mTickRadius; t = mCircleCenter[1] - mTickRadius; r = mCircleCenter[0] + mTickRadius; b = mCircleCenter[1] + mTickRadius; mTickRectF = new RectF(l, t, r, b); mInnerArcRadius = mOuterCircleRadius - mCircleWidth - mTickLength - mInnerArcWidth / 2 - mSpacing * 2; l = mCircleCenter[0] - mInnerArcRadius; t = mCircleCenter[1] - mInnerArcRadius; r = mCircleCenter[0] + mInnerArcRadius; b = mCircleCenter[1] + mInnerArcRadius; mInnerArcRectF = new RectF(l, t, r, b); l += mInnerArcWidth; t += mInnerArcWidth; r -= mInnerArcWidth; b -= mInnerArcWidth; mTextRectF = new RectF(l, t, r, b); mTrianglePath = new Path(); mTrianglePath.moveTo(mCircleCenter[0] - mPadding / 2, mPadding / 4); mTrianglePath.lineTo(mCircleCenter[0] + mPadding / 2, mPadding / 4); mTrianglePath.lineTo(mCircleCenter[0], mPadding - mPadding / 4); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); System.out.println("on size changed"); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawDarkFlameMaster(canvas); drawInnerArc(canvas); } /** * 画外圆, 计算当前指针角度对应的刻度, 遍历旋转绘制刻度 * @param canvas */ private void drawDarkFlameMaster(Canvas canvas) { /* draw circle */ canvas.drawCircle(mCircleCenter[0], mCircleCenter[1], mPointerRadius, mOuterCirclePaint); /* draw tick mark, triangle mark and color pointer */ int dBPointer = (int) (mPointerDegree * mDecibel / mInnerArcDegree); for (int i = 0; i <= mDecibel; i++) { canvas.save(); float rotateDegree; rotateDegree = mStartAngle + 90 + mPerDegree * i; canvas.rotate(rotateDegree, mCircleCenter[0], mCircleCenter[1]); if (i <= dBPointer) { mTickPaint.setColor(getPointerColor(i));//ContextCompat.getColor(mCtx, R.color.blair_grey)); canvas.drawLine( mCircleCenter[0], mTickRectF.top - mTickLength / 2, mCircleCenter[0], mTickRectF.top + mTickLength / 2, mTickPaint); if (i == dBPointer) { mPointerPaint.setColor(getPointerColor(i)); canvas.drawLine( mCircleCenter[0], mPadding, mCircleCenter[0], mTickRectF.top + mTickLength / 2, mPointerPaint); // canvas.drawPath(mTrianglePath, mTrianglePaint); } } else { mTickPaint.setColor(ContextCompat.getColor(mCtx, R.color.tension_grey)); canvas.drawLine( mCircleCenter[0], mTickRectF.top - mTickLength / 2, mCircleCenter[0], mTickRectF.top + mTickLength / 2, mTickPaint); } canvas.restore(); } drawLeapText(canvas, dBPointer + 1); } private void drawLeapText(Canvas canvas, int decibel) { String text = decibel + ""; mTextPaint.setTextSize(mLeapTextSize); mTextPaint.setColor(mBackgroundColor); canvas.drawCircle(mCircleCenter[0], mCircleCenter[1], Math.abs(mTextRectF.bottom - mTextRectF.top) / 2, mTextPaint); mTextPaint.setColor(ColorUtil.getColorReverse(mBackgroundColor)); float textWidth = mTextPaint.measureText(text) * 1.0f; float textHalfHeight = FontMatrixUtils.calcTextHalfHeightPoint(mTextPaint); canvas.drawText(text, mCircleCenter[0] - textWidth / 2, mCircleCenter[1] + textHalfHeight / 2, mTextPaint); mTextPaint.setTextSize(mLeapTextSize / 2); canvas.drawText("dB", mCircleCenter[0] + textWidth / 2, mCircleCenter[1] + textHalfHeight / 2, mTextPaint); } private void drawInnerArc(Canvas canvas) { /* draw colorful gradient */ SweepGradient sweepGradient = new SweepGradient( mCircleCenter[0], mCircleCenter[1], mInnerArcGradientColors, mGalaxyPositions); mInnerArcPaint.setShader(sweepGradient); Path path = new Path(); canvas.save(); canvas.rotate(mStartAngle, mCircleCenter[0], mCircleCenter[1]); path.addArc(mInnerArcRectF, 0, mInnerArcDegree); canvas.drawPath(path, mInnerArcPaint); canvas.restore(); } /** * 重置当前指针并开始动画 * reset current pointer and start anim * @param value */ public void setPointerDecibel(int value) { value = value % mDecibel; float degree = mInnerArcDegree * value / mDecibel; this.mLastValue = mPointerDegree; this.mPointerDegree = degree; startPointerAnim(); // invalidate(); } /** * SweepGradient 颜色值对应的1f:360f(圆的角度) * pointerDegreeRate 计算解释:pointerTick/totalPointer对应了颜色值的渐变, * 因为当前圆可以设置为存在缺口的圆弧, 所以按照比例同成于圆弧 galaxyDegree/360f(圆的角度) * 颜色区间计算:通过上述得到的float值, 去校验当前指针在 positions 的哪个区间, 然后换算当前颜色值RGB */ public int getPointerColor(int pointerTick) { if (mInnerArcGradientColors.length == 1) { return mInnerArcGradientColors[0]; } float degreeRate = mInnerArcDegree / 360f; float pointerDegreeRate = pointerTick * 1f / (mDecibel + 1) * degreeRate; int resSColor = ContextCompat.getColor(mCtx, R.color.white); int resEColor = ContextCompat.getColor(mCtx, R.color.oxygen_green); float rangeColorRate = 0f; for (int i = 0 ; i < mGalaxyPositions.length; i++) { if (i == 0) { resSColor = mInnerArcGradientColors[0]; resEColor = mInnerArcGradientColors[1]; continue; } if (pointerDegreeRate < mGalaxyPositions[i]) { float s = mGalaxyPositions[i-1]; float e = mGalaxyPositions[i]; rangeColorRate = (pointerDegreeRate - s) / (e - s); resSColor = mInnerArcGradientColors[i-1]; resEColor = mInnerArcGradientColors[i]; break; } } return ColorUtil.getCompositeColor(resSColor, resEColor, rangeColorRate); } private ValueAnimator mAnimator; private float mLastValue = 0f; private void startPointerAnim() { long duration = (long) (10 * Math.abs(mPointerDegree - mLastValue)); mAnimator = ValueAnimator.ofFloat(mLastValue, mPointerDegree); mAnimator.setDuration(duration); mAnimator.setInterpolator(new DecelerateInterpolator()); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mPointerDegree = (float) animation.getAnimatedValue(); postInvalidate(); } }); mAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (listener != null) { listener.startTension(); } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); mAnimator.start(); } private ServantListener listener; public void setServantListener(ServantListener listener) { this.listener = listener; } public interface ServantListener { void startTension(); } public int[] getGalaxyColors() { return mInnerArcGradientColors; } /** * 设置颜色的时候同时计算 positions * !不处理任何颜色值设置异常 * set color gradient and automatic calculate positions * not care about the color with positions exceptions, 'cause the os will handle with it */ public void setInnerArcColors(@Nullable int[] colors) { if (colors == null) { colors = new int[] { ContextCompat.getColor(mCtx, R.color.white), ContextCompat.getColor(mCtx, R.color.oxygen_green), ContextCompat.getColor(mCtx, R.color.cinnabar_red) }; } this.mInnerArcGradientColors = colors; setPositions(null); invalidate(); } /* not allow use */ private float[] getGalaxyPositions() { return mGalaxyPositions; } /* not allow use */ /** * calc per color to per position * @param positions */ private void setPositions(@Nullable float[] positions) { float degreeRate = mInnerArcDegree / 360f; if (positions == null) {// set positions average allocation positions = new float[mInnerArcGradientColors.length]; for (int i = 0; i < positions.length; i++) { positions[i] = i * degreeRate / (positions.length - 1); } } else {// use degree rate while reset positions for (int i = 0; i < positions.length; i++) { positions[i] = positions[i] * degreeRate; } } this.mGalaxyPositions = positions; } private float dp2Px(float dp) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, mCtx.getResources().getDisplayMetrics()); } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } }
dyzs/CompassServant
<|start_filename|>src/components/TodoForm.js<|end_filename|> import React from 'react' export default props => <form> <input type='text' className="new-todo" placeholder="What needs to be done?"/> </form>
togo-mentor/cypress-tutorial-build-todo-starter
<|start_filename|>node_modules/sortedlist/test/sample.js<|end_filename|> var SortedList = require("../SortedList"); function test() { // sample : ranges with no overlap var list = SortedList.create( { filter: function(val, pos) { return (this[pos] == null || (this[pos] != null && this[pos][1] < val[0])) && (this[pos+1] == null || (this[pos+1] != null && val[1] < this[pos+1][0])); }, compare: function(a, b) { if (a == null) return -1; if (b == null) return 1; var c = a[0] - b[0]; return (c > 0) ? 1 : (c == 0) ? 0 : -1; } }); var insertResult = list.insert( [152, 222], [33, 53], [48, 96], [928, 1743], [66, 67], [11, 12] ); console.log(insertResult) console.log(list.toArray()); console.assert(list.length, 5); console.assert(Array.isArray(list) === false); console.assert(list instanceof Array); } test(); <|start_filename|>node_modules/sortedlist/test/performance.js<|end_filename|> var SortedList = require("../SortedList"); var compare = function(a, b) { return a.val > b.val ? 1: -1; }; var list = SortedList.create({compare: compare}); console.time("inserting10000") for (var i=0; i<10000; i++) { var obj = {id : i, val: Math.random()}; list.insert(obj); } // list.forEach(function(obj) { // console.log(obj.id, obj.val); // }) console.timeEnd("inserting10000") list = SortedList.create({compare: compare}); console.time("pushing10000") for (var i=0; i<10000; i++) { var obj = {id : i, val: Math.random()}; list.push(obj); } list = list.sort(compare); console.timeEnd("pushing10000") console.time("arr10000") var arr = []; for (var i=0; i<10000; i++) { var obj = {id : i, val: Math.random()}; arr.push(obj); } arr = arr.sort(compare); console.timeEnd("arr10000") console.time("sorting100") for (var i=0; i<100; i++) { var obj = {id : i, val: Math.random()}; arr.push(obj); arr = arr.sort(compare); } arr = arr.sort(function(a, b) { return a.val > b.val ? 1: -1; }); console.timeEnd("sorting100") <|start_filename|>node_modules/sortedlist/test/simple.js<|end_filename|> var SortedList = require("../SortedList"); var list = new SortedList(); list.insert(13, 2, 9, 8, 0); console.log(list.toArray()); var arr = ["foo", "bar", "hoge"]; var strList = new SortedList(arr, { compare: "string" }); console.log(strList.toArray()); var list2= new SortedList([2,1,3,4,5], { resume : true }); console.log("resume (no checking)", list2.toArray())
HosinQM/FineProject
<|start_filename|>src/ads.json<|end_filename|> { "isTesting":true, "rateModel":1, "platforms":[ {"class":"KeymobAdapter","priority":50,"key1":"1"}, {"class":"AdmobAdapter","priority":50,"key1":"<KEY>","key2":"<KEY>"}, {"class":"AmazonAdapter","priority":50,"key1":"amazon ad id"}, {"class":"ChartboostAdapter","priority":50,"key1":"appid","key2":"sign"}, {"class":"InmobiAdapter","priority":50,"key1":"property id","key2":"banner id","key3":"interstitial id"}, {"class":"IadAdapter","priority":50,"key1":"appid"}, {"class":"BaiduAdapter","priority":50,"key1":"appid","key2":"bannerid","param":"{\"interstitialID\":\"interstitial ID\",\"videoID\":\"video ID\"}"}, {"class":"GDTAdapter","priority":10,"key1":"appid","key2":"banner id","param":"{\"interstitialID\":\"interstitial ID\",\"appWallID\":\"app Wall ID\"}"}, {"class":"AdcolonyAdapter","priority":10,"key1":"appid","key2":"zone interstitia","param":"video zone"}, {"class":"MMediaAdapter","priority":50,"key1":"banner id","key2":"Interstitial ID"} ] }
keymobdev/Air-ANE-Keymob
<|start_filename|>avrocli/parse.go<|end_filename|> package main import ( "fmt" "io/ioutil" "os" "strings" "github.com/sadlil/go-avro-phonetic" "github.com/spf13/cobra" ) func NewParseCmd() *cobra.Command { var filePath string cmd := &cobra.Command{ Use: "parse", Short: "file or text to parse", Run: func(cmd *cobra.Command, args []string) { if cmd.Flag("file").Changed { if filePath != "" { parseFile(filePath) return } } if len(args) > 0 { text := strings.Join(args, " ") parse(text) } }, } cmd.Flags().StringVarP(&filePath, "file", "f", "", "file location to parse") return cmd } func parse(text string) { text, err := avro.Parse(text) if err != nil { fmt.Fprintln(os.Stderr, "Failed to parse text, error: " + err.Error()) return } fmt.Fprintln(os.Stdout, text) } func parseFile(filePath string) { data, err := ioutil.ReadFile(filePath) if err != nil { fmt.Fprintln(os.Stderr, "Failed to parse file, error: " + err.Error()) return } text, err := avro.Parse(string(data)) if err != nil { fmt.Fprintln(os.Stderr, "Failed to parse text, error: " + err.Error()) return } destFileName := filePath[:strings.LastIndex(filePath, ".")] + ".bn" + filePath[strings.LastIndex(filePath, "."):] err = ioutil.WriteFile(destFileName, []byte(text), os.ModePerm) if err != nil { fmt.Fprintln(os.Stderr, "Failed to write text to the destination file, error: " + err.Error()) } }
sadlil/go-avro-phonetic
<|start_filename|>Makefile<|end_filename|> .PHONY: install_deps install_deps: # TODO: Use the Python zipfile module so we can remove this dependency. zip --version > /dev/null || { echo 'Error: Please install the "zip" utility using your system package manager (e.g. apt)'; exit 1; } pip install -r requirements.txt --user .PHONY: install_deps_venv install_deps_venv: pip install -r requirements.txt .PHONY: test test: install_deps test_inner .PHONY: test_venv test_venv: install_deps_venv test_inner .PHONY: test_inner test_inner: cp __init__.py chinese_prestudy.py python -m pytest -vv tests/ package.ankiaddon: __init__.py package.py ./package.py .PHONY: package package: package.ankiaddon .PHONY: install install: package.ankiaddon rm -rf package mkdir package cp package.ankiaddon package cd package && unzip package.ankiaddon rm package/package.ankiaddon rm -rf "${HOME}"/.local/share/Anki2/addons21/chinese_prestudy cp -r package "${HOME}"/.local/share/Anki2/addons21/chinese_prestudy
Damien-75/Chinese-Prestudy
<|start_filename|>tests/vendor/cget/pkg/pqrs-org__cpp-string/install/include/pqrs/string/trim.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2018. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <algorithm> #include <cctype> #include <string_view> #include <utf8cpp/utf8.h> namespace pqrs { namespace string { inline void trim_left(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) { return !std::isspace(c); })); } inline void trim_right(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int c) { return !std::isspace(c); }) .base(), s.end()); } inline void trim(std::string& s) { trim_left(s); trim_right(s); } inline std::string trim_left_copy(const std::string_view& s) { std::string result(s); trim_left(result); return result; } inline std::string trim_right_copy(const std::string_view& s) { std::string result(s); trim_right(result); return result; } inline std::string trim_copy(const std::string_view& s) { std::string result(s); trim(result); return result; } inline void trim_invalid_right(std::string& s) { auto pos = utf8::find_invalid(s); if (pos != std::string::npos) { s = s.substr(0, pos); } } inline std::string trim_invalid_right_copy(const std::string_view& s) { std::string result(s); trim_invalid_right(result); return result; } } // namespace string } // namespace pqrs <|start_filename|>tests/vendor/cget/pkg/pqrs-org__cpp-json/install/include/pqrs/json/unmarshal_error.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <stdexcept> namespace pqrs { namespace json { class unmarshal_error : public std::runtime_error { public: unmarshal_error(const std::string& message) : std::runtime_error(message) { } }; } // namespace json } // namespace pqrs <|start_filename|>tests/vendor/cget/pkg/pqrs-org__cpp-json/install/include/pqrs/json.hpp<|end_filename|> #pragma once // pqrs::json v1.3 // (C) Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include "json/marshal_error.hpp" #include "json/unmarshal_error.hpp" #include <nlohmann/json.hpp> #include <optional> #include <pqrs/string.hpp> namespace pqrs { namespace json { template <typename T> inline std::optional<T> find(const nlohmann::json& json, const std::string& key) { auto it = json.find(key); if (it != std::end(json)) { try { return it.value().get<T>(); } catch (std::exception&) { } } return std::nullopt; } inline std::optional<nlohmann::json::const_iterator> find_array(const nlohmann::json& json, const std::string& key) { auto it = json.find(key); if (it != std::end(json)) { if (it->is_array()) { return it; } } return std::nullopt; } inline std::optional<nlohmann::json::const_iterator> find_object(const nlohmann::json& json, const std::string& key) { auto it = json.find(key); if (it != std::end(json)) { if (it->is_object()) { return it; } } return std::nullopt; } inline std::optional<nlohmann::json::const_iterator> find_json(const nlohmann::json& json, const std::string& key) { auto it = json.find(key); if (it != std::end(json)) { return it; } return std::nullopt; } inline nlohmann::json find_copy(const nlohmann::json& json, const std::string& key, const nlohmann::json& fallback_value) { auto it = json.find(key); if (it != std::end(json)) { return it.value(); } return fallback_value; } // // type checks // inline std::string dump_for_error_message(const nlohmann::json& json) { return string::truncate(json.dump(), 256); } inline void requires_array(const nlohmann::json& json, const std::string& error_message_name) { using namespace std::string_literals; if (!json.is_array()) { throw unmarshal_error(error_message_name + " must be array, but is `"s + dump_for_error_message(json) + "`"s); } } inline void requires_boolean(const nlohmann::json& json, const std::string& error_message_name) { using namespace std::string_literals; if (!json.is_boolean()) { throw unmarshal_error(error_message_name + " must be boolean, but is `"s + dump_for_error_message(json) + "`"s); } } inline void requires_number(const nlohmann::json& json, const std::string& error_message_name) { using namespace std::string_literals; if (!json.is_number()) { throw unmarshal_error(error_message_name + " must be number, but is `"s + dump_for_error_message(json) + "`"s); } } inline void requires_object(const nlohmann::json& json, const std::string& error_message_name) { using namespace std::string_literals; if (!json.is_object()) { throw unmarshal_error(error_message_name + " must be object, but is `"s + dump_for_error_message(json) + "`"s); } } inline void requires_string(const nlohmann::json& json, const std::string& error_message_name) { using namespace std::string_literals; if (!json.is_string()) { throw unmarshal_error(error_message_name + " must be string, but is `"s + dump_for_error_message(json) + "`"s); } } } // namespace json } // namespace pqrs <|start_filename|>include/pqrs/osx/frontmost_application_monitor/monitor.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) // `pqrs::osx::frontmost_application_monitor` can be used safely in a multi-threaded environment. #include "application.hpp" #include "impl/objc.h" #include <nod/nod.hpp> #include <pqrs/dispatcher.hpp> namespace pqrs { namespace osx { namespace frontmost_application_monitor { class monitor final : public dispatcher::extra::dispatcher_client { public: // Signals (invoked from the dispatcher thread) nod::signal<void(std::shared_ptr<application>)> frontmost_application_changed; // Methods monitor(const monitor&) = delete; monitor(std::weak_ptr<dispatcher::dispatcher> weak_dispatcher) : dispatcher_client(weak_dispatcher), monitor_(nullptr) { } virtual ~monitor(void) { detach_from_dispatcher([this] { stop(); }); } void async_start(void) { enqueue_to_dispatcher([this] { if (monitor_) { return; } pqrs_osx_frontmost_application_monitor_initialize(&monitor_, static_cpp_callback, this); }); } void async_stop(void) { enqueue_to_dispatcher([this] { stop(); }); } private: void stop(void) { if (!monitor_) { return; } pqrs_osx_frontmost_application_monitor_terminate(&monitor_); monitor_ = nullptr; } static void static_cpp_callback(const char* bundle_identifier, const char* file_path, void* context) { auto m = reinterpret_cast<monitor*>(context); if (m) { m->cpp_callback(bundle_identifier, file_path); } } void cpp_callback(const char* bundle_identifier, const char* file_path) { auto application_ptr = std::make_shared<application>(); if (bundle_identifier) { application_ptr->set_bundle_identifier(bundle_identifier); } if (file_path) { application_ptr->set_file_path(file_path); } enqueue_to_dispatcher([this, application_ptr] { frontmost_application_changed(application_ptr); }); } pqrs_osx_frontmost_application_monitor_objc* monitor_; }; } // namespace frontmost_application_monitor } // namespace osx } // namespace pqrs <|start_filename|>tests/vendor/include/pqrs/string/trim.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2018. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <algorithm> #include <cctype> #include <string_view> namespace pqrs { namespace string { inline void trim_left(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) { return !std::isspace(c); })); } inline void trim_right(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int c) { return !std::isspace(c); }) .base(), s.end()); } inline void trim(std::string& s) { trim_left(s); trim_right(s); } inline std::string trim_left_copy(const std::string_view& s) { std::string result(s); trim_left(result); return result; } inline std::string trim_right_copy(const std::string_view& s) { std::string result(s); trim_right(result); return result; } static inline std::string trim_copy(const std::string_view& s) { std::string result(s); trim(result); return result; } } // namespace string } // namespace pqrs <|start_filename|>include/pqrs/osx/frontmost_application_monitor/impl/objc.h<|end_filename|> #pragma once // (C) Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #ifdef __cplusplus extern "C" { #endif // Do not use these functions directly. typedef void pqrs_osx_frontmost_application_monitor_objc; typedef void (*pqrs_osx_frontmost_application_monitor_callback)(const char* bundle_identifier, const char* file_path, void* context); bool pqrs_osx_frontmost_application_monitor_initialize(pqrs_osx_frontmost_application_monitor_objc** monitor, pqrs_osx_frontmost_application_monitor_callback callback, void* context); void pqrs_osx_frontmost_application_monitor_terminate(pqrs_osx_frontmost_application_monitor_objc** monitor); #ifdef __cplusplus } #endif <|start_filename|>tests/vendor/cget/pkg/pqrs-org__objc-weakify/install/include/pqrs/weakify.h<|end_filename|> #pragma once // pqrs::weakify v1.0 // Created by <NAME> on 2011-05-04. // Copyright (C) 2012 <NAME>. // Released under the MIT license. // 2019 <NAME> // Copied @weakify and @strongify from libextobjc and modified them. // https://github.com/jspahrsummers/libextobjc/blob/master/extobjc/EXTScope.h #import <Cocoa/Cocoa.h> #define weakify(VAR) \ autoreleasepool {} \ __weak __typeof(VAR) VAR##_weak_ = VAR; #define strongify(VAR) \ autoreleasepool {} \ _Pragma("clang diagnostic push"); \ _Pragma("clang diagnostic ignored \"-Wshadow\""); \ __strong typeof(VAR) VAR = VAR##_weak_; \ _Pragma("clang diagnostic pop"); <|start_filename|>tests/vendor/include/nlohmann/detail/macro_unscope.hpp<|end_filename|> #pragma once // restore GCC/clang diagnostic settings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_ASSERT #undef JSON_INTERNAL_CATCH #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_HAS_CPP_14 #undef JSON_HAS_CPP_17 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #undef JSON_EXPLICIT #include <nlohmann/thirdparty/hedley/hedley_undef.hpp> <|start_filename|>tests/vendor/include/pqrs/json/marshal_error.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <stdexcept> namespace pqrs { namespace json { class marshal_error : public std::runtime_error { public: marshal_error(const std::string& message) : std::runtime_error(message) { } }; } // namespace json } // namespace pqrs <|start_filename|>tests/vendor/include/utf8cpp/utf8/cpp11.h<|end_filename|> // Copyright 2018 <NAME> /* Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1 #define UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1 #include "checked.h" #include <string> namespace utf8 { inline void append(char32_t cp, std::string& s) { append(uint32_t(cp), std::back_inserter(s)); } inline std::string utf16to8(const std::u16string& s) { std::string result; utf16to8(s.begin(), s.end(), std::back_inserter(result)); return result; } inline std::u16string utf8to16(const std::string& s) { std::u16string result; utf8to16(s.begin(), s.end(), std::back_inserter(result)); return result; } inline std::string utf32to8(const std::u32string& s) { std::string result; utf32to8(s.begin(), s.end(), std::back_inserter(result)); return result; } inline std::u32string utf8to32(const std::string& s) { std::u32string result; utf8to32(s.begin(), s.end(), std::back_inserter(result)); return result; } inline std::size_t find_invalid(const std::string& s) { std::string::const_iterator invalid = find_invalid(s.begin(), s.end()); return (invalid == s.end()) ? std::string::npos : (invalid - s.begin()); } inline bool is_valid(const std::string& s) { return is_valid(s.begin(), s.end()); } inline std::string replace_invalid(const std::string& s, char32_t replacement) { std::string result; replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement); return result; } inline std::string replace_invalid(const std::string& s) { std::string result; replace_invalid(s.begin(), s.end(), std::back_inserter(result)); return result; } inline bool starts_with_bom(const std::string& s) { return starts_with_bom(s.begin(), s.end()); } } // namespace utf8 #endif // header guard <|start_filename|>tests/vendor/cget/pkg/pqrs-org__cpp-string/install/include/pqrs/string/truncate.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2020. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <sstream> #include <string_view> #include <utf8cpp/utf8.h> namespace pqrs { namespace string { inline std::string truncate(const std::string_view& s, size_t length, const std::string_view& placeholder = "...") { // Replace invalid character to ensure no invalid characters until the end of string before create substring. auto valid_string = utf8::replace_invalid(s); if (valid_string.length() <= length || length <= placeholder.length()) { return trim_invalid_right_copy(valid_string.substr(0, length)); } else { // Append placeholder std::stringstream ss; ss << trim_invalid_right_copy(valid_string.substr(0, length - placeholder.length())) << placeholder; return ss.str(); } } } // namespace string } // namespace pqrs <|start_filename|>tests/vendor/include/pqrs/string/predicate.hpp<|end_filename|> #pragma once // (C) Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <string_view> namespace pqrs { namespace string { // Polyfill of std::string_view::starts_with (C++20) inline bool starts_with(const std::string_view& s, const std::string_view& prefix) { return s.compare(0, prefix.size(), prefix) == 0; } // Polyfill of std::string_view::ends_with (C++20) inline bool ends_with(const std::string_view& s, const std::string_view& suffix) { if (s.size() < suffix.size()) { return false; } return s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; } } // namespace string } // namespace pqrs
pqrs-org/cpp-osx-frontmost_application_monitor
<|start_filename|>service.go<|end_filename|> package rest import "net/http" // Service holds application scope broker, logger and metrics adapters type Service struct { Broker Broker Logger Logger Metrics Metrics } // UseBroker - set the desired broker func (s *Service) UseBroker(b Broker) { s.Broker = b } // UseLogger - set the desired logger func (s *Service) UseLogger(l Logger) { s.Logger = l } // UseMetrics - set the desired metrics func (s *Service) UseMetrics(m Metrics) { s.Metrics = m } // Broker is an event stream adapter to notify other microservices of state changes type Broker interface { Publish(event string, v interface{}) error } // Logger is an leveled logging interface type Logger interface { Error(e error) } // Metrics is an adapter to track application performance metrics type Metrics interface { Incr(stat string, count int64) error Timing(stat string, delta int64) error NewTimer(stat string) func() } // Event - type Event struct { Request *http.Request Response *Response } // NewService - func NewService() *Service { return &Service{} }
dndungu/morest
<|start_filename|>tests/Flywheel/FlywheelTest.js<|end_filename|> const { makeComptroller, makeCToken } = require('../Utils/Compound'); const { etherExp, etherDouble, etherUnsigned } = require('../Utils/Ethereum'); async function compAccrued(comptroller, user) { return etherUnsigned(await call(comptroller, 'compAccrued', [user])); } async function compBalance(comptroller, user) { return etherUnsigned(await call(comptroller.comp, 'balanceOf', [user])) } describe('Flywheel', () => { let root, a1, a2, a3, accounts; let comptroller, cLOW, cREP, cZRX, cEVIL; beforeEach(async () => { let interestRateModelOpts = {borrowRate: 0.000001}; [root, a1, a2, a3, ...accounts] = saddle.accounts; comptroller = await makeComptroller(); cLOW = await makeCToken({comptroller, supportMarket: true, underlyingPrice: 1, interestRateModelOpts}); cREP = await makeCToken({comptroller, supportMarket: true, underlyingPrice: 2, interestRateModelOpts}); cZRX = await makeCToken({comptroller, supportMarket: true, underlyingPrice: 3, interestRateModelOpts}); cEVIL = await makeCToken({comptroller, supportMarket: false, underlyingPrice: 3, interestRateModelOpts}); }); it('should be able to claim rewards for supplier', async () => { const mkt = cREP; await send(comptroller.comp, 'transfer', [comptroller._address, etherUnsigned(50e18)], {from: root}); await send(mkt, "harnessSetBalance", [a1, etherUnsigned(5e18)]); await send(comptroller, "setCompSupplyState", [mkt._address, etherDouble(6), 10]); await send(comptroller, "setCompSupplierIndex", [mkt._address, a1, etherDouble(2)]) /* supplierAmount = 5e18 deltaIndex = marketStoredIndex - userStoredIndex = 6e36 - 2e36 = 4e36 suppliedAccrued+= supplierTokens * deltaIndex / 1e36 = 5e18 * 4e36 / 1e36 = 20e18 */ await send(comptroller, "claimComp", [a1]); expect(await compAccrued(comptroller, a1)).toEqualNumber(0); expect(await compBalance(comptroller, a1)).toEqualNumber(20e18); }); it('should be able to claim rewards for borrower', async () => { const mkt = cREP; await send(comptroller.comp, 'transfer', [comptroller._address, etherUnsigned(50e18)], {from: root}); await send(mkt, "harnessSetAccountBorrows", [a1, etherUnsigned(5e18), etherExp(1)]); await send(comptroller, "setCompBorrowState", [mkt._address, etherDouble(6), 10]); await send(comptroller, "setCompBorrowerIndex", [mkt._address, a1, etherDouble(1)]); /* 100 delta blocks, 10e18 origin total borrows, 0.5e18 borrowSpeed => 6e18 compBorrowIndex this tests that an acct with half the total borrows over that time gets 25e18 COMP borrowerAmount = borrowBalance * 1e18 / borrow idx = 5e18 * 1e18 / 1e18 = 5e18 deltaIndex = marketStoredIndex - userStoredIndex = 6e36 - 1e36 = 5e36 borrowerAccrued= borrowerAmount * deltaIndex / 1e36 = 5e18 * 5e36 / 1e36 = 25e18 */ await send(comptroller, "claimComp", [a1]); expect(await compAccrued(comptroller, a1)).toEqualNumber(0); expect(await compBalance(comptroller, a1)).toEqualNumber(25e18); }); });
antlia-io/compound-protocol
<|start_filename|>__fixtures__/say-#-hi.js<|end_filename|> console.log('Hello remark-code-import!'); console.log('This is another line...'); console.log('This is the last line'); console.log('Oops, here is another'); <|start_filename|>gatsby/index.js<|end_filename|> const toGatsbyRemarkPlugin = require('to-gatsby-remark-plugin'); const codeImport = require('../'); module.exports = toGatsbyRemarkPlugin(codeImport);
forbesmyester/remark-code-import
<|start_filename|>recycleview/src/main/java/com/hejunlin/tvsample/DetailListActivity.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.hejunlin.tvsample.widget.MetroViewBorderImpl; import com.hejunlin.tvsample.widget.AutoLayoutManager; import java.io.IOException; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by hejunlin on 2015/10/16. * blog: http://blog.csdn.net/hejjunlin */ public class DetailListActivity extends Activity { private MetroViewBorderImpl mMetroViewBorderImpl; private static final String TAG = DetailListActivity.class.getSimpleName(); private static final String URL = "http://gvod.video.51togic.com/api/v1/programs?mobile=false&version_code=102&device_id=419000000000000000005cc6d0b7e7e80000000000000000&city=%E5%8C%97%E4%BA%AC&vip=0&show_top_recommend=0"; private final List<DetailInfo> mDetailInfoList = new CopyOnWriteArrayList<>(); private OnDataFinishedListener mOnDataFinishedListener; public static interface StrProcessor { void OnParserJsonString(String line); } public static interface OnDataFinishedListener { void onPerformData(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detaillist); mMetroViewBorderImpl = new MetroViewBorderImpl(this); mMetroViewBorderImpl.setBackgroundResource(R.drawable.border_color); loadRecyclerViewMenuItem(); final StrProcessor parser = new StrProcessor() { @Override public void OnParserJsonString(String json) { parseJson(json); } }; mOnDataFinishedListener = new OnDataFinishedListener() { @Override public void onPerformData() { loadDataForRecyclerViewGridLayout(); } }; HttpUtils.asyncGet(URL, new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, ">> onFailure : e" + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { return; } try { String content = response.body().string(); Log.d(TAG, "detailInfo : content" + content); parser.OnParserJsonString(content); } catch (IOException e) { e.printStackTrace(); } } }); } private void parseJson(String content) { JSONObject jason = JSONObject.parseObject(content); JSONArray data = jason.getJSONArray("items"); int totalCount = Integer.parseInt(jason.getString("count")); mDetailInfoList.clear(); for (int i = 0; i < data.size(); i++) { DetailInfo info = new DetailInfo(); JSONObject jsonObj = (JSONObject) data.get(i); String infotext = jsonObj.getString("infotext"); String url = jsonObj.getString("poster"); String title = jsonObj.getString("title"); info.setPoster(url); info.setInfotext(infotext); info.setTitle(title); mDetailInfoList.add(info); Log.d(TAG, "parseJson mDetailInfoList " + mDetailInfoList.size()); } for (int j = 0; j < mDetailInfoList.size(); j++) { Log.d(TAG, "parseJson mDetailInfoList : " + j + "content : " + mDetailInfoList.get(j).toString()); } runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, ">> performData"); mOnDataFinishedListener.onPerformData(); } }); } private void loadRecyclerViewMenuItem() { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ry_menu_item); GridLayoutManager layoutManager = new GridLayoutManager(this, 1); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); recyclerView.setFocusable(false); mMetroViewBorderImpl.attachTo(recyclerView); createOptionItemData(recyclerView, R.layout.detail_menu_item); } private void loadDataForRecyclerViewGridLayout() { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ry_detail_list); GridLayoutManager gridlayoutManager = new AutoLayoutManager(this, 4); gridlayoutManager.setOrientation(GridLayoutManager.VERTICAL); recyclerView.setLayoutManager(gridlayoutManager); recyclerView.setFocusable(false); mMetroViewBorderImpl.attachTo(recyclerView); createData(recyclerView, R.layout.detail_list_item); } private void createData(RecyclerView recyclerView, int id) { MyAdapter adapter = new MyAdapter(this, mDetailInfoList, id); recyclerView.setAdapter(adapter); recyclerView.scrollToPosition(0); } private void createOptionItemData(RecyclerView recyclerView, int id) { OptionItemAdapter adapter = new OptionItemAdapter(this, id); recyclerView.setAdapter(adapter); recyclerView.scrollToPosition(0); } } <|start_filename|>metro/src/main/java/com/hejunlin/tvsample/widget/MetroItemFrameLayout.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.FrameLayout; /** * Created by hejunlin on 2015/7/19. * blog: http://blog.csdn.net/hejjunlin */ public class MetroItemFrameLayout extends FrameLayout implements IMetroItemRound { private MetroItemRound mMetroItemRound; public MetroItemFrameLayout(Context context) { super(context); init(context, null, 0); } public MetroItemFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public MetroItemFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, int defStyle) { mMetroItemRound = new MetroItemRound(this, context, attrs, defStyle); setWillNotDraw(false); } @Override public void draw(Canvas canvas) { mMetroItemRound.draw(canvas); } @Override public MetroItemRound getRoundImpl() { return mMetroItemRound; } @Override public void drawRadious(Canvas canvas) { super.draw(canvas); } } <|start_filename|>recycleview/src/main/java/com/hejunlin/tvsample/ImageUtils.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample; import android.content.Context; import android.content.res.Resources; import android.graphics.Point; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import com.squareup.picasso.Picasso; /** * Created by hejunlin on 2015/10/16. * blog: http://blog.csdn.net/hejjunlin */ public class ImageUtils { public static final float VER_POSTER_RATIO = 0.73f; public static final float HOR_POSTER_RATIO = 1.5f; public static void displayImage(ImageView view, String picUrl, int width, int height) { if (picUrl != null && !picUrl.isEmpty() && view != null && height > 0 && width > 0) { if (height > width) Picasso.with(view.getContext()).load(picUrl).error(R.drawable.ic_vip_movie).centerCrop().resize(width, height).into(view); else Picasso.with(view.getContext()).load(picUrl).error(R.drawable.ic_vip_movie).centerCrop().resize(width, height).into(view); } } public static void displayImage(ImageView view, String picUrl) { if (picUrl != null && !picUrl.isEmpty() && view != null) Picasso.with(view.getContext()).load(picUrl).into(view); } public static void fixHorPosterRatio(final ImageView image) { image.post(new Runnable() { @Override public void run() { int width = image.getWidth(); int height = Math.round((float) width / HOR_POSTER_RATIO); image.getLayoutParams().height = height; image.setVisibility(View.VISIBLE); } }); } public static void fixVerPosterRatio(final ImageView image) { image.post(new Runnable() { @Override public void run() { int width = image.getWidth(); int height = Math.round((float) width / VER_POSTER_RATIO); image.getLayoutParams().height = height; image.setVisibility(View.VISIBLE); } }); } public static Point getGridVerPosterSize(Context mContext, int columns) { int width = getScreenWidthPixels(mContext) / columns; width = width - 2 * mContext.getResources().getDimensionPixelSize(R.dimen.margin_small); int height = Math.round((float) width / VER_POSTER_RATIO); Point point = new Point(); point.x = width; point.y = height; return point; } public static Point getGridHorPosterSize(Context mContext, int columns) { int width = getScreenWidthPixels(mContext) / columns; width = width - 2 * mContext.getResources().getDimensionPixelSize(R.dimen.margin_small); int height = Math.round((float) width / HOR_POSTER_RATIO); Point point = new Point(); point.x = width; point.y = height; return point; } public static int getScreenWidthPixels(Context mContext) { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; return width; } public static int getScreenHeightPixels(Context mContext) { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); int height = size.y; return height; } public static float convertPixelsToDp(float px) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); float dp = px / (metrics.densityDpi / 160f); return Math.round(dp); } public static float convertDpToPixel(float dp) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); float px = dp * (metrics.densityDpi / 160f); return Math.round(px); } } <|start_filename|>recycleview/src/main/java/com/hejunlin/tvsample/AppManager.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import com.google.gson.Gson; import java.io.File; import okhttp3.Cache; import okhttp3.OkHttpClient; /** * Created by hejunlin on 2016/9/16. * blog: http://blog.csdn.net/hejjunlin */ public class AppManager extends Application { private static Context mContext; private static OkHttpClient mHttpClient; private static Gson mGson; private static final long SIZE_OF_HTTP_CACHE = 10 * 1024 * 1024; @Override public void onCreate() { super.onCreate(); mContext = this; mHttpClient = new OkHttpClient(); mGson = new Gson(); initHttpClient(mHttpClient, mContext); } private void initHttpClient(OkHttpClient client, Context context) { File httpCacheDirectory = context.getCacheDir(); Cache httpResponseCache = new Cache(httpCacheDirectory, SIZE_OF_HTTP_CACHE); // try { // httpResponseCache = // } catch (IOException e) { // Log.e("Retrofit", "Could not create http cache", e); // } // client.setCache(httpResponseCache); } public static Resources getResource() { return mContext.getResources(); } public static Context getContext() { return mContext; } public static OkHttpClient getHttpClient() { return mHttpClient; } public static Gson getGson() { return mGson; } public static String getIMEI() { try { TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String IMEI_Number = telephonyManager.getDeviceId(); if ((IMEI_Number != null) && (IMEI_Number.length() > 0)) { return IMEI_Number; } } catch (Exception localException) { localException.printStackTrace(); } return null; } public static boolean checkPermission(Context paramContext, String paramString) { return paramContext.checkCallingOrSelfPermission(paramString) == PackageManager.PERMISSION_GRANTED; } public static boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } public static boolean isNetworkMobile() { ConnectivityManager conMan = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); if (conMan.getNetworkInfo(0) != null) { final NetworkInfo.State mobile = conMan.getNetworkInfo(0).getState(); if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) return true; else return false; } else return false; } public static boolean isNetworkWifi() { ConnectivityManager conMan = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); if (conMan.getNetworkInfo(1) != null) { final NetworkInfo.State wifi = conMan.getNetworkInfo(1).getState(); if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) return true; else return false; } else return false; } /** * 读取application 节点 meta-data 信息 */ public static String buildChannel() { try { ApplicationInfo appInfo = mContext.getPackageManager() .getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA); String mTag = appInfo.metaData.getString("UMENG_CHANNEL"); return mTag; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } } <|start_filename|>recycleview/src/main/java/com/hejunlin/tvsample/HttpUtils.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample; import android.app.Activity; import android.os.Handler; import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import okhttp3.Response; /** * Created by hejunlin on 2015/10/16. * blog: http://blog.csdn.net/hejjunlin */ public class HttpUtils { private static final String REQUEST_TAG = HttpUtils.class.getSimpleName(); private static final String USER_AGENT = "Python-urllib/3.4"; public static Request buildRequest(String url) { if (AppManager.isNetworkAvailable()) { int maxAge = 60 * 60 * 24; // read from cache for 1 day Request request = new Request.Builder() .tag(REQUEST_TAG) .header("User-agent", USER_AGENT) .url(url) .build(); return request; } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale Request request = new Request.Builder() .tag(REQUEST_TAG) .header("User-agent", USER_AGENT) .url(url) .build(); return request; } } public static void asyncGet(String url, Activity activity, Callback callback) { Request request = buildRequest(url); asyncGet(request, activity, callback); } public static String syncGet(String url) { Request request = buildRequest(url); Log.d(REQUEST_TAG, "sync request Url: " + request.toString()); try { Response response = AppManager.getHttpClient().newCall(request).execute(); if (response.code() == 200) { String ret = new String(response.body().bytes(), "utf-8"); return ret; } } catch (IOException e) { e.printStackTrace(); } return null; } public static void asyncGet(String url, Callback callback) { Request request = buildRequest(url); asyncGet(request, callback); } public static void asyncGet(Request request, Callback callback) { Log.d(REQUEST_TAG, "async request Url: " + request.toString()); AppManager.getHttpClient().newCall(request).enqueue(callback); } public static void asyncGet(Request request, final Activity activity, final Callback callback) { Log.d(REQUEST_TAG, "async request Url: " + request.toString()); AppManager.getHttpClient().newCall(request).enqueue(new Callback() { Handler mainHandler = new Handler(activity.getMainLooper()); @Override public void onFailure(final Call call, final IOException e) { mainHandler.post(new Runnable() { @Override public void run() { callback.onFailure(call, e); } }); } @Override public void onResponse(final Call call, final Response response) throws IOException { mainHandler.post(new Runnable() { @Override public void run() { try { callback.onResponse(call, response); } catch (IOException e) { e.printStackTrace(); } } }); } }); } } <|start_filename|>recycleview/src/main/java/com/hejunlin/tvsample/widget/AutoLayoutManager.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample.widget; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; /** * Created by hejunlin on 2015/10/16. * blog: http://blog.csdn.net/hejjunlin */ public class AutoLayoutManager extends GridLayoutManager { public AutoLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public AutoLayoutManager(Context context, int spanCount) { super(context, spanCount); } public AutoLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) { super(context, spanCount, orientation, reverseLayout); } @Override public View onFocusSearchFailed(View focused, int focusDirection, RecyclerView.Recycler recycler, RecyclerView.State state) { // Need to be called in order to layout new row/column View nextFocus = super.onFocusSearchFailed(focused, focusDirection, recycler, state); if (nextFocus == null) { return null; } int fromPos = getPosition(focused); int nextPos = getNextViewPos(fromPos, focusDirection); return findViewByPosition(nextPos); } /** * Manually detect next view to focus. * * @param fromPos from what position start to seek. * @param direction in what direction start to seek. Your regular * {@code View.FOCUS_*}. * @return adapter position of next view to focus. May be equal to * {@code fromPos}. */ protected int getNextViewPos(int fromPos, int direction) { int offset = calcOffsetToNextView(direction); if (hitBorder(fromPos, offset)) { //return fromPos; } return fromPos + offset; } /** * Calculates position offset. * * @param direction regular {@code View.FOCUS_*}. * @return position offset according to {@code direction}. */ protected int calcOffsetToNextView(int direction) { int spanCount = getSpanCount(); int orientation = getOrientation(); if (orientation == VERTICAL) { switch (direction) { case View.FOCUS_DOWN: return spanCount; case View.FOCUS_UP: return -spanCount; case View.FOCUS_RIGHT: return 1; case View.FOCUS_LEFT: return -1; } } else if (orientation == HORIZONTAL) { switch (direction) { case View.FOCUS_DOWN: return 1; case View.FOCUS_UP: return -1; case View.FOCUS_RIGHT: return spanCount; case View.FOCUS_LEFT: return -spanCount; } } return 0; } /** * Checks if we hit borders. * * @param from from what position. * @param offset offset to new position. * @return {@code true} if we hit border. */ private boolean hitBorder(int from, int offset) { int spanCount = getSpanCount(); if (Math.abs(offset) == 1) { int spanIndex = from % spanCount; int newSpanIndex = spanIndex + offset; return newSpanIndex < 0 || newSpanIndex >= spanCount; } else { int newPos = from + offset; return newPos < 0 || newPos >= spanCount; } } } <|start_filename|>recycleview/src/main/java/com/hejunlin/tvsample/DetailInfo.java<|end_filename|> /* * Copyright (C) 2016 hejunlin <<EMAIL>> * Github:https://github.com/hejunlin2013/TVSample * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.hejunlin.tvsample; import com.google.gson.annotations.Expose; /** * Created by hejunlin on 2016/10/15. * blog: http://blog.csdn.net/hejjunlin */ public class DetailInfo { @Expose private String title; @Expose private String poster; @Expose private String infotext; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getInfotext() { return infotext; } public void setInfotext(String infotext) { this.infotext = infotext; } public String getPoster() { return poster; } public void setPoster(String poster) { this.poster = poster; } @Override public String toString() { return "DetailInfo{" + "mTitle='" + title + '\'' + ", mTextDesc=" + infotext + ", mPostImageUrl='" + poster + '\'' + '}'; } }
dyjm2012/admin
<|start_filename|>hacs.json<|end_filename|> { "name": "Office 365 Integration", "homeassistant": "0.103", "persistent_directory": ".O365-token-cache", "render_readme": true } <|start_filename|>custom_components/o365/manifest.json<|end_filename|> { "domain": "o365", "name": "Office 365 Calendar", "documentation": "https://github.com/PTST/O365Calendar-HomeAssistant", "dependencies": ["configurator", "http"], "codeowners": ["@PTST"], "requirements": ["O365==2.0.9", "BeautifulSoup4==4.8.2"] }
mshish/O365-HomeAssistant
<|start_filename|>func/helpers/jwt-helpers.js<|end_filename|> const jwt = require("jsonwebtoken"); function createJwt(data, duration) { const options = { issuer: 'ban-appeals-backend' }; if (duration) { options.expiresIn = duration; } return jwt.sign(data, process.env.JWT_SECRET, options); } function decodeJwt(token) { return jwt.verify(token, process.env.JWT_SECRET); } module.exports = { createJwt, decodeJwt };
Towsif12/discord-ban-appeals
<|start_filename|>version/version_test.go<|end_filename|> /* Copyright 2020 The Flux authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package version import ( "testing" ) func TestParseVersion(t *testing.T) { tests := []struct { version string err bool }{ {"v1.2.3", false}, {"v1.0", true}, {"v1", true}, {"v1.2.beta", true}, {"v1.2-5", true}, {"v1.2-beta.5", true}, {"\nv1.2", true}, {"v1.2.0-x.Y.0+metadata", false}, {"v1.2.0-x.Y.0+metadata-width-hypen", false}, {"v1.2.3-rc1-with-hypen", false}, {"v1.2.3.4", true}, } for _, tc := range tests { _, err := ParseVersion(tc.version) if tc.err && err == nil { t.Fatalf("expected error for version: %s", tc.version) } else if !tc.err && err != nil { t.Fatalf("error for version %s: %s", tc.version, err) } } }
defreng/pkg
<|start_filename|>src/main/java/com/github/ghthou/googleauthenticator/GoogleAuthenticatorIntegrationApplication.java<|end_filename|> package com.github.ghthou.googleauthenticator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.env.ConfigurableEnvironment; import lombok.extern.slf4j.Slf4j; @Slf4j @SpringBootApplication public class GoogleAuthenticatorIntegrationApplication { public static void main(String[] args) { ConfigurableEnvironment env = SpringApplication .run(GoogleAuthenticatorIntegrationApplication.class, args).getEnvironment(); String port = env.getProperty("server.port", "8080"); log.info("项目信息 http://localhost:{}", port); log.info("二维码 http://localhost:{}/qr_code", port); } } <|start_filename|>src/main/java/com/github/ghthou/googleauthenticator/util/QRCodeUtils.java<|end_filename|> package com.github.ghthou.googleauthenticator.util; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * 二维码工具类 */ public class QRCodeUtils { /** 二维码宽度(默认) */ private static final int WIDTH = 300; /** 二维码高度(默认) */ private static final int HEIGHT = 300; /** 二维码文件格式 */ private static final String FILE_FORMAT = "png"; /** 二维码参数 */ private static final Map<EncodeHintType, Object> HINTS = new HashMap(); static { //字符编码 HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8"); //容错等级 H为最高 HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //边距 HINTS.put(EncodeHintType.MARGIN, 2); } /** * 返回一个 BufferedImage 对象 * * @param content 二维码内容 */ public static BufferedImage toBufferedImage(String content) throws WriterException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS); return MatrixToImageWriter.toBufferedImage(bitMatrix); } /** * 返回一个 BufferedImage 对象 * * @param content 二维码内容 * @param width 宽 * @param height 高 */ public static BufferedImage toBufferedImage(String content, int width, int height) throws WriterException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, HINTS); return MatrixToImageWriter.toBufferedImage(bitMatrix); } /** * 将二维码图片输出到一个流中 * * @param content 二维码内容 * @param stream 输出流 */ public static void writeToStream(String content, OutputStream stream) throws WriterException, IOException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS); MatrixToImageWriter.writeToStream(bitMatrix, FILE_FORMAT, stream); } /** * 将二维码图片输出到一个流中 * * @param content 二维码内容 * @param stream 输出流 * @param width 宽 * @param height 高 */ public static void writeToStream(String content, OutputStream stream, int width, int height) throws WriterException, IOException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, HINTS); MatrixToImageWriter.writeToStream(bitMatrix, FILE_FORMAT, stream); } /** * 生成二维码图片文件 * * @param content 二维码内容 * @param path 文件保存路径 */ public static void createQRCodeFile(String content, String path) throws WriterException, IOException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS); MatrixToImageWriter.writeToPath(bitMatrix, FILE_FORMAT, new File(path).toPath()); } /** * 生成二维码图片文件 * * @param content 二维码内容 * @param path 文件保存路径 * @param width 宽 * @param height 高 */ public static void createQRCodeFile(String content, String path, int width, int height) throws WriterException, IOException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, HINTS); MatrixToImageWriter.writeToPath(bitMatrix, FILE_FORMAT, new File(path).toPath()); } } <|start_filename|>src/main/java/com/github/ghthou/googleauthenticator/controller/GoogleAuthenticatorIntegrationController.java<|end_filename|> package com.github.ghthou.googleauthenticator.controller; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.stream.Collectors; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.text.StringSubstitutor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import com.github.ghthou.googleauthenticator.util.GoogleAuthenticatorUtils; import com.github.ghthou.googleauthenticator.util.QRCodeUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Lists; import lombok.SneakyThrows; @RestController public class GoogleAuthenticatorIntegrationController { /** 服务名称,如 Google Github 等(不参与运算,只是为了与其他服务作区分) */ public static final String ISSUER = "测试服务"; /** 测试时使用的密钥 */ public static final String TEST_SECRET_KEY = "<KEY>"; /** * 测试相关信息 */ @GetMapping public String info() { // 为了方便测试,使用测试密钥 String secretKey = TEST_SECRET_KEY; List<LocalDateTime> dateList = Lists.newArrayList(); LocalDateTime now = LocalDateTime.now(); // 当前时间0秒 LocalDateTime begin = now.withSecond(0); // 当前时间往后10分钟 LocalDateTime end = begin.plusMinutes(10); for (LocalDateTime d = begin; d.isBefore(end); d = d.plusSeconds(30)) { dateList.add(d); } String tableStr = dateList.stream().map(dateTime -> { String format1 = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); String totpCode = GoogleAuthenticatorUtils .generateTOTP(secretKey, dateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli() / 1000 / 30); return format1 + "&emsp;" + totpCode; }).collect(Collectors.joining("<br>")); String format = "密钥:&emsp;${secret}<br><br>TOTP 一次性密码列表<br>"; Builder<String, String> mapBuilder = ImmutableMap.builder(); mapBuilder.put("secret", secretKey); return StringSubstitutor.replace(format, mapBuilder.build()) + tableStr; } /** * 生成 Google Authenticator Key Uri 二维码 */ @SneakyThrows @GetMapping("/qr_code") public void qrCode(HttpServletResponse response) { // 获取用户名称(从数据库或者缓存),可以是登录名,邮箱,手机(不参与运算,只是为了与其他服务作区分) String account = "<EMAIL>"; // 生成密钥,并保存到数据库 // String secretKey = GoogleAuthenticatorUtils.createSecretKey(); // 为了方便测试,使用测试密钥 String secretKey = TEST_SECRET_KEY; // 生成 Key Uri String keyUri = GoogleAuthenticatorUtils.createKeyUri(secretKey, account, ISSUER); // 根据 keyUri 生成二维码图片 try (ServletOutputStream outputStream = response.getOutputStream()) { QRCodeUtils.writeToStream(keyUri, outputStream); } } /** * 绑定验证 * * @param totpCode TOTP 一次性密码 */ @PostMapping("/bind_verification") public Boolean bindVerification(String totpCode) { // 根据登录用户信息获取密钥 // String secretKey = 从数据库中获取; // 为了方便测试,使用测试密钥 String secretKey = TEST_SECRET_KEY; if (GoogleAuthenticatorUtils.verification(secretKey, totpCode)) { // 设置用户开启二步验证,更新用户信息 // 生成备用验证码,保存到数据库,同时返回到前台显示,并提示用户进行保存.在用户手机丢失后,或者 APP 验证信息被误删,可以通过使用备用验证码的方式进行登录 return Boolean.TRUE; } return Boolean.FALSE; } /** * 登录 */ @PostMapping("/login") public Boolean login(String userName, String passWord, String totpCode) { // 首先进行密码校验 // 然后校验 TOTP 一次性密码 // 为了方便测试,使用测试密钥 String secretKey = TEST_SECRET_KEY; return GoogleAuthenticatorUtils.verification(secretKey, totpCode); } }
gh-thou/study-googleAuthenticator
<|start_filename|>docs/build/html/example.html<|end_filename|> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="Python"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Simple Running Example &#8212; BOML 0.1.0 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="Core Modules" href="modules.html" /> <link rel="prev" title="Installation" href="installation.html" /> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="simple-running-example"> <h1>Simple Running Example<a class="headerlink" href="#simple-running-example" title="Permalink to this headline">¶</a></h1> <div class="highlight-sh"><div class="highlight"><pre><span></span><span class="c1"># start from laoding data</span> from boml import utils from test_script.script_helper import * <span class="nv">dataset</span> <span class="o">=</span> boml.load_data.meta_omniglot<span class="o">(</span> <span class="nv">std_num_classes</span><span class="o">=</span>args.classes, <span class="nv">examples_train</span><span class="o">=</span>args.examples_train, <span class="nv">examples_test</span><span class="o">=</span>args.examples_test, <span class="o">)</span> <span class="nv">ex</span> <span class="o">=</span> boml.BOMLExperiment<span class="o">(</span>dataset<span class="o">)</span> print<span class="o">(</span><span class="s2">&quot;experiment built!&quot;</span><span class="o">)</span> <span class="c1"># build network structure and define hyperparameters</span> <span class="nv">boml_ho</span> <span class="o">=</span> boml.BOMLOptimizer<span class="o">(</span> <span class="nv">method</span><span class="o">=</span><span class="s2">&quot;MetaInit&quot;</span>, <span class="nv">inner_method</span><span class="o">=</span><span class="s2">&quot;Simple&quot;</span>, <span class="nv">outer_method</span><span class="o">=</span><span class="s2">&quot;Simple&quot;</span> <span class="o">)</span> <span class="nv">meta_learner</span> <span class="o">=</span> boml_ho.meta_learner<span class="o">(</span><span class="nv">_input</span><span class="o">=</span>ex.x, <span class="nv">dataset</span><span class="o">=</span>dataset, <span class="nv">meta_model</span><span class="o">=</span><span class="s2">&quot;V1&quot;</span><span class="o">)</span> print<span class="o">(</span><span class="s2">&quot;meta learner built!&quot;</span><span class="o">)</span> ex.model <span class="o">=</span> boml_ho.base_learner<span class="o">(</span><span class="nv">_input</span><span class="o">=</span>ex.x, <span class="nv">meta_learner</span><span class="o">=</span>meta_learner<span class="o">)</span> <span class="c1"># define LL objectives and LL calculation process</span> print<span class="o">(</span><span class="s2">&quot;base learner built!&quot;</span><span class="o">)</span> <span class="nv">loss_inner</span> <span class="o">=</span> utils.cross_entropy<span class="o">(</span><span class="nv">pred</span><span class="o">=</span>ex.model.out, <span class="nv">label</span><span class="o">=</span>ex.y<span class="o">)</span> <span class="nv">accuracy</span> <span class="o">=</span> utils.classification_acc<span class="o">(</span><span class="nv">pred</span><span class="o">=</span>ex.model.out, <span class="nv">label</span><span class="o">=</span>ex.y<span class="o">)</span> <span class="nv">inner_grad</span> <span class="o">=</span> boml_ho.ll_problem<span class="o">(</span> <span class="nv">inner_objective</span><span class="o">=</span>loss_inner, <span class="nv">learning_rate</span><span class="o">=</span>args.lr, <span class="nv">T</span><span class="o">=</span>args.T, <span class="nv">experiment</span><span class="o">=</span>ex, <span class="nv">var_list</span><span class="o">=</span>ex.model.var_list, <span class="o">)</span> <span class="c1"># define UL objectives and UL calculation process</span> <span class="nv">loss_outer</span> <span class="o">=</span> utils.cross_entropy<span class="o">(</span><span class="nv">pred</span><span class="o">=</span>ex.model.re_forward<span class="o">(</span>ex.x_<span class="o">)</span>.out, <span class="nv">label</span><span class="o">=</span>ex.y_<span class="o">)</span> boml_ho.ul_problem<span class="o">(</span> <span class="nv">outer_objective</span><span class="o">=</span>loss_outer, <span class="nv">meta_learning_rate</span><span class="o">=</span>args.meta_lr, <span class="nv">inner_grad</span><span class="o">=</span>inner_grad, <span class="nv">meta_param</span><span class="o">=</span>tf.get_collection<span class="o">(</span>boml.extension.GraphKeys.METAPARAMETERS<span class="o">)</span>, <span class="o">)</span> <span class="c1"># aggregate all the defined operations</span> boml_ho.aggregate_all<span class="o">()</span> <span class="c1"># Meta training step</span> with tf.Session<span class="o">()</span> as sess: tf.global_variables_initializer<span class="o">()</span>.run<span class="o">(</span><span class="nv">session</span><span class="o">=</span>sess<span class="o">)</span> <span class="k">for</span> itr in range<span class="o">(</span>args.meta_train_iterations<span class="o">)</span>: <span class="c1"># generate the feed_dict for calling run() everytime</span> <span class="nv">train_batch</span> <span class="o">=</span> BatchQueueMock<span class="o">(</span> dataset.train, <span class="m">1</span>, args.meta_batch_size, utils.get_rand_state<span class="o">(</span><span class="m">1</span><span class="o">)</span> <span class="o">)</span> tr_fd, <span class="nv">v_fd</span> <span class="o">=</span> utils.feed_dict<span class="o">(</span>train_batch.get_single_batch<span class="o">()</span>, ex<span class="o">)</span> boml_ho.run<span class="o">(</span>tr_fd, v_fd<span class="o">)</span> print<span class="o">(</span><span class="s2">&quot;finish one meta-iteration &quot;</span><span class="o">)</span> <span class="k">if</span> itr % <span class="nv">100</span> <span class="o">==</span> <span class="m">0</span>: print<span class="o">(</span>sess.run<span class="o">(</span>loss_inner, utils.merge_dicts<span class="o">(</span>tr_fd, v_fd<span class="o">)))</span> </pre></div> </div> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="index.html">Documentation overview</a><ul> <li>Previous: <a href="installation.html" title="previous chapter">Installation</a></li> <li>Next: <a href="modules.html" title="next chapter">Core Modules</a></li> </ul></li> </ul> </div> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/example.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2020, <NAME>, <NAME>. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.3</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> | <a href="_sources/example.rst.txt" rel="nofollow">Page source</a> </div> </body> </html> <|start_filename|>exp_scripts/run_trhg_simple_version.bat<|end_filename|> @echo off cd ../test_script python test_meta_feat.py --name_of_args_json_file ../exp_config/trhg_simple_version.json <|start_filename|>exp_config/maml_simple_version.json<|end_filename|> { "mode":"train", "dataset":"omniglot", "classes":5, "T":5, "meta_lr":0.001, "lr":0.1, "examples_train":1, "examples_test":15, "meta_batch_size":4, "meta_train_iterations":5000, "method":"MetaInit", "inner_method":"Simple", "outer_method":"Simple", "learn_lr":"false", "logdir":"../tmp/", "print_interval":100, "save_interval":100 } <|start_filename|>docs/build/html/built_in.html<|end_filename|> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="Python"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Core Built-in Functions &#8212; BOML 0.1.0 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="core-built-in-functions"> <h1>Core Built-in Functions<a class="headerlink" href="#core-built-in-functions" title="Permalink to this headline">¶</a></h1> <ol class="arabic"> <li><p class="first">BOMLOptimizer.meta_learner:</p> <ul> <li><dl class="first docutils"> <dt>Aliases:</dt> <dd><blockquote class="first"> <div><ul class="simple"> <li>boml.boml_optimizer.BOMLOptimizer.meta_learner()</li> </ul> </div></blockquote> <div class="last highlight-sh"><div class="highlight"><pre><span></span>boml.boml_optimizer.BOMLOptimizer.meta_learner<span class="o">(</span> _input, dataset, <span class="nv">meta_model</span><span class="o">=</span><span class="s1">&#39;V1&#39;</span>, <span class="nv">name</span><span class="o">=</span><span class="s1">&#39;Hyper_Net&#39;</span>, <span class="nv">use_T</span><span class="o">=</span>False, <span class="nv">use_Warp</span><span class="o">=</span>False, **model_args <span class="o">)</span> </pre></div> </div> </dd> </dl> </li> </ul> <p>This method must be called once at first to build meta modules and initialize meta parameters and neural networks.</p> <ul> <li><p class="first">Args:</p> <blockquote> <div><ul class="simple"> <li>_input: orginal input for neural network construction;</li> <li>dataset: which dataset to use for training and testing. It should be initialized before being passed into the function</li> <li>meta_model: model chosen for neural network construction, <cite>V1</cite> for C4L with fully connected layer,`V2` for Residual blocks with fully connected layer.</li> <li>name: name for Meta model modules used for BOMLNet initialization</li> <li>use_T: whether to use T layer for C4L neural networks</li> <li>use_Warp: whether to use Warp layer for C4L neural networks</li> <li>model_args: optional arguments to set specific parameters of neural networks.</li> </ul> </div></blockquote> </li> </ul> </li> <li><p class="first">BOMLOptimizer.base_learner:</p> <ul> <li><dl class="first docutils"> <dt>Aliases:</dt> <dd><blockquote class="first"> <div><ul class="simple"> <li>boml.boml_optimizer.BOMLOptimizer.base_learner()</li> </ul> </div></blockquote> <div class="last highlight-sh"><div class="highlight"><pre><span></span>boml.boml_optimizer.BOMLOptimizer.base_learner<span class="o">(</span> _input, meta_learner, <span class="nv">name</span><span class="o">=</span><span class="s1">&#39;Task_Net&#39;</span>, <span class="nv">weights_initializer</span><span class="o">=</span>tf.zeros_initializer <span class="o">)</span> </pre></div> </div> </dd> </dl> </li> </ul> <p>This method has to be called for every experiment and takes responsibility for defining task-specific modules and inner optimizer.</p> <ul> <li><p class="first">Args:</p> <blockquote> <div><ul class="simple"> <li>_input: orginal input for neural network construction of task-specific module;</li> <li>meta_learner: returned value of meta_learner function, which is a instance of BOMLNet or its child classes</li> <li>name: name for Base model modules used for BOMLNet initialization</li> <li>weights_initializer: initializer function for task_specific network, called by 'MetaRepr' method</li> </ul> </div></blockquote> </li> <li><p class="first">Returns: task-specific model part</p> </li> </ul> </li> <li><p class="first">BOMLOptimizer.ll_problem:</p> <blockquote> <div><ul class="simple"> <li><dl class="first docutils"> <dt>Aliases:</dt> <dd><ul class="first last"> <li>boml.boml_optimizer.BOMLOptimizer.ll_problem()</li> </ul> </dd> </dl> </li> </ul> <div class="highlight-sh"><div class="highlight"><pre><span></span>boml.boml_optimizer.BOMLOptimizer.ll_problem<span class="o">(</span> inner_objective, learning_rate, T, <span class="nv">inner_objective_optimizer</span><span class="o">=</span><span class="s1">&#39;SGD&#39;</span>, <span class="nv">outer_objective</span><span class="o">=</span>None, <span class="nv">learn_lr</span><span class="o">=</span>False, <span class="nv">alpha_init</span><span class="o">=</span><span class="m">0</span>.0, <span class="nv">s</span><span class="o">=</span><span class="m">1</span>.0, <span class="nv">t</span><span class="o">=</span><span class="m">1</span>.0, <span class="nv">learn_alpha</span><span class="o">=</span>False, <span class="nv">learn_st</span><span class="o">=</span>False, <span class="nv">learn_alpha_itr</span><span class="o">=</span>False, <span class="nv">var_list</span><span class="o">=</span>None, <span class="nv">init_dynamics_dict</span><span class="o">=</span>None, <span class="nv">first_order</span><span class="o">=</span>False, <span class="nv">loss_func</span><span class="o">=</span>utils.cross_entropy, <span class="nv">momentum</span><span class="o">=</span><span class="m">0</span>.5, <span class="nv">beta1</span><span class="o">=</span><span class="m">0</span>.0, <span class="nv">beta2</span><span class="o">=</span><span class="m">0</span>.999, <span class="nv">regularization</span><span class="o">=</span>None, <span class="nv">experiment</span><span class="o">=</span>None, <span class="nv">scalor</span><span class="o">=</span><span class="m">0</span>.0, **inner_kargs <span class="o">)</span> </pre></div> </div> </div></blockquote> <p>After construction of neural networks, solutions to lower level problems should be regulated in ll_problem.</p> <ul class="simple"> <li><dl class="first docutils"> <dt>Args:</dt> <dd><ul class="first last"> <li>inner_objective: loss function for the inner optimization problem</li> <li>learning_rate: step size for inner loop optimization</li> <li>T: numbers of steps for inner gradient descent optimization</li> <li>inner_objective_optimizer: Optimizer type for the outer parameters, should be in list [<cite>SGD</cite>,`Momentum`,`Adam`]</li> <li>outer_objective: loss function for the outer optimization problem, which need to be claimed in BDA agorithm</li> <li>alpha_init: initial value of ratio of inner objective to outer objective in BDA algorithm</li> <li>s,t: coefficients of aggregation of inner and outer objectives in BDA algorithm, default to be 1.0</li> <li>learn_alpha: specify parameter for BDA algorithm to decide whether to initialize alpha as a hyper parameter</li> <li>learn_alpha_itr: parameter for BDA algorithm to specify whether to initialize alpha as a vector, of which every dimension's value is step-wise scale factor fot the optimization process</li> <li>learn_st: specify parameter for BDA algorithm to decide whether to initialize s and t as hyper parameters</li> <li>first_order: specific parameter to define whether to use implement first order MAML, default to be <cite>FALSE</cite></li> <li>loss_func: specifying which type of loss function is used for the maml-based method, which should be consistent with the form to compute the inner objective</li> <li>momentum: specific parameter for Optimizer.BOMLOptMomentum to set initial value of momentum</li> <li>regularization: whether to add regularization terms in the inner objective</li> <li>experiment: instance of Experiment to use in the Lower Level Problem, especifially needed in the <cite>MetaRper</cite> type of method.</li> <li>var_list: optional list of variables (of the inner optimization problem)</li> <li>inner_kargs: optional arguments to pass to <cite>boml.boml_optimizer.BOMLOptimizer.compute_gradients</cite></li> </ul> </dd> </dl> </li> <li>Returns: task-specific model part</li> </ul> </li> <li><p class="first">BOMLOptimizer.ul_problem</p> <ul> <li><p class="first">Aliases:</p> <blockquote> <div><blockquote> <div><ul> <li><p class="first">boml.boml_optimizer.BOMLOptimizer.ul_problem()</p> <blockquote> <div><div class="highlight-sh"><div class="highlight"><pre><span></span>boml.boml_optimizer.BOMLOptimizer.ul_Problem<span class="o">(</span> outer_objective, meta_learning_rate, inner_grad, <span class="nv">meta_param</span><span class="o">=</span>None, <span class="nv">outer_objective_optimizer</span><span class="o">=</span><span class="s1">&#39;Adam&#39;</span>, <span class="nv">epsilon</span><span class="o">=</span><span class="m">1</span>.0, <span class="nv">momentum</span><span class="o">=</span><span class="m">0</span>.5, <span class="nv">global_step</span><span class="o">=</span>None <span class="o">)</span> </pre></div> </div> </div></blockquote> </li> </ul> </div></blockquote> <p>This method define upper level problems and choose optimizer to optimize meta parameters, which should be called afer ll_problem.</p> <ul> <li><p class="first">Args:</p> <blockquote> <div><ul class="simple"> <li>outer_objective: scalar tensor for the outer objective</li> <li>meta_learning_rate: step size for outer loop optimization</li> <li>inner_grad: Returned value of boml.BOMLOptimizer.LLProblem()</li> <li>meta_param: optional list of outer parameters and model parameters</li> <li>outer_objective_optimizer: Optimizer type for the outer parameters, should be in list [<cite>SGD</cite>,`Momentum`,`Adam`]</li> <li>epsilon: Float, cofffecients to be used in DARTS algorithm</li> <li>momentum: specific parameters to be used to initialize <cite>Momentum</cite> algorithm</li> </ul> </div></blockquote> </li> <li><p class="first">Returns:meta_param list, used for debugging</p> </li> </ul> </div></blockquote> </li> </ul> </li> <li><p class="first">aggregate_all:</p> <ul> <li><p class="first">Aliases:</p> <blockquote> <div><blockquote> <div><ul class="simple"> <li>boml.boml_optimizer.BOMLOptimizer.aggregate_all()</li> </ul> </div></blockquote> <dl class="docutils"> <dt>::</dt> <dd><dl class="first last docutils"> <dt>boml.boml_optimizer.BOMLOptimizer.aggregate_all(</dt> <dd><p class="first last">aggregation_fn=None, gradient_clip=None )</p> </dd> </dl> </dd> </dl> </div></blockquote> </li> <li><dl class="first docutils"> <dt>Args:</dt> <dd><ul class="first last simple"> <li>aggregation_fn:Optional operation to aggregate multiple outer_gradients (for the same meta parameter),by (default: reduce_mean)</li> <li>gradient_clip: optional operation to clip the aggregated outer gradients</li> </ul> </dd> </dl> </li> <li><p class="first">Returns: None</p> </li> </ul> </li> </ol> <blockquote> <div>Finally, aggregate_all has to be called to aggregate gradient of different tasks, and define operations to apply outer gradients and update meta parametes.</div></blockquote> <ol class="arabic" start="6"> <li><p class="first">run:</p> <ul> <li><dl class="first docutils"> <dt>Aliases:</dt> <dd><ul class="first simple"> <li>boml.boml_optimizer.BOMLOptimizer.run()</li> </ul> <div class="last highlight-sh"><div class="highlight"><pre><span></span>boml.boml_optimizer.BOMLOptimizer.run<span class="o">(</span> <span class="nv">inner_objective_feed_dicts</span><span class="o">=</span>None, <span class="nv">outer_objective_feed_dicts</span><span class="o">=</span>None, <span class="nv">session</span><span class="o">=</span>None, <span class="nv">_skip_hyper_ts</span><span class="o">=</span>False, <span class="nv">_only_hyper_ts</span><span class="o">=</span>False, <span class="nv">callback</span><span class="o">=</span>None <span class="o">)</span> </pre></div> </div> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Args:</dt> <dd><ul class="first last simple"> <li>inner_objective_feed_dicts: an optional feed dictionary for the inner problem. Can be a function of step, which accounts for, e.g. stochastic gradient descent.</li> <li>outer_objective_feed_dicts: an optional feed dictionary for the outer optimization problem (passed to the evaluation of outer objective). Can be a function of hyper-iterations steps (i.e. global variable), which may account for, e.g. stochastic evaluation of outer objective.</li> <li>session: optional session</li> <li>callback: optional callback function of signature (step (int), feed_dictionary, <cite>tf.Session</cite>) -&gt; None that are called after every forward iteration.</li> </ul> </dd> </dl> </li> <li><p class="first">Returns: None</p> </li> </ul> </li> </ol> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="index.html">Documentation overview</a><ul> </ul></li> </ul> </div> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/built_in.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2020, <NAME>, <NAME>. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.3</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> | <a href="_sources/built_in.rst.txt" rel="nofollow">Page source</a> </div> </body> </html> <|start_filename|>exp_scripts/run_maml_simple_version.bat<|end_filename|> @echo off cd ../test_script python test_meta_init.py --name_of_args_json_file ../exp_config/maml_simple_version.json <|start_filename|>docs/build/html/index.html<|end_filename|> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="Python"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Welcome to BOML&#39;s documentation! &#8212; BOML 0.1.0 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="Installation" href="installation.html" /> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="welcome-to-boml-s-documentation"> <h1>Welcome to BOML's documentation!<a class="headerlink" href="#welcome-to-boml-s-documentation" title="Permalink to this headline">¶</a></h1> <p><strong>Configuration &amp; Status</strong></p> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="PyPi Package" src="https://badge.fury.io/py/boml.svg" /></a> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="build status" src="https://travis-ci.com/dut-media-lab/BOML.svg?branch=master" /></a> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="codecov" src="https://codecov.io/gh/dut-media-lab/BOML/branch/master/graph/badge.svg" /></a> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="Documentation Status" src="https://readthedocs.org/projects/pybml/badge/?version=latest" /></a> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="License" src="https://img.shields.io/badge/license-MIT-000000.svg" /></a> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="Language" src="https://img.shields.io/github/languages/top/dut-media-lab/BOML" /></a> <a class="reference external image-reference" href="https://github.com/dut-media-lab/BOML"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg" /></a> <p>BOML is a modularized optimization library that unifies several ML algorithms into a common bilevel optimization framework. It provides interfaces to implement popular bilevel optimization algorithms, so that you could quickly build your own meta learning neural network and test its performance.</p> <p><strong>Key features of BOML</strong></p> <ul class="simple"> <li><strong>Unified bilevel optimization framework</strong> to address different categories of existing meta-learning paradigms.</li> <li><strong>Modularized algorithmic structure</strong> to integrate a variety of optimization techniques and popular methods.</li> <li><strong>Unit tests with Travis CI and Codecov</strong> to reach 99% coverage, and following <strong>PEP8 naming convention</strong> to guarantee the code quality.</li> <li><strong>Comprehensive documentations</strong> using sphinx and <strong>flexible functional interfaces</strong> similar to conventional optimizers to help researchers quickly get familiar with the procedures.</li> </ul> <p><strong>Optimization Routine</strong></p> <p>The figure below illustrates the general optimization process by organized modules in BOML.</p> <img alt="Bilevel Optimization Routine" class="align-center" src="_static/img/optimization_routine.png" /> <p><strong>Documentation</strong></p> <div class="toctree-wrapper compound"> <p class="caption"><span class="caption-text">Getting Started</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="installation.html">Installation</a></li> <li class="toctree-l1"><a class="reference internal" href="example.html">Simple Running Example</a></li> </ul> </div> <div class="toctree-wrapper compound"> <p class="caption"><span class="caption-text">Core Modules of BOML</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="modules.html">Core Modules</a></li> <li class="toctree-l1"><a class="reference internal" href="builtin.html">Core Builtin Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="extension.html">Extensible Modules</a></li> </ul> </div> <div class="toctree-wrapper compound"> <p class="caption"><span class="caption-text">Additional Information</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="references.html">Related Papers</a></li> <li class="toctree-l1"><a class="reference internal" href="license.html">Authors and License</a></li> </ul> </div> <p><strong>Related Links</strong></p> <ul class="simple"> <li><a class="reference external" href="https://github.com/dut-media-lab/BOML">Go to the project home page</a></li> <li><a class="reference external" href="https://codeload.github.com/dut-media-lab/BOML/zip/master">Download the latest code bundle</a></li> </ul> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="#">Documentation overview</a><ul> <li>Next: <a href="installation.html" title="next chapter">Installation</a></li> </ul></li> </ul> </div> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/index.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2020, <NAME>, <NAME>. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.3</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> | <a href="_sources/index.rst.txt" rel="nofollow">Page source</a> </div> </body> </html> <|start_filename|>exp_config/rhg_simple_version.json<|end_filename|> { "mode":"train", "dataset":"omniglot", "classes":5, "T":5, "meta_lr":0.001, "lr":0.1, "examples_train":1, "examples_test":15, "meta_batch_size":8, "meta_train_iterations":5000, "method":"MetaFeat", "inner_method": "Trad", "outer_method":"Reverse", "learn_lr":"false", "logdir":".../tmp/", "print_interval":100, "save_interval":100 } <|start_filename|>docs/build/html/modules.html<|end_filename|> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="Python"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Core Modules &#8212; BOML 0.1.0 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="Core Builtin Functions" href="builtin.html" /> <link rel="prev" title="Simple Running Example" href="example.html" /> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="core-modules"> <h1>Core Modules<a class="headerlink" href="#core-modules" title="Permalink to this headline">¶</a></h1> <ol class="arabic"> <li><p class="first">load_data</p> <ul> <li><dl class="first docutils"> <dt>Related:</dt> <dd><blockquote class="first"> <div><ul class="simple"> <li>boml.load_data.meta_omniglot</li> <li>boml.load_data.meta_mini_imagenet</li> <li>boml.load_data.mnist</li> <li>...</li> </ul> </div></blockquote> <div class="highlight-sh"><div class="highlight"><pre><span></span>boml.meta_omniglot<span class="o">(</span> <span class="nv">folder</span><span class="o">=</span>DATA_FOLDER, <span class="nv">std_num_classes</span><span class="o">=</span>None, <span class="nv">examples_train</span><span class="o">=</span>None, <span class="nv">examples_test</span><span class="o">=</span>None, <span class="nv">one_hot_enc</span><span class="o">=</span>True, <span class="nv">_rand</span><span class="o">=</span><span class="m">0</span>, <span class="nv">n_splits</span><span class="o">=</span>None<span class="o">)</span> boml.meta_mini_imagenet<span class="o">(</span> <span class="nv">folder</span><span class="o">=</span>DATA_FOLDER, <span class="nv">sub_folders</span><span class="o">=</span>None, <span class="nv">std_num_classes</span><span class="o">=</span>None, <span class="nv">examples_train</span><span class="o">=</span>None, <span class="nv">examples_test</span><span class="o">=</span>None, <span class="nv">resize</span><span class="o">=</span><span class="m">84</span>, <span class="nv">one_hot_enc</span><span class="o">=</span>True, <span class="nv">load_all_images</span><span class="o">=</span>True, <span class="nv">h5</span><span class="o">=</span>False <span class="o">)</span> </pre></div> </div> <p class="last">boml.load_data manages different datasets and generate batches of tasks for training and testing.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Args:</dt> <dd><ul class="first last simple"> <li>folder: str, root folder name. Use os module to modify the path to the datasets</li> <li>std_num_classes: number of classes for N-way classification</li> <li>examples_train: number of examples to be picked in each generated per classes for training (eg .1 shot, examples_train=1)</li> <li>examples_test: number of examples to be picked in each generated per classes for testing</li> <li>one_hot_enc: whether to adopt one hot encoding</li> <li>_rand: random seed or RandomState for generate training, validation, testing meta-datasets split</li> <li>n_splits: num classes per split</li> </ul> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Usage:</dt> <dd><div class="first last highlight-sh"><div class="highlight"><pre><span></span><span class="nv">dataset</span> <span class="o">=</span> boml.meta_omniglot<span class="o">(</span> args.num_classes, args.num_examples, args.examples_test <span class="o">)</span> </pre></div> </div> </dd> </dl> </li> <li><p class="first">Returns: an initialized instance of data loader</p> </li> </ul> </li> <li><p class="first">Experiment</p> <ul> <li><dl class="first docutils"> <dt>Aliases:</dt> <dd><blockquote class="first"> <div><ul class="simple"> <li>boml.load_data.Experiment</li> </ul> </div></blockquote> <div class="highlight-sh"><div class="highlight"><pre><span></span>boml.Experiment<span class="o">(</span> <span class="nv">dataset</span><span class="o">=</span>None, <span class="nv">dtype</span><span class="o">=</span>tf.float32 <span class="o">)</span> </pre></div> </div> <p class="last">boml.Experiment manages inputs, outputs and task-specific parameters.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Args:</dt> <dd><ul class="first last simple"> <li>dataset: initialized instance of load_data</li> <li>dtype: default tf.float32</li> </ul> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Attributes:</dt> <dd><ul class="first last simple"> <li>x: input placeholder of input for your defined lower level problem</li> <li>y: label placeholder of output for yourdefined lower level problem</li> <li>x_:input placeholder of input for your defined upper level problem</li> <li>y_:label placeholder of output for your defined upper level problem</li> <li>model: used to restore the task-specific model</li> <li>errors: dictionary to restore defined loss functions of different levels</li> <li>scores: dictionary to restore defined accuracies functions</li> <li>optimizer: dictonary to restore optimized chosen for inner and outer loop optimization</li> </ul> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Usage:</dt> <dd><div class="first last highlight-sh"><div class="highlight"><pre><span></span><span class="nv">ex</span> <span class="o">=</span> boml.Experiment<span class="o">(</span><span class="nv">datasets</span> <span class="o">=</span> dataset<span class="o">)</span> ex.errors<span class="o">[</span><span class="s1">&#39;training&#39;</span><span class="o">]</span> <span class="o">=</span> boml.utils.cross_entropy<span class="o">(</span> <span class="nv">pred</span><span class="o">=</span>ex.model.out, <span class="nv">label</span><span class="o">=</span>ex.y, <span class="nv">method</span><span class="o">=</span><span class="s1">&#39;MetaRper&#39;</span><span class="o">)</span> ex.scores<span class="o">[</span><span class="s1">&#39;accuracy&#39;</span><span class="o">]</span> <span class="o">=</span> tf.contrib.metrics.accuracy<span class="o">(</span> tf.argmax<span class="o">(</span>tf.nn.softmax<span class="o">(</span>ex.model.out<span class="o">)</span>, <span class="m">1</span><span class="o">)</span>, tf.argmax<span class="o">(</span>ex.y, <span class="m">1</span><span class="o">))</span> ex.optimizer<span class="o">[</span><span class="s1">&#39;apply_updates&#39;</span><span class="o">]</span>, <span class="nv">_</span> <span class="o">=</span> boml.BOMLOptSGD<span class="o">(</span> <span class="nv">learning_rate</span><span class="o">=</span>lr0 <span class="o">)</span>.minimize<span class="o">(</span> ex.errors<span class="o">[</span><span class="s1">&#39;training&#39;</span><span class="o">]</span>, <span class="nv">var_list</span><span class="o">=</span>ex.model.var_list <span class="o">)</span> </pre></div> </div> </dd> </dl> </li> <li><p class="first">Returns: an initialized instance of Experiment</p> </li> </ul> </li> <li><p class="first">BOMLOptimizer</p> <ul> <li><dl class="first docutils"> <dt>Aliases:</dt> <dd><blockquote class="first"> <div><ul class="simple"> <li>boml.boml_optimizer.BOMLOptimizer</li> </ul> </div></blockquote> <div class="highlight-sh"><div class="highlight"><pre><span></span>boml.BOMLOptimizer<span class="o">(</span> <span class="nv">Method</span><span class="o">=</span>None, <span class="nv">inner_method</span><span class="o">=</span>None, <span class="nv">outer_method</span><span class="o">=</span>None, <span class="nv">truncate_iter</span><span class="o">=</span>-1, <span class="nv">experiments</span><span class="o">=[]</span> <span class="o">)</span> </pre></div> </div> <p class="last">BOMLOptimizer is the main class in <cite>boml</cite>, which takes responsibility for the whole process of model construnction and back propagation.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Args:</dt> <dd><ul class="first last simple"> <li>Method: define basic method for following training process, it should be included in [<cite>MetaInit</cite>, <cite>MetaRepr</cite>], <cite>MetaInit</cite> type includes methods like <cite>MAML</cite>, <cite>FOMAML</cite>, <cite>MT-net</cite>, <cite>WarpGrad</cite>; <cite>MetaRepr</cite> type includes methods like <cite>BA</cite>, <cite>RHG</cite>, <cite>TG</cite>, <cite>HOAG</cite>, <cite>DARTS</cite>;</li> <li>inner_method: method chosen for solving LLproblem, including [<cite>Trad</cite> , <cite>Simple</cite>, <cite>Aggr</cite>], MetaRepr type choose either <cite>Trad</cite> for traditional optimization strategies or <cite>Aggr</cite> for Gradient Aggragation optimization. 'MetaInit' type should choose <cite>Simple</cite>, and set specific parameters for detailed method choices like FOMAML or MT-net.</li> <li>outer_method: method chosen for solving LLproblem, including [<cite>Reverse</cite> ,`Simple`, <cite>DARTS</cite>, <cite>Implcit</cite>], <cite>MetaInit</cite> type should choose <cite>Simple</cite>, and set specific parameters for detailed method choices like <cite>FOMAML</cite></li> <li>truncate_iter: specific parameter for <cite>Truncated Gradient</cite> method, defining number of iterations to truncate in the Back propagation process</li> <li>experiments: list of Experiment objects that has already been initialized</li> </ul> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Usage:</dt> <dd><div class="first last highlight-sh"><div class="highlight"><pre><span></span><span class="nv">ex</span> <span class="o">=</span> boml.Experiment<span class="o">(</span> boml.meta_omniglot<span class="o">(</span><span class="m">5</span>,1,15<span class="o">)</span> <span class="o">)</span> <span class="nv">boml_ho</span> <span class="o">=</span> boml.BOMLOptimizer<span class="o">(</span> <span class="nv">Method</span><span class="o">=</span><span class="s1">&#39;MetaRper&#39;</span>, <span class="nv">inner_method</span><span class="o">=</span><span class="s1">&#39;Simple&#39;</span>, <span class="nv">outer_method</span><span class="o">=</span><span class="s1">&#39;Simple&#39;</span>, <span class="nv">experiments</span><span class="o">=</span>ex <span class="o">)</span> </pre></div> </div> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Utility Functions:</dt> <dd><ul class="first last simple"> <li>learning_rate(): returns defined inner learning rate</li> <li>meta_learning_rate(): returns defined outer learning rate</li> <li>Method: return defined method type</li> <li>param_dict: return the dictionary that restores general parameters, like use_t,use_warp, output shape of defined model, learn_lr, s, t, alpha, first_order.</li> </ul> </dd> </dl> </li> <li><p class="first">Returns: an initialized instance of BOMLOptimizer</p> </li> </ul> </li> </ol> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="index.html">Documentation overview</a><ul> <li>Previous: <a href="example.html" title="previous chapter">Simple Running Example</a></li> <li>Next: <a href="builtin.html" title="next chapter">Core Builtin Functions</a></li> </ul></li> </ul> </div> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/modules.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2020, <NAME>, <NAME>. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.3</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> | <a href="_sources/modules.rst.txt" rel="nofollow">Page source</a> </div> </body> </html>
bmlsoc/PyBML
<|start_filename|>test/test-version.js<|end_filename|> // Copyright IBM Corp. 2015. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 'use strict'; var debug = require('debug')('strongloop:test'); var exec = require('child_process').execFile; var pkg = require('../package.json'); var slc = require.resolve('../bin/slc'); var tap = require('tap'); tap.test('version should print slc and node versions', function(t) { var args = [slc, '--version']; var opts = {encoding: 'utf8'}; t.comment('exec %s arg %j opt %j', process.execPath, args, opts); debug = t.comment.bind(t); exec(process.execPath, args, opts, function(er, stdout) { debug('er=%j', er); t.ifError(er); debug('stdout=<\n%s>', stdout); // Length of expected dependencies + 1 for strong_agent var expected = require('../lib/version.js').__REPORT_DEPENDENCIES; var reported = stdout.trim().split('\n'); debug('expected: %d - %j', expected.length, expected); debug('reported: %d - %j', reported.length, reported); t.assert(!pkg.peerDependencies, 'package has no peer deps'); // The strongloop and strong-agent packages are always reported in addition // to the strong- deps. t.equal(reported.length, expected.length + 2); var line0 = reported[0]; t.match(line0, /^strongloop v[-.0-9]* .node v.+$/); t.notEqual(line0.indexOf(process.version), -1); t.end(); }); }); <|start_filename|>lib/commands/update.js<|end_filename|> // Copyright IBM Corp. 2014,2015. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 var exec = require('child_process').exec; var PACKAGE = require('../../package.json'); var VERSION = PACKAGE.version; module.exports = function(argv, options, loader) { if (options.help || options.h) { return loader.printUsage('update'); } console.log('strongloop at %s; trying self-update...', VERSION); checkVersions(); function install(name, callback) { console.log('npm install -g %s; this may take a moment...', name); exec('npm -q install -X f -g ' + name, callback); } function checkVersions() { install('strongloop', function(err, stdout, stderr) { if (err) { return loader.error(stderr); } exec('slc version', function(err, stdout, stderr) { if (err) { return loader.error(stderr); } console.log('Updated to:\n%s', stdout); }); }); } }; <|start_filename|>lib/loader.js<|end_filename|> // Copyright IBM Corp. 2013,2015. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 // // # CommandLoader // // The CommandLoader is responsible for loading and validating Command modules // present at a configurable location in the filesystem. // var assert = require('assert'); var debug = require('debug')('slc'); var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var path = require('path'); var optimist = require('optimist'); var util = require('util'); // // ## CommandLoader `CommandLoader(obj)` // // Creates a new instance of CommandLoader with the following options: // * root - The location of Command modules in the filesystem, represented as a // String. Defaults to a sibling 'commands' folder. // * strict - If true, CommandLoader will emit 'error' events if its run with a // primary argument that doesn't exist as a command. Otherwise, that argument // will be included in the fallback command's arguments. Defaults to `true`. // * usage - If `--help` or `-h` are passed as options, this command will be // used to generate a usage summary. Defaults to 'help'. // * fallback - If an unknown command is specified while running, this command // is used instead. Defaults to the same as `usage`. // * default - The command to run when no command is specified in argv. // Defaults to the same as `usage`. // * manuals - If set, this location will be used as a repository of named // manual files by loadManual() // // Commands are modules required from `root`. They must have a .run function, // and a .usage string. Or, if module exports justa a function, that function // will be used as the .run function, and if .usage is undefined it will be // loaded by loadManual(). function CommandLoader(obj) { if (!(this instanceof CommandLoader)) { return new CommandLoader(obj); } obj = obj || {}; this.root = obj.root || path.resolve(__dirname, 'commands'); this.strict = true; this.usage = obj.usage || 'help'; this.fallback = obj.fallback || this.usage; this.default = obj.default || this.usage; this.manuals = obj.manuals || null; } util.inherits(CommandLoader, EventEmitter); CommandLoader.createLoader = CommandLoader; // // ## isCommand `CommandLoader.isCommand(module)` // // Returns `true` if **module** is a valid Command, `false` otherwise. // CommandLoader.isCommand = isCommand; function isCommand(module) { return !!module && typeof module.run === 'function'; } // // ## parse `parse(argv, [options])` // // Parses **argv** as an Array of Strings, whether command line arguments or // similar. If **options** is specified, is it used to configure `optimist` // accordingly. // // Returns an Object with `-f` and `--foo` arguments as members and extraneous // arguments as members of the `_` Array. // CommandLoader.prototype.parse = parse; function parse(argv, options) { return optimist(argv).options(options || {}).argv; } // // ## run `run([argv])` // // Synchronously parses **argv**, or `process.argv` otherwise. If a command is // present, that command is run. If no command is run, the configured `fallback` // command is run instead. // CommandLoader.prototype.run = run; function run(argv) { var self = this; var options = self.parse(argv || (argv = process.argv.slice(2))); var command = null; debug('slc.run:', 'argv', argv, 'options', options); if (argv[0] === '-h' || argv[0] === '--help') { return self.printUsage('slc'); } else if (argv[0] === '-v' || argv[0] === '--version' || argv[0] === 'version') { // For backards compatibility with docs return require('./version')(); } else if (!options._.length) { return self.printUsage('slc'); } else { // Otherwise, if we've provided our own command, use that. command = self.getRun(options._[0]); // Build the new, command-local `argv` and `options`. if (command) { argv = argv.slice(argv.indexOf(options._[0]) + 1); options = self.parse(argv); } else if (self.strict) { return self.error( '"%s" is not an slc command. See `slc --help` for more information.', options._[0]); } else { command = self.getRun(self.fallback); } } assert(command); process.env.SLC_COMMAND = command.command; command(argv, options, self); return self; } // // ## loadCommand `loadCommand(name)` // // Synchronously loads the Command module for **name**. // // Returns either a Command or null if the command could not be loaded. // CommandLoader.prototype.loadCommand = loadCommand; function loadCommand(name) { var self = this; var module = null; // Try to support slc loopback:model var index = name.indexOf(':'); if (index !== -1) { name = name.substring(0, index); } var command = path.resolve(this.root, String(name)); try { module = require(command); } catch (e) { debug('require %s failed with', command, e); if (e && e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(command) !== -1) { // In this case, the command was not found. Without the indexOf(), if the // command implementation had a buggy require of a module that couldn't be // found, it would be handled as if the command wasn't present. return null; } return self.error('Error loading module "%s":\n', name, e); } if (typeof module === 'function' || typeof module.run === 'function') { module = { name: name, run: module.run || module, usage: self.loadManual(name) }; } if (!CommandLoader.isCommand(module)) { return null; } return module; } // // ## getUsage `getUsage(name)` // // Returns the usage information for the **name** Command, represented as a // String. If **name** cannot be found, returns `null`. // CommandLoader.prototype.getUsage = getUsage; function getUsage(name) { var self = this; var module = self.loadCommand(name); return module ? module.usage : null; } CommandLoader.prototype.printUsage = printUsage; function printUsage(name) { console.log(this.loadManual(name)); } // // ## getRun `getRun(name)` // // Returns the run Function for the **name** Command. If **name** cannot be // found, returns `null`. // CommandLoader.prototype.getRun = getRun; function getRun(name) { var self = this; var module = self.loadCommand(name); debug('loadCommand', 'name', name, 'run?', module && typeof module.run, 'usage?', module && typeof module.usage); if (module && module.run) { module.run.command = module.name; } return module ? module.run : null; } // // ## error `error(format, ...)` // // Emits a new error event for user handling, arguments are formatted // with `util.format()`. // CommandLoader.prototype.error = error; function error() { var self = this; var message = util.format.apply(null, arguments); self.emit('error', new Error(message)); return self; } // // ## loadManual `loadManual(name)` // // Synchronously loads the manual file for **name** if it exists within a // configured `loader.manuals` folder. // // Returns the file's contents if it exists, `null` otherwise. // // Files are required to be in UTF-8 format. // CommandLoader.prototype.loadManual = loadManual; function loadManual(name) { var self = this; assert(self.manuals); function filename(ext) { return path.resolve(self.manuals, name + ext); } // Return txt files, if we have them, otherwise man pages (which require // massaging on windows). try { return fs.readFileSync(filename('.txt'), 'utf8'); } catch (er) { /* eslint no-empty:0 */ } try { var usage = fs.readFileSync(filename(''), 'utf8'); if (process.platform === 'win32') { // Any char, followed by a backspace. var boldPair = new RegExp('.\b', 'g'); var clean = usage.replace(boldPair, ''); usage = clean; } return usage; } catch (er) { /* eslint no-empty:0 */ } return null; } module.exports = CommandLoader; <|start_filename|>lib/command.js<|end_filename|> // Copyright IBM Corp. 2014,2016. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 module.exports = function Command(command, npmModule) { return function(argv, _options, loader) { var options = { env: process.env, stdio: 'inherit' }; var resolvedCommand; try { resolvedCommand = require.resolve(npmModule + '/' + command); } catch (er) { var msg = 'Error running %s (%s), it may need installation,' + ' try `npm update -g strongloop`.'; loader.error(msg, command, er.message); } // Transmit full original command name to children options.env.CMD = 'slc ' + process.env.SLC_COMMAND; // Build a new `argv` with full path for command // The first argv value should be the path to the node executable process.argv = [process.argv[0], resolvedCommand].concat(argv); require('module')._load(resolvedCommand, null, true); }; }; <|start_filename|>lib/shim.js<|end_filename|> // Copyright IBM Corp. 2013,2014. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 function shim(name, oldFn) { return function(argv, options, loader) { var program = require('commander'); oldFn(program, function(err) { if (err) { loader.error(err); } }); program.parse(['magically eaten', 'me, too', name].concat(argv)); }; } module.exports = shim; <|start_filename|>lib/commands/loopback.js<|end_filename|> // Copyright IBM Corp. 2014,2015. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 var nopt = require('nopt'); var path = require('path'); var debug = require('debug')('slc:loopback'); var lbGenerator = require('generator-loopback'); var yeoman = lbGenerator._yeoman; // generator-loopback should export _yeoman if (!yeoman) { try { // Try to use the yeoman-generator from generator-loopback module yeoman = require('generator-loopback/node_modules/yeoman-generator'); } catch (err) { // Fall back the peer/parent dep yeoman = require('yeoman-generator'); } } module.exports = function loopback(argv, options, loader) { var opts = nopt({ help: Boolean, version: Boolean, generators: Boolean }, { h: '--help', v: '--version', l: '--generators' }); if (opts.version) { var _package = lbGenerator._package; if (!_package) { var pkg = require('generator-loopback/package.json'); _package = pkg.name + ': ' + pkg.version; } console.log(_package); return; } var args = process.argv.slice(2); debug('invoking slc %s', args.join(' ')); var env = yeoman(); // Make sure slc loopback is delegated to slc loopback:app (the default // subgenerator) env.alias(/^([^:]+)$/, '$1:app'); // Change the working directory to the generator-loopback module so that // yoeman can discover the generators var root = path.dirname(require.resolve('generator-loopback/package.json')); var cwd = process.cwd(); debug('changing directory to %s', root); process.chdir(root); // lookup for every namespaces, within the environments.paths and lookups env.lookup(); debug('changing directory back to %s', cwd); process.chdir(cwd); // Switch back // list generators if (opts.generators) { console.log('Available loopback generators: '); console.log(Object.keys(env.getGeneratorsMeta()).filter(function(name) { return name.indexOf('loopback:') !== -1; }).join('\n')); return; } env.on('end', function() { console.log('Done running loopback generator'); }); env.on('error', function(err) { loader.error('Error', 'slc ' + args.join(' '), '\n', opts.debug ? err.stack : err.message); // process.exit(err.code || 1); }); env.run(args, opts); }; <|start_filename|>bin/slc.js<|end_filename|> #!/usr/bin/env node // Copyright IBM Corp. 2015,2016. All Rights Reserved. // Node module: strongloop // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 require('../lib/loader') .createLoader({ manuals: require('path').resolve(__dirname, '..', 'man') }) .on('error', function(err) { console.error(err.message); process.exit(1); }) .run();
ashumz/strongloop
<|start_filename|>init.bat<|end_filename|> ::chcp 65001 pip install -r requirements.txt cmd.exe <|start_filename|>Dockerfile<|end_filename|> FROM python:3.6-alpine MAINTAINER zsnmwy <<EMAIL>> ENV LIBRARY_PATH=/lib:/usr/lib WORKDIR /app RUN apk add --no-cache --virtual bili git build-base python-dev py-pip jpeg-dev zlib-dev && \ git clone https://github.com/yjqiang/bili2.0.git /app && \ pip install --no-cache-dir -r requirements.txt && \ rm -r /var/cache/apk && \ rm -r /usr/share/man && \ apk del bili && \ apk add --no-cache libjpeg-turbo git CMD git pull && \ pip install --no-cache-dir -r requirements.txt && \ python ./run.py
Liu-0726/bili2.0
<|start_filename|>jbox2d-library/src/main/java/org/jbox2d/dynamics/Body.java<|end_filename|> /******************************************************************************* * Copyright (c) 2013, <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. * * 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. ******************************************************************************/ package org.jbox2d.dynamics; import org.jbox2d.collision.broadphase.BroadPhase; import org.jbox2d.collision.shapes.MassData; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Rot; import org.jbox2d.common.Sweep; import org.jbox2d.common.Transform; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.contacts.Contact; import org.jbox2d.dynamics.contacts.ContactEdge; import org.jbox2d.dynamics.joints.JointEdge; /** * A rigid body. These are created via World.createBody. * * @author <NAME> */ public class Body { public static final int e_islandFlag = 0x0001; public static final int e_awakeFlag = 0x0002; public static final int e_autoSleepFlag = 0x0004; public static final int e_bulletFlag = 0x0008; public static final int e_fixedRotationFlag = 0x0010; public static final int e_activeFlag = 0x0020; public static final int e_toiFlag = 0x0040; public BodyType m_type; public int m_flags; public int m_islandIndex; /** * The body origin transform. */ public final Transform m_xf = new Transform(); /** * The previous transform for particle simulation */ public final Transform m_xf0 = new Transform(); /** * The swept motion for CCD */ public final Sweep m_sweep = new Sweep(); public final Vec2 m_linearVelocity = new Vec2(); public float m_angularVelocity = 0; public final Vec2 m_force = new Vec2(); public float m_torque = 0; public World m_world; public Body m_prev; public Body m_next; public Fixture m_fixtureList; public int m_fixtureCount; public JointEdge m_jointList; public ContactEdge m_contactList; public float m_mass, m_invMass; // Rotational inertia about the center of mass. public float m_I, m_invI; public float m_linearDamping; public float m_angularDamping; public float m_gravityScale; public float m_sleepTime; public Object m_userData; public Body(final BodyDef bd, World world) { assert (bd.position.isValid()); assert (bd.linearVelocity.isValid()); assert (bd.gravityScale >= 0.0f); assert (bd.angularDamping >= 0.0f); assert (bd.linearDamping >= 0.0f); m_flags = 0; if (bd.bullet) { m_flags |= e_bulletFlag; } if (bd.fixedRotation) { m_flags |= e_fixedRotationFlag; } if (bd.allowSleep) { m_flags |= e_autoSleepFlag; } if (bd.awake) { m_flags |= e_awakeFlag; } if (bd.active) { m_flags |= e_activeFlag; } m_world = world; m_xf.p.set(bd.position); m_xf.q.set(bd.angle); m_sweep.localCenter.setZero(); m_sweep.c0.set(m_xf.p); m_sweep.c.set(m_xf.p); m_sweep.a0 = bd.angle; m_sweep.a = bd.angle; m_sweep.alpha0 = 0.0f; m_jointList = null; m_contactList = null; m_prev = null; m_next = null; m_linearVelocity.set(bd.linearVelocity); m_angularVelocity = bd.angularVelocity; m_linearDamping = bd.linearDamping; m_angularDamping = bd.angularDamping; m_gravityScale = bd.gravityScale; m_force.setZero(); m_torque = 0.0f; m_sleepTime = 0.0f; m_type = bd.type; if (m_type == BodyType.DYNAMIC) { m_mass = 1f; m_invMass = 1f; } else { m_mass = 0f; m_invMass = 0f; } m_I = 0.0f; m_invI = 0.0f; m_userData = bd.userData; m_fixtureList = null; m_fixtureCount = 0; } /** * Creates a fixture and attach it to this body. Use this function if you need to set some fixture * parameters, like friction. Otherwise you can create the fixture directly from a shape. If the * density is non-zero, this function automatically updates the mass of the body. Contacts are not * created until the next time step. * * @param def the fixture definition. * @warning This function is locked during callbacks. */ public final Fixture createFixture(FixtureDef def) { assert (m_world.isLocked() == false); if (m_world.isLocked() == true) { return null; } Fixture fixture = new Fixture(); fixture.create(this, def); if ((m_flags & e_activeFlag) == e_activeFlag) { BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase; fixture.createProxies(broadPhase, m_xf); } fixture.m_next = m_fixtureList; m_fixtureList = fixture; ++m_fixtureCount; fixture.m_body = this; // Adjust mass properties if needed. if (fixture.m_density > 0.0f) { resetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. m_world.m_flags |= World.NEW_FIXTURE; return fixture; } private final FixtureDef fixDef = new FixtureDef(); /** * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use * FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. * If the density is non-zero, this function automatically updates the mass of the body. * * @param shape the shape to be cloned. * @param density the shape density (set to zero for static bodies). * @warning This function is locked during callbacks. */ public final Fixture createFixture(Shape shape, float density) { fixDef.shape = shape; fixDef.density = density; return createFixture(fixDef); } /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts * associated with this fixture. This will automatically adjust the mass of the body if the body * is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly * destroyed when the body is destroyed. * * @param fixture the fixture to be removed. * @warning This function is locked during callbacks. */ public final void destroyFixture(Fixture fixture) { assert (m_world.isLocked() == false); if (m_world.isLocked() == true) { return; } assert (fixture.m_body == this); // Remove the fixture from this body's singly linked list. assert (m_fixtureCount > 0); Fixture node = m_fixtureList; Fixture last = null; // java change boolean found = false; while (node != null) { if (node == fixture) { node = fixture.m_next; found = true; break; } last = node; node = node.m_next; } // You tried to remove a shape that is not attached to this body. assert (found); // java change, remove it from the list if (last == null) { m_fixtureList = fixture.m_next; } else { last.m_next = fixture.m_next; } // Destroy any contacts associated with the fixture. ContactEdge edge = m_contactList; while (edge != null) { Contact c = edge.contact; edge = edge.next; Fixture fixtureA = c.getFixtureA(); Fixture fixtureB = c.getFixtureB(); if (fixture == fixtureA || fixture == fixtureB) { // This destroys the contact and removes it from // this body's contact list. m_world.m_contactManager.destroy(c); } } if ((m_flags & e_activeFlag) == e_activeFlag) { BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase; fixture.destroyProxies(broadPhase); } fixture.destroy(); fixture.m_body = null; fixture.m_next = null; fixture = null; --m_fixtureCount; // Reset the mass data. resetMassData(); } /** * Set the position of the body's origin and rotation. This breaks any contacts and wakes the * other bodies. Manipulating a body's transform may cause non-physical behavior. Note: contacts * are updated on the next call to World.step(). * * @param position the world position of the body's local origin. * @param angle the world rotation in radians. */ public final void setTransform(Vec2 position, float angle) { assert (m_world.isLocked() == false); if (m_world.isLocked() == true) { return; } m_xf.q.set(angle); m_xf.p.set(position); // m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter); Transform.mulToOutUnsafe(m_xf, m_sweep.localCenter, m_sweep.c); m_sweep.a = angle; m_sweep.c0.set(m_sweep.c); m_sweep.a0 = m_sweep.a; BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase; for (Fixture f = m_fixtureList; f != null; f = f.m_next) { f.synchronize(broadPhase, m_xf, m_xf); } } /** * Get the body transform for the body's origin. * * @return the world transform of the body's origin. */ public final Transform getTransform() { return m_xf; } /** * Get the world body origin position. Do not modify. * * @return the world position of the body's origin. */ public final Vec2 getPosition() { return m_xf.p; } /** * Get the angle in radians. * * @return the current world rotation angle in radians. */ public final float getAngle() { return m_sweep.a; } /** * Get the world position of the center of mass. Do not modify. */ public final Vec2 getWorldCenter() { return m_sweep.c; } /** * Get the local position of the center of mass. Do not modify. */ public final Vec2 getLocalCenter() { return m_sweep.localCenter; } /** * Set the linear velocity of the center of mass. * * @param v the new linear velocity of the center of mass. */ public final void setLinearVelocity(Vec2 v) { if (m_type == BodyType.STATIC) { return; } if (Vec2.dot(v, v) > 0.0f) { setAwake(true); } m_linearVelocity.set(v); } /** * Get the linear velocity of the center of mass. Do not modify, instead use * {@link #setLinearVelocity(Vec2)}. * * @return the linear velocity of the center of mass. */ public final Vec2 getLinearVelocity() { return m_linearVelocity; } /** * Set the angular velocity. * * @param omega the new angular velocity in radians/second. */ public final void setAngularVelocity(float w) { if (m_type == BodyType.STATIC) { return; } if (w * w > 0f) { setAwake(true); } m_angularVelocity = w; } /** * Get the angular velocity. * * @return the angular velocity in radians/second. */ public final float getAngularVelocity() { return m_angularVelocity; } /** * Get the gravity scale of the body. * * @return */ public float getGravityScale() { return m_gravityScale; } /** * Set the gravity scale of the body. * * @param gravityScale */ public void setGravityScale(float gravityScale) { this.m_gravityScale = gravityScale; } /** * Apply a force at a world point. If the force is not applied at the center of mass, it will * generate a torque and affect the angular velocity. This wakes up the body. * * @param force the world force vector, usually in Newtons (N). * @param point the world position of the point of application. */ public final void applyForce(Vec2 force, Vec2 point) { if (m_type != BodyType.DYNAMIC) { return; } if (isAwake() == false) { setAwake(true); } // m_force.addLocal(force); // Vec2 temp = tltemp.get(); // temp.set(point).subLocal(m_sweep.c); // m_torque += Vec2.cross(temp, force); m_force.x += force.x; m_force.y += force.y; m_torque += (point.x - m_sweep.c.x) * force.y - (point.y - m_sweep.c.y) * force.x; } /** * Apply a force to the center of mass. This wakes up the body. * * @param force the world force vector, usually in Newtons (N). */ public final void applyForceToCenter(Vec2 force) { if (m_type != BodyType.DYNAMIC) { return; } if (isAwake() == false) { setAwake(true); } m_force.x += force.x; m_force.y += force.y; } /** * Apply a torque. This affects the angular velocity without affecting the linear velocity of the * center of mass. This wakes up the body. * * @param torque about the z-axis (out of the screen), usually in N-m. */ public final void applyTorque(float torque) { if (m_type != BodyType.DYNAMIC) { return; } if (isAwake() == false) { setAwake(true); } m_torque += torque; } /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the * angular velocity if the point of application is not at the center of mass. This wakes up the * body if 'wake' is set to true. If the body is sleeping and 'wake' is false, then there is no * effect. * * @param impulse the world impulse vector, usually in N-seconds or kg-m/s. * @param point the world position of the point of application. * @param wake also wake up the body */ public final void applyLinearImpulse(Vec2 impulse, Vec2 point, boolean wake) { if (m_type != BodyType.DYNAMIC) { return; } if (!isAwake()) { if (wake) { setAwake(true); } else { return; } } m_linearVelocity.x += impulse.x * m_invMass; m_linearVelocity.y += impulse.y * m_invMass; m_angularVelocity += m_invI * ((point.x - m_sweep.c.x) * impulse.y - (point.y - m_sweep.c.y) * impulse.x); } /** * Apply an angular impulse. * * @param impulse the angular impulse in units of kg*m*m/s */ public void applyAngularImpulse(float impulse) { if (m_type != BodyType.DYNAMIC) { return; } if (isAwake() == false) { setAwake(true); } m_angularVelocity += m_invI * impulse; } /** * Get the total mass of the body. * * @return the mass, usually in kilograms (kg). */ public final float getMass() { return m_mass; } /** * Get the central rotational inertia of the body. * * @return the rotational inertia, usually in kg-m^2. */ public final float getInertia() { return m_I + m_mass * (m_sweep.localCenter.x * m_sweep.localCenter.x + m_sweep.localCenter.y * m_sweep.localCenter.y); } /** * Get the mass data of the body. The rotational inertia is relative to the center of mass. * * @return a struct containing the mass, inertia and center of the body. */ public final void getMassData(MassData data) { // data.mass = m_mass; // data.I = m_I + m_mass * Vec2.dot(m_sweep.localCenter, m_sweep.localCenter); // data.center.set(m_sweep.localCenter); data.mass = m_mass; data.I = m_I + m_mass * (m_sweep.localCenter.x * m_sweep.localCenter.x + m_sweep.localCenter.y * m_sweep.localCenter.y); data.center.x = m_sweep.localCenter.x; data.center.y = m_sweep.localCenter.y; } /** * Set the mass properties to override the mass properties of the fixtures. Note that this changes * the center of mass position. Note that creating or destroying fixtures can also alter the mass. * This function has no effect if the body isn't dynamic. * * @param massData the mass properties. */ public final void setMassData(MassData massData) { // TODO_ERIN adjust linear velocity and torque to account for movement of center. assert (m_world.isLocked() == false); if (m_world.isLocked() == true) { return; } if (m_type != BodyType.DYNAMIC) { return; } m_invMass = 0.0f; m_I = 0.0f; m_invI = 0.0f; m_mass = massData.mass; if (m_mass <= 0.0f) { m_mass = 1f; } m_invMass = 1.0f / m_mass; if (massData.I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) { m_I = massData.I - m_mass * Vec2.dot(massData.center, massData.center); assert (m_I > 0.0f); m_invI = 1.0f / m_I; } final Vec2 oldCenter = m_world.getPool().popVec2(); // Move center of mass. oldCenter.set(m_sweep.c); m_sweep.localCenter.set(massData.center); // m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter); Transform.mulToOutUnsafe(m_xf, m_sweep.localCenter, m_sweep.c0); m_sweep.c.set(m_sweep.c0); // Update center of mass velocity. // m_linearVelocity += Cross(m_angularVelocity, m_sweep.c - oldCenter); final Vec2 temp = m_world.getPool().popVec2(); temp.set(m_sweep.c).subLocal(oldCenter); Vec2.crossToOut(m_angularVelocity, temp, temp); m_linearVelocity.addLocal(temp); m_world.getPool().pushVec2(2); } private final MassData pmd = new MassData(); /** * This resets the mass properties to the sum of the mass properties of the fixtures. This * normally does not need to be called unless you called setMassData to override the mass and you * later want to reset the mass. */ public final void resetMassData() { // Compute mass data from shapes. Each shape has its own density. m_mass = 0.0f; m_invMass = 0.0f; m_I = 0.0f; m_invI = 0.0f; m_sweep.localCenter.setZero(); // Static and kinematic bodies have zero mass. if (m_type == BodyType.STATIC || m_type == BodyType.KINEMATIC) { // m_sweep.c0 = m_sweep.c = m_xf.position; m_sweep.c0.set(m_xf.p); m_sweep.c.set(m_xf.p); m_sweep.a0 = m_sweep.a; return; } assert (m_type == BodyType.DYNAMIC); // Accumulate mass over all fixtures. final Vec2 localCenter = m_world.getPool().popVec2(); localCenter.setZero(); final Vec2 temp = m_world.getPool().popVec2(); final MassData massData = pmd; for (Fixture f = m_fixtureList; f != null; f = f.m_next) { if (f.m_density == 0.0f) { continue; } f.getMassData(massData); m_mass += massData.mass; // center += massData.mass * massData.center; temp.set(massData.center).mulLocal(massData.mass); localCenter.addLocal(temp); m_I += massData.I; } // Compute center of mass. if (m_mass > 0.0f) { m_invMass = 1.0f / m_mass; localCenter.mulLocal(m_invMass); } else { // Force all dynamic bodies to have a positive mass. m_mass = 1.0f; m_invMass = 1.0f; } if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) { // Center the inertia about the center of mass. m_I -= m_mass * Vec2.dot(localCenter, localCenter); assert (m_I > 0.0f); m_invI = 1.0f / m_I; } else { m_I = 0.0f; m_invI = 0.0f; } Vec2 oldCenter = m_world.getPool().popVec2(); // Move center of mass. oldCenter.set(m_sweep.c); m_sweep.localCenter.set(localCenter); // m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter); Transform.mulToOutUnsafe(m_xf, m_sweep.localCenter, m_sweep.c0); m_sweep.c.set(m_sweep.c0); // Update center of mass velocity. // m_linearVelocity += Cross(m_angularVelocity, m_sweep.c - oldCenter); temp.set(m_sweep.c).subLocal(oldCenter); final Vec2 temp2 = oldCenter; Vec2.crossToOutUnsafe(m_angularVelocity, temp, temp2); m_linearVelocity.addLocal(temp2); m_world.getPool().pushVec2(3); } /** * Get the world coordinates of a point given the local coordinates. * * @param localPoint a point on the body measured relative the the body's origin. * @return the same point expressed in world coordinates. */ public final Vec2 getWorldPoint(Vec2 localPoint) { Vec2 v = new Vec2(); getWorldPointToOut(localPoint, v); return v; } public final void getWorldPointToOut(Vec2 localPoint, Vec2 out) { Transform.mulToOut(m_xf, localPoint, out); } /** * Get the world coordinates of a vector given the local coordinates. * * @param localVector a vector fixed in the body. * @return the same vector expressed in world coordinates. */ public final Vec2 getWorldVector(Vec2 localVector) { Vec2 out = new Vec2(); getWorldVectorToOut(localVector, out); return out; } public final void getWorldVectorToOut(Vec2 localVector, Vec2 out) { Rot.mulToOut(m_xf.q, localVector, out); } public final void getWorldVectorToOutUnsafe(Vec2 localVector, Vec2 out) { Rot.mulToOutUnsafe(m_xf.q, localVector, out); } /** * Gets a local point relative to the body's origin given a world point. * * @param a point in world coordinates. * @return the corresponding local point relative to the body's origin. */ public final Vec2 getLocalPoint(Vec2 worldPoint) { Vec2 out = new Vec2(); getLocalPointToOut(worldPoint, out); return out; } public final void getLocalPointToOut(Vec2 worldPoint, Vec2 out) { Transform.mulTransToOut(m_xf, worldPoint, out); } /** * Gets a local vector given a world vector. * * @param a vector in world coordinates. * @return the corresponding local vector. */ public final Vec2 getLocalVector(Vec2 worldVector) { Vec2 out = new Vec2(); getLocalVectorToOut(worldVector, out); return out; } public final void getLocalVectorToOut(Vec2 worldVector, Vec2 out) { Rot.mulTrans(m_xf.q, worldVector, out); } public final void getLocalVectorToOutUnsafe(Vec2 worldVector, Vec2 out) { Rot.mulTransUnsafe(m_xf.q, worldVector, out); } /** * Get the world linear velocity of a world point attached to this body. * * @param a point in world coordinates. * @return the world velocity of a point. */ public final Vec2 getLinearVelocityFromWorldPoint(Vec2 worldPoint) { Vec2 out = new Vec2(); getLinearVelocityFromWorldPointToOut(worldPoint, out); return out; } public final void getLinearVelocityFromWorldPointToOut(Vec2 worldPoint, Vec2 out) { final float tempX = worldPoint.x - m_sweep.c.x; final float tempY = worldPoint.y - m_sweep.c.y; out.x = -m_angularVelocity * tempY + m_linearVelocity.x; out.y = m_angularVelocity * tempX + m_linearVelocity.y; } /** * Get the world velocity of a local point. * * @param a point in local coordinates. * @return the world velocity of a point. */ public final Vec2 getLinearVelocityFromLocalPoint(Vec2 localPoint) { Vec2 out = new Vec2(); getLinearVelocityFromLocalPointToOut(localPoint, out); return out; } public final void getLinearVelocityFromLocalPointToOut(Vec2 localPoint, Vec2 out) { getWorldPointToOut(localPoint, out); getLinearVelocityFromWorldPointToOut(out, out); } /** Get the linear damping of the body. */ public final float getLinearDamping() { return m_linearDamping; } /** Set the linear damping of the body. */ public final void setLinearDamping(float linearDamping) { m_linearDamping = linearDamping; } /** Get the angular damping of the body. */ public final float getAngularDamping() { return m_angularDamping; } /** Set the angular damping of the body. */ public final void setAngularDamping(float angularDamping) { m_angularDamping = angularDamping; } public BodyType getType() { return m_type; } /** * Set the type of this body. This may alter the mass and velocity. * * @param type */ public void setType(BodyType type) { assert (m_world.isLocked() == false); if (m_world.isLocked() == true) { return; } if (m_type == type) { return; } m_type = type; resetMassData(); if (m_type == BodyType.STATIC) { m_linearVelocity.setZero(); m_angularVelocity = 0.0f; m_sweep.a0 = m_sweep.a; m_sweep.c0.set(m_sweep.c); synchronizeFixtures(); } setAwake(true); m_force.setZero(); m_torque = 0.0f; // Delete the attached contacts. ContactEdge ce = m_contactList; while (ce != null) { ContactEdge ce0 = ce; ce = ce.next; m_world.m_contactManager.destroy(ce0.contact); } m_contactList = null; // Touch the proxies so that new contacts will be created (when appropriate) BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase; for (Fixture f = m_fixtureList; f != null; f = f.m_next) { int proxyCount = f.m_proxyCount; for (int i = 0; i < proxyCount; ++i) { broadPhase.touchProxy(f.m_proxies[i].proxyId); } } } /** Is this body treated like a bullet for continuous collision detection? */ public final boolean isBullet() { return (m_flags & e_bulletFlag) == e_bulletFlag; } /** Should this body be treated like a bullet for continuous collision detection? */ public final void setBullet(boolean flag) { if (flag) { m_flags |= e_bulletFlag; } else { m_flags &= ~e_bulletFlag; } } /** * You can disable sleeping on this body. If you disable sleeping, the body will be woken. * * @param flag */ public void setSleepingAllowed(boolean flag) { if (flag) { m_flags |= e_autoSleepFlag; } else { m_flags &= ~e_autoSleepFlag; setAwake(true); } } /** * Is this body allowed to sleep * * @return */ public boolean isSleepingAllowed() { return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; } /** * Set the sleep state of the body. A sleeping body has very low CPU cost. * * @param flag set to true to put body to sleep, false to wake it. * @param flag */ public void setAwake(boolean flag) { if (flag) { if ((m_flags & e_awakeFlag) == 0) { m_flags |= e_awakeFlag; m_sleepTime = 0.0f; } } else { m_flags &= ~e_awakeFlag; m_sleepTime = 0.0f; m_linearVelocity.setZero(); m_angularVelocity = 0.0f; m_force.setZero(); m_torque = 0.0f; } } /** * Get the sleeping state of this body. * * @return true if the body is awake. */ public boolean isAwake() { return (m_flags & e_awakeFlag) == e_awakeFlag; } /** * Set the active state of the body. An inactive body is not simulated and cannot be collided with * or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you * pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will * be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy * fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive * and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive * body are implicitly inactive. An inactive body is still owned by a World object and remains in * the body list. * * @param flag */ public void setActive(boolean flag) { assert (m_world.isLocked() == false); if (flag == isActive()) { return; } if (flag) { m_flags |= e_activeFlag; // Create all proxies. BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase; for (Fixture f = m_fixtureList; f != null; f = f.m_next) { f.createProxies(broadPhase, m_xf); } // Contacts are created the next time step. } else { m_flags &= ~e_activeFlag; // Destroy all proxies. BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase; for (Fixture f = m_fixtureList; f != null; f = f.m_next) { f.destroyProxies(broadPhase); } // Destroy the attached contacts. ContactEdge ce = m_contactList; while (ce != null) { ContactEdge ce0 = ce; ce = ce.next; m_world.m_contactManager.destroy(ce0.contact); } m_contactList = null; } } /** * Get the active state of the body. * * @return */ public boolean isActive() { return (m_flags & e_activeFlag) == e_activeFlag; } /** * Set this body to have fixed rotation. This causes the mass to be reset. * * @param flag */ public void setFixedRotation(boolean flag) { if (flag) { m_flags |= e_fixedRotationFlag; } else { m_flags &= ~e_fixedRotationFlag; } resetMassData(); } /** * Does this body have fixed rotation? * * @return */ public boolean isFixedRotation() { return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; } /** Get the list of all fixtures attached to this body. */ public final Fixture getFixtureList() { return m_fixtureList; } /** Get the list of all joints attached to this body. */ public final JointEdge getJointList() { return m_jointList; } /** * Get the list of all contacts attached to this body. * * @warning this list changes during the time step and you may miss some collisions if you don't * use ContactListener. */ public final ContactEdge getContactList() { return m_contactList; } /** Get the next body in the world's body list. */ public final Body getNext() { return m_next; } /** Get the user data pointer that was provided in the body definition. */ public final Object getUserData() { return m_userData; } /** * Set the user data. Use this to store your application specific data. */ public final void setUserData(Object data) { m_userData = data; } /** * Get the parent world of this body. */ public final World getWorld() { return m_world; } // djm pooling private final Transform pxf = new Transform(); protected final void synchronizeFixtures() { final Transform xf1 = pxf; // xf1.position = m_sweep.c0 - Mul(xf1.R, m_sweep.localCenter); // xf1.q.set(m_sweep.a0); // Rot.mulToOutUnsafe(xf1.q, m_sweep.localCenter, xf1.p); // xf1.p.mulLocal(-1).addLocal(m_sweep.c0); // inlined: xf1.q.s = MathUtils.sin(m_sweep.a0); xf1.q.c = MathUtils.cos(m_sweep.a0); xf1.p.x = m_sweep.c0.x - xf1.q.c * m_sweep.localCenter.x + xf1.q.s * m_sweep.localCenter.y; xf1.p.y = m_sweep.c0.y - xf1.q.s * m_sweep.localCenter.x - xf1.q.c * m_sweep.localCenter.y; // end inline for (Fixture f = m_fixtureList; f != null; f = f.m_next) { f.synchronize(m_world.m_contactManager.m_broadPhase, xf1, m_xf); } } public final void synchronizeTransform() { // m_xf.q.set(m_sweep.a); // // // m_xf.position = m_sweep.c - Mul(m_xf.R, m_sweep.localCenter); // Rot.mulToOutUnsafe(m_xf.q, m_sweep.localCenter, m_xf.p); // m_xf.p.mulLocal(-1).addLocal(m_sweep.c); // m_xf.q.s = MathUtils.sin(m_sweep.a); m_xf.q.c = MathUtils.cos(m_sweep.a); Rot q = m_xf.q; Vec2 v = m_sweep.localCenter; m_xf.p.x = m_sweep.c.x - q.c * v.x + q.s * v.y; m_xf.p.y = m_sweep.c.y - q.s * v.x - q.c * v.y; } /** * This is used to prevent connected bodies from colliding. It may lie, depending on the * collideConnected flag. * * @param other * @return */ public boolean shouldCollide(Body other) { // At least one body should be dynamic. if (m_type != BodyType.DYNAMIC && other.m_type != BodyType.DYNAMIC) { return false; } // Does a joint prevent collision? for (JointEdge jn = m_jointList; jn != null; jn = jn.next) { if (jn.other == other) { if (jn.joint.getCollideConnected() == false) { return false; } } } return true; } protected final void advance(float t) { // Advance to the new safe time. This doesn't sync the broad-phase. m_sweep.advance(t); m_sweep.c.set(m_sweep.c0); m_sweep.a = m_sweep.a0; m_xf.q.set(m_sweep.a); // m_xf.position = m_sweep.c - Mul(m_xf.R, m_sweep.localCenter); Rot.mulToOutUnsafe(m_xf.q, m_sweep.localCenter, m_xf.p); m_xf.p.mulLocal(-1).addLocal(m_sweep.c); } }
michaelboccara/jbox2d
<|start_filename|>_components/offcanvas/offcanvas.html<|end_filename|> <button class="fr-offcanvas-open js-fr-offcanvas-open" aria-controls="offcanvas-1"> Open #1 </button> <button class="fr-offcanvas-open js-fr-offcanvas-open" aria-controls="offcanvas-2"> Open #2 </button> <section class="fr-offcanvas fr-offcanvas--left js-fr-offcanvas" id="offcanvas-1"> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim <a href="#">ipsam voluptatem</a> quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor. </p> <p> Sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem <a href="#">ullam corporis suscipit</a> laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa, sunt modi! Nobis ab quia soluta, perspiciatis <a href="#">laudantium eveniet</a> quaerat sed, quod hic debitis earum repellendus optio, inventore ex facere possimus. </p> <button class="fr-offcanvas-close js-fr-offcanvas-close"> Close </button> </section> <section class="fr-offcanvas js-fr-offcanvas" id="offcanvas-2"> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim <a href="#">ipsam voluptatem</a> quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor. </p> <button class="fr-offcanvas-close js-fr-offcanvas-close"> Close </button> </section> <|start_filename|>_components/dialogmodal/package.json<|end_filename|> { "name": "fr-dialogmodal", "version": "1.0.4", "description": "Frend's accessible, modern modal component.", "homepage": "https://frend.co/components/dialogmodal", "main": "dialogmodal.js", "style": "dialogmodal.css", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/frend/frend.co/tree/gh-pages/_components/dialogmodal" }, "keywords": [ "dialogmodal", "dialog", "modal", "alert", "accessible", "es2015" ], "author": "Frend <<EMAIL>> (https://frend.co)", "license": "MIT", "bugs": { "url": "https://github.com/frend/frend.co/issues" } } <|start_filename|>js/modules/webfont-detector.js<|end_filename|> if (sessionStorage.FontsLoaded) { document.documentElement.className += ' fonts-loaded'; } <|start_filename|>js/master.js<|end_filename|> /** * Global scripts */ import webFontLoader from './modules/webfont-loader'; // Run webFontLoader(); <|start_filename|>_components/accordion/accordion.js<|end_filename|> 'use strict'; /** * @param {object} options Object containing configuration overrides */ const Fraccordion = function ({ selector: selector = '.js-fr-accordion', headerSelector: headerSelector = '.js-fr-accordion__header', headerIdPrefix: headerIdPrefix = 'accordion-header', panelSelector: panelSelector = '.js-fr-accordion__panel', panelIdPrefix: panelIdPrefix = 'accordion-panel', firstPanelsOpenByDefault: firstPanelsOpenByDefault = true, multiselectable: multiselectable = true, readyClass: readyClass = 'fr-accordion--is-ready', transitionLength: transitionLength = 250 } = {}) { // CONSTANTS const doc = document; const docEl = doc.documentElement; const _q = (el, ctx = doc) => [].slice.call(ctx.querySelectorAll(el)); // SUPPORTS if (!('querySelector' in doc) || !('addEventListener' in window) || !docEl.classList) return; // SETUP // set accordion element NodeLists let accordionContainers = _q(selector); // A11Y function _addA11y (accordionContainer) { // get accordion elements const accordionHeaders = _q(headerSelector, accordionContainer); const accordionPanels = _q(panelSelector, accordionContainer); // add relevant roles and properties accordionContainer.setAttribute('role', 'tablist'); accordionContainer.setAttribute('aria-multiselectable', multiselectable); accordionHeaders.forEach((accordionHeader) => { accordionHeader.setAttribute('role', 'tab'); accordionHeader.setAttribute('aria-controls', accordionHeader.id.replace(headerIdPrefix, panelIdPrefix)); // make headers focusable, this is preferred over wrapping contents in native button element accordionHeader.setAttribute('tabindex', 0); }); accordionPanels.forEach((accordionPanel) => { accordionPanel.setAttribute('role', 'tabpanel'); accordionPanel.setAttribute('aria-labelledby', accordionPanel.id.replace(panelIdPrefix, headerIdPrefix)); // make tabpanel focusable accordionPanel.setAttribute('tabindex', 0); }); } function _removeA11y (accordionContainer) { // get accordion elements const accordionHeaders = _q(headerSelector, accordionContainer); const accordionPanels = _q(panelSelector, accordionContainer); // remove roles and properties accordionContainer.removeAttribute('role'); accordionContainer.removeAttribute('aria-multiselectable'); accordionHeaders.forEach((accordionHeader) => { accordionHeader.removeAttribute('role'); accordionHeader.removeAttribute('aria-controls'); accordionHeader.removeAttribute('aria-selected'); accordionHeader.removeAttribute('aria-expanded'); // remove headers focusablility accordionHeader.removeAttribute('tabindex'); }); accordionPanels.forEach((accordionPanel) => { accordionPanel.removeAttribute('role'); accordionPanel.removeAttribute('aria-labelledby'); accordionPanel.removeAttribute('aria-hidden'); // remove tabpanel focusablibility accordionPanel.removeAttribute('tabindex'); }); } // UTILS function _getPanelHeight (panel) { // set auto height and read offsetHeight panel.style.height = 'auto'; let height = panel.offsetHeight; // remove style panel.style.height = ''; return height; } function _setPanelHeight (panel) { // get panel height let panelHeight = _getPanelHeight(panel); // recalc style and layout panel.getBoundingClientRect(); // set height on panel, reset to 'auto' on transition complete panel.style.height = panelHeight + 'px'; setTimeout(() => { panel.style.transition = 'none'; panel.style.height = 'auto' // recalc style and layout panel.getBoundingClientRect(); panel.style.transition = ''; }, transitionLength); } function _unsetPanelHeight (panel) { // get panel height let panelHeight = _getPanelHeight(panel); // set panel height from 'auto' to px panel.style.height = panelHeight + 'px'; // recalc style and layout panel.getBoundingClientRect(); // reset height panel.style.height = 0; } // ACTIONS function _hideAllPanels (accordionContainer) { // get accordion elements const siblingHeaders = _q(headerSelector, accordionContainer); const siblingPanels = _q(panelSelector, accordionContainer); // set inactives siblingHeaders.forEach((header) => { header.setAttribute('tabindex', -1); header.setAttribute('aria-selected', 'false'); header.setAttribute('aria-expanded', 'false'); }); siblingPanels.forEach((panel) => { if (panel.getAttribute('aria-hidden') === 'false') _unsetPanelHeight(panel); // toggle aria-hidden panel.setAttribute('aria-hidden', 'true'); }); } function _hidePanel (target) { // get panel let activePanel = doc.getElementById(target.getAttribute('aria-controls')); target.setAttribute('aria-selected', 'false'); target.setAttribute('aria-expanded', 'false'); // toggle aria-hidden _unsetPanelHeight(activePanel); activePanel.setAttribute('aria-hidden', 'true'); } function _showPanel (target) { // get panel let activePanel = doc.getElementById(target.getAttribute('aria-controls')); // set attributes on header target.setAttribute('tabindex', 0); target.setAttribute('aria-selected', 'true'); target.setAttribute('aria-expanded', 'true'); // toggle aria-hidden and set height on panel _setPanelHeight(activePanel); activePanel.setAttribute('aria-hidden', 'false'); setTimeout(() => _bindAccordionEvents(target.parentNode), transitionLength); } function _togglePanel (target) { // get context of accordion container and its children let thisContainer = target.parentNode; // close target panel if already active if (target.getAttribute('aria-selected') === 'true') { _hidePanel(target); return; } // if not multiselectable hide all, then show target if (!multiselectable) _hideAllPanels(thisContainer); _showPanel(target); if (transitionLength > 0) _unbindAccordionEvents(thisContainer); } function _giveHeaderFocus (headerSet, i) { // remove focusability from inactives headerSet.forEach((header) => { header.setAttribute('tabindex', -1); }); // set active focus headerSet[i].setAttribute('tabindex', 0); headerSet[i].focus(); } // EVENTS function _eventHeaderClick (e) { _togglePanel(e.currentTarget); } function _eventHeaderKeydown (e) { // collect header targets, and their prev/next let currentHeader = e.currentTarget; let isModifierKey = e.metaKey || e.altKey; // get context of accordion container and its children let thisContainer = currentHeader.parentNode; let theseHeaders = _q(headerSelector, thisContainer); let currentHeaderIndex = [].indexOf.call(theseHeaders, currentHeader); // don't catch key events when ⌘ or Alt modifier is present if (isModifierKey) return; // catch enter/space, left/right and up/down arrow key events // if new panel show it, if next/prev move focus switch (e.keyCode) { case 13: case 32: _togglePanel(currentHeader); e.preventDefault(); break; case 37: case 38: { let previousHeaderIndex = (currentHeaderIndex === 0) ? theseHeaders.length - 1 : currentHeaderIndex - 1; _giveHeaderFocus(theseHeaders, previousHeaderIndex); e.preventDefault(); break; } case 39: case 40: { let nextHeaderIndex = (currentHeaderIndex < theseHeaders.length - 1) ? currentHeaderIndex + 1 : 0; _giveHeaderFocus(theseHeaders, nextHeaderIndex); e.preventDefault(); break; } default: break; } } // BIND EVENTS function _bindAccordionEvents (accordionContainer) { const accordionHeaders = _q(headerSelector, accordionContainer); // bind all accordion header click and keydown events accordionHeaders.forEach((accordionHeader) => { accordionHeader.addEventListener('click', _eventHeaderClick); accordionHeader.addEventListener('keydown', _eventHeaderKeydown); }); } // UNBIND EVENTS function _unbindAccordionEvents (accordionContainer) { const accordionHeaders = _q(headerSelector, accordionContainer); // unbind all accordion header click and keydown events accordionHeaders.forEach((accordionHeader) => { accordionHeader.removeEventListener('click', _eventHeaderClick); accordionHeader.removeEventListener('keydown', _eventHeaderKeydown); }); } // DESTROY function destroy () { accordionContainers.forEach((accordionContainer) => { _removeA11y(accordionContainer); _unbindAccordionEvents(accordionContainer); accordionContainer.classList.remove(readyClass); }); } // INIT function init () { if (accordionContainers.length) { accordionContainers.forEach((accordionContainer) => { _addA11y(accordionContainer); _bindAccordionEvents(accordionContainer); _hideAllPanels(accordionContainer); // set all first accordion panels active on init if required (default behaviour) // otherwise make sure first accordion header for each is focusable if (firstPanelsOpenByDefault) { _togglePanel(accordionContainer.querySelector(headerSelector)); } else { accordionContainer.querySelector(headerSelector).setAttribute('tabindex', 0); } // set ready style hook accordionContainer.classList.add(readyClass); }); } } init(); // REVEAL API return { init, destroy } } // module exports export default Fraccordion; <|start_filename|>_components/dialogmodal/dialogmodal.css<|end_filename|> .fr-dialogmodal--is-ready { height: 100%; left: 0; position: fixed; top: 0; width: 100%; z-index: 10; } .fr-dialogmodal--is-ready .fr-dialogmodal-modal { left: 50%; position: absolute; top: 50%; -webkit-transform: translateX(-50%) translateY(-50%); /* Modal blurs when using translate3d */ transform: translateX(-50%) translateY(-50%); /* Modal blurs when using translate3d */ } .fr-dialogmodal--is-ready[aria-hidden="true"] { visibility: hidden; } .fr-dialogmodal--is-ready[aria-hidden="false"] { visibility: visible; } <|start_filename|>gulpfile.js<|end_filename|> //---------------------------------------------------------------------- // Modules //---------------------------------------------------------------------- // Files var pkg = require('./package.json'); var config = require('./webpack.config.js'); // Global var cache = require('gulp-cached'); var clean = require('gulp-clean'); var gulp = require('gulp'); var rename = require('gulp-rename'); var runSequence = require('run-sequence'); // CSS var autoprefixer = require('autoprefixer'); var nano = require('gulp-cssnano'); var sass = require('gulp-sass'); var scsslint = require('gulp-scss-lint'); var sourcemaps = require('gulp-sourcemaps'); var postcss = require('gulp-postcss'); // JS var concat = require('gulp-concat'); var eslint = require('gulp-eslint'); var uglify = require('gulp-uglify'); var webpack = require('webpack-stream'); // Components var babelify = require('babelify'); var browserify = require('browserify'); var buffer = require('vinyl-buffer'); var es = require('event-stream'); var glob = require('glob'); var source = require('vinyl-source-stream'); //---------------------------------------------------------------------- // Setup //---------------------------------------------------------------------- var src = { css: { master: './css/master.scss', project: [ './css/**/*.scss', './css/master.scss', '!./css/site/_generic.reset.scss', '!./css/site/_components.syntax.scss', '!./css/site/_tools.mq.scss' ], output: 'global', dist: './css/dist/' }, js: { initial: { project: [ './node_modules/fg-loadcss/src/loadCSS.js', './node_modules/fg-loadjs/loadJS.js', './js/modules/webfont-detector.js', './js/modules/feature-detection.js' ], output: 'initial' }, global: { master: './js/master.js', project: [ './js/master.js', './js/modules/*.js', '!./js/_vendor/*.js', '!./js/dist/*.js' ], output: 'global' }, dist: './js/dist/' }, component: { prefix: 'Fr', path: './_components/', project: [ './_components/**/*.js', '!./_components/**/dist/*.js' ] }, includes: './_includes/_assets/' }; var options = { sass: { includePaths: ['./css/scss'], errLogToConsole: true }, autoprefixer: { browsers: ['last 4 versions'], flexbox: 'no-2009', remove: false }, babelify: { presets: ['es2015'], plugins: ['add-module-exports'] } }; //---------------------------------------------------------------------- // Tasks //---------------------------------------------------------------------- // Lint //---------------------------------------------------------------------- gulp.task('lint:css', function () { return gulp.src(src.css.project) .pipe(cache('scsslint')) .pipe(scsslint()) .pipe(scsslint.failReporter()); }); gulp.task('lint:js', function () { return gulp.src(src.js.global.project) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:component', function () { return gulp.src(src.component.project) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); // Clean //---------------------------------------------------------------------- gulp.task('clean:css', function () { return gulp.src(src.css.dist, { read: false }).pipe(clean()); }); gulp.task('clean:js', function () { return gulp.src(src.js.dist, { read: false }).pipe(clean()); }); // Build //---------------------------------------------------------------------- gulp.task('build:css', function () { return gulp.src(src.css.master) // compile & transform .pipe(sass(options.sass)) .pipe(sourcemaps.init()) .pipe(postcss([ autoprefixer(options.autoprefixer) ])) .pipe(sourcemaps.write()) // save minified output .pipe(nano()) .pipe(rename(src.css.output + '.min.css')) .pipe(gulp.dest(src.css.dist)); }); gulp.task('build:js:initial', function () { return gulp.src(src.js.initial.project) .pipe(concat(src.js.initial.output)) // save minified output .pipe(uglify()) .pipe(rename(src.js.initial.output + '.min.js')) .pipe(gulp.dest(src.js.dist)) .pipe(gulp.dest(src.includes)); }); gulp.task('build:js:global', function () { return gulp.src(src.js.global.master) // bundle modules .pipe(webpack(config)) // save minified output .pipe(uglify()) .pipe(rename(src.js.global.output + '.min.js')) .pipe(gulp.dest(src.js.dist)); }); gulp.task('build:component', function (done) { // use glob to catch file names/directories glob(src.component.path + '*/*.js', function(err, files) { // catch errors if (err) done(err); // create task per file var tasks = files.map(function (entry) { // get file props var dir = entry.split(src.component.path)[1], name = dir.split('/')[0]; // use this to expose standalone module name return browserify({ entries: [entry], debug: true, // includes sourcemaps standalone: src.component.prefix + name }) .transform(babelify, options.babelify) .bundle() .pipe(source(entry)) .pipe(buffer()) .pipe(uglify()) .pipe(rename({ dirname: '', extname: '.min.js', prefix: src.component.prefix.toLowerCase() })) .pipe(gulp.dest(src.component.path + name + '/dist')); }); es.merge(tasks).on('end', done); }); }); // Watch //---------------------------------------------------------------------- gulp.task('watch', function () { gulp.watch(src.css.project, ['lint:css', 'build:css']); gulp.watch(src.js.global.project, ['lint:js', 'build:js:global']); gulp.watch(src.component.project, ['lint:component', 'build:component']); }); // Default tasks //---------------------------------------------------------------------- // SITE //--------------- // 'gulp' - Runs build gulp.task('default', ['build']); // 'gulp lint' - Lints CSS/JS project files gulp.task('lint', ['lint:css', 'lint:js']); // 'gulp clean' - Cleans CSS/JS dist directories gulp.task('clean', ['clean:css', 'clean:js']); // 'gulp build' - Lints, cleans, builds modernizr then builds CSS/JS output files, lint errors halt build gulp.task('build', function (callback) { runSequence( ['lint'], ['clean'], ['build:css', 'build:js:initial', 'build:js:global'], callback ); }); // COMPONENTS //--------------- // 'gulp component' - Lints and builds JS output for components, lint errors halt build gulp.task('component', function (callback) { runSequence( ['lint:component'], ['build:component'], callback ); }); <|start_filename|>_components/tabs/tabs.css<|end_filename|> /* Container */ .fr-tabs { } /* Tablist */ .fr-tabs__tablist { } .fr-tabs--is-ready .fr-tabs__tablist-item { display: inline; } .fr-tabs__tab { } .fr-tabs__tab[tabindex="0"] { } /* Tabpanel */ .fr-tabs__panel { } .fr-tabs__panel[aria-hidden="true"] { display: none; } <|start_filename|>_components/tooltip/tooltip.js<|end_filename|> 'use strict'; // Polyfill matches as per https://github.com/jonathantneal/closest Element.prototype.matches = Element.prototype.matches || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector; /** * @param {object} options Object containing configuration overrides */ const Frtooltip = function ({ selector: selector = '.js-fr-tooltip', tooltipSelector: tooltipSelector = '.js-fr-tooltip-tooltip', toggleSelector: toggleSelector = '.js-fr-tooltip-toggle', tooltipIdPrefix: tooltipIdPrefix = 'tooltip', readyClass: readyClass = 'fr-tooltip--is-ready' } = {}) { // CONSTANTS const doc = document; const docEl = doc.documentElement; const _q = (el, ctx = doc) => [].slice.call(ctx.querySelectorAll(el)); // SUPPORTS if (!('querySelector' in doc) || !('addEventListener' in window) || !docEl.classList) return; // SETUP let tooltipContainers = _q(selector); // TEMP let currTooltip = null; // UTILS function _defer (fn) { // wrapped in setTimeout to delay binding until previous rendering has completed if (typeof fn === 'function') setTimeout(fn, 0); } function _closest (el, selector) { while (el) { if (el.matches(selector)) break; el = el.parentElement; } return el; } // A11Y function _addA11y (container, i) { // get relative elements let toggle = _q(toggleSelector, container)[0]; let tooltip = _q(tooltipSelector, container)[0]; // create new button and replace toggle var button = doc.createElement('button'); button.setAttribute('class', toggle.getAttribute('class')); button.setAttribute('aria-expanded', 'false'); button.setAttribute('aria-describedby', ''); button.textContent = toggle.textContent; container.replaceChild(button, toggle); // add tooltip attributes tooltip.setAttribute('role', 'tooltip'); tooltip.setAttribute('id', tooltipIdPrefix + '-' + i); tooltip.setAttribute('aria-hidden', 'true'); tooltip.setAttribute('aria-live', 'polite'); } function _removeA11y (container) { // get relative elements let toggle = _q(toggleSelector, container)[0]; let tooltip = _q(tooltipSelector, container)[0]; // create new span and replace toggle var span = doc.createElement('span'); span.setAttribute('class', toggle.getAttribute('class')); span.textContent = toggle.textContent; container.replaceChild(span, toggle); // remove tooltip attributes tooltip.removeAttribute('role'); tooltip.removeAttribute('id'); tooltip.removeAttribute('aria-hidden'); tooltip.removeAttribute('aria-live'); } // ACTIONS function _showTooltip (toggle, tooltip) { // assign describedby matching tooltip reference let tooltipId = tooltip.getAttribute('id'); toggle.setAttribute('aria-describedby', tooltipId); // set visible state toggle.setAttribute('aria-expanded', 'true'); tooltip.setAttribute('aria-hidden', 'false'); // store temp reference to tooltip currTooltip = tooltip; // bind doc close events _defer(_bindDocClick); _defer(_bindDocKey); } function _hideTooltip (toggle, tooltip) { // remove tooltip reference toggle.setAttribute('aria-describedby', ''); // set visible state toggle.setAttribute('aria-expanded', 'false'); tooltip.setAttribute('aria-hidden', 'true'); // remove tooltip temp reference currTooltip = null; // unbind doc close events _unbindDocClick(); _unbindDocKey(); } function destroy () { tooltipContainers.forEach((container, i) => { _removeA11y(container, i); _unbindToggleEvents(container); container.classList.remove(readyClass); }); // reset temp references currTooltip = null; // unbind global events _unbindDocClick(); _unbindDocKey(); } // EVENTS function _eventTogglePointer (e) { // close any open tooltips if (currTooltip) _hideTooltip(currTooltip.previousElementSibling, currTooltip); // get relevant tooltip elements let toggle = e.target; let tooltip = toggle.nextElementSibling; // show or hide if toggle is 'expanded' if (toggle.getAttribute('aria-expanded') === 'false') { _showTooltip(toggle, tooltip); } else { _hideTooltip(toggle, tooltip); } } function _eventTogglePointerLeave () { if (currTooltip) _hideTooltip(currTooltip.previousElementSibling, currTooltip); } function _eventDocClick (e) { // check if target is panel or child of let isTooltip = e.target === currTooltip; let isTooltipchild = _closest(e.target, tooltipSelector); if (!isTooltip && !isTooltipchild) _hideTooltip(currTooltip.previousElementSibling, currTooltip); } function _eventDocKey (e) { // esc key if (e.keyCode === 27) _hideTooltip(currTooltip.previousElementSibling, currTooltip); } // BIND EVENTS function _bindToggleEvents (container) { const toggle = _q(toggleSelector, container)[0]; toggle.addEventListener('click', _eventTogglePointer); toggle.addEventListener('mouseenter', _eventTogglePointer); toggle.addEventListener('mouseleave', _eventTogglePointerLeave); } function _bindDocClick () { doc.addEventListener('click', _eventDocClick); doc.addEventListener('touchstart', _eventDocClick); } function _bindDocKey () { doc.addEventListener('keydown', _eventDocKey); } // UNBIND EVENTS function _unbindToggleEvents (container) { const toggle = _q(toggleSelector, container)[0]; toggle.removeEventListener('click', _eventTogglePointer); toggle.removeEventListener('mouseenter', _eventTogglePointer); toggle.removeEventListener('mouseleave', _eventTogglePointerLeave); } function _unbindDocClick () { doc.removeEventListener('click', _eventDocClick); doc.removeEventListener('touchstart', _eventDocClick); } function _unbindDocKey () { doc.removeEventListener('keydown', _eventDocKey); } // INIT function init () { if (!tooltipContainers) return; // loop through each tooltip element tooltipContainers.forEach((container, i) => { _addA11y(container, i); _bindToggleEvents(container); container.classList.add(readyClass); }); } init(); // REVEAL API return { init, destroy } } // module exports export default Frtooltip; <|start_filename|>_components/accordion/accordion.html<|end_filename|> <div class="fr-accordion js-fr-accordion"> <h2 id="accordion-header-1" class="fr-accordion__header js-fr-accordion__header">Accordion header 1</h2> <div id="accordion-panel-1" class="fr-accordion__panel js-fr-accordion__panel"> <div class="fr-accordion__inner"> <h3>Accordion panel 1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> <h2 id="accordion-header-2" class="fr-accordion__header js-fr-accordion__header">Accordion header 2</h2> <div id="accordion-panel-2" class="fr-accordion__panel js-fr-accordion__panel"> <div class="fr-accordion__inner"> <h3>Accordion panel 2</h3> <p>Mauris rhoncus commodo sapien, eu porttitor libero gravida at. Maecenas a dapibus lorem. Suspendisse fermentum neque ligula, et dapibus libero volutpat scelerisque. Cras vitae enim interdum, fringilla sapien quis, posuere purus. Morbi dictum arcu sapien, eget malesuada lorem ultricies non. Etiam tellus neque, dapibus ac rutrum ut, mollis vel nibh.</p> </div> </div> <h2 id="accordion-header-3" class="fr-accordion__header js-fr-accordion__header">Accordion header 3</h2> <div id="accordion-panel-3" class="fr-accordion__panel js-fr-accordion__panel"> <div class="fr-accordion__inner"> <h3>Accordion panel 3</h3> <p>Quisque facilisis fermentum ex, in iaculis felis porta et. Phasellus sapien neque, sagittis vitae erat vitae, consequat vulputate lacus. Donec sit amet mattis ipsum. Ut metus ipsum, consectetur tincidunt imperdiet sed, consequat sed urna. Morbi id feugiat magna. Nunc ut aliquet quam. Morbi auctor sapien quam. Cras lorem neque, imperdiet ut mollis non, cursus scelerisque augue.</p> </div> </div> </div> <|start_filename|>_components/tooltip/tooltip.css<|end_filename|> /* Container */ .fr-tooltip--is-ready { position: relative; } /* Toolip */ .fr-tooltip--is-ready .fr-tooltip-tooltip { bottom: 100%; position: absolute; visibility: hidden; } .fr-tooltip--is-ready .fr-tooltip-tooltip[aria-hidden="false"] { visibility: visible; } /* No JS */ .fr-tooltip:not(.fr-tooltip--is-ready) .fr-tooltip-tooltip::before { content: " ("; } .fr-tooltip:not(.fr-tooltip--is-ready) .fr-tooltip-tooltip::after { content: ")"; } <|start_filename|>_components/dialogmodal/dialogmodal.html<|end_filename|> <button class="fr-dialogmodal-open js-fr-dialogmodal-open" aria-controls="modal-1" type="button"> Open Dialog </button> <div class="fr-dialogmodal js-fr-dialogmodal" id="modal-1"> <div class="fr-dialogmodal-modal js-fr-dialogmodal-modal" aria-labelledby="modal-1-title"> <div role="document"> <h2 id="modal-1-title">Dialog title</h2> <p>Lorem ipsum <a href="#">exercitation</a> sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ullamco laboris nisi ut <a href="#">commodo</a> ex ea consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla <a href="#">reprehenderit</a>. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <button class="fr-dialogmodal-close js-fr-dialogmodal-close" aria-label="Close Dialog" type="button"> ✕ </button> </div> </div> </div> <|start_filename|>_components/bypasslinks/bypasslinks.css<|end_filename|> .js-fr-bypasslinks { left: 0; position: fixed; top: 0; z-index: 100; } .js-fr-bypasslinks a { display: inline-block; position: absolute; top: -200%; white-space: nowrap; } .js-fr-bypasslinks a:focus, .js-fr-bypasslinks a:active { top: 0; } <|start_filename|>_components/bypasslinks/bypasslinks.js<|end_filename|> 'use strict'; /** * @param {object} options Object containing configuration overrides */ const Frbypasslinks = function({ selector: selector = '.js-fr-bypasslinks' } = {}) { // CONSTANTS const doc = document; const _q = (el, ctx = doc) => [].slice.call(ctx.querySelectorAll(el)); // SUPPORTS if (!('querySelector' in doc) || !('addEventListener' in window)) return; // SETUP // get bypass links NodeList const container = _q(selector)[0]; // TEMP let currTarget = null; // ACTIONS function _addFocusability (link) { // get target element let id = link.getAttribute('href').slice(1); let target = doc.getElementById(id); // set tabindex to allow focus if (target) target.setAttribute('tabindex', -1); } function _removeFocusability (link) { // get target element let id = link.getAttribute('href').slice(1); let target = doc.getElementById(id); // remove ability to focus (stops user highlighting element on click) if (target) target.removeAttribute('tabindex'); } function destroy () { // loop through each bypass link and remove event bindings _q('a', container).forEach(link => { _unbindPointerClick(link) _addFocusability(link); }); if (currTarget) _unbindTargetBlur(currTarget); } // EVENTS function _eventPointerClick (e) { // get target element let id = e.target.getAttribute('href').slice(1); let target = doc.getElementById(id); // don't try to apply relevant atts/focus if target isn't present if (!target) return; // set tabindex to allow focus target.setAttribute('tabindex', -1); target.focus(); // save target reference currTarget = target; // bind blur event on target _bindTargetBlur(target); } function _eventTargetBlur (e) { // remove ability to focus (stops user highlighting element on click) e.target.removeAttribute('tabindex'); // remove target reference currTarget = null; // unbind blur event _unbindTargetBlur(e.target); } // BIND EVENTS function _bindPointerClick (link) { // bind interaction event link.addEventListener('click', _eventPointerClick); } function _bindTargetBlur (target) { // bind blur event on target element target.addEventListener('blur', _eventTargetBlur); } // UNBIND EVENTS function _unbindPointerClick (link) { // unbind interaction event link.removeEventListener('click', _eventPointerClick); } function _unbindTargetBlur (target) { // unbind blur event on target element target.removeEventListener('blur', _eventTargetBlur); } // INIT function init () { // detect if bypass links exist in the document if (!container) return; // loop through each bypass link _q('a', container).forEach(link => { _bindPointerClick(link); _removeFocusability(link); }); } init(); // REVEAL API return { init, destroy } } // module exports export default Frbypasslinks; <|start_filename|>js/modules/webfont-loader.js<|end_filename|> 'use strict'; import 'promis'; import FontFaceObserver from 'fontfaceobserver'; const WebFontLoader = function() { // CONSTANTS const doc = document; const docEl = doc.documentElement; // SUPPORTS if (!('querySelector' in doc) || !('addEventListener' in window) || !docEl.classList) return; // SETUP const storageId = 'FontsLoaded'; const classLoaded = 'fonts-loaded'; const fonts = [ (new FontFaceObserver('Freight Text', { weight: 400 })).check(), (new FontFaceObserver('Freight Text', { weight: 400, style: 'italic' })).check(), (new FontFaceObserver('Benton Sans Cond Medium', { weight: 400 })).check() ]; // EVENTS function eventFontsLoaded () { docEl.classList.add(classLoaded); sessionStorage[storageId] = true; } // INIT function init () { Promise.all(fonts).then(eventFontsLoaded); } init(); } // module exports export default WebFontLoader; <|start_filename|>_components/accordion/accordion.css<|end_filename|> /* Container */ .fr-accordion { } /* Accordion header */ .fr-accordion--is-ready .fr-accordion__header { cursor: pointer; } /* Accordion panel */ .fr-accordion--is-ready .fr-accordion__panel { overflow: hidden; } .fr-accordion__panel[aria-hidden="true"] { visibility: hidden; height: 0; } .fr-accordion__panel[aria-hidden="false"] { visibility: visible; } <|start_filename|>_components/bypasslinks/bypasslinks.html<|end_filename|> <ul class="fr-bypasslinks js-fr-bypasslinks"> <li> <a class="fr-bypasslinks__link" href="#example-1"> Skip to example 1 </a> </li> <li> <a class="fr-bypasslinks__link" href="#example-2"> Skip to example 2 </a> </li> </ul> <div id="example-1" tabindex="-1"> <p> Tab through the page to access the bypass links. Voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim <a href="#">ipsam voluptatem</a> quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor. </p> </div> <div id="example-2" tabindex="-1"> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim <a href="#">ipsam voluptatem</a> quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor. </p> </div> <|start_filename|>js/modules/feature-detection.js<|end_filename|> document.documentElement.className = document.documentElement.className.replace('no-js', 'js'); <|start_filename|>_components/tabs/tabs.html<|end_filename|> <div class="fr-tabs js-fr-tabs"> <ul class="fr-tabs__tablist js-fr-tabs__tablist"> <li class="fr-tabs__tablist-item"> <a class="fr-tabs__tab" id="tab1" href="#panel1">Tab 1</a> </li> <li class="fr-tabs__tablist-item"> <a class="fr-tabs__tab" id="tab2" href="#panel2">Tab 2</a> </li> <li class="fr-tabs__tablist-item"> <a class="fr-tabs__tab" id="tab3" href="#panel3">Tab 3</a> </li> </ul> <section class="fr-tabs__panel js-fr-tabs__panel" id="panel1"> <h3>Tab panel 1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </section> <section class="fr-tabs__panel js-fr-tabs__panel" id="panel2"> <h3>Tab panel 2</h3> <p>Mauris rhoncus commodo sapien, eu porttitor libero gravida at. Maecenas a dapibus lorem. Suspendisse fermentum neque ligula, et dapibus libero volutpat scelerisque. Cras vitae enim interdum, fringilla sapien quis, posuere purus. Morbi dictum arcu sapien, eget malesuada lorem ultricies non. Etiam tellus neque, dapibus ac rutrum ut, mollis vel nibh.</p> </section> <section class="fr-tabs__panel js-fr-tabs__panel" id="panel3"> <h3>Tab panel 3</h3> <p>Quisque facilisis fermentum ex, in iaculis felis porta et. Phasellus sapien neque, sagittis vitae erat vitae, consequat vulputate lacus. Donec sit amet mattis ipsum. Ut metus ipsum, consectetur tincidunt imperdiet sed, consequat sed urna. Morbi id feugiat magna. Nunc ut aliquet quam. Morbi auctor sapien quam. Cras lorem neque, imperdiet ut mollis non, cursus scelerisque augue.</p> </section> </div> <|start_filename|>_components/offcanvas/offcanvas.css<|end_filename|> /* Panel */ .fr-offcanvas--is-ready { background-color: #fff; height: 100%; left: 100%; overflow: auto; max-width: 300px; position: fixed; top: 0; transform: translateX(0); width: 100%; will-change: translateX; } /* Panel - Visible */ .fr-offcanvas--is-ready[aria-hidden="false"] { transform: translateX(-100%); }
hoojaoh/frend.co
<|start_filename|>style.css<|end_filename|> /* generic */ html, body { margin: 0; font-size: 20px; background: gray; } div { -webkit-box-sizing: border-box; } #frame { width: 400px; height: 515px; background: white; } #frame > table { width: 100%; height: 100%; border: 0; border-collapse: collapse; } #frame > table > tbody > tr > td { width: 50%; padding: 10px; border-bottom: 1px solid black; text-align: center; vertical-align: top; } #frame > table > tbody > tr > td:first-child { border-right: 1px solid black; } #frame > table > tbody > tr > td:last-child { border-right: 0 !important; } p { margin: 10px 0; } /* date */ #datetime #time { font-size: 80px; margin: 10px 0; } /* weather */ #weather .weather-icon { float: left; margin-left: 20px; } #weather .temperature { font-size: 40px; } #weather .unit { vertical-align: top; } #weather .current-weather { float: left; width: 200px; } #weather .humidity-label { font-size: 15px; } /* traffic */ #traffic { border-bottom: 0; } #traffic table { width: 100%; } #traffic td { font-size: 15px; } #traffic td.mins { font-size: 120%; } #traffic td.jam-warner div { width: 20px; height: 20px; background: black; margin: 5px; float: right; } #traffic td.jam-warner div:first-child { -webkit-animation: blink 2s step-start 0s infinite; } #traffic td.jam-warner div:last-child { -webkit-animation: blink 2s step-start 0s infinite reverse; } @-webkit-keyframes blink { 50% { opacity: 0.0; } } /* washing */ #washing a { color: black; text-decoration: none; display: inline-block; border: 1px solid grey; -webkit-border-radius: 10px; padding: 10px; margin: 5px; font-size: 30px; } #washing a.washing-ready { -webkit-animation: flash 2s step-start 0s infinite; } @-webkit-keyframes flash { 50% { background: black; color: white; } } <|start_filename|>scripts.js<|end_filename|> var lastRefresh = new Date(); // auto refresh and time function padWithZeros(i) { if (i < 10) { i = "0" + i; } return i; } function startTime(refreshMinutes) { var now = new Date(); var h = now.getHours(); var m = now.getMinutes(); // add a zero in front of numbers<10 m = padWithZeros(m); document.getElementById('time').innerHTML = h + ":" + m; t = setTimeout(function () { startTime(refreshMinutes) }, 2000); if ((lastRefresh.getTime() + refreshMinutes * 1000) < now.getTime()) { lastRefresh = new Date(); location.reload(true); } } // washing control $.get('washing.php', function(data) { $('#washing-control').html(data); activateWashingControls(); }); function activateWashingControls() { var washingControl = $('#washing-control'); washingControl.find('a.washing-start').click(function (e) { $('#washing-control').html("..."); $.post('washing.php', {'start-wash': $(e.target).attr('href')}, function(data) { $('#washing-control').html(data); activateWashingControls(); }); return false; }); washingControl.find('a.washing-stop').click(function () { $('#washing-control').html("..."); $.post('washing.php', {'stop-wash': true}, function(data) { $('#washing-control').html(data); activateWashingControls(); }); return false; }); }
RolandColored/kobo-display
<|start_filename|>src/core/meshcop/dataset_manager_ftd.cpp<|end_filename|> /* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file implements MeshCoP Datasets manager to process commands. * */ #include "meshcop/dataset_manager.hpp" #if OPENTHREAD_FTD #include <stdio.h> #include <openthread/platform/radio.h> #include "coap/coap_message.hpp" #include "common/as_core_type.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" #include "common/random.hpp" #include "common/timer.hpp" #include "meshcop/dataset.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_leader.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" #include "thread/uri_paths.hpp" namespace ot { namespace MeshCoP { RegisterLogModule("DatasetManager"); Error DatasetManager::AppendMleDatasetTlv(Message &aMessage) const { Dataset dataset; IgnoreError(Read(dataset)); return dataset.AppendMleDatasetTlv(GetType(), aMessage); } Error DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { Tlv tlv; uint16_t offset = aMessage.GetOffset(); bool isUpdateFromCommissioner = false; bool doesAffectConnectivity = false; bool doesAffectNetworkKey = false; bool hasNetworkKey = false; StateTlv::State state = StateTlv::kReject; Dataset dataset; Timestamp activeTimestamp; ChannelTlv channel; uint16_t sessionId; Ip6::NetworkPrefix meshLocalPrefix; NetworkKey networkKey; uint16_t panId; VerifyOrExit(Get<Mle::MleRouter>().IsLeader()); // verify that TLV data size is less than maximum TLV value size while (offset < aMessage.GetLength()) { SuccessOrExit(aMessage.Read(offset, tlv)); VerifyOrExit(tlv.GetLength() <= Dataset::kMaxValueSize); offset += sizeof(tlv) + tlv.GetLength(); } // verify that does not overflow dataset buffer VerifyOrExit((offset - aMessage.GetOffset()) <= Dataset::kMaxSize); // verify the request includes a timestamp that is ahead of the locally stored value SuccessOrExit(Tlv::Find<ActiveTimestampTlv>(aMessage, activeTimestamp)); if (GetType() == Dataset::kPending) { Timestamp pendingTimestamp; SuccessOrExit(Tlv::Find<PendingTimestampTlv>(aMessage, pendingTimestamp)); VerifyOrExit(Timestamp::Compare(&pendingTimestamp, mLocal.GetTimestamp()) > 0); } else { VerifyOrExit(Timestamp::Compare(&activeTimestamp, mLocal.GetTimestamp()) > 0); } // check channel if (Tlv::FindTlv(aMessage, channel) == kErrorNone) { VerifyOrExit(channel.IsValid()); if (channel.GetChannel() != Get<Mac::Mac>().GetPanChannel()) { doesAffectConnectivity = true; } } // check PAN ID if (Tlv::Find<PanIdTlv>(aMessage, panId) == kErrorNone && panId != Get<Mac::Mac>().GetPanId()) { doesAffectConnectivity = true; } // check mesh local prefix if (Tlv::Find<MeshLocalPrefixTlv>(aMessage, meshLocalPrefix) == kErrorNone && meshLocalPrefix != Get<Mle::MleRouter>().GetMeshLocalPrefix()) { doesAffectConnectivity = true; } // check network key if (Tlv::Find<NetworkKeyTlv>(aMessage, networkKey) == kErrorNone) { NetworkKey localNetworkKey; hasNetworkKey = true; Get<KeyManager>().GetNetworkKey(localNetworkKey); if (networkKey != localNetworkKey) { doesAffectConnectivity = true; doesAffectNetworkKey = true; } } // check active timestamp rollback if (GetType() == Dataset::kPending && (!hasNetworkKey || !doesAffectNetworkKey)) { // no change to network key, active timestamp must be ahead const Timestamp *localActiveTimestamp = Get<ActiveDatasetManager>().GetTimestamp(); VerifyOrExit(Timestamp::Compare(&activeTimestamp, localActiveTimestamp) > 0); } // check commissioner session id if (Tlv::Find<CommissionerSessionIdTlv>(aMessage, sessionId) == kErrorNone) { const CommissionerSessionIdTlv *localId; isUpdateFromCommissioner = true; localId = As<CommissionerSessionIdTlv>( Get<NetworkData::Leader>().GetCommissioningDataSubTlv(Tlv::kCommissionerSessionId)); VerifyOrExit(localId != nullptr && localId->GetCommissionerSessionId() == sessionId); } // verify an MGMT_ACTIVE_SET.req from a Commissioner does not affect connectivity VerifyOrExit(!isUpdateFromCommissioner || GetType() == Dataset::kPending || !doesAffectConnectivity); if (isUpdateFromCommissioner) { // Thread specification allows partial dataset changes for MGMT_ACTIVE_SET.req/MGMT_PENDING_SET.req // from Commissioner based on existing active dataset. IgnoreError(Get<ActiveDatasetManager>().Read(dataset)); } if (GetType() == Dataset::kPending || !doesAffectConnectivity) { offset = aMessage.GetOffset(); while (offset < aMessage.GetLength()) { DatasetTlv datasetTlv; SuccessOrExit(datasetTlv.ReadFromMessage(aMessage, offset)); switch (datasetTlv.GetType()) { case Tlv::kCommissionerSessionId: // do not store Commissioner Session ID TLV break; case Tlv::kDelayTimer: { DelayTimerTlv &delayTimerTlv = As<DelayTimerTlv>(datasetTlv); if (doesAffectNetworkKey && delayTimerTlv.GetDelayTimer() < DelayTimerTlv::kDelayTimerDefault) { delayTimerTlv.SetDelayTimer(DelayTimerTlv::kDelayTimerDefault); } else if (delayTimerTlv.GetDelayTimer() < Get<Leader>().GetDelayTimerMinimal()) { delayTimerTlv.SetDelayTimer(Get<Leader>().GetDelayTimerMinimal()); } } OT_FALL_THROUGH; default: SuccessOrExit(dataset.SetTlv(datasetTlv)); break; } offset += static_cast<uint16_t>(datasetTlv.GetSize()); } SuccessOrExit(Save(dataset)); Get<NetworkData::Leader>().IncrementVersionAndStableVersion(); } else { Get<PendingDatasetManager>().ApplyActiveDataset(activeTimestamp, aMessage); } state = StateTlv::kAccept; // notify commissioner if update is from thread device if (!isUpdateFromCommissioner) { const CommissionerSessionIdTlv *localSessionId; Ip6::Address destination; localSessionId = As<CommissionerSessionIdTlv>( Get<NetworkData::Leader>().GetCommissioningDataSubTlv(Tlv::kCommissionerSessionId)); VerifyOrExit(localSessionId != nullptr); SuccessOrExit( Get<Mle::MleRouter>().GetCommissionerAloc(destination, localSessionId->GetCommissionerSessionId())); Get<Leader>().SendDatasetChanged(destination); } exit: if (Get<Mle::MleRouter>().IsLeader()) { SendSetResponse(aMessage, aMessageInfo, state); } return (state == StateTlv::kAccept) ? kErrorNone : kErrorDrop; } void DatasetManager::SendSetResponse(const Coap::Message & aRequest, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { Error error = kErrorNone; Coap::Message *message; message = Get<Tmf::Agent>().NewPriorityResponseMessage(aRequest); VerifyOrExit(message != nullptr, error = kErrorNoBufs); SuccessOrExit(error = Tlv::Append<StateTlv>(*message, aState)); SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, aMessageInfo)); LogInfo("sent dataset set response"); exit: FreeMessageOnError(message, error); } Error DatasetManager::DatasetTlv::ReadFromMessage(const Message &aMessage, uint16_t aOffset) { Error error = kErrorNone; SuccessOrExit(error = aMessage.Read(aOffset, this, sizeof(Tlv))); VerifyOrExit(GetLength() <= Dataset::kMaxValueSize, error = kErrorParse); SuccessOrExit(error = aMessage.Read(aOffset + sizeof(Tlv), mValue, GetLength())); VerifyOrExit(Tlv::IsValid(*this), error = kErrorParse); exit: return error; } Error ActiveDatasetManager::GenerateLocal(void) { Error error = kErrorNone; Dataset dataset; VerifyOrExit(Get<Mle::MleRouter>().IsAttached(), error = kErrorInvalidState); VerifyOrExit(!mLocal.IsTimestampPresent(), error = kErrorAlready); IgnoreError(Read(dataset)); if (dataset.GetTlv<ActiveTimestampTlv>() == nullptr) { Timestamp timestamp; timestamp.Clear(); IgnoreError(dataset.SetTlv(Tlv::kActiveTimestamp, timestamp)); } if (dataset.GetTlv<ChannelTlv>() == nullptr) { ChannelTlv tlv; tlv.Init(); tlv.SetChannel(Get<Mac::Mac>().GetPanChannel()); IgnoreError(dataset.SetTlv(tlv)); } if (dataset.GetTlv<ChannelMaskTlv>() == nullptr) { ChannelMaskTlv tlv; tlv.Init(); tlv.SetChannelMask(Get<Mac::Mac>().GetSupportedChannelMask().GetMask()); IgnoreError(dataset.SetTlv(tlv)); } if (dataset.GetTlv<ExtendedPanIdTlv>() == nullptr) { IgnoreError(dataset.SetTlv(Tlv::kExtendedPanId, Get<ExtendedPanIdManager>().GetExtPanId())); } if (dataset.GetTlv<MeshLocalPrefixTlv>() == nullptr) { IgnoreError(dataset.SetTlv(Tlv::kMeshLocalPrefix, Get<Mle::MleRouter>().GetMeshLocalPrefix())); } if (dataset.GetTlv<NetworkKeyTlv>() == nullptr) { NetworkKey networkKey; Get<KeyManager>().GetNetworkKey(networkKey); IgnoreError(dataset.SetTlv(Tlv::kNetworkKey, networkKey)); } if (dataset.GetTlv<NetworkNameTlv>() == nullptr) { NameData nameData = Get<NetworkNameManager>().GetNetworkName().GetAsData(); IgnoreError(dataset.SetTlv(Tlv::kNetworkName, nameData.GetBuffer(), nameData.GetLength())); } if (dataset.GetTlv<PanIdTlv>() == nullptr) { IgnoreError(dataset.SetTlv(Tlv::kPanId, Get<Mac::Mac>().GetPanId())); } if (dataset.GetTlv<PskcTlv>() == nullptr) { Pskc pskc; if (Get<KeyManager>().IsPskcSet()) { Get<KeyManager>().GetPskc(pskc); } else { SuccessOrExit(error = pskc.GenerateRandom()); } IgnoreError(dataset.SetTlv(Tlv::kPskc, pskc)); } if (dataset.GetTlv<SecurityPolicyTlv>() == nullptr) { SecurityPolicyTlv tlv; tlv.Init(); tlv.SetSecurityPolicy(Get<KeyManager>().GetSecurityPolicy()); IgnoreError(dataset.SetTlv(tlv)); } SuccessOrExit(error = mLocal.Save(dataset)); IgnoreError(Restore()); LogInfo("Generated local dataset"); exit: return error; } void ActiveDatasetManager::StartLeader(void) { IgnoreError(GenerateLocal()); Get<Tmf::Agent>().AddResource(mResourceSet); } void ActiveDatasetManager::StopLeader(void) { Get<Tmf::Agent>().RemoveResource(mResourceSet); } void ActiveDatasetManager::HandleSet(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<ActiveDatasetManager *>(aContext)->HandleSet(AsCoapMessage(aMessage), AsCoreType(aMessageInfo)); } void ActiveDatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { SuccessOrExit(DatasetManager::HandleSet(aMessage, aMessageInfo)); IgnoreError(ApplyConfiguration()); exit: return; } void PendingDatasetManager::StartLeader(void) { StartDelayTimer(); Get<Tmf::Agent>().AddResource(mResourceSet); } void PendingDatasetManager::StopLeader(void) { Get<Tmf::Agent>().RemoveResource(mResourceSet); } void PendingDatasetManager::HandleSet(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<PendingDatasetManager *>(aContext)->HandleSet(AsCoapMessage(aMessage), AsCoreType(aMessageInfo)); } void PendingDatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { SuccessOrExit(DatasetManager::HandleSet(aMessage, aMessageInfo)); StartDelayTimer(); exit: return; } void PendingDatasetManager::ApplyActiveDataset(const Timestamp &aTimestamp, Coap::Message &aMessage) { uint16_t offset = aMessage.GetOffset(); Dataset dataset; VerifyOrExit(Get<Mle::MleRouter>().IsAttached()); while (offset < aMessage.GetLength()) { DatasetTlv datasetTlv; SuccessOrExit(datasetTlv.ReadFromMessage(aMessage, offset)); offset += static_cast<uint16_t>(datasetTlv.GetSize()); IgnoreError(dataset.SetTlv(datasetTlv)); } // add delay timer tlv IgnoreError(dataset.SetTlv(Tlv::kDelayTimer, Get<Leader>().GetDelayTimerMinimal())); // add pending timestamp tlv dataset.SetTimestamp(Dataset::kPending, aTimestamp); IgnoreError(DatasetManager::Save(dataset)); // reset delay timer StartDelayTimer(); exit: return; } } // namespace MeshCoP } // namespace ot #endif // OPENTHREAD_FTD <|start_filename|>src/core/thread/mlr_manager.cpp<|end_filename|> /* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file implements MLR management. */ #include "mlr_manager.hpp" #if OPENTHREAD_CONFIG_MLR_ENABLE || (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) #include "common/as_core_type.hpp" #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" #include "net/ip6_address.hpp" #include "thread/thread_netif.hpp" #include "thread/uri_paths.hpp" #include "utils/slaac_address.hpp" namespace ot { RegisterLogModule("MlrManager"); MlrManager::MlrManager(Instance &aInstance) : InstanceLocator(aInstance) #if (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE , mRegisterMulticastListenersCallback(nullptr) , mRegisterMulticastListenersContext(nullptr) #endif , mReregistrationDelay(0) , mSendDelay(0) , mMlrPending(false) #if (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE , mRegisterMulticastListenersPending(false) #endif { } void MlrManager::HandleNotifierEvents(Events aEvents) { #if OPENTHREAD_CONFIG_MLR_ENABLE if (aEvents.Contains(kEventIp6MulticastSubscribed)) { UpdateLocalSubscriptions(); } #endif if (aEvents.Contains(kEventThreadRoleChanged) && Get<Mle::MleRouter>().IsChild()) { // Reregistration after re-attach UpdateReregistrationDelay(true); } } void MlrManager::HandleBackboneRouterPrimaryUpdate(BackboneRouter::Leader::State aState, const BackboneRouter::BackboneRouterConfig &aConfig) { OT_UNUSED_VARIABLE(aConfig); bool needRereg = aState == BackboneRouter::Leader::kStateAdded || aState == BackboneRouter::Leader::kStateToTriggerRereg; UpdateReregistrationDelay(needRereg); } #if OPENTHREAD_CONFIG_MLR_ENABLE void MlrManager::UpdateLocalSubscriptions(void) { #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE // Check multicast addresses are newly listened against Children for (Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (addr.GetMlrState() == kMlrStateToRegister && IsAddressMlrRegisteredByAnyChild(addr.GetAddress())) { addr.SetMlrState(kMlrStateRegistered); } } #endif CheckInvariants(); ScheduleSend(0); } bool MlrManager::IsAddressMlrRegisteredByNetif(const Ip6::Address &aAddress) const { bool ret = false; OT_ASSERT(aAddress.IsMulticastLargerThanRealmLocal()); for (const Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses()) { if (addr.GetAddress() == aAddress && addr.GetMlrState() == kMlrStateRegistered) { ExitNow(ret = true); } } exit: return ret; } #endif // OPENTHREAD_CONFIG_MLR_ENABLE #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE bool MlrManager::IsAddressMlrRegisteredByAnyChildExcept(const Ip6::Address &aAddress, const Child *aExceptChild) const { bool ret = false; OT_ASSERT(aAddress.IsMulticastLargerThanRealmLocal()); for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid)) { if (&child != aExceptChild && child.HasMlrRegisteredAddress(aAddress)) { ExitNow(ret = true); } } exit: return ret; } void MlrManager::UpdateProxiedSubscriptions(Child & aChild, const Ip6::Address *aOldMlrRegisteredAddresses, uint16_t aOldMlrRegisteredAddressNum) { VerifyOrExit(aChild.IsStateValid()); // Search the new multicast addresses and set its flag accordingly for (const Ip6::Address &address : aChild.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { bool isMlrRegistered = false; // Check if it's a new multicast address against old addresses for (size_t i = 0; i < aOldMlrRegisteredAddressNum; i++) { if (aOldMlrRegisteredAddresses[i] == address) { isMlrRegistered = true; break; } } #if OPENTHREAD_CONFIG_MLR_ENABLE // Check if it's a new multicast address against parent Netif isMlrRegistered = isMlrRegistered || IsAddressMlrRegisteredByNetif(address); #endif // Check if it's a new multicast address against other Children isMlrRegistered = isMlrRegistered || IsAddressMlrRegisteredByAnyChildExcept(address, &aChild); aChild.SetAddressMlrState(address, isMlrRegistered ? kMlrStateRegistered : kMlrStateToRegister); } exit: LogMulticastAddresses(); CheckInvariants(); if (aChild.HasAnyMlrToRegisterAddress()) { ScheduleSend(Random::NonCrypto::GetUint16InRange(1, Mle::kParentAggregateDelay)); } } #endif // OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE void MlrManager::ScheduleSend(uint16_t aDelay) { OT_ASSERT(!mMlrPending || mSendDelay == 0); VerifyOrExit(!mMlrPending); if (aDelay == 0) { mSendDelay = 0; SendMulticastListenerRegistration(); } else if (mSendDelay == 0 || mSendDelay > aDelay) { mSendDelay = aDelay; } UpdateTimeTickerRegistration(); exit: return; } void MlrManager::UpdateTimeTickerRegistration(void) { if (mSendDelay == 0 && mReregistrationDelay == 0) { Get<TimeTicker>().UnregisterReceiver(TimeTicker::kMlrManager); } else { Get<TimeTicker>().RegisterReceiver(TimeTicker::kMlrManager); } } void MlrManager::SendMulticastListenerRegistration(void) { Error error; Mle::MleRouter &mle = Get<Mle::MleRouter>(); Ip6::Address addresses[kIp6AddressesNumMax]; uint8_t addressesNum = 0; VerifyOrExit(!mMlrPending, error = kErrorBusy); VerifyOrExit(mle.IsAttached(), error = kErrorInvalidState); VerifyOrExit(mle.IsFullThreadDevice() || mle.GetParent().IsThreadVersion1p1(), error = kErrorInvalidState); VerifyOrExit(Get<BackboneRouter::Leader>().HasPrimary(), error = kErrorInvalidState); #if OPENTHREAD_CONFIG_MLR_ENABLE // Append Netif multicast addresses for (Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (addressesNum >= kIp6AddressesNumMax) { break; } if (addr.GetMlrState() == kMlrStateToRegister) { AppendToUniqueAddressList(addresses, addressesNum, addr.GetAddress()); addr.SetMlrState(kMlrStateRegistering); } } #endif #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE // Append Child multicast addresses for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid)) { if (addressesNum >= kIp6AddressesNumMax) { break; } if (!child.HasAnyMlrToRegisterAddress()) { continue; } for (const Ip6::Address &address : child.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (addressesNum >= kIp6AddressesNumMax) { break; } if (child.GetAddressMlrState(address) == kMlrStateToRegister) { AppendToUniqueAddressList(addresses, addressesNum, address); child.SetAddressMlrState(address, kMlrStateRegistering); } } } #endif VerifyOrExit(addressesNum > 0, error = kErrorNotFound); SuccessOrExit( error = SendMulticastListenerRegistrationMessage( addresses, addressesNum, nullptr, &MlrManager::HandleMulticastListenerRegistrationResponse, this)); mMlrPending = true; // Generally Thread 1.2 Router would send MLR.req on bebelf for MA (scope >=4) subscribed by its MTD child. // When Thread 1.2 MTD attaches to Thread 1.1 parent, 1.2 MTD should send MLR.req to PBBR itself. // In this case, Thread 1.2 sleepy end device relies on fast data poll to fetch the response timely. if (!Get<Mle::Mle>().IsRxOnWhenIdle()) { Get<DataPollSender>().SendFastPolls(); } exit: if (error != kErrorNone) { SetMulticastAddressMlrState(kMlrStateRegistering, kMlrStateToRegister); if (error == kErrorNoBufs) { ScheduleSend(1); } } LogMulticastAddresses(); CheckInvariants(); } #if (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE Error MlrManager::RegisterMulticastListeners(const otIp6Address * aAddresses, uint8_t aAddressNum, const uint32_t * aTimeout, otIp6RegisterMulticastListenersCallback aCallback, void * aContext) { Error error; VerifyOrExit(aAddresses != nullptr, error = kErrorInvalidArgs); VerifyOrExit(aAddressNum > 0 && aAddressNum <= kIp6AddressesNumMax, error = kErrorInvalidArgs); VerifyOrExit(aContext == nullptr || aCallback != nullptr, error = kErrorInvalidArgs); #if !OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE VerifyOrExit(Get<MeshCoP::Commissioner>().IsActive(), error = kErrorInvalidState); #else if (!Get<MeshCoP::Commissioner>().IsActive()) { LogWarn("MLR.req without active commissioner session for test."); } #endif // Only allow one outstanding registration if callback is specified. VerifyOrExit(!mRegisterMulticastListenersPending, error = kErrorBusy); SuccessOrExit(error = SendMulticastListenerRegistrationMessage( aAddresses, aAddressNum, aTimeout, &MlrManager::HandleRegisterMulticastListenersResponse, this)); mRegisterMulticastListenersPending = true; mRegisterMulticastListenersCallback = aCallback; mRegisterMulticastListenersContext = aContext; exit: return error; } void MlrManager::HandleRegisterMulticastListenersResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, Error aResult) { static_cast<MlrManager *>(aContext)->HandleRegisterMulticastListenersResponse(AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), aResult); } void MlrManager::HandleRegisterMulticastListenersResponse(otMessage * aMessage, const otMessageInfo *aMessageInfo, Error aResult) { OT_UNUSED_VARIABLE(aMessageInfo); uint8_t status; Error error; Ip6::Address failedAddresses[kIp6AddressesNumMax]; uint8_t failedAddressNum = 0; otIp6RegisterMulticastListenersCallback callback = mRegisterMulticastListenersCallback; void * context = mRegisterMulticastListenersContext; mRegisterMulticastListenersPending = false; mRegisterMulticastListenersCallback = nullptr; mRegisterMulticastListenersContext = nullptr; error = ParseMulticastListenerRegistrationResponse(aResult, AsCoapMessagePtr(aMessage), status, failedAddresses, failedAddressNum); if (callback != nullptr) { callback(context, error, status, failedAddresses, failedAddressNum); } } #endif // (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE Error MlrManager::SendMulticastListenerRegistrationMessage(const otIp6Address * aAddresses, uint8_t aAddressNum, const uint32_t * aTimeout, Coap::ResponseHandler aResponseHandler, void * aResponseContext) { OT_UNUSED_VARIABLE(aTimeout); Error error = kErrorNone; Mle::MleRouter & mle = Get<Mle::MleRouter>(); Coap::Message * message = nullptr; Tmf::MessageInfo messageInfo(GetInstance()); Ip6AddressesTlv addressesTlv; VerifyOrExit(Get<BackboneRouter::Leader>().HasPrimary(), error = kErrorInvalidState); message = Get<Tmf::Agent>().NewConfirmablePostMessage(UriPath::kMlr); VerifyOrExit(message != nullptr, error = kErrorNoBufs); addressesTlv.Init(); addressesTlv.SetLength(sizeof(Ip6::Address) * aAddressNum); SuccessOrExit(error = message->Append(addressesTlv)); SuccessOrExit(error = message->AppendBytes(aAddresses, sizeof(Ip6::Address) * aAddressNum)); #if (OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE) && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE if (Get<MeshCoP::Commissioner>().IsActive()) { SuccessOrExit( error = Tlv::Append<ThreadCommissionerSessionIdTlv>(*message, Get<MeshCoP::Commissioner>().GetSessionId())); } if (aTimeout != nullptr) { SuccessOrExit(error = Tlv::Append<ThreadTimeoutTlv>(*message, *aTimeout)); } #else OT_ASSERT(aTimeout == nullptr); #endif if (!mle.IsFullThreadDevice() && mle.GetParent().IsThreadVersion1p1()) { uint8_t pbbrServiceId; SuccessOrExit(error = Get<BackboneRouter::Leader>().GetServiceId(pbbrServiceId)); SuccessOrExit(error = mle.GetServiceAloc(pbbrServiceId, messageInfo.GetPeerAddr())); } else { messageInfo.GetPeerAddr().SetToRoutingLocator(mle.GetMeshLocalPrefix(), Get<BackboneRouter::Leader>().GetServer16()); } messageInfo.SetSockAddrToRloc(); error = Get<Tmf::Agent>().SendMessage(*message, messageInfo, aResponseHandler, aResponseContext); LogInfo("Sent MLR.req: addressNum=%d", aAddressNum); exit: LogInfo("SendMulticastListenerRegistrationMessage(): %s", ErrorToString(error)); FreeMessageOnError(message, error); return error; } void MlrManager::HandleMulticastListenerRegistrationResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, Error aResult) { static_cast<MlrManager *>(aContext)->HandleMulticastListenerRegistrationResponse( AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), aResult); } void MlrManager::HandleMulticastListenerRegistrationResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult) { OT_UNUSED_VARIABLE(aMessageInfo); uint8_t status; Error error; Ip6::Address failedAddresses[kIp6AddressesNumMax]; uint8_t failedAddressNum = 0; error = ParseMulticastListenerRegistrationResponse(aResult, aMessage, status, failedAddresses, failedAddressNum); FinishMulticastListenerRegistration(error == kErrorNone && status == ThreadStatusTlv::MlrStatus::kMlrSuccess, failedAddresses, failedAddressNum); if (error == kErrorNone && status == ThreadStatusTlv::MlrStatus::kMlrSuccess) { // keep sending until all multicast addresses are registered. ScheduleSend(0); } else { otBackboneRouterConfig config; uint16_t reregDelay; // The Device has just attempted a Multicast Listener Registration which failed, and it retries the same // registration with a random time delay chosen in the interval [0, Reregistration Delay]. // This is required by Thread 1.2 Specification 5.24.2.3 if (Get<BackboneRouter::Leader>().GetConfig(config) == kErrorNone) { reregDelay = config.mReregistrationDelay > 1 ? Random::NonCrypto::GetUint16InRange(1, config.mReregistrationDelay) : 1; ScheduleSend(reregDelay); } } } Error MlrManager::ParseMulticastListenerRegistrationResponse(Error aResult, Coap::Message *aMessage, uint8_t & aStatus, Ip6::Address * aFailedAddresses, uint8_t & aFailedAddressNum) { Error error; uint16_t addressesOffset, addressesLength; aStatus = ThreadStatusTlv::MlrStatus::kMlrGeneralFailure; VerifyOrExit(aResult == kErrorNone && aMessage != nullptr, error = kErrorParse); VerifyOrExit(aMessage->GetCode() == Coap::kCodeChanged, error = kErrorParse); SuccessOrExit(error = Tlv::Find<ThreadStatusTlv>(*aMessage, aStatus)); if (ThreadTlv::FindTlvValueOffset(*aMessage, Ip6AddressesTlv::kIp6Addresses, addressesOffset, addressesLength) == kErrorNone) { VerifyOrExit(addressesLength % sizeof(Ip6::Address) == 0, error = kErrorParse); VerifyOrExit(addressesLength / sizeof(Ip6::Address) <= kIp6AddressesNumMax, error = kErrorParse); for (uint16_t offset = 0; offset < addressesLength; offset += sizeof(Ip6::Address)) { IgnoreError(aMessage->Read(addressesOffset + offset, aFailedAddresses[aFailedAddressNum])); aFailedAddressNum++; } } VerifyOrExit(aFailedAddressNum == 0 || aStatus != ThreadStatusTlv::MlrStatus::kMlrSuccess, error = kErrorParse); exit: LogMlrResponse(aResult, error, aStatus, aFailedAddresses, aFailedAddressNum); return aResult != kErrorNone ? aResult : error; } void MlrManager::SetMulticastAddressMlrState(MlrState aFromState, MlrState aToState) { #if OPENTHREAD_CONFIG_MLR_ENABLE for (Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (addr.GetMlrState() == aFromState) { addr.SetMlrState(aToState); } } #endif #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid)) { for (const Ip6::Address &address : child.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (child.GetAddressMlrState(address) == aFromState) { child.SetAddressMlrState(address, aToState); } } } #endif } void MlrManager::FinishMulticastListenerRegistration(bool aSuccess, const Ip6::Address *aFailedAddresses, uint8_t aFailedAddressNum) { OT_ASSERT(mMlrPending); mMlrPending = false; #if OPENTHREAD_CONFIG_MLR_ENABLE for (Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (addr.GetMlrState() == kMlrStateRegistering) { bool success = aSuccess || !AddressListContains(aFailedAddresses, aFailedAddressNum, addr.GetAddress()); addr.SetMlrState(success ? kMlrStateRegistered : kMlrStateToRegister); } } #endif #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid)) { for (const Ip6::Address &address : child.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { if (child.GetAddressMlrState(address) == kMlrStateRegistering) { bool success = aSuccess || !AddressListContains(aFailedAddresses, aFailedAddressNum, address); child.SetAddressMlrState(address, success ? kMlrStateRegistered : kMlrStateToRegister); } } } #endif LogMulticastAddresses(); CheckInvariants(); } void MlrManager::HandleTimeTick(void) { if (mSendDelay > 0 && --mSendDelay == 0) { SendMulticastListenerRegistration(); } if (mReregistrationDelay > 0 && --mReregistrationDelay == 0) { Reregister(); } UpdateTimeTickerRegistration(); } void MlrManager::Reregister(void) { LogInfo("MLR Reregister!"); SetMulticastAddressMlrState(kMlrStateRegistered, kMlrStateToRegister); CheckInvariants(); ScheduleSend(0); // Schedule for the next renewing. UpdateReregistrationDelay(false); } void MlrManager::UpdateReregistrationDelay(bool aRereg) { Mle::MleRouter &mle = Get<Mle::MleRouter>(); bool needSendMlr = (mle.IsFullThreadDevice() || mle.GetParent().IsThreadVersion1p1()) && Get<BackboneRouter::Leader>().HasPrimary(); if (!needSendMlr) { mReregistrationDelay = 0; } else { BackboneRouter::BackboneRouterConfig config; uint32_t reregDelay; uint32_t effectiveMlrTimeout; IgnoreError(Get<BackboneRouter::Leader>().GetConfig(config)); if (aRereg) { reregDelay = config.mReregistrationDelay > 1 ? Random::NonCrypto::GetUint16InRange(1, config.mReregistrationDelay) : 1; } else { // Calculate renewing period according to Thread Spec. 5.24.2.3.2 // The random time t SHOULD be chosen such that (0.5* MLR-Timeout) < t < (MLR-Timeout – 9 seconds). effectiveMlrTimeout = config.mMlrTimeout > Mle::kMlrTimeoutMin ? config.mMlrTimeout : static_cast<uint32_t>(Mle::kMlrTimeoutMin); reregDelay = Random::NonCrypto::GetUint32InRange((effectiveMlrTimeout >> 1u) + 1, effectiveMlrTimeout - 9); } if (mReregistrationDelay == 0 || mReregistrationDelay > reregDelay) { mReregistrationDelay = reregDelay; } } UpdateTimeTickerRegistration(); LogDebg("MlrManager::UpdateReregistrationDelay: rereg=%d, needSendMlr=%d, ReregDelay=%lu", aRereg, needSendMlr, mReregistrationDelay); } void MlrManager::LogMulticastAddresses(void) { #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_DEBG) LogDebg("-------- Multicast Addresses --------"); #if OPENTHREAD_CONFIG_MLR_ENABLE for (const Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses()) { LogDebg("%-32s%c", addr.GetAddress().ToString().AsCString(), "-rR"[addr.GetMlrState()]); } #endif #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid)) { for (const Ip6::Address &address : child.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { LogDebg("%-32s%c %04x", address.ToString().AsCString(), "-rR"[child.GetAddressMlrState(address)], child.GetRloc16()); } } #endif #endif // OT_SHOULD_LOG_AT(OT_LOG_LEVEL_DEBG) } void MlrManager::AppendToUniqueAddressList(Ip6::Address (&aAddresses)[kIp6AddressesNumMax], uint8_t & aAddressNum, const Ip6::Address &aAddress) { #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE for (uint8_t i = 0; i < aAddressNum; i++) { if (aAddresses[i] == aAddress) { ExitNow(); } } #endif aAddresses[aAddressNum++] = aAddress; #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE exit: #endif return; } bool MlrManager::AddressListContains(const Ip6::Address *aAddressList, uint8_t aAddressListSize, const Ip6::Address &aAddress) { bool contains = false; // An empty address list is treated as if it contains all failed addresses. VerifyOrExit(aAddressListSize > 0, contains = true); for (uint8_t i = 0; i < aAddressListSize; i++) { if (aAddressList[i] == aAddress) { ExitNow(contains = true); } } exit: return contains; } void MlrManager::LogMlrResponse(Error aResult, Error aError, uint8_t aStatus, const Ip6::Address *aFailedAddresses, uint8_t aFailedAddressNum) { OT_UNUSED_VARIABLE(aResult); OT_UNUSED_VARIABLE(aError); OT_UNUSED_VARIABLE(aStatus); OT_UNUSED_VARIABLE(aFailedAddresses); OT_UNUSED_VARIABLE(aFailedAddressNum); #if OT_SHOULD_LOG_AT(OT_LOG_LEVEL_WARN) if (aResult == kErrorNone && aError == kErrorNone && aStatus == ThreadStatusTlv::MlrStatus::kMlrSuccess) { LogInfo("Receive MLR.rsp OK"); } else { LogWarn("Receive MLR.rsp: result=%s, error=%s, status=%d, failedAddressNum=%d", ErrorToString(aResult), ErrorToString(aError), aStatus, aFailedAddressNum); for (uint8_t i = 0; i < aFailedAddressNum; i++) { LogWarn("MA failed: %s", aFailedAddresses[i].ToString().AsCString()); } } #endif } void MlrManager::CheckInvariants(void) const { #if OPENTHREAD_EXAMPLES_SIMULATION uint16_t registeringNum = 0; OT_ASSERT(!mMlrPending || mSendDelay == 0); #if OPENTHREAD_CONFIG_MLR_ENABLE for (Ip6::Netif::ExternalMulticastAddress &addr : Get<ThreadNetif>().IterateExternalMulticastAddresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { registeringNum += (addr.GetMlrState() == kMlrStateRegistering); } #endif #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE for (Child &child : Get<ChildTable>().Iterate(Child::kInStateValid)) { for (const Ip6::Address &address : child.IterateIp6Addresses(Ip6::Address::kTypeMulticastLargerThanRealmLocal)) { registeringNum += (child.GetAddressMlrState(address) == kMlrStateRegistering); } } #endif OT_ASSERT(registeringNum == 0 || mMlrPending); #endif // OPENTHREAD_EXAMPLES_SIMULATION } } // namespace ot #endif // OPENTHREAD_CONFIG_MLR_ENABLE <|start_filename|>src/core/config/platform.h<|end_filename|> /* * Copyright (c) 2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file includes compile-time configurations for platform-specific services. * */ #ifndef CONFIG_PLATFORM_H_ #define CONFIG_PLATFORM_H_ /** * @def OPENTHREAD_CONFIG_PLATFORM_INFO * * The platform-specific string to insert into the OpenThread version string. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_INFO #define OPENTHREAD_CONFIG_PLATFORM_INFO "NONE" #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT * * The message pool is managed by platform defined logic when this flag is set. * This feature would typically be used when operating in a multi-threaded system * and multiple threads need to access the message pool. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT #define OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_ASSERT_MANAGEMENT * * The assert is managed by platform defined logic when this flag is set. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_ASSERT_MANAGEMENT #define OPENTHREAD_CONFIG_PLATFORM_ASSERT_MANAGEMENT 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_NETIF_ENABLE * * Define to 1 to enable platform NETIF support. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_NETIF_ENABLE #define OPENTHREAD_CONFIG_PLATFORM_NETIF_ENABLE 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_UDP_ENABLE * * Define to 1 to enable platform UDP support. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_UDP_ENABLE #define OPENTHREAD_CONFIG_PLATFORM_UDP_ENABLE 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE * * Define to 1 if you want to enable microsecond backoff timer implemented in platform. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE #define OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_RADIO_COEX_ENABLE * * Define to 1 if you want to enable radio coexistence implemented in platform. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_RADIO_COEX_ENABLE #define OPENTHREAD_CONFIG_PLATFORM_RADIO_COEX_ENABLE 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE * * Specifies the rx frame buffer size used by `SpinelInterface` in RCP host (posix) code. This is applicable/used when * `RadioSpinel` platform is used. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE #define OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE 8192 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_SUPPORT * * Define to 1 if you want to enable proprietary radio support as defined by platform. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_SUPPORT #define OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_SUPPORT 0 #endif /** * @def OPENTHREAD_CONFIG_PSA_ITS_NVM_OFFSET * * Default NVM offset while using key refs. Platforms can override this definition based on implementation * */ #ifndef OPENTHREAD_CONFIG_PSA_ITS_NVM_OFFSET #define OPENTHREAD_CONFIG_PSA_ITS_NVM_OFFSET 0x20000 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE * * Define to 1 if you want to enable key ref usage support as defined by platform. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE #define OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE 0 #endif /** * @def OPENTHREAD_CONFIG_PLATFORM_MAC_KEYS_EXPORTABLE_ENABLE * * Define to 1 if you want to make MAC keys exportable. * */ #ifndef OPENTHREAD_CONFIG_PLATFORM_MAC_KEYS_EXPORTABLE_ENABLE #define OPENTHREAD_CONFIG_PLATFORM_MAC_KEYS_EXPORTABLE_ENABLE 0 #endif #if OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_SUPPORT #if (!defined(OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_PAGE) || \ !defined(OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_MIN) || \ !defined(OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_MAX) || \ !defined(OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_MASK)) #error "Proprietary radio support requires\ OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_PAGE,\ OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_MIN,\ OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_MAX and\ OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_MASK\ to be defined by Platform." #endif #if OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_CHANNEL_PAGE > 31 #error "Maximum Proprietary Channel Page value currently supported is 31." #endif #endif #endif // CONFIG_PLATFORM_H_ <|start_filename|>src/lib/spinel/spinel.c<|end_filename|> /* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /* * ------------------------------------------------------------------- * * ## Unit Test ## * * This file includes its own unit test. To compile the unit test, * simply compile this file with the macro SPINEL_SELF_TEST set to 1. * For example: * * cc spinel.c -Wall -DSPINEL_SELF_TEST=1 -o spinel * * ------------------------------------------------------------------- */ // ---------------------------------------------------------------------------- // MARK: - // MARK: Headers #include "spinel.h" #include <errno.h> #include <limits.h> #ifndef SPINEL_PLATFORM_HEADER /* These are all already included in the spinel platform header * if SPINEL_PLATFORM_HEADER was defined. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #endif // #ifndef SPINEL_PLATFORM_HEADER // ---------------------------------------------------------------------------- // MARK: - // IAR's errno.h apparently doesn't define EOVERFLOW. #ifndef EOVERFLOW // There is no real good choice for what to set // errno to in this case, so we just pick the // value '1' somewhat arbitrarily. #define EOVERFLOW 1 #endif // IAR's errno.h apparently doesn't define EINVAL. #ifndef EINVAL // There is no real good choice for what to set // errno to in this case, so we just pick the // value '1' somewhat arbitrarily. #define EINVAL 1 #endif // IAR's errno.h apparently doesn't define ENOMEM. #ifndef ENOMEM // There is no real good choice for what to set // errno to in this case, so we just pick the // value '1' somewhat arbitrarily. #define ENOMEM 1 #endif #ifndef SPINEL_PLATFORM_SHOULD_LOG_ASSERTS #define SPINEL_PLATFORM_SHOULD_LOG_ASSERTS 0 #endif #ifndef SPINEL_PLATFORM_DOESNT_IMPLEMENT_ERRNO_VAR #define SPINEL_PLATFORM_DOESNT_IMPLEMENT_ERRNO_VAR 0 #endif #ifndef SPINEL_PLATFORM_DOESNT_IMPLEMENT_FPRINTF #define SPINEL_PLATFORM_DOESNT_IMPLEMENT_FPRINTF 0 #endif #ifndef SPINEL_SELF_TEST #define SPINEL_SELF_TEST 0 #endif #if defined(errno) && SPINEL_PLATFORM_DOESNT_IMPLEMENT_ERRNO_VAR #error "SPINEL_PLATFORM_DOESNT_IMPLEMENT_ERRNO_VAR is set but errno is already defined." #endif // Work-around for platforms that don't implement the `errno` variable. #if !defined(errno) && SPINEL_PLATFORM_DOESNT_IMPLEMENT_ERRNO_VAR static int spinel_errno_workaround_; #define errno spinel_errno_workaround_ #endif // SPINEL_PLATFORM_DOESNT_IMPLEMENT_ERRNO_VAR #ifndef assert_printf #if SPINEL_PLATFORM_DOESNT_IMPLEMENT_FPRINTF #define assert_printf(fmt, ...) printf(__FILE__ ":%d: " fmt "\n", __LINE__, __VA_ARGS__) #else // if SPINEL_PLATFORM_DOESNT_IMPLEMENT_FPRINTF #define assert_printf(fmt, ...) fprintf(stderr, __FILE__ ":%d: " fmt "\n", __LINE__, __VA_ARGS__) #endif // else SPINEL_PLATFORM_DOESNT_IMPLEMENT_FPRINTF #endif #ifndef require_action #if SPINEL_PLATFORM_SHOULD_LOG_ASSERTS #define require_action(c, l, a) \ do \ { \ if (!(c)) \ { \ assert_printf("Requirement Failed (%s)", #c); \ a; \ goto l; \ } \ } while (0) #else // if DEBUG #define require_action(c, l, a) \ do \ { \ if (!(c)) \ { \ a; \ goto l; \ } \ } while (0) #endif // else DEBUG #endif // ifndef require_action #ifndef require #define require(c, l) require_action(c, l, {}) #endif #ifndef strnlen static size_t spinel_strnlen(const char *s, size_t maxlen) { size_t ret; for (ret = 0; (ret < maxlen) && (s[ret] != 0); ret++) { // Empty loop. } return ret; } #else #define spinel_strnlen strnlen #endif typedef struct { va_list obj; } va_list_obj; #define SPINEL_MAX_PACK_LENGTH 32767 // ---------------------------------------------------------------------------- // This function validates whether a given byte sequence (string) follows UTF8 encoding. static bool spinel_validate_utf8(const uint8_t *string) { bool ret = true; uint8_t byte; uint8_t continuation_bytes = 0; while ((byte = *string++) != 0) { if ((byte & 0x80) == 0) { continue; } // This is a leading byte 1xxx-xxxx. if ((byte & 0x40) == 0) // 10xx-xxxx { // We got a continuation byte pattern without seeing a leading byte earlier. ret = false; goto bail; } else if ((byte & 0x20) == 0) // 110x-xxxx { continuation_bytes = 1; } else if ((byte & 0x10) == 0) // 1110-xxxx { continuation_bytes = 2; } else if ((byte & 0x08) == 0) // 1111-0xxx { continuation_bytes = 3; } else // 1111-1xxx (invalid pattern). { ret = false; goto bail; } while (continuation_bytes-- != 0) { byte = *string++; // Verify the continuation byte pattern 10xx-xxxx if ((byte & 0xc0) != 0x80) { ret = false; goto bail; } } } bail: return ret; } // ---------------------------------------------------------------------------- // MARK: - spinel_ssize_t spinel_packed_uint_decode(const uint8_t *bytes, spinel_size_t len, unsigned int *value_ptr) { spinel_ssize_t ret = 0; unsigned int value = 0; unsigned int i = 0; do { if ((len < sizeof(uint8_t)) || (i >= sizeof(unsigned int) * CHAR_BIT)) { ret = -1; break; } value |= (unsigned int)(bytes[0] & 0x7F) << i; i += 7; ret += sizeof(uint8_t); bytes += sizeof(uint8_t); len -= sizeof(uint8_t); } while ((bytes[-1] & 0x80) == 0x80); if ((ret > 0) && (value_ptr != NULL)) { *value_ptr = value; } return ret; } spinel_ssize_t spinel_packed_uint_size(unsigned int value) { spinel_ssize_t ret; if (value < (1 << 7)) { ret = 1; } else if (value < (1 << 14)) { ret = 2; } else if (value < (1 << 21)) { ret = 3; } else if (value < (1 << 28)) { ret = 4; } else { ret = 5; } return ret; } spinel_ssize_t spinel_packed_uint_encode(uint8_t *bytes, spinel_size_t len, unsigned int value) { const spinel_ssize_t encoded_size = spinel_packed_uint_size(value); if ((spinel_ssize_t)len >= encoded_size) { spinel_ssize_t i; for (i = 0; i != encoded_size - 1; ++i) { *bytes++ = (value & 0x7F) | 0x80; value = (value >> 7); } *bytes++ = (value & 0x7F); } return encoded_size; } const char *spinel_next_packed_datatype(const char *pack_format) { int depth = 0; do { switch (*++pack_format) { case '(': depth++; break; case ')': depth--; if (depth == 0) { pack_format++; } break; } } while ((depth > 0) && *pack_format != 0); return pack_format; } static spinel_ssize_t spinel_datatype_vunpack_(bool in_place, const uint8_t *data_in, spinel_size_t data_len, const char * pack_format, va_list_obj * args) { spinel_ssize_t ret = 0; // Buffer length sanity check require_action(data_len <= SPINEL_MAX_PACK_LENGTH, bail, (ret = -1, errno = EINVAL)); for (; *pack_format != 0; pack_format = spinel_next_packed_datatype(pack_format)) { if (*pack_format == ')') { // Don't go past the end of a struct. break; } switch ((spinel_datatype_t)pack_format[0]) { case SPINEL_DATATYPE_BOOL_C: { bool *arg_ptr = va_arg(args->obj, bool *); require_action(data_len >= sizeof(uint8_t), bail, (ret = -1, errno = EOVERFLOW)); if (arg_ptr) { *arg_ptr = data_in[0] != 0; } ret += sizeof(uint8_t); data_in += sizeof(uint8_t); data_len -= sizeof(uint8_t); break; } case SPINEL_DATATYPE_INT8_C: case SPINEL_DATATYPE_UINT8_C: { uint8_t *arg_ptr = va_arg(args->obj, uint8_t *); require_action(data_len >= sizeof(uint8_t), bail, (ret = -1, errno = EOVERFLOW)); if (arg_ptr) { *arg_ptr = data_in[0]; } ret += sizeof(uint8_t); data_in += sizeof(uint8_t); data_len -= sizeof(uint8_t); break; } case SPINEL_DATATYPE_INT16_C: case SPINEL_DATATYPE_UINT16_C: { uint16_t *arg_ptr = va_arg(args->obj, uint16_t *); require_action(data_len >= sizeof(uint16_t), bail, (ret = -1, errno = EOVERFLOW)); if (arg_ptr) { *arg_ptr = (uint16_t)((data_in[1] << 8) | data_in[0]); } ret += sizeof(uint16_t); data_in += sizeof(uint16_t); data_len -= sizeof(uint16_t); break; } case SPINEL_DATATYPE_INT32_C: case SPINEL_DATATYPE_UINT32_C: { uint32_t *arg_ptr = va_arg(args->obj, uint32_t *); require_action(data_len >= sizeof(uint32_t), bail, (ret = -1, errno = EOVERFLOW)); if (arg_ptr) { *arg_ptr = (uint32_t)((data_in[3] << 24) | (data_in[2] << 16) | (data_in[1] << 8) | data_in[0]); } ret += sizeof(uint32_t); data_in += sizeof(uint32_t); data_len -= sizeof(uint32_t); break; } case SPINEL_DATATYPE_INT64_C: case SPINEL_DATATYPE_UINT64_C: { uint64_t *arg_ptr = va_arg(args->obj, uint64_t *); require_action(data_len >= sizeof(uint64_t), bail, (ret = -1, errno = EOVERFLOW)); if (arg_ptr) { uint32_t l32 = (uint32_t)((data_in[3] << 24) | (data_in[2] << 16) | (data_in[1] << 8) | data_in[0]); uint32_t h32 = (uint32_t)((data_in[7] << 24) | (data_in[6] << 16) | (data_in[5] << 8) | data_in[4]); *arg_ptr = ((uint64_t)l32) | (((uint64_t)h32) << 32); } ret += sizeof(uint64_t); data_in += sizeof(uint64_t); data_len -= sizeof(uint64_t); break; } case SPINEL_DATATYPE_IPv6ADDR_C: { require_action(data_len >= sizeof(spinel_ipv6addr_t), bail, (ret = -1, errno = EOVERFLOW)); if (in_place) { spinel_ipv6addr_t *arg = va_arg(args->obj, spinel_ipv6addr_t *); if (arg) { memcpy(arg, data_in, sizeof(spinel_ipv6addr_t)); } } else { const spinel_ipv6addr_t **arg_ptr = va_arg(args->obj, const spinel_ipv6addr_t **); if (arg_ptr) { *arg_ptr = (const spinel_ipv6addr_t *)data_in; } } ret += sizeof(spinel_ipv6addr_t); data_in += sizeof(spinel_ipv6addr_t); data_len -= sizeof(spinel_ipv6addr_t); break; } case SPINEL_DATATYPE_EUI64_C: { require_action(data_len >= sizeof(spinel_eui64_t), bail, (ret = -1, errno = EOVERFLOW)); if (in_place) { spinel_eui64_t *arg = va_arg(args->obj, spinel_eui64_t *); if (arg) { memcpy(arg, data_in, sizeof(spinel_eui64_t)); } } else { const spinel_eui64_t **arg_ptr = va_arg(args->obj, const spinel_eui64_t **); if (arg_ptr) { *arg_ptr = (const spinel_eui64_t *)data_in; } } ret += sizeof(spinel_eui64_t); data_in += sizeof(spinel_eui64_t); data_len -= sizeof(spinel_eui64_t); break; } case SPINEL_DATATYPE_EUI48_C: { require_action(data_len >= sizeof(spinel_eui48_t), bail, (ret = -1, errno = EOVERFLOW)); if (in_place) { spinel_eui48_t *arg = va_arg(args->obj, spinel_eui48_t *); if (arg) { memcpy(arg, data_in, sizeof(spinel_eui48_t)); } } else { const spinel_eui48_t **arg_ptr = va_arg(args->obj, const spinel_eui48_t **); if (arg_ptr) { *arg_ptr = (const spinel_eui48_t *)data_in; } } ret += sizeof(spinel_eui48_t); data_in += sizeof(spinel_eui48_t); data_len -= sizeof(spinel_eui48_t); break; } case SPINEL_DATATYPE_UINT_PACKED_C: { unsigned int * arg_ptr = va_arg(args->obj, unsigned int *); spinel_ssize_t pui_len = spinel_packed_uint_decode(data_in, data_len, arg_ptr); // Range check require_action(NULL == arg_ptr || (*arg_ptr < SPINEL_MAX_UINT_PACKED), bail, (ret = -1, errno = ERANGE)); require(pui_len > 0, bail); require(pui_len <= (spinel_ssize_t)data_len, bail); ret += pui_len; data_in += pui_len; data_len -= (spinel_size_t)pui_len; break; } case SPINEL_DATATYPE_UTF8_C: { size_t len; // Make sure we have at least one byte. require_action(data_len > 0, bail, (ret = -1, errno = EOVERFLOW)); // Add 1 for zero termination. If not zero terminated, // len will then be data_len+1, which we will detect // in the next check. len = spinel_strnlen((const char *)data_in, data_len) + 1; // Verify that the string is zero terminated. require_action(len <= data_len, bail, (ret = -1, errno = EOVERFLOW)); // Verify the string follows valid UTF8 encoding. require_action(spinel_validate_utf8(data_in), bail, (ret = -1, errno = EINVAL)); if (in_place) { char * arg = va_arg(args->obj, char *); size_t len_arg = va_arg(args->obj, size_t); if (arg) { require_action(len_arg >= len, bail, (ret = -1, errno = ENOMEM)); memcpy(arg, data_in, len); } } else { const char **arg_ptr = va_arg(args->obj, const char **); if (arg_ptr) { *arg_ptr = (const char *)data_in; } } ret += (spinel_size_t)len; data_in += len; data_len -= (spinel_size_t)len; break; } case SPINEL_DATATYPE_DATA_C: case SPINEL_DATATYPE_DATA_WLEN_C: { spinel_ssize_t pui_len = 0; uint16_t block_len = 0; const uint8_t *block_ptr = data_in; void * arg_ptr = va_arg(args->obj, void *); unsigned int * block_len_ptr = va_arg(args->obj, unsigned int *); char nextformat = *spinel_next_packed_datatype(pack_format); if ((pack_format[0] == SPINEL_DATATYPE_DATA_WLEN_C) || ((nextformat != 0) && (nextformat != ')'))) { pui_len = spinel_datatype_unpack(data_in, data_len, SPINEL_DATATYPE_UINT16_S, &block_len); block_ptr += pui_len; require(pui_len > 0, bail); require(block_len < SPINEL_FRAME_MAX_SIZE, bail); } else { block_len = (uint16_t)data_len; pui_len = 0; } require_action((spinel_ssize_t)data_len >= (block_len + pui_len), bail, (ret = -1, errno = EOVERFLOW)); if (in_place) { require_action(NULL != block_len_ptr && *block_len_ptr >= block_len, bail, (ret = -1, errno = EINVAL)); memcpy(arg_ptr, block_ptr, block_len); } else { const uint8_t **block_ptr_ptr = (const uint8_t **)arg_ptr; if (NULL != block_ptr_ptr) { *block_ptr_ptr = block_ptr; } } if (NULL != block_len_ptr) { *block_len_ptr = block_len; } block_len += (uint16_t)pui_len; ret += block_len; data_in += block_len; data_len -= block_len; break; } case 'T': case SPINEL_DATATYPE_STRUCT_C: { spinel_ssize_t pui_len = 0; uint16_t block_len = 0; spinel_ssize_t actual_len = 0; const uint8_t *block_ptr = data_in; char nextformat = *spinel_next_packed_datatype(pack_format); if ((pack_format[0] == SPINEL_DATATYPE_STRUCT_C) || ((nextformat != 0) && (nextformat != ')'))) { pui_len = spinel_datatype_unpack(data_in, data_len, SPINEL_DATATYPE_UINT16_S, &block_len); block_ptr += pui_len; require(pui_len > 0, bail); require(block_len < SPINEL_FRAME_MAX_SIZE, bail); } else { block_len = (uint16_t)data_len; pui_len = 0; } require_action((spinel_ssize_t)data_len >= (block_len + pui_len), bail, (ret = -1, errno = EOVERFLOW)); actual_len = spinel_datatype_vunpack_(false, block_ptr, block_len, pack_format + 2, args); require_action(actual_len > -1, bail, (ret = -1, errno = EOVERFLOW)); if (pui_len) { block_len += (uint16_t)pui_len; } else { block_len = (uint16_t)actual_len; } ret += block_len; data_in += block_len; data_len -= block_len; break; } case '.': // Skip. break; case SPINEL_DATATYPE_ARRAY_C: default: // Unsupported Type! ret = -1; errno = EINVAL; goto bail; } } return ret; bail: return ret; } spinel_ssize_t spinel_datatype_unpack_in_place(const uint8_t *data_in, spinel_size_t data_len, const char * pack_format, ...) { spinel_ssize_t ret; va_list_obj args; va_start(args.obj, pack_format); ret = spinel_datatype_vunpack_(true, data_in, data_len, pack_format, &args); va_end(args.obj); return ret; } spinel_ssize_t spinel_datatype_unpack(const uint8_t *data_in, spinel_size_t data_len, const char *pack_format, ...) { spinel_ssize_t ret; va_list_obj args; va_start(args.obj, pack_format); ret = spinel_datatype_vunpack_(false, data_in, data_len, pack_format, &args); va_end(args.obj); return ret; } spinel_ssize_t spinel_datatype_vunpack_in_place(const uint8_t *data_in, spinel_size_t data_len, const char * pack_format, va_list args) { spinel_ssize_t ret; va_list_obj args_obj; va_copy(args_obj.obj, args); ret = spinel_datatype_vunpack_(true, data_in, data_len, pack_format, &args_obj); va_end(args_obj.obj); return ret; } spinel_ssize_t spinel_datatype_vunpack(const uint8_t *data_in, spinel_size_t data_len, const char * pack_format, va_list args) { spinel_ssize_t ret; va_list_obj args_obj; va_copy(args_obj.obj, args); ret = spinel_datatype_vunpack_(false, data_in, data_len, pack_format, &args_obj); va_end(args_obj.obj); return ret; } static spinel_ssize_t spinel_datatype_vpack_(uint8_t * data_out, spinel_size_t data_len_max, const char * pack_format, va_list_obj * args) { spinel_ssize_t ret = 0; // Buffer length sanity check require_action(data_len_max <= SPINEL_MAX_PACK_LENGTH, bail, (ret = -1, errno = EINVAL)); if (data_out == NULL) { data_len_max = 0; } for (; *pack_format != 0; pack_format = spinel_next_packed_datatype(pack_format)) { if (*pack_format == ')') { // Don't go past the end of a struct. break; } switch ((spinel_datatype_t)*pack_format) { case SPINEL_DATATYPE_BOOL_C: { bool arg = (bool)va_arg(args->obj, int); ret += sizeof(uint8_t); if (data_len_max >= sizeof(uint8_t)) { data_out[0] = (arg != false); data_out += sizeof(uint8_t); data_len_max -= sizeof(uint8_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_INT8_C: case SPINEL_DATATYPE_UINT8_C: { uint8_t arg = (uint8_t)va_arg(args->obj, int); ret += sizeof(uint8_t); if (data_len_max >= sizeof(uint8_t)) { data_out[0] = arg; data_out += sizeof(uint8_t); data_len_max -= sizeof(uint8_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_INT16_C: case SPINEL_DATATYPE_UINT16_C: { uint16_t arg = (uint16_t)va_arg(args->obj, int); ret += sizeof(uint16_t); if (data_len_max >= sizeof(uint16_t)) { data_out[1] = (arg >> 8) & 0xff; data_out[0] = (arg >> 0) & 0xff; data_out += sizeof(uint16_t); data_len_max -= sizeof(uint16_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_INT32_C: case SPINEL_DATATYPE_UINT32_C: { uint32_t arg = (uint32_t)va_arg(args->obj, int); ret += sizeof(uint32_t); if (data_len_max >= sizeof(uint32_t)) { data_out[3] = (arg >> 24) & 0xff; data_out[2] = (arg >> 16) & 0xff; data_out[1] = (arg >> 8) & 0xff; data_out[0] = (arg >> 0) & 0xff; data_out += sizeof(uint32_t); data_len_max -= sizeof(uint32_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_INT64_C: case SPINEL_DATATYPE_UINT64_C: { uint64_t arg = va_arg(args->obj, uint64_t); ret += sizeof(uint64_t); if (data_len_max >= sizeof(uint64_t)) { data_out[7] = (arg >> 56) & 0xff; data_out[6] = (arg >> 48) & 0xff; data_out[5] = (arg >> 40) & 0xff; data_out[4] = (arg >> 32) & 0xff; data_out[3] = (arg >> 24) & 0xff; data_out[2] = (arg >> 16) & 0xff; data_out[1] = (arg >> 8) & 0xff; data_out[0] = (arg >> 0) & 0xff; data_out += sizeof(uint64_t); data_len_max -= sizeof(uint64_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_IPv6ADDR_C: { spinel_ipv6addr_t *arg = va_arg(args->obj, spinel_ipv6addr_t *); ret += sizeof(spinel_ipv6addr_t); if (data_len_max >= sizeof(spinel_ipv6addr_t)) { *(spinel_ipv6addr_t *)data_out = *arg; data_out += sizeof(spinel_ipv6addr_t); data_len_max -= sizeof(spinel_ipv6addr_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_EUI48_C: { spinel_eui48_t *arg = va_arg(args->obj, spinel_eui48_t *); ret += sizeof(spinel_eui48_t); if (data_len_max >= sizeof(spinel_eui48_t)) { *(spinel_eui48_t *)data_out = *arg; data_out += sizeof(spinel_eui48_t); data_len_max -= sizeof(spinel_eui48_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_EUI64_C: { spinel_eui64_t *arg = va_arg(args->obj, spinel_eui64_t *); ret += sizeof(spinel_eui64_t); if (data_len_max >= sizeof(spinel_eui64_t)) { *(spinel_eui64_t *)data_out = *arg; data_out += sizeof(spinel_eui64_t); data_len_max -= sizeof(spinel_eui64_t); } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_UINT_PACKED_C: { uint32_t arg = va_arg(args->obj, uint32_t); spinel_ssize_t encoded_size; // Range Check require_action(arg < SPINEL_MAX_UINT_PACKED, bail, { ret = -1; errno = EINVAL; }); encoded_size = spinel_packed_uint_encode(data_out, data_len_max, arg); ret += encoded_size; if ((spinel_ssize_t)data_len_max >= encoded_size) { data_out += encoded_size; data_len_max -= (spinel_size_t)encoded_size; } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_UTF8_C: { const char *string_arg = va_arg(args->obj, const char *); size_t string_arg_len = 0; if (string_arg) { string_arg_len = strlen(string_arg) + 1; } else { string_arg = ""; string_arg_len = 1; } ret += (spinel_size_t)string_arg_len; if (data_len_max >= string_arg_len) { memcpy(data_out, string_arg, string_arg_len); data_out += string_arg_len; data_len_max -= (spinel_size_t)string_arg_len; } else { data_len_max = 0; } break; } case SPINEL_DATATYPE_DATA_WLEN_C: case SPINEL_DATATYPE_DATA_C: { const uint8_t *arg = va_arg(args->obj, const uint8_t *); uint32_t data_size_arg = va_arg(args->obj, uint32_t); spinel_ssize_t size_len = 0; char nextformat = *spinel_next_packed_datatype(pack_format); if ((pack_format[0] == SPINEL_DATATYPE_DATA_WLEN_C) || ((nextformat != 0) && (nextformat != ')'))) { size_len = spinel_datatype_pack(data_out, data_len_max, SPINEL_DATATYPE_UINT16_S, data_size_arg); require_action(size_len > 0, bail, { ret = -1; errno = EINVAL; }); } ret += (spinel_size_t)size_len + data_size_arg; if (data_len_max >= (spinel_size_t)size_len + data_size_arg) { data_out += size_len; data_len_max -= (spinel_size_t)size_len; if (data_out && arg) { memcpy(data_out, arg, data_size_arg); } data_out += data_size_arg; data_len_max -= data_size_arg; } else { data_len_max = 0; } break; } case 'T': case SPINEL_DATATYPE_STRUCT_C: { spinel_ssize_t struct_len = 0; spinel_ssize_t size_len = 0; char nextformat = *spinel_next_packed_datatype(pack_format); require_action(pack_format[1] == '(', bail, { ret = -1; errno = EINVAL; }); // First we figure out the size of the struct { va_list_obj subargs; va_copy(subargs.obj, args->obj); struct_len = spinel_datatype_vpack_(NULL, 0, pack_format + 2, &subargs); va_end(subargs.obj); } if ((pack_format[0] == SPINEL_DATATYPE_STRUCT_C) || ((nextformat != 0) && (nextformat != ')'))) { size_len = spinel_datatype_pack(data_out, data_len_max, SPINEL_DATATYPE_UINT16_S, struct_len); require_action(size_len > 0, bail, { ret = -1; errno = EINVAL; }); } ret += size_len + struct_len; if (struct_len + size_len <= (spinel_ssize_t)data_len_max) { data_out += size_len; data_len_max -= (spinel_size_t)size_len; struct_len = spinel_datatype_vpack_(data_out, data_len_max, pack_format + 2, args); data_out += struct_len; data_len_max -= (spinel_size_t)struct_len; } else { data_len_max = 0; } break; } case '.': // Skip. break; default: // Unsupported Type! ret = -1; errno = EINVAL; goto bail; } } bail: return ret; } spinel_ssize_t spinel_datatype_pack(uint8_t *data_out, spinel_size_t data_len_max, const char *pack_format, ...) { int ret; va_list_obj args; va_start(args.obj, pack_format); ret = spinel_datatype_vpack_(data_out, data_len_max, pack_format, &args); va_end(args.obj); return ret; } spinel_ssize_t spinel_datatype_vpack(uint8_t * data_out, spinel_size_t data_len_max, const char * pack_format, va_list args) { int ret; va_list_obj args_obj; va_copy(args_obj.obj, args); ret = spinel_datatype_vpack_(data_out, data_len_max, pack_format, &args_obj); va_end(args_obj.obj); return ret; } // ---------------------------------------------------------------------------- // MARK: - // LCOV_EXCL_START struct spinel_cstr { uint32_t val; const char *str; }; static const char *spinel_to_cstr(const struct spinel_cstr *table, uint32_t val) { int i; for (i = 0; table[i].str; i++) if (val == table[i].val) return table[i].str; return "UNKNOWN"; } const char *spinel_command_to_cstr(spinel_command_t command) { static const struct spinel_cstr spinel_commands_cstr[] = { {SPINEL_CMD_NOOP, "NOOP"}, {SPINEL_CMD_RESET, "RESET"}, {SPINEL_CMD_PROP_VALUE_GET, "PROP_VALUE_GET"}, {SPINEL_CMD_PROP_VALUE_SET, "PROP_VALUE_SET"}, {SPINEL_CMD_PROP_VALUE_INSERT, "PROP_VALUE_INSERT"}, {SPINEL_CMD_PROP_VALUE_REMOVE, "PROP_VALUE_REMOVE"}, {SPINEL_CMD_PROP_VALUE_IS, "PROP_VALUE_IS"}, {SPINEL_CMD_PROP_VALUE_INSERTED, "PROP_VALUE_INSERTED"}, {SPINEL_CMD_PROP_VALUE_REMOVED, "PROP_VALUE_REMOVED"}, {SPINEL_CMD_NET_SAVE, "NET_SAVE"}, {SPINEL_CMD_NET_CLEAR, "NET_CLEAR"}, {SPINEL_CMD_NET_RECALL, "NET_RECALL"}, {SPINEL_CMD_HBO_OFFLOAD, "HBO_OFFLOAD"}, {SPINEL_CMD_HBO_RECLAIM, "HBO_RECLAIM"}, {SPINEL_CMD_HBO_DROP, "HBO_DROP"}, {SPINEL_CMD_HBO_OFFLOADED, "HBO_OFFLOADED"}, {SPINEL_CMD_HBO_RECLAIMED, "HBO_RECLAIMED"}, {SPINEL_CMD_HBO_DROPPED, "HBO_DROPPED"}, {SPINEL_CMD_PEEK, "PEEK"}, {SPINEL_CMD_PEEK_RET, "PEEK_RET"}, {SPINEL_CMD_POKE, "POKE"}, {SPINEL_CMD_PROP_VALUE_MULTI_GET, "PROP_VALUE_MULTI_GET"}, {SPINEL_CMD_PROP_VALUE_MULTI_SET, "PROP_VALUE_MULTI_SET"}, {SPINEL_CMD_PROP_VALUES_ARE, "PROP_VALUES_ARE"}, {0, NULL}, }; return spinel_to_cstr(spinel_commands_cstr, command); } const char *spinel_prop_key_to_cstr(spinel_prop_key_t prop_key) { static const struct spinel_cstr spinel_prop_cstr[] = { {SPINEL_PROP_LAST_STATUS, "LAST_STATUS"}, {SPINEL_PROP_PROTOCOL_VERSION, "PROTOCOL_VERSION"}, {SPINEL_PROP_NCP_VERSION, "NCP_VERSION"}, {SPINEL_PROP_INTERFACE_TYPE, "INTERFACE_TYPE"}, {SPINEL_PROP_VENDOR_ID, "VENDOR_ID"}, {SPINEL_PROP_CAPS, "CAPS"}, {SPINEL_PROP_INTERFACE_COUNT, "INTERFACE_COUNT"}, {SPINEL_PROP_POWER_STATE, "POWER_STATE"}, {SPINEL_PROP_HWADDR, "HWADDR"}, {SPINEL_PROP_LOCK, "LOCK"}, {SPINEL_PROP_HBO_MEM_MAX, "HBO_MEM_MAX"}, {SPINEL_PROP_HBO_BLOCK_MAX, "HBO_BLOCK_MAX"}, {SPINEL_PROP_HOST_POWER_STATE, "HOST_POWER_STATE"}, {SPINEL_PROP_MCU_POWER_STATE, "MCU_POWER_STATE"}, {SPINEL_PROP_GPIO_CONFIG, "GPIO_CONFIG"}, {SPINEL_PROP_GPIO_STATE, "GPIO_STATE"}, {SPINEL_PROP_GPIO_STATE_SET, "GPIO_STATE_SET"}, {SPINEL_PROP_GPIO_STATE_CLEAR, "GPIO_STATE_CLEAR"}, {SPINEL_PROP_TRNG_32, "TRNG_32"}, {SPINEL_PROP_TRNG_128, "TRNG_128"}, {SPINEL_PROP_TRNG_RAW_32, "TRNG_RAW_32"}, {SPINEL_PROP_UNSOL_UPDATE_FILTER, "UNSOL_UPDATE_FILTER"}, {SPINEL_PROP_UNSOL_UPDATE_LIST, "UNSOL_UPDATE_LIST"}, {SPINEL_PROP_PHY_ENABLED, "PHY_ENABLED"}, {SPINEL_PROP_PHY_CHAN, "PHY_CHAN"}, {SPINEL_PROP_PHY_CHAN_SUPPORTED, "PHY_CHAN_SUPPORTED"}, {SPINEL_PROP_PHY_FREQ, "PHY_FREQ"}, {SPINEL_PROP_PHY_CCA_THRESHOLD, "PHY_CCA_THRESHOLD"}, {SPINEL_PROP_PHY_TX_POWER, "PHY_TX_POWER"}, {SPINEL_PROP_PHY_FEM_LNA_GAIN, "PHY_FEM_LNA_GAIN"}, {SPINEL_PROP_PHY_RSSI, "PHY_RSSI"}, {SPINEL_PROP_PHY_RX_SENSITIVITY, "PHY_RX_SENSITIVITY"}, {SPINEL_PROP_PHY_PCAP_ENABLED, "PHY_PCAP_ENABLED"}, {SPINEL_PROP_PHY_CHAN_PREFERRED, "PHY_CHAN_PREFERRED"}, {SPINEL_PROP_PHY_CHAN_MAX_POWER, "PHY_CHAN_MAX_POWER"}, {SPINEL_PROP_JAM_DETECT_ENABLE, "JAM_DETECT_ENABLE"}, {SPINEL_PROP_JAM_DETECTED, "JAM_DETECTED"}, {SPINEL_PROP_JAM_DETECT_RSSI_THRESHOLD, "JAM_DETECT_RSSI_THRESHOLD"}, {SPINEL_PROP_JAM_DETECT_WINDOW, "JAM_DETECT_WINDOW"}, {SPINEL_PROP_JAM_DETECT_BUSY, "JAM_DETECT_BUSY"}, {SPINEL_PROP_JAM_DETECT_HISTORY_BITMAP, "JAM_DETECT_HISTORY_BITMAP"}, {SPINEL_PROP_CHANNEL_MONITOR_SAMPLE_INTERVAL, "CHANNEL_MONITOR_SAMPLE_INTERVAL"}, {SPINEL_PROP_CHANNEL_MONITOR_RSSI_THRESHOLD, "CHANNEL_MONITOR_RSSI_THRESHOLD"}, {SPINEL_PROP_CHANNEL_MONITOR_SAMPLE_WINDOW, "CHANNEL_MONITOR_SAMPLE_WINDOW"}, {SPINEL_PROP_CHANNEL_MONITOR_SAMPLE_COUNT, "CHANNEL_MONITOR_SAMPLE_COUNT"}, {SPINEL_PROP_CHANNEL_MONITOR_CHANNEL_OCCUPANCY, "CHANNEL_MONITOR_CHANNEL_OCCUPANCY"}, {SPINEL_PROP_RADIO_CAPS, "RADIO_CAPS"}, {SPINEL_PROP_RADIO_COEX_METRICS, "RADIO_COEX_METRICS"}, {SPINEL_PROP_RADIO_COEX_ENABLE, "RADIO_COEX_ENABLE"}, {SPINEL_PROP_MAC_SCAN_STATE, "MAC_SCAN_STATE"}, {SPINEL_PROP_MAC_SCAN_MASK, "MAC_SCAN_MASK"}, {SPINEL_PROP_MAC_SCAN_PERIOD, "MAC_SCAN_PERIOD"}, {SPINEL_PROP_MAC_SCAN_BEACON, "MAC_SCAN_BEACON"}, {SPINEL_PROP_MAC_15_4_LADDR, "MAC_15_4_LADDR"}, {SPINEL_PROP_MAC_15_4_SADDR, "MAC_15_4_SADDR"}, {SPINEL_PROP_MAC_15_4_PANID, "MAC_15_4_PANID"}, {SPINEL_PROP_MAC_RAW_STREAM_ENABLED, "MAC_RAW_STREAM_ENABLED"}, {SPINEL_PROP_MAC_PROMISCUOUS_MODE, "MAC_PROMISCUOUS_MODE"}, {SPINEL_PROP_MAC_ENERGY_SCAN_RESULT, "MAC_ENERGY_SCAN_RESULT"}, {SPINEL_PROP_MAC_DATA_POLL_PERIOD, "MAC_DATA_POLL_PERIOD"}, {SPINEL_PROP_MAC_ALLOWLIST, "MAC_ALLOWLIST"}, {SPINEL_PROP_MAC_ALLOWLIST_ENABLED, "MAC_ALLOWLIST_ENABLED"}, {SPINEL_PROP_MAC_EXTENDED_ADDR, "MAC_EXTENDED_ADDR"}, {SPINEL_PROP_MAC_SRC_MATCH_ENABLED, "MAC_SRC_MATCH_ENABLED"}, {SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, "MAC_SRC_MATCH_SHORT_ADDRESSES"}, {SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, "MAC_SRC_MATCH_EXTENDED_ADDRESSES"}, {SPINEL_PROP_MAC_DENYLIST, "MAC_DENYLIST"}, {SPINEL_PROP_MAC_DENYLIST_ENABLED, "MAC_DENYLIST_ENABLED"}, {SPINEL_PROP_MAC_FIXED_RSS, "MAC_FIXED_RSS"}, {SPINEL_PROP_MAC_CCA_FAILURE_RATE, "MAC_CCA_FAILURE_RATE"}, {SPINEL_PROP_MAC_MAX_RETRY_NUMBER_DIRECT, "MAC_MAX_RETRY_NUMBER_DIRECT"}, {SPINEL_PROP_MAC_MAX_RETRY_NUMBER_INDIRECT, "MAC_MAX_RETRY_NUMBER_INDIRECT"}, {SPINEL_PROP_NET_SAVED, "NET_SAVED"}, {SPINEL_PROP_NET_IF_UP, "NET_IF_UP"}, {SPINEL_PROP_NET_STACK_UP, "NET_STACK_UP"}, {SPINEL_PROP_NET_ROLE, "NET_ROLE"}, {SPINEL_PROP_NET_NETWORK_NAME, "NET_NETWORK_NAME"}, {SPINEL_PROP_NET_XPANID, "NET_XPANID"}, {SPINEL_PROP_NET_NETWORK_KEY, "NET_NETWORK_KEY"}, {SPINEL_PROP_NET_KEY_SEQUENCE_COUNTER, "NET_KEY_SEQUENCE_COUNTER"}, {SPINEL_PROP_NET_PARTITION_ID, "NET_PARTITION_ID"}, {SPINEL_PROP_NET_REQUIRE_JOIN_EXISTING, "NET_REQUIRE_JOIN_EXISTING"}, {SPINEL_PROP_NET_KEY_SWITCH_GUARDTIME, "NET_KEY_SWITCH_GUARDTIME"}, {SPINEL_PROP_NET_PSKC, "NET_PSKC"}, {SPINEL_PROP_THREAD_LEADER_ADDR, "THREAD_LEADER_ADDR"}, {SPINEL_PROP_THREAD_PARENT, "THREAD_PARENT"}, {SPINEL_PROP_THREAD_CHILD_TABLE, "THREAD_CHILD_TABLE"}, {SPINEL_PROP_THREAD_LEADER_RID, "THREAD_LEADER_RID"}, {SPINEL_PROP_THREAD_LEADER_WEIGHT, "THREAD_LEADER_WEIGHT"}, {SPINEL_PROP_THREAD_LOCAL_LEADER_WEIGHT, "THREAD_LOCAL_LEADER_WEIGHT"}, {SPINEL_PROP_THREAD_NETWORK_DATA, "THREAD_NETWORK_DATA"}, {SPINEL_PROP_THREAD_NETWORK_DATA_VERSION, "THREAD_NETWORK_DATA_VERSION"}, {SPINEL_PROP_THREAD_STABLE_NETWORK_DATA, "THREAD_STABLE_NETWORK_DATA"}, {SPINEL_PROP_THREAD_STABLE_NETWORK_DATA_VERSION, "THREAD_STABLE_NETWORK_DATA_VERSION"}, {SPINEL_PROP_THREAD_ON_MESH_NETS, "THREAD_ON_MESH_NETS"}, {SPINEL_PROP_THREAD_OFF_MESH_ROUTES, "THREAD_OFF_MESH_ROUTES"}, {SPINEL_PROP_THREAD_ASSISTING_PORTS, "THREAD_ASSISTING_PORTS"}, {SPINEL_PROP_THREAD_ALLOW_LOCAL_NET_DATA_CHANGE, "THREAD_ALLOW_LOCAL_NET_DATA_CHANGE"}, {SPINEL_PROP_THREAD_MODE, "THREAD_MODE"}, {SPINEL_PROP_THREAD_CHILD_TIMEOUT, "THREAD_CHILD_TIMEOUT"}, {SPINEL_PROP_THREAD_RLOC16, "THREAD_RLOC16"}, {SPINEL_PROP_THREAD_ROUTER_UPGRADE_THRESHOLD, "THREAD_ROUTER_UPGRADE_THRESHOLD"}, {SPINEL_PROP_THREAD_CONTEXT_REUSE_DELAY, "THREAD_CONTEXT_REUSE_DELAY"}, {SPINEL_PROP_THREAD_NETWORK_ID_TIMEOUT, "THREAD_NETWORK_ID_TIMEOUT"}, {SPINEL_PROP_THREAD_ACTIVE_ROUTER_IDS, "THREAD_ACTIVE_ROUTER_IDS"}, {SPINEL_PROP_THREAD_RLOC16_DEBUG_PASSTHRU, "THREAD_RLOC16_DEBUG_PASSTHRU"}, {SPINEL_PROP_THREAD_ROUTER_ROLE_ENABLED, "THREAD_ROUTER_ROLE_ENABLED"}, {SPINEL_PROP_THREAD_ROUTER_DOWNGRADE_THRESHOLD, "THREAD_ROUTER_DOWNGRADE_THRESHOLD"}, {SPINEL_PROP_THREAD_ROUTER_SELECTION_JITTER, "THREAD_ROUTER_SELECTION_JITTER"}, {SPINEL_PROP_THREAD_PREFERRED_ROUTER_ID, "THREAD_PREFERRED_ROUTER_ID"}, {SPINEL_PROP_THREAD_NEIGHBOR_TABLE, "THREAD_NEIGHBOR_TABLE"}, {SPINEL_PROP_THREAD_CHILD_COUNT_MAX, "THREAD_CHILD_COUNT_MAX"}, {SPINEL_PROP_THREAD_LEADER_NETWORK_DATA, "THREAD_LEADER_NETWORK_DATA"}, {SPINEL_PROP_THREAD_STABLE_LEADER_NETWORK_DATA, "THREAD_STABLE_LEADER_NETWORK_DATA"}, {SPINEL_PROP_THREAD_JOINERS, "THREAD_JOINERS"}, {SPINEL_PROP_THREAD_COMMISSIONER_ENABLED, "THREAD_COMMISSIONER_ENABLED"}, {SPINEL_PROP_THREAD_TMF_PROXY_ENABLED, "THREAD_TMF_PROXY_ENABLED"}, {SPINEL_PROP_THREAD_TMF_PROXY_STREAM, "THREAD_TMF_PROXY_STREAM"}, {SPINEL_PROP_THREAD_UDP_FORWARD_STREAM, "THREAD_UDP_FORWARD_STREAM"}, {SPINEL_PROP_THREAD_DISCOVERY_SCAN_JOINER_FLAG, "THREAD_DISCOVERY_SCAN_JOINER_FLAG"}, {SPINEL_PROP_THREAD_DISCOVERY_SCAN_ENABLE_FILTERING, "THREAD_DISCOVERY_SCAN_ENABLE_FILTERING"}, {SPINEL_PROP_THREAD_DISCOVERY_SCAN_PANID, "THREAD_DISCOVERY_SCAN_PANID"}, {SPINEL_PROP_THREAD_STEERING_DATA, "THREAD_STEERING_DATA"}, {SPINEL_PROP_THREAD_ROUTER_TABLE, "THREAD_ROUTER_TABLE"}, {SPINEL_PROP_THREAD_ACTIVE_DATASET, "THREAD_ACTIVE_DATASET"}, {SPINEL_PROP_THREAD_PENDING_DATASET, "THREAD_PENDING_DATASET"}, {SPINEL_PROP_THREAD_MGMT_SET_ACTIVE_DATASET, "THREAD_MGMT_SET_ACTIVE_DATASET"}, {SPINEL_PROP_THREAD_MGMT_SET_PENDING_DATASET, "THREAD_MGMT_SET_PENDING_DATASET"}, {SPINEL_PROP_DATASET_ACTIVE_TIMESTAMP, "DATASET_ACTIVE_TIMESTAMP"}, {SPINEL_PROP_DATASET_PENDING_TIMESTAMP, "DATASET_PENDING_TIMESTAMP"}, {SPINEL_PROP_DATASET_DELAY_TIMER, "DATASET_DELAY_TIMER"}, {SPINEL_PROP_DATASET_SECURITY_POLICY, "DATASET_SECURITY_POLICY"}, {SPINEL_PROP_DATASET_RAW_TLVS, "DATASET_RAW_TLVS"}, {SPINEL_PROP_THREAD_CHILD_TABLE_ADDRESSES, "THREAD_CHILD_TABLE_ADDRESSES"}, {SPINEL_PROP_THREAD_NEIGHBOR_TABLE_ERROR_RATES, "THREAD_NEIGHBOR_TABLE_ERROR_RATES"}, {SPINEL_PROP_THREAD_ADDRESS_CACHE_TABLE, "THREAD_ADDRESS_CACHE_TABLE"}, {SPINEL_PROP_THREAD_MGMT_GET_ACTIVE_DATASET, "THREAD_MGMT_GET_ACTIVE_DATASET"}, {SPINEL_PROP_THREAD_MGMT_GET_PENDING_DATASET, "THREAD_MGMT_GET_PENDING_DATASET"}, {SPINEL_PROP_DATASET_DEST_ADDRESS, "DATASET_DEST_ADDRESS"}, {SPINEL_PROP_THREAD_NEW_DATASET, "THREAD_NEW_DATASET"}, {SPINEL_PROP_THREAD_CSL_PERIOD, "THREAD_CSL_PERIOD"}, {SPINEL_PROP_THREAD_CSL_TIMEOUT, "THREAD_CSL_TIMEOUT"}, {SPINEL_PROP_THREAD_CSL_CHANNEL, "THREAD_CSL_CHANNEL"}, {SPINEL_PROP_THREAD_DOMAIN_NAME, "THREAD_DOMAIN_NAME"}, {SPINEL_PROP_THREAD_LINK_METRICS_QUERY, "THREAD_LINK_METRICS_QUERY"}, {SPINEL_PROP_THREAD_LINK_METRICS_QUERY_RESULT, "THREAD_LINK_METRICS_QUERY_RESULT"}, {SPINEL_PROP_THREAD_LINK_METRICS_PROBE, "THREAD_LINK_METRICS_PROBE"}, {SPINEL_PROP_THREAD_LINK_METRICS_MGMT_ENH_ACK, "THREAD_LINK_METRICS_MGMT_ENH_ACK"}, {SPINEL_PROP_THREAD_LINK_METRICS_MGMT_ENH_ACK_IE, "THREAD_LINK_METRICS_MGMT_ENH_ACK_IE"}, {SPINEL_PROP_THREAD_LINK_METRICS_MGMT_FORWARD, "THREAD_LINK_METRICS_MGMT_FORWARD"}, {SPINEL_PROP_THREAD_LINK_METRICS_MGMT_RESPONSE, "THREAD_LINK_METRICS_MGMT_RESPONSE"}, {SPINEL_PROP_THREAD_MLR_REQUEST, "THREAD_MLR_REQUEST"}, {SPINEL_PROP_THREAD_MLR_RESPONSE, "THREAD_MLR_RESPONSE"}, {SPINEL_PROP_THREAD_BACKBONE_ROUTER_PRIMARY, "THREAD_BACKBONE_ROUTER_PRIMARY"}, {SPINEL_PROP_THREAD_BACKBONE_ROUTER_LOCAL_STATE, "THREAD_BACKBONE_ROUTER_LOCAL_STATE"}, {SPINEL_PROP_THREAD_BACKBONE_ROUTER_LOCAL_CONFIG, "THREAD_BACKBONE_ROUTER_LOCAL_CONFIG"}, {SPINEL_PROP_THREAD_BACKBONE_ROUTER_LOCAL_REGISTER, "THREAD_BACKBONE_ROUTER_LOCAL_REGISTER"}, {SPINEL_PROP_THREAD_BACKBONE_ROUTER_LOCAL_REGISTRATION_JITTER, "THREAD_BACKBONE_ROUTER_LOCAL_REGISTRATION_JITTER"}, {SPINEL_PROP_MESHCOP_JOINER_STATE, "MESHCOP_JOINER_STATE"}, {SPINEL_PROP_MESHCOP_JOINER_COMMISSIONING, "MESHCOP_JOINER_COMMISSIONING"}, {SPINEL_PROP_IPV6_LL_ADDR, "IPV6_LL_ADDR"}, {SPINEL_PROP_IPV6_ML_ADDR, "IPV6_ML_ADDR"}, {SPINEL_PROP_IPV6_ML_PREFIX, "IPV6_ML_PREFIX"}, {SPINEL_PROP_IPV6_ADDRESS_TABLE, "IPV6_ADDRESS_TABLE"}, {SPINEL_PROP_IPV6_ROUTE_TABLE, "IPV6_ROUTE_TABLE"}, {SPINEL_PROP_IPV6_ICMP_PING_OFFLOAD, "IPV6_ICMP_PING_OFFLOAD"}, {SPINEL_PROP_IPV6_MULTICAST_ADDRESS_TABLE, "IPV6_MULTICAST_ADDRESS_TABLE"}, {SPINEL_PROP_IPV6_ICMP_PING_OFFLOAD_MODE, "IPV6_ICMP_PING_OFFLOAD_MODE"}, {SPINEL_PROP_STREAM_DEBUG, "STREAM_DEBUG"}, {SPINEL_PROP_STREAM_RAW, "STREAM_RAW"}, {SPINEL_PROP_STREAM_NET, "STREAM_NET"}, {SPINEL_PROP_STREAM_NET_INSECURE, "STREAM_NET_INSECURE"}, {SPINEL_PROP_STREAM_LOG, "STREAM_LOG"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_STATE, "MESHCOP_COMMISSIONER_STATE"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_JOINERS, "MESHCOP_COMMISSIONER_JOINERS"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_PROVISIONING_URL, "MESHCOP_COMMISSIONER_PROVISIONING_URL"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_SESSION_ID, "MESHCOP_COMMISSIONER_SESSION_ID"}, {SPINEL_PROP_MESHCOP_JOINER_DISCERNER, "MESHCOP_JOINER_DISCERNER"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_ANNOUNCE_BEGIN, "MESHCOP_COMMISSIONER_ANNOUNCE_BEGIN"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_ENERGY_SCAN, "MESHCOP_COMMISSIONER_ENERGY_SCAN"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_ENERGY_SCAN_RESULT, "MESHCOP_COMMISSIONER_ENERGY_SCAN_RESULT"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_PAN_ID_QUERY, "MESHCOP_COMMISSIONER_PAN_ID_QUERY"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_PAN_ID_CONFLICT_RESULT, "MESHCOP_COMMISSIONER_PAN_ID_CONFLICT_RESULT"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_MGMT_GET, "MESHCOP_COMMISSIONER_MGMT_GET"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_MGMT_SET, "MESHCOP_COMMISSIONER_MGMT_SET"}, {SPINEL_PROP_MESHCOP_COMMISSIONER_GENERATE_PSKC, "MESHCOP_COMMISSIONER_GENERATE_PSKC"}, {SPINEL_PROP_CHANNEL_MANAGER_NEW_CHANNEL, "CHANNEL_MANAGER_NEW_CHANNEL"}, {SPINEL_PROP_CHANNEL_MANAGER_DELAY, "CHANNEL_MANAGER_DELAY"}, {SPINEL_PROP_CHANNEL_MANAGER_SUPPORTED_CHANNELS, "CHANNEL_MANAGER_SUPPORTED_CHANNELS"}, {SPINEL_PROP_CHANNEL_MANAGER_FAVORED_CHANNELS, "CHANNEL_MANAGER_FAVORED_CHANNELS"}, {SPINEL_PROP_CHANNEL_MANAGER_CHANNEL_SELECT, "CHANNEL_MANAGER_CHANNEL_SELECT"}, {SPINEL_PROP_CHANNEL_MANAGER_AUTO_SELECT_ENABLED, "CHANNEL_MANAGER_AUTO_SELECT_ENABLED"}, {SPINEL_PROP_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL, "CHANNEL_MANAGER_AUTO_SELECT_INTERVAL"}, {SPINEL_PROP_THREAD_NETWORK_TIME, "THREAD_NETWORK_TIME"}, {SPINEL_PROP_TIME_SYNC_PERIOD, "TIME_SYNC_PERIOD"}, {SPINEL_PROP_TIME_SYNC_XTAL_THRESHOLD, "TIME_SYNC_XTAL_THRESHOLD"}, {SPINEL_PROP_CHILD_SUPERVISION_INTERVAL, "CHILD_SUPERVISION_INTERVAL"}, {SPINEL_PROP_CHILD_SUPERVISION_CHECK_TIMEOUT, "CHILD_SUPERVISION_CHECK_TIMEOUT"}, {SPINEL_PROP_RCP_VERSION, "RCP_VERSION"}, {SPINEL_PROP_RCP_ENH_ACK_PROBING, "ENH_ACK_PROBING"}, {SPINEL_PROP_RCP_CSL_ACCURACY, "CSL_ACCURACY"}, {SPINEL_PROP_RCP_CSL_UNCERTAINTY, "CSL_UNCERTAINTY"}, {SPINEL_PROP_PARENT_RESPONSE_INFO, "PARENT_RESPONSE_INFO"}, {SPINEL_PROP_SLAAC_ENABLED, "SLAAC_ENABLED"}, {SPINEL_PROP_SUPPORTED_RADIO_LINKS, "SUPPORTED_RADIO_LINKS"}, {SPINEL_PROP_NEIGHBOR_TABLE_MULTI_RADIO_INFO, "NEIGHBOR_TABLE_MULTI_RADIO_INFO"}, {SPINEL_PROP_SRP_CLIENT_START, "SRP_CLIENT_START"}, {SPINEL_PROP_SRP_CLIENT_LEASE_INTERVAL, "SRP_CLIENT_LEASE_INTERVAL"}, {SPINEL_PROP_SRP_CLIENT_KEY_LEASE_INTERVAL, "SRP_CLIENT_KEY_LEASE_INTERVAL"}, {SPINEL_PROP_SRP_CLIENT_HOST_INFO, "SRP_CLIENT_HOST_INFO"}, {SPINEL_PROP_SRP_CLIENT_HOST_NAME, "SRP_CLIENT_HOST_NAME"}, {SPINEL_PROP_SRP_CLIENT_HOST_ADDRESSES, "SRP_CLIENT_HOST_ADDRESSES"}, {SPINEL_PROP_SRP_CLIENT_SERVICES, "SRP_CLIENT_SERVICES"}, {SPINEL_PROP_SRP_CLIENT_HOST_SERVICES_REMOVE, "SRP_CLIENT_HOST_SERVICES_REMOVE"}, {SPINEL_PROP_SRP_CLIENT_HOST_SERVICES_CLEAR, "SRP_CLIENT_HOST_SERVICES_CLEAR"}, {SPINEL_PROP_SRP_CLIENT_EVENT, "SRP_CLIENT_EVENT"}, {SPINEL_PROP_SRP_CLIENT_SERVICE_KEY_ENABLED, "SRP_CLIENT_SERVICE_KEY_ENABLED"}, {SPINEL_PROP_SERVER_ALLOW_LOCAL_DATA_CHANGE, "SERVER_ALLOW_LOCAL_DATA_CHANGE"}, {SPINEL_PROP_SERVER_SERVICES, "SERVER_SERVICES"}, {SPINEL_PROP_SERVER_LEADER_SERVICES, "SERVER_LEADER_SERVICES"}, {SPINEL_PROP_RCP_API_VERSION, "RCP_API_VERSION"}, {SPINEL_PROP_UART_BITRATE, "UART_BITRATE"}, {SPINEL_PROP_UART_XON_XOFF, "UART_XON_XOFF"}, {SPINEL_PROP_15_4_PIB_PHY_CHANNELS_SUPPORTED, "15_4_PIB_PHY_CHANNELS_SUPPORTED"}, {SPINEL_PROP_15_4_PIB_MAC_PROMISCUOUS_MODE, "15_4_PIB_MAC_PROMISCUOUS_MODE"}, {SPINEL_PROP_15_4_PIB_MAC_SECURITY_ENABLED, "15_4_PIB_MAC_SECURITY_ENABLED"}, {SPINEL_PROP_CNTR_RESET, "CNTR_RESET"}, {SPINEL_PROP_CNTR_TX_PKT_TOTAL, "CNTR_TX_PKT_TOTAL"}, {SPINEL_PROP_CNTR_TX_PKT_ACK_REQ, "CNTR_TX_PKT_ACK_REQ"}, {SPINEL_PROP_CNTR_TX_PKT_ACKED, "CNTR_TX_PKT_ACKED"}, {SPINEL_PROP_CNTR_TX_PKT_NO_ACK_REQ, "CNTR_TX_PKT_NO_ACK_REQ"}, {SPINEL_PROP_CNTR_TX_PKT_DATA, "CNTR_TX_PKT_DATA"}, {SPINEL_PROP_CNTR_TX_PKT_DATA_POLL, "CNTR_TX_PKT_DATA_POLL"}, {SPINEL_PROP_CNTR_TX_PKT_BEACON, "CNTR_TX_PKT_BEACON"}, {SPINEL_PROP_CNTR_TX_PKT_BEACON_REQ, "CNTR_TX_PKT_BEACON_REQ"}, {SPINEL_PROP_CNTR_TX_PKT_OTHER, "CNTR_TX_PKT_OTHER"}, {SPINEL_PROP_CNTR_TX_PKT_RETRY, "CNTR_TX_PKT_RETRY"}, {SPINEL_PROP_CNTR_TX_ERR_CCA, "CNTR_TX_ERR_CCA"}, {SPINEL_PROP_CNTR_TX_PKT_UNICAST, "CNTR_TX_PKT_UNICAST"}, {SPINEL_PROP_CNTR_TX_PKT_BROADCAST, "CNTR_TX_PKT_BROADCAST"}, {SPINEL_PROP_CNTR_TX_ERR_ABORT, "CNTR_TX_ERR_ABORT"}, {SPINEL_PROP_CNTR_RX_PKT_TOTAL, "CNTR_RX_PKT_TOTAL"}, {SPINEL_PROP_CNTR_RX_PKT_DATA, "CNTR_RX_PKT_DATA"}, {SPINEL_PROP_CNTR_RX_PKT_DATA_POLL, "CNTR_RX_PKT_DATA_POLL"}, {SPINEL_PROP_CNTR_RX_PKT_BEACON, "CNTR_RX_PKT_BEACON"}, {SPINEL_PROP_CNTR_RX_PKT_BEACON_REQ, "CNTR_RX_PKT_BEACON_REQ"}, {SPINEL_PROP_CNTR_RX_PKT_OTHER, "CNTR_RX_PKT_OTHER"}, {SPINEL_PROP_CNTR_RX_PKT_FILT_WL, "CNTR_RX_PKT_FILT_WL"}, {SPINEL_PROP_CNTR_RX_PKT_FILT_DA, "CNTR_RX_PKT_FILT_DA"}, {SPINEL_PROP_CNTR_RX_ERR_EMPTY, "CNTR_RX_ERR_EMPTY"}, {SPINEL_PROP_CNTR_RX_ERR_UKWN_NBR, "CNTR_RX_ERR_UKWN_NBR"}, {SPINEL_PROP_CNTR_RX_ERR_NVLD_SADDR, "CNTR_RX_ERR_NVLD_SADDR"}, {SPINEL_PROP_CNTR_RX_ERR_SECURITY, "CNTR_RX_ERR_SECURITY"}, {SPINEL_PROP_CNTR_RX_ERR_BAD_FCS, "CNTR_RX_ERR_BAD_FCS"}, {SPINEL_PROP_CNTR_RX_ERR_OTHER, "CNTR_RX_ERR_OTHER"}, {SPINEL_PROP_CNTR_RX_PKT_DUP, "CNTR_RX_PKT_DUP"}, {SPINEL_PROP_CNTR_RX_PKT_UNICAST, "CNTR_RX_PKT_UNICAST"}, {SPINEL_PROP_CNTR_RX_PKT_BROADCAST, "CNTR_RX_PKT_BROADCAST"}, {SPINEL_PROP_CNTR_TX_IP_SEC_TOTAL, "CNTR_TX_IP_SEC_TOTAL"}, {SPINEL_PROP_CNTR_TX_IP_INSEC_TOTAL, "CNTR_TX_IP_INSEC_TOTAL"}, {SPINEL_PROP_CNTR_TX_IP_DROPPED, "CNTR_TX_IP_DROPPED"}, {SPINEL_PROP_CNTR_RX_IP_SEC_TOTAL, "CNTR_RX_IP_SEC_TOTAL"}, {SPINEL_PROP_CNTR_RX_IP_INSEC_TOTAL, "CNTR_RX_IP_INSEC_TOTAL"}, {SPINEL_PROP_CNTR_RX_IP_DROPPED, "CNTR_RX_IP_DROPPED"}, {SPINEL_PROP_CNTR_TX_SPINEL_TOTAL, "CNTR_TX_SPINEL_TOTAL"}, {SPINEL_PROP_CNTR_RX_SPINEL_TOTAL, "CNTR_RX_SPINEL_TOTAL"}, {SPINEL_PROP_CNTR_RX_SPINEL_ERR, "CNTR_RX_SPINEL_ERR"}, {SPINEL_PROP_CNTR_RX_SPINEL_OUT_OF_ORDER_TID, "CNTR_RX_SPINEL_OUT_OF_ORDER_TID"}, {SPINEL_PROP_CNTR_IP_TX_SUCCESS, "CNTR_IP_TX_SUCCESS"}, {SPINEL_PROP_CNTR_IP_RX_SUCCESS, "CNTR_IP_RX_SUCCESS"}, {SPINEL_PROP_CNTR_IP_TX_FAILURE, "CNTR_IP_TX_FAILURE"}, {SPINEL_PROP_CNTR_IP_RX_FAILURE, "CNTR_IP_RX_FAILURE"}, {SPINEL_PROP_MSG_BUFFER_COUNTERS, "MSG_BUFFER_COUNTERS"}, {SPINEL_PROP_CNTR_ALL_MAC_COUNTERS, "CNTR_ALL_MAC_COUNTERS"}, {SPINEL_PROP_CNTR_MLE_COUNTERS, "CNTR_MLE_COUNTERS"}, {SPINEL_PROP_CNTR_ALL_IP_COUNTERS, "CNTR_ALL_IP_COUNTERS"}, {SPINEL_PROP_CNTR_MAC_RETRY_HISTOGRAM, "CNTR_MAC_RETRY_HISTOGRAM"}, {SPINEL_PROP_NEST_STREAM_MFG, "NEST_STREAM_MFG"}, {SPINEL_PROP_NEST_LEGACY_ULA_PREFIX, "NEST_LEGACY_ULA_PREFIX"}, {SPINEL_PROP_NEST_LEGACY_LAST_NODE_JOINED, "NEST_LEGACY_LAST_NODE_JOINED"}, {SPINEL_PROP_DEBUG_TEST_ASSERT, "DEBUG_TEST_ASSERT"}, {SPINEL_PROP_DEBUG_NCP_LOG_LEVEL, "DEBUG_NCP_LOG_LEVEL"}, {SPINEL_PROP_DEBUG_TEST_WATCHDOG, "DEBUG_TEST_WATCHDOG"}, {SPINEL_PROP_RCP_MAC_FRAME_COUNTER, "RCP_MAC_FRAME_COUNTER"}, {SPINEL_PROP_RCP_MAC_KEY, "RCP_MAC_KEY"}, {SPINEL_PROP_DEBUG_LOG_TIMESTAMP_BASE, "DEBUG_LOG_TIMESTAMP_BASE"}, {SPINEL_PROP_DEBUG_TREL_TEST_MODE_ENABLE, "DEBUG_TREL_TEST_MODE_ENABLE"}, {0, NULL}, }; return spinel_to_cstr(spinel_prop_cstr, prop_key); } const char *spinel_net_role_to_cstr(uint8_t net_role) { static const struct spinel_cstr spinel_net_cstr[] = { {SPINEL_NET_ROLE_DETACHED, "NET_ROLE_DETACHED"}, {SPINEL_NET_ROLE_CHILD, "NET_ROLE_CHILD"}, {SPINEL_NET_ROLE_ROUTER, "NET_ROLE_ROUTER"}, {SPINEL_NET_ROLE_LEADER, "NET_ROLE_LEADER"}, {0, NULL}, }; return spinel_to_cstr(spinel_net_cstr, net_role); } const char *spinel_mcu_power_state_to_cstr(uint8_t mcu_power_state) { static const struct spinel_cstr spinel_mcu_power_state_cstr[] = { {SPINEL_MCU_POWER_STATE_ON, "MCU_POWER_STATE_ON"}, {SPINEL_MCU_POWER_STATE_LOW_POWER, "MCU_POWER_STATE_LOW_POWER"}, {SPINEL_MCU_POWER_STATE_OFF, "MCU_POWER_STATE_OFF"}, {0, NULL}, }; return spinel_to_cstr(spinel_mcu_power_state_cstr, mcu_power_state); } const char *spinel_status_to_cstr(spinel_status_t status) { static const struct spinel_cstr spinel_status_cstr[] = { {SPINEL_STATUS_OK, "OK"}, {SPINEL_STATUS_FAILURE, "FAILURE"}, {SPINEL_STATUS_UNIMPLEMENTED, "UNIMPLEMENTED"}, {SPINEL_STATUS_INVALID_ARGUMENT, "INVALID_ARGUMENT"}, {SPINEL_STATUS_INVALID_STATE, "INVALID_STATE"}, {SPINEL_STATUS_INVALID_COMMAND, "INVALID_COMMAND"}, {SPINEL_STATUS_INVALID_INTERFACE, "INVALID_INTERFACE"}, {SPINEL_STATUS_INTERNAL_ERROR, "INTERNAL_ERROR"}, {SPINEL_STATUS_SECURITY_ERROR, "SECURITY_ERROR"}, {SPINEL_STATUS_PARSE_ERROR, "PARSE_ERROR"}, {SPINEL_STATUS_IN_PROGRESS, "IN_PROGRESS"}, {SPINEL_STATUS_NOMEM, "NOMEM"}, {SPINEL_STATUS_BUSY, "BUSY"}, {SPINEL_STATUS_PROP_NOT_FOUND, "PROP_NOT_FOUND"}, {SPINEL_STATUS_DROPPED, "DROPPED"}, {SPINEL_STATUS_EMPTY, "EMPTY"}, {SPINEL_STATUS_CMD_TOO_BIG, "CMD_TOO_BIG"}, {SPINEL_STATUS_NO_ACK, "NO_ACK"}, {SPINEL_STATUS_CCA_FAILURE, "CCA_FAILURE"}, {SPINEL_STATUS_ALREADY, "ALREADY"}, {SPINEL_STATUS_ITEM_NOT_FOUND, "ITEM_NOT_FOUND"}, {SPINEL_STATUS_INVALID_COMMAND_FOR_PROP, "INVALID_COMMAND_FOR_PROP"}, {SPINEL_STATUS_RESPONSE_TIMEOUT, "RESPONSE_TIMEOUT"}, {SPINEL_STATUS_JOIN_FAILURE, "JOIN_FAILURE"}, {SPINEL_STATUS_JOIN_SECURITY, "JOIN_SECURITY"}, {SPINEL_STATUS_JOIN_NO_PEERS, "JOIN_NO_PEERS"}, {SPINEL_STATUS_JOIN_INCOMPATIBLE, "JOIN_INCOMPATIBLE"}, {SPINEL_STATUS_JOIN_RSP_TIMEOUT, "JOIN_RSP_TIMEOUT"}, {SPINEL_STATUS_JOIN_SUCCESS, "JOIN_SUCCESS"}, {SPINEL_STATUS_RESET_POWER_ON, "RESET_POWER_ON"}, {SPINEL_STATUS_RESET_EXTERNAL, "RESET_EXTERNAL"}, {SPINEL_STATUS_RESET_SOFTWARE, "RESET_SOFTWARE"}, {SPINEL_STATUS_RESET_FAULT, "RESET_FAULT"}, {SPINEL_STATUS_RESET_CRASH, "RESET_CRASH"}, {SPINEL_STATUS_RESET_ASSERT, "RESET_ASSERT"}, {SPINEL_STATUS_RESET_OTHER, "RESET_OTHER"}, {SPINEL_STATUS_RESET_UNKNOWN, "RESET_UNKNOWN"}, {SPINEL_STATUS_RESET_WATCHDOG, "RESET_WATCHDOG"}, {0, NULL}, }; return spinel_to_cstr(spinel_status_cstr, status); } const char *spinel_capability_to_cstr(spinel_capability_t capability) { static const struct spinel_cstr spinel_cap_cstr[] = { {SPINEL_CAP_LOCK, "LOCK"}, {SPINEL_CAP_NET_SAVE, "NET_SAVE"}, {SPINEL_CAP_HBO, "HBO"}, {SPINEL_CAP_POWER_SAVE, "POWER_SAVE"}, {SPINEL_CAP_COUNTERS, "COUNTERS"}, {SPINEL_CAP_JAM_DETECT, "JAM_DETECT"}, {SPINEL_CAP_PEEK_POKE, "PEEK_POKE"}, {SPINEL_CAP_WRITABLE_RAW_STREAM, "WRITABLE_RAW_STREAM"}, {SPINEL_CAP_GPIO, "GPIO"}, {SPINEL_CAP_TRNG, "TRNG"}, {SPINEL_CAP_CMD_MULTI, "CMD_MULTI"}, {SPINEL_CAP_UNSOL_UPDATE_FILTER, "UNSOL_UPDATE_FILTER"}, {SPINEL_CAP_MCU_POWER_STATE, "MCU_POWER_STATE"}, {SPINEL_CAP_PCAP, "PCAP"}, {SPINEL_CAP_802_15_4_2003, "802_15_4_2003"}, {SPINEL_CAP_802_15_4_2006, "802_15_4_2006"}, {SPINEL_CAP_802_15_4_2011, "802_15_4_2011"}, {SPINEL_CAP_802_15_4_PIB, "802_15_4_PIB"}, {SPINEL_CAP_802_15_4_2450MHZ_OQPSK, "802_15_4_2450MHZ_OQPSK"}, {SPINEL_CAP_802_15_4_915MHZ_OQPSK, "802_15_4_915MHZ_OQPSK"}, {SPINEL_CAP_802_15_4_868MHZ_OQPSK, "802_15_4_868MHZ_OQPSK"}, {SPINEL_CAP_802_15_4_915MHZ_BPSK, "802_15_4_915MHZ_BPSK"}, {SPINEL_CAP_802_15_4_868MHZ_BPSK, "802_15_4_868MHZ_BPSK"}, {SPINEL_CAP_802_15_4_915MHZ_ASK, "802_15_4_915MHZ_ASK"}, {SPINEL_CAP_802_15_4_868MHZ_ASK, "802_15_4_868MHZ_ASK"}, {SPINEL_CAP_CONFIG_FTD, "CONFIG_FTD"}, {SPINEL_CAP_CONFIG_MTD, "CONFIG_MTD"}, {SPINEL_CAP_CONFIG_RADIO, "CONFIG_RADIO"}, {SPINEL_CAP_ROLE_ROUTER, "ROLE_ROUTER"}, {SPINEL_CAP_ROLE_SLEEPY, "ROLE_SLEEPY"}, {SPINEL_CAP_NET_THREAD_1_0, "NET_THREAD_1_0"}, {SPINEL_CAP_NET_THREAD_1_1, "NET_THREAD_1_1"}, {SPINEL_CAP_NET_THREAD_1_2, "NET_THREAD_1_2"}, {SPINEL_CAP_RCP_API_VERSION, "RCP_API_VERSION"}, {SPINEL_CAP_MAC_ALLOWLIST, "MAC_ALLOWLIST"}, {SPINEL_CAP_MAC_RAW, "MAC_RAW"}, {SPINEL_CAP_OOB_STEERING_DATA, "OOB_STEERING_DATA"}, {SPINEL_CAP_CHANNEL_MONITOR, "CHANNEL_MONITOR"}, {SPINEL_CAP_CHANNEL_MANAGER, "CHANNEL_MANAGER"}, {SPINEL_CAP_OPENTHREAD_LOG_METADATA, "OPENTHREAD_LOG_METADATA"}, {SPINEL_CAP_TIME_SYNC, "TIME_SYNC"}, {SPINEL_CAP_CHILD_SUPERVISION, "CHILD_SUPERVISION"}, {SPINEL_CAP_POSIX, "POSIX"}, {SPINEL_CAP_SLAAC, "SLAAC"}, {SPINEL_CAP_RADIO_COEX, "RADIO_COEX"}, {SPINEL_CAP_MAC_RETRY_HISTOGRAM, "MAC_RETRY_HISTOGRAM"}, {SPINEL_CAP_MULTI_RADIO, "MULTI_RADIO"}, {SPINEL_CAP_SRP_CLIENT, "SRP_CLIENT"}, {SPINEL_CAP_DUA, "DUA"}, {SPINEL_CAP_REFERENCE_DEVICE, "REFERENCE_DEVICE"}, {SPINEL_CAP_ERROR_RATE_TRACKING, "ERROR_RATE_TRACKING"}, {SPINEL_CAP_THREAD_COMMISSIONER, "THREAD_COMMISSIONER"}, {SPINEL_CAP_THREAD_TMF_PROXY, "THREAD_TMF_PROXY"}, {SPINEL_CAP_THREAD_UDP_FORWARD, "THREAD_UDP_FORWARD"}, {SPINEL_CAP_THREAD_JOINER, "THREAD_JOINER"}, {SPINEL_CAP_THREAD_BORDER_ROUTER, "THREAD_BORDER_ROUTER"}, {SPINEL_CAP_THREAD_SERVICE, "THREAD_SERVICE"}, {SPINEL_CAP_THREAD_CSL_RECEIVER, "THREAD_CSL_RECEIVER"}, {SPINEL_CAP_THREAD_BACKBONE_ROUTER, "THREAD_BACKBONE_ROUTER"}, {SPINEL_CAP_NEST_LEGACY_INTERFACE, "NEST_LEGACY_INTERFACE"}, {SPINEL_CAP_NEST_LEGACY_NET_WAKE, "NEST_LEGACY_NET_WAKE"}, {SPINEL_CAP_NEST_TRANSMIT_HOOK, "NEST_TRANSMIT_HOOK"}, {0, NULL}, }; return spinel_to_cstr(spinel_cap_cstr, capability); } // LCOV_EXCL_STOP /* -------------------------------------------------------------------------- */ #if SPINEL_SELF_TEST int main(void) { int ret = -1; const spinel_eui64_t static_eui64 = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}}; const char static_string[] = "static_string"; uint8_t buffer[1024]; ssize_t len; len = spinel_datatype_pack(buffer, sizeof(buffer), "CiiLUE", 0x88, 9, 0xA3, 0xDEADBEEF, static_string, &static_eui64); if (len != 30) { printf("error:%d: len != 30; (%d)\n", __LINE__, (int)len); goto bail; } { const char *str = NULL; // Length ends right before the string. len = spinel_datatype_unpack(buffer, 8, "CiiLU", NULL, NULL, NULL, NULL, &str); if (len != -1) { printf("error:%d: len != -1; (%d)\n", __LINE__, (int)len); goto bail; } if (str != NULL) { printf("error:%d: str != NULL\n", __LINE__); goto bail; } } len = 30; { uint8_t c = 0; unsigned int i1 = 0; unsigned int i2 = 0; uint32_t l = 0; const char * str = NULL; const spinel_eui64_t *eui64 = NULL; len = spinel_datatype_unpack(buffer, (spinel_size_t)len, "CiiLUE", &c, &i1, &i2, &l, &str, &eui64); if (len != 30) { printf("error:%d: len != 30; (%d)\n", __LINE__, (int)len); goto bail; } if (c != 0x88) { printf("error: x != 0x88; (%d)\n", c); goto bail; } if (i1 != 9) { printf("error: i1 != 9; (%d)\n", i1); goto bail; } if (i2 != 0xA3) { printf("error: i2 != 0xA3; (0x%02X)\n", i2); goto bail; } if (l != 0xDEADBEEF) { printf("error: l != 0xDEADBEEF; (0x%08X)\n", (unsigned int)l); goto bail; } if (strcmp(str, static_string) != 0) { printf("error:%d: strcmp(str,static_string) != 0\n", __LINE__); goto bail; } if (memcmp(eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0) { printf("error:%d: memcmp(eui64, &eui64, sizeof(spinel_eui64_t)) != 0\n", __LINE__); goto bail; } } { uint8_t c = 0; unsigned int i1 = 0; unsigned int i2 = 0; uint32_t l = 0; char str[sizeof(static_string)]; spinel_eui64_t eui64 = {{0}}; len = spinel_datatype_unpack_in_place(buffer, (spinel_size_t)len, "CiiLUE", &c, &i1, &i2, &l, &str, sizeof(str), &eui64); if (len != 30) { printf("error:%d: len != 30; (%d)\n", __LINE__, (int)len); goto bail; } if (c != 0x88) { printf("error: x != 0x88; (%d)\n", c); goto bail; } if (i1 != 9) { printf("error: i1 != 9; (%d)\n", i1); goto bail; } if (i2 != 0xA3) { printf("error: i2 != 0xA3; (0x%02X)\n", i2); goto bail; } if (l != 0xDEADBEEF) { printf("error: l != 0xDEADBEEF; (0x%08X)\n", (unsigned int)l); goto bail; } if (strcmp(str, static_string) != 0) { printf("error:%d: strcmp(str,static_string) != 0\n", __LINE__); goto bail; } if (memcmp(&eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0) { printf("error:%d: memcmp(&eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0\n", __LINE__); goto bail; } } // ----------------------------------- memset(buffer, 0xAA, sizeof(buffer)); len = spinel_datatype_pack(buffer, sizeof(buffer), "Cit(iL)UE", 0x88, 9, 0xA3, 0xDEADBEEF, static_string, &static_eui64); if (len != 32) { printf("error:%d: len != 32; (%d)\n", __LINE__, (int)len); goto bail; } { uint8_t c = 0; unsigned int i1 = 0; unsigned int i2 = 0; uint32_t l = 0; const char * str = NULL; spinel_eui64_t *eui64 = NULL; len = spinel_datatype_unpack(buffer, (spinel_size_t)len, "Cit(iL)UE", &c, &i1, &i2, &l, &str, &eui64); if (len != 32) { printf("error:%d: len != 24; (%d)\n", __LINE__, (int)len); goto bail; } if (c != 0x88) { printf("error: x != 0x88; (%d)\n", c); goto bail; } if (i1 != 9) { printf("error: i1 != 9; (%d)\n", i1); goto bail; } if (i2 != 0xA3) { printf("error: i2 != 0xA3; (0x%02X)\n", i2); goto bail; } if (l != 0xDEADBEEF) { printf("error: l != 0xDEADBEEF; (0x%08X)\n", (unsigned int)l); goto bail; } if (strcmp(str, static_string) != 0) { printf("error:%d: strcmp(str,static_string) != 0\n", __LINE__); goto bail; } if (memcmp(eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0) { printf("error:%d: memcmp(eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0\n", __LINE__); goto bail; } } { uint8_t c = 0; unsigned int i1 = 0; unsigned int i2 = 0; uint32_t l = 0; char str[sizeof(static_string)]; spinel_eui64_t eui64 = {{0}}; len = spinel_datatype_unpack_in_place(buffer, (spinel_size_t)len, "Cit(iL)UE", &c, &i1, &i2, &l, &str, sizeof(str), &eui64); if (len != 32) { printf("error:%d: len != 24; (%d)\n", __LINE__, (int)len); goto bail; } if (c != 0x88) { printf("error: x != 0x88; (%d)\n", c); goto bail; } if (i1 != 9) { printf("error: i1 != 9; (%d)\n", i1); goto bail; } if (i2 != 0xA3) { printf("error: i2 != 0xA3; (0x%02X)\n", i2); goto bail; } if (l != 0xDEADBEEF) { printf("error: l != 0xDEADBEEF; (0x%08X)\n", (unsigned int)l); goto bail; } if (strcmp(str, static_string) != 0) { printf("error:%d: strcmp(str,static_string) != 0\n", __LINE__); goto bail; } if (memcmp(&eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0) { printf("error:%d: memcmp(&eui64, &static_eui64, sizeof(spinel_eui64_t)) != 0\n", __LINE__); goto bail; } } { // Test UTF8 validation - Good/Valid strings // Single symbols const uint8_t single1[] = {0}; // 0000 const uint8_t single2[] = {0x7F, 0x00}; // 007F const uint8_t single3[] = {0xC2, 0x80, 0x00}; // 080 const uint8_t single4[] = {0xDF, 0xBF, 0x00}; // 07FF const uint8_t single5[] = {0xE0, 0xA0, 0x80, 0x00}; // 0800 const uint8_t single6[] = {0xEF, 0xBF, 0xBF, 0x00}; // FFFF const uint8_t single7[] = {0xF0, 0x90, 0x80, 0x80, 0x00}; // 010000 const uint8_t single8[] = {0xF4, 0x8F, 0xBF, 0xBF, 0x00}; // 10FFFF // Strings const uint8_t str1[] = "spinel"; const uint8_t str2[] = "OpenThread"; const uint8_t str3[] = {0x41, 0x7F, 0xEF, 0xBF, 0xBF, 0xC2, 0x80, 0x21, 0x33, 0x00}; const uint8_t str4[] = {0xCE, 0xBA, 0xE1, 0xBD, 0xB9, 0xCF, 0x83, 0xCE, 0xBC, 0xCE, 0xB5, 0x00}; // κόσμε const uint8_t str5[] = {0x3D, 0xF4, 0x8F, 0xBF, 0xBF, 0x01, 0xE0, 0xA0, 0x83, 0x22, 0xEF, 0xBF, 0xBF, 0x00}; const uint8_t str6[] = {0xE5, 0xA2, 0x82, 0xE0, 0xA0, 0x80, 0xC2, 0x83, 0xC2, 0x80, 0xF4, 0x8F, 0xBF, 0xBF, 0xF4, 0x8F, 0xBF, 0xBF, 0xDF, 0xBF, 0x21, 0x00}; const uint8_t * good_strings[] = {single1, single2, single3, single4, single5, single6, single7, single8, str1, str2, str3, str4, str5, str6, NULL}; const uint8_t **str_ptr; for (str_ptr = &good_strings[0]; *str_ptr != NULL; str_ptr++) { if (!spinel_validate_utf8(*str_ptr)) { printf("error: spinel_validate_utf8() did not correctly detect a valid UTF8 sequence!\n"); goto bail; } } } { // Test UTF8 validation - Bad/Invalid strings // Single symbols (invalid) const uint8_t single1[] = {0xF8, 0x00}; const uint8_t single2[] = {0xF9, 0x00}; const uint8_t single3[] = {0xFA, 0x00}; const uint8_t single4[] = {0xFF, 0x00}; // Bad continuations const uint8_t bad1[] = {0xDF, 0x0F, 0x00}; const uint8_t bad2[] = {0xE0, 0xA0, 0x10, 0x00}; const uint8_t bad3[] = {0xF0, 0x90, 0x80, 0x60, 0x00}; const uint8_t bad4[] = {0xF4, 0x8F, 0xBF, 0x0F, 0x00}; const uint8_t bad5[] = {0x21, 0xA0, 0x00}; const uint8_t bad6[] = {0xCE, 0xBA, 0xE1, 0xBD, 0xB9, 0xCF, 0x83, 0xCE, 0xBC, 0xCE, 0x00}; const uint8_t * bad_strings[] = {single1, single2, single3, single4, bad1, bad2, bad3, bad4, bad5, bad6, NULL}; const uint8_t **str_ptr; for (str_ptr = &bad_strings[0]; *str_ptr != NULL; str_ptr++) { if (spinel_validate_utf8(*str_ptr)) { printf("error: spinel_validate_utf8() did not correctly detect an invalid UTF8 sequence\n"); goto bail; } } } printf("OK\n"); ret = 0; return ret; bail: printf("FAILURE\n"); return ret; } #endif // #if SPINEL_SELF_TEST <|start_filename|>src/core/border_router/router_advertisement.cpp<|end_filename|> /* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file includes implementations for ICMPv6 Router Advertisement. * */ #include "border_router/router_advertisement.hpp" #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE #include "common/as_core_type.hpp" #include "common/code_utils.hpp" namespace ot { namespace BorderRouter { namespace RouterAdv { const Option *Option::GetNextOption(const Option *aCurOption, const uint8_t *aBuffer, uint16_t aBufferLength) { const uint8_t *nextOption = nullptr; const uint8_t *bufferEnd = aBuffer + aBufferLength; VerifyOrExit(aBuffer != nullptr, nextOption = nullptr); if (aCurOption == nullptr) { nextOption = aBuffer; } else { nextOption = reinterpret_cast<const uint8_t *>(aCurOption) + aCurOption->GetSize(); } VerifyOrExit(nextOption + sizeof(Option) <= bufferEnd, nextOption = nullptr); VerifyOrExit(reinterpret_cast<const Option *>(nextOption)->GetSize() > 0, nextOption = nullptr); VerifyOrExit(nextOption + reinterpret_cast<const Option *>(nextOption)->GetSize() <= bufferEnd, nextOption = nullptr); exit: return reinterpret_cast<const Option *>(nextOption); } //---------------------------------------------------------------------------------------------------------------------- // PrefixInfoOption void PrefixInfoOption::Init(void) { Clear(); SetType(Type::kPrefixInfo); SetSize(sizeof(PrefixInfoOption)); OT_UNUSED_VARIABLE(mReserved2); } void PrefixInfoOption::SetPrefix(const Ip6::Prefix &aPrefix) { mPrefixLength = aPrefix.mLength; mPrefix = AsCoreType(&aPrefix.mPrefix); } void PrefixInfoOption::GetPrefix(Ip6::Prefix &aPrefix) const { aPrefix.Set(mPrefix.GetBytes(), mPrefixLength); } bool PrefixInfoOption::IsValid(void) const { return (GetSize() >= sizeof(*this)) && (mPrefixLength <= Ip6::Prefix::kMaxLength) && (GetPreferredLifetime() <= GetValidLifetime()); } //---------------------------------------------------------------------------------------------------------------------- // RouteInfoOption void RouteInfoOption::Init(void) { Clear(); SetType(Type::kRouteInfo); } void RouteInfoOption::SetPreference(RoutePreference aPreference) { mResvdPrf &= ~kPreferenceMask; mResvdPrf |= (NetworkData::RoutePreferenceToValue(aPreference) << kPreferenceOffset) & kPreferenceMask; } RoutePreference RouteInfoOption::GetPreference(void) const { return NetworkData::RoutePreferenceFromValue((mResvdPrf & kPreferenceMask) >> kPreferenceOffset); } void RouteInfoOption::SetPrefix(const Ip6::Prefix &aPrefix) { SetLength(OptionLengthForPrefix(aPrefix.mLength)); mPrefixLength = aPrefix.mLength; memcpy(GetPrefixBytes(), aPrefix.GetBytes(), aPrefix.GetBytesSize()); } void RouteInfoOption::GetPrefix(Ip6::Prefix &aPrefix) const { aPrefix.Set(GetPrefixBytes(), mPrefixLength); } bool RouteInfoOption::IsValid(void) const { return (GetSize() >= kMinSize) && (mPrefixLength <= Ip6::Prefix::kMaxLength) && (GetLength() >= OptionLengthForPrefix(mPrefixLength)) && NetworkData::IsRoutePreferenceValid(GetPreference()); } uint8_t RouteInfoOption::OptionLengthForPrefix(uint8_t aPrefixLength) { static constexpr uint8_t kMaxPrefixLenForOptionLen1 = 0; static constexpr uint8_t kMaxPrefixLenForOptionLen2 = 64; uint8_t length; // The Option Length can be 1, 2, or 3 depending on the prefix // length // // - 1 when prefix len is zero. // - 2 when prefix len is less then or equal to 64. // - 3 otherwise. if (aPrefixLength == kMaxPrefixLenForOptionLen1) { length = 1; } else if (aPrefixLength <= kMaxPrefixLenForOptionLen2) { length = 2; } else { length = 3; } return length; } //---------------------------------------------------------------------------------------------------------------------- // RouterAdvMessage void RouterAdvMessage::SetToDefault(void) { OT_UNUSED_VARIABLE(mCode); OT_UNUSED_VARIABLE(mCurHopLimit); OT_UNUSED_VARIABLE(mReachableTime); OT_UNUSED_VARIABLE(mRetransTimer); Clear(); mType = Ip6::Icmp::Header::kTypeRouterAdvert; } RoutePreference RouterAdvMessage::GetDefaultRouterPreference(void) const { return NetworkData::RoutePreferenceFromValue((mFlags & kPreferenceMask) >> kPreferenceOffset); } void RouterAdvMessage::SetDefaultRouterPreference(RoutePreference aPreference) { mFlags &= ~kPreferenceMask; mFlags |= (NetworkData::RoutePreferenceToValue(aPreference) << kPreferenceOffset) & kPreferenceMask; } //---------------------------------------------------------------------------------------------------------------------- // RouterAdvMessage RouterSolicitMessage::RouterSolicitMessage(void) { mHeader.Clear(); mHeader.SetType(Ip6::Icmp::Header::kTypeRouterSolicit); } } // namespace RouterAdv } // namespace BorderRouter } // namespace ot #endif // OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE <|start_filename|>src/core/border_router/infra_if.hpp<|end_filename|> /* * Copyright (c) 2022, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file includes definitions for infrastructure network interface. * */ #ifndef INFRA_IF_HPP_ #define INFRA_IF_HPP_ #include "openthread-core-config.h" #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE #include <openthread/platform/infra_if.h> #include "common/data.hpp" #include "common/error.hpp" #include "common/locator.hpp" #include "common/string.hpp" #include "net/ip6.hpp" namespace ot { namespace BorderRouter { /** * This class represents the infrastructure network interface on a border router. * */ class InfraIf : public InstanceLocator { public: static constexpr uint16_t kInfoStringSize = 20; ///< Max chars for the info string (`ToString()`). typedef String<kInfoStringSize> InfoString; ///< String type returned from `ToString()`. typedef Data<kWithUint16Length> Icmp6Packet; ///< An IMCPv6 packet (data containing the IP payload) /** * This constructor initializes the `InfraIf`. * * @param[in] aInstance A OpenThread instance. * */ explicit InfraIf(Instance &aInstance); /** * This method initializes the `InfraIf`. * * @param[in] aIfIndex The infrastructure interface index. * * @retval kErrorNone Successfully initialized the `InfraIf`. * @retval kErrorInvalidArgs The index of the infra interface is not valid. * @retval kErrorInvalidState The `InfraIf` is already initialized. * */ Error Init(uint32_t aIfIndex); /** * This method deinitilaizes the `InfraIf`. * */ void Deinit(void); /** * This method indicates whether or not the `InfraIf` is initialized. * * @retval TRUE The `InfraIf` is initialized. * @retval FALSE The `InfraIf` is not initialized. * */ bool IsInitialized(void) const { return mInitialized; } /** * This method indicates whether or not the infra interface is running. * * @retval TRUE The infrastructure interface is running. * @retval FALSE The infrastructure interface is not running. * */ bool IsRunning(void) const { return mIsRunning; } /** * This method returns the infrastructure interface index. * * @returns The interface index or zero if not initialized. * */ uint32_t GetIfIndex(void) const { return mIfIndex; } /** * This method indicates whether or not the infra interface has the given IPv6 address assigned. * * This method MUST be used when interface is initialized. * * @param[in] aAddress The IPv6 address. * * @retval TRUE The infrastructure interface has @p aAddress. * @retval FALSE The infrastructure interface does not have @p aAddress. * */ bool HasAddress(const Ip6::Address &aAddress); /** * This method sends an ICMPv6 Neighbor Discovery packet on the infrastructure interface. * * This method MUST be used when interface is initialized. * * @param[in] aPacket The ICMPv6 packet to send. * @param[in] aDestination The destination address. * * @retval kErrorNone Successfully sent the ICMPv6 message. * @retval kErrorFailed Failed to send the ICMPv6 message. * */ Error Send(const Icmp6Packet &aPacket, const Ip6::Address &aDestination); /** * This method processes a received ICMPv6 Neighbor Discovery packet from an infrastructure interface. * * @param[in] aIfIndex The infrastructure interface index on which the ICMPv6 message is received. * @param[in] aSource The IPv6 source address. * @param[in] aPacket The ICMPv6 packet. * */ void HandledReceived(uint32_t aIfIndex, const Ip6::Address &aSource, const Icmp6Packet &aPacket); /** * This method handles infrastructure interface state changes. * * @param[in] aIfIndex The infrastructure interface index. * @param[in] aIsRunning A boolean that indicates whether the infrastructure interface is running. * * @retval kErrorNone Successfully updated the infra interface status. * @retval kErrorInvalidState The `InfraIf` is not initialized. * @retval kErrorInvalidArgs The @p IfIndex does not match the interface index of `InfraIf`. * */ Error HandleStateChanged(uint32_t aIfIndex, bool aIsRunning); /** * This method converts the `InfraIf` to a human-readable string. * * @returns The string representation of `InfraIf`. * */ InfoString ToString(void) const; private: bool mInitialized : 1; bool mIsRunning : 1; uint32_t mIfIndex; }; } // namespace BorderRouter } // namespace ot #endif // OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE #endif // INFRA_IF_HPP_ <|start_filename|>src/core/border_router/infra_if.cpp<|end_filename|> /* * Copyright (c) 2022, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file implements infrastructure network interface. */ #include "infra_if.hpp" #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE #include "border_router/routing_manager.hpp" #include "common/as_core_type.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/logging.hpp" #include "net/icmp6.hpp" namespace ot { namespace BorderRouter { RegisterLogModule("InfraIf"); InfraIf::InfraIf(Instance &aInstance) : InstanceLocator(aInstance) , mInitialized(false) , mIsRunning(false) , mIfIndex(0) { } Error InfraIf::Init(uint32_t aIfIndex) { Error error = kErrorNone; VerifyOrExit(!mInitialized, error = kErrorInvalidState); VerifyOrExit(aIfIndex > 0, error = kErrorInvalidArgs); mIfIndex = aIfIndex; mInitialized = true; LogInfo("Init %s", ToString().AsCString()); exit: return error; } void InfraIf::Deinit(void) { mInitialized = false; mIsRunning = false; mIfIndex = 0; LogInfo("Deinit"); } bool InfraIf::HasAddress(const Ip6::Address &aAddress) { OT_ASSERT(mInitialized); return otPlatInfraIfHasAddress(mIfIndex, &aAddress); } Error InfraIf::Send(const Icmp6Packet &aPacket, const Ip6::Address &aDestination) { OT_ASSERT(mInitialized); return otPlatInfraIfSendIcmp6Nd(mIfIndex, &aDestination, aPacket.GetBytes(), aPacket.GetLength()); } void InfraIf::HandledReceived(uint32_t aIfIndex, const Ip6::Address &aSource, const Icmp6Packet &aPacket) { Error error = kErrorNone; VerifyOrExit(mInitialized && mIsRunning, error = kErrorInvalidState); VerifyOrExit(aIfIndex == mIfIndex, error = kErrorDrop); VerifyOrExit(aPacket.GetBytes() != nullptr, error = kErrorInvalidArgs); VerifyOrExit(aPacket.GetLength() >= sizeof(Ip6::Icmp::Header), error = kErrorParse); Get<RoutingManager>().HandleReceived(aPacket, aSource); exit: if (error != kErrorNone) { LogDebg("Dropped ICMPv6 message: %s", ErrorToString(error)); } } Error InfraIf::HandleStateChanged(uint32_t aIfIndex, bool aIsRunning) { Error error = kErrorNone; VerifyOrExit(mInitialized, error = kErrorInvalidState); VerifyOrExit(aIfIndex == mIfIndex, error = kErrorInvalidArgs); VerifyOrExit(aIsRunning != mIsRunning); LogInfo("State changed: %sRUNNING -> %sRUNNING", mIsRunning ? "" : "NOT ", aIsRunning ? "" : "NOT "); mIsRunning = aIsRunning; Get<RoutingManager>().HandleInfraIfStateChanged(); exit: return error; } InfraIf::InfoString InfraIf::ToString(void) const { InfoString string; string.Append("infra netif %u", mIfIndex); return string; } //--------------------------------------------------------------------------------------------------------------------- extern "C" void otPlatInfraIfRecvIcmp6Nd(otInstance * aInstance, uint32_t aInfraIfIndex, const otIp6Address *aSrcAddress, const uint8_t * aBuffer, uint16_t aBufferLength) { InfraIf::Icmp6Packet packet; packet.Init(aBuffer, aBufferLength); AsCoreType(aInstance).Get<InfraIf>().HandledReceived(aInfraIfIndex, AsCoreType(aSrcAddress), packet); } extern "C" otError otPlatInfraIfStateChanged(otInstance *aInstance, uint32_t aInfraIfIndex, bool aIsRunning) { return AsCoreType(aInstance).Get<InfraIf>().HandleStateChanged(aInfraIfIndex, aIsRunning); } } // namespace BorderRouter } // namespace ot #endif // OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE <|start_filename|>src/core/thread/panid_query_server.cpp<|end_filename|> /* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * This file implements the PAN ID Query Server. */ #include "panid_query_server.hpp" #include "coap/coap_message.hpp" #include "common/as_core_type.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/uri_paths.hpp" namespace ot { RegisterLogModule("MeshCoP"); PanIdQueryServer::PanIdQueryServer(Instance &aInstance) : InstanceLocator(aInstance) , mChannelMask(0) , mPanId(Mac::kPanIdBroadcast) , mTimer(aInstance, PanIdQueryServer::HandleTimer) , mPanIdQuery(UriPath::kPanIdQuery, &PanIdQueryServer::HandleQuery, this) { Get<Tmf::Agent>().AddResource(mPanIdQuery); } void PanIdQueryServer::HandleQuery(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<PanIdQueryServer *>(aContext)->HandleQuery(AsCoapMessage(aMessage), AsCoreType(aMessageInfo)); } void PanIdQueryServer::HandleQuery(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { uint16_t panId; Ip6::MessageInfo responseInfo(aMessageInfo); uint32_t mask; VerifyOrExit(aMessage.IsPostRequest()); VerifyOrExit((mask = MeshCoP::ChannelMaskTlv::GetChannelMask(aMessage)) != 0); SuccessOrExit(Tlv::Find<MeshCoP::PanIdTlv>(aMessage, panId)); mChannelMask = mask; mCommissioner = aMessageInfo.GetPeerAddr(); mPanId = panId; mTimer.Start(kScanDelay); if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { SuccessOrExit(Get<Tmf::Agent>().SendEmptyAck(aMessage, responseInfo)); LogInfo("sent panid query response"); } exit: return; } void PanIdQueryServer::HandleScanResult(Mac::ActiveScanResult *aScanResult, void *aContext) { static_cast<PanIdQueryServer *>(aContext)->HandleScanResult(aScanResult); } void PanIdQueryServer::HandleScanResult(Mac::ActiveScanResult *aScanResult) { if (aScanResult != nullptr) { if (aScanResult->mPanId == mPanId) { mChannelMask |= 1 << aScanResult->mChannel; } } else if (mChannelMask != 0) { SendConflict(); } } void PanIdQueryServer::SendConflict(void) { Error error = kErrorNone; MeshCoP::ChannelMaskTlv channelMask; Tmf::MessageInfo messageInfo(GetInstance()); Coap::Message * message; message = Get<Tmf::Agent>().NewPriorityConfirmablePostMessage(UriPath::kPanIdConflict); VerifyOrExit(message != nullptr, error = kErrorNoBufs); channelMask.Init(); channelMask.SetChannelMask(mChannelMask); SuccessOrExit(error = channelMask.AppendTo(*message)); SuccessOrExit(error = Tlv::Append<MeshCoP::PanIdTlv>(*message, mPanId)); messageInfo.SetSockAddrToRlocPeerAddrTo(mCommissioner); SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo)); LogInfo("sent panid conflict"); exit: FreeMessageOnError(message, error); MeshCoP::LogError("send panid conflict", error); } void PanIdQueryServer::HandleTimer(Timer &aTimer) { aTimer.Get<PanIdQueryServer>().HandleTimer(); } void PanIdQueryServer::HandleTimer(void) { IgnoreError(Get<Mac::Mac>().ActiveScan(mChannelMask, 0, HandleScanResult, this)); mChannelMask = 0; } } // namespace ot <|start_filename|>examples/platforms/simulation/system.c<|end_filename|> /* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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. */ /** * @file * @brief * This file includes the platform-specific initializers. */ #include "platform-simulation.h" #if OPENTHREAD_SIMULATION_VIRTUAL_TIME == 0 #include <assert.h> #include <errno.h> #include <getopt.h> #include <libgen.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <syslog.h> #include <openthread/tasklet.h> #include <openthread/platform/alarm-milli.h> #include <openthread/platform/radio.h> uint32_t gNodeId = 1; extern bool gPlatformPseudoResetWasRequested; extern otRadioCaps gRadioCaps; static volatile bool gTerminate = false; static void handleSignal(int aSignal) { OT_UNUSED_VARIABLE(aSignal); gTerminate = true; } /** * This enumeration defines the argument return values. * */ enum { OT_SIM_OPT_HELP = 'h', OT_SIM_OPT_ENABLE_ENERGY_SCAN = 'E', OT_SIM_OPT_SLEEP_TO_TX = 't', OT_SIM_OPT_TIME_SPEED = 's', OT_SIM_OPT_UNKNOWN = '?', }; static void PrintUsage(const char *aProgramName, int aExitCode) { fprintf(stderr, "Syntax:\n" " %s [Options] NodeId\n" "Options:\n" " -h --help Display this usage information.\n" " -E --enable-energy-scan Enable energy scan capability.\n" " -t --sleep-to-tx Let radio support direct transition from sleep to TX with CSMA.\n" " -s --time-speed=val Speed up the time in simulation.\n", aProgramName); exit(aExitCode); } void otSysInit(int aArgCount, char *aArgVector[]) { char * endptr; uint32_t speedUpFactor = 1; static const struct option long_options[] = { {"help", no_argument, 0, OT_SIM_OPT_HELP}, {"enable-energy-scan", no_argument, 0, OT_SIM_OPT_SLEEP_TO_TX}, {"sleep-to-tx", no_argument, 0, OT_SIM_OPT_SLEEP_TO_TX}, {"time-speed", required_argument, 0, OT_SIM_OPT_TIME_SPEED}, {0, 0, 0, 0}, }; if (gPlatformPseudoResetWasRequested) { gPlatformPseudoResetWasRequested = false; return; } optind = 1; while (true) { int c = getopt_long(aArgCount, aArgVector, "Ehts:", long_options, NULL); if (c == -1) { break; } switch (c) { case OT_SIM_OPT_UNKNOWN: PrintUsage(aArgVector[0], EXIT_FAILURE); break; case OT_SIM_OPT_HELP: PrintUsage(aArgVector[0], EXIT_SUCCESS); break; case OT_SIM_OPT_ENABLE_ENERGY_SCAN: gRadioCaps |= OT_RADIO_CAPS_ENERGY_SCAN; break; case OT_SIM_OPT_SLEEP_TO_TX: gRadioCaps |= OT_RADIO_CAPS_SLEEP_TO_TX; break; case OT_SIM_OPT_TIME_SPEED: speedUpFactor = (uint32_t)strtol(optarg, &endptr, 10); if (*endptr != '\0' || speedUpFactor == 0) { fprintf(stderr, "Invalid value for TimerSpeedUpFactor: %s\n", optarg); exit(EXIT_FAILURE); } break; default: break; } } if (optind != aArgCount - 1) { PrintUsage(aArgVector[0], EXIT_FAILURE); } gNodeId = (uint32_t)strtol(aArgVector[optind], &endptr, 0); if (*endptr != '\0' || gNodeId < 1 || gNodeId > MAX_NETWORK_SIZE) { fprintf(stderr, "Invalid NodeId: %s\n", aArgVector[optind]); exit(EXIT_FAILURE); } openlog(basename(aArgVector[0]), LOG_PID, LOG_USER); setlogmask(setlogmask(0) & LOG_UPTO(LOG_NOTICE)); signal(SIGTERM, &handleSignal); signal(SIGHUP, &handleSignal); platformAlarmInit(speedUpFactor); platformRadioInit(); #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE platformTrelInit(speedUpFactor); #endif platformRandomInit(); } bool otSysPseudoResetWasRequested(void) { return gPlatformPseudoResetWasRequested; } void otSysDeinit(void) { platformRadioDeinit(); #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE platformTrelDeinit(); #endif } void otSysProcessDrivers(otInstance *aInstance) { fd_set read_fds; fd_set write_fds; fd_set error_fds; int max_fd = -1; struct timeval timeout; int rval; FD_ZERO(&read_fds); FD_ZERO(&write_fds); FD_ZERO(&error_fds); platformUartUpdateFdSet(&read_fds, &write_fds, &error_fds, &max_fd); platformAlarmUpdateTimeout(&timeout); platformRadioUpdateFdSet(&read_fds, &write_fds, &timeout, &max_fd); #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE platformTrelUpdateFdSet(&read_fds, &write_fds, &timeout, &max_fd); #endif if (otTaskletsArePending(aInstance)) { timeout.tv_sec = 0; timeout.tv_usec = 0; } rval = select(max_fd + 1, &read_fds, &write_fds, &error_fds, &timeout); if (rval >= 0) { platformUartProcess(); platformRadioProcess(aInstance, &read_fds, &write_fds); } else if (errno != EINTR) { perror("select"); exit(EXIT_FAILURE); } platformAlarmProcess(aInstance); #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE platformTrelProcess(aInstance, &read_fds, &write_fds); #endif if (gTerminate) { exit(0); } } #endif // OPENTHREAD_SIMULATION_VIRTUAL_TIME == 0
sarah-iot/openthread
<|start_filename|>Projects/iOS < 6/PSUpdateApp/MainViewController.h<|end_filename|> // // MainViewController.h // PSUpdateApp // // Created by iBo on 18/02/13. // Copyright (c) 2013 D-Still. All rights reserved. // #import <UIKit/UIKit.h> @interface MainViewController : UIViewController @end <|start_filename|>Projects/iOS > 6/PSUpdateApp/AppDelegate.h<|end_filename|> // // AppDelegate.h // PSUpdateApp // // Created by iBo on 9/13/13. // Copyright (c) 2013 iBo. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end <|start_filename|>Projects/iOS < 6/PSUpdateAppTests/PSUpdateAppTests.h<|end_filename|> // // PSUpdateAppTests.h // PSUpdateAppTests // // Created by iBo on 19/02/13. // Copyright (c) 2013 D-Still. All rights reserved. // #import <SenTestingKit/SenTestingKit.h> @interface PSUpdateAppTests : SenTestCase @end <|start_filename|>PSUpdateApp/CWLSynthesizeSingleton.h<|end_filename|> // // CWLSynthesizeSingleton.h // CocoaWithLove // // Created by <NAME> on 2011/08/23. // Copyright (c) 2011 <NAME>. All rights reserved. // // Permission is given to use this source code file, free of charge, in any // project, commercial or otherwise, entirely at your risk, with the condition // that any redistribution (in part or whole) of source code must retain // this copyright and permission notice. Attribution in compiled projects is // appreciated but not required. // #import <objc/runtime.h> #define CWL_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, accessorMethodName) \ + (classname *)accessorMethodName; #if __has_feature(objc_arc) #define CWL_SYNTHESIZE_SINGLETON_RETAIN_METHODS #else #define CWL_SYNTHESIZE_SINGLETON_RETAIN_METHODS \ - (id)retain \ { \ return self; \ } \ \ - (NSUInteger)retainCount \ { \ return NSUIntegerMax; \ } \ \ - (oneway void)release \ { \ } \ \ - (id)autorelease \ { \ return self; \ } #endif #define CWL_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, accessorMethodName) \ \ static classname *accessorMethodName##Instance = nil; \ \ + (classname *)accessorMethodName \ { \ @synchronized(self) \ { \ if (accessorMethodName##Instance == nil) \ { \ accessorMethodName##Instance = [super allocWithZone:NULL]; \ accessorMethodName##Instance = [accessorMethodName##Instance init]; \ method_exchangeImplementations(\ class_getClassMethod([accessorMethodName##Instance class], @selector(accessorMethodName)),\ class_getClassMethod([accessorMethodName##Instance class], @selector(cwl_lockless_##accessorMethodName)));\ method_exchangeImplementations(\ class_getInstanceMethod([accessorMethodName##Instance class], @selector(init)),\ class_getInstanceMethod([accessorMethodName##Instance class], @selector(cwl_onlyInitOnce)));\ } \ } \ \ return accessorMethodName##Instance; \ } \ \ + (classname *)cwl_lockless_##accessorMethodName \ { \ return accessorMethodName##Instance; \ } \ \ + (id)allocWithZone:(NSZone *)zone \ { \ return [self accessorMethodName]; \ } \ \ - (id)copyWithZone:(NSZone *)zone \ { \ return self; \ } \ - (id)cwl_onlyInitOnce \ { \ return self;\ } \ \ CWL_SYNTHESIZE_SINGLETON_RETAIN_METHODS #define CWL_DECLARE_SINGLETON_FOR_CLASS(classname) CWL_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, shared##classname) #define CWL_SYNTHESIZE_SINGLETON_FOR_CLASS(classname) CWL_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, shared##classname) <|start_filename|>Projects/iOS < 6/PSUpdateApp/PSAppDelegate.h<|end_filename|> // // PSAppDelegate.h // PSUpdateApp // // Created by iBo on 18/02/13. // Copyright (c) 2013 D-Still. All rights reserved. // #import <UIKit/UIKit.h> @interface PSAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end <|start_filename|>PSUpdateApp/PSUpdateApp.h<|end_filename|> // // PSUpdateApp.h // PSUpdateApp // // Created by iBo on 18/02/13. // Copyright (c) 2013 D-Still. All rights reserved. // #import <Foundation/Foundation.h> #import "CWLSynthesizeSingleton.h" typedef void(^PSUpdateAppCompletionBlock)(NSError *error, BOOL success, id JSON); typedef enum { DefaultStrategy = 0, ForceStrategy, RemindStrategy } UpdateStrategy; @interface PSUpdateApp : NSObject CWL_DECLARE_SINGLETON_FOR_CLASS(PSUpdateApp) @property (nonatomic) NSString *appID, *appStoreLocation, *appName, *route, *updatePageUrl; @property (nonatomic) UpdateStrategy strategy; @property (nonatomic) int daysUntilPrompt; @property (nonatomic) NSDate *remindDate; + (id) startWithRoute:(NSString *)route; + (id) startWithAppID:(NSString *)appId; + (id) startWithAppID:(NSString *)appId store:(NSString *)store; - (void) detectAppVersion:(PSUpdateAppCompletionBlock)completionBlock; - (void) setURLAdHoc:(NSString *)url; @end
danielebogo/PSUpdateApp
<|start_filename|>public/js/upload.js<|end_filename|> // drag to upload var fileInput = document.getElementById('image-input'); var urlInput = document.getElementById('select-url-input'); window.addEventListener('paste', e => { if (e.clipboardData.getData('text/plain') !== '') { // contains text, could be a URL urlInput.value = e.clipboardData.getData('text/plain'); $('#url-form').submit(); } else { // contains a file fileInput.files = e.clipboardData.files; $('#upload-form').submit(); } }); $('#image-input').on('change', function() { var selectImage = $('#select-image'); var cancelImage = $('#cancel-image'); selectImage.text('click again to upload ' + $(this).val().replace('C:\\fakepath\\', '')).css({ 'margin-bottom' : '10px', 'display' : 'block' }); cancelImage.removeClass('hidden'); selectImage.off(); selectImage.on('click', function() { selectImage.off(); cancelImage.addClass('hidden'); $('#upload-form').submit(); selectImage.text('Your image is uploading, please wait'); } ); }); $('#select-image, #cancel-image').on('click', function() { $('#image-input').click(); }); $('.delete').on('click', function() { return confirm('Are you sure? This image WILL BE DELETED'); }); $('#ban').on('click', function() { return confirm('Are you sure? This user will be BANNED and ALL OF THEIR IMAGES WILL BE DELETED'); }); $('#links li input').on('click', function() { $(this).select(); });
lfiore/upld
<|start_filename|>GPhotoApp.js<|end_filename|> /** * GitHub https://github.com/tanaikech/GPhotoApp<br> * Create new album.<br> * @param {Object} object Object * @return {Object} Return Object */ function createAlbum(object) { return new GPhotoApp().CreateAlbum(object); } /** * Get album list.<br> * @param {Bool} excludeNonAppCreatedData excludeNonAppCreatedData * @return {Object} Return Object */ function getAlbumList(excludeNonAppCreatedData) { return new GPhotoApp().GetAlbumList(excludeNonAppCreatedData); } /** * Get mediaItem list.<br> * @return {Object} Return Object */ function getMediaItemList() { return new GPhotoApp().GetMediaItemList(); } /** * Get mediaItems.<br> * @param {Object} object Object * @return {Object} Return Object */ function getMediaItems(object) { return new GPhotoApp().GetMediaItems(object); } /** * Upload mediaItems using Blob.<br> * @param {Object} object Object * @return {Object} Return Object */ function uploadMediaItems(object) { return new GPhotoApp().UploadMediaItems(object); } ; (function(r) { var GPhotoApp; GPhotoApp = (function() { var getUploadToken; class GPhotoApp { constructor(p_) { this.accessToken = ScriptApp.getOAuthToken(); } // --- methods --- begin CreateAlbum(obj_) { var params, res, url; if (!obj_) { throw new Error("Please input resource object."); } if (typeof obj_ === "string") { obj_ = { album: { title: obj_ } }; } url = "https://photoslibrary.googleapis.com/v1/albums"; params = { url: url, method: "post", muteHttpExceptions: true, headers: { Authorization: `Bearer ${this.accessToken}` }, payload: JSON.stringify(obj_), contentType: "application/json" }; res = UrlFetchApp.fetchAll([params])[0]; if (res.getResponseCode() !== 200) { throw new Error(res.getContentText()); } return JSON.parse(res.getContentText()); } GetAlbumList(excludeNonAppCreatedData_) { var albums, excludeNonAppCreatedData, pageToken, params, res, url; if (!excludeNonAppCreatedData) { excludeNonAppCreatedData = false; } url = `https://photoslibrary.googleapis.com/v1/albums?fields=*&pageSize=50&excludeNonAppCreatedData=${excludeNonAppCreatedData}`; params = { method: "get", muteHttpExceptions: true, headers: { Authorization: `Bearer ${this.accessToken}` } }; albums = []; pageToken = ""; while (true) { params.url = url + (pageToken ? `&nextPageToken=${pageToken}` : ""); res = UrlFetchApp.fetchAll([params])[0]; r = JSON.parse(res.getContentText()); if (res.getResponseCode() !== 200) { throw new Error(res.getContentText()); } Array.prototype.push.apply(albums, r.albums); pageToken = r.nextPageToken; if (!pageToken) { break; } } return albums; } GetMediaItemList() { var mediaItems, pageToken, params, res, url; url = "https://photoslibrary.googleapis.com/v1/mediaItems?fields=*&pageSize=100"; params = { method: "get", muteHttpExceptions: true, headers: { Authorization: `Bearer ${this.accessToken}` } }; mediaItems = []; pageToken = ""; while (true) { params.url = url + (pageToken ? `&nextPageToken=${pageToken}` : ""); res = UrlFetchApp.fetchAll([params])[0]; r = JSON.parse(res.getContentText()); if (res.getResponseCode() !== 200) { throw new Error(res.getContentText()); } Array.prototype.push.apply(mediaItems, r.mediaItems); pageToken = r.nextPageToken; if (!pageToken) { break; } } return mediaItems; } GetMediaItems(obj_) { var params, q, res, url; if (!obj_ || !("mediaItemIds" in obj_)) { throw new Error("Please input resource object."); } url = "https://photoslibrary.googleapis.com/v1/mediaItems:batchGet"; q = obj_.mediaItemIds.reduce((s, e, i, a) => { return s += "mediaItemIds=" + e + (a.length - 1 === i ? "" : "&"); }, "?"); params = { url: url + q, method: "post", muteHttpExceptions: true, headers: { Authorization: `Bearer ${this.accessToken}`, "x-http-method-override": "GET" } }; res = UrlFetchApp.fetchAll([params])[0]; if (res.getResponseCode() !== 200) { throw new Error(res.getContentText()); } return JSON.parse(res.getContentText()); } UploadMediaItems(obj_) { var newMediaItems, params, payload, res, url; if (!obj_) { throw new Error("Please input resource object."); } url = "https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate"; newMediaItems = obj_.items.map((e) => { return { description: e.description, simpleMediaItem: { fileName: e.filename, uploadToken: getUploadToken.call(this, e) } }; }); payload = { albumId: obj_.albumId, newMediaItems: newMediaItems }; params = { url: url, method: "post", muteHttpExceptions: true, headers: { Authorization: `Bearer ${this.accessToken}` }, contentType: "application/json", payload: JSON.stringify(payload) }; res = UrlFetchApp.fetchAll([params])[0]; if (res.getResponseCode() !== 200) { throw new Error(res.getContentText()); } return JSON.parse(res.getContentText()); } }; GPhotoApp.name = "GPhotoApp"; // --- methods --- end getUploadToken = function(obj_) { var params, res, url; url = "https://photoslibrary.googleapis.com/v1/uploads"; params = { url: url, method: "post", muteHttpExceptions: true, headers: { Authorization: `Bearer ${this.accessToken}`, "X-Goog-Upload-File-Name": obj_.filename, "X-Goog-Upload-Protocol": "raw" }, contentType: "application/octet-stream", payload: obj_.blob }; res = UrlFetchApp.fetchAll([params])[0]; if (res.getResponseCode() !== 200) { throw new Error(res.getContentText()); } return res.getContentText(); }; return GPhotoApp; }).call(this); return r.GPhotoApp = GPhotoApp; })(this);
tanaikech/GPhotoApp
<|start_filename|>start-client/src/components/utils/Hash.js<|end_filename|> import queryString from 'query-string' import { toast } from 'react-toastify' import { useContext, useEffect, useState } from 'react' import { AppContext } from '../reducer/App' import { InitializrContext } from '../reducer/Initializr' import { isValidParams } from './ApiUtils' const getHash = () => { return window.location.hash } const clearHash = () => { if (window.location.hash) { if (window.history.pushState) { window.history.pushState(null, null, window.location.pathname) } else { window.history.hash = `` } } } export default function useHash() { const [hash, setHash] = useState(getHash()) const { dispatch } = useContext(InitializrContext) const { config, complete } = useContext(AppContext) useEffect(() => { const handler = () => { setHash(getHash()) } window.addEventListener('hashchange', handler) return () => { window.removeEventListener('hashchange', handler) } }, []) useEffect(() => { if (complete && hash) { const params = queryString.parse(`?${hash.substr(2)}`) dispatch({ type: 'LOAD', payload: { params, lists: config.lists } }) clearHash() setHash('') if (isValidParams(params)) { toast.success(`Configuration loaded.`) } } }, [complete, hash, dispatch, config]) return null } <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/description/InvalidJvmVersionHelpDocumentCustomizer.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.description; import java.util.Objects; import io.spring.initializr.generator.project.ProjectDescription; import io.spring.initializr.generator.project.ProjectDescriptionDiff; import io.spring.initializr.generator.spring.documentation.HelpDocument; import io.spring.initializr.generator.spring.documentation.HelpDocumentCustomizer; /** * A {@link HelpDocumentCustomizer} that adds a warning when the JVM level was changed. * * @author <NAME> */ public class InvalidJvmVersionHelpDocumentCustomizer implements HelpDocumentCustomizer { private final ProjectDescriptionDiff diff; private final ProjectDescription description; public InvalidJvmVersionHelpDocumentCustomizer(ProjectDescriptionDiff diff, ProjectDescription description) { this.diff = diff; this.description = description; } @Override public void customize(HelpDocument document) { this.diff.ifLanguageChanged(this.description, (original, current) -> { String originalJvmVersion = original.jvmVersion(); String currentJvmVersion = current.jvmVersion(); if (!Objects.equals(originalJvmVersion, currentJvmVersion)) { document.getWarnings().addItem(String.format( "The JVM level was changed from '%s' to '%s', review the [JDK Version Range](%s) on the wiki for more details.", originalJvmVersion, currentJvmVersion, "https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Versions#jdk-version-range")); } }); } } <|start_filename|>start-client/src/components/common/share/Popover.js<|end_filename|> import PropTypes from 'prop-types' import get from 'lodash.get' import React, { useEffect, useRef, useState } from 'react' import { CSSTransition, TransitionGroup } from 'react-transition-group' import { CopyToClipboard } from 'react-copy-to-clipboard' import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock' import useWindowsUtils from '../../utils/WindowsUtils' function Popover({ shareUrl, open, onClose }) { const [button, setButton] = useState('Copy') const wrapper = useRef(null) const input = useRef(null) const link = useRef(null) const windowsUtils = useWindowsUtils() useEffect(() => { const clickOutside = event => { const children = get(wrapper, 'current') if (children && !children.contains(event.target)) { onClose() } } document.addEventListener('mousedown', clickOutside) if (get(input, 'current')) { get(input, 'current').focus() } return () => { document.removeEventListener('mousedown', clickOutside) } }, [onClose, input]) const onEnter = () => { setButton('Copy') } useEffect(() => { if (get(wrapper, 'current') && open) { disableBodyScroll(get(wrapper, 'current')) } return () => { clearAllBodyScrollLocks() } }, [wrapper, open]) const onCopy = () => { setButton('Copied!') input.current.focus() setTimeout(() => { onClose() }, 1000) } const urlToShare = `${windowsUtils.origin}/#!${shareUrl}` return ( <> <TransitionGroup component={null}> {open && ( <CSSTransition onEnter={onEnter} classNames='popup' timeout={300}> <div className='popup-share'> <div className='popop-share-container' ref={wrapper}> <div className='popup-header'> <h1>Share your configuration</h1> </div> <div className='popup-content'> {/* eslint-disable-next-line */} <label htmlFor='input-share'> Use this link to share the current configuration. Attributes can be removed from the URL if you want to rely on our defaults. </label> <div className='control'> <input onFocus={event => { event.target.select() }} id='input-share' className={`input ${ button === 'Copied!' ? 'padding-lg' : '' }`} onKeyDown={event => { if (event.key === 'Escape') { onClose() } }} readOnly value={urlToShare} ref={input} /> <CopyToClipboard onCopy={onCopy} text={urlToShare}> <a href='/#' onClick={e => { e.preventDefault() }} className='button' ref={link} > <span className='button-content' tabIndex='-1'> <span>{button}</span> </span> </a> </CopyToClipboard> </div> </div> <div className='popup-action'> <a href='/#' onClick={e => { e.preventDefault() onClose() }} className='button' > <span className='button-content' tabIndex='-1'> <span>Close</span> <span className='secondary desktop-only'>ESC</span> </span> </a> </div> </div> </div> </CSSTransition> )} </TransitionGroup> </> ) } Popover.propTypes = { shareUrl: PropTypes.string.isRequired, open: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, } export default Popover <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/build/maven/MavenBuildSystemHelpDocumentCustomizer.java<|end_filename|> /* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.build.maven; import io.spring.initializr.generator.project.ProjectDescription; import io.spring.initializr.generator.spring.documentation.HelpDocument; import io.spring.initializr.generator.spring.documentation.HelpDocumentCustomizer; import io.spring.initializr.generator.version.Version; import io.spring.initializr.generator.version.VersionParser; import io.spring.initializr.generator.version.VersionRange; /** * A {@link HelpDocumentCustomizer} that adds reference links for Apache Maven. * * @author <NAME> * @author <NAME> */ class MavenBuildSystemHelpDocumentCustomizer implements HelpDocumentCustomizer { private static final VersionRange SPRING_BOOT_2_3_OR_LATER = VersionParser.DEFAULT.parseRange("2.3.0.M1"); private static final VersionRange NEW_DOC_STRUCTURE = VersionParser.DEFAULT.parseRange("2.3.0.M4"); private final Version springBootVersion; private final boolean springBoot23; private final boolean newDocStructure; MavenBuildSystemHelpDocumentCustomizer(ProjectDescription description) { this.springBootVersion = description.getPlatformVersion(); this.springBoot23 = SPRING_BOOT_2_3_OR_LATER.match(this.springBootVersion); this.newDocStructure = NEW_DOC_STRUCTURE.match(this.springBootVersion); } @Override public void customize(HelpDocument document) { document.gettingStarted().addReferenceDocLink("https://maven.apache.org/guides/index.html", "Official Apache Maven documentation"); String referenceGuideUrl = generateReferenceGuideUrl(); document.gettingStarted().addReferenceDocLink(referenceGuideUrl, "Spring Boot Maven Plugin Reference Guide"); if (this.springBoot23) { String buildImageSection = referenceGuideUrl + "#build-image"; document.gettingStarted().addReferenceDocLink(buildImageSection, "Create an OCI image"); } } private String generateReferenceGuideUrl() { String baseUrlFormat = "https://docs.spring.io/spring-boot/docs/%s/maven-plugin/"; if (this.springBoot23) { String location = (this.newDocStructure) ? "reference/html/" : "html/"; baseUrlFormat = baseUrlFormat + location; } return String.format(baseUrlFormat, this.springBootVersion); } } <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/code/kotlin/ReactorKotlinExtensionsCustomizer.java<|end_filename|> /* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.code.kotlin; import io.spring.initializr.generator.buildsystem.Build; import io.spring.initializr.generator.buildsystem.Dependency; import io.spring.initializr.generator.spring.build.BuildCustomizer; import io.spring.initializr.generator.spring.build.BuildMetadataResolver; import io.spring.initializr.metadata.InitializrMetadata; /** * A {@link BuildCustomizer} that automatically adds "reactor-kotlin-extensions" when a * dependency with the {@code reactive} facet is selected. * * @author <NAME> */ class ReactorKotlinExtensionsCustomizer implements BuildCustomizer<Build> { private final BuildMetadataResolver buildResolver; ReactorKotlinExtensionsCustomizer(InitializrMetadata metadata) { this.buildResolver = new BuildMetadataResolver(metadata); } @Override public void customize(Build build) { if (this.buildResolver.hasFacet(build, "reactive")) { build.dependencies().add("reactor-kotlin-extensions", Dependency.withCoordinates("io.projectreactor.kotlin", "reactor-kotlin-extensions")); } } } <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/dependency/springrestdocs/SpringRestDocsProjectGenerationConfiguration.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.dependency.springrestdocs; import io.spring.initializr.generator.buildsystem.gradle.GradleBuildSystem; import io.spring.initializr.generator.buildsystem.maven.MavenBuildSystem; import io.spring.initializr.generator.condition.ConditionalOnBuildSystem; import io.spring.initializr.generator.condition.ConditionalOnRequestedDependency; import io.spring.initializr.generator.project.ProjectGenerationConfiguration; import org.springframework.context.annotation.Bean; /** * {@link ProjectGenerationConfiguration} for generation of projects that depend on Spring * REST Docs. * * @author <NAME> */ @ProjectGenerationConfiguration @ConditionalOnRequestedDependency("restdocs") public class SpringRestDocsProjectGenerationConfiguration { @Bean public SpringRestDocsBuildCustomizer springRestDocsBuildCustomizer() { return new SpringRestDocsBuildCustomizer(); } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public SpringRestDocsGradleBuildCustomizer restDocsGradleBuildCustomizer() { return new SpringRestDocsGradleBuildCustomizer(); } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public SpringRestDocsMavenBuildCustomizer restDocsMavenBuildCustomizer() { return new SpringRestDocsMavenBuildCustomizer(); } } <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/dependency/springrestdocs/SpringRestDocsBuildCustomizer.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.dependency.springrestdocs; import io.spring.initializr.generator.buildsystem.Build; import io.spring.initializr.generator.buildsystem.DependencyScope; import io.spring.initializr.generator.spring.build.BuildCustomizer; /** * A {@link BuildCustomizer} that tunes the REST Docs dependency based on the web * framework that the application is using. * * @author <NAME> */ public class SpringRestDocsBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) { if (switchToWebTestClient(build)) { build.dependencies().remove("restdocs"); build.dependencies().add("restdocs-webtestclient", "org.springframework.restdocs", "spring-restdocs-webtestclient", DependencyScope.TEST_COMPILE); } } private boolean switchToWebTestClient(Build build) { if (build.dependencies().has("web")) { return false; } if (build.dependencies().has("webflux") || build.dependencies().has("jersey")) { return true; } return false; } } <|start_filename|>start-client/src/components/common/builder/Control.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' const Control = ({ text, children, labelFor }) => { return ( <div className='control'> <label className='label' htmlFor={labelFor}> {text} </label> <div className='control-element'>{children}</div> </div> ) } Control.defaultProps = { children: null, labelFor: '', } Control.propTypes = { children: PropTypes.node, labelFor: PropTypes.string, text: PropTypes.string.isRequired, } export default Control <|start_filename|>start-site/src/main/java/io/spring/start/site/support/CacheableDependencyManagementVersionResolver.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.support; import java.util.Map; import io.spring.initializr.versionresolver.DependencyManagementVersionResolver; import org.springframework.cache.annotation.Cacheable; /** * A {@link DependencyManagementVersionResolver} that uses the metadata cache to store * dependency management resolution. * * @author <NAME> */ public class CacheableDependencyManagementVersionResolver implements DependencyManagementVersionResolver { private final DependencyManagementVersionResolver delegate; public CacheableDependencyManagementVersionResolver(DependencyManagementVersionResolver delegate) { this.delegate = delegate; } @Override @Cacheable("initializr.metadata") public Map<String, String> resolve(String groupId, String artifactId, String version) { return this.delegate.resolve(groupId, artifactId, version); } } <|start_filename|>start-client/src/components/common/dependency/Item.js<|end_filename|> import PropTypes from 'prop-types' import get from 'lodash.get' import React, { useContext } from 'react' import { IconEnter } from '../icons' import { InitializrContext } from '../../reducer/Initializr' const Item = ({ item, selected, onSelect, onAdd, group, index }) => { const { dispatch } = useContext(InitializrContext) const onClick = event => { event.preventDefault() if (item.valid) { dispatch({ type: 'ADD_DEPENDENCY', payload: { id: item.id }, }) } onAdd() } return ( <li key={`li-${get(item, 'id')}`}> <a href='/' className={`dependency ${selected ? 'selected' : ''} ${ !item.valid ? 'disabled' : '' }`} onClick={onClick} onMouseMove={() => { onSelect(index) }} > <strong> {get(item, 'name')}{' '} {group && <span className='group'>{get(item, 'group')}</span>} </strong> <span>{get(item, 'description')}</span> <IconEnter /> {!item.valid && <span className='invalid'>{item.message}</span>} </a> </li> ) } Item.defaultProps = { selected: false, group: true, } Item.propTypes = { selected: PropTypes.bool, group: PropTypes.bool, onSelect: PropTypes.func.isRequired, onAdd: PropTypes.func.isRequired, index: PropTypes.number.isRequired, item: PropTypes.shape({ description: PropTypes.string.isRequired, group: PropTypes.string.isRequired, id: PropTypes.string.isRequired, keywords: PropTypes.string, message: PropTypes.string, name: PropTypes.string.isRequired, valid: PropTypes.bool.isRequired, }).isRequired, } export default Item <|start_filename|>start-client/src/components/common/builder/Actions.js<|end_filename|> import BodyClassName from 'react-body-classname' import PropTypes from 'prop-types' import React from 'react' const Actions = ({ children }) => { return ( <div className='actions'> <div className='actions-container'>{children}</div> </div> ) } Actions.defaultProps = { children: null, } Actions.propTypes = { children: PropTypes.node, } export default Actions <|start_filename|>start-client/src/components/common/form/Overlay.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' import { CSSTransition, TransitionGroup } from 'react-transition-group' function Overlay({ open }) { return ( <TransitionGroup component={null}> {open && ( <CSSTransition classNames='overlay' timeout={100}> <div className='overlay' /> </CSSTransition> )} </TransitionGroup> ) } Overlay.propTypes = { open: PropTypes.bool.isRequired, } export default Overlay <|start_filename|>start-client/src/components/common/explore/index.js<|end_filename|> export { default as Explore } from './Explore' <|start_filename|>start-client/src/components/common/share/Share.js<|end_filename|> import '../../../styles/share.scss' import PropTypes from 'prop-types' import React from 'react' import Popover from './Popover' import { Overlay } from '../form' function Share({ shareUrl, open, onClose }) { return ( <> <Popover open={open || false} shareUrl={shareUrl} onClose={onClose} /> <Overlay open={open || false} /> </> ) } Share.propTypes = { shareUrl: PropTypes.string.isRequired, open: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, } export default Share <|start_filename|>start-site-verification/src/test/java/io/spring/start/site/DependencyResolver.java<|end_filename|> /* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import io.spring.initializr.metadata.BillOfMaterials; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.collection.CollectRequest; import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.internal.impl.DefaultRepositorySystem; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.RemoteRepository.Builder; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactDescriptorException; import org.eclipse.aether.resolution.ArtifactDescriptorRequest; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.DependencyResult; import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; import org.eclipse.aether.spi.connector.transport.GetTask; import org.eclipse.aether.spi.connector.transport.PeekTask; import org.eclipse.aether.spi.connector.transport.PutTask; import org.eclipse.aether.spi.connector.transport.Transporter; import org.eclipse.aether.spi.connector.transport.TransporterFactory; import org.eclipse.aether.spi.locator.ServiceLocator; import org.eclipse.aether.transfer.NoTransporterException; import org.eclipse.aether.transport.http.HttpTransporterFactory; import org.eclipse.aether.util.artifact.JavaScopes; import org.eclipse.aether.util.filter.DependencyFilterUtils; import org.eclipse.aether.util.repository.SimpleArtifactDescriptorPolicy; import org.springframework.util.FileSystemUtils; final class DependencyResolver { private static final Collection<DependencyResolver> instances = new ArrayList<>(); private static final ThreadLocal<DependencyResolver> instanceForThread = ThreadLocal.withInitial(() -> { DependencyResolver instance = new DependencyResolver(); instances.add(instance); return instance; }); private static final RepositoryPolicy repositoryPolicy = new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_IGNORE); static final RemoteRepository mavenCentral = createRemoteRepository("central", "https://repo1.maven.org/maven2", false); private static final Map<String, List<Dependency>> managedDependencies = new ConcurrentHashMap<>(); private final Path localRepositoryLocation; private final RepositorySystemSession repositorySystemSession; private final RepositorySystem repositorySystem; DependencyResolver() { try { ServiceLocator serviceLocator = createServiceLocator(); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(false, false)); this.localRepositoryLocation = Files.createTempDirectory("metadata-validation-m2"); LocalRepository localRepository = new LocalRepository(this.localRepositoryLocation.toFile()); this.repositorySystem = serviceLocator.getService(RepositorySystem.class); session.setLocalRepositoryManager( this.repositorySystem.newLocalRepositoryManager(session, localRepository)); session.setReadOnly(); this.repositorySystemSession = session; } catch (Exception ex) { throw new RuntimeException(ex); } } static RemoteRepository createRemoteRepository(String id, String url, boolean snapshot) { Builder repositoryBuilder = new Builder(id, "default", url); if (snapshot) { repositoryBuilder.setSnapshotPolicy(repositoryPolicy); } else { repositoryBuilder.setReleasePolicy(repositoryPolicy); } return repositoryBuilder.build(); } static List<String> resolveDependencies(String groupId, String artifactId, String version, List<BillOfMaterials> boms, List<RemoteRepository> repositories) { DependencyResolver instance = instanceForThread.get(); List<Dependency> managedDependencies = instance.getManagedDependencies(boms, repositories); Dependency aetherDependency = new Dependency(new DefaultArtifact(groupId, artifactId, "pom", instance.getVersion(groupId, artifactId, version, managedDependencies)), "compile"); CollectRequest collectRequest = new CollectRequest((org.eclipse.aether.graph.Dependency) null, Collections.singletonList(aetherDependency), repositories); collectRequest.setManagedDependencies(managedDependencies); DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME)); try { return instance.resolveDependencies(dependencyRequest).getArtifactResults().stream() .map(ArtifactResult::getArtifact) .map((artifact) -> artifact.getGroupId() + ":" + artifact.getArtifactId()) .collect(Collectors.toList()); } catch (DependencyResolutionException ex) { throw new RuntimeException(ex); } } static void cleanUp() { instances.forEach(DependencyResolver::deleteLocalRepository); } void deleteLocalRepository() { try { FileSystemUtils.deleteRecursively(this.localRepositoryLocation); } catch (IOException ex) { // Continue } } private List<Dependency> getManagedDependencies(List<BillOfMaterials> boms, List<RemoteRepository> repositories) { return boms.stream().flatMap( (bom) -> getManagedDependencies(bom.getGroupId(), bom.getArtifactId(), bom.getVersion(), repositories)) .collect(Collectors.toList()); } private Stream<Dependency> getManagedDependencies(String groupId, String artifactId, String version, List<RemoteRepository> repositories) { String key = groupId + ":" + artifactId + ":" + version; List<org.eclipse.aether.graph.Dependency> managedDependencies = DependencyResolver.managedDependencies .computeIfAbsent(key, (coords) -> resolveManagedDependencies(groupId, artifactId, version, repositories)); return managedDependencies.stream(); } private List<org.eclipse.aether.graph.Dependency> resolveManagedDependencies(String groupId, String artifactId, String version, List<RemoteRepository> repositories) { try { return this.repositorySystem .readArtifactDescriptor(this.repositorySystemSession, new ArtifactDescriptorRequest( new DefaultArtifact(groupId, artifactId, "pom", version), repositories, null)) .getManagedDependencies(); } catch (ArtifactDescriptorException ex) { throw new RuntimeException(ex); } } private DependencyResult resolveDependencies(DependencyRequest dependencyRequest) throws DependencyResolutionException { DependencyResult resolved = this.repositorySystem.resolveDependencies(this.repositorySystemSession, dependencyRequest); return resolved; } private String getVersion(String groupId, String artifactId, String version, List<org.eclipse.aether.graph.Dependency> managedDependencies) { if (version != null) { return version; } for (org.eclipse.aether.graph.Dependency managedDependency : managedDependencies) { if (groupId.equals(managedDependency.getArtifact().getGroupId()) && artifactId.equals(managedDependency.getArtifact().getArtifactId())) { return managedDependency.getArtifact().getVersion(); } } return null; } private static ServiceLocator createServiceLocator() { DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.addService(RepositorySystem.class, DefaultRepositorySystem.class); locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, DependencyResolver.JarSkippingHttpTransporterFactory.class); return locator; } private static class JarSkippingHttpTransporterFactory implements TransporterFactory { private final HttpTransporterFactory delegate = new HttpTransporterFactory(); @Override public Transporter newInstance(RepositorySystemSession session, RemoteRepository repository) throws NoTransporterException { return new JarGetSkippingTransporter(this.delegate.newInstance(session, repository)); } @Override public float getPriority() { return 5.0f; } private static final class JarGetSkippingTransporter implements Transporter { private final Transporter delegate; private JarGetSkippingTransporter(Transporter delegate) { this.delegate = delegate; } @Override public int classify(Throwable error) { return this.delegate.classify(error); } @Override public void peek(PeekTask task) throws Exception { this.delegate.peek(task); } @Override public void get(GetTask task) throws Exception { if (task.getLocation().getPath().endsWith(".jar")) { return; } this.delegate.get(task); } @Override public void put(PutTask task) throws Exception { this.delegate.put(task); } @Override public void close() { this.delegate.close(); } } } } <|start_filename|>start-client/src/components/common/layout/LogoMobile.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' const LogoMobile = ({ className }) => { return ( <svg aria-hidden='true' focusable='false' data-icon='spring-initializr' role='img' xmlns='http://www.w3.org/2000/svg' className={className} viewBox='0 0 454 145' > <g> <path className='st0' d='M153.4,62.6l-30.2-52.3c-2.6-4.5-9.1-8.3-14.3-8.3H48.5c-5.2,0-11.7,3.7-14.3,8.3L4,62.6 c-2.6,4.5-2.6,12,0,16.5l30.2,52.3c2.6,4.5,9.1,8.3,14.3,8.3h60.4c5.2,0,11.7-3.7,14.3-8.3l30.2-52.3 C156.1,74.5,156.1,67.1,153.4,62.6z' /> <g> <circle className='st1' cx='36.7' cy='115.2' r='6.1' /> </g> <g> <path className='st1' d='M139,97.4C121.3,121,83.5,113,59.3,114.2c0,0-4.3,0.2-8.6,0.9c0,0,1.6-0.7,3.7-1.4c17-5.9,25-7.1,35.4-12.4 c19.4-9.9,38.7-31.6,42.7-54.1c-7.4,21.6-29.9,40.3-50.3,47.8c-14,5.2-39.3,10.2-39.3,10.2l-1-0.5C24.5,96.4,24,59,55.3,47 C69,41.7,82.2,44.6,97,41.1c15.8-3.8,34.1-15.6,41.6-31.1C146.9,34.8,156.9,73.5,139,97.4z' /> <path className='st0' d='M138.6,10c8.3,24.8,18.4,63.5,0.4,87.4c-11.1,14.8-30.1,17.2-48.7,17.2c-8.8,0-17.5-0.5-25.2-0.5 c-2,0-3.9,0-5.7,0.1c0,0-4.3,0.2-8.6,0.9c0,0,1.6-0.7,3.7-1.4c17-5.9,25-7.1,35.4-12.4c19.4-9.9,38.7-31.6,42.7-54.1 c-7.4,21.6-29.9,40.3-50.3,47.8c-14,5.2-39.3,10.2-39.3,10.2l0,0l-1-0.5C24.5,96.4,24,59,55.3,47C69,41.7,82.2,44.6,97,41.1 C112.8,37.4,131.1,25.5,138.6,10 M139.1,2.1l-3.2,6.6c-7.5,15.6-25.8,26.2-39.6,29.5C90.1,39.7,84,40,78.2,40.3 c-7.7,0.4-15.7,0.8-23.9,3.9C35,51.6,27.6,67.8,27.1,80.5c-0.5,12.1,4.7,22.6,13.2,26.9c0.5,0.3,1.6,0.9,2.5,0.9h1.3l0.2-0.2 c5.8-1.2,26.5-5.6,38.9-10.1c8.6-3.2,18.3-8.6,27.1-15.8c-6.5,6.9-14.1,12.7-21.8,16.6c-6.3,3.2-11.7,4.9-19.2,7.2 c-4.4,1.3-9.5,2.9-15.7,5c-2.2,0.7-3.8,1.5-3.9,1.5l-2.2,4.5l3.9,1.2c4.1-0.7,8.2-0.9,8.3-0.9c1.7-0.1,3.5-0.1,5.5-0.1 c3.7,0,7.6,0.1,11.7,0.3c4.4,0.1,8.9,0.3,13.5,0.3c18.5,0,39-2.2,51.1-18.4c14.1-18.8,14.2-48.3,0.1-90.2L139.1,2.1L139.1,2.1z' /> </g> </g> <g> <g> <path className='st0' d='M182.5,59.7c-0.9-0.5-1.5-1.5-1.5-2.8c0-1.8,1.5-3.3,3.3-3.3c0.7,0,1.3,0.2,1.8,0.5c3.5,2.3,7.1,3.5,10.3,3.5 c3.5,0,5.6-1.5,5.6-3.9v-0.2c0-2.8-3.8-3.8-8-5c-5.3-1.5-11.2-3.6-11.2-10.5v-0.2c0-6.8,5.6-10.9,12.7-10.9 c3.8,0,7.8,1.1,11.3,2.9c1.2,0.6,2,1.7,2,3.1c0,1.9-1.5,3.3-3.5,3.3c-0.7,0-1.1-0.2-1.6-0.4c-2.9-1.5-5.9-2.4-8.4-2.4 c-3.2,0-5,1.5-5,3.5v0.2c0,2.7,3.9,3.8,8.1,5.1c5.3,1.6,11.1,4.1,11.1,10.4v0.2c0,7.5-5.9,11.3-13.3,11.3 C191.5,64,186.6,62.5,182.5,59.7z' /> <path className='st0' d='M212.5,31c0-2.3,1.8-4.1,4.1-4.1s4.1,1.8,4.1,4.1v2.4c2.7-3.8,6.4-6.7,12.2-6.7c8.4,0,16.6,6.6,16.6,18.6v0.2 c0,11.9-8.2,18.6-16.6,18.6c-5.9,0-9.7-3-12.2-6.3v12.7c0,2.3-1.8,4.1-4.1,4.1c-2.2,0-4.1-1.8-4.1-4.1V31z M241.2,45.5v-0.2 c0-6.9-4.7-11.4-10.2-11.4c-5.6,0-10.4,4.7-10.4,11.4v0.2c0,6.8,4.8,11.4,10.4,11.4C236.5,57,241.2,52.6,241.2,45.5z' /> <path className='st0' d='M252.6,31c0-2.3,1.8-4.1,4.1-4.1c2.3,0,4.1,1.8,4.1,4.1v2c0.4-3,5.4-6.1,9-6.1c2.6,0,4.1,1.7,4.1,4.1 c0,2.1-1.5,3.6-3.3,3.9c-5.9,1-9.8,6.1-9.8,13.1v11.8c0,2.2-1.8,4.1-4.1,4.1c-2.2,0-4.1-1.8-4.1-4.1L252.6,31L252.6,31L252.6,31z' /> <path className='st0' d='M277,31.1c0-2.3,1.8-4.1,4.1-4.1s4.1,1.8,4.1,4.1v28.8c0,2.3-1.8,4.1-4.1,4.1c-2.2,0-4.1-1.8-4.1-4.1V31.1z' /> <path className='st0' d='M289.4,31.1c0-2.3,1.8-4.1,4.1-4.1c2.3,0,4.1,1.8,4.1,4.1v1.7c2.3-3.3,5.6-5.9,11.2-5.9 c8.1,0,12.7,5.4,12.7,13.7v19.3c0,2.3-1.8,4.1-4.1,4.1s-4.1-1.8-4.1-4.1V43.2c0-5.6-2.7-8.8-7.7-8.8c-4.7,0-8.1,3.3-8.1,8.9v16.7 c0,2.3-1.8,4.1-4.1,4.1c-2.2,0-4.1-1.8-4.1-4.1V31.1L289.4,31.1z' /> <path className='st0' d='M357.5,26.9c-2.3,0-4.1,1.8-4.1,4.1v2.4c-2.7-3.8-6.4-6.7-12.2-6.7c-8.4,0-16.6,6.6-16.6,18.6v0.2 c0,11.9,8.2,18.6,16.6,18.6c5.9,0,9.7-3,12.2-6.2c-0.4,6.5-4.4,9.8-11.3,9.8c-4.1,0-7.7-1-11-2.8c-0.4-0.2-0.9-0.3-1.5-0.3 c-1.9,0-3.5,1.5-3.5,3.3c0,1.6,0.9,2.7,2.3,3.3c4.4,2.1,8.8,3.2,13.9,3.2c6.5,0,11.5-1.5,14.7-4.8c3-3,4.5-7.4,4.5-13.4V31 C361.6,28.7,359.7,26.9,357.5,26.9z M343.1,56.9c-5.6,0-10.2-4.4-10.2-11.5v-0.2c0-6.9,4.7-11.4,10.2-11.4 c5.6,0,10.4,4.7,10.4,11.4v0.2C353.6,52.3,348.7,56.9,343.1,56.9z' /> <path className='st0' d='M285.3,17.1c0,2.3-1.8,4.1-4.1,4.1c-2.3,0-4.1-1.8-4.1-4.1s1.8-4.1,4.1-4.1C283.3,12.9,285.3,14.8,285.3,17.1 z' /> </g> <g> <path className='st0' d='M371,35.5c-2.3,0-4.2-1.9-4.2-4.2c0-2.4,1.9-4.2,4.2-4.2c2.4,0,4.2,1.9,4.2,4.2S373.3,35.5,371,35.5z M371,27.7c-2,0-3.6,1.6-3.6,3.6s1.6,3.6,3.6,3.6c2,0,3.6-1.6,3.6-3.6C374.5,29.2,373,27.7,371,27.7z M372.1,33.6l-1.2-1.9H370 v1.9h-0.7v-4.8h2c0.8,0,1.6,0.6,1.6,1.5c0,1.1-1,1.5-1.2,1.5l1.3,1.9H372.1L372.1,33.6z M371.3,29.5H370v1.7h1.3 c0.4,0,0.8-0.3,0.8-0.8C372.2,29.8,371.7,29.5,371.3,29.5z' /> </g> </g> <g> <path fill='currentColor' d='M181,86.4c0-2.7,2.2-4.9,5-4.9c2.7,0,4.9,2.3,4.9,4.9c0,2.7-2.2,5-4.9,5C183.2,91.5,181,89.1,181,86.4z M181.6,97h8.7v36.8 h-8.7V97z' /> <path fill='currentColor' d='M233.7,110.4v23.4h-8.4v-21.7c0-5-3.2-8.5-7.8-8.5c-4.5,0-8.4,3.1-8.9,7v23.3h-8.7V97h8.7v4.9c2.3-3.4,6.5-5.8,11.4-5.8 C228,96.1,233.7,102.1,233.7,110.4z' /> <path fill='currentColor' d='M242.5,86.4c0-2.7,2.2-4.9,5-4.9c2.7,0,4.9,2.3,4.9,4.9c0,2.7-2.2,5-4.9,5C244.7,91.5,242.5,89.1,242.5,86.4z M243.1,97 h8.7v36.8h-8.7V97z' /> <path fill='currentColor' d='M282.2,131.8c-2.1,1.8-5.1,2.9-7.8,2.9c-6.1,0-10.4-4.4-10.4-10.6v-19.9h-5.3V97h5.3V86.9h8.5V97h8.4v7.2h-8.4V123 c0,2.5,1.6,4.3,3.6,4.3c1.5,0,2.8-0.5,3.6-1.3L282.2,131.8z' /> <path fill='currentColor' d='M288.5,86.4c0-2.7,2.2-4.9,5-4.9c2.7,0,4.9,2.3,4.9,4.9c0,2.7-2.2,5-4.9,5C290.7,91.5,288.5,89.1,288.5,86.4z M289,97h8.7 v36.8H289V97z' /> <path fill='currentColor' d='M339.2,111.7v22.2h-8.5v-4.4c-2.7,3.4-7.3,5.3-11.6,5.3c-7.8,0-13.7-4.6-13.7-11.7c0-7.3,6.8-12.2,15-12.2 c3.3,0,7,0.7,10.4,2v-1c0-4.3-2.4-8.4-9-8.4c-3.5,0-6.8,1.2-10,2.8l-3-6.1c5.2-2.5,10.1-3.9,14.7-3.9 C333.2,96.1,339.2,102.4,339.2,111.7z M330.7,122.3v-4.1c-2.7-0.9-5.8-1.5-9-1.5c-4.4,0-7.8,2.4-7.8,5.9c0,3.5,3.1,5.7,7.2,5.7 C325.2,128.3,329.7,126.2,330.7,122.3z' /> <path fill='currentColor' d='M348.6,84h8.7v49.8h-8.7V84z' /> <path fill='currentColor' d='M366.3,86.4c0-2.7,2.2-4.9,5-4.9c2.7,0,4.9,2.3,4.9,4.9c0,2.7-2.2,5-4.9,5C368.5,91.5,366.3,89.1,366.3,86.4z M366.9,97 h8.7v36.8h-8.7V97z' /> <path fill='currentColor' d='M383.7,127.5l19.6-22.9h-19.1V97h30.6l-0.1,6.4l-19.6,22.9h19.8v7.6h-31.1L383.7,127.5L383.7,127.5z' /> <path fill='currentColor' d='M444.8,96.1v7.4c-7.9,0-13.2,4.7-13.2,11.7v18.6h-8.7V97h8.7v7.1C434,99.2,438.8,96.1,444.8,96.1z' /> </g> </svg> ) } LogoMobile.defaultProps = { className: '', } LogoMobile.propTypes = { className: PropTypes.string, } export default LogoMobile <|start_filename|>start-client/src/App.js<|end_filename|> import './styles/app.scss' import React from 'react' import { ToastContainer } from 'react-toastify' import { render } from 'react-dom' import Application from './components/Application' import Close from './components/common/form/Close' import { AppProvider } from './components/reducer/App' import { InitializrProvider } from './components/reducer/Initializr' render( <AppProvider> <InitializrProvider> <ToastContainer closeButton={<Close />} position='top-center' hideProgressBar /> <Application /> </InitializrProvider> </AppProvider>, document.getElementById('app') ) <|start_filename|>start-client/src/components/common/explore/Select.js<|end_filename|> import PropTypes from 'prop-types' import get from 'lodash.get' import React, { useEffect, useState } from 'react' function Select({ tree, selected, onClickItem }) { const [array, setArray] = useState([]) useEffect(() => { const treeToArray = map => { const recursive = (mapRec, acc) => { mapRec.forEach(item => { if (item.type !== 'folder') { acc.push(item) } else if (get(item, 'children')) { recursive(item.children, acc) } }) return acc } return recursive(map, []) } setArray(treeToArray(tree.children)) }, [tree, setArray]) const getPlaceholderPath = depth => { return depth > 0 ? `${[...Array(depth).keys()].map(() => '..').join('/')}/` : '' } const renderItem = (item, depth = 0) => { if (item.type === 'folder') { return ( <> <option value={item.path} key={item.path} disabled> {getPlaceholderPath(depth)} {item.filename} </option> {get(item, 'children') && ( <>{item.children.map(it => renderItem(it, depth + 1))}</> )} </> ) } const isDisabled = get(item, 'language') === null return ( <option disabled={isDisabled} key={item.path} value={item.path}> {getPlaceholderPath(depth)} {item.filename} </option> ) } return ( <select value={selected.path} onChange={event => { const item = array.find(it => it.path === event.target.value) if (item) { onClickItem(item) } }} > {tree.children.map(item => renderItem(item, 0))} </select> ) } Select.propTypes = { tree: PropTypes.shape({ children: PropTypes.arrayOf( PropTypes.shape({ type: PropTypes.string, }) ), }).isRequired, selected: PropTypes.shape({ path: PropTypes.string.isRequired, }).isRequired, onClickItem: PropTypes.func.isRequired, } export default Select <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/description/InvalidPackageNameHelpDocumentCustomizer.java<|end_filename|> /* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.description; import io.spring.initializr.generator.project.ProjectDescription; import io.spring.initializr.generator.project.ProjectDescriptionDiff; import io.spring.initializr.generator.spring.documentation.HelpDocument; import io.spring.initializr.generator.spring.documentation.HelpDocumentCustomizer; /** * A {@link HelpDocumentCustomizer} that adds a warning when the package name was changed. * * @author <NAME> */ public class InvalidPackageNameHelpDocumentCustomizer implements HelpDocumentCustomizer { private final ProjectDescriptionDiff diff; private final ProjectDescription description; public InvalidPackageNameHelpDocumentCustomizer(ProjectDescriptionDiff diff, ProjectDescription description) { this.diff = diff; this.description = description; } @Override public void customize(HelpDocument document) { this.diff.ifPackageNameChanged(this.description, (original, current) -> document.getWarnings() .addItem(String.format( "The original package name '%s' is invalid and this project uses '%s' instead.", original, current))); } } <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/build/gradle/ManagedDependenciesDependencyManagementPluginVersionResolver.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.build.gradle; import java.util.function.Function; import io.spring.initializr.generator.project.ProjectDescription; import io.spring.initializr.generator.spring.build.gradle.DependencyManagementPluginVersionResolver; import io.spring.initializr.versionresolver.DependencyManagementVersionResolver; /** * {@link DependencyManagementPluginVersionResolver} that determines the dependency * management plugin version using the dependency management from the project * description's Boot version. * * @author <NAME> */ public class ManagedDependenciesDependencyManagementPluginVersionResolver implements DependencyManagementPluginVersionResolver { private final DependencyManagementVersionResolver resolver; private final Function<ProjectDescription, String> fallback; public ManagedDependenciesDependencyManagementPluginVersionResolver(DependencyManagementVersionResolver resolver, Function<ProjectDescription, String> fallback) { this.resolver = resolver; this.fallback = fallback; } @Override public String resolveDependencyManagementPluginVersion(ProjectDescription description) { String pluginVersion = this.resolver .resolve("org.springframework.boot", "spring-boot-dependencies", description.getPlatformVersion().toString()) .get("io.spring.gradle:dependency-management-plugin"); return (pluginVersion != null) ? pluginVersion : this.fallback.apply(description); } } <|start_filename|>start-client/src/components/common/dependency/List.js<|end_filename|> import get from 'lodash.get' import React, { useContext } from 'react' import { CSSTransition, TransitionGroup } from 'react-transition-group' import { AppContext } from '../../reducer/App' import { IconRemove } from '../icons' import { InitializrContext } from '../../reducer/Initializr' function List() { const { values, dispatch } = useContext(InitializrContext) const { dependencies } = useContext(AppContext) const list = get(values, 'dependencies', []).map(dep => { return dependencies.list.find(item => item.id === dep) }) return ( <TransitionGroup component='ul' className='dependencies-list'> {list.map(item => { return ( <CSSTransition timeout={300} classNames='fade' key={`f${item.id}`}> <li key={`d0${item.id}`}> <div className={`dependency-item ${!item.valid ? 'disabled' : ''}`} key={`d1${item.id}`} > <strong key={`d2${item.id}`}> {item.name}{' '} <span className='group'>{get(item, 'group')}</span> </strong> {item.valid && ( <span key={`d4${item.id}`} className='description'> {item.description} </span> )} <a href='/' onClick={event => { event.preventDefault() dispatch({ type: 'REMOVE_DEPENDENCY', payload: { id: item.id }, }) }} key={item.id} className='icon' > <span className='a-content' tabIndex='-1'> <IconRemove /> </span> </a> {!item.valid && ( <span className='invalid' key={`warning${item.id}`}> {item.message} </span> )} </div> </li> </CSSTransition> ) })} </TransitionGroup> ) } export default List <|start_filename|>start-client/src/components/common/share/index.js<|end_filename|> export { default as Share } from './Share' <|start_filename|>start-client/src/components/common/form/index.js<|end_filename|> export { default as Radio } from './Radio' export { default as Form } from './Form' export { default as Button } from './Button' export { default as Overlay } from './Overlay' <|start_filename|>start-client/src/components/utils/WindowsUtils.js<|end_filename|> import { useEffect, useState } from 'react' function getProperties() { return { symb: window.navigator.userAgent.toLowerCase().indexOf('mac') > -1 ? '⌘' : 'Ctrl', origin: window.location.origin, height: window.innerHeight, width: window.innerWidth, } } export default function useWindowsUtils() { const isClient = typeof window === 'object' const [symb] = useState(getProperties().symb) const [origin] = useState(getProperties().origin) const [height, setHeight] = useState(getProperties().height) const [width, setWidth] = useState(getProperties().width) useEffect(() => { if (!isClient) { return false } function handleResize() { setHeight(window.innerHeight) setWidth(window.innerWidth) } window.addEventListener('resize', handleResize) return () => window.removeEventListener('resize', handleResize) }, [isClient]) return { symb, origin, height, width } } <|start_filename|>start-client/src/components/common/builder/index.js<|end_filename|> export { default as Control } from './Control' export { default as Loading } from './Loading' export { default as FieldInput } from './FieldInput' export { default as FieldRadio } from './FieldRadio' export { default as Actions } from './Actions' export { default as Fields } from './Fields' export { default as Warnings } from './Warnings' export { default as Placeholder } from './Placeholder' <|start_filename|>start-site/src/test/java/io/spring/start/site/extension/dependency/springsecurity/SpringSecurityRSocketBuildCustomizerTests.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.dependency.springsecurity; import io.spring.initializr.metadata.Dependency; import io.spring.initializr.web.project.ProjectRequest; import io.spring.start.site.extension.AbstractExtensionTests; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringSecurityRSocketBuildCustomizer}. * * @author <NAME> */ class SpringSecurityRSocketBuildCustomizerTests extends AbstractExtensionTests { @Test void securityRSocketIsAddedWithSecurityAndRSocket() { ProjectRequest request = createProjectRequest("security", "rsocket"); assertThat(mavenPom(request)).hasDependency(Dependency.createSpringBootStarter("security")) .hasDependency(Dependency.createSpringBootStarter("rsocket")) .hasDependency("org.springframework.security", "spring-security-messaging") .hasDependency("org.springframework.security", "spring-security-rsocket"); } @Test void securityRSocketIsNotAddedWithRSocketOnly() { ProjectRequest request = createProjectRequest("rsocket"); assertThat(mavenPom(request)).hasDependency(Dependency.createSpringBootStarter("rsocket")) .doesNotHaveDependency("org.springframework.security", "spring-security-messaging") .doesNotHaveDependency("org.springframework.security", "spring-security-rsocket"); } @Test void securityRSocketIsNotAddedWithSecurityOnly() { ProjectRequest request = createProjectRequest("security"); assertThat(mavenPom(request)).hasDependency(Dependency.createSpringBootStarter("security")) .doesNotHaveDependency("org.springframework.security", "spring-security-messaging") .doesNotHaveDependency("org.springframework.security", "spring-security-rsocket"); } } <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/dependency/springsecurity/SpringSecurityRSocketBuildCustomizer.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.dependency.springsecurity; import io.spring.initializr.generator.buildsystem.Build; import io.spring.initializr.generator.buildsystem.Dependency; import io.spring.initializr.generator.spring.build.BuildCustomizer; /** * A {@link BuildCustomizer} that provides Spring Security's RSocket support when both * RSocket and Spring Security are selected. * * @author <NAME> */ public class SpringSecurityRSocketBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) { if (build.dependencies().has("rsocket")) { build.dependencies().add("security-rsocket", Dependency.withCoordinates("org.springframework.security", "spring-security-rsocket")); build.dependencies().add("security-messaging", Dependency.withCoordinates("org.springframework.security", "spring-security-messaging")); } } } <|start_filename|>start-client/src/components/common/form/Close.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' import { IconTimes } from '../icons' const Close = ({ onClose }) => ( <a href='/#' className='toast-close' onClick={event => { event.preventDefault() if (onClose) { onClose() } }} > <IconTimes /> </a> ) Close.defaultProps = { onClose: null, } Close.propTypes = { onClose: PropTypes.func, } export default Close <|start_filename|>start-client/src/components/common/icons/index.js<|end_filename|> export { IconTimes } from './Icons' export { IconPlus } from './Icons' export { IconGithub } from './Icons' export { IconTwitter } from './Icons' export { IconCaretDown } from './Icons' export { IconList } from './Icons' export { IconSearch } from './Icons' export { IconCheck } from './Icons' export { IconChevronLeft } from './Icons' export { IconChevronRight } from './Icons' export { IconChevronUp } from './Icons' export { IconChevronDown } from './Icons' export { IconFolder } from './Icons' export { IconFile } from './Icons' export { IconNavigation } from './Icons' export { IconSun } from './Icons' export { IconMoon } from './Icons' export { IconRemove } from './Icons' export { IconEnter } from './Icons' export { IconSpring } from './IconSpring' <|start_filename|>start-client/src/components/common/explore/Loading.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' import { Placeholder } from '../builder' function Loading({ onClose }) { return ( <> <a href='/#' onClick={e => { e.preventDefault() onClose() }} > {' '} </a> <div className='colset-explorer'> <div className='left'> <div className='head'> <Placeholder width='70px' type='text' /> </div> <div className='explorer-content'> <ul className='explorer-ul-placeholder'> <li> <Placeholder type='text' width='66px' /> </li> <li> <Placeholder type='text' width='60px' /> </li> <li> <Placeholder type='text' width='45px' /> </li> <li> <Placeholder type='text' width='87px' /> </li> <li> <Placeholder type='text' width='80px' /> </li> <li> <Placeholder type='text' width='94px' /> </li> <li> <Placeholder type='text' width='86px' /> </li> </ul> </div> </div> <div className='right'> <div className='head'> <div className='actions-file'> <Placeholder width='120px' type='button' /> <Placeholder width='78px' type='button' /> </div> </div> <div className='is-mobile explorer-select placeholder-explorer-select'> <div className='placeholder-select' /> </div> <div className='explorer-content' /> </div> <div className='explorer-actions'> <Placeholder className='placeholder-button-download' type='button' /> <a href='/#' onClick={e => { e.preventDefault() onClose() }} className='button' > <span className='button-content'> <span>Close</span> <span className='secondary desktop-only'>ESC</span> </span> </a> </div> </div> </> ) } Loading.propTypes = { onClose: PropTypes.func.isRequired, } export default Loading <|start_filename|>start-client/src/components/common/layout/Social.js<|end_filename|> import React from 'react' import { IconGithub, IconTwitter } from '../icons' const Social = () => ( <div className='social'> <a rel='noreferrer noopener' target='_blank' href='https://github.com/spring-io/start.spring.io' > <IconGithub /> </a> <a rel='noreferrer noopener' target='_blank' href='https://twitter.com/springboot' > <IconTwitter /> </a> </div> ) export default Social <|start_filename|>start-site/src/test/java/io/spring/start/site/extension/dependency/springamqp/SpringRabbitTestBuildCustomizerTests.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.dependency.springamqp; import io.spring.initializr.generator.buildsystem.Build; import io.spring.initializr.generator.buildsystem.Dependency; import io.spring.initializr.generator.buildsystem.DependencyScope; import io.spring.initializr.generator.buildsystem.maven.MavenBuild; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringRabbitTestBuildCustomizer}. * * @author <NAME> */ class SpringRabbitTestBuildCustomizerTests { @Test void customizeAddsSpringRabbitTest() { Build build = new MavenBuild(); new SpringRabbitTestBuildCustomizer().customize(build); assertThat(build.dependencies().ids()).containsOnly("spring-rabbit-test"); Dependency springRabbitTest = build.dependencies().get("spring-rabbit-test"); assertThat(springRabbitTest.getGroupId()).isEqualTo("org.springframework.amqp"); assertThat(springRabbitTest.getArtifactId()).isEqualTo("spring-rabbit-test"); assertThat(springRabbitTest.getScope()).isEqualTo(DependencyScope.TEST_COMPILE); } } <|start_filename|>start-client/src/components/utils/Version.js<|end_filename|> const strictRange = /\[(.*),(.*)\]/ const halfopenRightRange = /\[(.*),(.*)\)/ const halfopenLeftRange = /\((.*),(.*)\]/ const qualifiers = ['M', 'RC', 'BUILD-SNAPSHOT', 'RELEASE'] export const parseQualifier = version => { const qual = (version || '') .replace(/\d+/g, '') .replace(/\./g, ' ') .replace(/\s/g, '') return qualifiers.indexOf(qual) > -1 ? qual : 'RELEASE' } export const parseVersion = version => { const r = version.toString().split('.') if (r.length < 2) { return { version, } } return { version, short: `${r[0]}.${r[1]}.${r[2]}`, major: `${r[0]}.${r[1]}.x`, qualify: qualifiers.indexOf(parseQualifier(version)), minor: +r[2], } } export const compare = (a, b) => { let result const versionA = a.split('.') const versionB = b.split('.') if (versionA.length === 3) { versionA[3] = '' } if (versionB.length === 3) { versionB[3] = '' } for (let i = 0; i < 3; i += 1) { result = parseInt(versionA[i], 10) - parseInt(versionB[i], 10) if (result !== 0) { return result } } const qualify = version => qualifiers.indexOf(parseQualifier(version)) result = qualify(a) - qualify(b) if (result !== 0) { return result } return versionA[3].localeCompare(versionB[3]) } export const parseReleases = releases => { return releases.map(release => { const version = parseVersion(release.key) return version }) } export const isInRange = (version, range) => { if (!range) { return true } const strickMatch = range.match(strictRange) if (strickMatch) { return ( compare(strickMatch[1], version) <= 0 && compare(strickMatch[2], version) >= 0 ) } const horMatch = range.match(halfopenRightRange) if (horMatch) { return ( compare(horMatch[1], version) <= 0 && compare(horMatch[2], version) > 0 ) } const holMatch = range.match(halfopenLeftRange) if (holMatch) { return ( compare(holMatch[1], version) < 0 && compare(holMatch[2], version) >= 0 ) } return compare(range, version) <= 0 } export const rangeToText = range => { const strictMatch = range.match(strictRange) if (strictMatch) { return `>= ${strictMatch[1]} and <= ${strictMatch[2]}` } const horMatch = range.match(halfopenRightRange) if (horMatch) { return `>= ${horMatch[1]} and < ${horMatch[2]}` } const holMatch = range.match(halfopenLeftRange) if (holMatch) { return `> ${holMatch[1]} and <= ${holMatch[2]}` } return `>= ${range}` } export const getValidDependencies = (boot, dependencies) => { return dependencies .map(dep => { const compatibility = dep.versionRange ? isInRange(boot, dep.versionRange) : true if (!compatibility) { return null } return dep }) .filter(d => !!d) } <|start_filename|>start-client/src/components/common/explore/Explore.js<|end_filename|> import '../../../styles/explore.scss' import FileSaver from 'file-saver' import JSZip from 'jszip' import PropTypes from 'prop-types' import get from 'lodash.get' import React, { useContext, useEffect, useRef, useState } from 'react' import { CSSTransition, TransitionGroup } from 'react-transition-group' import { CopyToClipboard } from 'react-copy-to-clipboard' import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock' import { toast } from 'react-toastify' import Code from './Code' import Loading from './Loading' import Select from './Select' import Tree from './Tree' import useWindowsUtils from '../../utils/WindowsUtils' import { AppContext } from '../../reducer/App' import { createTree, findRoot } from '../../utils/Zip' function Explore({ open, onClose, projectName, blob }) { const [button, setButton] = useState('Copy') const [tree, setTree] = useState(null) const [selected, setSelected] = useState(null) const { dispatch, explore } = useContext(AppContext) const wrapper = useRef(null) const windowsUtils = useWindowsUtils() useEffect(() => { const load = async () => { try { const zipJs = new JSZip() const { files } = await zipJs.loadAsync(blob).catch(() => { throw Error(`Could not load the ZIP project.`) }) const path = `${findRoot({ files })}/` const result = await createTree(files, path, path, zipJs).catch(() => { throw Error(`Could not read the ZIP project.`) }) setSelected(result.selected) setTree(result.tree) } catch (e) { dispatch({ type: 'UPDATE', payload: { explore: false } }) toast.error(e.message) } } if (explore && blob) { load() } }, [explore, blob, dispatch]) useEffect(() => { if (get(wrapper, 'current') && open) { disableBodyScroll(get(wrapper, 'current')) } return () => { clearAllBodyScrollLocks() } }, [wrapper, open, selected, tree]) const onCopy = () => { setButton('Copied!') setTimeout(() => { setButton('Copy!') }, 3000) } const download = file => { const blobFile = new Blob([file.content], { type: 'text/plain;charset=utf-8', }) FileSaver.saveAs(blobFile, file.filename) } const downloadZip = () => { FileSaver.saveAs(blob, projectName) } const onEnded = () => { setTimeout(() => { setTree(null) setSelected(null) clearAllBodyScrollLocks() }, 350) } return ( <TransitionGroup component={null}> {open && ( <CSSTransition onExit={onEnded} classNames='explorer' timeout={500}> <div className='explorer'> {tree && selected ? ( <div className='colset-explorer'> <div className='left'> <div className='head'> <strong>{projectName}</strong> </div> <div className='explorer-content'> <Tree selected={selected} onClickItem={item => { setSelected(item) }} tree={tree} /> </div> </div> <div className='is-mobile explorer-select'> <Select selected={selected} onClickItem={item => { setSelected(item) }} tree={tree} /> </div> <div className='right'> {selected && ( <> <div className='head'> <div className='actions-file'> <a href='/#' onClick={e => { e.preventDefault() download(selected) }} className='button' > <span className='button-content' tabIndex='-1'> <span>Download</span> </span> </a> <CopyToClipboard onCopy={onCopy} text={get(selected, 'content', '')} > <a href='/#' onClick={e => { e.preventDefault() }} className='button' > <span className='button-content' tabIndex='-1'> <span>{button}</span> </span> </a> </CopyToClipboard> {get(selected, 'language') === 'markdown' && ( <> <a href='/#' onClick={e => { e.preventDefault() const newSelected = { ...selected } newSelected.force = !get( selected, 'force', false ) setSelected(newSelected) }} className='button' > <span className='button-content' tabIndex='-1'> <span> {get(selected, 'force', false) ? 'Preview' : 'View source'} </span> </span> </a> </> )} </div> </div> <div className='explorer-content' ref={wrapper}> <Code item={selected} onChange={() => {}} /> </div> </> )} </div> <div className='explorer-actions'> <a href='/#' onClick={e => { e.preventDefault() downloadZip() }} className='button' > <span className='button-content' tabIndex='-1'> <span>Download</span> <span className='secondary desktop-only'> {windowsUtils.symb} + ⏎ </span> </span> </a> <a href='/#' onClick={e => { e.preventDefault() onClose() }} className='button' > <span className='button-content' tabIndex='-1'> <span>Close</span> <span className='secondary desktop-only'>ESC</span> </span> </a> </div> </div> ) : ( <Loading onClose={onClose} /> )} </div> </CSSTransition> )} </TransitionGroup> ) } Explore.defaultProps = { projectName: '', blob: null, } Explore.propTypes = { open: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, projectName: PropTypes.string, blob: PropTypes.instanceOf(Blob), } export default Explore <|start_filename|>start-client/src/components/common/dependency/index.js<|end_filename|> export { default as DependencyDialog } from './Dialog' export { default as Dependency } from './Dependency' <|start_filename|>start-client/src/components/common/builder/Loading.js<|end_filename|> import React from 'react' import Actions from './Actions' import Control from './Control' import Placeholder from './Placeholder' export default function Loading() { return ( <> <div className='colset colset-main'> <div className='left'> <div className='colset'> <div className='left'> <Control text='Project'> <Placeholder type='radio' width='97px' /> <Placeholder type='radio' width='98px' /> </Control> </div> <div className='right'> <Control text='Language'> <Placeholder type='radio' width='30px' /> <Placeholder type='radio' width='36px' /> <Placeholder type='radio' width='40px' /> </Control> </div> </div> <Control text='Spring Boot'> <Placeholder type='radio' width='100px' /> <Placeholder type='radio' width='98px' /> <Placeholder type='radio' width='98px' /> <Placeholder type='radio' width='120px' /> <Placeholder type='radio' width='140px' /> <Placeholder type='radio' width='98px' /> </Control> <Control text='Project Metadata'> <div> <div className='control control-inline control-placeholder'> <span className='placeholder-label'>Group</span> <Placeholder type='input' /> </div> <div className='control control-inline control-placeholder'> <span className='placeholder-label'>Artifact</span> <Placeholder type='input' /> </div> <div className='control control-inline control-placeholder'> <span className='placeholder-label'>Name</span> <Placeholder type='input' /> </div> <div className='control control-inline control-placeholder'> <span className='placeholder-label'>Description</span> <Placeholder type='input' /> </div> <div className='control control-inline control-placeholder'> <span className='placeholder-label'>Package name</span> <Placeholder type='input' /> </div> <div className='control control-inline control-placeholder' style={{ height: 30 }} > <span className='placeholder-label' style={{ marginRight: 20 }}> Packaging </span> <Placeholder type='radio' width='20px' /> <Placeholder type='radio' width='20px' /> </div> <div className='control control-inline control-placeholder' style={{ height: 30 }} > <span className='placeholder-label' style={{ marginRight: 20 }}> Java </span> <Placeholder type='radio' width='12px' /> <Placeholder type='radio' width='12px' /> <Placeholder type='radio' width='12px' /> </div> </div> </Control> </div> <div className='right'> <div className='control'> <div className='dependency-header'> <span className='label'>Dependencies</span> <Placeholder className='placeholder-button-dep' type='button' /> </div> </div> </div> </div> <Actions> <Placeholder className='placeholder-button-submit' type='button' /> <Placeholder className='placeholder-button-explore' type='button' /> <Placeholder className='placeholder-button-share' type='button' /> </Actions> </> ) } <|start_filename|>start-client/src/components/common/form/Form.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' const Form = ({ onSubmit, children }) => ( <form className='form' onSubmit={onSubmit} autoComplete='off'> <input style={{ display: 'none' }} type='text' name='fakeusernameremembered' /> <input style={{ display: 'none' }} type='password' name='<PASSWORD>' /> {children} </form> ) Form.defaultProps = { children: null, } Form.propTypes = { onSubmit: PropTypes.func.isRequired, children: PropTypes.node, } export default Form <|start_filename|>start-client/src/components/utils/Theme.js<|end_filename|> import { useState } from 'react' function getTheme() { const isDarkConfig = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches const theme = localStorage.getItem('springtheme') if (!theme) { return isDarkConfig ? 'dark' : 'light' } return theme } export default function useTheme() { const [darkTheme] = useState(getTheme()) return darkTheme } <|start_filename|>start-client/src/components/common/layout/index.js<|end_filename|> export { default as Logo } from './Logo' export { default as Header } from './Header' export { default as SideLeft } from './SideLeft' export { default as SideRight } from './SideRight' <|start_filename|>start-site/src/main/java/io/spring/start/site/extension/dependency/lombok/LombokGradleBuildCustomizer.java<|end_filename|> /* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.start.site.extension.dependency.lombok; import io.spring.initializr.generator.buildsystem.DependencyScope; import io.spring.initializr.generator.buildsystem.gradle.GradleBuild; import io.spring.initializr.generator.spring.build.BuildCustomizer; import io.spring.initializr.metadata.Dependency; import io.spring.initializr.metadata.InitializrMetadata; /** * Complete the setup for Lombok with Gradle by adding Lombok with {@code compileOnly} * scope as well. * * @author <NAME> */ public class LombokGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private final InitializrMetadata metadata; public LombokGradleBuildCustomizer(InitializrMetadata metadata) { this.metadata = metadata; } @Override public void customize(GradleBuild build) { Dependency lombok = this.metadata.getDependencies().get("lombok"); build.dependencies().add("lombok-compileOnly", lombok.getGroupId(), lombok.getArtifactId(), DependencyScope.COMPILE_ONLY); } } <|start_filename|>start-client/src/components/common/builder/FieldError.js<|end_filename|> import PropTypes from 'prop-types' import React from 'react' function FieldError({ children }) { return ( <div className='control-error'> <p className='title'> <strong>{children}</strong> </p> </div> ) } FieldError.propTypes = { children: PropTypes.string.isRequired, } export default FieldError <|start_filename|>start-client/src/components/common/layout/SideRight.js<|end_filename|> import React, { useContext } from 'react' import { AppContext } from '../../reducer/App' import { IconMoon, IconSun } from '../icons' const SideRight = () => { const { dispatch, theme } = useContext(AppContext) return ( <div id='side-right'> <div className='side-container'> <div className='switch'> <a href='/' onClick={e => { e.preventDefault() dispatch({ type: 'UPDATE', payload: { theme: 'light', }, }) }} className={`button inverse top ${ theme === 'light' ? 'active' : '' }`} > <span className='button-content' tabIndex='-1'> <IconSun /> </span> </a> <a href='/' onClick={e => { e.preventDefault() dispatch({ type: 'UPDATE', payload: { theme: 'dark', }, }) }} className={`button inverse ${theme === 'dark' ? 'active' : ''}`} > <span className='button-content' tabIndex='-1'> <IconMoon /> </span> </a> </div> </div> </div> ) } export default SideRight
ZheSun88/start.spring.io
<|start_filename|>test/context.spec.js<|end_filename|> import chai, { expect } from 'chai'; import ApiModule from '../src'; describe('context.metadataKeys', () => { it('single module', () => { const request = new ApiModule({ metadatas: { interfaceA: { name: 'interfaceA', method: 'GET', url: '/test' } }, module: false }).getInstance().interfaceA; expect(request.context.metadataKeys).to.be.deep.equal(['interfaceA']); }); it('multiple module', () => { const request = new ApiModule({ metadatas: { modA: { interface: { name: 'modA', method: 'GET', url: '/test' } } }, module: true }).getInstance().modA.interface; expect(request.context.metadataKeys).to.be.deep.equal(['modA', 'interface']); }); }); describe('context should be reset in second calls', () => { it('data, error, response', () => { const apiMod = new ApiModule({ metadatas: { interfaceA: { name: 'interfaceA', method: 'GET', url: '/test' } }, module: false }); apiMod.useBefore((context, next) => { // set error on purpose context.setError('I am an Error occurred before real request'); context.setResponse({ data: 123 }); context.setAxiosOptions({ headers: { 'x-app': 1 } }); next(); }); const request = apiMod.getInstance().interfaceA; // first request request(); let collector = {}; apiMod.useBefore((context, next) => { collector = { data: context.data, response: context.response, responseError: context.responseError, axiosOptions: context.axiosOptions, } next(); }); const secondData = {}; request(secondData); expect(collector.data).to.be.equal(secondData); expect(collector.response).to.be.equal(null); expect(collector.responseError).to.be.equal(null); expect(collector.axiosOptions).to.be.deep.equal({}); }); }); <|start_filename|>test/middleware.spec.js<|end_filename|> import chai, { expect } from 'chai'; import utils from './utils'; import ApiModule from '../src'; describe('foreRequestMiddleware', () => { let server, apiModule; before('Setup server', done => { server = utils.createBounceServer(7788); server.on('listening', () => { done(); }); }); after('Stop and clean server', done => { server.on('close', () => { server = null; done(); }); server.close(); }); beforeEach(() => { apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788' }, metadatas: { test: { url: '/', method: 'post' }, testParams: { url: '/user/:id/{time}', method: 'get' } }, module: false }); }); afterEach(() => { apiModule.foreRequestHook = null; apiModule.postRequestHook = null; apiModule.fallbackHook = null; }); it('foreRequestMiddleWare set another data', async () => { const data = { body: { a: 1, b: 2 } }; const anotherData = { body: { c: 3, d: 4 } }; apiModule.useBefore((context, next) => { expect(context.responseError).to.be.equal(null); expect(context.data).to.be.equal(data); context.setData(anotherData); expect(context.data).to.be.equal(anotherData); next(); }); try { const res = await apiModule.getInstance().test(data); expect(res.data).to.be.not.deep.equal(data.body); expect(res.data).to.be.deep.equal(anotherData.body); } catch (err) { throw 'It should not go here' } }); it('request was success, but fore-request middleware set an error', async () => { const error = new Error('I am an error'); apiModule.useBefore((context, next) => { expect(context.responseError).to.be.equal(null); context.setError(error); expect(context.responseError).to.be.equal(error); next(); }); try { await apiModule.getInstance().test(); throw 'It should not go here'; } catch (err) { expect(err).to.be.equal(error); } }); it('the request was successful, but fore-request middleware passes an error in the `next` function', async () => { const error = new Error('I am an error'); apiModule.useBefore((context, next) => { expect(context.responseError).to.be.equal(null); next(error); expect(context.responseError).to.be.equal(error); }); try { await apiModule.getInstance().test(); throw 'It should not go here'; } catch (err) { expect(err).to.be.equal(error); } }); it('`next` function parameters will override response error', async () => { const error = new Error('An error'); const anotherError = 'An error'; apiModule.useBefore((context, next) => { expect(context.responseError).to.be.equal(null); context.setError(error); expect(context.responseError).to.be.equal(error); next(anotherError); }); try { await apiModule.getInstance().test(); } catch (err) { expect(err).to.be.not.equal(error); expect(err).to.be.match(new RegExp(anotherError)); } }); it('fore-request middleware set a new axios options', done => { const token = 'Basic ' + Buffer.from('I am a token').toString('base64'); apiModule.useBefore((context, next) => { context.setAxiosOptions({ baseURL: 'http://localhost:8877', headers: { 'authorization': token } }); next(); }); const server = utils.createServer(8877, (req, res) => { const authHeader = req.headers['authorization']; expect(authHeader).to.be.equal(token); server.on('close', () => { done(); }); server.close(); }); server.on('listening', async () => { try { await apiModule.getInstance().test(null); } catch (error) { throw 'It should not go here'; } }); }); it('fore-request middleware set axios options would be override by request axios options', async () => { apiModule.useBefore((context, next) => { context.setAxiosOptions({ baseURL: 'http://localhost:8877', headers: { 'x-custom-header': 'I am custom header' } }); next(); }); try { const res = await apiModule.getInstance().test(null, { baseURL: 'http://localhost:7788' }); expect(res).to.be.ok; expect(res.config.baseURL).to.be.equal('http://localhost:7788'); expect(res.config.headers['x-custom-header']).to.be.equal('I am custom header'); } catch (error) { console.error(error); throw 'It should not go here'; } }); it('context.baseURL and context.url', async () => { const baseURL = 'http://localhost:7788/api'; const id = 123; const now = Date.now(); apiModule.useBefore((context, next) => { expect(context.baseURL).to.be.equal(baseURL); expect(context.url).to.be.equal(`${baseURL}/user/${id}/${now}`); next(); }); const request = apiModule.getInstance().testParams; try { const res = await request( { params: { id, time: now } }, { baseURL } ); expect(res).to.be.ok; expect(res.config.url).to.be.equal(request.context.url); expect(res.config.baseURL).to.be.equal(request.context.baseURL); } catch (error) { console.log(error); throw 'It should not go here'; } }); it('fore-request middleware set illegal axios options', async () => { utils.overrideConsole(); apiModule.useBefore((context, next) => { const produceError = () => { context.setAxiosOptions(null); }; expect(produceError).to.throw(/configure axios options error/); next(); }); try { await apiModule.getInstance().test(); } catch (error) { console.error(error); } utils.recoverConsole(); }); it('error occurred in fore-request middleware', async () => { utils.overrideConsole(); apiModule.useBefore((context, next) => { throw 'I am an Error'; next(); }); try { await apiModule.getInstance().test(); } catch (error) { expect(error).to.be.match(/An error occurred in foreRequestMiddleWare/); } utils.recoverConsole(); }); it('error occurred in fore-request middleware, but request would send normally', async () => { apiModule.useBefore((context, next) => { throw 'I am an Error'; next(); }); try { const res = await apiModule.getInstance().test(); expect(res).to.be.ok; } catch (error) { throw 'It should not go here'; } }); }); describe('postRequestMiddleware', () => { let server, apiModule; before('Setup server', done => { server = utils.createServer(7788); server.on('listening', () => { done(); }); }); after('Stop and clean server', done => { server.on('close', () => { server = null; done(); }); server.close(); }); beforeEach(() => { apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788' }, metadatas: { test: { url: '/', method: 'get' } }, module: false }); }); afterEach(() => { apiModule.foreRequestHook = null; apiModule.postRequestHook = null; apiModule.fallbackHook = null; }); it('the request was successful, postRequestMiddleWare set another response', async () => { const anotherResponse = { code: 0, list: [] }; apiModule.useAfter((context, next) => { expect(context.responseError).to.be.equal(null); expect(context.response.data).to.be.deep.equal(utils.defaultServerRespose); context.response.data = anotherResponse; context.setResponse(context.response); expect(context.response.data).to.be.equal(anotherResponse); next(); }); try { const data = await apiModule.getInstance().test(); expect(data.data).to.be.not.equal(utils.defaultServerRespose); expect(data.data).to.be.equal(anotherResponse); } catch (err) { throw 'It should not go here' } }); it('the request was successful, post-request middleware passes an error in the `next` function', async () => { const error = new Error('I am an error'); apiModule.useAfter((context, next) => { expect(context.responseError).to.be.equal(null); expect(context.response.data).to.be.deep.equal(utils.defaultServerRespose); next(error); expect(context.responseError).to.be.equal(error); }); try { await apiModule.getInstance().test(); throw 'It should not go here'; } catch (err) { expect(err).to.be.equal(error); } }); it('error occurred in post-request middleware', async () => { try { apiModule.useAfter((context, next) => { throw 'I am an Error'; next(); }); await apiModule.getInstance().test(); } catch (error) { expect(error).to.be.match(/An error occurred in postRequestMiddleWare/); } }); it('error occurred in post-request middleware, but request would send normally', async () => { apiModule.useAfter((context, next) => { throw 'I am an Error'; next(); }); try { const res = await apiModule.getInstance().test(); expect(res).to.be.ok; } catch (error) { throw 'It should not go here'; } }); }); describe('fallbackMiddleware', () => { let server, apiModule; before('Setup server', done => { server = utils.createBounceServer(7788); server.on('listening', () => { done(); }); }); after('Stop and clean server', done => { server.on('close', () => { server = null; done(); }); server.close(); }); beforeEach(() => { apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788', timeout: 500 }, metadatas: { test: { url: '/', method: 'post' } }, module: false, console: true }); }); afterEach(() => { apiModule.foreRequestHook = null; apiModule.postRequestHook = null; apiModule.fallbackHook = null; }); it('fallback middleware set another error', async () => { const error = new Error('I am an error'); const serverResponse = { code: 500, message: 'Internal server error' }; apiModule.getAxios().interceptors.response.use(response => { if (response.data.code === 200) { return response.data.data; } else { return Promise.reject(response.data); } }); apiModule.useCatch((context, next) => { expect(context.responseError).to.be.not.equal(null); expect(context.responseError).to.be.deep.equal(serverResponse); context.setError(error); next(); }); try { await apiModule.getInstance().test({ body: serverResponse }); throw 'It should not go here'; } catch (err) { expect(err).to.be.not.equal(serverResponse); expect(err).to.be.equal(error); } }); it('fallback middleware `next` function parameters will override response error', async () => { const error = new Error('I am an error'); const anotherError = 'I am an error'; apiModule.getAxios().interceptors.response.use(response => { if (response.data.code === 200) { return response.data.data; } else { return Promise.reject(response.data); } }); apiModule.useCatch((context, next) => { expect(context.responseError).to.be.not.equal(null); context.setError(error); next(anotherError); }); try { await apiModule.getInstance().test({ body: { code: 500, message: 'Internal server error' } }); throw 'It should not go here'; } catch (err) { expect(err).to.be.not.equal(error); expect(err).to.be.an('Error'); expect(err).to.be.not.a('String'); expect(err).to.be.match(new RegExp(anotherError)); } }); it('request was success, and fallback middleware will not be called', async () => { apiModule.useCatch((context, next) => { throw 'It should not go here'; next(); }); try { const data = await apiModule.getInstance().test(); expect(data).to.be.ok; } catch (err) { throw 'It should not go here'; } }); it('error occurred in fallback middleware', async () => { try { apiModule.useBefore((context, next) => { context.setError('I am an error'); next(); }); apiModule.useCatch((context, next) => { throw 'I am an Error'; next(); }); await apiModule.getInstance().test(); throw 'It should not go here'; } catch (error) { console.log(error); expect(error).to.be.match(/I am an error/); } }); it('error occurred in fallback middleware, but request would send normally', async () => { try { apiModule.useCatch((context, next) => { throw 'I am an Error'; next(); }); const res = await apiModule.getInstance().test(); expect(res).to.be.ok; } catch (error) { throw 'It should not go here'; } }); it('default error handler', async () => { utils.overrideConsole(); apiModule.useCatch(null); try { const request = apiModule.getInstance().test; request.context.setAxiosOptions({ // typo on purpose baseURL: 'http://localhost:8877' }); request(); } catch (error) { console.log('error: ', error); expect(error).to.be.match(/\[ApiModule\] \[post \/\] failed with /); } utils.recoverConsole(); }); }); <|start_filename|>es/context.js<|end_filename|> import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var Context = /*#__PURE__*/function () { // Private members function Context(apiMetadata, options) { _classCallCheck(this, Context); _defineProperty(this, "_options", void 0); _defineProperty(this, "_metadata", void 0); _defineProperty(this, "_metadataKeys", ''); _defineProperty(this, "_data", null); _defineProperty(this, "_response", null); _defineProperty(this, "_responseError", null); _defineProperty(this, "_reqAxiosOpts", {}); _defineProperty(this, "_metaAxiosOpts", {}); this._metadata = apiMetadata; this._options = options; } /** * set request data * @param {any} data * @return {Context} */ _createClass(Context, [{ key: "setData", value: function setData(data) { this._data = data; return this; } /** * set response data * @param {any} response * @return {Context} */ }, { key: "setResponse", value: function setResponse(response) { this._response = response; return this; } /** * set response error * @param {any} error * @return {Context} */ }, { key: "setError", value: function setError(error) { this._responseError = error; return this; } /** * set single axios request options * @param {AxiosOptions} axiosOptions * @private */ }, { key: "_setRequestOptions", value: function _setRequestOptions(axiosOptions) { if (isObject(axiosOptions)) { this._reqAxiosOpts = axiosOptions; } else { console.error("[ApiModule] the request parameter, the parameter `".concat(axiosOptions, "` is not an object")); } return this; } /** * set axios options (Designed for invocation in middleware) * @param {*} axiosOptions * @public */ }, { key: "setAxiosOptions", value: function setAxiosOptions(axiosOptions) { if (isObject(axiosOptions)) { this._metaAxiosOpts = axiosOptions; } else { console.error("[ApiModule] configure axios options error, the parameter `".concat(axiosOptions, "` is not an object")); } return this; } }, { key: "metadata", get: function get() { return _objectSpread({}, this._metadata); } }, { key: "metadataKeys", get: function get() { return this._metadataKeys; } }, { key: "method", get: function get() { return this._metadata.method; } }, { key: "baseURL", get: function get() { return this.axiosOptions.baseURL || ''; } }, { key: "url", get: function get() { var url = this._metadata.url; var _ref = this.data || {}, params = _ref.params; if (isObject(params)) { // handle api like /a/:id/b/{param} return this.baseURL + url.replace(/\B(?::(\w+)|{(\w+)})/g, function () { return params[(arguments.length <= 1 ? undefined : arguments[1]) || (arguments.length <= 2 ? undefined : arguments[2])]; }); } else { return this.baseURL + url; } } }, { key: "data", get: function get() { return this._data; } }, { key: "response", get: function get() { return this._response; } }, { key: "responseError", get: function get() { return this._responseError; } }, { key: "axiosOptions", get: function get() { // request axios options > metadata axios options var _reqAxiosOpts = this._reqAxiosOpts, _metaAxiosOpts = this._metaAxiosOpts; return Object.assign({}, _metaAxiosOpts, _reqAxiosOpts); } }]); return Context; }(); export { Context as default }; function isObject(target) { return Object.prototype.toString.call(target) === '[object Object]'; } <|start_filename|>src/context.js<|end_filename|> export default class Context { // Private members _options; _metadata; _metadataKeys = ''; _data = null; _response = null; _responseError = null; _reqAxiosOpts = {}; _metaAxiosOpts = {}; constructor(apiMetadata, options) { this._metadata = apiMetadata; this._options = options; } /** * set request data * @param {any} data * @return {Context} */ setData(data) { this._data = data; return this; } /** * set response data * @param {any} response * @return {Context} */ setResponse(response) { this._response = response; return this; } /** * set response error * @param {any} error * @return {Context} */ setError(error) { this._responseError = error; return this; } /** * set single axios request options * @param {AxiosOptions} axiosOptions * @private */ _setRequestOptions(axiosOptions) { if (isObject(axiosOptions)) { this._reqAxiosOpts = axiosOptions; } else { console.error(`[ApiModule] the request parameter, the parameter \`${axiosOptions}\` is not an object`); } return this; } /** * set axios options (Designed for invocation in middleware) * @param {*} axiosOptions * @public */ setAxiosOptions(axiosOptions) { if (isObject(axiosOptions)) { this._metaAxiosOpts = axiosOptions; } else { console.error(`[ApiModule] configure axios options error, the parameter \`${axiosOptions}\` is not an object`); } return this; } get metadata() { return { ...this._metadata }; } get metadataKeys() { return this._metadataKeys; } get method() { return this._metadata.method; } get baseURL() { return this.axiosOptions.baseURL || ''; } get url() { const { url } = this._metadata; const { params } = this.data || {}; if (isObject(params)) { // handle api like /a/:id/b/{param} return this.baseURL + url .replace(/\B(?::(\w+)|{(\w+)})/g, (...args) => { return params[args[1] || args[2]]; }); } else { return this.baseURL + url; } } get data() { return this._data; } get response() { return this._response; } get responseError() { return this._responseError; } get axiosOptions() { // request axios options > metadata axios options const { _reqAxiosOpts, _metaAxiosOpts } = this; return Object.assign({}, _metaAxiosOpts, _reqAxiosOpts); } } function isObject(target) { return Object.prototype.toString.call(target) === '[object Object]'; } <|start_filename|>test/request.spec.js<|end_filename|> import chai, { expect } from 'chai'; import ApiModule from '../src'; import utils from './utils'; describe('request by baseConfig', () => { let config, apiModule, apiMapper; beforeEach('Setup ApiModule', () => { config = { baseURL: 'http://localhost:7788' }; apiModule = new ApiModule({ baseConfig: config, module: false, metadatas: { test: { url: '/api/test', method: 'post' } } }); apiMapper = apiModule.getInstance(); }); it('axios should get be configured right', () => { const axios = apiModule.getAxios(); expect(axios.defaults).to.have.contain(config); }); it('server should get right data package', done => { const postData = { body: { a: 1, b: 2 } }; const server = utils.createServer(7788, req => { let rawData = ''; req.on('data', chunk => rawData += chunk); req.on('end', () => { server.on('close', () => { done(); }); server.close(); const data = JSON.parse(rawData); expect(data).to.be.deep.equal(postData.body); }); }); server.on('listening', () => { apiMapper.test(postData); }); }); }); describe('api metadata mapper', () => { beforeEach(() => { utils.overrideConsole(); }); afterEach(() => { utils.recoverConsole(); }); it('api request mapper set non-object options', () => { const apiModule = new ApiModule({ module: false, metadatas: { test: { url: '/test', method: 'get' } } }); expect(() => apiModule.getInstance().test(null, null)).to.throw(/the request parameter/); }); it('test path parameter mode url', done => { const apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788' }, module: false, metadatas: { test: { url: '/api/{id}/:time/info', method: 'post' } } }); const apiMapper = apiModule.getInstance(); const id = 123; const time = Date.now(); const server = utils.createServer(7788, req => { server.on('close', () => { done(); }); console.log(req.url); expect(req.url).to.be.equal(`/api/${id}/${time}/info?o=calvin&v=von`); server.close(); }); server.on('listening', () => { apiMapper.test({ params: { id, time }, query: { o: 'calvin', v: 'von' } }); }) }); it('api request mapper options', done => { try { const apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788' }, module: false, metadatas: { test: { url: '/api/info', method: 'post' } } }); const apiMapper = apiModule.getInstance(); const server = utils.createServer(7788, req => { let rawData = ''; req.on('data', chunk => rawData += chunk); req.on('end', () => { server.on('close', () => { done(); }); expect(rawData).to.be.equal("{\"a\":1,\"b\":2}"); server.close(); }); }); server.on('listening', () => { apiMapper.test({ body: { a: 1, b: 2 } }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, baseURL: 'http://localhost:7788' }); }); } catch (error) { console.log(error) } }); }); describe('cancellation', () => { let server; before('Setup server', done => { server = utils.createServer(7788); server.on('listening', done); }); after('Stop and clean server', done => { server.on('close', () => { done(); }); server.close(); server = null; }); it('request cancellation', async () => { const apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788', timeout: 10000 }, module: false, metadatas: { test: { url: '/api/info', method: 'get' } } }); const apiMapper = apiModule.getInstance(); const cancelSource = apiModule.generateCancellationSource(); try { cancelSource.cancel('Canceled by the user'); await apiMapper.test( null, { cancelToken: cancelSource.token } ); } catch (error) { expect(error.message).to.be.equal('Canceled by the user'); } }); }); <|start_filename|>test/constructor.spec.js<|end_filename|> import chai, { expect } from 'chai'; import ApiModule from '../src'; describe('baseConfig', () => { it('options of instance contain original config', () => { const config = { baseConfig: { baseURL: 'http://api.yourdomain.com', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-test-header': 'api-module' }, withCredentials: true, timeout: 60000 }, console: false, module: false, metadatas: {} }; const apiModule = new ApiModule(config); expect(apiModule.options).to.be.contain(config); }); it('api mapper contains \'$module\' property that refs to ApiModule instance', () => { const apiModule = new ApiModule(); const apiMapper = apiModule.getInstance(); expect(apiMapper).to.has.ownProperty('$module'); expect(apiMapper['$module']).to.be.equal(apiModule); }); it('no modular namespace api metas', () => { const apiModule = new ApiModule({ module: false, metadatas: { test: { url: '/api/test', method: 'get' } } }); const apiMapper = apiModule.getInstance(); expect(apiMapper).to.have.all.keys('test'); }); it('multiple modular namespaces api metas', () => { const apiModule = new ApiModule({ module: true, metadatas: { main: { test: { url: '/api/test', method: 'get' } }, sub: { subTest: { url: '/sub/test', method: 'get' } } } }); const apiMapper = apiModule.getInstance(); expect(apiMapper).to.have.all.keys('main', 'sub').but.not.have.all.keys('test', 'subTest'); }); it('metadatas passing empty meta value should throw error', () => { const produceEmptyMeta = () => { new ApiModule({ module: false, metadatas: { test: {}, } }); }; const produceNullMeta = () => { new ApiModule({ module: false, metadatas: { other: null, } }); }; const produceUndefinedMeta = () => { new ApiModule({ module: false, metadatas: { another: undefined } }); }; expect(produceEmptyMeta).to.throw(Error, /api metadata \[(\w+)\]: 'method' or 'url' value not found/i); expect(produceNullMeta).to.throw(TypeError, /api metadata \[(\w+)\] is not an object/i); expect(produceUndefinedMeta).to.throw(TypeError, /api metadata \[(\w+)\] is not an object/i); }); it('one instance will return same instance of axios', () => { const apiModule = new ApiModule({ api: {} }); expect(apiModule.getAxios()).to.be.equal(apiModule.getAxios()); }); }); <|start_filename|>test/method.spec.js<|end_filename|> import chai, { expect } from 'chai'; import utils from './utils'; import ApiModule from '../src'; function cleanHooks() { ApiModule.foreRequestHook = null; ApiModule.postRequestHook = null; ApiModule.fallbackHook = null; } describe('useBefore methods', () => { let server; let testMetadata, testData, apiModule, apiMapper; before('Setup server', done => { server = utils.createServer(7788); server.on('listening', () => { done(); }); }); after('Stop and clean server', done => { server.on('close', () => { server = null; done(); }); cleanHooks(); server.close(); }); beforeEach(() => { testMetadata = { url: '/api/test', method: 'get', name: 'test middleware methods' }; testData = { query: { a: 1, b: 2 }, body: { c: 11, d: 22 } }; apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788' }, module: false, metadatas: { test: testMetadata } }); apiMapper = apiModule.getInstance(); }); afterEach(() => { cleanHooks(); }); it('static method globalBefore', async () => { ApiModule.globalBefore((context, next) => { expect(context.metadata).to.be.not.equal(testMetadata); expect(context.metadata).to.be.eql(testMetadata); expect(context.data).to.be.equal(testData); next(); }); await apiMapper.test(testData); }); it('instance method useBefore', async () => { apiModule.useBefore((context, next) => { expect(context.metadata).to.be.not.equal(testMetadata); expect(context.metadata).to.be.eql(testMetadata); expect(context.data).to.be.equal(testData); next(); }); await apiMapper.test(testData); }); it('instance method would override static method', async () => { apiModule.useBefore((context, next) => { expect(context).to.be.ok; next(); }); ApiModule.globalBefore((context, next) => { next(); }); await apiMapper.test(testData); }); it('static before method passing `null` would not throw an error', async () => { ApiModule.globalBefore(null); await apiMapper.test(testData); }); it('static before method passing `123` would not throw an error', async () => { ApiModule.globalBefore(123); await apiMapper.test(testData); }); it('static before method passing undefined would not throw an error', async () => { ApiModule.globalBefore(); await apiMapper.test(testData); }); it('instance before method passing undefined would not throw an error', async () => { apiModule.useBefore(); await apiMapper.test(testData); }); it('passed some error then reject the request', (done) => { apiModule.useBefore((context, next) => { next(new Error('some thing happened')); }); apiMapper.test(testData) .catch(err => { done(); }) }) }); describe('useAfter methods', () => { let server; let testMetadata, testData, apiModule, apiMapper; before('Setup server', done => { server = utils.createServer(7788, (req, res) => { let rawData = ''; req.on('data', chunk => rawData += chunk); req.on('end', () => { const data = JSON.parse(rawData); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ code: 200, data })); }); // prevent default response action return true; }); server.on('listening', () => { done(); }); }); after('Stop and clean server', done => { server.on('close', () => { server = null; done(); }); server.close(); cleanHooks(); }); beforeEach('Setup ApiModule', () => { testMetadata = { url: '/api/test', method: 'get', }; testData = { query: { a: 1, b: 2 }, body: { c: 11, d: 22 } }; apiModule = new ApiModule({ baseConfig: { baseURL: 'http://localhost:7788' }, module: false, metadatas: { test: testMetadata } }); apiMapper = apiModule.getInstance(); apiModule.getAxios().interceptors.response.use(response => { return response.data.data; }); }); afterEach('Clean ApiModule', () => { cleanHooks(); }); it('static after method globalAfter', async () => { ApiModule.globalAfter((context, next) => { expect(context.metadata).to.be.not.equal(testMetadata); expect(context.metadata).to.be.eql(testMetadata); next(); }); const res = await apiMapper.test(testData); expect(res).to.be.eql(testData.body); }); it('instance after method useAfter', async () => { apiModule.useAfter((context, next) => { expect(context.metadata).to.be.eql(testMetadata); next(); }); const res = await apiMapper.test(testData); expect(res).to.be.eql(testData.body); }); it('instance after method would override static method', async () => { apiModule.useAfter((context, next) => { next(); }); ApiModule.globalAfter((context, next) => { next(new Error('It should not go here.')); }); const res = await apiMapper.test(testData); expect(res).to.be.eql(testData.body); }); it('static after method passing `null` would not throw an errors', async () => { ApiModule.globalAfter(null); await apiMapper.test(testData); }); it('static after method passing `123` would not throw an error', async () => { ApiModule.globalAfter(123); await apiMapper.test(testData); }); it('static after method passing undefined would not throw an error', async () => { ApiModule.globalAfter(); await apiMapper.test(testData); }); it('instance after method passing undefined would not throw an error', async () => { apiModule.useAfter(); await apiMapper.test(testData); }); }); describe('useCatch methods', () => { let server; let testMetadata, testData, apiModule, apiMapper; before('Setup server', done => { server = utils.createServer(7788); server.on('listening', () => { done(); }); }); after('Stop and clean server', done => { server.on('close', () => { server = null; done(); }); server.close(); cleanHooks(); }); beforeEach('Setup ApiModule', () => { testMetadata = { url: '/api/test', method: 'get', name: 'test middleware methods' }; testData = { query: { a: 1, b: 2 }, body: { c: 11, d: 22 } }; apiModule = new ApiModule({ baseConfig: { // a typo error on purpose baseURL: 'http://localhost:7789', timeout: 0 }, module: false, console: true, metadatas: { test: testMetadata } }); apiMapper = apiModule.getInstance(); }); afterEach('Clean ApiModule', () => { cleanHooks(); }); it('static catch method useCatch', async () => { const middlewareError = new Error('I made a mistake'); ApiModule.globalBefore((context, next) => { // context.setError(); next(middlewareError); }); ApiModule.globalCatch((context, next) => { expect(context.metadata).to.be.deep.equal(testMetadata); expect(context.data).to.be.deep.equal(testData); expect(context.responseError).to.be.equal(middlewareError); next(); }); try { await apiMapper.test(testData); } catch (error) { expect(error).to.be.equal(middlewareError); } }); it('instance catch method useCatch', async () => { const middlewareError = new Error('I made a mistake'); apiModule.useBefore((context, next) => { // context.setError(); next(middlewareError); }); apiModule.useCatch((context, next) => { expect(context.metadata).to.be.deep.equal(testMetadata); expect(context.data).to.be.deep.equal(testData); expect(context.responseError).to.be.equal(middlewareError); next(); }); try { await apiMapper.test(testData); } catch (error) { expect(error).to.be.equal(middlewareError); } }); it('instance catch method would override static method', async () => { const error = new Error('A mistake'); const anthorError = new Error('Anthor mistake'); apiModule.useBefore((context, next) => { next(error); }); apiModule.useCatch((context, next) => { expect(context.responseError).to.be.equal(error); context.setError(anthorError); next(); }); ApiModule.globalCatch((context, next) => { throw 'It should not go here'; next(); }); try { await apiMapper.test(testData); } catch (err) { expect(err).to.be.equal(anthorError); expect(err).to.be.not.equal(error); } }); it('static catch method passing `null` would not throw an error', async () => { ApiModule.globalCatch(null); apiModule.useBefore((context, next) => { next('error'); }); try { apiMapper.test(testData) expect(1).to.be.ok; } catch (error) { throw 'It should not go here'; } }); it('static catch method passing `123` would not throw an error', async () => { ApiModule.globalCatch(123); apiModule.useBefore((context, next) => { next('error'); }); try { apiMapper.test(testData) expect(1).to.be.ok; } catch (error) { throw 'It should not go here'; } }); it('static catch method passing undefined would not throw an error', async () => { ApiModule.globalCatch(); apiModule.useBefore((context, next) => { next('error'); }); try { apiMapper.test(testData) expect(1).to.be.ok; } catch (error) { throw 'It should not go here'; } }); it('instance catch method passing undefined would not throw an error', async () => { apiModule.useCatch(); expect(true).to.be.ok; }); }); <|start_filename|>lib/index.js<|end_filename|> (function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "./api-module"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("./api-module")); } else { var mod = { exports: {} }; factory(mod.exports, global.apiModule); global.index = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _apiModule) { "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(_exports, "__esModule", { value: true }); _exports.default = void 0; _apiModule = _interopRequireDefault(_apiModule); var _default = _apiModule.default; _exports.default = _default; module.exports = exports.default; }); <|start_filename|>src/api-module.js<|end_filename|> import axios from 'axios'; import Context from './context'; const defaultMiddleware = (context, next) => next(context.responseError); /** * Api Module class * * @static {Function} foreRequestHook * @static {Function} postRequestHook * @static {Function} fallbackHook * * @member {Object} options * @member {Function} foreRequestHook * @member {Function} postRequestHook * @member {Function} fallbackHook * * @method useBefore(hook) * @method useAfter(hook) * @method useCatch(hook) * @method getAxios() * @method getInstance() * @method generateCancellationSource() get axios cancellation source for cancel api */ export default class ApiModule { static foreRequestHook; static postRequestHook; static fallbackHook; options = {}; apiMapper; foreRequestHook; postRequestHook; fallbackHook; constructor(config = {}) { const { metadatas = {}, module: modularNsp, console: useConsole = true, baseConfig = {}, } = config; this.options = { axios: axios.create(baseConfig), metadatas, module: modularNsp, console: useConsole, baseConfig }; this.apiMapper = {}; if (modularNsp) { // moduled namespace Object.keys(metadatas).forEach(apiName => { this.apiMapper[apiName] = this._proxyable(metadatas[apiName], apiName); }); } else { // single module this.apiMapper = this._proxyable(metadatas); } Object.defineProperty(this.apiMapper, '$module', { configurable: false, enumerable: false, writable: false, value: this }); } /** * Register fore-request middleWare globally (for all instances) * @param {Function} foreRequestHook(context, next) */ static globalBefore(foreRequestHook = defaultMiddleware) { ApiModule.foreRequestHook = foreRequestHook; } /** * Register post-request middleware globally (for all instances) * @param {Function} foreRequestHook(apiMeta, data = {}, next) */ static globalAfter(postRequestHook = defaultMiddleware) { ApiModule.postRequestHook = postRequestHook; } /** * Register fallback MiddleWare Globally (For All Instance) * @param {Function} fallbackHook(apiMeta, data = {}, next) */ static globalCatch(fallbackHook = defaultMiddleware) { ApiModule.fallbackHook = fallbackHook; } /** * Registe Fore-Request MiddleWare * @param {Function} foreRequestHook(apiMeta, data = {}, next) */ useBefore(foreRequestHook = defaultMiddleware) { this.foreRequestHook = foreRequestHook; } /** * Registe Post-Request MiddleWare * @param {Function} foreRequestHook(apiMeta, data = {}, next) */ useAfter(postRequestHook = defaultMiddleware) { this.postRequestHook = postRequestHook; } /** * Registe Fallback MiddleWare * @param {Function} fallbackHook(apiMeta, data = {}, next) */ useCatch(fallbackHook = defaultMiddleware) { this.fallbackHook = fallbackHook; } /** * get axios cancellation source for cancel api * @returns {CancelTokenSource} */ generateCancellationSource() { return axios.CancelToken.source(); } /** * @returns {Axios} get instance of Axios */ getAxios() { return this.options.axios; } /** * @returns {Object} get instance of api metadata mapper */ getInstance() { return this.apiMapper; } /** * fore-request middleware * @param {Context} context * @param {Function} next */ foreRequestMiddleWare(context, next) { const hookFunction = this.foreRequestHook || ApiModule.foreRequestHook || defaultMiddleware; if (typeof hookFunction === 'function') { try { hookFunction.call(this, context, next); } catch (error) { console.error('[ApiModule] An error occurred in foreRequestMiddleWare: ', error); next(); } } else { console.warn(`[ApiModule] foreRequestMiddleWare: ${hookFunction} is not a valid foreRequestHook function`); next(); } } /** * post-request middleware * @param {Context} context * @param {Function} next */ postRequestMiddleWare(context, next) { const hookFunction = this.postRequestHook || ApiModule.postRequestHook || defaultMiddleware; if (typeof hookFunction === 'function') { try { hookFunction.call(this, context, next); } catch (error) { console.error('[ApiModule] An error occurred in postRequestMiddleWare: ', error); next(); } } else { console.warn(`[ApiModule] postRequestMiddleWare: ${hookFunction} is not a valid foreRequestHook function`); next(); } } /** * fallback middleWare * @param {Context} context * @param {Function} next */ fallbackMiddleWare(context, next) { const defaultErrorHandler = () => { if (this.options.console) { const { method, url } = context.metadata; const msg = `[ApiModule] [${method.toUpperCase()} ${url}] failed with ${error.message}`; console.error(new Error(msg)); } next(); }; const error = context.responseError; const hookFunction = this.fallbackHook || ApiModule.fallbackHook || defaultErrorHandler; if (typeof hookFunction === 'function') { try { hookFunction.call(this, context, next); } catch (error) { console.error('[ApiModule] An error occurred in fallbackMiddleWare: ', error); next(); } } else { console.warn(`[ApiModule] fallbackMiddleWare: ${hookFunction} is not a valid fallbackHook function`); defaultErrorHandler(); } } // tranfer single module api meta info to request _proxyable(target, apiName) { const _target = {}; for (const key in target) { if (target.hasOwnProperty(key)) { _target[key] = this._proxyApiMetadata(target, key, apiName); } } return _target; } // map api meta to to request _proxyApiMetadata(target, key, parentKey) { const metadata = target[key]; if (Object.prototype.toString.call(metadata) !== '[object Object]') { throw new TypeError(`[ApiModule] api metadata [${key}] is not an object`); } const context = new Context(metadata, this.options); context._metadataKeys = [parentKey, key].filter(Boolean); if (!context.url || !context.method) { console.warn(`[ApiModule] check your api metadata for [${key}]: `, metadata); throw new Error(`[ApiModule] api metadata [${key}]: 'method' or 'url' value not found`); } /** * Collect errors and set errors uniformly. Returns if there is an error * @param {Error|any} err * @return {Boolean} */ const handleResponseError = err => { const error = err || context.responseError; if (!error) return false; if (error instanceof Error) { context.setError(error); } else if (typeof error === 'string') { context.setError(new Error(error)); } else { context.setError(error); } return true; }; const request = (data, opt = {}) => { context .setError(null) .setResponse(null) .setAxiosOptions({}) .setData(data) ._setRequestOptions(opt); return new Promise((resolve, reject) => { this.foreRequestMiddleWare(context, err => { if (handleResponseError(err)) { this.fallbackMiddleWare(context, () => { reject(context.responseError); }); } else { const { query = {}, body = {} } = context.data || {}; const config = Object.assign( {}, { method: context.method.toLowerCase(), url: context.url, params: query, data: body, }, context.axiosOptions ); this.options.axios(config) .then(res => { context.setResponse(res); this.postRequestMiddleWare(context, err => { if (handleResponseError(err)) { throw context.responseError; } resolve(context.response); }); }) .catch(error => { handleResponseError(error); this.fallbackMiddleWare(context, err => { handleResponseError(err); reject(context.responseError); }); }); } }) }) }; request.context = context; return request; } } <|start_filename|>test/utils.js<|end_filename|> import http from 'http'; const originConsole = { log: console.log, warn: console.warn, error: console.error, }; export default { /** * @param {Number} port * @param {Function} callback stop default response action when return true */ createServer(port, callback = new Function()) { return http.createServer((req, res) => { if (callback(req, res)) { return; } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(this.defaultServerRespose)); }).listen(port); }, /** * Respond to the data that request * @param {Number} port */ createBounceServer(port) { return http.createServer((req, res) => { let rawData = ''; req.on('data', chunk => rawData += chunk); req.on('end', () => { const data = JSON.parse(rawData); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(data)); }); }).listen(port); }, defaultServerRespose: { code: 200, msg: 'success' }, overrideConsole() { console.warn = txt => { throw txt; } console.error = txt => { throw txt; } }, recoverConsole() { console.log = originConsole.log; console.warn = originConsole.warn; console.error = originConsole.error; } } <|start_filename|>lib/api-module.js<|end_filename|> (function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "@babel/runtime/helpers/classCallCheck", "@babel/runtime/helpers/createClass", "@babel/runtime/helpers/defineProperty", "axios", "./context"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("@babel/runtime/helpers/classCallCheck"), require("@babel/runtime/helpers/createClass"), require("@babel/runtime/helpers/defineProperty"), require("axios"), require("./context")); } else { var mod = { exports: {} }; factory(mod.exports, global.classCallCheck, global.createClass, global.defineProperty, global.axios, global.context); global.apiModule = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _classCallCheck2, _createClass2, _defineProperty2, _axios, _context) { "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(_exports, "__esModule", { value: true }); _exports.default = void 0; _classCallCheck2 = _interopRequireDefault(_classCallCheck2); _createClass2 = _interopRequireDefault(_createClass2); _defineProperty2 = _interopRequireDefault(_defineProperty2); _axios = _interopRequireDefault(_axios); _context = _interopRequireDefault(_context); var defaultMiddleware = function defaultMiddleware(context, next) { return next(context.responseError); }; /** * Api Module class * * @static {Function} foreRequestHook * @static {Function} postRequestHook * @static {Function} fallbackHook * * @member {Object} options * @member {Function} foreRequestHook * @member {Function} postRequestHook * @member {Function} fallbackHook * * @method useBefore(hook) * @method useAfter(hook) * @method useCatch(hook) * @method getAxios() * @method getInstance() * @method generateCancellationSource() get axios cancellation source for cancel api */ var ApiModule = /*#__PURE__*/function () { function ApiModule() { var _this = this; var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _classCallCheck2.default)(this, ApiModule); (0, _defineProperty2.default)(this, "options", {}); (0, _defineProperty2.default)(this, "apiMapper", void 0); (0, _defineProperty2.default)(this, "foreRequestHook", void 0); (0, _defineProperty2.default)(this, "postRequestHook", void 0); (0, _defineProperty2.default)(this, "fallbackHook", void 0); var _config$metadatas = config.metadatas, metadatas = _config$metadatas === void 0 ? {} : _config$metadatas, modularNsp = config.module, _config$console = config.console, useConsole = _config$console === void 0 ? true : _config$console, _config$baseConfig = config.baseConfig, baseConfig = _config$baseConfig === void 0 ? {} : _config$baseConfig; this.options = { axios: _axios.default.create(baseConfig), metadatas: metadatas, module: modularNsp, console: useConsole, baseConfig: baseConfig }; this.apiMapper = {}; if (modularNsp) { // moduled namespace Object.keys(metadatas).forEach(function (apiName) { _this.apiMapper[apiName] = _this._proxyable(metadatas[apiName], apiName); }); } else { // single module this.apiMapper = this._proxyable(metadatas); } Object.defineProperty(this.apiMapper, '$module', { configurable: false, enumerable: false, writable: false, value: this }); } /** * Register fore-request middleWare globally (for all instances) * @param {Function} foreRequestHook(context, next) */ (0, _createClass2.default)(ApiModule, [{ key: "useBefore", /** * Registe Fore-Request MiddleWare * @param {Function} foreRequestHook(apiMeta, data = {}, next) */ value: function useBefore() { var foreRequestHook = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMiddleware; this.foreRequestHook = foreRequestHook; } /** * Registe Post-Request MiddleWare * @param {Function} foreRequestHook(apiMeta, data = {}, next) */ }, { key: "useAfter", value: function useAfter() { var postRequestHook = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMiddleware; this.postRequestHook = postRequestHook; } /** * Registe Fallback MiddleWare * @param {Function} fallbackHook(apiMeta, data = {}, next) */ }, { key: "useCatch", value: function useCatch() { var fallbackHook = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMiddleware; this.fallbackHook = fallbackHook; } /** * get axios cancellation source for cancel api * @returns {CancelTokenSource} */ }, { key: "generateCancellationSource", value: function generateCancellationSource() { return _axios.default.CancelToken.source(); } /** * @returns {Axios} get instance of Axios */ }, { key: "getAxios", value: function getAxios() { return this.options.axios; } /** * @returns {Object} get instance of api metadata mapper */ }, { key: "getInstance", value: function getInstance() { return this.apiMapper; } /** * fore-request middleware * @param {Context} context * @param {Function} next */ }, { key: "foreRequestMiddleWare", value: function foreRequestMiddleWare(context, next) { var hookFunction = this.foreRequestHook || ApiModule.foreRequestHook || defaultMiddleware; if (typeof hookFunction === 'function') { try { hookFunction.call(this, context, next); } catch (error) { console.error('[ApiModule] An error occurred in foreRequestMiddleWare: ', error); next(); } } else { console.warn("[ApiModule] foreRequestMiddleWare: ".concat(hookFunction, " is not a valid foreRequestHook function")); next(); } } /** * post-request middleware * @param {Context} context * @param {Function} next */ }, { key: "postRequestMiddleWare", value: function postRequestMiddleWare(context, next) { var hookFunction = this.postRequestHook || ApiModule.postRequestHook || defaultMiddleware; if (typeof hookFunction === 'function') { try { hookFunction.call(this, context, next); } catch (error) { console.error('[ApiModule] An error occurred in postRequestMiddleWare: ', error); next(); } } else { console.warn("[ApiModule] postRequestMiddleWare: ".concat(hookFunction, " is not a valid foreRequestHook function")); next(); } } /** * fallback middleWare * @param {Context} context * @param {Function} next */ }, { key: "fallbackMiddleWare", value: function fallbackMiddleWare(context, next) { var _this2 = this; var defaultErrorHandler = function defaultErrorHandler() { if (_this2.options.console) { var _context$metadata = context.metadata, method = _context$metadata.method, url = _context$metadata.url; var msg = "[ApiModule] [".concat(method.toUpperCase(), " ").concat(url, "] failed with ").concat(error.message); console.error(new Error(msg)); } next(); }; var error = context.responseError; var hookFunction = this.fallbackHook || ApiModule.fallbackHook || defaultErrorHandler; if (typeof hookFunction === 'function') { try { hookFunction.call(this, context, next); } catch (error) { console.error('[ApiModule] An error occurred in fallbackMiddleWare: ', error); next(); } } else { console.warn("[ApiModule] fallbackMiddleWare: ".concat(hookFunction, " is not a valid fallbackHook function")); defaultErrorHandler(); } } // tranfer single module api meta info to request }, { key: "_proxyable", value: function _proxyable(target, apiName) { var _target = {}; for (var key in target) { if (target.hasOwnProperty(key)) { _target[key] = this._proxyApiMetadata(target, key, apiName); } } return _target; } // map api meta to to request }, { key: "_proxyApiMetadata", value: function _proxyApiMetadata(target, key, parentKey) { var _this3 = this; var metadata = target[key]; if (Object.prototype.toString.call(metadata) !== '[object Object]') { throw new TypeError("[ApiModule] api metadata [".concat(key, "] is not an object")); } var context = new _context.default(metadata, this.options); context._metadataKeys = [parentKey, key].filter(Boolean); if (!context.url || !context.method) { console.warn("[ApiModule] check your api metadata for [".concat(key, "]: "), metadata); throw new Error("[ApiModule] api metadata [".concat(key, "]: 'method' or 'url' value not found")); } /** * Collect errors and set errors uniformly. Returns if there is an error * @param {Error|any} err * @return {Boolean} */ var handleResponseError = function handleResponseError(err) { var error = err || context.responseError; if (!error) return false; if (error instanceof Error) { context.setError(error); } else if (typeof error === 'string') { context.setError(new Error(error)); } else { context.setError(error); } return true; }; var request = function request(data) { var opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; context.setError(null).setResponse(null).setAxiosOptions({}).setData(data)._setRequestOptions(opt); return new Promise(function (resolve, reject) { _this3.foreRequestMiddleWare(context, function (err) { if (handleResponseError(err)) { _this3.fallbackMiddleWare(context, function () { reject(context.responseError); }); } else { var _ref = context.data || {}, _ref$query = _ref.query, query = _ref$query === void 0 ? {} : _ref$query, _ref$body = _ref.body, body = _ref$body === void 0 ? {} : _ref$body; var config = Object.assign({}, { method: context.method.toLowerCase(), url: context.url, params: query, data: body }, context.axiosOptions); _this3.options.axios(config).then(function (res) { context.setResponse(res); _this3.postRequestMiddleWare(context, function (err) { if (handleResponseError(err)) { throw context.responseError; } resolve(context.response); }); }).catch(function (error) { handleResponseError(error); _this3.fallbackMiddleWare(context, function (err) { handleResponseError(err); reject(context.responseError); }); }); } }); }); }; request.context = context; return request; } }], [{ key: "globalBefore", value: function globalBefore() { var foreRequestHook = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMiddleware; ApiModule.foreRequestHook = foreRequestHook; } /** * Register post-request middleware globally (for all instances) * @param {Function} foreRequestHook(apiMeta, data = {}, next) */ }, { key: "globalAfter", value: function globalAfter() { var postRequestHook = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMiddleware; ApiModule.postRequestHook = postRequestHook; } /** * Register fallback MiddleWare Globally (For All Instance) * @param {Function} fallbackHook(apiMeta, data = {}, next) */ }, { key: "globalCatch", value: function globalCatch() { var fallbackHook = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMiddleware; ApiModule.fallbackHook = fallbackHook; } }]); return ApiModule; }(); _exports.default = ApiModule; (0, _defineProperty2.default)(ApiModule, "foreRequestHook", void 0); (0, _defineProperty2.default)(ApiModule, "postRequestHook", void 0); (0, _defineProperty2.default)(ApiModule, "fallbackHook", void 0); module.exports = exports.default; });
CalvinVon/axios-api-module
<|start_filename|>source/cheer_list.json<|end_filename|> [ "Cheer", "DoodleCheer", "BibleThump", "cheerwhal", "Corgo", "uni", "ShowLove", "Party", "SeemsGood", "Pride", "Kappa", "FrankerZ", "HeyGuys", "DansGame", "EleGiggle", "TriHard", "Kreygasm", "4Head", "SwiftRage", "NotLikeThis", "FailFish", "VoHiYo", "PJSalt", "MrDestructoid", "bday", "RIPCheer", "Shamrock", "BitBoss", "Streamlabs", "Muxy", "HolidayCheer", "Goal", "Anon" ]
feelsogood0705/dcconfeelsogood
<|start_filename|>examples/popups.js<|end_filename|> document.addEventListener('DOMContentLoaded', function (event) { var button = document.querySelector('.animate-slide'), closeButton = document.querySelector('.animation-container__close'), radios = document.getElementsByName('animation'), animationTypeSpan = document.querySelectorAll('[data-animation-type]'), select = document.getElementById('animation-select'), mainBlock = document.querySelector('[data-block="out"]'), customOverlay = document.querySelector('.custom-overlay'), container = '.animation-container', popup = '[data-block="in"]', animation, showOverlay, radioButtonValue; function animateBlocks(event) { showOverlay = document.getElementById('is_overlay').checked; if (getComputedStyle(document.getElementById('animation-list')).display !== 'none') { animation = document.querySelector('input[type=radio]:checked').getAttribute('id'); } else { if (getComputedStyle(document.getElementById('animation-select')).display !== 'none') { animation = select.options[select.selectedIndex].value; } } document.querySelector(popup).setAttribute('data-type', 'popup'); AnimateTransition({ container: container, blockIn: popup, animation: animation, onTransitionStart: function (blockIn, blockOut, container, event) { button.setAttribute('disabled', 'disabled'); mainBlock.style.backgroundImage = 'none'; if (showOverlay) { customOverlay.style.display = 'block'; } }, onTransitionEnd: function (blockIn, blockOut, container, event) { } }); } button.addEventListener('click', animateBlocks); /** * Closes popup * @param {Event} event */ function closePopup(event) { animation = animation.replace(/-in([^-in]*)$/, '-out$1'); showOverlay = document.getElementById('is_overlay').checked; AnimateTransition({ container: container, blockOut: popup, animation: animation, showOverlay: showOverlay, onTransitionEnd: function (blockIn, blockOut, container, event) { container.appendChild(blockOut); button.removeAttribute('disabled'); blockOut.removeAttribute('data-type'); mainBlock.style.backgroundImage = ''; if (showOverlay) { customOverlay.style.display = 'none'; } } }); } closeButton.addEventListener('click', closePopup); /** * Changes animation type in code example on radio button click * @param {Event} event */ function radioClick(event) { radioButtonValue = event.target.id; for (var index = 0; index < animationTypeSpan.length; index += 1) { animationTypeSpan[index].innerText = "'" + radioButtonValue + "'"; } } for (var index = 0; index < radios.length; index += 1) { radios[index].addEventListener('click', radioClick); } }); <|start_filename|>animateTransition_original.js<|end_filename|> var animateTransition = (function(){ "use strict"; var prefixes = ["webkit", "moz", "MS", "o", ""], overlay = document.createElement('div'); overlay.className = 'transition-overlay'; // Utils function showOverlay() { document.body.appendChild(overlay); } function hideOverlay() { if (overlay.parentNode) { document.body.removeChild(overlay); } } function getElement(selector) { if (!selector) { return null; } return selector.tagName ? selector : document.querySelector(selector); } function addPrefixedEvent(element, eventName, callback) { for (var i = 0; i < prefixes.length; i++) { if (!prefixes[i]) { eventName = eventName.toLowerCase(); } element.addEventListener(prefixes[i]+eventName, callback, false); } } function removePrefixedEvent(element, eventName, callback) { for (var i = 0; i < prefixes.length; i++) { if (!prefixes[i]) { eventName = eventName.toLowerCase(); } element.removeEventListener(prefixes[i]+eventName, callback, false); } } function hasClass(obj,cname) { return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false); } function addClass(obj,cname) { if (obj && !hasClass(obj,cname)) { obj.className += " "+cname; } } function removeClass(obj,cname) { if (obj && hasClass(obj,cname)) { obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(?=\\s|$)'),''); } } function getFakeEventObj(name) { return { type: 'fake', animationName: name || 'none', stopPropagation: function() {} } } function pagesTransition(options) { var container, pageIn, pageOut, animationName, pageInClassName, pageOutClassName, transitionTypeName, beforeTransition, onTransitionStart, onTransitionEnd, timer, timeOut = 3500; // initialize options options = options || {}; container = getElement(options.container) || document.body; pageIn = getElement(options.pageIn); pageOut = getElement(options.pageOut); animationName = options.animation || 'none'; beforeTransition = options.beforeTransition || function() {}; onTransitionStart = options.onTransitionStart || function() {}; onTransitionEnd = options.onTransitionEnd || function() {}; pageInClassName = animationName + '-transition-view-to-show'; pageOutClassName = animationName + '-transition-view-to-hide'; transitionTypeName = 'transition-' + animationName; if (pageIn === pageOut) { return; } // Stop animation if any of pages still in animation process if ( (pageIn && pageIn.busy) || (pageOut && pageOut.busy)) { window.console.log("You try apply new animation cannot be applied to the same element until previous animation is not finished."); } // You can use beforeTransition callback to define extra logic. // If result of the callback will be false then pages transition will be aborted. if (beforeTransition && beforeTransition(pageIn, pageOut, container) === false) { return; } // Init onAnimationStart event handler function onAnimationStart(e) { if (e.animationName !== animationName) { return; } onTransitionStart(pageIn, pageOut, container, e); removePrefixedEvent(container, 'AnimationStart', onAnimationStart); } addPrefixedEvent(container, 'AnimationStart', onAnimationStart); // Init onAnimationEnd event handler function onAnimationEnd(e) { if (e.animationName !== animationName) { return; } e.stopPropagation(); if (pageIn) { pageIn.busy = false; } if (pageOut) { pageOut.busy = false; if(pageOut.parentNode === container){ container.removeChild(pageOut); } removeClass(pageOut, pageOutClassName); } onTransitionEnd(pageIn, pageOut, container, e); removeClass(container, transitionTypeName); removeClass(pageIn, pageInClassName); if (timer) { clearTimeout(timer); } hideOverlay(); removePrefixedEvent(container, 'AnimationEnd', onAnimationEnd); } addPrefixedEvent(container, 'AnimationEnd', onAnimationEnd); // If animation was not set - show new page without transition if (animationName === 'none') { if (pageIn) { container.appendChild(pageIn); } onTransitionStart(pageIn, pageOut, container, getFakeEventObj()); if (pageOut) { try { container.removeChild(pageOut); } catch (err) { window.console.log('You try apply new animation without subject'); } onTransitionEnd(pageIn, pageOut, container, getFakeEventObj()); } else { onTransitionEnd(pageIn, pageOut, container, getFakeEventObj()); } return; } // Init pages transition: // ---------------------- // Prepare new page for transition. if (pageIn) { pageIn.busy = true; addClass(pageIn, pageInClassName); container.appendChild(pageIn); // we don't need pageOut.offsetHeight; because we add it with css class } if (pageOut) { pageOut.busy = true; addClass(pageOut, pageOutClassName); pageOut.offsetHeight; // plz don't delete it - it hack } // Enable overlay layer to protect from accidental clicks until animation ends showOverlay(); // Set timeout for case if onAnimationEnd event will not occur timer = window.setTimeout(function() { onAnimationEnd( getFakeEventObj(animationName) ); }, timeOut); // Add predefined CSS class to start CSS animation addClass(container, transitionTypeName); } return pagesTransition; }()); if (typeof exports !== "undefined") { exports.module = animateTransition; } <|start_filename|>examples/blocks.js<|end_filename|> document.addEventListener('DOMContentLoaded', function (event) { var button = document.querySelector('.animate-slide'), radios = document.getElementsByName('animation'), container = '.animation-container', blockIn = '[data-block="in"]', blockOut = '[data-block="out"]', select = document.getElementById('animation-select'), animationTypeSpan = document.querySelectorAll('[data-animation-type]'), radioButtonValue, animation; function animateBlocks(event) { if (getComputedStyle(document.getElementById('animation-list')).display !== 'none') { animation = document.querySelector('input[type=radio]:checked').getAttribute('id'); } else { if (getComputedStyle(select).display !== 'none') { animation = select.options[select.selectedIndex].value; } } AnimateTransition({ container: container, blockIn: blockIn, blockOut: blockOut, animation: animation, onTransitionStart: function (blockIn, blockOut, container, event) { button.setAttribute('disabled', 'disabled'); }, onTransitionEnd: function (blockIn, blockOut, container, event) { button.removeAttribute('disabled'); if (blockOut) { blockIn.setAttribute('data-block', 'out'); blockOut.setAttribute('data-block', 'in'); container.appendChild(blockOut); } } }); } button.addEventListener('click', animateBlocks); /** * Changes animation type in code example on radio button click * @param {Event} event */ function radioClick(event) { radioButtonValue = event.target.id; for (var index = 0; index < animationTypeSpan.length; index += 1) { animationTypeSpan[index].innerText = "'" + radioButtonValue + "'"; } } for (var index = 0; index < radios.length; index += 1) { radios[index].addEventListener('click', radioClick); } }); <|start_filename|>Gruntfile.js<|end_filename|> module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), copy : { build: { files: [ {src: 'src/<%= pkg.name %>.source.js', dest: 'src/<%= pkg.name %>.js'} ] } }, comments: { build: { options: { singleline: true, multiline: true }, src: [ 'src/<%= pkg.name %>.js'] } }, uglify: { build: { options: { }, files: [ { dest: 'src/<%= pkg.name %>.min.js', src: 'src/<%= pkg.name %>.js' } ] } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-stripcomments'); grunt.registerTask('release', ['copy:build', 'comments:build', 'uglify:build']); }; <|start_filename|>src/animateTransition.source.js<|end_filename|> (function (root, factory) { if (typeof define === 'function' && define.amd) { define(function () { return (root.AnimateTransition = factory()); }); } else if (typeof module === 'object' && module.exports) { module.exports = (root.AnimateTransition = factory()); } else { root.AnimateTransition = factory(); } }(this, function () { 'use strict'; var animateTransition; /** * Animate Transition */ function AnimateTransition() { var prefixes = ['webkit', 'moz', 'MS', 'o', ''], overlay = document.createElement('div'); overlay.className = 'transition-overlay'; // Utils function showOverlay() { document.body.appendChild(overlay); } function hideOverlay() { if (overlay.parentNode) { document.body.removeChild(overlay); } } function getElement(selector) { if (!selector) { return null; } return selector.tagName ? selector : document.querySelector(selector); } function addPrefixedEvent(element, eventName, callback) { for (var i = 0; i < prefixes.length; i++) { if (!prefixes[i]) { eventName = eventName.toLowerCase(); } element.addEventListener(prefixes[i] + eventName, callback, false); } } function removePrefixedEvent(element, eventName, callback) { for (var i = 0; i < prefixes.length; i++) { if (!prefixes[i]) { eventName = eventName.toLowerCase(); } element.removeEventListener(prefixes[i] + eventName, callback, false); } } // @todo replaced 'cname' by 'className' function hasClass(obj, className) { return (obj.className ? obj.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')) : false); } // @todo replaced 'cname' by 'className' function addClass(obj, className) { if (obj && !hasClass(obj, className)) { obj.className += " " + className; } } // @todo replaced 'cname' by 'className' function removeClass(obj, className) { if (obj && hasClass(obj, className)) { obj.className = obj.className.replace(new RegExp('(\\s|^)' + className + '(?=\\s|$)'), ''); } } function getFakeEventObj(name) { return { type: 'fake', animationName: name || 'none', stopPropagation: function () { } } } // @todo replaced 'pages' by 'blocks' // @todo we can use it no only for pages function blocksTransition(options) { var container, blockIn, blockOut, animationName, blockInClassName, blockOutClassName, transitionTypeName, beforeTransition, onTransitionStart, onTransitionEnd, timer, timeOut = 3500; // initialize options options = options || {}; container = getElement(options.container) || document.body; blockIn = getElement(options.blockIn); blockOut = getElement(options.blockOut); animationName = options.animation || 'none'; beforeTransition = options.beforeTransition || function () { }; onTransitionStart = options.onTransitionStart || function () { }; onTransitionEnd = options.onTransitionEnd || function () { }; blockInClassName = animationName + '-transition-view-to-show'; blockOutClassName = animationName + '-transition-view-to-hide'; transitionTypeName = 'transition-' + animationName; // @todo added verification of the absence of all blocks if (!blockIn && !blockOut) { console.log('Blocks are not defined'); return; } if (blockIn === blockOut) { // @todo added error log console.log('You are trying to animate same element'); return; } // Stop animation if any still in animation process if ((blockIn && blockIn.busy) || (blockOut && blockOut.busy)) { console.log('You try apply new animation cannot be applied to the same element until previous animation is not finished.'); // @todo added return; need to check return; } // You can use beforeTransition callback to define extra logic. // If result of the callback will be false then transition will be aborted. if (beforeTransition && beforeTransition(blockIn, blockOut, container) === false) { // @todo added error log console.log('Result of the beforeTransition callback is false'); return; } // Init onAnimationStart event handler function onAnimationStart(e) { if (e.animationName !== animationName) { return; } onTransitionStart(blockIn, blockOut, container, e); removePrefixedEvent(container, 'AnimationStart', onAnimationStart); } addPrefixedEvent(container, 'AnimationStart', onAnimationStart); // Init onAnimationEnd event handler function onAnimationEnd(e) { if (e.animationName !== animationName) { return; } e.stopPropagation(); if (blockIn) { blockIn.busy = false; } if (blockOut) { blockOut.busy = false; if (blockOut.parentNode === container) { container.removeChild(blockOut); } // @todo is needed to add else or wrap in try/catch? removeClass(blockOut, blockOutClassName); } onTransitionEnd(blockIn, blockOut, container, e); removeClass(container, transitionTypeName); removeClass(blockIn, blockInClassName); if (timer) { clearTimeout(timer); } hideOverlay(); removePrefixedEvent(container, 'AnimationEnd', onAnimationEnd); } addPrefixedEvent(container, 'AnimationEnd', onAnimationEnd); // If animation was not set - show new block without transition if (animationName === 'none') { if (blockIn) { container.appendChild(blockIn); } onTransitionStart(blockIn, blockOut, container, getFakeEventObj()); if (blockOut) { try { container.removeChild(blockOut); } catch (err) { console.log('You try apply new animation without subject'); } onTransitionEnd(blockIn, blockOut, container, getFakeEventObj()); } else { onTransitionEnd(blockIn, blockOut, container, getFakeEventObj()); } return; } // Init transition: // ---------------------- // Prepare for new transition. if (blockIn) { blockIn.busy = true; addClass(blockIn, blockInClassName); container.appendChild(blockIn); // we don't need blockOut.offsetHeight; because we add it with css class } if (blockOut) { blockOut.busy = true; addClass(blockOut, blockOutClassName); // @todo replaced comment // force WebKit to redraw/repaint without propagation blockOut.offsetHeight; } // Enable overlay layer to protect from accidental clicks until animation ends showOverlay(); // Set timeout for case if onAnimationEnd event will not occur timer = window.setTimeout(function () { onAnimationEnd(getFakeEventObj(animationName)); }, timeOut); // Add predefined CSS class to start CSS animation addClass(container, transitionTypeName); } // @todo replaced 'pages' by 'blocks' return blocksTransition; } animateTransition = new AnimateTransition(); animateTransition.Constructor = AnimateTransition; return animateTransition; }));
fnnzzz/AnimateTransition
<|start_filename|>bem-platform/pages/index/index.min.css<|end_filename|> html { height: 100%; } .page { height: 100%; margin: 0; padding: 0; background: #EEE; font: 13px Tahoma, Sans-Serif; } .page__inner { width: 700px; min-height: 100%; margin: auto; background: #FFF; } .heading { margin: 0 0 16px 0; } .heading_level_1 { letter-spacing: 1px; color: #FFF; font-size: 23.4px; } .heading_level_2 { color: #293499; font-size: 16.9px; } .heading_level_3 { text-transform: uppercase; color: #293499; background: #DDE6FF; font-size: 13px; } .search { font-size: 10.4px; } .search__field { display: block; width: 10em; font-size: 9px; } .button { -ms-touch-action: manipulation; touch-action: manipulation; } .button { display: inline-block; vertical-align: bottom; font-size: 9px; } .main { min-height: 100%; padding-bottom: 42px; } .clearfix:after { display: table; clear: both; content: ''; } .sidebar { float: left; width: 20%; } .nav { margin: 50px 0; padding: 0; list-style: none; } .nav__item_separate { margin: 22px 0; } .nav__link { display: block; margin: 5px 0; padding: 2px 5px; text-decoration: none; color: #000; border: 1px solid #FFF; border-right: 0; border-left: 0; background: #DDE6FF; font-size: 10.4px; } .nav__link:hover { color: #FFF; background: #D00; } .nav__link_current { color: #FFF; background: #293499; } .link { -ms-touch-action: manipulation; touch-action: manipulation; } .link_disabled { pointer-events: none; } .content { float: left; width: 55%; } .content__title { margin-top: 20px; margin-bottom: 10px; padding: 0 15px; } .content__article { padding: 0 15px; } .text { /* There can be some styles for content imported from backed */ } .text img { float: left; margin: 0 15px 15px 0; padding: 5px; border: 1px solid #45F; } .text p { /* There can be some styles for html-elements in text-content block */ } .news { float: right; width: 25%; } .news__title { margin: 0 0 20px 0; padding: 10px; } .news__article { margin: 20px 5px; font-size: 10.4px; } .news__date { float: left; margin: 0 5px 0 0; color: #293499; font-size: 10.4px; font-weight: bold; } .news__text { display: inline; color: #293499; } .news__text p:last-of-type { display: inline; } .news__link { padding-right: 13px; color: #D00; } .footer { position: absolute; bottom: 0; width: 700px; height: 42px; color: #FFF; background: #45F; } .footer__text { margin: 5px; font-size: 9.1px; } .footer__link { color: #FFF; } .header { padding: 20px; background: #45F; } .header__title { display: inline-block; margin: 0; padding-left: 40px; letter-spacing: 1px; font-size: 23.4px; } .header__search { float: right; } .header__label { display: inline-block; color: #FFF; } <|start_filename|>bem-css/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <title>Holy Grail Markup</title> <link rel="stylesheet" href="style.css"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-86724647-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-86724647-1'); </script> </head> <body class="page"> <div class="page__inner"> <div class="header"> <!-- We specially use 'title' class here instead of 'logo' in order to set an example of problems with the same classnames in different parts of site The same block called 'title' also located in div.content. --> <h1 class="header__title title">CompanyName</h1> <form class="header__search search"> <label class="header__label label">Type to search: <input class="search__field input" type="text"> </label> <button class="button" type="submit">Search</button> </form> </div> <div class="main"> <div class="sidebar"> <ul class="nav"> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/oocss" class="nav__link">OOCSS</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/smacss" class="nav__link">SMACSS</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/atomic" class="nav__link">Atomic</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/organic" class="nav__link">Organic</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-css/" class="nav__link nav__link--active">BEM CSS</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-sass/" class="nav__link">BEM SASS</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-flexboxgrid/" class="nav__link">BEM Flexbox Grid</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-bootstrap-4/" class="nav__link">BEM Bootstrap 4</a> </li> <li class="nav__item"> <a href="http://aleshaoleg.github.io/holy-grail-markup/bem-platform/pages/index/" class="nav__link">BEM Platform</a> </li> <li class="nav__item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/css-modules/" class="nav__link">CSS-modules</a> </li> <li class="nav__item nav__item--separate"> <a href="https://aleshaoleg.github.io/holy-grail-markup/raw" class="nav__link">Raw</a> </li> </ul> </div> <div class="content"> <!-- The same block called 'title' also located in div.header, so as the result we have to figure out some other name for it. --> <h2 class="content__title heading heading--level_2">About Company</h2> <div class="content__article text"> <img src="imgpsh_fullsize.jpg" alt="Image"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed erat diam, posuere rhoncus justo tempus, ornare vehicula lorem. Donec egestas et nisl non dapibus. Morbi congue, purus ac lobortis feugiat, nunc nulla facilisis lacus, ac laoreet urna dui a lorem. Quisque ligula nisi, tristique in ligula vitae, dapibus tempus lectus.</p> <p>Cras eget ipsum mattis, pharetra nulla vitae, laoreet dui.</p> <p>Duis in erat a lectus consequat auctor quis vel ligula. Quisque rhoncus sapien sit amet augue mollis convallis. Curabitur pharetra nunc a massa dictum, eu iaculis dolor egestas. Suspendisse potenti. Nam id lorem risus. Suspendisse potenti.</p> </div> </div> <div class="news"> <h2 class="news__title heading heading--level_3">News</h2> <div class="news__article"> <h3 class="news__date">01.01.16</h3> <div class="news__text"> <p>Vestibulum semper convallis mauris vitae lobortis. Pellentesque lobortis sem a cursus varius. Phasellus dignissim diam eget lectus cursus finibus.</p> </div> </div> <div class="news__article"> <h3 class="news__date">03.01.16</h3> <div class="news__text"> <p>Nam placerat tellus vitae rhoncus ornare. Suspendisse scelerisque lorem id turpis efficitur facilisis. Vivamus enim magna, hendrerit id rutrum at, euismod ac orci.</p> </div> <a href="#" class="news__link">Read more...</a> </div> <div class="news__article"> <h3 class="news__date">08.01.16</h3> <div class="news__text"> <p>Maecenas sed orci turpis. Donec pretium lorem in purus porta hendrerit. Praesent at placerat lacus, ac ultrices ligula. Cras at consequat velit. Vivamus dapibus metus at nisl imperdiet imperdiet.</p> </div> <a href="#" class="news__link">Read more...</a> </div> </div> </div> <div class="footer"> <span class="footer__text">© 2016 CompanyName, Inc. All Rights Reserved.</span> <span class="footer__text">Site support: <a href="mailto:<EMAIL>" class="footer__link"><EMAIL></a></span> </div> </div> </body> </html> <|start_filename|>atomic/index.html<|end_filename|> <!DOCTYPE html> <html class="H(100%) Bgc(#eee)"> <head> <title>Holy Grail Markup</title> <link rel="stylesheet" href="style.css"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-86724647-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-86724647-1'); </script> </head> <body class="Pos(r) Mih(100%) My(0) Mx(a) Bgc(#fff) W(700px) Ff(Tahoma) Fz(13px)"> <div class="Bgc(#45f) C(#fff)"> <h1 class="My(0) Py(20px) Px(60px) Fz(180%) Lts(1px)">CompanyName</h1> </div> <div class="Ov(h) Mih(100%) Pb(42px)"> <div class="Fl(start) W(55%) Mstart(20%)"> <h2 class="Mt(20px) Mb(10px) Fz(130%) Px(15px) C(#293499)">About Company</h2> <div class="Px(15px)"> <img class="Fl(start) P(5px) Bdw(1px) Bds(s) Bdc(#45f) Mend(15px) Mb(15px)" src="imgpsh_fullsize.jpg" alt="Image"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed erat diam, posuere rhoncus justo tempus, ornare vehicula lorem. Donec egestas et nisl non dapibus. Morbi congue, purus ac lobortis feugiat, nunc nulla facilisis lacus, ac laoreet urna dui a lorem. Quisque ligula nisi, tristique in ligula vitae, dapibus tempus lectus.</p> <p>Cras eget ipsum mattis, pharetra nulla vitae, laoreet dui.</p> <p>Duis in erat a lectus consequat auctor quis vel ligula. Quisque rhoncus sapien sit amet augue mollis convallis. Curabitur pharetra nunc a massa dictum, eu iaculis dolor egestas. Suspendisse potenti. Nam id lorem risus. Suspendisse potenti.</p> </div> </div> <div class="Fl(start) W(20%) Mstart(-75%)"> <ul class="Mt(51px) Pstart(0) List(n) Fz(80%)"> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/oocss" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">OOCSS</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/smacss" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">SMACSS</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/atomic" class="D(b) Px(5px) Py(2px) Bgc(#293499) C(#fff) Td(n) C(#fff):h Bgc(#d00):h">Atomic</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/organic" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">Organic</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-css/" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">BEM CSS</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-sass/" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">BEM SASS</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-flexboxgrid/" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">BEM Flexbox Grid</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-bootstrap-4/" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">BEM Bootstrap 4</a> </li> <li class="My(7px)"> <a href="http://aleshaoleg.github.io/holy-grail-markup/bem-platform/pages/index" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">BEM Platform</a> </li> <li class="My(7px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/css-modules/" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">CSS-modules</a> </li> <li class="My(24px)"> <a href="https://aleshaoleg.github.io/holy-grail-markup/raw" class="D(b) Px(5px) Py(2px) Bgc(#dde6ff) C(#000) Td(n) C(#fff):h Bgc(#d00):h">Raw</a> </li> </ul> <form class="Pos(a) T(0) End(0) Fz(80%) M(20px)"> <label class="D(ib) C(#fff)">Type to search: <input class="D(b) W(10em) Fz(9px)" type="text"> </label> <button class="D(ib) Fz(9px)" type="submit">Search</button> </form> </div> <div class="W(25%) Fl(end) C(#293499)"> <h2 class="Mt(0) Mb(20px) P(10px) Bgc(#dde6ff) Tt(u) Fw(b) Fz(13px)">News</h2> <div class="Mx(5px) My(20px) Fz(80%)"> <h3 class="Fl(start) Fz(100%) Fw(b) My(0) Mend(5px)">01.01.16</h3> <p class="D(i)">Vestibulum semper convallis mauris vitae lobortis. Pellentesque lobortis sem a cursus varius. Phasellus dignissim diam eget lectus cursus finibus.</p> </div> <div class="Mx(5px) My(20px) Fz(80%)"> <h3 class="Fl(start) Fz(100%) Fw(b) My(0) Mend(5px)">03.01.16</h3> <p class="D(i)">Nam placerat tellus vitae rhoncus ornare. Suspendisse scelerisque lorem id turpis efficitur facilisis. Vivamus enim magna, hendrerit id rutrum at, euismod ac orci.</p> <a href="#" class="C(#d00) Pend(13px)">Read more...</a> </div> <div class="Mx(5px) My(20px) Fz(80%)"> <h3 class="Fl(start) Fz(100%) Fw(b) My(0) Mend(5px)">08.01.16</h3> <p class="D(i)">Maecenas sed orci turpis. Donec pretium lorem in purus porta hendrerit. Praesent at placerat lacus, ac ultrices ligula. Cras at consequat velit. Vivamus dapibus metus at nisl imperdiet imperdiet.</p> <a href="#" class="C(#d00) Pend(13px)">Read more...</a> </div> </div> </div> <div class="Pos(a) B(0) W(100%) H(42px) Bgc(#45f) C(#fff) Fz(70%)"> <p class="M(5px)">© 2016 CompanyName, Inc. All Rights Reserved.</p> <p class="M(5px)">Site support: <a class="C(#fff)" href="mailto:<EMAIL>"><EMAIL></a></p> </div> </body> </html> <|start_filename|>raw/index.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Holy Grail Markup</title> <link rel="stylesheet" href="style.css"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-86724647-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-86724647-1'); </script> </head> <body> <div id="title"> <h1>CompanyName</h1> </div> <div id="content"> <div id="main"> <h2>About Company</h2> <p><img class="picture" src="imgpsh_fullsize.jpg" alt=""></p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed erat diam, posuere rhoncus justo tempus, ornare vehicula lorem. Donec egestas et nisl non dapibus. Morbi congue, purus ac lobortis feugiat, nunc nulla facilisis lacus, ac laoreet urna dui a lorem. Quisque ligula nisi, tristique in ligula vitae, dapibus tempus lectus. </p> <p> Cras eget ipsum mattis, pharetra nulla vitae, laoreet dui. </p> <p> Duis in erat a lectus consequat auctor quis vel ligula. Quisque rhoncus sapien sit amet augue mollis convallis. Curabitur pharetra nunc a massa dictum, eu iaculis dolor egestas. Suspendisse potenti. Nam id lorem risus. Suspendisse potenti. </p> </div> <div id="sections"> <ul> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/oocss" class="light-blue">OOCSS</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/smacss" class="light-blue">SMACSS</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/atomic" class="light-blue">Atomic</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/organic" class="light-blue">Organic</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-css/" class="light-blue">BEM CSS</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-sass/" class="light-blue">BEM SASS</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-flexboxgrid/" class="light-blue">BEM Flexbox Grid</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-bootstrap-4/" class="light-blue">BEM Bootstrap 4</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-platform/pages/index/" class="light-blue">BEM Platform</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/css-modules/" class="light-blue">CSS-modules</a> </li> <li> <a href="https://aleshaoleg.github.io/holy-grail-markup/raw" class="blue separate">Raw</a> </li> </ul> <form id="search" action="search/" method="get"> <p>Type to search:</p> <p><input type="text"> <button type="submit">Search</button></p> </form> </div> <div id="news"> <h2>News</h2> <h3>01.01.16</h3> <p> Vestibulum semper convallis mauris vitae lobortis. Pellentesque lobortis sem a cursus varius. Phasellus dignissim diam eget lectus cursus finibus. </p> <h3>03.01.16</h3> <p> Nam placerat tellus vitae rhoncus ornare. Suspendisse scelerisque lorem id turpis efficitur facilisis. Vivamus enim magna, hendrerit id rutrum at, euismod ac orci. <a href="news/2016/01/03/elevators/">Read more...</a> </p> <h3>08.01.16</h3> <p> Maecenas sed orci turpis. Donec pretium lorem in purus porta hendrerit. Praesent at placerat lacus, ac ultrices ligula. Cras at consequat velit. Vivamus dapibus metus at nisl imperdiet imperdiet. <a href="news/2016/01/08/redesign/">Read more...</a> </p> </div> </div> <div id="meta"> <p>© 2016 CompanyName, Inc. All Rights Reserved.</p> <p>Site support: <a href="mailto:<EMAIL>"><EMAIL></a></p> </div> </body> </html> <|start_filename|>bem-platform/specificity-graph/specificity.json<|end_filename|> [{"selectorIndex":0,"line":1,"specificity":1,"selectors":"html"},{"selectorIndex":1,"line":5,"specificity":10,"selectors":".page"},{"selectorIndex":2,"line":13,"specificity":10,"selectors":".page__inner"},{"selectorIndex":3,"line":20,"specificity":10,"selectors":".heading"},{"selectorIndex":4,"line":24,"specificity":10,"selectors":".heading_level_1"},{"selectorIndex":5,"line":30,"specificity":10,"selectors":".heading_level_2"},{"selectorIndex":6,"line":35,"specificity":10,"selectors":".heading_level_3"},{"selectorIndex":7,"line":42,"specificity":10,"selectors":".search"},{"selectorIndex":8,"line":46,"specificity":10,"selectors":".search__field"},{"selectorIndex":9,"line":52,"specificity":10,"selectors":".button"},{"selectorIndex":10,"line":57,"specificity":10,"selectors":".button"},{"selectorIndex":11,"line":63,"specificity":10,"selectors":".main"},{"selectorIndex":12,"line":68,"specificity":11,"selectors":".clearfix:after"},{"selectorIndex":13,"line":74,"specificity":10,"selectors":".sidebar"},{"selectorIndex":14,"line":79,"specificity":10,"selectors":".nav"},{"selectorIndex":15,"line":85,"specificity":10,"selectors":".nav__item_separate"},{"selectorIndex":16,"line":89,"specificity":10,"selectors":".nav__link"},{"selectorIndex":17,"line":102,"specificity":20,"selectors":".nav__link:hover"},{"selectorIndex":18,"line":107,"specificity":10,"selectors":".nav__link_current"},{"selectorIndex":19,"line":112,"specificity":10,"selectors":".link"},{"selectorIndex":20,"line":117,"specificity":10,"selectors":".link_disabled"},{"selectorIndex":21,"line":121,"specificity":10,"selectors":".content"},{"selectorIndex":22,"line":126,"specificity":10,"selectors":".content__title"},{"selectorIndex":23,"line":132,"specificity":10,"selectors":".content__article"},{"selectorIndex":24,"line":136,"specificity":10,"selectors":".text"},{"selectorIndex":25,"line":140,"specificity":11,"selectors":".text img"},{"selectorIndex":26,"line":147,"specificity":11,"selectors":".text p"},{"selectorIndex":27,"line":151,"specificity":10,"selectors":".news"},{"selectorIndex":28,"line":156,"specificity":10,"selectors":".news__title"},{"selectorIndex":29,"line":161,"specificity":10,"selectors":".news__article"},{"selectorIndex":30,"line":166,"specificity":10,"selectors":".news__date"},{"selectorIndex":31,"line":174,"specificity":10,"selectors":".news__text"},{"selectorIndex":32,"line":179,"specificity":21,"selectors":".news__text p:last-of-type"},{"selectorIndex":33,"line":183,"specificity":10,"selectors":".news__link"},{"selectorIndex":34,"line":188,"specificity":10,"selectors":".footer"},{"selectorIndex":35,"line":197,"specificity":10,"selectors":".footer__text"},{"selectorIndex":36,"line":202,"specificity":10,"selectors":".footer__link"},{"selectorIndex":37,"line":206,"specificity":10,"selectors":".header"},{"selectorIndex":38,"line":211,"specificity":10,"selectors":".header__title"},{"selectorIndex":39,"line":219,"specificity":10,"selectors":".header__search"},{"selectorIndex":40,"line":223,"specificity":10,"selectors":".header__label"}] <|start_filename|>organic/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <title>Holy Grail Markup</title> <link rel="stylesheet" href="style.css"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-86724647-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-86724647-1'); </script> </head> <body> <div class="wrapper"> <div class="header"> <h1 class="header-title">CompanyName</h1> <form class="header-search"> <label class="label">Type to search: <input class="label-field" type="text"> </label> <button class="button" type="submit">Search</button> </form> </div> <div class="main"> <div class="nav"> <ul class="nav-list"> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/oocss" class="nav-link">OOCSS</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/smacss" class="nav-link">SMACSS</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/atomic" class="nav-link">Atomic</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/organic" class="nav-link nav-link-active">Organic</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-css/" class="nav-link">BEM CSS</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-sass/" class="nav-link">BEM SASS</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-flexboxgrid/" class="nav-link">BEM Flexbox Grid</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-bootstrap-4/" class="nav-link">BEM Bootstrap 4</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/bem-platform/pages/index/" class="nav-link">BEM Platform</a> </li> <li class="nav-item"> <a href="https://aleshaoleg.github.io/holy-grail-markup/css-modules/" class="nav-link">CSS-modules</a> </li> <li class="nav-item nav-item--separate"> <a href="https://aleshaoleg.github.io/holy-grail-markup/raw" class="nav-link">Raw</a> </li> </ul> </div> <div class="content"> <h2 class="content-title">About Company</h2> <div class="content-article"> <img src="imgpsh_fullsize.jpg" class="content-image" alt=""> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed erat diam, posuere rhoncus justo tempus, ornare vehicula lorem. Donec egestas et nisl non dapibus. Morbi congue, purus ac lobortis feugiat, nunc nulla facilisis lacus, ac laoreet urna dui a lorem. Quisque ligula nisi, tristique in ligula vitae, dapibus tempus lectus.</p> <p>Cras eget ipsum mattis, pharetra nulla vitae, laoreet dui.</p> <p>Duis in erat a lectus consequat auctor quis vel ligula. Quisque rhoncus sapien sit amet augue mollis convallis. Curabitur pharetra nunc a massa dictum, eu iaculis dolor egestas. Suspendisse potenti. Nam id lorem risus. Suspendisse potenti.</p> </div> </div> <div class="news"> <h2 class="news-title">News</h2> <div class="news-article"> <h3 class="news-date">01.01.16</h3> <div class="news-text"> <p>Vestibulum semper convallis mauris vitae lobortis. Pellentesque lobortis sem a cursus varius. Phasellus dignissim diam eget lectus cursus finibus.</p> </div> </div> <div class="news-article"> <h3 class="news-date">03.01.16</h3> <div class="news-text"> <p>Nam placerat tellus vitae rhoncus ornare. Suspendisse scelerisque lorem id turpis efficitur facilisis. Vivamus enim magna, hendrerit id rutrum at, euismod ac orci.</p> </div> <a href="#" class="news-link">Read more...</a> </div> <div class="news-article"> <h3 class="news-date">08.01.16</h3> <div class="news-text"> <p>Maecenas sed orci turpis. Donec pretium lorem in purus porta hendrerit. Praesent at placerat lacus, ac ultrices ligula. Cras at consequat velit. Vivamus dapibus metus at nisl imperdiet imperdiet.</p> </div> <a href="#" class="news-link">Read more...</a> </div> </div> </div> <div class="footer"> <span class="footer-text">© 2016 CompanyName, Inc. All Rights Reserved.</span> <span class="footer-text">Site support: <a href="mailto:<EMAIL>" class="footer-link"><EMAIL></a></span> </div> </div> </body> </html> <|start_filename|>Gruntfile.js<|end_filename|> module.exports = function(grunt) { grunt.initConfig({ csscount: { dev: { src: [ 'atomic/style.css', 'bem-bootstrap-4/style.css', 'bem-css/style.css', 'bem-flexboxgrid/style.css', 'bem-platform/pages/index/index.css', 'bem-sass/style.css', 'css-modules/build/style.css', 'oocss/style.css', 'organic/style.css', 'raw/style.css', 'smacss/basic.css', 'smacss/layouts.css', 'smacss/modules.css', 'smacss/states.css', 'smacss/themes.css' ] } } }); grunt.loadNpmTasks('grunt-css-count'); grunt.registerTask('default', ['csscount']); };
starrohan999/holy-grail-markup
<|start_filename|>package-lock.json<|end_filename|> { "name": "s3-mongo-backup", "version": "2.0.2", "lockfileVersion": 1, "requires": true, "dependencies": { "aws-sdk": { "version": "2.82.0", "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.82.0.tgz", "integrity": "sha1-qUz+kMFe4OQD8A8GZdzLmKqT4fg=" }, "eslint": { "version": "3.19.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-3.19.0.tgz", "integrity": "sha1-yPxiAcf0DdCJQbh8CFdnOGpnmsw=", "dev": true }, "moment": { "version": "2.19.3", "resolved": "https://registry.npmjs.org/moment/-/moment-2.19.3.tgz", "integrity": "sha1-vbmdJw1tf9p4zA+6zoVeJ/59pp8=" }, "mongodb-uri": { "version": "0.9.7", "resolved": "https://registry.npmjs.org/mongodb-uri/-/mongodb-uri-0.9.7.tgz", "integrity": "sha1-D3ca0W9IOuZfQoeWlCjp+8SqYYE=" } } }
ishanjain28/s3-mongo-backup
<|start_filename|>Assets/HhotateA/MagicalDresserInventorySystem/Editor/MagicalDresserInventorySaveData.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System.Collections.Generic; using UnityEngine; using System; using System.Linq; using HhotateA.AvatarModifyTools.Core; using UnityEditor; using UnityEngine.Serialization; using System.Reflection; using UnityEditor.IMGUI.Controls; using UnityEngine.Internal; namespace HhotateA.AvatarModifyTools.MagicalDresserInventorySystem { public class MagicalDresserInventorySaveData : ScriptableObject { [FormerlySerializedAs("name")] public string saveName = "MagicalDresserInventorySaveData"; public string avatarName; public int avatarGUID; public Texture2D icon = null; public List<MenuElement> menuElements = new List<MenuElement>(); public LayerSettings[] layerSettingses; public AvatarModifyData assets; public bool useMenuTemplate; public List<MenuTemplate> menuTemplate = new List<MenuTemplate>(); public List<MenuTemplate> ReloadTemplates() { return MenuTemplate.ReloadTemplates(menuTemplate, menuElements); } public bool idleOverride = true; public bool materialOverride = true; public bool createAnimWhenNotChangedActive = false; public MagicalDresserInventorySaveData() { layerSettingses = Enumerable.Range(0,Enum.GetValues(typeof(LayerGroup)).Length). Select(l=>new LayerSettings()).ToArray(); } public void SaveGUID(GameObject root) { avatarGUID = root.GetInstanceID(); avatarName = root.name; root = root.transform.parent?.gameObject; while (root) { avatarName = root.name + "/" + avatarName; root = root.transform.parent?.gameObject; } } public GameObject GetRoot() { return GameObject.Find(avatarName); var root = GameObject.Find(avatarName); if (root) { if (root.GetInstanceID() == avatarGUID) { return root; } } return null; } public void ApplyRoot(GameObject root) { foreach (var menuElement in menuElements) { foreach (var item in menuElement.activeItems) { item.GetRelativeGameobject(root.transform); } // menuElement.activeItems = menuElement.activeItems.Where(e => e.obj != null).ToList(); foreach (var item in menuElement.inactiveItems) { item.GetRelativeGameobject(root.transform); } // menuElement.inactiveItems = menuElement.inactiveItems.Where(e => e.obj != null).ToList(); } } public void ApplyPath(GameObject root) { foreach (var menuElement in menuElements) { foreach (var item in menuElement.SafeActiveItems()) { item.GetRelativePath(root); } menuElement.activeItems = menuElement.activeItems.Where(e => !String.IsNullOrWhiteSpace(e.path)).ToList(); foreach (var item in menuElement.SafeInactiveItems()) { item.GetRelativePath(root); } menuElement.inactiveItems = menuElement.inactiveItems.Where(e => !String.IsNullOrWhiteSpace(e.path)).ToList(); } } public void RepairReference(string path,GameObject obj,GameObject root) { foreach (var menuElement in menuElements) { foreach (var item in menuElement.activeItems) { if (item.path == path) { item.obj = obj; item.ReloadRendOption(); if(root != null) item.GetRelativePath(root); } } foreach (var item in menuElement.inactiveItems) { if (item.path == path) { item.obj = obj; item.ReloadRendOption(); if(root != null) item.GetRelativePath(root); } } } } } [Serializable] public class MenuTemplate { public string name; public Texture2D icon; public List<MenuTemplate> childs = new List<MenuTemplate>(); public string menuGUID; public bool autoCreate = true; [SerializeField] int guid = 0; public int GetGuid() { if (guid == 0) { guid = Guid.NewGuid().GetHashCode(); } return guid; } public MenuTemplate FIndTemplateElement(int id, Action<MenuTemplate, MenuTemplate> onFind = null) { childs = childs.Distinct().ToList(); foreach (var child in childs) { if (child.guid == id) { onFind?.Invoke(child,this); return child; } var e = child.FIndTemplateElement(id,onFind); if (e != null) { return e; } } return null; } public static MenuTemplate FIndTemplateElement(List<MenuTemplate> root,int id, Action<MenuTemplate, MenuTemplate> onFind = null) { foreach (var child in root) { if (child.guid == id) { onFind?.Invoke(child,null); return child; } var e = child.FIndTemplateElement(id,onFind); if (e != null) { return e; } } return null; } public MenuTemplate FindMenuElement(string id, Action<MenuTemplate, MenuTemplate> onFind = null) { childs = childs.Distinct().ToList(); foreach (var child in childs) { if (child.menuGUID == id) { onFind?.Invoke(child,this); return child; } var e = child.FindMenuElement(id,onFind); if (e != null) { return e; } } return null; } public static MenuTemplate FindMenuElement(List<MenuTemplate> root,string id, Action<MenuTemplate, MenuTemplate> onFind = null) { foreach (var child in root) { if (child.menuGUID == id) { onFind?.Invoke(child,null); return child; } var e = child.FindMenuElement(id,onFind); if (e != null) { return e; } } return null; } public void FindElement(Predicate<MenuTemplate> predicate, Action<MenuTemplate, MenuTemplate> onFind = null) { childs = childs.Distinct().ToList(); foreach (var child in childs) { if (predicate.Invoke(child)) { onFind?.Invoke(child,this); } } } public static void FindElement(List<MenuTemplate> root, Predicate<MenuTemplate> predicate, Action<MenuTemplate, MenuTemplate> onFind = null) { foreach (var child in root) { if (predicate.Invoke(child)) { onFind?.Invoke(child,null); child.FindElement(predicate,onFind); } } } public void DeleateOverlapElement(MenuTemplate origin) { childs = childs.Distinct().ToList(); for (int i = 0; i < childs.Count; i ++ ) { if(String.IsNullOrWhiteSpace(childs[i].menuGUID)) continue; if (childs[i].menuGUID == origin.menuGUID && childs[i] != origin) { childs.Remove(childs[i]); i--; continue; } else { childs[i].DeleateOverlapElement(origin); } } } public void DeleateNullMenuElement(List<MenuElement> datas) { childs = childs.Distinct().ToList(); for (int i = 0; i < childs.Count; i ++ ) { if (String.IsNullOrWhiteSpace(childs[i].menuGUID)) { childs[i].DeleateNullMenuElement(datas); } else { var menu = datas.FirstOrDefault(e => e.guid == childs[i].menuGUID); if (menu == null) { childs.Remove(childs[i]); i--; continue; } else { childs[i].icon = menu.icon; childs[i].name = menu.name; childs[i].DeleateNullMenuElement(datas); } // メニューは子を持たないので初期化 childs[i].childs = new List<MenuTemplate>(); } } } public void DeleateAutoCreate() { childs = childs.Distinct().ToList(); for (int i = 0; i < childs.Count; i ++ ) { if (!String.IsNullOrWhiteSpace(childs[i].menuGUID) && childs[i].autoCreate) { childs.Remove(childs[i]); i--; continue; } else if (childs[i].childs.Count == 0 && childs[i].autoCreate) { childs.Remove(childs[i]); i--; continue; } else { childs[i].DeleateAutoCreate(); } } } public void RecursionAutoCreateFalse() { autoCreate = false; foreach (var child in childs) { child.RecursionAutoCreateFalse(); } } public static List<MenuTemplate> ReloadTemplates(List<MenuTemplate> menus,List<MenuElement> datas) { // メニュー参照切れ項目の削除 foreach (var menu in menus) { menu.DeleateNullMenuElement(datas); } foreach (var data in datas) { var current = FindMenuElement(menus, data.guid); if (current == null) { current = new MenuTemplate() { name = data.name, icon = data.icon, menuGUID = data.guid, autoCreate = true, }; } else { FindMenuElement(menus, data.guid, (e, p) => { if (e.autoCreate) { p.childs.Remove(e); } }); } if (current.autoCreate) { var root = data.isToggle ? menus.FirstOrDefault(e => e.name == "Items" && e.autoCreate) : menus.FirstOrDefault(e => e.name == data.layer.ToString() && e.autoCreate); // 親オブジェクトの検知 MenuTemplate.FindElement(menus,e => { var menu = datas.FirstOrDefault(m => m.guid == e.menuGUID); if (menu == null) return false; if (data.isToggle) { return e.autoCreate && menu.isToggle; } else { return e.autoCreate && !menu.isToggle && menu.layer == data.layer; } }, (e, p) => { if (p != null) { root = p; } }); if (root == null) { if (data.isToggle) { root = new MenuTemplate() { name = "Items", icon = data.icon, autoCreate = true, }; } else { root = new MenuTemplate() { name = data.layer.ToString(), icon = data.icon, autoCreate = true, }; } menus.Add(root); } root.childs.Add(current); } } // root直下の処理 for (int i = 0; i < menus.Count; i ++ ) { if (String.IsNullOrWhiteSpace(menus[i].menuGUID) && menus[i].childs.Count == 0 && menus[i].autoCreate) { menus.Remove(menus[i]); i--; continue; } if (!String.IsNullOrWhiteSpace(menus[i].menuGUID)) { var menu = datas.FirstOrDefault(e => e.guid == menus[i].menuGUID); if (menu == null) { menus.Remove(menus[i]); i--; continue; } } } return menus; } } [Serializable] public class LayerSettings { public bool isSaved = true; public bool isRandom = false; //public DefaultValue defaultValue; public string defaultElementGUID = ""; public MenuElement GetDefaultElement(List<MenuElement> datas) { return datas.FirstOrDefault(d => d.guid == defaultElementGUID); } public void SetDefaultElement(MenuElement element) { if (element != null) { defaultElementGUID = element.guid; } else { defaultElementGUID = ""; } } } [Serializable] public class MenuElement { public string name; public Texture2D icon; public List<ItemElement> activeItems = new List<ItemElement>(); public List<ItemElement> SafeActiveItems() { return activeItems.Where(e => e.obj != null).ToList(); } public List<ItemElement> UnSafeActiveItems() { return activeItems.Where(e => e.obj == null).ToList(); } public List<ItemElement> inactiveItems = new List<ItemElement>(); public List<ItemElement> SafeInactiveItems() { return inactiveItems.Where(e => e.obj != null).ToList(); } public List<ItemElement> UnSafeInactiveItems() { return inactiveItems.Where(e => e.obj == null).ToList(); } public bool isToggle = true; public LayerGroup layer = LayerGroup.Layer_A; public bool isSaved = true; public bool isDefault = false; public bool isRandom = false; public bool isTaboo = false; public string param = ""; public int value = 0; public string guid; public List<SyncElement> activeSyncElements = new List<SyncElement>(); public List<SyncElement> inactiveSyncElements = new List<SyncElement>(); public bool extendOverrides = false; public bool isOverrideActivateTransition = false; public ItemElement overrideActivateTransition = new ItemElement(); public bool isOverrideInactivateTransition = false; public ItemElement overrideInactivateTransition = new ItemElement(); public MenuElement() { guid = System.Guid.NewGuid().ToString(); } public string DefaultIcon() { return isToggle ? EnvironmentGUIDs.itemIcon : layer == LayerGroup.Layer_A ? EnvironmentGUIDs.dressAIcon : layer == LayerGroup.Layer_B ? EnvironmentGUIDs.dressBIcon : layer == LayerGroup.Layer_C ? EnvironmentGUIDs.dressCIcon : EnvironmentGUIDs.itemboxIcon; } public void SetToDefaultIcon() { icon = AssetUtility.LoadAssetAtGuid<Texture2D>(DefaultIcon()); } public bool IsDefaultIcon() { return AssetDatabase.GetAssetPath(icon) == AssetDatabase.GUIDToAssetPath(DefaultIcon()); } public void SetLayer(bool t) { if (IsDefaultIcon()) { isToggle = t; SetToDefaultIcon(); } else { isToggle = t; } } public void SetLayer(LayerGroup l) { if (IsDefaultIcon()) { layer = l; SetToDefaultIcon(); } else { layer = l; } } } [Serializable] public class SyncElement { public string guid; public float delay; public bool syncOn; public bool syncOff; public SyncElement(string id) { guid = id; delay = -1f; syncOn = false; syncOff = false; } } [Serializable] public class ItemElement { public string path; // なぜかここが[System.NonSerialized]だとばぐる(たぶんInstanceしてるから) public GameObject obj; public bool active = true; public FeedType type = FeedType.None; public float delay = 0f; public float duration = 1f; //public Shader animationShader; public Material animationMaterial; public string animationParam = "_AnimationTime"; public float animationParamOff = 0f; public float animationParamOn = 1f; public bool extendOption = false; public List<RendererOption> rendOptions = new List<RendererOption>(); public ItemElement() { } public ItemElement(GameObject o,GameObject root = null,bool defaultActive = true) { obj = o; active = defaultActive; rendOptions = obj.GetComponentsInChildren<Renderer>().Select(r => new RendererOption(r, o)).ToList(); if(root) GetRelativePath(root); } public ItemElement Clone(bool invert = false) { return new ItemElement(obj) { active = invert ? !active : active, path = path, type = type, delay = delay, duration = duration, animationMaterial = animationMaterial, animationParam = animationParam, rendOptions = rendOptions.Select(r=>r.Clone(obj,invert)).ToList(), }; } public void GetRelativePath(GameObject root) { if (!obj) return; if (obj == root) { path = ""; } else { path = obj.gameObject.name; Transform parent = obj.transform.parent; while (parent != null) { if(parent.gameObject == root) break; path = parent.name + "/" + path; parent = parent.parent; } } } public void GetRelativeGameobject(Transform root) { if (String.IsNullOrWhiteSpace(path)) { obj = root.gameObject; ReloadRendOption(); } else { root = root.Find(path); obj = root?.gameObject; ReloadRendOption(); } } public void ReloadRendOption() { if (obj == null) { } else { var currentRendOptions = rendOptions.ToList(); var newRendOptions = obj.GetComponentsInChildren<Renderer>().Select(r => new RendererOption(r, obj)).ToList(); for (int i = 0; i < newRendOptions.Count; i++) { var currentRendOption = currentRendOptions.FirstOrDefault(r => r.path == newRendOptions[i].path && r.mesh == newRendOptions[i].mesh); if (currentRendOption!=null) { currentRendOption.GetRelativeGameobject(obj.transform); if (currentRendOption.changeMaterialsOptions.Count == newRendOptions[i].changeMaterialsOptions.Count && currentRendOption.changeBlendShapeOptions.Count == newRendOptions[i].changeBlendShapeOptions.Count) { currentRendOptions.Remove(currentRendOption); newRendOptions[i] = currentRendOption; } } } for (int i = 0; i < currentRendOptions.Count; i++) { currentRendOptions[i].rend = null; } newRendOptions.AddRange(currentRendOptions); rendOptions = newRendOptions; } } } [Serializable] public class RendererOption { [SerializeField] bool rendDisable = false; public bool RendEnable { get { return !rendDisable; } set { rendDisable = !value; } } public string path; // なぜかここが[System.NonSerialized]だとばぐる(たぶんInstanceしてるから) public Renderer rend; public Mesh mesh; public bool ExtendOption { get; set; } public List<MaterialOption> changeMaterialsOptions = new List<MaterialOption>(); public List<BlendShapeOption> changeBlendShapeOptions = new List<BlendShapeOption>(); public RendererOption(Renderer r, GameObject root) { rend = r; if (rend) { mesh = rend.GetMesh(); RendEnable = rend.enabled; GetRelativePath(root); changeMaterialsOptions = rend.sharedMaterials.Select(m => new MaterialOption(m)).ToList(); if (rend is SkinnedMeshRenderer) { changeBlendShapeOptions = Enumerable.Range(0, r.GetMesh().blendShapeCount).Select(i => new BlendShapeOption((rend as SkinnedMeshRenderer).GetBlendShapeWeight(i))).ToList(); } } } public RendererOption Clone(GameObject root,bool invert = false) { var clone = new RendererOption(rend, root); if (rend) { clone.changeMaterialsOptions = changeMaterialsOptions.Select(e => e.Clone()).ToList(); clone.changeBlendShapeOptions = changeBlendShapeOptions.Select(e=> e.Clone()).ToList(); if (invert) { for (int i = 0; i < changeMaterialsOptions.Count; i++) { clone.changeMaterialsOptions[i].material = rend.sharedMaterials[i]; } if (rend is SkinnedMeshRenderer) { for (int i = 0; i < changeBlendShapeOptions.Count; i++) { clone.changeBlendShapeOptions[i].weight = (rend as SkinnedMeshRenderer).GetBlendShapeWeight(i); } } } } return clone; } public void GetRelativePath(GameObject root) { if (!rend) return; if (rend.gameObject == root) { path = ""; } else { path = rend.gameObject.name; Transform parent = rend.transform.parent; while (parent != null) { if(parent.gameObject == root) break; path = parent.name + "/" + path; parent = parent.parent; } } } public void GetRelativeGameobject(Transform root) { if (!String.IsNullOrWhiteSpace(path)) { root = root.Find(path); } if (root == null) { rend = null; return; } rend = root.gameObject.GetComponent<Renderer>(); } } [Serializable] public class MaterialOption { public bool change = false; public Material material; public float delay = -1f; // public float duration = 1f; public MaterialOption(Material mat) { material = mat; } public MaterialOption Clone() { var clone = new MaterialOption(material); clone.change = change; clone.delay = delay; // clone.duration = duration; return clone; } } [Serializable] public class BlendShapeOption { public bool change = false; public float weight; public float delay = -1f; public float duration = 1f; public BlendShapeOption(float w) { weight = w; } public BlendShapeOption Clone() { var clone = new BlendShapeOption(weight); clone.change = change; clone.delay = delay; clone.duration = duration; return clone; } } public static class AssetLink { public static Material GetMaterialByType(this FeedType type) { if (type == FeedType.Fade) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.fadeMaterial); } if (type == FeedType.Crystallize) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.crystallizeMaterial); } if (type == FeedType.Dissolve) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.disolveMaterial); } if (type == FeedType.Draw) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.drawMaterial); } if (type == FeedType.Explosion) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.explosionMaterial); } if (type == FeedType.Geom) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.geomMaterial); } if (type == FeedType.Mosaic) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.mosaicMaterial); } if (type == FeedType.Polygon) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.polygonMaterial); } if (type == FeedType.Bounce) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.scaleMaterial); } if (type == FeedType.Leaf) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.leafMaterial); } if (type == FeedType.Bloom) { return AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.bloomMaterial); } return null; } public static FeedType GetTypeByMaterial(this Material mat) { var guid = AssetUtility.GetAssetGuid(mat); if (guid == EnvironmentGUIDs.fadeMaterial) { return FeedType.Fade; } if (guid == EnvironmentGUIDs.crystallizeMaterial) { return FeedType.Crystallize; } if (guid == EnvironmentGUIDs.disolveMaterial) { return FeedType.Dissolve; } if (guid == EnvironmentGUIDs.drawMaterial) { return FeedType.Draw; } if (guid == EnvironmentGUIDs.explosionMaterial) { return FeedType.Explosion; } if (guid == EnvironmentGUIDs.geomMaterial) { return FeedType.Geom; } if (guid == EnvironmentGUIDs.mosaicMaterial) { return FeedType.Mosaic; } if (guid == EnvironmentGUIDs.polygonMaterial) { return FeedType.Polygon; } if (guid == EnvironmentGUIDs.scaleMaterial) { return FeedType.Bounce; } if (guid == EnvironmentGUIDs.leafMaterial) { return FeedType.Leaf; } if (guid == EnvironmentGUIDs.bloomMaterial) { return FeedType.Bloom; } return FeedType.None; } } public enum FeedType { None, Scale, Shader, Fade, Crystallize, Dissolve, Draw, Explosion, Geom, Mosaic, Polygon, Bounce, Leaf, Bloom, } public enum LayerGroup : int { Layer_A, Layer_B, Layer_C, Layer_D, Layer_E, Layer_F, Layer_G, Layer_H, Layer_I, Layer_J, } public enum ToggleGroup { IsToggle, } public class MenuTemplateTreeView : TreeView { private MagicalDresserInventorySaveData data; public event Action<MenuElement> OnSelect; public MenuTemplateTreeView(TreeViewState state) : base(state) { showAlternatingRowBackgrounds = true; } public MenuTemplateTreeView(TreeViewState state, MultiColumnHeader multiColumnHeader) : base(state, multiColumnHeader) { showAlternatingRowBackgrounds = true; } protected override void RowGUI (RowGUIArgs args) { var isFolder = args.item == null ? true : args.item?.id == 0 ? true : String.IsNullOrWhiteSpace(MenuTemplate.FIndTemplateElement(data.menuTemplate, args.item.id)?.menuGUID ?? ""); Rect rect = args.rowRect; rect.x += GetContentIndent(args.item); GUIStyle textStyle = new GUIStyle(GUI.skin.label); // textStyle.alignment = TextAnchor.MiddleCenter; // textStyle.fontSize = fontSize; // if ((args.item as MenuTemplateTreeViewItem).isFolder) if(isFolder) { textStyle.fontStyle = FontStyle.Bold; /*textStyle.active = new GUIStyleState() { textColor = Color.gray };*/ } else { textStyle.fontStyle = FontStyle.Italic; /*textStyle.active = new GUIStyleState() { textColor = Color.red };*/ } EditorGUI.LabelField(rect,args.item.displayName,textStyle); //toggleRect.width = 16f; //GUI.DrawTexture(toggleRect, texture); //base.RowGUI(args); } protected override void SelectionChanged (IList<int> selectedIds) { if (selectedIds.Count > 0) { var template = MenuTemplate.FIndTemplateElement(data.menuTemplate, selectedIds[0]); var menu = data.menuElements.FirstOrDefault(e => e.guid == template.menuGUID); OnSelect?.Invoke(menu); } } public List<MenuTemplate> GetSelectTemplates() { var templates = new List<MenuTemplate>(); var selectedIds = GetSelection(); if (selectedIds.Count > 0) { var template = MenuTemplate.FIndTemplateElement(data.menuTemplate, selectedIds[0]); if (template != null) { templates.Add(template); } } return templates; } protected override TreeViewItem BuildRoot() { var root = MenuTemplateTreeViewItem.CreateFolder(0,-1,"Root"); if (data.menuTemplate.Count == 0) { root.AddChild(MenuTemplateTreeViewItem.CreateMenu(1,0,"Null")); } else { foreach (var menu in data.menuTemplate) { root.AddChild(GetTreeElement(menu)); } } return root; } protected override bool CanStartDrag(TreeView.CanStartDragArgs args) { if (data.menuTemplate.Count == 0) { return false; } else { return true; } } protected override void SetupDragAndDrop(SetupDragAndDropArgs args) { DragAndDrop.PrepareStartDrag(); DragAndDrop.paths = null; DragAndDrop.objectReferences = new UnityEngine.Object[] {}; DragAndDrop.SetGenericData("MenuTemplateTreeViewItem", new List<int>(args.draggedItemIDs)); DragAndDrop.visualMode = DragAndDropVisualMode.Copy; DragAndDrop.StartDrag("MenuTemplateTreeView"); } protected override DragAndDropVisualMode HandleDragAndDrop(DragAndDropArgs args) { DragAndDropVisualMode visualMode = DragAndDropVisualMode.None; var draggedIDs = DragAndDrop.GetGenericData("MenuTemplateTreeViewItem") as List<int>; if (draggedIDs != null && draggedIDs.Count > 0) { visualMode = DragAndDropVisualMode.Move; if (args.performDrop) { foreach (var draggedID in draggedIDs) { var parent = args.parentItem == null ? null : args.parentItem?.id == 0 ? null : MenuTemplate.FIndTemplateElement(data.menuTemplate, args.parentItem.id); // メニューの子にメニューを入れない if (parent != null) if (!String.IsNullOrWhiteSpace(parent.menuGUID)) continue; var element = MenuTemplate.FIndTemplateElement(data.menuTemplate, draggedID, (e, p) => { e.RecursionAutoCreateFalse(); if (p == null) { data.menuTemplate.Remove(e); } else { p.childs.Remove(e); } //args.parentItem.children.Remove(args.parentItem.children.FirstOrDefault(c => c.id == draggedID)); }); if (element != null) { int id = args.insertAtIndex; if (parent == null) { if (id < 0 || id > data.menuTemplate.Count) { data.menuTemplate.Add(element); } else { data.menuTemplate.Insert(id,element); } } else { if (id < 0 || id > parent.childs.Count) { parent.childs.Add(element); } else { parent.childs.Insert(id,element); } } } } ReloadTemplates(); } } return visualMode; } protected override bool CanRename(TreeViewItem item) { return true; return item.displayName.Length <= 10; } protected override void RenameEnded(RenameEndedArgs args) { if (args.acceptedRename) { var template = MenuTemplate.FIndTemplateElement(data.menuTemplate, args.itemID); if (template != null) { template.name = args.newName; if (!String.IsNullOrWhiteSpace(template.menuGUID)) { var menu = data.menuElements.FirstOrDefault(e => e.guid == template.menuGUID); if (menu != null) { menu.name = args.newName; } } template.RecursionAutoCreateFalse(); } ReloadTemplates(); } } public void Setup(MagicalDresserInventorySaveData d) { data = d; ReloadTemplates(); } public void ReloadTemplates() { data.ReloadTemplates(); ReloadItemIcons(rootItem); Reload(); } public void ReloadItemIcons(TreeViewItem parent) { if(parent==null) return; if(parent.children==null) return; foreach (var item in parent.children) { if (item.id != 1) { var template = MenuTemplate.FIndTemplateElement(data.menuTemplate, item.id); if (template == null) { // parent.children.Remove(item); } else { if (String.IsNullOrWhiteSpace(template.menuGUID)) { item.displayName = template.name; item.icon = template.icon; ReloadItemIcons(item); } else { var menu = data.menuElements.FirstOrDefault(e => e.guid == template.menuGUID); if (menu == null) { // parent.children.Remove(item); } else { item.displayName = menu.name; item.icon = menu.icon; } } } } } } MenuTemplateTreeViewItem GetTreeElement(MenuTemplate template,int depth = 0) { if (template.childs.Count == 0) { var root = MenuTemplateTreeViewItem.CreateMenu(template.GetGuid(),depth,template.name,template.icon); return root; } else { var root = MenuTemplateTreeViewItem.CreateFolder(template.GetGuid(),depth,template.name,template.icon); foreach (var menu in template.childs) { root.AddChild(GetTreeElement(menu,depth+1)); } return root; } } class MenuTemplateTreeViewItem : TreeViewItem { public bool isFolder = true; public static MenuTemplateTreeViewItem CreateFolder(int id, int depth, string name, Texture2D icon = null) { return new MenuTemplateTreeViewItem() { id = id, depth = depth, displayName = name, icon = icon, isFolder = true }; } public static MenuTemplateTreeViewItem CreateMenu(int id, int depth, string name, Texture2D icon = null) { return new MenuTemplateTreeViewItem() { id = id, depth = depth, displayName = name, icon = icon, isFolder = false }; } } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/TextureCombinater.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using System.IO; using Color = UnityEngine.Color; namespace HhotateA.AvatarModifyTools.Core { public class TextureCombinater { const int maxResolution = 4096; public static Texture2D CombinateSaveTexture(Texture2D[] texs,string path = null,int tilling = 0,int margin = 0) { var combinatedTexture = CombinateTextures(texs,tilling,margin); if (!string.IsNullOrWhiteSpace(path)) combinatedTexture = ConvertToPngAndSave(path, combinatedTexture); return combinatedTexture; } public static Texture2D CombinateTextures(Texture2D[] textures,int tilling = 0,int margin = 0) { if (tilling == 0) { while (textures.Length > tilling * tilling) { tilling++; } } int resolution = Mathf.Min(textures[0].width,maxResolution/tilling); List<Texture2D> resizedTexs = new List<Texture2D>(); foreach (var texture in textures) { if(texture==null) resizedTexs.Add(ResizeTexture(Texture2D.blackTexture, resolution, resolution, margin)); else resizedTexs.Add(ResizeTexture(texture, resolution, resolution, margin)); } Texture2D combinatedTexture = new Texture2D(resolution * tilling, resolution * tilling); int i = 0; for (int column = tilling-1; column >= 0; column--) { for (int row = 0; row < tilling; row++) { if (i < resizedTexs.Count) { if (resizedTexs[i] != null) { combinatedTexture.SetPixels(row * resolution, column * resolution, resolution, resolution, GetTexturePixels(resizedTexs[i])); } else { // 透明で上書き combinatedTexture.SetPixels(row * resolution, column * resolution, resolution, resolution, Enumerable.Repeat<Color>(Color.clear, resolution * resolution).ToArray()); } } else { // 透明で上書き combinatedTexture.SetPixels(row * resolution, column * resolution, resolution, resolution, Enumerable.Repeat<Color>(Color.clear, resolution * resolution).ToArray()); } i++; } } return combinatedTexture; } public static Texture2D ResizeSaveTexture(string path,Texture2D texture, int newWidth, int newHeight) { return ConvertToPngAndSave(path, GetReadableTexture(texture,newWidth,newHeight)); } public static Texture2D ResizeTexture(Texture2D texture, int newWidth, int newHeight,int margin = 0) { if (!texture) return null; if (margin > 0) { var tempTex = new Texture2D(newWidth-2*margin, newHeight-2*margin); Graphics.ConvertTexture(texture, tempTex); var resizedTexture = new Texture2D(newWidth, newHeight); // 透明で上書き resizedTexture.SetPixels(0, 0, newWidth, newHeight, Enumerable.Repeat<Color>(Color.clear, newWidth * newHeight).ToArray()); resizedTexture.SetPixels(margin, margin, newWidth-2*margin, newHeight-2*margin, GetTexturePixels(tempTex)); resizedTexture.Apply(); return resizedTexture; } else { var resizedTexture = new Texture2D(newWidth, newHeight); Graphics.ConvertTexture(texture, resizedTexture); return resizedTexture; } } public static Texture2D ConvertToPngAndSave(string path,Texture2D texture) { if (!texture) return null; byte[] bytes = texture.EncodeToPNG(); // File.WriteAllBytes(path, bytes); using (var fs = new System.IO.FileStream(Path.GetFullPath(path), System.IO.FileMode.Create, System.IO.FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); } path = AssetUtility.GetProjectRelativePath(path); AssetDatabase.ImportAsset(path); var importer = TextureImporter.GetAtPath(path) as TextureImporter; if (importer) { importer.alphaIsTransparency = true; importer.streamingMipmaps = true; for (int texsize = 32; texsize <= texture.width; texsize = texsize * 2) { importer.maxTextureSize = texsize; } importer.SaveAndReimport(); } return AssetDatabase.LoadAssetAtPath<Texture2D>(path); } public static Texture2D ConvertToPngAndSave(string path,RenderTexture texture) { if (!texture) return null; byte[] bytes = Texture2Bytes(texture); // File.WriteAllBytes(path, bytes); using (var fs = new System.IO.FileStream(Path.GetFullPath(path), System.IO.FileMode.Create, System.IO.FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); } path = AssetUtility.GetProjectRelativePath(path); AssetDatabase.ImportAsset(path); var importer = TextureImporter.GetAtPath(path) as TextureImporter; if (importer) { importer.alphaIsTransparency = true; importer.streamingMipmaps = true; for (int texsize = 32; texsize <= texture.width; texsize = texsize * 2) { importer.maxTextureSize = texsize; } importer.SaveAndReimport(); } return AssetDatabase.LoadAssetAtPath<Texture2D>(path); } public static Color[] GetTexturePixels(Texture2D texture) { return GetReadableTexture(texture).GetPixels(); } public static Texture2D GetReadableTexture(Texture2D texture, int newWidth=0, int newHeight=0) { if (!texture) return null; int width = newWidth == 0 ? texture.width : newWidth; int height = newHeight == 0 ? texture.height : newHeight; RenderTexture rt = RenderTexture.GetTemporary( width,height,0, RenderTextureFormat.Default, RenderTextureReadWrite.Default); RenderTexture currentRT = RenderTexture.active; Graphics.Blit(texture, rt); RenderTexture.active = rt; var t = new Texture2D(width,height); t.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); t.Apply(); RenderTexture.active = currentRT; RenderTexture.ReleaseTemporary(rt); return t; } public static RenderTexture GetReadableRenderTexture(Texture texture) { if (!texture) return null; RenderTexture rt = new RenderTexture(texture.width,texture.height,0,RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); rt.enableRandomWrite = true; rt.Create(); RenderTexture currentRT = RenderTexture.active; Graphics.Blit(texture, rt); RenderTexture.active = currentRT; rt.name = texture.name; return rt; } public static Texture2D Bytes2Texture(byte[] bytes) { int pos = 16; int width = 0; for (int i = 0; i < 4; i++) { width = width * 256 + bytes[pos++]; } int height = 0; for (int i = 0; i < 4; i++) { height = height * 256 + bytes[pos++]; } Texture2D texture = new Texture2D(width, height, TextureFormat.RGBAFloat, false); texture.LoadImage(bytes); return texture; } public static byte[] Texture2Bytes(RenderTexture texture) { if (!texture) return null; Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGBAFloat, false); var current = RenderTexture.active; RenderTexture.active = texture; tex.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0); RenderTexture.active = current; tex.Apply(); return tex.EncodeToPNG(); } public static Color GetPixel(RenderTexture rt,int x,int y) { var currentRT = RenderTexture.active; RenderTexture.active = rt; var texture = new Texture2D(rt.width, rt.height); texture.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); texture.Apply(); var colors = texture.GetPixel(x,y); RenderTexture.active = currentRT; return colors; } public static Texture2D Texture2Texture2D(Texture texture) { if (!texture) return null; var result = new Texture2D( texture.width, texture.height, TextureFormat.RGBA32, false ); var currentRT = RenderTexture.active; var rt = new RenderTexture( texture.width, texture.height, 32 ); Graphics.Blit( texture, rt ); RenderTexture.active = rt; var source = new Rect( 0, 0, rt.width, rt.height ); result.ReadPixels( source, 0, 0 ); result.Apply(); RenderTexture.active = currentRT; return result; } public static Texture2DArray CreateTexture2DArray(Texture2D[] textures) { textures = textures.Where(t => t != null).ToArray(); int widthMax = textures.Max(t => t.width); int width = 1; while (width < widthMax) { width *= 2; } int heightMax = textures.Max(t => t.height); int height = 1; while (height < heightMax) { height *= 2; } var result = new Texture2DArray(width, height, textures.Length, TextureFormat.ARGB32, true) { filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, }; for (var i = 0; i < textures.Length; i++) { var texture = GetReadableTexture(textures[i]); texture = ResizeTexture(texture, width, height); result.SetPixels(GetTexturePixels(texture), i, 0); } result.Apply(); return result; } public static Vector4[] GetGradientBuffer(Gradient gradient,int step = 256) { var buffer = new Vector4[step]; for (int i = 0;i<step;i++) { buffer[i] = gradient.Evaluate((float)i / (float)step); } return buffer; } public static int GetMipMapCount(Texture2D tex) { return tex.mipmapCount; } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/TexturePainter.shader<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ Shader "HhotateA/TexturePainter" { Properties { _Overlay ("_Overlay",2D) = "black" {} _Color0 ("Color", Color) = (1,1,1,1) _Color1 ("Color", Color) = (1,1,1,1) _Color2 ("Color", Color) = (1,1,1,1) _Color3 ("Color", Color) = (1,1,1,1) _Color4 ("Color", Color) = (1,1,1,1) _Color5 ("Color", Color) = (1,1,1,1) _Color6 ("Color", Color) = (1,1,1,1) _Color7 ("Color", Color) = (1,1,1,1) _Color8 ("Color", Color) = (1,1,1,1) _Color9 ("Color", Color) = (1,1,1,1) _Color10 ("Color", Color) = (1,1,1,1) _Color11 ("Color", Color) = (1,1,1,1) _Color12 ("Color", Color) = (1,1,1,1) _Color13 ("Color", Color) = (1,1,1,1) _Color14 ("Color", Color) = (1,1,1,1) //_Color15 ("Color", Color) = (1,1,1,1) _Comparison0 ("Color", Color) = (1,1,1,1) _Comparison1 ("Color", Color) = (1,1,1,1) _Comparison2 ("Color", Color) = (1,1,1,1) _Comparison3 ("Color", Color) = (1,1,1,1) _Comparison4 ("Color", Color) = (1,1,1,1) _Comparison5 ("Color", Color) = (1,1,1,1) _Comparison6 ("Color", Color) = (1,1,1,1) _Comparison7 ("Color", Color) = (1,1,1,1) _Comparison8 ("Color", Color) = (1,1,1,1) _Comparison9 ("Color", Color) = (1,1,1,1) _Comparison10 ("Color", Color) = (1,1,1,1) _Comparison11 ("Color", Color) = (1,1,1,1) _Comparison12 ("Color", Color) = (1,1,1,1) _Comparison13 ("Color", Color) = (1,1,1,1) _Comparison14 ("Color", Color) = (1,1,1,1) //_Comparison15 ("Color", Color) = (1,1,1,1) _Layer0 ("",2D) = "black" {} _Layer1 ("",2D) = "black" {} _Layer2 ("",2D) = "black" {} _Layer3 ("",2D) = "black" {} _Layer4 ("",2D) = "black" {} _Layer5 ("",2D) = "black" {} _Layer6 ("",2D) = "black" {} _Layer7 ("",2D) = "black" {} _Layer8 ("",2D) = "black" {} _Layer9 ("",2D) = "black" {} _Layer10 ("",2D) = "black" {} _Layer11 ("",2D) = "black" {} _Layer12 ("",2D) = "black" {} _Layer13 ("",2D) = "black" {} _Layer14 ("",2D) = "black" {} //_Layer15 ("",2D) = "black" {} _Mode0 ("",int) = 1 _Mode1 ("",int) = 1 _Mode2 ("",int) = 1 _Mode3 ("",int) = 1 _Mode4 ("",int) = 1 _Mode5 ("",int) = 1 _Mode6 ("",int) = 1 _Mode7 ("",int) = 1 _Mode8 ("",int) = 1 _Mode9 ("",int) = 1 _Mode10 ("",int) = 1 _Mode11 ("",int) = 1 _Mode12 ("",int) = 1 _Mode13 ("",int) = 1 _Mode14 ("",int) = 1 _Mode15 ("",int) = 1 _Alpha0 ("",int) = 1 _Alpha1 ("",int) = 1 _Alpha2 ("",int) = 1 _Alpha3 ("",int) = 1 _Alpha4 ("",int) = 1 _Alpha5 ("",int) = 1 _Alpha6 ("",int) = 1 _Alpha7 ("",int) = 1 _Alpha8 ("",int) = 1 _Alpha9 ("",int) = 1 _Alpha10 ("",int) = 1 _Alpha11 ("",int) = 1 _Alpha12 ("",int) = 1 _Alpha13 ("",int) = 1 _Alpha14 ("",int) = 1 //_Alpha15 ("",int) = 1 _Settings0 ("Settings", vector) = (0,0,0,0) _Settings1 ("Settings", vector) = (0,0,0,0) _Settings2 ("Settings", vector) = (0,0,0,0) _Settings3 ("Settings", vector) = (0,0,0,0) _Settings4 ("Settings", vector) = (0,0,0,0) _Settings5 ("Settings", vector) = (0,0,0,0) _Settings6 ("Settings", vector) = (0,0,0,0) _Settings7 ("Settings", vector) = (0,0,0,0) _Settings8 ("Settings", vector) = (0,0,0,0) _Settings9 ("Settings", vector) = (0,0,0,0) _Settings10 ("Settings", vector) = (0,0,0,0) _Settings11 ("Settings", vector) = (0,0,0,0) _Settings12 ("Settings", vector) = (0,0,0,0) _Settings13 ("Settings", vector) = (0,0,0,0) _Settings14 ("Settings", vector) = (0,0,0,0) //_Settings15 ("Settings", vector) = (0,0,0,0) _Mask0 ("",int) = -1 _Mask1 ("",int) = -1 _Mask2 ("",int) = -1 _Mask3 ("",int) = -1 _Mask4 ("",int) = -1 _Mask5 ("",int) = -1 _Mask6 ("",int) = -1 _Mask7 ("",int) = -1 _Mask8 ("",int) = -1 _Mask9 ("",int) = -1 _Mask10 ("",int) = -1 _Mask11 ("",int) = -1 _Mask12 ("",int) = -1 _Mask13 ("",int) = -1 _Mask14 ("",int) = -1 //_Mask15 ("",int) = -1 } SubShader { Lighting Off Blend One Zero Pass { Name "Update" CGPROGRAM #include "UnityCustomRenderTexture.cginc" #pragma vertex InitCustomRenderTextureVertexShader #pragma fragment frag #pragma target 3.0 /*enum BlendMode { disable, normal, additive, multiply, subtraction, division, bloom, hsv, color, alphaMask };*/ #define Layer(num) \ uniform float4 _Color##num;\ uniform float4 _Comparison##num;\ uniform sampler2D _Layer##num;\ uniform float4 _Layer##num##_ST;\ uniform int _Mode##num;\ uniform int _Alpha##num;\ uniform float4 _Settings##num;\ uniform int _Mask##num;\ #define LayerCol(origin,num,mask) \ if(_Mask##num == -1)\ {\ ##origin = lerp(\ ##origin,\ OverrideColor(##origin,_Layer##num,TRANSFORM_TEX(IN.localTexcoord.xy,_Layer##num),_Color##num,_Comparison##num,_Settings##num,_Mode##num,_Alpha##num),\ float4(mask.rgb*mask.a,mask.a));\ }\ else\ {\ ##mask = OverrideColor(##mask,_Layer##num,TRANSFORM_TEX(IN.localTexcoord.xy,_Layer##num),_Color##num,_Comparison##num,_Settings##num,_Mode##num,_Alpha##num);\ }\ /*float4 _Color0,_Color1,_Color2,_Color3,_Color4,_Color5,_Color6,_Color7,_Color8,_Color9,_Color10,_Color11,_Color12,_Color13,_Color14,_Color15; sampler2D _Layer0,_Layer1,_Layer2,_Layer3,_Layer4,_Layer5,_Layer6,_Layer7,_Layer8,_Layer9,_Layer10,_Layer11,_Layer12,_Layer13,_Layer14,_Layer15; float4 _Layer0_ST,_Layer1_ST,_Layer2_ST,_Layer3_ST,_Layer4_ST,_Layer5_ST,_Layer6_ST,_Layer7_ST,_Layer8_ST,_Layer9_ST,_Layer10_ST,_Layer11_ST,_Layer12_ST,_Layer13_ST,_Layer14_ST,_Layer15_ST; int _Mode0,_Mode1,_Mode2,_Mode3,_Mode4,_Mode5,_Mode6,_Mode7,_Mode8,_Mode9,_Mode10,_Mode11,_Mode12,_Mode13,_Mode14,_Mode15;*/ sampler2D _Overlay; float4 _Overlay_ST; Layer(0) Layer(1) Layer(2) Layer(3) Layer(4) Layer(5) Layer(6) Layer(7) Layer(8) Layer(9) Layer(10) Layer(11) Layer(12) Layer(13) Layer(14) //Layer(15) static float3 linecolumn[41]={ float3(-4.0, 0.0, 1.0), float3(-3.0,-1.0, 4.0), float3(-3.0, 0.0, 1.0), float3(-3.0, 1.0, 4.0), float3(-2.0,-2.0, 6.0), float3(-2.0,-1.0, 3.0), float3(-2.0, 0.0,17.0), float3(-2.0, 1.0, 3.0), float3(-2.0, 2.0, 6.0), float3(-1.0,-3.0, 4.0), float3(-1.0,-2.0, 3.0), float3(-1.0,-1.0,26.0), float3(-1.0, 0.0,10.0), float3(-1.0, 1.0,26.0), float3(-1.0, 2.0, 3.0), float3(-1.0, 3.0, 4.0), float3( 0.0,-4.0, 1.0), float3( 0.0,-3.0, 1.0), float3( 0.0,-2.0,17.0), float3( 0.0,-1.0,10.0), float3( 0.0, 0.0,31.0), float3( 0.0, 1.0,10.0), float3( 0.0, 2.0,17.0), float3( 0.0, 3.0, 1.0), float3( 0.0, 4.0, 1.0), float3( 1.0,-3.0, 4.0), float3( 1.0,-2.0, 3.0), float3( 1.0,-1.0,26.0), float3( 1.0, 0.0,10.0), float3( 1.0, 1.0,26.0), float3( 1.0, 2.0, 3.0), float3( 1.0, 3.0, 4.0), float3( 2.0,-2.0, 6.0), float3( 2.0,-1.0, 3.0), float3( 2.0, 0.0,17.0), float3( 2.0, 1.0, 3.0), float3( 2.0, 2.0, 6.0), float3( 3.0,-1.0, 4.0), float3( 3.0, 0.0, 1.0), float3( 3.0, 1.0, 4.0), float3( 4.0, 0.0, 1.0), }; inline float3 rgb2hsv(float3 c) { float4 K = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); float4 p = lerp(float4(c.bg, K.wz), float4(c.gb, K.xy), step(c.b, c.g)); float4 q = lerp(float4(p.xyw, c.r), float4(c.r, p.yzx), step(p.x, c.r)); float d = q.x - min(q.w, q.y); float e = 1.0e-10; return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); } inline fixed3 hsv2rgb(float3 hsv){ fixed4 t = fixed4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); fixed3 p = abs(frac(hsv.xxx + t.xyz) * 6.0 - t.www); return hsv.z * lerp(t.xxx, clamp(p - t.xxx, 0.0, 1.0), hsv.y); } float getGray(float4 rgb) { return (rgb.x+rgb.y+rgb.z)*rgb.w*0.3333333333333333; } float getGray(float3 rgb) { return (rgb.x+rgb.y+rgb.z)*0.3333333333333333; } float4 OverrideColor(float4 col,sampler2D tex,float2 uv,float4 color,float4 comparison,float4 settings,int mode,int alpha) { if(uv.x<0.0 || 1.0<uv.x || uv.y<0.0 || 1.0<uv.y ) return col; float4 l = tex2D(tex,uv); float4 lc = l*color; if(mode == 1) // normal { col.rgb = lerp( lerp(col.rgb,lc.rgb,lc.a), lc.rgb, lc.a); col.a = saturate(col.a+(1.0-col.a)*lc.a); } else if (mode == 2) // additive { col.rgb = lerp(col.rgb,col.rgb+lc.rgb,lc.a); } else if (mode == 3) // multiply { col.rgb = lerp(col.rgb,col.rgb*lc.rgb,lc.a); } else if (mode == 4) // subtraction { col.rgb = lerp(col.rgb,col.rgb-lc.rgb,lc.a); } else if (mode == 5) //division { if(l.a>0.0) { col.rgb = lerp(col.rgb,saturate(col.rgb/max(lc.rgb,0.001)),lc.a); } } else if(mode == 6) // bloom { float4 sumcolor = (float4)0.0; #ifdef RichBloom [unroll] for(int index=0;index<41;index++) { float2 offsetUV = uv + float2(settings.x*linecolumn[index].x,settings.y*linecolumn[index].y) * settings.z; float4 sc = tex2D(tex,offsetUV)*color; float sv = pow(saturate(linecolumn[index].z/31.0) , 1.0-saturate(getGray(sc)/settings.w)); sumcolor += sc * sv; } sumcolor = sumcolor*31.0/331.0; #else sumcolor += tex2D(tex,uv+float2(-settings.x,-settings.y) * settings.z)*color; sumcolor += tex2D(tex,uv+float2(-settings.x, settings.y) * settings.z)*color; sumcolor += tex2D(tex,uv+float2( settings.x,-settings.y) * settings.z)*color; sumcolor += tex2D(tex,uv+float2( settings.x, settings.y) * settings.z)*color; sumcolor *= 0.25; #endif col.rgb = lerp( lerp(col.rgb,sumcolor.rgb,sumcolor.a), sumcolor.rgb, lc.a); } else if(mode == 7) // HSV { float3 hsv = rgb2hsv(col.rgb); hsv = float3( settings.x <= 0.0 ? hsv.x + settings.x : settings.x, settings.y <= 0.0 ? lerp(0.0,hsv.y,settings.y+1.0) : lerp(hsv.y,1.0,settings.y), settings.z <= 0.0 ? lerp(0.0,hsv.z,settings.z+1.0) : lerp(hsv.z,1.0,settings.z)); float3 rgb = hsv2rgb(float3(hsv.x,hsv.y,hsv.z)); col.rgb = lerp(col.rgb,rgb,getGray(lc)); } else if(mode == 8) // color { float a = 1.0/((2.0-settings.x)*settings.w); float d = -a*distance(col,comparison) + a * settings.x*settings.w; float4 c = lerp( 0, color - lerp(comparison,col,settings.z), pow(saturate(d),1.0-settings.y) ); col += c * getGray(l); } else if(mode == 9) // Alpha Mask { col.a = lerp(col.a,getGray(lc.rgb),lc.a); } else if(mode == 10) // override { col = l; } return col; } float4 frag(v2f_customrendertexture IN) : COLOR { float4 col = float4(0,0,0,0); float4 mask = float4(1,1,1,1); /*col = OverrideColor(col,_Layer0,TRANSFORM_TEX(IN.localTexcoord.xy,_Layer0),_Color0,_Settings0,_Mode0); col = tex2D(_Layer0,IN.localTexcoord.xy);*/ //col = tex2D(_Layer0,IN.localTexcoord.xy); LayerCol(col,0,mask); LayerCol(col,1,mask); LayerCol(col,2,mask); LayerCol(col,3,mask); LayerCol(col,4,mask); LayerCol(col,5,mask); LayerCol(col,6,mask); LayerCol(col,7,mask); LayerCol(col,8,mask); LayerCol(col,9,mask); LayerCol(col,10,mask); LayerCol(col,11,mask); LayerCol(col,12,mask); LayerCol(col,13,mask); LayerCol(col,14,mask); //LayerCol(col,15,mask); float4 overlay = tex2D(_Overlay, TRANSFORM_TEX(IN.localTexcoord.xy,_Overlay)); //return overlay; return lerp(col,overlay,overlay.a); } ENDCG } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/TextureCreater.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System.Collections.Generic; using UnityEngine; using System.Linq; using System.Runtime.InteropServices; namespace HhotateA.AvatarModifyTools.Core { public class TextureCreator { public string name = ""; private CustomRenderTexture targetTexture; private Material targetMaterial; // private int editIndex = -1; private List<LayerData> layerDatas = new List<LayerData>(); public List<LayerData> LayerDatas => layerDatas; public LayerData GetLayerData(int index) => layerDatas[index]; private LayerData editLayer; private int maxLayer = 14; public TextureCreator(Texture baselayer) { name = baselayer.name; if (baselayer != null) { ResizeTexture(baselayer.width, baselayer.height); AddLayer(baselayer); } } ComputeShader GetComputeShader() { return AssetUtility.LoadAssetAtGuid<ComputeShader>(EnvironmentVariable.computeShader); } public Texture GetTexture(int index = -1) { if (0 <= index && index < LayerCount()) { return layerDatas[index].texture; } // SyncLayers(false); return targetTexture; } public void SetLayers(List<LayerData> layers) { foreach (var layer in layerDatas) { layer.Release(); } layerDatas = layers; } public void AddLayers(List<LayerData> layers) { layers.AddRange(layerDatas); layerDatas = layers; } // 最大キャッシュ数 private int maxCaches { get => EnvironmentVariable.maxCaches; } private List<RenderTexture> caches = new List<RenderTexture>(); private int cashIndex = -1; public RenderTexture GetEditTexture() { return editLayer.texture; } public LayerData GetEditLayer() { return editLayer; } public RenderTexture GetTemporaryTexture() { RenderTexture maskTexture = RenderTexture .GetTemporary(GetEditTexture().width, GetEditTexture().height, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); maskTexture.enableRandomWrite = true; maskTexture.Create(); var currentRT = RenderTexture.active; Graphics.Blit(GetTexture(), maskTexture); RenderTexture.active = currentRT; return maskTexture; } public void AddCash() { var cash = RenderTexture.Instantiate(GetEditTexture()); var currentRT = RenderTexture.active; Graphics.Blit(GetEditTexture(),cash); RenderTexture.active = currentRT; while (cashIndex+1 < caches.Count) { caches[caches.Count-1].Release(); caches[caches.Count-1].DiscardContents(); caches.RemoveAt(caches.Count-1); } if (caches.Count > maxCaches) { caches[1].Release(); caches[1].DiscardContents(); caches.RemoveAt(1); } caches.Add(cash); cashIndex = caches.Count - 1; } public bool CanUndo() { return cashIndex > 0; } public void UndoEditTexture() { if (CanUndo()) { var currentRT = RenderTexture.active; Graphics.Blit(caches[cashIndex-1],GetEditTexture()); RenderTexture.active = currentRT; cashIndex--; } } public bool CanRedo() { return cashIndex < caches.Count-1; } public void RedoEditTexture() { if (CanRedo()) { var currentRT = RenderTexture.active; Graphics.Blit(caches[cashIndex+1],GetEditTexture()); RenderTexture.active = currentRT; cashIndex++; } } public void ResetCashes() { foreach (var cache in caches) { cache.Release(); } caches = new List<RenderTexture>(); cashIndex = -1; } public int LayerCount() { return layerDatas.Count; } public void ResizeTexture(int width, int height) { if(targetTexture) targetTexture.Release(); targetTexture = new CustomRenderTexture(width,height); targetMaterial = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentVariable.texturePainterShader)); targetTexture.initializationSource = CustomRenderTextureInitializationSource.Material; targetTexture.initializationMode = CustomRenderTextureUpdateMode.OnDemand; targetTexture.updateMode = CustomRenderTextureUpdateMode.OnDemand; /*targetTexture.initializationMode = CustomRenderTextureUpdateMode.Realtime; targetTexture.updateMode = CustomRenderTextureUpdateMode.Realtime;*/ targetTexture.initializationMaterial = targetMaterial; targetTexture.material = targetMaterial; targetTexture.Create(); targetTexture.Initialize(); SyncLayers(); } public void AddLayer(Texture tex = null) { if(LayerCount() > maxLayer) return; if (tex == null) { var rt = new RenderTexture(targetTexture.width,targetTexture.height,0,RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); rt.enableRandomWrite = true; rt.Create(); tex = rt; tex.name = "NewLayer" + LayerCount().ToString(); } else { tex = TextureCombinater.GetReadableRenderTexture(tex); } layerDatas.Insert(0,new LayerData((RenderTexture)tex)); SyncLayers(); } public void AddLayer(Color col,Gradient gradient = null) { if(LayerCount() > maxLayer) return; if(gradient==null) gradient = new Gradient(); var rt = new RenderTexture(targetTexture.width,targetTexture.height,0,RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); rt.enableRandomWrite = true; rt.Create(); var tex = rt; ClearColor(tex,col,gradient); tex.name = "NewLayer" + LayerCount().ToString(); layerDatas.Insert(0,new LayerData((RenderTexture)tex) { active = true, }); SyncLayers(); } public void AddMask(Color col,Gradient gradient = null) { if(LayerCount() > maxLayer) return; if(gradient==null) gradient = new Gradient(); var rt = new RenderTexture(targetTexture.width,targetTexture.height,0,RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); rt.enableRandomWrite = true; rt.Create(); var tex = rt; ClearColor(tex,col,gradient); tex.name = "Mask" + LayerCount().ToString(); layerDatas.Insert(0,new LayerData((RenderTexture)tex) { active = true, layerMode = BlendMode.Override, isMask = true }); SyncLayers(); } public Texture SyncLayers() { for (int i = 0; i < maxLayer; i++) { if (i < LayerCount()) { var ld = layerDatas[layerDatas.Count-1-i]; targetMaterial.SetTexture("_Layer"+i,ld.texture); targetMaterial.SetTextureScale("_Layer"+i,new Vector2(ld.scale.x,ld.scale.y)); targetMaterial.SetTextureOffset("_Layer"+i,new Vector2(ld.offset.x,ld.offset.y)); targetMaterial.SetInt("_Mode"+i, ld.active ? (int) ld.layerMode : (int) BlendMode.Disable); targetMaterial.SetColor("_Color"+i, ld.color); targetMaterial.SetColor("_Comparison"+i, ld.comparison); if (ld.layerMode == BlendMode.HSV) { targetMaterial.SetVector("_Settings"+i, ld.settings); } else if(ld.layerMode == BlendMode.Color) { targetMaterial.SetVector("_Settings"+i, new Vector4(1f, 0f, ld.settings.z, ld.settings.w)); } else if(ld.layerMode == BlendMode.Bloom) { targetMaterial.SetVector("_Settings"+i, new Vector4(1f/(float)ld.texture.width, 1f/(float)ld.texture.height, ld.settings.z, ld.settings.w)); } targetMaterial.SetInt("_Mask"+i, ld.isMask ? 1 : -1); } else { targetMaterial.SetTexture("_Layer"+i,null); } } return targetTexture; } public void LayersUpdate() { SyncLayers(); targetTexture.Initialize(); } public void ChangeEditLayer(int index) { if (0 <= index && index < LayerCount()) { editLayer = layerDatas[index]; ResetCashes(); AddCash(); } } public void ReplaceLayer(int from,int to) { if (from < LayerCount() && to < LayerCount()) { var l = layerDatas[from]; layerDatas[from] = layerDatas[to]; layerDatas[to] = l; } } public void DeleateLayer(int index) { layerDatas[index].texture.Release(); layerDatas[index].texture.DiscardContents(); layerDatas.RemoveAt(index); } public void CopyLayer(int index) { layerDatas.Insert(0,new LayerData(TextureCombinater.GetReadableRenderTexture(layerDatas[index].texture)) { active = layerDatas[index].active, color = layerDatas[index].color, comparison = layerDatas[index].comparison, isMask = layerDatas[index].isMask, layerMode = layerDatas[index].layerMode, name = layerDatas[index].name, offset = layerDatas[index].offset, scale = layerDatas[index].scale, settings = layerDatas[index].settings }); } public void SetLayerActive(int index,bool val) { layerDatas[index].active = val; } public void DrawLine(Vector2 from,Vector2 to,Color brushColor,Gradient gradient,float brushWidth,float brushStrength,float brushPower = 0f) { if (editLayer == null) return; if (0f < from.x && from.x < 1f && 0f < from.y && from.y < 1f && 0f < to.x && to.x < 1f && 0f < to.y && to.y < 1f) { var compute = GetComputeShader(); int kernel = compute.FindKernel("DrawLine"); compute.SetInt("_Width",GetEditTexture().width); compute.SetInt("_Height",GetEditTexture().height); compute.SetVector("_Color",brushColor); compute.SetVector("_FromPoint",from); compute.SetVector("_ToPoint",to); compute.SetFloat("_BrushWidth",brushWidth); compute.SetFloat("_BrushStrength",brushStrength); compute.SetFloat("_BrushPower",brushPower); compute.SetTexture(kernel,"_ResultTex",GetEditTexture()); compute.Dispatch(kernel, GetEditTexture().width,GetEditTexture().height,1); } } public void FillTriangle(Mesh mesh,int index,Color color,int areaExpansion = 1) { var compute = GetComputeShader(); int kernel = compute.FindKernel("TriangleFill"); var uvs = new ComputeBuffer(mesh.uv.Length,Marshal.SizeOf(typeof(Vector2))); var tris = new ComputeBuffer(mesh.triangles.Length,sizeof(int)); uvs.SetData(mesh.uv); tris.SetData(mesh.triangles); compute.SetBuffer(kernel,"_UVs",uvs); compute.SetBuffer(kernel,"_Triangles",tris); compute.SetTexture(kernel, "_ResultTex", GetEditTexture()); compute.SetVector("_Color", color); compute.SetInt("_Width", GetEditTexture().width); compute.SetInt("_Height", GetEditTexture().height); compute.SetInt("_TriangleID", index); compute.SetInt("_AreaExpansion", areaExpansion); compute.Dispatch(kernel, GetEditTexture().width, GetEditTexture().height, 1); uvs.Release(); tris.Release(); } public void FillTriangles(Mesh mesh,List<int> index,Color color,Gradient gradient,Vector2 from, Vector2 to,int areaExpansion = 1) { var compute = GetComputeShader(); int kernel = compute.FindKernel("TriangleFillGradient"); var xmax = mesh.vertices.Max(v => v.x); var xmin = mesh.vertices.Min(v => v.x); var ymax = mesh.vertices.Max(v => v.y); var ymin = mesh.vertices.Min(v => v.y); var zmax = mesh.vertices.Max(v => v.z); var zmin = mesh.vertices.Min(v => v.z); var normalizedVertices = mesh.vertices.Select(v => new Vector3( v.x * (xmax - xmin) - xmin, v.y * (ymax - ymin) - ymin, v.z * (zmax - zmin) - zmin)).ToArray(); var uvs = new ComputeBuffer(mesh.uv.Length,Marshal.SizeOf(typeof(Vector2))); var verts = new ComputeBuffer(mesh.vertices.Length,Marshal.SizeOf(typeof(Vector3))); var tris = new ComputeBuffer(mesh.triangles.Length,sizeof(int)); uvs.SetData(mesh.uv); verts.SetData(mesh.vertices); tris.SetData(mesh.triangles); compute.SetBuffer(kernel,"_UVs",uvs); compute.SetBuffer(kernel,"_Vertices",uvs); compute.SetBuffer(kernel,"_Triangles",tris); compute.SetTexture(kernel, "_ResultTex", GetEditTexture()); compute.SetVector("_Color", color); compute.SetInt("_Width", GetEditTexture().width); compute.SetInt("_Height", GetEditTexture().height); compute.SetVector("_FromPoint",from); compute.SetVector("_ToPoint",to); var gradientBuffer = new ComputeBuffer(256, Marshal.SizeOf(typeof(Vector4))); gradientBuffer.SetData(TextureCombinater.GetGradientBuffer(gradient,256)); compute.SetBuffer(kernel, "_Gradient", gradientBuffer); compute.SetInt("_AreaExpansion", areaExpansion); for (int i = 0; i < index.Count; i++) { if (0 < index[i] && index[i] < mesh.triangles.Length / 3) { compute.SetInt("_TriangleID", index[i]); compute.Dispatch(kernel, GetEditTexture().width, GetEditTexture().height, 1); } } uvs.Release(); verts.Release(); tris.Release(); gradientBuffer.Release(); } public void ReadUVMap(Mesh mesh) { RenderTexture uvMap = new RenderTexture(targetTexture.width,targetTexture.height,0,RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); uvMap.enableRandomWrite = true; uvMap.Create(); uvMap.name = "UVMap"; var compute = GetComputeShader(); int kernel = compute.FindKernel("DrawUV"); var uvs = new ComputeBuffer(mesh.uv.Length,Marshal.SizeOf(typeof(Vector2))); var tris = new ComputeBuffer(mesh.triangles.Length,sizeof(int)); uvs.SetData(mesh.uv); tris.SetData(mesh.triangles); compute.SetInt("_Width",uvMap.width); compute.SetInt("_Height",uvMap.height); compute.SetVector("_Color",Vector4.one); compute.SetBuffer(kernel,"_UVs",uvs); compute.SetBuffer(kernel,"_Triangles",tris); compute.SetTexture(kernel,"_ResultTex",uvMap); compute.Dispatch(kernel, mesh.triangles.Length/3,1,1); uvs.Release(); tris.Release(); AddLayer(uvMap); } public void ClearColor(Texture rt,Color color,Gradient gradient) { var compute = GetComputeShader(); int kernel = compute.FindKernel("ClearColorGradient"); compute.SetVector("_Color",color); compute.SetTexture(kernel,"_ResultTex",rt); var gradientBuffer = new ComputeBuffer(rt.height, Marshal.SizeOf(typeof(Vector4))); gradientBuffer.SetData(TextureCombinater.GetGradientBuffer(gradient,rt.height)); compute.SetBuffer(kernel, "_Gradient", gradientBuffer); compute.Dispatch(kernel, rt.width,rt.height,1); gradientBuffer.Release(); } public void FillColor(Vector2 uv, Color brushColor,Gradient gradient,float threshold = 0.007f,int areaExpansion = 1,bool maskAllLayers = true) { if (0f < uv.x && uv.x < 1f && 0f < uv.y && uv.y < 1f) { RenderTexture maskTexture = maskAllLayers ? GetTemporaryTexture() : GetEditTexture(); var compute = GetComputeShader(); Vector2Int pix = new Vector2Int( (int) (uv.x * (float) maskTexture.width), (int) (uv.y * (float) maskTexture.height)); // 種まき var seedPixelsArray = Enumerable.Range(0, maskTexture.width * maskTexture.height) .Select(_ => 0).ToArray(); seedPixelsArray[maskTexture.width * pix.y + pix.x] = 2; var seedPixels = new ComputeBuffer(seedPixelsArray.Length, sizeof(int)); seedPixels.SetData(seedPixelsArray); compute.SetFloat("_ColorMargin", threshold); compute.SetInt("_Width", maskTexture.width); compute.SetInt("_Height", maskTexture.height); compute.SetVector("_Color", brushColor); // 領域判定 int kernel = compute.FindKernel("SeedFill"); compute.SetTexture(kernel, "_ResultTex", maskTexture); compute.SetBuffer(kernel, "_SeedPixels", seedPixels); for (int i = 0; i < 10; i++) { for (int j = 0; j < 50; j++) { compute.Dispatch(kernel, maskTexture.width, maskTexture.height, 1); } seedPixels.GetData(seedPixelsArray); int jobCount = seedPixelsArray.Where(s => s == 2).Count(); if (seedPixelsArray.Where(s => s == 2).Count() == 0) break; } // 色塗り kernel = compute.FindKernel("FillColorPointGradient"); compute.SetVector("_Point",uv); compute.SetInt("_Width", GetEditTexture().width); compute.SetInt("_Height", GetEditTexture().height); compute.SetTexture(kernel, "_ResultTex", GetEditTexture()); var gradientBuffer = new ComputeBuffer(GetEditTexture().width, Marshal.SizeOf(typeof(Vector4))); gradientBuffer.SetData(TextureCombinater.GetGradientBuffer(gradient,GetEditTexture().width)); compute.SetBuffer(kernel, "_Gradient", gradientBuffer); compute.SetBuffer(kernel, "_SeedPixels", seedPixels); compute.SetInt("_AreaExpansion", areaExpansion); compute.Dispatch(kernel, GetEditTexture().width, GetEditTexture().height, 1); seedPixels.Release(); gradientBuffer.Release(); if(maskAllLayers) RenderTexture.ReleaseTemporary(maskTexture); } } public void FillColor(Vector2 from, Vector2 to, Color brushColor,Gradient gradient,float threshold = 0.007f,int areaExpansion = 1,bool maskAllLayers = true) { if (0f < to.x && to.x < 1f && 0f < to.y && to.y < 1f) { RenderTexture maskTexture = maskAllLayers ? GetTemporaryTexture() : GetEditTexture(); var compute = GetComputeShader(); Vector2Int pix = new Vector2Int( (int) (to.x * (float) maskTexture.width), (int) (to.y * (float) maskTexture.height)); // 種まき var seedPixelsArray = Enumerable.Range(0, maskTexture.width * maskTexture.height) .Select(_ => 0).ToArray(); seedPixelsArray[maskTexture.width * pix.y + pix.x] = 2; var seedPixels = new ComputeBuffer(seedPixelsArray.Length, sizeof(int)); seedPixels.SetData(seedPixelsArray); compute.SetFloat("_ColorMargin", threshold); compute.SetInt("_Width", maskTexture.width); compute.SetInt("_Height", maskTexture.height); compute.SetVector("_Color", brushColor); // 領域判定 int kernel = compute.FindKernel("SeedFill"); compute.SetTexture(kernel, "_ResultTex", maskTexture); compute.SetBuffer(kernel, "_SeedPixels", seedPixels); for (int i = 0; i < 10; i++) { for (int j = 0; j < 50; j++) { compute.Dispatch(kernel, maskTexture.width, maskTexture.height, 1); } seedPixels.GetData(seedPixelsArray); int jobCount = seedPixelsArray.Where(s => s == 2).Count(); if (seedPixelsArray.Where(s => s == 2).Count() == 0) break; } // 色塗り kernel = compute.FindKernel("FillColorLineGradient"); compute.SetVector("_FromPoint",from); compute.SetVector("_ToPoint",to); compute.SetInt("_Width", GetEditTexture().width); compute.SetInt("_Height", GetEditTexture().height); compute.SetTexture(kernel, "_ResultTex", GetEditTexture()); var gradientBuffer = new ComputeBuffer(GetEditTexture().width, Marshal.SizeOf(typeof(Vector4))); gradientBuffer.SetData(TextureCombinater.GetGradientBuffer(gradient,GetEditTexture().width)); compute.SetBuffer(kernel, "_Gradient", gradientBuffer); compute.SetBuffer(kernel, "_SeedPixels", seedPixels); compute.SetInt("_AreaExpansion", areaExpansion); compute.Dispatch(kernel, GetEditTexture().width, GetEditTexture().height, 1); seedPixels.Release(); gradientBuffer.Release(); if(maskAllLayers) RenderTexture.ReleaseTemporary(maskTexture); } } public void DrawStamp(Texture stamp, Vector2 uv, Vector2 scale, Color col, float rot = 0f) { if (0f < uv.x && uv.x < 1f && 0f < uv.y && uv.y < 1f) { float w = (float)stamp.width; int s = 1; while (w > (float) GetEditTexture().width * scale.x) { w *= 0.5f; s++; } s = Mathf.Clamp(s, 1, TextureCombinater.GetMipMapCount((Texture2D)stamp)); var compute = GetComputeShader(); int kernel = compute.FindKernel("DrawStamp"); compute.SetInt("_Width", GetEditTexture().width); compute.SetInt("_Height", GetEditTexture().height); compute.SetTexture(kernel, "_ResultTex", GetEditTexture()); compute.SetInt("_StampWidth", stamp.width); compute.SetInt("_StampHeight", stamp.height); compute.SetVector("_Color", col); compute.SetTexture(kernel, "_Stamp", stamp,s-1); compute.SetVector("_StampUV", uv); compute.SetVector("_StampScale", scale); compute.SetFloat("_StampRotation", rot); compute.Dispatch(kernel, GetEditTexture().width, GetEditTexture().height, 1); } } public Texture GetStamp(Vector2 from,Vector2 to,bool maskAllLayers = true) { RenderTexture maskTexture = maskAllLayers ? GetTemporaryTexture() : GetEditTexture(); var currentRT = RenderTexture.active; RenderTexture.active = maskTexture; from = new Vector2(Mathf.Clamp01(from.x),Mathf.Clamp01(from.y)); to = new Vector2(Mathf.Clamp01(to.x),Mathf.Clamp01(to.y)); var fromxy = new Vector2(from.x * maskTexture.width, (1.0f-from.y) * maskTexture.height); var toxy = new Vector2(to.x * maskTexture.width, (1.0f-to.y) * maskTexture.height); var min = new Vector2(Mathf.Min(fromxy.x,toxy.x),Mathf.Min(fromxy.y,toxy.y)); var max = new Vector2(Mathf.Max(fromxy.x,toxy.x),Mathf.Max(fromxy.y,toxy.y)); if ((int) min.x == (int) max.x) return null; if ((int)min.y == (int)max.y) return null; var texture = new Texture2D((int)max.x-(int)min.x,(int)max.y-(int)min.y,TextureFormat.RGBAFloat,false); texture.ReadPixels(new Rect(min.x, min.y, max.x, max.y), 0, 0); texture.Apply(); RenderTexture.active = currentRT; if(maskAllLayers) RenderTexture.ReleaseTemporary(maskTexture); return texture; } public Color SpuitColor(Vector2 uv,bool maskAllLayers = true) { RenderTexture maskTexture = maskAllLayers ? GetTemporaryTexture() : GetEditTexture(); Vector2Int pix = new Vector2Int( (int) (uv.x * (float) maskTexture.width), (int) (uv.y * (float) maskTexture.height)); var c = TextureCombinater.GetPixel(maskTexture, pix.x, pix.y); if(maskAllLayers) RenderTexture.ReleaseTemporary(maskTexture); return c; } public void Gaussian(Vector2 from,Vector2 to,float brushWidth,float brushStrength,float brushPower = 0f) { var compute = GetComputeShader(); int kernel = compute.FindKernel("Gaussian"); compute.SetFloat("_BrushWidth",brushWidth); compute.SetFloat("_BrushStrength",brushStrength); compute.SetFloat("_BrushPower",brushPower); compute.SetInt("_Width",GetEditTexture().width); compute.SetInt("_Height",GetEditTexture().height); compute.SetVector("_FromPoint",from); compute.SetVector("_ToPoint",to); compute.SetTexture(kernel,"_ResultTex",GetEditTexture()); compute.Dispatch(kernel, GetEditTexture().width,GetEditTexture().height,1); } public Texture SaveTexture(string path) { return TextureCombinater.ConvertToPngAndSave(path,(RenderTexture) GetTexture()); } public void Release() { targetTexture.Release(); foreach (var layer in layerDatas) { layer.Release(); } } } [System.SerializableAttribute] public class LayerData { public string name = ""; public RenderTexture texture; public byte[] origin; public Vector2 scale = new Vector2(1,1); public Vector2 offset = new Vector2(0,0); public bool active = true; public BlendMode layerMode = BlendMode.Normal; public Color color = Color.white; public Color comparison = Color.black; public Vector4 settings = Vector4.zero; public bool isMask = false; public LayerData(RenderTexture rt) { texture = rt; name = rt.name; } public LayerData(byte[] png) { origin = png; } public void Release() { if (texture) { texture.Release(); } } } public enum BlendMode { Disable, Normal, Additive, Multiply, Subtraction, Division, Bloom, HSV, Color, AlphaMask, Override, }; } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/DebugTools/TestWindow.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System; using System.Linq; using UnityEditor; using UnityEngine; using UnityEditor.Callbacks; #if VRC_SDK_VRCSDK3 using UnityEditor.Animations; using VRC.SDK3.Avatars.Components; using VRC.SDK3.Avatars.ScriptableObjects; #endif namespace HhotateA.AvatarModifyTools.Core { public class TestWindow : WindowBase { [OnOpenAssetAttribute] public static bool OpenAsset(int instanceID, int line) { if (EditorUtility.InstanceIDToObject(instanceID).GetType() == typeof(AvatarModifyData)) { ShowWindow(EditorUtility.InstanceIDToObject(instanceID) as AvatarModifyData); } return false; } public static void ShowWindow(AvatarModifyData data) { var wnd = GetWindow<TestWindow>(); wnd.titleContent = new GUIContent("AvatarModifyTool"); wnd.data = data; } [MenuItem("Window/HhotateA/DebugTools/AvatarModifyTool",false,1)] public static void ShowWindow() { var wnd = GetWindow<TestWindow>(); wnd.titleContent = new GUIContent("AvatarModifyTool"); wnd.data = CreateInstance<AvatarModifyData>(); } private AvatarModifyData data; private bool extendItems = true; private bool saveOrigin = true; private string prefix = ""; private void OnGUI() { TitleStyle("HhotateA.AvatarModifyTools.Core"); #if VRC_SDK_VRCSDK3 if(data==null) return; // EditorGUILayout.LabelField("DATA : " + data.saveName); data.saveName = EditorGUILayout.TextField("DATA : ",prefix); AvatartField("Avatar"); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { data.locomotion_controller = (AnimatorController) EditorGUILayout.ObjectField("locomotion : ", data.locomotion_controller, typeof(AnimatorController), true); data.idle_controller = (AnimatorController) EditorGUILayout.ObjectField("idle : ", data.idle_controller, typeof(AnimatorController), true); data.gesture_controller = (AnimatorController) EditorGUILayout.ObjectField("gesture : ", data.gesture_controller, typeof(AnimatorController), true); data.action_controller = (AnimatorController) EditorGUILayout.ObjectField("action : ", data.action_controller, typeof(AnimatorController), true); data.fx_controller = (AnimatorController) EditorGUILayout.ObjectField("fx : ", data.fx_controller, typeof(AnimatorController), true); data.parameter = (VRCExpressionParameters) EditorGUILayout.ObjectField("params : ", data.parameter, typeof(VRCExpressionParameters), true); data.menu = (VRCExpressionsMenu) EditorGUILayout.ObjectField("menu : ", data.menu, typeof(VRCExpressionsMenu), true); extendItems = EditorGUILayout.Foldout(extendItems, "Items"); if (extendItems) { var count = EditorGUILayout.IntField("ItemCount", data.items.Length); count = Mathf.Max(0, count); if (data.items.Length < count) { var itemList = data.items.ToList(); for (int i = data.items.Length; i < count; i++) { itemList.Add(new Item()); } data.items = itemList.ToArray(); } else if (data.items.Length > count) { var itemList = data.items.ToList(); itemList = itemList.GetRange(0, count); data.items = itemList.ToArray(); } foreach (var item in data.items) { using (new EditorGUILayout.HorizontalScope()) { item.prefab = (GameObject) EditorGUILayout.ObjectField(item.prefab, typeof(GameObject), true); item.target = (HumanBodyBones) EditorGUILayout.EnumPopup(item.target); } } } } if (ShowOptions()) { saveOrigin = EditorGUILayout.Toggle("Save Origin", saveOrigin); prefix = EditorGUILayout.TextField("Prefix : ",prefix); } using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Setup")) { try { var mod = new AvatarModifyTool(avatar); ApplySettings(mod).ModifyAvatar(data, ""); } catch (Exception e) { OnError(e); throw; } OnFinishSetup(); } if (GUILayout.Button("Revert")) { try { var mod = new AvatarModifyTool(avatar); mod.RevertByAssets(data); } catch (Exception e) { OnError(e); throw; } OnFinishRevert(); } } using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Save")) { var path = EditorUtility.SaveFilePanel("Save", data.GetAssetDir(), data.saveName, "asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } try { data = Instantiate(data); AssetDatabase.CreateAsset(data, FileUtil.GetProjectRelativePath(path)); } catch (Exception e) { OnError(e); throw; } OnSave(); } if (GUILayout.Button("Load")) { var path = EditorUtility.OpenFilePanel("Load", data.GetAssetDir(), "asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } try { var d = AssetDatabase.LoadAssetAtPath<AvatarModifyData>(FileUtil.GetProjectRelativePath(path)); if (d == null) { status.Warning("Load Failure"); return; } else { data = d; } } catch (Exception e) { OnError(e); throw; } OnLoad(); } } status.Display(); Signature(); #else EditorGUILayout.LabelField("Please Import VRCSDK"); #endif } } } <|start_filename|>Assets/HhotateA/MeshModifyTool/Editor/MeshModifyTool.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using HhotateA.AvatarModifyTools.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.Animations; namespace HhotateA.AvatarModifyTools.MeshModifyTool { public class MeshModifyTool : EditorWindow { [MenuItem("Window/HhotateA/にゃんにゃんメッシュエディター(MeshModifyTool)",false,201)] public static void ShowWindow() { var wnd = GetWindow<MeshModifyTool>(); wnd.titleContent = new GUIContent("にゃんにゃんメッシュエディター"); } // ボタン設定 private int drawButton = 0; private int rotateButton = 1; private int moveButton = 2; // ショートカット取得 private bool keyboardShortcut = false; private bool keyboardShift = false; private bool keyboardCtr = false; private bool keyboardAlt = false; private int shortcutToolBuffer = -1; // 改造するメッシュのルートオブジェクト private GameObject avatar; // avatar配下のMeshオブジェクト private Renderer[] rends; // rendsごとのMeshsCreater private MeshCreater[] meshsCreaters; // rendsにもともと入っていたメッシュの保存 private Mesh[] defaultMeshs; // 現在編集中のrendsのindex private int editIndex = -1; // 現在編集中のMeshsCreaterを取得する便利関数 MeshCreater editMeshCreater { get { if (meshsCreaters == null) { return null; } if (0 <= editIndex && editIndex < meshsCreaters.Length) { return meshsCreaters[editIndex]; } else { return null; } } } // Remesh機能用 private int triangleCount = 0; private SkinnedMeshRenderer weightOrigin; // カメラ表示用補助クラス AvatarMonitor avatarMonitor; private const int previewLayer = 2; private Vector2 rendsScroll = Vector2.zero; private bool viewOption = false; private Material wireFrameMaterial; Color wireFrameColor = Color.white; private Material[] defaultMaterials; private Material[] normalMaterials; private float normalAlpha = 0f; // スカルプトモード,ペン設定 private MeshPenTool.ExtraTool penMode = MeshPenTool.ExtraTool.Default; private float brushPower = 0.001f; private float brushWidth = 0.03f; private float brushStrength = 1f; private bool xMirror, yMirror, zMirror; bool selectMode => (penMode == MeshPenTool.ExtraTool.SelectLand || penMode == MeshPenTool.ExtraTool.UnSelectLand || penMode == MeshPenTool.ExtraTool.SelectVertex || penMode == MeshPenTool.ExtraTool.UnSelectVertex); // 頂点編集モード用,操作点 private GameObject controllPoint_from; private GameObject controllPoint_to; // ワイヤーフレーム表示用オブジェクト private GameObject controllMesh_edit; private MeshCollider controllMesh_editCollider; private MeshFilter controllMesh_editFilter; // メッシュ編集モード用,頂点リスト private List<int> controll_vertexes = new List<int>(); // メッシュ編集モード用オブジェクト private GameObject controllMesh_select; private MeshFilter controllMesh_selectFilter; // メッシュ編集モード用Transform private Vector3 transformPosition; private Vector3 transformRotation; private Vector3 transformScale; // UV変形用 private UVViewer uvViewer; private Vector4 uvTexelSize; private Material activeMaterial; // 保存するBlendShapeの名前 private string blendShapeName = "BlendShapeName"; // 各種設定項目 private bool isSelectVertex = true; private bool isRandomizeVertex = false; private bool isRealtimeTransform = true; private bool isSelectOverlappingVertexes = true; private bool isVertexRemove = false; private bool isSaveAll = false; private bool isGenerateNewMesh = false; private bool extendExperimental = false; private bool extendSaveOption = false; private bool extendRawdata = false; private bool isDecimateBone = false; private DecimateBoneMode decimateBoneMode; enum DecimateBoneMode { DeleateDisableBones, DeleateNonHumanoidBones, } // mesh simpler private float meshSimplerQuality = 0.5f; // MergeBone機能用 private bool isMergeBone = false; /*private Animator originHuman; private Animator targetHuman;*/ private GameObject targetHuman; private MergeBoneMode mergeBoneMode; enum MergeBoneMode { Merge, Constraint, } private bool isCombineMesh = false; private CombineMeshMode combineMeshMode; enum CombineMeshMode { CombineAllMesh, CombineActiveMesh, } private bool isCombineMaterial = false; private CombineMaterialMode combineMaterialMode; enum CombineMaterialMode { ByMaterial, ByShader, ForceCombine, } // 不安定項目を非有効化する設定 private bool disableNotRecommend = true; // 編集ツールプリセット private MeshPenTool[] _penTools; private MeshPenTool[] penTools { get { if (_penTools == null) { _penTools = new MeshPenTool[4] { new MeshPenTool(EnvironmentGUIDs.smoothTooIcon,"Smooth",MeshPenTool.ExtraTool.Default,2f,0.003f,0.03f), new MeshPenTool(EnvironmentGUIDs.linerToolIcon,"Liner",MeshPenTool.ExtraTool.Default,1f,-0.01f,0.03f), new MeshPenTool(EnvironmentGUIDs.constantToolIcon,"Constant",MeshPenTool.ExtraTool.Default,10f,null,0f), new MeshPenTool(EnvironmentGUIDs.detailToolIcon,"Detail",MeshPenTool.ExtraTool.DetailMode,null,null,0f), }; } return _penTools; } } // 拡張編集ツールプリセット private MeshPenTool[] _extraTools; MeshPenTool[] extraTools { get { if (_extraTools == null) { _extraTools = new MeshPenTool[4] { new MeshPenTool(EnvironmentGUIDs.selectLandToolIcon,"SelectLand",MeshPenTool.ExtraTool.SelectLand,null,null,0f), new MeshPenTool(EnvironmentGUIDs.unSelectLandToolIcon,"UnSelectLand",MeshPenTool.ExtraTool.UnSelectLand,null,null,0f), new MeshPenTool(EnvironmentGUIDs.selectVertexToolIcon,"SelectVertex",MeshPenTool.ExtraTool.SelectVertex,null,null,0f), new MeshPenTool(EnvironmentGUIDs.unSelectVertexToolIcon,"UnSelectVertex",MeshPenTool.ExtraTool.UnSelectVertex,null,null,0f), }; } return _extraTools; } } // 拡張編集ツールプリセット private MeshPenTool[] _betaTools; MeshPenTool[] betaTools { get { if (_betaTools == null) { _betaTools = new MeshPenTool[4] { new MeshPenTool("","WeightCopy",MeshPenTool.ExtraTool.WeightCopy,null,null,0f), new MeshPenTool("","Eraser",MeshPenTool.ExtraTool.TriangleEraser,null,null,0f), new MeshPenTool("","Decimate",MeshPenTool.ExtraTool.Decimate,null,null,0f), new MeshPenTool("","Subdivision",MeshPenTool.ExtraTool.Subdivision,null,null,0f), }; } return _betaTools; } } private int casheCount = -1; // 最終選択頂点のデータ Vector2 rowScroll = Vector2.zero; // private bool displayRawData => activeExperimentalBeta; Vector3 rawPosition = Vector3.zero; Vector3 rawNormal = Vector3.up; Vector3 rawTangent = Vector3.right; Color rawColor = Color.white; private Vector2[] rawUVs = Enumerable.Range(0, 8).Select(_ => Vector2.zero).ToArray(); KeyValuePair<int,float>[] rawWeights = new KeyValuePair<int,float>[4]; private int[] rawIDs = Enumerable.Range(0, 3).ToArray(); /// <summary> /// 表示部,実装は置かないこと /// </summary> private void OnGUI() { using (new EditorGUILayout.HorizontalScope()) { // ウィンドウ左側 using (new EditorGUILayout.VerticalScope()) { if (rends == null) { WindowBase.TitleStyle("にゃんにゃんメッシュエディター"); WindowBase.DetailStyle("Unityだけでアバターのメッシュ改変ができるツールです.",EnvironmentGUIDs.readme); avatar = EditorGUILayout.ObjectField("", avatar, typeof(GameObject), true) as GameObject; if (GUILayout.Button("Setup")) { Setup(avatar); } WindowBase.Signature(); return; } rendsScroll = EditorGUILayout.BeginScrollView(rendsScroll, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); using (new EditorGUILayout.VerticalScope( GUI.skin.box )) { for(int i=0;i<rends.Length;i++) { using (new EditorGUILayout.HorizontalScope()) { rends[i].gameObject.SetActive(EditorGUILayout.Toggle("", rends[i].gameObject.activeSelf,GUILayout.Width(20))); using (new EditorGUI.DisabledScope(editIndex == i)) { if (GUILayout.Button(rends[i].name, GUILayout.Width(250))) { rends[i].gameObject.SetActive(true); SelectMeshCreater(i); } } } } } EditorGUILayout.EndScrollView(); // 選択中オブジェクトが非アクティブになったら,選択解除 if (editIndex != -1) { if (!rends[editIndex].gameObject.activeSelf) { SelectMeshCreater(-1); } } using (new EditorGUILayout.VerticalScope(GUILayout.ExpandHeight(true))) { EditorGUILayout.LabelField(" "); } //activeExperimentalAlpha = EditorGUILayout.Toggle("ActiveExperimental", activeExperimentalAlpha); //if (activeExperimentalAlpha) { using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { isSelectVertex = EditorGUILayout.Toggle("SelectVertexMode", isSelectVertex); isRealtimeTransform = EditorGUILayout.Toggle("RealtimeTransform", isRealtimeTransform, GUILayout.Width(200)); // isRemoveAsBlendShape = EditorGUILayout.Toggle("DeleteAsBlendShape", isRemoveAsBlendShape, GUILayout.Width(155)); isSelectOverlappingVertexes = EditorGUILayout.Toggle("SelectOverlapping", isSelectOverlappingVertexes, GUILayout.Width(155)); keyboardShortcut = EditorGUILayout.Toggle( new GUIContent("Keyboard Shortcut", "Shortcuts : \n" + " Alt + Right Drag : Move \n" + " Alt + Left Drag : Rotate \n" + " Ctr + Z : Undo \n" + " Ctr + Y : Redo \n" + " Shift + Wheel : Power Change \n" + " Ctr Hold: Reverse Power \n" + " Alt + Wheel : Strength Change \n" + " SelectMode : \n" + " Shift Hold: SelectLand \n" + " Ctr Hold: UnSelect \n"), keyboardShortcut); using (new EditorGUILayout.HorizontalScope()) { // if (activeExperimentalAlpha) { foreach (var penTool in extraTools) { if (penTool.Button(ref penMode, ref brushPower, ref brushWidth, ref brushStrength)) { if (penMode != MeshPenTool.ExtraTool.DetailMode) DestroyControllPoint(); if (!selectMode) ReloadMesh(false); } } } } if (selectMode) { using (new EditorGUI.DisabledScope(editMeshCreater?.IsComputeLandVertexes() ?? false)) { using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("SelectAll")) { ResetSelect(); RevertSelect(editMeshCreater.VertexsCount() - 1); ResetSelectTransform(editMeshCreater); ReloadMesh(false, editMeshCreater, controll_vertexes); } if (GUILayout.Button("SelectNone")) { ResetSelect(); ResetSelectTransform(editMeshCreater); ReloadMesh(false, editMeshCreater, controll_vertexes); } if (GUILayout.Button("RevertSelect")) { RevertSelect(editMeshCreater.VertexsCount() - 1); ResetSelectTransform(editMeshCreater); ReloadMesh(false, editMeshCreater, controll_vertexes); } } } } extendExperimental = EditorGUILayout.Foldout(extendExperimental, "Experimentals"); if (extendExperimental) { using (var check = new EditorGUI.ChangeCheckScope()) { wireFrameColor = EditorGUILayout.ColorField("Wire Frame Color", wireFrameColor); normalAlpha = EditorGUILayout.Slider("Normal",normalAlpha,0f,1f); if (check.changed) { if (wireFrameMaterial != null) { wireFrameMaterial.SetColor("_Color",wireFrameColor); } if (normalAlpha > 0.1f) { CreateNormalMesh(); foreach (var normalMaterial in normalMaterials) { normalMaterial.SetFloat("_NormalAlpha",normalAlpha); } } else { rends[editIndex].sharedMaterials = defaultMaterials.ToArray(); } } } if (editMeshCreater != null) { using (var check = new EditorGUI.ChangeCheckScope()) { var isRecalculateNormals = EditorGUILayout.Toggle("Recalculate Normals", editMeshCreater.IsRecalculateNormals); if (check.changed) { foreach (var meshsCreater in meshsCreaters) { meshsCreater.IsRecalculateNormals = isRecalculateNormals; meshsCreater.IsRecalculateBlendShapeNormals = isRecalculateNormals; } } } } isVertexRemove = EditorGUILayout.Toggle("Delete Vertex", isVertexRemove); extendRawdata = EditorGUILayout.Toggle("View Raw Data", extendRawdata); // EditorGUILayout.LabelField("NotRecommended", GUILayout.Width(120)); using (new EditorGUILayout.HorizontalScope()) { foreach (var betaTool in betaTools) { if (betaTool.Button(ref penMode, ref brushPower, ref brushWidth, ref brushStrength)) { if (penMode != MeshPenTool.ExtraTool.DetailMode) DestroyControllPoint(); if (penMode == MeshPenTool.ExtraTool.Decimate) DecimateSelect(); if (penMode == MeshPenTool.ExtraTool.Subdivision) SubdivisionSelect(); } } } using (new EditorGUI.DisabledScope(disableNotRecommend)) { // あんまよくない isRandomizeVertex = EditorGUILayout.Toggle("RandomizeVertex", isRandomizeVertex); // 動かない(重すぎる) using (new EditorGUILayout.HorizontalScope()) { weightOrigin = EditorGUILayout.ObjectField("", weightOrigin, typeof(SkinnedMeshRenderer), true, GUILayout.Width(155)) as SkinnedMeshRenderer; if (GUILayout.Button("CopyBoneWeight", GUILayout.Width(125))) { if (weightOrigin) { editMeshCreater.CopyBoneWeight( new SkinnedMeshRenderer[1] {weightOrigin}); } } } // 精度悪い,重い using (new EditorGUILayout.HorizontalScope()) { triangleCount = EditorGUILayout.IntField("", triangleCount, GUILayout.Width(155)); if (GUILayout.Button("Decimate", GUILayout.Width(125))) { Decimate(); } } } using (new EditorGUILayout.HorizontalScope()) { meshSimplerQuality = EditorGUILayout.FloatField("", meshSimplerQuality, GUILayout.Width(155)); if (GUILayout.Button("MeshSimplifier", GUILayout.Width(125))) { var meshSimplifier = new ThirdParty.MeshSimplifier.MeshSimplifier(); meshSimplifier.Initialize(rends[editIndex].GetMesh()); meshSimplifier.SimplifyMesh(meshSimplerQuality); rends[editIndex].SetMesh(meshSimplifier.ToMesh()); meshsCreaters[editIndex] = new MeshCreater(rends[editIndex],avatar.transform); SelectMeshCreater(editIndex); } } } } } EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUI.DisabledScope(penMode == MeshPenTool.ExtraTool.TriangleEraser)) { using (new EditorGUI.DisabledScope(!editMeshCreater?.CanUndo() ?? false)) { if (GUILayout.Button("Undo")) { DestroyControllPoint(); editMeshCreater?.UndoCaches(); ReloadMesh(false,editMeshCreater,controll_vertexes); } } using (new EditorGUI.DisabledScope(!editMeshCreater?.CanRedo() ?? false)) { if (GUILayout.Button("Redo")) { DestroyControllPoint(); editMeshCreater?.RedoCaches(); ReloadMesh(false,editMeshCreater,controll_vertexes); } } } } EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { foreach (var penTool in penTools) { if (penTool.Button(ref penMode, ref brushPower, ref brushWidth, ref brushStrength)) { if (penMode != MeshPenTool.ExtraTool.DetailMode) DestroyControllPoint(); if (!selectMode) ReloadMesh(false); } } } if(penMode == MeshPenTool.ExtraTool.Default) { brushPower = EditorGUILayout.Slider("BrushPower",brushPower, -0.03f, 0.03f); brushWidth = EditorGUILayout.Slider("BrushWidth",brushWidth, 0f, 0.1f); brushStrength = EditorGUILayout.Slider("BrushStrength",brushStrength, 0, 10); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("Mirror(x,y,z)",GUILayout.Width(120)); xMirror = EditorGUILayout.Toggle("", xMirror,GUILayout.Width(50)); yMirror = EditorGUILayout.Toggle("", yMirror,GUILayout.Width(50)); zMirror = EditorGUILayout.Toggle("", zMirror,GUILayout.Width(50)); } } else if (penMode == MeshPenTool.ExtraTool.DetailMode || penMode == MeshPenTool.ExtraTool.Subdivision) { using (new EditorGUILayout.HorizontalScope()) { Vector3 p; if (controllPoint_to) { p = EditorGUILayout.Vector3Field("", controllPoint_to.transform.localPosition); if (p != controllPoint_to.transform.localPosition) { controllPoint_to.transform.localPosition = p; } } else { p = EditorGUILayout.Vector3Field("", Vector3.zero); } if (GUILayout.Button("Transform")) { if (controllPoint_from && controllPoint_to) { TransfromMeshMirror(editMeshCreater,controllPoint_from.transform.localPosition,controllPoint_to.transform.localPosition); GenerateControllPoint(editMeshCreater,controllPoint_to.transform.localPosition); } } if (isRealtimeTransform) { if (controllPoint_from && controllPoint_to) { if ( Vector3.Distance(controllPoint_from.transform.position, controllPoint_to.transform.position) > 0.001f) { TransfromMeshMirror(editMeshCreater,controllPoint_from.transform.localPosition,controllPoint_to.transform.localPosition,false); controllPoint_from.transform.localPosition = controllPoint_to.transform.localPosition; casheCount = 100; } else { casheCount--; } if (casheCount == 0) { TransfromMeshMirror(editMeshCreater,controllPoint_from.transform.localPosition,controllPoint_to.transform.localPosition,true); } } } } brushWidth = EditorGUILayout.Slider("BrushWidth",brushWidth, 0f, 0.1f); brushStrength = EditorGUILayout.Slider("BrushStrength",brushStrength, 0, 10); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("Mirror(x,y,z)",GUILayout.Width(120)); xMirror = EditorGUILayout.Toggle("", xMirror,GUILayout.Width(50)); yMirror = EditorGUILayout.Toggle("", yMirror,GUILayout.Width(50)); zMirror = EditorGUILayout.Toggle("", zMirror,GUILayout.Width(50)); } } else if (selectMode) { using (new EditorGUI.DisabledScope(editMeshCreater?.IsComputeLandVertexes() ?? false)) { if (isRealtimeTransform && controllMesh_select) { controllMesh_select.transform.localPosition = EditorGUILayout.Vector3Field("Position", controllMesh_select.transform.localPosition); controllMesh_select.transform.localRotation = Quaternion.Euler(EditorGUILayout.Vector3Field("Rotation", controllMesh_select.transform.localEulerAngles)); controllMesh_select.transform.localScale = EditorGUILayout.Vector3Field("Scale", controllMesh_select.transform.localScale); } else { transformPosition = EditorGUILayout.Vector3Field("Position", transformPosition); transformRotation = EditorGUILayout.Vector3Field("Rotation", transformRotation); transformScale = EditorGUILayout.Vector3Field("Scale", transformScale); } using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Transform")) { TransfomControllMesh(); } if (GUILayout.Button("Copy")) { CopyControllMesh(); } if (GUILayout.Button("Deleate")) { DeleateControllMesh(); } } } } EditorGUILayout.Space(); extendSaveOption = EditorGUILayout.Foldout(extendSaveOption, "Save Option"); if (extendSaveOption) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("",GUILayout.Width(5)); using (new EditorGUILayout.VerticalScope()) { if (isCombineMesh) { using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.Toggle("Save All", false); EditorGUILayout.Toggle("Generate New Mesh", true); } } else { isSaveAll = EditorGUILayout.Toggle("Save All", isSaveAll); if (isMergeBone) { using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.Toggle("Generate New Mesh", true); } } else { isGenerateNewMesh = EditorGUILayout.Toggle("Generate New Mesh", isGenerateNewMesh); } } using (new EditorGUILayout.HorizontalScope()) { isDecimateBone = EditorGUILayout.ToggleLeft("Decimate Bone", isDecimateBone, GUILayout.Width(130)); using (new EditorGUI.DisabledScope(!isDecimateBone)) { EditorGUILayout.LabelField(" ", GUILayout.Width(20)); decimateBoneMode = (DecimateBoneMode) EditorGUILayout.EnumPopup("", decimateBoneMode, GUILayout.Width(145)); } } using (new EditorGUILayout.HorizontalScope()) { isCombineMesh = EditorGUILayout.ToggleLeft("Combine Mesh", isCombineMesh, GUILayout.Width(130)); using (new EditorGUI.DisabledScope(!isCombineMesh)) { EditorGUILayout.LabelField(" ", GUILayout.Width(20)); combineMeshMode = (CombineMeshMode) EditorGUILayout.EnumPopup("", combineMeshMode, GUILayout.Width(145)); } } using (new EditorGUILayout.HorizontalScope()) { isCombineMaterial = EditorGUILayout.ToggleLeft("Combine Materials", isCombineMaterial, GUILayout.Width(130)); using (new EditorGUI.DisabledScope(!isCombineMaterial)) { EditorGUILayout.LabelField(" ", GUILayout.Width(20)); combineMaterialMode = (CombineMaterialMode) EditorGUILayout.EnumPopup("", combineMaterialMode, GUILayout.Width(145)); } } using (new EditorGUILayout.HorizontalScope()) { isMergeBone = EditorGUILayout.ToggleLeft("Change Bone", isMergeBone, GUILayout.Width(130)); using (new EditorGUI.DisabledScope(!isMergeBone)) { EditorGUILayout.LabelField(" ", GUILayout.Width(20)); targetHuman = (GameObject) EditorGUILayout.ObjectField("", targetHuman, typeof(GameObject), true, GUILayout.Width(95)); mergeBoneMode = (MergeBoneMode) EditorGUILayout.EnumPopup("", mergeBoneMode, GUILayout.Width(50)); } } } } using (new EditorGUILayout.HorizontalScope()) { blendShapeName = EditorGUILayout.TextField("", blendShapeName,GUILayout.Width(155)); using (new EditorGUI.DisabledScope(!editMeshCreater?.CanUndo() ?? true)) { if (GUILayout.Button("SaveAsBlendShape",GUILayout.Width(125))) { editMeshCreater.SaveAsBlendshape(blendShapeName); ReloadMesh(false); editMeshCreater.ResetCaches(); } } } } using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUI.DisabledScope(editMeshCreater == null && !isSaveAll && !isCombineMesh)) { if (GUILayout.Button("Export")) { SaveAll(()=>Save()); } } } EditorGUILayout.Space(); } using (new EditorGUILayout.VerticalScope()) { if (avatarMonitor != null) { var avatarMonitorWidth = extendRawdata ? 750 : 300; int positionDrag = keyboardShortcut && keyboardAlt ? drawButton : moveButton; bool canNotTouch = keyboardShortcut && (keyboardShift || keyboardCtr); bool canNotWheel = keyboardShortcut && (keyboardShift || keyboardAlt); if (keyboardShortcut && keyboardAlt) { avatarMonitor.SetSpeed(0.1f,0.5f,0.3f); } else { avatarMonitor.SetSpeed(); } avatarMonitor.Display( (int) position.width-avatarMonitorWidth, (int) position.height-10, rotateButton, positionDrag, !canNotTouch, !canNotWheel); if (editIndex != -1) { AvatarMonitorTouch(editMeshCreater); } } } if (extendRawdata) { using (new EditorGUILayout.VerticalScope()) { rowScroll = EditorGUILayout.BeginScrollView(rowScroll, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { rawPosition = EditorGUILayout.Vector3Field("Position", rawPosition); rawNormal = EditorGUILayout.Vector3Field("Normal", rawNormal); rawTangent = EditorGUILayout.Vector3Field("Tangent", rawTangent); rawColor = EditorGUILayout.ColorField("Color", rawColor); for (int i = 0; i < rawUVs.Length; i++) { rawUVs[i] = EditorGUILayout.Vector2Field("UV" + i, rawUVs[i]); } for (int i = 0; i < rawWeights.Length; i++) { using (new EditorGUILayout.HorizontalScope()) { rawWeights[i] = new KeyValuePair<int, float>( EditorGUILayout.IntField("BoneIndex" + i, rawWeights[i].Key), EditorGUILayout.FloatField("Weight", rawWeights[i].Value)); } } if (GUILayout.Button("UpdateData")) { SetRawData(); } } EditorGUILayout.Space(); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { using (new EditorGUILayout.HorizontalScope()) { for (int i = 0; i < rawIDs.Length; i++) { rawIDs[i] = EditorGUILayout.IntField("", rawIDs[i],GUILayout.Width(135)); } } if (GUILayout.Button("GenerateTriangle")) { GenerateTriangle(); } } EditorGUILayout.Space(); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("UV_ST"); uvTexelSize = EditorGUILayout.Vector4Field("", uvTexelSize); } using (new EditorGUI.DisabledScope(uvTexelSize.x==0f || uvTexelSize.y==0f)) { if (GUILayout.Button("TransformUV")) { editMeshCreater.TransformUV( new Vector2(1f/uvTexelSize.x,1f/uvTexelSize.y),new Vector2(-uvTexelSize.z,-uvTexelSize.w),controll_vertexes); ReloadMesh(false); uvTexelSize = new Vector4(1f,1f,0f,0f); uvViewer?.ReadUVMap(editMeshCreater.CreateEditMesh(controll_vertexes)); } } uvViewer?.UVTextureSize(new Vector2(uvTexelSize.x,uvTexelSize.y),new Vector2(uvTexelSize.z,uvTexelSize.w)); uvViewer?.Display(400,400); if (GUILayout.Button("Divided 4")) { editMeshCreater.TransformUV(new Vector2(0.5f,0.5f),new Vector2(0f,0f)); ReloadMesh(false); uvTexelSize = new Vector4(1f,1f,0f,0f); uvViewer?.BaseTextureSize(new Vector2(2f,2f),new Vector2(0f,0f)); uvViewer?.ReadUVMap(editMeshCreater.CreateEditMesh(controll_vertexes)); activeMaterial.SetTextureScale("_MainTex",new Vector2(2f,2f)); } } EditorGUILayout.EndScrollView(); } } } var ec = Event.current; // キー関係 if (keyboardShortcut) { Undo.ClearAll(); if (ec.type == EventType.KeyDown) { if (ec.keyCode == KeyCode.LeftShift || ec.keyCode == KeyCode.RightShift) { keyboardShift = true; if (penMode == MeshPenTool.ExtraTool.SelectVertex) { penMode = MeshPenTool.ExtraTool.SelectLand; } else if (penMode == MeshPenTool.ExtraTool.UnSelectVertex) { penMode = MeshPenTool.ExtraTool.UnSelectLand; } } if (ec.keyCode == KeyCode.LeftControl || ec.keyCode == KeyCode.RightControl) { keyboardCtr = true; if (penMode == MeshPenTool.ExtraTool.SelectVertex) { penMode = MeshPenTool.ExtraTool.UnSelectVertex; } else if (penMode == MeshPenTool.ExtraTool.SelectLand) { penMode = MeshPenTool.ExtraTool.UnSelectLand; } } if (ec.keyCode == KeyCode.LeftAlt || ec.keyCode == KeyCode.RightAlt) { keyboardAlt = true; } if (ec.keyCode == KeyCode.Z) { DestroyControllPoint(); editMeshCreater?.UndoCaches(); ReloadMesh(false,editMeshCreater,controll_vertexes); } if (ec.keyCode == KeyCode.Y) { DestroyControllPoint(); editMeshCreater?.RedoCaches(); ReloadMesh(false,editMeshCreater,controll_vertexes); } } if (ec.type == EventType.KeyUp) { if (ec.keyCode == KeyCode.LeftShift || ec.keyCode == KeyCode.RightShift) { keyboardShift = false; if (penMode == MeshPenTool.ExtraTool.SelectLand) { penMode = MeshPenTool.ExtraTool.SelectVertex; } else if (penMode == MeshPenTool.ExtraTool.UnSelectLand) { penMode = MeshPenTool.ExtraTool.UnSelectVertex; } } if (ec.keyCode == KeyCode.LeftControl || ec.keyCode == KeyCode.RightControl) { keyboardCtr = false; if (penMode == MeshPenTool.ExtraTool.UnSelectVertex) { penMode = MeshPenTool.ExtraTool.SelectVertex; } else if (penMode == MeshPenTool.ExtraTool.UnSelectLand) { penMode = MeshPenTool.ExtraTool.SelectLand; } } if (ec.keyCode == KeyCode.LeftAlt || ec.keyCode == KeyCode.RightAlt) { keyboardAlt = false; } } if (ec.type == EventType.ScrollWheel) { if (keyboardShift) { brushWidth = brushWidth + -ec.delta.y * 0.001f; } if (keyboardAlt) { brushStrength = brushStrength + -ec.delta.y * 0.05f; } } } } /// <summary> /// 毎フレーム更新する /// </summary> private void Update () { Repaint(); } /// <summary> /// Window閉じるとき処理,メッシュの後片付け /// </summary> private void OnDestroy() { DestroyControllMeshes(); for(int i=0;i<rends.Length;i++) { rends[i].SetMesh(defaultMeshs[i]); } avatarMonitor?.Release(); avatarMonitor = null; } void Setup(GameObject anim) { DestroyControllMeshes(); rends = anim.transform.GetComponentsInChildren<Renderer>().Where(r=>r.GetMesh()!=null).ToArray(); defaultMeshs = rends.Select(m => m.GetMesh()).ToArray(); meshsCreaters = rends.Select(m => new MeshCreater(m,avatar.transform)).ToArray(); if(avatarMonitor!=null) avatarMonitor.Release(); avatarMonitor = new AvatarMonitor(anim.transform); editIndex = -1; } void AddRend(Renderer rend) { if (rend == null) return; if (rend.GetMesh() == null) return; int i = rends.Length; rends = rends.Append(rend).ToArray(); defaultMeshs = defaultMeshs.Append(rend.GetMesh()).ToArray(); meshsCreaters = meshsCreaters.Append(new MeshCreater(rend,avatar.transform)).ToArray(); SelectMeshCreater(i); } void SelectMeshCreater(int i) { DestroyControllMeshes(); editIndex = i; if(editIndex!=-1) ReloadMesh(false,editMeshCreater,controll_vertexes); } void SaveAll(Action saveAction) { if (isSaveAll && !(isCombineMesh && combineMeshMode == CombineMeshMode.CombineAllMesh)) { int max = rends.Length; for (int i = 0; i < max; i++) { SelectMeshCreater(i); saveAction?.Invoke(); } } else { if (editIndex == -1) { SelectMeshCreater(0); } saveAction?.Invoke(); } } bool Save() { var path = EditorUtility.SaveFilePanel("Save", "Assets", rends[editIndex].name+"_Edit", "mesh"); if (string.IsNullOrWhiteSpace(path)) return false; path = FileUtil.GetProjectRelativePath(path); var dir = Path.GetDirectoryName(path); var file = Path.GetFileNameWithoutExtension(path); DestroyEditMesh(); DestroyControllPoint(); ReloadMesh(false); MeshCreater mc = new MeshCreater(editMeshCreater); if (isCombineMesh) { if (combineMeshMode == CombineMeshMode.CombineActiveMesh) { mc = new MeshCreater(avatar.transform,meshsCreaters.Where(m=>m.RendBone.gameObject.activeSelf).ToArray()); } else if(combineMeshMode == CombineMeshMode.CombineAllMesh) { mc = new MeshCreater(avatar.transform,meshsCreaters); } } if (isCombineMaterial) { if (combineMaterialMode == CombineMaterialMode.ByMaterial) { mc.CombineMesh(); } else if(combineMaterialMode == CombineMaterialMode.ByShader) { var mat = mc.MaterialAtlas(Path.Combine(dir, file)); rends[editIndex].sharedMaterials = mat.ToArray(); defaultMaterials = mat.ToArray(); } else if(combineMaterialMode == CombineMaterialMode.ForceCombine) { mc.ForceCombine(); } } if (isMergeBone && targetHuman != null) { if (mergeBoneMode == MergeBoneMode.Merge) { //var sm = SaveMeshCreater(meshsCreaters[editIndex],dir,file); mc = MergeBone( mc, dir, file); } else if(mergeBoneMode == MergeBoneMode.Constraint) { mc = CombineBone( mc, dir, file); } } if (isDecimateBone) { if (decimateBoneMode == DecimateBoneMode.DeleateNonHumanoidBones) { if (rends[editIndex] is SkinnedMeshRenderer) { DisableNonHumanBone(rends[editIndex] as SkinnedMeshRenderer); } mc = DeleateDisableBone(mc); } else if (decimateBoneMode == DecimateBoneMode.DeleateDisableBones) { mc = DeleateDisableBone(mc); } } if (isMergeBone && targetHuman != null) { var sm = SaveMeshCreater(mc,dir,file); sm.transform.SetParent(targetHuman.transform); AddRend(sm); } else if (isCombineMesh && combineMeshMode == CombineMeshMode.CombineAllMesh) { var sm = SaveMeshCreater(mc,dir,file); AddRend(sm); } else if (isGenerateNewMesh) { var sm = SaveMeshCreater(mc,dir,file); AddRend(sm); } else { defaultMeshs[editIndex] = SaveMeshCreater(mc,dir,file,rends[editIndex]); } return true; } /// <summary> /// MeshCreaterのメッシュをファイルに保存する /// </summary> /// <param name="mc"></param> /// <param name="dir"></param> /// <param name="file"></param> /// <param name="rend"></param> /// <returns></returns> Mesh SaveMeshCreater(MeshCreater mc,string dir,string file,Renderer rend) { if (isRandomizeVertex) { var mat = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentGUIDs.DecryptionShader)); var p = Path.GetDirectoryName(AssetDatabase.GetAssetPath(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentGUIDs.DecryptionShader))); File.WriteAllText(Path.Combine(p,"Keys.cginc"), mc.Encryption(mat)); mc.MaterialAtlas(Path.Combine(dir,file)); mc.CombineMesh(); } mc.Create(false); var m = mc.Save(Path.Combine(dir, file + ".mesh")); if (rend != null) { rend.SetMesh(m); rend.sharedMaterials = mc.GetMaterials(); } return m; } SkinnedMeshRenderer SaveMeshCreater(MeshCreater mc,string dir,string file) { if (isRandomizeVertex) { var mat = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentGUIDs.DecryptionShader)); var p = Path.GetDirectoryName(AssetDatabase.GetAssetPath(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentGUIDs.DecryptionShader))); File.WriteAllText(Path.Combine(p,"Keys.cginc"), mc.Encryption(mat)); mc.MaterialAtlas(Path.Combine(dir,file)); mc.CombineMesh(); } mc.Create(false); var m = mc.Save(Path.Combine(dir, file + ".mesh")); var sm = mc.ToSkinMesh(file,avatar.transform); sm.transform.localPosition = Vector3.zero; sm.transform.localRotation = Quaternion.identity; sm.transform.localScale = Vector3.one; var smsm = sm.GetComponent<SkinnedMeshRenderer>(); smsm.SetMesh(m); return smsm; } /// <summary> /// カメラ表示,インタラクト処理 /// </summary> /// <param name="mc"></param> void AvatarMonitorTouch(MeshCreater mc) { // ショートカット使用中は書かない if (keyboardShortcut && keyboardAlt) return; var ec = Event.current; if (penMode == MeshPenTool.ExtraTool.Default) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetControllPoint(GetEditMeshCollider(), isSelectVertex, h => { TransfromMeshMirror(mc, h); }); } } else if (penMode == MeshPenTool.ExtraTool.DetailMode) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetControllPoint(GetEditMeshCollider(), isSelectVertex, h => { GenerateControllPoint(mc, h); }); } } else if(penMode == MeshPenTool.ExtraTool.TriangleEraser) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), h => { mc.RemoveTriangle(h); ReloadMesh(true, mc); }); } } else if(penMode == MeshPenTool.ExtraTool.SelectLand) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), h => { mc.ComputeLandVertexes(mc.GetVertexIndex(h)[0], v => { if (!controll_vertexes.Contains(v)) controll_vertexes.Add(v); }, _ => { ResetSelectTransform(mc); ReloadMesh(false, mc, controll_vertexes); }, isSelectOverlappingVertexes); }); } } else if(penMode == MeshPenTool.ExtraTool.UnSelectLand) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), h => { mc.ComputeLandVertexes(mc.GetVertexIndex(h)[0], v => { if (controll_vertexes.Contains(v)) controll_vertexes.Remove(v); }, _ => { ResetSelectTransform(mc); ReloadMesh(false, mc, controll_vertexes); }, isSelectOverlappingVertexes); }); } } else if(penMode == MeshPenTool.ExtraTool.SelectVertex) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), h => { for (int i = 0; i < 3; i++) { var v = mc.GetVertexIndex(h)[i]; if (!controll_vertexes.Contains(v)) controll_vertexes.Add(v); } ResetSelectTransform(mc); ReloadMesh(false, mc, controll_vertexes); }); } } else if(penMode == MeshPenTool.ExtraTool.UnSelectVertex) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), h => { for (int i = 0; i < 3; i++) { var v = mc.GetVertexIndex(h)[i]; if (controll_vertexes.Contains(v)) controll_vertexes.Remove(v); } ResetSelectTransform(mc); ReloadMesh(false, mc, controll_vertexes); }); } } else if (penMode == MeshPenTool.ExtraTool.WeightCopy) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetVertex(GetEditMeshCollider(), (h, p) => { GenerateControllPoint(mc, p); mc.WeightCopy(controll_vertexes, h); //penMode = PenTool.ExtraTool.Default; ReloadMesh(false, mc, controll_vertexes); }); } } else if(penMode == MeshPenTool.ExtraTool.Decimate) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), h => { mc.Decimate(h); ReloadMesh(true, mc); }); } } else if(penMode == MeshPenTool.ExtraTool.Subdivision) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetTriangle(GetEditMeshCollider(), (h, p) => { GenerateControllPoint(mc, p); mc.Subdivision(h, p, isSelectVertex); ReloadMesh(true, mc); }); } } if (extendRawdata) { if (ec.type == EventType.MouseDown && ec.button == drawButton) { avatarMonitor.GetVertex(GetEditMeshCollider(), (h, p) => { GetRawData(h); InitializeUVViewer(h); }); } } } void InitializeUVViewer(int v) { editMeshCreater.GetTriangleList(new List<int>(v), (s, l) => { var m = editMeshCreater.GetMaterials()[s]; if (uvViewer == null) { uvViewer = new UVViewer(m); } else if (activeMaterial != m) { uvViewer.Release(); uvViewer = new UVViewer(m); } activeMaterial = m; uvViewer?.ReadUVMap(editMeshCreater.CreateEditMesh(controll_vertexes)); },3); } /// <summary> /// 頂点編集モード用コントロールポイントの作成 /// </summary> /// <param name="mc"></param> /// <param name="pos"></param> void GenerateControllPoint(MeshCreater mc,Vector3 pos,bool twoControll = true) { DestroyControllPoint(); controllPoint_from = GameObject.CreatePrimitive(PrimitiveType.Sphere); controllPoint_from.name = "EditVertex_From"; controllPoint_from.transform.localScale = new Vector3(0.009f,0.009f,0.009f) * avatarMonitor.GetBound; controllPoint_from.transform.SetParent(mc.RendBone); controllPoint_from.transform.localPosition = pos; controllPoint_from.hideFlags = HideFlags.HideAndDontSave; var mat_from = new Material(Shader.Find("Unlit/Color")); mat_from.color = Color.blue; controllPoint_from.GetComponent<Renderer>().sharedMaterial = mat_from; if (twoControll) { controllPoint_to = GameObject.CreatePrimitive(PrimitiveType.Sphere); controllPoint_to.name = "EditVertex_To"; controllPoint_to.transform.localScale = new Vector3(0.01f,0.01f,0.01f) * avatarMonitor.GetBound; controllPoint_to.transform.SetParent(mc.RendBone); controllPoint_to.transform.localPosition = pos; controllPoint_to.hideFlags = HideFlags.HideAndDontSave; var mat_to = new Material(Shader.Find("Unlit/Color")); mat_to.color = Color.red; controllPoint_to.GetComponent<Renderer>().sharedMaterial = mat_to; if (isRealtimeTransform) { controllPoint_to.hideFlags = HideFlags.DontSave; Selection.activeGameObject = controllPoint_to; } } } /// <summary> /// 頂点編集モード用コントロールポイントの削除 /// </summary> void DestroyControllPoint() { if(controllPoint_from) DestroyImmediate(controllPoint_from); if(controllPoint_to) DestroyImmediate(controllPoint_to); } /// <summary> /// Mirrorを適応した変形 /// </summary> /// <param name="mc"></param> /// <param name="from"></param> /// <param name="to_null">nullならカメラ方向に変形</param> /// <param name="cashes"></param> void TransfromMeshMirror(MeshCreater mc,Vector3 from, Vector3? to_null = null,bool cashes = true) { var to = to_null ?? mc.CalculateLocalVec(-avatarMonitor.WorldSpaceCameraVec()); bool isVec = to_null == null; TransformMesh(mc,from,to,isVec); if (xMirror) { var from_m = new Vector3(-from.x,from.y,from.z); var to_m = new Vector3(-to.x,to.y,to.z); TransformMesh(mc,from_m,to_m,isVec); } if (yMirror) { var from_m = new Vector3(from.x,-from.y,from.z); var to_m = new Vector3(to.x,-to.y,to.z); TransformMesh(mc,from_m,to_m,isVec); } if (zMirror) { var from_m = new Vector3(from.x,from.y,-from.z); var to_m = new Vector3(to.x,to.y,-to.z); TransformMesh(mc,from_m,to_m,isVec); } if (xMirror&&yMirror) { var from_m = new Vector3(-from.x,-from.y,from.z); var to_m = new Vector3(-to.x,-to.y,to.z); TransformMesh(mc,from_m,to_m,isVec); } if (yMirror&&zMirror) { var from_m = new Vector3(from.x,-from.y,-from.z); var to_m = new Vector3(to.x,-to.y,-to.z); TransformMesh(mc,from_m,to_m,isVec); } if (zMirror&&xMirror) { var from_m = new Vector3(-from.x,from.y,-from.z); var to_m = new Vector3(-to.x,to.y,-to.z); TransformMesh(mc,from_m,to_m,isVec); } if (xMirror&&yMirror&&zMirror) { var from_m = new Vector3(-from.x,-from.y,-from.z); var to_m = new Vector3(-to.x,-to.y,-to.z); TransformMesh(mc,from_m,to_m,isVec); } ReloadMesh(cashes,mc); } /// <summary> /// 頂点編集 /// </summary> /// <param name="mc"></param> /// <param name="from"></param> /// <param name="to">isVecならローカル方向</param> /// <param name="isVec"></param> void TransformMesh(MeshCreater mc,Vector3 from,Vector3 to,bool isVec) { if (isVec) { if (keyboardShortcut && keyboardCtr) { mc.TransformMesh(from, to, -brushPower*avatarMonitor.GetBound, brushWidth*avatarMonitor.GetBound, brushStrength); } else { mc.TransformMesh(from, to, brushPower*avatarMonitor.GetBound, brushWidth*avatarMonitor.GetBound, brushStrength); } } else { mc.TransformMesh(from, to, brushWidth*avatarMonitor.GetBound, brushStrength); } } /// <summary> /// メッシュ編集,選択解除 /// </summary> void ResetSelect() { controll_vertexes = new List<int>(); } /// <summary> /// メッシュ編集,選択反転 /// </summary> /// <param name="max"></param> void RevertSelect(int max) { controll_vertexes = Enumerable.Range(0, max).Where(n => !controll_vertexes.Contains(n)).ToList(); } /// <summary> /// UITransformリセット /// </summary> /// <param name="mc"></param> void ResetSelectTransform(MeshCreater mc) { transformPosition = mc.ComputeCenterPoint(controll_vertexes); transformRotation = Vector3.zero; transformScale = Vector3.one; uvTexelSize = new Vector4(1f,1f,0f,0f); } /// <summary> /// メッシュ編集,メッシュ移動 /// </summary> void TransfomControllMesh() { if (isRealtimeTransform) { editMeshCreater?.TransformVertexes( controll_vertexes, controllMesh_select.transform.localPosition, controllMesh_select.transform.localEulerAngles, controllMesh_select.transform.localScale); controllMesh_select.transform.localPosition = Vector3.zero; controllMesh_select.transform.localRotation = Quaternion.identity; controllMesh_select.transform.localScale = Vector3.one; } else { editMeshCreater?.TransformVertexes( controll_vertexes, transformPosition, transformRotation, transformScale); transformPosition = editMeshCreater.ComputeCenterPoint(controll_vertexes); transformRotation = Vector3.zero; transformScale = Vector3.one; } ReloadMesh(true,editMeshCreater,controll_vertexes); } /// <summary> /// メッシュ編集,メッシュコピーと移動 /// </summary> void CopyControllMesh() { var vertexBefor = editMeshCreater?.VertexsCount() ?? 0; editMeshCreater?.CopyVertexes(controll_vertexes, false); var vertexAfter = editMeshCreater?.VertexsCount() ?? 0; controll_vertexes = Enumerable.Range(vertexBefor, vertexAfter - vertexBefor).ToList(); TransfomControllMesh(); } /// <summary> /// メッシュ編集,メッシュ削除 /// </summary> void DeleateControllMesh() { editMeshCreater?.RemoveVertexesTriangles(controll_vertexes,false,isVertexRemove); ResetSelect(); ReloadMesh( isVertexRemove,editMeshCreater,controll_vertexes); } /// <summary> /// 編集用メッシュの一括削除 /// </summary> void DestroyControllMeshes() { DestroyNormalMesh(); DestroyEditMesh(); DestroySelectMesh(); DestroyControllPoint(); ResetSelect(); } /// <summary> /// メッシュの更新 /// </summary> /// <param name="cashes"></param> /// <param name="mc"></param> /// <param name="verts"></param> void ReloadMesh(bool cashes = true,MeshCreater mc = null,List<int> verts = null,Renderer rend = null) { if (mc == null) { mc = editMeshCreater; if (mc == null) return; } if (verts == null) { verts = controll_vertexes; } if (rend == null) { if (0 <= editIndex && editIndex < meshsCreaters.Length) { rend = rends?[editIndex]; } else { return; } } rend.SetMesh(mc.Create(false)); if (!selectMode && verts.Count != 0) { ResetSelect(); } SetEditMesh(mc,CreateEditMesh(mc, verts)); defaultMaterials = rend.sharedMaterials.ToArray(); normalMaterials = rends[editIndex].sharedMaterials.Select(mat => { var m = new Material(AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.NormalMaterial)); m.mainTexture = mat.mainTexture; return m; }).ToArray(); CreateNormalMesh(); if (cashes) { mc.AddCaches(); } if (isRealtimeTransform && verts.Count > 0 && selectMode) { var wp = mc.ComputeCenterPoint(verts); SetSelectMesh(mc,CreateSelectMesh(mc, verts,wp)); controllMesh_select.transform.localPosition = wp; } else { DestroySelectMesh(); } triangleCount = mc.TrianglesCount(); } /// <summary> /// ワイヤーフレームのメッシュコライダー取得 /// </summary> /// <returns></returns> MeshCollider GetEditMeshCollider() { return controllMesh_editCollider; } /// <summary> /// ワイヤーフレーム用メッシュの更新 /// </summary> GameObject SetEditMesh(MeshCreater mc,Mesh mesh) { if (controllMesh_edit == null) { controllMesh_edit = mc.ToMesh("EditMesh",true); controllMesh_edit.hideFlags = HideFlags.HideAndDontSave; controllMesh_edit.layer = previewLayer; controllMesh_editCollider = controllMesh_edit.GetComponent<MeshCollider>(); controllMesh_editFilter = controllMesh_edit.GetComponent<MeshFilter>(); var rend = controllMesh_edit.GetComponent<MeshRenderer>(); if (wireFrameMaterial == null) { wireFrameMaterial = new Material(AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.OverlayWireFrameMaterial)); wireFrameMaterial.SetFloat("_ZTest",4); wireFrameMaterial.SetColor("_Color",wireFrameColor); } rend.sharedMaterials = Enumerable.Range(0,rend.sharedMaterials.Length).Select(_=> wireFrameMaterial).ToArray(); } controllMesh_editFilter.sharedMesh = mesh; controllMesh_editCollider.sharedMesh = controllMesh_editFilter.sharedMesh; return controllMesh_edit; } /// <summary> /// ワイヤーフレーム用メッシュの作成 /// </summary> Mesh CreateEditMesh(MeshCreater mc,List<int> verts) { if (verts.Count == 0) { if (controllMesh_editFilter == null) { return mc.CreateEditMesh(null,null); } else { return mc.CreateEditMesh(null,null, controllMesh_editFilter.sharedMesh); } } else { if (controllMesh_editFilter == null) { return mc.CreateEditMesh(verts,null, null); } else { return mc.CreateEditMesh(verts,null, controllMesh_editFilter.sharedMesh); } } } /// <summary> /// ワイヤーフレーム用メッシュの削除 /// </summary> void DestroyEditMesh(MeshCreater mc = null) { if (controllMesh_edit) { DestroyImmediate(controllMesh_edit); } } void CreateNormalMesh() { if (editIndex < 0) return; if (normalAlpha > 0.1f) { rends[editIndex].sharedMaterials = normalMaterials; } else { rends[editIndex].sharedMaterials = defaultMaterials.ToArray(); } } void DestroyNormalMesh() { if (editIndex < 0) return; if (defaultMaterials != null) { rends[editIndex].sharedMaterials = defaultMaterials.ToArray(); } } /// <summary> /// メッシュ編集モード用メッシュの更新 /// </summary> GameObject SetSelectMesh(MeshCreater mc,Mesh mesh) { if (controllMesh_select == null) { controllMesh_select = mc.ToMesh("SelectMesh", false); controllMesh_select.hideFlags = HideFlags.DontSave; controllMesh_selectFilter = controllMesh_select.GetComponent<MeshFilter>(); var rend = controllMesh_select.GetComponent<MeshRenderer>(); var mat = new Material(AssetUtility.LoadAssetAtGuid<Material>(EnvironmentGUIDs.OverlayWireFrameMaterial)); mat.SetFloat("_ZTest",2); rend.sharedMaterials = Enumerable.Range(0,rend.sharedMaterials.Length). Select(_=> mat).ToArray(); } controllMesh_selectFilter.sharedMesh = mesh; if (isRealtimeTransform) { Selection.activeGameObject = controllMesh_select; } return controllMesh_select; } /// <summary> /// メッシュ編集モード用メッシュの作成 /// </summary> Mesh CreateSelectMesh(MeshCreater mc,List<int> verts,Vector3? wp) { if (controllMesh_select) { var mesh = mc.CreateEditMesh(null, verts, controllMesh_selectFilter.sharedMesh,-wp); return mesh; } else { var mesh = mc.CreateEditMesh(null, verts,null,-wp); return mesh; } } /// <summary> /// メッシュ編集モード用メッシュの削除 /// </summary> void DestroySelectMesh() { if (controllMesh_select) { DestroyImmediate(controllMesh_select); } } /// <summary> /// ポリゴン数削減 /// たぶん動かない /// </summary> void Decimate() { if (editMeshCreater.TrianglesCount() != triangleCount) { int decimate = editMeshCreater.TrianglesCount() / (editMeshCreater.TrianglesCount() - triangleCount); int decimateIndex = decimate; while (editMeshCreater.TrianglesCount() > triangleCount) { if (decimateIndex > editMeshCreater.TrianglesCount()) decimateIndex = decimate; editMeshCreater.Decimate(decimateIndex); decimateIndex += decimate; } ReloadMesh(false); } } void DecimateSelect() { var tris = editMeshCreater.GetTriangleList(controll_vertexes); for (int i = 0; i < tris.Count; i++) { int index = tris[i] - i * 4; if(index>0) editMeshCreater.Decimate(index); } ReloadMesh(false); } void SubdivisionSelect() { var tris = editMeshCreater.GetTriangleList(controll_vertexes); for (int i = 0; i < tris.Count; i++) { editMeshCreater.Subdivision(tris[i]-i); } ReloadMesh(false); } /// <summary> /// ボーンの参照先を変更する /// </summary> MeshCreater MergeBone(MeshCreater mc,string dir,string file) { // ここからボーンの参照 mc.ChangeBones(targetHuman,avatar,true); return mc; } /// <summary> /// ボーンの参照先を,コンストレイントボーンに変更する /// </summary> MeshCreater CombineBone(MeshCreater mc,string dir,string file) { // ここからボーンの参照 var t = targetHuman.GetBones(); var o = avatar.GetBones(); var p = targetHuman.transform.Find(avatar.name + "_bones") ?? new GameObject(avatar.name + "_bones").transform; p.SetParent(targetHuman.transform); p.localPosition = Vector3.zero; p.localRotation = Quaternion.identity; p.localScale = Vector3.one; mc.ChangeBones(targetHuman,avatar, true,b => { var bp = b.parent; if (t.Contains(bp)) { var bpobject = p.Find(bp.name); if (bpobject == null) { bpobject = new GameObject(bp.name).transform; bpobject.SetPositionAndRotation(bp.position,bp.rotation); bpobject.SetParent(p); var c = bpobject.gameObject.AddComponent<ParentConstraint>(); c.AddSource(new ConstraintSource() { sourceTransform = bp, weight = 1f }); c.constraintActive = true; } b.SetParent(bpobject,false); } }, rb => { editMeshCreater.RootBone = rb; }); return mc; } /// <summary> /// コンストレイントボーンを設定する /// </summary> void ConstraintBone() { var t = targetHuman.GetBones(); var o = avatar.GetBones(); for (int i = 0; i < t.Length; i++) { if (t[i] && o[i]) { var s = new ConstraintSource() { sourceTransform = t[i], weight = 1f }; var c = o[i].gameObject.AddComponent<ParentConstraint>(); c.AddSource(s); } } } void GetTableInChild(ref Dictionary<Transform,Transform> table,Transform bone,Transform target) { Debug.Log(bone.transform.childCount+"child"+bone.name); foreach (Transform cb in bone.transform) { var ct = target.Find(cb.name); if (ct != null) { table.Add(cb,ct); GetTableInChild(ref table, cb, ct); } } } /// <summary> /// HumanBone以外を参照から外す /// </summary> /// <param name="rend"></param> void DisableNonHumanBone(SkinnedMeshRenderer rend) { var humanBones = avatar.GetBones(); foreach (var bone in rend.bones) { if(!humanBones.Contains(bone)) bone.gameObject.SetActive(false); } ReloadMesh(false); } /// <summary> /// ヒエラルキー上で非アクティブなボーンを参照から外す /// </summary> /// <param name="rend"></param> MeshCreater DeleateDisableBone(MeshCreater mc) { mc.MergeDisableBones(); return mc; } void GetRawData(int vid) { if (editMeshCreater != null) { rawPosition = editMeshCreater.GetPosition(vid); rawNormal = editMeshCreater.GetNormal(vid); rawTangent = editMeshCreater.GetTangent(vid); rawColor = editMeshCreater.GetColor(vid); rawUVs = editMeshCreater.GetUVs(vid); rawWeights = editMeshCreater.GetWeightData(vid); rawIDs[0] = rawIDs[1]; rawIDs[1] = rawIDs[2]; rawIDs[2] = vid; } } void SetRawData() { if (editMeshCreater != null) { editMeshCreater.SetRawData(rawIDs[2],rawPosition,rawNormal,rawTangent,rawColor,rawUVs,rawWeights); ReloadMesh(false); } } void GenerateTriangle() { if (editMeshCreater != null) { editMeshCreater.AddTriangle(rawIDs[0],rawIDs[1],rawIDs[2]); ReloadMesh(false); } } /// <summary> /// 編集ツールの設定値保存用 /// </summary> class MeshPenTool { private Texture icon; private string name; private ExtraTool? extraTool; private float? brushPower; private float? brushWidth; private float? brushStrength; public MeshPenTool(string guid, string n, ExtraTool? e = null, float? s = null, float? p = null, float? w = null) { if (!string.IsNullOrWhiteSpace(guid)) { var i = AssetUtility.LoadAssetAtGuid<Texture>(guid); icon = i; } name = n; extraTool = e; brushPower = p; brushWidth = w; brushStrength = s; } public MeshPenTool(Texture i, string n, ExtraTool? e = null, float? s = null, float? p = null, float? w = null) { icon = i; name = n; extraTool = e; brushPower = p; brushWidth = w; brushStrength = s; } public MeshPenTool(Texture2D i, string n, ExtraTool? e = null, float? s = null, float? p = null, float? w = null) { icon = i; name = n; extraTool = e; brushPower = p; brushWidth = w; brushStrength = s; } public bool Button(ref ExtraTool e,ref float p,ref float w,ref float s) { using (new EditorGUI.DisabledScope( e == (extraTool ?? e) && p == (brushPower ?? p) && w == (brushWidth ?? w) && s == (brushStrength ?? s))) { if (icon) { if (GUILayout.Button(icon)) { e = extraTool ?? e; p = brushPower ?? p; w = brushWidth ?? w; s = brushStrength ?? s; return true; } } else { if (GUILayout.Button(name)) { e = extraTool ?? e; p = brushPower ?? p; w = brushWidth ?? w; s = brushStrength ?? s; return true; } } } return false; } public enum ExtraTool { Default, DetailMode, TriangleEraser, SelectLand, UnSelectLand, SelectVertex, UnSelectVertex, WeightCopy, Decimate, Subdivision } private bool FloatEqual(float a, float? b) { return Mathf.Abs(a - b ?? a) < 0.01f; } } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/DebugTools/SetupVRChatLayers.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using UnityEditor; namespace HhotateA.AvatarModifyTools.DebugTools { public class SetupVRChatLayers { [MenuItem("Window/HhotateA/DebugTools/SetupVRChatLayers",false,3)] static void SetupLayers() { SetupLayer(); SetupCollider(); } static void SetupLayer() { var path = "ProjectSettings/TagManager.asset"; var managers = AssetDatabase.LoadAllAssetsAtPath(path); foreach (var manager in managers) { var m = new SerializedObject(manager); var prop = m.FindProperty("layers"); for (int i = 0; i < prop.arraySize; i++) { var p = prop.GetArrayElementAtIndex(i); p.stringValue = layers[i]; } m.ApplyModifiedProperties(); } } private static string[] layers = new string[32] { "Default", "TransparentFX", "Ignore Raycast", "", "Water", "UI", "", "", "Interactive", "Player", "PlayerLocal", "Environment", "UiMenu", "Pickup", "PickupNoEnvironment", "StereoLeft", "StereoRight", "Walkthrough", "MirrorReflection", "reserved2", "reserved3", "reserved4", "", "", "", "", "", "", "", "", "", "" }; static void SetupCollider() { var path = "ProjectSettings/DynamicsManager.asset"; var managers = AssetDatabase.LoadAllAssetsAtPath(path); foreach (var manager in managers) { var m = new SerializedObject(manager); var prop = m.FindProperty("m_LayerCollisionMatrix"); for (int i = 0; i < prop.arraySize; i++) { prop.GetArrayElementAtIndex(i).longValue = collisionMatrix[i]; } m.ApplyModifiedProperties(); } } private static uint[] collisionMatrix = new uint[32] { 0b_1111111010111111011111, 0b_1111111010111111011111, 0b_1111111010111111011111, 0b_1111111111111111111111, 0b_1111111010111111011111, 0b_0000000000000011001000, 0b_1111111111111111111111, 0b_1111111111111111111111, 0b_1111111010111111011111, 0b_1111000000100111011111, 0b_1111000000100111011111, 0b_1111111010111111011111, 0b_0000000000000011001000, 0b_0000111110100111011111, 0b_0000000010000011001000, 0b_1111111010100111011111, 0b_1111111010100111011111, 0b_1111111010100111011111, 0b_1111111000111111011111, 0b_1111111000111111011111, 0b_1111111000111111011111, 0b_1111111000111111011111, 0b_0, 0b_0, 0b_0, 0b_0, 0b_0, 0b_0, 0b_0, 0b_0, 0b_0, 0b_0, }; } } <|start_filename|>Assets/HhotateA/MagicalDresserMakeupSystem/Editor/MagicalDresserMakeupSystem.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using HhotateA.AvatarModifyTools.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEngine; using UnityEditor; using UnityEditor.Animations; using Task = System.Threading.Tasks.Task; #if VRC_SDK_VRCSDK3 using VRC.SDK3.Avatars.Components; #endif namespace HhotateA.AvatarModifyTools.MagicalDresserMakeupSystem { public class MagicalDresserSetup : WindowBase { [MenuItem("Window/HhotateA/マジックドレッサーメイクアップ(MDMakeup)",false,107)] public static void ShowWindow() { var wnd = GetWindow<MagicalDresserSetup>(); wnd.titleContent = new GUIContent("マジックドレッサーメイクアップ(MDMakeupSystem)"); wnd.Show(); } private Renderer makeupRenderer; private ColorRotateMode matMode = ColorRotateMode.Texture; private ShapeRotateMode shapeMode = ShapeRotateMode.None; bool[] mats = new bool[0]; bool[] shapes = new bool[0]; Vector2 matScroll = Vector2.zero; Vector2 shapeScroll = Vector2.zero; int taskDone = 0; int taskTodo = 0; private string saveName = "MagicDresser"; enum ColorRotateMode { None, Texture, RGB, HSV, } enum ShapeRotateMode { None, Radial, Toggle, } private float threshold = 1f / 60f; private void OnGUI() { TitleStyle("マジックドレッサーメイクアップ(MDMakeupSystem)"); DetailStyle("VRChat上でのメニューからの色変えや,BlendShapeの切り替えを設定するツールです.",EnvironmentGUIDs.readme); #if VRC_SDK_VRCSDK3 EditorGUILayout.Space(); AvatartField(); EditorGUILayout.Space(); EditorGUILayout.Space(); var rend = EditorGUILayout.ObjectField("Renderer", makeupRenderer, typeof(Renderer), true) as Renderer; if (makeupRenderer != rend) { makeupRenderer = rend; if (makeupRenderer) { mats = Enumerable.Range(0, makeupRenderer.sharedMaterials.Length).Select(_ => true).ToArray(); shapes = Enumerable.Range(0, makeupRenderer.GetMesh().blendShapeCount).Select(_ => false).ToArray(); saveName = "MagicDresser_" + makeupRenderer.name; } } EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { matMode = (ColorRotateMode) EditorGUILayout.EnumPopup("Color Change", matMode); matScroll = EditorGUILayout.BeginScrollView(matScroll, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); using (new EditorGUI.DisabledScope(matMode == ColorRotateMode.None)) { for (int i = 0; i < mats.Length; i++) { mats[i] = EditorGUILayout.Toggle(makeupRenderer.sharedMaterials[i].name, mats[i]); } } EditorGUILayout.EndScrollView(); } using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { if (shapes.Length > 0) { shapeMode = (ShapeRotateMode) EditorGUILayout.EnumPopup("Shape Change", shapeMode); shapeScroll = EditorGUILayout.BeginScrollView(shapeScroll, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); using (new EditorGUI.DisabledScope(shapeMode == ShapeRotateMode.None)) { for (int i = 0; i < shapes.Length; i++) { shapes[i] = EditorGUILayout.Toggle(makeupRenderer.GetMesh().GetBlendShapeName(i), shapes[i]); } } EditorGUILayout.EndScrollView(); } } } EditorGUILayout.Space(); if (ShowOptions()) { if (GUILayout.Button("Force Revert")) { var mod = new AvatarModifyTool(avatar); mod.RevertByKeyword(EnvironmentGUIDs.prefix); OnFinishRevert(); } } EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Setup")) { var path = EditorUtility.SaveFilePanel("Save", "Assets", "MagicDresser_" + makeupRenderer.name,"controller"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } try { Setup(path); OnFinishSetup(); DetectAnimatorError(); } catch (Exception e) { OnError(e); throw; } } status.Display(); EditorGUILayout.LabelField("Task " + taskDone + " / " + taskTodo); EditorGUILayout.Space(); EditorGUILayout.Space(); #else VRCErrorLabel(); #endif Signature(); } void Setup(string path) { taskDone = 0; taskTodo = 1; #if VRC_SDK_VRCSDK3 string fileName = System.IO.Path.GetFileNameWithoutExtension(path); saveName = fileName; path = FileUtil.GetProjectRelativePath(path); string fileDir = System.IO.Path.GetDirectoryName (path); AnimatorControllerCreator animAsset = new AnimatorControllerCreator(fileName,false); animAsset.CreateAsset(path); MenuCreater menuAsset = new MenuCreater(fileName); ParametersCreater paramAsset = new ParametersCreater(fileName); if (matMode == ColorRotateMode.Texture) { SetupTexture(path, makeupRenderer,mats, ref animAsset, ref menuAsset, ref paramAsset); } else if(matMode == ColorRotateMode.HSV) { SetupHSV(path, makeupRenderer,mats, ref animAsset, ref menuAsset, ref paramAsset); } else if(matMode == ColorRotateMode.RGB) { SetupColor(path, makeupRenderer,mats, ref animAsset, ref menuAsset, ref paramAsset); } if (shapeMode == ShapeRotateMode.Radial) { SetupBlendShapeRadial(path, makeupRenderer,shapes, ref animAsset, ref menuAsset, ref paramAsset); } else if(shapeMode == ShapeRotateMode.Toggle) { SetupBlendShapeToggle(path, makeupRenderer,shapes, ref animAsset, ref menuAsset, ref paramAsset); } var mod = new AvatarModifyTool(avatar,fileDir); var assets = ScriptableObject.CreateInstance<AvatarModifyData>(); { assets.fx_controller = animAsset.Create(); assets.menu = menuAsset.CreateAsset(path, true); assets.parameter = paramAsset.CreateAsset(path, true); }; AssetDatabase.AddObjectToAsset(assets,path); ApplySettings(mod).ModifyAvatar(assets,EnvironmentGUIDs.prefix); taskDone += 1; #endif } #if VRC_SDK_VRCSDK3 void SetupHSV(string path,Renderer rend, bool[] mat, ref AnimatorControllerCreator animAsset, ref MenuCreater menuAsset, ref ParametersCreater paramAsset) { var paramH = saveName + "_H"; var paramS = saveName + "_S"; var paramV = saveName + "_V"; animAsset.AddParameter(paramH,0.5f); animAsset.AddParameter(paramS,0.5f); animAsset.AddParameter(paramV,0.5f); paramAsset.AddParam(paramH,0.5f,true); paramAsset.AddParam(paramS,0.5f,true); paramAsset.AddParam(paramV,0.5f,true); var idleAnim = new AnimationClipCreator(saveName+"_Idle",avatarAnim.gameObject).CreateAsset(path,true); var activateAnim = new AnimationClipCreator(saveName+"_ChangeMaterial",avatarAnim.gameObject); var inactivateAnim = new AnimationClipCreator(saveName+"_RevertMaterial",avatarAnim.gameObject); var rotateHAnim = new AnimationClipCreator(saveName+"_RotateH",avatarAnim.gameObject); var rotateSAnim = new AnimationClipCreator(saveName+"_RotateS",avatarAnim.gameObject); var rotateVAnim = new AnimationClipCreator(saveName+"_RotateV",avatarAnim.gameObject); var filterMat = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentGUIDs.filterShader)); var clippingMat = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentGUIDs.clippingShader)); filterMat.name = "Filter"; clippingMat.name = "Clipping"; AssetDatabase.AddObjectToAsset(filterMat,path); AssetDatabase.AddObjectToAsset(clippingMat,path); // フィルターオブジェクトの作成 var clone = rend.transform.FindInChildren(rend.name + "(clone)_" + saveName + "_Filter")?.gameObject; if (clone == null) { clone = Instantiate(rend.gameObject, rend.transform); clone.name = EnvironmentGUIDs.prefix + rend.name + "(clone)_" + saveName + "_Filter"; foreach (Transform child in clone.transform) { DestroyImmediate(child.gameObject); } var r = clone.GetComponent<Renderer>(); var rms = mats.Select(e=>e?filterMat:clippingMat).ToArray(); r.sharedMaterials = rms; } var cloneRend = clone.GetComponent<Renderer>(); activateAnim.AddKeyframe_Gameobject(clone.gameObject,0f,true); inactivateAnim.AddKeyframe_Gameobject(clone.gameObject,0f,false); activateAnim.AddKeyframe_Gameobject(clone.gameObject,1f/60f,true); inactivateAnim.AddKeyframe_Gameobject(clone.gameObject,1f/60f,false); rotateHAnim.AddKeyframe_MaterialParam(0f,cloneRend,"_H",0f); rotateHAnim.AddKeyframe_MaterialParam(256f/60f,cloneRend,"_H",1f); rotateSAnim.AddKeyframe_MaterialParam(0f,cloneRend,"_S",0f); rotateSAnim.AddKeyframe_MaterialParam(256f/60f,cloneRend,"_S",1f); rotateVAnim.AddKeyframe_MaterialParam(0f,cloneRend,"_V",0f); rotateVAnim.AddKeyframe_MaterialParam(256f/60f,cloneRend,"_V",1f); animAsset.CreateLayer(saveName); animAsset.AddDefaultState("Idle"); animAsset.AddState("Activate", activateAnim.CreateAsset(path,true)); animAsset.AddState("Inactive", inactivateAnim.CreateAsset(path,true)); animAsset.AddState("Controll"); animAsset.AddTransition("Idle", "Activate", paramH, 0.5f + threshold,true); animAsset.AddTransition("Idle", "Activate", paramH, 0.5f - threshold,false); animAsset.AddTransition("Idle", "Activate", paramS, 0.5f + threshold,true); animAsset.AddTransition("Idle", "Activate", paramS, 0.5f - threshold,false); animAsset.AddTransition("Idle", "Activate", paramV, 0.5f + threshold,true); animAsset.AddTransition("Idle", "Activate", paramV, 0.5f - threshold,false); animAsset.AddTransition("Activate","Controll"); animAsset.AddTransition("Controll","Inactive",new AnimatorCondition[6] { new AnimatorCondition() {mode = AnimatorConditionMode.Less,parameter = paramH,threshold = 0.5f+threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Greater,parameter = paramH,threshold = 0.5f-threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Less,parameter = paramS,threshold = 0.5f+threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Greater,parameter = paramS,threshold = 0.5f-threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Less,parameter = paramV,threshold = 0.5f+threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Greater,parameter = paramV,threshold = 0.5f-threshold}, }); animAsset.AddTransition("Inactive","Idle"); animAsset.CreateLayer(paramH); animAsset.AddState("Idle",idleAnim); animAsset.AddState("Controll", rotateHAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle", "Controll", paramH, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramH, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Idle", "Controll", paramS, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramS, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Idle", "Controll", paramV, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramV, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",paramH); animAsset.SetStateSpeed("Controll",threshold); animAsset.CreateLayer(paramS); animAsset.AddState("Idle",idleAnim); animAsset.AddState("Controll", rotateSAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle", "Controll", paramH, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramH, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Idle", "Controll", paramS, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramS, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Idle", "Controll", paramV, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramV, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",paramS); animAsset.SetStateSpeed("Controll",threshold); animAsset.CreateLayer(paramV); animAsset.AddState("Idle",idleAnim); animAsset.AddState("Controll", rotateVAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle", "Controll", paramH, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramH, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Idle", "Controll", paramS, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramS, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Idle", "Controll", paramV, 0.5f + threshold,true,true,1f); animAsset.AddTransition("Idle", "Controll", paramV, 0.5f - threshold,false,true,1f); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",paramV); animAsset.SetStateSpeed("Controll",threshold); var menu = new MenuCreater(saveName); menu.AddRadial("色相",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.rotateHIcon),paramH); menu.AddRadial("彩度",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.rotateSIcon),paramS); menu.AddRadial("明度",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.rotateVIcon),paramV); menuAsset.AddSubMenu(menu.CreateAsset(path, true),rend.name + "Color",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.dresserIcon)); } void SetupColor(string path,Renderer rend, bool[] mat, ref AnimatorControllerCreator animAsset, ref MenuCreater menuAsset, ref ParametersCreater paramAsset) { string fileName = System.IO.Path.GetFileNameWithoutExtension(path); string fileDir = System.IO.Path.GetDirectoryName (path); var paramR = fileName + "_R"; var paramG = fileName + "_G"; var paramB = fileName + "_B"; animAsset.AddParameter(paramR,0f); animAsset.AddParameter(paramG,0f); animAsset.AddParameter(paramB,0f); paramAsset.AddParam(paramR,0f,true); paramAsset.AddParam(paramG,0f,true); paramAsset.AddParam(paramB,0f,true); var idleAnim = new AnimationClipCreator(fileName+"_Idle",avatarAnim.gameObject).CreateAsset(path,true); var activateAnim = new AnimationClipCreator(fileName+"_ChangeMaterial",avatarAnim.gameObject); var inactivateAnim = new AnimationClipCreator(fileName+"_RevertMaterial",avatarAnim.gameObject); var rotateRAnim = new AnimationClipCreator(fileName+"_RotateR",avatarAnim.gameObject); var rotateGAnim = new AnimationClipCreator(fileName+"_RotateG",avatarAnim.gameObject); var rotateBAnim = new AnimationClipCreator(fileName+"_RotateB",avatarAnim.gameObject); for (int i = 0; i < rend.sharedMaterials.Length; i++) { if(mat[i] == false) continue; var colorChangeMaterial = rend.sharedMaterials[i]; if (colorChangeMaterial.mainTexture) { var grayMat = new Material(colorChangeMaterial); SyncGrayTexture(colorChangeMaterial.mainTexture, Path.Combine(fileDir, fileName + colorChangeMaterial.mainTexture.name + ".png"), t => grayMat.mainTexture = t); activateAnim.AddKeyframe_Material(rend, grayMat, 0f, i); inactivateAnim.AddKeyframe_Material(rend, colorChangeMaterial, 0f, i); activateAnim.AddKeyframe_Material(rend, grayMat, 1f / 60f, i); inactivateAnim.AddKeyframe_Material(rend, colorChangeMaterial, 1f / 60f, i); AssetDatabase.AddObjectToAsset(grayMat,path); } } foreach (var param in Enum.GetValues(typeof(ColorParamsEnum))) { if (!rend.sharedMaterial.HasProperty(param.ToString())) continue; var current = rend.sharedMaterial.GetColor(param.ToString()); rotateRAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".r", current.r); rotateRAnim.AddKeyframe_MaterialParam(1f/60f, rend, param.ToString()+".r", current.r*0.1f); rotateRAnim.AddKeyframe_MaterialParam(256f/60f, rend, param.ToString()+".r", current.r*1.1f); rotateGAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".g", current.g); rotateGAnim.AddKeyframe_MaterialParam(1f/60f, rend, param.ToString()+".g", current.g*0.1f); rotateGAnim.AddKeyframe_MaterialParam(256f/60f, rend, param.ToString()+".g", current.g*1.1f); rotateBAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".b", current.b); rotateBAnim.AddKeyframe_MaterialParam(1f/60f, rend, param.ToString()+".b", current.b*0.1f); rotateBAnim.AddKeyframe_MaterialParam(256f/60f, rend, param.ToString()+".b", current.b*1.1f); /*resetRAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".r", current.r); resetRAnim.AddKeyframe_MaterialParam(1f/60f, rend, param.ToString()+".r", current.r); resetGAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".g", current.g); resetGAnim.AddKeyframe_MaterialParam(1f/60f, rend, param.ToString()+".g", current.g); resetBAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".b", current.b); resetBAnim.AddKeyframe_MaterialParam(1f/60f, rend, param.ToString()+".b", current.b); inactivateAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".r", current.r); inactivateAnim.AddKeyframe_MaterialParam(1f, rend, param.ToString()+".r", current.r); inactivateAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".g", current.g); inactivateAnim.AddKeyframe_MaterialParam(1f, rend, param.ToString()+".g", current.g); inactivateAnim.AddKeyframe_MaterialParam(0f, rend, param.ToString()+".b", current.b); inactivateAnim.AddKeyframe_MaterialParam(1f, rend, param.ToString()+".b", current.b);*/ } animAsset.CreateLayer(fileName); animAsset.AddDefaultState("Idle"); animAsset.AddState("Activate", activateAnim.CreateAsset(path,true)); animAsset.AddState("Inactive", inactivateAnim.CreateAsset(path,true)); animAsset.AddState("Controll"); animAsset.AddTransition("Idle","Activate",paramR,threshold); animAsset.AddTransition("Idle","Activate",paramG,threshold); animAsset.AddTransition("Idle","Activate",paramB,threshold); animAsset.AddTransition("Activate","Controll"); animAsset.AddTransition("Controll","Inactive",new AnimatorCondition[3] { new AnimatorCondition() {mode = AnimatorConditionMode.Less,parameter = paramR,threshold = threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Less,parameter = paramG,threshold = threshold}, new AnimatorCondition() {mode = AnimatorConditionMode.Less,parameter = paramB,threshold = threshold} }); animAsset.AddTransition("Inactive","Idle"); animAsset.CreateLayer(paramR); animAsset.AddState("Idle",idleAnim); animAsset.AddState("Controll", rotateRAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle","Controll",paramR,threshold,true,true,1f); animAsset.AddTransition("Idle","Controll",paramG,threshold,true,true,1f); animAsset.AddTransition("Idle","Controll",paramB,threshold,true,true,1f); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",paramR); animAsset.SetStateSpeed("Controll",0f); animAsset.CreateLayer(paramG); animAsset.AddState("Idle",idleAnim); animAsset.AddState("Controll", rotateGAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle","Controll",paramR,threshold,true,true,1f); animAsset.AddTransition("Idle","Controll",paramG,threshold,true,true,1f); animAsset.AddTransition("Idle","Controll",paramB,threshold,true,true,1f); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",paramG); animAsset.SetStateSpeed("Controll",0f); animAsset.CreateLayer(paramB); animAsset.AddState("Idle",idleAnim); animAsset.AddState("Controll", rotateBAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle","Controll",paramR,threshold,true,true,1f); animAsset.AddTransition("Idle","Controll",paramG,threshold,true,true,1f); animAsset.AddTransition("Idle","Controll",paramB,threshold,true,true,1f); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",paramB); animAsset.SetStateSpeed("Controll",0f); var m = new MenuCreater("ColorMenu"); m.AddRadial("赤",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.rotateRIcon),paramR); m.AddRadial("緑",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.rotateGIcon),paramG); m.AddRadial("青",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.rotateBIcon),paramB); m.CreateAsset(path, true); menuAsset.AddSubMenu(m.Create(),rend.name + "Color",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.dresserIcon)); } public void SetupTexture(string path,Renderer rend, bool[] mat, ref AnimatorControllerCreator animAsset, ref MenuCreater menuAsset, ref ParametersCreater paramAsset) { string fileName = System.IO.Path.GetFileNameWithoutExtension(path); string fileDir = System.IO.Path.GetDirectoryName (path); var param = fileName + "_RotationColor"; var idleAnim = new AnimationClipCreator(fileName+"_Idle",avatarAnim.gameObject).CreateAsset(path,true); var controllAnim = new AnimationClipCreator(fileName+"_Controll",avatarAnim.gameObject); var matlist = new Dictionary<Material, Material[]>(); for (int i = 0; i < rend.sharedMaterials.Length; i++) { if(mat[i] == false) continue; controllAnim.AddKeyframe_Material(rend, rend.sharedMaterials[i], 0f, i); if (!matlist.ContainsKey(rend.sharedMaterials[i])) { taskTodo += EnvironmentGUIDs.rotateHSV.Length; matlist.Add( rend.sharedMaterials[i], Enumerable.Range(0,EnvironmentGUIDs.rotateHSV.Length).Select(j => { var rotateMat = new Material(rend.sharedMaterials[i]); SyncHSVTexture( rend.sharedMaterials[i].mainTexture, Path.Combine(fileDir, fileName + rend.sharedMaterials[i].mainTexture.name + "_" + i + "_" + j + ".png"), EnvironmentGUIDs.rotateHSV[j], t => { rotateMat.mainTexture = t; taskTodo += 1; Repaint(); }); AssetDatabase.AddObjectToAsset(rotateMat,path); return rotateMat; }).ToArray()); } for (int j = 0; j < EnvironmentGUIDs.rotateHSV.Length; j++) { controllAnim.AddKeyframe_Material(rend,matlist[rend.sharedMaterials[i]][j],(float)j+1f,i); } } animAsset.CreateLayer(fileName); animAsset.AddDefaultState("Idle",idleAnim); animAsset.AddState("Controll", controllAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle","Controll",param,threshold,true); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",param); animAsset.SetStateSpeed("Controll",0f); animAsset.Create(); paramAsset.AddParam(param,0f,true); menuAsset.AddRadial(rend.name + "Color",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.dresserIcon),param); } void SetupBlendShapeRadial(string path, Renderer rend, bool[] shape, ref AnimatorControllerCreator animAsset, ref MenuCreater menuAsset, ref ParametersCreater paramAsset) { if (!shape.Any(e=>e==true)) return; string fileName = System.IO.Path.GetFileNameWithoutExtension(path); string fileDir = System.IO.Path.GetDirectoryName (path); var param = fileName + "_BlendShape"; var idleAnim = new AnimationClipCreator(fileName+"_Idle",avatarAnim.gameObject).CreateAsset(path,true); var controllAnim = new AnimationClipCreator(fileName+"_Controll",avatarAnim.gameObject); for (int i = 0; i < shape.Length; i++) { if(shape[i] == false) continue; controllAnim.AddKeyframe(0f,rend, "blendShape."+rend.GetMesh().GetBlendShapeName(i) , 0f); controllAnim.AddKeyframe(256f/60f,rend, "blendShape."+rend.GetMesh().GetBlendShapeName(i) , 100f); } animAsset.CreateLayer(fileName); animAsset.AddDefaultState("Idle",idleAnim); animAsset.AddState("Controll", controllAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle","Controll",param,threshold,true); animAsset.AddTransition("Controll","Idle",false); animAsset.SetStateTime("Controll",param); animAsset.SetStateSpeed("Controll",0f); animAsset.Create(); paramAsset.AddParam(param,0f,true); menuAsset.AddRadial(rend.name + "_Shape",AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.blendShapeIcon),param); } void SetupBlendShapeToggle(string path, Renderer rend, bool[] shape, ref AnimatorControllerCreator animAsset, ref MenuCreater menuAsset, ref ParametersCreater paramAsset) { if (!shape.Any(e=>e==true)) return; string fileName = System.IO.Path.GetFileNameWithoutExtension(path); string fileDir = System.IO.Path.GetDirectoryName (path); for (int i = 0; i < shape.Length; i++) { if(shape[i] == false) continue; var param = fileName + "_BlendShapeToggle_" + rend.GetMesh().GetBlendShapeName(i); var idleAnim = new AnimationClipCreator(fileName+"_Idle",avatarAnim.gameObject).CreateAsset(path,true); var activateAnim = new AnimationClipCreator(fileName+"_Activate_"+rend.GetMesh().GetBlendShapeName(i),avatarAnim.gameObject); var inactivateAnim = new AnimationClipCreator(fileName+"_Inactivate_"+rend.GetMesh().GetBlendShapeName(i),avatarAnim.gameObject); activateAnim.AddKeyframe(0f,rend, "blendShape."+rend.GetMesh().GetBlendShapeName(i) , 100f); activateAnim.AddKeyframe(1f/60f,rend, "blendShape."+rend.GetMesh().GetBlendShapeName(i) , 100f); inactivateAnim.AddKeyframe(0f,rend, "blendShape."+rend.GetMesh().GetBlendShapeName(i) , 0f); inactivateAnim.AddKeyframe(1f/60f,rend, "blendShape."+rend.GetMesh().GetBlendShapeName(i) , 0f); animAsset.CreateLayer( fileName + "_" + i.ToString() + rend.GetMesh().GetBlendShapeName(i)); animAsset.AddDefaultState("Idle",idleAnim); animAsset.AddState("Active",idleAnim); animAsset.AddState("Inactive",idleAnim); animAsset.AddState("Activate", activateAnim.CreateAsset(path, true)); animAsset.AddState("Inactivate", inactivateAnim.CreateAsset(path, true)); animAsset.AddTransition("Idle","Activate",param,true); animAsset.AddTransition("Idle","Inactivate",param,false); animAsset.AddTransition("Activate","Active"); animAsset.AddTransition("Inactivate","Inactive"); animAsset.AddTransition("Inactive","Activate",param,true); animAsset.AddTransition("Active","Inactivate",param,false); animAsset.Create(); paramAsset.AddParam(param,false,true); menuAsset.AddToggle(rend.GetMesh().GetBlendShapeName(i),AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.blendShapeIcon),param); } } #endif async void SyncHSVTexture(Texture tex,string path,Vector3 hsv,Action<Texture> onSave) { var texcreater = new TextureCreator(tex); await Task.Delay(100); texcreater.AddLayer(Color.white); { var layer = texcreater.GetLayerData(0); layer.layerMode = BlendMode.HSV; layer.settings = new Vector4(hsv.x,hsv.y,hsv.z,0f); texcreater.LayersUpdate(); } await Task.Delay(100); var t = texcreater.SaveTexture(path); onSave?.Invoke(t); } async void SyncGrayTexture(Texture tex,string path,Action<Texture> onSave) { var texcreater = new TextureCreator(tex); await Task.Delay(100); texcreater.AddLayer(Color.white); var layer = texcreater.GetLayerData(0); layer.layerMode = BlendMode.HSV; layer.settings = new Vector4(0f,-1f,0f,0f); texcreater.LayersUpdate(); await Task.Delay(100); var t = texcreater.SaveTexture(path); onSave?.Invoke(t); } enum ColorParamsEnum { _Color, //UTS _BaseColor, _1st_ShadeColor, _2nd_ShadeColor, } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/EnvironmentVariable.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ namespace HhotateA.AvatarModifyTools.Core { /// <summary> /// 環境変数用staticクラス /// </summary> public static class EnvironmentVariable { public static string version = "1.30.18"; public static string githubLink = "https://github.com/HhotateA/AvatarModifyTools"; public static string icon = "1549a00a4e9d1734ca9f8862981c623f"; public static string iconMat = "d8f2ec63ea255c24f8fe567fac92c852"; public static string computeShader = "8e33ed767aaabf04eae3c3866bece392"; public static int maxCaches = 16; public static string idleAnimation = "b0f4aa27579b9c442a87f46f90d20192"; public static string baseAnimator = "4e4e1a372a526074884b7311d6fc686b"; public static string idleAnimator = "573a1373059632b4d820876efe2d277f"; public static string gestureAnimator = "404d228aeae421f4590305bc4cdaba16"; public static string actionAnimator = "3e479eeb9db24704a828bffb15406520"; public static string fxAnimator = "d40be620cf6c698439a2f0a5144919fe"; public static string arrowIcon = "ab0f6a0e53ae8fd4aab1efed5effa7eb"; public static string linkIcon = "20b4b9db03a839148b2a2166e53c9123"; public static string nottingAvatarMask = "fb3cb20bd9fa4fa47ba68b49d8db8a43"; public static string nottingAnim = "1927de9efc6d12140be0499624f05160"; public static string texturePreviewShader = "e422dd8b39cd79343b42ffba228bb53b"; public static string texturePainterShader = "3cfd9a4da725f0c41b16979b05bd5a53"; public static string[] vrchatParams = new string[] { "IsLocal", "Viseme", "GestureLeft", "GestureRight", "GestureLeftWeight", "GestureRightWeight", "AngularY", "VelocityX", "VelocityY", "VelocityZ", "Upright", "Grounded", "Seated", "AFK", "TrackingType", "VRMode", "MuteSelf", "InStation", "Expression1", "Expression2", "Expression3", "Expression4", "Expression5", "Expression6", "Expression7", "Expression8", "Expression9", "Expression10", "Expression11", "Expression12", "Expression13", "Expression14", "Expression15", "Expression16", }; public static string[][] boneNamePatterns = new string[][] { new string[] { "Hips","Hip"}, new string[] { "LeftUpperLeg","UpperLeg_Left","UpperLeg_L","Leg_Left","Leg_L"}, new string[] { "RightUpperLeg","UpperLeg_Right","UpperLeg_R","Leg_Right","Leg_R"}, new string[] { "LeftLowerLeg","LowerLeg_Left","LowerLeg_L","Knee_Left","Knee_L"}, new string[] { "RightLowerLeg","LowerLeg_Right","LowerLeg_R","Knee_Right","Knee_R"}, new string[] { "LeftFoot","Foot_Left","Foot_L"}, new string[] { "RightFoot","Foot_Right","Foot_R"}, new string[] { "Spine"}, new string[] { "Chest"}, new string[] { "Neck"}, new string[] { "Head"}, new string[] { "LeftShoulder","Shoulder_Left","Shoulder_L"}, new string[] { "RightShoulder","Shoulder_Right","Shoulder_R"}, new string[] { "LeftUpperArm","UpperArm_Left","UpperArm_L","Arm_Left","Arm_L"}, new string[] { "RightUpperArm","UpperArm_Right","UpperArm_R","Arm_Right","Arm_R"}, new string[] { "LeftLowerArm","LowerArm_Left","LowerArm_L"}, new string[] { "RightLowerArm","LowerArm_Right","LowerArm_R"}, new string[] { "LeftHand","Hand_Left","Hand_L"}, new string[] { "RightHand","Hand_Right","Hand_R"}, new string[] { "LeftToes","Toes_Left","Toe_Left","ToeIK_L","Toes_L","Toe_L"}, new string[] { "RightToes","Toes_Right","Toe_Right","ToeIK_R","Toes_R","Toe_R"}, new string[] { "LeftEye","Eye_Left","Eye_L"}, new string[] { "RightEye","Eye_Right","Eye_R"}, new string[] { "Jaw"}, new string[] { "LeftThumbProximal","ProximalThumb_Left","ProximalThumb_L"}, new string[] { "LeftThumbIntermediate","IntermediateThumb_Left","IntermediateThumb_L"}, new string[] { "LeftThumbDistal","DistalThumb_Left","DistalThumb_L"}, new string[] { "LeftIndexProximal","ProximalIndex_Left","ProximalIndex_L"}, new string[] { "LeftIndexIntermediate","IntermediateIndex_Left","IntermediateIndex_L"}, new string[] { "LeftIndexDistal","DistalIndex_Left","DistalIndex_L"}, new string[] { "LeftMiddleProximal","ProximalMiddle_Left","ProximalMiddle_L"}, new string[] { "LeftMiddleIntermediate","IntermediateMiddle_Left","IntermediateMiddle_L"}, new string[] { "LeftMiddleDistal","DistalMiddle_Left","DistalMiddle_L"}, new string[] { "LeftRingProximal","ProximalRing_Left","ProximalRing_L"}, new string[] { "LeftRingIntermediate","IntermediateRing_Left","IntermediateRing_L"}, new string[] { "LeftRingDistal","DistalRing_Left","DistalRing_L"}, new string[] { "LeftLittleProximal","ProximalLittle_Left","ProximalLittle_L"}, new string[] { "LeftLittleIntermediate","IntermediateLittle_Left","IntermediateLittle_L"}, new string[] { "LeftLittleDistal","DistalLittle_Left","DistalLittle_L"}, new string[] { "RightThumbProximal","ProximalThumb_Right","ProximalThumb_R"}, new string[] { "RightThumbIntermediate","IntermediateThumb_Right","IntermediateThumb_R"}, new string[] { "RightThumbDistal","DistalThumb_Right","DistalThumb_R"}, new string[] { "RightIndexProximal","ProximalIndex_Right","ProximalIndex_R"}, new string[] { "RightIndexIntermediate","IntermediateIndex_Right","IntermediateIndex_R"}, new string[] { "RightIndexDistal","DistalIndex_Right","DistalIndex_R"}, new string[] { "RightMiddleProximal","ProximalMiddle_Right","ProximalMiddle_R"}, new string[] { "RightMiddleIntermediate","IntermediateMiddle_Right","IntermediateMiddle_R"}, new string[] { "RightMiddleDistal","DistalMiddle_Right","DistalMiddle_R"}, new string[] { "RightRingProximal","ProximalRing_Right","ProximalRing_R"}, new string[] { "RightRingIntermediate","IntermediateRing_Right","IntermediateRing_R"}, new string[] { "RightRingDistal","DistalRing_Right","DistalRing_R"}, new string[] { "RightLittleProximal","ProximalLittle_Right","ProximalLittle_R"}, new string[] { "RightLittleIntermediate","IntermediateLittle_Right","IntermediateLittle_R"}, new string[] { "RightLittleDistal","DistalLittle_Right","DistalLittle_R"}, new string[] { "UpperChest"}, new string[] { "LastBone","Armature"}, // 本来的ではないけど,Rootもhitさせたい }; } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/AssetUtility.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; using System.Text; using System.Reflection; namespace HhotateA.AvatarModifyTools.Core { /// <summary> /// 便利関数用staticクラス /// </summary> public static class AssetUtility { public static T LoadAssetAtGuid<T>(string guid) where T : Object { var path = AssetDatabase.GUIDToAssetPath(guid); var asset = AssetDatabase.LoadAssetAtPath<T>(path); return asset; } public static string GetAssetGuid(Object obj) { var path = AssetDatabase.GetAssetPath(obj); if (!String.IsNullOrWhiteSpace(path)) { return AssetDatabase.AssetPathToGUID(path); } return ""; } public static string GetRelativePath(Transform root, Transform o) { if (o.gameObject == root.gameObject) { return ""; } string path = o.gameObject.name; Transform parent = o.transform.parent; while (parent != null) { if (parent.gameObject == root.gameObject) break; path = parent.name + "/" + path; parent = parent.parent; } return path; } public static string GetProjectRelativePath(string path) { path = path.Replace('\\', '/'); if (!path.StartsWith("Assets/")) { path = FileUtil.GetProjectRelativePath(path); } return path; } public static Transform FindInChildren(this Transform parent, string childName) { foreach (Transform child in parent) { if (child.name == childName) { return child; } else { Transform found = FindInChildren(child, childName); if (found != null) { return found; } } } return null; } public static void RecursionInChildren(this Transform parent, Action<Transform> onFind) { onFind?.Invoke(parent); foreach (Transform child in parent) { child.RecursionInChildren(onFind); } } public static string GetAssetDir(this ScriptableObject asset) { var path = AssetDatabase.GetAssetPath(asset); if (String.IsNullOrWhiteSpace(path)) { return "Assets"; } return Path.GetDirectoryName(path); } public static string GetAssetName(this ScriptableObject asset) { var path = AssetDatabase.GetAssetPath(asset); if (String.IsNullOrWhiteSpace(path)) { return asset.name; } return Path.GetFileName(path).Split('.')[0]; return Path.GetFileNameWithoutExtension(path); } public static Transform[] GetBones(this GameObject root) { Transform[] bones = new Transform[Enum.GetValues(typeof(HumanBodyBones)).Length]; var anim = root.GetComponent<Animator>(); foreach (HumanBodyBones humanBone in Enum.GetValues(typeof(HumanBodyBones))) { Transform bone = null; if (humanBone != HumanBodyBones.LastBone) { if (anim != null) { if (anim.isHuman) { bone = anim.GetBoneTransform(humanBone); } } } if (bone == null) { var boneNames = EnvironmentVariable.boneNamePatterns.FirstOrDefault(b => b[0] == humanBone.ToString()); if(boneNames == null) continue; foreach (var boneName in boneNames) { root.transform.RecursionInChildren(t => { if (bone == null) { string s = boneName.Replace(".", "").Replace("_", "").Replace(" ", "").ToUpper(); string d = t.gameObject.name.Replace(".", "").Replace("_", "").Replace(" ", "").ToUpper(); if (d.Contains(s)) { bone = t; } } }); if (bone != null) break; } } bones[(int) humanBone] = bone; } return bones; } // パラメータ文字列から2バイト文字の除去を行う public static string GetSafeParam(this string param,string prefix = "",bool hash = true) { if (String.IsNullOrWhiteSpace(param)) return ""; if (EnvironmentVariable.vrchatParams.Contains(param)) return param; if (hash) { param = GetNihongoHash(param); } if (!param.StartsWith(prefix)) { param = prefix + param; } return param; } public static string GetNihongoHash(string origin) { StringBuilder builder = new StringBuilder(); foreach (char ch in origin ) { if ( "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHJIJKLMNOPQRSTUVWXYZ!\"#$%&'()=-~^|\\`@{[}]*:+;_?/>.<,".IndexOf(ch) >= 0 ) { builder.Append(ch); } else { int hash = ch.GetHashCode(); int code = hash % 26; code += (int)'A'; code = Mathf.Clamp(code, (int) 'A', (int) 'Z'); builder.Append((char)code); } } return builder.ToString(); } public static List<string> GetMembers(Type type) { MemberInfo[] members = type.GetMembers(BindingFlags.Public); List<string> l = new List<string>(); foreach (MemberInfo m in members) { l.Add(m.Name); } return l; } } } <|start_filename|>Assets/HhotateA/EmojiParticle/Editor/EnvironmentGUIDs.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ namespace HhotateA.AvatarModifyTools.EmojiParticle { public static class EnvironmentGUIDs { public static string prefix = "HhotateA_EP_"; public static string readme = "a0b40f9092ea1bd419ae89844c1699ed"; public static string emojiModifyData = "7a095102f4fbaf64db6c9ed439a3e4df"; public static string particlePrefab = "1ed7af9f3244e954d83c99e2ec259025"; public static string particleAudio = "0baab8dcbb7593a45aece66a544782fc"; } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/TexturePreviewer.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using UnityEngine; using UnityEditor; using System; namespace HhotateA.AvatarModifyTools.Core { public class TexturePreviewer { private TextureCreator textureCreater; private CustomRenderTexture targetTexture; private Material targetMaterial; private CustomRenderTexture previewTexture; private Material previewMaterial; private float previewScale = 1f; Vector2 previewPosition = new Vector2(0.5f,0.5f); private Rect rect; public float dragSpeedRate { get; set; } = 1f; public float scrollSpeedRate { get; set; } = 1f; private float dragSpeedBase = 0.0015f; private float scrollSpeedBase = 0.01f; private float dragSpeed => dragSpeedBase * dragSpeedRate; private float scrollSpeed => scrollSpeedBase * scrollSpeedRate; private RenderTexture overlayTexture; public TexturePreviewer(TextureCreator tc) { if (tc == null) { throw new NullReferenceException("Missing Texture Creater"); } textureCreater = tc; previewTexture = new CustomRenderTexture(textureCreater.GetTexture().width,textureCreater.GetTexture().height); previewMaterial = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentVariable.texturePreviewShader)); previewMaterial.SetTexture("_MainTex",textureCreater.GetTexture()); previewTexture.initializationSource = CustomRenderTextureInitializationSource.Material; previewTexture.initializationMode = CustomRenderTextureUpdateMode.OnDemand; previewTexture.updateMode = CustomRenderTextureUpdateMode.OnDemand; previewTexture.initializationMaterial = previewMaterial; previewTexture.material = previewMaterial; previewTexture.Create(); targetTexture = new CustomRenderTexture(textureCreater.GetTexture().width,textureCreater.GetTexture().height); targetMaterial = new Material(AssetUtility.LoadAssetAtGuid<Shader>(EnvironmentVariable.texturePreviewShader)); targetMaterial.SetTexture("_MainTex",textureCreater.GetTexture()); targetTexture.initializationSource = CustomRenderTextureInitializationSource.Material; targetTexture.initializationMode = CustomRenderTextureUpdateMode.OnDemand; targetTexture.updateMode = CustomRenderTextureUpdateMode.OnDemand; targetTexture.initializationMaterial = targetMaterial; targetTexture.material = targetMaterial; targetTexture.Create(); rect = new Rect(); } ComputeShader GetComputeShader() { return AssetUtility.LoadAssetAtGuid<ComputeShader>(EnvironmentVariable.computeShader); } public Texture GetTexture() { Vector4 scale = new Vector4(0f ,0f ,1f ,1f ); targetMaterial.SetVector("_Scale",scale); targetMaterial.SetTexture("_Overlay",overlayTexture); targetTexture.Initialize(); return targetTexture; } public void SetSpeed(float move = 1f, float wheel = 1f) { dragSpeedRate = move; scrollSpeedRate = wheel; } public void Display(int width, int height, bool moveLimit = true, int rotationDrag = 2, int positionDrag = 1,bool canTouch = true,bool canWheel = true) { textureCreater.LayersUpdate(); rect = GUILayoutUtility.GetRect(width, height, GUI.skin.box); EditorGUI.DrawPreviewTexture(rect, ScalePreview(width,height,moveLimit)); var e = Event.current; if (rect.Contains(e.mousePosition)) { if (canTouch) { if (e.type == EventType.MouseDrag && e.button == rotationDrag) { } if (e.type == EventType.MouseDrag && e.button == positionDrag) { previewPosition += new Vector2(-e.delta.x, e.delta.y) * previewScale * dragSpeed; } } if(canWheel) { if (e.type == EventType.ScrollWheel) { var p = new Vector3(e.mousePosition.x - rect.x, rect.height - e.mousePosition.y + rect.y,1f); var uv = new Vector2(p.x/rect.width,p.y/rect.height); Vector2 previewUV = (uv - new Vector2(0.5f, 0.5f)) * previewScale + previewPosition; if (moveLimit) { previewScale = Mathf.Clamp(previewScale + e.delta.y * scrollSpeed,0.05f,1f); } else { previewScale = Mathf.Clamp(previewScale + e.delta.y * scrollSpeed,0.05f,2.5f); } previewPosition = previewUV - (uv - new Vector2(0.5f, 0.5f))*previewScale; } } } } public bool IsInDisplay(Vector2 pos) { return rect.Contains(pos); } public void MouseOverlay(Texture tex,float scale = 1f,float rotate = 0f) { var e = Event.current; } public Vector2 Touch(Action<Vector2,Vector2> onDrag = null) { var e = Event.current; if (rect.Contains(e.mousePosition)) { var p = new Vector3(e.mousePosition.x - rect.x, rect.height - e.mousePosition.y + rect.y,1f); var uv = new Vector2(p.x/rect.width,p.y/rect.height); Vector2 previewUV = (uv - new Vector2(0.5f, 0.5f)) * previewScale + previewPosition; if (e.type == EventType.MouseDrag) { // drag前 var pd = new Vector3(e.mousePosition.x - rect.x - e.delta.x, rect.height - e.mousePosition.y + rect.y + e.delta.y,1f); var uvd = new Vector2(pd.x/rect.width,pd.y/rect.height); Vector2 previewUVd = (uvd - new Vector2(0.5f, 0.5f)) * previewScale + previewPosition; onDrag?.Invoke(previewUVd,previewUV); } return previewUV; } return new Vector2(-1f,-1f); } CustomRenderTexture ScalePreview(int width,int height,bool moveLimit = true) { var x = 1f; var y = 1f; if (width < height) { x = (float) width / (float) height; } if (height < width) { y = (float) height / (float) width; } Vector4 scale = new Vector4( previewPosition.x - previewScale * 0.5f * x, previewPosition.y - previewScale * 0.5f * y, previewPosition.x + previewScale * 0.5f * x, previewPosition.y + previewScale * 0.5f * y); if (moveLimit) { if (scale.x < 0f) previewPosition.x -= scale.x; if (scale.z > 1f) previewPosition.x -= scale.z-1f; if (scale.y < 0f) previewPosition.y -= scale.y; if (scale.w > 1f) previewPosition.y -= scale.w-1f; } previewMaterial.SetVector("_Scale",scale); previewMaterial.SetTexture("_Overlay",overlayTexture); previewTexture.Initialize(); return previewTexture; } public void Release() { previewTexture.Release(); } public void PreviewPoint(Vector2 uv, Color brushColor, float brushWidth, float brushStrength) { PreviewClear(); if (0f < uv.x && uv.x < 1f && 0f < uv.y && uv.y < 1f) { var compute = GetComputeShader(); int kernel = compute.FindKernel("ClearColor"); compute.SetVector("_Color",Vector4.zero); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.Dispatch(kernel, overlayTexture.width,overlayTexture.height,1); kernel = compute.FindKernel("DrawPoint"); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.SetVector("_Color", brushColor); compute.SetInt("_Width",overlayTexture.width); compute.SetInt("_Height",overlayTexture.height); compute.SetVector("_Point",uv); compute.SetFloat("_BrushWidth",brushWidth); compute.SetFloat("_BrushStrength",brushStrength); compute.SetFloat("_BrushPower",1f); compute.Dispatch(kernel, overlayTexture.width,overlayTexture.height,1); } } public void PreviewStamp(Texture stamp, Vector2 uv, Vector2 scale, Color col, float rot = 0f) { PreviewClear(); if (0f < uv.x && uv.x < 1f && 0f < uv.y && uv.y < 1f) { var compute = GetComputeShader(); int kernel = compute.FindKernel("ClearColor"); compute.SetVector("_Color",Vector4.zero); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.Dispatch(kernel, overlayTexture.width,overlayTexture.height,1); kernel = compute.FindKernel("DrawStamp"); compute.SetInt("_Width",overlayTexture.width); compute.SetInt("_Height",overlayTexture.height); compute.SetTexture(kernel, "_ResultTex", overlayTexture); compute.SetInt("_StampWidth", stamp.width); compute.SetInt("_StampHeight", stamp.height); compute.SetVector("_Color", col); compute.SetTexture(kernel, "_Stamp", stamp); compute.SetVector("_StampUV", uv); compute.SetVector("_StampScale", scale); compute.SetFloat("_StampRotation", rot); compute.Dispatch(kernel, overlayTexture.width, overlayTexture.height, 1); } } public void PreviewLine(Vector2 from,Vector2 to,Color brushColor,float brushWidth,float brushStrength) { PreviewClear(); if (0f < from.x && from.x < 1f && 0f < from.y && from.y < 1f && 0f < to.x && to.x < 1f && 0f < to.y && to.y < 1f) { var compute = GetComputeShader(); int kernel = compute.FindKernel("ClearColor"); compute.SetVector("_Color",Vector4.zero); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.Dispatch(kernel, overlayTexture.width,overlayTexture.height,1); kernel = compute.FindKernel("DrawLine"); compute.SetInt("_Width",overlayTexture.width); compute.SetInt("_Height",overlayTexture.height); compute.SetVector("_Color",brushColor); compute.SetVector("_FromPoint",from); compute.SetVector("_ToPoint",to); compute.SetFloat("_BrushWidth",brushWidth); compute.SetFloat("_BrushStrength",brushStrength); compute.SetFloat("_BrushPower",1f); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.Dispatch(kernel, overlayTexture.width, overlayTexture.height, 1); } } public void PreviewBox(Vector2 from,Vector2 to,Color brushColor,float brushWidth,float brushStrength) { PreviewClear(); if (0f < from.x && from.x < 1f && 0f < from.y && from.y < 1f && 0f < to.x && to.x < 1f && 0f < to.y && to.y < 1f) { var compute = GetComputeShader(); int kernel = compute.FindKernel("ClearColor"); compute.SetVector("_Color",Vector4.zero); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.Dispatch(kernel, overlayTexture.width,overlayTexture.height,1); kernel = compute.FindKernel("DrawBox"); compute.SetInt("_Width",overlayTexture.width); compute.SetInt("_Height",overlayTexture.height); compute.SetVector("_Color",brushColor); compute.SetVector("_FromPoint",from); compute.SetVector("_ToPoint",to); compute.SetFloat("_BrushWidth",brushWidth); compute.SetFloat("_BrushStrength",brushStrength); compute.SetFloat("_BrushPower",1f); compute.SetTexture(kernel,"_ResultTex",overlayTexture); compute.Dispatch(kernel, overlayTexture.width, overlayTexture.height, 1); } } public void PreviewClear() { if (overlayTexture == null) { overlayTexture = new RenderTexture( previewTexture.width, previewTexture.height,0,RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default); overlayTexture.enableRandomWrite = true; overlayTexture.Create(); } } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/AvatarModifyTool.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using System.IO; using UnityEditor.Animations; using UnityEngine.Animations; using Object = UnityEngine.Object; using AnimatorLayerType = HhotateA.AvatarModifyTools.Core.AnimatorUtility.AnimatorLayerType; #if VRC_SDK_VRCSDK3 using VRC.SDK3.Avatars.ScriptableObjects; using VRC.SDK3.Avatars.Components; #endif namespace HhotateA.AvatarModifyTools.Core { /// <summary> /// VRCAvatarDescriptorへのアセット適応を一括して行うクラス /// </summary> public class AvatarModifyTool { #if VRC_SDK_VRCSDK3 private VRCAvatarDescriptor avatar; #else private Animator avatar; #endif private AnimatorModifier animMod; public bool DuplicateAssets {private get; set; } = true; public bool OverrideSettings {private get; set; } = true; public bool RenameParameters {private get; set; } = false; public bool ModifyOriginalAsset {private get; set; } = false; public bool AutoAddNextPage {private get; set; } = false; public bool OverrideNullAnimation {private get; set; } = true; private string exportDir = "Assets/"; string prefix = ""; public bool? WriteDefaultOverride { set { animMod.writeDefaultOverride = value; } } // コンストラクタ,VRCSDKない環境でもうまく動くよう引数を調節 #if VRC_SDK_VRCSDK3 public AvatarModifyTool(VRCAvatarDescriptor a, string dir = "Assets/Export") { avatar = a; Init(dir); } #else public AvatarModifyTool(Animator a, string dir = "Assets/Export") { avatar = a; Init(dir); } #endif public AvatarModifyTool(MonoBehaviour a, string dir = "Assets/Export") { #if VRC_SDK_VRCSDK3 avatar = a.GetComponent<VRCAvatarDescriptor>(); #else avatar = a.GetComponent<Animator>(); #endif Init(dir); } void Init(string dir = "Assets/Export") { if (avatar == null) { throw new NullReferenceException("Avatar reference missing"); } if (dir == "Assets/Export") { if (!AssetDatabase.IsValidFolder(dir)) { AssetDatabase.CreateFolder("Assets", "Export"); } } exportDir = File.GetAttributes(dir) .HasFlag(FileAttributes.Directory) ? dir : Path.GetDirectoryName(dir); animMod = new AnimatorModifier(); animMod.onFindParam += GetSafeParam; animMod.onFindAnimationClip += clip => MakeCopy<AnimationClip>(clip); animMod.onFindAvatarMask += CloneAvatarMask; } /// <summary> /// アバターにmodを適応する /// </summary> /// <param name="assets"></param> /// <param name="keyword"></param> /// <exception cref="NullReferenceException"></exception> public void ModifyAvatar(AvatarModifyData assets, string keyword = "") { prefix = keyword; if (ModifyOriginalAsset) assets = RenameAssetsParameters(assets); if (OverrideSettings) RevertByAssets(assets); animMod.animRepathList = new Dictionary<string, string>(); if (assets.items != null) { foreach (var item in assets.items) { ModifyGameObject(item.prefab, out var from, out var to, item.target); animMod.animRepathList.Add(from, to); } } #if VRC_SDK_VRCSDK3 // オフセットの記録 animMod.layerOffset = ComputeLayersOffset(assets); #endif // Animatorの改変 ModifyAvatarAnimatorController(AnimatorLayerType.Locomotion,assets.locomotion_controller); ModifyAvatarAnimatorController(AnimatorLayerType.Idle,assets.idle_controller); ModifyAvatarAnimatorController(AnimatorLayerType.Gesture,assets.gesture_controller); ModifyAvatarAnimatorController(AnimatorLayerType.Action,assets.action_controller); ModifyAvatarAnimatorController(AnimatorLayerType.Fx,assets.fx_controller); #if VRC_SDK_VRCSDK3 // Avatar項目の改変 ModifyExpressionParameter(assets.parameter); ModifyExpressionMenu(assets.menu); #endif AssetDatabase.SaveAssets(); EditorUtility.SetDirty(avatar); } /// <summary> /// アバターのmodを取り除く /// </summary> /// <param name="assets"></param> /// <param name="keyword"></param> /// <exception cref="NullReferenceException"></exception> public void RevertByAssets(AvatarModifyData assets, string keyword = "") { prefix = keyword; if (ModifyOriginalAsset) assets = RenameAssetsParameters(assets); if (avatar != null) { animMod.animRepathList = new Dictionary<string, string>(); if (assets.items != null) { foreach (var item in assets.items) { RevertGameObject(item.prefab, item.target); } } RevertAnimator(AnimatorLayerType.Locomotion,assets.locomotion_controller); RevertAnimator(AnimatorLayerType.Idle,assets.idle_controller); RevertAnimator(AnimatorLayerType.Gesture,assets.gesture_controller); RevertAnimator(AnimatorLayerType.Action,assets.action_controller); RevertAnimator(AnimatorLayerType.Fx,assets.fx_controller); #if VRC_SDK_VRCSDK3 RevertExpressionParameter(assets.parameter); RevertExpressionMenu(assets.menu); #endif AssetDatabase.SaveAssets(); } else { throw new NullReferenceException("VRCAvatarDescriptor : avatar not found"); } EditorUtility.SetDirty(avatar); } /// <summary> /// keywordを元に,アバターの改変を取り除く /// </summary> /// <param name="keyword"></param> /// <exception cref="NullReferenceException"></exception> public void RevertByKeyword(string keyword) { if (avatar != null) { DeleateInChild(avatar.transform, keyword); RevertAnimator(AnimatorLayerType.Locomotion, keyword); RevertAnimator(AnimatorLayerType.Idle, keyword); RevertAnimator(AnimatorLayerType.Gesture, keyword); RevertAnimator(AnimatorLayerType.Action, keyword); RevertAnimator(AnimatorLayerType.Fx, keyword); #if VRC_SDK_VRCSDK3 RevertExpressionParameter(keyword); RevertExpressionMenu(keyword); #endif AssetDatabase.SaveAssets(); } else { throw new NullReferenceException("VRCAvatarDescriptor : avatar not found"); } EditorUtility.SetDirty(avatar); } public void RepathAnimators(GameObject from, GameObject to) { var fromPath = GetRelativePath(from.transform); var toPath = GetRelativePath(to.transform); RepathAnimators(fromPath, toPath); } public void RepathAnimators(string from, string to) { #if VRC_SDK_VRCSDK3 foreach (var playableLayer in avatar.baseAnimationLayers) { if (playableLayer.animatorController == null) continue; animMod.SetOrigin((AnimatorController) playableLayer.animatorController).RepathAnims(from,to); } #else animMod.SetOrigin((AnimatorController) avatar.runtimeAnimatorController).RepathAnims(from,to); #endif } public List<string> HasWriteDefaultLayers() { var layers = new List<string>(); #if VRC_SDK_VRCSDK3 foreach (var playableLayer in avatar.baseAnimationLayers) { if (playableLayer.animatorController == null) continue; layers.AddRange(animMod.SetOrigin((AnimatorController) playableLayer.animatorController).WriteDefaultLayers()); } #else layers.AddRange(animMod.SetOrigin((AnimatorController) avatar.runtimeAnimatorController).WriteDefaultLayers()); #endif return layers; } public List<string> HasActivateKeyframeLayers(GameObject[] obj) { var path = obj.Where(o => o != null).Select(o => GetRelativePath(o.transform)).ToArray(); return HasKeyframeLayers(path, "m_IsActive"); } public List<string> HasMaterialKeyframeLayers(GameObject[] obj) { var path = obj.Where(o => o != null).Select(o => GetRelativePath(o.transform)).ToArray(); return HasKeyframeLayers(path, "m_Materials"); } public List<string> HasKeyframeLayers(string[] path, string attribute = "") { var layers = new List<string>(); #if VRC_SDK_VRCSDK3 foreach (var playableLayer in avatar.baseAnimationLayers) { if (playableLayer.animatorController == null) continue; layers.AddRange( animMod. SetOrigin((AnimatorController) playableLayer.animatorController). HasKeyframeLayers(path, attribute)); } #else layers.AddRange( animMod. SetOrigin((AnimatorController) avatar.runtimeAnimatorController). HasKeyframeLayers(path, attribute)); #endif return layers; } AvatarModifyData RenameAssetsParameters(AvatarModifyData assets) { assets.locomotion_controller = animMod.SetOrigin(assets.locomotion_controller).AnimatorControllerParameterRename(); assets.idle_controller = animMod.SetOrigin(assets.idle_controller).AnimatorControllerParameterRename(); assets.action_controller = animMod.SetOrigin(assets.action_controller).AnimatorControllerParameterRename(); assets.gesture_controller = animMod.SetOrigin(assets.gesture_controller).AnimatorControllerParameterRename(); assets.fx_controller = animMod.SetOrigin(assets.fx_controller).AnimatorControllerParameterRename(); #if VRC_SDK_VRCSDK3 assets.menu = ExpressionMenuParameterRename(assets.menu); assets.parameter = ExpressionParameterRename(assets.parameter); #endif return assets; } #region ObjectCombinator /// <summary> /// prefabをボーン下にインスタンスする /// </summary> /// <param name="avatar"></param> /// <param name="prefab"></param> /// <param name="target"></param> void ModifyGameObject(GameObject prefab, out string fromPath, out string toPath, HumanBodyBones target = HumanBodyBones.Hips) { fromPath = ""; toPath = ""; // オブジェクトのインスタンシエイト var instance = GameObject.Instantiate(prefab, avatar.transform); instance.name = prefab.name; fromPath = GetRelativePath(instance.transform); if (!RenameParameters) { instance.name = prefab.name; } else if (prefab.name.StartsWith(prefix)) { instance.name = prefab.name; } else { instance.name = prefix + prefab.name; } toPath = GetRelativePath(instance.transform); var humanoid = avatar.GetComponent<Animator>(); var constraint = instance.GetComponent<ParentConstraint>(); if (constraint) { // コンストレイントでの設定 constraint.constraintActive = false; constraint.weight = 1f; if (humanoid != null) { if (humanoid.isHuman) { Transform bone = humanoid.GetBoneTransform(target); if (constraint != null) { constraint.AddSource(new ConstraintSource() { weight = 1f, sourceTransform = bone }); constraint.constraintActive = true; } } } } else if (humanoid) { //ボーン差し替えでの設定 if (humanoid.isHuman) { Transform bone = humanoid.GetBoneTransform(target); if (bone) { instance.transform.SetParent(bone); instance.transform.localPosition = new Vector3(0f, 0f, 0f); } } toPath = GetRelativePath(instance.transform); } if (fromPath == toPath) { fromPath = ""; toPath = ""; } } void RevertGameObject(GameObject prefab, HumanBodyBones target = HumanBodyBones.Hips) { // オブジェクトのインスタンシエイト var humanoid = avatar.GetComponent<Animator>(); var constraint = prefab.GetComponent<ParentConstraint>(); if (constraint) { // コンストレイントでの設定 foreach (Transform child in avatar.transform) { if (child.name == prefab.name) GameObject.DestroyImmediate(child.gameObject); } } else if (humanoid) { //ボーン差し替えでの設定 if (humanoid.isHuman) { Transform bone = humanoid.GetBoneTransform(target); if (bone) { foreach (Transform child in bone) { if (child.name == prefab.name) GameObject.DestroyImmediate(child.gameObject); } } } } } void DeleateInChild(Transform parent, string keyword) { for (int i = 0; i < parent.childCount;) { if (parent.GetChild(i).gameObject.name.StartsWith(keyword)) { GameObject.DestroyImmediate(parent.GetChild(i).gameObject); } else { DeleateInChild(parent.GetChild(i), keyword); i++; } } } #endregion #region AnimatorCombinator AnimatorController GetAvatarAnimatorController(AnimatorLayerType type) { #if VRC_SDK_VRCSDK3 var index = Array.FindIndex(avatar.baseAnimationLayers, l => l.type == type.GetVRChatAnimatorLayerType()); if (avatar.baseAnimationLayers[index].animatorController) { return (AnimatorController) avatar.baseAnimationLayers[index].animatorController; } return null; #else return avatar.runtimeAnimatorController as AnimatorController; #endif } void SetAvatarAnimatorController(AnimatorLayerType type, AnimatorController controller) { #if VRC_SDK_VRCSDK3 avatar.customizeAnimationLayers = true; var index = Array.FindIndex(avatar.baseAnimationLayers, l => l.type == type.GetVRChatAnimatorLayerType()); if (index == -1) { Debug.LogError("Animation Layers" + type.GetVRChatAnimatorLayerType() + " Not Found"); return; } avatar.baseAnimationLayers[index].isDefault = false; avatar.baseAnimationLayers[index].animatorController = controller; #else avatar.runtimeAnimatorController = controller; #endif } bool GetAvatarAnimatorControllerExists(AnimatorLayerType type) { #if VRC_SDK_VRCSDK3 var index = Array.FindIndex(avatar.baseAnimationLayers, l => l.type == type.GetVRChatAnimatorLayerType()); if (index == -1) { Debug.LogError("Animation Layers" + type.GetVRChatAnimatorLayerType() + " Not Found"); return false; } return avatar.baseAnimationLayers[index].animatorController != null; #else return avatar.runtimeAnimatorController != null; #endif } void ModifyAvatarAnimatorController(AnimatorLayerType type, AnimatorController controller) { if (controller == null) return; if (!GetAvatarAnimatorControllerExists(type)) { if (type == AnimatorLayerType.Locomotion) { SetAvatarAnimatorController(type, MakeCopy<AnimatorController>( AssetUtility.LoadAssetAtGuid<AnimatorController>(EnvironmentVariable.baseAnimator))); } else if (type == AnimatorLayerType.Idle) { SetAvatarAnimatorController(type, MakeCopy<AnimatorController>( AssetUtility.LoadAssetAtGuid<AnimatorController>(EnvironmentVariable.idleAnimator))); } else if (type == AnimatorLayerType.Gesture) { SetAvatarAnimatorController(type, MakeCopy<AnimatorController>( AssetUtility.LoadAssetAtGuid<AnimatorController>(EnvironmentVariable.gestureAnimator))); } else if (type == AnimatorLayerType.Action) { SetAvatarAnimatorController(type, MakeCopy<AnimatorController>( AssetUtility.LoadAssetAtGuid<AnimatorController>(EnvironmentVariable.actionAnimator))); } else if (type == AnimatorLayerType.Fx) { SetAvatarAnimatorController(type, MakeCopy<AnimatorController>( AssetUtility.LoadAssetAtGuid<AnimatorController>(EnvironmentVariable.fxAnimator))); } } animMod.SetOrigin(GetAvatarAnimatorController(type)).ModifyAnimatorController(controller); } void RevertAnimator(AnimatorLayerType type, string keyword) { if (String.IsNullOrWhiteSpace(keyword)) return; if (GetAvatarAnimatorControllerExists(type)) { animMod.SetOrigin(GetAvatarAnimatorController(type)).RevertAnimator(keyword); } } void RevertAnimator(AnimatorLayerType type, AnimatorController controller) { if (controller == null) return; if (GetAvatarAnimatorControllerExists(type)) { animMod.SetOrigin(GetAvatarAnimatorController(type)).RevertAnimator(controller); } } #if VRC_SDK_VRCSDK3 Dictionary<AnimatorLayerType, int> ComputeLayersOffset(AvatarModifyData assets) { var layerOffset = new Dictionary<AnimatorLayerType, int>(); foreach (AnimatorLayerType type in Enum.GetValues(typeof(AnimatorLayerType))) { layerOffset.Add(type,GetLayerOffset(assets,type)); } return layerOffset; } int GetLayerOffset(AvatarModifyData assets,AnimatorLayerType type) { var index = Array.FindIndex(avatar.baseAnimationLayers,l => l.type == type.GetVRChatAnimatorLayerType()); if (index == -1) { Debug.LogError("Animation Layers" + type.GetVRChatAnimatorLayerType() + " Not Found"); return 0; } if (avatar.customizeAnimationLayers == false) return 0; if (avatar.baseAnimationLayers[index].isDefault == true) return 0; if (!avatar.baseAnimationLayers[index].animatorController) return 0; AnimatorController a = (AnimatorController) avatar.baseAnimationLayers[index].animatorController; AnimatorController b = type == AnimatorLayerType.Idle ? assets.idle_controller : type == AnimatorLayerType.Gesture ? assets.gesture_controller : type == AnimatorLayerType.Action ? assets.action_controller : type == AnimatorLayerType.Fx ? assets.fx_controller : null; if (a == null) return 0; if (b == null) return a.layers.Length; int i = 0; foreach (var la in a.layers) { if (b.layers.Any(lb => la.name == lb.name)) { continue; } else { i++; } } return i; } #endif AvatarMask CloneAvatarMask(AvatarMask origin) { if (origin) { if (AssetUtility.GetAssetGuid(origin) == EnvironmentVariable.nottingAvatarMask) { var mask = new AvatarMask(); foreach (AvatarMaskBodyPart p in Enum.GetValues(typeof(AvatarMaskBodyPart))) { if (p != AvatarMaskBodyPart.LastBodyPart) { mask.SetHumanoidBodyPartActive(p, false); } } var ts = Childs(avatar.transform); mask.transformCount = ts.Count; for (int i = 0; i < ts.Count; i++) { mask.SetTransformPath(i, AssetUtility.GetRelativePath(avatar.transform, ts[i])); mask.SetTransformActive(i, false); } var path = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(exportDir, avatar.gameObject.name + "_NottingMask.mask")); AssetDatabase.CreateAsset(mask, path); return mask; } } return origin; } List<Transform> Childs(Transform p, bool root = false) { var l = new List<Transform>(); if (!root) { l.Add(p); } foreach (Transform c in p) { l.AddRange(Childs(c)); } return l; } #endregion #region MenuCombinator #if VRC_SDK_VRCSDK3 VRCExpressionsMenu GetExpressionMenu(VRCExpressionsMenu defaultMenus = null) { return avatar.expressionsMenu; } void SetExpressionMenu(VRCExpressionsMenu menu = null) { avatar.customExpressions = true; avatar.expressionsMenu = menu; } bool GetExpressionMenuExist() { if (avatar.customExpressions == true) { if (avatar.expressionsMenu != null) { return true; } } return false; } /// <summary> /// ExpressionsMenuの安全な結合 /// </summary> /// <param name="menus"></param> /// <param name="origin"></param> void ModifyExpressionMenu(VRCExpressionsMenu menus) { if (menus == null) return; if (GetExpressionMenuExist()) { var parentnmenu = GetExpressionMenu(); if (menus == parentnmenu) return; var current = parentnmenu; foreach (var control in menus.controls) { int menuMax = 8; while (current.controls.Count >= menuMax && AutoAddNextPage) // 項目が上限に達していたら次ページに飛ぶ { if (current.controls[menuMax - 1].name == "NextPage" && current.controls[menuMax - 1].type == VRCExpressionsMenu.Control.ControlType.SubMenu && current.controls[menuMax - 1].subMenu != null) { current = current.controls[menuMax - 1].subMenu; } else { var m = new MenuCreater("NextPage"); m.AddControll(current.controls[menuMax - 1]); var submenu = m.CreateAsset(exportDir); current.controls[menuMax - 1] = new VRCExpressionsMenu.Control() { name = "NextPage", icon = AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentVariable.arrowIcon), type = VRCExpressionsMenu.Control.ControlType.SubMenu, subMenu = submenu }; current = submenu; } EditorUtility.SetDirty(current); } var newController = new VRCExpressionsMenu.Control() { name = control.name, icon = control.icon, labels = control.labels, parameter = new VRCExpressionsMenu.Control.Parameter() { name = GetSafeParam(control.parameter.name) }, style = control.style, subMenu = control.subMenu, type = control.type, value = control.value }; if (control.subParameters != null) { newController.subParameters = control.subParameters.Select(cc => { return new VRCExpressionsMenu.Control.Parameter() {name = GetSafeParam(cc.name)}; }).ToArray(); } if (control.subMenu != null) { if (ModifyOriginalAsset) { newController.subMenu = control.subMenu; } else { var menu = Object.Instantiate(newController.subMenu); AssetDatabase.CreateAsset(menu, AssetDatabase.GenerateUniqueAssetPath(Path.Combine(exportDir, menu.name + ".asset"))); newController.subMenu = ExpressionMenuParameterRename(menu); } } current.controls.Add(newController); } SetExpressionMenu(parentnmenu); EditorUtility.SetDirty(parentnmenu); } else { if (DuplicateAssets) { var current = MakeCopy<VRCExpressionsMenu>(menus, false); SetExpressionMenu(current); EditorUtility.SetDirty(current); } else { SetExpressionMenu(menus); } } } void RevertExpressionMenu(VRCExpressionsMenu menus) { if (menus == null) return; if (GetExpressionMenuExist()) { var parentnmenu = GetExpressionMenu(); if (parentnmenu == menus) { SetExpressionMenu(null); } RevertMenu(menus, parentnmenu); EditorUtility.SetDirty(parentnmenu); } } void RevertMenu(VRCExpressionsMenu menus, VRCExpressionsMenu parentnmenu) { if (menus == null) return; if (parentnmenu == null) return; var newControll = new List<VRCExpressionsMenu.Control>(); foreach (var controll in parentnmenu.controls) { if (controll.name == "NextPage" && controll.icon == AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentVariable.arrowIcon) && controll.type == VRCExpressionsMenu.Control.ControlType.SubMenu) { if (controll.subMenu) RevertMenu(menus, controll.subMenu); } else if (menus.controls.Any(c => ( c.name == controll.name && c.icon == controll.icon && c.type == controll.type && GetSafeParam(c.parameter.name) == controll.parameter.name))) { } else { newControll.Add(controll); } } parentnmenu.controls = newControll.ToList(); EditorUtility.SetDirty(parentnmenu); } void RevertExpressionMenu(string keyword) { if (String.IsNullOrWhiteSpace(keyword)) return; if (GetExpressionMenuExist()) { var parentnmenu = GetExpressionMenu(); RevertMenu(keyword, parentnmenu); EditorUtility.SetDirty(parentnmenu); } } void RevertMenu(string keyword, VRCExpressionsMenu parentnmenu) { if (parentnmenu == null) return; var newControll = new List<VRCExpressionsMenu.Control>(); foreach (var controll in parentnmenu.controls) { if (controll.type == VRCExpressionsMenu.Control.ControlType.SubMenu) { if (controll.subMenu != null) { RevertMenu(keyword, controll.subMenu); if (controll.subMenu.controls.Count > 0) { newControll.Add(controll); } } } else if (controll.parameter.name.StartsWith(keyword)) { } else if (controll.subParameters.Any(p => p.name.StartsWith(keyword))) { } else { newControll.Add(controll); } } parentnmenu.controls = newControll.ToList(); EditorUtility.SetDirty(parentnmenu); } VRCExpressionsMenu ExpressionMenuParameterRename(VRCExpressionsMenu menu) { if (menu == null) return null; if (menu.controls == null) return null; // menu = ScriptableObject.Instantiate(menu); menu.controls = menu.controls.Select(c => { if (c.type == VRCExpressionsMenu.Control.ControlType.SubMenu) { c.subMenu = ExpressionMenuParameterRename(c.subMenu); } c.parameter = new VRCExpressionsMenu.Control.Parameter() {name = GetSafeParam(c.parameter.name)}; if (c.subParameters != null) { c.subParameters = c.subParameters.Select(cc => { return new VRCExpressionsMenu.Control.Parameter() {name = GetSafeParam(cc.name)}; }).ToArray(); } return c; }).ToList(); EditorUtility.SetDirty(menu); return menu; } #endif #endregion #region ParametersCombinater #if VRC_SDK_VRCSDK3 VRCExpressionParameters GetExpressionParameter() { return avatar.expressionParameters; } void SetExpressionParameter(VRCExpressionParameters param = null) { avatar.customExpressions = true; avatar.expressionParameters = param; } bool GetExpressionParameterExist() { if (avatar.customExpressions == true) { if (avatar.expressionParameters != null) { return true; } } return false; } /// <summary> /// ExpressionParametersの安全な結合 /// </summary> /// <param name="parameters"></param> /// <param name="origin"></param> void ModifyExpressionParameter(VRCExpressionParameters parameters) { if (parameters == null) return; if (GetExpressionParameterExist()) { var current = GetExpressionParameter(); if (parameters == current) return; foreach (var parameter in parameters.parameters) { AddExpressionParameter(current, parameter.name, parameter.valueType, parameter.saved, parameter.defaultValue); } EditorUtility.SetDirty(current); } else { if (DuplicateAssets) { var current = MakeCopy<VRCExpressionParameters>(parameters, false); SetExpressionParameter(current); EditorUtility.SetDirty(current); } else { SetExpressionParameter(parameters); } } } void AddExpressionParameter(VRCExpressionParameters parameters, string name, VRCExpressionParameters.ValueType type, bool saved = true, float value = 0f) { var newParm = parameters.parameters.Where(p => p.name != GetSafeParam(name)).ToList(); // 新規パラメータ追加 newParm.Add(new VRCExpressionParameters.Parameter() { name = GetSafeParam(name), valueType = type, saved = saved, defaultValue = value }); parameters.parameters = newParm.ToArray(); EditorUtility.SetDirty(parameters); } void RevertExpressionParameter(VRCExpressionParameters parameters) { if (parameters == null) return; if (GetExpressionParameterExist()) { var current = GetExpressionParameter(); if (parameters == current) { SetExpressionParameter(null); } var newParams = new List<VRCExpressionParameters.Parameter>(); foreach (var parameter in current.parameters) { if (parameters.parameters.Any(p => ( GetSafeParam(p.name) == GetSafeParam(parameter.name) && p.valueType == parameter.valueType))) { } else { newParams.Add(parameter); } } current.parameters = newParams.ToArray(); EditorUtility.SetDirty(current); } } void RevertExpressionParameter(string keyword) { if (String.IsNullOrWhiteSpace(keyword)) return; if (GetExpressionParameterExist()) { var current = GetExpressionParameter(); current.parameters = current.parameters.Where(p => !p.name.StartsWith(keyword)).ToArray(); EditorUtility.SetDirty(current); } } VRCExpressionParameters ExpressionParameterRename(VRCExpressionParameters param) { if (param == null) return null; if (param.parameters == null) return null; // param = ScriptableObject.Instantiate(param); param.parameters = param.parameters.Select(p => new VRCExpressionParameters.Parameter() { name = GetSafeParam(p.name), saved = p.saved, defaultValue = p.defaultValue, valueType = p.valueType } ).ToArray(); EditorUtility.SetDirty(param); return param; } #endif #endregion string GetRelativePath(Transform o) { return AssetUtility.GetRelativePath(avatar.transform, o); } T SafeCopy<T>(T obj) where T : Object { if (ExistAssetObject(obj)) { return obj; } else { return MakeCopy<T>(obj); } } bool ExistAssetObject(Object obj) { var path = AssetDatabase.GetAssetPath(obj); return !String.IsNullOrWhiteSpace(path); } T MakeCopy<T>(T origin, bool cloneSubAssets = true) where T : Object { string sufix = origin is AnimatorController ? ".controller" : origin is AnimationClip ? ".anim" : ".asset"; if (origin != null) { var path = AssetDatabase.GetAssetPath(origin); string copyPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(exportDir, origin.name + "_copy" + sufix)); if (!String.IsNullOrWhiteSpace(path)) { if (cloneSubAssets) { AssetDatabase.CopyAsset(path, copyPath); Debug.Log("Copy : " + origin.name + "from:" + path + " to:" + copyPath); } else { T clone = Object.Instantiate(origin); AssetDatabase.CreateAsset(clone, copyPath); Debug.Log("Instance : " + origin.name + " to " + copyPath); } } else { AssetDatabase.CreateAsset(origin, copyPath); Debug.Log("Create : " + origin.name + " to " + copyPath); } return (T) AssetDatabase.LoadAssetAtPath<T>(copyPath); } return null; } // パラメータ文字列から2バイト文字の除去を行う public string GetSafeParam(string param) { return param.GetSafeParam(prefix, RenameParameters); } } } <|start_filename|>Assets/HhotateA/MeshModifyTool/Shaders/Normal.shader<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ Shader "HhotateA/MeshModifyTool/Normal" { Properties { _MainTex ("Texture", 2D) = "white" {} _NormalAlpha ("NormalAlpha",range(0,1)) = 0 } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { Tags {"Queue"="Opaque"} CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float4 normal : NORMAL; float2 uv : TEXCOORD; }; struct v2f { float4 vertex : SV_POSITION; float4 normal : NORMAL; float2 uv : TEXCOORD; }; sampler2D _MainTex; float4 _MainTex_ST; float _NormalAlpha; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.normal = v.normal; o.uv = TRANSFORM_TEX(v.uv, _MainTex); return o; } fixed4 frag (v2f i) : SV_Target { fixed4 col = tex2D(_MainTex, i.uv); col = lerp(col,i.normal,_NormalAlpha); return col; } ENDCG } } } <|start_filename|>Assets/HhotateA/MagicalDresserInventorySystem/Editor/MagicalDresserInventorySetup.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using HhotateA.AvatarModifyTools.Core; using UnityEditor; using UnityEditorInternal; using UnityEngine; using UnityEditor.Callbacks; using UnityEditor.IMGUI.Controls; using Object = System.Object; #if VRC_SDK_VRCSDK3 using VRC.SDK3.Avatars.Components; #endif namespace HhotateA.AvatarModifyTools.MagicalDresserInventorySystem { public class MagicalDresserInventorySetup : WindowBase { [OnOpenAssetAttribute] public static bool OpenAsset(int instanceID, int line) { if (EditorUtility.InstanceIDToObject(instanceID).GetType() == typeof(MagicalDresserInventorySaveData)) { OpenSavedWindow(EditorUtility.InstanceIDToObject(instanceID) as MagicalDresserInventorySaveData); } return false; } [MenuItem("Window/HhotateA/マジックドレッサーインベントリ(MDInventorySystem)",false,106)] public static void ShowWindow() { OpenSavedWindow(); } private MagicalDresserInventorySaveData data; private List<MenuElement> menuElements => data.menuElements; private SerializedProperty prop; ReorderableList menuReorderableList; MenuTemplateTreeView menuTreeView; private bool displayItemMode = true; private bool displaySyncTransition = false; // <renderer original material,<transition sample material, use material>> Dictionary<Material,Dictionary<Material, Material>> matlist = new Dictionary<Material,Dictionary<Material, Material>>(); Dictionary<GameObject,bool> defaultActive = new Dictionary<GameObject, bool>(); Dictionary<Renderer,bool> defaultRendEnable = new Dictionary<Renderer, bool>(); Dictionary<Renderer, Material[]> defaultMaterials = new Dictionary<Renderer, Material[]>(); Dictionary<BlendShapeReference,float> defaultBlendShapes = new Dictionary<BlendShapeReference, float>(); struct BlendShapeReference { public SkinnedMeshRenderer rend; public int index; } private bool openMenuList = true; Vector2 scrollLeft = Vector2.zero; Vector2 scrollLeftTree = Vector2.zero; Vector2 scrollRight = Vector2.zero; Material GetAnimationMaterial(Material origin,Material animMat) { if (origin == null) return null; if (!matlist.ContainsKey(animMat)) { matlist.Add(animMat,new Dictionary<Material,Material>()); } if (!matlist[animMat].ContainsKey(origin)) { if (animMat.GetTypeByMaterial() != FeedType.None) { var mat = animMat.GetTypeByMaterial().GetMaterialByType(); mat = Instantiate(mat); if(origin.mainTexture) mat.mainTexture = origin.mainTexture; matlist[animMat].Add(origin,mat); } else { var mat = new Material(animMat); mat.name = origin.name + "_" + animMat.name; mat.mainTexture = origin.mainTexture; matlist[animMat].Add(origin,mat); } } return matlist[animMat][origin]; } public static void OpenSavedWindow(MagicalDresserInventorySaveData saveddata = null) { var wnd = GetWindow<MagicalDresserInventorySetup>(); wnd.titleContent = new GUIContent("マジックドレッサーインベントリ(MDInventorySystem)"); wnd.minSize = new Vector2(850, 500); wnd.maxSize = new Vector2(850,2000); if (saveddata == null) { saveddata = CreateInstance<MagicalDresserInventorySaveData>(); saveddata.icon = AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.itemboxIcon); } // wnd.data = Instantiate(saveddata); wnd.data = saveddata; wnd.LoadReorderableList(); var root = wnd.data.GetRoot(); if (root) { #if VRC_SDK_VRCSDK3 wnd.avatar = root.GetComponent<VRCAvatarDescriptor>(); #endif if (wnd.avatar) { wnd.data.ApplyRoot(wnd.avatar.gameObject); } } wnd.LoadReorderableList(); } void LoadReorderableList() { menuReorderableList = new ReorderableList(menuElements, typeof(MenuElement), true, true, false,false) { drawHeaderCallback = r => { EditorGUI.LabelField(r,"Menu Elements"); }, elementHeight = 60+6, drawElementCallback = (r, i, a, f) => DrawMenuElement(r,i), onAddCallback = l => AddMenu(), onSelectCallback = l => { SetObjectActiveForScene(menuElements[l.index]); scrollRight = Vector2.zero; } }; menuTreeView = new MenuTemplateTreeView(new TreeViewState ()); menuTreeView.Setup(data); menuTreeView.OnSelect += (m) => { menuReorderableList.index = data.menuElements.FindIndex(e=>e==m); SetObjectActiveForScene(m); scrollRight = Vector2.zero; }; } void DrawMenuElement(Rect r, int i) { if (0 > i || menuElements.Count <= i) { EditorGUI.LabelField(r,"Null" + i); return; } var d = menuElements[i]; if(d == null) return; { var rh = r; rh.width = rh.height; d.icon = (Texture2D) EditorGUI.ObjectField (rh,d.icon, typeof(Texture2D), false); r.width -= rh.width; r.x += rh.width+10; } r.height -= 6; r.height /= 3; r.width *= 0.95f; d.name = EditorGUI.TextField(r,"", d.name); r.y += 2; r.y += r.height; if (d.isToggle) { var rh = r; rh.width = 20; d.SetLayer( EditorGUI.Toggle(rh, "", d.isToggle)); rh.x += rh.width; rh.width = 120; using (new EditorGUI.DisabledScope(true)) { EditorGUI.EnumPopup(rh, (ToggleGroup)0); } rh.x += rh.width+10; rh.width = 20; d.isRandom = EditorGUI.Toggle(rh, "", d.isRandom); rh.x += rh.width; rh.width = 100; EditorGUI.LabelField(rh, "Is Random"); } else { var rh = r; rh.width = 20; d.SetLayer( EditorGUI.Toggle(rh, "", d.isToggle)); rh.x += rh.width; rh.width = 120; d.SetLayer( (LayerGroup) EditorGUI.EnumPopup(rh, d.layer)); rh.x += rh.width+10; rh.width = 20; data.layerSettingses[(int) d.layer].isRandom = EditorGUI.Toggle(rh, "", data.layerSettingses[(int) d.layer].isRandom); rh.x += rh.width; rh.width = 60; using (new EditorGUI.DisabledScope(d.isTaboo)) { EditorGUI.LabelField(rh, d.isTaboo ? "is Taboo" : "Is Random"); } //if (data.layerSettingses[(int) d.layer].isRandom) { rh.x += rh.width+5; rh.width = 20; d.isTaboo = EditorGUI.Toggle(rh, "", d.isTaboo); } } r.y += 2; r.y += r.height; if (d.isToggle) { var rh = r; rh.width = 20; d.isSaved = EditorGUI.Toggle(rh, "", d.isSaved); rh.x += rh.width; rh.width = 100; EditorGUI.LabelField(rh, "Is Saved"); rh.x += rh.width + 30; rh.width = 20; d.isDefault = EditorGUI.Toggle(rh, "", d.isDefault); rh.x += rh.width; rh.width = 100; EditorGUI.LabelField(rh, "Is Default"); } else { var rh = r; rh.width = 20; data.layerSettingses[(int)d.layer].isSaved = EditorGUI.Toggle(rh, "", data.layerSettingses[(int)d.layer].isSaved); rh.x += rh.width; rh.width = 100; EditorGUI.LabelField(rh, "Is Saved"); rh.x += rh.width + 30; rh.width = 20; if (data.layerSettingses[(int) d.layer].GetDefaultElement(menuElements) == d) { rh.width = 20; if (!EditorGUI.Toggle(rh, "",true)) { data.layerSettingses[(int) d.layer].SetDefaultElement(null); } rh.x += rh.width; rh.width = 100; EditorGUI.LabelField(rh, "Is Default"); } else { rh.width = 20; if (EditorGUI.Toggle(rh, "",false)) { data.layerSettingses[(int) d.layer].SetDefaultElement(d); } rh.x += rh.width; rh.width = 100; EditorGUI.LabelField(rh, "Is Default"); } } } void DrawFolderElement(Rect r, MenuTemplate d) { var rh = r; rh.width = rh.height; d.icon = (Texture2D) EditorGUI.ObjectField (rh,d.icon, typeof(Texture2D), false); r.width -= rh.width; r.x += rh.width+10; r.height -= 6; r.height /= 3; r.width *= 0.95f; d.name = EditorGUI.TextField(r,"", d.name); } private void OnGUI() { TitleStyle("マジックドレッサーインベントリ"); DetailStyle("アバターのメニューから,服やアイテムの入れ替えを行える設定ツールです.",EnvironmentGUIDs.readme); #if VRC_SDK_VRCSDK3 EditorGUILayout.Space(); AvatartField("",()=> { RevertObjectActiveForScene(); data.ApplyRoot(avatar.gameObject); data.SaveGUID(avatar.gameObject); LoadReorderableList(); }); EditorGUILayout.Space(); EditorGUILayout.Space(); if (!avatar) { GUILayout.Label("シーン上のアバターをドラッグ&ドロップ"); EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { data.icon = (Texture2D) EditorGUILayout.ObjectField(data.icon, typeof(Texture2D), false, GUILayout.Width(60), GUILayout.Height(60)); using (new EditorGUILayout.VerticalScope()) { data.saveName = EditorGUILayout.TextField(data.saveName, GUILayout.Height(20)); } } return; } var index = menuReorderableList.index; using (new EditorGUILayout.VerticalScope()) { using (new EditorGUILayout.HorizontalScope(GUI.skin.box)) { data.icon = (Texture2D) EditorGUILayout.ObjectField(data.icon, typeof(Texture2D), false, GUILayout.Width(60), GUILayout.Height(60)); using (new EditorGUILayout.VerticalScope()) { data.saveName = EditorGUILayout.TextField(data.saveName, GUILayout.Height(20)); using (new EditorGUILayout.HorizontalScope()) { using (new EditorGUILayout.VerticalScope()) { data.materialOverride = EditorGUILayout.ToggleLeft("Override Default Value Animation", data.materialOverride); data.idleOverride = EditorGUILayout.ToggleLeft("Override Animation On Idle State", data.idleOverride); } using (new EditorGUILayout.VerticalScope()) { data.createAnimWhenNotChangedActive = EditorGUILayout.ToggleLeft("Create Anim when Not Changed Active", data.createAnimWhenNotChangedActive); data.useMenuTemplate = EditorGUILayout.ToggleLeft("Use Menu Template", data.useMenuTemplate); } } } } EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.Space(10); using (new EditorGUILayout.VerticalScope(GUILayout.Width(350))) { using (var check = new EditorGUI.ChangeCheckScope()) { if (data.useMenuTemplate) { using (new EditorGUILayout.VerticalScope(GUI.skin.box,GUILayout.Width(330))) { var menuelementRect = EditorGUILayout.GetControlRect(false, 60); if (menuReorderableList.index >= 0) { DrawMenuElement(menuelementRect, menuReorderableList.index); } else { var selectFolders = menuTreeView.GetSelectTemplates(); if (selectFolders.Count > 0) { DrawFolderElement(menuelementRect, selectFolders[0]); } } } scrollLeftTree = EditorGUILayout.BeginScrollView(scrollLeftTree, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); var treeRect = EditorGUILayout.GetControlRect(false, openMenuList ? (position.height-300)/2 : position.height-300); treeRect.width = 375; menuTreeView.OnGUI(treeRect); EditorGUILayout.EndScrollView(); using (new EditorGUILayout.HorizontalScope()) { if(GUILayout.Button("Reset",GUILayout.Width(75))) { ResetTemplate(); } EditorGUILayout.LabelField("",GUILayout.Width(100)); if(GUILayout.Button("New Folder",GUILayout.Width(75))) { AddFolder(); } EditorGUILayout.LabelField(" ",GUILayout.Width(10)); using (new EditorGUI.DisabledScope(menuTreeView.GetSelectTemplates().Count == 0 && !(0 <= menuReorderableList.index && menuReorderableList.index < menuElements.Count))) { if(GUILayout.Button("-",GUILayout.Width(30))) { if (0 <= menuReorderableList.index && menuReorderableList.index < menuElements.Count) { menuElements.RemoveAt(menuReorderableList.index); } else { var selectFolders = menuTreeView.GetSelectTemplates(); // foreach (var selectFolder in selectFolders) { var selectFolder = selectFolders[0]; if (String.IsNullOrWhiteSpace(selectFolder.menuGUID)) { MenuTemplate.FIndTemplateElement(data.menuTemplate, selectFolder.GetGuid(), (e, p) => { if (p == null) { if (data.menuTemplate.Contains(e)) { data.menuTemplate.Remove(e); } } else { p.childs.Remove(e); } }); } else { var menu = menuElements.FirstOrDefault(e => e.guid == selectFolder.menuGUID); if (menu != null) { menuElements.Remove(menu); } } } } menuTreeView.ReloadTemplates(); } } EditorGUILayout.LabelField(" ",GUILayout.Width(2)); if(GUILayout.Button("+",GUILayout.Width(30))) { AddMenu(); } } openMenuList = EditorGUILayout.ToggleLeft("Extend Menu List",openMenuList); if (openMenuList) { scrollLeft = EditorGUILayout.BeginScrollView(scrollLeft, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView,GUILayout.Width(375),GUILayout.ExpandHeight(false)); menuReorderableList.DoLayoutList(); EditorGUILayout.EndScrollView(); } else { } EditorGUILayout.Space(); EditorGUILayout.LabelField(" ",GUILayout.ExpandHeight(true)); } else { scrollLeft = EditorGUILayout.BeginScrollView(scrollLeft, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView,GUILayout.Width(375),GUILayout.ExpandHeight(false)); menuReorderableList.DoLayoutList(); EditorGUILayout.EndScrollView(); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField(" ",GUILayout.Width(275)); using (new EditorGUI.DisabledScope(!(0 <= menuReorderableList.index && menuReorderableList.index < menuElements.Count))) { if(GUILayout.Button("-",GUILayout.Width(30))) { if(0 <= menuReorderableList.index && menuReorderableList.index < menuElements.Count) { menuElements.RemoveAt(menuReorderableList.index); } } } EditorGUILayout.LabelField(" ",GUILayout.Width(5)); if(GUILayout.Button("+",GUILayout.Width(30))) { AddMenu(); } } EditorGUILayout.Space(); } if (check.changed) { if (0 <= index && index < menuElements.Count) { SetObjectActiveForScene(menuElements[menuReorderableList.index]); } menuTreeView.ReloadTemplates(); } } } EditorGUILayout.Space(10); using (new EditorGUILayout.VerticalScope(GUILayout.Width(400))) { var itemListStyle = new GUIStyle(); var itemListStyleNormal = itemListStyle.normal; itemListStyleNormal.background = Texture2D.grayTexture; itemListStyle.normal = itemListStyleNormal; using (new EditorGUILayout.VerticalScope(itemListStyle)) { if (0 <= index && index < menuElements.Count) { EditorGUILayout.LabelField(menuElements[index].name,GUILayout.Width(210)); using (var r = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField(""); var rect = r.rect; rect.height += 5; var tabstyleActive = new GUIStyle(GUI.skin.button); tabstyleActive.stretchWidth = true; var ns = tabstyleActive.normal; ns.background = Texture2D.blackTexture; ns.textColor = Color.gray; tabstyleActive.normal = ns; var tabstyleDisable = new GUIStyle(GUI.skin.box); tabstyleDisable.stretchWidth = true; rect.width /= 2; if (GUI.Button(rect, "ON", displayItemMode ? tabstyleDisable : tabstyleActive)) { displayItemMode = true; SetObjectActiveForScene(menuElements[index]); } rect.x += rect.width; if (GUI.Button(rect, "OFF", displayItemMode ? tabstyleActive : tabstyleDisable)) { displayItemMode = false; SetObjectActiveForScene(menuElements[index]); } } using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { ItemLabelDisplay(); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); ItemElementDisplay(menuElements[index]); scrollRight = EditorGUILayout.BeginScrollView(scrollRight, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); if (displayItemMode) { using (var check = new EditorGUI.ChangeCheckScope()) { foreach (var item in menuElements[index].UnSafeActiveItems()) { ItemElementDisplay(item, false, true, false, false, false, menuElements[index], (o) => { data.RepairReference(item.path, o, avatar.gameObject); }, () => { menuElements[index].activeItems.Remove(item); }); } foreach (var item in menuElements[index].SafeActiveItems()) { ItemElementDisplay(item, true, true, true, true, true, menuElements[index], (o) => { // item.obj = o; }, () => { menuElements[index].activeItems.Remove(item); }); } if (!menuElements[index].isToggle) { foreach (var item in ComputeLayerAnotherItems(menuElements[index])) { ItemElementDisplay(item, true, false, true, true, true, menuElements[index], (o) => { // item.obj = o; }, () => { menuElements[index].activeItems.Remove(item); }, () => { menuElements[index].activeItems.Add(item); }); } } if (check.changed) { SetObjectActiveForScene(menuElements[index]); // SyncItemActive(menuElements[index].activeItems, menuElements[index].inactiveItems, true); } } } else { using (var check = new EditorGUI.ChangeCheckScope()) { foreach (var item in menuElements[index].UnSafeInactiveItems()) { ItemElementDisplay(item, false, true, false, false, false, menuElements[index], (o) => { data.RepairReference(item.path, o, avatar.gameObject); }, () => { menuElements[index].inactiveItems.Remove(item); }); } foreach (var item in menuElements[index].SafeInactiveItems()) { ItemElementDisplay(item, true, true, true, true, true, menuElements[index], (o) => { // item.obj = o; }, () => { menuElements[index].inactiveItems.Remove(item); }); } foreach (var item in ComputeLayerInactiveItems(menuElements[index])) { using (var add = new EditorGUI.ChangeCheckScope()) { ItemElementDisplay(item, false, false, true, true, false, menuElements[index], (o) => { // item.obj = o; }, () => { menuElements[index].inactiveItems.Remove(item); }, () => { menuElements[index].inactiveItems.Add(item); }); } } if (check.changed) { SetObjectActiveForScene(menuElements[index]); // SyncItemActive(menuElements[index].inactiveItems, menuElements[index].activeItems, true); } } } EditorGUILayout.EndScrollView(); var newItem = (GameObject) EditorGUILayout.ObjectField("", null, typeof(GameObject), true, GUILayout.Width(370)); if (newItem) { if (menuElements[index].activeItems.All(e => e.obj != newItem)) { menuElements[index].activeItems.Add(new ItemElement(newItem, avatar.gameObject, IsMenuElementDefault(menuElements[index]) ? newItem.gameObject.activeSelf : !newItem.gameObject.activeSelf)); } SetObjectActiveForScene(menuElements[index]); } //sync element using (new EditorGUILayout.HorizontalScope()) { displaySyncTransition = EditorGUILayout.Foldout(displaySyncTransition, "Sync Elements"); EditorGUILayout.LabelField(" ",GUILayout.Width(40),GUILayout.ExpandWidth(true)); EditorGUILayout.LabelField("Delay",GUILayout.Width(50)); EditorGUILayout.LabelField("",GUILayout.Width(10)); EditorGUILayout.LabelField("On",GUILayout.Width(25)); EditorGUILayout.LabelField("Off",GUILayout.Width(25)); } using (new EditorGUILayout.VerticalScope()) { if (displaySyncTransition) { foreach (var menuElement in menuElements) { if (menuElements[index] != menuElement) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField(" ",GUILayout.Width(50),GUILayout.ExpandWidth(true)); EditorGUILayout.LabelField(menuElement.name,GUILayout.Width(100)); var syncElement = displayItemMode ? menuElements[index].activeSyncElements.FirstOrDefault(e => e.guid == menuElement.guid): menuElements[index].inactiveSyncElements.FirstOrDefault(e => e.guid == menuElement.guid); //var syncOffElements = displayItemMode ? menuElements[index].activeSyncOffElements : menuElements[index].inactiveSyncOffElements; if (syncElement == null) { using (var check = new EditorGUI.ChangeCheckScope()) { syncElement = new SyncElement(menuElement.guid); if (EditorGUILayout.Toggle("", syncElement.delay>=0, GUILayout.Width(25))) { syncElement.delay = 0f; } else { syncElement.delay = -1f; } using (new EditorGUI.DisabledScope(true)) { syncElement.delay = EditorGUILayout.FloatField("", syncElement.delay, GUILayout.Width(50)); } EditorGUILayout.LabelField("",GUILayout.Width(15)); syncElement.syncOn = EditorGUILayout.Toggle("", syncElement.syncOn, GUILayout.Width(25)); syncElement.syncOff = EditorGUILayout.Toggle("", syncElement.syncOff, GUILayout.Width(25)); if (check.changed) { if (displayItemMode) { menuElements[index].activeSyncElements.Add(syncElement); } else { menuElements[index].inactiveSyncElements.Add(syncElement); } } } } else { if (EditorGUILayout.Toggle("", syncElement.delay>=0, GUILayout.Width(25))) { syncElement.delay = 0f; } else { syncElement.delay = -1f; } using (new EditorGUI.DisabledScope(true)) { syncElement.delay = EditorGUILayout.FloatField("", syncElement.delay, GUILayout.Width(50)); } EditorGUILayout.LabelField("",GUILayout.Width(15)); if (EditorGUILayout.Toggle("", syncElement.syncOn, GUILayout.Width(25))) { if (!syncElement.syncOn) { // 重複防止 syncElement.syncOn = true; syncElement.syncOff = false; } } else { syncElement.syncOn = false; } if(EditorGUILayout.Toggle("", syncElement.syncOff, GUILayout.Width(25))) { if (!syncElement.syncOff) { // 重複防止 syncElement.syncOff = true; syncElement.syncOn = false; } } else { syncElement.syncOff = false; } } } } } } } } } else { EditorGUILayout.LabelField("null"); } } EditorGUILayout.Space(); if (ShowOptions()) { if (GUILayout.Button("Force Revert")) { RevertObjectActiveForScene(); var mod = new AvatarModifyTool(avatar); mod.RevertByKeyword(EnvironmentGUIDs.prefix); OnFinishRevert(); } } EditorGUILayout.Space(); EditorGUILayout.Space(); using (new EditorGUI.DisabledScope(avatar == null)) { if (GUILayout.Button("Setup")) { RevertObjectActiveForScene(); var path = EditorUtility.SaveFilePanel("Save", data.GetAssetDir(), data.GetAssetName(), "mdinventry.asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } if (String.IsNullOrWhiteSpace(data.saveName)) { string fileName = System.IO.Path.GetFileNameWithoutExtension(path); data.saveName = fileName; } try { data = Instantiate(data); LoadReorderableList(); // data.ApplyPath(avatar.gameObject); path = FileUtil.GetProjectRelativePath(path); AssetDatabase.CreateAsset(data, path); Setup(path); OnFinishSetup(); var conflict = FindConflict(); if (conflict.Count > 0) { //status.Warning("Detect Conflict Layer : " + conflict[0]); status.Warning("Complete Setup (Detect Conflict Layers)"); foreach (var c in conflict) { Debug.LogWarning("Detect Conflict Layer : " + c); } } DetectAnimatorError(); } catch (Exception e) { OnError(e); throw; } } } EditorGUILayout.Space(); if (GUILayout.Button("Export Animation")) { RevertObjectActiveForScene(); var path = EditorUtility.SaveFilePanel("Save", data.GetAssetDir(), data.GetAssetName(), "anim"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } data.saveName = Path.GetFileNameWithoutExtension(path); try { // data = Instantiate(data); // LoadReorderableList(); // data.ApplyPath(avatar.gameObject); // AssetDatabase.CreateAsset(data, FileUtil.GetProjectRelativePath(path)); SaveAnim(path); status.Success("Finish Export"); } catch (Exception e) { OnError(e); throw; } } EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Save Settings")) { var path = EditorUtility.SaveFilePanel("Save", data.GetAssetDir(), data.GetAssetName(),"mdinventry.asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } data = Instantiate(data); LoadReorderableList(); AssetDatabase.CreateAsset(data, FileUtil.GetProjectRelativePath(path)); OnSave(); } if (GUILayout.Button("Load Settings")) { var path = EditorUtility.OpenFilePanel("Load", data.GetAssetDir(), "mdinventry.asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } var d = AssetDatabase.LoadAssetAtPath<MagicalDresserInventorySaveData>(FileUtil.GetProjectRelativePath(path)); if (d == null) { status.Warning("Load Failure"); return; } else { data = d; LoadReorderableList(); } // avatarの設定 if (avatar) { data.ApplyRoot(avatar.gameObject); } else { var root = d.GetRoot(); if (root) { #if VRC_SDK_VRCSDK3 avatar = root.GetComponent<VRCAvatarDescriptor>(); #endif if (avatar) { data.ApplyRoot(avatar.gameObject); } } } OnLoad(); } } status.Display(); Signature(); } } } #else VRCErrorLabel(); #endif } bool GetLayerDefaultActive(LayerGroup layer,GameObject obj) { var item = data.layerSettingses[(int) layer].GetDefaultElement(menuElements).SafeActiveItems() .FirstOrDefault(e => e.obj == obj); if (item != null) { return item.active; } return true; } void ItemLabelDisplay() { GUIStyle label = new GUIStyle(GUI.skin.label); label.fontSize = 10; label.wordWrap = true; label.alignment = TextAnchor.LowerLeft; using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("IsActive", label,GUILayout.Width(55)); EditorGUILayout.LabelField("Object", label,GUILayout.Width(150)); EditorGUILayout.LabelField("Delay", label,GUILayout.Width(50)); EditorGUILayout.LabelField("Duration", label,GUILayout.Width(50)); EditorGUILayout.LabelField("Type", label,GUILayout.Width(100)); } } void ItemElementDisplay(MenuElement parentmenu) { using (new EditorGUILayout.VerticalScope()) { using (new EditorGUILayout.HorizontalScope()) { parentmenu.extendOverrides = EditorGUILayout.Foldout(parentmenu.extendOverrides, "Override Transitions"); } if (parentmenu.extendOverrides) { using (new EditorGUILayout.HorizontalScope()) { var item = parentmenu.overrideActivateTransition; EditorGUILayout.LabelField(" ", GUILayout.Width(30)); parentmenu.isOverrideActivateTransition = EditorGUILayout.Toggle("", parentmenu.isOverrideActivateTransition, GUILayout.Width(30)); EditorGUILayout.LabelField("Activate Transition", GUILayout.Width(150)); item.delay = EditorGUILayout.FloatField("", item.delay, GUILayout.Width(50)); item.duration = EditorGUILayout.FloatField("", item.duration, GUILayout.Width(50)); item.type = (FeedType) EditorGUILayout.EnumPopup("", item.type, GUILayout.Width(100)); } if (parentmenu.overrideActivateTransition.type == FeedType.Shader) { ShaderOptionDisplay(parentmenu.overrideActivateTransition); } using (new EditorGUILayout.HorizontalScope()) { var item = parentmenu.overrideInactivateTransition; EditorGUILayout.LabelField("", GUILayout.Width(30)); parentmenu.isOverrideInactivateTransition = EditorGUILayout.Toggle("", parentmenu.isOverrideInactivateTransition, GUILayout.Width(30)); EditorGUILayout.LabelField("Inactivate Transition", GUILayout.Width(150)); item.delay = EditorGUILayout.FloatField("", item.delay, GUILayout.Width(50)); item.duration = EditorGUILayout.FloatField("", item.duration, GUILayout.Width(50)); item.type = (FeedType) EditorGUILayout.EnumPopup("", item.type, GUILayout.Width(100)); } if (parentmenu.overrideInactivateTransition.type == FeedType.Shader) { ShaderOptionDisplay(parentmenu.overrideInactivateTransition); } } } } void ItemElementDisplay(ItemElement item,bool activeEdit = true,bool objEdit = true,bool timeEdit = true,bool typeEdit = true, bool optionEdit = true, MenuElement parentmenu = null,Action<GameObject> onSetObject = null,Action onRemoveObject = null,Action onChange = null) { bool overrideMode = false; if (parentmenu != null) { if (item.active && parentmenu.isOverrideActivateTransition) { overrideMode = true; } if (!item.active && parentmenu.isOverrideInactivateTransition) { overrideMode = true; } } using (new EditorGUILayout.HorizontalScope()) { //EditorGUILayout.LabelField("",GUILayout.Width(5)); var r = GUILayoutUtility.GetRect(new GUIContent(""), GUI.skin.toggle,GUILayout.Width(25)); using (new EditorGUI.DisabledScope(!optionEdit)) { item.extendOption = EditorGUI.Foldout(r, item.extendOption, ""); } using (var change = new EditorGUI.ChangeCheckScope()) { using (new EditorGUI.DisabledScope(!activeEdit)) { item.active = EditorGUILayout.Toggle("", item.active, GUILayout.Width(30)); } using (new EditorGUI.DisabledScope(!objEdit)) { var o = (GameObject) EditorGUILayout.ObjectField("", item.obj, typeof(GameObject), true, GUILayout.Width(110)); if (item.obj == null) { if (o != null) { // item.obj = o; onSetObject?.Invoke(o); } if (GUILayout.Button("×", GUILayout.Width(40))) { // item.obj = null; onRemoveObject?.Invoke(); } EditorGUILayout.LabelField(" ",GUILayout.Width(10)); EditorGUILayout.LabelField("Missing :",GUILayout.Width(50)); EditorGUILayout.TextField(item.path,GUILayout.Width(140)); return; } else { if (o == null) { // 消されたときのみ上書き // item.obj = null; onRemoveObject?.Invoke(); } if (GUILayout.Button(objEdit ? "×" : "Sync", GUILayout.Width(40))) { // item.obj = null; onRemoveObject?.Invoke(); } } } if (overrideMode) { if (item.active) { using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.FloatField("", parentmenu.overrideActivateTransition.delay, GUILayout.Width(50)); EditorGUILayout.FloatField("", parentmenu.overrideActivateTransition.duration, GUILayout.Width(50)); EditorGUILayout.EnumPopup("", parentmenu.overrideActivateTransition.type, GUILayout.Width(100)); } } else { using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.FloatField("", parentmenu.overrideInactivateTransition.delay, GUILayout.Width(50)); EditorGUILayout.FloatField("", parentmenu.overrideInactivateTransition.duration, GUILayout.Width(50)); EditorGUILayout.EnumPopup("", parentmenu.overrideInactivateTransition.type, GUILayout.Width(100)); } } } else { using (new EditorGUI.DisabledScope(!timeEdit)) { item.delay = EditorGUILayout.FloatField("", item.delay, GUILayout.Width(50)); item.duration = EditorGUILayout.FloatField("", item.duration, GUILayout.Width(50)); } using (new EditorGUI.DisabledScope(!typeEdit)) { item.type = (FeedType) EditorGUILayout.EnumPopup("", item.type, GUILayout.Width(100)); } } if (change.changed) { onChange?.Invoke(); } } } if (overrideMode) { if (item.active) { if (item.extendOption && optionEdit) { foreach (var rendOption in item.rendOptions) { RendererOptionDisplay(item, rendOption); } GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); } } else { if (item.extendOption && optionEdit) { foreach (var rendOption in item.rendOptions) { RendererOptionDisplay(item, rendOption); } GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); } } } else { if (item.type == FeedType.Shader) { ShaderOptionDisplay(item); } if (item.extendOption && optionEdit) { foreach (var rendOption in item.rendOptions) { RendererOptionDisplay(item, rendOption); } GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); } } } void ShaderOptionDisplay(ItemElement item) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("", GUILayout.Width(100)); item.animationMaterial = (Material) EditorGUILayout.ObjectField("", item.animationMaterial, typeof(Material), false, GUILayout.Width(100)); EditorGUILayout.LabelField("", GUILayout.Width(5)); item.animationParam = EditorGUILayout.TextField( item.animationParam, GUILayout.Width(100)); EditorGUILayout.LabelField("", GUILayout.Width(5)); item.animationParamOff = EditorGUILayout.FloatField(item.animationParamOff,GUILayout.Width(30)); EditorGUILayout.LabelField("=>", GUILayout.Width(20)); item.animationParamOn = EditorGUILayout.FloatField(item.animationParamOn,GUILayout.Width(30)); } } void RendererOptionDisplay(ItemElement item, RendererOption rendOption) { if(rendOption == null) return; if(rendOption.rend == null) return; using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("", GUILayout.Width(25)); if (item.active) { rendOption.RendEnable = EditorGUILayout.Toggle("", rendOption.RendEnable, GUILayout.Width(30)); } else { using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.Toggle("", false, GUILayout.Width(30)); } } rendOption.ExtendOption = EditorGUILayout.Foldout(rendOption.ExtendOption, rendOption.rend.name); } if (rendOption.ExtendOption) { for (int i = 0; i < rendOption.changeMaterialsOptions.Count; i++) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("",GUILayout.Width(60)); var toggle = EditorGUILayout.Toggle("", rendOption.changeMaterialsOptions[i].change, GUILayout.Width(25)); if (toggle != rendOption.changeMaterialsOptions[i].change) { // 変更があった場合レイヤー内に伝播 if (menuElements[menuReorderableList.index].isToggle) { ToggleMaterialOption(menuElements[menuReorderableList.index], rendOption.rend, i, toggle); } else { ToggleMaterialOption(menuElements[menuReorderableList.index].layer, rendOption.rend, i, toggle); } } EditorGUILayout.LabelField(rendOption.rend.sharedMaterials[i]?.name, GUILayout.Width(95)); if (!rendOption.changeMaterialsOptions[i].change) { EditorGUILayout.LabelField("", GUILayout.Width(75)); } else { if (EditorGUILayout.Toggle("", rendOption.changeMaterialsOptions[i].delay < 0, GUILayout.Width(25))) { if (rendOption.changeMaterialsOptions[i].delay >= 0) { rendOption.changeMaterialsOptions[i].delay = -1f; } } else { if (rendOption.changeMaterialsOptions[i].delay < 0) { rendOption.changeMaterialsOptions[i].delay = 0f; } } using (new EditorGUI.DisabledScope(rendOption.changeMaterialsOptions[i].delay < 0)) { rendOption.changeMaterialsOptions[i].delay = EditorGUILayout.FloatField("", rendOption.changeMaterialsOptions[i].delay, GUILayout.Width(50)); } } if (toggle) { rendOption.changeMaterialsOptions[i].material = (Material) EditorGUILayout.ObjectField("", rendOption.changeMaterialsOptions[i].material, typeof(Material), false,GUILayout.Width(150)); } else { rendOption.changeMaterialsOptions[i].material = rendOption.rend.sharedMaterials[i]; using (new EditorGUI.DisabledScope(true)) { /*EditorGUILayout.ObjectField("", new Material(Shader.Find("Unlit/Color")){name = "No Change"}, typeof(Object), false,GUILayout.Width(150));*/ EditorGUILayout.LabelField("NoChange",GUILayout.Width(150)); } } } } for (int i = 0; i < rendOption.changeBlendShapeOptions.Count; i++) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("",GUILayout.Width(60)); var toggle = EditorGUILayout.Toggle("", rendOption.changeBlendShapeOptions[i].change, GUILayout.Width(25)); if (toggle != rendOption.changeBlendShapeOptions[i].change) { // 変更があった場合レイヤー内に伝播 if (menuElements[menuReorderableList.index].isToggle) { ToggleBlendshapeOption(menuElements[menuReorderableList.index], rendOption.rend as SkinnedMeshRenderer, i, toggle); } else { ToggleBlendshapeOption(menuElements[menuReorderableList.index].layer, rendOption.rend as SkinnedMeshRenderer, i, toggle); } } rendOption.changeBlendShapeOptions[i].change = toggle; EditorGUILayout.LabelField(rendOption.rend.GetMesh().GetBlendShapeName(i), GUILayout.Width(125)); if (!rendOption.changeBlendShapeOptions[i].change) { EditorGUILayout.LabelField("", GUILayout.Width(95)); } else { if (EditorGUILayout.Toggle("", rendOption.changeBlendShapeOptions[i].delay < 0, GUILayout.Width(25))) { if (rendOption.changeBlendShapeOptions[i].delay >= 0) { rendOption.changeBlendShapeOptions[i].delay = -1f; } } else { if (rendOption.changeBlendShapeOptions[i].delay < 0) { rendOption.changeBlendShapeOptions[i].delay = 0f; } } using (new EditorGUI.DisabledScope(rendOption.changeBlendShapeOptions[i].delay<0)) { rendOption.changeBlendShapeOptions[i].delay = EditorGUILayout.FloatField("", rendOption.changeBlendShapeOptions[i].delay, GUILayout.Width(50)); rendOption.changeBlendShapeOptions[i].duration = EditorGUILayout.FloatField("", rendOption.changeBlendShapeOptions[i].duration, GUILayout.Width(50)); } } if (toggle) { rendOption.changeBlendShapeOptions[i].weight = GUILayout.HorizontalSlider(rendOption.changeBlendShapeOptions[i].weight, 0f, 100f,GUILayout.Width(40)); rendOption.changeBlendShapeOptions[i].weight = EditorGUILayout.FloatField(rendOption.changeBlendShapeOptions[i].weight,GUILayout.Width(30)); } else { rendOption.changeBlendShapeOptions[i].weight = GetDefaultBlendshape(rendOption.rend as SkinnedMeshRenderer, i); using (new EditorGUI.DisabledScope(true)) { var noChange = GUILayout.HorizontalSlider (-1f, 0f, 100f,GUILayout.Width(40)); EditorGUILayout.LabelField("NoChange",GUILayout.Width(30)); } } } } } } void SaveAnim(string path) { path = FileUtil.GetProjectRelativePath(path); string fileName = System.IO.Path.GetFileNameWithoutExtension(path); string fileDir = System.IO.Path.GetDirectoryName (path); for (int i = 0; i < menuElements.Count; i++) { var menuElement = menuElements[i]; var activateAnim = new AnimationClipCreator(menuElement.name+"_Activate",avatar.gameObject); var inactivateAnim = new AnimationClipCreator(menuElement.name+"_Inactivate",avatar.gameObject); foreach (var item in menuElement.SafeActiveItems()) { if (item.active) { SaveElementActive(item,activateAnim); } else { SaveElementInactive(item,activateAnim); } } foreach (var item in menuElement.SafeInactiveItems()) { if (item.active) { SaveElementActive(item,inactivateAnim); } else { SaveElementInactive(item,inactivateAnim); } } activateAnim.CreateAsset(Path.Combine(fileDir,fileName+"_Activate.anim")); inactivateAnim.CreateAsset(Path.Combine(fileDir,fileName+"_InactivateAnim.anim")); } SaveMaterials(fileDir,false); } void Setup(string path) { string fileName = Path.GetFileNameWithoutExtension(path); string fileDir = Path.GetDirectoryName (path); #if VRC_SDK_VRCSDK3 var p = new ParametersCreater(fileName); var c = new AnimatorControllerCreator(fileName,false); // var m = new MenuCreater(fileName); var idleAnim = new AnimationClipCreator("Idle", avatar.gameObject).CreateAsset(path, true); var toggleMenuElements = menuElements.Where(e => e.isToggle).ToList(); for(int i = 0; i <toggleMenuElements.Count ; i++) { var menuElement = toggleMenuElements[i]; if (menuElement.isToggle) { var param = data.saveName + "_Toggle" + i.ToString(); p.AddParam(param,menuElement.isDefault,menuElement.isSaved); c.CreateLayer(param); c.AddParameter(param,menuElement.isDefault); if (menuElement.isRandom) { c.AddDefaultState("Initialize",null); c.AddState("Default",null); c.AddTransition("Initialize","Default"); c.ParameterDriver("Initialize",param,0,1,0.5f); } else { c.AddDefaultState("Default",null); } var activeAnim = new AnimationClipCreator(menuElement.name+"_Active",avatar.gameObject); var activateAnim = new AnimationClipCreator(menuElement.name+"_Activate",avatar.gameObject); var inactiveAnim = new AnimationClipCreator(menuElement.name+"_Inactive",avatar.gameObject); var inactivateAnim = new AnimationClipCreator(menuElement.name+"_Inactivate",avatar.gameObject); var activeItems = menuElement.SafeActiveItems(); activeItems.AddRange(ComputeLayerAnotherItems(menuElement)); var inactiveItems = menuElement.SafeInactiveItems(); inactiveItems.AddRange(ComputeLayerInactiveItems(menuElement)); // rend option (material,blend shapeの変更適応) foreach (var activeItem in activeItems) { var inactiveItem = inactiveItems.FirstOrDefault(e => activeItem.obj == e.obj); if (inactiveItem != null) { RendererOptionTransition(inactiveItem,activeItem,activateAnim); RendererOptionTransition(activeItem,inactiveItem,inactivateAnim); } } // On時のTransitionとIdle foreach (var item in activeItems) { if (item.active) { SaveElementActive(item,activateAnim,activeAnim, menuElement); } else { SaveElementInactive(item,activateAnim,activeAnim, menuElement); } } // Off時のTransitionとIdle foreach (var item in inactiveItems) { if (item.active) { SaveElementActive(item,inactivateAnim,inactiveAnim, menuElement); } else { SaveElementInactive(item,inactivateAnim,inactiveAnim, menuElement); } } c.AddState("Active", activeAnim.CreateAsset(path,true)); c.AddState("Activate", activateAnim.CreateAsset(path,true)); c.AddState("Inactive", inactiveAnim.CreateAsset(path,true)); c.AddState("Inactivate", inactivateAnim.CreateAsset(path,true)); c.AddState("ActiveIdle", data.idleOverride ? activeAnim.Create() : idleAnim); c.AddState("InactiveIdle", data.idleOverride ? inactiveAnim.Create() : idleAnim); c.AddTransition("Default","Active",param,true); c.AddTransition("Default","Inactive",param,false); c.AddTransition("Activate","Active"); c.AddTransition("Active","ActiveIdle"); c.AddTransition("ActiveIdle","Inactivate",param,false); c.AddTransition("Inactivate","Inactive"); c.AddTransition("Inactive","InactiveIdle"); c.AddTransition("InactiveIdle","Activate",param,true); //m.AddToggle(menuElement.name,menuElement.icon,param); menuElement.param = param; menuElement.value = 1; } } foreach (LayerGroup layer in Enum.GetValues(typeof(LayerGroup))) { var layerMenuElements = menuElements.Where(e => !e.isToggle && e.layer == layer).ToList(); if (layerMenuElements.Count == 0) continue; var param = data.saveName + "_" + layer.ToString(); p.AddParam(param,0,data.layerSettingses[(int) layer].isSaved); c.CreateLayer(param); layerMenuElements = layerMenuElements.OrderBy(e => e.isTaboo ? 100 : 0).ToList(); var d = data.layerSettingses[(int) layer].GetDefaultElement(data.menuElements); if (d==null) { var menu = new MenuElement() { name = "Default", activeItems = ComputeDefaultItems(layer), isToggle = false, isTaboo = true, layer = layer, }; layerMenuElements.Insert(0,menu); } else { layerMenuElements.Remove(d); layerMenuElements.Insert(0,d); } if (data.layerSettingses[(int) layer].isRandom) { // ランダム設定の反映 c.AddDefaultState("Initialize",null); c.AddState("Default",null); c.AddTransition("Initialize","Default"); c.ParameterDriver("Initialize",param, layerMenuElements[0].isTaboo ? 1 : 0, layerMenuElements.Count(e=>!e.isTaboo) - 1 + (layerMenuElements[0].isTaboo ? 1 : 0) ); } else { c.AddDefaultState("Default",null); } for (int i = 0; i < layerMenuElements.Count; i++) { var menuElement = layerMenuElements[i]; var itemElements = menuElement.SafeActiveItems(); itemElements.AddRange(ComputeLayerAnotherItems(menuElement)); var activeAnim = new AnimationClipCreator(layer.ToString() + i.ToString() + "_Active", avatar.gameObject); foreach (var item in itemElements) { activeAnim.AddKeyframe_Gameobject(item.obj,0f,item.active); activeAnim.AddKeyframe_Gameobject(item.obj,1f/60f,item.active); // option処理 foreach (var rendOption in item.rendOptions) { if (rendOption.rend == null) continue; if (rendOption.rend is SkinnedMeshRenderer) { activeAnim.AddKeyframe(0f, rendOption.rend as SkinnedMeshRenderer, "m_Enabled", rendOption.RendEnable ? 1 : 0); activeAnim.AddKeyframe(1f/60f, rendOption.rend as SkinnedMeshRenderer, "m_Enabled", rendOption.RendEnable ? 1 : 0); } else if(rendOption.rend is MeshRenderer) { activeAnim.AddKeyframe(0f, rendOption.rend as MeshRenderer, "m_Enabled", rendOption.RendEnable ? 1 : 0); activeAnim.AddKeyframe(1f/60f, rendOption.rend as MeshRenderer, "m_Enabled", rendOption.RendEnable ? 1 : 0); } for (int j = 0; j < rendOption.changeMaterialsOptions.Count; j++) { if (rendOption.changeMaterialsOptions[j].change) { activeAnim.AddKeyframe_Material(rendOption.rend,rendOption.changeMaterialsOptions[j].material,0f,j); activeAnim.AddKeyframe_Material(rendOption.rend,rendOption.changeMaterialsOptions[j].material,1f/60f,j); } else if(data.materialOverride) { // デフォルトのマテリアルで上書き(同期エラー対策) activeAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[j],0f,j); activeAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[j],1f/60f,j); } /*activeAnim.AddKeyframe_MaterialParam(0f, rendOption.rend, "_AnimationTime", 1f); activeAnim.AddKeyframe_MaterialParam(1f/60f, rendOption.rend, "_AnimationTime", 1f);*/ } for (int j = 0; j < rendOption.changeBlendShapeOptions.Count; j++) { if (rendOption.changeBlendShapeOptions[j].change) { var rs = rendOption.rend as SkinnedMeshRenderer; activeAnim.AddKeyframe(0f, rs, "blendShape."+rs.GetMesh().GetBlendShapeName(j) , rendOption.changeBlendShapeOptions[j].weight); activeAnim.AddKeyframe(1f/60f, rs, "blendShape."+rs.GetMesh().GetBlendShapeName(j) , rendOption.changeBlendShapeOptions[j].weight); } } } } c.AddState(i.ToString() + "_Active", activeAnim.CreateAsset(path,true)); c.AddState(i.ToString() + "_Idle", data.idleOverride ? activeAnim.Create() : idleAnim); if (menuElement.isTaboo || (data.layerSettingses[(int) layer].isRandom && menuElement.activeSyncElements.Count != 0)) { c.AddState(i.ToString() + "_Initialize", activeAnim.Create()); c.AddTransition("Default",i.ToString() + "_Initialize",param,i); if (menuElement.isTaboo) { // タブー設定に当たったらデフォルトに送る c.ParameterDriver(i.ToString() + "_Initialize",param,0); c.AddTransition(i.ToString() + "_Initialize",0.ToString() + "_Active"); } else { c.AddTransition(i.ToString() + "_Initialize",i.ToString() + "_Active"); } } else { c.AddTransition("Default",i.ToString() + "_Active",param,i); } c.AddTransition(i.ToString() + "_Active",i.ToString() + "_Idle"); //m.AddToggle(menuElement.name,menuElement.icon,param,i); menuElement.param = param; menuElement.value = i; } for (int i = 0; i < layerMenuElements.Count; i++) { for (int j = 0; j < layerMenuElements.Count; j++) { if(i==j) continue; var transitionAnim = new AnimationClipCreator( layer.ToString() + j.ToString() + "to" + i.ToString() + "_Transition", avatar.gameObject); var fromItems = layerMenuElements[j].SafeActiveItems(); fromItems.AddRange(ComputeLayerAnotherItems(layerMenuElements[j])); var toItems = layerMenuElements[i].SafeActiveItems(); toItems.AddRange(ComputeLayerAnotherItems(layerMenuElements[i])); foreach (var item in ComputeDefaultItems(layer)) { var fromItem = fromItems.FirstOrDefault(e => e.obj == item.obj); var toItem = toItems.FirstOrDefault(e => e.obj == item.obj); // レイヤー内で参照されているアイテムすべてについてとらんじちよん if (fromItem == null && toItem == null) { } else if (fromItem == null) { SaveElementTransition(toItem,transitionAnim, false); } else if (toItem == null) { SaveElementTransition(fromItem,transitionAnim,true); } else { // rend option (material,blend shapeの変更適応) RendererOptionTransition(fromItem,toItem,transitionAnim); // 次のステートでも表示状態の変更がなければ状態変更のアニメをつけない処理 if (data.createAnimWhenNotChangedActive || fromItem.active != toItem.active) { // transition animation SaveElementTransition(toItem,transitionAnim, false); } } } c.AddState(j.ToString() + "to" + i.ToString() + "_Transition", transitionAnim.CreateAsset(path,true)); c.AddTransition(j.ToString() + "_Idle",j.ToString() + "to" + i.ToString() + "_Transition",param,i); c.AddTransition(j.ToString() + "to" + i.ToString() + "_Transition",i.ToString() + "_Active"); } } } // パラメーターシンク foreach (var menuElement in menuElements) { foreach (var syncElement in menuElement.activeSyncElements) { if (!syncElement.syncOn && !syncElement.syncOff) continue; var syncParam = menuElements.FirstOrDefault(e => e.guid == syncElement.guid); if (syncParam == null) continue; c.SetEditLayer(c.GetEditLayer(menuElement.param)); if (syncElement.delay < 0) { if (menuElement.isToggle) { c.ParameterDriver( "Active" , syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } else { c.ParameterDriver( menuElement.value.ToString() + "_Active", syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } } else { if (menuElement.isToggle) { c.ParameterDriver( "Activate" , syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } else { var states = c.GetStates(".*" + "to" + menuElement.value.ToString() + "_Transition").Distinct().ToArray(); foreach (var state in states) { c.ParameterDriver( state, syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } } } // ランダムで代入時も同様に処理 if (data.layerSettingses[(int) menuElement.layer].isRandom) { if (menuElement.isToggle) { c.ParameterDriver( menuElement.value.ToString() + "_Initialize", syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } else { c.ParameterDriver( menuElement.value.ToString() + "_Initialize", syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } } } if (menuElement.isToggle) { foreach (var syncElement in menuElement.inactiveSyncElements) { if (!syncElement.syncOn && !syncElement.syncOff) continue; var syncParam = menuElements.FirstOrDefault(e => e.guid == syncElement.guid); if (syncParam == null) continue; if (syncElement.delay < 0) { c.SetEditLayer(c.GetEditLayer(menuElement.param)); c.ParameterDriver( "Inactive" , syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } else { c.SetEditLayer(c.GetEditLayer(menuElement.param)); c.ParameterDriver( "Inactivate" , syncParam.param, syncElement.syncOn ? syncParam.value : 0f); } } } } MenuCreater pm = new MenuCreater("ParentMenu"); MenuCreater m = new MenuCreater(fileName); if (data.useMenuTemplate) { // テンプレートの整合性チェック data.ReloadTemplates(); foreach (var menu in data.menuTemplate) { if (String.IsNullOrWhiteSpace(menu.menuGUID)) { var a = CreateTemplateMenu(menu, path); m.AddSubMenu(a.CreateAsset(path, true),menu.name,menu.icon); } else { var a = data.menuElements.FirstOrDefault(e => e.guid == menu.menuGUID); if (a != null) { if (a.isToggle) { m.AddToggle(menu.name,menu.icon,a.param); } else { m.AddToggle(menu.name,menu.icon,a.param,a.value); } } } } } else { foreach (var menuElement in menuElements) { if (menuElement.isToggle) { m.AddToggle(menuElement.name,menuElement.icon,menuElement.param); } else { m.AddToggle(menuElement.name,menuElement.icon,menuElement.param,menuElement.value); } } } pm.AddSubMenu(m.CreateAsset(path, true),data.saveName,data.icon); //p.LoadParams(c,true); var mod = new AvatarModifyTool(avatar,fileDir); var assets = CreateInstance<AvatarModifyData>(); { assets.fx_controller = c.CreateAsset(path, true); assets.parameter = p.CreateAsset(path, true); assets.menu = pm.CreateAsset(path,true); } AssetDatabase.AddObjectToAsset(assets,path); data.assets = assets; ApplySettings(mod).ModifyAvatar(assets,EnvironmentGUIDs.prefix); #endif SaveMaterials(path,true); } #if VRC_SDK_VRCSDK3 MenuCreater CreateTemplateMenu(MenuTemplate menu,string path) { var m = new MenuCreater(menu.name); foreach (var element in menu.childs) { if (String.IsNullOrWhiteSpace(element.menuGUID)) { var a = CreateTemplateMenu(element, path); m.AddSubMenu(a.CreateAsset(path, true),element.name,element.icon); } else { var a = data.menuElements.FirstOrDefault(e => e.guid == element.menuGUID); if (a != null) { if (a.isToggle) { m.AddToggle(element.name,element.icon,a.param); } else { m.AddToggle(element.name,element.icon,a.param,a.value); } } } } return m; } #endif void SaveElementTransition(ItemElement element, AnimationClipCreator transitionAnim, bool invert = false, MenuElement parentmenu = null) { if (invert) { if (element.active) { SaveElementInactive(element,transitionAnim,null,parentmenu); } else { SaveElementActive(element,transitionAnim,null,parentmenu); } } else { if (element.active) { SaveElementActive(element,transitionAnim,null,parentmenu); } else { SaveElementInactive(element,transitionAnim,null,parentmenu); } } } void SaveElementActive(ItemElement element, AnimationClipCreator transitionAnim = null, AnimationClipCreator setAnim = null, MenuElement parentmenu = null) { if (setAnim != null) { ActiveAnimation(setAnim,element.obj,true); // option処理 foreach (var rendOption in element.rendOptions) { if(rendOption.rend == null) continue; setAnim.AddKeyframe(0f, rendOption.rend, "m_Enabled", rendOption.RendEnable ? 1 : 0); setAnim.AddKeyframe(1f/60f, rendOption.rend, "m_Enabled", rendOption.RendEnable ? 1 : 0); for (int i = 0; i < rendOption.changeMaterialsOptions.Count; i++) { if (rendOption.changeMaterialsOptions[i].change) { setAnim.AddKeyframe_Material(rendOption.rend,rendOption.changeMaterialsOptions[i].material,0f,i); setAnim.AddKeyframe_Material(rendOption.rend,rendOption.changeMaterialsOptions[i].material,1f/60f,i); } else if(data.materialOverride) { // デフォルトのマテリアルで上書き(同期エラー対策) setAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[i],0f,i); setAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[i],1f/60f,i); } /*setAnim.AddKeyframe_MaterialParam(0f, rendOption.rend, "_AnimationTime", 1f); setAnim.AddKeyframe_MaterialParam(1f/60f, rendOption.rend, "_AnimationTime", 1f);*/ } for (int i = 0; i < rendOption.changeBlendShapeOptions.Count; i++) { if (rendOption.changeBlendShapeOptions[i].change) { var rs = rendOption.rend as SkinnedMeshRenderer; setAnim.AddKeyframe(0f, rs, "blendShape."+rs.GetMesh().GetBlendShapeName(i) , rendOption.changeBlendShapeOptions[i].weight); setAnim.AddKeyframe(1f/60f, rs, "blendShape."+rs.GetMesh().GetBlendShapeName(i) , rendOption.changeBlendShapeOptions[i].weight); } } } if (data.materialOverride) { setAnim.AddKeyframe_Scale(0f,element.obj.transform,element.obj.transform.localScale); setAnim.AddKeyframe_Scale(1f/60f,element.obj.transform,element.obj.transform.localScale); } } if (transitionAnim != null) { // 上書き設定 if (parentmenu != null) { if (parentmenu.isOverrideActivateTransition) { if (parentmenu.overrideActivateTransition.type == FeedType.None) { ActiveAnimation(transitionAnim,element.obj,true,parentmenu.overrideActivateTransition.delay); } else if(parentmenu.overrideActivateTransition.type == FeedType.Scale) { ScaleAnimation(transitionAnim, element.obj, parentmenu.overrideActivateTransition.delay, parentmenu.overrideActivateTransition.duration, true); } else if(parentmenu.overrideActivateTransition.type == FeedType.Shader) { ShaderAnimation(transitionAnim, element.obj, parentmenu.overrideActivateTransition.delay, parentmenu.overrideActivateTransition.duration, parentmenu.overrideActivateTransition.animationMaterial, parentmenu.overrideActivateTransition.animationParam, parentmenu.overrideActivateTransition.animationParamOff, parentmenu.overrideActivateTransition.animationParamOn); } else { ShaderAnimation(transitionAnim, element.obj, parentmenu.overrideActivateTransition.delay, parentmenu.overrideActivateTransition.duration, parentmenu.overrideActivateTransition.type.GetMaterialByType(), "_AnimationTime", 0f,1f); ChangeMaterialDefault(transitionAnim,element.obj,parentmenu.overrideActivateTransition.delay+parentmenu.overrideActivateTransition.duration+1f/60f); } return; } } if (element.type == FeedType.None) { ActiveAnimation(transitionAnim,element.obj,true,element.delay); } else if(element.type == FeedType.Scale) { ScaleAnimation(transitionAnim, element.obj, element.delay, element.duration, true); } else if(element.type == FeedType.Shader) { ShaderAnimation(transitionAnim, element.obj, element.delay, element.duration, element.animationMaterial, element.animationParam,element.animationParamOff,element.animationParamOn); } else { ShaderAnimation(transitionAnim, element.obj, element.delay, element.duration, element.type.GetMaterialByType(), "_AnimationTime", 0f,1f); ChangeMaterialDefault(transitionAnim,element.obj,element.delay+element.duration+1f/60f); } } } void SaveElementInactive(ItemElement element, AnimationClipCreator transitionAnim = null, AnimationClipCreator setAnim = null, MenuElement parentmenu = null) { if (setAnim != null) { ActiveAnimation(setAnim,element.obj,false); // option処理 foreach (var rendOption in element.rendOptions) { if(rendOption.rend == null) continue; for (int i = 0; i < rendOption.changeMaterialsOptions.Count; i++) { if (rendOption.changeMaterialsOptions[i].change) { setAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[i],0f,i); setAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[i],1f/60f,i); } if(data.materialOverride) { // デフォルトのマテリアルで上書き(同期エラー対策) /*setAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[i],0f,i); setAnim.AddKeyframe_Material(rendOption.rend,rendOption.rend.sharedMaterials[i],1f/60f,i);*/ } /*setAnim.AddKeyframe_MaterialParam(0f, rendOption.rend, "_AnimationTime", 0f); setAnim.AddKeyframe_MaterialParam(1f/60f, rendOption.rend, "_AnimationTime", 0f);*/ } for (int i = 0; i < rendOption.changeBlendShapeOptions.Count; i++) { if (rendOption.changeBlendShapeOptions[i].change) { var rs = rendOption.rend as SkinnedMeshRenderer; setAnim.AddKeyframe(0f, rs, "blendShape."+rendOption.rend.GetMesh().GetBlendShapeName(i) , rs.GetBlendShapeWeight(i)); setAnim.AddKeyframe(1f/60f, rs, "blendShape."+rendOption.rend.GetMesh().GetBlendShapeName(i) , rs.GetBlendShapeWeight(i)); } } } } if(transitionAnim != null) { // 上書き設定 if (parentmenu != null) { if (parentmenu.isOverrideInactivateTransition) { if (parentmenu.overrideInactivateTransition.type == FeedType.None) { ActiveAnimation(transitionAnim, element.obj,false, parentmenu.overrideInactivateTransition.delay); } else if(parentmenu.overrideInactivateTransition.type == FeedType.Scale) { ScaleAnimation(transitionAnim, element.obj, parentmenu.overrideInactivateTransition.delay, parentmenu.overrideInactivateTransition.duration, false); } else if(parentmenu.overrideInactivateTransition.type == FeedType.Shader) { ShaderAnimation(transitionAnim, element.obj, parentmenu.overrideInactivateTransition.delay, parentmenu.overrideInactivateTransition.duration, parentmenu.overrideInactivateTransition.animationMaterial, parentmenu.overrideInactivateTransition.animationParam, parentmenu.overrideInactivateTransition.animationParamOn, parentmenu.overrideInactivateTransition.animationParamOff); } else { ShaderAnimation(transitionAnim, element.obj, parentmenu.overrideInactivateTransition.delay, parentmenu.overrideInactivateTransition.duration, parentmenu.overrideInactivateTransition.type.GetMaterialByType(), "_AnimationTime", 1f,0f); ChangeMaterialDefault(transitionAnim,element.obj,parentmenu.overrideInactivateTransition.delay+parentmenu.overrideInactivateTransition.duration+1f/60f); } return; } } if (element.type == FeedType.None) { ActiveAnimation(transitionAnim, element.obj,false, element.delay); } else if(element.type == FeedType.Scale) { ScaleAnimation(transitionAnim, element.obj, element.delay, element.duration, false); } else if(element.type == FeedType.Shader) { ShaderAnimation(transitionAnim, element.obj,element.delay,element.duration, element.animationMaterial, element.animationParam,element.animationParamOn, element.animationParamOff); } else { ShaderAnimation(transitionAnim, element.obj, element.delay, element.duration, element.type.GetMaterialByType(), "_AnimationTime", 1f,0f); ActiveAnimation(transitionAnim,element.obj,false,element.delay+element.duration+1f/60f); ChangeMaterialDefault(transitionAnim,element.obj,element.delay+element.duration+2f/60f); } } } void RendererOptionTransition(ItemElement fromElement,ItemElement toElement, AnimationClipCreator transitionAnim) { foreach (var rendOpt in toElement.rendOptions) { if(rendOpt.rend == null) continue; var rend = rendOpt.rend; var to = toElement.rendOptions.FirstOrDefault(r => r.rend == rend); if(to==null) continue; var from = fromElement.rendOptions.FirstOrDefault(r => r.rend == rend); if(from==null) continue; if (from.changeMaterialsOptions.Count == to.changeMaterialsOptions.Count) { for (int i = 0; i < to.changeMaterialsOptions.Count; i++) { if (to.changeMaterialsOptions[i].change) { if(to.changeMaterialsOptions[i].material == null) continue; if(from.changeMaterialsOptions[i].material == to.changeMaterialsOptions[i].material) continue; if (to.changeMaterialsOptions[i].delay < 0) { } else { if(to.changeMaterialsOptions[i].delay < 1f/60f)transitionAnim.AddKeyframe_Material(rend,GetDefaultMaterial(rend,i),0f,i); transitionAnim.AddKeyframe_Material(rend,to.changeMaterialsOptions[i].material,to.changeMaterialsOptions[i].delay,i); } } } } if (from.changeBlendShapeOptions.Count == to.changeBlendShapeOptions.Count) { for (int i = 0; i < from.changeBlendShapeOptions.Count; i++) { if (to.changeBlendShapeOptions[i].change) { if (0f > to.changeBlendShapeOptions[i].weight && to.changeBlendShapeOptions[i].weight > 100f) continue; if (Mathf.Abs(from.changeBlendShapeOptions[i].weight - to.changeBlendShapeOptions[i].weight) < 1f) continue; if (to.changeBlendShapeOptions[i].delay < 0) { } else { //transitionAnim.AddKeyframe_Material(rend.rend,rend.changeBlendShapeOptions[i].weight); transitionAnim.AddKeyframe(to.changeBlendShapeOptions[i].delay, rend as SkinnedMeshRenderer, "blendShape." + rend.GetMesh().GetBlendShapeName(i), from.changeBlendShapeOptions[i].change ? from.changeBlendShapeOptions[i].weight : (rend as SkinnedMeshRenderer).GetBlendShapeWeight(i)); transitionAnim.AddKeyframe( to.changeBlendShapeOptions[i].delay + to.changeBlendShapeOptions[i].duration, rend as SkinnedMeshRenderer, "blendShape." + rend.GetMesh().GetBlendShapeName(i), to.changeBlendShapeOptions[i].weight); } } } } } } AnimationClipCreator ScaleAnimation(AnimationClipCreator anim,GameObject obj, float delay = 0f, float duration = 1f, bool activate = true,bool bounce = false) { anim.AddKeyframe_Gameobject(obj,0f,true); var defaultScale = obj.transform.localScale; if (activate) { anim.AddKeyframe_Scale( 0f,obj.transform,Vector3.zero); anim.AddKeyframe_Scale( delay,obj.transform,Vector3.zero); if (bounce) { anim.AddKeyframe_Scale(delay+duration*0.6f,obj.transform, defaultScale*1.2f); anim.AddKeyframe_Scale(delay+duration*0.8f,obj.transform, defaultScale*0.9f); } anim.AddKeyframe_Scale(delay+duration,obj.transform,defaultScale); } else { anim.AddKeyframe_Scale(delay,obj.transform,defaultScale); if (bounce) { anim.AddKeyframe_Scale(delay+duration*0.2f,obj.transform, defaultScale*1.2f); anim.AddKeyframe_Scale(delay+duration*0.4f,obj.transform, defaultScale*0.9f); } anim.AddKeyframe_Scale( delay+duration,obj.transform,Vector3.zero); anim.AddKeyframe_Gameobject(obj,delay+duration,false); anim.AddKeyframe_Scale(delay+duration+1f/60f,obj.transform,defaultScale); } return anim; } AnimationClipCreator ShaderAnimation(AnimationClipCreator anim,GameObject obj,float delay = 0f , float duration = 1f, Material mat = null,string param = "",float from = 0f, float to = 1f) { anim.AddKeyframe_Gameobject(obj,delay,true); ChangeMaterialShader(anim,obj,mat,delay); foreach (Renderer rend in obj.GetComponentsInChildren<Renderer>()) { anim.AddKeyframe_MaterialParam(delay, rend, param, from); anim.AddKeyframe_MaterialParam(delay+duration, rend, param, to); } return anim; } AnimationClipCreator ActiveAnimation(AnimationClipCreator anim, GameObject obj,bool value,float time = 0f) { if (time < 1f / 60f) { anim.AddKeyframe_Gameobject(obj,0f,value); } else { anim.AddKeyframe_Gameobject(obj,0f,!value); } anim.AddKeyframe_Gameobject(obj,time,value); return anim; } void ChangeMaterialDefault(AnimationClipCreator anim,GameObject obj,float time = 0f) { foreach (Renderer rend in obj.GetComponentsInChildren<Renderer>()) { for (int i = 0; i < rend.sharedMaterials.Length; i++) { anim.AddKeyframe_Material(rend,rend.sharedMaterials[i],time,i); } } } void ChangeMaterialShader(AnimationClipCreator anim,GameObject obj, Material shader,float time = 0f) { foreach (Renderer rend in obj.GetComponentsInChildren<Renderer>()) { for (int i = 0; i < rend.sharedMaterials.Length; i++) { anim.AddKeyframe_Material(rend, GetAnimationMaterial(rend.sharedMaterials[i],shader),time,i); } } } // 生成したマテリアルを保存する void SaveMaterials(string path,bool subAsset = false) { foreach (var mats in matlist) { foreach (var mat in mats.Value) { if (subAsset) { AssetDatabase.AddObjectToAsset(mat.Value,path); } else { AssetDatabase.CreateAsset(mat.Value, AssetDatabase.GenerateUniqueAssetPath( Path.Combine(path,mat.Value.name + ".mat"))); } } } matlist = new Dictionary<Material, Dictionary<Material, Material>>(); } // メニューで設定されている状態に,シーンのアクティブ,マテリアル,BlendShapeを反映する void SetObjectActiveForScene(MenuElement menu,bool active = true, bool material = true, bool blendShape = true) { RevertObjectActiveForScene(active,material,blendShape); if (menu == null) return; var activeItems = menu.SafeActiveItems(); activeItems.AddRange(ComputeLayerAnotherItems(menu)); var inactiveItems = menu.SafeInactiveItems(); inactiveItems.AddRange(ComputeLayerInactiveItems(menu)); var items = displayItemMode ? activeItems : inactiveItems; foreach (var item in items) { if (active) { GetDefaultActive(item.obj); item.obj.SetActive(item.active); } foreach (var option in item.rendOptions) { if (option.rend) { GetDefaultRendEnable(option.rend); option.rend.enabled = option.RendEnable; if (material) { for (int i = 0; i < option.changeMaterialsOptions.Count; i++) { GetDefaultMaterial(option.rend, i); if (option.changeMaterialsOptions[i].change) { var mats = option.rend.sharedMaterials.ToArray(); mats[i] = option.changeMaterialsOptions[i].material; option.rend.sharedMaterials = mats.ToArray(); } } } if (blendShape) { for (int i = 0; i < option.changeBlendShapeOptions.Count; i++) { GetDefaultBlendshape(option.rend as SkinnedMeshRenderer, i); if (option.changeBlendShapeOptions[i].change) { (option.rend as SkinnedMeshRenderer)?.SetBlendShapeWeight(i,option.changeBlendShapeOptions[i].weight); } } } } } } } // シーンのアクティブ,マテリアル,BlendShapeをリセットする void RevertObjectActiveForScene(bool active = true, bool material = true, bool blendShape = true) { if (active) { foreach (var oa in defaultActive) { oa.Key.SetActive(oa.Value); } } if (material) { foreach (var dm in defaultMaterials) { dm.Key.sharedMaterials = dm.Value.ToArray(); } } if (blendShape) { foreach (var db in defaultBlendShapes) { db.Key.rend.SetBlendShapeWeight(db.Key.index,db.Value); } } } // デフォルトのアクティブ状態(シーン)を記録&取得する bool GetDefaultActive(GameObject obj) { if (!obj) return false; if (!defaultActive.ContainsKey(obj)) { defaultActive.Add(obj,obj.activeSelf); } return defaultActive[obj]; } // デフォルトのマテリアル状態(シーン)を記録&取得する bool GetDefaultRendEnable(Renderer rend) { if (rend == null) return false; if (!defaultRendEnable.ContainsKey(rend)) { defaultRendEnable.Add(rend,rend.enabled); } return defaultRendEnable[rend]; } // デフォルトのマテリアル状態(シーン)を記録&取得する Material GetDefaultMaterial(Renderer rend, int index) { if (rend == null) return null; if (!defaultMaterials.ContainsKey(rend)) { defaultMaterials.Add(rend,rend.sharedMaterials.ToArray()); } if ( 0 <= index && index < defaultMaterials[rend].Length) { return defaultMaterials[rend][index]; } return null; } // デフォルトのBlendShape状態(シーン)を記録&取得する float GetDefaultBlendshape(SkinnedMeshRenderer rend, int index) { if (rend == null) return -1f; var key = new BlendShapeReference() { rend = rend, index = index, }; if (!defaultBlendShapes.ContainsKey(key)) { defaultBlendShapes.Add(key,rend.GetBlendShapeWeight(index)); } return defaultBlendShapes[key]; } // RendererOptionが編集済みかどうか bool IsModifyRendererOption(ItemElement item) { return item.rendOptions.Any(ro => ro.changeMaterialsOptions.Any(e => e.change) || ro.changeBlendShapeOptions.Any(e => e.change)); } // アイテムのアクティブを2メニュー間で合わせる void SyncItemActive(List<ItemElement> srcs, List<ItemElement> dsts, bool invert = false, bool checkOptions = true) { foreach (var dst in dsts) { var src = srcs.FirstOrDefault(e => e.obj == dst.obj); if (src != null) { if (checkOptions) { if(!RendOptionEqual(src,dst)) continue; // if(IsModifyRendererOption(dst) || IsModifyRendererOption(src)) continue; } dst.active = invert ? !src.active : src.active; } } } bool RendOptionEqual(ItemElement srcs, ItemElement dsts) { foreach (var src in srcs.rendOptions) { var dst = dsts.rendOptions.FirstOrDefault(d => d.rend == src.rend); if (src != null && dst != null) { for (int i = 0; i < src.changeMaterialsOptions.Count && i < dst.changeMaterialsOptions.Count; i++) { if (src.changeMaterialsOptions[i].change && dst.changeMaterialsOptions[i].change) { if (src.changeMaterialsOptions[i].material != dst.changeMaterialsOptions[i].material) { return false; } } } for (int i = 0; i < src.changeBlendShapeOptions.Count && i < dst.changeBlendShapeOptions.Count; i++) { if (src.changeBlendShapeOptions[i].change && dst.changeBlendShapeOptions[i].change) { if (Mathf.Abs(src.changeBlendShapeOptions[i].weight - dst.changeBlendShapeOptions[i].weight)<1f) { return false; } } } } } return true; } List<ItemElement> ComputeLayerInactiveItems(MenuElement menu) { var activeItems = menu.SafeActiveItems(); if (!menu.isToggle) { activeItems.AddRange(ComputeLayerAnotherItems(menu)); } return activeItems.Where(e=>menu.SafeInactiveItems().All(f=>f.obj!=e.obj)).Select(e=>e.Clone(true)).ToList(); } // レイヤー内の未設定アイテムを走査し返す List<ItemElement> ComputeLayerAnotherItems(MenuElement menu) { if (!menu.isToggle) { var items = GetActiveItems(menu.layer). Where(e => menu.SafeActiveItems().All(f => f.obj != e.obj)). Select(e => e.Clone(true)).ToList(); if (IsMenuElementDefault(menu)) { // デフォルトエレメントならアクティブをシーンの状態に合わせる foreach (var item in items) { item.active = GetDefaultActive(item.obj); foreach (var rendOption in item.rendOptions) { if(rendOption.rend == null) continue; rendOption.rend.enabled = GetDefaultRendEnable(rendOption.rend); foreach (var another in items.SelectMany(e=>e.rendOptions)) { if (rendOption.rend == another.rend) { // Material設定の上書き for (int i = 0; i < rendOption.changeMaterialsOptions.Count; i++) { if (rendOption.changeMaterialsOptions[i] != null) break; if (another.changeMaterialsOptions[i] != null) { rendOption.changeMaterialsOptions[i] = new MaterialOption(rendOption.rend.sharedMaterials[i]) { change = true }; } } // BlendShapel設定の上書き for (int i = 0; i < rendOption.changeBlendShapeOptions.Count; i++) { if (rendOption.changeBlendShapeOptions[i].change) break; if (another.changeBlendShapeOptions[i].change) { rendOption.changeBlendShapeOptions[i] = new BlendShapeOption((rendOption.rend as SkinnedMeshRenderer)?.GetBlendShapeWeight(i) ?? 0f) { change = true }; } } } } } } } var inactiveItems = GetInactiveItems(menu.layer); foreach (var item in items) { var inactiveItem = inactiveItems.FirstOrDefault(e => e.obj == item.obj && e.active == item.active); if (inactiveItem != null) { item.delay = inactiveItem.delay; item.duration = inactiveItem.duration; item.type = inactiveItem.type; item.animationMaterial = inactiveItem.animationMaterial; item.animationParam = inactiveItem.path; } } return items; } return new List<ItemElement>(); } // そのメニューがデフォルト値か返す bool IsMenuElementDefault(MenuElement menu) { if (menu.isToggle) { return menu.isDefault; } else { return data.layerSettingses[(int) menu.layer].GetDefaultElement(menuElements) == menu; } } // レイヤーのデフォルトステートがない場合,シーン状態をデフォルトステートとして記録する List<ItemElement> ComputeDefaultItems(LayerGroup layer) { var items = GetActiveItems(layer); foreach (var item in items) { item.active = item.obj.gameObject.activeSelf; } return items; } // レイヤー内の全メニューを走査し,未設定のActiveアイテムを集める List<ItemElement> GetActiveItems(LayerGroup layer) { var items = new List<ItemElement>(); foreach (var menuElement in menuElements) { if (!menuElement.isToggle && menuElement.layer == layer) { foreach (var item in menuElement.SafeActiveItems()) { items.Add(item.Clone()); } } } return DistinctList(items); } // レイヤー内の全メニューを走査し,未設定のInactiveアイテムを集める List<ItemElement> GetInactiveItems(LayerGroup layer) { var items = new List<ItemElement>(); foreach (var menuElement in menuElements) { if (!menuElement.isToggle && menuElement.layer == layer) { foreach (var item in menuElement.SafeInactiveItems()) { items.Add(item.Clone()); } } } return items; } // ItemElementの重複削除 List<ItemElement> DistinctList(List<ItemElement> origin) { var items = new List<ItemElement>(); foreach (var item in origin) { if (items.All(e => e.obj != item.obj)) { items.Add(item); } } return items; } // レイヤー内のRendererOptionの有効無効を同期 void ToggleMaterialOption(LayerGroup layer,Renderer rend,int index,bool val) { foreach (var r in data.menuElements. Where(m=>m.layer == layer). SelectMany(m=>m.SafeActiveItems()). SelectMany(i=>i.rendOptions)) { if (r.rend == rend) { if (!r.changeMaterialsOptions[index].change) { r.changeMaterialsOptions[index].material = rend.sharedMaterials[index]; } r.changeMaterialsOptions[index].change = val; } } } // メニュー内のRendererOptionの有効無効を同期 void ToggleMaterialOption(MenuElement menu,Renderer rend,int index,bool val) { foreach (var ie in menu.SafeActiveItems()) { foreach (var ro in ie.rendOptions) { if (ro.rend == null) continue; if (ro.rend == rend) { if (!ro.changeMaterialsOptions[index].change) { ro.changeMaterialsOptions[index].material = rend.sharedMaterials[index]; } ro.changeMaterialsOptions[index].change = val; } } } foreach (var ie in menu.SafeInactiveItems()) { foreach (var ro in ie.rendOptions) { if (ro.rend == rend) { if (ro.rend == null) continue; if (!ro.changeMaterialsOptions[index].change) { ro.changeMaterialsOptions[index].material = rend.sharedMaterials[index]; } ro.changeMaterialsOptions[index].change = val; } } } } // レイヤー内のRendererOptionの有効無効を同期 void ToggleBlendshapeOption(LayerGroup layer,SkinnedMeshRenderer rend,int index,bool val) { foreach (var r in data.menuElements. Where(m=>m.layer == layer). SelectMany(m=>m.SafeActiveItems()). SelectMany(i=>i.rendOptions)) { if (r.rend == null) continue; if (r.rend == rend) { if (!r.changeBlendShapeOptions[index].change) { r.changeBlendShapeOptions[index] = new BlendShapeOption(GetDefaultBlendshape(rend,index)); } r.changeBlendShapeOptions[index].change = val; } } } // メニュー内のRendererOptionの有効無効を同期 void ToggleBlendshapeOption(MenuElement menu,SkinnedMeshRenderer rend,int index,bool val) { foreach (var ie in menu.SafeActiveItems()) { foreach (var ro in ie.rendOptions) { if (ro.rend == null) continue; if (ro.rend == rend) { if (!ro.changeBlendShapeOptions[index].change) { ro.changeBlendShapeOptions[index] = new BlendShapeOption(GetDefaultBlendshape(rend,index)); } ro.changeBlendShapeOptions[index].change = val; } } } foreach (var ie in menu.SafeInactiveItems()) { foreach (var ro in ie.rendOptions) { if (ro.rend == null) continue; if (ro.rend == rend) { if (!ro.changeBlendShapeOptions[index].change) { ro.changeBlendShapeOptions[index] = new BlendShapeOption(GetDefaultBlendshape(rend,index)); } ro.changeBlendShapeOptions[index].change = val; } } } } void AddMenu() { menuElements.Add(new MenuElement() { name = "Menu" + menuElements.Count, icon = AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.itemIcon) }); } void AddFolder() { data.menuTemplate.Add(new MenuTemplate() { name = "Folder", icon = AssetUtility.LoadAssetAtGuid<Texture2D>(EnvironmentGUIDs.itemboxIcon), autoCreate = false }); } void ResetTemplate() { data.menuTemplate = new List<MenuTemplate>(); } List<string> FindConflict() { #if VRC_SDK_VRCSDK3 AvatarModifyTool mod = new AvatarModifyTool(avatar); ApplySettings(mod); var items = new List<GameObject>(); foreach (var menu in data.menuElements) { foreach (var item in menu.activeItems) { items.Add(item.obj); } } items = items.Distinct().ToList(); var conflictLayers = mod.HasActivateKeyframeLayers(items.ToArray()).Where(l => !l.StartsWith(EnvironmentGUIDs.prefix + mod.GetSafeParam(data.saveName))).Where(l=> !l.StartsWith(EnvironmentGUIDs.prefix + data.saveName)).ToList(); conflictLayers = conflictLayers.Distinct().ToList(); return conflictLayers; #else return new List<string>(); #endif } private void OnDestroy() { RevertObjectActiveForScene(); SaveMaterials("Assets/Export"); } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/DebugTools/PackageExporter.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using HhotateA.AvatarModifyTools.Core; using System; using System.IO; using UnityEditor; using UnityEngine; using Application = UnityEngine.Application; namespace HhotateA.AvatarModifyTools.DebugTools { public class PackageExporter { const string toolsFolder = "Assets/HhotateA"; const string coreToolFolder = "Assets/HhotateA/AvatarModifyTool"; [MenuItem("Window/HhotateA/DebugTools/PackageExporter",false,2)] static void Export() { var path = EditorUtility.SaveFilePanel("Export", "Assets", "_v"+EnvironmentVariable.version,"unitypackage"); if (String.IsNullOrWhiteSpace(path)) return; string dir = Path.GetDirectoryName(path); string version = System.IO.Path.GetFileNameWithoutExtension(path); var fullpackagePath = Path.Combine(dir, "FullPackage" + version + ".unitypackage"); AssetDatabase.ExportPackage(toolsFolder, fullpackagePath,ExportPackageOptions.Recurse); var folders = AssetDatabase.GetSubFolders(toolsFolder); foreach (var folder in folders) { if (folder != coreToolFolder) { var toolName = folder.Replace(toolsFolder, "").Replace("/",""); var exportFolder = Path.Combine(dir, toolName+version); System.IO.Directory.CreateDirectory(exportFolder); File.Copy(fullpackagePath,Path.Combine(exportFolder, "FullPackage" + version + ".unitypackage")); AssetDatabase.ExportPackage(new string[]{coreToolFolder,folder},Path.Combine(exportFolder,toolName+version+".unitypackage"), ExportPackageOptions.Recurse | ExportPackageOptions.Interactive); var readmePath = Application.dataPath.Replace("Assets", Path.Combine(folder,"Readme.md")); Debug.Log(readmePath); if (File.Exists(readmePath)) { File.Copy(readmePath,Path.Combine(exportFolder,"Readme.txt")); } var manualPath = Application.dataPath.Replace("Assets", Path.Combine(folder, "Manual")); if (Directory.Exists(readmePath)) { FolderCopy(manualPath, Path.Combine(exportFolder, "Manual")); } } } } static void FolderCopy(string src, string dst) { DirectoryInfo srcDir = new DirectoryInfo(src); if (srcDir.Exists) { Directory.CreateDirectory(dst); } DirectoryInfo[] folders = srcDir.GetDirectories(); FileInfo[] files = srcDir.GetFiles(); foreach (FileInfo file in files) { if(file.Name.Contains(".meta")) continue; string path = Path.Combine(dst, file.Name); file.CopyTo(path, true); } foreach (DirectoryInfo subfolder in folders) { string path = Path.Combine(dst, subfolder.Name); FolderCopy(subfolder.FullName, path); } } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/TexturePreview.shader<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ Shader "HhotateA/TexturePreview" { Properties { _Overlay ("_Overlay",2D) = "black" {} _OverlayUV ("_OverlayUV",vector) = (0,0,1,1) _OverlayScale ("_OverlayScale",float) = 1 _OverlayRotate ("_OverlayRotate",float) = 0 _MainTex ("_MainTex",2D) = "black" {} _Scale ("_Scale",vector) = (0,0,0,0) } SubShader { Lighting Off Blend One Zero Pass { CGPROGRAM #include "UnityCustomRenderTexture.cginc" #pragma vertex InitCustomRenderTextureVertexShader #pragma fragment frag #pragma target 3.0 sampler2D _Overlay; float4 _Overlay_ST; float4 _OverlayUV; float _OverlayScale, _OverlayRotate; sampler2D _MainTex; float4 _Scale; float4 frag(v2f_customrendertexture IN) : COLOR { uint2 check = IN.localTexcoord.xy*50.0; float4 base = check.x%2==check.y%2 ? float4(0.8,0.8,0.8,1.0) : float4(1,1,1,1); float2 uv = _Scale.xy; uv += (_Scale.zw - _Scale.xy) * IN.localTexcoord.xy; float4 col = tex2D(_MainTex, uv); if(uv.x<0.0 || 1.0<uv.x || uv.y<0.0 || 1.0<uv.y ) col.a = 0.0; /*float2 overlayUV = saturate(TRANSFORM_TEX(IN.localTexcoord.xy, _Overlay)); overlayUV += _OverlayUV.xy; overlayUV -= float2(0.5,0.5); overlayUV = float2( overlayUV.x*cos(_OverlayRotate) - overlayUV.y*sin(_OverlayRotate), overlayUV.x*sin(_OverlayRotate) + overlayUV.y*cos(_OverlayRotate)); overlayUV /= _OverlayScale; overlayUV /= _OverlayUV.zw; overlayUV += float2(0.5,0.5); float4 overlay = tex2D(_Overlay, overlayUV);*/ float4 overlay = tex2D(_Overlay, uv); return lerp(lerp(base,col,col.a),overlay,overlay.a); } ENDCG } } } <|start_filename|>Assets/HhotateA/EmojiParticle/Editor/EmojiParticleSetup.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using HhotateA.AvatarModifyTools.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEditor.Animations; using UnityEngine; using UnityEditor.Callbacks; using UnityEditorInternal; using AnimatorControllerParameterType = UnityEngine.AnimatorControllerParameterType; #if VRC_SDK_VRCSDK3 using VRC.SDK3.Avatars.Components; #endif namespace HhotateA.AvatarModifyTools.EmojiParticle { public class EmojiParticleSetup : WindowBase { [MenuItem("Window/HhotateA/絵文字パーティクルセットアップ(EmojiParticleSetup)",false,102)] public static void ShowWindow() { OpenSavedWindow(); } public static void OpenSavedWindow(EmojiSaveData saveddata = null) { var wnd = GetWindow<EmojiParticleSetup>(); wnd.titleContent = new GUIContent("EmojiParticleSetup"); if (saveddata == null) { saveddata = CreateInstance<EmojiSaveData>(); } // wnd.data = Instantiate(saveddata); wnd.data = saveddata; wnd.LoadReorderableList(); } private Target target; ReorderableList emojiReorderableList; private EmojiSaveData data; Vector2 scroll = Vector2.zero; enum Target { Hip, Head, RightHand, LeftHand } void LoadReorderableList() { emojiReorderableList = new ReorderableList(data.emojis,typeof(IconElement),true,false,true,true) { elementHeight = 60, drawHeaderCallback = (r) => EditorGUI.LabelField(r,"Emojis","絵文字を追加してください"), drawElementCallback = (r, i, a, f) => { r.height -= 4; r.y += 2; var d = data.emojis[i]; var recth = r; var emojiRect = r; emojiRect.width = emojiRect.height + 25; emojiRect.x = r.width - emojiRect.width; recth.height /= 3; recth.width = r.width - emojiRect.width; var rectw = recth; rectw.width -= 50; d.name = EditorGUI.TextField(rectw,"", d.name); rectw.x += rectw.width; rectw.width /= 2; rectw = recth; rectw.y += rectw.height; rectw.width = recth.width / 2; rectw.width /= 6; rectw.x += rectw.width; rectw.width *= 2; EditorGUI.LabelField(rectw,"Count"); rectw.x += rectw.width; rectw.width = rectw.width * 2 / 3; d.count = EditorGUI.IntField(rectw, d.count); rectw.x += rectw.width; rectw.width = recth.width / 2; rectw.width /= 6; rectw.x += rectw.width; rectw.width *= 2; EditorGUI.LabelField(rectw,"Scale"); rectw.x += rectw.width; rectw.width = rectw.width * 2 / 3; d.scale = EditorGUI.FloatField(rectw, d.scale); rectw = recth; rectw.y += 2 * rectw.height; rectw.width = recth.width / 2; rectw.width /= 6; rectw.x += rectw.width; rectw.width *= 2; EditorGUI.LabelField(rectw,"LifeTime"); rectw.x += rectw.width; rectw.width = rectw.width * 2 / 3; d.lifetime = EditorGUI.FloatField(rectw, d.lifetime); rectw.x += rectw.width; rectw.width = recth.width / 2; rectw.width /= 6; rectw.x += rectw.width; rectw.width *= 2; EditorGUI.LabelField(rectw,"Speed"); rectw.x += rectw.width; rectw.width = rectw.width * 2 / 3; d.speed = EditorGUI.FloatField(rectw, d.speed); emojiRect.width = emojiRect.height; d.emoji = (Texture2D) EditorGUI.ObjectField(emojiRect,"",d.emoji,typeof(Texture2D),true); emojiRect.x += emojiRect.width; emojiRect.height /= 3; EditorGUI.LabelField(emojiRect,"Options"); emojiRect.y += emojiRect.height; d.effectPrefab = (GameObject) EditorGUI.ObjectField(emojiRect, d.effectPrefab,typeof(GameObject), false); emojiRect.y += emojiRect.height; d.effectAudio = (AudioClip) EditorGUI.ObjectField(emojiRect, d.effectAudio,typeof(AudioClip), false); d.count = Mathf.Clamp(d.count, 1, 50); if (d.scale <= 0f) d.scale = 0.4f; if (d.lifetime < 1f / 60f) d.lifetime = 2f; }, onRemoveCallback = l => data.emojis.RemoveAt(l.index), onAddCallback = l => data.emojis.Add(new IconElement("",null)) }; } private void OnGUI() { TitleStyle("絵文字パーティクルセットアップ"); DetailStyle("アバターに好きな画像の絵文字を実装する,簡単なセットアップツールです.",EnvironmentGUIDs.readme); #if VRC_SDK_VRCSDK3 EditorGUILayout.Space(); AvatartField(); EditorGUILayout.Space(); EditorGUILayout.Space(); data.saveName = EditorGUILayout.TextField("Save Name",data.saveName); EditorGUILayout.Space(); EditorGUILayout.Space(); target = (Target) EditorGUILayout.EnumPopup("Target", target); EditorGUILayout.Space(); scroll = EditorGUILayout.BeginScrollView(scroll, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.scrollView); emojiReorderableList.DoLayoutList(); EditorGUILayout.EndScrollView(); EditorGUILayout.Space(); if (ShowOptions()) { if (GUILayout.Button("Force Revert")) { var am = new AvatarModifyTool(avatar); am.RevertByKeyword(EnvironmentGUIDs.prefix); OnFinishRevert(); } } EditorGUILayout.Space(); EditorGUILayout.Space(); using (new EditorGUI.DisabledScope(avatar==null)) { if (GUILayout.Button("Setup")) { var asset = AssetUtility.LoadAssetAtGuid<AvatarModifyData>(EnvironmentGUIDs.emojiModifyData); asset = Instantiate(asset); var path = EditorUtility.SaveFilePanel("Save", data.GetAssetDir(), data.GetAssetName(), "emojiparticle.asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } if (String.IsNullOrWhiteSpace(data.saveName)) { string fileName = System.IO.Path.GetFileNameWithoutExtension(path); data.saveName = fileName; } path = FileUtil.GetProjectRelativePath(path); try { data = Instantiate(data); AssetDatabase.CreateAsset(data, path); var modifyAsset = Setup(asset); data.assets = modifyAsset; AssetDatabase.AddObjectToAsset(modifyAsset, path); var mod = new AvatarModifyTool(avatar, AssetDatabase.GetAssetPath(data)); ApplySettings(mod).ModifyAvatar(modifyAsset,EnvironmentGUIDs.prefix); AssetDatabase.SaveAssets(); OnFinishSetup(); DetectAnimatorError(); } catch (Exception e) { OnError(e); throw; } } } EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Save Settings")) { var path = EditorUtility.SaveFilePanel("Save", data.GetAssetDir(), data.GetAssetName(),"emojiparticle.asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } data = Instantiate(data); LoadReorderableList(); AssetDatabase.CreateAsset(data, FileUtil.GetProjectRelativePath(path)); OnSave(); } if (GUILayout.Button("Load Settings")) { var path = EditorUtility.OpenFilePanel("Load", data.GetAssetDir(), "emojiparticle.asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } var d = AssetDatabase.LoadAssetAtPath<EmojiSaveData>(FileUtil.GetProjectRelativePath(path)); if (d == null) { status.Warning("Load Failure"); return; } else { data = d; LoadReorderableList(); } OnLoad(); } } status.Display(); #else VRCErrorLabel(); #endif Signature(); } #if VRC_SDK_VRCSDK3 AvatarModifyData Setup(AvatarModifyData assets) { var settingsPath = AssetDatabase.GetAssetPath(data); string fileDir = Path.GetDirectoryName (settingsPath); string param = data.saveName; foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(settingsPath)) { if (AssetDatabase.IsSubAsset(asset)) { DestroyImmediate(asset, true); } } AssetDatabase.Refresh(); int tilling = 1; while (data.emojis.Count > tilling * tilling) tilling++; // 結合テクスチャの作成 var textures = data.emojis.Select(icon=>icon.ToTexture2D()).ToArray(); var combinatedTexture = TextureCombinater.CombinateSaveTexture(textures,Path.Combine(fileDir,data.saveName+"_tex"+".png"),tilling,4); combinatedTexture.name = data.saveName+"_tex"; // マテリアルの作成 var combinatedMaterial = SaveParticleMaterial(combinatedTexture); combinatedMaterial.name = data.saveName+"_mat"; AssetDatabase.AddObjectToAsset(combinatedMaterial,settingsPath); // param var pc = new ParametersCreater("EmojiParticleParam"); pc.AddParam(param,0); // メニューの作成 var iconMenus = new MenuCreater(data.saveName+"_icons",true); for (int i = 0; i < data.emojis.Count; i++) { // 0はデフォルトなので+1 iconMenus.AddButton(data.emojis[i].name,data.emojis[i].ToTexture2D(),param,i+1); } // Modify用メニュー作成 var menu = new MenuCreater("mainMenu"); menu.AddSubMenu(iconMenus.CreateAsset(settingsPath,true),"EmojiParticles",TextureCombinater.ResizeSaveTexture( Path.Combine(fileDir,data.saveName+"_icon"+".png"), combinatedTexture, 256,256)); if (overrideSettings) { var oldSettings = avatar.transform.FindInChildren(EnvironmentGUIDs.prefix + data.saveName); if (oldSettings) { DestroyImmediate(oldSettings.gameObject); } } // オリジナルアセットのパーティクルコンポーネント差し替え var prefab = Instantiate(AssetUtility.LoadAssetAtGuid<GameObject>(EnvironmentGUIDs.particlePrefab)); prefab.name = EnvironmentGUIDs.prefix + data.saveName; var ps = prefab.GetComponentsInChildren<ParticleSystem>()[0]; ps.GetComponent<ParticleSystemRenderer>().material = combinatedMaterial; var ts = ps.textureSheetAnimation; ts.enabled = true; ts.numTilesX = tilling; ts.numTilesY = tilling; ps.gameObject.SetActive(false); var human = avatar.GetComponent<Animator>(); if (human != null) { // 追従先差し替え switch (target) { case Target.Hip: //assets.items[0].target = HumanBodyBones.Hips; prefab.transform.SetParent(human.GetBoneTransform(HumanBodyBones.Hips)); ps.transform.localPosition = new Vector3(0.0f,0.25f,0.25f); break; case Target.Head: //assets.items[0].target = HumanBodyBones.Head; prefab.transform.SetParent(human.GetBoneTransform(HumanBodyBones.Head)); ps.transform.localPosition = new Vector3(0.0f,0.25f,0.25f); break; case Target.RightHand: //assets.items[0].target = HumanBodyBones.RightHand; prefab.transform.SetParent(human.GetBoneTransform(HumanBodyBones.RightHand)); ps.transform.localPosition = Vector3.zero; break; case Target.LeftHand: //assets.items[0].target = HumanBodyBones.LeftHand; prefab.transform.SetParent(human.GetBoneTransform(HumanBodyBones.LeftHand)); ps.transform.localPosition = Vector3.zero; break; } prefab.transform.localPosition = Vector3.zero; prefab.transform.localRotation = Quaternion.identity; } // AnimationClipの作成 var controller = new AnimatorControllerCreator("Emoji_Controller","EmojiParticle"+data.saveName); controller.AddParameter(param,AnimatorControllerParameterType.Int); var reset = new AnimationClipCreator("Emoji_Anim_Reset",avatar.gameObject); reset.AddKeyframe_Gameobject(ps.gameObject, 0f, false); reset.AddKeyframe_Gameobject(ps.gameObject, 1f/60f, false); reset.AddKeyframe(0f, ps,"UVModule.startFrame.scalar",0f); reset.AddKeyframe(1f/60f, ps,"UVModule.startFrame.scalar",0f); //reset.CreateAnimation(ps.gameObject,"m_IsActive",0f,0f,1f); //reset.CreateAnimation(ps,"UVModule.startFrame.scalar",0f,0f,0f); controller.AddState("Idle",null); controller.AddState("Reset",null); controller.SetDefaultState("Idle"); controller.AddTransition("Reset","Idle",true); for (int i = 0; i < data.emojis.Count; i++) { var anim = new AnimationClipCreator("Emoji_Anim"+i,avatar.gameObject); var v = (float) i / (float) (tilling * tilling); anim.AddKeyframe_Gameobject(ps.gameObject, 0f, false); anim.AddKeyframe(0f, ps,"UVModule.startFrame.scalar",v); anim.AddKeyframe(0f, ps,"InitialModule.startLifetime.scalar",data.emojis[i].lifetime); anim.AddKeyframe(0f, ps,"EmissionModule.m_Bursts.Array.data[0].countCurve.scalar",data.emojis[i].count); anim.AddKeyframe(0f, ps,"InitialModule.startSize.scalar",data.emojis[i].scale); anim.AddKeyframe(0f, ps,"InitialModule.startSpeed.scalar",data.emojis[i].speed); anim.AddKeyframe_Gameobject(ps.gameObject, 1f/60f, true); anim.AddKeyframe_Gameobject(ps.gameObject, data.emojis[i].lifetime+1f/60f, true); if (data.emojis[i].effectPrefab != null) { int index = data.emojis.Select(e => e.effectPrefab).Distinct().ToList() .FindIndex(e => e == data.emojis[i].effectPrefab); var o = prefab.transform.Find("Effect_"+index)?.gameObject; if (o == null) { o = Instantiate(data.emojis[i].effectPrefab ,prefab.transform); o.name = "Effect_"+index; o.transform.localPosition = Vector3.zero; o.transform.localRotation = Quaternion.identity; o.SetActive(false); reset.AddKeyframe_Gameobject(o,0f,false); reset.AddKeyframe_Gameobject(o,1f/60f,false); } anim.AddKeyframe_Gameobject(o,0f,true); anim.AddKeyframe_Gameobject(o,data.emojis[i].lifetime,true); anim.AddKeyframe_Pos(0f,o.transform,Vector3.zero); anim.AddKeyframe_Pos(data.emojis[i].lifetime,o.transform,Vector3.forward*data.emojis[i].speed); } if (data.emojis[i].effectAudio != null) { int index = data.emojis.Select(e => e.effectAudio).Distinct().ToList() .FindIndex(e => e == data.emojis[i].effectAudio); var o = prefab.transform.Find("SE_"+index)?.gameObject; if (o == null) { o = Instantiate(AssetUtility.LoadAssetAtGuid<GameObject>(EnvironmentGUIDs.particleAudio) ,prefab.transform); o.name = "SE_"+index; var audio = o.GetComponent<AudioSource>(); audio.clip = data.emojis[i].effectAudio; o.transform.localPosition = Vector3.zero; o.transform.localRotation = Quaternion.identity; o.SetActive(false); reset.AddKeyframe_Gameobject(o,0f,false); reset.AddKeyframe_Gameobject(o,1f/60f,false); } anim.AddKeyframe_Gameobject(o,0f,true); anim.AddKeyframe_Gameobject(o,data.emojis[i].lifetime,true); anim.AddKeyframe_Pos(0f,o.transform,Vector3.zero); anim.AddKeyframe_Pos(data.emojis[i].lifetime,o.transform,Vector3.forward*data.emojis[i].speed); } var a = anim.CreateAsset(settingsPath, true); controller.AddState("Emoji_"+i,a); // 0はデフォルトなので+1 controller.AddTransition("Any", "Emoji_" + i, param, i + 1, true,false); controller.AddTransition("Emoji_" + i,"Reset",true ); } var r = reset.CreateAsset(settingsPath, true); controller.SetMotion("Idle",r); controller.SetMotion("Reset",r); controller.LayerMask(AvatarMaskBodyPart.Body,false,false); controller.LayerTransformMask(avatar.gameObject,false); AvatarModifyData newAssets = CreateInstance<AvatarModifyData>(); { newAssets.fx_controller = controller.CreateAsset(settingsPath, true); newAssets.parameter = pc.CreateAsset(settingsPath,true); newAssets.menu = menu.CreateAsset(settingsPath,true); } return newAssets; } #endif Material SaveParticleMaterial(Texture combinatedTextures,string path = null) { var material = new Material(Shader.Find("Particles/Standard Unlit")); material.SetTexture("_MainTex",combinatedTextures); material.SetFloat("_Mode",2); { // from https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/6a63f93bc1f20ce6cd47f981c7494e8328915621/Editor/StandardParticlesShaderGUI.cs#L579 material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_BlendOp", (int)UnityEngine.Rendering.BlendOp.Add); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; } if (!String.IsNullOrWhiteSpace(path)) { AssetDatabase.CreateAsset(material,path); material = AssetDatabase.LoadAssetAtPath<Material>(path); } return material; } [OnOpenAssetAttribute(1)] public static bool step1(int instanceID, int line) { if (EditorUtility.InstanceIDToObject(instanceID).GetType() == typeof(EmojiSaveData)) { EmojiParticleSetup.OpenSavedWindow(EditorUtility.InstanceIDToObject(instanceID) as EmojiSaveData); } return false; } } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/DebugTools/TextureArrayData.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System.Collections.Generic; using UnityEngine; namespace HhotateA.AvatarModifyTools.DebugTools { public class TextureArrayData : ScriptableObject { public List<Texture> textures = new List<Texture>(); } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/AnimatorModifier.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityEditor.Animations; using AnimatorLayerType = HhotateA.AvatarModifyTools.Core.AnimatorUtility.AnimatorLayerType; #if VRC_SDK_VRCSDK3 using VRC.SDKBase; using VRC.SDK3.Avatars.Components; #endif namespace HhotateA.AvatarModifyTools.Core { public class AnimatorModifier { public AnimatorModifier(AnimatorController c = null) { this.currentController = c; } public AnimatorModifier SetOrigin(AnimatorController c) { this.currentController = c; return this; } public AnimatorController currentController; public event Func<string,string> onFindParam; public event Func<AnimationClip,AnimationClip> onFindAnimationClip; public event Func<AvatarMask,AvatarMask> onFindAvatarMask; public Dictionary<string, string> animRepathList = new Dictionary<string, string>(); public bool? writeDefaultOverride { get; set; } = null; public Dictionary<AnimatorLayerType, int> layerOffset = new Dictionary<AnimatorLayerType, int>(); /// <summary> /// AnimatorControllerのStateMachineとParameterの結合 /// </summary> /// <param name="origin"></param> public AnimatorController ModifyAnimatorController(AnimatorController origin) { if (currentController == null) return null; if (currentController == origin) return null; int originLayerCount = currentController.layers.Length; CloneLayers(origin); CloneAnimatorParamaters(currentController, origin); for (int i = originLayerCount; i < currentController.layers.Length; i++) { SaveLayer(currentController.layers[i], AssetDatabase.GetAssetPath(currentController)); } EditorUtility.SetDirty(currentController); return currentController; } public AnimatorController RevertAnimator(AnimatorController origin) { if (currentController == null) return null; if (currentController == origin) return null; var newLayers = new List<AnimatorControllerLayer>(); foreach (var layer in currentController.layers) { if (origin.layers.Any(l => OnFindParam(l.name) == OnFindParam(layer.name))) { } else { newLayers.Add(layer); } } currentController.layers = newLayers.ToArray(); EditorUtility.SetDirty(currentController); return currentController; } public AnimatorController RevertAnimator(string keyword) { if (currentController == null) return null; currentController.parameters = currentController.parameters.Where(p => !p.name.StartsWith(keyword)).ToArray(); currentController.layers = currentController.layers.Where(l => !l.name.StartsWith(keyword)).ToArray(); EditorUtility.SetDirty(currentController); return currentController; } public List<string> WriteDefaultLayers() { var layers = new List<string>(); if (currentController == null) return layers; foreach (var layer in currentController.layers) { if (HaWriteDefaultStateMachine(layer.stateMachine)) { layers.Add(layer.name); } } return layers; } public List<string> HasKeyframeLayers(string[] path, string attribute = "") { var layers = new List<string>(); if (currentController == null) return layers; foreach (var layer in currentController.layers) { if (HasKeyFrameStateMachine(layer.stateMachine, path, attribute)) { layers.Add(layer.name); } } return layers; } public AnimatorController AnimatorControllerParameterRename() { if (currentController == null) return null; currentController.parameters = currentController.parameters.Select(p => new AnimatorControllerParameter() { name = OnFindParam(p.name), type = p.type, defaultBool = p.defaultBool, defaultFloat = p.defaultFloat, defaultInt = p.defaultInt, }).ToArray(); currentController.layers = currentController.layers.Select(l => { l.name = OnFindParam(l.name); l.stateMachine = StateMachineParameterRename(l.stateMachine); return l; }).ToArray(); EditorUtility.SetDirty(currentController); return currentController; } public AnimatorController RepathAnims(string from, string to) { if (currentController == null) return null; foreach (var layer in currentController.layers) { RePathStateMachine(layer.stateMachine, from, to); } EditorUtility.SetDirty(currentController); return currentController; } #region AnimatorCombinator /// <summary> /// AnimatorController全レイヤーの安全な結合 /// </summary> /// <param name="originController"></param> void CloneLayers(AnimatorController originController) { if (currentController != originController && currentController != null && originController != null) { foreach (var layer in originController.layers) { // すでに同名レイヤーがあれば削除する int index = Array.FindIndex(currentController.layers, l => l.name == OnFindParam(layer.name)); if (index > -1) currentController.RemoveLayer(index); // レイヤーの複製 var newLayer = CloneLayer(layer); currentController.AddLayer(newLayer); } } } /// <summary> /// AnimatorControllerのLayerごとの複製 /// </summary> /// <param name="originLayer"></param> /// <returns></returns> AnimatorControllerLayer CloneLayer(AnimatorControllerLayer originLayer) { var cloneLayer = new AnimatorControllerLayer() { avatarMask = OnFindAvatarMask(originLayer.avatarMask), blendingMode = originLayer.blendingMode, defaultWeight = originLayer.defaultWeight, iKPass = originLayer.iKPass, name = OnFindParam(originLayer.name), syncedLayerAffectsTiming = originLayer.syncedLayerAffectsTiming, syncedLayerIndex = originLayer.syncedLayerIndex, // StateMachineは別途複製 stateMachine = CloneStateMachine(originLayer.stateMachine), }; CloneTrasitions(cloneLayer.stateMachine, originLayer.stateMachine); return cloneLayer; } /// <summary> /// Statemachineの複製 /// </summary> /// <param name="originMachine"></param> /// <returns></returns> AnimatorStateMachine CloneStateMachine(AnimatorStateMachine originMachine) { var cloneChildMachine = originMachine.stateMachines.Select(cs => new ChildAnimatorStateMachine() { position = cs.position, stateMachine = CloneStateMachine(cs.stateMachine) }).ToList(); var cloneStates = CloneStates(originMachine); // StateMachineの複製 var cloneStateMachine = new AnimatorStateMachine { anyStatePosition = originMachine.anyStatePosition, entryPosition = originMachine.entryPosition, exitPosition = originMachine.exitPosition, hideFlags = originMachine.hideFlags, name = originMachine.name, parentStateMachinePosition = originMachine.parentStateMachinePosition, // ChildAnimatorStateMachineは別途複製 states = cloneStates.ToArray(), stateMachines = cloneChildMachine.ToArray(), defaultState = cloneStates.FirstOrDefault(s => s.state.name == originMachine.defaultState.name).state, }; return cloneStateMachine; } /// <summary> /// ChildAnimationStateの複製 /// </summary> /// <param name="originMachine"></param> /// <returns></returns> List<ChildAnimatorState> CloneStates(AnimatorStateMachine originMachine) { // Stateの複製 var cloneStates = new List<ChildAnimatorState>(); foreach (var animstate in originMachine.states) { cloneStates.Add(CloneChildAnimatorState(animstate)); } return cloneStates; } void CloneTrasitions(AnimatorStateMachine clone, AnimatorStateMachine origin) { // リスト作成 var cloneStates = new List<AnimatorState>(); var originStates = new List<AnimatorState>(); var cloneMachines = GetStatemachines(clone); var originMachines = GetStatemachines(origin); foreach (var m in cloneMachines) { cloneStates.AddRange(m.states.Select(s => s.state).ToList()); } foreach (var m in originMachines) { originStates.AddRange(m.states.Select(s => s.state).ToList()); } // Transitionの複製 foreach (var originState in originStates) { var cloneState = cloneStates.FirstOrDefault(s => s.name == originState.name); if (cloneState != null) { foreach (var originTransition in originState.transitions) { var cloneTransition = new AnimatorStateTransition(); if (originTransition.isExit) { cloneTransition = cloneState.AddExitTransition(); } if (originTransition.destinationState != null) { var destinationState = cloneStates.FirstOrDefault(s => s.name == originTransition.destinationState.name); cloneTransition = cloneState.AddTransition(destinationState); } if (originTransition.destinationStateMachine != null) { var destinationState = cloneMachines.FirstOrDefault(s => s.name == originTransition.destinationStateMachine.name); cloneTransition = cloneState.AddTransition(destinationState); } CopyAnimatorStateTransition(cloneTransition, originTransition); } CopyStateBehaviours(cloneState, originState); } else { Debug.LogError("NullState Copy"); } } foreach (var originMachine in originMachines) { var cloneMachine = cloneMachines.FirstOrDefault(m => m.name == originMachine.name); if (cloneMachine != null) { foreach (var originTransition in originMachine.anyStateTransitions) { var cloneTransition = new AnimatorStateTransition(); if (originTransition.destinationState != null) { var destinationState = cloneStates.FirstOrDefault(s => s.name == originTransition.destinationState.name); cloneTransition = cloneMachine.AddAnyStateTransition(destinationState); } if (originTransition.destinationStateMachine != null) { var destinationState = cloneMachines.FirstOrDefault(s => s.name == originTransition.destinationStateMachine.name); cloneTransition = cloneMachine.AddAnyStateTransition(destinationState); } CopyAnimatorStateTransition(cloneTransition, originTransition); } foreach (var originTransition in originMachine.entryTransitions) { var cloneTransition = new AnimatorTransition(); if (originTransition.destinationState != null) { var destinationState = cloneStates.FirstOrDefault(s => s.name == originTransition.destinationState.name); cloneTransition = cloneMachine.AddEntryTransition(destinationState); } if (originTransition.destinationStateMachine != null) { var destinationState = cloneMachines.FirstOrDefault(s => s.name == originTransition.destinationStateMachine.name); cloneTransition = cloneMachine.AddEntryTransition(destinationState); } CopyAnimatorTransition(cloneTransition, originTransition); } } else { Debug.LogError("NullStateMachine Copy"); } } } List<AnimatorStateMachine> GetStatemachines(AnimatorStateMachine root) { var l = new List<AnimatorStateMachine>(); l.Add(root); foreach (var stateMachine in root.stateMachines) { l.AddRange(GetStatemachines(stateMachine.stateMachine)); } return l; } AnimatorStateTransition CopyAnimatorStateTransition(AnimatorStateTransition clone, AnimatorStateTransition origin) { clone.duration = origin.duration; clone.offset = origin.offset; clone.interruptionSource = origin.interruptionSource; clone.orderedInterruption = origin.orderedInterruption; clone.exitTime = origin.exitTime; clone.hasExitTime = origin.hasExitTime; clone.hasFixedDuration = origin.hasFixedDuration; clone.canTransitionToSelf = origin.canTransitionToSelf; CopyAnimatorTransition(clone, origin); return clone; } AnimatorTransitionBase CopyAnimatorTransition(AnimatorTransitionBase clone, AnimatorTransitionBase origin) { clone.name = origin.name; clone.hideFlags = origin.hideFlags; clone.solo = origin.solo; clone.mute = origin.mute; clone.isExit = origin.isExit; foreach (var originCondition in origin.conditions) { clone.AddCondition(originCondition.mode, originCondition.threshold, OnFindParam(originCondition.parameter)); } return clone; } ChildAnimatorState CloneChildAnimatorState(ChildAnimatorState origin) { var clone = new ChildAnimatorState() { position = origin.position, state = CloneAnimationState(origin.state) }; return clone; } AnimatorState CloneAnimationState(AnimatorState origin) { var clone = new AnimatorState() { cycleOffset = origin.cycleOffset, cycleOffsetParameter = OnFindParam(origin.cycleOffsetParameter), cycleOffsetParameterActive = origin.cycleOffsetParameterActive, hideFlags = origin.hideFlags, iKOnFeet = origin.iKOnFeet, mirror = origin.mirror, mirrorParameter = OnFindParam(origin.mirrorParameter), mirrorParameterActive = origin.mirrorParameterActive, motion = CloneMotion(origin.motion), name = origin.name, speed = origin.speed, speedParameter = OnFindParam(origin.speedParameter), speedParameterActive = origin.speedParameterActive, tag = origin.tag, timeParameter = OnFindParam(origin.timeParameter), timeParameterActive = origin.timeParameterActive, writeDefaultValues = writeDefaultOverride ?? origin.writeDefaultValues }; return clone; } Motion CloneMotion(Motion origin) { if (origin == null) { return OnFindAnimationClip(null); /*if (OverrideNullAnimation) { return AssetUtility.LoadAssetAtGuid<AnimationClip>(EnvironmentVariable.nottingAnim); } else { return null; }*/ } if (origin is BlendTree) { var o = origin as BlendTree; BlendTree c = new BlendTree() { blendParameter = OnFindParam(o.blendParameter), blendParameterY = OnFindParam(o.blendParameterY), children = o.children.Select(m => new ChildMotion() { cycleOffset = m.cycleOffset, directBlendParameter = OnFindParam(m.directBlendParameter), mirror = m.mirror, motion = CloneMotion(m.motion), position = m.position, threshold = m.threshold, timeScale = m.timeScale, }).ToArray(), blendType = o.blendType, hideFlags = o.hideFlags, maxThreshold = o.maxThreshold, minThreshold = o.minThreshold, name = o.name, useAutomaticThresholds = o.useAutomaticThresholds, }; return c; } else if (origin is AnimationClip) { if (animRepathList.Count > 0) { return RePathAnimation((AnimationClip) origin); } return origin; } return origin; } AnimatorState CopyStateBehaviours(AnimatorState clone, AnimatorState origin) { var behaviours = new List<StateMachineBehaviour>(); foreach (var behaviour in origin.behaviours) { #if VRC_SDK_VRCSDK3 if (behaviour is VRCAnimatorLayerControl) { VRCAnimatorLayerControl o = behaviour as VRCAnimatorLayerControl; var c = ScriptableObject.CreateInstance<VRCAnimatorLayerControl>(); { c.ApplySettings = o.ApplySettings; c.debugString = o.debugString; c.playable = o.playable; if (layerOffset == null) { c.layer = o.layer; } else { c.layer = o.layer + layerOffset[o.playable.GetAnimatorLayerType()]; // レイヤーが増えた分加算する } c.blendDuration = o.blendDuration; c.goalWeight = o.goalWeight; c.playable = o.playable; } behaviours.Add(c); } else if (behaviour is VRCAvatarParameterDriver) { VRCAvatarParameterDriver o = behaviour as VRCAvatarParameterDriver; var c = ScriptableObject.CreateInstance<VRCAvatarParameterDriver>(); { c.name = o.name; c.parameters = o.parameters.Select(p => { return new VRC_AvatarParameterDriver.Parameter() { name = OnFindParam(p.name), chance = p.chance, type = p.type, value = p.value, valueMin = p.valueMin, valueMax = p.valueMax }; }).ToList(); c.debugString = o.debugString; c.hideFlags = o.hideFlags; c.localOnly = o.localOnly; c.ApplySettings = o.ApplySettings; } behaviours.Add(c); } else { var c = ScriptableObject.Instantiate(behaviour); behaviours.Add(c); } #else var c = ScriptableObject.Instantiate(behaviour); behaviours.Add(c); #endif } clone.behaviours = behaviours.ToArray(); return clone; } void SaveLayer(AnimatorControllerLayer l, string path) { // if(l.avatarMask) AssetDatabase.AddObjectToAsset(l.avatarMask,path); SaveStateMachine(l.stateMachine, path); } void SaveStateMachine(AnimatorStateMachine machine, string path) { machine.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(machine, path); foreach (var s in machine.states) { AssetDatabase.AddObjectToAsset(s.state, path); SaveMotion(s.state.motion, path); foreach (var t in s.state.transitions) { t.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(t, path); } foreach (var b in s.state.behaviours) { b.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(b, path); } } foreach (var t in machine.entryTransitions) { t.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(t, path); } foreach (var t in machine.anyStateTransitions) { t.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(t, path); } foreach (var m in machine.stateMachines) { SaveStateMachine(m.stateMachine, path); foreach (var b in m.stateMachine.behaviours) { b.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(b, path); } } } void SaveMotion(Motion motion, string path) { if (motion == null) return; if (motion is BlendTree) { BlendTree tree = (BlendTree) motion; tree.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(tree, path); foreach (var m in tree.children) { SaveMotion(m.motion, path); } } } /// <summary> /// AnimatorControllerのパラメータの安全な結合 /// </summary> /// <param name="cloneController"></param> /// <param name="originController"></param> void CloneAnimatorParamaters(AnimatorController cloneController, AnimatorController originController) { if (cloneController != originController || cloneController != null || originController != null) { foreach (var parameter in originController.parameters) { // すでに同名パラメーターがあれば削除する int index = Array.FindIndex(cloneController.parameters, p => p.name == OnFindParam(parameter.name)); if (index > -1) cloneController.RemoveParameter(cloneController.parameters[index]); // パラメーターのコピー cloneController.AddParameter(new AnimatorControllerParameter() { defaultBool = parameter.defaultBool, defaultFloat = parameter.defaultFloat, defaultInt = parameter.defaultInt, name = OnFindParam(parameter.name), type = parameter.type, }); } } } #endregion #region RenameParams AnimatorStateMachine StateMachineParameterRename(AnimatorStateMachine machine) { machine.states = machine.states.Select(s => { if (s.state.motion is BlendTree) { BlendTree BlendTreeParameterRename(BlendTree b) { b.blendParameter = OnFindParam(b.blendParameter); b.blendParameterY = OnFindParam(b.blendParameterY); b.children = b.children.Select(c => { if (c.motion is BlendTree) { c.motion = BlendTreeParameterRename((BlendTree) c.motion); } return c; }).ToArray(); return b; } s.state.motion = BlendTreeParameterRename((BlendTree) s.state.motion); } s.state.timeParameter = OnFindParam(s.state.timeParameter); s.state.speedParameter = OnFindParam(s.state.speedParameter); s.state.mirrorParameter = OnFindParam(s.state.mirrorParameter); s.state.cycleOffsetParameter = OnFindParam(s.state.cycleOffsetParameter); s.state.transitions = s.state.transitions.Select(t => { t.conditions = t.conditions.Select(c => new AnimatorCondition() { mode = c.mode, parameter = OnFindParam(c.parameter), threshold = c.threshold }).ToArray(); return t; }).ToArray(); s.state.behaviours = s.state.behaviours.Select(b => { #if VRC_SDK_VRCSDK3 if (b is VRCAvatarParameterDriver) { var p = (VRCAvatarParameterDriver) b; p.parameters = p.parameters.Select(e => { e.name = OnFindParam(e.name); return e; }).ToList(); } #endif return b; }).ToArray(); return s; }).ToArray(); machine.entryTransitions = machine.entryTransitions.Select(t => { t.conditions = t.conditions.Select(c => new AnimatorCondition() { mode = c.mode, parameter = OnFindParam(c.parameter), threshold = c.threshold }).ToArray(); return t; }).ToArray(); machine.anyStateTransitions = machine.anyStateTransitions.Select(t => { t.conditions = t.conditions.Select(c => new AnimatorCondition() { mode = c.mode, parameter = OnFindParam(c.parameter), threshold = c.threshold }).ToArray(); return t; }).ToArray(); machine.stateMachines = machine.stateMachines.Select(m => { StateMachineParameterRename(m.stateMachine); m.stateMachine.behaviours = m.stateMachine.behaviours.Select(b => { #if VRC_SDK_VRCSDK3 if (b is VRCAvatarParameterDriver) { var p = (VRCAvatarParameterDriver) b; p.parameters = p.parameters.Select(e => { e.name = OnFindParam(e.name); return e; }).ToList(); } #endif return b; }).ToArray(); return m; }).ToArray(); return machine; } #endregion #region RepathAnim /// <summary> /// アニメーションのパスを書き換える /// </summary> /// <param name="clip"></param> /// <returns></returns> AnimationClip RePathAnimation(AnimationClip clip) { bool hasPath = false; using (var o = new SerializedObject(clip)) { var i = o.GetIterator(); while (i.Next(true)) { if (i.name == "path" && i.propertyType == SerializedPropertyType.String) { foreach (var ft in animRepathList) { if (i.stringValue.StartsWith(ft.Key)) { hasPath = true; break; } } } } } if (hasPath) { clip = OnFindAnimationClip(clip); using (var o = new SerializedObject(clip)) { var i = o.GetIterator(); while (i.Next(true)) { if (i.name == "path" && i.propertyType == SerializedPropertyType.String) { foreach (var ft in animRepathList) { if (i.stringValue.StartsWith(ft.Key)) { i.stringValue = i.stringValue.Replace(ft.Key, ft.Value); } } } } o.ApplyModifiedProperties(); } } return clip; } void RePathStateMachine(AnimatorStateMachine machine, string from, string to) { foreach (var s in machine.states) { if (s.state.motion) { RePathMotion(s.state.motion, from, to); } } foreach (var m in machine.stateMachines) { RePathStateMachine(m.stateMachine, from, to); } } void RePathMotion(Motion motion, string from, string to) { if (motion is BlendTree) { BlendTree tree = (BlendTree) motion; foreach (var m in tree.children) { RePathMotion(m.motion, from, to); } } else if (motion is AnimationClip) { AnimationClip clip = (AnimationClip) motion; RePathAnimation(clip, from, to); } } AnimationClip RePathAnimation(AnimationClip clip, string from, string to) { bool hasPath = false; using (var o = new SerializedObject(clip)) { var i = o.GetIterator(); while (i.Next(true)) { if (i.name == "path" && i.propertyType == SerializedPropertyType.String) { if (i.stringValue.StartsWith(from)) { hasPath = true; break; } } } } if (hasPath) { clip = OnFindAnimationClip(clip); using (var o = new SerializedObject(clip)) { var i = o.GetIterator(); while (i.Next(true)) { if (i.name == "path" && i.propertyType == SerializedPropertyType.String) { if (i.stringValue.StartsWith(from)) { i.stringValue = i.stringValue.Replace(from, to); } } } o.ApplyModifiedProperties(); } } return clip; } #endregion #region AnimatorChecker bool HaWriteDefaultStateMachine(AnimatorStateMachine machine) { foreach (var s in machine.states) { if (s.state.motion) { return s.state.writeDefaultValues; } } foreach (var m in machine.stateMachines) { if (HaWriteDefaultStateMachine(m.stateMachine)) { return true; } } return false; } bool HasKeyFrameStateMachine(AnimatorStateMachine machine, string[] path, string attribute = "") { foreach (var s in machine.states) { if (s.state.motion) { if (HasKeyframeMotion(s.state.motion, path, attribute)) { return true; } } } foreach (var m in machine.stateMachines) { if (HasKeyFrameStateMachine(m.stateMachine, path, attribute)) { return true; } } return false; } bool HasKeyframeMotion(Motion motion, string[] path, string attribute = "") { if (motion is BlendTree) { BlendTree tree = (BlendTree) motion; foreach (var m in tree.children) { if (HasKeyframeMotion(m.motion, path, attribute)) { return true; } } } else if (motion is AnimationClip) { AnimationClip clip = (AnimationClip) motion; if (HasKeyframeAnimation(clip, path, attribute)) { return true; } } return false; } bool HasKeyframeAnimation(AnimationClip clip, string[] path, string attribute = "") { using (var o = new SerializedObject(clip)) { var curves = o.FindProperty("m_FloatCurves"); for (int i = curves.arraySize - 1; i >= 0; i--) { var pathProp = curves.GetArrayElementAtIndex(i).FindPropertyRelative("path"); var attributeProp = curves.GetArrayElementAtIndex(i).FindPropertyRelative("attribute"); if (pathProp != null) { if (path.Contains(pathProp.stringValue)) { if (String.IsNullOrWhiteSpace(attribute)) { return true; } else { if (attributeProp.stringValue.Contains(attribute)) { return true; } } } } } } return false; } #endregion string OnFindParam(string param) { if (onFindParam != null) { return onFindParam(param); } return param; } AnimationClip OnFindAnimationClip(AnimationClip origin) { if (onFindAnimationClip != null) { return onFindAnimationClip(origin); } return origin; } AvatarMask OnFindAvatarMask(AvatarMask origin) { if (onFindAvatarMask != null) { return onFindAvatarMask(origin); } return origin; } } public static class AnimatorUtility { public enum AnimatorLayerType { Locomotion, Idle, Gesture, Action, Fx } #if VRC_SDK_VRCSDK3 public static VRCAvatarDescriptor.AnimLayerType GetVRChatAnimatorLayerType(this AnimatorLayerType type) { switch (type) { case AnimatorLayerType.Locomotion : return VRCAvatarDescriptor.AnimLayerType.Base; case AnimatorLayerType.Idle : return VRCAvatarDescriptor.AnimLayerType.Additive; case AnimatorLayerType.Gesture : return VRCAvatarDescriptor.AnimLayerType.Gesture; case AnimatorLayerType.Action : return VRCAvatarDescriptor.AnimLayerType.Action; case AnimatorLayerType.Fx : return VRCAvatarDescriptor.AnimLayerType.FX; } return VRCAvatarDescriptor.AnimLayerType.Base; } public static AnimatorLayerType GetAnimatorLayerType(this VRCAvatarDescriptor.AnimLayerType type) { switch (type) { case VRCAvatarDescriptor.AnimLayerType.Base : return AnimatorLayerType.Locomotion; case VRCAvatarDescriptor.AnimLayerType.Additive : return AnimatorLayerType.Idle; case VRCAvatarDescriptor.AnimLayerType.Gesture : return AnimatorLayerType.Gesture; case VRCAvatarDescriptor.AnimLayerType.Action : return AnimatorLayerType.Action; case VRCAvatarDescriptor.AnimLayerType.FX : return AnimatorLayerType.Fx; } return AnimatorLayerType.Locomotion; } public static AnimatorLayerType GetAnimatorLayerType(this VRC_AnimatorLayerControl.BlendableLayer type) { switch (type) { case VRC_AnimatorLayerControl.BlendableLayer.Additive : return AnimatorLayerType.Idle; case VRC_AnimatorLayerControl.BlendableLayer.Gesture : return AnimatorLayerType.Gesture; case VRC_AnimatorLayerControl.BlendableLayer.Action : return AnimatorLayerType.Action; case VRC_AnimatorLayerControl.BlendableLayer.FX : return AnimatorLayerType.Fx; } return AnimatorLayerType.Locomotion; } #endif } } <|start_filename|>Assets/HhotateA/AvatarModifyTool/Editor/DebugTools/TextureArrayMaker.cs<|end_filename|> /* AvatarModifyTools https://github.com/HhotateA/AvatarModifyTools Copyright (c) 2021 @HhotateA_xR This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ using HhotateA.AvatarModifyTools.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; using UnityEditor.Callbacks; namespace HhotateA.AvatarModifyTools.DebugTools { public class TextureArrayMaker : WindowBase { [OnOpenAssetAttribute(0)] public static bool OpenAsset(int instanceID, int line) { if (EditorUtility.InstanceIDToObject(instanceID).GetType() == typeof(TextureArrayData)) { ShowWindow(EditorUtility.InstanceIDToObject(instanceID) as TextureArrayData); } return false; } [MenuItem("Window/HhotateA/DebugTools/TextureArrayMaker",false,4)] public static void ShowWindow() { var wnd = GetWindow<TextureArrayMaker>(); wnd.titleContent = new GUIContent("TextureArrayMaker"); wnd.data = CreateInstance<TextureArrayData>(); wnd.withAsset = false; } public static void ShowWindow(TextureArrayData d) { var wnd = GetWindow<TextureArrayMaker>(); wnd.titleContent = new GUIContent("TextureArrayMaker"); if (d == null) { wnd.data = CreateInstance<TextureArrayData>(); wnd.withAsset = false; } else { wnd.data = d; wnd.withAsset = true; } } public bool withAsset = false; private TextureArrayData data; private List<Texture> textures { get => data.textures; set => data.textures = value; } private void OnGUI() { TitleStyle("TextureArrayMaker"); var tc = EditorGUILayout.IntField("Texture Array Size",textures.Count); if (tc < textures.Count) { data.textures = textures.GetRange(0, tc); } else if(tc > textures.Count) { textures.AddRange(new Texture[tc-textures.Count].ToList()); } for(int i = 0; i < textures.Count; i ++) { textures[i] = (Texture) EditorGUILayout.ObjectField(textures[i], typeof(Texture), true); } withAsset = EditorGUILayout.Toggle("SaveWithAsset", withAsset); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("SaveCombine")) { var path = EditorUtility.SaveFilePanel("Save", "Assets", "CombineTexture", "png"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } try { TextureCombinater.CombinateSaveTexture( textures.Select(t=> TextureCombinater.Texture2Texture2D(t)).ToArray(),path); if (withAsset) { data = Instantiate(data); AssetDatabase.CreateAsset(data, Path.Combine( Path.GetDirectoryName(FileUtil.GetProjectRelativePath(path)), Path.GetFileNameWithoutExtension(FileUtil.GetProjectRelativePath(path))+".asset")); } } catch (Exception e) { OnError(e); throw; } OnSave(); } if (GUILayout.Button("SaveArray")) { var path = EditorUtility.SaveFilePanel("Save", "Assets", "TextureArray", "asset"); if (string.IsNullOrEmpty(path)) { OnCancel(); return; } try { var asset = TextureCombinater.CreateTexture2DArray( textures.Select(t=> TextureCombinater.Texture2Texture2D(t)).ToArray()); AssetDatabase.CreateAsset(asset, FileUtil.GetProjectRelativePath(path)); if (withAsset) { data = Instantiate(data); AssetDatabase.AddObjectToAsset(data, FileUtil.GetProjectRelativePath(path)); } } catch (Exception e) { OnError(e); throw; } OnSave(); } } status.Display(); Signature(); } } }
Narazaka/AvatarModifyTools
<|start_filename|>c/tests/simple_test.c<|end_filename|> // THE BEERWARE LICENSE (Revision 42): // <thenoviceoof> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you // think this stuff is worth it, you can buy me a beer in return // - <NAME> (thenoviceoof) #include <base92.h> #include <stdio.h> int main() { int i; char *str = "\0"; if(strcmp(base92encode(str, 1), "!!") != 0) exit(1); if(base92decode("!!", &i)[0] != 0) exit(1); return 0; } <|start_filename|>c/tests/chr_decode.c<|end_filename|> // THE BEERWARE LICENSE (Revision 42): // <thenoviceoof> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you // think this stuff is worth it, you can buy me a beer in return // - <NAME> (thenoviceoof) #include <stdio.h> #include <base92.h> int main() { if(base92chr_decode('!') != 0) exit(1); if(base92chr_decode('#') != 1) exit(1); if(base92chr_decode('_') != 61) exit(1); if(base92chr_decode('a') != 62) exit(1); if(base92chr_decode('}') != 90) exit(1); if(base92chr_decode(' ') != 255) exit(1); return 0; } <|start_filename|>c/tests/utils.h<|end_filename|> // THE BEERWARE LICENSE (Revision 42): // <thenoviceoof> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you // think this stuff is worth it, you can buy me a beer in return // - <NAME> (thenoviceoof) #include <stdlib.h> unsigned char *stringify(char *str, int i) { int j; unsigned char *s; s = (unsigned char*)malloc(sizeof(char) * i + 1); for (j = 0; j < i; j++) { s[j] = str[j]; } s[j+1] = 0; return s; } <|start_filename|>c/src/base92.h<|end_filename|> // THE BEERWARE LICENSE (Revision 42): // <thenoviceoof> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you // think this stuff is worth it, you can buy me a beer in return // - <NAME> (thenoviceoof) // check if the header has been included before #ifndef BASE92 #define BASE92 #include <stdlib.h> #include <string.h> unsigned char base92chr_encode(unsigned char byt); unsigned char base92chr_decode(unsigned char byt); unsigned char* base92encode(unsigned char* str, int len); unsigned char* base92decode(unsigned char* str, int *len); #endif <|start_filename|>c/tests/lengths.c<|end_filename|> // THE BEERWARE LICENSE (Revision 42): // <thenoviceoof> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you // think this stuff is worth it, you can buy me a beer in return // - <NAME> (thenoviceoof) #include <base92.h> #include <utils.h> int LEN = 13; int main() { char **strs; char *str, *s; int i, j; strs = (char**)malloc(LEN*sizeof(char*)); strs[0] = "D,"; strs[1] = "D8*"; strs[2] = "D81Q"; strs[3] = "D81RC"; strs[4] = "D81RPyB"; strs[5] = "D81RPya("; strs[6] = "D81RPya.&"; strs[7] = "D81RPya.)h"; strs[8] = "D81RPya.)hg6"; strs[9] = "D81RPya.)hgN2"; strs[10] = "D81RPya.)hgNA%"; strs[11] = "D81RPya.)hgNA($"; strs[12] = "D81RPya.)hgNA(%s"; str = (char*)malloc((LEN)*sizeof(char)); str[0] = 0; for(i = 0; i < LEN; i++) { str[i] = 'a'; str[i+1] = 0; if(strcmp(base92encode(str, i+1), strs[i]) != 0) exit(1); s = base92decode(strs[i], &j); if(strcmp(stringify(s, j), str) != 0) exit(1); } return 0; }
backbord/base92
<|start_filename|>ohm/Voxel.h<|end_filename|> // Copyright (c) 2020 // Commonwealth Scientific and Industrial Research Organisation (CSIRO) // ABN 41 687 119 230 // // Author: <NAME> #ifndef OHMVOXEL_H #define OHMVOXEL_H #include "OhmConfig.h" #include "Key.h" #include "MapChunk.h" #include "MapLayer.h" #include "MapLayout.h" #include "OccupancyMap.h" #include "VoxelBlock.h" #include <cinttypes> #include <type_traits> #include <glm/vec3.hpp> namespace ohm { namespace detail { /// Internal helper to manage updating const/mutable chunks with the base as the mutable version. template <typename T> struct VoxelChunkAccess { /// Resolve a mutable chunk for @p key from @p map , creating the chunk if required. /// @param map The map of interest. /// @param key The key to resolve the chunk for. /// @return The chunk for @p key . static MapChunk *chunk(OccupancyMap *map, const Key &key) { return map->region(key.regionKey(), true); } /// Update the first valid index for @p chunk using @p voxel_index . /// @param chunk The map chunk being touched: must be valid. /// @param voxel_index The linear index of the modified voxel. static void touch(MapChunk *chunk, unsigned voxel_index) { chunk->updateFirstValid(voxel_index); } /// Mark @p chunk as having been updated within @p layer_index . /// This will @c OccupancyMap::touch() the @p map and update the stamps in @p chunk relevant to @p layer_index . /// @param map The map of interest. /// @param chunk The map chunk being touched: must be valid. /// @param layer_index The voxel memory index in chunk which has been modified. static void touch(OccupancyMap *map, MapChunk *chunk, int layer_index) { chunk->dirty_stamp = map->touch(); chunk->touched_stamps[layer_index].store(chunk->dirty_stamp, std::memory_order_relaxed); } /// Write the @p value to the voxel at @p voxel_index within @p voxel_memory . /// @param voxel_memory Start of the voxel memory. /// @param voxel_index Index of the voxel within @p voxel_memory - strided by @c T . /// @param value The value to write. /// @param flags_change Flags to set in @p flags . /// @param flags Flags to modify by setting @p flags_change . static void writeVoxel(uint8_t *voxel_memory, unsigned voxel_index, const T &value, unsigned flags_change, uint16_t *flags) { memcpy(voxel_memory + sizeof(T) * voxel_index, &value, sizeof(T)); *flags |= flags_change; } }; /// Internal helper to manage const chunks. Supports fetching existing chunks, but no modification. template <typename T> struct VoxelChunkAccess<const T> { /// Query the @c MapChunk pointer for @p key. /// @param map The Occupancy map of interest /// @param key The key to get a chunk for. /// @return The @c MapChunk for key, or null if the chunk does not exist. static const MapChunk *chunk(const OccupancyMap *map, const Key &key) { return map->region(key.regionKey()); } /// Noop. /// @param chunk Ignored. /// @param voxel_index Ignored. static void touch(const MapChunk *chunk, unsigned voxel_index) { (void)chunk; (void)voxel_index; } /// Noop. /// @param map Ignored. /// @param chunk Ignored. /// @param layer_index Ignored. static void touch(const OccupancyMap *map, const MapChunk *chunk, int layer_index) { (void)map; (void)chunk; (void)layer_index; } static void writeVoxel(uint8_t voxel_memory, unsigned voxel_index, const T &value, unsigned flags_change, uint16_t *flags) = delete; }; } // namespace detail /// The @c Voxel interface provides a semi optimal abstraction and book keeping for accessing voxel data. /// /// The @c Voxel interface deals directly with the @c MapLayer abstraction of the @c OccupancyMap , providing access /// to the data within a single @p MapLayer . The template type is used to resolve the data within the layer as /// the template type, supporting mutable and const access (see below). The template type is validated against /// the data in the proposed layer index by checking the size of @c T against the size of the data stored in the /// layer. The layer index is invalidated when the sizes do not match. /// /// A mutable @c Voxel is one where the template type @c T is non-const, while a const @c Voxel has a const template /// type @c T . Only a mutable @c Voxel can create new @c MapChunks within the @c OccupancyMap . This occurs /// immediately on setting a key, generally via @c setKey() . Additional book keeping is managed by the mutable /// @c Voxel to ensure correct update of @c OccupancyMap::stamp() (via @c OccupancyMap::touch() ) as well as /// updating appropriate @c MapChunk stamps. The @c MapChunk::first_valid_index is also updated for the occupancy /// layer. /// /// A @c Voxel is initialised to reference a specific @c MapLayer within a specific @c OccupancyMap . At this point /// the @c Voxel should pass @c isValidLayer() to ensure that the map is valid, the layer reference is valid and /// that the size of @c T matches the @c MayLayer voxel size. Specific voxels can then be referenced via @c setKey() /// to identify which voxel to reference. This resolves the @c MapChunk , creating the chunk in a mutable @c Voxel /// if required. A const @c Voxel will never create a new @c MapChunk and may have a valid @c Key , with a null /// @c MapChunk . /// /// From this we see that a @c Voxel may be in one of several states. Below we list the states and various methods /// which can be used to check these states. /// /// State description | `isLayerValid()` | `isValidReference()` | `isValid()` | `errorFlags()` /// ------------------------------- | ---------------- | --------------------- | ----------- | ------------- /// Null map | false | false | false | `NullMap` /// `layerIndex()` out of range | false | false | false | `InvalidLayerIndex` /// `sizeof(T)!=voxelByteSize()` * | false | false | false | `VoxelSizeMismatch` /// Initialised | true | false | false | 0 /// Key set, chunk null (const only)| true | true | false | 0 /// Key set, chunk resolved | true | true | true | 0 /// /// * see @c MapLayer::voxelByteSize() /// /// There are various ways to set a @c Voxel to reference a specific voxel using @c setKey() or some constructors. /// The @c setKey() function supports various overloads. The first accepts a @c Key which references a voxel. This /// key is immediately used to resolve the @c MapChunk then the specific voxel @c data() on request. Setting to a key /// in the same @c MapChunk as the current maintains the current @c MapChunk pointer. @c setKey() also accepts a /// @c Key with a @c MapChunk for cases where the caller already has a reference to the correct @c MapChunk . This /// chunk pointer is assumed to be correct and is not validated. /// /// The key may also be set from another @c Voxel even one for a different layer. This copies the @c Key and /// @c MapChunk from the other @c Voxel saving on a looking into the map to resolve the chunk. This call is validated /// only to ensure that the @c OccupancyMap pointers match, setting @c Error::kMapMismatch on failure. /// /// Finally a voxel reference may be set from an @c OccupancyMap::iterator for a mutable voxel or an /// @c OccupancyMap::const_iterator for a const voxel. This call also assumes the @c MapChunk in the iterator is valid /// and will save a looking into the map. Note that the iterator is assumed to be valid by the @c Voxel and is not /// validated. That is, a @c Voxel must not be initialised from an @c end() or otherwise invalid iterator. /// /// A similar set of parametrisation of the @c Voxel constructors also exist. /// /// For convenience the free function @c setVoxelKey() may be used to initialise a number of @c Voxel references, /// presumably to different layers, from a single key reference. This is a variadic template function accepting /// at least two arguments. The first is the key reference object - a @c Key , iterator or valid @c Voxel reference - /// followed by any number of @c Voxel objects. Take care to ensure that the first argument is always a valid key /// reference. /// /// For optimal memory access a @c MapChunk should be accessed as linearly as possible. This is mostly only applicable /// to reading only access. For write access some gains are to be made by referencing voxels in a spatially coherent /// fashion, ones which are likely to fall in the same @c MapChunk . This helps keep @c Voxel overheads to a /// minimum, but direct access to and linear traversal of voxel data may be more optimal with manual book keeping /// to manage the various stamps and @c MapChunk::first_valid_index . /// /// Typical usage is illustrated in the example below, populating a line in the map and reading a line of voxels. /// /// @code /// void populateLine(ohm::OccupancyMap &map) ///{ /// // Create a voxel reference for accessing voxel occupancy. /// ohm::Voxel<float> occupancy(&map, map.layout().occupancyLayer()); /// // Create a voxel reference for accessing VoxelMean. /// ohm::Voxel<ohm::VoxelMean> mean(&map, map.layout().meanLayer()); /// /// // Ensure the occupancy layer is ok. /// if (!occupancy.isLayerValid()) /// { /// return; /// } /// /// glm::dvec3 sample(0, 0, 0); /// for (int i = 0; i < 10; ++i) /// { /// sample.x = i * map.resolution(); /// const Key key = map.voxelKey(sample); /// /// // Below we look at several methods for setting the keys for the Voxel objects. Note that they have equivalent /// // results and only one need be used. The process of setting the Key instantiates the MapChunk in map. /// /// // 1. Set each voxel individually. This has some slight additional overhead as each Voxel resolved the chunk. /// occupancy.setKey(key); /// mean.setKey(key); /// /// // 2. Set one Voxel key directly, the subsequent items are chained and the chunk is resolved once. /// mean.setKey(occupancy.setKey(key)); /// /// // 3. Equivalent, but slightly more readable version of 2. Note this version is open to mistakenly passing a /// // Voxel for the first argument rather than a Key and not actually setting a key. /// ohm::setVoxelKey(key, occupancy, mean); /// /// // Next we look at some different ways of setting occupancy. Again, only 1 need be used. /// // A) Set occupancy directly: /// occupancy.data() = map.hitValue(); /// /// // B) Use helper function. Assumes occupancy.isValid() is true /// ohm::integrateHit(occupancy); // in VoxelOccupancy.h /// /// // Finally update the voxel mean. Using both techniques below results in adding the sample twice, so the /// // mean count will be 2. /// // i. Safe version, with mean.isValid() may be false. /// ohm::updatePositionSafe(mean, sample); // in VoxelMean.h /// // ii. Unchecked version, where mean.isValid() is assumed to be true. We check explicitly because we have not /// // checked mean.isLayerValid() above. /// if (mean.isValid()) /// { /// ohm::updatePositionUnsafe(mean, sample); // in VoxelMean.h /// } /// } ///} /// /// void walkLine(const ohm::OccupancyMap &map) ///{ /// // Create a voxel reference for accessing voxel occupancy. /// ohm::Voxel<const float> occupancy(&map, map.layout().occupancyLayer()); /// // Create a voxel reference for accessing VoxelMean. /// ohm::Voxel<const ohm::VoxelMean> mean(&map, map.layout().meanLayer()); /// /// glm::dvec3 sample(0, 0, 0); /// for (int i = 0; i < 12; ++i) // iterate further than the original line /// { /// sample.x = i * map.resolution(); /// const Key key = map.voxelKey(sample); /// /// // Use option 3 from above to set the key. /// // This will not create the chunk if it does not exist because we are using const template types for /// // Voxel. /// ohm::setVoxelKey(key, occupancy, mean); /// /// std::cout << "check map at (" << sample.x << "," << sample.y << "," << sample.z << ")" << std::endl; /// std::cout << "occupancy: "; /// if (!ohm::isUnobservedOrNull(occupancy)) // in VoxelOccupancy.h /// { /// std::cout << occupancy.data() << std::endl; /// } /// else /// { /// std::cout << "unobserved" << std::endl; /// } /// /// // The the voxel position, safely. This will be the voxel centre if VoxelMean is not supported. /// const glm::dvec3 voxel_pos = ohm::positionSafe(mean); // in VoxelMean.h /// std::cout << "position: (" << voxel_pos.x << "," << voxel_pos.y << "," << voxel_pos.z << ")" << std::endl; /// } ///} /// @endcode /// /// @par Lazy update /// A @c Voxel object keeps track of changes made to it's current chunk and voxel. However, it uses a lazy update for /// changing @c MapChunk members such as @c MapChunk::dirty_stamp, @c MapChunk::touched_stamps and /// @c MapChunk::first_valid_index. Retaining a @c Voxel object can lead to cirsumstances whereby these values are out /// of date and subsequent map operations do not consider the @c MapChunk modifier (incorrect stamp values), or being /// indexing the chunk at the wrong location (@c first_valid_index). This lazy update is particularly important to /// consider when using a @c GpuMap as the @c GpuMapCache only uploads data from CPU to GPU memory based on changes to /// the @c MapChunk::touched_stamp values. /// /// A @c Voxel is considered committed when one of the following occurs: /// /// - The @c Voxel is destructed /// - The @c Voxel is @c reset() /// - A call to @c commit() is made /// - The @c Voxel key changes (see below) /// /// Changes to the @c Voxel key provide further subtle complications in that the @c MapChunk stamps will only be updated /// when the new key references a different @c MapChunk (or a null region). /// /// @note The map must outlive the voxel. Generally this will be true when using @c Voxel objects within a limited /// scope. However care must be taken when an @c OccupancyMap and a @c Voxel reference to that map exist in the same /// scope or when performing operations which can invalidate the @c MapLayout or clear the map. In these cases, /// all @c Voxel objects should be explicitly released via @c Voxel::release() . /// /// @tparam T The data type expected to be contained in the @c MapLayer to operate on. Checked for size match with /// layer content. Note that compiler alignment of structures may cause mismatches between the data added to a /// @c MapLayer and the size of @c T as @c MapLayer content will not be padded while @c T may be. /// /// @todo Add validation debug compile flag which validate the various initalisations and data access calls. template <typename T> class Voxel { public: /// Non-const data type for @c T using DataType = typename std::remove_const<T>::type; /// Const or non-const @c OccupancyMap iterator to support construction from an iterator. Saves on resolving /// the @c MapChunk again. using MapIteratorType = typename std::conditional<std::is_const<T>::value, OccupancyMap::const_iterator, OccupancyMap::iterator>::type; /// Const or non-const @c OccupancyMap pointer based on @c T constness using MapTypePtr = typename std::conditional<std::is_const<T>::value, const OccupancyMap *, OccupancyMap *>::type; /// Const or non-const @c MapChunk pointer based on @c T constness using MapChunkPtr = typename std::conditional<std::is_const<T>::value, const MapChunk *, MapChunk *>::type; /// Voxel data pointer - always a @c uint8_t type with @c const added if @c T is @c const . using VoxelDataPtr = typename std::conditional<std::is_const<T>::value, const uint8_t *, uint8_t *>::type; /// Error flag values indicating why initialisation may have failed. enum class Error : uint16_t { kNone = 0, ///< No error kNullMap = (1u << 0u), ///< @c OccupancyMap is null kInvalidLayerIndex = (1u << 1u), ///< The given layer index is invalid. kVoxelSizeMismatch = (1u << 2u), ///< The @c MapLayer voxel size does not match the size of @c T kMapMismatch = (1u << 3u) ///< When two @c Voxel object maps do not match such as in @c setKey() chaining. }; /// Book keeping flags. enum class Flag : uint16_t { kNone = 0, ///< Nothing of note kIsOccupancyLayer = (1u << 0u), ///< Marks that this @c Voxel points to the occupancy layer of @c OccupancyMap. kCompressionLock = (1u << 1u), ///< Indicates the layer's @c VoxelBlock has been retained in @c chunk_. kTouchedChunk = (1u << 2u), ///< Marks that the current @c MapChunk data has been accessed for mutation. kTouchedVoxel = (1u << 3u), ///< Marks that the current voxel data has been accessed for mutation. /// Flag values which are not propagated in copy assignment. kNonPropagatingFlags = kTouchedChunk | kTouchedVoxel | kCompressionLock // NOLINT(hicpp-signed-bitwise) }; /// Empty constructor generating an invalid voxel with no map. Voxel() = default; /// Copy constructor - same type. /// @param other The voxel to copy. Voxel(const Voxel<T> &other); /// RValue constructor - same type. /// @param other The voxel to copy. Voxel(Voxel<T> &&other) noexcept; /// Copy constructor from a different type. Copies the map, chunk and key, but references a different layer/type. /// @param other The base voxel to copy. /// @param layer_index The @c MapLayer to access for the type @c T . template <typename U> Voxel(const Voxel<U> &other, int layer_index); /// Create a @c Voxel reference for @c map and the specified @c layer_index . The map and layer are validated /// (see @c Error flags) and @c isLayerValid() will be true on success. The key is not set so @c isValid() remains /// false. /// @param map The map to access and mutate for non-const @c Voxel types. /// @param layer_index The @c MapLayer to access for the type @c T . Voxel(MapTypePtr map, int layer_index); /// Create a @c Voxel reference for @c map and the specified @c layer_index and reference the voxel at @c key. The /// map and layer are validated (see @c Error flags) and @c isLayerValid() will be true on success. The key is also /// set and @c isValid() will be true for a mutable @c Voxel , creating the @c MapChunk if required. A non-mutable /// @c Voxel will still not be valid in the case where the @p key references a @c MapChunk which does not exist. /// @param map The map to access and mutate for non-const @c Voxel types. /// @param layer_index The @c MapLayer to access for the type @c T . /// @param key The key for the voxel to initially reference. May be changed layer with @c setKey() . Voxel(MapTypePtr map, int layer_index, const Key &key); /// Set the @c Voxel to reference the start of the voxel buffer within the @c MapChunk associated with the given /// @p region_key . This is equivalent to using @c Key(region_key,0,0,0) . /// @param map The map to access and mutate for non-const @c Voxel types. /// @param layer_index The @c MapLayer to access for the type @c T . /// @param region_key The region coordinate key for the chunk to reference. Voxel(MapTypePtr map, int layer_index, const glm::i16vec3 &region_key); /// Create a @c Voxel reference from a @c OccupancyMap::iterator (mutable @c Voxel ) or a /// @c OccupancyMap::const_iterator (const @c Voxel ). This is similar to using the /// @c Voxel(MapTypePtr,layer_index,key) constructor, with the map, chunk and key always coming from the iterator. /// This will never create a @c MapChunk as it is assumed to be valid in the iterator. Voxel(const MapIteratorType &iter, int layer_index); /// Destructor, ensures book keeping operations are completed on the @c MapChunk . inline ~Voxel() { updateTouch(false); } /// Check if the map and layer references are valid and error flags are clear. /// @return True if the @c map() is not null, the @c layerIndex() is valid and @c errorFlags() are zero. inline bool isLayerValid() const { return map_ && layer_index_ >= 0 && error_flags_ == 0; } /// Check if the voxel reference is valid for @c data() calls. /// @return True if @c isLayerValid() and the @c chunk() and @c key() values are non-null. inline bool isValid() const { return isLayerValid() && chunk_ && key_ != Key::kNull && voxel_memory_ != nullptr; } /// Check if the voxel reference is invalid. /// @return The logical negation of @c isValid() inline bool isNull() const { return isLayerValid() && (!chunk_ || key_ == Key::kNull || voxel_memory_ == nullptr); } /// Check if the @c Voxel is a valid voxel reference. This does not check the @c chunk() . /// @return True if @c isValidLayer() and the key is non-null. inline bool isValidReference() const { return isLayerValid() && key_ != Key::kNull; } /// Nullify the @c Voxel . This clears the map, layer, chunk and key values. Book keeping is performed as required. inline void reset() { *this = Voxel<T>(); } /// Commit any oustanding write operations. A @c Voxel object keeps track of changes made to it's current chunk and /// voxel. However, it uses a lazy update for changing @c MapChunk members such as @c MapChunk::dirty_stamp, /// @c MapChunk::touched_stamps and @c MapChunk::first_valid_index . This function ensures inline void commit() { updateTouch(true); } /// Query the pointer to the @c OccupancyMap . /// @return The map pointer. inline MapTypePtr map() const { return map_; } /// Query the pointer to the @c MapChunk . /// @return The chunk pointer. inline MapChunkPtr chunk() const { return chunk_; } /// Query the current @c Key reference. /// @return The current key value. inline Key key() const { return key_; } /// Query the index of the target @c MapLayer in the @c OccupancyMap . /// @return The map layer to target. inline int layerIndex() const { return layer_index_; } /// Query the cached @c MapLayer::dimensions() . /// @return The map layer voxel dimensions. inline glm::u8vec3 layerDim() const { return layer_dim_; } /// Query the status @c Flag values for the voxel. These are generally book keeping flags. /// @return The current status flags. inline unsigned flags() const { return flags_; } /// Query the status @c Error flag values for the voxel. /// @return The current error flags. inline unsigned errorFlags() const { return error_flags_; } /// Set the voxel @c Key . This may create a @c MapChunk for a mutable @c Voxel . /// @param key The key for the voxel to reference. Must be non-null and in range. /// @return `*this` Voxel<T> &setKey(const Key &key); /// Set the voxel @c Key with a pre-resolved @c MapChunk . /// @param key The key for the voxel to reference. Must be non-null and in range. /// @param chunk A pointer to the correct chunk for the @c Key . This must be the correct chunk. /// @return `*this` Voxel<T> &setKey(const Key &key, MapChunkPtr chunk); template <typename U> /// Set the voxel key from another @c Voxel reference. This copies the @c MapChunk from @p other . /// /// Will set the @c Error::kMapMismatch flag if the map pointers do not match between @c this and @p other. /// @param other The voxel to initialise from. /// @return `*this` Voxel<T> &setKey(const Voxel<U> &other); /// Set the voxel reference from an @c OccupancyMap::iterator (mutable) or @c OccupancyMap::const_iterator (const). /// @param iter The iterator to set the voxel reference from. Must be a valid voxel iterator. /// @return `*this` Voxel<T> &setKey(const MapIteratorType &iter); /// Resolve the linearised voxel index into the @c MapChunk layer. @c isValidReference() must be true before /// calling. /// @return The linear voxel index resolved from the key. inline unsigned voxelIndex() const { return ohm::voxelIndex(key_, layer_dim_); } /// Access the data for the current voxel. This is a convenience wrapper for the @c read() function which returns /// the template data type. Only call if @c isValid() is true. /// @return The data for the current voxel. DataType data() const { DataType d; read(&d); return d; } /// Read the current voxel data value. /// /// This reads the data for the current @c voxelIndex() into @p value . This call does no error checking and /// assumes that all pointers and index values have been validated. /// /// @param[out] value Pointer where to write the voxel data of type @c T for the currently referenced voxel. /// @return The read value - i.e., `*value`. inline const DataType &read(DataType *value) const { memcpy(value, voxel_memory_ + sizeof(T) * voxelIndex(), sizeof(T)); return *value; } /// Write the current voxel data @p value . /// /// This writes @p value to the current @c voxelIndex() location. This call does no error checking and /// assumes that all pointers and index values have been validated. This can only be called if @c T is a non const /// type. /// /// @param[in] value Value to write for the current voxel. inline void write(const DataType &value) { detail::VoxelChunkAccess<T>::writeVoxel(voxel_memory_, voxelIndex(), value, unsigned(Flag::kTouchedChunk) | unsigned(Flag::kTouchedVoxel), &flags_); } /// Return a pointer to the start of the voxel memory for the current chunk. /// @c isValid() must be true before calling. /// @return A pointer to the voxel memory for the currently referenced chunk. inline VoxelDataPtr voxelMemory() const { return voxel_memory_; } /// Attempt to step the voxel reference to the next voxel in the current @c MapChunk . /// /// This first validates @c isValidReference() before attempting to modify the @c key() . On success, the /// key will reference the next @c voxelIndex() in the @c MapChunk . /// /// @return True on success. bool nextInRegion(); /// Swap this voxel content with @p other . /// @param other The voxel to exchange data with. void swap(Voxel &other); /// Assignment operator. Performs book keeping before assignment. /// /// Note that some @c Flag values will not be copied by the assignment. See @c Flag::kNonPropagatingFlags . /// @param other The voxel reference to assign from. /// @return `*this` Voxel &operator=(const Voxel<T> &other); /// Move assignent operator. /// @param other The rvalue reference to move data from. /// @return `*this` Voxel &operator=(Voxel<T> &&other) noexcept; protected: /// Internal key set function. Performs book keeping for @c Flag::kIsOccupancyLayer and @c Flag::kTouchedVoxel . /// @param key The key value to set. inline void setKeyInternal(const Key &key) { updateVoxelTouch(); key_ = key; } /// Internal chunk set function. Performs book keeping for @c Flag::kTouchedChunk . /// @param chunk The chunk to set the voxel to reference. inline void setChunk(MapChunkPtr chunk) { if (chunk_ != chunk) { updateChunkTouchAndCompression(false); chunk_ = chunk; if (chunk_ && layer_index_ != -1) { chunk_->voxel_blocks[layer_index_]->retain(); flags_ |= unsigned(Flag::kCompressionLock); voxel_memory_ = chunk_->voxel_blocks[layer_index_]->voxelBytes(); } else { voxel_memory_ = nullptr; } } } /// Validate the @c layerIndex() . May invalidate the layer index and set @c Error flag values. void validateLayer(); /// Perform book keeping for the currently referenced voxel. Handles @c Flag::kIsOccupancyLayer and /// @c Flag::kTouchedVoxel . This only needs to do work when @c Flag::kIsOccupancyLayer is true by updating /// @c MapChunk::first_valid_index the @c Flag::kTouchedVoxel has been set. @c Flag::kTouchedVoxel is cleared. /// /// Safe to call when no book keeping needs to be done or the voxel reference is invalid. void updateVoxelTouch(); /// Perform book keeping for the current chunk. Handles @c Flag::kTouchedChunk by ensuring @c OccupancyMap::touch() /// is called then updating the @c MapChunk::dirty_stamp and the @c MapChunk::touched_stamps for the referenced /// layer. @c Flag::kTouchedChunk is cleared. /// /// Safe to call when no book keeping needs to be done or the voxel reference is invalid. /// /// @param retain_chunk True to keep the chunk memory retained (uncompressed), false to release the chunk and set it /// to null. Should only be true for @c commit(), where the voxel reference is also retained. void updateChunkTouchAndCompression(bool retain_chunk); /// Full book keeping calling @c updateVoxelTouch() and @c updateChunkTouchAndCompression() . /// /// Safe to call when no book keeping needs to be done or the voxel reference is invalid. /// @param retain_chunk True to keep the chunk memory retained (uncompressed), false to release the chunk and set it /// to null. Should only be true for @c commit(), where the voxel reference is also retained. inline void updateTouch(bool retain_chunk) { updateVoxelTouch(); updateChunkTouchAndCompression(retain_chunk); } private: VoxelDataPtr voxel_memory_ = nullptr; ///< A pointer to the start of voxel memory within the current chunk. MapTypePtr map_ = nullptr; ///< @c OccupancyMap pointer MapChunkPtr chunk_ = nullptr; ///< Current @c MapChunk pointer - may be null even with a valid key reference. Key key_ = Key::kNull; ///< Current voxel @c Key reference. int layer_index_ = -1; ///< The target map layer. Validated on construction. glm::u8vec3 layer_dim_{ 0, 0, 0 }; ///< The voxel dimensions of the layer. uint16_t flags_ = 0; ///< Current status/book keeping flags uint16_t error_flags_ = 0; ///< Current error flags. }; /// @overload template <typename KeyType, typename T> void setVoxelKey2(const KeyType &key, Voxel<T> &voxel) { voxel.setKey(key); } /// A less safe version of @c setVoxelKey(). This version isn't as safe as it accepts any @c KeyType , which opens up /// up bugs where the first argument is an invalid @c Voxel reference, rather than the expected usage where the first /// argument is a @c Key or @c OccupancyMap::iterator . /// @param key The object from which to set the key value. Expected to be a @c Key , @c OccupancyMap::iterator or /// @c OccupancyMap::const_iterator /// @param voxel The first @c Voxel to set the key for. /// @param args Additional @c Voxel references. template <typename KeyType, typename T, typename... Args> void setVoxelKey2(const KeyType &key, Voxel<T> &voxel, Args &...args) { setVoxelKey2(voxel.setKey(key), args...); } /// @overload template <typename T> void setVoxelKey(const Key &key, Voxel<T> &voxel) { voxel.setKey(key); } /// @overload template <typename T> void setVoxelKey(const OccupancyMap::iterator &iter, Voxel<T> &voxel) { voxel.setKey(iter); } /// @overload template <typename T> void setVoxelKey(const OccupancyMap::const_iterator &iter, Voxel<T> &voxel) { voxel.setKey(iter); } /// Set the key value for multiple @c Voxel objects with reduced overhead by resolving the @c MapChunk once. /// @param key The object from which to set the key value. /// @param voxel The first @c Voxel to set the key for. /// @param args Additional @c Voxel references. template <typename T, typename... Args> void setVoxelKey(const Key &key, Voxel<T> &voxel, Args &...args) { setVoxelKey2(key, voxel, args...); } /// Set the key value for multiple @c Voxel from a map iterator. /// @param iter The occupancy map iterator to set from. /// @param voxel The first @c Voxel to set the key for. Must be a mutable voxel. /// @param args Additional @c Voxel references. template <typename T, typename... Args> void setVoxelKey(const OccupancyMap::iterator &iter, Voxel<T> &voxel, Args &...args) { setVoxelKey2(iter, voxel, args...); } /// Set the key value for multiple @c Voxel from a map iterator. /// @param iter The occupancy map iterator to set from. /// @param voxel The first @c Voxel to set the key for. Must be a const voxel. /// @param args Additional @c Voxel references. template <typename T, typename... Args> void setVoxelKey(const OccupancyMap::const_iterator &iter, Voxel<T> &voxel, Args &...args) { setVoxelKey2(iter, voxel, args...); } template <typename T> Voxel<T>::Voxel(const Voxel<T> &other) : map_(other.map_) , chunk_(nullptr) , key_(other.key_) , layer_index_(other.layer_index_) , layer_dim_(other.layer_dim_) , flags_(other.flags_ & ~unsigned(Flag::kNonPropagatingFlags)) , error_flags_(other.error_flags_) { // Do not set chunk or voxel_memory_ pointers directly. Use the method call to ensure flags are correctly // maintained. setChunk(other.chunk_); } template <typename T> Voxel<T>::Voxel(Voxel<T> &&other) noexcept : voxel_memory_(std::exchange(other.voxel_memory_, nullptr)) , map_(std::exchange(other.map_, nullptr)) , chunk_(std::exchange(other.chunk_, nullptr)) , key_(std::exchange(other.key_, Key::kNull)) , layer_index_(std::exchange(other.layer_index_, -1)) , layer_dim_(std::exchange(other.layer_dim_, glm::u8vec3(0, 0, 0))) , flags_(std::exchange(other.flags_, 0u)) , error_flags_(std::exchange(other.error_flags_, 0u)) {} template <typename T> template <typename U> Voxel<T>::Voxel(const Voxel<U> &other, int layer_index) : map_(other.map()) , chunk_(nullptr) , key_(other.key()) , layer_index_(layer_index) , flags_(other.flags() & ~unsigned(Flag::kNonPropagatingFlags)) , error_flags_(other.errorFlags()) { validateLayer(); // Do not set chunk or voxel_memory_ pointers directly. Use the method call to ensure flags are correctly // maintained. setChunk(other.chunk()); } template <typename T> Voxel<T>::Voxel(MapTypePtr map, int layer_index) : map_(map) , layer_index_(layer_index) { validateLayer(); } template <typename T> Voxel<T>::Voxel(MapTypePtr map, int layer_index, const Key &key) : Voxel<T>(map, layer_index) { if (map) { setKey(key); } } template <typename T> Voxel<T>::Voxel(MapTypePtr map, int layer_index, const glm::i16vec3 &region_key) : Voxel<T>(map, layer_index, Key(region_key, 0, 0, 0)) {} template <typename T> Voxel<T>::Voxel(const MapIteratorType &iter, int layer_index) : Voxel<T>(iter.map(), layer_index, iter.key()) { setChunk(iter.chunk()); } template <typename T> Voxel<T> &Voxel<T>::setKey(const Key &key) { setKeyInternal(key); if (!chunk_ || chunk_->region.coord != key.regionKey()) { // Create chunk if not read only access. setChunk(detail::VoxelChunkAccess<T>::chunk(map_, key)); } return *this; } template <typename T> Voxel<T> &Voxel<T>::setKey(const Key &key, MapChunkPtr chunk) { setKeyInternal(key); setChunk(chunk); return *this; } template <typename T> Voxel<T> &Voxel<T>::setKey(const MapIteratorType &iter) { setKeyInternal(*iter); setChunk(iter.chunk()); return *this; } template <typename T> template <typename U> Voxel<T> &Voxel<T>::setKey(const Voxel<U> &other) { setKeyInternal(other.key()); setChunk(other.chunk()); error_flags_ |= !(map_ == other.map()) * unsigned(Error::kMapMismatch); return *this; } template <typename T> bool Voxel<T>::nextInRegion() { if (isValidReference()) { if (key_.localKey().x + 1 == layer_dim_.x) { if (key_.localKey().y + 1 == layer_dim_.y) { if (key_.localKey().z + 1 == layer_dim_.z) { return false; } key_.setLocalKey(glm::u8vec3(0, 0, key_.localKey().z + 1)); } else { key_.setLocalKey(glm::u8vec3(0, key_.localKey().y + 1, key_.localKey().z)); } } else { key_.setLocalAxis(0, key_.localKey().x + 1); } return true; } return false; } template <typename T> void Voxel<T>::swap(Voxel &other) { std::swap(voxel_memory_, other.voxel_memory_); std::swap(map_, other.map_); std::swap(chunk_, other.chunk_); std::swap(key_, other.key_); std::swap(layer_index_, other.layer_index_); std::swap(layer_dim_, other.layer_dim_); std::swap(flags_, other.flags_); std::swap(error_flags_, other.error_flags_); } template <typename T> Voxel<T> &Voxel<T>::operator=(const Voxel<T> &other) { if (&other != this) { updateTouch(false); // Note: this will set the chunk to null. map_ = other.map_; setKeyInternal(other.key_); layer_index_ = other.layer_index_; layer_dim_ = other.layer_dim_; flags_ = other.flags_ & ~unsigned(Flag::kNonPropagatingFlags); error_flags_ = other.error_flags_; // Do not set chunk or voxel_memory_ pointers directly. Use the method call to ensure flags are correctly // maintained. voxel_memory_ = nullptr; // About to be resolved in setChunk() setChunk(other.chunk_); } return *this; } template <typename T> Voxel<T> &Voxel<T>::operator=(Voxel<T> &&other) noexcept { Voxel<T> copy(std::move(other)); swap(copy); return *this; } template <typename T> void Voxel<T>::validateLayer() { if (layer_index_ >= 0) { const MapLayer *layer = map_ ? map_->layout().layerPtr(layer_index_) : nullptr; if (!map_) { error_flags_ |= unsigned(Error::kNullMap); } else if (!layer) { // Invalid layer. error_flags_ |= unsigned(Error::kInvalidLayerIndex); } else if (layer->voxelByteSize() != sizeof(T)) { // Incorrect layer size. error_flags_ |= unsigned(Error::kVoxelSizeMismatch); } else { layer_dim_ = layer->dimensions(map_->regionVoxelDimensions()); } flags_ &= ~unsigned(Flag::kIsOccupancyLayer); flags_ |= (layer && map_ && layer_index_ == map_->layout().occupancyLayer()) * unsigned(Flag::kIsOccupancyLayer); } } template <typename T> void Voxel<T>::updateVoxelTouch() { if ((flags_ & unsigned(Flag::kIsOccupancyLayer) | unsigned(Flag::kTouchedVoxel)) && chunk_) { detail::VoxelChunkAccess<T>::touch(chunk_, voxelIndex()); } flags_ &= ~unsigned(Flag::kTouchedVoxel); } template <typename T> void Voxel<T>::updateChunkTouchAndCompression(bool retain_chunk) { if (map_ && chunk_) { if (flags_ & unsigned(Flag::kTouchedChunk)) { detail::VoxelChunkAccess<T>::touch(map_, chunk_, layer_index_); } if (!retain_chunk && (flags_ & unsigned(Flag::kCompressionLock))) { chunk_->voxel_blocks[layer_index_]->release(); chunk_ = nullptr; } } // Always clear Flag::kTouchedChunk however, we only clear Flag::kCompressionLock if we are not retaining the chunk. auto clear_flags = unsigned(Flag::kTouchedChunk); clear_flags |= !!retain_chunk * unsigned(Flag::kCompressionLock); flags_ &= ~clear_flags; } } // namespace ohm #endif // OHMVOXEL_H
csiro-robotics/ohm
<|start_filename|>Makefile<|end_filename|> DOCUMENT := dialogue view: $(DOCUMENT).pdf xdg-open $< .PHONY: $(DOCUMENT).pdf $(DOCUMENT).pdf: latexmk -pdf $(DOCUMENT) .PHONY: $(DOCUMENT).icml $(DOCUMENT).icml: pandoc -s -f latex -t icml -o $@ --bibliography=$(DOCUMENT).bib -C --csl=splncs.csl $(DOCUMENT).tex .PHONY: $(DOCUMENT).docx $(DOCUMENT).docx: pandoc -s -f latex -t docx -o $@ --bibliography=$(DOCUMENT).bib -C --csl=splncs.csl $(DOCUMENT).tex .PHONY: $(DOCUMENT).xml $(DOCUMENT).xml: latexml $(DOCUMENT) --destination=$@ .PHONY: $(DOCUMENT).html $(DOCUMENT).html: $(DOCUMENT).xml latexmlpost --format=html5 --nopresentationmathml --mathsvg --svg --destination=$@ $< .PHONY: $(DOCUMENT).rtf $(DOCUMENT).rtf: $(DOCUMENT).html soffice --convert-to 'rtf:Rich Text Format' $(DOCUMENT).html --headless clean: latexmk -C -pdf $(DOCUMENT) rm -fv *-converted-to.pdf rm -fv $(DOCUMENT).{xml,html,icml,docx,rtf,pdf,bbl} rm -fv LaTeXML.cache LaTeXML.css ltx-article.css
nlpub/dialogue-latex
<|start_filename|>src/test/kotlin/net/corda/yo/Tests.kt<|end_filename|> package net.corda.yo import net.corda.core.node.services.queryBy import net.corda.core.node.services.vault.QueryCriteria.VaultCustomQueryCriteria import net.corda.core.node.services.vault.builder import net.corda.core.utilities.getOrThrow import net.corda.node.internal.StartedNode import net.corda.testing.* import net.corda.testing.contracts.DUMMY_PROGRAM_ID import net.corda.testing.contracts.DummyState import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetwork.MockNode import net.corda.yo.YoState.YoSchemaV1.PersistentYoState import org.junit.After import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class YoFlowTests { lateinit var net: MockNetwork lateinit var a: StartedNode<MockNode> lateinit var b: StartedNode<MockNode> @Before fun setup() { setCordappPackages("net.corda.yo") net = MockNetwork() val nodes = net.createSomeNodes(2) a = nodes.partyNodes[0] b = nodes.partyNodes[1] net.runNetwork() } @After fun tearDown() { unsetCordappPackages() net.stopNodes() } @Test fun flowWorksCorrectly() { val yo = YoState(a.info.legalIdentities.first(), b.info.legalIdentities.first()) val flow = YoFlow(b.info.legalIdentities.first()) val future = a.services.startFlow(flow).resultFuture net.runNetwork() val stx = future.getOrThrow() // Check yo transaction is stored in the storage service. val bTx = b.services.validatedTransactions.getTransaction(stx.id) assertEquals(bTx, stx) print("bTx == $stx\n") // Check yo state is stored in the vault. b.database.transaction { // Simple query. val bYo = b.services.vaultService.queryBy<YoState>().states.single().state.data assertEquals(bYo.toString(), yo.toString()) print("$bYo == $yo\n") // Using a custom criteria directly referencing schema entity attribute. val expression = builder { PersistentYoState::yo.equal("Yo!") } val customQuery = VaultCustomQueryCriteria(expression) val bYo2 = b.services.vaultService.queryBy<YoState>(customQuery).states.single().state.data assertEquals(bYo2.yo, yo.yo) print("$bYo2 == $yo\n") } } } class YoContractTests { @Before fun setup() { setCordappPackages("net.corda.yo", "net.corda.testing.contracts") } @After fun tearDown() { unsetCordappPackages() } @Test fun yoTransactionMustBeWellFormed() { // A pre-made Yo to Bob. val yo = YoState(ALICE, BOB) // Tests. ledger { // Input state present. transaction { input(DUMMY_PROGRAM_ID) { DummyState() } command(ALICE_PUBKEY) { YoContract.Send() } output(YO_CONTRACT_ID) { yo } this.failsWith("There can be no inputs when Yo'ing other parties.") } // Wrong command. transaction { output(YO_CONTRACT_ID) { yo } command(ALICE_PUBKEY) { DummyCommandData } this.failsWith("") } // Command signed by wrong key. transaction { output(YO_CONTRACT_ID) { yo } command(MINI_CORP_PUBKEY) { YoContract.Send() } this.failsWith("The Yo! must be signed by the sender.") } // Sending to yourself is not allowed. transaction { output(YO_CONTRACT_ID) { YoState(ALICE, ALICE) } command(ALICE_PUBKEY) { YoContract.Send() } this.failsWith("No sending Yo's to yourself!") } transaction { output(YO_CONTRACT_ID) { yo } command(ALICE_PUBKEY) { YoContract.Send() } this.verifies() } } } }
roger3cev/yo-cordapp
<|start_filename|>src/pages/account/component.js<|end_filename|> import React, { PureComponent } from 'react' import { StyleSheet, View, Text, Button } from 'react-native' import { Navigation } from 'react-native-navigation' const styles = StyleSheet.create({ login: { margin: 20, marginBottom: 60, justifyContent: 'flex-end', flex: 1 } }) export class Account extends PureComponent { visitProfile = () => { const { navigator } = this.props navigator.push({ screen: 'githubnative.Profile', title: 'Profile', animated: true }) } render () { const { token, login, logout } = this.props return ( <View style={styles.login}> <Button onPress={this.visitProfile} title='Profile' style={{fontSize: 18, marginTop: 10}} /> { token ? ( <Button onPress={logout} style={{fontSize: 18, marginTop: 10}} color='red' title='Logout' /> ) : ( <Button onPress={login} style={{fontSize: 18, marginTop: 10}} color='#007aff' title='Login' /> ) } </View> ) } } export default Account <|start_filename|>src/redux/code/actionTypes.js<|end_filename|> export default { SET_REPO_CONTENT: 'SET_REPO_CONTENT', SET_RAW_CONTENT: 'SET_RAW_CONTENT', GO_BACK: 'GO_BACK' } <|start_filename|>src/pages/search/component.js<|end_filename|> import React, { PureComponent } from 'react' import { StyleSheet, TextInput, View, Text, ScrollView, SegmentedControlIOS, ActivityIndicator, TouchableOpacity } from 'react-native' import { RepoItem, UserItem } from '../../components' const styles = StyleSheet.create({ list: { flex: 1, flexDirection: 'column' }, inputWrapper: { borderColor: 'rgba(0, 0, 0, 0.2)', borderBottomWidth: 1, marginBottom: 8 }, searchInput: { padding: 8, height: 40 } }) export class Search extends PureComponent { visitProfile = (login) => { const { fetchUser, navigator } = this.props fetchUser(login) navigator.push({ screen: 'githubnative.Profile', title: login, animated: true }) } visitRepo = repo => { const { navigator } = this.props navigator.push({ screen: 'githubnative.Repo', title: repo.name || repo.full_name, animated: true }) } renderResultList = () => { const { results, category, loading, navigator } = this.props if (!loading && !results.length) return console.log(results) if (loading) { return ( <ActivityIndicator /> ) } if (category === 0) { console.log('at user') return ( <ScrollView> { results.map((n, index) => ( <TouchableOpacity key={index} onPress={() => this.visitProfile(n.login)}> <UserItem user={n} /> </TouchableOpacity> )) } </ScrollView> ) } else { return ( <ScrollView> { results.map((n, index) => ( <TouchableOpacity onPress={() => this.visitRepo(n)} key={index}> <RepoItem repo={n} /> </TouchableOpacity> )) } </ScrollView> ) } } render () { const { text, category, setSearchText, setSearchCategory, searchUsersOrRepos, } = this.props return ( <View style={styles.list}> <View style={styles.inputWrapper}> <TextInput placeholder='Search' style={styles.searchInput} onChangeText={text => setSearchText(text)} onSubmitEditing={searchUsersOrRepos} value={text} returnKeyType='search' enablesReturnKeyAutomatically={true} editable={true} /> </View> <SegmentedControlIOS values={['Users', 'Repos']} selectedIndex={category} style={{marginLeft: 8, marginRight: 8}} onChange={({ nativeEvent: { selectedSegmentIndex } }) => setSearchCategory(selectedSegmentIndex)} tintColor='#373838' /> <View style={{marginTop: 10}}> {this.renderResultList()} </View> </View> ) } } export default Search <|start_filename|>src/pages/repo/component.js<|end_filename|> import React, { PureComponent } from 'react' import fecha from 'fecha' import { ActivityIndicator, TouchableOpacity, ScrollView, StyleSheet, Button, Image, View, Text, } from 'react-native' import isEmptyObject from 'is-empty-object' import { RepoItem } from '../../components' export class Repo extends PureComponent { viewCode = () => { const { navigator } = this.props navigator.push({ screen: 'githubnative.Tree', title: 'Tree', animated: true }) } render () { const { repo, loading } = this.props if (loading || isEmptyObject(repo)) { return ( <ActivityIndicator style={{marginTop: 40}}/> ) } return ( <View style={styles.repo}> <View style={styles.breakdown}> <Image source={{uri: repo.owner.avatar_url}} style={styles.avatar} /> <View style={styles.repoDescription}> <Text style={styles.name}>{repo.name}</Text> <Text style={styles.description}>{repo.description}</Text> </View> </View> <View style={styles.detailRow}> <Text style={styles.statItem}>Stars {repo.stargazers_count}</Text> <Text style={styles.statItem}>Issues {repo.open_issues}</Text> <Text style={styles.statItem}>Forks {repo.forks_count}</Text> </View> <View style={styles.detailItem}> <Text>Updated</Text> <Text>{fecha.format(new Date(repo.updated_at), 'M/D/YY h:mm A')}</Text> </View> <TouchableOpacity onPress={this.viewCode}> <View style={styles.detailItem}> <Text>View Code</Text> <Text>{repo.language}</Text> </View> </TouchableOpacity> </View> ) } } export default Repo const styles = StyleSheet.create({ repo: { flex: 1, padding: 20 }, avatar: { height: 60, width: 60, borderRadius: 30, marginRight: 10 }, repoDescription: { flex: 1 }, name: { fontSize: 20 }, description: { fontSize: 14, color: 'gray' }, breakdown: { flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', paddingBottom: 10 }, detailRow: { flexDirection: 'row', width: '100%', alignItems: 'center', justifyContent: 'space-around', padding: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', paddingBottom: 10 }, detailItem: { flexDirection: 'row', width: '100%', alignItems: 'center', justifyContent: 'space-between', padding: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', paddingBottom: 10 }, statItem: { alignItems: 'center' } }) <|start_filename|>src/pages/account/index.js<|end_filename|> import Account from './container' export default Account <|start_filename|>src/pages/notifications/index.js<|end_filename|> import Notifications from './container' export default Notifications <|start_filename|>src/redux/search/actions.js<|end_filename|> import { searchRepos, searchUsers } from '../../api/github-api' import { requestSearch, receiveSearch } from '../loading/actions' import t from './actionTypes' export function setSearchText (text) { return { type: t.SET_SEARCH_TEXT, text } } export function setSearchCategory (category) { return dispatch => { dispatch(setSearchText('')) dispatch(setSearchResults([])) dispatch({ type: t.SET_SEARCH_CATEGORY, category }) } } function setSearchResults (results) { return { type: t.SET_SEARCH_RESULTS, results } } export function searchUsersOrRepos () { return (dispatch, getState) => { const state = getState() const { text, category } = state.search let searchToRun if (category === 0) { searchToRun = searchUsers } else { searchToRun = searchRepos } dispatch(requestSearch()) console.log(text) searchToRun(text) .then(({ data: { items } }) => { dispatch(receiveSearch()) dispatch(setSearchResults(items)) }) .catch(err => { dispatch(receiveSearch()) }) } } <|start_filename|>src/pages/repos/component.js<|end_filename|> import React, { PureComponent } from 'react' import sortOn from 'sort-on' import { StyleSheet, TextInput, View, Text, ScrollView, RefreshControl, TouchableOpacity } from 'react-native' import { RepoItem } from '../../components' const styles = StyleSheet.create({ list: { flex: 1 } }) export class Repos extends PureComponent { visitRepo = repo => { const { navigator } = this.props navigator.push({ screen: 'githubnative.Repo', title: repo.name || repo.full_name, animated: true }) } render () { const { list, loading, fetchRepos, navigator } = this.props return ( <View style={styles.list}> <ScrollView style={{height: 0}} refreshControl={ <RefreshControl refreshing={loading} onRefresh={fetchRepos} tintColor='black' title='Loading...' titleColor='black' colors={['#ff0000', '#00ff00', '#0000ff']} progressBackgroundColor='#ffff00' /> } > { list.map((n, index) => ( <TouchableOpacity onPress={() => this.visitRepo(n)} key={index}> <RepoItem repo={n} /> </TouchableOpacity> )) } </ScrollView> </View> ) } } export default Repos <|start_filename|>src/pages/tree/index.js<|end_filename|> import Tree from './container' export default Tree <|start_filename|>src/pages/repo/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import Component from './component' function mapStateToProps ({ repo, loading }) { return { repo: repo.data, loading: loading.repos } } function mapDispatchToProps (dispatch) { return {} } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/redux/trending/reducer.js<|end_filename|> import t from './actionTypes' const initialState = { list: [], language: 'any', time: '8' } export default (state = initialState, action) => { switch (action.type) { case t.SET_TRENDING: return { ...state, list: action.trending } case t.SET_TRENDING_LANGUAGE: return { ...state, language: action.language } case t.SET_TRENDING_TIME: return { ...state, time: action.time } default: return state } } <|start_filename|>src/components/index.js<|end_filename|> export * from './repo-item' export * from './user-item' <|start_filename|>src/redux/notifications/actionTypes.js<|end_filename|> export default { SET_NOTIFICATIONS: 'SET_NOTIFICATIONS' } <|start_filename|>src/pages/notifications/component.js<|end_filename|> import React, { PureComponent } from 'react' import { StyleSheet, TextInput, View, Text, ScrollView, RefreshControl, Linking, TouchableOpacity } from 'react-native' import { partial } from 'ap' import fecha from 'fecha' const styles = StyleSheet.create({ list: { flex: 1 }, item: { width: '100%', paddingLeft: 20, paddingRight: 20, paddingTop: 10, paddingBottom: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)' }, title: { fontSize: 14, fontWeight: 'bold' }, repo: { fontSize: 16 } }) export class Notifications extends PureComponent { state = { url: null } focusNotification = ({ url }) => { // Linking.openURL(`https://github.com/notifications`) } render () { // const { notifications, url } = this.state const { list, loading, fetchNotifications, navigator } = this.props navigator.setTabBadge({ badge: list.length }) if (!list) return null return ( <View style={styles.list}> <ScrollView style={{height: 0}} refreshControl={ <RefreshControl refreshing={loading} onRefresh={fetchNotifications} tintColor='black' title='Loading...' titleColor='black' colors={['#ff0000', '#00ff00', '#0000ff']} progressBackgroundColor='#ffff00' /> } > { list.map((n, index) => ( <TouchableOpacity onPress={partial(this.focusNotification, n)} key={index}> <View style={styles.item}> <Text style={styles.title}>{n.subject.title}</Text> <Text style={styles.repo}>{n.repository.full_name}</Text> <Text>{fecha.format(new Date(n.updated_at), 'M/D/YY h:mm A')} </Text> </View> </TouchableOpacity> )) } </ScrollView> </View> ) } } export default Notifications <|start_filename|>src/redux/user/actions.js<|end_filename|> import OAuthManager from 'react-native-oauth' import t from './actionTypes' import { saveToken, getCurrentUserProfile } from '../../api/github-api' import config from '../../../config.json' import { fetchNotifications } from '../notifications/actions' import { setUserProfile } from '../profile/actions' import { fetchTimeline } from '../timeline/actions' import { fetchTrending } from '../trending/actions' import { fetchIssues } from '../issues/actions' import { fetchRepos } from '../repos/actions' const manager = new OAuthManager('githubnative') manager.configure(config) export function fetchProfile () { return dispatch => { dispatch(requestProfile()) getCurrentUserProfile() .then(({ data }) => { dispatch(receiveProfile()) dispatch(setLogin(data.login)) dispatch(setUserProfile(data)) }) .catch(err => { dispatch(receiveProfile()) }) } } function setLogin (login) { return { type: t.SET_LOGIN, login } } export function login () { return dispatch => { manager.authorize('github', {scopes: 'user repo notifications'}) .then(({ response }) => { const token = response.credentials.accessToken dispatch(setToken(token)) }) .catch(err => console.log('There was an error')) } } export function logout () { return dispatch => { manager.deauthorize('github') } } export function setToken (token) { saveToken(token) return dispatch => { dispatch({ type: t.SET_TOKEN, token }) // get initial data dispatch(fetchNotifications()) dispatch(fetchTimeline()) dispatch(fetchTrending()) dispatch(fetchIssues()) dispatch(fetchRepos()) dispatch(fetchProfile()) } } <|start_filename|>src/pages/search/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { setSearchText, setSearchCategory, searchUsersOrRepos } from '../../redux/search/actions' import { fetchUser } from '../../redux/profile/actions' import Component from './component' function mapStateToProps ({ search, loading }) { return { text: search.text, category: search.category, results: search.results, loading: loading.search } } function mapDispatchToProps (dispatch) { return { setSearchText: v => dispatch(setSearchText(v)), setSearchCategory: v => dispatch(setSearchCategory(v)), searchUsersOrRepos: () => dispatch(searchUsersOrRepos()), fetchUser: (login) => dispatch(fetchUser(login)) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/redux/trending/actions.js<|end_filename|> import sortOn from 'sort-on' import t from './actionTypes' import { getTrending } from '../../api/trending-api' import { requestTrending, receiveTrending } from '../loading/actions' export function fetchTrending () { return (dispatch, getState) => { const state = getState() const { time, language } = state.trending dispatch(requestTrending()) getTrending({time, language}) .then(({ repos }) => { dispatch(receiveTrending()) const data = sortOn(repos, '-stargazers_count') dispatch(setTrending(data)) }) .catch(err => { dispatch(receiveTrending()) }) } } export function setTrending (trending) { return { type: t.SET_TRENDING, trending } } export function setLanguage (language) { return dispatch => { dispatch({ type: t.SET_TRENDING_LANGUAGE, language }) dispatch(fetchTrending()) } } export function setTime (time) { return dispatch => { dispatch({ type: t.SET_TRENDING_TIME, time }) dispatch(fetchTrending()) } } <|start_filename|>src/pages/repo/index.js<|end_filename|> import Repo from './container' export default Repo <|start_filename|>src/pages/profile/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchTrending } from '../../redux/trending/actions' import Component from './component' const mapStateToProps = ({ profile, repos, loading }) => ({ profile: profile.profile, repos: repos.list, loading: loading.profile }) // function mapDispatchToProps (dispatch) { // return { // fetchTrending: () => dispatch(fetchTrending()) // } // } export default connect( mapStateToProps, // mapDispatchToProps )(Component) <|start_filename|>src/redux/profile/reducer.js<|end_filename|> import t from './actionTypes' const initialState = { profile: {} } export default (state = initialState, action) => { switch (action.type) { case t.SET_USER_PROFILE: return { ...state, profile: action.profile } default: return state } } <|start_filename|>src/redux/index.js<|end_filename|> import { combineReducers, createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import user from './user/reducer' import notifications from './notifications/reducer' import timeline from './timeline/reducer' import trending from './trending/reducer' import loading from './loading/reducer' import profile from './profile/reducer' import search from './search/reducer' import issues from './issues/reducer' import repos from './repos/reducer' import repo from './repo/reducer' import code from './code/reducer' const reducers = combineReducers({ user, code, notifications, timeline, issues, repos, repo, loading, trending, profile, search }) export function configureStore () { return createStore(reducers, applyMiddleware(thunk)) } <|start_filename|>src/pages/repos/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchRepos } from '../../redux/repos/actions' import Component from './component' function mapStateToProps (state) { return { list: state.repos.list, loading: state.loading.repos } } function mapDispatchToProps (dispatch) { return { fetchRepos: () => dispatch(fetchRepos()) } } class ComponentContainer extends PureComponent { componentWillMount () { this.props.fetchRepos() } render () { return ( <Component {...this.props} /> ) } } export default connect( mapStateToProps, mapDispatchToProps )(ComponentContainer) <|start_filename|>src/redux/trending/actionTypes.js<|end_filename|> export default { SET_TRENDING: 'SET_TRENDING', SET_TRENDING_LANGUAGE: 'SET_TRENDING_LANGUAGE', SET_TRENDING_TIME: 'SET_TRENDING_TIME' } <|start_filename|>src/router.js<|end_filename|> import React from 'react' import { View, Text } from 'react-native' import { Navigation } from 'react-native-navigation' import { Provider } from 'react-redux' import { configureStore } from './redux' import { login } from './redux/user/actions' import Screens from './screens' const store = configureStore() Screens(store, Provider) // login first thing! store.dispatch(login()) Navigation.startTabBasedApp({ tabs: [ { label: 'Trending', screen: 'githubnative.Trending', title: 'Trending', icon: require('./icons/trending.png') }, { label: 'Timeline', screen: 'githubnative.Timeline', title: 'Timeline', icon: require('./icons/timeline.png') }, { label: 'Notifications', screen: 'githubnative.Notifications', title: 'Notifications', icon: require('./icons/notifications.png') }, { label: 'Issues', screen: 'githubnative.Issues', title: 'Issues', icon: require('./icons/issues.png') }, { label: 'Search', screen: 'githubnative.Search', title: 'Search', icon: require('./icons/search.png') }, { label: 'Account', screen: 'githubnative.Account', title: 'Account', icon: require('./icons/account.png') }, { label: 'Repos', screen: 'githubnative.Repos', title: 'Repos', icon: require('./icons/repos.png') } ] }) // // drawer: { // left: { // screen: 'githubnative.Login' // } // }, // tabsStyle: { // tabBarTranslucent: false // } <|start_filename|>src/pages/account/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { setToken, login, logout } from '../../redux/user/actions' import Component from './component' function mapStateToProps (state) { const { token } = state.user return { token } } function mapDispatchToProps (dispatch) { return { setToken: (t) => dispatch(setToken(t)), login: (t) => dispatch(login(t)), logout: (t) => dispatch(logout(t)) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/screens.js<|end_filename|> import React from 'react' import { View, Text } from 'react-native' import { Navigation } from 'react-native-navigation' import Account from './pages/account' import Issues from './pages/issues' import Notifications from './pages/notifications' import Timeline from './pages/timeline' import Repos from './pages/repos' import Repo from './pages/repo' import EditTrending from './pages/edit-trending' import Trending from './pages/trending' import Profile from './pages/profile' import Search from './pages/search' import Tree from './pages/tree' import Code from './pages/code' export default function (store, Provider) { Navigation.registerComponent('githubnative.Account', () => Account, store, Provider) Navigation.registerComponent('githubnative.Profile', () => Profile, store, Provider) Navigation.registerComponent('githubnative.Notifications', () => Notifications, store, Provider) Navigation.registerComponent('githubnative.Repos', () => Repos, store, Provider) Navigation.registerComponent('githubnative.Repo', () => Repo, store, Provider) Navigation.registerComponent('githubnative.Search', () => Search, store, Provider) Navigation.registerComponent('githubnative.Issues', () => Issues, store, Provider) Navigation.registerComponent('githubnative.Timeline', () => Timeline, store, Provider) Navigation.registerComponent('githubnative.EditTrending', () => EditTrending, store, Provider) Navigation.registerComponent('githubnative.Trending', () => Trending, store, Provider) Navigation.registerComponent('githubnative.Tree', () => Tree, store, Provider) Navigation.registerComponent('githubnative.Code', () => Code, store, Provider) } <|start_filename|>src/pages/code/index.js<|end_filename|> import Code from './container' export default Code <|start_filename|>src/redux/issues/actionTypes.js<|end_filename|> export default { SET_ISSUES: 'SET_ISSUES' } <|start_filename|>src/redux/code/reducer.js<|end_filename|> import t from './actionTypes' const initialState = { content: [], raw: {} } export default (state = initialState, action) => { switch (action.type) { case t.SET_REPO_CONTENT: return { ...state, content: [...state.content, action.content] } case t.SET_RAW_CONTENT: return { ...state, raw: action.content } case t.GO_BACK: // get rid of most recent element state.content.pop() return { ...state, content: [...state.content] } default: return state } } <|start_filename|>src/pages/repos/index.js<|end_filename|> import Repos from './container' export default Repos <|start_filename|>src/pages/edit-trending/component.js<|end_filename|> import React, { PureComponent } from 'react' import sortOn from 'sort-on' import { StyleSheet, View, Text, Button, Picker } from 'react-native' const styles = StyleSheet.create({ list: { flex: 1, justifyContent: 'space-between' } }) export class EditTrending extends PureComponent { dismissModal = () => { const { navigator } = this.props navigator.dismissModal({ animationType: 'slide-down' }) } setTime = value => { this.props.setTime(value) } setLanguage = value => { this.props.setLanguage(value) } render () { const { time, language } = this.props return ( <View style={styles.list}> <View> <Picker selectedValue={time} onValueChange={this.setTime}> <Picker.Item label='Last Day' value='2' /> <Picker.Item label='Last Week' value='8' /> <Picker.Item label='Last Month' value='31' /> <Picker.Item label='Last Year' value='365' /> </Picker> <Picker selectedValue={language} onValueChange={this.setLanguage}> <Picker.Item label='Any' value='any' /> <Picker.Item label='JavaScript' value='js' /> <Picker.Item label='Top Golang' value='go' /> <Picker.Item label='Top iOS' value='ios' /> <Picker.Item label='Top Python' value='python' /> <Picker.Item label='Top CSS' value='css' /> </Picker> </View> <Button title='Close' color='red' style={{height: 80}} onPress={this.dismissModal} /> </View> ) } } export default EditTrending <|start_filename|>src/components/repo-item.js<|end_filename|> import React from 'react' import { Text, View, StyleSheet, Image } from 'react-native' const styles = StyleSheet.create({ item: { width: '100%', paddingLeft: 20, paddingRight: 20, paddingBottom: 10, paddingTop: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)' }, row: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%' }, title: { fontSize: 16, fontWeight: 'bold', marginBottom: 10 }, repo: { fontSize: 16 }, starRow: { flexDirection: 'row', alignItems: 'center' }, star: { height: 15, width: 15, marginRight: 5 } }) export const RepoItem = ({ repo }) => { return ( <View style={styles.item}> <Text style={styles.title}>{repo.name}</Text> <Text style={{marginBottom: 10}}>{repo.description}</Text> <View style={styles.row}> <Text style={styles.repo}>{repo.language}</Text> <View style={styles.starRow}> <Image source={require('../icons/star@2x.png')} style={styles.star} /> <Text>{repo.stargazers_count}</Text> </View> </View> </View> ) } export default RepoItem <|start_filename|>src/redux/repos/actionTypes.js<|end_filename|> export default { SET_REPOS: 'SET_REPOS' } <|start_filename|>src/redux/user/actionTypes.js<|end_filename|> export default { SET_TOKEN: 'SET_TOKEN', SET_LOGIN: 'SET_LOGIN' } <|start_filename|>src/redux/search/reducer.js<|end_filename|> import t from './actionTypes' const initialState = { text: '', category: 0, results: [] } export default (state = initialState, action) => { switch (action.type) { case t.SET_SEARCH_TEXT: return { ...state, text: action.text } case t.SET_SEARCH_CATEGORY: return { ...state, category: action.category } case t.SET_SEARCH_RESULTS: return { ...state, results: action.results } default: return state } } <|start_filename|>src/api/trending-api.js<|end_filename|> export async function getTrending ({ time, language }) { if (language === 'any') { language = 'javascript%20language%3Apython%20language%3Apythonlanguage%3Apython%20language%3Ago%20language%3Ahtml%20language%3Acss%20language%3Ajava' } try { const res = await fetchData(`https://github-trending.now.sh/?language=${language}&daysAgo=${time}`) const { repos } = await res.json() return { repos } } catch (err) { throw err } } function fetchData (url) { return fetch(url) } <|start_filename|>src/pages/edit-trending/index.js<|end_filename|> import EditTrending from './container' export default EditTrending <|start_filename|>src/pages/code/component.js<|end_filename|> import React, { Component } from 'react' import SyntaxHighlighter from 'react-native-syntax-highlighter' import { docco } from 'react-syntax-highlighter/dist/styles' import { atob } from 'abab' import isEmptyObject from 'is-empty-object' import { MarkdownView } from 'react-native-markdown-view' import { ScrollView, View, Text, StyleSheet, ActivityIndicator } from 'react-native' const styles = StyleSheet.create({ list: { flex: 1 } }) export class Code extends Component { render () { const { raw, loading } = this.props if (loading === true || isEmptyObject(raw)) { return ( <ActivityIndicator style={{marginTop: 50}} /> ) } let isMarkdown = raw.name.match(/.md/) let language = '' if (raw.name.match(/.js/)) { language = 'JavaScript' } else if (raw.name.match(/.html/)) { language = 'HTML' } else if (raw.name.match(/.css/)) { language = 'CSS' } else if (raw.name.match(/.json/)) { language = 'JSON' } const content = atob(raw.content) return ( <View style={styles.list}> { isMarkdown ? <MarkdownView>{content}</MarkdownView> : ( <SyntaxHighlighter language={language} style={docco} > {content} </SyntaxHighlighter> ) } </View> ) } } export default Code <|start_filename|>src/pages/tree/component.js<|end_filename|> import React, { PureComponent } from 'react' import { View, Text, Image, StyleSheet, ScrollView, TouchableOpacity } from 'react-native' import { partial } from 'ap' import fecha from 'fecha' const styles = StyleSheet.create({ list: { flex: 1 }, contentLink: { width: '100%', padding: 16, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', flexDirection: 'row', alignItems: 'center' }, fileName: { fontSize: 16 }, typeIcon: { marginRight: 10 } }) export class Tree extends PureComponent { goNested = (path, isDirectory) => { const { navigator, fetchNestedRepoContent } = this.props fetchNestedRepoContent(path, isDirectory) if (!isDirectory) { const { navigator } = this.props navigator.push({ screen: 'githubnative.Code', title: path, animated: true }) } } renderIsntRootBack = () => { const { content, goBack } = this.props if (content.length > 1) { return ( <TouchableOpacity style={styles.contentLink} onPress={goBack} > <Text style={styles.fileName}>..</Text> </TouchableOpacity> ) } } render () { const { content } = this.props const currPath = content[content.length - 1] return ( <View style={styles.list}> <ScrollView style={{flex: 1}} > {this.renderIsntRootBack()} { currPath.map(({ name, type, path }, index) => { const isDirectory = type === 'dir' return ( <TouchableOpacity key={index} style={styles.contentLink} onPress={() => this.goNested(path, isDirectory)} > <Image style={styles.typeIcon} source={ isDirectory ? require('../../icons/dir@2x.png') : require('../../icons/file@2x.png') } /> <Text style={styles.fileName}>{name}</Text> </TouchableOpacity> ) }) } </ScrollView> </View> ) } } export default Tree <|start_filename|>src/pages/search/index.js<|end_filename|> import Search from './container' export default Search <|start_filename|>src/redux/search/actionTypes.js<|end_filename|> export default { SET_SEARCH_TEXT: 'SET_SEARCH_TEXT', SET_SEARCH_CATEGORY: 'SET_SEARCH_CATEGORY', SET_SEARCH_RESULTS: 'SET_SEARCH_RESULTS' } <|start_filename|>src/pages/trending/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchTrending } from '../../redux/trending/actions' import { fetchRepo } from '../../redux/repo/actions' import Component from './component' function mapStateToProps (state) { return { list: state.trending.list, loading: state.loading.trending } } function mapDispatchToProps (dispatch) { return { fetchTrending: () => dispatch(fetchTrending()), fetchRepo: repo => dispatch(fetchRepo(repo)) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/pages/timeline/index.js<|end_filename|> import Timeline from './container' export default Timeline <|start_filename|>src/redux/profile/actionTypes.js<|end_filename|> export default { SET_USER_PROFILE: 'SET_USER_PROFILE' } <|start_filename|>src/api/github-api.js<|end_filename|> const api = 'https://api.github.com' let token = '' export const setToken = t => token = t export const saveToken = t => token = t export const getToken = t => token export async function getNotifications () { try { const res = await fetchData('notifications?all=true') const data = await res.json() return { data } } catch (err) { throw err } } export async function getRepos () { try { const res = await fetchData('user/repos?per_page=1000') const data = await res.json() return { data } } catch (err) { throw err } } export async function getRepo (name) { try { const res = await fetchData(`repos/${name}`) const data = await res.json() return { data } } catch (err) { throw err } } export async function getRepoContent (name) { try { const res = await fetchData(`repos/${name}/contents`) const data = await res.json() return { data } } catch (err) { throw err } } export async function getNestedRepoContent (name, path) { try { const res = await fetchData(`repos/${name}/contents/${path}`) const data = await res.json() return { data } } catch (err) { throw err } } export async function getTimeline () { try { const res = await fetchData('users/hanford/received_events') const data = await res.json() return { data } } catch (err) { throw err } } export async function getIssues () { try { const res = await fetchData('user/issues') const data = await res.json() return { data } } catch (err) { throw err } } export async function getUsersProfile (login) { try { const res = await fetchData(`users/${login}`) const data = await res.json() return { data } } catch (err) { throw err } } export async function getUsersRepos (login) { try { const res = await fetchData(`users/${login}/repos?per_page=1000`) const data = await res.json() return { data } } catch (err) { throw err } } export async function getCurrentUserProfile () { try { const res = await fetchData('user') const data = await res.json() return { data } } catch (err) { throw err } } export async function searchRepos (query) { try { const res = await fetchData(`search/repositories?q=${query}`) const data = await res.json() return { data } } catch (err) { throw err } } export async function searchUsers (query) { try { const res = await fetchData(`search/users?q=${query}`) const data = await res.json() return { data } } catch (err) { throw err } } function fetchData (url) { let ghUrl = `${api}/${url}` let authedUrl = '' console.log(ghUrl) if (url.indexOf('?') > -1) { authedUrl = `${ghUrl}&access_token=${token}` } else { authedUrl = `${ghUrl}?access_token=${token}` } return fetch(authedUrl) } // export function searchRepos (query) { // console.log('searching', query) // return fetch(`${api}/repo/search/${query}`) // .then(r => r.json()) // .then(data => { // return { // data // } // }) // .catch(err => { // throw err // }) // } <|start_filename|>src/redux/repo/actionTypes.js<|end_filename|> export default { SET_REPO: 'SET_REPO' } <|start_filename|>src/pages/timeline/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchUser } from '../../redux/profile/actions' import { fetchRepo } from '../../redux/repo/actions' import { fetchTimeline } from '../../redux/timeline/actions' import Component from './component' function mapStateToProps ({ timeline, loading, user }) { return { list: timeline.list, loading: loading.timeline, user: user.login } } function mapDispatchToProps (dispatch) { return { fetchTimeline: () => dispatch(fetchTimeline()), fetchUser: login => dispatch(fetchUser(login)), fetchRepo: name => dispatch(fetchRepo(name)) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/pages/issues/component.js<|end_filename|> import React, { PureComponent } from 'react' import { StyleSheet, TextInput, View, Text, ScrollView, RefreshControl, TouchableOpacity, Animated } from 'react-native' import { partial } from 'ap' const styles = StyleSheet.create({ list: { flex: 1 }, title: { fontSize: 18, fontWeight: 'bold', marginBottom: 5 }, issue: { fontSize: 16, color: '#00bf8b', fontWeight: 'bold', textAlign: 'right', display: 'flex', }, item: { display: 'flex', flexDirection: 'column', paddingRight: 20, paddingLeft: 20, paddingBottom: 10, paddingTop: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', flex: 1, width: '100%', }, row: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' } }) export class Issues extends PureComponent { state = { scaleValue: new Animated.Value(1) } constructor () { super() this.runAnimation() } runAnimation = () => { this.state.scaleValue.setValue(1) Animated.sequence([ Animated.timing(this.state.scaleValue, { toValue: 2, duration: 500, }), Animated.timing(this.state.scaleValue, { toValue: 1.0, duration: 500, }) ]).start(() => this.runAnimation()) } render () { const { list, loading, fetchIssues } = this.props const { scaleValue } = this.state console.log(scaleValue) return ( <View style={styles.list}> <ScrollView style={{height: 0}} refreshControl={ <RefreshControl refreshing={loading} onRefresh={fetchIssues} tintColor='black' title='Loading...' titleColor='black' colors={['#ff0000', '#00ff00', '#0000ff']} progressBackgroundColor='#ffff00' /> } > { list.map((n, index) => ( <TouchableOpacity key={index}> <View style={styles.item}> <Text style={styles.title}>{n.title}</Text> <View style={styles.row}> <Text>Assigned: {n.assignee.login}</Text> <View> <Animated.Text style={{ color: '#00bf8b', transform: [ {scale: scaleValue} ] }} > {n.state === 'open' ? '•' : 'x'} </Animated.Text> </View> </View> </View> </TouchableOpacity> )) } </ScrollView> </View> ) } } export default Issues <|start_filename|>src/redux/profile/actions.js<|end_filename|> import { getUsersProfile, getUsersRepos } from '../../api/github-api' import { requestProfile, receiveProfile } from '../loading/actions' import { setRepos } from '../repos/actions' import t from './actionTypes' export function setUserProfile (profile) { return { type: t.SET_USER_PROFILE, profile } } export function fetchUser (login) { return dispatch => { dispatch(requestProfile()) Promise.all([ getUsersProfile(login), getUsersRepos(login) ]) .then(data => { dispatch(receiveProfile()) dispatch(setUserProfile(data[0].data)) dispatch(setRepos(data[1].data)) }) .catch(err => { dispatch(receiveProfile()) }) } } <|start_filename|>src/redux/timeline/actions.js<|end_filename|> import t from './actionTypes' import { requestNotifications, receiveNotifications } from '../loading/actions' import { getTimeline } from '../../api/github-api' export function fetchTimeline () { return dispatch => { dispatch(requestNotifications()) getTimeline() .then(({ data }) => { dispatch(receiveNotifications()) dispatch(setTimeline(data)) }) .catch(err => { dispatch(receiveNotifications()) }) } } export function setTimeline (timeline) { return { type: t.SET_TIMELINE, timeline } } <|start_filename|>src/pages/issues/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchIssues } from '../../redux/issues/actions' import Component from './component' function mapStateToProps (state) { return { list: state.issues.list, loading: state.loading.issues } } function mapDispatchToProps (dispatch) { return { fetchIssues: () => dispatch(fetchIssues()) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/pages/code/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchNestedRepoContent, goBack } from '../../redux/code/actions' import Component from './component' function mapStateToProps ({ code, loading }) { return { loading: loading.repos, raw: code.raw } } function mapDispatchToProps (dispatch) { return { } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/redux/loading/actions.js<|end_filename|> import t from './actionTypes' export function requestIssues () { return { type: t.REQUEST_ISSUES } } export function receiveIssues () { return { type: t.RECEIVE_ISSUES } } export function requestRepos () { return { type: t.REQUEST_REPOS } } export function receiveRepos () { return { type: t.RECEIVE_REPOS } } export function requestTimeline () { return { type: t.REQUEST_TIMELINE } } export function receiveTimeline () { return { type: t.RECEIVE_TIMELINE } } export function requestNotifications () { return { type: t.REQUEST_NOTIFICATIONS } } export function receiveNotifications () { return { type: t.RECEIVE_NOTIFICATIONS } } export function requestTrending () { return { type: t.REQUEST_TRENDING } } export function receiveTrending () { return { type: t.RECEIVE_TRENDING } } export function requestProfile () { return { type: t.REQUEST_PROFILE } } export function receiveProfile () { return { type: t.RECEIVE_PROFILE } } export function requestSearch () { return { type: t.REQUEST_SEARCH } } export function receiveSearch () { return { type: t.RECEIVE_SEARCH } } <|start_filename|>src/redux/code/actions.js<|end_filename|> import sortOn from 'sort-on' import t from './actionTypes' import { getRepoContent, getNestedRepoContent } from '../../api/github-api' import { requestRepos, receiveRepos } from '../loading/actions' export function fetchRepoContent (name) { return dispatch => { dispatch(requestRepos()) getRepoContent(name) .then(({ data }) => { dispatch(receiveRepos()) dispatch(setRepoContent(data)) }) .catch(err => { dispatch(receiveRepos()) }) } } export function fetchNestedRepoContent (path, isDirectory) { return (dispatch, getState) => { const state = getState() const { repo: { data: { full_name }}} = state dispatch(requestRepos()) getNestedRepoContent(full_name, path) .then(({ data }) => { dispatch(receiveRepos()) console.log(data, isDirectory) if (isDirectory) { dispatch(setRepoContent(data)) } else { dispatch(setRawContent(data)) } }) .catch(err => { dispatch(receiveRepos()) }) } } function setRawContent (content) { return { type: t.SET_RAW_CONTENT, content } } function setRepoContent (content) { return { type: t.SET_REPO_CONTENT, content } } export function goBack () { return { type: t.GO_BACK } } <|start_filename|>src/redux/issues/actions.js<|end_filename|> import t from './actionTypes' import { getIssues } from '../../api/github-api' import { requestNotifications, receiveNotifications } from '../loading/actions' export function fetchIssues () { return dispatch => { dispatch(requestNotifications()) getIssues() .then(({ data }) => { dispatch(receiveNotifications()) dispatch(setIssues(data)) }) .catch(err => { dispatch(receiveNotifications()) }) } } export function setIssues (issues) { return { type: t.SET_ISSUES, issues } } <|start_filename|>src/redux/loading/reducer.js<|end_filename|> import t from './actionTypes' const initialState = { issues: false, repos: false, notifications: false, timeline: false, trending: false, profile: false, search: false } export default (state = initialState, action) => { switch (action.type) { case t.REQUEST_ISSUES: return { ...state, issues: true } case t.RECEIVE_ISSUES: return { ...state, issues: false } case t.REQUEST_REPOS: return { ...state, repos: true } case t.RECEIVE_REPOS: return { ...state, repos: false } case t.REQUEST_TIMELINE: return { ...state, timeline: true } case t.RECEIVE_TIMELINE: return { ...state, timeline: false } case t.REQUEST_NOTIFICATIONS: return { ...state, notifications: true } case t.RECEIVE_NOTIFICATIONS: return { ...state, notifications: false } case t.REQUEST_TRENDING: return { ...state, trending: false } case t.RECEIVE_TRENDING: return { ...state, trending: false } case t.REQUEST_PROFILE: return { ...state, profile: true } case t.RECEIVE_PROFILE: return { ...state, profile: false } case t.REQUEST_SEARCH: return { ...state, search: true, } case t.RECEIVE_SEARCH: return { ...state, search: false, } default: return state } } <|start_filename|>src/redux/repos/actions.js<|end_filename|> import sortOn from 'sort-on' import t from './actionTypes' import { getRepos } from '../../api/github-api' import { requestRepos, receiveRepos } from '../loading/actions' export function fetchRepos () { return dispatch => { dispatch(requestRepos()) getRepos() .then(({ data }) => { dispatch(receiveRepos()) dispatch(setRepos(repos)) }) .catch(err => { dispatch(receiveRepos()) }) } } function sortRepos (repos) { return sortOn(repos, '-stargazers_count') } export function setRepos (repos) { repos = sortRepos(repos) return { type: t.SET_REPOS, repos } } <|start_filename|>src/redux/loading/actionTypes.js<|end_filename|> export default { REQUEST_ISSUES: 'REQUEST_ISSUES', RECEIVE_ISSUES: 'RECEIVE_ISSUES', REQUEST_REPOS: 'REQUEST_REPOS', RECEIVE_REPOS: 'RECEIVE_REPOS', REQUEST_TIMELINE: 'REQUEST_TIMELINE', RECEIVE_TIMELINE: 'RECEIVE_TIMELINE', REQUEST_NOTIFICATIONS: 'REQUEST_NOTIFICATIONS', RECEIVE_NOTIFICATIONS: 'RECEIVE_NOTIFICATIONS', REQUEST_TRENDING: 'REQUEST_TRENDING', RECEIVE_TRENDING: 'RECEIVE_TRENDING', REQUEST_PROFILE: 'REQUEST_PROFILE', RECEIVE_PROFILE: 'RECEIVE_PROFILE', REQUEST_SEARCH: 'REQUEST_SEARCH', RECEIVE_SEARCH: 'RECEIVE_SEARCH' } <|start_filename|>src/pages/notifications/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchNotifications } from '../../redux/notifications/actions' import Component from './component' function mapStateToProps (state) { return { list: state.notifications.list, loading: state.loading.notifications } } function mapDispatchToProps (dispatch) { return { fetchNotifications: () => dispatch(fetchNotifications()) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/redux/timeline/actionTypes.js<|end_filename|> export default { SET_TIMELINE: 'SET_TIMELINE' } <|start_filename|>src/pages/timeline/component.js<|end_filename|> import React, { PureComponent } from 'react' import { StyleSheet, View, Text, ScrollView, RefreshControl, Image, TouchableOpacity } from 'react-native' import fecha from 'fecha' import { compile } from 'parse-github-event' const styles = StyleSheet.create({ list: { flex: 1 }, item: { width: '100%', padding: 20, flexDirection: 'row', borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', }, title: { overflow: 'hidden', width: '85%', display: 'flex', flexDirection: 'column' }, ava: { height: 36, width: 36, borderRadius: 4 }, shadow: { borderRadius: 4, marginRight: 10, } }) export class Timeline extends PureComponent { // static navigatorButtons = { // rightButtons: [ // { // title: 'Profile', // id: 'profile' // } // ] // } // // constructor(props) { // super(props) // // this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent) // } visitProfile = ({ login }) => { const { fetchUser, navigator } = this.props fetchUser(login) navigator.push({ screen: 'githubnative.Profile', title: login, animated: true }) } visitRepo = ({ repo }) => { const { fetchRepo, navigator } = this.props fetchRepo(repo.name) navigator.push({ screen: 'githubnative.Repo', title: repo.name, animated: true }) } // onNavigatorEvent = ({ type, id }) => { // const { user } = this.props // // if (type === 'NavBarButtonPress') { // if (id === 'profile') { // this.visitProfile({ login: user }) // } // } // } render () { const { list, loading, fetchTimeline } = this.props return ( <View style={styles.list}> <ScrollView style={{height: 0}} refreshControl={ <RefreshControl refreshing={loading} onRefresh={fetchTimeline} tintColor='black' title='Loading...' titleColor='black' colors={['#ff0000', '#00ff00', '#0000ff']} progressBackgroundColor='#ffff00' /> } > { list.map((ti, index) => { const parsed = compile(ti) return ( <View style={styles.item} key={index}> <View style={styles.shadow}> <TouchableOpacity onPress={() => this.visitProfile(ti.actor)}> <Image source={{uri: ti.actor.avatar_url}} style={styles.ava} /> </TouchableOpacity> </View> <TouchableOpacity onPress={() => this.visitRepo(ti)}> <View style={styles.title}> <Text>{fecha.format(new Date(ti.created_at), 'M/D/YY h:mm A')}</Text> <Text>{parsed}</Text> </View> </TouchableOpacity> </View> ) }) } </ScrollView> </View> ) } } export default Timeline <|start_filename|>src/components/user-item.js<|end_filename|> import React from 'react' import { Text, View, StyleSheet, Image } from 'react-native' const styles = StyleSheet.create({ item: { width: '100%', paddingLeft: 20, paddingRight: 20, paddingBottom: 10, paddingTop: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', display: 'flex', flexDirection: 'row', alignItems: 'center', width: '100%' }, title: { fontSize: 16, fontWeight: 'bold' }, ava: { height: 36, width: 36, borderRadius: 4, marginRight: 10 } }) // onPress={() => this.visitProfile(ti.actor)} export const UserItem = ({ user }) => ( <View style={styles.item}> <Image source={{uri: user.avatar_url}} style={styles.ava} /> <Text style={styles.title}>{user.login}</Text> </View> ) export default UserItem <|start_filename|>src/pages/profile/component.js<|end_filename|> import React, { PureComponent } from 'react' import sortOn from 'sort-on' import { StyleSheet, Image, View, Text, TouchableOpacity, ActivityIndicator } from 'react-native' import Repos from '../repos/container' export class Profile extends PureComponent { render () { const { profile, loading, navigator } = this.props const { name, login, company, location, email, blog, bio, public_repos, followers, following } = profile if (loading) return <ActivityIndicator style={{marginTop: 30}}/> return ( <View style={styles.list} > <View style={styles.topSection}> <View style={styles.row}> <Image style={{width: 110, height: 110, borderRadius: 8, marginRight: 10}} source={{uri: profile.avatar_url}} /> <View> <Text style={{fontSize: 18}}>{name}</Text> <Text style={{color: 'gray'}}>{login}</Text> <Text style={styles.sub}>{company}</Text> <Text style={styles.sub}>{location}</Text> <Text style={styles.sub}>{email}</Text> </View> </View> <Text style={{paddingTop: 10}}>{blog}</Text> <Text style={{paddingTop: 10}}>{bio}</Text> </View> <View style={styles.statRow}> <View style={styles.statItem}> <Text style={styles.count}>{public_repos}</Text> <Text style={styles.label}>Repos</Text> </View> <View style={styles.statItem}> <Text style={styles.count}>{followers}</Text> <Text style={styles.label}>Followers</Text> </View> <View style={styles.statItem}> <Text style={styles.count}>{following}</Text> <Text style={styles.label}>Following</Text> </View> </View> <Repos /> </View> ) } } const styles = StyleSheet.create({ list: { flex: 1 }, topSection: { paddingBottom: 10, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,.1)', backgroundColor: '#fafbfc', padding: 10 }, row: { flexDirection: 'row' }, name: { fontSize: 16, color: 'gray' }, count: { fontWeight: 'bold', fontSize: 22 }, sub: { fontSize: 16 }, label: { fontSize: 16 }, statItem: { alignItems: 'center' }, statRow: { flexDirection: 'row', width: '100%', alignItems: 'center', justifyContent: 'space-around', padding: 10, borderColor: 'rgba(0,0,0,.1)', borderBottomWidth: 1 }, closeButton: { width: '100%', height: 50, borderTopWidth: 1, borderColor: 'rgba(0,0,0,.1)', backgroundColor: '#fafbfc', alignItems: 'center', justifyContent: 'center' } }) export default Profile <|start_filename|>App.js<|end_filename|> import React, { Component } from 'react' import { StyleSheet, Text, View } from 'react-native' import GithubIssues from './src/router' export default class App extends Component { render () { return <GithubIssues /> } } <|start_filename|>src/pages/edit-trending/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { setLanguage, setTime } from '../../redux/trending/actions' import Component from './component' function mapStateToProps (state) { console.log(state.trending.language, state.trending.time) return { language: state.trending.language, time: state.trending.time } } function mapDispatchToProps (dispatch) { return { setLanguage: language => dispatch(setLanguage(language)), setTime: time => dispatch(setTime(time)) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/pages/tree/container.js<|end_filename|> import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { fetchNestedRepoContent, goBack } from '../../redux/code/actions' import Component from './component' function mapStateToProps ({ code: { content }}) { return { content } } function mapDispatchToProps (dispatch) { return { fetchNestedRepoContent: (path, isDirectory) => dispatch(fetchNestedRepoContent(path, isDirectory)), goBack: () => dispatch(goBack()) } } export default connect( mapStateToProps, mapDispatchToProps )(Component) <|start_filename|>src/pages/issues/index.js<|end_filename|> import Issues from './container' export default Issues <|start_filename|>src/pages/trending/component.js<|end_filename|> import React, { PureComponent } from 'react' import sortOn from 'sort-on' import { StyleSheet, View, Text, ScrollView, RefreshControl, TouchableOpacity, ActivityIndicator } from 'react-native' import { RepoItem } from '../../components' const styles = StyleSheet.create({ list: { flex: 1 } }) export class Trending extends PureComponent { static navigatorButtons = { leftButtons: [ { title: 'Edit', id: 'edit' } ], rightButtons: [ { title: 'Search', id: 'search', icon: require('../../icons/search.png') } ] } constructor(props) { super(props) this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent) } visitRepo = repo => { const { navigator, fetchRepo } = this.props const name = repo.full_name || repo.name fetchRepo(name) navigator.push({ screen: 'githubnative.Repo', title: name, animated: true }) } onNavigatorEvent = ({ type, id }) => { const { user, navigator } = this.props if (type === 'NavBarButtonPress') { if (id === 'search') { navigator.push({ screen: 'githubnative.Search', title: 'Search', animated: true }) } else if (id === 'edit') { navigator.showModal({ screen: 'githubnative.EditTrending', title: 'Edit Trending', animationType: 'slide-up' }) } } } render () { const { list, loading, fetchRepos } = this.props if (loading) { return ( <ActivityIndicator style={{marginTop: 50}} /> ) } return ( <View style={styles.list}> <ScrollView style={{height: 0}} refreshControl={ <RefreshControl refreshing={loading} onRefresh={fetchRepos} tintColor='black' title='Loading...' titleColor='black' colors={['#ff0000', '#00ff00', '#0000ff']} progressBackgroundColor='#ffff00' /> } > { list.map((n, index) => ( <TouchableOpacity key={index} onPress={() => this.visitRepo(n)}> <RepoItem repo={n} /> </TouchableOpacity> )) } </ScrollView> </View> ) } } export default Trending <|start_filename|>src/redux/repo/actions.js<|end_filename|> import sortOn from 'sort-on' import t from './actionTypes' import { getRepo, getRepoContent } from '../../api/github-api' import { fetchRepoContent } from '../code/actions' import { requestRepos, receiveRepos } from '../loading/actions' export function fetchRepo (name) { return dispatch => { dispatch(requestRepos()) dispatch(fetchRepoContent(name)) getRepo(name) .then(({ data }) => { dispatch(receiveRepos()) dispatch(setRepo(data)) }) .catch(err => { dispatch(receiveRepos()) }) } } function setRepo (repo) { return { type: t.SET_REPO, repo } } <|start_filename|>src/redux/notifications/actions.js<|end_filename|> import t from './actionTypes' import { getNotifications } from '../../api/github-api' import { requestNotifications, receiveNotifications } from '../loading/actions' export function fetchNotifications () { return dispatch => { dispatch(requestNotifications()) getNotifications() .then(({ data }) => { dispatch(receiveNotifications()) dispatch(setNotifications(data)) }) .catch(err => { dispatch(receiveNotifications()) }) } } export function setNotifications (notifications) { return { type: t.SET_NOTIFICATIONS, notifications } }
hanford/Mobile-Github-Client
<|start_filename|>lib/plugin.js<|end_filename|> /*! * plugin.js - rosetta plugin for hsd. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const assert = require('bsert'); const HTTP = require('./http'); const pkg = require('./pkg'); /** * @exports plugin */ const plugin = exports; /** * Plugin * @extends Index */ class Plugin { /** * Create a plugin. * @constructor * @param {Node} node */ constructor(node) { this.opened = false; this.config = node.config.filter(pkg.core); this.config.open(`${pkg.core}.conf`); this.http = new HTTP({ network: node.network, logger: node.logger, node: node, prefix: this.config.prefix, ssl: this.config.bool('ssl'), keyFile: this.config.path('ssl-key'), certFile: this.config.path('ssl-cert'), host: this.config.str('http-host'), port: this.config.uint('http-port'), apiKey: this.config.str('api-key'), noAuth: this.config.bool('no-auth'), cors: this.config.bool('cors') }); } /** * Open the plugin. * @returns {Promise} */ async open() { assert(!this.opened, 'plugin is already open.'); this.opened = true; await this.http.open(); } /** * Close the plugin. * @returns {Promise} */ async close() { assert(this.opened, 'plugin is not open.'); this.opened = false; await this.http.close(); } } /** * Plugin name. * @const {String} */ plugin.id = pkg.name; /** * Plugin initialization. * @param {Node} node * @returns {Plugin} */ plugin.init = function init(node) { return new Plugin(node); }; <|start_filename|>lib/currency.js<|end_filename|> /*! * currency.js - currency object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const pkg = require('./pkg'); class Currency { toJSON() { return { symbol: pkg.unit.toUpperCase(), decimals: pkg.decimals, metadata: { Issuer: pkg.organization } }; } } // Singleton const currency = new Currency(); module.exports = currency; <|start_filename|>lib/errs.js<|end_filename|> /*! * errs.js - errs for rosetta. * Copyright (c) 2020, The Handshake Developers (MIT License). * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const errs = { TX_REQUIRED: { code: 1, message: 'Transaction is required.', retriable: true }, TX_HASH_REQUIRED: { code: 2, message: 'Transaction hash is required.', retriable: true }, BLOCK_REQUIRED: { code: 3, message: 'Block is required.', retriable: true }, BLOCK_HEIGHT_REQUIRED: { code: 4, message: 'Block height is required.', retriable: true }, BLOCK_HASH_MISMATCH: { code: 5, message: 'Block hash mismatch.', retriable: true }, ACCOUNT_REQUIRED: { code: 6, message: 'Account is required.', retriable: true }, ADDRESS_REQUIRED: { code: 7, message: 'Address is required.', retriable: true }, NETWORK_REQUIRED: { code: 8, message: 'Network is required.', retriable: true }, OPTIONS_REQUIRED: { code: 9, message: 'Options is required.', retriable: true }, INVALID_NETWORK: { code: 10, message: 'Invalid network.', retriable: true }, INVALID_BLOCKCHAIN: { code: 11, message: 'Invalid blockchain.', retriable: true }, INVALID_TX: { code: 12, message: 'Invalid transaction.', retriable: true }, INVALID_SIGNED_TX: { code: 13, message: 'Invalid signed transaction.', retriable: true }, BLOCK_NOT_FOUND: { code: 14, message: 'Block not found.', retriable: true }, TX_NOT_FOUND: { code: 15, message: 'Transaction not found.', retriable: true }, VIEW_NOT_FOUND: { code: 16, message: 'Coin view not found.', retriable: true }, TX_RELAY_ERROR: { code: 17, message: 'Error relaying transaction.', retriable: false }, QUERY_NOT_SUPPORTED: { code: 18, message: 'Query not supported', retriable: false }, UNKNOWN_ERROR: { code: 32, message: 'Unknown error.', retriable: false } }; module.exports = errs; <|start_filename|>lib/mempool.js<|end_filename|> /*! * mempool.js - mempool object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; class Mempool { constructor(txs) { this.txs = txs; } hashes() { const hashes = []; for (const tx of this.txs) hashes.push({ hash: tx.toString('hex') }); return hashes; } toJSON() { return { 'transaction_identifiers': this.hashes() }; } } module.exports = Mempool; <|start_filename|>test/data/construction/metadata/request.json<|end_filename|> { "network_identifier": { "blockchain": "handshake", "network": "simnet" }, "options": {} } <|start_filename|>lib/op.js<|end_filename|> /*! * op.js - operation object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const currency = require('./currency'); class Op { constructor(index, address, value, metadata) { this.index = index; this.address = address; this.value = value; this.metadata = metadata || {}; } toJSON() { return { operation_identifier: { index: this.index, network_index: 0 }, type: 'TRANSFER', status: 'SUCCESS', account: { address: this.address.toString(this.network) }, amount: { value: this.value.toString(), currency: currency }, metadata: this.metadata }; } } module.exports = Op; <|start_filename|>lib/network.js<|end_filename|> /*! * network.js - network object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const pkg = require('./pkg'); const errs = require('./errs'); class List { constructor(network) { this.network = network; } toJSON() { return { network_identifiers: [{ blockchain: pkg.blockchain, network: this.network.toString() }] }; } } class Options { constructor(agent) { this.agent = agent; } toJSON() { return { version: { rosetta_version: pkg.rosetta, node_version: this.agent, middleware_version: pkg.version }, allow: { operation_statuses: [ { status: 'SUCCESS', successful: true } ], operation_types: [ 'TRANSFER' ], errors: Object.values(errs) } }; } } class Status { constructor(peers, tip, network) { this.peers = peers; this.tip = tip; this.network = network; } toJSON() { return { current_block_identifier: { index: this.tip.height, hash: this.tip.hash.toString('hex') }, current_block_timestamp: this.tip.time * 1000, genesis_block_identifier: { index: this.network.genesis.height, hash: this.network.genesis.hash.toString('hex') }, peers: this.peers }; } } exports.NetworkList = List; exports.NetworkOptions = Options; exports.NetworkStatus = Status; <|start_filename|>lib/account.js<|end_filename|> /*! * account.js - account object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const currency = require('./currency'); class AccountBalance { constructor(height, block, balance) { this.height = height; this.block = block; this.balance = balance; } toJSON() { return { block_identifier: { index: this.height, hash: this.block.hash().toString('hex') }, balances: [ { value: this.balance.toString(), currency: currency } ] }; } } module.exports = AccountBalance; <|start_filename|>lib/pkg.js<|end_filename|> /*! * pkg.js - package constants for rosetta. * Copyright (c) 2020, The Handshake Developers (MIT License). * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const pkg = exports; /** * Package Name * @const {String} * @default */ pkg.name = 'hs-rosetta'; /** * Project Name * @const {String} * @default */ pkg.core = 'rosetta'; /** * Organization Name * @const {String} * @default */ pkg.organization = 'handshake-org'; /** * Blockchain Name * @const {String} * @default */ pkg.blockchain = 'handshake'; /** * Currency Name * @const {String} * @default */ pkg.currency = 'handshake'; /** * Currency Unit * @const {String} * @default */ pkg.unit = 'hns'; /** * Base Unit (dollarydoos!) * @const {String} * @default */ pkg.base = 'doo'; /** * Decimals * @const {String} * @default */ pkg.decimals = 6; /** * Config file name. * @const {String} * @default */ pkg.cfg = `${pkg.core}.conf`; /** * Current version string. * @const {String} * @default */ pkg.version = '0.0.1'; /** * Repository URL. * @const {String} * @default */ pkg.url = `https://github.com/${pkg.organization}/${pkg.name}`; /** * Rosetta version * @const {String} * @default */ pkg.rosetta = '1.3.1'; <|start_filename|>lib/http.js<|end_filename|> /*! * http.js - rosetta http server for hsd. * Copyright (c) 2020, The Handshake Developers (MIT License). * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const assert = require('bsert'); const path = require('path'); const hsd = require('hsd'); const Validator = require('bval'); const {Server} = require('bweb'); const base58 = require('bcrypto/lib/encoding/base58'); const sha256 = require('bcrypto/lib/sha256'); const random = require('bcrypto/lib/random'); const {NetworkList, NetworkOptions, NetworkStatus} = require('./network'); const AccountBalance = require('./account'); const Mempool = require('./mempool'); const Block = require('./block'); const BlockMeta = require('./blockmeta'); const TX = require('./tx'); const pkg = require('./pkg'); const errs = require('./errs'); const util = require('./util'); /** * HTTP * @alias module:http.Server */ class HTTP extends Server { /** * Create an http server. * @constructor * @param {Object} options */ constructor(options) { super(new HTTPOptions(options)); this.logger = this.options.logger.context('hs-rosetta'); this.node = this.options.node; this.network = this.node.network; this.chain = this.node.chain; this.mempool = this.node.mempool; this.rpc = this.node.rpc; this.pool = this.node.pool; assert(this.chain.options.indexTX, 'index-tx is required'); assert(this.chain.options.indexAddress, 'index-address is required'); this.init(); } /** * Initialize routes. * @private */ init() { this.on('request', (req, res) => { if (req.method === 'POST' && req.pathname === '/') return; this.logger.debug('Request for method=%s path=%s (%s).', req.method, req.pathname, req.socket.remoteAddress); }); this.on('listening', (address) => { this.logger.info('Rosetta HTTP server listening on %s (port=%d).', address.address, address.port); }); this.on('error', (err) => { console.error(err); }); this.initRouter(); } /** * Initialize routes. * @private */ initRouter() { if (this.options.cors) this.use(this.cors()); if (!this.options.noAuth) { this.use(this.basicAuth({ hash: sha256.digest, password: this.options.apiKey, realm: 'node' })); } this.use(this.bodyParser({ type: 'json' })); this.use(this.jsonRPC()); this.use(this.router()); this.error((err, req, res) => { const code = err.statusCode || 500; res.json(code, { code: err.code || 32, message: err.message, retriable: true }); }); this.post('/network/list', async (req, res) => { const list = new NetworkList(this.network); res.json(200, list.toJSON()); }); this.post('/network/options', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); const options = new NetworkOptions(this.pool.options.agent); res.json(200, options.toJSON()); }); this.post('/network/status', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); const peers = []; for (let peer = this.pool.peers.head(); peer; peer = peer.next) { if (!peer.connected) continue; peers.push({ peer_id: peer.hostname() }); } const status = new NetworkStatus(peers, this.chain.tip, this.network); res.json(200, status.toJSON()); }); this.post('/account/balance', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); enforce(valid.has('account_identifier'), errs.ACCOUNT_REQUIRED); const address = valid.child('account_identifier').str('address'); enforce(address, errs.ADDRESS_REQUIRED); let height; if (valid.has('block_identifier')) { height = valid.child('block_identifier').uint('index'); enforce(height != null, errs.BLOCK_HEIGHT_REQUIRED); } // We do not support querying account balance by height yet. if (height != null) { throw errs.QUERY_NOT_SUPPORTED; } height = this.chain.height; const coins = await this.chain.getCoinsByAddress(address); const block = await this.chain.getBlock(height); if (!block) { throw errs.BLOCK_NOT_FOUND; } let balance = 0; for (const coin of coins) { if (coin.address.isUnspendable()) continue; if (coin.covenant.isUnspendable()) continue; if (util.isUnspendable(coin.covenant)) continue; balance += coin.value; } const account = new AccountBalance(height, block, balance); res.json(200, account.toJSON()); }); this.post('/block', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); enforce(valid.has('block_identifier'), errs.BLOCK_REQUIRED); const hash = valid.child('block_identifier').uintbhash('hash'); const height = valid.child('block_identifier').uint('index'); enforce(height != null, errs.BLOCK_HEIGHT_REQUIRED); const block = await this.chain.getBlock(height); if (!block) { throw errs.BLOCK_NOT_FOUND; } if (hash) { enforce(block.hashHex() === hash.toString('hex'), errs.BLOCK_HASH_MISMATCH); } const view = await this.chain.getBlockView(block); if (!view) { throw errs.BLOCK_NOT_FOUND; } const prev = new BlockMeta(height, block.hash()); if (prev.height !== 0) { prev.height = await this.chain.getHeight(block.prevBlock); prev.hash = block.prevBlock; } const result = new Block(height, block, view, prev, this.network); res.json(200, result.toJSON()); }); this.post('/block/transaction', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); enforce(valid.has('block_identifier'), errs.BLOCK_REQUIRED); enforce(valid.has('transaction_identifier'), errs.TX_REQUIRED); let hash = valid.child('block_identifier').uintbhash('hash'); const height = valid.child('block_identifier').uint('index'); enforce(height != null, errs.BLOCK_HEIGHT_REQUIRED); const block = await this.chain.getBlock(height); if (!block) { throw errs.BLOCK_NOT_FOUND; } if (hash) { enforce(block.hashHex() === hash.toString('hex'), errs.BLOCK_HASH_MISMATCH); } hash = valid.child('transaction_identifier').uintbhash('hash'); enforce(hash, errs.TX_HASH_REQUIRED); const tx = await this.chain.getTX(hash); if (!tx) { throw errs.TX_NOT_FOUND; } const view = await this.chain.getBlockView(block); if (!view) { throw errs.VIEW_NOT_FOUND; } const transaction = new TX(tx, view, this.network); res.json(200, {transaction: transaction.toJSON()}); }); this.post('/construction/metadata', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); enforce(valid.has('options'), errs.OPTIONS_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); res.json(200, { metadata: { recent_block_hash: this.chain.tip.hash.toString('hex') } } ); }); this.post('/construction/submit', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); enforce(valid.buf('signed_transaction'), errs.INVALID_SIGNED_TX); let raw, tx; try { raw = valid.buf('signed_transaction'); tx = hsd.TX.decode(raw); } catch (err) { throw errs.INVALID_TX; } try { await this.mempool.addTX(tx); this.pool.broadcast(tx); } catch (err) { throw errs.TX_RELAY_ERROR; } res.json(200, { transaction_identifier: { hash: tx.txid() } }); }); this.post('/mempool', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); const txs = this.mempool.getSnapshot(); const mempool = new Mempool(txs); res.json(200, mempool.toJSON()); }); this.post('/mempool/transaction', async (req, res) => { const valid = Validator.fromRequest(req); enforce(valid.has('network_identifier'), errs.NETWORK_REQUIRED); const blockchain = valid.child('network_identifier').str('blockchain'); const network = valid.child('network_identifier').str('network'); enforce(blockchain === pkg.blockchain, errs.INVALID_BLOCKCHAIN); enforce(network === this.network.toString(), errs.INVALID_NETWORK); enforce(valid.has('transaction_identifier'), errs.TX_REQUIRED); const hash = valid.child('transaction_identifier').uintbhash('hash'); const tx = this.mempool.getTX(hash); if (!tx) { throw errs.TX_NOT_FOUND; } const view = await this.mempool.getCoinView(tx); if (!view) { throw errs.VIEW_NOT_FOUND; } const transaction = new TX(tx, view, this.network); res.json(200, {transaction: transaction.toJSON()}); }); } } class HTTPOptions { /** * HTTPOptions * @alias module:http.HTTPOptions * @constructor * @param {Object} options */ constructor(options) { this.logger = null; this.node = null; this.apiKey = base58.encode(random.randomBytes(20)); this.apiHash = sha256.digest(Buffer.from(this.apiKey, 'ascii')); this.noAuth = false; this.cors = false; this.prefix = null; this.host = '127.0.0.1'; this.port = 8080; this.ssl = false; this.keyFile = null; this.certFile = null; this.fromOptions(options); } /** * Inject properties from object. * @private * @param {Object} options * @returns {HTTPOptions} */ fromOptions(options) { assert(options); assert(options.node && typeof options.node === 'object', 'Rosetta HTTP Server requires a Node.'); this.node = options.node; this.logger = options.node.logger; if (options.logger != null) { assert(typeof options.logger === 'object'); this.logger = options.logger; } if (options.apiKey != null) { assert(typeof options.apiKey === 'string', 'API key must be a string.'); assert(options.apiKey.length <= 255, 'API key must be under 256 bytes.'); this.apiKey = options.apiKey; this.apiHash = sha256.digest(Buffer.from(this.apiKey, 'ascii')); } if (options.noAuth != null) { assert(typeof options.noAuth === 'boolean'); this.noAuth = options.noAuth; } if (options.cors != null) { assert(typeof options.cors === 'boolean'); this.cors = options.cors; } if (options.prefix != null) { assert(typeof options.prefix === 'string'); this.prefix = options.prefix; this.keyFile = path.join(this.prefix, 'key.pem'); this.certFile = path.join(this.prefix, 'cert.pem'); } if (options.host != null) { assert(typeof options.host === 'string'); this.host = options.host; } if (options.port != null) { assert((options.port & 0xffff) === options.port, 'Port must be a number.'); this.port = options.port; } if (options.ssl != null) { assert(typeof options.ssl === 'boolean'); this.ssl = options.ssl; } if (options.keyFile != null) { assert(typeof options.keyFile === 'string'); this.keyFile = options.keyFile; } if (options.certFile != null) { assert(typeof options.certFile === 'string'); this.certFile = options.certFile; } // Allow no-auth implicitly // if we're listening locally. if (!options.apiKey) { if (this.host === '127.0.0.1' || this.host === '::1') this.noAuth = true; } return this; } } /* * Helpers */ function enforce(value, err) { if (!value) { throw err; } } /* * Expose */ module.exports = HTTP; <|start_filename|>lib/util.js<|end_filename|> /*! * util.js - util for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const CovenantTypes = require('./covenant'); function isUnspendable(covenant) { // REGISTER->REVOKE covenants have no effect. if (covenant.type >= CovenantTypes.REGISTER && covenant.type <= CovenantTypes.REVOKE) { return true; } return false; } exports.isUnspendable = isUnspendable; <|start_filename|>test/data/mempool/transaction/request.json<|end_filename|> { "network_identifier": { "blockchain": "handshake", "network": "simnet" }, "transaction_identifier": { "hash": "<placeholder>" } } <|start_filename|>lib/block.js<|end_filename|> /*! * block.js - block object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const TX = require('./tx'); class Block { constructor(height, block, view, prev, network) { this.height = height; this.block = block; this.view = view; this.prev = prev; this.network = network; } transactions() { const transactions = []; for (const transaction of this.block.txs) { const tx = new TX(transaction, this.view, this.network); transactions.push(tx); } return transactions; } toJSON() { return { block: { block_identifier: { index: this.height, hash: this.block.hashHex() }, parent_block_identifier: this.prev, timestamp: this.block.time * 1000, transactions: this.transactions(), metadata: { transactions_root: this.block.merkleRoot.toString('hex'), difficulty: toDifficulty(this.block.bits) } } }; } } function toDifficulty(bits) { let shift = (bits >>> 24) & 0xff; let diff = 0x0000ffff / (bits & 0x00ffffff); while (shift < 29) { diff *= 256.0; shift++; } while (shift > 29) { diff /= 256.0; shift--; } return diff; } module.exports = Block; <|start_filename|>lib/covenant.js<|end_filename|> /*! * covenant.js - covenant object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const CovenantTypes = { NONE: 0, CLAIM: 1, OPEN: 2, BID: 3, REVEAL: 4, REDEEM: 5, REGISTER: 6, UPDATE: 7, RENEW: 8, TRANSFER: 9, FINALIZE: 10, REVOKE: 11 }; module.exports = CovenantTypes; <|start_filename|>lib/blockmeta.js<|end_filename|> /*! * blockmeta.js - blockmeta object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; class BlockMeta { constructor(height, hash) { this.height = height; this.hash = hash; } toJSON() { return { index: this.height, hash: this.hash.toString('hex') }; } } module.exports = BlockMeta; <|start_filename|>lib/tx.js<|end_filename|> /*! * tx.js - tx object for rosetta. * Copyright (c) 2020, The Handshake Developers. * https://github.com/handshake-org/hs-rosetta */ 'use strict'; const Op = require('./op'); const util = require('./util'); class TX { constructor(tx, view, network) { this.tx = tx; this.view = view; this.network = network; } operations() { const operations = []; if (!this.tx.isCoinbase()) { for (const input of this.tx.inputs) { const coin = this.view.getCoinFor(input); const addr = coin.getHash(); if (!addr) continue; if (util.isUnspendable(coin.covenant)) continue; const address = coin.address.toString(this.network); const value = '-' + coin.value.toString(); const metadata = { asm: input.witness.toASM(), hex: input.witness.toHex() }; const op = new Op(operations.length, address, value, metadata); operations.push(op); } } for (const output of this.tx.outputs) { if (output.isUnspendable()) continue; const addr = output.getHash(); if (!addr) continue; if (util.isUnspendable(output.covenant)) continue; const address = output.address.toString(this.network); const value = output.value.toString(); const op = new Op(operations.length, address, value); operations.push(op); } return operations; } toJSON() { return { transaction_identifier: { hash: this.tx.hash().toString('hex') }, operations: this.operations(), metadata: { size: this.tx.getSize(), lockTime: this.tx.locktime } }; } } module.exports = TX; <|start_filename|>test/rosetta-http-test.js<|end_filename|> /* eslint-env mocha */ /* eslint prefer-arrow-callback: "off" */ 'use strict'; const assert = require('bsert'); const hsd = require('hsd'); const FullNode = hsd.FullNode; const {Client} = require('bcurl'); const {NodeClient} = require('hs-client'); const network = hsd.Network.get('simnet'); const client = new Client({ port: 8080 }); const node = new FullNode({ network: network.toString(), memory: true, workers: true, indexTX: true, indexAddress: true, plugins: [require('../lib/plugin'), hsd.wallet.plugin] }); const {wdb} = node.require('walletdb'); const nclient = new NodeClient({ port: network.rpcPort, apiKey: 'foo' }); let wallet = null; const endpoints = [ '/network/list', '/network/options', '/network/status', '/account/balance', '/block', '/block/transaction', '/construction/metadata', '/mempool' ]; describe('Rosetta Schema', function() { this.timeout(15000); it('should open node', async () => { await node.open(); await client.open(); }); for (const endpoint of endpoints) { it(`should match POST response for ${endpoint}`, async () => { const params = require(`./data${endpoint}/request.json`); const expected = require(`./data${endpoint}/response.json`); const data = await client.post(endpoint, params); assert.deepEqual(data, expected); }); } { let tx, cbAddress, toAddress, changeAddress = null; it('should mine 100 blocks', async () => { wallet = await wdb.create(); cbAddress = await wallet.receiveAddress(); await mineBlocks(100, cbAddress.toString(network)); }); it('should match POST response for /construction/submit', async () => { toAddress = await wallet.receiveAddress(); changeAddress = await wallet.changeAddress(); const mtx = await wallet.createTX({ rate: 100000, outputs: [{ value: 100000, address: toAddress }], changeAddress: changeAddress }); await wallet.sign(mtx); assert(mtx.isSigned()); tx = mtx.toTX(); await wdb.addTX(tx); const endpoint = '/construction/submit'; const params = require(`./data${endpoint}/request.json`); params.signed_transaction = tx.toRaw().toString('hex'); const expected = require(`./data${endpoint}/response.json`); const data = await client.post(endpoint, params); expected.transaction_identifier.hash = tx.hash().toString('hex'); assert.deepEqual(data, expected); }); it('should match POST response for /mempool/transaction', async () => { await sleep(500); const endpoint = '/mempool/transaction'; const params = require(`./data${endpoint}/request.json`); params.transaction_identifier.hash = tx.hash().toString('hex'); const expected = require(`./data${endpoint}/response.json`); expected.transaction.transaction_identifier.hash = tx.hash().toString('hex'); expected.transaction.operations[0].account.address = cbAddress.toString(network); expected.transaction.operations[1].account.address = toAddress.toString(network); expected.transaction.operations[2].account.address = changeAddress.toString(network); expected.transaction.operations[0].metadata.asm = tx.inputs[0].witness.toASM(); expected.transaction.operations[0].metadata.hex = tx.inputs[0].witness.toHex(); const data = await client.post(endpoint, params); assert.deepEqual(data, expected); }); } it('should cleanup', async () => { await client.close(); await node.close(); }); }); // take into account race conditions async function mineBlocks(count, address) { for (let i = 0; i < count; i++) { const obj = { complete: false }; node.once('block', () => { obj.complete = true; }); await nclient.execute('generatetoaddress', [1, address]); await forValue(obj, 'complete', true); } } async function forValue(obj, key, val, timeout = 30000) { assert(typeof obj === 'object'); assert(typeof key === 'string'); const ms = 10; let interval = null; let count = 0; return new Promise((resolve, reject) => { interval = setInterval(() => { if (obj[key] === val) { clearInterval(interval); resolve(); } else if (count * ms >= timeout) { clearInterval(interval); reject(new Error('Timeout waiting for value.')); } count += 1; }, ms); }); }; async function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)); }
tuxcanfly/hs-rosetta
<|start_filename|>sql/dmlgen/dmltestgenerated/output_gen.go<|end_filename|> // Code generated by corestoreio/pkg/util/codegen. DO NOT EDIT. // Generated by sql/dmlgen. DO NOT EDIT. // +build !ignore // +build !ignored package dmltestgenerated import ( "context" "database/sql" "fmt" "io" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/cstrace" ) // CatalogProductIndexEAVDecimalIDX represents a single row for DB table // catalog_product_index_eav_decimal_idx. Auto generated. // Table comment: Catalog Product EAV Decimal Indexer Index Table type CatalogProductIndexEAVDecimalIDX struct { EntityID uint32 // entity_id int(10) unsigned NOT NULL PRI "Entity ID" AttributeID uint32 // attribute_id smallint(5) unsigned NOT NULL PRI "Attribute ID" StoreID uint32 // store_id smallint(5) unsigned NOT NULL PRI "Store ID" SourceID uint32 // source_id int(10) unsigned NOT NULL PRI DEFAULT '0' "Original entity Id for attribute value" Value null.Decimal // value decimal(12,4) NOT NULL MUL "Value" } // CoreConfiguration represents a single row for DB table core_configuration. // Auto generated. // Table comment: Config Data //easyjson:json type CoreConfiguration struct { ConfigID uint32 `json:"config_id,omitempty" max_len:"10"` // config_id int(10) unsigned NOT NULL PRI auto_increment "Id" Scope string `json:"scope,omitempty" max_len:"8"` // scope varchar(8) NOT NULL MUL DEFAULT ''default'' "Scope" ScopeID int32 `json:"scope_id" xml:"scope_id"` // scope_id int(11) NOT NULL DEFAULT '0' "Scope Id" Expires null.Time `json:"expires,omitempty" ` // expires datetime NULL DEFAULT 'NULL' "Value expiration time" Path string `json:"x_path" xml:"y_path" max_len:"255"` // path varchar(255) NOT NULL DEFAULT ''general'' "Config Path overwritten" Value null.String `json:"value,omitempty" max_len:"65535"` // value text NULL DEFAULT 'NULL' "Value" VersionTs time.Time `json:"version_ts,omitempty" ` // version_ts timestamp(6) NOT NULL STORED GENERATED "Timestamp Start Versioning" VersionTe time.Time `json:"version_te,omitempty" ` // version_te timestamp(6) NOT NULL PRI STORED GENERATED "Timestamp End Versioning" } // CustomerAddressEntity represents a single row for DB table // customer_address_entity. Auto generated. // Table comment: Customer Address Entity //easyjson:json type CustomerAddressEntity struct { EntityID uint32 `max_len:"10"` // entity_id int(10) unsigned NOT NULL PRI auto_increment "Entity ID" IncrementID null.String `max_len:"50"` // increment_id varchar(50) NULL DEFAULT 'NULL' "Increment Id" ParentID null.Uint32 `max_len:"10"` // parent_id int(10) unsigned NULL MUL DEFAULT 'NULL' "Parent ID" CreatedAt time.Time // created_at timestamp NOT NULL DEFAULT 'current_timestamp()' "Created At" UpdatedAt time.Time // updated_at timestamp NOT NULL DEFAULT 'current_timestamp()' on update current_timestamp() "Updated At" IsActive bool `max_len:"5"` // is_active smallint(5) unsigned NOT NULL DEFAULT '1' "Is Active" City string `max_len:"255"` // city varchar(255) NOT NULL "City" Company null.String `max_len:"255"` // company varchar(255) NULL DEFAULT 'NULL' "Company" CountryID string `max_len:"255"` // country_id varchar(255) NOT NULL "Country" Firstname string `max_len:"255"` // firstname varchar(255) NOT NULL "First Name" Lastname string `max_len:"255"` // lastname varchar(255) NOT NULL "Last Name" Postcode null.String `max_len:"255"` // postcode varchar(255) NULL DEFAULT 'NULL' "Zip/Postal Code" Region null.String `max_len:"255"` // region varchar(255) NULL DEFAULT 'NULL' "State/Province" Street string `max_len:"65535"` // street text NOT NULL "Street Address" } type customerEntityRelations struct { parent *CustomerEntity CustomerAddressEntities *CustomerAddressEntities // Reversed 1:M customer_entity.entity_id => customer_address_entity.parent_id } func (e *CustomerEntity) setRelationParent() { if e.Relations != nil && e.Relations.parent == nil { e.Relations.parent = e } } func (e *CustomerEntity) NewRelations() *customerEntityRelations { e.Relations = &customerEntityRelations{parent: e} return e.Relations } // CustomerEntity represents a single row for DB table customer_entity. Auto // generated. // Table comment: Customer Entity //easyjson:json type CustomerEntity struct { EntityID uint32 `max_len:"10"` // entity_id int(10) unsigned NOT NULL PRI auto_increment "Entity ID" WebsiteID null.Uint32 `max_len:"5"` // website_id smallint(5) unsigned NULL MUL DEFAULT 'NULL' "Website ID" Email null.String `max_len:"255"` // email varchar(255) NULL MUL DEFAULT 'NULL' "Email" GroupID uint32 `max_len:"5"` // group_id smallint(5) unsigned NOT NULL DEFAULT '0' "Group ID" StoreID null.Uint32 `max_len:"5"` // store_id smallint(5) unsigned NULL MUL DEFAULT '0' "Store ID" CreatedAt time.Time // created_at timestamp NOT NULL DEFAULT 'current_timestamp()' "Created At" UpdatedAt time.Time // updated_at timestamp NOT NULL DEFAULT 'current_timestamp()' on update current_timestamp() "Updated At" IsActive bool `max_len:"5"` // is_active smallint(5) unsigned NOT NULL DEFAULT '1' "Is Active" CreatedIn null.String `max_len:"255"` // created_in varchar(255) NULL DEFAULT 'NULL' "Created From" Firstname null.String `max_len:"255"` // firstname varchar(255) NULL MUL DEFAULT 'NULL' "First Name" Lastname null.String `max_len:"255"` // lastname varchar(255) NULL MUL DEFAULT 'NULL' "Last Name" Dob null.Time // dob date NULL DEFAULT 'NULL' "Date of Birth" passwordHash null.String `max_len:"128"` // password_hash varchar(128) NULL DEFAULT 'NULL' "Password_hash" RpToken null.String `max_len:"128"` // rp_token varchar(128) NULL DEFAULT 'NULL' "Reset password token" RpTokenCreatedAt null.Time // rp_token_created_at datetime NULL DEFAULT 'NULL' "Reset password token creation time" DefaultBilling null.Uint32 `max_len:"10"` // default_billing int(10) unsigned NULL DEFAULT 'NULL' "Default Billing Address" DefaultShipping null.Uint32 `max_len:"10"` // default_shipping int(10) unsigned NULL DEFAULT 'NULL' "Default Shipping Address" Gender null.Uint32 `max_len:"5"` // gender smallint(5) unsigned NULL DEFAULT 'NULL' "Gender" Relations *customerEntityRelations } // DmlgenTypes represents a single row for DB table dmlgen_types. Auto generated. // // Just another comment. //easyjson:json type DmlgenTypes struct { ID int32 `json:"id,omitempty" max_len:"10"` // id int(11) NOT NULL PRI auto_increment "" ColBigint1 null.Int64 `json:"col_bigint_1,omitempty" max_len:"19"` // col_bigint_1 bigint(20) NULL DEFAULT 'NULL' "" ColBigint2 int64 `json:"col_bigint_2,omitempty" max_len:"19"` // col_bigint_2 bigint(20) NOT NULL DEFAULT '0' "" ColBigint3 null.Uint64 `json:"col_bigint_3,omitempty" max_len:"20"` // col_bigint_3 bigint(20) unsigned NULL DEFAULT 'NULL' "" ColBigint4 uint64 `json:"col_bigint_4,omitempty" max_len:"20"` // col_bigint_4 bigint(20) unsigned NOT NULL DEFAULT '0' "" ColBlob []byte `json:"col_blob,omitempty" max_len:"65535"` // col_blob blob NULL DEFAULT 'NULL' "" ColDate1 null.Time `json:"col_date_1,omitempty" ` // col_date_1 date NULL DEFAULT 'NULL' "" ColDate2 time.Time `json:"col_date_2,omitempty" ` // col_date_2 date NOT NULL DEFAULT ''0000-00-00'' "" ColDatetime1 null.Time `json:"col_datetime_1,omitempty" ` // col_datetime_1 datetime NULL DEFAULT 'NULL' "" ColDatetime2 time.Time `json:"col_datetime_2,omitempty" ` // col_datetime_2 datetime NOT NULL DEFAULT ''0000-00-00 00:00:00'' "" ColDecimal101 null.Decimal `json:"col_decimal_10_1,omitempty" max_len:"10"` // col_decimal_10_1 decimal(10,1) unsigned NULL DEFAULT 'NULL' "" ColDecimal124 null.Decimal `json:"col_decimal_12_4,omitempty" max_len:"12"` // col_decimal_12_4 decimal(12,4) NULL DEFAULT 'NULL' "" PriceA124 null.Decimal `json:"price_a_12_4,omitempty" max_len:"12"` // price_a_12_4 decimal(12,4) NULL DEFAULT 'NULL' "" PriceB124 null.Decimal `json:"price_b_12_4,omitempty" max_len:"12"` // price_b_12_4 decimal(12,4) NOT NULL DEFAULT '0.0000' "" ColDecimal123 null.Decimal `json:"col_decimal_12_3,omitempty" max_len:"12"` // col_decimal_12_3 decimal(12,3) NOT NULL DEFAULT '0.000' "" ColDecimal206 null.Decimal `json:"col_decimal_20_6,omitempty" max_len:"20"` // col_decimal_20_6 decimal(20,6) NOT NULL DEFAULT '0.000000' "" ColDecimal2412 null.Decimal `json:"col_decimal_24_12,omitempty" max_len:"24"` // col_decimal_24_12 decimal(24,12) NOT NULL DEFAULT '0.000000000000' "" ColInt1 null.Int32 `json:"col_int_1,omitempty" max_len:"10"` // col_int_1 int(10) NULL DEFAULT 'NULL' "" ColInt2 int32 `json:"col_int_2,omitempty" max_len:"10"` // col_int_2 int(10) NOT NULL DEFAULT '0' "" ColInt3 null.Uint32 `json:"col_int_3,omitempty" max_len:"10"` // col_int_3 int(10) unsigned NULL DEFAULT 'NULL' "" ColInt4 uint32 `json:"col_int_4,omitempty" max_len:"10"` // col_int_4 int(10) unsigned NOT NULL DEFAULT '0' "" ColLongtext1 null.String `json:"col_longtext_1,omitempty" max_len:"4294967295"` // col_longtext_1 longtext NULL DEFAULT 'NULL' "" ColLongtext2 string `json:"col_longtext_2,omitempty" max_len:"4294967295"` // col_longtext_2 longtext NOT NULL DEFAULT '''' "" ColMediumblob []byte `json:"col_mediumblob,omitempty" max_len:"16777215"` // col_mediumblob mediumblob NULL DEFAULT 'NULL' "" ColMediumtext1 null.String `json:"col_mediumtext_1,omitempty" max_len:"16777215"` // col_mediumtext_1 mediumtext NULL DEFAULT 'NULL' "" ColMediumtext2 string `json:"col_mediumtext_2,omitempty" max_len:"16777215"` // col_mediumtext_2 mediumtext NOT NULL DEFAULT '''' "" ColSmallint1 null.Int32 `json:"col_smallint_1,omitempty" max_len:"5"` // col_smallint_1 smallint(5) NULL DEFAULT 'NULL' "" ColSmallint2 int32 `json:"col_smallint_2,omitempty" max_len:"5"` // col_smallint_2 smallint(5) NOT NULL DEFAULT '0' "" ColSmallint3 null.Uint32 `json:"col_smallint_3,omitempty" max_len:"5"` // col_smallint_3 smallint(5) unsigned NULL DEFAULT 'NULL' "" ColSmallint4 uint32 `json:"col_smallint_4,omitempty" max_len:"5"` // col_smallint_4 smallint(5) unsigned NOT NULL DEFAULT '0' "" HasSmallint5 bool `json:"has_smallint_5,omitempty" max_len:"5"` // has_smallint_5 smallint(5) unsigned NOT NULL DEFAULT '0' "" IsSmallint5 null.Bool `json:"is_smallint_5,omitempty" max_len:"5"` // is_smallint_5 smallint(5) NULL DEFAULT 'NULL' "" ColText null.String `json:"col_text,omitempty" max_len:"65535"` // col_text text NULL DEFAULT 'NULL' "" ColTimestamp1 time.Time `json:"col_timestamp_1,omitempty" ` // col_timestamp_1 timestamp NOT NULL DEFAULT 'current_timestamp()' "" ColTimestamp2 null.Time `json:"col_timestamp_2,omitempty" ` // col_timestamp_2 timestamp NULL DEFAULT 'NULL' "" ColTinyint1 int32 `json:"col_tinyint_1,omitempty" max_len:"3"` // col_tinyint_1 tinyint(1) NOT NULL DEFAULT '0' "" ColVarchar1 string `json:"col_varchar_1,omitempty" max_len:"1"` // col_varchar_1 varchar(1) NOT NULL DEFAULT ''0'' "" ColVarchar100 null.String `json:"col_varchar_100,omitempty" max_len:"100"` // col_varchar_100 varchar(100) NULL DEFAULT 'NULL' "" ColVarchar16 string `json:"col_varchar_16,omitempty" max_len:"16"` // col_varchar_16 varchar(16) NOT NULL DEFAULT ''de_DE'' "" ColChar1 null.String `json:"col_char_1,omitempty" max_len:"21"` // col_char_1 char(21) NULL DEFAULT 'NULL' "" ColChar2 string `json:"col_char_2,omitempty" max_len:"17"` // col_char_2 char(17) NOT NULL DEFAULT ''xchar'' "" } // SalesOrderStatusState represents a single row for DB table // sales_order_status_state. Auto generated. // Table comment: Sales Order Status Table //easyjson:json type SalesOrderStatusState struct { Status string `max_len:"32"` // status varchar(32) NOT NULL PRI "Status" State string `max_len:"32"` // state varchar(32) NOT NULL PRI "Label" IsDefault bool `max_len:"5"` // is_default smallint(5) unsigned NOT NULL DEFAULT '0' "Is Default" VisibleOnFront uint32 `max_len:"5"` // visible_on_front smallint(5) unsigned NOT NULL DEFAULT '0' "Visible on front" } // ViewCustomerAutoIncrement represents a single row for DB table // view_customer_auto_increment. Auto generated. // Table comment: VIEW //easyjson:json type ViewCustomerAutoIncrement struct { CeEntityID uint32 `max_len:"10"` // ce_entity_id int(10) unsigned NOT NULL DEFAULT '0' "Entity ID" Email null.String `max_len:"255"` // email varchar(255) NULL DEFAULT 'NULL' "Email" Firstname string `max_len:"255"` // firstname varchar(255) NOT NULL "First Name" Lastname string `max_len:"255"` // lastname varchar(255) NOT NULL "Last Name" City string `max_len:"255"` // city varchar(255) NOT NULL "City" } // ViewCustomerNoAutoIncrement represents a single row for DB table // view_customer_no_auto_increment. Auto generated. // Table comment: VIEW //easyjson:json type ViewCustomerNoAutoIncrement struct { Email null.String `max_len:"255"` // email varchar(255) NULL DEFAULT 'NULL' "Email" Firstname string `max_len:"255"` // firstname varchar(255) NOT NULL "First Name" Lastname string `max_len:"255"` // lastname varchar(255) NOT NULL "Last Name" City string `max_len:"255"` // city varchar(255) NOT NULL "City" } // TableName constants define the names of all tables. const ( TableNameCatalogProductIndexEAVDecimalIDX = "catalog_product_index_eav_decimal_idx" TableNameCoreConfiguration = "core_configuration" TableNameCustomerAddressEntity = "customer_address_entity" TableNameCustomerEntity = "customer_entity" TableNameDmlgenTypes = "dmlgen_types" TableNameSalesOrderStatusState = "sales_order_status_state" TableNameViewCustomerAutoIncrement = "view_customer_auto_increment" TableNameViewCustomerNoAutoIncrement = "view_customer_no_auto_increment" ) // Columns struct provides for all tables the name of the columns. Allows type // safety. var Columns = struct { CatalogProductIndexEAVDecimalIDX struct { EntityID string AttributeID string StoreID string SourceID string Value string } CoreConfiguration struct { ConfigID string Scope string ScopeID string Expires string Path string Value string VersionTs string VersionTe string } CustomerAddressEntity struct { EntityID string IncrementID string ParentID string CreatedAt string UpdatedAt string IsActive string City string Company string CountryID string Firstname string Lastname string Postcode string Region string Street string } CustomerEntity struct { EntityID string WebsiteID string Email string GroupID string StoreID string CreatedAt string UpdatedAt string IsActive string CreatedIn string Firstname string Lastname string Dob string PasswordHash string RpToken string RpTokenCreatedAt string DefaultBilling string DefaultShipping string Gender string } DmlgenTypes struct { ID string ColBigint1 string ColBigint2 string ColBigint3 string ColBigint4 string ColBlob string ColDate1 string ColDate2 string ColDatetime1 string ColDatetime2 string ColDecimal101 string ColDecimal124 string PriceA124 string PriceB124 string ColDecimal123 string ColDecimal206 string ColDecimal2412 string ColInt1 string ColInt2 string ColInt3 string ColInt4 string ColLongtext1 string ColLongtext2 string ColMediumblob string ColMediumtext1 string ColMediumtext2 string ColSmallint1 string ColSmallint2 string ColSmallint3 string ColSmallint4 string HasSmallint5 string IsSmallint5 string ColText string ColTimestamp1 string ColTimestamp2 string ColTinyint1 string ColVarchar1 string ColVarchar100 string ColVarchar16 string ColChar1 string ColChar2 string } SalesOrderStatusState struct { Status string State string IsDefault string VisibleOnFront string } ViewCustomerAutoIncrement struct { CeEntityID string Email string Firstname string Lastname string City string } ViewCustomerNoAutoIncrement struct { Email string Firstname string Lastname string City string } }{ CatalogProductIndexEAVDecimalIDX: struct { EntityID string AttributeID string StoreID string SourceID string Value string }{ EntityID: "entity_id", AttributeID: "attribute_id", StoreID: "store_id", SourceID: "source_id", Value: "value", }, CoreConfiguration: struct { ConfigID string Scope string ScopeID string Expires string Path string Value string VersionTs string VersionTe string }{ ConfigID: "config_id", Scope: "scope", ScopeID: "scope_id", Expires: "expires", Path: "path", Value: "value", VersionTs: "version_ts", VersionTe: "version_te", }, CustomerAddressEntity: struct { EntityID string IncrementID string ParentID string CreatedAt string UpdatedAt string IsActive string City string Company string CountryID string Firstname string Lastname string Postcode string Region string Street string }{ EntityID: "entity_id", IncrementID: "increment_id", ParentID: "parent_id", CreatedAt: "created_at", UpdatedAt: "updated_at", IsActive: "is_active", City: "city", Company: "company", CountryID: "country_id", Firstname: "firstname", Lastname: "lastname", Postcode: "postcode", Region: "region", Street: "street", }, CustomerEntity: struct { EntityID string WebsiteID string Email string GroupID string StoreID string CreatedAt string UpdatedAt string IsActive string CreatedIn string Firstname string Lastname string Dob string PasswordHash string RpToken string RpTokenCreatedAt string DefaultBilling string DefaultShipping string Gender string }{ EntityID: "entity_id", WebsiteID: "website_id", Email: "email", GroupID: "group_id", StoreID: "store_id", CreatedAt: "created_at", UpdatedAt: "updated_at", IsActive: "is_active", CreatedIn: "created_in", Firstname: "firstname", Lastname: "lastname", Dob: "dob", PasswordHash: "<PASSWORD>", RpToken: "rp_token", RpTokenCreatedAt: "rp_token_created_at", DefaultBilling: "default_billing", DefaultShipping: "default_shipping", Gender: "gender", }, DmlgenTypes: struct { ID string ColBigint1 string ColBigint2 string ColBigint3 string ColBigint4 string ColBlob string ColDate1 string ColDate2 string ColDatetime1 string ColDatetime2 string ColDecimal101 string ColDecimal124 string PriceA124 string PriceB124 string ColDecimal123 string ColDecimal206 string ColDecimal2412 string ColInt1 string ColInt2 string ColInt3 string ColInt4 string ColLongtext1 string ColLongtext2 string ColMediumblob string ColMediumtext1 string ColMediumtext2 string ColSmallint1 string ColSmallint2 string ColSmallint3 string ColSmallint4 string HasSmallint5 string IsSmallint5 string ColText string ColTimestamp1 string ColTimestamp2 string ColTinyint1 string ColVarchar1 string ColVarchar100 string ColVarchar16 string ColChar1 string ColChar2 string }{ ID: "id", ColBigint1: "col_bigint_1", ColBigint2: "col_bigint_2", ColBigint3: "col_bigint_3", ColBigint4: "col_bigint_4", ColBlob: "col_blob", ColDate1: "col_date_1", ColDate2: "col_date_2", ColDatetime1: "col_datetime_1", ColDatetime2: "col_datetime_2", ColDecimal101: "col_decimal_10_1", ColDecimal124: "col_decimal_12_4", PriceA124: "price_a_12_4", PriceB124: "price_b_12_4", ColDecimal123: "col_decimal_12_3", ColDecimal206: "col_decimal_20_6", ColDecimal2412: "col_decimal_24_12", ColInt1: "col_int_1", ColInt2: "col_int_2", ColInt3: "col_int_3", ColInt4: "col_int_4", ColLongtext1: "col_longtext_1", ColLongtext2: "col_longtext_2", ColMediumblob: "col_mediumblob", ColMediumtext1: "col_mediumtext_1", ColMediumtext2: "col_mediumtext_2", ColSmallint1: "col_smallint_1", ColSmallint2: "col_smallint_2", ColSmallint3: "col_smallint_3", ColSmallint4: "col_smallint_4", HasSmallint5: "has_smallint_5", IsSmallint5: "is_smallint_5", ColText: "col_text", ColTimestamp1: "col_timestamp_1", ColTimestamp2: "col_timestamp_2", ColTinyint1: "col_tinyint_1", ColVarchar1: "col_varchar_1", ColVarchar100: "col_varchar_100", ColVarchar16: "col_varchar_16", ColChar1: "col_char_1", ColChar2: "col_char_2", }, SalesOrderStatusState: struct { Status string State string IsDefault string VisibleOnFront string }{ Status: "status", State: "state", IsDefault: "is_default", VisibleOnFront: "visible_on_front", }, ViewCustomerAutoIncrement: struct { CeEntityID string Email string Firstname string Lastname string City string }{ CeEntityID: "ce_entity_id", Email: "email", Firstname: "firstname", Lastname: "lastname", City: "city", }, ViewCustomerNoAutoIncrement: struct { Email string Firstname string Lastname string City string }{ Email: "email", Firstname: "firstname", Lastname: "lastname", City: "city", }, } // Event functions are getting dispatched during before or after handling a // collection or an entity. // Context is always non-nil but either collection or entity pointer will be set. type ( EventCatalogProductIndexEAVDecimalIDXFn func(context.Context, *CatalogProductIndexEAVDecimalIDXes, *CatalogProductIndexEAVDecimalIDX) error EventCoreConfigurationFn func(context.Context, *CoreConfigurations, *CoreConfiguration) error EventCustomerAddressEntityFn func(context.Context, *CustomerAddressEntities, *CustomerAddressEntity) error EventCustomerEntityFn func(context.Context, *CustomerEntities, *CustomerEntity) error EventDmlgenTypesFn func(context.Context, *DmlgenTypesCollection, *DmlgenTypes) error EventSalesOrderStatusStateFn func(context.Context, *SalesOrderStatusStates, *SalesOrderStatusState) error EventViewCustomerAutoIncrementFn func(context.Context, *ViewCustomerAutoIncrements, *ViewCustomerAutoIncrement) error EventViewCustomerNoAutoIncrementFn func(context.Context, *ViewCustomerNoAutoIncrements, *ViewCustomerNoAutoIncrement) error ) // DBMOption provides various options to the DBM object. type DBMOption struct { Trace cstrace.Tracer TableOptions []ddl.TableOption // gets applied at the beginning TableOptionsAfter []ddl.TableOption // gets applied at the end InitSelectFn func(*dml.Select) *dml.Select InitUpdateFn func(*dml.Update) *dml.Update InitDeleteFn func(*dml.Delete) *dml.Delete InitInsertFn func(*dml.Insert) *dml.Insert eventCatalogProductIndexEAVDecimalIDXFunc [dml.EventFlagMax][]EventCatalogProductIndexEAVDecimalIDXFn eventCoreConfigurationFunc [dml.EventFlagMax][]EventCoreConfigurationFn eventCustomerAddressEntityFunc [dml.EventFlagMax][]EventCustomerAddressEntityFn eventCustomerEntityFunc [dml.EventFlagMax][]EventCustomerEntityFn eventDmlgenTypesFunc [dml.EventFlagMax][]EventDmlgenTypesFn eventSalesOrderStatusStateFunc [dml.EventFlagMax][]EventSalesOrderStatusStateFn eventViewCustomerAutoIncrementFunc [dml.EventFlagMax][]EventViewCustomerAutoIncrementFn eventViewCustomerNoAutoIncrementFunc [dml.EventFlagMax][]EventViewCustomerNoAutoIncrementFn } // AddEventCatalogProductIndexEAVDecimalIDX adds a specific defined event call // back to the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventCatalogProductIndexEAVDecimalIDX(event dml.EventFlag, fn EventCatalogProductIndexEAVDecimalIDXFn) *DBMOption { o.eventCatalogProductIndexEAVDecimalIDXFunc[event] = append(o.eventCatalogProductIndexEAVDecimalIDXFunc[event], fn) return o } // AddEventCoreConfiguration adds a specific defined event call back to the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventCoreConfiguration(event dml.EventFlag, fn EventCoreConfigurationFn) *DBMOption { o.eventCoreConfigurationFunc[event] = append(o.eventCoreConfigurationFunc[event], fn) return o } // AddEventCustomerAddressEntity adds a specific defined event call back to the // DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventCustomerAddressEntity(event dml.EventFlag, fn EventCustomerAddressEntityFn) *DBMOption { o.eventCustomerAddressEntityFunc[event] = append(o.eventCustomerAddressEntityFunc[event], fn) return o } // AddEventCustomerEntity adds a specific defined event call back to the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventCustomerEntity(event dml.EventFlag, fn EventCustomerEntityFn) *DBMOption { o.eventCustomerEntityFunc[event] = append(o.eventCustomerEntityFunc[event], fn) return o } // AddEventDmlgenTypes adds a specific defined event call back to the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventDmlgenTypes(event dml.EventFlag, fn EventDmlgenTypesFn) *DBMOption { o.eventDmlgenTypesFunc[event] = append(o.eventDmlgenTypesFunc[event], fn) return o } // AddEventSalesOrderStatusState adds a specific defined event call back to the // DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventSalesOrderStatusState(event dml.EventFlag, fn EventSalesOrderStatusStateFn) *DBMOption { o.eventSalesOrderStatusStateFunc[event] = append(o.eventSalesOrderStatusStateFunc[event], fn) return o } // AddEventViewCustomerAutoIncrement adds a specific defined event call back to // the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventViewCustomerAutoIncrement(event dml.EventFlag, fn EventViewCustomerAutoIncrementFn) *DBMOption { o.eventViewCustomerAutoIncrementFunc[event] = append(o.eventViewCustomerAutoIncrementFunc[event], fn) return o } // AddEventViewCustomerNoAutoIncrement adds a specific defined event call back to // the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventViewCustomerNoAutoIncrement(event dml.EventFlag, fn EventViewCustomerNoAutoIncrementFn) *DBMOption { o.eventViewCustomerNoAutoIncrementFunc[event] = append(o.eventViewCustomerNoAutoIncrementFunc[event], fn) return o } // DBM defines the DataBaseManagement object for the tables // catalog_product_index_eav_decimal_idx, core_configuration, // customer_address_entity, customer_entity, dmlgen_types, // sales_order_status_state, view_customer_auto_increment, // view_customer_no_auto_increment type DBM struct { *ddl.Tables option DBMOption } func (dbm DBM) eventCatalogProductIndexEAVDecimalIDXFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *CatalogProductIndexEAVDecimalIDXes, e *CatalogProductIndexEAVDecimalIDX) error { if len(dbm.option.eventCatalogProductIndexEAVDecimalIDXFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventCatalogProductIndexEAVDecimalIDXFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventCoreConfigurationFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *CoreConfigurations, e *CoreConfiguration) error { if len(dbm.option.eventCoreConfigurationFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventCoreConfigurationFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventCustomerAddressEntityFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *CustomerAddressEntities, e *CustomerAddressEntity) error { if len(dbm.option.eventCustomerAddressEntityFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventCustomerAddressEntityFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventCustomerEntityFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *CustomerEntities, e *CustomerEntity) error { if len(dbm.option.eventCustomerEntityFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventCustomerEntityFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventDmlgenTypesFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *DmlgenTypesCollection, e *DmlgenTypes) error { if len(dbm.option.eventDmlgenTypesFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventDmlgenTypesFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventSalesOrderStatusStateFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *SalesOrderStatusStates, e *SalesOrderStatusState) error { if len(dbm.option.eventSalesOrderStatusStateFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventSalesOrderStatusStateFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventViewCustomerAutoIncrementFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *ViewCustomerAutoIncrements, e *ViewCustomerAutoIncrement) error { if len(dbm.option.eventViewCustomerAutoIncrementFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventViewCustomerAutoIncrementFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventViewCustomerNoAutoIncrementFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *ViewCustomerNoAutoIncrements, e *ViewCustomerNoAutoIncrement) error { if len(dbm.option.eventViewCustomerNoAutoIncrementFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventViewCustomerNoAutoIncrementFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } // NewDBManager returns a goified version of the MySQL/MariaDB table schema for // the tables: catalog_product_index_eav_decimal_idx, core_configuration, // customer_address_entity, customer_entity, dmlgen_types, // sales_order_status_state, view_customer_auto_increment, // view_customer_no_auto_increment Auto generated by dmlgen. func NewDBManager(ctx context.Context, dbmo *DBMOption) (*DBM, error) { tbls, err := ddl.NewTables(append([]ddl.TableOption{ddl.WithCreateTable(ctx, TableNameCatalogProductIndexEAVDecimalIDX, "", TableNameCoreConfiguration, "", TableNameCustomerAddressEntity, "", TableNameCustomerEntity, "", TableNameDmlgenTypes, "", TableNameSalesOrderStatusState, "", TableNameViewCustomerAutoIncrement, "", TableNameViewCustomerNoAutoIncrement, "")}, dbmo.TableOptions...)...) if err != nil { return nil, errors.WithStack(err) } if dbmo.InitSelectFn == nil { dbmo.InitSelectFn = func(s *dml.Select) *dml.Select { return s } } if dbmo.InitUpdateFn == nil { dbmo.InitUpdateFn = func(s *dml.Update) *dml.Update { return s } } if dbmo.InitDeleteFn == nil { dbmo.InitDeleteFn = func(s *dml.Delete) *dml.Delete { return s } } if dbmo.InitInsertFn == nil { dbmo.InitInsertFn = func(s *dml.Insert) *dml.Insert { return s } } err = tbls.Options( ddl.WithQueryDBR(map[string]dml.QueryBuilder{ "CatalogProductIndexEAVDecimalIDXesSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Select("*")), "CatalogProductIndexEAVDecimalIDXesSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Select("*")).Where( dml.Columns(`entity_id`, `attribute_id`, `store_id`, `source_id`).In().Tuples(), ), "CatalogProductIndexEAVDecimalIDXSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Select("*")).Where( dml.Columns(`entity_id`, `attribute_id`, `store_id`, `source_id`).Equal().Tuples(), ), "CatalogProductIndexEAVDecimalIDXUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Update().Where( dml.Columns(`entity_id`, `attribute_id`, `store_id`, `source_id`).Equal().Tuples(), )), "CatalogProductIndexEAVDecimalIDXDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Delete().Where( dml.Columns(`entity_id`, `attribute_id`, `store_id`, `source_id`).In().Tuples(), )), "CatalogProductIndexEAVDecimalIDXInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Insert()), "CatalogProductIndexEAVDecimalIDXUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX).Insert()).OnDuplicateKey(), "CoreConfigurationsSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameCoreConfiguration).Select("*")), "CoreConfigurationsSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCoreConfiguration).Select("*")).Where( dml.Column(`config_id`).In().PlaceHolder(), ), "CoreConfigurationSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCoreConfiguration).Select("*")).Where( dml.Column(`config_id`).Equal().PlaceHolder(), ), "CoreConfigurationUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameCoreConfiguration).Update().Where( dml.Column(`config_id`).Equal().PlaceHolder(), )), "CoreConfigurationDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameCoreConfiguration).Delete().Where( dml.Column(`config_id`).In().PlaceHolder(), )), "CoreConfigurationInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameCoreConfiguration).Insert()), "CoreConfigurationUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameCoreConfiguration).Insert()).OnDuplicateKey(), "CustomerAddressEntitiesSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerAddressEntity).Select("*")), "CustomerAddressEntitiesSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerAddressEntity).Select("*")).Where( dml.Column(`entity_id`).In().PlaceHolder(), ), "CustomerAddressEntitySelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerAddressEntity).Select("*")).Where( dml.Column(`entity_id`).Equal().PlaceHolder(), ), "CustomerAddressEntityUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameCustomerAddressEntity).Update().Where( dml.Column(`entity_id`).Equal().PlaceHolder(), )), "CustomerAddressEntityDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameCustomerAddressEntity).Delete().Where( dml.Column(`entity_id`).In().PlaceHolder(), )), "CustomerAddressEntityInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameCustomerAddressEntity).Insert()), "CustomerAddressEntityUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameCustomerAddressEntity).Insert()).OnDuplicateKey(), "CustomerEntitiesSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerEntity).Select("*")), "CustomerEntitiesSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerEntity).Select("*")).Where( dml.Column(`entity_id`).In().PlaceHolder(), ), "CustomerEntitySelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerEntity).Select("*")).Where( dml.Column(`entity_id`).Equal().PlaceHolder(), ), "CustomerEntityUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameCustomerEntity).Update().Where( dml.Column(`entity_id`).Equal().PlaceHolder(), )), "CustomerEntityDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameCustomerEntity).Delete().Where( dml.Column(`entity_id`).In().PlaceHolder(), )), "CustomerEntityInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameCustomerEntity).Insert()), "CustomerEntityUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameCustomerEntity).Insert()).OnDuplicateKey(), // <FOREIGN_KEY_QUERIES customer_entity > "CustomerAddressEntitiesDeleteByFK": dbmo.InitDeleteFn(tbls.MustTable(TableNameCustomerAddressEntity).Delete().Where( dml.Column(`parent_id`).Equal().PlaceHolder(), )), "CustomerAddressEntitiesSelectByFK": dbmo.InitSelectFn(tbls.MustTable(TableNameCustomerAddressEntity).Select("*").Where( dml.Column(`parent_id`).Equal().PlaceHolder(), )), // </FOREIGN_KEY_QUERIES customer_entity > "DmlgenTypesCollectionSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameDmlgenTypes).Select("*")), "DmlgenTypesCollectionSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameDmlgenTypes).Select("*")).Where( dml.Column(`id`).In().PlaceHolder(), ), "DmlgenTypesSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameDmlgenTypes).Select("*")).Where( dml.Column(`id`).Equal().PlaceHolder(), ), "DmlgenTypesUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameDmlgenTypes).Update().Where( dml.Column(`id`).Equal().PlaceHolder(), )), "DmlgenTypesDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameDmlgenTypes).Delete().Where( dml.Column(`id`).In().PlaceHolder(), )), "DmlgenTypesInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameDmlgenTypes).Insert()), "DmlgenTypesUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameDmlgenTypes).Insert()).OnDuplicateKey(), "SalesOrderStatusStatesSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameSalesOrderStatusState).Select("*")), "SalesOrderStatusStatesSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameSalesOrderStatusState).Select("*")).Where( dml.Columns(`status`, `state`).In().Tuples(), ), "SalesOrderStatusStateSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameSalesOrderStatusState).Select("*")).Where( dml.Columns(`status`, `state`).Equal().Tuples(), ), "SalesOrderStatusStateUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameSalesOrderStatusState).Update().Where( dml.Columns(`status`, `state`).Equal().Tuples(), )), "SalesOrderStatusStateDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameSalesOrderStatusState).Delete().Where( dml.Columns(`status`, `state`).In().Tuples(), )), "SalesOrderStatusStateInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameSalesOrderStatusState).Insert()), "SalesOrderStatusStateUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameSalesOrderStatusState).Insert()).OnDuplicateKey(), "ViewCustomerAutoIncrementsSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameViewCustomerAutoIncrement).Select("*")), "ViewCustomerAutoIncrementsSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameViewCustomerAutoIncrement).Select("*")).Where( dml.Column(`ce_entity_id`).In().PlaceHolder(), ), "ViewCustomerAutoIncrementSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameViewCustomerAutoIncrement).Select("*")).Where( dml.Column(`ce_entity_id`).Equal().PlaceHolder(), ), }), ) if err != nil { return nil, err } if err := tbls.Options(dbmo.TableOptionsAfter...); err != nil { return nil, err } if dbmo.Trace == nil { dbmo.Trace = cstrace.NewNoopTracerProvider().Tracer("") } return &DBM{Tables: tbls, option: *dbmo}, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *CatalogProductIndexEAVDecimalIDX) Copy() *CatalogProductIndexEAVDecimalIDX { if e == nil { return &CatalogProductIndexEAVDecimalIDX{} } e2 := *e // for now a shallow copy return &e2 } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *CatalogProductIndexEAVDecimalIDX) MapColumns(cm *dml.ColumnMap) error { for cm.Next(5) { switch c := cm.Column(); c { case "entity_id", "0": cm.Uint32(&e.EntityID) case "attribute_id", "1": cm.Uint32(&e.AttributeID) case "store_id", "2": cm.Uint32(&e.StoreID) case "source_id", "3": cm.Uint32(&e.SourceID) case "value", "4": cm.Decimal(&e.Value) default: return errors.NotFound.Newf("[dmltestgenerated] CatalogProductIndexEAVDecimalIDX Column %q not found", c) } } return errors.WithStack(cm.Err()) } type CatalogProductIndexEAVDecimalIDXLoadArgs struct { _Named_Fields_Required struct{} EntityID uint32 AttributeID uint32 StoreID uint32 SourceID uint32 } func (e *CatalogProductIndexEAVDecimalIDX) Load(ctx context.Context, dbm *DBM, arg CatalogProductIndexEAVDecimalIDXLoadArgs, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXSelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDX can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs arg.EntityID,arg.AttributeID,arg.StoreID,arg.SourceID into the context as value to search for a cache entry in the event function. if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXSelectByPK", opts...).Load(ctx, e, arg.EntityID, arg.AttributeID, arg.StoreID, arg.SourceID); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *CatalogProductIndexEAVDecimalIDX) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDX can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXDeleteByPK", opts...).ExecContext(ctx, e.EntityID, e.AttributeID, e.StoreID, e.SourceID); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CatalogProductIndexEAVDecimalIDX) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDX can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CatalogProductIndexEAVDecimalIDX) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDX can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CatalogProductIndexEAVDecimalIDX) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDX can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // Empty empties all the fields of the current object. Also known as Reset. func (e *CatalogProductIndexEAVDecimalIDX) Empty() *CatalogProductIndexEAVDecimalIDX { *e = CatalogProductIndexEAVDecimalIDX{} return e } // IsSet returns true if the entity has non-empty primary keys. func (e *CatalogProductIndexEAVDecimalIDX) IsSet() bool { return e.EntityID > 0 && e.AttributeID > 0 && e.StoreID > 0 && e.SourceID > 0 } // This variable can be set in another file to provide a custom validator. var validateCatalogProductIndexEAVDecimalIDX func(*CatalogProductIndexEAVDecimalIDX) error // Validate runs internal consistency tests. func (e *CatalogProductIndexEAVDecimalIDX) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateCatalogProductIndexEAVDecimalIDX != nil { return validateCatalogProductIndexEAVDecimalIDX(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *CatalogProductIndexEAVDecimalIDX) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "entity_id:", e.EntityID, "\n", "attribute_id:", e.AttributeID, "\n", "store_id:", e.StoreID, "\n", "source_id:", e.SourceID, "\n", "value:", e.Value, "\n", ) return int64(n2), err } // CatalogProductIndexEAVDecimalIDXes represents a collection type for DB table // catalog_product_index_eav_decimal_idx // Not thread safe. Auto generated. type CatalogProductIndexEAVDecimalIDXes struct { Data []*CatalogProductIndexEAVDecimalIDX `json:"data,omitempty"` } // NewCatalogProductIndexEAVDecimalIDXes creates a new initialized collection. // Auto generated. func NewCatalogProductIndexEAVDecimalIDXes() *CatalogProductIndexEAVDecimalIDXes { return &CatalogProductIndexEAVDecimalIDXes{ Data: make([]*CatalogProductIndexEAVDecimalIDX, 0, 5), } } // Append will add a new item at the end of * CatalogProductIndexEAVDecimalIDXes // . Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Append(n ...*CatalogProductIndexEAVDecimalIDX) *CatalogProductIndexEAVDecimalIDXes { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Clear() *CatalogProductIndexEAVDecimalIDXes { if cc == nil { *cc = CatalogProductIndexEAVDecimalIDXes{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Cut(i, j int) *CatalogProductIndexEAVDecimalIDXes { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } func (cc *CatalogProductIndexEAVDecimalIDXes) scanColumns(cm *dml.ColumnMap, e *CatalogProductIndexEAVDecimalIDX) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *CatalogProductIndexEAVDecimalIDXes) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e CatalogProductIndexEAVDecimalIDX if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "entity_id": cm = cm.Uint32s(cc.EntityIDs()...) case "attribute_id": cm = cm.Uint32s(cc.AttributeIDs()...) case "store_id": cm = cm.Uint32s(cc.StoreIDs()...) case "source_id": cm = cm.Uint32s(cc.SourceIDs()...) default: return errors.NotFound.Newf("[dmltestgenerated] CatalogProductIndexEAVDecimalIDXes Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } type CatalogProductIndexEAVDecimalIDXesDBLoadArgs struct { _Named_Fields_Required struct{} EntityID uint32 AttributeID uint32 StoreID uint32 SourceID uint32 } func (cc *CatalogProductIndexEAVDecimalIDXes) DBLoad(ctx context.Context, dbm *DBM, pkIDs []CatalogProductIndexEAVDecimalIDXesDBLoadArgs, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXesDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs EntityID,AttributeID,StoreID,SourceID into the context as value to search for a cache entry in the event function. if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } cacheKey := "CatalogProductIndexEAVDecimalIDXesSelectAll" var args []interface{} if len(pkIDs) > 0 { args = make([]interface{}, 0, len(pkIDs)*4) for _, pk := range pkIDs { args = append(args, pk.EntityID) args = append(args, pk.AttributeID) args = append(args, pk.StoreID) args = append(args, pk.SourceID) } cacheKey = "CatalogProductIndexEAVDecimalIDXesSelectByPK" } if _, err = dbm.ConnPool.WithCacheKey(cacheKey, opts...).Load(ctx, cc, args...); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *CatalogProductIndexEAVDecimalIDXes) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXesDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return nil, errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDXes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *CatalogProductIndexEAVDecimalIDXes) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXesUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDXes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXUpdateByPK", opts...) dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(TableNameCatalogProductIndexEAVDecimalIDX, 1, res, err); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *CatalogProductIndexEAVDecimalIDXes) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXesInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDXes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXInsert", opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(TableNameCatalogProductIndexEAVDecimalIDX, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)) } func (cc *CatalogProductIndexEAVDecimalIDXes) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CatalogProductIndexEAVDecimalIDXesUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CatalogProductIndexEAVDecimalIDXes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CatalogProductIndexEAVDecimalIDXUpsertByPK", opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(TableNameCatalogProductIndexEAVDecimalIDX, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCatalogProductIndexEAVDecimalIDXFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Delete(i int) *CatalogProductIndexEAVDecimalIDXes { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* CatalogProductIndexEAVDecimalIDX // . Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Each(f func(*CatalogProductIndexEAVDecimalIDX)) *CatalogProductIndexEAVDecimalIDXes { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Filter(f func(*CatalogProductIndexEAVDecimalIDX) bool) *CatalogProductIndexEAVDecimalIDXes { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Insert(n *CatalogProductIndexEAVDecimalIDX, i int) *CatalogProductIndexEAVDecimalIDXes { z := cc.Data // copy the slice header z = append(z, &CatalogProductIndexEAVDecimalIDX{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CatalogProductIndexEAVDecimalIDXes) Len() int { if cc == nil { return 0 } return len(cc.Data) } // EntityIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CatalogProductIndexEAVDecimalIDXes) EntityIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.EntityID) } return ret } // AttributeIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CatalogProductIndexEAVDecimalIDXes) AttributeIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.AttributeID) } return ret } // StoreIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CatalogProductIndexEAVDecimalIDXes) StoreIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.StoreID) } return ret } // SourceIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CatalogProductIndexEAVDecimalIDXes) SourceIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.SourceID) } return ret } // Validate runs internal consistency tests on all items. func (cc *CatalogProductIndexEAVDecimalIDXes) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *CatalogProductIndexEAVDecimalIDXes) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *CoreConfiguration) Copy() *CoreConfiguration { if e == nil { return &CoreConfiguration{} } e2 := *e // for now a shallow copy return &e2 } // AssignLastInsertID updates the increment ID field with the last inserted ID // from an INSERT operation. Implements dml.InsertIDAssigner. Auto generated. func (e *CoreConfiguration) AssignLastInsertID(id int64) { e.ConfigID = uint32(id) } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *CoreConfiguration) MapColumns(cm *dml.ColumnMap) error { for cm.Next(8) { switch c := cm.Column(); c { case "config_id", "0": cm.Uint32(&e.ConfigID) case "scope", "1": cm.String(&e.Scope) case "scope_id", "2": cm.Int32(&e.ScopeID) case "expires", "3": cm.NullTime(&e.Expires) case "path", "storage_location", "config_directory", "4": cm.String(&e.Path) case "value", "5": cm.NullString(&e.Value) case "version_ts", "6": cm.Time(&e.VersionTs) case "version_te", "7": cm.Time(&e.VersionTe) default: return errors.NotFound.Newf("[dmltestgenerated] CoreConfiguration Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *CoreConfiguration) Load(ctx context.Context, dbm *DBM, primaryKey uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationSelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("CoreConfigurationSelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *CoreConfiguration) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationDeleteByPK", opts...).ExecContext(ctx, e.ConfigID); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CoreConfiguration) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CoreConfiguration) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CoreConfiguration) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // Empty empties all the fields of the current object. Also known as Reset. func (e *CoreConfiguration) Empty() *CoreConfiguration { *e = CoreConfiguration{}; return e } // IsSet returns true if the entity has non-empty primary keys. func (e *CoreConfiguration) IsSet() bool { return e.ConfigID > 0 } // This variable can be set in another file to provide a custom validator. var validateCoreConfiguration func(*CoreConfiguration) error // Validate runs internal consistency tests. func (e *CoreConfiguration) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateCoreConfiguration != nil { return validateCoreConfiguration(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *CoreConfiguration) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "config_id:", e.ConfigID, "\n", "scope:", e.Scope, "\n", "scope_id:", e.ScopeID, "\n", "expires:", e.Expires, "\n", "path:", e.Path, "\n", "value:", e.Value, "\n", "version_ts:", e.VersionTs, "\n", "version_te:", e.VersionTe, "\n", ) return int64(n2), err } // CoreConfigurations represents a collection type for DB table // core_configuration // Not thread safe. Auto generated. //easyjson:json type CoreConfigurations struct { Data []*CoreConfiguration `json:"data,omitempty"` } // NewCoreConfigurations creates a new initialized collection. Auto generated. func NewCoreConfigurations() *CoreConfigurations { return &CoreConfigurations{ Data: make([]*CoreConfiguration, 0, 5), } } // Append will add a new item at the end of * CoreConfigurations . Auto generated // via dmlgen. func (cc *CoreConfigurations) Append(n ...*CoreConfiguration) *CoreConfigurations { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *CoreConfigurations) Clear() *CoreConfigurations { if cc == nil { *cc = CoreConfigurations{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *CoreConfigurations) Cut(i, j int) *CoreConfigurations { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } // AssignLastInsertID traverses through the slice and sets an incrementing new ID // to each entity. func (cc *CoreConfigurations) AssignLastInsertID(id int64) { for i := 0; i < len(cc.Data); i++ { cc.Data[i].AssignLastInsertID(id + int64(i)) } } func (cc *CoreConfigurations) scanColumns(cm *dml.ColumnMap, e *CoreConfiguration) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *CoreConfigurations) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e CoreConfiguration if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "config_id": cm = cm.Uint32s(cc.ConfigIDs()...) default: return errors.NotFound.Newf("[dmltestgenerated] CoreConfigurations Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *CoreConfigurations) DBLoad(ctx context.Context, dbm *DBM, pkIDs []uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationsDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs ConfigID into the context as value to search for a cache entry in the event function. if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("CoreConfigurationsSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("CoreConfigurationsSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *CoreConfigurations) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationsDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return nil, errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *CoreConfigurations) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationsUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CoreConfigurationUpdateByPK", opts...) dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(TableNameCoreConfiguration, 1, res, err); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *CoreConfigurations) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationsInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CoreConfigurationInsert", opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(TableNameCoreConfiguration, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)) } func (cc *CoreConfigurations) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CoreConfigurationsUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CoreConfigurationUpsertByPK", opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(TableNameCoreConfiguration, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *CoreConfigurations) Delete(i int) *CoreConfigurations { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* CoreConfiguration . Auto // generated via dmlgen. func (cc *CoreConfigurations) Each(f func(*CoreConfiguration)) *CoreConfigurations { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *CoreConfigurations) Filter(f func(*CoreConfiguration) bool) *CoreConfigurations { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *CoreConfigurations) Insert(n *CoreConfiguration, i int) *CoreConfigurations { z := cc.Data // copy the slice header z = append(z, &CoreConfiguration{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CoreConfigurations) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CoreConfigurations) Len() int { if cc == nil { return 0 } return len(cc.Data) } // ConfigIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CoreConfigurations) ConfigIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.ConfigID) } return ret } // Paths belongs to the column "path" and returns a slice or appends to a slice // only unique values of that column. The values will be filtered internally in a // Go map. No DB query gets executed. Auto generated. func (cc *CoreConfigurations) UniquePaths(ret ...string) []string { if cc == nil { return nil } if ret == nil { ret = make([]string, 0, len(cc.Data)) } dupCheck := make(map[string]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.Path] { ret = append(ret, e.Path) dupCheck[e.Path] = true } } return ret } // Validate runs internal consistency tests on all items. func (cc *CoreConfigurations) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *CoreConfigurations) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *CustomerAddressEntity) Copy() *CustomerAddressEntity { if e == nil { return &CustomerAddressEntity{} } e2 := *e // for now a shallow copy return &e2 } // AssignLastInsertID updates the increment ID field with the last inserted ID // from an INSERT operation. Implements dml.InsertIDAssigner. Auto generated. func (e *CustomerAddressEntity) AssignLastInsertID(id int64) { e.EntityID = uint32(id) } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *CustomerAddressEntity) MapColumns(cm *dml.ColumnMap) error { for cm.Next(14) { switch c := cm.Column(); c { case "entity_id", "0": cm.Uint32(&e.EntityID) case "increment_id", "1": cm.NullString(&e.IncrementID) case "parent_id", "2": cm.NullUint32(&e.ParentID) case "created_at", "3": cm.Time(&e.CreatedAt) case "updated_at", "4": cm.Time(&e.UpdatedAt) case "is_active", "5": cm.Bool(&e.IsActive) case "city", "6": cm.String(&e.City) case "company", "7": cm.NullString(&e.Company) case "country_id", "8": cm.String(&e.CountryID) case "firstname", "9": cm.String(&e.Firstname) case "lastname", "10": cm.String(&e.Lastname) case "postcode", "11": cm.NullString(&e.Postcode) case "region", "12": cm.NullString(&e.Region) case "street", "13": cm.String(&e.Street) default: return errors.NotFound.Newf("[dmltestgenerated] CustomerAddressEntity Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *CustomerAddressEntity) Load(ctx context.Context, dbm *DBM, primaryKey uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntitySelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("CustomerAddressEntity can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntitySelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *CustomerAddressEntity) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntityDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerAddressEntity can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntityDeleteByPK", opts...).ExecContext(ctx, e.EntityID); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CustomerAddressEntity) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntityUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerAddressEntity can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntityUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CustomerAddressEntity) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntityInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerAddressEntity can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntityInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CustomerAddressEntity) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntityUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerAddressEntity can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntityUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // Empty empties all the fields of the current object. Also known as Reset. func (e *CustomerAddressEntity) Empty() *CustomerAddressEntity { *e = CustomerAddressEntity{} return e } // IsSet returns true if the entity has non-empty primary keys. func (e *CustomerAddressEntity) IsSet() bool { return e.EntityID > 0 } // This variable can be set in another file to provide a custom validator. var validateCustomerAddressEntity func(*CustomerAddressEntity) error // Validate runs internal consistency tests. func (e *CustomerAddressEntity) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateCustomerAddressEntity != nil { return validateCustomerAddressEntity(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *CustomerAddressEntity) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "entity_id:", e.EntityID, "\n", "increment_id:", e.IncrementID, "\n", "parent_id:", e.ParentID, "\n", "created_at:", e.CreatedAt, "\n", "updated_at:", e.UpdatedAt, "\n", "is_active:", e.IsActive, "\n", "city:", e.City, "\n", "company:", e.Company, "\n", "country_id:", e.CountryID, "\n", "firstname:", e.Firstname, "\n", "lastname:", e.Lastname, "\n", "postcode:", e.Postcode, "\n", "region:", e.Region, "\n", "street:", e.Street, "\n", ) return int64(n2), err } // CustomerAddressEntities represents a collection type for DB table // customer_address_entity // Not thread safe. Auto generated. //easyjson:json type CustomerAddressEntities struct { Data []*CustomerAddressEntity `json:"data,omitempty"` } // NewCustomerAddressEntities creates a new initialized collection. Auto // generated. func NewCustomerAddressEntities() *CustomerAddressEntities { return &CustomerAddressEntities{ Data: make([]*CustomerAddressEntity, 0, 5), } } // Append will add a new item at the end of * CustomerAddressEntities . Auto // generated via dmlgen. func (cc *CustomerAddressEntities) Append(n ...*CustomerAddressEntity) *CustomerAddressEntities { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *CustomerAddressEntities) Clear() *CustomerAddressEntities { if cc == nil { *cc = CustomerAddressEntities{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *CustomerAddressEntities) Cut(i, j int) *CustomerAddressEntities { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } // AssignLastInsertID traverses through the slice and sets an incrementing new ID // to each entity. func (cc *CustomerAddressEntities) AssignLastInsertID(id int64) { for i := 0; i < len(cc.Data); i++ { cc.Data[i].AssignLastInsertID(id + int64(i)) } } func (cc *CustomerAddressEntities) scanColumns(cm *dml.ColumnMap, e *CustomerAddressEntity) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *CustomerAddressEntities) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e CustomerAddressEntity if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "entity_id": cm = cm.Uint32s(cc.EntityIDs()...) default: return errors.NotFound.Newf("[dmltestgenerated] CustomerAddressEntities Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *CustomerAddressEntities) DBLoad(ctx context.Context, dbm *DBM, pkIDs []uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntitiesDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs EntityID into the context as value to search for a cache entry in the event function. if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntitiesSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntitiesSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *CustomerAddressEntities) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntitiesDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return nil, errors.NotValid.Newf("CustomerAddressEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntityDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *CustomerAddressEntities) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntitiesUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CustomerAddressEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CustomerAddressEntityUpdateByPK", opts...) dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(TableNameCustomerAddressEntity, 1, res, err); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *CustomerAddressEntities) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntitiesInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CustomerAddressEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CustomerAddressEntityInsert", opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(TableNameCustomerAddressEntity, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)) } func (cc *CustomerAddressEntities) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerAddressEntitiesUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CustomerAddressEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CustomerAddressEntityUpsertByPK", opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(TableNameCustomerAddressEntity, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCustomerAddressEntityFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *CustomerAddressEntities) Delete(i int) *CustomerAddressEntities { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* CustomerAddressEntity . Auto // generated via dmlgen. func (cc *CustomerAddressEntities) Each(f func(*CustomerAddressEntity)) *CustomerAddressEntities { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *CustomerAddressEntities) Filter(f func(*CustomerAddressEntity) bool) *CustomerAddressEntities { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *CustomerAddressEntities) Insert(n *CustomerAddressEntity, i int) *CustomerAddressEntities { z := cc.Data // copy the slice header z = append(z, &CustomerAddressEntity{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CustomerAddressEntities) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CustomerAddressEntities) Len() int { if cc == nil { return 0 } return len(cc.Data) } // EntityIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CustomerAddressEntities) EntityIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.EntityID) } return ret } // Validate runs internal consistency tests on all items. func (cc *CustomerAddressEntities) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *CustomerAddressEntities) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } func (r *customerEntityRelations) DeleteCustomerAddressEntities(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error { dbr := dbm.ConnPool.WithCacheKey("CustomerAddressEntitiesDeleteByFK", opts...) res, err := dbr.ExecContext(ctx, r.parent.EntityID) err = dbr.ResultCheckFn(TableNameCustomerAddressEntity, len(r.CustomerAddressEntities.Data), res, err) if err == nil && r.CustomerAddressEntities != nil { r.CustomerAddressEntities.Clear() } return errors.WithStack(err) } func (r *customerEntityRelations) InsertCustomerAddressEntities(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error { if r.CustomerAddressEntities == nil || len(r.CustomerAddressEntities.Data) == 0 { return nil } for _, e2 := range r.CustomerAddressEntities.Data { e2.ParentID = null.MakeUint32(uint32(r.parent.EntityID)) } return errors.WithStack(r.CustomerAddressEntities.DBInsert(ctx, dbm, opts...)) } func (r *customerEntityRelations) UpdateCustomerAddressEntities(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { if r.CustomerAddressEntities == nil || len(r.CustomerAddressEntities.Data) == 0 { dbr := dbm.ConnPool.WithCacheKey("CustomerAddressEntitiesDeleteByFK", opts...) res, err := dbr.ExecContext(ctx, r.parent.EntityID) return dbr.ResultCheckFn(TableNameCustomerAddressEntity, -1, res, errors.WithStack(err)) } for _, e2 := range r.CustomerAddressEntities.Data { e2.ParentID = null.MakeUint32(uint32(r.parent.EntityID)) } err = r.CustomerAddressEntities.DBUpdate(ctx, dbm, opts...) return errors.WithStack(err) } func (r *customerEntityRelations) LoadCustomerAddressEntities(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (rowCount uint64, err error) { if r.CustomerAddressEntities == nil { r.CustomerAddressEntities = &CustomerAddressEntities{} } r.CustomerAddressEntities.Clear() rowCount, err = dbm.ConnPool.WithCacheKey("CustomerAddressEntitiesSelectByFK", opts...).Load(ctx, r.CustomerAddressEntities, r.parent.EntityID) return rowCount, errors.WithStack(err) } func (r *customerEntityRelations) InsertAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error { if err := r.InsertCustomerAddressEntities(ctx, dbm, opts...); err != nil { return errors.WithStack(err) } return nil } func (r *customerEntityRelations) LoadAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { if _, err = r.LoadCustomerAddressEntities(ctx, dbm, opts...); err != nil { return errors.WithStack(err) } return nil } func (r *customerEntityRelations) UpdateAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error { if err := r.UpdateCustomerAddressEntities(ctx, dbm, opts...); err != nil { return errors.WithStack(err) } return nil } func (r *customerEntityRelations) DeleteAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error { if err := r.DeleteCustomerAddressEntities(ctx, dbm, opts...); err != nil { return errors.WithStack(err) } return nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *CustomerEntity) Copy() *CustomerEntity { if e == nil { return &CustomerEntity{} } e2 := *e // for now a shallow copy return &e2 } // AssignLastInsertID updates the increment ID field with the last inserted ID // from an INSERT operation. Implements dml.InsertIDAssigner. Auto generated. func (e *CustomerEntity) AssignLastInsertID(id int64) { e.EntityID = uint32(id) } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *CustomerEntity) MapColumns(cm *dml.ColumnMap) error { for cm.Next(18) { switch c := cm.Column(); c { case "entity_id", "0": cm.Uint32(&e.EntityID) case "website_id", "1": cm.NullUint32(&e.WebsiteID) case "email", "2": cm.NullString(&e.Email) case "group_id", "3": cm.Uint32(&e.GroupID) case "store_id", "4": cm.NullUint32(&e.StoreID) case "created_at", "5": cm.Time(&e.CreatedAt) case "updated_at", "6": cm.Time(&e.UpdatedAt) case "is_active", "7": cm.Bool(&e.IsActive) case "created_in", "8": cm.NullString(&e.CreatedIn) case "firstname", "9": cm.NullString(&e.Firstname) case "lastname", "10": cm.NullString(&e.Lastname) case "dob", "11": cm.NullTime(&e.Dob) case "password_hash", "12": cm.NullString(&e.passwordHash) case "rp_token", "13": cm.NullString(&e.RpToken) case "rp_token_created_at", "14": cm.NullTime(&e.RpTokenCreatedAt) case "default_billing", "15": cm.NullUint32(&e.DefaultBilling) case "default_shipping", "16": cm.NullUint32(&e.DefaultShipping) case "gender", "17": cm.NullUint32(&e.Gender) default: return errors.NotFound.Newf("[dmltestgenerated] CustomerEntity Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *CustomerEntity) Load(ctx context.Context, dbm *DBM, primaryKey uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntitySelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("CustomerEntity can't be nil") } e.setRelationParent() qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("CustomerEntitySelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *CustomerEntity) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntityDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerEntity can't be nil") } e.setRelationParent() qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerEntityDeleteByPK", opts...).ExecContext(ctx, e.EntityID); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CustomerEntity) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntityUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerEntity can't be nil") } e.setRelationParent() qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerEntityUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CustomerEntity) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntityInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerEntity can't be nil") } e.setRelationParent() qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerEntityInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CustomerEntity) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntityUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("CustomerEntity can't be nil") } e.setRelationParent() qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerEntityUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // Empty empties all the fields of the current object. Also known as Reset. func (e *CustomerEntity) Empty() *CustomerEntity { *e = CustomerEntity{}; return e } // IsSet returns true if the entity has non-empty primary keys. func (e *CustomerEntity) IsSet() bool { return e.EntityID > 0 } // Set PasswordHash sets the data for a private and security sensitive field. func (e *CustomerEntity) SetPasswordHash(d null.String) *CustomerEntity { e.passwordHash = d return e } // Get PasswordHash returns the data from a private and security sensitive // field. func (e *CustomerEntity) GetPasswordHash() null.String { return e.passwordHash } // This variable can be set in another file to provide a custom validator. var validateCustomerEntity func(*CustomerEntity) error // Validate runs internal consistency tests. func (e *CustomerEntity) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateCustomerEntity != nil { return validateCustomerEntity(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *CustomerEntity) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "entity_id:", e.EntityID, "\n", "website_id:", e.WebsiteID, "\n", "email:", e.Email, "\n", "group_id:", e.GroupID, "\n", "store_id:", e.StoreID, "\n", "created_at:", e.CreatedAt, "\n", "updated_at:", e.UpdatedAt, "\n", "is_active:", e.IsActive, "\n", "created_in:", e.CreatedIn, "\n", "firstname:", e.Firstname, "\n", "lastname:", e.Lastname, "\n", "dob:", e.Dob, "\n", "rp_token:", e.RpToken, "\n", "rp_token_created_at:", e.RpTokenCreatedAt, "\n", "default_billing:", e.DefaultBilling, "\n", "default_shipping:", e.DefaultShipping, "\n", "gender:", e.Gender, "\n", ) return int64(n2), err } // CustomerEntities represents a collection type for DB table customer_entity // Not thread safe. Auto generated. //easyjson:json type CustomerEntities struct { Data []*CustomerEntity `json:"data,omitempty"` } // NewCustomerEntities creates a new initialized collection. Auto generated. func NewCustomerEntities() *CustomerEntities { return &CustomerEntities{ Data: make([]*CustomerEntity, 0, 5), } } // Append will add a new item at the end of * CustomerEntities . Auto generated // via dmlgen. func (cc *CustomerEntities) Append(n ...*CustomerEntity) *CustomerEntities { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *CustomerEntities) Clear() *CustomerEntities { if cc == nil { *cc = CustomerEntities{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *CustomerEntities) Cut(i, j int) *CustomerEntities { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } // AssignLastInsertID traverses through the slice and sets an incrementing new ID // to each entity. func (cc *CustomerEntities) AssignLastInsertID(id int64) { for i := 0; i < len(cc.Data); i++ { cc.Data[i].AssignLastInsertID(id + int64(i)) } } func (cc *CustomerEntities) scanColumns(cm *dml.ColumnMap, e *CustomerEntity) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *CustomerEntities) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e CustomerEntity if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "entity_id": cm = cm.Uint32s(cc.EntityIDs()...) default: return errors.NotFound.Newf("[dmltestgenerated] CustomerEntities Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *CustomerEntities) DBLoad(ctx context.Context, dbm *DBM, pkIDs []uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntitiesDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs EntityID into the context as value to search for a cache entry in the event function. if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("CustomerEntitiesSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("CustomerEntitiesSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *CustomerEntities) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntitiesDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return nil, errors.NotValid.Newf("CustomerEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CustomerEntityDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *CustomerEntities) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntitiesUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CustomerEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CustomerEntityUpdateByPK", opts...) dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(TableNameCustomerEntity, 1, res, err); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *CustomerEntities) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntitiesInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CustomerEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CustomerEntityInsert", opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(TableNameCustomerEntity, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)) } func (cc *CustomerEntities) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "CustomerEntitiesUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("CustomerEntities can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventCustomerEntityFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("CustomerEntityUpsertByPK", opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(TableNameCustomerEntity, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCustomerEntityFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *CustomerEntities) Delete(i int) *CustomerEntities { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* CustomerEntity . Auto generated // via dmlgen. func (cc *CustomerEntities) Each(f func(*CustomerEntity)) *CustomerEntities { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *CustomerEntities) Filter(f func(*CustomerEntity) bool) *CustomerEntities { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *CustomerEntities) Insert(n *CustomerEntity, i int) *CustomerEntities { z := cc.Data // copy the slice header z = append(z, &CustomerEntity{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CustomerEntities) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *CustomerEntities) Len() int { if cc == nil { return 0 } return len(cc.Data) } // EntityIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CustomerEntities) EntityIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.EntityID) } return ret } // Validate runs internal consistency tests on all items. func (cc *CustomerEntities) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *CustomerEntities) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *DmlgenTypes) Copy() *DmlgenTypes { if e == nil { return &DmlgenTypes{} } e2 := *e // for now a shallow copy return &e2 } // AssignLastInsertID updates the increment ID field with the last inserted ID // from an INSERT operation. Implements dml.InsertIDAssigner. Auto generated. func (e *DmlgenTypes) AssignLastInsertID(id int64) { e.ID = int32(id) } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *DmlgenTypes) MapColumns(cm *dml.ColumnMap) error { for cm.Next(41) { switch c := cm.Column(); c { case "id", "0": cm.Int32(&e.ID) case "col_bigint_1", "1": cm.NullInt64(&e.ColBigint1) case "col_bigint_2", "2": cm.Int64(&e.ColBigint2) case "col_bigint_3", "3": cm.NullUint64(&e.ColBigint3) case "col_bigint_4", "4": cm.Uint64(&e.ColBigint4) case "col_blob", "5": cm.Byte(&e.ColBlob) case "col_date_1", "6": cm.NullTime(&e.ColDate1) case "col_date_2", "7": cm.Time(&e.ColDate2) case "col_datetime_1", "8": cm.NullTime(&e.ColDatetime1) case "col_datetime_2", "9": cm.Time(&e.ColDatetime2) case "col_decimal_10_1", "10": cm.Decimal(&e.ColDecimal101) case "col_decimal_12_4", "11": cm.Decimal(&e.ColDecimal124) case "price_a_12_4", "12": cm.Decimal(&e.PriceA124) case "price_b_12_4", "13": cm.Decimal(&e.PriceB124) case "col_decimal_12_3", "14": cm.Decimal(&e.ColDecimal123) case "col_decimal_20_6", "15": cm.Decimal(&e.ColDecimal206) case "col_decimal_24_12", "16": cm.Decimal(&e.ColDecimal2412) case "col_int_1", "17": cm.NullInt32(&e.ColInt1) case "col_int_2", "18": cm.Int32(&e.ColInt2) case "col_int_3", "19": cm.NullUint32(&e.ColInt3) case "col_int_4", "20": cm.Uint32(&e.ColInt4) case "col_longtext_1", "21": cm.NullString(&e.ColLongtext1) case "col_longtext_2", "22": cm.String(&e.ColLongtext2) case "col_mediumblob", "23": cm.Byte(&e.ColMediumblob) case "col_mediumtext_1", "24": cm.NullString(&e.ColMediumtext1) case "col_mediumtext_2", "25": cm.String(&e.ColMediumtext2) case "col_smallint_1", "26": cm.NullInt32(&e.ColSmallint1) case "col_smallint_2", "27": cm.Int32(&e.ColSmallint2) case "col_smallint_3", "28": cm.NullUint32(&e.ColSmallint3) case "col_smallint_4", "29": cm.Uint32(&e.ColSmallint4) case "has_smallint_5", "30": cm.Bool(&e.HasSmallint5) case "is_smallint_5", "31": cm.NullBool(&e.IsSmallint5) case "col_text", "32": cm.NullString(&e.ColText) case "col_timestamp_1", "33": cm.Time(&e.ColTimestamp1) case "col_timestamp_2", "34": cm.NullTime(&e.ColTimestamp2) case "col_tinyint_1", "35": cm.Int32(&e.ColTinyint1) case "col_varchar_1", "36": cm.String(&e.ColVarchar1) case "col_varchar_100", "37": cm.NullString(&e.ColVarchar100) case "col_varchar_16", "38": cm.String(&e.ColVarchar16) case "col_char_1", "39": cm.NullString(&e.ColChar1) case "col_char_2", "40": cm.String(&e.ColChar2) default: return errors.NotFound.Newf("[dmltestgenerated] DmlgenTypes Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *DmlgenTypes) Load(ctx context.Context, dbm *DBM, primaryKey int32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesSelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("DmlgenTypes can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("DmlgenTypesSelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *DmlgenTypes) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("DmlgenTypes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("DmlgenTypesDeleteByPK", opts...).ExecContext(ctx, e.ID); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *DmlgenTypes) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("DmlgenTypes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("DmlgenTypesUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *DmlgenTypes) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("DmlgenTypes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("DmlgenTypesInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *DmlgenTypes) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("DmlgenTypes can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("DmlgenTypesUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // Empty empties all the fields of the current object. Also known as Reset. func (e *DmlgenTypes) Empty() *DmlgenTypes { *e = DmlgenTypes{}; return e } // IsSet returns true if the entity has non-empty primary keys. func (e *DmlgenTypes) IsSet() bool { return e.ID != 0 } // This variable can be set in another file to provide a custom validator. var validateDmlgenTypes func(*DmlgenTypes) error // Validate runs internal consistency tests. func (e *DmlgenTypes) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateDmlgenTypes != nil { return validateDmlgenTypes(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *DmlgenTypes) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "id:", e.ID, "\n", "col_bigint_1:", e.ColBigint1, "\n", "col_bigint_2:", e.ColBigint2, "\n", "col_bigint_3:", e.ColBigint3, "\n", "col_bigint_4:", e.ColBigint4, "\n", "col_blob:", e.ColBlob, "\n", "col_date_1:", e.ColDate1, "\n", "col_date_2:", e.ColDate2, "\n", "col_datetime_1:", e.ColDatetime1, "\n", "col_datetime_2:", e.ColDatetime2, "\n", "col_decimal_10_1:", e.ColDecimal101, "\n", "col_decimal_12_4:", e.ColDecimal124, "\n", "price_a_12_4:", e.PriceA124, "\n", "price_b_12_4:", e.PriceB124, "\n", "col_decimal_12_3:", e.ColDecimal123, "\n", "col_decimal_20_6:", e.ColDecimal206, "\n", "col_decimal_24_12:", e.ColDecimal2412, "\n", "col_int_1:", e.ColInt1, "\n", "col_int_2:", e.ColInt2, "\n", "col_int_3:", e.ColInt3, "\n", "col_int_4:", e.ColInt4, "\n", "col_longtext_1:", e.ColLongtext1, "\n", "col_longtext_2:", e.ColLongtext2, "\n", "col_mediumblob:", e.ColMediumblob, "\n", "col_mediumtext_1:", e.ColMediumtext1, "\n", "col_mediumtext_2:", e.ColMediumtext2, "\n", "col_smallint_1:", e.ColSmallint1, "\n", "col_smallint_2:", e.ColSmallint2, "\n", "col_smallint_3:", e.ColSmallint3, "\n", "col_smallint_4:", e.ColSmallint4, "\n", "has_smallint_5:", e.HasSmallint5, "\n", "is_smallint_5:", e.IsSmallint5, "\n", "col_text:", e.ColText, "\n", "col_timestamp_1:", e.ColTimestamp1, "\n", "col_timestamp_2:", e.ColTimestamp2, "\n", "col_tinyint_1:", e.ColTinyint1, "\n", "col_varchar_1:", e.ColVarchar1, "\n", "col_varchar_100:", e.ColVarchar100, "\n", "col_varchar_16:", e.ColVarchar16, "\n", "col_char_1:", e.ColChar1, "\n", "col_char_2:", e.ColChar2, "\n", ) return int64(n2), err } // DmlgenTypesCollection represents a collection type for DB table dmlgen_types // Not thread safe. Auto generated. // // Just another comment. //easyjson:json type DmlgenTypesCollection struct { Data []*DmlgenTypes `json:"data,omitempty"` } // NewDmlgenTypesCollection creates a new initialized collection. Auto // generated. func NewDmlgenTypesCollection() *DmlgenTypesCollection { return &DmlgenTypesCollection{ Data: make([]*DmlgenTypes, 0, 5), } } // Append will add a new item at the end of * DmlgenTypesCollection . Auto // generated via dmlgen. func (cc *DmlgenTypesCollection) Append(n ...*DmlgenTypes) *DmlgenTypesCollection { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Clear() *DmlgenTypesCollection { if cc == nil { *cc = DmlgenTypesCollection{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Cut(i, j int) *DmlgenTypesCollection { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } // AssignLastInsertID traverses through the slice and sets an incrementing new ID // to each entity. func (cc *DmlgenTypesCollection) AssignLastInsertID(id int64) { for i := 0; i < len(cc.Data); i++ { cc.Data[i].AssignLastInsertID(id + int64(i)) } } func (cc *DmlgenTypesCollection) scanColumns(cm *dml.ColumnMap, e *DmlgenTypes) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *DmlgenTypesCollection) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e DmlgenTypes if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "id": cm = cm.Int32s(cc.IDs()...) default: return errors.NotFound.Newf("[dmltestgenerated] DmlgenTypesCollection Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *DmlgenTypesCollection) DBLoad(ctx context.Context, dbm *DBM, pkIDs []int32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesCollectionDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs ID into the context as value to search for a cache entry in the event function. if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("DmlgenTypesCollectionSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("DmlgenTypesCollectionSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *DmlgenTypesCollection) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesCollectionDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return nil, errors.NotValid.Newf("DmlgenTypesCollection can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("DmlgenTypesDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *DmlgenTypesCollection) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesCollectionUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("DmlgenTypesCollection can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("DmlgenTypesUpdateByPK", opts...) dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(TableNameDmlgenTypes, 1, res, err); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *DmlgenTypesCollection) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesCollectionInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("DmlgenTypesCollection can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("DmlgenTypesInsert", opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(TableNameDmlgenTypes, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)) } func (cc *DmlgenTypesCollection) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "DmlgenTypesCollectionUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("DmlgenTypesCollection can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("DmlgenTypesUpsertByPK", opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(TableNameDmlgenTypes, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventDmlgenTypesFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Delete(i int) *DmlgenTypesCollection { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* DmlgenTypes . Auto generated via // dmlgen. func (cc *DmlgenTypesCollection) Each(f func(*DmlgenTypes)) *DmlgenTypesCollection { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Filter(f func(*DmlgenTypes) bool) *DmlgenTypesCollection { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Insert(n *DmlgenTypes, i int) *DmlgenTypesCollection { z := cc.Data // copy the slice header z = append(z, &DmlgenTypes{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *DmlgenTypesCollection) Len() int { if cc == nil { return 0 } return len(cc.Data) } // IDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *DmlgenTypesCollection) IDs(ret ...int32) []int32 { if cc == nil { return nil } if ret == nil { ret = make([]int32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.ID) } return ret } // ColDate2s belongs to the column "col_date_2" and returns a slice or appends to // a slice only unique values of that column. The values will be filtered // internally in a Go map. No DB query gets executed. Auto generated. func (cc *DmlgenTypesCollection) UniqueColDate2s(ret ...time.Time) []time.Time { if cc == nil { return nil } if ret == nil { ret = make([]time.Time, 0, len(cc.Data)) } dupCheck := make(map[time.Time]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.ColDate2] { ret = append(ret, e.ColDate2) dupCheck[e.ColDate2] = true } } return ret } // PriceA124s belongs to the column "price_a_12_4" and returns a slice or appends // to a slice only unique values of that column. The values will be filtered // internally in a Go map. No DB query gets executed. Auto generated. func (cc *DmlgenTypesCollection) UniquePriceA124s(ret ...null.Decimal) []null.Decimal { if cc == nil { return nil } if ret == nil { ret = make([]null.Decimal, 0, len(cc.Data)) } dupCheck := make(map[null.Decimal]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.PriceA124] { ret = append(ret, e.PriceA124) dupCheck[e.PriceA124] = true } } return ret } // ColInt1s belongs to the column "col_int_1" and returns a slice or appends to a // slice only unique values of that column. The values will be filtered // internally in a Go map. No DB query gets executed. Auto generated. func (cc *DmlgenTypesCollection) UniqueColInt1s(ret ...int32) []int32 { if cc == nil { return nil } if ret == nil { ret = make([]int32, 0, len(cc.Data)) } dupCheck := make(map[int32]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.ColInt1.Int32] { ret = append(ret, e.ColInt1.Int32) dupCheck[e.ColInt1.Int32] = true } } return ret } // ColInt2s belongs to the column "col_int_2" and returns a slice or appends to a // slice only unique values of that column. The values will be filtered // internally in a Go map. No DB query gets executed. Auto generated. func (cc *DmlgenTypesCollection) UniqueColInt2s(ret ...int32) []int32 { if cc == nil { return nil } if ret == nil { ret = make([]int32, 0, len(cc.Data)) } dupCheck := make(map[int32]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.ColInt2] { ret = append(ret, e.ColInt2) dupCheck[e.ColInt2] = true } } return ret } // HasSmallint5s belongs to the column "has_smallint_5" and returns a slice or // appends to a slice only unique values of that column. The values will be // filtered internally in a Go map. No DB query gets executed. Auto generated. func (cc *DmlgenTypesCollection) UniqueHasSmallint5s(ret ...bool) []bool { if cc == nil { return nil } if ret == nil { ret = make([]bool, 0, len(cc.Data)) } dupCheck := make(map[bool]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.HasSmallint5] { ret = append(ret, e.HasSmallint5) dupCheck[e.HasSmallint5] = true } } return ret } // ColVarchar100s belongs to the column "col_varchar_100" and returns a slice or // appends to a slice only unique values of that column. The values will be // filtered internally in a Go map. No DB query gets executed. Auto generated. func (cc *DmlgenTypesCollection) UniqueColVarchar100s(ret ...string) []string { if cc == nil { return nil } if ret == nil { ret = make([]string, 0, len(cc.Data)) } dupCheck := make(map[string]bool, len(cc.Data)) for _, e := range cc.Data { if !dupCheck[e.ColVarchar100.Data] { ret = append(ret, e.ColVarchar100.Data) dupCheck[e.ColVarchar100.Data] = true } } return ret } // Validate runs internal consistency tests on all items. func (cc *DmlgenTypesCollection) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *DmlgenTypesCollection) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *SalesOrderStatusState) Copy() *SalesOrderStatusState { if e == nil { return &SalesOrderStatusState{} } e2 := *e // for now a shallow copy return &e2 } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *SalesOrderStatusState) MapColumns(cm *dml.ColumnMap) error { for cm.Next(4) { switch c := cm.Column(); c { case "status", "0": cm.String(&e.Status) case "state", "1": cm.String(&e.State) case "is_default", "2": cm.Bool(&e.IsDefault) case "visible_on_front", "3": cm.Uint32(&e.VisibleOnFront) default: return errors.NotFound.Newf("[dmltestgenerated] SalesOrderStatusState Column %q not found", c) } } return errors.WithStack(cm.Err()) } type SalesOrderStatusStateLoadArgs struct { _Named_Fields_Required struct{} Status string State string } func (e *SalesOrderStatusState) Load(ctx context.Context, dbm *DBM, arg SalesOrderStatusStateLoadArgs, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStateSelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs arg.Status,arg.State into the context as value to search for a cache entry in the event function. if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateSelectByPK", opts...).Load(ctx, e, arg.Status, arg.State); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *SalesOrderStatusState) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStateDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateDeleteByPK", opts...).ExecContext(ctx, e.Status, e.State); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *SalesOrderStatusState) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStateUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *SalesOrderStatusState) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStateInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *SalesOrderStatusState) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStateUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return nil, errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // Empty empties all the fields of the current object. Also known as Reset. func (e *SalesOrderStatusState) Empty() *SalesOrderStatusState { *e = SalesOrderStatusState{} return e } // IsSet returns true if the entity has non-empty primary keys. func (e *SalesOrderStatusState) IsSet() bool { return e.Status != "" && e.State != "" } // This variable can be set in another file to provide a custom validator. var validateSalesOrderStatusState func(*SalesOrderStatusState) error // Validate runs internal consistency tests. func (e *SalesOrderStatusState) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateSalesOrderStatusState != nil { return validateSalesOrderStatusState(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *SalesOrderStatusState) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "status:", e.Status, "\n", "state:", e.State, "\n", "is_default:", e.IsDefault, "\n", "visible_on_front:", e.VisibleOnFront, "\n", ) return int64(n2), err } // SalesOrderStatusStates represents a collection type for DB table // sales_order_status_state // Not thread safe. Auto generated. //easyjson:json type SalesOrderStatusStates struct { Data []*SalesOrderStatusState `json:"data,omitempty"` } // NewSalesOrderStatusStates creates a new initialized collection. Auto // generated. func NewSalesOrderStatusStates() *SalesOrderStatusStates { return &SalesOrderStatusStates{ Data: make([]*SalesOrderStatusState, 0, 5), } } // Append will add a new item at the end of * SalesOrderStatusStates . Auto // generated via dmlgen. func (cc *SalesOrderStatusStates) Append(n ...*SalesOrderStatusState) *SalesOrderStatusStates { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Clear() *SalesOrderStatusStates { if cc == nil { *cc = SalesOrderStatusStates{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Cut(i, j int) *SalesOrderStatusStates { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } func (cc *SalesOrderStatusStates) scanColumns(cm *dml.ColumnMap, e *SalesOrderStatusState) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *SalesOrderStatusStates) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e SalesOrderStatusState if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "status": cm = cm.Strings(cc.Statuss()...) case "state": cm = cm.Strings(cc.States()...) default: return errors.NotFound.Newf("[dmltestgenerated] SalesOrderStatusStates Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } type SalesOrderStatusStatesDBLoadArgs struct { _Named_Fields_Required struct{} Status string State string } func (cc *SalesOrderStatusStates) DBLoad(ctx context.Context, dbm *DBM, pkIDs []SalesOrderStatusStatesDBLoadArgs, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStatesDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs Status,State into the context as value to search for a cache entry in the event function. if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } cacheKey := "SalesOrderStatusStatesSelectAll" var args []interface{} if len(pkIDs) > 0 { args = make([]interface{}, 0, len(pkIDs)*2) for _, pk := range pkIDs { args = append(args, pk.Status) args = append(args, pk.State) } cacheKey = "SalesOrderStatusStatesSelectByPK" } if _, err = dbm.ConnPool.WithCacheKey(cacheKey, opts...).Load(ctx, cc, args...); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *SalesOrderStatusStates) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStatesDeleteByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return nil, errors.NotValid.Newf("SalesOrderStatusStates can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *SalesOrderStatusStates) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStatesUpdateByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("SalesOrderStatusStates can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("SalesOrderStatusStateUpdateByPK", opts...) dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(TableNameSalesOrderStatusState, 1, res, err); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *SalesOrderStatusStates) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStatesInsert") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("SalesOrderStatusStates can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("SalesOrderStatusStateInsert", opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(TableNameSalesOrderStatusState, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)) } func (cc *SalesOrderStatusStates) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "SalesOrderStatusStatesUpsertByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if cc == nil { return errors.NotValid.Newf("SalesOrderStatusStates can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err := dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey("SalesOrderStatusStateUpsertByPK", opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(TableNameSalesOrderStatusState, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Delete(i int) *SalesOrderStatusStates { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* SalesOrderStatusState . Auto // generated via dmlgen. func (cc *SalesOrderStatusStates) Each(f func(*SalesOrderStatusState)) *SalesOrderStatusStates { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Filter(f func(*SalesOrderStatusState) bool) *SalesOrderStatusStates { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Insert(n *SalesOrderStatusState, i int) *SalesOrderStatusStates { z := cc.Data // copy the slice header z = append(z, &SalesOrderStatusState{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *SalesOrderStatusStates) Len() int { if cc == nil { return 0 } return len(cc.Data) } // Statuss returns a slice with the data or appends it to a slice. // Auto generated. func (cc *SalesOrderStatusStates) Statuss(ret ...string) []string { if cc == nil { return nil } if ret == nil { ret = make([]string, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.Status) } return ret } // States returns a slice with the data or appends it to a slice. // Auto generated. func (cc *SalesOrderStatusStates) States(ret ...string) []string { if cc == nil { return nil } if ret == nil { ret = make([]string, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.State) } return ret } // Validate runs internal consistency tests on all items. func (cc *SalesOrderStatusStates) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *SalesOrderStatusStates) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *ViewCustomerAutoIncrement) Copy() *ViewCustomerAutoIncrement { if e == nil { return &ViewCustomerAutoIncrement{} } e2 := *e // for now a shallow copy return &e2 } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *ViewCustomerAutoIncrement) MapColumns(cm *dml.ColumnMap) error { for cm.Next(5) { switch c := cm.Column(); c { case "ce_entity_id", "0": cm.Uint32(&e.CeEntityID) case "email", "1": cm.NullString(&e.Email) case "firstname", "2": cm.String(&e.Firstname) case "lastname", "3": cm.String(&e.Lastname) case "city", "4": cm.String(&e.City) default: return errors.NotFound.Newf("[dmltestgenerated] ViewCustomerAutoIncrement Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *ViewCustomerAutoIncrement) Load(ctx context.Context, dbm *DBM, primaryKey uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "ViewCustomerAutoIncrementSelectByPK") defer func() { cstrace.Status(span, err, ""); span.End() }() if e == nil { return errors.NotValid.Newf("ViewCustomerAutoIncrement can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("ViewCustomerAutoIncrementSelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } // Empty empties all the fields of the current object. Also known as Reset. func (e *ViewCustomerAutoIncrement) Empty() *ViewCustomerAutoIncrement { *e = ViewCustomerAutoIncrement{} return e } // IsSet returns true if the entity has non-empty primary keys. func (e *ViewCustomerAutoIncrement) IsSet() bool { return e.CeEntityID > 0 } // This variable can be set in another file to provide a custom validator. var validateViewCustomerAutoIncrement func(*ViewCustomerAutoIncrement) error // Validate runs internal consistency tests. func (e *ViewCustomerAutoIncrement) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateViewCustomerAutoIncrement != nil { return validateViewCustomerAutoIncrement(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *ViewCustomerAutoIncrement) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "ce_entity_id:", e.CeEntityID, "\n", "email:", e.Email, "\n", "firstname:", e.Firstname, "\n", "lastname:", e.Lastname, "\n", "city:", e.City, "\n", ) return int64(n2), err } // ViewCustomerAutoIncrements represents a collection type for DB table // view_customer_auto_increment // Not thread safe. Auto generated. //easyjson:json type ViewCustomerAutoIncrements struct { Data []*ViewCustomerAutoIncrement `json:"data,omitempty"` } // NewViewCustomerAutoIncrements creates a new initialized collection. Auto // generated. func NewViewCustomerAutoIncrements() *ViewCustomerAutoIncrements { return &ViewCustomerAutoIncrements{ Data: make([]*ViewCustomerAutoIncrement, 0, 5), } } // Append will add a new item at the end of * ViewCustomerAutoIncrements . Auto // generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Append(n ...*ViewCustomerAutoIncrement) *ViewCustomerAutoIncrements { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Clear() *ViewCustomerAutoIncrements { if cc == nil { *cc = ViewCustomerAutoIncrements{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Cut(i, j int) *ViewCustomerAutoIncrements { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } func (cc *ViewCustomerAutoIncrements) scanColumns(cm *dml.ColumnMap, e *ViewCustomerAutoIncrement) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *ViewCustomerAutoIncrements) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e ViewCustomerAutoIncrement if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *ViewCustomerAutoIncrements) DBLoad(ctx context.Context, dbm *DBM, pkIDs []uint32, opts ...dml.DBRFunc) (err error) { ctx, span := dbm.option.Trace.Start(ctx, "ViewCustomerAutoIncrementsDBLoad") defer func() { cstrace.Status(span, err, ""); span.End() }() cc.Clear() qo := dml.FromContextQueryOptions(ctx) // put the IDs CeEntityID into the context as value to search for a cache entry in the event function. if err = dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("ViewCustomerAutoIncrementsSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("ViewCustomerAutoIncrementsSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Delete(i int) *ViewCustomerAutoIncrements { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* ViewCustomerAutoIncrement . Auto // generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Each(f func(*ViewCustomerAutoIncrement)) *ViewCustomerAutoIncrements { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Filter(f func(*ViewCustomerAutoIncrement) bool) *ViewCustomerAutoIncrements { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Insert(n *ViewCustomerAutoIncrement, i int) *ViewCustomerAutoIncrements { z := cc.Data // copy the slice header z = append(z, &ViewCustomerAutoIncrement{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Len() int { if cc == nil { return 0 } return len(cc.Data) } // Validate runs internal consistency tests on all items. func (cc *ViewCustomerAutoIncrements) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *ViewCustomerAutoIncrements) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } // Copy copies the struct and returns a new pointer. TODO use deepcopy tool to // generate code afterwards func (e *ViewCustomerNoAutoIncrement) Copy() *ViewCustomerNoAutoIncrement { if e == nil { return &ViewCustomerNoAutoIncrement{} } e2 := *e // for now a shallow copy return &e2 } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *ViewCustomerNoAutoIncrement) MapColumns(cm *dml.ColumnMap) error { for cm.Next(4) { switch c := cm.Column(); c { case "email", "0": cm.NullString(&e.Email) case "firstname", "1": cm.String(&e.Firstname) case "lastname", "2": cm.String(&e.Lastname) case "city", "3": cm.String(&e.City) default: return errors.NotFound.Newf("[dmltestgenerated] ViewCustomerNoAutoIncrement Column %q not found", c) } } return errors.WithStack(cm.Err()) } // The table/view ViewCustomerNoAutoIncrement does not have a primary key. // SKipping to generate DML functions based on the PK. // Empty empties all the fields of the current object. Also known as Reset. func (e *ViewCustomerNoAutoIncrement) Empty() *ViewCustomerNoAutoIncrement { *e = ViewCustomerNoAutoIncrement{} return e } // This variable can be set in another file to provide a custom validator. var validateViewCustomerNoAutoIncrement func(*ViewCustomerNoAutoIncrement) error // Validate runs internal consistency tests. func (e *ViewCustomerNoAutoIncrement) Validate() error { if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) } if validateViewCustomerNoAutoIncrement != nil { return validateViewCustomerNoAutoIncrement(e) } return nil } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (e *ViewCustomerNoAutoIncrement) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code. n2, err := fmt.Fprint(w, "email:", e.Email, "\n", "firstname:", e.Firstname, "\n", "lastname:", e.Lastname, "\n", "city:", e.City, "\n", ) return int64(n2), err } // ViewCustomerNoAutoIncrements represents a collection type for DB table // view_customer_no_auto_increment // Not thread safe. Auto generated. //easyjson:json type ViewCustomerNoAutoIncrements struct { Data []*ViewCustomerNoAutoIncrement `json:"data,omitempty"` } // NewViewCustomerNoAutoIncrements creates a new initialized collection. Auto // generated. func NewViewCustomerNoAutoIncrements() *ViewCustomerNoAutoIncrements { return &ViewCustomerNoAutoIncrements{ Data: make([]*ViewCustomerNoAutoIncrement, 0, 5), } } // Append will add a new item at the end of * ViewCustomerNoAutoIncrements . Auto // generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Append(n ...*ViewCustomerNoAutoIncrement) *ViewCustomerNoAutoIncrements { cc.Data = append(cc.Data, n...) return cc } // Clear will reset the data slice or create a new type. Useful for reusing the // underlying backing slice array. Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Clear() *ViewCustomerNoAutoIncrements { if cc == nil { *cc = ViewCustomerNoAutoIncrements{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc } // Cut will remove items i through j-1. Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Cut(i, j int) *ViewCustomerNoAutoIncrements { z := cc.Data // copy slice header copy(z[i:], z[j:]) for k, n := len(z)-j+i, len(z); k < n; k++ { z[k] = nil // this avoids the memory leak } z = z[:len(z)-j+i] cc.Data = z return cc } func (cc *ViewCustomerNoAutoIncrements) scanColumns(cm *dml.ColumnMap, e *ViewCustomerNoAutoIncrement) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *ViewCustomerNoAutoIncrements) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear() } var e ViewCustomerNoAutoIncrement if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) default: return errors.NotSupported.Newf("[dmltestgenerated] Unknown Mode: %q", string(m)) } return cm.Err() } // The table/view ViewCustomerNoAutoIncrements does not have a primary key. // Skipping to generate DML functions based on the PK. // Delete will remove an item from the slice. Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Delete(i int) *ViewCustomerNoAutoIncrements { z := cc.Data // copy the slice header end := len(z) - 1 cc.Swap(i, end) copy(z[i:], z[i+1:]) z[end] = nil // this should avoid the memory leak z = z[:end] cc.Data = z return cc } // Each will run function f on all items in []* ViewCustomerNoAutoIncrement . // Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Each(f func(*ViewCustomerNoAutoIncrement)) *ViewCustomerNoAutoIncrements { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Filter filters the current slice by predicate f without memory allocation. // Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Filter(f func(*ViewCustomerNoAutoIncrement) bool) *ViewCustomerNoAutoIncrements { if cc == nil { return nil } b, i := cc.Data[:0], 0 for _, e := range cc.Data { if f(e) { b = append(b, e) } i++ } for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak } cc.Data = b return cc } // Insert will place a new item at position i. Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Insert(n *ViewCustomerNoAutoIncrement, i int) *ViewCustomerNoAutoIncrements { z := cc.Data // copy the slice header z = append(z, &ViewCustomerNoAutoIncrement{}) copy(z[i+1:], z[i:]) z[i] = n cc.Data = z return cc } // Swap will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] } // Len will satisfy the sort.Interface. Auto generated via dmlgen. func (cc *ViewCustomerNoAutoIncrements) Len() int { if cc == nil { return 0 } return len(cc.Data) } // Validate runs internal consistency tests on all items. func (cc *ViewCustomerNoAutoIncrements) Validate() (err error) { if len(cc.Data) == 0 { return nil } for i, ld := 0, len(cc.Data); i < ld && err == nil; i++ { err = cc.Data[i].Validate() } return } // WriteTo implements io.WriterTo and writes the field names and their values to // w. This is especially useful for debugging or or generating a hash of the // struct. func (cc *ViewCustomerNoAutoIncrements) WriteTo(w io.Writer) (n int64, err error) { for i, d := range cc.Data { n2, err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err, "[dmltestgenerated] WriteTo failed at index %d", i) } n += n2 } return n, nil } <|start_filename|>sql/dml/condition.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "database/sql/driver" "fmt" "strings" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" ) const ( logicalAnd byte = 'a' logicalOr byte = 'o' logicalXor byte = 'x' logicalNot byte = 'n' ) // Comparison functions and operators describe all available possibilities. const ( Null Op = 'n' // IS NULL NotNull Op = 'N' // IS NOT NULL In Op = '∈' // IN ? NotIn Op = '∉' // NOT IN ? Between Op = 'b' // BETWEEN ? AND ? NotBetween Op = 'B' // NOT BETWEEN ? AND ? Like Op = 'l' // LIKE ? NotLike Op = 'L' // NOT LIKE ? Greatest Op = '≫' // GREATEST(?,?,?) returns NULL if any value is NULL. Least Op = '≪' // LEAST(?,?,?) If any value is NULL, the result is NULL. Equal Op = '=' // = ? NotEqual Op = '≠' // != ? Exists Op = '∃' // EXISTS(subquery) NotExists Op = '∄' // NOT EXISTS(subquery) Less Op = '<' // < Greater Op = '>' // > LessOrEqual Op = '≤' // <= GreaterOrEqual Op = '≥' // >= Regexp Op = 'r' // REGEXP ? NotRegexp Op = 'R' // NOT REGEXP ? Xor Op = '⊻' // XOR ? SpaceShip Op = '\U0001f680' // a <=> b is equivalent to a = b OR (a IS NULL AND b IS NULL) NULL-safe equal to operator Coalesce Op = 'c' // Returns the first non-NULL value in the list, or NULL if there are no non-NULL arguments. ) // Op the Operator, defines comparison and operator functions used in any // conditions. The upper case letter always negates. // https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html // https://mariadb.com/kb/en/mariadb/comparison-operators/ type Op rune // String transforms the rune into a string. func (o Op) String() string { if o < 1 { o = Equal } return string(o) } func (o Op) write(w *bytes.Buffer, args ...interface{}) (err error) { var arg interface{} if len(args) == 1 { arg = args[0] } switch o { case NotIn, NotLike, NotRegexp, NotBetween, NotExists: w.WriteString(" NOT") } switch o { case Null: _, err = w.WriteString(" IS NULL") case NotNull: _, err = w.WriteString(" IS NOT NULL") case In, NotIn: w.WriteString(" IN ") err = writeInterfaces(w, args) case Like, NotLike: w.WriteString(" LIKE ") err = writeInterfaceValue(arg, w, 0) case Regexp, NotRegexp: w.WriteString(" REGEXP ") err = writeInterfaceValue(arg, w, 0) case Between, NotBetween: w.WriteString(" BETWEEN ") if arg == nil { w.WriteByte(placeHolderRune) w.WriteString(" AND ") // don't write the last place holder as it gets written somewhere else } else { if err = writeInterfaceValue(arg, w, 1); err != nil { return errors.WithStack(err) } w.WriteString(" AND ") if err = writeInterfaceValue(arg, w, 2); err != nil { return errors.WithStack(err) } } case Greatest: w.WriteString(" GREATEST ") err = writeInterfaces(w, args) case Least: w.WriteString(" LEAST ") err = writeInterfaces(w, args) case Coalesce: w.WriteString(" COALESCE ") err = writeInterfaces(w, args) case Xor: w.WriteString(" XOR ") err = writeInterfaceValue(arg, w, 0) case Exists, NotExists: w.WriteString(" EXISTS ") err = writeInterfaces(w, args) case Less: w.WriteString(" < ") err = writeInterfaceValue(arg, w, 0) case Greater: w.WriteString(" > ") err = writeInterfaceValue(arg, w, 0) case LessOrEqual: w.WriteString(" <= ") err = writeInterfaceValue(arg, w, 0) case GreaterOrEqual: w.WriteString(" >= ") err = writeInterfaceValue(arg, w, 0) case SpaceShip: w.WriteString(" <=> ") err = writeInterfaceValue(arg, w, 0) case NotEqual: w.WriteString(" != ") err = writeInterfaceValue(arg, w, 0) default: // and case Equal w.WriteString(" = ") err = writeInterfaceValue(arg, w, 0) } return } // Conditions provides a list where the left hand side gets an assignment from // the right hand side. Mostly used in type Conditions []*Condition // Clone creates a clone of the current object. func (cs Conditions) Clone() Conditions { if cs == nil { return nil } cs2 := make(Conditions, len(cs)) for i, c := range cs { cs2[i] = c.Clone() } return cs2 } // Reset resets the slice to length zero and retains the allocated memory. func (cs *Conditions) Reset() Conditions { cs2 := *cs for i := range cs2 { cs2[i] = nil } *cs = cs2[:0] return *cs } // Joins defines multiple join conditions. type Joins []*join // Clone creates a new clone of the current object. func (js Joins) Clone() Joins { if js == nil { return nil } c := make(Joins, len(js)) for i, j := range js { c[i] = j.Clone() } return c } type join struct { // JoinType can be LEFT, RIGHT, INNER, OUTER, CROSS or another word. JoinType string // Table name and alias of the table Table id // On join on those conditions On Conditions } // Clone creates a new clone of the current object. func (j *join) Clone() *join { if j == nil { return nil } c := *j c.Table = j.Table.Clone() c.On = j.On.Clone() return &c } // Condition implements a single condition often used in WHERE, ON, SET and ON // DUPLICATE KEY UPDATE. Please use the helper functions instead of using this // type directly. type Condition struct { previousErr error Aliased string // Left can contain either a valid identifier or an expression. Set field // `IsLeftExpression` to true to avoid quoting of the this field. Left can also // contain a string in the format `qualifier.identifier`. Left string // Right defines the right hand side for an assignment which can be either a // single argument, multiple arguments in case of an expression, a sub // select or a name of a column. Right struct { // Column defines a column name to compare to. The column, with an // optional qualifier, gets quoted, in case IsExpression is false. Column string // PlaceHolder can be a :named or the MySQL/MariaDB place holder // character `?`. If set, the current condition just acts as a place // holder for a prepared statement or an interpolation. In case of a // :named place holder for a prepared statement, the :named string gets // replaced with the `?`. The allowed characters are unicode letters and // digits. PlaceHolder string // arg gets written into the SQL string as a persistent argument arg interface{} // Only set in case of no expression // args same as arg but only used in case of an expression. args []interface{} // Select adds a sub-select to the where statement. Column must be // either a column name or anything else which can handle the result of // a sub-select. Sub *Select // IsExpression if true field `Column` gets treated as an expression. // Additionally the field Right.args will be read to extract any // given args. IsExpression bool } // Operator contains the comparison logic like LIKE, IN, GREATER, etc ... // defaults to EQUAL. Operator Op // IsLeftExpression if set to true, the field Left won't get quoted and // treated as an expression. Additionally the field Right.args will be // read to extract any given args. IsLeftExpression bool // Logical states how multiple WHERE statements will be connected. // Default to AND. Possible values are a=AND, o=OR, x=XOR, n=NOT Logical byte // Columns is a list of column names which get quoted during SQL statement // creation in the JOIN part for the USING syntax. Additionally used in ON // DUPLICATE KEY. Columns []string } // Clone creates a new clone of the current object. It resets the internal error // field. func (c *Condition) Clone() *Condition { if c == nil { return nil } c2 := *c c2.previousErr = nil if c2.Right.args != nil { a2 := make([]interface{}, len(c2.Right.args)) copy(a2, c2.Right.args) c2.Right.args = a2 } c2.Right.Sub = c.Right.Sub.Clone() c2.Columns = cloneStringSlice(c.Columns) return &c2 } // Alias assigns an alias name to the condition. func (c *Condition) Alias(a string) *Condition { c.Aliased = a return c } // And sets the logical AND operator func (c *Condition) And() *Condition { c.Logical = logicalAnd return c } // Or sets the logical OR operator func (c *Condition) Or() *Condition { c.Logical = logicalOr return c } func (c *Condition) isExpression() bool { return c.IsLeftExpression || c.Right.IsExpression } // Columns add syntactic sugar to a JOIN or ON DUPLICATE KEY statement: In case // of JOIN: The USING(column_list) clause names a list of columns that must // exist in both tables. If tables a and b both contain columns c1, c2, and c3, // the following join compares corresponding columns from the two tables: // a LEFT JOIN b USING (c1, c2, c3) // The columns list gets quoted while writing the query string. In case of ON // DUPLICATE KEY each column gets written like: `column`=VALUES(`column`). // Any other field in *Condition gets ignored once field Columns has been set. func Columns(columns ...string) *Condition { return &Condition{ Columns: columns, } } // Column adds a new condition. func Column(columnName string) *Condition { return &Condition{ Left: columnName, } } // Expr adds an unquoted SQL expression to a column, WHERE, HAVING, SET or ON DUPLICATE // KEY statement. Each item of an expression gets written into the buffer // without a separator. func Expr(expression string) *Condition { return &Condition{ Left: expression, IsLeftExpression: true, } } // ParenthesisOpen sets an open parenthesis "(". Mostly used for OR conditions // in combination with AND conditions. func ParenthesisOpen() *Condition { return &Condition{ Left: "(", } } // ParenthesisClose sets a closing parenthesis ")". Mostly used for OR // conditions in combination with AND conditions. func ParenthesisClose() *Condition { return &Condition{ Left: ")", } } /////////////////////////////////////////////////////////////////////////////// // COMPARISON OPERATOR /////////////////////////////////////////////////////////////////////////////// // Op sets a custom operator func (c *Condition) Op(o Op) *Condition { c.Operator = o return c } func (c *Condition) Null() *Condition { c.Operator = Null return c } func (c *Condition) NotNull() *Condition { c.Operator = NotNull return c } func (c *Condition) In() *Condition { c.Operator = In return c } func (c *Condition) NotIn() *Condition { c.Operator = NotIn return c } func (c *Condition) Between() *Condition { c.Operator = Between return c } func (c *Condition) NotBetween() *Condition { c.Operator = NotBetween return c } func (c *Condition) Like() *Condition { c.Operator = Like return c } func (c *Condition) NotLike() *Condition { c.Operator = NotLike return c } func (c *Condition) Greatest() *Condition { c.Operator = Greatest return c } func (c *Condition) Least() *Condition { c.Operator = Least return c } func (c *Condition) Equal() *Condition { c.Operator = Equal return c } func (c *Condition) NotEqual() *Condition { c.Operator = NotEqual return c } func (c *Condition) Exists() *Condition { c.Operator = Exists return c } func (c *Condition) NotExists() *Condition { c.Operator = NotExists return c } func (c *Condition) Less() *Condition { c.Operator = Less return c } func (c *Condition) Greater() *Condition { c.Operator = Greater return c } func (c *Condition) LessOrEqual() *Condition { c.Operator = LessOrEqual return c } func (c *Condition) GreaterOrEqual() *Condition { c.Operator = GreaterOrEqual return c } func (c *Condition) Regexp() *Condition { c.Operator = Regexp return c } func (c *Condition) NotRegexp() *Condition { c.Operator = NotRegexp return c } func (c *Condition) Xor() *Condition { c.Operator = Xor return c } func (c *Condition) SpaceShip() *Condition { c.Operator = SpaceShip return c } func (c *Condition) Coalesce() *Condition { c.Operator = Coalesce return c } /////////////////////////////////////////////////////////////////////////////// // TYPES /////////////////////////////////////////////////////////////////////////////// // Column compares the left hand side with this column name. func (c *Condition) Column(col string) *Condition { c.Right.Column = col return c } // NamedArg treats a condition as a place holder. If set the MySQL/MariaDB // placeholder `?` will be used and the provided name gets replaced. Records // which implement ColumnMapper must also use this name. A dot in the name (for // e.g. setting a qualifier) is not allowed. func (c *Condition) NamedArg(n string) *Condition { c.Right.PlaceHolder = n return c } // PlaceHolder treats a condition as a placeholder. Sets the database specific // placeholder character "?". Mostly used in prepared statements and for // interpolation. func (c *Condition) PlaceHolder() *Condition { c.Right.PlaceHolder = placeHolderStr return c } // Tuples allows to build a query string for tuple comparison. // SELECT * FROM catalog_product_index_decimal_idx WHERE // (entity_id,attribute_id,store_id,source_id) IN ( // (4,4,4,4), (3,3,3,3), (dynamical values) // ); // See test ... TBC func (c *Condition) Tuples() *Condition { c.Right.PlaceHolder = placeHolderTuples return c } // PlaceHolders treats a condition as a string with multiple placeholders. Sets // the database specific placeholder character "?" as many times as specified in // variable count. Mostly used in prepared statements and for interpolation and // when using the IN clause. func (c *Condition) PlaceHolders(count int) *Condition { switch count { case 1: c.Right.PlaceHolder = "(?)" case 2: c.Right.PlaceHolder = "(?,?)" case 3: c.Right.PlaceHolder = "(?,?,?)" } if c.Right.PlaceHolder != "" { return c } var buf strings.Builder buf.WriteByte('(') for i := 0; i < count; i++ { if i > 0 { buf.WriteByte(',') } buf.WriteByte(placeHolderRune) } buf.WriteByte(')') c.Right.PlaceHolder = buf.String() return c } // Sub compares the left hand side with the SELECT of the right hand side. // Choose the appropriate comparison operator, default is IN. func (c *Condition) Sub(sub *Select) *Condition { c.Right.Sub = sub if c.Operator == 0 { c.Operator = In } return c } // Expr compares the left hand side with the expression of the right hand // side. func (c *Condition) Expr(expression string) *Condition { c.Right.Column = expression c.Right.IsExpression = c.Right.Column != "" return c } func (c *Condition) Int(i int) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, int64(i)) return c } c.Right.arg = i return c } func (c *Condition) Ints(i ...int) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, i) return c } c.Right.arg = i return c } func (c *Condition) Int64(i int64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, i) return c } c.Right.arg = i return c } func (c *Condition) Int64s(i ...int64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, i) return c } c.Right.arg = i return c } func (c *Condition) Uint64(i uint64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, i) return c } c.Right.arg = i return c } func (c *Condition) Uint64s(i ...uint64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, i) return c } c.Right.arg = i return c } // Add when needed // func (c *Condition) Decimals(d ...Decimal) *Condition {} func (c *Condition) Decimal(d null.Decimal) *Condition { v := d.String() if c.isExpression() { if v == sqlStrNullUC { c.Right.args = append(c.Right.args, nil) } else { c.Right.args = append(c.Right.args, v) } return c } if v == sqlStrNullUC { c.Right.arg = nil } else { c.Right.arg = v } return c } func (c *Condition) Float64(f float64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, f) return c } c.Right.arg = f return c } func (c *Condition) Float64s(f ...float64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, f) return c } c.Right.arg = f return c } func (c *Condition) Str(s string) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, s) return c } c.Right.arg = s return c } func (c *Condition) Strs(s ...string) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, s) return c } c.Right.arg = s return c } func (c *Condition) Bool(b bool) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, b) return c } c.Right.arg = b return c } func (c *Condition) Bools(b ...bool) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, b) return c } c.Right.arg = b return c } // Bytes uses a byte slice for comparison. Providing a nil value returns a // NULL type. Detects between valid UTF-8 strings and binary data. Later gets // hex encoded. func (c *Condition) Bytes(p []byte) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, p) return c } c.Right.arg = p return c } func (c *Condition) BytesSlice(p ...[]byte) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, p) return c } c.Right.arg = p return c } func (c *Condition) Time(t time.Time) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, t) return c } c.Right.arg = t return c } func (c *Condition) Times(t ...time.Time) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, t) return c } c.Right.arg = t return c } func (c *Condition) NullString(nv null.String) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullStrings(nv ...null.String) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullFloat64(nv null.Float64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullFloat64s(nv ...null.Float64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullInt64(nv null.Int64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullInt64s(nv ...null.Int64) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullBool(nv null.Bool) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullBools(nv ...null.Bool) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullTime(nv null.Time) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } func (c *Condition) NullTimes(nv ...null.Time) *Condition { if c.isExpression() { c.Right.args = append(c.Right.args, nv) return c } c.Right.arg = nv return c } // Values only usable in case for ON DUPLICATE KEY to generate a statement like: // column=VALUES(column) func (c *Condition) Values() *Condition { // noop just to lower the cognitive overload when reading the code where // this function gets used. return c } // DriverValue adds multiple of the same underlying values to the argument // slice. When using different values, the last applied value wins and gets // added to the argument slice. For example driver.Values of type `int` will // result in []int. func (c *Condition) DriverValue(dv ...driver.Valuer) *Condition { if c.previousErr != nil { return c } c.Right.args, c.previousErr = driverValue(c.Right.args, dv...) return c } // DriverValues adds each driver.Value as its own argument to the argument // slice. It panics if the underlying type is not one of the allowed of // interface driver.Valuer. func (c *Condition) DriverValues(dv ...driver.Valuer) *Condition { if c.previousErr != nil { return c } c.Right.args, c.previousErr = driverValues(c.Right.args, dv...) return c } /////////////////////////////////////////////////////////////////////////////// // FUNCTIONS / EXPRESSIONS /////////////////////////////////////////////////////////////////////////////// // SQLCase see description at function SQLCase. func (c *Condition) SQLCase(value, defaultValue string, compareResult ...string) *Condition { c.Right.Column = sqlCase(value, defaultValue, compareResult...) c.Right.IsExpression = c.Right.Column != "" return c } // SQLIfNull see description at function SQLIfNull. func (c *Condition) SQLIfNull(expression ...string) *Condition { c.Right.Column = sqlIfNull(expression) c.Right.IsExpression = c.Right.Column != "" return c } /////////////////////////////////////////////////////////////////////////////// // INTERNAL /////////////////////////////////////////////////////////////////////////////// // write writes the conditions for usage as restrictions in WHERE, HAVING or // JOIN clauses. conditionType enum of j=join, w=where, h=having func (cs Conditions) write(w *bytes.Buffer, conditionType byte, placeHolders []string, isWithDBR bool) (_placeHolders []string, err error) { if len(cs) == 0 { return placeHolders, nil } switch conditionType { case 'w': w.WriteString(" WHERE ") case 'h': w.WriteString(" HAVING ") } i := 0 for _, cnd := range cs { if cnd.previousErr != nil { return nil, errors.WithStack(cnd.previousErr) } if conditionType == 'j' { if len(cnd.Columns) > 0 { w.WriteString(" USING (") for j, c := range cnd.Columns { if j > 0 { w.WriteByte(',') } Quoter.quote(w, c) } w.WriteByte(')') return placeHolders, nil // done, only one USING allowed } if i == 0 { w.WriteString(" ON ") } } if cnd.Left == ")" { w.WriteString(cnd.Left) continue } if i > 0 { // How the WHERE conditions are connected switch cnd.Logical { case logicalAnd: w.WriteString(" AND ") case logicalOr: w.WriteString(" OR ") case logicalXor: w.WriteString(" XOR ") case logicalNot: w.WriteString(" NOT ") default: w.WriteString(" AND ") } } if cnd.Left == "(" { i = 0 w.WriteString(cnd.Left) continue } w.WriteByte('(') // Code is a bit duplicated but can be refactored later. The order of // the `case`s has been carefully implemented. switch lenArgs := len(cnd.Right.args); { case cnd.IsLeftExpression: var phCount int phCount, err = writeExpression(w, cnd.Left, cnd.Right.args) if err != nil { return nil, errors.WithStack(err) } // Only write the operator in case there is no place holder and we // have one value. switch { case phCount == 0 && (lenArgs == 1 || cnd.Right.arg != nil) && cnd.Operator > 0: eArg := cnd.Right.arg if eArg == nil { eArg = cnd.Right.args[0] } cnd.Operator.write(w, eArg) case cnd.Right.Sub != nil: if err = cnd.Operator.write(w); err != nil { return nil, errors.WithStack(err) } w.WriteByte('(') placeHolders, err = cnd.Right.Sub.toSQL(w, placeHolders) if err != nil { return nil, errors.Wrapf(err, "[dml] write failed SubSelect for table: %q", cnd.Right.Sub.Table.String()) } w.WriteByte(')') } case cnd.Right.IsExpression: Quoter.WriteIdentifier(w, cnd.Left) if err = cnd.Operator.write(w); err != nil { return nil, errors.WithStack(err) } if _, err = writeExpression(w, cnd.Right.Column, cnd.Right.args); err != nil { return nil, errors.WithStack(err) } case cnd.Right.Sub != nil: Quoter.WriteIdentifier(w, cnd.Left) if err = cnd.Operator.write(w); err != nil { return nil, errors.WithStack(err) } w.WriteByte('(') placeHolders, err = cnd.Right.Sub.toSQL(w, placeHolders) if err != nil { return nil, errors.Wrapf(err, "[dml] write failed SubSelect for table: %q", cnd.Right.Sub.Table.String()) } w.WriteByte(')') case cnd.Right.arg != nil && lenArgs == 0: // One Argument and no expression Quoter.WriteIdentifier(w, cnd.Left) if al, _ := sliceLen(cnd.Right.arg); al > 1 && cnd.Operator == 0 { // no operator but slice applied, so creating an IN query. cnd.Operator = In } if err = cnd.Operator.write(w, cnd.Right.arg); err != nil { return nil, errors.WithStack(err) } case cnd.Right.arg == nil && lenArgs > 0: Quoter.WriteIdentifier(w, cnd.Left) if totalSliceLenSimple(cnd.Right.args) > 1 && cnd.Operator == 0 { // no operator but slice applied, so creating an IN query. cnd.Operator = In } if err = cnd.Operator.write(w, cnd.Right.args...); err != nil { return nil, errors.WithStack(err) } case cnd.Right.Column != "": // compares the left column with the right column Quoter.WriteIdentifier(w, cnd.Left) if err = cnd.Operator.write(w); err != nil { return nil, errors.WithStack(err) } Quoter.WriteIdentifier(w, cnd.Right.Column) case cnd.Right.PlaceHolder == placeHolderTuples: w.WriteByte('(') for j, col := range cnd.Columns { if j > 0 { w.WriteString(", ") } Quoter.quote(w, col) } w.WriteByte(')') if err = cnd.Operator.write(w); err != nil { return nil, errors.WithStack(err) } if isWithDBR { fmt.Fprintf(w, placeHolderTuples, len(cnd.Columns)) // BuilderBase.buildToSQL needs this hack to see if we have a tuple. If // so, sets containsTuples to true. placeHolders = append(placeHolders, placeHolderTuples) } else { w.WriteByte('(') writeTuplePlaceholders(w, 1, uint(len(cnd.Columns))) w.WriteByte(')') } case cnd.Right.PlaceHolder != "": Quoter.WriteIdentifier(w, cnd.Left) if err = cnd.Operator.write(w); err != nil { return nil, errors.WithStack(err) } switch { case cnd.Right.PlaceHolder == placeHolderStr: placeHolders = append(placeHolders, cnd.Left) w.WriteByte(placeHolderRune) case isNamedArg(cnd.Right.PlaceHolder): w.WriteByte(placeHolderRune) ph := cnd.Right.PlaceHolder if !strings.HasPrefix(cnd.Right.PlaceHolder, namedArgStartStr) { ph = namedArgStartStr + ph } placeHolders = append(placeHolders, ph) default: placeHolders = append(placeHolders, cnd.Left) w.WriteString(cnd.Right.PlaceHolder) } case cnd.Right.arg == nil && lenArgs == 0: // No Argument at all, which kinda is the default case Quoter.WriteIdentifier(w, cnd.Left) cOp := cnd.Operator if cOp == 0 { cOp = Null } if err = cOp.write(w); err != nil { return nil, errors.WithStack(err) } default: panic(errors.NotSupported.Newf("[dml] Multiple arguments for a column are not supported\nWhereFragment: %#v\n", cnd)) } w.WriteByte(')') i++ } return placeHolders, errors.WithStack(err) } func (cs Conditions) writeSetClauses(w *bytes.Buffer, placeHolders []string) ([]string, error) { for i, cnd := range cs { if i > 0 { w.WriteString(", ") } Quoter.quote(w, cnd.Left) w.WriteByte('=') switch { case cnd.Right.arg != nil && len(cnd.Right.args) == 0: // One Argument and no expression if err := writeInterfaceValue(cnd.Right.arg, w, 0); err != nil { return nil, errors.WithStack(err) } case cnd.Right.IsExpression: // maybe that case is superfluous if _, err := writeExpression(w, cnd.Right.Column, cnd.Right.args); err != nil { return nil, errors.WithStack(err) } placeHolders = append(placeHolders, cnd.Left) case cnd.Right.Sub != nil: w.WriteByte('(') var err error if placeHolders, err = cnd.Right.Sub.toSQL(w, placeHolders); err != nil { return nil, errors.WithStack(err) } w.WriteByte(')') default: placeHolders = append(placeHolders, cnd.Left) w.WriteByte(placeHolderRune) } } return placeHolders, nil } func writeSQLValues(w *bytes.Buffer, column string) { w.WriteString("VALUES(") Quoter.quote(w, column) w.WriteByte(')') } var onDuplicateKeyPart = []byte(` ON DUPLICATE KEY UPDATE `) const onDuplicateKeyPartS = ` ON DUPLICATE KEY UPDATE ` // writeOnDuplicateKey writes the columns to `w` and appends the arguments to // `args` and returns `args`. // https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html func (cs Conditions) writeOnDuplicateKey(w *bytes.Buffer, placeHolders []string) ([]string, error) { if len(cs) == 0 { return placeHolders, nil } w.Write(onDuplicateKeyPart) for i, cnd := range cs { addColon := false for j, col := range cnd.Columns { if j > 0 { w.WriteString(", ") } Quoter.quote(w, col) w.WriteByte('=') writeSQLValues(w, col) addColon = true } if cnd.Left == "" { continue } if i > 0 || addColon { w.WriteString(", ") } Quoter.quote(w, cnd.Left) w.WriteByte('=') switch { case cnd.Right.IsExpression: // maybe that case is superfluous if _, err := writeExpression(w, cnd.Right.Column, cnd.Right.args); err != nil { return nil, errors.WithStack(err) } case cnd.Right.PlaceHolder != "": switch { case cnd.Right.PlaceHolder == placeHolderStr: placeHolders = append(placeHolders, cnd.Left) w.WriteByte(placeHolderRune) case isNamedArg(cnd.Right.PlaceHolder): w.WriteByte(placeHolderRune) ph := cnd.Right.PlaceHolder if !strings.HasPrefix(cnd.Right.PlaceHolder, namedArgStartStr) { ph = namedArgStartStr + ph } placeHolders = append(placeHolders, ph) default: placeHolders = append(placeHolders, cnd.Left) w.WriteString(cnd.Right.PlaceHolder) } case cnd.Right.arg == nil: writeSQLValues(w, cnd.Left) case cnd.Right.arg != nil: if err := writeInterfaceValue(cnd.Right.arg, w, 0); err != nil { return nil, errors.WithStack(err) } default: placeHolders = append(placeHolders, cnd.Left) w.WriteByte(placeHolderRune) } } return placeHolders, nil } // splitColumn splits a string via its last dot into the qualifier and the // column name. func splitColumn(identifier string) (qualifier, column string) { // dot at a beginning and end of a string is illegal. // Using LastIndexByte allows to retain the database qualifier, so: // database.table.column will become in the return "database.table", "column" if dotIndex := strings.LastIndexByte(identifier, '.'); dotIndex > 0 && dotIndex+1 < len(identifier) { return identifier[:dotIndex], identifier[dotIndex+1:] } return "", identifier } <|start_filename|>sql/dml/errors_test.go<|end_filename|> package dml import ( "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/util/assert" "github.com/go-sql-driver/mysql" ) func TestMySQLFromError(t *testing.T) { myErr := &mysql.MySQLError{ Number: 1062, Message: "Duplicate Key", } haveM := MySQLMessageFromError(errors.Fatal.New(myErr, "Outer fatal error")) assert.Exactly(t, "Duplicate Key", haveM) haveN := MySQLNumberFromError(errors.Fatal.New(myErr, "Outer fatal error")) assert.Exactly(t, uint16(1062), haveN) } <|start_filename|>sql/dml/select_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml_test import ( "bytes" "context" "encoding/json" "fmt" "io" "sync/atomic" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/sync/bgwork" "github.com/corestoreio/pkg/util/assert" ) type fakePerson struct { ID int FirstName string LastName string Sex string BirthDate time.Time Weight int Height int UpdateTime time.Time } // MapColumns implements interface ColumnMapper only partially. func (p *fakePerson) MapColumns(cm *dml.ColumnMap) error { for cm.Next(8) { switch c := cm.Column(); c { case "id", "0": cm.Int(&p.ID) case "first_name", "1": cm.String(&p.FirstName) case "last_name", "2": cm.String(&p.LastName) case "sex", "3": cm.String(&p.Sex) case "birth_date", "4": cm.Time(&p.BirthDate) case "weight", "5": cm.Int(&p.Weight) case "height", "6": cm.Int(&p.Height) case "update_time", "7": cm.Time(&p.UpdateTime) default: return errors.NotFound.Newf("[dml_test] fakePerson Column %q not found", c) } } return cm.Err() } type fakePersons struct { Data []fakePerson } func (cc *fakePersons) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapScan: if cm.Count == 0 { cc.Data = cc.Data[:0] } var p fakePerson if err := p.MapColumns(cm); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, p) default: return errors.NotSupported.Newf("[dml] Unknown Mode: %q", string(m)) } return cm.Err() } func TestSelect_QueryContext(t *testing.T) { t.Run("ToSQL Error because empty select", func(t *testing.T) { sel := &dml.Select{} rows, err := sel.WithDBR(dbMock{}).QueryContext(context.Background()) assert.Nil(t, rows) assert.ErrorIsKind(t, errors.Empty, err) }) t.Run("Error", func(t *testing.T) { sel := &dml.Select{ BuilderBase: dml.BuilderBase{ Table: dml.MakeIdentifier("tableX"), }, } sel.AddColumns("a", "b") selDBR := sel.WithDBR(dbMock{ error: errors.AlreadyClosed.Newf("Who closed myself?"), }) rows, err := selDBR.QueryContext(context.Background()) assert.Nil(t, rows) assert.ErrorIsKind(t, errors.AlreadyClosed, err) }) t.Run("Success", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) smr := sqlmock.NewRows([]string{"a"}).AddRow("row1").AddRow("row2") dbMock.ExpectQuery("SELECT `a` FROM `tableX`").WillReturnRows(smr) sel := dbc.WithQueryBuilder(dml.NewSelect("a").From("tableX")) rows, err := sel.QueryContext(context.Background()) assert.NoError(t, err) defer dmltest.Close(t, rows) var xx []string for rows.Next() { var x string assert.NoError(t, rows.Scan(&x)) xx = append(xx, x) } assert.Exactly(t, []string{"row1", "row2"}, xx) }) } var ( _ dml.ColumnMapper = (*TableCoreConfigDataSlice)(nil) _ dml.ColumnMapper = (*TableCoreConfigData)(nil) _ io.Closer = (*TableCoreConfigDataSlice)(nil) ) // TableCoreConfigDataSlice represents a collection type for DB table core_config_data // Generated via tableToStruct. type TableCoreConfigDataSlice struct { Data []*TableCoreConfigData err error // just for testing not needed otherwise } // TableCoreConfigData represents a type for DB table core_config_data // Generated via tableToStruct. type TableCoreConfigData struct { ConfigID int64 `json:",omitempty"` // config_id int(10) unsigned NOT NULL PRI auto_increment Scope string `json:",omitempty"` // scope varchar(8) NOT NULL MUL DEFAULT 'default' ScopeID int64 `json:",omitempty"` // scope_id int(11) NOT NULL DEFAULT '0' Path string `json:",omitempty"` // path varchar(255) NOT NULL DEFAULT 'general' Value null.String `json:",omitempty"` // value text NULL } func (p *TableCoreConfigData) MapColumns(cm *dml.ColumnMap) error { for cm.Next(5) { switch c := cm.Column(); c { case "config_id", "0": cm.Int64(&p.ConfigID) case "scope", "1": cm.String(&p.Scope) case "scope_id", "2": cm.Int64(&p.ScopeID) case "path", "3": cm.String(&p.Path) case "value", "4": cm.NullString(&p.Value) default: return errors.NotFound.Newf("[dml] Field %q not found", c) } } return cm.Err() } func (ps *TableCoreConfigDataSlice) MapColumns(cm *dml.ColumnMap) error { if ps.err != nil { return ps.err } switch m := cm.Mode(); m { case dml.ColumnMapScan: // case for scanning when loading certain rows, hence we write data from // the DB into the struct in each for-loop. if cm.Count == 0 { ps.Data = ps.Data[:0] } p := new(TableCoreConfigData) if err := p.MapColumns(cm); err != nil { return errors.WithStack(err) } ps.Data = append(ps.Data, p) case dml.ColumnMapCollectionReadSet, dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: // noop not needed default: return errors.NotSupported.Newf("[dml] Unknown Mode: %q", string(m)) } return nil } func (ps *TableCoreConfigDataSlice) Close() error { return ps.err } func TestSelect_Load(t *testing.T) { t.Run("success no condition", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectQuery(dmltest.SQLMockQuoteMeta("SELECT * FROM `core_config_data`")). WillReturnRows(dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data.csv"))) ccd := &TableCoreConfigDataSlice{} _, err := dbc.WithQueryBuilder(dml.NewSelect("*").From("core_config_data")).Load(context.Background(), ccd) assert.NoError(t, err) buf := new(bytes.Buffer) je := json.NewEncoder(buf) for _, c := range ccd.Data { if err := je.Encode(c); err != nil { t.Fatalf("%+v", err) } } assert.Exactly(t, "{\"ConfigID\":2,\"Scope\":\"default\",\"Path\":\"web/unsecure/base_url\",\"Value\":\"http://mgeto2.local/\"}\n{\"ConfigID\":3,\"Scope\":\"website\",\"ScopeID\":11,\"Path\":\"general/locale/code\",\"Value\":\"en_US\"}\n{\"ConfigID\":4,\"Scope\":\"default\",\"Path\":\"general/locale/timezone\",\"Value\":\"Europe/Berlin\"}\n{\"ConfigID\":5,\"Scope\":\"default\",\"Path\":\"currency/options/base\",\"Value\":\"EUR\"}\n{\"ConfigID\":15,\"Scope\":\"store\",\"ScopeID\":33,\"Path\":\"design/head/includes\",\"Value\":\"\\u003clink rel=\\\"stylesheet\\\" type=\\\"text/css\\\" href=\\\"{{MEDIA_URL}}styles.css\\\" /\\u003e\"}\n{\"ConfigID\":16,\"Scope\":\"default\",\"Path\":\"admin/security/use_case_sensitive_login\",\"Value\":null}\n{\"ConfigID\":17,\"Scope\":\"default\",\"Path\":\"admin/security/session_lifetime\",\"Value\":\"90000\"}\n", buf.String()) }) t.Run("success In with one ARG", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectQuery(dmltest.SQLMockQuoteMeta("SELECT `config_id` FROM `core_config_data` WHERE (`config_id` IN (?)")). WillReturnRows(dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_ints.csv"))). WithArgs(199) var dst []int64 dst, err := dbc.WithQueryBuilder(dml.NewSelect("config_id").From("core_config_data").Where( dml.Column("config_id").In().PlaceHolder(), )).ExpandPlaceHolders().LoadInt64s(context.Background(), dst, []int64{199}) assert.NoError(t, err) // wrong result set for correct query. maybe some one can fix the returned data. assert.Exactly(t, []int64{2, 3, 4, 16, 17}, dst) }) t.Run("success In with two ARGs", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectQuery(dmltest.SQLMockQuoteMeta("SELECT `config_id` FROM `core_config_data` WHERE (`config_id` IN (?,?))")). WillReturnRows(dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_ints.csv"))). WithArgs(199, 217) var dst []int64 dst, err := dbc.WithQueryBuilder(dml.NewSelect("config_id").From("core_config_data").Where( dml.Column("config_id").In().PlaceHolder(), )).ExpandPlaceHolders().LoadInt64s(context.Background(), dst, []int64{199, 217}) assert.NoError(t, err) assert.Exactly(t, []int64{2, 3, 4, 16, 17}, dst) }) t.Run("row error", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) r := sqlmock.NewRows([]string{"config_id"}).FromCSVString("222\n333\n"). RowError(1, errors.ConnectionFailed.Newf("Con failed")) dbMock.ExpectQuery("SELECT").WillReturnRows(r) ccd := &TableCoreConfigDataSlice{} _, err := dbc.WithQueryBuilder(dml.NewSelect("config_id").From("core_config_data")).Load(context.Background(), ccd) assert.ErrorIsKind(t, errors.ConnectionFailed, err) }) t.Run("ioClose error", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) r := sqlmock.NewRows([]string{"config_id"}).FromCSVString("222\n333\n").AddRow("3456") dbMock.ExpectQuery("SELECT").WillReturnRows(r) ccd := &TableCoreConfigDataSlice{ err: errors.Duplicated.Newf("Somewhere exists a duplicate entry"), } _, err := dbc.WithQueryBuilder(dml.NewSelect("config_id").From("core_config_data")).Load(context.Background(), ccd) assert.ErrorIsKind(t, errors.Duplicated, err) }) } func TestSelect_Prepare(t *testing.T) { t.Run("Prepare Error", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectPrepare("SELECT `a`, `b` FROM `tableX`").WillReturnError(errors.AlreadyClosed.Newf("Who closed myself?")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("a", "b").From("tableX")) assert.NotNil(t, stmt) assert.ErrorIsKind(t, errors.AlreadyClosed, stmt.PreviousError()) }) t.Run("Prepare IN", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `id` FROM `tableX` WHERE (`id` IN (?,?))")) prep.ExpectQuery().WithArgs(3739, 3740). WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(78)) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("id").From("tableX").Where(dml.Column("id").In().PlaceHolders(2))) ints, err := stmt.LoadInt64s(context.Background(), nil, 3739, 3740) assert.NoError(t, err) assert.Exactly(t, []int64{78}, ints) }) t.Run("Query", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `name`, `email` FROM `dml_person` WHERE (`id` = ?)")) prep.ExpectQuery().WithArgs(6789). WillReturnRows(sqlmock.NewRows([]string{"name", "email"}).AddRow("<NAME>", "<EMAIL>")) prep.ExpectQuery().WithArgs(6790). WillReturnRows(sqlmock.NewRows([]string{"name", "email"}).AddRow("<NAME>", "<EMAIL>")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("name", "email").From("dml_person").Where(dml.Column("id").PlaceHolder()), ) defer dmltest.Close(t, stmt) t.Run("Context", func(t *testing.T) { rows, err := stmt.QueryContext(context.Background(), 6789) assert.NoError(t, err) defer dmltest.Close(t, rows) cols, err := rows.Columns() assert.NoError(t, err) assert.Exactly(t, []string{"name", "email"}, cols) }) t.Run("RowContext", func(t *testing.T) { row := stmt.QueryRowContext(context.Background(), 6790) n, e := "", "" assert.NoError(t, row.Scan(&n, &e)) assert.Exactly(t, "<NAME>", n) assert.Exactly(t, "<EMAIL>", e) }) }) t.Run("Records in final args", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `name`, `email` FROM `dml_person` WHERE (`id` = ?) AND (`name` = ?)")) prep.ExpectQuery().WithArgs(4211, "<NAME>"). WillReturnRows(sqlmock.NewRows([]string{"name", "email"}).AddRow("<NAME>", "<EMAIL>")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("name", "email").From("dml_person"). Where(dml.Column("id").PlaceHolder(), dml.Column("name").PlaceHolder())) t.Run("Context", func(t *testing.T) { p := &dmlPerson{ ID: 4211, Name: "<NAME>", } rows, err := stmt.QueryContext(context.Background(), dml.Qualify("", p)) assert.NoError(t, err) defer dmltest.Close(t, rows) cols, err := rows.Columns() assert.NoError(t, err) assert.Exactly(t, []string{"name", "email"}, cols) }) }) t.Run("QueryContext", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `name`, `email` FROM `dml_person` WHERE (`id` = ?)")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("name", "email").From("dml_person"). Where(dml.Column("id").PlaceHolder())) defer dmltest.Close(t, stmt) const iterations = 3 t.Run("WithArguments", func(t *testing.T) { for i := 0; i < iterations; i++ { prep.ExpectQuery().WithArgs(6899). WillReturnRows(sqlmock.NewRows([]string{"name", "email"}).AddRow("<NAME>", "<EMAIL>")) } // use loop with Query+ and add args before for i := 0; i < iterations; i++ { rows, err := stmt.QueryContext(context.Background(), 6899) assert.NoError(t, err) cols, err := rows.Columns() assert.NoError(t, err) assert.Exactly(t, []string{"name", "email"}, cols) dmltest.Close(t, rows) } }) t.Run("WithRecords_OK", func(t *testing.T) { for i := 0; i < iterations; i++ { prep.ExpectQuery().WithArgs(6900). WillReturnRows(sqlmock.NewRows([]string{"name", "email"}).AddRow("<NAME>", "<EMAIL>")) } p := &dmlPerson{ID: 6900} for i := 0; i < iterations; i++ { rows, err := stmt.QueryContext(context.Background(), dml.Qualify("", p)) assert.NoError(t, err) cols, err := rows.Columns() assert.NoError(t, err) assert.Exactly(t, []string{"name", "email"}, cols) dmltest.Close(t, rows) } }) t.Run("WithRecords_Error", func(t *testing.T) { p := &TableCoreConfigDataSlice{err: errors.Duplicated.Newf("Found a duplicate")} rows, err := stmt.QueryContext(context.Background(), dml.Qualify("", p)) assert.ErrorIsKind(t, errors.Duplicated, err) assert.Nil(t, rows) }) }) t.Run("Load", func(t *testing.T) { t.Run("multi rows", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `config_id`, `scope_id`, `path` FROM `core_config_data` WHERE (`config_id` IN ?)")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("config_id", "scope_id", "path").From("core_config_data"). Where(dml.Column("config_id").In().PlaceHolder())) defer dmltest.Close(t, stmt) columns := []string{"config_id", "scope_id", "path"} prep.ExpectQuery().WithArgs(345). WillReturnRows(sqlmock.NewRows(columns).AddRow(3, 4, "a/b/c").AddRow(4, 4, "a/b/d")) ccd := &TableCoreConfigDataSlice{} rc, err := stmt.Load(context.Background(), ccd, 345) assert.NoError(t, err) assert.Exactly(t, uint64(2), rc) assert.Exactly(t, "&{3 4 a/b/c null}", fmt.Sprintf("%v", ccd.Data[0])) assert.Exactly(t, "&{4 4 a/b/d null}", fmt.Sprintf("%v", ccd.Data[1])) }) t.Run("Int64", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `scope_id` FROM `core_config_data` WHERE (`config_id` = ?)")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("scope_id").From("core_config_data"). Where(dml.Column("config_id").PlaceHolder())) defer dmltest.Close(t, stmt) columns := []string{"scope_id"} prep.ExpectQuery().WithArgs(346).WillReturnRows(sqlmock.NewRows(columns).AddRow(35)) val, found, err := stmt.LoadNullInt64(context.Background(), 346) assert.NoError(t, err) assert.True(t, found) assert.Exactly(t, null.MakeInt64(35), val) }) t.Run("Int64s", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `scope_id` FROM `core_config_data` WHERE (`config_id` IN ?)")) stmt := dbc.WithPrepare(context.Background(), dml.NewSelect("scope_id").From("core_config_data"). Where(dml.Column("config_id").In().PlaceHolder())) defer dmltest.Close(t, stmt) columns := []string{"scope_id"} prep.ExpectQuery().WithArgs(346, 347).WillReturnRows(sqlmock.NewRows(columns).AddRow(36).AddRow(37)) val, err := stmt.LoadInt64s(context.Background(), nil, []int64{346, 347}) assert.NoError(t, err) assert.Exactly(t, []int64{36, 37}, val) }) }) } func TestSelect_Argument_Iterate(t *testing.T) { dbc := dmltest.MustConnectDB(t) defer dmltest.Close(t, dbc) defer dmltest.SQLDumpLoad(t, "testdata/person_ffaker*", &dmltest.SQLDumpOptions{DSN: dbc.DSN()}).Deferred() rowCount, found, err := dbc.WithQueryBuilder(dml.NewSelect().Count().From("dml_fake_person")).LoadNullInt64(context.Background()) assert.NoError(t, err) assert.True(t, found) if rowCount.Int64 < 10000 { t.Skipf("dml_fake_person table contains less than 10k items, seems not to be installed. Got %d items", rowCount.Int64) } t.Run("serial", func(t *testing.T) { t.Run("error in mapper", func(t *testing.T) { err := dbc.WithQueryBuilder( dml.NewSelect().AddColumns("id", "weight", "height", "update_time").From("dml_fake_person"). Limit(0, 5).OrderBy("id"), ).IterateSerial(context.Background(), func(cm *dml.ColumnMap) error { return errors.Blocked.Newf("Mapping blocked") }) assert.ErrorIsKind(t, errors.Blocked, err) }) t.Run("serial serial", func(t *testing.T) { const rowCount = 500 selExec := dbc.WithQueryBuilder(dml.NewSelect().From("dml_fake_person").AddColumns("id", "weight", "height", "update_time"). OrderByRandom("id", rowCount)) var counter int err := selExec.IterateSerial(context.Background(), func(cm *dml.ColumnMap) error { fp := &fakePerson{} if err := fp.MapColumns(cm); err != nil { return err } if fp.Weight < 1 || fp.Height < 1 || fp.ID < 0 || fp.UpdateTime.IsZero() { return errors.NotValid.Newf("failed to load fakePerson: one of the four fields (id,weight,height,update_time) is empty: %#v", fp) } counter++ return nil }) assert.NoError(t, err) assert.Exactly(t, rowCount, counter, "Should have loaded %d rows", rowCount) }) t.Run("serial parallel", func(t *testing.T) { // Do not run such a construct in production. const limit = 5 const concurrencyLevel = 10 processFakePerson := func(selProc *dml.DBR, i int) { // testing.T does not work in parallel context, so we use panic :-( fp := &fakePerson{} var counter int err := selProc.IterateSerial(context.Background(), func(cm *dml.ColumnMap) error { if err := fp.MapColumns(cm); err != nil { return err } // fmt.Printf("%d: %#v\n", i, fp) if fp.Weight < 1 || fp.Height < 1 || fp.ID < i || fp.UpdateTime.IsZero() { return errors.NotValid.Newf("failed to load fakePerson: one of the four fields (id,weight,height,update_time) is empty: %#v", fp) } counter++ return nil }, i, i+5) ifErrPanic(err) ifNotEqualPanic(counter, limit, "Should have loaded this amount of rows") } // dbc.Schema()+". that is a hack :-( fpSel := dbc.WithQueryBuilder(dml.NewSelect("id", "weight", "height", "update_time").From(dbc.Schema()+".dml_fake_person"). Where( dml.Column("id").Between().PlaceHolder(), ). Limit(0, limit).OrderBy("id")).Interpolate() t.Run("WG01 (query, conn pool)", func(t *testing.T) { bgwork.Wait(concurrencyLevel, func(index int) { // Every goroutine creates its own underlying connection to the // SQL server. This makes sense because each dataset is unique. processFakePerson(fpSel, index*concurrencyLevel) }) }) t.Run("WG02 (prepared,multi conn)", func(t *testing.T) { stmt, err := fpSel.Prepare(context.Background()) assert.NoError(t, err) defer dmltest.Close(t, stmt) bgwork.Wait(concurrencyLevel, func(index int) { // Every goroutine creates its own underlying connection to the // SQL server and prepares its own statement in the SQL server // despite having one single pointer to *sql.Stmt. processFakePerson(stmt, index*concurrencyLevel) }) }) }) }) const concurrencyLevel = 4 t.Run("parallel", func(t *testing.T) { t.Run("error wrong concurrency level", func(t *testing.T) { err := dbc.WithQueryBuilder(dml.NewSelect().From("dml_fake_person").AddColumns("id", "weight", "height", "update_time"). Limit(0, 50).OrderBy("id")).IterateParallel(context.Background(), 0, func(cm *dml.ColumnMap) error { return nil }) assert.ErrorIsKind(t, errors.OutOfRange, err) }) t.Run("error in mapper of all workers", func(t *testing.T) { err := dbc.WithQueryBuilder(dml.NewSelect().From("dml_fake_person").AddColumns("id", "weight", "height", "update_time"). Limit(0, 50).OrderBy("id")).IterateParallel(context.Background(), concurrencyLevel, func(cm *dml.ColumnMap) error { return errors.Blocked.Newf("Mapping blocked error") }) assert.ErrorIsKind(t, errors.Blocked, err) }) t.Run("successful 40 rows fibonacci", func(t *testing.T) { sel01 := dml.NewSelect("id", "weight", "height", "update_time").From(dbc.Schema()+".dml_fake_person"). Where(dml.Column("id").LessOrEqual().Int(60)). Limit(0, 40) sel01.IsOrderByRand = true rowsLoadedCounter := new(int32) err := dbc.WithQueryBuilder(sel01).IterateParallel(context.Background(), concurrencyLevel, func(cm *dml.ColumnMap) error { var fp fakePerson if err := fp.MapColumns(cm); err != nil { return err } if fp.Weight < 1 || fp.Height < 1 || fp.ID < 1 || fp.UpdateTime.IsZero() { return errors.NotValid.Newf("failed to load fakePerson: one of the four fields (id,weight,height,update_time) is empty: %#v", fp) } if fp.ID < 41 { _ = fib(uint(fp.ID)) // fi := fib(uint(fp.ID)) // println("a 591", int(cm.Count), fp.ID, fi) } /* else { println("a 597", int(cm.Count), fp.ID) } */ // fmt.Printf("%d: FIB:%d: fakePerson ID %d\n", cm.Count, fib(uint(fp.ID)), fp.ID) atomic.AddInt32(rowsLoadedCounter, 1) return nil }) assert.NoError(t, err) assert.Exactly(t, int32(40), *rowsLoadedCounter, "Should load this amount of rows from the database server.") }) }) } func fib(n uint) uint { if n == 0 { return 0 } else if n == 1 { return 1 } else { return fib(n-1) + fib(n-2) } } func TestSelect_Clone(t *testing.T) { dbc, dbMock := dmltest.MockDB(t, dml.WithLogger(log.BlackHole{}, func() string { return "uniqueID" })) defer dmltest.MockClose(t, dbc, dbMock) t.Run("nil", func(t *testing.T) { var s *dml.Select s2 := s.Clone() assert.Nil(t, s) assert.Nil(t, s2) }) t.Run("non-nil", func(t *testing.T) { s := dml.NewSelect().FromAlias("dml_people", "p1").AddColumns("p1.*"). AddColumnsAliases("p2.name", "p2Name", "p2.email", "p2Email"). RightJoin( dml.MakeIdentifier("dml_people").Alias("p2"), dml.Columns("id", "email"), ). Where( dml.Column("name").Like().PlaceHolder(), ). OrderBy("email"). GroupBy("last_name"). Having( dml.Column("income").LessOrEqual().PlaceHolder(), ) s2 := s.Clone() notEqualPointers(t, s, s2) notEqualPointers(t, s.BuilderConditional.Wheres, s2.BuilderConditional.Wheres) notEqualPointers(t, s.BuilderConditional.Joins, s2.BuilderConditional.Joins) notEqualPointers(t, s.BuilderConditional.OrderBys, s2.BuilderConditional.OrderBys) notEqualPointers(t, s.GroupBys, s2.GroupBys) notEqualPointers(t, s.Havings, s2.Havings) // assert.Exactly(t, s.db, s2.db) // test it via fmt.Sprintf? }) } func TestSelect_When_Unless(t *testing.T) { t.Run("true and no default", func(t *testing.T) { s := dml.NewSelect("entity_id").From("catalog_product_entity") s.When(true, func(s2 *dml.Select) { s2.Where(dml.Column("sku").Like().Str("4711")) }, nil) assert.Exactly(t, "SELECT `entity_id` FROM `catalog_product_entity` WHERE (`sku` LIKE '4711')", s.String()) }) t.Run("false and no default", func(t *testing.T) { s := dml.NewSelect("entity_id").From("catalog_product_entity") s.When(false, func(s2 *dml.Select) { s2.Where(dml.Column("sku").Like().Str("4711")) }, nil) assert.Exactly(t, "SELECT `entity_id` FROM `catalog_product_entity`", s.String()) }) t.Run("Unless true and default", func(t *testing.T) { s := dml.NewSelect("entity_id").From("catalog_product_entity") s.Unless(true, func(s2 *dml.Select) { s2.Where(dml.Column("sku").Like().Str("4712")) }, func(s2 *dml.Select) { s2.Where(dml.Column("sku").Like().Str("4713")) }) assert.Exactly(t, "SELECT `entity_id` FROM `catalog_product_entity` WHERE (`sku` LIKE '4713')", s.String()) }) } func TestPrepareWithDBR(t *testing.T) { t.Run("all dml types", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("SELECT `a1` FROM `a`")).WillBeClosed() dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("(SELECT * FROM `b1`) UNION (SELECT * FROM `b2`)")).WillBeClosed() dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("UPDATE `c` SET `c1`=?")).WillBeClosed() dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("WITH `one` AS (SELECT 1) SELECT * FROM `one`")).WillBeClosed() dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("DELETE FROM `e`")).WillBeClosed() dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("INSERT INTO `d` (`d1`) VALUES (?)")).WillBeClosed() ctx := context.Background() for _, a := range []*dml.DBR{ dbc.WithPrepare(ctx, dml.NewSelect().From("a").AddColumns("a1")), dbc.WithPrepare(ctx, dml.NewUnion(dml.NewSelect("*").From("b1"), dml.NewSelect("*").From("b2"))), dbc.WithPrepare(ctx, dml.NewUpdate("c").AddColumns("c1")), dbc.WithPrepare(ctx, dml.NewWith( dml.WithCTE{Name: "one", Select: dml.NewSelect().Unsafe().AddColumns("1")}, ).Select(dml.NewSelect().Star().From("one"))), dbc.WithPrepare(ctx, dml.NewDelete("e")), dbc.WithPrepare(ctx, dml.NewInsert("d").AddColumns("d1").BuildValues()), } { dmltest.Close(t, a) } }) t.Run("select error", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) ctx := context.Background() err := dbc.WithPrepare(ctx, dml.NewSelect().From("a")).Close() assert.ErrorIsKind(t, errors.Empty, err) }) t.Run("union error", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) ctx := context.Background() err := dbc.WithPrepare(ctx, dml.NewUnion(dml.NewSelect("*").From("b"))).Close() assert.ErrorIsKind(t, errors.Empty, err) }) } func TestDBR_ExpandTuples(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) ctx := context.Background() dbr := dbc.WithQueryBuilder(dml.NewSelect().Star().From("core_config_data").Where( dml.Columns("entity_id", "attribute_id", "store_id", "source_id").In().Tuples(), )).ExpandPlaceHolders() t.Run("1,4 tuple, no interpolate", func(t *testing.T) { dbMock.ExpectQuery(dmltest.SQLMockQuoteMeta("SELECT * FROM `core_config_data` WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN ((?,?,?,?)))")). WithArgs(1, 2, 3, 4). WillReturnRows(dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data.csv"))) ccd := &TableCoreConfigDataSlice{} _, err := dbr.Load(ctx, ccd, 1, 2, 3, 4) assert.NoError(t, err) }) t.Run("2,4 tuple, no interpolate", func(t *testing.T) { dbMock.ExpectQuery(dmltest.SQLMockQuoteMeta("SELECT * FROM `core_config_data` WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN ((?,?,?,?),(?,?,?,?)))")). WithArgs("b1", 2, 3, 4, "a11", 22, 33, 44). WillReturnRows(dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data.csv"))) ccd := &TableCoreConfigDataSlice{} _, err := dbr.Load(ctx, ccd, "b1", 2, 3, 4, "a11", 22, 33, 44) assert.NoError(t, err) }) t.Run("1,4 tuple, with interpolate", func(t *testing.T) { dbMock.ExpectQuery(dmltest.SQLMockQuoteMeta("SELECT * FROM `core_config_data` WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN ((1,2,3,4)))")). WithArgs(). WillReturnRows(dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data.csv"))) ccd := &TableCoreConfigDataSlice{} _, err := dbr.Interpolate().Load(ctx, ccd, 1, 2, 3, 4) assert.NoError(t, err) }) } <|start_filename|>sql/dml/update_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func TestUpdate_Basics(t *testing.T) { t.Run("all rows", func(t *testing.T) { qb := NewUpdate("a").AddClauses( Column("b").Int64(1), Column("c").Int(2)) compareToSQL(t, qb, errors.NoKind, "UPDATE `a` SET `b`=1, `c`=2", "") }) t.Run("single row", func(t *testing.T) { compareToSQL(t, NewUpdate("a"). AddClauses( Column("b").Int(1), Column("c").Int(2), ).Where(Column("id").Int(1)), errors.NoKind, "UPDATE `a` SET `b`=1, `c`=2 WHERE (`id` = 1)", "UPDATE `a` SET `b`=1, `c`=2 WHERE (`id` = 1)") }) t.Run("order by", func(t *testing.T) { qb := NewUpdate("a").AddClauses(Column("b").Int(1), Column("c").Int(2)). OrderBy("col1", "col2").OrderByDesc("col2", "col3").Unsafe().OrderBy("concat(1,2,3)") compareToSQL(t, qb, errors.NoKind, "UPDATE `a` SET `b`=1, `c`=2 ORDER BY `col1`, `col2`, `col2` DESC, `col3` DESC, concat(1,2,3)", "UPDATE `a` SET `b`=1, `c`=2 ORDER BY `col1`, `col2`, `col2` DESC, `col3` DESC, concat(1,2,3)") }) t.Run("limit offset", func(t *testing.T) { compareToSQL(t, NewUpdate("a").AddClauses(Column("b").Int(1)).Limit(10), errors.NoKind, "UPDATE `a` SET `b`=1 LIMIT 10", "UPDATE `a` SET `b`=1 LIMIT 10") }) t.Run("same column name in SET and WHERE", func(t *testing.T) { compareToSQL(t, NewUpdate("dml_people").AddClauses(Column("key").Str("6-revoked")).Where(Column("key").Str("6")), errors.NoKind, "UPDATE `dml_people` SET `key`='6-revoked' WHERE (`key` = '6')", "UPDATE `dml_people` SET `key`='6-revoked' WHERE (`key` = '6')") }) t.Run("placeholder in columns", func(t *testing.T) { u := NewUpdate("dml_people").AddClauses( Column("key").PlaceHolder(), ).Where(Column("key").Str("6")).WithDBR(dbMock{}).TestWithArgs("Ke' --yX") compareToSQL(t, u, errors.NoKind, "UPDATE `dml_people` SET `key`=? WHERE (`key` = '6')", "UPDATE `dml_people` SET `key`='Ke\\' --yX' WHERE (`key` = '6')", "Ke' --yX") }) } func TestUpdate_SetExprToSQL(t *testing.T) { t.Run("no placeholder", func(t *testing.T) { compareToSQL(t, NewUpdate("a"). AddClauses( Column("foo").Int(1), Column("bar").Expr("COALESCE(bar, 0) + 1"), ).Where(Column("id").Int(9)), errors.NoKind, "UPDATE `a` SET `foo`=1, `bar`=COALESCE(bar, 0) + 1 WHERE (`id` = 9)", "UPDATE `a` SET `foo`=1, `bar`=COALESCE(bar, 0) + 1 WHERE (`id` = 9)", ) }) t.Run("with slice in WHERE clause", func(t *testing.T) { compareToSQL(t, NewUpdate("a"). AddClauses( Column("foo").Int(1), Column("bar").Expr("COALESCE(bar, 0) + 1"), ).Where(Column("id").In().Int64s(10, 11)), errors.NoKind, "UPDATE `a` SET `foo`=1, `bar`=COALESCE(bar, 0) + 1 WHERE (`id` IN (10,11))", "UPDATE `a` SET `foo`=1, `bar`=COALESCE(bar, 0) + 1 WHERE (`id` IN (10,11))", ) }) t.Run("with placeholder", func(t *testing.T) { u := NewUpdate("a"). AddClauses( Column("fooNULL").PlaceHolder(), Column("bar99").Expr("COALESCE(bar, 0) + ?"), ). Where(Column("id").Int(9)). WithDBR(dbMock{}) compareToSQL(t, u.TestWithArgs(null.String{}, uint(99)), errors.NoKind, "UPDATE `a` SET `fooNULL`=?, `bar99`=COALESCE(bar, 0) + ? WHERE (`id` = 9)", "", //"UPDATE `a` SET `foo`=1, `bar`=COALESCE(bar, 0) + 2 WHERE (`id` = 9)", nil, int64(99)) assert.Exactly(t, []string{"fooNULL", "bar99"}, u.cachedSQL.qualifiedColumns) }) } func TestUpdateKeywordColumnName(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) // Insert a user with a key _, err := NewInsert("dml_people").AddColumns("name", "email", "key"). WithDBR(s.DB).ExecContext(context.TODO(), "Benjamin", "<EMAIL>", "6") assert.NoError(t, err) // Update the key res, err := NewUpdate("dml_people").AddClauses(Column("key").Str("6-revoked")).Where(Column("key").Str("6")).WithDBR(s.DB).ExecContext(context.TODO()) assert.NoError(t, err) // Assert our record was updated (and only our record) rowsAff, err := res.RowsAffected() assert.NoError(t, err) assert.Exactly(t, int64(1), rowsAff) var person dmlPerson _, err = NewSelect("id", "name", "key").From("dml_people"). Where(Column("email").Str("<EMAIL>")).WithDBR(s.DB).Load(context.TODO(), &person) assert.NoError(t, err) assert.Exactly(t, "Benjamin", person.Name) assert.Exactly(t, "6-revoked", person.Key.Data) } func TestUpdateReal(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) // Insert a George res, err := NewInsert("dml_people").AddColumns("name", "email"). WithDBR(s.DB).ExecContext(context.TODO(), "George", "<EMAIL>") assert.NoError(t, err) // Get George'ab ID id, err := res.LastInsertId() assert.NoError(t, err) // Rename our George to Barack _, err = NewUpdate("dml_people"). AddClauses(Column("name").Str("Barack"), Column("email").Str("<EMAIL>")). Where(Column("id").In().Int64s(id, 8888)).WithDBR(s.DB).ExecContext(context.TODO()) // Meaning of 8888: Just to see if the SQL with place holders gets created correctly assert.NoError(t, err) var person dmlPerson _, err = NewSelect("*").From("dml_people").Where(Column("id").Int64(id)).WithDBR(s.DB).Load(context.TODO(), &person) assert.NoError(t, err) assert.Exactly(t, id, int64(person.ID)) assert.Exactly(t, "Barack", person.Name) assert.Exactly(t, true, person.Email.Valid) assert.Exactly(t, "<EMAIL>", person.Email.Data) } func TestUpdate_ToSQL_Without_Column_Arguments(t *testing.T) { t.Run("with condition values", func(t *testing.T) { u := NewUpdate("catalog_product_entity").AddColumns("sku", "updated_at") u.Where(Column("entity_id").In().Int64s(1, 2, 3)) compareToSQL(t, u, errors.NoKind, "UPDATE `catalog_product_entity` SET `sku`=?, `updated_at`=? WHERE (`entity_id` IN (1,2,3))", "", ) }) t.Run("without condition values", func(t *testing.T) { u := NewUpdate("catalog_product_entity").AddColumns("sku", "updated_at") u.Where(Column("entity_id").In().PlaceHolder()) compareToSQL(t, u, errors.NoKind, "UPDATE `catalog_product_entity` SET `sku`=?, `updated_at`=? WHERE (`entity_id` IN ?)", "", ) }) } func TestUpdate_SetRecord(t *testing.T) { pRec := &dmlPerson{ ID: 12345, Name: "Gopher", Email: null.MakeString("<EMAIL>"), } t.Run("without where", func(t *testing.T) { u := NewUpdate("dml_person").AddColumns("name", "email").WithDBR(dbMock{}).TestWithArgs(Qualify("", pRec)) compareToSQL(t, u, errors.NoKind, "UPDATE `dml_person` SET `name`=?, `email`=?", "UPDATE `dml_person` SET `name`='Gopher', `email`='<EMAIL>'", "Gopher", "<EMAIL>", ) }) t.Run("with where", func(t *testing.T) { u := NewUpdate("dml_person").AddColumns("name", "email"). Where(Column("id").PlaceHolder()).WithDBR(dbMock{}) compareToSQL(t, u.TestWithArgs(Qualify("", pRec)), errors.NoKind, "UPDATE `dml_person` SET `name`=?, `email`=? WHERE (`id` = ?)", "UPDATE `dml_person` SET `name`='Gopher', `email`='<EMAIL>' WHERE (`id` = 12345)", "Gopher", "<EMAIL>", int64(12345), ) assert.Exactly(t, []string{"name", "email", "id"}, u.cachedSQL.qualifiedColumns) }) t.Run("fails column `key` not in entity object", func(t *testing.T) { u := NewUpdate("dml_person").AddColumns("name", "email"). AddClauses(Column("keyXXX").PlaceHolder()). Where(Column("id").PlaceHolder()). WithDBR(dbMock{}).TestWithArgs(Qualify("", pRec)) compareToSQL(t, u, errors.NotFound, "", "", ) }) } func TestUpdate_SetColumns(t *testing.T) { u := NewUpdate("dml_person").AddColumns("name", "email"). AddClauses(Column("keyXXX").PlaceHolder()). Where(Column("id").PlaceHolder()) u.SetColumns("firstname", "dob") compareToSQL(t, u, errors.NoKind, "UPDATE `dml_person` SET `firstname`=?, `dob`=? WHERE (`id` = ?)", "", ) } <|start_filename|>sql/urlvalues/values.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: values.proto // +build csall proto package urlvalues import ( fmt "fmt" io "io" math "math" math_bits "math/bits" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. var ( _ = proto.Marshal _ = fmt.Errorf _ = 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.GoGoProtoPackageIsVersion3 // please upgrade the proto package type ProtoKeyValue struct { Key string `protobuf:"bytes,1,opt,name=Key,proto3" json:"Key,omitempty"` Value []string `protobuf:"bytes,2,rep,name=Value,proto3" json:"Value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ProtoKeyValue) Reset() { *m = ProtoKeyValue{} } func (m *ProtoKeyValue) String() string { return proto.CompactTextString(m) } func (*ProtoKeyValue) ProtoMessage() {} func (*ProtoKeyValue) Descriptor() ([]byte, []int) { return fileDescriptor_5d19e76c3b90e014, []int{0} } func (m *ProtoKeyValue) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ProtoKeyValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ProtoKeyValue.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ProtoKeyValue) XXX_Merge(src proto.Message) { xxx_messageInfo_ProtoKeyValue.Merge(m, src) } func (m *ProtoKeyValue) XXX_Size() int { return m.Size() } func (m *ProtoKeyValue) XXX_DiscardUnknown() { xxx_messageInfo_ProtoKeyValue.DiscardUnknown(m) } var xxx_messageInfo_ProtoKeyValue proto.InternalMessageInfo type ProtoKeyValues struct { Data []*ProtoKeyValue `protobuf:"bytes,1,rep,name=Data,proto3" json:"Data,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ProtoKeyValues) Reset() { *m = ProtoKeyValues{} } func (m *ProtoKeyValues) String() string { return proto.CompactTextString(m) } func (*ProtoKeyValues) ProtoMessage() {} func (*ProtoKeyValues) Descriptor() ([]byte, []int) { return fileDescriptor_5d19e76c3b90e014, []int{1} } func (m *ProtoKeyValues) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ProtoKeyValues) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ProtoKeyValues.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ProtoKeyValues) XXX_Merge(src proto.Message) { xxx_messageInfo_ProtoKeyValues.Merge(m, src) } func (m *ProtoKeyValues) XXX_Size() int { return m.Size() } func (m *ProtoKeyValues) XXX_DiscardUnknown() { xxx_messageInfo_ProtoKeyValues.DiscardUnknown(m) } var xxx_messageInfo_ProtoKeyValues proto.InternalMessageInfo func init() { proto.RegisterType((*ProtoKeyValue)(nil), "urlvalues.ProtoKeyValue") proto.RegisterType((*ProtoKeyValues)(nil), "urlvalues.ProtoKeyValues") } func init() { proto.RegisterFile("values.proto", fileDescriptor_5d19e76c3b90e014) } var fileDescriptor_5d19e76c3b90e014 = []byte{ // 183 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0x4b, 0xcc, 0x29, 0x4d, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x2c, 0x2d, 0xca, 0x81, 0x08, 0x48, 0xe9, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xa7, 0xe7, 0xeb, 0x83, 0x55, 0x24, 0x95, 0xa6, 0x81, 0x79, 0x60, 0x0e, 0x98, 0x05, 0xd1, 0xa9, 0x64, 0xce, 0xc5, 0x1b, 0x00, 0x62, 0x78, 0xa7, 0x56, 0x86, 0x81, 0x0c, 0x10, 0x12, 0xe0, 0x62, 0xf6, 0x4e, 0xad, 0x94, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0x31, 0x85, 0x44, 0xb8, 0x58, 0xc1, 0x52, 0x12, 0x4c, 0x0a, 0xcc, 0x1a, 0x9c, 0x41, 0x10, 0x8e, 0x92, 0x1d, 0x17, 0x1f, 0x8a, 0xc6, 0x62, 0x21, 0x1d, 0x2e, 0x16, 0x97, 0xc4, 0x92, 0x44, 0x09, 0x46, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x09, 0x3d, 0xb8, 0x9b, 0xf4, 0x50, 0x14, 0x06, 0x81, 0x55, 0x39, 0xc9, 0x9f, 0x78, 0x28, 0xc7, 0x70, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x10, 0x85, 0xf0, 0x48, 0x12, 0x1b, 0xd8, 0x81, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x73, 0xe9, 0xf4, 0x91, 0xea, 0x00, 0x00, 0x00, } func (m *ProtoKeyValue) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ProtoKeyValue) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ProtoKeyValue) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Value) > 0 { for iNdEx := len(m.Value) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Value[iNdEx]) copy(dAtA[i:], m.Value[iNdEx]) i = encodeVarintValues(dAtA, i, uint64(len(m.Value[iNdEx]))) i-- dAtA[i] = 0x12 } } if len(m.Key) > 0 { i -= len(m.Key) copy(dAtA[i:], m.Key) i = encodeVarintValues(dAtA, i, uint64(len(m.Key))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *ProtoKeyValues) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ProtoKeyValues) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ProtoKeyValues) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Data) > 0 { for iNdEx := len(m.Data) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Data[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintValues(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func encodeVarintValues(dAtA []byte, offset int, v uint64) int { offset -= sovValues(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *ProtoKeyValue) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Key) if l > 0 { n += 1 + l + sovValues(uint64(l)) } if len(m.Value) > 0 { for _, s := range m.Value { l = len(s) n += 1 + l + sovValues(uint64(l)) } } return n } func (m *ProtoKeyValues) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Data) > 0 { for _, e := range m.Data { l = e.Size() n += 1 + l + sovValues(uint64(l)) } } return n } func sovValues(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozValues(x uint64) (n int) { return sovValues(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *ProtoKeyValue) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowValues } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ProtoKeyValue: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ProtoKeyValue: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowValues } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthValues } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthValues } if postIndex > l { return io.ErrUnexpectedEOF } m.Key = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowValues } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthValues } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthValues } if postIndex > l { return io.ErrUnexpectedEOF } m.Value = append(m.Value, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipValues(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthValues } if (iNdEx + skippy) < 0 { return ErrInvalidLengthValues } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ProtoKeyValues) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowValues } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ProtoKeyValues: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ProtoKeyValues: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowValues } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthValues } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthValues } if postIndex > l { return io.ErrUnexpectedEOF } m.Data = append(m.Data, &ProtoKeyValue{}) if err := m.Data[len(m.Data)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipValues(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthValues } if (iNdEx + skippy) < 0 { return ErrInvalidLengthValues } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipValues(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowValues } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowValues } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowValues } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthValues } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupValues } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthValues } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthValues = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowValues = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupValues = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>sql/dml/interfaces_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" ) var ( _ QueryExecPreparer = (*dbMock)(nil) _ Execer = (*dbMock)(nil) ) type dbMock struct { error prepareFn func(query string) (*sql.Stmt, error) } func (pm dbMock) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { if pm.error != nil { return nil, pm.error } if pm.prepareFn != nil { return pm.prepareFn(query) } return new(sql.Stmt), nil } func (pm dbMock) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { if pm.error != nil { return nil, pm.error } return new(sql.Rows), nil } func (pm dbMock) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { if pm.error != nil { return nil, pm.error } return nil, nil } func (pm dbMock) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row { return new(sql.Row) } <|start_filename|>sql/ddl/foreign_key.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ddl import ( "context" "database/sql" "fmt" "io" "sort" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/storage/null" ) // KeyColumnUsage represents a single row for DB table `KEY_COLUMN_USAGE` type KeyColumnUsage struct { ConstraintCatalog string // CONSTRAINT_CATALOG varchar(512) NOT NULL DEFAULT '''' "" ConstraintSchema string // CONSTRAINT_SCHEMA varchar(64) NOT NULL DEFAULT '''' "" ConstraintName string // CONSTRAINT_NAME varchar(64) NOT NULL DEFAULT '''' "" TableCatalog string // TABLE_CATALOG varchar(512) NOT NULL DEFAULT '''' "" TableSchema string // TABLE_SCHEMA varchar(64) NOT NULL DEFAULT '''' "" TableName string // TABLE_NAME varchar(64) NOT NULL DEFAULT '''' "" ColumnName string // COLUMN_NAME varchar(64) NOT NULL DEFAULT '''' "" OrdinalPosition int64 // ORDINAL_POSITION bigint(10) NOT NULL DEFAULT '0' "" PositionInUniqueConstraint null.Int64 // POSITION_IN_UNIQUE_CONSTRAINT bigint(10) NULL DEFAULT 'NULL' "" ReferencedTableSchema null.String // REFERENCED_TABLE_SCHEMA varchar(64) NULL DEFAULT 'NULL' "" ReferencedTableName null.String // REFERENCED_TABLE_NAME varchar(64) NULL DEFAULT 'NULL' "" ReferencedColumnName null.String // REFERENCED_COLUMN_NAME varchar(64) NULL DEFAULT 'NULL' "" } // MapColumns implements interface ColumnMapper only partially. func (e *KeyColumnUsage) MapColumns(cm *dml.ColumnMap) error { for cm.Next(12) { switch c := cm.Column(); c { case "CONSTRAINT_CATALOG", "0": cm.String(&e.ConstraintCatalog) case "CONSTRAINT_SCHEMA", "1": cm.String(&e.ConstraintSchema) case "CONSTRAINT_NAME", "2": cm.String(&e.ConstraintName) case "TABLE_CATALOG", "3": cm.String(&e.TableCatalog) case "TABLE_SCHEMA", "4": cm.String(&e.TableSchema) case "TABLE_NAME", "5": cm.String(&e.TableName) case "COLUMN_NAME", "6": cm.String(&e.ColumnName) case "ORDINAL_POSITION", "7": cm.Int64(&e.OrdinalPosition) case "POSITION_IN_UNIQUE_CONSTRAINT", "8": cm.NullInt64(&e.PositionInUniqueConstraint) case "REFERENCED_TABLE_SCHEMA", "9": cm.NullString(&e.ReferencedTableSchema) case "REFERENCED_TABLE_NAME", "10": cm.NullString(&e.ReferencedTableName) case "REFERENCED_COLUMN_NAME", "11": cm.NullString(&e.ReferencedColumnName) default: return errors.NotFound.Newf("[testdata] KeyColumnUsage Column %q not found", c) } } return errors.WithStack(cm.Err()) } // Reset resets the struct to its empty fields. func (e *KeyColumnUsage) Reset() *KeyColumnUsage { *e = KeyColumnUsage{} return e } // KeyColumnUsageCollection represents a collection type for DB table KEY_COLUMN_USAGE // Not thread safe. Generated via dmlgen. type KeyColumnUsageCollection struct { Data []*KeyColumnUsage BeforeMapColumns func(uint64, *KeyColumnUsage) error AfterMapColumns func(uint64, *KeyColumnUsage) error } // Sort sorts the collection by constraint name. func (cc KeyColumnUsageCollection) Sort() { sort.Slice(cc.Data, func(i, j int) bool { return cc.Data[i].ConstraintName < cc.Data[j].ConstraintName }) } func (cc KeyColumnUsageCollection) scanColumns(cm *dml.ColumnMap, e *KeyColumnUsage, idx uint64) error { if err := cc.BeforeMapColumns(idx, e); err != nil { return errors.WithStack(err) } if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } if err := cc.AfterMapColumns(idx, e); err != nil { return errors.WithStack(err) } return nil } // MapColumns implements dml.ColumnMapper interface func (cc KeyColumnUsageCollection) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for i, e := range cc.Data { if err := cc.scanColumns(cm, e, uint64(i)); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Data = cc.Data[:0] } e := new(KeyColumnUsage) if err := cc.scanColumns(cm, e, cm.Count); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "TABLE_NAME": cm.Strings(cc.TableNames()...) case "COLUMN_NAME": cm.Strings(cc.ColumnNames()...) default: return errors.NotFound.Newf("[testdata] KeyColumnUsageCollection Column %q not found", c) } } default: return errors.NotSupported.Newf("[dml] Unknown Mode: %q", string(m)) } return cm.Err() } // TableNames belongs to the column `TABLE_NAME` and returns a // slice or appends to a slice only unique values of that column. The values // will be filtered internally in a Go map. No DB query gets executed. func (cc KeyColumnUsageCollection) TableNames(ret ...string) []string { if ret == nil { ret = make([]string, 0, len(cc.Data)) } dupCheck := make(map[string]struct{}, len(cc.Data)) for _, e := range cc.Data { if _, ok := dupCheck[e.TableName]; !ok { ret = append(ret, e.TableName) dupCheck[e.TableName] = struct{}{} } } return ret } // ColumnNames belongs to the column `COLUMN_NAME` and returns a // slice or appends to a slice only unique values of that column. The values // will be filtered internally in a Go map. No DB query gets executed. func (cc KeyColumnUsageCollection) ColumnNames(ret ...string) []string { if ret == nil { ret = make([]string, 0, len(cc.Data)) } dupCheck := make(map[string]struct{}, len(cc.Data)) for _, e := range cc.Data { if _, ok := dupCheck[e.ColumnName]; !ok { ret = append(ret, e.ColumnName) dupCheck[e.ColumnName] = struct{}{} } } return ret } // LoadKeyColumnUsage returns all foreign key columns from a list of table names // in the current database. Map key contains TABLE_NAME and value // contains all of the table foreign keys. All columns from all tables gets // selected when you don't provide the argument `tables`. func LoadKeyColumnUsage(ctx context.Context, db dml.Querier, tables ...string) (tc map[string]KeyColumnUsageCollection, err error) { const selFkWhere = ` AND REFERENCED_TABLE_NAME IN ?` const selFkOrderBy = ` ORDER BY TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION, COLUMN_NAME` const selFkTablesColumns = `SELECT CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, POSITION_IN_UNIQUE_CONSTRAINT, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = DATABASE()` + selFkWhere + selFkOrderBy const selFkAllTablesColumns = `SELECT CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, POSITION_IN_UNIQUE_CONSTRAINT, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = DATABASE()` + selFkOrderBy var rows *sql.Rows if len(tables) == 0 { rows, err = db.QueryContext(ctx, selFkAllTablesColumns) if err != nil { return nil, errors.Wrapf(err, "[ddl] LoadKeyColumnUsage QueryContext for tables %v", tables) } } else { sqlStr, _, err := dml.Interpolate(selFkTablesColumns).Strs(tables...).ToSQL() if err != nil { return nil, errors.Wrapf(err, "[ddl] LoadKeyColumnUsage dml.ExpandPlaceHolders for tables %v", tables) } rows, err = db.QueryContext(ctx, sqlStr) if err != nil { return nil, errors.Wrapf(err, "[ddl] LoadKeyColumnUsage QueryContext for tables %v with WHERE clause", tables) } } defer func() { // Not testable with the sqlmock package :-( if err2 := rows.Close(); err2 != nil && err == nil { err = errors.Wrap(err2, "[ddl] LoadKeyColumnUsage.Rows.Close") } }() tc = make(map[string]KeyColumnUsageCollection) rc := new(dml.ColumnMap) for rows.Next() { if err = rc.Scan(rows); err != nil { return nil, errors.Wrapf(err, "[ddl] LoadKeyColumnUsage Scan Query for tables: %v", tables) // due to the defer } kcu := new(KeyColumnUsage) if err = kcu.MapColumns(rc); err != nil { return nil, errors.WithStack(err) } if !kcu.ReferencedTableName.Valid || !kcu.ReferencedColumnName.Valid { err = errors.Fatal.Newf("[ddl] LoadKeyColumnUsage: The columns ReferencedTableName or ReferencedColumnName cannot be null: %#v", kcu) return } kcuc := tc[kcu.TableName] kcuc.Data = append(kcuc.Data, kcu) tc[kcu.TableName] = kcuc } if err = rows.Err(); err != nil { err = errors.WithStack(err) } return } // ReverseKeyColumnUsage reverses the argument to a new key column usage // collection. E.g. customer_entity, catalog_product_entity and other tables // have a foreign key to table store.store_id which is a OneToOne relationship. // When reversed the table store, as map key, points to customer_entity and // catalog_product_entity which becomes then a OneToMany relationship. If that // makes sense is another topic. func ReverseKeyColumnUsage(kcu map[string]KeyColumnUsageCollection) (kcuRev map[string]KeyColumnUsageCollection) { kcuRev = make(map[string]KeyColumnUsageCollection, len(kcu)) for _, kcuc := range kcu { for _, kcucd := range kcuc.Data { kcucRev := kcuRev[kcucd.ReferencedTableName.Data] kcucRev.Data = append(kcucRev.Data, &KeyColumnUsage{ ConstraintCatalog: kcucd.ConstraintCatalog, ConstraintSchema: kcucd.ConstraintSchema, ConstraintName: kcucd.ConstraintName, TableCatalog: kcucd.TableCatalog, TableSchema: kcucd.ReferencedTableSchema.Data, TableName: kcucd.ReferencedTableName.Data, ColumnName: kcucd.ReferencedColumnName.Data, OrdinalPosition: kcucd.OrdinalPosition, PositionInUniqueConstraint: kcucd.PositionInUniqueConstraint, ReferencedTableSchema: null.MakeString(kcucd.TableSchema), ReferencedTableName: null.MakeString(kcucd.TableName), ReferencedColumnName: null.MakeString(kcucd.ColumnName), }) kcuRev[kcucd.ReferencedTableName.Data] = kcucRev } } return kcuRev } type relationKeyType int func (r relationKeyType) String() string { switch r { case fKeyTypeNone: return "relKey:none" case fKeyTypePRI: return "relKey:PRI" case fKeyTypeMUL: return "relKey:MUL" default: panic("relationKeyType unknown type") } } const ( fKeyTypeNone relationKeyType = iota fKeyTypePRI fKeyTypeMUL ) type relTarget struct { column string referencedTable string referencedColumn string relationKeyType } type relTargets []relTarget func (rt relTargets) hasManyToMany() bool { if len(rt) != 2 { return false } // 1. both main columns must be different named. // 2. key relation type must be equal and PRI // 3. referenced tables must be different return rt[0].column != rt[1].column && rt[0].relationKeyType == fKeyTypePRI && rt[0].relationKeyType == rt[1].relationKeyType && rt[0].referencedTable != rt[1].referencedTable && rt[0].referencedColumn != rt[1].referencedColumn } // KeyRelationShips contains an internal cache about the database foreign key // structure. It can only be created via function GenerateKeyRelationships. type KeyRelationShips struct { // making the map private makes this type race free as reading the map from // multiple goroutines is allowed without a lock. // map[mainTable][]relTarget relMap map[string]relTargets } // IsOneToOne func (krs KeyRelationShips) IsOneToOne(mainTable, mainColumn, referencedTable, referencedColumn string) bool { for _, rel := range krs.relMap[mainTable] { if rel.column == mainColumn && rel.referencedTable == referencedTable && rel.referencedColumn == referencedColumn && rel.relationKeyType == fKeyTypePRI { return true } } return false } // IsOneToMany returns true for a oneToMany or switching the tables for a ManyToOne relationship func (krs KeyRelationShips) IsOneToMany(referencedTable, referencedColumn, mainTable, mainColumn string) bool { for _, rel := range krs.relMap[referencedTable] { if rel.column == referencedColumn && rel.referencedTable == mainTable && rel.referencedColumn == mainColumn && rel.relationKeyType == fKeyTypeMUL { return true } } return false } // ManyToManyTarget figures out if a table has M:N relationships and returns the // target table and its column or empty strings if not found. func (krs KeyRelationShips) ManyToManyTarget(linkTable, linkColumn string) (oppositeTable string, oppositeColumn string) { targetRefs := krs.relMap[linkTable] if targetRefs.hasManyToMany() { if targetRefs[0].column == linkColumn { return targetRefs[1].referencedTable, targetRefs[1].referencedColumn } if targetRefs[1].column == linkColumn { return targetRefs[0].referencedTable, targetRefs[0].referencedColumn } } return "", "" } // Debug writes the internal map in a sorted list to w. func (krs KeyRelationShips) Debug(w io.Writer) { keys := make([]string, 0, len(krs.relMap)) for k := range krs.relMap { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { for _, rel := range krs.relMap[k] { fmt.Fprintf(w, "main: %s.%s => ref: %s.%s => %s\n", k, rel.column, rel.referencedTable, rel.referencedColumn, rel.relationKeyType) } } } // GenerateKeyRelationships loads the foreign key relationships between a list of // given tables or all tables in a database. Might not yet work across several // databases on the same file system. func GenerateKeyRelationships(ctx context.Context, db dml.Querier, foreignKeys map[string]KeyColumnUsageCollection) (KeyRelationShips, error) { krs := KeyRelationShips{ relMap: map[string]relTargets{}, } fieldCount, err := countFieldsForTables(ctx, db) if err != nil { return KeyRelationShips{}, errors.WithStack(err) } for _, kcuc := range foreignKeys { for _, kcu := range kcuc.Data { // OneToOne relationship krs.relMap[kcu.TableName] = append(krs.relMap[kcu.TableName], relTarget{ column: kcu.ColumnName, referencedTable: kcu.ReferencedTableName.Data, referencedColumn: kcu.ReferencedColumnName.Data, relationKeyType: fKeyTypePRI, }) // if referenced table has only one PK, then the reversed relationship of OneToMany is not possible if tc, ok := fieldCount[kcu.ReferencedTableName.Data]; ok && tc.Pri == 1 && tc.Empty == 0 && tc.Mul == 0 { // OneToOne reversed is also possible krs.relMap[kcu.ReferencedTableName.Data] = append(krs.relMap[kcu.ReferencedTableName.Data], relTarget{ column: kcu.ReferencedColumnName.Data, referencedTable: kcu.TableName, referencedColumn: kcu.ColumnName, relationKeyType: fKeyTypePRI, }) } if tc, ok := fieldCount[kcu.TableName]; ok && (tc.Empty > 0 || tc.Pri > 1 || tc.Mul == 2) { krs.relMap[kcu.ReferencedTableName.Data] = append(krs.relMap[kcu.ReferencedTableName.Data], relTarget{ column: kcu.ReferencedColumnName.Data, referencedTable: kcu.TableName, referencedColumn: kcu.ColumnName, relationKeyType: fKeyTypeMUL, }) } } } return krs, nil } type columnKeyCount struct { Empty, Mul, Pri, Uni int } func countFieldsForTables(ctx context.Context, db dml.Querier) (_ map[string]*columnKeyCount, err error) { const sqlQry = `SELECT TABLE_NAME, COLUMN_KEY, COUNT(*) AS FIELD_COUNT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() GROUP BY TABLE_NAME,COLUMN_KEY` // TODO limit query to referencedTables, if provided rows, err := db.QueryContext(ctx, sqlQry) if err != nil { return nil, errors.WithStack(err) } defer func() { // Not testable with the sqlmock package :-( if err2 := rows.Close(); err2 != nil && err == nil { err = errors.WithStack(err2) } }() col3 := &struct { TableName string ColumnKey string Count int }{ "", "", 0, } ret := map[string]*columnKeyCount{} for rows.Next() { if err = rows.Scan(&col3.TableName, &col3.ColumnKey, &col3.Count); err != nil { return nil, errors.WithStack(err) } ckc := ret[col3.TableName] if ckc == nil { ret[col3.TableName] = new(columnKeyCount) ckc = ret[col3.TableName] } switch col3.ColumnKey { case "": ckc.Empty = col3.Count case "MUL": ckc.Mul = col3.Count case "PRI": ckc.Pri = col3.Count case "UNI": ckc.Uni = col3.Count default: return nil, errors.NotSupported.Newf("[ddl] ColumnKey %q not supported", col3.ColumnKey) } col3.TableName = "" col3.ColumnKey = "" col3.Count = 0 } if err = rows.Err(); err != nil { err = errors.WithStack(err) } return ret, err } func DisableForeignKeys(ctx context.Context, db dml.Execer, callBack func() error) (err error) { if _, err = db.ExecContext(ctx, "SET foreign_key_checks = 0;"); err != nil { return errors.WithStack(err) } defer func() { if _, err2 := db.ExecContext(ctx, "SET foreign_key_checks = 1;"); err2 != nil && err == nil { err = errors.WithStack(err2) } }() if err = callBack(); err != nil { return errors.WithStack(err) } return nil } <|start_filename|>sql/dml/insert_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/sync/bgwork" "github.com/corestoreio/pkg/util/assert" ) var _ ColumnMapper = (*someRecord)(nil) type someRecord struct { SomethingID int UserID int64 Other bool } func (sr someRecord) MapColumns(cm *ColumnMap) error { for cm.Next(3) { switch c := cm.Column(); c { case "something_id", "0": cm.Int(&sr.SomethingID) case "user_id", "1": cm.Int64(&sr.UserID) case "other", "2": cm.Bool(&sr.Other) default: return errors.NotFound.Newf("[dml_test] Column %q not found", c) } } return cm.Err() } func TestInsert_NoArguments(t *testing.T) { t.Run("ToSQL", func(t *testing.T) { ins := NewInsert("tableA").AddColumns("a", "b").BuildValues() compareToSQL2(t, ins, errors.NoKind, "INSERT INTO `tableA` (`a`,`b`) VALUES (?,?)") }) t.Run("WithDBR.ToSQL", func(t *testing.T) { ins := NewInsert("tableA").AddColumns("a", "b").WithDBR(dbMock{}) compareToSQL2(t, ins, errors.NoKind, "INSERT INTO `tableA` (`a`,`b`) VALUES (?,?)") }) } func TestInsert_SetValuesCount(t *testing.T) { t.Run("No BuildValues", func(t *testing.T) { ins := NewInsert("a").AddColumns("b", "c") compareToSQL2(t, ins, errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES ", ) assert.Exactly(t, []string{"b", "c"}, ins.qualifiedColumns) }) t.Run("BuildValues", func(t *testing.T) { ins := NewInsert("a").AddColumns("b", "c").BuildValues() compareToSQL2(t, ins, errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES (?,?)", ) assert.Exactly(t, []string{"b", "c"}, ins.qualifiedColumns) }) t.Run("set to two", func(t *testing.T) { compareToSQL2(t, NewInsert("a").AddColumns("b", "c").SetRowCount(2).BuildValues(), errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES (?,?),(?,?)", ) }) t.Run("with values", func(t *testing.T) { ins := NewInsert("dml_people").AddColumns("name", "key") inA := ins.WithDBR(nil) compareToSQL2(t, inA.TestWithArgs("Barack", "44"), errors.NoKind, "INSERT INTO `dml_people` (`name`,`key`) VALUES (?,?)", "Barack", "44", ) assert.Exactly(t, []string{"name", "key"}, ins.qualifiedColumns) }) t.Run("with record", func(t *testing.T) { person := dmlPerson{Name: "Barack"} person.Email.Valid = true person.Email.Data = "<EMAIL>" compareToSQL2(t, NewInsert("dml_people").AddColumns("name", "email").WithDBR(dbMock{}).TestWithArgs(Qualify("", &person)), errors.NoKind, "INSERT INTO `dml_people` (`name`,`email`) VALUES (?,?)", "Barack", "<EMAIL>", ) }) } func TestInsertKeywordColumnName(t *testing.T) { // Insert a column whose name is reserved s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) ins := NewInsert("dml_people").AddColumns("name", "key").WithDBR(s.DB) compareExecContext(t, ins, []interface{}{"Barack", "44"}, 0, 1) } func TestInsertReal(t *testing.T) { // Insert by specifying values s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) err := s.RegisterByQueryBuilder(map[string]QueryBuilder{ "selectID": NewSelect("*").From("dml_people").Where(Column("id").PlaceHolder()), }) assert.NoError(t, err) ins := s.WithQueryBuilder(NewInsert("dml_people").AddColumns("name", "email")) lastInsertID, _ := compareExecContext(t, ins, []interface{}{"Barack", "<EMAIL>"}, 3, 0) validateInsertingBarack(t, s, lastInsertID) // Insert by specifying a record (ptr to struct) person := dmlPerson{Name: "Barack"} person.Email.Valid = true person.Email.Data = "<EMAIL>" lastInsertID, _ = compareExecContext(t, ins, []interface{}{Qualify("", &person)}, 4, 0) validateInsertingBarack(t, s, lastInsertID) } func validateInsertingBarack(t *testing.T, c *ConnPool, lastInsertID int64) { var person dmlPerson _, err := c.WithCacheKey("selectID").Load(context.TODO(), &person, lastInsertID) assert.NoError(t, err) assert.Exactly(t, lastInsertID, int64(person.ID)) assert.Exactly(t, "Barack", person.Name) assert.Exactly(t, true, person.Email.Valid) assert.Exactly(t, "<EMAIL>", person.Email.Data) } func TestInsertReal_OnDuplicateKey(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) p := &dmlPerson{ Name: "Pike", Email: null.MakeString("<EMAIL>"), } res, err := NewInsert("dml_people").AddColumns("name", "email"). WithDBR(s.DB).ExecContext(context.TODO(), Qualify("", p)) if err != nil { t.Fatalf("%+v", err) } assert.Exactly(t, uint64(3), p.ID, "Last Insert ID must be three") inID, err := res.LastInsertId() if err != nil { t.Fatalf("%+v", err) } { var p dmlPerson _, err = NewSelect("*").From("dml_people").Where(Column("id").Int64(inID)).WithDBR(s.DB).Load(context.TODO(), &p) assert.NoError(t, err) assert.Exactly(t, "Pike", p.Name) assert.Exactly(t, "<EMAIL>", p.Email.Data) } p.Name = "-" p.Email.Data = "<EMAIL>" res, err = NewInsert("dml_people"). AddColumns("id", "name", "email"). AddOnDuplicateKey(Column("name").Str("Pik3"), Column("email").Values()). WithDBR(s.DB). ExecContext(context.TODO(), Qualify("", p)) if err != nil { t.Fatalf("%+v", err) } inID2, err := res.LastInsertId() if err != nil { t.Fatalf("%+v", err) } assert.Exactly(t, inID, inID2) { var p dmlPerson _, err = NewSelect("*").From("dml_people").Where(Column("id").Int64(inID)). WithDBR(s.DB).Load(context.TODO(), &p) assert.NoError(t, err) assert.Exactly(t, "Pik3", p.Name) assert.Exactly(t, "<EMAIL>", p.Email.Data) } } func TestInsert_FromSelect(t *testing.T) { t.Run("One Placeholder, ON DUPLICATE KEY", func(t *testing.T) { ins := NewInsert("tableA").AddColumns("a", "b").OnDuplicateKey() compareToSQL(t, ins.FromSelect(NewSelect("something_id", "user_id"). From("some_table"). Where( Column("d").PlaceHolder(), Column("e").Str("wat"), ). OrderByDesc("id"), ). WithDBR(nil).TestWithArgs(897), errors.NoKind, "INSERT INTO `tableA` (`a`,`b`) SELECT `something_id`, `user_id` FROM `some_table` WHERE (`d` = ?) AND (`e` = 'wat') ORDER BY `id` DESC ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`)", "INSERT INTO `tableA` (`a`,`b`) SELECT `something_id`, `user_id` FROM `some_table` WHERE (`d` = 897) AND (`e` = 'wat') ORDER BY `id` DESC ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`)", int64(897), ) assert.Exactly(t, []string{"d"}, ins.qualifiedColumns) }) t.Run("one PH, complex SELECT", func(t *testing.T) { ins := NewInsert("tableA").AddColumns("a", "b", "c") compareToSQL(t, ins.FromSelect(NewSelect("something_id", "user_id", "other"). From("some_table"). Where( ParenthesisOpen(), Column("d").PlaceHolder(), Column("e").Str("wat").Or(), ParenthesisClose(), Column("a").In().Int64s(1, 2, 3), ). OrderByDesc("id"). Paginate(1, 20), ). WithDBR(dbMock{}).TestWithArgs(4444), errors.NoKind, "INSERT INTO `tableA` (`a`,`b`,`c`) SELECT `something_id`, `user_id`, `other` FROM `some_table` WHERE ((`d` = ?) OR (`e` = 'wat')) AND (`a` IN (1,2,3)) ORDER BY `id` DESC LIMIT 0,20", "INSERT INTO `tableA` (`a`,`b`,`c`) SELECT `something_id`, `user_id`, `other` FROM `some_table` WHERE ((`d` = 4444) OR (`e` = 'wat')) AND (`a` IN (1,2,3)) ORDER BY `id` DESC LIMIT 0,20", int64(4444), ) assert.Exactly(t, []string{"d"}, ins.qualifiedColumns) }) t.Run("Two placeholders", func(t *testing.T) { ins := NewInsert("tableA").AddColumns("a", "b") compareToSQL(t, ins.FromSelect(NewSelect("something_id", "user_id"). From("some_table"). Where( Column("d").PlaceHolder(), Column("a").In().Int64s(1, 2, 3), Column("e").PlaceHolder(), ), ).WithDBR(dbMock{}).TestWithArgs("Guys!", 4444), errors.NoKind, "INSERT INTO `tableA` (`a`,`b`) SELECT `something_id`, `user_id` FROM `some_table` WHERE (`d` = ?) AND (`a` IN (1,2,3)) AND (`e` = ?)", "INSERT INTO `tableA` (`a`,`b`) SELECT `something_id`, `user_id` FROM `some_table` WHERE (`d` = 'Guys!') AND (`a` IN (1,2,3)) AND (`e` = 4444)", "Guys!", int64(4444), ) assert.Exactly(t, []string{"d", "e"}, ins.qualifiedColumns) }) t.Run("Record Simple,no select", func(t *testing.T) { p := &dmlPerson{ Name: "Pike", Email: null.MakeString("<EMAIL>"), } ins := NewInsert("dml_people").AddColumns("name", "email"). WithDBR(dbMock{}).TestWithArgs(Qualify("", p)) compareToSQL(t, ins, errors.NoKind, "INSERT INTO `dml_people` (`name`,`email`) VALUES (?,?)", "INSERT INTO `dml_people` (`name`,`email`) VALUES ('Pike','<EMAIL>')", "Pike", "<EMAIL>", ) }) t.Run("Record Complex", func(t *testing.T) { p := &dmlPerson{ ID: 20180128, Name: "<NAME>", Email: null.MakeString("<EMAIL>"), } p2 := &dmlPerson{ Dob: 1970, } sel := NewSelect("a", "b"). FromAlias("dml_person", "dp"). Join(MakeIdentifier("dml_group").Alias("dg"), Column("dp.id").PlaceHolder()). Where( Column("dg.dob").Greater().PlaceHolder(), Column("age").Less().Int(56), Column("size").Greater().NamedArg("xSize"), ParenthesisOpen(), Column("dp.name").PlaceHolder(), Column("e").Str("wat").Or(), ParenthesisClose(), Column("fPlaceholder").LessOrEqual().PlaceHolder(), Column("g").Greater().Int(3), Column("h").In().Int64s(4, 5, 6), ). GroupBy("ab"). Having( Column("dp.email").PlaceHolder(), Column("n").Str("wh3r3"), ). OrderBy("l") ins := NewInsert("tableA").AddColumns("a", "b").FromSelect(sel).WithDBR(dbMock{}) compareToSQL(t, ins.TestWithArgs(Qualify("dp", p), Qualify("dg", p2), sql.Named("xSize", 678) /*fPlaceholder*/, 3.14159), errors.NoKind, "INSERT INTO `tableA` (`a`,`b`) SELECT `a`, `b` FROM `dml_person` AS `dp` INNER JOIN `dml_group` AS `dg` ON (`dp`.`id` = ?) WHERE (`dg`.`dob` > ?) AND (`age` < 56) AND (`size` > ?) AND ((`dp`.`name` = ?) OR (`e` = 'wat')) AND (`fPlaceholder` <= ?) AND (`g` > 3) AND (`h` IN (4,5,6)) GROUP BY `ab` HAVING (`dp`.`email` = ?) AND (`n` = 'wh3r3') ORDER BY `l`", "INSERT INTO `tableA` (`a`,`b`) SELECT `a`, `b` FROM `dml_person` AS `dp` INNER JOIN `dml_group` AS `dg` ON (`dp`.`id` = 20180128) WHERE (`dg`.`dob` > 1970) AND (`age` < 56) AND (`size` > 678) AND ((`dp`.`name` = '<NAME>') OR (`e` = 'wat')) AND (`fPlaceholder` <= 3.14159) AND (`g` > 3) AND (`h` IN (4,5,6)) GROUP BY `ab` HAVING (`dp`.`email` = '<EMAIL>') AND (`n` = 'wh3r3') ORDER BY `l`", int64(20180128), int64(1970), int64(678), "<NAME>", 3.14159, "<EMAIL>", ) }) } func TestInsert_Replace_Ignore(t *testing.T) { // this generated statement does not comply the SQL standard compareToSQL(t, NewInsert("a"). Replace().Ignore(). AddColumns("b", "c"). WithDBR(dbMock{}).TestWithArgs(1, 2, 3, 4), errors.NoKind, "REPLACE IGNORE INTO `a` (`b`,`c`) VALUES (?,?),(?,?)", "REPLACE IGNORE INTO `a` (`b`,`c`) VALUES (1,2),(3,4)", int64(1), int64(2), int64(3), int64(4), ) } func TestInsert_WithoutColumns(t *testing.T) { t.Run("each column in its own Arg", func(t *testing.T) { compareToSQL(t, NewInsert("catalog_product_link").SetRowCount(3). WithDBR(dbMock{}).TestWithArgs(2046, 33, 3, 2046, 34, 3, 2046, 35, 3), errors.NoKind, "INSERT INTO `catalog_product_link` VALUES (?,?,?),(?,?,?),(?,?,?)", "INSERT INTO `catalog_product_link` VALUES (2046,33,3),(2046,34,3),(2046,35,3)", int64(2046), int64(33), int64(3), int64(2046), int64(34), int64(3), int64(2046), int64(35), int64(3), ) }) } func TestInsert_sqlNamedArg(t *testing.T) { t.Run("one row", func(t *testing.T) { compareToSQL(t, NewInsert("catalog_product_link").AddColumns("product_id", "linked_product_id", "link_type_id"). WithDBR(dbMock{}).TestWithArgs([]sql.NamedArg{ {Name: "product_id", Value: 2046}, {Name: "linked_product_id", Value: 33}, {Name: "link_type_id", Value: 3}, }), errors.NoKind, "INSERT INTO `catalog_product_link` (`product_id`,`linked_product_id`,`link_type_id`) VALUES (?,?,?)", "INSERT INTO `catalog_product_link` (`product_id`,`linked_product_id`,`link_type_id`) VALUES (2046,33,3)", int64(2046), int64(33), int64(3), ) }) // TODO implement expression handling, requires some refactorings // t.Run("expression no args", func(t *testing.T) { // compareToSQL(t, NewInsert("catalog_product_link"). // WithPairs( // Column("product_id").Int64(2046), // Column("type_name").Expression("CONCAT(`product_id`,'Manufacturer')"), // Column("link_type_id").Int64(3), // ), // errors.NoKind, // "INSERT INTO `catalog_product_link` (`product_id`,`linked_product_id`,`link_type_id`) VALUES (?,CONCAT(`product_id`,'Manufacturer'),?)", // "INSERT INTO `catalog_product_link` (`product_id`,`linked_product_id`,`link_type_id`) VALUES (2046,CONCAT(`product_id`,'Manufacturer'),3)", // int64(2046), int64(33), int64(3), // ) //}) t.Run("multiple rows triggers NO error", func(t *testing.T) { compareToSQL(t, NewInsert("catalog_product_link").AddColumns("product_id", "linked_product_id", "link_type_id"). WithDBR(dbMock{}).TestWithArgs([]sql.NamedArg{ {Name: "product_id", Value: 2046}, {Name: "linked_product_id", Value: 33}, {Name: "link_type_id", Value: 3}, {Name: "product_id", Value: 2046}, {Name: "linked_product_id", Value: 34}, {Name: "link_type_id", Value: 3}, }), errors.NoKind, "INSERT INTO `catalog_product_link` (`product_id`,`linked_product_id`,`link_type_id`) VALUES (?,?,?),(?,?,?)", "INSERT INTO `catalog_product_link` (`product_id`,`linked_product_id`,`link_type_id`) VALUES (2046,33,3),(2046,34,3)", int64(2046), int64(33), int64(3), int64(2046), int64(34), int64(3), ) }) } func TestInsert_DisableBuildCache(t *testing.T) { insA := NewInsert("a").AddColumns("b", "c"). OnDuplicateKey().WithDBR(dbMock{}) const cachedSQLPlaceHolder = "INSERT INTO `a` (`b`,`c`) VALUES (?,?),(?,?),(?,?) ON DUPLICATE KEY UPDATE `b`=VALUES(`b`), `c`=VALUES(`c`)" t.Run("without interpolate", func(t *testing.T) { for i := 0; i < 3; i++ { sql, args, err := insA.TestWithArgs(1, 2, 3, 4, 5, 6).ToSQL() assert.NoError(t, err) assert.Exactly(t, cachedSQLPlaceHolder, sql) assert.Exactly(t, []interface{}{int64(1), int64(2), int64(3), int64(4), int64(5), int64(6)}, args) insA.Reset() } }) t.Run("with interpolate", func(t *testing.T) { insA := insA.Reset().Interpolate() qb := insA.testWithArgs(1, 2, 3, 4, 5, 6) const cachedSQLInterpolated = "INSERT INTO `a` (`b`,`c`) VALUES (1,2),(3,4),(5,6) ON DUPLICATE KEY UPDATE `b`=VALUES(`b`), `c`=VALUES(`c`)" for i := 0; i < 3; i++ { sql, args, err := qb.ToSQL() assert.NoError(t, err) assert.Exactly(t, cachedSQLInterpolated, sql) assert.Nil(t, args) } }) } func TestInsert_AddArguments(t *testing.T) { t.Run("single WithDBR", func(t *testing.T) { compareToSQL(t, NewInsert("a").AddColumns("b", "c").WithDBR(dbMock{}).TestWithArgs(1, 2), errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES (?,?)", "INSERT INTO `a` (`b`,`c`) VALUES (1,2)", int64(1), int64(2), ) }) t.Run("multi WithDBR on duplicate key", func(t *testing.T) { compareToSQL(t, NewInsert("a").AddColumns("b", "c"). OnDuplicateKey(). WithDBR(dbMock{}).TestWithArgs(1, 2, 3, 4, 5, 6), errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES (?,?),(?,?),(?,?) ON DUPLICATE KEY UPDATE `b`=VALUES(`b`), `c`=VALUES(`c`)", "INSERT INTO `a` (`b`,`c`) VALUES (1,2),(3,4),(5,6) ON DUPLICATE KEY UPDATE `b`=VALUES(`b`), `c`=VALUES(`c`)", int64(1), int64(2), int64(3), int64(4), int64(5), int64(6), ) }) t.Run("single AddValues", func(t *testing.T) { compareToSQL(t, NewInsert("a").AddColumns("b", "c").WithDBR(dbMock{}).TestWithArgs(1, 2), errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES (?,?)", "INSERT INTO `a` (`b`,`c`) VALUES (1,2)", int64(1), int64(2), ) }) t.Run("multi AddValues on duplicate key", func(t *testing.T) { compareToSQL(t, NewInsert("a").AddColumns("b", "c"). OnDuplicateKey().WithDBR(dbMock{}).TestWithArgs(1, 2, 3, 4, 5, 6), errors.NoKind, "INSERT INTO `a` (`b`,`c`) VALUES (?,?),(?,?),(?,?) ON DUPLICATE KEY UPDATE `b`=VALUES(`b`), `c`=VALUES(`c`)", "INSERT INTO `a` (`b`,`c`) VALUES (1,2),(3,4),(5,6) ON DUPLICATE KEY UPDATE `b`=VALUES(`b`), `c`=VALUES(`c`)", int64(1), int64(2), int64(3), int64(4), int64(5), int64(6), ) }) } func TestInsert_OnDuplicateKey(t *testing.T) { t.Run("Exclude only", func(t *testing.T) { compareToSQL(t, NewInsert("customer_gr1d_flat"). AddColumns("entity_id", "name", "email", "group_id", "created_at", "website_id"). AddOnDuplicateKeyExclude("entity_id"). WithDBR(dbMock{}).TestWithArgs(1, "Martin", "<EMAIL>", 3, "2019-01-01", 2), errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `created_at`=VALUES(`created_at`), `website_id`=VALUES(`website_id`)", "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (1,'Martin','<EMAIL>',3,'2019-01-01',2) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `created_at`=VALUES(`created_at`), `website_id`=VALUES(`website_id`)", int64(1), "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), ) }) t.Run("Exclude plus custom field value", func(t *testing.T) { compareToSQL(t, NewInsert("customer_gr1d_flat"). AddColumns("entity_id", "name", "email", "group_id", "created_at", "website_id"). AddOnDuplicateKeyExclude("entity_id"). AddOnDuplicateKey(Column("created_at").Time(now())). WithDBR(dbMock{}).TestWithArgs(1, "Martin", "<EMAIL>", 3, "2019-01-01", 2), errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`='2006-01-02 15:04:05'", "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (1,'Martin','<EMAIL>',3,'2019-01-01',2) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`='2006-01-02 15:04:05'", int64(1), "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), ) }) t.Run("Exclude plus default place holder, DBR", func(t *testing.T) { ins := NewInsert("customer_gr1d_flat"). AddColumns("entity_id", "name", "email", "group_id", "created_at", "website_id"). AddOnDuplicateKeyExclude("entity_id"). AddOnDuplicateKey(Column("created_at").PlaceHolder()) insA := ins.WithDBR(dbMock{}).TestWithArgs( 1, "Martin", "<EMAIL>", 3, "2019-01-01", 2, sql.Named("time", now()), ) compareToSQL(t, insA, errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`=?", "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (1,'Martin','<EMAIL>',3,'2019-01-01',2) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`='2006-01-02 15:04:05'", int64(1), "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), now(), ) assert.Exactly(t, []string{"entity_id", "name", "email", "group_id", "created_at", "website_id", "created_at"}, ins.qualifiedColumns) }) t.Run("Exclude plus default place holder, iface", func(t *testing.T) { ins := NewInsert("customer_gr1d_flat"). AddColumns("entity_id", "name", "email", "group_id", "created_at", "website_id"). AddOnDuplicateKeyExclude("entity_id"). AddOnDuplicateKey(Column("created_at").PlaceHolder()) insA := ins.WithDBR(dbMock{}) compareToSQL2(t, insA.TestWithArgs(1, "Martin", "<EMAIL>", 3, "2019-01-01", 2, now()), errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`=?", int64(1), "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), now(), ) assert.Exactly(t, []string{"entity_id", "name", "email", "group_id", "created_at", "website_id", "created_at"}, insA.cachedSQL.qualifiedColumns) }) t.Run("Exclude plus custom place holder", func(t *testing.T) { ins := NewInsert("customer_gr1d_flat"). AddColumns("entity_id", "name", "email", "group_id", "created_at", "website_id"). AddOnDuplicateKeyExclude("entity_id"). AddOnDuplicateKey(Column("created_at").NamedArg("time")). WithDBR(dbMock{}) compareToSQL(t, ins.TestWithArgs(1, "Martin", "<EMAIL>", 3, "2019-01-01", 2, sql.Named("time", now())), errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`=?", "INSERT INTO `customer_gr1d_flat` (`entity_id`,`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (1,'Martin','<EMAIL>',3,'2019-01-01',2) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `website_id`=VALUES(`website_id`), `created_at`='2006-01-02 15:04:05'", int64(1), "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), now(), ) assert.Exactly(t, []string{"entity_id", "name", "email", "group_id", "created_at", "website_id", ":time"}, ins.cachedSQL.qualifiedColumns) }) t.Run("Enabled for all columns", func(t *testing.T) { ins := NewInsert("customer_gr1d_flat"). AddColumns("name", "email", "group_id", "created_at", "website_id"). OnDuplicateKey().WithDBR(dbMock{}).TestWithArgs("Martin", "<EMAIL>", 3, "2019-01-01", 2) compareToSQL(t, ins, errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `created_at`=VALUES(`created_at`), `website_id`=VALUES(`website_id`)", "INSERT INTO `customer_gr1d_flat` (`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES ('Martin','<EMAIL>',3,'2019-01-01',2) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `created_at`=VALUES(`created_at`), `website_id`=VALUES(`website_id`)", "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), ) // testing for being idempotent compareToSQL(t, ins, errors.NoKind, "INSERT INTO `customer_gr1d_flat` (`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `created_at`=VALUES(`created_at`), `website_id`=VALUES(`website_id`)", "", //"INSERT INTO `customer_gr1d_flat` (`name`,`email`,`group_id`,`created_at`,`website_id`) VALUES ('Martin','<EMAIL>',3,'2019-01-01',2) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `email`=VALUES(`email`), `group_id`=VALUES(`group_id`), `created_at`=VALUES(`created_at`), `website_id`=VALUES(`website_id`)", "Martin", "<EMAIL>", int64(3), "2019-01-01", int64(2), ) }) } // TestInsert_Parallel_Bind_Slice is a tough test because first a complex SQL // statement from a collection and second it runs in parallel. func TestInsert_Parallel_Bind_Slice(t *testing.T) { wantArgs := []interface{}{ "<NAME>", "<EMAIL>", "<NAME>", "<EMAIL>", "<NAME>", "<EMAIL>", } persons := &dmlPersons{ Data: []*dmlPerson{ {Name: "<NAME>", Email: null.MakeString("<EMAIL>")}, {Name: "<NAME>", Email: null.MakeString("<EMAIL>")}, {Name: "<NAME>", Email: null.MakeString("<EMAIL>")}, }, } ins := NewInsert("dml_personXXX").AddColumns("name", "email"). SetRowCount(len(persons.Data)) const ( wantPH = "INSERT INTO `dml_personXXX` (`name`,`email`) VALUES (?,?),(?,?),(?,?)" wantIP = "INSERT INTO `dml_personXXX` (`name`,`email`) VALUES ('<NAME>','<EMAIL>'),('<NAME>','<EMAIL>'),('<NAME>','<EMAIL>')" ) const concurrencyLevel = 10 bgwork.Wait(concurrencyLevel, func(index int) { // Don't use such a construct in production code! // TODO try to move this above to see if it's race free. insA := ins.WithDBR(nil) compareToSQL(t, insA.TestWithArgs(Qualify("", persons)), errors.NoKind, wantPH, wantIP, wantArgs...) compareToSQL(t, insA.TestWithArgs(Qualify("", persons)), errors.NoKind, wantPH, wantIP, wantArgs...) }) } func TestInsert_Expressions_In_Values(t *testing.T) { t.Run("1 string expression one row", func(t *testing.T) { ins := NewInsert("catalog_product_customer_relation"). AddColumns("product_id", "sort_order"). WithPairs( Column("customer_id").Expr("IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0)"), ).BuildValues() compareToSQL2(t, ins, errors.NoKind, "INSERT INTO `catalog_product_customer_relation` (`product_id`,`sort_order`,`customer_id`) VALUES (?,?,IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0))", ) }) // TODO Not yet supported. some calculations necessary in Insert.toSQL // t.Run("2 string expression multiple rows", func(t *testing.T) { // ins := NewInsert("catalog_product_customer_relation"). // AddColumns("product_id", "sort_order"). // WithPairs( // Column("customer_id").Expr("IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0)"), // Column("customer_id").Expr("IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0)"), // ).BuildValues() // // compareToSQL2(t, ins, errors.NoKind, // "INSERT INTO `catalog_product_customer_relation` (`product_id`,`sort_order`,`customer_id`) VALUES (?,?,IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0)),(?,?,IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0))", // ) //}) t.Run("sub select", func(t *testing.T) { // do not use such a construct like the test query. use such a construct: /* INSERT INTO catalog_product_customer_relation (product_id, sort_order, group_id) SELECT ? AS product_id, ? AS sort_order, group_id FROM customer_group WHERE name = ?; */ ins := NewInsert("catalog_product_customer_relation"). AddColumns("product_id", "sort_order"). WithPairs( Column("group_id").Sub( NewSelect("group_id").From("customer_group").Where( Column("name").Equal().PlaceHolder(), ), ), ).BuildValues() compareToSQL(t, ins, errors.NoKind, "INSERT INTO `catalog_product_customer_relation` (`product_id`,`sort_order`,`group_id`) VALUES (?,?,(SELECT `group_id` FROM `customer_group` WHERE (`name` = ?)))", "", ) }) t.Run("all possibilities", func(t *testing.T) { ins := NewInsert("catalog_product_customer_relation"). AddColumns("product_id", "sort_order"). WithPairs( Column("customer_id").Expr("IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0)"), Column("group_id").Sub( NewSelect("group_id").From("customer_group").Where( Column("name").Equal().PlaceHolder(), ), ), ).BuildValues() compareToSQL(t, ins, errors.NoKind, "INSERT INTO `catalog_product_customer_relation` (`product_id`,`sort_order`,`customer_id`,`group_id`) VALUES (?,?,IFNULL(SELECT entity_id FROM customer_entity WHERE email like ?,0),(SELECT `group_id` FROM `customer_group` WHERE (`name` = ?)))", "", ) }) } <|start_filename|>sql/ddl/columns.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ddl import ( "bytes" "context" "database/sql" "fmt" "strings" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/bufferpool" "github.com/corestoreio/pkg/util/slices" ) // Helper constants to detect certain features of a table and or column. const ( columnPrimary = "PRI" columnUnique = "UNI" columnNull = "YES" columnAutoIncrement = "auto_increment" columnUnsigned = "unsigned" columnCurrentTimestamp = "CURRENT_TIMESTAMP" ) // Columns contains a slice of column types type Columns []*Column // Column contains information about one database table column retrieved from // information_schema.COLUMNS type Column struct { Field string // `COLUMN_NAME` varchar(64) NOT NULL DEFAULT '', Pos uint64 // `ORDINAL_POSITION` bigint(21) unsigned NOT NULL DEFAULT '0', Default null.String // `COLUMN_DEFAULT` longtext, Null string // `IS_NULLABLE` varchar(3) NOT NULL DEFAULT '', // DataType contains the basic type of a column like smallint, int, mediumblob, // float, double, etc... but always transformed to lower case. DataType string // `DATA_TYPE` varchar(64) NOT NULL DEFAULT '', CharMaxLength null.Int64 // `CHARACTER_MAXIMUM_LENGTH` bigint(21) unsigned DEFAULT NULL, Precision null.Int64 // `NUMERIC_PRECISION` bigint(21) unsigned DEFAULT NULL, Scale null.Int64 // `NUMERIC_SCALE` bigint(21) unsigned DEFAULT NULL, // ColumnType full SQL string of the column type ColumnType string // `COLUMN_TYPE` longtext NOT NULL, // Key primary or unique or ... Key string // `COLUMN_KEY` varchar(3) NOT NULL DEFAULT '', Extra string // `EXTRA` varchar(30) NOT NULL DEFAULT '', Comment string // `COLUMN_COMMENT` varchar(1024) NOT NULL DEFAULT '', Generated string // `IS_GENERATED` varchar(6) NOT NULL DEFAULT '', MariaDB only https://mariadb.com/kb/en/library/information-schema-columns-table/ GenerationExpression null.String // `GENERATION_EXPRESSION` longtext DEFAULT NULL, MariaDB only https://mariadb.com/kb/en/library/information-schema-columns-table/ // Aliases specifies different names used for this column. Mainly used when // generating code for interface dml.ColumnMapper. For example // customer_entity.entity_id can also be sales_order.customer_id. The alias // would be just: entity_id:[]string{"customer_id"}. Aliases []string // Uniquified used when generating code to uniquify the values in a // collection when the column is not a primary or unique key. The values get // returned in its own primitive slice. Uniquified bool // StructTag used in code generation and applies a custom struct tag. StructTag string } // TODO check DB flavor: if MySQL or MariaDB, first one does not have column IS_GENERATED const ( selTablesColumnsBaseSelect = `SELECT TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, COLUMN_TYPE, COLUMN_KEY, EXTRA, COLUMN_COMMENT, IS_GENERATED, GENERATION_EXPRESSION FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE()` // DMLLoadColumns specifies the data manipulation language for retrieving // all columns in the current database for a specific table. TABLE_NAME is // always lower case. selTablesColumns = selTablesColumnsBaseSelect + ` AND TABLE_NAME IN ? ORDER BY TABLE_NAME, ORDINAL_POSITION` selAllTablesColumns = selTablesColumnsBaseSelect + ` ORDER BY TABLE_NAME, ORDINAL_POSITION` ) // LoadColumns returns all columns from a list of table names in the current // database. Map key contains the table name. Returns a NotFound error if the // table is not available. All columns from all tables gets selected when you // don't provide the argument `tables`. func LoadColumns(ctx context.Context, db dml.Querier, tables ...string) (map[string]Columns, error) { var rows *sql.Rows if len(tables) == 0 { var err error rows, err = db.QueryContext(ctx, selAllTablesColumns) if err != nil { return nil, errors.Wrapf(err, "[ddl] LoadColumns QueryContext for tables %v", tables) } } else { sqlStr, _, err := dml.Interpolate(selTablesColumns).Strs(tables...).ToSQL() if err != nil { return nil, errors.Wrapf(err, "[ddl] LoadColumns dml.ExpandPlaceHolders for tables %v", tables) } rows, err = db.QueryContext(ctx, sqlStr) if err != nil { return nil, errors.Wrapf(err, "[ddl] LoadColumns QueryContext for tables %v with WHERE clause", tables) } } var err error defer func() { // Not testable with the sqlmock package :-( if err2 := rows.Close(); err2 != nil && err == nil { err = errors.WithStack(err2) } }() tc := make(map[string]Columns) rc := new(dml.ColumnMap) for rows.Next() { if err = rc.Scan(rows); err != nil { return nil, errors.Wrapf(err, "[ddl] Scan Query for tables: %v", tables) } var c *Column var tableName string c, tableName, err = newColumn(rc) if err != nil { return nil, errors.WithStack(err) } if _, ok := tc[tableName]; !ok { tc[tableName] = make(Columns, 0, 10) } c.DataType = strings.ToLower(c.DataType) tc[tableName] = append(tc[tableName], c) } if err = rows.Err(); err != nil { return nil, errors.WithStack(err) } if len(tc) == 0 { return nil, errors.NotFound.Newf("[ddl] Tables %v not found", tables) } return tc, err } // Filter filters the columns by predicate f and appends the column pointers to // the optional argument `cols`. func (cs Columns) Filter(f func(*Column) bool, cols ...*Column) Columns { for _, c := range cs { if f(c) { cols = append(cols, c) } } return cols } // Each applies function f to all elements. func (cs Columns) Each(f func(*Column)) Columns { for _, c := range cs { f(c) } return cs } // FieldNames returns all column names and appends it to `fn`, if provided. func (cs Columns) FieldNames(fn ...string) []string { if fn == nil { fn = make([]string, 0, len(cs)) } for _, c := range cs { if c.Field != "" { fn = append(fn, c.Field) } } return fn } func colIsPK(c *Column) bool { return c.IsPK() && !c.IsSystemVersioned() } // colIsPKView use the field name to guess if that might be a primary key. must be improved. func colIsPKView(c *Column) bool { return (c.Field == "id" || strings.HasSuffix(c.Field, "_id")) && !c.IsSystemVersioned() } func colIsUnique(c *Column) bool { return c.IsUnique() && !c.IsSystemVersioned() } func colIsNotSysVers(c *Column) bool { return !c.IsSystemVersioned() } // columnsIsEligibleForUpsert filters out all current-timestamp, virtual, system versioned // and auto_increment columns for update or insert operations. func columnsIsEligibleForUpsert(c *Column) bool { var d, e string // d = default; e = extra var hasCTd, hasCTe bool // CT = current time if c.Default.Valid { d = strings.ToLower(c.Default.Data) hasCTd = strings.Contains(d, "current_timestamp") } if c.Extra != "" { e = strings.ToLower(c.Extra) hasCTe = strings.Contains(e, "current_timestamp") } return !c.IsGenerated() && !c.IsSystemVersioned() && e != "auto_increment" && !hasCTd && !hasCTe } // PrimaryKeys returns all primary key columns. It may append the columns to the // provided argument slice. func (cs Columns) PrimaryKeys(cols ...*Column) Columns { return cs.Filter(colIsPK, cols...) } // ViewPrimaryKeys is a special function for views which might be able to figure // out the primary key columns. Neither MySQL nor MariaDB do not report which // columns are primary keys in a view. Current implementation checks if a column // name ends with `_id` or is `id` to consider it as a primary key. func (cs Columns) ViewPrimaryKeys(cols ...*Column) Columns { return cs.Filter(colIsPKView, cols...) } // UniqueKeys returns all unique key columns. It may append the columns to the // provided argument slice. func (cs Columns) UniqueKeys(cols ...*Column) Columns { return cs.Filter(colIsUnique, cols...) } // UniqueColumns returns all columns which are either a single primary key or a // single unique key. If a PK or UK consists of more than one column, then they // won't be included in the returned Columns slice. The result might be appended // to argument `cols`, if provided. func (cs Columns) UniqueColumns(cols ...*Column) Columns { if cols == nil { cols = make(Columns, 0, 3) // 3 is just a guess } pkCount, ukCount := 0, 0 for _, c := range cs { if c.IsPK() { pkCount++ } if c.IsUnique() { ukCount++ } } if pkCount >= 1 { cols = cs.PrimaryKeys(cols...) } if ukCount >= 1 { cols = cs.UniqueKeys(cols...) } return cols } func colIsNotPK(c *Column) bool { return !c.IsPK() && !c.IsUnique() && c.GenerationExpression.Data == "" } // NonPrimaryColumns returns all non primary key and non-unique key columns. func (cs Columns) NonPrimaryColumns() Columns { return cs.Filter(colIsNotPK) } // Len returns the length func (cs Columns) Len() int { return len(cs) } // Less compares via the Pos field. func (cs Columns) Less(i, j int) bool { return cs[i].Pos < cs[j].Pos } // Swap changes the position func (cs Columns) Swap(i, j int) { cs[i], cs[j] = cs[j], cs[i] } // Contains returns true if fieldName is contained in slice Columns. func (cs Columns) Contains(fieldName string) bool { for _, c := range cs { if c.Field == fieldName { return true } } return false } func colIsNotUniquified(c *Column) bool { return c.Uniquified && c.GenerationExpression.Data == "" } // UniquifiedColumns returns all columns which have the flag Uniquified set to // true. The result might be appended to argument `cols`, if provided. func (cs Columns) UniquifiedColumns(cols ...*Column) Columns { return cs.Filter(colIsNotUniquified, cols...) } // ByField finds a column by its field name. Case sensitive. Guaranteed to // return a non-nil return value. func (cs Columns) ByField(fieldName string) *Column { for _, c := range cs { if c.Field == fieldName { return c } } return new(Column) } // @todo add maybe more ByNull(), ByType(), ByKey(), ByDefault(), ByExtra() // String same as GoString() func (cs Columns) String() string { return cs.GoString() } // GoString returns the Go types representation. See interface fmt.GoStringer func (cs Columns) GoString() string { // fix tests if you change this layout of the returned string var buf bytes.Buffer _, _ = buf.WriteString("ddl.Columns{\n") for _, c := range cs { _, _ = fmt.Fprintf(&buf, "%#v,\n", c) } _ = buf.WriteByte('}') return buf.String() } // First returns the first column from the slice. Guaranteed to a non-nil return // value. func (cs Columns) First() *Column { if len(cs) > 0 { return cs[0] } return new(Column) } // JoinFields joins the field names into a string, separated by the provided // separator. func (cs Columns) JoinFields(sep string) string { buf := bufferpool.Get() defer bufferpool.Put(buf) i := 0 for _, c := range cs { if c.Field != "" { if i > 0 { buf.WriteString(sep) } buf.WriteString(c.Field) i++ } } return buf.String() } // newColumn creates a new column pointer and maps it from a raw database row // its bytes into the type Column. func newColumn(rc *dml.ColumnMap) (c *Column, tableName string, err error) { c = new(Column) for rc.Next(15) { switch col := rc.Column(); col { case "TABLE_NAME", "0": rc.String(&tableName) case "COLUMN_NAME", "1": rc.String(&c.Field) case "ORDINAL_POSITION", "2": rc.Uint64(&c.Pos) case "COLUMN_DEFAULT", "3": rc.NullString(&c.Default) case "IS_NULLABLE", "4": rc.String(&c.Null) case "DATA_TYPE", "5": rc.String(&c.DataType) case "CHARACTER_MAXIMUM_LENGTH", "6": rc.NullInt64(&c.CharMaxLength) case "NUMERIC_PRECISION", "7": rc.NullInt64(&c.Precision) case "NUMERIC_SCALE", "8": rc.NullInt64(&c.Scale) case "COLUMN_TYPE", "9": rc.String(&c.ColumnType) case "COLUMN_KEY", "10": rc.String(&c.Key) case "EXTRA", "11": rc.String(&c.Extra) case "COLUMN_COMMENT", "12": rc.String(&c.Comment) case "IS_GENERATED", "13": rc.String(&c.Generated) case "GENERATION_EXPRESSION", "14": rc.NullString(&c.GenerationExpression) case "aliases": // TODO the query must be extendable for all three columns to attach any table from any DB. if aliases := ""; rc.Mode() == dml.ColumnMapScan { rc.String(&aliases) c.Aliases = strings.Split(aliases, ",") } else { aliases = strings.Join(c.Aliases, ",") rc.String(&aliases) } case "uniquified": rc.Bool(&c.Uniquified) case "struct_tag": rc.String(&c.StructTag) default: return nil, "", errors.NotSupported.Newf("[ddl] Column %q not supported or alias not found", col) } } return c, tableName, errors.WithStack(rc.Err()) } // GoComment creates a comment from a database column to be used in Go code func (c *Column) GoComment() string { sqlNull := "NOT NULL" if c.IsNull() { sqlNull = "NULL" } sqlDefault := "" if c.Default.Valid { sqlDefault = "DEFAULT '" + c.Default.Data + "'" } return fmt.Sprintf("// %s %s %s %s %s %s %q", c.Field, c.ColumnType, sqlNull, c.Key, sqlDefault, c.Extra, c.Comment, ) } // GoString returns the Go types representation. See interface fmt.GoStringer func (c *Column) GoString() string { // mauybe this can be removed ... // fix tests if you change this layout of the returned string or rename columns. buf := bufferpool.Get() defer bufferpool.Put(buf) _, _ = buf.WriteString("&ddl.Column{") fmt.Fprintf(buf, "Field: %q, ", c.Field) if c.Pos > 0 { fmt.Fprintf(buf, "Pos: %d, ", c.Pos) } if c.Default.Valid { fmt.Fprintf(buf, "Default: null.MakeString(%q), ", c.Default.Data) } if c.Null != "" { fmt.Fprintf(buf, "Null: %q, ", c.Null) } if c.DataType != "" { fmt.Fprintf(buf, "DataType: %q, ", c.DataType) } if c.CharMaxLength.Valid { fmt.Fprintf(buf, "CharMaxLength: null.MakeInt64(%d), ", c.CharMaxLength.Int64) } if c.Precision.Valid { fmt.Fprintf(buf, "Precision: null.MakeInt64(%d), ", c.Precision.Int64) } if c.Scale.Valid { fmt.Fprintf(buf, "Scale: null.MakeInt64(%d), ", c.Scale.Int64) } if c.ColumnType != "" { fmt.Fprintf(buf, "ColumnType: %q, ", c.ColumnType) } if c.Key != "" { fmt.Fprintf(buf, "Key: %q, ", c.Key) } if c.Extra != "" { fmt.Fprintf(buf, "Extra: %q, ", c.Extra) } if c.Comment != "" { fmt.Fprintf(buf, "Comment: %q, ", c.Comment) } if len(c.Aliases) > 0 { fmt.Fprintf(buf, "Aliases: %#v, ", c.Aliases) } if c.Uniquified { fmt.Fprintf(buf, "Uniquified: %t, ", c.Uniquified) } if c.StructTag != "" { fmt.Fprintf(buf, "StructTag: %q, ", c.StructTag) } if c.Generated != "" { fmt.Fprintf(buf, "Generated: %q, ", c.Generated) } if c.GenerationExpression.Valid { fmt.Fprintf(buf, "GenerationExpression: %q, ", c.GenerationExpression.Data) } _ = buf.WriteByte('}') return buf.String() } // IsNull checks if column can have null values func (c *Column) IsNull() bool { return c.Null == columnNull } // IsPK checks if column is a primary key func (c *Column) IsPK() bool { return c.Field != "" && c.Key == columnPrimary } // IsUnique checks if column is a unique key func (c *Column) IsUnique() bool { return c.Field != "" && c.Key == columnUnique } // IsAutoIncrement checks if column has an auto increment property func (c *Column) IsAutoIncrement() bool { return c.Field != "" && c.Extra == columnAutoIncrement } // IsUnsigned checks if field TypeRaw contains the word unsigned. func (c *Column) IsUnsigned() bool { return strings.Contains(c.ColumnType, columnUnsigned) } // IsCurrentTimestamp checks if the Default field is a current timestamp func (c *Column) IsCurrentTimestamp() bool { return c.Default.Data == columnCurrentTimestamp } // IsGenerated returns true if the column is a virtual generated column. func (c *Column) IsGenerated() bool { return c.Generated == "ALWAYS" || c.GenerationExpression.Valid } // IsSystemVersioned returns true if the column gets used for system versioning. // https://mariadb.com/kb/en/library/system-versioned-tables/ func (c *Column) IsSystemVersioned() bool { return c.GenerationExpression.Valid && (c.GenerationExpression.Data == "ROW START" || c.GenerationExpression.Data == "ROW END") } // IsFloat returns true if a column is of one of the types: decimal, double or // float. func (c *Column) IsFloat() bool { switch c.DataType { case "decimal", "double", "float": return true } return false } // IsTime returns true if the column is a date, datetime, time or timestamp. func (c *Column) IsTime() bool { switch c.DataType { case "date", "datetime", "time", "timestamp": return true } return false } // IsMoney checks if a column contains a MySQL decimal or float type and if the // column name has a special naming. // This function needs a lot of care ... func (c *Column) IsMoney() bool { // needs more love switch { // could us a long list of || statements but switch looks nicer :-) case columnTypes.byName.moneyEqual.Contains(c.Field): return true case columnTypes.byName.money.ContainsReverse(c.Field): return true case columnTypes.byName.moneySW.StartsWithReverse(c.Field): return true } return false } // IsBool returns true if column is of type `int` and its name starts with a // special string like: `used_`, `is_`, `has_`. func (c *Column) IsBool() (ok bool) { switch c.DataType { case "int", "tinyint", "smallint", "bigint": ok = true case "bit": return true } return ok && columnTypes.byName.bool.ContainsReverse(c.Field) } // IsChar returns true if the column can contain a string or byte values. func (c *Column) IsChar() bool { return c.CharMaxLength.Valid && c.CharMaxLength.Int64 > 0 } // IsBlobDataType returns true if the columns data type is neither blob, // text, binary nor json. It doesn't matter if tiny, long or small has been // prefixed. func (c *Column) IsBlobDataType() bool { dt := strings.ToLower(c.DataType) return strings.Contains(dt, "blob") || strings.Contains(dt, "text") || strings.Contains(dt, "binary") || strings.Contains(dt, "json") } // HasEqualType returns true if the type matches and nullable. func (c *Column) HasEqualType(c2 *Column) bool { return c != nil && c2 != nil && c.ColumnType != "" && c.ColumnType == c2.ColumnType && c.Null == c2.Null } // columnTypes looks ugly but ... refactor later. // the slices in this struct are only for reading. no mutex protection required. // which partial column name triggers a specific type in Go or MySQL. var columnTypes = struct { byName struct { bool slices.String money slices.String moneySW slices.String moneyEqual slices.String } }{ struct { bool slices.String // contains money slices.String // contains moneySW slices.String // sw == starts with moneyEqual slices.String }{ slices.String{"used_", "is_", "has_", "increment_per_store"}, slices.String{"price", "_tax", "tax_", "_amount", "amount_", "total", "adjustment", "discount"}, slices.String{"base_", "grand_"}, slices.String{"value", "price", "cost", "msrp"}, }, } <|start_filename|>sql/dml/with.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "github.com/corestoreio/errors" ) // WithCTE defines a common table expression used in the type `With`. type WithCTE struct { Name string // Columns, optionally, the number of names in the list must be the same as // the number of columns in the result set. Columns []string // Select clause as a common table expression. Has precedence over the Union field. Select *Select // Union clause as a common table expression. Select field pointer must be // nil to trigger SQL generation of this field. Union *Union } // Clone creates a cloned object of the current one. func (cte WithCTE) Clone() WithCTE { cte.Columns = cloneStringSlice(cte.Columns) cte.Select = cte.Select.Clone() cte.Union = cte.Union.Clone() return cte } // With represents a common table expression. Common Table Expressions (CTEs) // are a standard SQL feature, and are essentially temporary named result sets. // Non-recursive CTES are basically 'query-local VIEWs'. One CTE can refer to // another. The syntax is more readable than nested FROM (SELECT ...). One can // refer to a CTE from multiple places. They are better than copy-pasting // FROM(SELECT ...) // // Common Table Expression versus Derived Table: Better readability; Can be // referenced multiple times; Can refer to other CTEs; Improved performance. // // https://dev.mysql.com/doc/refman/8.0/en/with.html // // https://mariadb.com/kb/en/mariadb/non-recursive-common-table-expressions-overview/ // // http://mysqlserverteam.com/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes/ // // http://dankleiman.com/2018/02/06/3-ways-to-level-up-your-sql-as-a-software-engineer/ // // Supported in: MySQL >=8.0.1 and MariaDb >=10.2 type With struct { BuilderBase Subclauses []WithCTE // TopLevel a union type which allows only one of the fields to be set. TopLevel struct { Select *Select Union *Union Update *Update Delete *Delete } IsRecursive bool // See Recursive() } // NewWith creates a new WITH statement with multiple common table expressions // (CTE). func NewWith(expressions ...WithCTE) *With { return &With{ Subclauses: expressions, } } // Select gets used in the top level statement. func (b *With) Select(topLevel *Select) *With { b.TopLevel.Select = topLevel return b } // Update gets used in the top level statement. func (b *With) Update(topLevel *Update) *With { b.TopLevel.Update = topLevel return b } // Delete gets used in the top level statement. func (b *With) Delete(topLevel *Delete) *With { b.TopLevel.Delete = topLevel return b } // Union gets used in the top level statement. func (b *With) Union(topLevel *Union) *With { b.TopLevel.Union = topLevel return b } // Recursive common table expressions are one having a subquery that refers to // its own name. The WITH clause must begin with WITH RECURSIVE if any CTE in // the WITH clause refers to itself. (If no CTE refers to itself, RECURSIVE is // permitted but not required.) Common applications of recursive CTEs include // series generation and traversal of hierarchical or tree-structured data. It // is simpler, when experimenting with WITH RECURSIVE, to put this at the start // of your session: `SET max_execution_time = 10000;` so that the runaway query // aborts automatically after 10 seconds, if the WHERE clause wasn’t correct. func (b *With) Recursive() *With { b.IsRecursive = true return b } // ToSQL converts the select statement into a string and returns its arguments. func (b *With) ToSQL() (string, []interface{}, error) { rawSQL, err := b.buildToSQL(b) if err != nil { return "", nil, errors.WithStack(err) } return rawSQL, nil, nil } func (b *With) toSQL(w *bytes.Buffer, placeHolders []string) (_ []string, err error) { w.WriteString("WITH ") if b.IsRecursive { w.WriteString("RECURSIVE ") } for i, sc := range b.Subclauses { Quoter.quote(w, sc.Name) if len(sc.Columns) > 0 { w.WriteRune(' ') w.WriteRune('(') for j, c := range sc.Columns { if j > 0 { w.WriteRune(',') } Quoter.quote(w, c) } w.WriteRune(')') } w.WriteString(" AS (") switch { case sc.Select != nil: placeHolders, err = sc.Select.toSQL(w, placeHolders) if err != nil { return nil, errors.WithStack(err) } case sc.Union != nil: placeHolders, err = sc.Union.toSQL(w, placeHolders) if err != nil { return nil, errors.WithStack(err) } } w.WriteRune(')') if i < len(b.Subclauses)-1 { w.WriteRune(',') } w.WriteRune('\n') } switch { case b.TopLevel.Select != nil: placeHolders, err = b.TopLevel.Select.toSQL(w, placeHolders) return placeHolders, errors.WithStack(err) case b.TopLevel.Union != nil: placeHolders, err = b.TopLevel.Union.toSQL(w, placeHolders) return placeHolders, errors.WithStack(err) case b.TopLevel.Update != nil: placeHolders, err = b.TopLevel.Update.toSQL(w, placeHolders) return placeHolders, errors.WithStack(err) case b.TopLevel.Delete != nil: placeHolders, err = b.TopLevel.Delete.toSQL(w, placeHolders) return placeHolders, errors.WithStack(err) } return nil, errors.Empty.Newf("[dml] Type With misses a top level statement") } // Clone creates a clone of the current object, leaving fields DB and Log // untouched. func (b *With) Clone() *With { if b == nil { return nil } c := *b c.BuilderBase = b.BuilderBase.Clone() if ls := len(b.Subclauses); ls > 0 { c.Subclauses = make([]WithCTE, ls) for i, s := range b.Subclauses { c.Subclauses[i] = s.Clone() } } c.TopLevel.Select = b.TopLevel.Select.Clone() c.TopLevel.Union = b.TopLevel.Union.Clone() c.TopLevel.Update = b.TopLevel.Update.Clone() c.TopLevel.Delete = b.TopLevel.Delete.Clone() return &c } <|start_filename|>sql/dml/select.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "fmt" "github.com/corestoreio/errors" ) // Select contains the clauses for a SELECT statement. Wildcard `SELECT *` // statements are not really supported. // http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful type Select struct { BuilderBase BuilderConditional // Columns represents a slice of names and its optional identifiers. Wildcard // `SELECT *` statements are not really supported: // http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful Columns ids // TODO: create a possibility of the Select type which has a half-pre-rendered // SQL statement where a developer can only modify or append WHERE clauses. // especially useful during code generation GroupBys ids Havings Conditions IsStar bool // IsStar generates a SELECT * FROM query IsCountStar bool // IsCountStar retains the column names but executes a COUNT(*) query. IsDistinct bool // See Distinct() IsStraightJoin bool // See StraightJoin() IsSQLNoCache bool // See SQLNoCache() IsForUpdate bool // See ForUpdate() IsLockInShareMode bool // See LockInShareMode() IsOrderByDeactivated bool // See OrderByDeactivated() IsOrderByRand bool // enables the original slow ORDER BY RAND() clause OffsetCount uint64 } // NewSelect creates a new Select object. func NewSelect(columns ...string) *Select { s := new(Select) if len(columns) == 1 && columns[0] == "*" { s.Star() } else { s.Columns = s.Columns.AppendColumns(false, columns...) } return s } // NewSelectWithDerivedTable creates a new derived table (Subquery in the FROM // Clause) using the provided sub-select in the FROM part together with an alias // name. Appends the arguments of the sub-select to the parent *Select pointer // arguments list. SQL result may look like: // SELECT a,b FROM (SELECT x,y FROM `product` AS `p`) AS `t` // https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html func NewSelectWithDerivedTable(subSelect *Select, aliasName string) *Select { return &Select{ BuilderBase: BuilderBase{ Table: id{ DerivedTable: subSelect, Aliased: aliasName, }, }, } } // Distinct marks the statement at a DISTINCT SELECT. It specifies removal of // duplicate rows from the result set. func (b *Select) Distinct() *Select { b.IsDistinct = true return b } // Unsafe see BuilderBase.IsUnsafe which weakens security when building the SQL // string. This function must be called before calling any other function. func (b *Select) Unsafe() *Select { b.IsUnsafe = true return b } // StraightJoin forces the optimizer to join the tables in the order in which // they are listed in the FROM clause. You can use this to speed up a query if // the optimizer joins the tables in nonoptimal order. func (b *Select) StraightJoin() *Select { b.IsStraightJoin = true return b } // SQLNoCache tells the server that it does not use the query cache. It neither // checks the query cache to see whether the result is already cached, nor does // it cache the query result. func (b *Select) SQLNoCache() *Select { b.IsSQLNoCache = true return b } // ForUpdate sets for index records the search encounters, locks the rows and // any associated index entries, the same as if you issued an UPDATE statement // for those rows. Other transactions are blocked from updating those rows, from // doing SELECT ... LOCK IN SHARE MODE, or from reading the data in certain // transaction isolation levels. Consistent reads ignore any locks set on the // records that exist in the read view. (Old versions of a record cannot be // locked; they are reconstructed by applying undo logs on an in-memory copy of // the record.) // Note: Locking of rows for update using SELECT FOR UPDATE only applies when // autocommit is disabled (either by beginning transaction with START // TRANSACTION or by setting autocommit to 0. If autocommit is enabled, the rows // matching the specification are not locked. // https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html func (b *Select) ForUpdate() *Select { b.IsForUpdate = true return b } // LockInShareMode sets a shared mode lock on any rows that are read. Other // sessions can read the rows, but cannot modify them until your transaction // commits. If any of these rows were changed by another transaction that has // not yet committed, your query waits until that transaction ends and then uses // the latest values. // https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html func (b *Select) LockInShareMode() *Select { b.IsLockInShareMode = true return b } // Count executes a COUNT(*) as `counted` query without touching or changing the // currently set columns. func (b *Select) Count() *Select { b.IsCountStar = true return b } // Star creates a SELECT * FROM query. Such queries are discouraged from using. func (b *Select) Star() *Select { b.IsStar = true return b } // From sets the table for the SELECT FROM part. func (b *Select) From(from string) *Select { b.Table = MakeIdentifier(from) return b } // FromAlias sets the table and its alias name for a `SELECT ... FROM table AS // alias` query. func (b *Select) FromAlias(from, alias string) *Select { b.Table = MakeIdentifier(from).Alias(alias) return b } // AddColumns appends more columns to the Columns slice. If a column name is not // valid identifier that column gets switched into an expression. // AddColumns("a","b") // `a`,`b` // AddColumns("a,b","z","c,d") // a,b,`z`,c,d // AddColumns("t1.name","t1.sku","price") // `t1`.`name`, `t1`.`sku`,`price` func (b *Select) AddColumns(cols ...string) *Select { b.Columns = b.Columns.AppendColumns(b.IsUnsafe, cols...) return b } // AddColumnsAliases expects a balanced slice of "Column1, Alias1, Column2, // Alias2" and adds both to the Columns slice. An imbalanced slice will cause a // panic. If a column name is not valid identifier that column gets switched // into an expression. // AddColumnsAliases("t1.name","t1Name","t1.sku","t1SKU") // `t1`.`name` AS `t1Name`, `t1`.`sku` AS `t1SKU` // AddColumnsAliases("(e.price*x.tax*t.weee)", "final_price") // error: `(e.price*x.tax*t.weee)` AS `final_price` func (b *Select) AddColumnsAliases(columnAliases ...string) *Select { b.Columns = b.Columns.AppendColumnsAliases(b.IsUnsafe, columnAliases...) return b } // AddColumnsConditions adds a condition as a column to the statement. The // operator field gets ignored. DBR in the condition gets applied to the // RawArguments field to maintain the correct order of arguments. // AddColumnsConditions(Expr("(e.price*x.tax*t.weee)").Alias("final_price")) // (e.price*x.tax*t.weee) AS `final_price` func (b *Select) AddColumnsConditions(expressions ...*Condition) *Select { b.Columns, b.ärgErr = b.Columns.appendConditions(expressions) return b } // Where appends a WHERE clause to the statement for the given string and args // or map of column/value pairs. func (b *Select) Where(wf ...*Condition) *Select { b.Wheres = append(b.Wheres, wf...) return b } // When applies the function `fn` query changes if the given "test" is true. // Providing the optional second function, uses it as the default value, if test // is false. `defaultFn` can be nil. func (b *Select) When(test bool, fn func(*Select), defaultFn func(*Select)) *Select { // TODO add this to other DML types switch { case test: fn(b) // test is true, applies callback case defaultFn != nil: defaultFn(b) // default value, if test is false } return b } // Unless applies the function `fn` query changes if the given "test" is false. // Providing the optional second function, uses it as the default value, if test // is false. `defaultFn` can be nil. func (b *Select) Unless(test bool, fn func(*Select), defaultFn func(*Select)) *Select { // TODO add this to other DML types return b.When(!test, fn, defaultFn) } // GroupBy appends columns to group the statement. A column gets always quoted // if it is a valid identifier otherwise it will be treated as an expression. // MySQL does not sort the results set. To avoid the overhead of sorting that // GROUP BY produces this function should add an ORDER BY NULL with function // `OrderByDeactivated`. func (b *Select) GroupBy(columns ...string) *Select { b.GroupBys = b.GroupBys.AppendColumns(b.IsUnsafe, columns...) return b } // GroupByAsc sorts the groups in ascending order. A column gets always quoted // if it is a valid identifier otherwise it will be treated as an expression. No // need to add an ORDER BY clause. When you use ORDER BY or GROUP BY to sort a // column in a SELECT, the server sorts values using only the initial number of // bytes indicated by the max_sort_length system variable. func (b *Select) GroupByAsc(columns ...string) *Select { b.GroupBys = b.GroupBys.AppendColumns(b.IsUnsafe, columns...).applySort(len(columns), sortAscending) return b } // GroupByDesc sorts the groups in descending order. A column gets always quoted // if it is a valid identifier otherwise it will be treated as an expression. No // need to add an ORDER BY clause. When you use ORDER BY or GROUP BY to sort a // column in a SELECT, the server sorts values using only the initial number of // bytes indicated by the max_sort_length system variable. func (b *Select) GroupByDesc(columns ...string) *Select { b.GroupBys = b.GroupBys.AppendColumns(b.IsUnsafe, columns...).applySort(len(columns), sortDescending) return b } // Having appends a HAVING clause to the statement func (b *Select) Having(wf ...*Condition) *Select { b.Havings = append(b.Havings, wf...) return b } // OrderByDeactivated deactivates ordering of the result set by applying ORDER // BY NULL to the SELECT statement. Very useful for GROUP BY queries. func (b *Select) OrderByDeactivated() *Select { b.IsOrderByDeactivated = true return b } // OrderBy appends columns to the ORDER BY statement for ascending sorting. A // column gets always quoted if it is a valid identifier otherwise it will be // treated as an expression. When you use ORDER BY or GROUP BY to sort a column // in a SELECT, the server sorts values using only the initial number of bytes // indicated by the max_sort_length system variable. // A column name can also contain the suffix words " ASC" or " DESC" to indicate // the sorting. This avoids using the method OrderByDesc when sorting certain // columns descending. func (b *Select) OrderBy(columns ...string) *Select { b.OrderBys = b.OrderBys.AppendColumns(b.IsUnsafe, columns...) return b } // OrderByDesc appends columns to the ORDER BY statement for descending sorting. // A column gets always quoted if it is a valid identifier otherwise it will be // treated as an expression. When you use ORDER BY or GROUP BY to sort a column // in a SELECT, the server sorts values using only the initial number of bytes // indicated by the max_sort_length system variable. func (b *Select) OrderByDesc(columns ...string) *Select { b.OrderBys = b.OrderBys.AppendColumns(b.IsUnsafe, columns...).applySort(len(columns), sortDescending) return b } // OrderByRandom sorts the table randomly by not using ORDER BY RAND() rather // using a JOIN with the single primary key column. This function overwrites // previously set ORDER BY statements and the field LimitCount. The generated // SQL by this function is about 3-4 times faster than ORDER BY RAND(). The // generated SQL does not work for all queries. The underlying SQL statement // might change without notice. func (b *Select) OrderByRandom(idColumnName string, limit uint64) *Select { // Source https://stackoverflow.com/a/36013954 ;-) b.OrderByRandColumnName = idColumnName b.LimitCount = limit return b } // Limit sets a limit for the statement; overrides any existing LIMIT. // Don't build a pagination with offset or you go straight to hell. func (b *Select) Limit(offset uint64, limit uint64) *Select { b.OffsetCount = offset b.LimitCount = limit b.LimitValid = true return b } // Paginate sets LIMIT/OFFSET for the statement based on the given page/perPage // Assumes page/perPage are valid. Page and perPage must be >= 1. // Deprecated see a talk from <NAME> - Modern SQL func (b *Select) Paginate(page, perPage uint64) *Select { b.Limit((page-1)*perPage, perPage) return b } // Join creates an INNER join construct. By default, the onConditions are glued // together with AND. func (b *Select) Join(table id, onConditions ...*Condition) *Select { b.join("INNER", table, onConditions...) return b } // LeftJoin creates a LEFT join construct. By default, the onConditions are // glued together with AND. func (b *Select) LeftJoin(table id, onConditions ...*Condition) *Select { b.join("LEFT", table, onConditions...) return b } // RightJoin creates a RIGHT join construct. By default, the onConditions are // glued together with AND. func (b *Select) RightJoin(table id, onConditions ...*Condition) *Select { b.join("RIGHT", table, onConditions...) return b } // OuterJoin creates an OUTER join construct. By default, the onConditions are // glued together with AND. func (b *Select) OuterJoin(table id, onConditions ...*Condition) *Select { b.join("OUTER", table, onConditions...) return b } // CrossJoin creates a CROSS join construct. By default, the onConditions are // glued together with AND. func (b *Select) CrossJoin(table id, onConditions ...*Condition) *Select { b.join("CROSS", table, onConditions...) return b } // ToSQL generates the SQL string and might caches it internally, if not // disabled. func (b *Select) ToSQL() (string, []interface{}, error) { rawSQL, err := b.buildToSQL(b) return rawSQL, nil, err } // ToSQL serialized the Select to a SQL string // It returns the string with placeholders and a slice of query arguments func (b *Select) toSQL(w *bytes.Buffer, placeHolders []string) (_placeHolders []string, err error) { if b.BuilderBase.ärgErr != nil { return nil, b.BuilderBase.ärgErr } if len(b.Columns) == 0 && !b.IsCountStar && !b.IsStar { return nil, errors.Empty.Newf("[dml] Select: no columns specified") } w.WriteString("SELECT ") if b.IsDistinct { w.WriteString("DISTINCT ") } if b.IsStraightJoin { w.WriteString("STRAIGHT_JOIN ") } if b.IsSQLNoCache { w.WriteString("SQL_NO_CACHE ") } switch { case b.IsStar: w.WriteByte('*') case b.IsCountStar: w.WriteString("COUNT(*) AS ") Quoter.quote(w, "counted") default: if placeHolders, err = b.Columns.writeQuoted(w, placeHolders); err != nil { return nil, errors.WithStack(err) } } if !b.Table.isEmpty() { w.WriteString(" FROM ") if placeHolders, err = b.Table.writeQuoted(w, placeHolders); err != nil { return nil, errors.WithStack(err) } } joins := b.Joins if b.OrderByRandColumnName != "" { // This ORDER BY RAND() statement enables a 3-4 better processing in the // server. countSel := NewSelect().AddColumnsConditions( Expr(fmt.Sprintf("((%d / COUNT(*)) * 10)", b.LimitCount)), ).From(b.Table.Name).Where(b.Wheres...) idSel := NewSelect(b.OrderByRandColumnName).From(b.Table.Name). Where(Expr("RAND()").Less().Sub(countSel)). Where(b.Wheres...). Limit(0, b.LimitCount) idSel.IsOrderByRand = true joins = append(joins, &join{ Table: id{ DerivedTable: idSel, Aliased: "rand" + b.Table.Name, }, On: Conditions{Columns(b.OrderByRandColumnName)}, }) } for _, f := range joins { w.WriteByte(' ') w.WriteString(f.JoinType) w.WriteString(" JOIN ") if placeHolders, err = f.Table.writeQuoted(w, placeHolders); err != nil { return nil, errors.WithStack(err) } if placeHolders, err = f.On.write(w, 'j', placeHolders, b.isWithDBR); err != nil { return nil, errors.WithStack(err) } } if placeHolders, err = b.Wheres.write(w, 'w', placeHolders, b.isWithDBR); err != nil { return nil, errors.WithStack(err) } if len(b.GroupBys) > 0 { w.WriteString(" GROUP BY ") for i, c := range b.GroupBys { if i > 0 { w.WriteString(", ") } if placeHolders, err = c.writeQuoted(w, placeHolders); err != nil { return nil, errors.WithStack(err) } } } if placeHolders, err = b.Havings.write(w, 'h', placeHolders, b.isWithDBR); err != nil { return nil, errors.WithStack(err) } switch { case b.IsOrderByDeactivated: w.WriteString(" ORDER BY NULL") case b.IsOrderByRand: w.WriteString(" ORDER BY RAND()") default: sqlWriteOrderBy(w, b.OrderBys, false) } sqlWriteLimitOffset(w, b.LimitValid, true, b.OffsetCount, b.LimitCount) switch { case b.IsLockInShareMode: w.WriteString(" LOCK IN SHARE MODE") case b.IsForUpdate: w.WriteString(" FOR UPDATE") } return placeHolders, err } // Clone creates a clone of the current object, leaving fields DB and Log // untouched. func (b *Select) Clone() *Select { if b == nil { return nil } c := *b c.BuilderBase = b.BuilderBase.Clone() c.BuilderConditional = b.BuilderConditional.Clone() c.Columns = b.Columns.Clone() c.GroupBys = b.GroupBys.Clone() c.Havings = b.Havings.Clone() return &c } <|start_filename|>sql/urlvalues/values_proto.go<|end_filename|> // +build csall proto package urlvalues // ProtoToValues converts a proto message to a Values type. It appends to // argument vals, which can be nil. func ProtoToValues(vals Values, pkv *ProtoKeyValues) Values { if vals == nil { vals = make(Values, len(pkv.Data)) } for _, kv := range pkv.Data { vals[kv.Key] = kv.Value } return vals } // ValuesToProto converts a Values map to a proto message. func ValuesToProto(vals Values) *ProtoKeyValues { var pkv ProtoKeyValues pkv.Data = make([]*ProtoKeyValue, 0, len(vals)) for k, v := range vals { pkv.Data = append(pkv.Data, &ProtoKeyValue{ Key: k, Value: v, }) } return &pkv } <|start_filename|>storage/objcache/service_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 objcache import ( "context" "encoding" "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/util/assert" ) func TestNewProcessor_NewError(t *testing.T) { t.Run("level1 error", func(t *testing.T) { p, err := NewService( func() (Storager, error) { return nil, errors.NotImplemented.Newf("ups") }, NewBlackHoleClient(nil), nil, ) assert.Nil(t, p) assert.True(t, errors.NotImplemented.Match(err), "Error: %s", err) }) t.Run("level2 error", func(t *testing.T) { p, err := NewService( NewBlackHoleClient(nil), func() (Storager, error) { return nil, errors.NotImplemented.Newf("ups") }, nil, ) assert.Nil(t, p) assert.True(t, errors.NotImplemented.Match(err), "Error: %s", err) }) } var ( _ encoding.TextMarshaler = (*encodingText)(nil) _ encoding.TextUnmarshaler = (*encodingText)(nil) _ encoding.BinaryUnmarshaler = (*encodingBinary)(nil) _ encoding.BinaryMarshaler = (*encodingBinary)(nil) ) type encodingText string func (e *encodingText) UnmarshalText(text []byte) error { *e = encodingText(text) return nil } func (e encodingText) MarshalText() (text []byte, err error) { return []byte(e), nil } type encodingBinary string func (e *encodingBinary) UnmarshalBinary(text []byte) error { *e = encodingBinary(text) return nil } func (e encodingBinary) MarshalBinary() (text []byte, err error) { return []byte(e), nil } func TestEncoding_Text_Binary(t *testing.T) { t.Parallel() // Not using any codec p, err := NewService(NewCacheSimpleInmemory, NewCacheSimpleInmemory, &ServiceOptions{Codec: nil}) assert.NoError(t, err) defer assert.NoError(t, p.Close()) ctx := context.TODO() t.Run("Text", func(t *testing.T) { obj := encodingText("Hello World 🎉") err := p.Set(ctx, "kt", obj, 0) assert.NoError(t, err) var obj2 encodingText err = p.Get(ctx, "kt", &obj2) assert.NoError(t, err) assert.Exactly(t, obj, obj2) assert.NotEmpty(t, obj2) }) t.Run("Binary", func(t *testing.T) { obj := encodingBinary("Hello World 🎉") err := p.Set(ctx, "kt", obj, 0) assert.NoError(t, err) var obj2 encodingBinary err = p.Get(ctx, "kt", &obj2) assert.NoError(t, err) assert.Exactly(t, obj, obj2) assert.NotEmpty(t, obj2) }) } <|start_filename|>sql/dmlgen/proto.go<|end_filename|> package dmlgen import ( "bufio" "bytes" "fmt" "go/ast" "go/build" "go/token" "io" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "github.com/alecthomas/repr" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/util/codegen" "github.com/corestoreio/pkg/util/strs" "golang.org/x/tools/go/packages" ) // ProtocOptions allows to modify the protoc CLI command. type ProtocOptions struct { WorkingDirectory string ProtoGen string // default go, options: gofast, gogo, gogofast, gogofaster and other installed proto generators ProtoPath []string // where to find other *.proto files; if empty the usual defaults apply GoOutPath string // where to write the generated proto files; default "." GoOpt []string // each entry generates a "--go_opt" argument // GoSourceRelative if the paths=source_relative flag is specified, the output // file is placed in the same relative directory as the input file. For // example, an input file protos/buzz.proto results in an output file at // protos/buzz.pb.go. GoSourceRelative bool GRPC bool GRPCOpt []string // each entry generates a "--go-grpc_opt" argument GRPCGatewayOutMap []string // GRPC must be enabled in the above field GRPCGatewayOutPath string // GRPC must be enabled in the above field SwaggerOutPath string CustomArgs []string // TODO add validation plugin, either // https://github.com/mwitkow/go-proto-validators as used in github.com/go_go/grpc-example/proto/example.proto // This github.com/mwitkow/go-proto-validators seems dead. // or https://github.com/envoyproxy/protoc-gen-validate // Requirement: error messages must be translatable and maybe use an errors.Kind type } var defaultProtoPaths = make([]string, 0, 8) func init() { preDefinedPaths := [...]string{ build.Default.GOPATH + "/src/", "vendor/github.com/grpc-ecosystem/grpc-gateway/", "vendor/", ".", } for _, pdp := range preDefinedPaths { if _, err := os.Stat(pdp); !os.IsNotExist(err) { defaultProtoPaths = append(defaultProtoPaths, pdp) } } } func (po *ProtocOptions) toArgs() []string { if po.GRPC { if po.GRPCGatewayOutMap == nil { po.GRPCGatewayOutMap = []string{ "allow_patch_feature=false", } } if po.GRPCGatewayOutPath == "" { po.GRPCGatewayOutPath = "." } } if po.GoOutPath == "" { po.GoOutPath = "." } else { if err := os.MkdirAll(filepath.Clean(po.GoOutPath), 0751); err != nil { panic(err) } } if po.ProtoPath == nil { po.ProtoPath = append(po.ProtoPath, defaultProtoPaths...) } if po.ProtoGen == "" { po.ProtoGen = "go" } args := []string{ "--" + po.ProtoGen + "_out=" + po.GoOutPath, "--proto_path", strings.Join(po.ProtoPath, ":"), } if po.GoSourceRelative { args = append(args, "--go_opt=paths=source_relative") } for _, o := range po.GoOpt { args = append(args, "--go_opt="+o) } if po.GRPC { args = append(args, "--go-grpc_out="+po.GoOutPath) if po.GoSourceRelative { args = append(args, "--go-grpc_opt=paths=source_relative") } for _, o := range po.GRPCOpt { args = append(args, "--go-grpc_opt="+o) } } if po.GRPC && len(po.GRPCGatewayOutMap) > 0 { args = append(args, "--grpc-gateway_out="+strings.Join(po.GRPCGatewayOutMap, ",")+":"+po.GRPCGatewayOutPath) } if po.SwaggerOutPath != "" { args = append(args, "--swagger_out="+po.SwaggerOutPath) } return append(args, po.CustomArgs...) } func (po *ProtocOptions) chdir() (deferred func(), _ error) { deferred = func() {} if po.WorkingDirectory != "" { oldWD, err := os.Getwd() if err != nil { return nil, errors.WithStack(err) } if err := os.Chdir(po.WorkingDirectory); err != nil { return nil, errors.Wrapf(err, "[dmlgen] Failed to chdir to %q", po.WorkingDirectory) } deferred = func() { _ = os.Chdir(oldWD) } } return deferred, nil } // RunProtoc searches all *.proto files in the given path and calls protoc // to generate the Go source code. func RunProtoc(protoFilesPath string, po *ProtocOptions) error { restoreFn, err := po.chdir() if err != nil { return errors.WithStack(err) } defer restoreFn() protoFilesPath = filepath.Clean(protoFilesPath) if ps := string(os.PathSeparator); !strings.HasSuffix(protoFilesPath, ps) { protoFilesPath += ps } protoFiles, err := filepath.Glob(protoFilesPath + "*.proto") if err != nil { return errors.Wrapf(err, "[dmlgen] Can't access proto files in path %q", protoFilesPath) } cmd := exec.Command("protoc", append(po.toArgs(), protoFiles...)...) cmdStr := fmt.Sprintf("\ncd %s && %s\n\n", po.WorkingDirectory, cmd) if isDebug() { if po.WorkingDirectory == "" { po.WorkingDirectory = "." } print(cmdStr) } out, err := cmd.CombinedOutput() if err != nil { return errors.Wrapf(err, "[dmlgen] %s%s", out, cmdStr) } scanner := bufio.NewScanner(bytes.NewReader(out)) for scanner.Scan() { text := scanner.Text() if !strings.Contains(text, "WARNING") { return errors.WriteFailed.Newf("[dmlgen] protoc Error: %s", text) } } // what a hack: find all *.pb.go files and remove `import null // "github.com/corestoreio/pkg/storage/null"` because no other way to get // rid of the unused import or reference that import somehow in the // generated file :-( Once there's a better solution, remove this code. pbGoFiles, err := filepath.Glob(protoFilesPath + "*.pb.*go") if err != nil { return errors.Wrapf(err, "[dmlgen] Can't access pb.go files in path %q", protoFilesPath) } removeImports := [][]byte{ []byte("import null \"github.com/corestoreio/pkg/storage/null\"\n"), []byte("null \"github.com/corestoreio/pkg/storage/null\"\n"), } for _, file := range pbGoFiles { fContent, err := ioutil.ReadFile(file) if err != nil { return errors.WithStack(err) } for _, ri := range removeImports { fContent = bytes.Replace(fContent, ri, nil, -1) } if err := ioutil.WriteFile(file, fContent, 0o644); err != nil { return errors.WithStack(err) } } // build a mapper between DB and proto :-( return nil } // GenerateSerializer writes the protocol buffer specifications into `w` and its test // sources into wTest, if there are any tests. func (g *Generator) GenerateSerializer(wMain, wTest io.Writer) error { switch g.Serializer { case "protobuf": if err := g.generateProto(wMain); err != nil { return errors.WithStack(err) } case "fbs": panic("not yet supported") case "", "default", "none": return nil // do nothing default: return errors.NotAcceptable.Newf("[dmlgen] Serializer %q not supported.", g.Serializer) } return nil } func (g *Generator) generateProto(w io.Writer) error { proto := codegen.NewProto(g.Package) const importTimeStamp = `import "google/protobuf/timestamp.proto";` proto.Pln(importTimeStamp) proto.Pln(`import "github.com/corestoreio/pkg/storage/null/null.proto";`) var hasGoPackageOption bool for _, o := range g.SerializerHeaderOptions { proto.Pln(`option ` + o + `;`) if !hasGoPackageOption { hasGoPackageOption = strings.Contains(o, "go_package") } } if !hasGoPackageOption { proto.Pln(`option go_package = `, fmt.Sprintf("%q;", g.PackageSerializer)) } var hasTimestampField bool for _, tblname := range g.sortedTableNames() { t := g.Tables[tblname] // must panic if table name not found fieldMapFn := g.defaultTableConfig.FieldMapFn if fieldMapFn == nil { fieldMapFn = t.fieldMapFn } if fieldMapFn == nil { fieldMapFn = defaultFieldMapFn } proto.C(t.EntityName(), `represents a single row for`, t.Table.Name, `DB table. Auto generated.`) if t.Table.TableComment != "" { proto.C("Table comment:", t.Table.TableComment) } proto.Pln(`message`, t.EntityName(), `{`) { proto.In() var lastColumnPos uint64 t.Table.Columns.Each(func(c *ddl.Column) { if t.IsFieldPublic(c.Field) { serType := g.serializerType(c) if !hasTimestampField && strings.HasPrefix(serType, "google.protobuf.Timestamp") { hasTimestampField = true } // extend here with a custom code option, if someone needs proto.Pln(serType, strs.ToGoCamelCase(c.Field), `=`, c.Pos, `; //`, c.Comment) lastColumnPos = c.Pos } }) lastColumnPos++ if g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityRelationships) { // for debugging see Table.fnEntityStruct function. This code is only different in the Pln function. var hasAtLeastOneRelationShip int relationShipSeen := map[string]bool{} if kcuc, ok := g.kcu[t.Table.Name]; ok { // kcu = keyColumnUsage && kcuc = keyColumnUsageCollection for _, kcuce := range kcuc.Data { if !kcuce.ReferencedTableName.Valid { continue } hasAtLeastOneRelationShip++ // case ONE-TO-MANY isOneToMany := g.krs.IsOneToMany(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) isRelationAllowed := g.isAllowedRelationship(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) hasTable := g.Tables[kcuce.ReferencedTableName.Data] != nil if isOneToMany && hasTable && isRelationAllowed { proto.Pln(fieldMapFn(pluralize(kcuce.ReferencedTableName.Data)), fieldMapFn(pluralize(kcuce.ReferencedTableName.Data)), "=", lastColumnPos, ";", "// 1:M", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) lastColumnPos++ } // case ONE-TO-ONE isOneToOne := g.krs.IsOneToOne(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) if isOneToOne && hasTable && isRelationAllowed { proto.Pln(fieldMapFn(strs.ToGoCamelCase(kcuce.ReferencedTableName.Data)), fieldMapFn(strs.ToGoCamelCase(kcuce.ReferencedTableName.Data)), "=", lastColumnPos, ";", "// 1:1", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) lastColumnPos++ } // case MANY-TO-MANY targetTbl, targetColumn := g.krs.ManyToManyTarget(kcuce.TableName, kcuce.ColumnName) // hasTable variable shall not be added because usually the link table does not get loaded. if isRelationAllowed && targetTbl != "" && targetColumn != "" { proto.Pln(fieldMapFn(pluralize(targetTbl)), " *", pluralize(targetTbl), t.customStructTagFields[targetTbl], "// M:N", kcuce.TableName+"."+kcuce.ColumnName, "via", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data, "=>", targetTbl+"."+targetColumn, ) } } } if kcuc, ok := g.kcuRev[t.Table.Name]; ok { // kcu = keyColumnUsage && kcuc = keyColumnUsageCollection for _, kcuce := range kcuc.Data { if !kcuce.ReferencedTableName.Valid { continue } hasAtLeastOneRelationShip++ // case ONE-TO-MANY isOneToMany := g.krs.IsOneToMany(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) isRelationAllowed := g.isAllowedRelationship(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) hasTable := g.Tables[kcuce.ReferencedTableName.Data] != nil keySeen := fieldMapFn(pluralize(kcuce.ReferencedTableName.Data)) relationShipSeenAlready := relationShipSeen[keySeen] // case ONE-TO-MANY if isRelationAllowed && isOneToMany && hasTable && !relationShipSeenAlready { proto.Pln(fieldMapFn(pluralize(kcuce.ReferencedTableName.Data)), fieldMapFn(pluralize(kcuce.ReferencedTableName.Data)), "=", lastColumnPos, ";", "// Reversed 1:M", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) relationShipSeen[keySeen] = true lastColumnPos++ } // case ONE-TO-ONE isOneToOne := g.krs.IsOneToOne(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) if isRelationAllowed && isOneToOne && hasTable { proto.Pln(fieldMapFn(strs.ToGoCamelCase(kcuce.ReferencedTableName.Data)), fieldMapFn(strs.ToGoCamelCase(kcuce.ReferencedTableName.Data)), "=", lastColumnPos, ";", "// Reversed 1:1", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) lastColumnPos++ } // case MANY-TO-MANY targetTbl, targetColumn := g.krs.ManyToManyTarget(kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) if targetTbl != "" && targetColumn != "" { keySeen := fieldMapFn(pluralize(targetTbl)) isRelationAllowed = g.isAllowedRelationship(kcuce.TableName, kcuce.ColumnName, targetTbl, targetColumn) && !relationShipSeen[keySeen] relationShipSeen[keySeen] = true } // case MANY-TO-MANY // hasTable shall not be added because usually the link table does not get loaded. if isRelationAllowed && targetTbl != "" && targetColumn != "" { proto.Pln(fieldMapFn(pluralize(targetTbl)), fieldMapFn(pluralize(targetTbl)), "=", lastColumnPos, ";", "// Reversed M:N", kcuce.TableName+"."+kcuce.ColumnName, "via", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data, "=>", targetTbl+"."+targetColumn, ) lastColumnPos++ } } } } proto.Out() } proto.Pln(`}`) proto.C(t.CollectionName(), `represents multiple rows for the`, t.Table.Name, `DB table. Auto generated.`) proto.Pln(`message`, t.CollectionName(), `{`) { proto.In() proto.Pln(`repeated`, t.EntityName(), `Data = 1;`) proto.Out() } proto.Pln(`}`) } if !hasTimestampField { // bit hacky to remove the import of timestamp proto but for now OK. removedImport := strings.ReplaceAll(proto.String(), importTimeStamp, "") proto.Reset() proto.WriteString(removedImport) } return proto.GenerateFile(w) } func buildDMLProtoMapper(dmlGoFilesFullImportPath, protoGoFilesFullImportPath string) error { cfg := &packages.Config{Mode: packages.NeedFiles | packages.NeedSyntax} pkgs, err := packages.Load(cfg, dmlGoFilesFullImportPath, protoGoFilesFullImportPath) if err != nil { return fmt.Errorf("failed to packages.Load: %w", err) } if packages.PrintErrors(pkgs) > 0 { panic("errors occurred") } dmlgenTypes := map[string][]fieldTypeInfo{} protoTypes := map[string][]fieldTypeInfo{} var protoPackageName string var dmlgenPackageName string // Print the names of the source files // for each package listed on the command line. for _, pkg := range pkgs { repr.Println(pkg.PkgPath, pkg.ID, pkg.GoFiles) for _, sntx := range pkg.Syntax { structNameAndType := buildDMLProtoASTDecl(sntx.Decls) switch { case dmlGoFilesFullImportPath == pkg.ID: dmlgenPackageName = sntx.Name.Name for n, fti := range structNameAndType { dmlgenTypes[n] = append(dmlgenTypes[n], fti...) } case protoGoFilesFullImportPath == pkg.ID: protoPackageName = sntx.Name.Name for n, fti := range structNameAndType { protoTypes[n] = append(protoTypes[n], fti...) } } } } if protoPackageName == "" { return fmt.Errorf("protoPackageName cannot be empty or no files found to parse") } repr.Println(dmlgenTypes) repr.Println(protoTypes) // <generate converter from proto to dml> cg := codegen.NewGo(protoPackageName) cg.AddImports(dmlGoFilesFullImportPath) for protoStructName, protoFieldTypeInfos := range protoTypes { cg.Pln(`func (x *`, protoStructName, `) ToDBType(optional *`, dmlgenPackageName, `.`, protoStructName, `) *`, dmlgenPackageName, `.`, protoStructName, `{`) cg.In() cg.Pln(`if optional == nil { optional = new(`, dmlgenPackageName, `.`, protoStructName, `) }`) cg.In() dmlgenFieldTypeInfos, ok := dmlgenTypes[protoStructName] if !ok { return fmt.Errorf("proto struct %q not found in generated dml package %q", protoStructName, dmlgenPackageName) } for idx, pft := range protoFieldTypeInfos { dmlft := dmlgenFieldTypeInfos[idx] if pft.isPointer && pft.externalPkgName == "null" { cg.Pln(`optional.`, pft.fname, ` .Reset()`) } getter := codegen.SkipWS(`Get`, pft.fname, `()`) switch { case pft.isSlice: cg.Pln(`optional.`, dmlft.fname, ` = optional.`, dmlft.fname, `[:0]`) cg.Pln(`for _, d := range x.`, pft.fname, ` {`) { cg.Pln(`optional.`, dmlft.fname, ` = append(optional.`, pft.fname, `, d.ToDBType(nil))`) } cg.Pln(`}`) case pft.isPointer && pft.isStruct: // proto type is a pointer switch { case strings.HasSuffix(dmlft.ftype, "time.Time") && strings.HasSuffix(pft.ftype, "timestamppb.Timestamp"): cg.Pln(`optional.`, dmlft.fname, ` = x.`, getter, `.AsTime() `) case strings.HasSuffix(dmlft.ftype, "null.Time") && strings.HasSuffix(pft.ftype, "timestamppb.Timestamp"): cg.Pln(`optional.`, dmlft.fname, `.SetProto( x.`, getter, `)`) case strings.HasSuffix(dmlft.ftype, "null.Decimal") && strings.HasSuffix(pft.ftype, "null.Decimal"): cg.Pln(`optional.`, dmlft.fname, `.SetPtr( x.`, getter, `)`) default: cg.Pln(`optional.`, dmlft.fname, ` = *x.`, pft.fname, `// TODO BUG fix`, pft.ftype, "isStruct", pft.isStruct) } case pft.isPointer: if dmlgenFieldTypeInfos[idx].externalPkgName == "null" { cg.Pln(`optional.`, dmlft.fname, `.SetPtr( x.`, pft.fname, `)`, `//1`, pft.ftype, "isStruct", pft.isStruct) } else { cg.Pln(`optional.`, dmlft.fname, ` = x.`, pft.fname, `//2`, dmlft.ftype, "=>", pft.ftype, "isStruct", pft.isStruct, pft.isSlice, dmlft.isSlice) } default: cg.Pln(`optional.`, dmlft.fname, ` = x.`, pft.fname, `//3`, pft.ftype, "isStruct", pft.isStruct) } } cg.Out() cg.Pln(`return optional`) // end &type{ cg.Out() cg.Pln(`}`) // end func } mapperFileName := filepath.Join(build.Default.GOPATH, "src", protoGoFilesFullImportPath, "/mapper.go") f, err := os.Create(mapperFileName) if err != nil { return fmt.Errorf("failed to create file: %w", err) } defer f.Close() return cg.GenerateFile(f) // </generate converter from proto to dml> return nil } type fieldTypeInfo struct { fname string ftype string externalPkgName string isPointer bool isStruct bool // if false, then a primitive and true then a struct type like *timestamppb.Timestamp isSlice bool } func buildDMLProtoASTDecl(decls []ast.Decl) map[string][]fieldTypeInfo { // map[structName] []Fields ret := map[string][]fieldTypeInfo{} for _, node := range decls { switch node.(type) { case *ast.GenDecl: genDecl := node.(*ast.GenDecl) genDeclSpecsLOOP: for _, spec := range genDecl.Specs { switch spec.(type) { case *ast.TypeSpec: typeSpec := spec.(*ast.TypeSpec) if !typeSpec.Name.IsExported() { continue genDeclSpecsLOOP } switch tst := typeSpec.Type.(type) { case *ast.StructType: fieldTypeInfos := []fieldTypeInfo{} for _, field := range tst.Fields.List { fieldType := fieldToType(field) for _, name := range field.Names { if isExported(name.Name) { fieldType.fname = name.Name fieldTypeInfos = append(fieldTypeInfos, fieldType) } } // end for } // end for ret[typeSpec.Name.Name] = fieldTypeInfos } } } } } return ret } // fieldToType returns the type name and whether if it's exported. func fieldToType(f *ast.Field) fieldTypeInfo { switch arg := f.Type.(type) { case *ast.ArrayType: n := astNodeName(arg.Elt) _, isSlice := arg.Elt.(*ast.StarExpr) // special custom slice, not []byte or anything else. return fieldTypeInfo{ftype: "[]" + n, isSlice: isSlice} case *ast.Ellipsis: n := astNodeName(arg.Elt) return fieldTypeInfo{ftype: n} case *ast.FuncType: // Do not print the function signature to not overload the trace. return fieldTypeInfo{ftype: "func"} case *ast.Ident: return fieldTypeInfo{ftype: arg.Name} case *ast.InterfaceType: return fieldTypeInfo{ftype: "interface{}"} case *ast.SelectorExpr: if ident, ok := arg.X.(*ast.Ident); ok && ident.Name != "" { return fieldTypeInfo{ftype: ident.Name + "." + arg.Sel.Name, externalPkgName: ident.Name, isStruct: true} } return fieldTypeInfo{ftype: arg.Sel.Name} case *ast.StarExpr: if sel, ok := arg.X.(*ast.SelectorExpr); ok { if ident, ok := sel.X.(*ast.Ident); ok && ident.Name != "" { n := astNodeName(arg.X) return fieldTypeInfo{ftype: "*" + ident.Name + "." + n, externalPkgName: ident.Name, isPointer: true, isStruct: true} } } n := astNodeName(arg.X) return fieldTypeInfo{ftype: "*" + n, isPointer: true} case *ast.MapType: return fieldTypeInfo{ftype: fmt.Sprintf("map[%s]%s", astNodeName(arg.Key), astNodeName(arg.Value))} case *ast.ChanType: return fieldTypeInfo{ftype: fmt.Sprintf("chan %s", astNodeName(arg.Value))} default: return fieldTypeInfo{ftype: "<unknown>"} } } func isExported(name string) bool { switch name { case "bool", "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "float32", "float64", "complex64", "complex128", "string", "int", "uint", "uintptr", "byte", "rune": return true } return token.IsExported(name) } func astNodeName(n ast.Node) string { switch t := n.(type) { case *ast.InterfaceType: return "interface{}" case *ast.Ident: return t.Name case *ast.SelectorExpr: return t.Sel.Name case *ast.StarExpr: return "*" + astNodeName(t.X) default: return "<unknown>" } } <|start_filename|>storage/objcache/bench_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 csall package objcache_test import ( "context" "io" "os" "strconv" "testing" "github.com/allegro/bigcache" "github.com/corestoreio/pkg/storage/objcache" "github.com/ugorji/go/codec" ) func benchmarkCountry(iterationsSetGet int, level2 objcache.NewStorageFn, opts *objcache.ServiceOptions) func(b *testing.B) { return func(b *testing.B) { p, err := objcache.NewService(nil, level2, opts) if err != nil { b.Fatal(err) } defer func() { if err := p.Close(); err != nil { b.Fatal(err) } }() var cntry interface{} = mustGetTestCountry() // type already gob.Registered ... const wantCountryISO = "US" ctx := context.TODO() b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { var i int64 for pb.Next() { key := strconv.FormatInt(i, 10) // 1 alloc i++ if err := p.Set(ctx, key, cntry, 0); err != nil { b.Fatalf("%+v", err) } // Double execution might detect storing of type information in streaming encoders for j := 0; j < iterationsSetGet; j++ { var newCntry Country if err := p.Get(ctx, key, &newCntry); err != nil { b.Fatalf("%+v", err) } if newCntry.Country.IsoCode != wantCountryISO { b.Fatalf("Country ISO Code must be %q, Have %q", wantCountryISO, newCntry.Country.IsoCode) } } } }) } } func benchmarkStores(iterationsSetGet int, level2 objcache.NewStorageFn, opts *objcache.ServiceOptions) func(b *testing.B) { return func(b *testing.B) { p, err := objcache.NewService(nil, level2, opts) if err != nil { b.Fatal(err) } defer func() { if err := p.Close(); err != nil { b.Fatal(err) } }() var ts interface{} = getTestStores() // type already gob.Registered ... const wantStoreCode = "nz" ctx := context.TODO() b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { var i int64 for pb.Next() { key := strconv.FormatInt(i, 10) // 1 alloc i++ if err := p.Set(ctx, key, ts, 0); err != nil { b.Fatal(err) } // Double execution might detect storing of type information in streaming encoders for j := 0; j < iterationsSetGet; j++ { var newTS TableStoreSlice if err := p.Get(ctx, key, &newTS); err != nil { b.Fatal(err) } if have := newTS[5].Code; have != wantStoreCode { b.Fatalf("Store Code in slice position 5 must be %q, Have %q", wantStoreCode, have) } } } }) } } func Benchmark_BigCache_Country(b *testing.B) { b.Run("Gob_1x", benchmarkCountry(1, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(gobCodec{}, Country{}))) b.Run("Gob_2x", benchmarkCountry(2, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(gobCodec{}, Country{}))) b.Run("JSON_1x", benchmarkCountry(1, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(JSONCodec{}))) b.Run("JSON_2x", benchmarkCountry(2, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(JSONCodec{}))) b.Run("MsgPack_1x", benchmarkCountry(1, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(newMsgPackCodec()))) b.Run("MsgPack_2x", benchmarkCountry(2, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(newMsgPackCodec()))) } func Benchmark_BigCache_Stores(b *testing.B) { b.Run("Gob_1x", benchmarkStores(1, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(gobCodec{}, TableStoreSlice{}))) b.Run("Gob_2x", benchmarkStores(2, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(gobCodec{}, TableStoreSlice{}))) b.Run("JSON_1x", benchmarkStores(1, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(JSONCodec{}))) b.Run("JSON_2x", benchmarkStores(2, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(JSONCodec{}))) b.Run("MsgPack_1x", benchmarkStores(1, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(newMsgPackCodec()))) b.Run("MsgPack_2x", benchmarkStores(2, objcache.NewBigCacheClient(bigcache.Config{}), newSrvOpt(newMsgPackCodec()))) } func Benchmark_Redis_Gob(b *testing.B) { redConURL := os.Getenv("CS_REDIS_TEST") // redis://127.0.0.1:6379/3 if redConURL == "" { b.Skip(`Skipping live test because environment CS_REDIS_TEST variable not found. export CS_REDIS_TEST="redis://127.0.0.1:6379/3" `) } b.Run("Country_1x", benchmarkCountry(1, objcache.NewRedisByURLClient(redConURL), newSrvOpt(gobCodec{}, Country{}))) b.Run("Country_2x", benchmarkCountry(2, objcache.NewRedisByURLClient(redConURL), newSrvOpt(gobCodec{}, Country{}))) b.Run("Stores_1x", benchmarkStores(1, objcache.NewRedisByURLClient(redConURL), newSrvOpt(gobCodec{}, TableStoreSlice{}))) b.Run("Stores_2x", benchmarkStores(2, objcache.NewRedisByURLClient(redConURL), newSrvOpt(gobCodec{}, TableStoreSlice{}))) } func Benchmark_Redis_MsgPack(b *testing.B) { redConURL := os.Getenv("CS_REDIS_TEST") // redis://127.0.0.1:6379/3 if redConURL == "" { b.Skip(`Skipping live test because environment CS_REDIS_TEST variable not found. export CS_REDIS_TEST="redis://127.0.0.1:6379/3" `) } b.Run("Country_1x", benchmarkCountry(1, objcache.NewRedisByURLClient(redConURL), newSrvOpt(newMsgPackCodec()))) b.Run("Country_2x", benchmarkCountry(2, objcache.NewRedisByURLClient(redConURL), newSrvOpt(newMsgPackCodec()))) b.Run("Stores_1x", benchmarkStores(1, objcache.NewRedisByURLClient(redConURL), newSrvOpt(newMsgPackCodec()))) b.Run("Stores_2x", benchmarkStores(2, objcache.NewRedisByURLClient(redConURL), newSrvOpt(newMsgPackCodec()))) } func Benchmark_File_Gob(b *testing.B) { defer func() { b.StopTimer() if err := os.RemoveAll("testdata/fs"); err != nil { b.Fatal(err) } b.StartTimer() }() b.Run("Country_1x", benchmarkCountry(1, objcache.NewFileSystemClient(nil), newSrvOpt(gobCodec{}, Country{}))) b.Run("Country_2x", benchmarkCountry(2, objcache.NewFileSystemClient(nil), newSrvOpt(gobCodec{}, Country{}))) b.Run("Stores_1x", benchmarkStores(1, objcache.NewFileSystemClient(nil), newSrvOpt(gobCodec{}, TableStoreSlice{}))) b.Run("Stores_2x", benchmarkStores(2, objcache.NewFileSystemClient(nil), newSrvOpt(gobCodec{}, TableStoreSlice{}))) } func Benchmark_LRU_Gob(b *testing.B) { b.Run("Country_1x", benchmarkCountry(1, objcache.NewLRU(nil), newSrvOpt(gobCodec{}, Country{}))) b.Run("Country_2x", benchmarkCountry(2, objcache.NewLRU(nil), newSrvOpt(gobCodec{}, Country{}))) b.Run("Stores_1x", benchmarkStores(1, objcache.NewLRU(nil), newSrvOpt(gobCodec{}, TableStoreSlice{}))) b.Run("Stores_2x", benchmarkStores(2, objcache.NewLRU(nil), newSrvOpt(gobCodec{}, TableStoreSlice{}))) } var ugmsgPackHandle codec.MsgpackHandle // msgPackCodec cannot be pooled because then it uses too much allocs and slows down. type msgPackCodec struct{} func newMsgPackCodec() msgPackCodec { return msgPackCodec{} } // NewEncoder returns a new json encoder which writes to w func (c msgPackCodec) NewEncoder(w io.Writer) objcache.Encoder { return codec.NewEncoder(w, &ugmsgPackHandle) } // NewDecoder returns a new json decoder which reads from r func (c msgPackCodec) NewDecoder(r io.Reader) objcache.Decoder { return codec.NewDecoder(r, &ugmsgPackHandle) } <|start_filename|>sql/dml/delete_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" "testing" "time" "github.com/corestoreio/pkg/util/conv" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func TestDeleteAllToSQL(t *testing.T) { compareToSQL2(t, NewDelete("a"), errors.NoKind, "DELETE FROM `a`") compareToSQL2(t, NewDelete("a").Alias("b"), errors.NoKind, "DELETE FROM `a` AS `b`") } func TestDeleteSingleToSQL(t *testing.T) { qb := NewDelete("a").Where(Column("id").Int(1)) compareToSQL2(t, qb, errors.NoKind, "DELETE FROM `a` WHERE (`id` = 1)", ) // test for being idempotent compareToSQL2(t, qb, errors.NoKind, "DELETE FROM `a` WHERE (`id` = 1)", ) } func TestDelete_OrderBy(t *testing.T) { t.Run("expr", func(t *testing.T) { compareToSQL2(t, NewDelete("a").Unsafe().OrderBy("b=c").OrderByDesc("d"), errors.NoKind, "DELETE FROM `a` ORDER BY b=c, `d` DESC", ) }) t.Run("asc", func(t *testing.T) { compareToSQL2(t, NewDelete("a").OrderBy("b").OrderBy("c"), errors.NoKind, "DELETE FROM `a` ORDER BY `b`, `c`", ) }) t.Run("desc", func(t *testing.T) { compareToSQL2(t, NewDelete("a").OrderBy("b").OrderByDesc("c").OrderBy("d").OrderByDesc("e", "f").OrderBy("g"), errors.NoKind, "DELETE FROM `a` ORDER BY `b`, `c` DESC, `d`, `e` DESC, `f` DESC, `g`", ) }) } func TestDelete_Limit_Offset(t *testing.T) { compareToSQL2(t, NewDelete("a").Limit(10).OrderBy("id"), errors.NoKind, "DELETE FROM `a` ORDER BY `id` LIMIT 10", ) } func TestDelete_Interpolate(t *testing.T) { compareToSQL2(t, NewDelete("tableA"). Where( Column("colA").GreaterOrEqual().Float64(3.14159), Column("colB").In().Ints(1, 2, 3, 45), Column("colC").Str("Hello"), ). Limit(10).OrderBy("id"), errors.NoKind, "DELETE FROM `tableA` WHERE (`colA` >= 3.14159) AND (`colB` IN (1,2,3,45)) AND (`colC` = 'Hello') ORDER BY `id` LIMIT 10", ) compareToSQL(t, NewDelete("tableA"). Where( Column("colA").GreaterOrEqual().Float64(3.14159), Column("colB").In().NamedArg("colB2"), ). Limit(10).OrderBy("id").WithDBR(nil).Interpolate().TestWithArgs(sql.Named("colB2", []int64{3, 4, 7, 8})), errors.NoKind, "DELETE FROM `tableA` WHERE (`colA` >= 3.14159) AND (`colB` IN ?) ORDER BY `id` LIMIT 10", "DELETE FROM `tableA` WHERE (`colA` >= 3.14159) AND (`colB` IN (3,4,7,8)) ORDER BY `id` LIMIT 10", int64(3), int64(4), int64(7), int64(8), ) } func TestDeleteReal(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) // Insert a Barack res, err := s.WithQueryBuilder(NewInsert("dml_people").AddColumns("name", "email")). ExecContext(context.TODO(), "Barack", "<EMAIL>") assert.NoError(t, err) assert.NotNil(t, res) // Get Barack'ab ID id, err := res.LastInsertId() assert.NoError(t, err, "LastInsertId") // Delete Barack res, err = s.WithQueryBuilder(NewDelete("dml_people").Where(Column("id").Int64(id))).ExecContext(context.TODO()) assert.NoError(t, err, "DeleteFrom") // Ensure we only reflected one row and that the id no longer exists rowsAff, err := res.RowsAffected() assert.NoError(t, err) assert.Exactly(t, int64(1), rowsAff, "RowsAffected") count, found, err := s.WithQueryBuilder(NewSelect().Count().From("dml_people").Where(Column("id").PlaceHolder())).LoadNullInt64(context.TODO(), id) assert.NoError(t, err) assert.True(t, found, "should have found a row") assert.Exactly(t, int64(0), count.Int64, "count") assert.Exactly(t, []string{ "DELETEf0d5f12cb21e7142", "DELETE FROM `dml_people` WHERE (`id` = 3)", "INSERT35b056eb359cf3ef", "INSERT INTO `dml_people` (`name`,`email`) VALUES ", "SELECT835edcaab6dec8d3", "SELECT COUNT(*) AS `counted` FROM `dml_people` WHERE (`id` = ?)", }, conv.ToStringSlice(s.CachedQueries())) } func TestDelete_BuildCacheDisabled(t *testing.T) { del := NewDelete("alpha").Where( Column("a").Str("b"), Column("b").PlaceHolder(), ).Limit(1).OrderBy("id") const iterations = 3 const cachedSQLPlaceHolder = "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = ?) ORDER BY `id` LIMIT 1" t.Run("without interpolate", func(t *testing.T) { for i := 0; i < iterations; i++ { sql, args, err := del.ToSQL() assert.NoError(t, err) assert.Exactly(t, cachedSQLPlaceHolder, sql) assert.Nil(t, args, "No arguments provided but got some") } // assert.Exactly(t, []string{"", "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = ?) ORDER BY `id` LIMIT 1"}, // del.CachedQueries()) }) t.Run("with interpolate", func(t *testing.T) { delA := del.WithDBR(nil) compareToSQL(t, delA.TestWithArgs(123), errors.NoKind, "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = ?) ORDER BY `id` LIMIT 1", "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = 123) ORDER BY `id` LIMIT 1", int64(123), ) delA.Reset() compareToSQL(t, delA.TestWithArgs(124), errors.NoKind, "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = ?) ORDER BY `id` LIMIT 1", "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = 124) ORDER BY `id` LIMIT 1", int64(124), ) // assert.Exactly(t, []string{"", "DELETE FROM `alpha` WHERE (`a` = 'b') AND (`b` = ?) ORDER BY `id` LIMIT 1"}, // del.CachedQueries()) }) } func TestDelete_Bind(t *testing.T) { p := &dmlPerson{ ID: 5555, Email: null.MakeString("<EMAIL>"), } t.Run("multiple args from Record", func(t *testing.T) { del := NewDelete("dml_people"). Where( Column("idI64").Greater().Int64(4), Column("id").Equal().PlaceHolder(), Column("float64_pi").Float64(3.14159), Column("email").PlaceHolder(), Column("int_e").Int(2718281), ).OrderBy("id"). WithDBR(nil).TestWithArgs(Qualify("", p)) compareToSQL2(t, del, errors.NoKind, "DELETE FROM `dml_people` WHERE (`idI64` > 4) AND (`id` = ?) AND (`float64_pi` = 3.14159) AND (`email` = ?) AND (`int_e` = 2718281) ORDER BY `id`", int64(5555), "<EMAIL>", ) }) t.Run("single arg from Record unqualified", func(t *testing.T) { del := NewDelete("dml_people"). Where( Column("id").PlaceHolder(), ).OrderBy("id"). WithDBR(nil) compareToSQL2(t, del.TestWithArgs(Qualify("", p)), errors.NoKind, "DELETE FROM `dml_people` WHERE (`id` = ?) ORDER BY `id`", int64(5555), ) assert.Exactly(t, []string{"id"}, del.cachedSQL.qualifiedColumns) }) t.Run("single arg from Record qualified", func(t *testing.T) { del := NewDelete("dml_people").Alias("dmlPpl"). Where( Column("id").PlaceHolder(), ).OrderBy("id"). WithDBR(nil) compareToSQL(t, del.TestWithArgs(Qualify("dmlPpl", p)), errors.NoKind, "DELETE FROM `dml_people` AS `dmlPpl` WHERE (`id` = ?) ORDER BY `id`", "DELETE FROM `dml_people` AS `dmlPpl` WHERE (`id` = 5555) ORDER BY `id`", int64(5555), ) assert.Exactly(t, []string{"id"}, del.cachedSQL.qualifiedColumns) }) t.Run("null type records", func(t *testing.T) { ntr := newNullTypedRecordWithData() del := NewDelete("null_type_table"). Where( Column("string_val").PlaceHolder(), Column("int64_val").PlaceHolder(), Column("float64_val").PlaceHolder(), Column("random1").Between().Float64s(1.2, 3.4), Column("time_val").PlaceHolder(), Column("bool_val").PlaceHolder(), ).OrderBy("id").WithDBR(nil).TestWithArgs(Qualify("", ntr)) compareToSQL2(t, del, errors.NoKind, "DELETE FROM `null_type_table` WHERE (`string_val` = ?) AND (`int64_val` = ?) AND (`float64_val` = ?) AND (`random1` BETWEEN 1.2 AND 3.4) AND (`time_val` = ?) AND (`bool_val` = ?) ORDER BY `id`", "wow", int64(42), 1.618, time.Date(2009, 1, 3, 18, 15, 5, 0, time.UTC), true, ) }) } <|start_filename|>sql/dmlgen/table.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dmlgen import ( "bytes" "fmt" "strconv" "strings" "text/tabwriter" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/util/bufferpool" "github.com/corestoreio/pkg/util/codegen" "github.com/corestoreio/pkg/util/strs" ) // table writes one database table into Go source code. type Table struct { Package string // Name of the package Table *ddl.Table Comment string // Comment above the struct type declaration HasAutoIncrement uint8 // 0=nil,1=false (has NO auto increment),2=true has auto increment HasEasyJSONMarshaler bool HasSerializer bool // writes the .proto file if true // PrivateFields key=snake case name of the DB column, value=true, the field must be private debug bool // gets set via isDebug function privateFields map[string]bool featuresInclude FeatureToggle featuresExclude FeatureToggle fieldMapFn func(dbIdentifier string) (newName string) customStructTagFields map[string]string relationshipSeen map[string]bool // to not print twice a relationship availableRelationships []relationShipInfo } type relationShipInfo struct { isCollection bool tableName string structName string mappedStructFieldName string // name of the struct in the relation struct columnName string } func (t *Table) getFieldMapFn(g *Generator) func(dbIdentifier string) (newName string) { fieldMapFn := g.defaultTableConfig.FieldMapFn if fieldMapFn == nil { fieldMapFn = t.fieldMapFn } if fieldMapFn == nil { fieldMapFn = defaultFieldMapFn } return fieldMapFn } func (t *Table) IsFieldPublic(dbColumnName string) bool { return !t.privateFields[dbColumnName] } func (t *Table) IsFieldPrivate(dbColumnName string) bool { return t.privateFields[dbColumnName] } func (t *Table) GoCamelMaybePrivate(fieldName string) string { su := strs.ToGoCamelCase(fieldName) if t.IsFieldPublic(fieldName) { return su } return strs.LcFirst(su) } func (t *Table) CollectionName() string { return pluralize(t.Table.Name) } func (t *Table) EntityName() string { return strs.ToGoCamelCase(t.Table.Name) } func (t *Table) EntityNameLCFirst() string { return strs.LcFirst(strs.ToGoCamelCase(t.Table.Name)) } func (t *Table) hasFeature(g *Generator, f FeatureToggle) bool { return g.hasFeature(t.featuresInclude, t.featuresExclude, f, 'a') // mode == AND } func (t *Table) fnCollectionStruct(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionStruct) { return } mainGen.C(t.CollectionName(), `represents a collection type for DB table`, t.Table.Name) mainGen.C(`Not thread safe. Auto generated.`) mainGen.C(t.Comment != "", t.Comment) mainGen.Pln(t.HasEasyJSONMarshaler, `//easyjson:json`) // do not use C() because it adds a whitespace between "//" and "e" mainGen.Pln(`type `, t.CollectionName(), ` struct {`) { mainGen.In() mainGen.Pln(`Data []*`, t.EntityName(), codegen.EncloseBT(`json:"data,omitempty"`)) if fn, ok := g.customCode["type_"+t.CollectionName()]; ok { fn(g, t, mainGen) } mainGen.Out() } mainGen.Pln(`}`) mainGen.C(`New`+t.CollectionName(), ` creates a new initialized collection. Auto generated.`) // TODO(idea): use a global pool which can register for each type the // before/after mapcolumn function so that the dev does not need to // assign each time. think if it's worth such a pattern. mainGen.Pln(`func New`+t.CollectionName(), `() *`, t.CollectionName(), ` {`) { mainGen.In() mainGen.Pln(`return &`, t.CollectionName(), `{`) { mainGen.In() mainGen.Pln(`Data: make([]*`, t.EntityName(), `, 0, 5),`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Out() } mainGen.Pln(`}`) } func (t *Table) fnEntityStruct(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityStruct) { return } mainGen.C(t.EntityName(), `represents a single row for DB table`, t.Table.Name+`. Auto generated.`) if t.Comment != "" { mainGen.C(t.Comment) } if t.Table.TableComment != "" { mainGen.C("Table comment:", t.Table.TableComment) } if t.HasEasyJSONMarshaler { mainGen.Pln(`//easyjson:json`) } // Generate table structs mainGen.Pln(`type `, t.EntityName(), ` struct {`) { if fn, ok := g.customCode["type_"+t.EntityName()]; ok { fn(g, t, mainGen) } else { mainGen.In() for _, c := range t.Table.Columns { structTag := "" if c.StructTag != "" { structTag += "`" + c.StructTag + "`" } mainGen.Pln(t.GoCamelMaybePrivate(c.Field), g.goTypeNull(c), structTag, c.GoComment()) } if len(t.availableRelationships) > 0 { mainGen.P(`Relations *`, t.relationStructName()) // TODO use customStructTagFields if fn, ok := g.customCode["type_relation_"+t.relationStructName()]; ok { fn(g, t, mainGen) } else { mainGen.Pln("") } } mainGen.Out() } } mainGen.Pln(`}`) } func (t *Table) relationStructName() string { return t.EntityNameLCFirst() + `Relations` } // this part is duplicated in the proto file generation function generateProto. func (t *Table) fnEntityRelationStruct(mainGen *codegen.Go, g *Generator) { _, ok1 := g.kcu[t.Table.Name] _, ok2 := g.kcuRev[t.Table.Name] if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityRelationships) || (!ok1 && !ok2) { return } fieldMapFn := t.getFieldMapFn(g) // only write the relation struct if there are some relations, if non, revert to the old buffer. mainGenBuf := mainGen.Buffer mainGen.Buffer = new(bytes.Buffer) defer func() { data := mainGen.Buffer.Bytes() mainGen.Buffer = mainGenBuf // restore old buffer if len(t.availableRelationships) > 0 { mainGen.Buffer.Write(data) } }() mainGen.Pln(`type `, t.relationStructName(), ` struct {`) mainGen.In() if fn, ok := g.customCode["type_"+t.relationStructName()]; ok { fn(g, t, mainGen) } mainGen.Pln(`parent *`, t.EntityName()) debugBuf := bufferpool.Get() defer bufferpool.Put(debugBuf) tabW := tabwriter.NewWriter(debugBuf, 6, 0, 2, ' ', 0) var hasAtLeastOneRelationShip int fmt.Fprintf(debugBuf, "RelationInfo for: %q\n", t.Table.Name) fmt.Fprintf(tabW, "Case\tis1:M\tis1:1\tseen?\tisRelAl\thasTable\tTarget Tbl M:N\tRelation\n") if kcuc, ok := g.kcu[t.Table.Name]; ok { // kcu = keyColumnUsage && kcuc = keyColumnUsageCollection for _, kcuce := range kcuc.Data { if !kcuce.ReferencedTableName.Valid { continue } hasAtLeastOneRelationShip++ // case ONE-TO-MANY isOneToMany := g.krs.IsOneToMany(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) isRelationAllowed := g.isAllowedRelationship(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) hasTable := g.Tables[kcuce.ReferencedTableName.Data] != nil fmt.Fprintf(tabW, "A1_1:M\t%t\t%t\t%t\t%t\t%t\t-\t%s => %s\n", isOneToMany, false, false, isRelationAllowed, hasTable, kcuce.TableName+"."+kcuce.ColumnName, kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) if isOneToMany && hasTable && isRelationAllowed { name := pluralize(kcuce.ReferencedTableName.Data) fieldName := fieldMapFn(name) t.availableRelationships = append(t.availableRelationships, relationShipInfo{ isCollection: true, tableName: kcuce.ReferencedTableName.Data, structName: name, mappedStructFieldName: fieldName, columnName: kcuce.ReferencedColumnName.Data, }) mainGen.Pln(fieldName, " *", name, t.customStructTagFields[kcuce.ReferencedTableName.Data], "// 1:M", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) } // case ONE-TO-ONE isOneToOne := g.krs.IsOneToOne(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) fmt.Fprintf(tabW, "B1_1:1\t%t\t%t\t%t\t%t\t%t\t-\t%s => %s\n", isOneToMany, isOneToOne, false, isRelationAllowed, hasTable, kcuce.TableName+"."+kcuce.ColumnName, kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) if isOneToOne && hasTable && isRelationAllowed { name := strs.ToGoCamelCase(kcuce.ReferencedTableName.Data) fieldName := fieldMapFn(name) t.availableRelationships = append(t.availableRelationships, relationShipInfo{ isCollection: true, tableName: kcuce.ReferencedTableName.Data, structName: name, mappedStructFieldName: fieldName, columnName: kcuce.ReferencedColumnName.Data, }) mainGen.Pln(fieldName, " *", name, t.customStructTagFields[kcuce.ReferencedTableName.Data], "// 1:1", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) } // case MANY-TO-MANY targetTbl, targetColumn := g.krs.ManyToManyTarget(kcuce.TableName, kcuce.ColumnName) fmt.Fprintf(tabW, "C1_M:N\t%t\t%t\t%t\t%t\t%t\t%s\t%s => %s\n", isOneToMany, isOneToOne, false, isRelationAllowed, hasTable, targetTbl+"."+targetColumn, kcuce.TableName+"."+kcuce.ColumnName, kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) // hasTable variable shall not be added because usually the link table does not get loaded. if isRelationAllowed && targetTbl != "" && targetColumn != "" { name := pluralize(targetTbl) fieldName := fieldMapFn(name) t.availableRelationships = append(t.availableRelationships, relationShipInfo{ isCollection: true, tableName: kcuce.ReferencedTableName.Data, structName: name, mappedStructFieldName: fieldName, columnName: kcuce.ReferencedColumnName.Data, }) mainGen.Pln(fieldName, " *", name, t.customStructTagFields[targetTbl], "// M:N", kcuce.TableName+"."+kcuce.ColumnName, "via", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data, "=>", targetTbl+"."+targetColumn, ) } } } if kcuc, ok := g.kcuRev[t.Table.Name]; ok { // kcu = keyColumnUsage && kcuc = keyColumnUsageCollection for _, kcuce := range kcuc.Data { if !kcuce.ReferencedTableName.Valid { continue } hasAtLeastOneRelationShip++ // case ONE-TO-MANY isOneToMany := g.krs.IsOneToMany(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) isRelationAllowed := g.isAllowedRelationship(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) hasTable := g.Tables[kcuce.ReferencedTableName.Data] != nil keySeen := fieldMapFn(pluralize(kcuce.ReferencedTableName.Data)) relationShipSeenAlready := t.relationshipSeen[keySeen] // case ONE-TO-MANY fmt.Fprintf(tabW, "A2_1:M rev\t%t\t%t\t%t\t%t\t%t\t-\t%s => %s\n", isOneToMany, false, relationShipSeenAlready, isRelationAllowed, hasTable, kcuce.TableName+"."+kcuce.ColumnName, kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) if isRelationAllowed && isOneToMany && hasTable && !relationShipSeenAlready { name := pluralize(kcuce.ReferencedTableName.Data) fieldName := fieldMapFn(name) t.availableRelationships = append(t.availableRelationships, relationShipInfo{ isCollection: true, tableName: kcuce.ReferencedTableName.Data, structName: name, mappedStructFieldName: fieldName, columnName: kcuce.ReferencedColumnName.Data, }) mainGen.Pln(fieldName, " *", name, t.customStructTagFields[kcuce.ReferencedTableName.Data], "// Reversed 1:M", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) t.relationshipSeen[keySeen] = true } // case ONE-TO-ONE isOneToOne := g.krs.IsOneToOne(kcuce.TableName, kcuce.ColumnName, kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) fmt.Fprintf(tabW, "B2_1:1 rev\t%t\t%t\t%t\t%t\t%t\t-\t%s => %s\n", isOneToMany, isOneToOne, relationShipSeenAlready, isRelationAllowed, hasTable, kcuce.TableName+"."+kcuce.ColumnName, kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) if isRelationAllowed && isOneToOne && hasTable { name := strs.ToGoCamelCase(kcuce.ReferencedTableName.Data) fieldName := fieldMapFn(name) t.availableRelationships = append(t.availableRelationships, relationShipInfo{ tableName: kcuce.ReferencedTableName.Data, structName: name, mappedStructFieldName: fieldName, columnName: kcuce.ReferencedColumnName.Data, }) mainGen.Pln(fieldName, " *", name, t.customStructTagFields[kcuce.ReferencedTableName.Data], "// Reversed 1:1", kcuce.TableName+"."+kcuce.ColumnName, "=>", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) } // case MANY-TO-MANY targetTbl, targetColumn := g.krs.ManyToManyTarget(kcuce.ReferencedTableName.Data, kcuce.ReferencedColumnName.Data) if targetTbl != "" && targetColumn != "" { keySeen := fieldMapFn(pluralize(targetTbl)) isRelationAllowed = g.isAllowedRelationship(kcuce.TableName, kcuce.ColumnName, targetTbl, targetColumn) && !t.relationshipSeen[keySeen] t.relationshipSeen[keySeen] = true } // case MANY-TO-MANY fmt.Fprintf(tabW, "C2_M:N rev\t%t\t%t\t%t\t%t\t%t\t%s\t%s => %s\n", isOneToMany, isOneToOne, relationShipSeenAlready, isRelationAllowed, hasTable, targetTbl+"."+targetColumn, kcuce.TableName+"."+kcuce.ColumnName, kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data) // hasTable shall not be added because usually the link table does not get loaded. if isRelationAllowed && targetTbl != "" && targetColumn != "" { name := pluralize(targetTbl) fieldName := fieldMapFn(name) t.availableRelationships = append(t.availableRelationships, relationShipInfo{ isCollection: true, tableName: kcuce.ReferencedTableName.Data, structName: name, mappedStructFieldName: fieldName, columnName: kcuce.ReferencedColumnName.Data, }) mainGen.Pln(fieldName, " *", name, t.customStructTagFields[targetTbl], "// Reversed M:N", kcuce.TableName+"."+kcuce.ColumnName, "via", kcuce.ReferencedTableName.Data+"."+kcuce.ReferencedColumnName.Data, "=>", targetTbl+"."+targetColumn, ) } } } if t.debug && hasAtLeastOneRelationShip > 0 { _ = tabW.Flush() fmt.Fprintf(debugBuf, "Relationship count: %d\n", hasAtLeastOneRelationShip) fmt.Println(debugBuf.String()) } mainGen.Out() mainGen.Pln(`}`) // end type struct mainGen.Pln(`func (e *`, t.EntityName(), `) setRelationParent() {`) mainGen.Pln(`if e.Relations != nil && e.Relations.parent == nil { e.Relations.parent = e } }`) mainGen.Pln(`func (e *`, t.EntityName(), `) NewRelations() *`, t.relationStructName(), ` {`) mainGen.Pln(`e.Relations = &`, t.relationStructName(), ` { parent: e } return e.Relations }`) } func (t *Table) fnEntityRelationMethods(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityRelationships) || len(t.availableRelationships) == 0 { return } parentPK := t.Table.Columns.PrimaryKeys().First() // TODO support multiple Primary Keys parentPKFieldName := strs.ToGoCamelCase(parentPK.Field) for _, rs := range t.availableRelationships { // <DELETE> mainGen.Pln(`func (r *`, t.relationStructName(), `) `, "Delete"+rs.mappedStructFieldName, `(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error {`) mainGen.Pln(`dbr := dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, rs.mappedStructFieldName, `DeleteByFK`, `"`), `, opts...)`) mainGen.Pln(`res, err := dbr.ExecContext(ctx, r.parent.`, parentPKFieldName, `)`) mainGen.Pln(`err = dbr.ResultCheckFn(`, constTableName(rs.tableName), `, len(r.`, rs.mappedStructFieldName, `.Data), res, err)`) mainGen.Pln(`if err == nil && r.`, rs.mappedStructFieldName, ` != nil { r.`, rs.mappedStructFieldName, `.Clear() }`) mainGen.Pln(`return errors.WithStack(err) }`) // </DELETE> // <INSERT> mainGen.Pln(`func (r *`, t.relationStructName(), `) `, codegen.SkipWS("Insert", rs.mappedStructFieldName), `(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error {`) mainGen.Pln(`if r.`, rs.mappedStructFieldName, ` == nil || len(r.`, rs.mappedStructFieldName, `.Data) == 0 { return nil } for _, e2 := range r.`, rs.mappedStructFieldName, `.Data { e2.`, strs.ToGoCamelCase(rs.columnName), ` = `, g.convertType( parentPK, g.findColumn(rs.tableName, rs.columnName), `r.parent.`+parentPKFieldName, ), ` } return errors.WithStack(r.`, rs.mappedStructFieldName, `.DBInsert(ctx, dbm, opts...)) }`) // </INSERT> // <UPDATE> mainGen.Pln(`func (r *customerEntityRelations) `, codegen.SkipWS(`Update`, rs.mappedStructFieldName), `(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) {`) mainGen.Pln(`if r.`, rs.mappedStructFieldName, ` == nil || len(r.`, rs.mappedStructFieldName, `.Data) == 0 { dbr := dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, rs.mappedStructFieldName, `DeleteByFK`, `"`), `, opts...) res, err := dbr.ExecContext(ctx, r.parent.`, parentPKFieldName, `) return dbr.ResultCheckFn(`, constTableName(rs.tableName), `, -1, res, errors.WithStack(err)) } for _, e2 := range r.`, rs.mappedStructFieldName, `.Data { e2.`, strs.ToGoCamelCase(rs.columnName), ` = `, g.convertType( parentPK, g.findColumn(rs.tableName, rs.columnName), `r.parent.`+parentPKFieldName, ), ` } err = r.`, rs.mappedStructFieldName, `.DBUpdate(ctx, dbm, opts...) return errors.WithStack(err) }`) // </UPDATE> // <SELECT> mainGen.Pln(`func (r *`, t.relationStructName(), `) `, "Load"+rs.mappedStructFieldName, `(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (rowCount uint64, err error) {`) mainGen.Pln(`if r.`, rs.mappedStructFieldName, ` == nil { r.`, rs.mappedStructFieldName, ` = &`, rs.mappedStructFieldName, `{} }`) mainGen.Pln(`r.`, rs.mappedStructFieldName, `.Clear() rowCount, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, rs.mappedStructFieldName, `SelectByFK"`), `, opts...).Load(ctx, r.`, rs.mappedStructFieldName, `, r.parent.EntityID) return rowCount, errors.WithStack(err) }`) // </SELECT> } // end for availableRelationships // TODO for all `All` functions add a possibility to load async. //g, ctx := errgroup.WithContext(ctx) //g.Go(func() error { // _, err = r.LoadCustomerAddressEntities(ctx, dbm, opts...) // return errors.WithStack(err) //}) //return g.Wait() // <INSERT_ALL> mainGen.Pln(`func (r *`, t.relationStructName(), `) InsertAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error {`) for _, rs := range t.availableRelationships { mainGen.Pln(`if err := r.`, codegen.SkipWS("Insert", rs.mappedStructFieldName), `(ctx, dbm, opts...); err != nil { return errors.WithStack(err) }`) } mainGen.Pln(`return nil }`) // </INSERT_ALL> // <SELECT_ALL> mainGen.Pln(`func (r *`, t.relationStructName(), `) LoadAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) {`) for _, rs := range t.availableRelationships { mainGen.Pln(`if _, err = r.`, codegen.SkipWS("Load", rs.mappedStructFieldName), `(ctx, dbm, opts...); err != nil { return errors.WithStack(err) }`) } mainGen.Pln(`return nil }`) // </SELECT_ALL> // <UPDATE_ALL> mainGen.Pln(`func (r *`, t.relationStructName(), `) UpdateAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error {`) for _, rs := range t.availableRelationships { mainGen.Pln(`if err := r.`, codegen.SkipWS("Update", rs.mappedStructFieldName), `(ctx, dbm, opts...); err != nil { return errors.WithStack(err) }`) } mainGen.Pln(`return nil }`) // </UPDATE_ALL> // <DELETE_ALL> mainGen.Pln(`func (r *`, t.relationStructName(), `) DeleteAll(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) error {`) for _, rs := range t.availableRelationships { mainGen.Pln(`if err := r.`, codegen.SkipWS("Delete", rs.mappedStructFieldName), `(ctx, dbm, opts...); err != nil { return errors.WithStack(err) }`) } mainGen.Pln(`return nil }`) // </DELETE_ALL> } func (t *Table) fnEntityGetSetPrivateFields(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityGetSetPrivateFields) { return } // Generates the Getter/Setter for private fields for _, c := range t.Table.Columns { if !t.IsFieldPrivate(c.Field) { continue } mainGen.C(`Set`, strs.ToGoCamelCase(c.Field), ` sets the data for a private and security sensitive field.`) mainGen.Pln(`func (e *`, t.EntityName(), `) Set`+strs.ToGoCamelCase(c.Field), `(d `, g.goTypeNull(c), `) *`, t.EntityName(), ` {`) { mainGen.In() mainGen.Pln(`e.`, t.GoCamelMaybePrivate(c.Field), ` = d`) mainGen.Pln(`return e`) mainGen.Out() } mainGen.Pln(`}`) mainGen.C(`Get`, strs.ToGoCamelCase(c.Field), ` returns the data from a private and security sensitive field.`) mainGen.Pln(`func (e *`, t.EntityName(), `) Get`+strs.ToGoCamelCase(c.Field), `() `, g.goTypeNull(c), `{`) { mainGen.In() mainGen.Pln(`return e.`, t.GoCamelMaybePrivate(c.Field)) mainGen.Out() } mainGen.Pln(`}`) } } func (t *Table) fnEntityEmpty(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityEmpty) { return } mainGen.C(`Empty empties all the fields of the current object. Also known as Reset.`) // no idea if pointer dereferencing is bad ... mainGen.Pln(`func (e *`, t.EntityName(), `) Empty() *`, t.EntityName(), ` { *e = `, t.EntityName(), `{}; return e }`) } func (t *Table) fnEntityIsSet(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityIsSet|FeatureDB|FeatureDBSelect) { return } tblPKs := t.Table.Columns.PrimaryKeys() if t.Table.IsView() { tblPKs = t.Table.Columns.ViewPrimaryKeys() } // TODO maybe unique keys should also be added. var buf strings.Builder i := 0 tblPKs.Each(func(c *ddl.Column) { if i > 0 { buf.WriteString(" && ") } buf.WriteString("e.") buf.WriteString(strs.ToGoCamelCase(c.Field)) buf.WriteString(mySQLType2GoComparisonOperator(c)) i++ }) if i == 0 { return // no PK fields found } mainGen.C(`IsSet returns true if the entity has non-empty primary keys.`) mainGen.Pln(`func (e *`, t.EntityName(), `) IsSet() bool { return `, buf.String(), ` }`) } func (t *Table) fnEntityCopy(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityCopy) { return } mainGen.C(`Copy copies the struct and returns a new pointer. TODO use deepcopy tool to generate code afterwards`) mainGen.Pln(`func (e *`, t.EntityName(), `) Copy() *`, t.EntityName(), ` { if e == nil { return &`, t.EntityName(), `{} } e2 := *e // for now a shallow copy return &e2 }`) } func (t *Table) fnEntityWriteTo(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityWriteTo) { return } mainGen.C(`WriteTo implements io.WriterTo and writes the field names and their values to w.`, `This is especially useful for debugging or or generating a hash of the struct.`) mainGen.Pln(`func (e *`, t.EntityName(), `) WriteTo(w io.Writer) (n int64, err error) { // for now this printing is good enough. If you need better swap out with your code.`) if fn, ok := g.customCode["func_"+t.EntityName()+"_WriteTo"]; ok { fn(g, t, mainGen) } else { mainGen.Pln(`n2, err := fmt.Fprint(w,`) mainGen.In() t.Table.Columns.Each(func(c *ddl.Column) { if t.IsFieldPublic(c.Field) { mainGen.Pln(`"`+c.Field+`:"`, `, e.`, strs.ToGoCamelCase(c.Field), `,`, `"\n",`) } }) mainGen.Pln(`)`) mainGen.Pln(`return int64(n2), err`) mainGen.Out() } mainGen.Pln(`}`) } func (t *Table) fnCollectionWriteTo(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityWriteTo) { return } mainGen.C(`WriteTo implements io.WriterTo and writes the field names and their values to w.`, `This is especially useful for debugging or or generating a hash of the struct.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) WriteTo(w io.Writer) (n int64, err error) { for i,d := range cc.Data { n2,err := d.WriteTo(w) if err != nil { return 0, errors.Wrapf(err,"[`+t.Package+`] WriteTo failed at index %d",i) } n+=n2 } return n,nil }`) } func (t *Table) fnEntityDBMapColumns(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureDBMapColumns| FeatureDB|FeatureDBSelect|FeatureDBDelete| FeatureDBInsert|FeatureDBUpdate|FeatureDBUpsert) { return } mainGen.C(`MapColumns implements interface ColumnMapper only partially. Auto generated.`) mainGen.Pln(`func (e *`, t.EntityName(), `) MapColumns(cm *dml.ColumnMap) error {`) { if fn, ok := g.customCode["func_"+t.EntityName()+"_MapColumns"]; ok { fn(g, t, mainGen) } mainGen.Pln(`for cm.Next(`, t.Table.Columns.Len(), `) {`) { mainGen.In() mainGen.Pln(`switch c := cm.Column(); c {`) { mainGen.In() t.Table.Columns.Each(func(c *ddl.Column) { mainGen.P(`case`, strconv.Quote(c.Field)) for _, a := range c.Aliases { mainGen.P(`,`, strconv.Quote(a)) } mainGen.Pln(codegen.SkipWS(`,"`, c.Pos-1, `"`), `:`) mainGen.Pln(`cm.`, g.goFuncNull(c), `(&e.`, t.GoCamelMaybePrivate(c.Field), `)`) }) mainGen.Pln(`default:`) mainGen.Pln(`return errors.NotFound.Newf("[`+g.Package+`]`, t.EntityName(), `Column %q not found", c)`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Pln(`return errors.WithStack(cm.Err())`) mainGen.Out() } mainGen.Pln(`}`) } func (t *Table) hasPKAutoInc() bool { var hasPKAutoInc bool t.Table.Columns.Each(func(c *ddl.Column) { if c.IsPK() && c.IsAutoIncrement() { hasPKAutoInc = true } if hasPKAutoInc { return } }) return hasPKAutoInc } func (t *Table) fnEntityDBAssignLastInsertID(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureDBAssignLastInsertID| FeatureDB|FeatureDBInsert|FeatureDBUpsert) { return } if !t.hasPKAutoInc() { return } mainGen.C(`AssignLastInsertID updates the increment ID field with the last inserted ID from an INSERT operation.`, `Implements dml.InsertIDAssigner. Auto generated.`) mainGen.Pln(`func (e *`, t.EntityName(), `) AssignLastInsertID(id int64) {`) { mainGen.In() t.Table.Columns.Each(func(c *ddl.Column) { if c.IsPK() && c.IsAutoIncrement() { mainGen.Pln(`e.`, t.GoCamelMaybePrivate(c.Field), ` = `, g.goType(c), `(id)`) } }) mainGen.Out() } mainGen.Pln(`}`) } func (t *Table) fnCollectionDBAssignLastInsertID(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureDBAssignLastInsertID| FeatureDB|FeatureDBInsert|FeatureDBUpsert) { return } if !t.hasPKAutoInc() { return } mainGen.C(`AssignLastInsertID traverses through the slice and sets an incrementing new ID to each entity.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) AssignLastInsertID(id int64) {`) { mainGen.In() mainGen.Pln(`for i:=0 ; i < len(cc.Data); i++ {`) { mainGen.In() mainGen.Pln(`cc.Data[i].AssignLastInsertID(id + int64(i))`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Out() } mainGen.Pln(`}`) } func (t *Table) fnCollectionUniqueGetters(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionUniqueGetters| FeatureDB|FeatureDBSelect|FeatureDBDelete| FeatureDBInsert|FeatureDBUpdate|FeatureDBUpsert) { return } // Generates functions to return all data as a slice from unique/primary // columns. for _, c := range t.Table.Columns.UniqueColumns() { gtn := g.goTypeNull(c) goCamel := strs.ToGoCamelCase(c.Field) mainGen.C(goCamel + `s returns a slice with the data or appends it to a slice.`) mainGen.C(`Auto generated.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) `, goCamel+`s(ret ...`+gtn, `) []`+gtn, ` {`) { mainGen.In() mainGen.Pln(`if cc == nil { return nil }`) mainGen.Pln(`if ret == nil {`) { mainGen.In() mainGen.Pln(`ret = make([]`+gtn, `, 0, len(cc.Data))`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Pln(`for _, e := range cc.Data {`) { mainGen.In() mainGen.Pln(`ret = append(ret, e.`+goCamel, `)`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Pln(`return ret`) mainGen.Out() } mainGen.Pln(`}`) } } func (t *Table) fnCollectionUniquifiedGetters(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionUniquifiedGetters) { return } // Generates functions to return data with removed duplicates from any // column which has set the flag Uniquified. for _, c := range t.Table.Columns.UniquifiedColumns() { goType := g.goType(c) goCamel := strs.ToGoCamelCase(c.Field) mainGen.C(goCamel+`s belongs to the column`, strconv.Quote(c.Field), `and returns a slice or appends to a slice only`, `unique values of that column. The values will be filtered internally in a Go map. No DB query gets`, `executed. Auto generated.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Unique`+goCamel+`s(ret ...`, goType, `) []`, goType, ` {`) { mainGen.In() mainGen.Pln(`if cc == nil { return nil }`) mainGen.Pln(`if ret == nil { ret = make([]`, goType, `, 0, len(cc.Data)) }`) // TODO: a reusable map and use different algorithms depending on // the size of the cc.Data slice. Sometimes a for/for loop runs // faster than a map. goPrimNull := g.toGoPrimitiveFromNull(c) mainGen.Pln(`dupCheck := make(map[`, goType, `]bool, len(cc.Data))`) mainGen.Pln(`for _, e := range cc.Data {`) { mainGen.In() mainGen.Pln(`if !dupCheck[e.`+goPrimNull, `] {`) { mainGen.In() mainGen.Pln(`ret = append(ret, e.`, goPrimNull, `)`) mainGen.Pln(`dupCheck[e.`+goPrimNull, `] = true`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Pln(`return ret`) mainGen.Out() } mainGen.Pln(`}`) } } func (t *Table) fnCollectionFilter(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionFilter) { return } mainGen.C(`Filter filters the current slice by predicate f without memory allocation. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Filter(f func(*`, t.EntityName(), `) bool) *`, t.CollectionName(), ` {`) { mainGen.In() mainGen.Pln(`if cc == nil { return nil }`) mainGen.Pln(`b,i := cc.Data[:0],0`) mainGen.Pln(`for _, e := range cc.Data {`) { mainGen.In() mainGen.Pln(`if f(e) {`) { mainGen.Pln(`b = append(b, e)`) } mainGen.Pln(`}`) // endif mainGen.Pln(`i++`) } mainGen.Out() mainGen.Pln(`}`) // for loop mainGen.Pln(`for i := len(b); i < len(cc.Data); i++ { cc.Data[i] = nil // this should avoid the memory leak }`) mainGen.Pln(`cc.Data = b`) mainGen.Pln(`return cc`) mainGen.Out() } mainGen.Pln(`}`) // function } func (t *Table) fnCollectionEach(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionEach) { return } mainGen.C(`Each will run function f on all items in []*`, t.EntityName(), `. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Each(f func(*`, t.EntityName(), `)) *`, t.CollectionName(), ` {`) { mainGen.Pln(`if cc == nil { return nil }`) mainGen.Pln(`for i := range cc.Data {`) { mainGen.Pln(`f(cc.Data[i])`) } mainGen.Pln(`}`) mainGen.Pln(`return cc`) } mainGen.Pln(`}`) } // Clear because Reset name is used by gogo protobuf func (t *Table) fnCollectionClear(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionClear) { return } mainGen.C(`Clear will reset the data slice or create a new type. Useful for reusing the underlying backing slice array. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Clear() *`, t.CollectionName(), ` { if cc == nil { *cc = `, t.CollectionName(), `{} return cc } if c := cap(cc.Data); c > len(cc.Data) { cc.Data = cc.Data[:c] } for i := 0; i < len(cc.Data); i++ { cc.Data[i] = nil } cc.Data = cc.Data[:0] return cc }`) } func (t *Table) fnCollectionCut(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionCut) { return } mainGen.C(`Cut will remove items i through j-1. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Cut(i, j int) *`, t.CollectionName(), ` {`) { mainGen.In() mainGen.Pln(`z := cc.Data // copy slice header`) mainGen.Pln(`copy(z[i:], z[j:])`) mainGen.Pln(`for k, n := len(z)-j+i, len(z); k < n; k++ {`) { mainGen.In() mainGen.Pln(`z[k] = nil // this avoids the memory leak`) mainGen.Out() } mainGen.Pln(`}`) mainGen.Pln(`z = z[:len(z)-j+i]`) mainGen.Pln(`cc.Data = z`) mainGen.Pln(`return cc`) mainGen.Out() } mainGen.Pln(`}`) } func (t *Table) fnCollectionSwap(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionSwap) { return } mainGen.C(`Swap will satisfy the sort.Interface. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Swap(i, j int) { cc.Data[i], cc.Data[j] = cc.Data[j], cc.Data[i] }`) mainGen.C(`Len will satisfy the sort.Interface. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Len() int { if cc == nil { return 0; }; return len(cc.Data); }`) } func (t *Table) fnCollectionDelete(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionDelete) { return } mainGen.C(`Delete will remove an item from the slice. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Delete(i int) *`, t.CollectionName(), ` {`) { mainGen.Pln(`z := cc.Data // copy the slice header`) mainGen.Pln(`end := len(z) - 1`) mainGen.Pln(`cc.Swap(i, end)`) mainGen.Pln(`copy(z[i:], z[i+1:])`) mainGen.Pln(`z[end] = nil // this should avoid the memory leak`) mainGen.Pln(`z = z[:end]`) mainGen.Pln(`cc.Data = z`) mainGen.Pln(`return cc`) } mainGen.Pln(`}`) } func (t *Table) fnCollectionInsert(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionInsert) { return } mainGen.C(`Insert will place a new item at position i. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Insert(n *`, t.EntityName(), `, i int) *`, t.CollectionName(), ` {`) { mainGen.Pln(`z := cc.Data // copy the slice header`) mainGen.Pln(`z = append(z, &`+t.EntityName(), `{})`) mainGen.Pln(`copy(z[i+1:], z[i:])`) mainGen.Pln(`z[i] = n`) mainGen.Pln(`cc.Data = z`) mainGen.Pln(`return cc`) } mainGen.Pln(`}`) } func (t *Table) fnCollectionAppend(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionAppend) { return } mainGen.C(`Append will add a new item at the end of *`, t.CollectionName(), `. Auto generated via dmlgen.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Append(n ...*`, t.EntityName(), `) *`, t.CollectionName(), ` {`) { mainGen.Pln(`cc.Data = append(cc.Data, n...)`) mainGen.Pln(`return cc`) } mainGen.Pln(`}`) } func (t *Table) fnEntityValidate(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityValidate) { return } fn, ok := g.customCode[t.EntityName()+".Validate"] if !ok { mainGen.C(`This variable can be set in another file to provide a custom validator.`) mainGen.Pln(`var validate`+t.EntityName(), ` func(*`, t.EntityName(), `) error `) } mainGen.C(`Validate runs internal consistency tests.`) mainGen.Pln(`func (e *`, t.EntityName(), `) Validate() error {`) { mainGen.In() mainGen.Pln(`if e == nil { return errors.NotValid.Newf("Type %T cannot be nil", e) }`) if ok { fn(g, t, mainGen) } else { mainGen.Pln(`if validate`+t.EntityName(), ` != nil { return validate`+t.EntityName(), `(e) }`) } mainGen.Out() } mainGen.Pln(`return nil }`) } func (t *Table) fnCollectionValidate(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureCollectionValidate) { return } mainGen.C(`Validate runs internal consistency tests on all items.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) Validate() (err error) {`) { mainGen.In() mainGen.Pln(`if len(cc.Data) == 0 { return nil }`) mainGen.Pln(`for i,ld := 0, len(cc.Data); i < ld && err == nil; i++ {`) { mainGen.Pln(`err = cc.Data[i].Validate()`) } mainGen.Pln(`}`) mainGen.Out() } mainGen.Pln(`return }`) } func (t *Table) fnCollectionDBMapColumns(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureDBMapColumns| FeatureDB|FeatureDBSelect|FeatureDBDelete|FeatureDBInsert|FeatureDBUpdate|FeatureDBUpsert) { return } mainGen.Pln(`func (cc *`, t.CollectionName(), `) scanColumns(cm *dml.ColumnMap, e *`, t.EntityName(), `) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil }`) mainGen.C(`MapColumns implements dml.ColumnMapper interface. Auto generated.`) mainGen.Pln(`func (cc *`, t.CollectionName(), `) MapColumns(cm *dml.ColumnMap) error {`) { mainGen.Pln(`switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } }`) mainGen.Pln(`case dml.ColumnMapScan: if cm.Count == 0 { cc.Clear(); } var e `, t.EntityName(), ` if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e)`) unqiueCols := t.Table.Columns.UniqueColumns() hasUniqueCols := unqiueCols.Len() > 0 mainGen.Pln(hasUniqueCols, `case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c {`) unqiueCols.Each(func(c *ddl.Column) { if !c.IsFloat() { mainGen.P(`case`, strconv.Quote(c.Field)) for _, a := range c.Aliases { mainGen.P(`,`, strconv.Quote(a)) } mainGen.Pln(`:`) mainGen.Pln(`cm = cm.`, g.goFuncNull(c)+`s(cc.`, strs.ToGoCamelCase(c.Field)+`s()...)`) } }) mainGen.Pln(hasUniqueCols, `default: return errors.NotFound.Newf("[`+t.Package+`]`, t.CollectionName(), `Column %q not found", c) } } // end for cm.Next`) mainGen.Pln(`default: return errors.NotSupported.Newf("[` + t.Package + `] Unknown Mode: %q", string(m)) } return cm.Err()`) } mainGen.Pln(`}`) // end func MapColumns } func (t *Table) fnCollectionDBMHandler(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureDB|FeatureDBSelect|FeatureDBDelete| FeatureDBInsert|FeatureDBUpdate|FeatureDBUpsert) { return } var bufPKStructArg strings.Builder var bufPKNames strings.Builder i := 0 tblPkCols := t.Table.Columns.PrimaryKeys() if t.Table.IsView() { tblPkCols = t.Table.Columns.ViewPrimaryKeys() } dbLoadStructArgOrSliceName := t.CollectionName() + "DBLoadArgs" bufPKStructArg.WriteString("type " + dbLoadStructArgOrSliceName + " struct {\n") bufPKStructArg.WriteString("\t_Named_Fields_Required struct{}\n") tblPkCols.Each(func(c *ddl.Column) { if i > 0 { bufPKNames.WriteByte(',') } goNamedField := strs.ToGoCamelCase(c.Field) if tblPkCols.Len() == 1 { dbLoadStructArgOrSliceName = g.goTypeNull(c) } else { bufPKStructArg.WriteString(goNamedField) bufPKStructArg.WriteByte(' ') bufPKStructArg.WriteString(g.goTypeNull(c) + "\n") } bufPKNames.WriteString(goNamedField) i++ }) bufPKStructArg.WriteString("}\n") if i == 0 { mainGen.C("The table/view", t.CollectionName(), "does not have a primary key. Skipping to generate DML functions based on the PK.") mainGen.Pln("\n") return } collectionPTRName := codegen.SkipWS("*", t.CollectionName()) entityEventName := codegen.SkipWS(`event`, t.EntityName(), `Func`) tracingEnabled := t.hasFeature(g, FeatureDBTracing) collectionFuncName := codegen.SkipWS(t.CollectionName(), "SelectAll") dmlEnabled := t.hasFeature(g, FeatureDBSelect) mainGen.Pln(dmlEnabled && tblPkCols.Len() > 1, bufPKStructArg.String()) mainGen.Pln(dmlEnabled, `func (cc `, collectionPTRName, `) DBLoad(ctx context.Context,dbm *DBM, pkIDs []`, dbLoadStructArgOrSliceName, `, opts ...dml.DBRFunc) (err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, t.CollectionName(), "DBLoad", `"`), `) defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `cc.Clear()`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `// put the IDs`, bufPKNames.String(), `into the context as value to search for a cache entry in the event function. if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache }`) if tblPkCols.Len() > 1 { // for tables with more than one PK mainGen.Pln(dmlEnabled, ` cacheKey := `, codegen.SkipWS(`"`, collectionFuncName, "", `"`), ` var args []interface{} if len(pkIDs) > 0 { args = make([]interface{}, 0, len(pkIDs)*`, tblPkCols.Len(), `) for _, pk := range pkIDs {`) tblPkCols.Each(func(c *ddl.Column) { mainGen.Pln(dmlEnabled, `args = append(args, pk.`, strs.ToGoCamelCase(c.Field), `)`) }) mainGen.Pln(dmlEnabled, `} cacheKey = `, codegen.SkipWS(`"`, t.CollectionName(), "SelectByPK", `"`), ` } if _, err = dbm.ConnPool.WithCacheKey(cacheKey, opts...).Load(ctx, cc, args...); err != nil { return errors.WithStack(err) }`) } else { mainGen.Pln(dmlEnabled, `if len(pkIDs) > 0 {`) mainGen.In() { mainGen.Pln(dmlEnabled, `if _, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, t.CollectionName(), "SelectByPK", `"`), `, opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err); }`) } mainGen.Out() mainGen.Pln(dmlEnabled, `} else {`) mainGen.In() { mainGen.Pln(dmlEnabled, `if _, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, collectionFuncName, "", `"`), `, opts...).Load(ctx, cc); err != nil { return errors.WithStack(err); }`) } mainGen.Out() mainGen.Pln(dmlEnabled, `}`) } mainGen.Pln(dmlEnabled, `return errors.WithStack(dbm.`, entityEventName, `(ctx, dml.EventFlagAfterSelect, qo.SkipEvents,cc, nil)) }`) if t.Table.IsView() { // skip here the delete,insert,update and upsert functions. return } dmlEnabled = t.hasFeature(g, FeatureDBDelete) collectionFuncName = codegen.SkipWS(t.EntityName(), "DeleteByPK") mainGen.Pln(dmlEnabled, `func (cc `, collectionPTRName, `) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result,err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, t.CollectionName(), "DeleteByPK", `"`), `) defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if cc == nil { return nil, errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.CollectionName()), `can't be nil") }`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, collectionFuncName, `"`), `, opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.`, entityEventName, `(ctx, dml.EventFlagAfterDelete, qo.SkipEvents,cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil }`) dmlEnabled = t.hasFeature(g, FeatureDBUpdate) collectionFuncName = codegen.SkipWS(t.EntityName(), "UpdateByPK") mainGen.Pln(dmlEnabled, `func (cc `, collectionPTRName, `) DBUpdate(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, t.CollectionName(), "UpdateByPK", `"`), `); defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if cc == nil { return errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.CollectionName()), `can't be nil") }`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) }`) mainGen.Pln(dmlEnabled, `dbr := dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, collectionFuncName, `"`), `, opts...)`) mainGen.Pln(dmlEnabled, `dbrStmt, err := dbr.Prepare(ctx) if err != nil { return errors.WithStack(err) }`) mainGen.Pln(dmlEnabled, `for _, c := range cc.Data { res, err := dbrStmt.ExecContext(ctx, c) if err := dbr.ResultCheckFn(`, constTableName(t.Table.Name), `, 1, res, err); err != nil { return errors.WithStack(err) } }`) mainGen.Pln(dmlEnabled, `return errors.WithStack(dbm.`, entityEventName, `(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents,cc, nil)) }`) dmlEnabled = t.hasFeature(g, FeatureDBInsert) collectionFuncName = codegen.SkipWS(t.EntityName(), "Insert") mainGen.Pln(dmlEnabled, `func (cc `, collectionPTRName, `) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, t.CollectionName(), "Insert", `"`), `); defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if cc == nil { return errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.CollectionName()), `can't be nil") }`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err := dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, collectionFuncName, `"`), `, opts...) res, err := dbr.ExecContext(ctx, cc) if err := dbr.ResultCheckFn(`, constTableName(t.Table.Name), `, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.`, entityEventName, `(ctx, dml.EventFlagAfterInsert, qo.SkipEvents,cc, nil)) }`) dmlEnabled = t.hasFeature(g, FeatureDBUpsert) collectionFuncName = codegen.SkipWS(t.EntityName(), "UpsertByPK") mainGen.Pln(dmlEnabled, `func (cc `, collectionPTRName, `) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, t.CollectionName(), "UpsertByPK", `"`), `); defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if cc == nil { return errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.CollectionName()), `can't be nil") }`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err := dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } dbr := dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, collectionFuncName, `"`), `, opts...) res, err := dbr.ExecContext(ctx, dml.Qualify("", cc)) if err := dbr.ResultCheckFn(`, constTableName(t.Table.Name), `, len(cc.Data), res, err); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.`, entityEventName, `(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents,cc, nil)) }`) } func (t *Table) fnEntityDBMHandler(mainGen *codegen.Go, g *Generator) { if !g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureDB|FeatureDBSelect|FeatureDBDelete| FeatureDBInsert|FeatureDBUpdate|FeatureDBUpsert) { return } var bufPKNamesAsArgs strings.Builder var bufPKStructArg strings.Builder var bufPKNames strings.Builder i := 0 tblPkCols := t.Table.Columns.PrimaryKeys() if t.Table.IsView() { tblPkCols = t.Table.Columns.ViewPrimaryKeys() } dbLoadStructArgOrSliceName := t.EntityName() + "LoadArgs" bufPKStructArg.WriteString("type " + dbLoadStructArgOrSliceName + " struct {\n") bufPKStructArg.WriteString("\t_Named_Fields_Required struct{}\n") loadArgName := "arg" if tblPkCols.Len() == 1 { loadArgName = "primaryKey" } tblPkCols.Each(func(c *ddl.Column) { if i > 0 { bufPKNames.WriteByte(',') bufPKNamesAsArgs.WriteByte(',') } goNamedField := strs.ToGoCamelCase(c.Field) if tblPkCols.Len() == 1 { dbLoadStructArgOrSliceName = g.goTypeNull(c) bufPKNames.WriteString(loadArgName) } else { bufPKStructArg.WriteString(goNamedField) bufPKStructArg.WriteByte(' ') bufPKStructArg.WriteString(g.goTypeNull(c) + "\n") bufPKNames.WriteString(loadArgName + "." + goNamedField) } bufPKNamesAsArgs.WriteString("e.") bufPKNamesAsArgs.WriteString(strs.ToGoCamelCase(c.Field)) i++ }) bufPKStructArg.WriteString("}\n") if i == 0 { mainGen.C("The table/view", t.EntityName(), "does not have a primary key. SKipping to generate DML functions based on the PK.") mainGen.Pln("\n") return } entityPTRName := codegen.SkipWS("*", t.EntityName()) entityEventName := codegen.SkipWS(`event`, t.EntityName(), `Func`) tracingEnabled := t.hasFeature(g, FeatureDBTracing) entityFuncName := codegen.SkipWS(t.EntityName(), "SelectByPK") dmlEnabled := t.hasFeature(g, FeatureDBSelect) mainGen.Pln(dmlEnabled && tblPkCols.Len() > 1, bufPKStructArg.String()) mainGen.Pln(dmlEnabled, `func (e `, entityPTRName, `) Load(ctx context.Context,dbm *DBM, `, loadArgName, ` `, dbLoadStructArgOrSliceName, `, opts ...dml.DBRFunc) (err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, entityFuncName, `"`), `) defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if e == nil { return errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.EntityName()), `can't be nil") }`) mainGen.Pln(dmlEnabled && len(t.availableRelationships) > 0, `e.setRelationParent()`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `// put the IDs`, bufPKNames.String(), `into the context as value to search for a cache entry in the event function. if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, entityFuncName, `"`), `, opts...).Load(ctx, e, `, &bufPKNames, `); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.`, entityEventName, `(ctx, dml.EventFlagAfterSelect, qo.SkipEvents,nil, e)) }`) if t.Table.IsView() { // skip here the delete,insert,update and upsert functions. return } dmlEnabled = t.hasFeature(g, FeatureDBDelete) entityFuncName = codegen.SkipWS(t.EntityName(), "DeleteByPK") mainGen.Pln(dmlEnabled, `func (e `, entityPTRName, `) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, entityFuncName, `"`), `) defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if e == nil { return nil, errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.EntityName()), `can't be nil") }`) mainGen.Pln(dmlEnabled && len(t.availableRelationships) > 0, `e.setRelationParent()`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, entityFuncName, `"`), `, opts...).ExecContext(ctx, `, bufPKNamesAsArgs.String(), `); err != nil { return nil, errors.WithStack(err) } if err = dbm.`, entityEventName, `(ctx, dml.EventFlagAfterDelete, qo.SkipEvents,nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil }`) dmlEnabled = t.hasFeature(g, FeatureDBUpdate) entityFuncName = codegen.SkipWS(t.EntityName(), "UpdateByPK") mainGen.Pln(dmlEnabled, `func (e `, entityPTRName, `) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, entityFuncName, `"`), `); defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if e == nil { return nil, errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.EntityName()), `can't be nil") }`) mainGen.Pln(dmlEnabled && len(t.availableRelationships) > 0, `e.setRelationParent()`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, entityFuncName, `"`), `, opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.`, entityEventName, `(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents,nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil }`) dmlEnabled = t.hasFeature(g, FeatureDBInsert) entityFuncName = codegen.SkipWS(t.EntityName(), "Insert") mainGen.Pln(dmlEnabled, `func (e `, entityPTRName, `) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, entityFuncName, `"`), `); defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if e == nil { return nil, errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.EntityName()), `can't be nil") }`) mainGen.Pln(dmlEnabled && len(t.availableRelationships) > 0, `e.setRelationParent()`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, entityFuncName, `"`), `, opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.`, entityEventName, `(ctx, dml.EventFlagAfterInsert, qo.SkipEvents,nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil }`) dmlEnabled = t.hasFeature(g, FeatureDBUpsert) entityFuncName = codegen.SkipWS(t.EntityName(), "UpsertByPK") mainGen.Pln(dmlEnabled, `func (e `, entityPTRName, `) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) {`) mainGen.Pln(dmlEnabled && tracingEnabled, ` ctx, span := dbm.option.Trace.Start(ctx, `, codegen.SkipWS(`"`, entityFuncName, `"`), `); defer func(){ cstrace.Status(span, err, ""); span.End(); }()`) mainGen.Pln(dmlEnabled, `if e == nil { return nil, errors.NotValid.Newf(`, codegen.SkipWS(`"`, t.EntityName()), `can't be nil") }`) mainGen.Pln(dmlEnabled && len(t.availableRelationships) > 0, `e.setRelationParent()`) mainGen.Pln(dmlEnabled, `qo := dml.FromContextQueryOptions(ctx)`) mainGen.Pln(dmlEnabled, `if err = dbm.`, entityEventName, `(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey(`, codegen.SkipWS(`"`, entityFuncName, `"`), `, opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.`, entityEventName, `(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents,nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil }`) } func (t *Table) fnDBMOptionsSQLBuildQueries(mainGen *codegen.Go, g *Generator) { tblPKLen := t.Table.Columns.PrimaryKeys().Len() tblPK := t.Table.Columns.PrimaryKeys() if t.Table.IsView() { tblPKLen = t.Table.Columns.ViewPrimaryKeys().Len() tblPK = t.Table.Columns.ViewPrimaryKeys() } var pkWhereIN strings.Builder var pkWhereEQ strings.Builder if tblPKLen == 1 { pkWhereIN.WriteString("\ndml.Column(`" + strings.Join(tblPK.FieldNames(), "`,`") + "`).In().") pkWhereIN.WriteString("PlaceHolder(),\n") pkWhereEQ.WriteString("\ndml.Column(`" + strings.Join(tblPK.FieldNames(), "`,`") + "`).Equal().") pkWhereEQ.WriteString("PlaceHolder(),\n") } else { pkWhereIN.WriteString("\ndml.Columns(`" + strings.Join(tblPK.FieldNames(), "`,`") + "`).In().") pkWhereIN.WriteString("Tuples(),\n") pkWhereEQ.WriteString("\ndml.Columns(`" + strings.Join(tblPK.FieldNames(), "`,`") + "`).Equal().") pkWhereEQ.WriteString("Tuples(),\n") } mainGen.Pln(tblPKLen > 0 && t.hasFeature(g, FeatureDBSelect|FeatureCollectionStruct), codegen.SkipWS(`"`, t.CollectionName(), `SelectAll"`), `: dbmo.InitSelectFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Select("*")),`) mainGen.Pln(tblPKLen > 0 && t.hasFeature(g, FeatureDBSelect|FeatureEntityStruct|FeatureCollectionStruct), codegen.SkipWS(`"`, t.CollectionName(), `SelectByPK"`), `: dbmo.InitSelectFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Select("*")).Where(`, pkWhereIN.String(), `),`) mainGen.Pln(tblPKLen > 0 && t.hasFeature(g, FeatureDBSelect|FeatureEntityStruct|FeatureCollectionStruct), codegen.SkipWS(`"`, t.EntityName(), `SelectByPK"`), `: dbmo.InitSelectFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Select("*")).Where(`, pkWhereEQ.String(), `),`) if t.Table.IsView() { return } mainGen.Pln(t.hasFeature(g, FeatureDBUpdate|FeatureEntityStruct|FeatureCollectionStruct), codegen.SkipWS(`"`, t.EntityName(), `UpdateByPK"`), `: dbmo.InitUpdateFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Update().Where(`, pkWhereEQ.String(), `)),`) mainGen.Pln(t.hasFeature(g, FeatureDBDelete|FeatureEntityStruct|FeatureCollectionStruct), codegen.SkipWS(`"`, t.EntityName(), `DeleteByPK"`), `: dbmo.InitDeleteFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Delete().Where(`, pkWhereIN.String(), `)),`) mainGen.Pln(t.hasFeature(g, FeatureDBInsert|FeatureEntityStruct|FeatureCollectionStruct), codegen.SkipWS(`"`, t.EntityName(), `Insert"`), `: dbmo.InitInsertFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Insert()),`) mainGen.Pln(t.hasFeature(g, FeatureDBUpsert|FeatureEntityStruct|FeatureCollectionStruct), codegen.SkipWS(`"`, t.EntityName(), `UpsertByPK"`), `: dbmo.InitInsertFn(tbls.MustTable(`, constTableName(t.Table.Name), `).Insert()).OnDuplicateKey(),`) // foreign keys if g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityRelationships) && len(t.availableRelationships) > 0 { mainGen.C(`<FOREIGN_KEY_QUERIES`, t.Table.Name, `>`) var fkWhereEQ bytes.Buffer for _, rs := range t.availableRelationships { fkWhereEQ.WriteString("\ndml.Column(`" + rs.columnName + "`).Equal().PlaceHolder(),\n") // DELETE FROM mainGen.Pln(codegen.SkipWS(`"`, rs.mappedStructFieldName, `DeleteByFK"`), `: dbmo.InitDeleteFn(tbls.MustTable(`, constTableName(rs.tableName), `).Delete().Where(`, fkWhereEQ.String(), `)),`) // SELECT FROM mainGen.Pln(codegen.SkipWS(`"`, rs.mappedStructFieldName, `SelectByFK"`), `: dbmo.InitSelectFn(tbls.MustTable(`, constTableName(rs.tableName), `).Select("*").Where(`, fkWhereEQ.String(), `)),`) // UPDATE not needed as it uses the default UPDATE fkWhereEQ.Reset() } mainGen.C(`</FOREIGN_KEY_QUERIES`, t.Table.Name, `>`) } } func (t *Table) generateTestOther(testGen *codegen.Go, g *Generator) (codeWritten int) { if g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityEmpty) { testGen.Pln(`t.Run("` + t.EntityName() + `_Empty", func(t *testing.T) {`) { testGen.Pln(`e:= new(`, t.EntityName(), `)`) testGen.Pln(`assert.NoError(t, ps.FakeData(e))`) testGen.Pln(`e.Empty()`) testGen.Pln(`assert.Exactly(t, *e, `, t.EntityName(), `{})`) } testGen.Pln(`})`) // end t.Run codeWritten++ } if g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityCopy) { testGen.Pln(`t.Run("` + t.EntityName() + `_Copy", func(t *testing.T) {`) { testGen.Pln(`e:= new(`, t.EntityName(), `)`) testGen.Pln(`assert.NoError(t, ps.FakeData(e))`) testGen.Pln(`e2 := e.Copy()`) testGen.Pln(`assert.Exactly(t, e, e2)`) testGen.Pln(`assert.NoError(t, ps.FakeData(e))`) testGen.Pln(`assert.NotEqual(t, e, e2)`) } testGen.Pln(`})`) // end t.Run codeWritten++ } if g.hasFeature(t.featuresInclude, t.featuresExclude, FeatureEntityValidate) { testGen.Pln(`t.Run("` + t.CollectionName() + `_Validate", func(t *testing.T) {`) { testGen.Pln(`c := `, t.CollectionName(), `{ Data: []*`, t.EntityName(), `{nil} }`) testGen.Pln(`assert.True(t, errors.NotValid.Match(c.Validate()))`) } testGen.Pln(`})`) // end t.Run codeWritten++ } // more feature tests to follow return } func (t *Table) generateTestDB(testGen *codegen.Go) { testGen.Pln(`t.Run("` + strs.ToGoCamelCase(t.Table.Name) + `_Entity", func(t *testing.T) {`) testGen.Pln(`tbl := tbls.MustTable(TableName`+strs.ToGoCamelCase(t.Table.Name), `)`) testGen.Pln(`selOneRow := tbl.Select("*").Where(`) for _, c := range t.Table.Columns { if c.IsPK() && c.IsAutoIncrement() { testGen.Pln(`dml.Column(`, strconv.Quote(c.Field), `).Equal().PlaceHolder(),`) } } testGen.Pln(`)`) testGen.Pln(`selTenRows := tbl.Select("*").Where(`) for _, c := range t.Table.Columns { if c.IsPK() && c.IsAutoIncrement() { testGen.Pln(`dml.Column(`, strconv.Quote(c.Field), `).LessOrEqual().Int(10),`) } } testGen.Pln(`)`) testGen.Pln(`selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow)`) testGen.Pln(`defer selOneRowDBR.Close()`) testGen.Pln(`selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows)`) if t.HasAutoIncrement < 2 { testGen.C(`this table/view does not support auto_increment`) testGen.Pln(`entCol := New`+t.CollectionName(), `()`) testGen.Pln(`rowCount, err := selTenRowsDBR.Load(ctx, entCol)`) testGen.Pln(`assert.NoError(t, err)`) testGen.Pln(`t.Logf("Collection load rowCount: %d", rowCount)`) } else { testGen.Pln(`entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx,tbl.Insert().BuildValues())`) testGen.Pln(`for i := 0; i < 9; i++ {`) { testGen.In() testGen.Pln(`entIn := new(`, strs.ToGoCamelCase(t.Table.Name), `)`) testGen.Pln(`assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i)`) testGen.Pln(`lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.` + strs.ToGoCamelCase(t.Table.Name) + `_Entity")(entINSERTStmtA.ExecContext(ctx,dml.Qualify("", entIn)))`) testGen.Pln(`entINSERTStmtA.Reset()`) testGen.Pln(`entOut := new(`, strs.ToGoCamelCase(t.Table.Name), `)`) testGen.Pln(`rowCount, err := selOneRowDBR.Load(ctx, entOut, lID)`) testGen.Pln(`assert.NoError(t, err)`) testGen.Pln(`assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i)`) for _, c := range t.Table.Columns { fn := t.GoCamelMaybePrivate(c.Field) switch { case c.IsTime(): // skip comparison as we can't mock time (yet) :-( case c.IsChar(): testGen.Pln(`assert.ExactlyLength(t,`, c.CharMaxLength.Int64, `, `, `&entIn.`, fn, `,`, `&entOut.`, fn, `,`, `"IDX%d:`, fn, `should match", lID)`) case !c.IsSystemVersioned(): testGen.Pln(`assert.Exactly(t, entIn.`, fn, `,`, `entOut.`, fn, `,`, `"IDX%d:`, fn, `should match", lID)`) default: testGen.C(`ignoring:`, c.Field) } } testGen.Out() } testGen.Pln(`}`) // endfor testGen.Pln(`dmltest.Close(t, entINSERTStmtA)`) testGen.Pln(`entCol := New`+t.CollectionName(), `()`) testGen.Pln(`rowCount, err := selTenRowsDBR.Load(ctx, entCol)`) testGen.Pln(`assert.NoError(t, err)`) testGen.Pln(`t.Logf("Collection load rowCount: %d", rowCount)`) testGen.Pln(`colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues())`) testGen.Pln(`lID := dmltest.CheckLastInsertID(t, "Error: `, t.CollectionName(), `")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol)))`) testGen.Pln(`t.Logf("Last insert ID into: %d", lID)`) } testGen.Pln(`})`) } <|start_filename|>sql/dml/update.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "github.com/corestoreio/errors" ) // Update contains the logic for an UPDATE statement. // TODO: add UPDATE JOINS type Update struct { BuilderBase BuilderConditional // SetClauses contains the column/argument association. For each column // there must be one argument. SetClauses Conditions } // NewUpdate creates a new Update object. func NewUpdate(table string) *Update { return &Update{ BuilderBase: BuilderBase{ Table: MakeIdentifier(table), }, } } // Alias sets an alias for the table name. func (b *Update) Alias(alias string) *Update { b.Table.Aliased = alias return b } // Unsafe see BuilderBase.IsUnsafe which weakens security when building the SQL // string. This function must be called before calling any other function. func (b *Update) Unsafe() *Update { b.IsUnsafe = true return b } // AddClauses appends a column/value pair for the statement. func (b *Update) AddClauses(c ...*Condition) *Update { b.SetClauses = append(b.SetClauses, c...) return b } // AddColumns adds columns whose values gets later derived from a ColumnMapper. // Those columns will get passed to the ColumnMapper implementation. func (b *Update) AddColumns(columnNames ...string) *Update { for _, col := range columnNames { b.SetClauses = append(b.SetClauses, Column(col)) } return b } // SetColumns resets the SetClauses slice and adds the columns. Same behaviour // as AddColumns. func (b *Update) SetColumns(columnNames ...string) *Update { b.SetClauses = b.SetClauses[:0] for _, col := range columnNames { b.SetClauses = append(b.SetClauses, Column(col)) } return b } // Where appends a WHERE clause to the statement func (b *Update) Where(wf ...*Condition) *Update { b.Wheres = append(b.Wheres, wf...) return b } // OrderBy appends columns to the ORDER BY statement for ascending sorting. A // column gets always quoted if it is a valid identifier otherwise it will be // treated as an expression. When you use ORDER BY or GROUP BY to sort a column // in a UPDATE, the server sorts values using only the initial number of bytes // indicated by the max_sort_length system variable. // A column name can also contain the suffix words " ASC" or " DESC" to indicate // the sorting. This avoids using the method OrderByDesc when sorting certain // columns descending. func (b *Update) OrderBy(columns ...string) *Update { b.OrderBys = b.OrderBys.AppendColumns(b.IsUnsafe, columns...) return b } // OrderByDesc appends columns to the ORDER BY statement for descending sorting. // A column gets always quoted if it is a valid identifier otherwise it will be // treated as an expression. When you use ORDER BY or GROUP BY to sort a column // in a UPDATE, the server sorts values using only the initial number of bytes // indicated by the max_sort_length system variable. func (b *Update) OrderByDesc(columns ...string) *Update { b.OrderBys = b.OrderBys.AppendColumns(b.IsUnsafe, columns...).applySort(len(columns), sortDescending) return b } // Limit sets a limit for the statement; overrides any existing LIMIT func (b *Update) Limit(limit uint64) *Update { b.LimitCount = limit b.LimitValid = true return b } // ToSQL converts the select statement into a string and returns its arguments. func (b *Update) ToSQL() (string, []interface{}, error) { rawSQL, err := b.buildToSQL(b) if err != nil { return "", nil, errors.WithStack(err) } return rawSQL,nil, nil } // ToSQL serialized the Update to a SQL string // It returns the string with placeholders and a slice of query arguments func (b *Update) toSQL(buf *bytes.Buffer, placeHolders []string) ([]string, error) { if b.Table.Name == "" { return nil, errors.Empty.Newf("[dml] Update: Table at empty") } if len(b.SetClauses) == 0 { return nil, errors.Empty.Newf("[dml] Update: No columns specified") } buf.WriteString("UPDATE ") _, _ = b.Table.writeQuoted(buf, nil) buf.WriteString(" SET ") placeHolders, err := b.SetClauses.writeSetClauses(buf, placeHolders) if err != nil { return nil, errors.WithStack(err) } // Write WHERE clause if we have any fragments placeHolders, err = b.Wheres.write(buf, 'w', placeHolders, b.isWithDBR) if err != nil { return nil, errors.WithStack(err) } sqlWriteOrderBy(buf, b.OrderBys, false) sqlWriteLimitOffset(buf, b.LimitValid, false, 0, b.LimitCount) return placeHolders, nil } // Clone creates a clone of the current object, leaving fields DB and Log // untouched. func (b *Update) Clone() *Update { if b == nil { return nil } c := *b c.BuilderBase = b.BuilderBase.Clone() c.BuilderConditional = b.BuilderConditional.Clone() c.SetClauses = b.SetClauses.Clone() return &c } <|start_filename|>storage/objcache/redis_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 redis csall package objcache_test import ( "context" "fmt" "testing" "time" "github.com/alicebob/miniredis" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/objcache" "github.com/corestoreio/pkg/util/assert" "github.com/corestoreio/pkg/util/strs" "github.com/gomodule/redigo/redis" ) func TestWithRedisURL_SetGet_Success(t *testing.T) { t.Parallel() t.Run("miniredis", func(t *testing.T) { mr := miniredis.NewMiniRedis() if err := mr.Start(); err != nil { t.Fatal(err) } defer mr.Close() redConURL := "redis://" + mr.Addr() testExpiration(t, func() { mr.FastForward(time.Second * 2) }, objcache.NewRedisByURLClient(redConURL), newSrvOpt(JSONCodec{})) }) t.Run("real redis integration", func(t *testing.T) { redConURL := lookupRedisEnv(t) testExpiration(t, func() { time.Sleep(time.Second * 2) }, objcache.NewRedisByURLClient(redConURL), newSrvOpt(JSONCodec{})) }) } func TestWithRedisURL_Get_NotFound_Mock(t *testing.T) { t.Parallel() mr := miniredis.NewMiniRedis() assert.NoError(t, mr.Start()) defer mr.Close() p, err := objcache.NewService(nil, objcache.NewRedisByURLClient("redis://"+mr.Addr()), newSrvOpt(JSONCodec{})) assert.NoError(t, err) defer func() { assert.NoError(t, p.Close()) }() key := strs.RandAlnum(30) var newVal float64 err = p.Get(context.TODO(), key, &newVal) assert.NoError(t, err, "Error: %+v", err) assert.Empty(t, newVal) } func TestWithRedisURLURL_ConFailure_Dial(t *testing.T) { t.Parallel() p, err := objcache.NewService(nil, objcache.NewRedisClient(&redis.Pool{ Dial: func() (redis.Conn, error) { return redis.Dial("tcp", "127.0.0.1:53344") }, // random port }, &objcache.RedisOption{}), newSrvOpt(JSONCodec{})) assert.True(t, errors.Fatal.Match(err), "Error: %s", err) assert.True(t, p == nil, "p is not nil") } func TestWithRedisURL_ConFailure(t *testing.T) { t.Parallel() var dialErrors = []struct { rawurl string errBhf errors.Kind }{ { "localhost", errors.NotSupported, // "invalid redis URL scheme", }, // The error message for invalid hosts is different in different // versions of Go, so just check that there is an error message. { "redis://weird url", errors.Fatal, }, { "redis://foo:bar:baz", errors.Fatal, }, { "http://www.google.com", errors.NotSupported, // "invalid redis URL scheme: http", }, { "redis://localhost:6379?db=", errors.Fatal, // "invalid database: abc123", }, } for i, test := range dialErrors { p, err := objcache.NewService(nil, objcache.NewRedisByURLClient(test.rawurl), newSrvOpt(JSONCodec{})) if test.errBhf > 0 { assert.True(t, test.errBhf.Match(err), "Index %d Error %+v", i, err) assert.Nil(t, p, "Index %d", i) } else { assert.NoError(t, err, "Index %d", i) assert.NotNil(t, p, "Index %d", i) } } } func TestWithRedisURL_ComplexParallel(t *testing.T) { mr := miniredis.NewMiniRedis() assert.NoError(t, mr.Start()) defer mr.Close() redConURL := fmt.Sprintf("redis://%s/?db=2", mr.Addr()) newServiceComplexParallelTest(t, objcache.NewRedisByURLClient(redConURL), nil) } func TestWithRedisURLMock_Delete(t *testing.T) { mr := miniredis.NewMiniRedis() assert.NoError(t, mr.Start()) defer mr.Close() redConURL := fmt.Sprintf("redis://%s/?db=2", mr.Addr()) newTestServiceDelete(t, objcache.NewRedisByURLClient(redConURL)) } func TestWithRedisURLReal_Delete(t *testing.T) { redConURL := lookupRedisEnv(t) newTestServiceDelete(t, objcache.NewRedisByURLClient(redConURL)) } <|start_filename|>sql/dml/naming.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "strings" "unicode" "unicode/utf8" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/util/bufferpool" ) const ( quote = "`" quoteRune = '`' ) // Quoter at the quoter to use for quoting text; use Mysql quoting by default. var Quoter = MysqlQuoter{ replacer: strings.NewReplacer(quote, ""), } // id is an identifier for table name or a column name or an alias for a sub // query. type id struct { // Derived Tables (Subqueries in the FROM Clause). A derived table is a // subquery in a SELECT statement FROM clause. Derived tables can return a // scalar, column, row, or table. Ignored in any other case. DerivedTable *Select // Name can be any kind of SQL expression or a valid identifier. It gets // quoted when `IsLeftExpression` is false. Name string // Expression has precedence over the `Name` field. Each line in an expression // gets written unchanged to the final SQL string. Expression string // Aliased must be a valid identifier allowed for alias usage. As soon as the field `Aliased` has been set // it gets append to the Name and Expression field: "sql AS Aliased" Aliased string // Sort applies only to GROUP BY and ORDER BY clauses. 'd'=descending, // 0=default or nothing; 'a'=ascending. Sort byte } const ( sortDescending byte = 'd' sortAscending byte = 'a' ) // MakeIdentifier creates a new quoted name with an optional alias `a`, which can be // empty. func MakeIdentifier(name string) id { return id{Name: name} } // Alias sets the aliased name for the `Name` field. func (a id) Alias(alias string) id { a.Aliased = alias; return a } // Clone creates a new object and takes care of a cloned DerivedTable field. func (a id) Clone() id { if nil != a.DerivedTable { a.DerivedTable = a.DerivedTable.Clone() } return a } // uncomment this functions and its test once needed // MakeExpressionAlias creates a new unquoted expression with an optional alias // `a`, which can be empty. // func MakeExpressionAlias(expression []string, a string) identifier { // return identifier{ // Expression: expression, // Aliased: a, // } //} func (a id) isEmpty() bool { return a.Name == "" && a.DerivedTable == nil && a.Expression == "" } // qualifier returns the correct qualifier for an identifier func (a id) qualifier() string { if a.Aliased != "" { return a.Aliased } return a.Name } // String returns the correct stringyfied statement. func (a id) String() string { if a.Expression != "" { buf := bufferpool.Get() defer bufferpool.Put(buf) buf.WriteString(a.Expression) buf.WriteString(" AS ") Quoter.quote(buf, a.Aliased) return buf.String() } return a.QuoteAs() } // NameAlias always quuotes the name and the alias func (a id) QuoteAs() string { return Quoter.NameAlias(a.Name, a.Aliased) } // writeQuoted writes the quoted table and its maybe alias into w. func (a id) writeQuoted(w *bytes.Buffer, placeHolders []string) (_ []string, err error) { if a.DerivedTable != nil { w.WriteByte('(') if placeHolders, err = a.DerivedTable.toSQL(w, placeHolders); err != nil { return nil, errors.WithStack(err) } w.WriteByte(')') w.WriteString(" AS ") Quoter.quote(w, a.Aliased) return placeHolders, nil } if a.Expression != "" { writeExpression(w, a.Expression, nil) } else { Quoter.WriteIdentifier(w, a.Name) } if a.Aliased != "" { w.WriteString(" AS ") Quoter.quote(w, a.Aliased) } if a.Sort == sortAscending { w.WriteString(" ASC") } if a.Sort == sortDescending { w.WriteString(" DESC") } return placeHolders, nil } // ids is a slice of identifiers. `idc` in the receiver means id-collection. type ids []id func (idc ids) Clone() ids { if idc == nil { return nil } c := make(ids, len(idc)) for idx, ido := range idc { c[idx] = ido.Clone() } return c } // writeQuoted writes all identifiers comma separated and quoted into w. func (idc ids) writeQuoted(w *bytes.Buffer, placeHolders []string) (_ []string, err error) { for i, a := range idc { if i > 0 { w.WriteString(", ") } if placeHolders, err = a.writeQuoted(w, placeHolders); err != nil { return nil, errors.WithStack(err) } } return placeHolders, nil } // setSort applies to last n items the sort order `sort` in reverse iteration. // Usuallay `lastNindexes` is len(object) because we decrement 1 from // `lastNindexes`. This function panics when lastNindexes does not match the // length of `identifiers`. func (idc ids) applySort(lastNindexes int, sort byte) ids { to := len(idc) - lastNindexes for i := len(idc) - 1; i >= to; i-- { idc[i].Sort = sort } return idc } // AppendColumns adds new columns to the identifier slice. If a column name is // not a valid identifier that column gets switched into an expression. You // should use this function when no arguments should be attached to an // expression, otherwise use the function appendConditions. If a column name // contains " ASC" or " DESC" as a suffix, the internal sorting flag gets set // and the words ASC or DESC removed. func (idc ids) AppendColumns(isUnsafe bool, columns ...string) ids { if cap(idc) == 0 { idc = make(ids, 0, len(columns)*2) } for _, c := range columns { var sorting byte switch { case strings.HasSuffix(c, " ASC"): c = c[:len(c)-4] sorting = sortAscending case strings.HasSuffix(c, " DESC"): c = c[:len(c)-5] sorting = sortDescending } ident := id{Name: c, Sort: sorting} if isUnsafe && isValidIdentifier(c) != 0 { ident.Expression = ident.Name ident.Name = "" } idc = append(idc, ident) } return idc } // AppendColumnsAliases expects a balanced slice where i=column name and // i+1=alias name. An imbalanced slice will cause a panic. If a column name is // not valid identifier that column gets switched into an expression. The alias // does not change. You should use this function when no arguments should be // attached to an expression, otherwise use the function appendConditions. func (idc ids) AppendColumnsAliases(isUnsafe bool, columns ...string) ids { if (len(columns) % 2) == 1 { // A programmer made an error panic(errors.Mismatch.Newf("[dml] Expecting a balanced slice! Got: %v", columns)) } if cap(idc) == 0 { idc = make(ids, 0, len(columns)/2) } for i := 0; i < len(columns); i = i + 2 { ident := id{Name: columns[i], Aliased: columns[i+1]} if isUnsafe && isValidIdentifier(ident.Name) != 0 { ident.Expression = ident.Name ident.Name = "" } idc = append(idc, ident) } return idc } // appendConditions adds an expression with arguments. SubSelects are not yet // supported. You should use this function when arguments should be attached to // the expression, otherwise use the function AppendColumns*. func (idc ids) appendConditions(expressions Conditions) (ids, error) { buf := bufferpool.Get() for _, e := range expressions { idf := id{Name: e.Left, Aliased: e.Aliased} if e.IsLeftExpression { idf.Expression = idf.Name idf.Name = "" if len(e.Right.args) > 0 { if err := writeInterpolate(buf, idf.Expression, e.Right.args); err != nil { bufferpool.Put(buf) return nil, errors.Wrapf(err, "[dml] ids.appendConditions with expression: %q", idf.Expression) } idf.Expression = buf.String() buf.Reset() } } idc = append(idc, idf) } bufferpool.Put(buf) return idc, nil } // MysqlQuoter implements Mysql-specific quoting type MysqlQuoter struct { replacer *strings.Replacer } func (mq MysqlQuoter) unQuote(s string) string { if strings.IndexByte(s, quoteRune) == -1 { return s } return mq.replacer.Replace(s) } func (mq MysqlQuoter) quote(w *bytes.Buffer, str string) { w.WriteByte(quoteRune) w.WriteString(mq.unQuote(str)) w.WriteByte(quoteRune) } func (mq MysqlQuoter) writeQualifierName(w *bytes.Buffer, q, n string) { mq.quote(w, q) w.WriteByte('.') mq.quote(w, n) } // Name quotes securely a name. // Name("tableName") => `tableName` // Name("table`Name") => `tableName` // https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html func (mq MysqlQuoter) Name(n string) string { return quote + mq.unQuote(n) + quote } // QualifierName quotes securely a qualifier and its name. // QualifierName("dbName", "tableName") => `dbName`.`tableName` // QualifierName("db`Name", "`tableName`") => `dbName`.`tableName` // https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html func (mq MysqlQuoter) QualifierName(q, n string) string { if q == "" { return mq.Name(n) } // return mq.Name(q) + "." + mq.Name(n) <-- too slow, too many allocs return quote + mq.unQuote(q) + quote + "." + quote + mq.unQuote(n) + quote } // WriteQualifierName same as function QualifierName but writes into w. func (mq MysqlQuoter) WriteQualifierName(w *bytes.Buffer, qualifier, name string) { if qualifier == "" { mq.quote(w, name) return } mq.quote(w, qualifier) w.WriteByte('.') mq.quote(w, name) } // NameAlias quotes with back ticks and splits at a dot into the qualified or // unqualified identifier. First argument table and/or column name (separated by // a dot) and second argument can be an alias. Both parts will get quoted. // NameAlias("f", "g") // "`f` AS `g`" // NameAlias("e.entity_id", "ee") // `e`.`entity_id` AS `ee` // NameAlias("e.entity_id", "") // `e`.`entity_id` func (mq MysqlQuoter) NameAlias(name, alias string) string { buf := bufferpool.Get() mq.WriteIdentifier(buf, name) if alias != "" { buf.WriteString(" AS ") Quoter.quote(buf, alias) } x := buf.String() bufferpool.Put(buf) return x } // WriteIdentifier quotes with back ticks and splits at a dot into the qualified // or unqualified identifier. First argument table and/or column name (separated // by a dot). It quotes always and each part. If a string contains quotes, they // won't get stripped. // WriteIdentifier(&buf,"tableName.ColumnName") -> `tableName`.`ColumnName` func (mq MysqlQuoter) WriteIdentifier(w *bytes.Buffer, name string) { switch { case name == "": return case name == sqlStrNullUC: // see calling func sqlIfNullQuote2 w.WriteString(name) return case strings.HasPrefix(name, quote) && strings.HasSuffix(name, quote): // not really secure // checks if there are quotes at the beginning and at the end. no white spaces allowed. w.WriteString(name) // already quoted return case strings.IndexByte(name, '.') == -1: // must be quoted mq.quote(w, name) return } if dotIndex := strings.IndexByte(name, '.'); dotIndex > 0 && dotIndex+1 < len(name) { // dot at a beginning of a string is illegal and at the end mq.quote(w, name[:dotIndex]) w.WriteByte('.') if a := name[dotIndex+1:]; a == sqlStar { w.WriteByte('*') } else { mq.quote(w, name[dotIndex+1:]) } return } mq.quote(w, name) } // ColumnsWithQualifier prefixes all columns in the slice `cols` with a qualifier and applies backticks. If a column name has already been // prefixed with a qualifier or an alias it will be ignored. This functions modifies // the argument slice `cols`. func (mq MysqlQuoter) ColumnsWithQualifier(t string, cols ...string) []string { for i, c := range cols { switch { case strings.IndexByte(c, quoteRune) >= 0: cols[i] = c case strings.IndexByte(c, '.') > 0: cols[i] = mq.NameAlias(c, "") default: cols[i] = mq.QualifierName(t, c) } } return cols } // MaxIdentifierLength see http://dev.mysql.com/doc/refman/5.7/en/identifiers.html const MaxIdentifierLength = 64 const dummyQualifier = "X" // just a dummy value, can be optimized later // IsValidIdentifier checks the permissible syntax for identifiers. Certain // objects within MySQL, including database, table, index, column, alias, view, // stored procedure, partition, tablespace, and other object names are known as // identifiers. ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, // underscore) Max length 63 characters. // It is recommended that you do not use names that begin with Me or MeN, where // M and N are integers. For example, avoid using 1e as an identifier, because // an expression such as 1e+3 is ambiguous. Depending on context, it might be // interpreted as the expression 1e + 3 or as the number 1e+3. // // Returns 0 if the identifier is valid. // // http://dev.mysql.com/doc/refman/5.7/en/identifiers.html func IsValidIdentifier(objectName string) (err error) { if v := isValidIdentifier(objectName); v != 0 { err = errors.NotValid.Newf("[dml] Invalid identifier %q (Case %d)", objectName, v) } return } func isValidIdentifier(s string) int8 { if s == sqlStar { return 0 } qualifier := dummyQualifier if i := strings.IndexByte(s, '.'); i >= 0 { qualifier = s[:i] s = s[i+1:] } validQualifier := isNameValid(qualifier) if validQualifier == 0 && s == sqlStar { return 0 } if validQualifier > 0 { return validQualifier } return isNameValid(s) } // isNameValid returns 0 if the name is valid or an error number identifying // where the name becomes invalid. func isNameValid(name string) int8 { if name == dummyQualifier { return 0 } ln := len(name) if ln > MaxIdentifierLength || name == "" { return 1 } pos := 0 for pos < ln { r, w := utf8.DecodeRuneInString(name[pos:]) if pos == 0 && unicode.IsDigit(r) { return 3 } pos += w if !mapAlNum(r) { return 2 } } return 0 } func mapAlNum(r rune) bool { var ok bool switch { case '0' <= r && r <= '9': ok = true case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z': ok = true case r == '$', r == '_': ok = true } return ok } func cloneStringSlice(sl []string) []string { if sl == nil { return nil } c := make([]string, len(sl)) copy(c, sl) return c } <|start_filename|>sql/mycanal/handler.go<|end_filename|> package mycanal import ( "context" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/sql/ddl" "golang.org/x/sync/errgroup" ) // TODO(CyS) investigate what would happen in case of transaction? should all // the events be gathered together once a transaction starts? because on // RollBack all events must be invalidated or better RowsEventHandler should not // be called at all. // RowsEventHandler calls your code when an event gets dispatched. type RowsEventHandler interface { // Do function handles a RowsEvent bound to a specific database. If it // returns an error behaviour of "Interrupted", the canal type will stop the // syncer. Binlog has three update event version, v0, v1 and v2. For v1 and // v2, the rows number must be even. Two rows for one event, format is // [before update row, after update row] for update v0, only one row for a // event, and we don't support this version yet. The Do function will run in // its own Goroutine. The provided argument `t` of type ddl.Table must only // be used for reading, changing `t` causes race conditions. Do(ctx context.Context, action string, t *ddl.Table, rows [][]interface{}) error // Complete runs before a binlog rotation event happens. Same error rules // apply here like for function Do(). The Complete function will run in its // own Goroutine. Complete(context.Context) error // String returns the name of the handler String() string } // RegisterRowsEventHandler adds a new event handler to the internal list. If a // table name gets provided the event handler is bound to that exact table name, // if the table has not been excluded via the global regexes. An empty tableName // calls the event handler for all tables. If a table name already exists, the // RowsEventHandler gets appended to that list. func (c *Canal) RegisterRowsEventHandler(tableNames []string, h ...RowsEventHandler) { // TODO consider an API to Deregister all handlers for a table name c.rsMu.Lock() defer c.rsMu.Unlock() if c.rsHandlers == nil { c.rsHandlers = make(map[string][]RowsEventHandler) } for _, tn := range tableNames { hs := c.rsHandlers[tn] c.rsHandlers[tn] = append(hs, h...) } if len(tableNames) == 0 { hs := c.rsHandlers[""] c.rsHandlers[""] = append(hs, h...) } } func (c *Canal) processRowsEventHandler(ctx context.Context, action string, table *ddl.Table, rows [][]interface{}) error { c.rsMu.RLock() defer c.rsMu.RUnlock() erg, ctx := errgroup.WithContext(ctx) errGoFn := func(h RowsEventHandler) func() error { return func() error { if err := h.Do(ctx, action, table, rows); err != nil { isInterr := errors.MatchKind(err, errors.Interrupted) if c.opts.Log.IsDebug() { c.opts.Log.Debug("myCanal.processRowsEventHandler.Go.Do.error", log.Err(err), log.Stringer("handler_name", h), log.Bool("is_interrupted", isInterr), log.String("action", action), log.String("schema", c.dsn.DBName), log.String("table", table.Name)) } if isInterr { return errors.WithStack(err) } } return nil } } if hs, ok := c.rsHandlers[table.Name]; ok && table.Name != "" { for _, h := range hs { erg.Go(errGoFn(h)) } } for _, h := range c.rsHandlers[""] { erg.Go(errGoFn(h)) } return errors.WithStack(erg.Wait()) } func (c *Canal) flushEventHandlers(ctx context.Context) error { defer log.WhenDone(c.opts.Log).Info("myCanal.flushEventHandlers") c.rsMu.RLock() defer c.rsMu.RUnlock() erg, ctx := errgroup.WithContext(ctx) for tblName, hs := range c.rsHandlers { for _, h := range hs { h := h erg.Go(func() error { if err := h.Complete(ctx); err != nil { isInterr := errors.MatchKind(err, errors.Interrupted) c.opts.Log.Info("myCanal.flushEventHandlers.Go.Complete.error", log.Err(err), log.Bool("is_interrupted", isInterr), log.Stringer("handler_name", h), log.String("table_name", tblName)) if isInterr { return errors.WithStack(err) } } return nil }) } } return errors.Wrap(erg.Wait(), "[mycanal] flushEventHandlers errgroup Wait") } <|start_filename|>storage/objcache/lru.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 objcache import ( "context" "time" "github.com/corestoreio/pkg/storage/lru" ) // LRUOptions allows to track the cache items either by object count or total // size in bytes. If tracking by `TrackBySize` gets enabled then `Capacity` must // have the value in bytes. Default 64MB. type LRUOptions struct { Capacity int64 // default 5000 objects TrackBySize bool TrackByObjectCount bool // default LRUCache *lru.Cache } // lruCache is an LRU cache. It is safe for concurrent access. type lruCache struct { opt LRUOptions } // NewLRU creates a new LRU Storage. Expirations are not supported. Argument `o` // can be nil, if so default values get applied. func NewLRU(o *LRUOptions) NewStorageFn { if o == nil { o = &LRUOptions{} } switch { case o.TrackBySize && o.Capacity == 0: o.Capacity = 1 << 26 // 64MB case o.TrackByObjectCount && o.Capacity == 0: o.Capacity = 5000 // objects case o.TrackBySize: case o.TrackByObjectCount: default: o.TrackByObjectCount = true o.Capacity = 5000 } if o.LRUCache == nil { o.LRUCache = lru.New(o.Capacity) } return func() (Storager, error) { return lruCache{ opt: *o, }, nil } } type itemBySize []byte func (li itemBySize) Size() int { return len(li) } type itemByCount []byte func (li itemByCount) Size() int { return 1 } func (c lruCache) Set(_ context.Context, keys []string, values [][]byte, _ []time.Duration) (err error) { for i, key := range keys { var v lru.Value = itemByCount(values[i]) if c.opt.TrackBySize { v = itemBySize(values[i]) } c.opt.LRUCache.Set(key, v) } return nil } // Get looks up a key's value from the cache. func (c lruCache) Get(_ context.Context, keys []string) (values [][]byte, err error) { for _, key := range keys { itm, ok := c.opt.LRUCache.Get(key) if ok { if c.opt.TrackByObjectCount { values = append(values, []byte(itm.(itemByCount))) } else { values = append(values, []byte(itm.(itemBySize))) } } else { values = append(values, nil) } } return } func (c lruCache) Truncate(_ context.Context) (err error) { c.opt.LRUCache.Clear() return nil } func (c lruCache) Delete(_ context.Context, keys []string) (err error) { for _, key := range keys { c.opt.LRUCache.Delete(key) } return nil } func (c lruCache) Close() error { c.opt.LRUCache.Clear() return nil } <|start_filename|>sql/dmlgen/dmltestgeneratedMToM/fkm2n_gen_test.go<|end_filename|> // Code generated by corestoreio/pkg/util/codegen. DO NOT EDIT. // Generated by sql/dmlgen. DO NOT EDIT. package dmltestgeneratedMToM import ( "context" "sort" "testing" "time" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/util/assert" "github.com/corestoreio/pkg/util/pseudo" ) func TestNewDBManagerDB_b0014848206a53c73619e6569577340a(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "../testdata/testAll_*_tables.sql", &dmltest.SQLDumpOptions{ SkipDBCleanup: true, }).Deferred() ctx, cancel := context.WithTimeout(context.Background(), time.Minute*2) defer cancel() tbls, err := NewDBManager(ctx, &DBMOption{TableOptions: []ddl.TableOption{ddl.WithConnPool(db)}}) assert.NoError(t, err) tblNames := tbls.Tables.Tables() sort.Strings(tblNames) assert.Exactly(t, []string{"athlete", "athlete_team", "athlete_team_member", "customer_address_entity", "customer_entity"}, tblNames) err = tbls.Validate(ctx) assert.NoError(t, err) var ps *pseudo.Service ps = pseudo.MustNewService(0, &pseudo.Options{Lang: "de", MaxFloatDecimals: 6}, pseudo.WithTagFakeFunc("website_id", func(maxLen int) interface{} { return 1 }), pseudo.WithTagFakeFunc("store_id", func(maxLen int) interface{} { return 1 }), ) t.Run("Athlete_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameAthlete) selOneRow := tbl.Select("*").Where( dml.Column("athlete_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("athlete_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(Athlete) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.Athlete_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(Athlete) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.AthleteID, entOut.AthleteID, "IDX%d: AthleteID should match", lID) assert.ExactlyLength(t, 340, &entIn.Firstname, &entOut.Firstname, "IDX%d: Firstname should match", lID) assert.ExactlyLength(t, 340, &entIn.Lastname, &entOut.Lastname, "IDX%d: Lastname should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewAthletes() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: Athletes ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("AthleteTeam_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameAthleteTeam) selOneRow := tbl.Select("*").Where( dml.Column("team_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("team_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(AthleteTeam) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.AthleteTeam_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(AthleteTeam) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.TeamID, entOut.TeamID, "IDX%d: TeamID should match", lID) assert.ExactlyLength(t, 340, &entIn.Name, &entOut.Name, "IDX%d: Name should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewAthleteTeams() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: AthleteTeams ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("AthleteTeamMember_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameAthleteTeamMember) selOneRow := tbl.Select("*").Where( dml.Column("id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(AthleteTeamMember) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.AthleteTeamMember_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(AthleteTeamMember) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.ID, entOut.ID, "IDX%d: ID should match", lID) assert.Exactly(t, entIn.TeamID, entOut.TeamID, "IDX%d: TeamID should match", lID) assert.Exactly(t, entIn.AthleteID, entOut.AthleteID, "IDX%d: AthleteID should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewAthleteTeamMembers() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: AthleteTeamMembers ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("CustomerAddressEntity_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCustomerAddressEntity) selOneRow := tbl.Select("*").Where( dml.Column("entity_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("entity_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(CustomerAddressEntity) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.CustomerAddressEntity_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(CustomerAddressEntity) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.EntityID, entOut.EntityID, "IDX%d: EntityID should match", lID) assert.ExactlyLength(t, 50, &entIn.IncrementID, &entOut.IncrementID, "IDX%d: IncrementID should match", lID) assert.Exactly(t, entIn.ParentID, entOut.ParentID, "IDX%d: ParentID should match", lID) assert.Exactly(t, entIn.IsActive, entOut.IsActive, "IDX%d: IsActive should match", lID) assert.ExactlyLength(t, 255, &entIn.City, &entOut.City, "IDX%d: City should match", lID) assert.ExactlyLength(t, 255, &entIn.Company, &entOut.Company, "IDX%d: Company should match", lID) assert.ExactlyLength(t, 255, &entIn.CountryID, &entOut.CountryID, "IDX%d: CountryID should match", lID) assert.ExactlyLength(t, 255, &entIn.Firstname, &entOut.Firstname, "IDX%d: Firstname should match", lID) assert.ExactlyLength(t, 255, &entIn.Lastname, &entOut.Lastname, "IDX%d: Lastname should match", lID) assert.ExactlyLength(t, 255, &entIn.Postcode, &entOut.Postcode, "IDX%d: Postcode should match", lID) assert.ExactlyLength(t, 255, &entIn.Region, &entOut.Region, "IDX%d: Region should match", lID) assert.ExactlyLength(t, 65535, &entIn.Street, &entOut.Street, "IDX%d: Street should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewCustomerAddressEntities() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: CustomerAddressEntities ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("CustomerEntity_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCustomerEntity) selOneRow := tbl.Select("*").Where( dml.Column("entity_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("entity_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(CustomerEntity) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.CustomerEntity_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(CustomerEntity) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.EntityID, entOut.EntityID, "IDX%d: EntityID should match", lID) assert.Exactly(t, entIn.WebsiteID, entOut.WebsiteID, "IDX%d: WebsiteID should match", lID) assert.ExactlyLength(t, 255, &entIn.Email, &entOut.Email, "IDX%d: Email should match", lID) assert.Exactly(t, entIn.GroupID, entOut.GroupID, "IDX%d: GroupID should match", lID) assert.Exactly(t, entIn.StoreID, entOut.StoreID, "IDX%d: StoreID should match", lID) assert.Exactly(t, entIn.IsActive, entOut.IsActive, "IDX%d: IsActive should match", lID) assert.ExactlyLength(t, 255, &entIn.CreatedIn, &entOut.CreatedIn, "IDX%d: CreatedIn should match", lID) assert.ExactlyLength(t, 255, &entIn.Firstname, &entOut.Firstname, "IDX%d: Firstname should match", lID) assert.ExactlyLength(t, 255, &entIn.Lastname, &entOut.Lastname, "IDX%d: Lastname should match", lID) assert.ExactlyLength(t, 128, &entIn.PasswordHash, &entOut.PasswordHash, "IDX%d: PasswordHash should match", lID) assert.ExactlyLength(t, 128, &entIn.RpToken, &entOut.RpToken, "IDX%d: RpToken should match", lID) assert.Exactly(t, entIn.DefaultBilling, entOut.DefaultBilling, "IDX%d: DefaultBilling should match", lID) assert.Exactly(t, entIn.DefaultShipping, entOut.DefaultShipping, "IDX%d: DefaultShipping should match", lID) assert.Exactly(t, entIn.Gender, entOut.Gender, "IDX%d: Gender should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewCustomerEntities() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: CustomerEntities ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) // Uncomment the next line for debugging to see all the queries. // t.Logf("queries: %#v", tbls.ConnPool.CachedQueries()) } <|start_filename|>sql/ddl/foreign_key_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ddl_test import ( "bytes" "context" "encoding/json" "testing" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func init() { null.MustSetJSONMarshaler(json.Marshal, json.Unmarshal) } func TestLoadForeignKeys_Integration(t *testing.T) { dbc := dmltest.MustConnectDB(t) defer dmltest.Close(t, dbc) defer dmltest.SQLDumpLoad(t, "testdata/testLoadForeignKeys*.sql", &dmltest.SQLDumpOptions{DSN: dbc.DSN()}).Deferred() t.Run("x859admin_user", func(t *testing.T) { tc, err := ddl.LoadKeyColumnUsage(context.TODO(), dbc.DB, "x859admin_user") assert.NoError(t, err) assert.Len(t, tc, 1, "Number of returned entries should be as stated") fkCols := tc["x859admin_passwords"] assert.NotNil(t, fkCols.Data) dataJSON, err := json.Marshal(fkCols.Data) assert.NoError(t, err) assert.Regexp(t, "\\[{\"ConstraintCatalog\":\"def\",\"ConstraintSchema\":\"[^\"]+\",\"ConstraintName\":\"ADMIN_PASSWORDS_USER_ID_ADMIN_USER_USER_ID\",\"TableCatalog\":\"def\",\"TableSchema\":\"[^\"]+\",\"TableName\":\"x859admin_passwords\",\"ColumnName\":\"user_id\",\"OrdinalPosition\":1,\"PositionInUniqueConstraint\":1,\"ReferencedTableSchema\":\"[^\"]+\",\"ReferencedTableName\":\"x859admin_user\",\"ReferencedColumnName\":\"user_id\"}\\]", string(dataJSON), ) }) t.Run("x910cms_block and x910cms_page", func(t *testing.T) { tc, err := ddl.LoadKeyColumnUsage(context.TODO(), dbc.DB, "x910cms_block", "x910cms_page") assert.NoError(t, err) assert.Len(t, tc, 2, "Number of returned entries should be as stated") dataJSON, err := json.Marshal(tc["x910cms_block_store"].Data) assert.NoError(t, err) assert.Regexp(t, "\\[{\"ConstraintCatalog\":\"def\",\"ConstraintSchema\":\"[^\"]+\",\"ConstraintName\":\"CMS_BLOCK_STORE_BLOCK_ID_CMS_BLOCK_BLOCK_ID\",\"TableCatalog\":\"def\",\"TableSchema\":\"[^\"]+\",\"TableName\":\"x910cms_block_store\",\"ColumnName\":\"block_id\",\"OrdinalPosition\":1,\"PositionInUniqueConstraint\":1,\"ReferencedTableSchema\":\"[^\"]+\",\"ReferencedTableName\":\"x910cms_block\",\"ReferencedColumnName\":\"block_id\"}\\]", string(dataJSON), ) dataJSON, err = json.Marshal(tc["x910cms_page_store"].Data) assert.NoError(t, err) assert.Regexp(t, "\\[{\"ConstraintCatalog\":\"def\",\"ConstraintSchema\":\"[^\"]+\",\"ConstraintName\":\"CMS_PAGE_STORE_PAGE_ID_CMS_PAGE_PAGE_ID\",\"TableCatalog\":\"def\",\"TableSchema\":\"[^\"]+\",\"TableName\":\"x910cms_page_store\",\"ColumnName\":\"page_id\",\"OrdinalPosition\":1,\"PositionInUniqueConstraint\":1,\"ReferencedTableSchema\":\"[^\"]+\",\"ReferencedTableName\":\"x910cms_page\",\"ReferencedColumnName\":\"page_id\"}\\]", string(dataJSON), ) }) t.Run("catalog_eav_attribute", func(t *testing.T) { tc, err := ddl.LoadKeyColumnUsage(context.TODO(), dbc.DB, "x910catalog_eav_attribute") assert.NoError(t, err) assert.Len(t, tc, 0, "Number of returned entries should be as stated") fkCols, ok := tc["x910catalog_eav_attribute"] assert.False(t, ok) assert.Nil(t, fkCols.Data) }) } func TestLoadKeyRelationships(t *testing.T) { dbc := dmltest.MustConnectDB(t) defer dmltest.Close(t, dbc) defer dmltest.SQLDumpLoad(t, "testdata/testLoadForeignKeys*.sql", &dmltest.SQLDumpOptions{DSN: dbc.DSN()}).Deferred() // dmltest.SQLDumpLoad(t, "testdata/testLoadForeignKeys*.sql", nil) ctx := context.Background() tc, err := ddl.LoadKeyColumnUsage(context.TODO(), dbc.DB) assert.NoError(t, err) krs, err := ddl.GenerateKeyRelationships(ctx, dbc.DB, tc) assert.NoError(t, err) var buf bytes.Buffer krs.Debug(&buf) t.Log("\n", buf.String()) assert.LenBetween(t, buf.String(), 1840, 2380) t.Run("ManyToMany", func(t *testing.T) { targetTable, targetColumn := krs.ManyToManyTarget("athlete_team_member", "team_id") assert.Exactly(t, "athlete", targetTable, "targetTable.targetColumn: %q.%q", targetTable, targetColumn) assert.Exactly(t, "athlete_id", targetColumn) targetTable, targetColumn = krs.ManyToManyTarget("athlete_team_member", "athlete_id") assert.Exactly(t, "athlete_team", targetTable) assert.Exactly(t, "team_id", targetColumn) targetTable, targetColumn = krs.ManyToManyTarget("athlete_team_member", "athlete_idx") assert.Exactly(t, "", targetTable) assert.Exactly(t, "", targetColumn) }) t.Run("OneToX", func(t *testing.T) { tests := []struct { checkFn func(referencedTable, referencedColumn, table, column string) bool referencedTable, referencedColumn, table, column string want bool }{ {krs.IsOneToOne, "x859admin_passwords", "user_id", "x859admin_user", "user_id", true}, {krs.IsOneToOne, "x859admin_user", "user_id", "<PASSWORD>_passwords", "user_id", false}, {krs.IsOneToMany, "x859admin_user", "user_id", "<PASSWORD>_passwords", "user_id", true}, {krs.IsOneToMany, "x859admin_passwords", "user_id", "x859admin_user", "user_id", false}, {krs.IsOneToOne, "x910cms_page_store", "page_id", "x910cms_page", "page_id", true}, {krs.IsOneToMany, "x910cms_page", "page_id", "x910cms_page_store", "page_id", true}, {krs.IsOneToMany, "store_group", "website_id", "store", "website_id", false}, // no FK constraint {krs.IsOneToOne, "store_group", "website_id", "store", "website_id", false}, // no FK constraint {krs.IsOneToMany, "store", "website_id", "store_group", "website_id", false}, // no FK constraint {krs.IsOneToOne, "store", "website_id", "store_group", "website_id", false}, {krs.IsOneToOne, "store_group", "website_id", "store_website", "website_id", true}, {krs.IsOneToMany, "store_website", "website_id", "store_group", "website_id", true}, // reversed above {krs.IsOneToOne, "catalog_category_entity", "entity_id", "sequence_catalog_category", "sequence_value", true}, // reversed must also be true for oneToOne because sequence_catalog_category contains only one column {krs.IsOneToOne, "sequence_catalog_category", "sequence_value", "catalog_category_entity", "entity_id", true}, {krs.IsOneToMany, "sequence_catalog_category", "sequence_value", "catalog_category_entity", "entity_id", false}, {krs.IsOneToMany, "catalog_category_entity", "entity_id", "sequence_catalog_category", "sequence_value", false}, } for i, test := range tests { assert.Exactly(t, test.want, test.checkFn(test.referencedTable, test.referencedColumn, test.table, test.column), "IDX %d %q.%q => %q.%q", i, test.referencedTable, test.referencedColumn, test.table, test.column, ) } }) } <|start_filename|>sql/dml/dml_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" "fmt" "os" "reflect" "testing" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" _ "github.com/go-sql-driver/mysql" ) /////////////////////////////////////////////////////////////////////////////// // TEST HELPERS /////////////////////////////////////////////////////////////////////////////// func createRealSession(t testing.TB) *ConnPool { dsn := os.Getenv("CS_DSN") if dsn == "" { t.Skip("Environment variable CS_DSN not found. Skipping ...") } cxn, err := NewConnPool( WithDSN(dsn), WithCreateDatabase(context.Background(), ""), ) if err != nil { t.Fatal(err) } return cxn } func createRealSessionWithFixtures(t testing.TB, c *installFixturesConfig) *ConnPool { sess := createRealSession(t) installFixtures(t, sess.DB, c) return sess } // testCloser for usage in conjunction with defer. // defer testCloser(t,db) // Cannot use dmltest.Close because of circular dependency. func testCloser(t testing.TB, c ioCloser) { t.Helper() if err := c.Close(); err != nil { t.Errorf("%+v", err) } } var ( _ ColumnMapper = (*dmlPerson)(nil) _ LastInsertIDAssigner = (*dmlPerson)(nil) _ ColumnMapper = (*dmlPersons)(nil) ) type dmlPerson struct { ID uint64 Name string Email null.String Key null.String Dob int } func (p *dmlPerson) AssignLastInsertID(id int64) { p.ID = uint64(id) } // RowScan loads a single row from a SELECT statement returning only one row func (p *dmlPerson) MapColumns(cm *ColumnMap) error { for cm.Next(5) { switch c := cm.Column(); c { case "id", "0": cm.Uint64(&p.ID) case "name", "1": cm.String(&p.Name) case "email", "2": cm.NullString(&p.Email) case "key", "3": cm.NullString(&p.Key) case "dob", "4": cm.Int(&p.Dob) case "store_id", "created_at", "total_income", "avg_income": // noop don't trigger the default case default: return errors.NotFound.Newf("[dml_test] dmlPerson Column %q not found", c) } } return errors.WithStack(cm.Err()) } type dmlPersons struct { Data []*dmlPerson } // MapColumns gets called in the `for rows.Next()` loop each time in case of IsNew func (ps *dmlPersons) MapColumns(cm *ColumnMap) error { switch m := cm.Mode(); m { case ColumnMapEntityReadAll, ColumnMapEntityReadSet: for _, p := range ps.Data { if err := p.MapColumns(cm); err != nil { return errors.WithStack(err) } } case ColumnMapScan: // case for scanning when loading certain rows, hence we write data from // the DB into the struct in each for-loop. if cm.Count == 0 { ps.Data = ps.Data[:0] } p := new(dmlPerson) if err := p.MapColumns(cm); err != nil { return errors.WithStack(err) } ps.Data = append(ps.Data, p) case ColumnMapCollectionReadSet: // See Test in select_test.go:TestSelect_SetRecord // SELECT, DELETE or UPDATE or INSERT with n columns // TODO in some INSERT statements this slice building code might not be needed. switch c := cm.Column(); c { case "id": cm.Uint64s(ps.IDs()...) case "name": cm.Strings(ps.Names()...) case "email": cm.NullStrings(ps.Emails()...) default: return errors.NotFound.Newf("[dml_test] dmlPerson Column %q not found", c) } default: return errors.NotSupported.Newf("[dml] Unknown Mode: %q", string(m)) } return cm.Err() } func (ps *dmlPersons) IDs(ret ...uint64) []uint64 { if ret == nil { ret = make([]uint64, 0, len(ps.Data)) } for _, p := range ps.Data { ret = append(ret, p.ID) } return ret } func (ps *dmlPersons) Names(ret ...string) []string { if ret == nil { ret = make([]string, 0, len(ps.Data)) } for _, p := range ps.Data { ret = append(ret, p.Name) } return ret } func (ps *dmlPersons) Emails(ret ...null.String) []null.String { if ret == nil { ret = make([]null.String, 0, len(ps.Data)) } for _, p := range ps.Data { ret = append(ret, p.Email) } return ret } // func (ps *dmlPersons) AssignLastInsertID(uint64) error { // // todo iterate and assign to the last item in the slice and assign // // decremented IDs to the previous items in the slice. // return nil //} // var _ ColumnMapper = (*nullTypedRecord)(nil) type nullTypedRecord struct { ID int64 StringVal null.String Int64Val null.Int64 Float64Val null.Float64 TimeVal null.Time BoolVal null.Bool DecimalVal null.Decimal } func (p *nullTypedRecord) MapColumns(cm *ColumnMap) error { for cm.Next(5) { switch c := cm.Column(); c { case "id", "0": cm.Int64(&p.ID) case "string_val", "1": cm.NullString(&p.StringVal) case "int64_val", "2": cm.NullInt64(&p.Int64Val) case "float64_val", "3": cm.NullFloat64(&p.Float64Val) case "time_val", "4": cm.NullTime(&p.TimeVal) case "bool_val", "5": cm.NullBool(&p.BoolVal) case "decimal_val", "6": cm.Decimal(&p.DecimalVal) default: return errors.NotFound.Newf("[dml_test] Column %q not found", c) } } return cm.Err() } func newNullTypedRecordWithData() *nullTypedRecord { return &nullTypedRecord{ ID: 2, StringVal: null.String{Data: "wow", Valid: true}, Int64Val: null.Int64{Int64: 42, Valid: true}, Float64Val: null.Float64{Float64: 1.618, Valid: true}, TimeVal: null.MakeTime(time.Date(2009, 1, 3, 18, 15, 5, 0, time.UTC)), BoolVal: null.Bool{Bool: true, Valid: true}, DecimalVal: null.Decimal{Precision: 12345, Scale: 3, Valid: true}, } } type installFixturesConfig struct { AddPeopleWithMaxUint64 bool } func installFixtures(t testing.TB, db *sql.DB, c *installFixturesConfig) { createPeopleTable := fmt.Sprintf(` CREATE TABLE dml_people ( id bigint(8) unsigned NOT NULL auto_increment PRIMARY KEY, name varchar(255) NOT NULL, email varchar(255), %s varchar(255), store_id smallint(5) unsigned DEFAULT 0 COMMENT 'Store Id', created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Created At', total_income decimal(12,4) NOT NULL DEFAULT 0.0000 COMMENT 'Used as float64', avg_income decimal(12,5) COMMENT 'Used as Decimal' ) `, "`key`") createNullTypesTable := ` CREATE TABLE dml_null_types ( id int(11) NOT NULL auto_increment PRIMARY KEY, string_val varchar(255) NULL, int64_val int(11) NULL, float64_val float NULL, time_val datetime NULL, bool_val bool NULL, decimal_val decimal(5,3) NULL ) ` // see also test case "LoadUint64 max Uint64 found" sqlToRun := []string{ "DROP TABLE IF EXISTS `dml_people`", createPeopleTable, "INSERT INTO dml_people (name,email,avg_income) VALUES ('<NAME>', '<EMAIL>',333.66677)", "INSERT INTO dml_people (name,email) VALUES ('Dmitri', '<EMAIL>')", "DROP TABLE IF EXISTS `dml_null_types`", createNullTypesTable, } if c != nil && c.AddPeopleWithMaxUint64 { sqlToRun = append(sqlToRun, "INSERT INTO `dml_people` (id,name,email) VALUES (18446744073700551613,'Cyrill', '<EMAIL>')") } for _, sqlStr := range sqlToRun { _, err := db.Exec(sqlStr) assert.NoError(t, err, "With SQL statement: %q", sqlStr) } } // compareToSQL compares a SQL object with a placeholder string and an optional // interpolated string. This function also exists in file dml_public_test.go to // avoid import cycles when using a single package dedicated for testing. func compareToSQL( t testing.TB, qb QueryBuilder, wantErrKind errors.Kind, wantSQLPlaceholders, wantSQLInterpolated string, wantArgs ...interface{}, ) { sqlStr, args, err := qb.ToSQL() if wantErrKind.Empty() { assert.NoError(t, err) } else { assert.ErrorIsKind(t, wantErrKind, err) } if wantSQLPlaceholders != "" { assert.Exactly(t, wantSQLPlaceholders, sqlStr, "Placeholder SQL strings do not match") assert.Exactly(t, wantArgs, args, "Placeholder Arguments do not match") } if wantSQLInterpolated == "" { return } if dml, ok := qb.(*DBR); ok { prev := dml.Options qb = dml.Interpolate() defer func() { dml.Options = prev; qb = dml }() } sqlStr, args, err = qb.ToSQL() // Call with enabled interpolation if wantErrKind.Empty() { assert.NoError(t, err) } else { assert.ErrorIsKind(t, wantErrKind, err) } assert.Exactly(t, wantSQLInterpolated, sqlStr, "Interpolated SQL strings do not match") assert.Nil(t, args, "DBR should be nil when the SQL string gets interpolated") } // compareToSQL2 This function also exists in file dml_public_test.go to // avoid import cycles when using a single package dedicated for testing. func compareToSQL2( t testing.TB, qb QueryBuilder, wantErrKind errors.Kind, wantSQL string, wantArgs ...interface{}, ) { t.Helper() sqlStr, args, err := qb.ToSQL() if wantErrKind.Empty() { assert.NoError(t, err, "With SQL %q", wantSQL) } else { assert.ErrorIsKind(t, wantErrKind, err) } assert.Exactly(t, wantSQL, sqlStr, "SQL strings do not match") assert.Exactly(t, wantArgs, args, "Arguments do not match") } func compareExecContext(t testing.TB, ex StmtExecer, args []interface{}, lastInsertID, rowsAffected int64) (retLastInsertID, retRowsAffected int64) { res, err := ex.ExecContext(context.Background(), args...) assert.NoError(t, err) assert.NotNil(t, res, "Returned result from ExecContext should not be nil") if lastInsertID > 0 { retLastInsertID, err = res.LastInsertId() assert.NoError(t, err) assert.Exactly(t, lastInsertID, retLastInsertID, "Last insert ID do not match") } if rowsAffected > 0 { retRowsAffected, err = res.RowsAffected() assert.NoError(t, err) assert.Exactly(t, rowsAffected, retRowsAffected, "Affected rows do not match") } return } func notEqualPointers(t *testing.T, o1, o2 interface{}, msgAndArgs ...interface{}) { p1 := reflect.ValueOf(o1) p2 := reflect.ValueOf(o2) if len(msgAndArgs) == 0 { msgAndArgs = []interface{}{"Pointers for type o1:%T o2:%T should not be equal", o1, o2} } assert.NotEqual(t, p1.Pointer(), p2.Pointer(), msgAndArgs...) } <|start_filename|>sql/dml/insert_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml_test import ( "context" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) var _ dml.ColumnMapper = (*someRecord)(nil) type someRecord struct { SomethingID int UserID int64 Other bool } func (sr someRecord) MapColumns(cm *dml.ColumnMap) error { for cm.Next(3) { switch c := cm.Column(); c { case "something_id", "0": cm.Int(&sr.SomethingID) case "user_id", "1": cm.Int64(&sr.UserID) case "other", "2": cm.Bool(&sr.Other) default: return errors.NotFound.Newf("[dml_test] Column %q not found", c) } } return cm.Err() } func TestInsert_Bind(t *testing.T) { objs := []someRecord{{1, 88, false}, {2, 99, true}, {3, 101, true}} wantArgs := []interface{}{int64(1), int64(88), false, int64(2), int64(99), true, int64(3), int64(101), true} t.Run("valid with multiple records", func(t *testing.T) { compareToSQL(t, dml.NewInsert("a"). AddColumns("something_id", "user_id", "other"). AddOnDuplicateKey( dml.Column("something_id").Int64(99), dml.Column("user_id").Values(), ).WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", objs[0]), dml.Qualify("", objs[1]), dml.Qualify("", objs[2])), errors.NoKind, "INSERT INTO `a` (`something_id`,`user_id`,`other`) VALUES (?,?,?),(?,?,?),(?,?,?) ON DUPLICATE KEY UPDATE `something_id`=99, `user_id`=VALUES(`user_id`)", "INSERT INTO `a` (`something_id`,`user_id`,`other`) VALUES (1,88,0),(2,99,1),(3,101,1) ON DUPLICATE KEY UPDATE `something_id`=99, `user_id`=VALUES(`user_id`)", wantArgs..., ) }) t.Run("without columns, all columns requested, with AddOnDuplicateKey", func(t *testing.T) { compareToSQL(t, dml.NewInsert("a"). AddOnDuplicateKey( dml.Column("something_id").Int64(99), dml.Column("user_id").Values(), ).WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", objs[0]), dml.Qualify("", objs[1]), dml.Qualify("", objs[2])), errors.NoKind, "INSERT INTO `a` VALUES (?,?,?),(?,?,?),(?,?,?) ON DUPLICATE KEY UPDATE `something_id`=99, `user_id`=VALUES(`user_id`)", "INSERT INTO `a` VALUES (1,88,0),(2,99,1),(3,101,1) ON DUPLICATE KEY UPDATE `something_id`=99, `user_id`=VALUES(`user_id`)", wantArgs..., ) }) t.Run("without columns, all columns requested, no dup key", func(t *testing.T) { customers := []*customerEntity{ {EntityID: 11, Firstname: "<NAME>", StoreID: 0x7, LifetimeSales: null.MakeFloat64(47.11), VoucherCodes: exampleStringSlice{"1FE9983E", "28E76FBC"}}, {EntityID: 12, Firstname: "<NAME>", StoreID: 0x7, LifetimeSales: null.MakeFloat64(28.94), VoucherCodes: exampleStringSlice{"4FE7787E", "15E59FBB", "794EFDE8"}}, {EntityID: 13, Firstname: "<NAME>", StoreID: 0x6, LifetimeSales: null.MakeFloat64(138.54), VoucherCodes: exampleStringSlice{""}}, } compareToSQL(t, dml.NewInsert("customer_entity"). WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", customers[0]), dml.Qualify("", customers[1]), dml.Qualify("", customers[2])), errors.NoKind, "INSERT INTO `customer_entity` VALUES (?,?,?,?,?),(?,?,?,?,?),(?,?,?,?,?)", "INSERT INTO `customer_entity` VALUES (11,'<NAME>',7,47.11,'1FE9983E|28E76FBC'),(12,'<NAME>',7,28.94,'4FE7787E|15E59FBB|794EFDE8'),(13,'<NAME>',6,138.54,'')", int64(11), "<NAME>", int64(7), 47.11, "1FE9983E|28E76FBC", int64(12), "<NAME>", int64(7), 28.94, "4FE7787E|15E59FBB|794EFDE8", int64(13), "<NAME>", int64(6), 138.54, "", ) }) t.Run("column not found", func(t *testing.T) { objs := []someRecord{{1, 88, false}, {2, 99, true}} compareToSQL(t, dml.NewInsert("a").AddColumns("something_it", "user_id", "other").WithDBR(dbMock{}).TestWithArgs( dml.Qualify("", objs[0]), dml.Qualify("", objs[1]), ), errors.NotFound, "", "", ) }) } func TestInsert_Prepare(t *testing.T) { t.Run("BuildValues not set Error", func(t *testing.T) { in := &dml.Insert{} in.AddColumns("a", "b") _, _, err := in.ToSQL() assert.ErrorIsKind(t, errors.Empty, err) }) t.Run("ToSQL Error", func(t *testing.T) { in := &dml.Insert{} in.AddColumns("a", "b") stmt, _, err := in.ToSQL() assert.Empty(t, stmt) assert.ErrorIsKind(t, errors.Empty, err) }) t.Run("DB Error", func(t *testing.T) { in := &dml.Insert{ Into: "table", } inDBR := in.WithDBR(dbMock{ error: errors.AlreadyClosed.Newf("Who closed myself?"), }) in.AddColumns("a", "b").BuildValues() stmt, err := inDBR.Prepare(context.Background()) assert.Nil(t, stmt) assert.ErrorIsKind(t, errors.AlreadyClosed, err) }) t.Run("ExecArgs One Row", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("INSERT INTO `customer_entity` (`email`,`group_id`,`created_at`) VALUES (?,?,?)")) prep.ExpectExec().WithArgs("a@b.c", 33, now()).WillReturnResult(sqlmock.NewResult(4, 0)) prep.ExpectExec().WithArgs("x<EMAIL>", 44, now().Add(time.Minute)).WillReturnResult(sqlmock.NewResult(5, 0)) stmt, err := dbc.WithQueryBuilder(dml.NewInsert("customer_entity"). AddColumns("email", "group_id", "created_at").BuildValues()). Prepare(context.Background()) assert.NoError(t, err, "failed creating a prepared statement") defer func() { assert.NoError(t, stmt.Close(), "Close on a prepared statement") }() tests := []struct { email string groupID int created_at time.Time insertID int64 }{ {"a<EMAIL>", 33, now(), 4}, {"x<EMAIL>", 44, now().Add(time.Minute), 5}, } for i, test := range tests { res, err := stmt.ExecContext(context.Background(), test.email, test.groupID, test.created_at) if err != nil { t.Fatalf("Index %d => %+v", i, err) } lid, err := res.LastInsertId() if err != nil { t.Fatalf("Result index %d with error: %s", i, err) } assert.Exactly(t, test.insertID, lid, "Index %d has different LastInsertIDs", i) stmt.Reset() } }) t.Run("ExecArgs Multi Row", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("INSERT INTO `customer_entity` (`email`,`group_id`) VALUES (?,?),(?,?)")) prep.ExpectExec().WithArgs("a<EMAIL>", 33, "<EMAIL>", 33).WillReturnResult(sqlmock.NewResult(6, 0)) prep.ExpectExec().WithArgs("x@y.z", 44, "<EMAIL>", 44).WillReturnResult(sqlmock.NewResult(7, 0)) stmt, err := dbc.WithQueryBuilder(dml.NewInsert("customer_entity"). AddColumns("email", "group_id").BuildValues().SetRowCount(2), ).Prepare(context.Background()) assert.NoError(t, err) defer func() { assert.NoError(t, stmt.Close(), "Close on a prepared statement") }() tests := []struct { email1 string groupID1 int email2 string groupID2 int insertID int64 }{ {"<EMAIL>", 33, "<EMAIL>", 33, 6}, {"<EMAIL>", 44, "<EMAIL>", 44, 7}, } for i, test := range tests { res, err := stmt.ExecContext(context.Background(), test.email1, test.groupID1, test.email2, test.groupID2) if err != nil { t.Fatalf("Index %d => %+v", i, err) } lid, err := res.LastInsertId() if err != nil { t.Fatalf("Result index %d with error: %s", i, err) } assert.Exactly(t, test.insertID, lid, "Index %d has different LastInsertIDs", i) stmt.Reset() } }) t.Run("ExecRecord One Row", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("INSERT INTO `dml_person` (`name`,`email`) VALUES (?,?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>").WillReturnResult(sqlmock.NewResult(4, 0)) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>").WillReturnResult(sqlmock.NewResult(5, 0)) stmt := dbc.WithPrepare(context.Background(), dml.NewInsert("dml_person"). AddColumns("name", "email").BuildValues()) defer dmltest.Close(t, stmt) tests := []struct { name string email string insertID int64 }{ {"<NAME>", "<EMAIL>", 4}, {"<NAME>", "<EMAIL>", 5}, } for i, test := range tests { p := &dmlPerson{ Name: test.name, Email: null.MakeString(test.email), } res, err := stmt.ExecContext(context.Background(), dml.Qualify("", p)) assert.NoError(t, err, "Index %d", i) lid, err := res.LastInsertId() assert.NoError(t, err, "Result index %d", i) assert.Exactly(t, test.insertID, lid, "Index %d has different LastInsertIDs", i) assert.Exactly(t, test.insertID, p.ID, "Index %d and model p has different LastInsertIDs", i) } }) t.Run("ExecContext", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("INSERT INTO `dml_person` (`name`,`email`) VALUES (?,?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>").WillReturnResult(sqlmock.NewResult(4, 0)) stmt, err := dbc.WithQueryBuilder(dml.NewInsert("dml_person"). AddColumns("name", "email"). BuildValues()). Prepare(context.Background()) assert.NoError(t, err, "failed creating a prepared statement") defer func() { assert.NoError(t, stmt.Close(), "Close on a prepared statement") }() res, err := stmt.ExecContext(context.Background(), "<NAME>", "<EMAIL>") assert.NoError(t, err, "failed to execute ExecContext") lid, err := res.LastInsertId() if err != nil { t.Fatal(err) } assert.Exactly(t, int64(4), lid, "Different LastInsertIDs") }) } func TestInsert_BuildValues(t *testing.T) { t.Run("WithArgs", func(t *testing.T) { p := &dmlPerson{ Name: "Pike", Email: null.MakeString("<EMAIL>"), } insA := dml.NewInsert("alpha"). AddColumns("name", "email").BuildValues(). WithDBR(dbMock{}) compareToSQL(t, insA.TestWithArgs(dml.Qualify("", p)), errors.NoKind, "INSERT INTO `alpha` (`name`,`email`) VALUES (?,?)", "", "Pike", "<EMAIL>", ) }) t.Run("WithoutArgs", func(t *testing.T) { ins := dml.NewInsert("alpha").AddColumns("name", "email").BuildValues() compareToSQL(t, ins, errors.NoKind, "INSERT INTO `alpha` (`name`,`email`) VALUES (?,?)", "", ) }) t.Run("reuse statement", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) ctx := context.Background() cp, err := dml.NewConnPool(dml.WithDB(dbc.DB)) assert.NoError(t, err) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("INSERT INTO `people` (`name`,`email`) VALUES (?,?)")). WithArgs("Pike", "<EMAIL>"). WillReturnResult(sqlmock.NewResult(1, 0)) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("INSERT INTO `people` (`name`,`email`) VALUES (?,?),(?,?)")). WithArgs("Pike1", "<EMAIL>", "Pike2", "<EMAIL>"). WillReturnResult(sqlmock.NewResult(1, 0)) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("INSERT INTO `people` (`name`,`email`) VALUES (?,?),(?,?),(?,?)")). WithArgs("Pike1", "<EMAIL>", "Pike2", "<EMAIL>", "Pike3", "<EMAIL>"). WillReturnResult(sqlmock.NewResult(1, 0)) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("INSERT INTO `people` (`name`,`email`) VALUES ('Pike4','<EMAIL>')")). WithArgs(). WillReturnResult(sqlmock.NewResult(1, 0)) inDBR := cp.WithQueryBuilder(dml.NewInsert("people").AddColumns("name", "email")) _, err = inDBR.ExecContext(ctx, &dmlPerson{Name: "Pike", Email: null.MakeString("<EMAIL>")}, ) assert.NoError(t, err) inDBR.Reset() _, err = inDBR.ExecContext(ctx, &dmlPerson{Name: "Pike1", Email: null.MakeString("<EMAIL>")}, &dmlPerson{Name: "Pike2", Email: null.MakeString("<EMAIL>")}, ) assert.NoError(t, err) inDBR.Reset() _, err = inDBR.ExecContext(ctx, &dmlPerson{Name: "Pike1", Email: null.MakeString("<EMAIL>")}, &dmlPerson{Name: "Pike2", Email: null.MakeString("<EMAIL>")}, &dmlPerson{Name: "Pike3", Email: null.MakeString("<EMAIL>")}, ) assert.NoError(t, err) inDBR.Interpolate().Reset() _, err = inDBR.ExecContext(ctx, &dmlPerson{Name: "Pike4", Email: null.MakeString("<EMAIL>")}, ) assert.NoError(t, err) }) } func TestInsert_Clone(t *testing.T) { dbc, dbMock := dmltest.MockDB(t, dml.WithLogger(log.BlackHole{}, func() string { return "uniqueID" })) defer dmltest.MockClose(t, dbc, dbMock) t.Run("nil", func(t *testing.T) { var i *dml.Insert i2 := i.Clone() assert.Nil(t, i) assert.Nil(t, i2) }) t.Run("non-nil AddColumns", func(t *testing.T) { i := dml.NewInsert("dml_people").AddColumns("name", "email") i2 := i.Clone() notEqualPointers(t, i, i2) notEqualPointers(t, i.Columns, i2.Columns) assert.Exactly(t, i.Pairs, i2.Pairs) assert.Exactly(t, i.RecordPlaceHolderCount, i2.RecordPlaceHolderCount) // assert.Exactly(t, i.db, i2.db) // how to test this as it is now unexported? fmt.Sprintf? }) t.Run("non-nil AddColumns", func(t *testing.T) { i := dml.NewInsert("dml_people").WithPairs( dml.Column("name").Str("Hans"), dml.Column("age").Int(79), ) i2 := i.Clone() notEqualPointers(t, i, i2) assert.Exactly(t, i.Columns, i2.Columns) notEqualPointers(t, i.Pairs, i2.Pairs) assert.Exactly(t, i.RecordPlaceHolderCount, i2.RecordPlaceHolderCount) // assert.Exactly(t, i.db, i2.db) // how to test this as it is now unexported? fmt.Sprintf? }) t.Run("non-nil OnDulicateKey", func(t *testing.T) { i := dml.NewInsert("a"). AddColumns("something_id", "user_id", "other"). AddOnDuplicateKey( dml.Column("something_id").Int64(99), dml.Column("user_id").Values(), ) i2 := i.Clone() notEqualPointers(t, i, i2) assert.Exactly(t, i.Columns, i2.Columns) assert.False(t, i2.IsOnDuplicateKey, "Should be false i2.IsOnDuplicateKey") assert.Exactly(t, i.IsOnDuplicateKey, i2.IsOnDuplicateKey) notEqualPointers(t, i.OnDuplicateKeys, i2.OnDuplicateKeys) }) } func TestInsert_WithArgs_record(t *testing.T) { objs := []productEntity{ {1, 5, "simple", null.MakeString("SOA9"), false}, {2, 5, "virtual", null.String{}, true}, } i := dml.NewInsert("catalog_product_entity"). WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", objs[0]), dml.Qualify("", objs[1])) compareToSQL(t, i, errors.NoKind, "INSERT INTO `catalog_product_entity` VALUES (?,?,?,?,?),(?,?,?,?,?)", "INSERT INTO `catalog_product_entity` VALUES (1,5,'simple','SOA9',0),(2,5,'virtual',NULL,1)", int64(1), int64(5), "simple", "SOA9", false, int64(2), int64(5), "virtual", nil, true, ) } <|start_filename|>sql/dmltest/loader_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dmltest import ( "context" "io" "os" "strings" "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/util/assert" ) func TestSQLDumpLoad(t *testing.T) { t.Parallel() t.Run("load sql files", func(t *testing.T) { exexCmd := func(ctx context.Context, r io.ReadCloser, cmd string, arg ...string) error { assert.Exactly(t, `bash`, cmd) args := strings.Join(arg, " ") assert.Contains(t, args, "mydefaults-") assert.Contains(t, args, "-c mysql --defaults-file=") assert.Contains(t, args, os.TempDir()) return nil } SQLDumpLoad(t, "testdata/*.sql", &SQLDumpOptions{ DSN: `cs2:cs2@tcp(localhost:3306)/testDB?parseTime=true&loc=UTC`, execCommandContext: exexCmd, }) }) t.Run("not files found", func(t *testing.T) { SQLDumpLoad(testingMock{T: t, wantErr: errors.NotFound}, "testdata/not_files_found", &SQLDumpOptions{ DSN: `cs2:cs2@tcp(localhost:3306)/testDB?parseTime=true&loc=UTC`, execCommandContext: func(ctx context.Context, r io.ReadCloser, cmd string, arg ...string) error { return nil }, }) }) t.Run("mysql fails", func(t *testing.T) { exexCmd := func(ctx context.Context, r io.ReadCloser, cmd string, arg ...string) error { return errors.NotImplemented.Newf("Cant handle it") } SQLDumpLoad(testingMock{T: t, wantErr: errors.NotImplemented}, "testdata/", &SQLDumpOptions{ DSN: `cs2:cs2@tcp(localhost:3306)/testDB?parseTime=true&loc=UTC`, execCommandContext: exexCmd, }) }) } type testingMock struct { *testing.T wantErr errors.Kind } func (tm testingMock) Fatalf(format string, args ...interface{}) { assert.True(tm.T, tm.wantErr.Match(args[0].(error))) } <|start_filename|>storage/objcache/service_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 objcache_test import ( "context" "encoding/gob" "encoding/json" "io" "io/ioutil" "math" "net" "reflect" "testing" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/objcache" "github.com/corestoreio/pkg/util/assert" "github.com/corestoreio/pkg/util/strs" "golang.org/x/sync/errgroup" ) var _ io.Closer = (*objcache.Service)(nil) func TestNewProcessor_EncoderError(t *testing.T) { t.Parallel() p, err := objcache.NewService(nil, objcache.NewCacheSimpleInmemory, newSrvOpt(gobCodec{})) assert.NoError(t, err) ch := struct { ErrChan chan error }{ ErrChan: make(chan error), } err = p.Set(context.TODO(), "key1", ch, 0) assert.EqualError(t, err, "[objcache] With key \"key1\" and dst type struct { ErrChan chan error }: gob: type struct { ErrChan chan error } has no exported fields", "Error: %s", err) } func debugSliceBytes(t testing.TB, data ...[]byte) { for i, d := range data { t.Logf("IDX:%02d: IsNil %t | %q", i, d == nil, string(d)) } } func newSrvOpt(c objcache.Codecer, primeObjects ...interface{}) *objcache.ServiceOptions { return &objcache.ServiceOptions{ Codec: c, PrimeObjects: primeObjects, } } type myString struct { data string err error } func (ms *myString) Unmarshal(data []byte) error { ms.data = string(data) return ms.err } func (ms *myString) Marshal() ([]byte, error) { return []byte(ms.data), ms.err } func TestService_Encoding(t *testing.T) { p, err := objcache.NewService(nil, objcache.NewCacheSimpleInmemory, newSrvOpt(gobCodec{})) assert.NoError(t, err) defer assert.NoError(t, p.Close()) t.Run("marshal error", func(t *testing.T) { dErr := &myString{err: errors.BadEncoding.Newf("Bad encoding")} err := p.Set(context.TODO(), "dErr", dErr, 0) assert.True(t, errors.BadEncoding.Match(err), "%+v", err) }) t.Run("unmarshal error", func(t *testing.T) { err := p.Set(context.TODO(), "dErr2", 1, 0) assert.NoError(t, err) dErr := &myString{err: errors.BadEncoding.Newf("Bad encoding")} err = p.Get(context.TODO(), "dErr2", dErr) assert.True(t, errors.BadEncoding.Match(err), "%+v", err) }) t.Run("marshal success", func(t *testing.T) { d1 := &myString{data: "HelloWorld"} d2 := &myString{data: "HalloWelt"} err = p.SetMulti(context.TODO(), []string{"d1x", "d2x"}, []interface{}{d1, d2}, nil) assert.NoError(t, err) d1.data = "" d2.data = "" err = p.GetMulti(context.TODO(), []string{"d1x", "d2x"}, []interface{}{d1, d2}) assert.NoError(t, err) assert.Exactly(t, "HelloWorld", d1.data) assert.Exactly(t, "HalloWelt", d2.data) }) } const iterations = 30 func testCountry(p *objcache.Service, key string) func() error { var val = mustGetTestCountry() return func() error { if err := p.Set(context.TODO(), key, val, 0); err != nil { return errors.WithStack(err) } for i := 0; i < iterations; i++ { var newVal = new(Country) if err := p.Get(context.TODO(), key, newVal); err != nil { return errors.WithStack(err) } if want, have := val.IP.String(), newVal.IP.String(); want != have { return errors.Mismatch.Newf("%q != %q", want, have) } if !reflect.DeepEqual(val, newVal) { return errors.Mismatch.Newf("%#v\n!=\n%#v", val, newVal) } } if err := p.Set(context.TODO(), key, Country{}, 0); err != nil { return errors.WithStack(err) } for i := 0; i < iterations; i++ { if err := p.Set(context.TODO(), key, val, 0); err != nil { return errors.WithStack(err) } } var newVal = new(Country) if err := p.Get(context.TODO(), key, newVal); err != nil { return errors.WithStack(err) } if !reflect.DeepEqual(val, newVal) { return errors.Mismatch.Newf("%#v\n!=\n%#v", val, newVal) } return nil } } func testStoreSlice(p *objcache.Service, key string) func() error { return func() error { var val = getTestStores() if err := p.Set(context.TODO(), key, val, 0); err != nil { return errors.WithStack(err) } for i := 0; i < iterations; i++ { var newVal TableStoreSlice if err := p.Get(context.TODO(), key, &newVal); err != nil { return errors.WithStack(err) } if !reflect.DeepEqual(val, newVal) { return errors.Mismatch.Newf("%#v\n!=\n%#v", val, newVal) } } if err := p.Set(context.TODO(), key, TableStoreSlice{}, 0); err != nil { return errors.WithStack(err) } for i := 0; i < iterations; i++ { if err := p.Set(context.TODO(), key, val, 0); err != nil { return errors.WithStack(err) } } var newVal TableStoreSlice if err := p.Get(context.TODO(), key, &newVal); err != nil { return errors.WithStack(err) } if !reflect.DeepEqual(val, newVal) { return errors.Mismatch.Newf("%#v\n!=\n%#v", val, newVal) } return nil } } func init() { gob.Register(&Country{}) gob.Register(&TableStoreSlice{}) } type Country struct { // IP contains the request IP address even if we run behind a proxy IP net.IP `json:"ip,omitempty"` City struct { Confidence int `json:"confidence,omitempty"` GeoNameID uint `json:"geoname_id,omitempty"` Names map[string]string `json:"names,omitempty"` } `json:"city,omitempty"` Continent struct { Code string `json:"code,omitempty"` GeoNameID uint `json:"geoname_id,omitempty"` Names map[string]string `json:"names,omitempty"` } `json:"continent,omitempty"` Country struct { Confidence int `json:"confidence,omitempty"` GeoNameID uint `json:"geoname_id,omitempty"` IsoCode string `json:"iso_code,omitempty"` Names map[string]string `json:"names,omitempty"` } `json:"country,omitempty"` Location struct { AccuracyRadius int `json:"accuracy_radius,omitempty"` AverageIncome int `json:"average_income,omitempty"` Latitude float64 `json:"latitude,omitempty"` Longitude float64 `json:"longitude,omitempty"` MetroCode int `json:"metro_code,omitempty"` PopulationDensity int `json:"population_density,omitempty"` TimeZone string `json:"time_zone,omitempty"` } `json:"location,omitempty"` Postal struct { Code string `json:"code,omitempty"` Confidence int `json:"confidence,omitempty"` } `json:"postal,omitempty"` RegisteredCountry struct { GeoNameID uint `json:"geoname_id,omitempty"` IsoCode string `json:"iso_code,omitempty"` Names map[string]string `json:"names,omitempty"` } `json:"registered_country,omitempty"` RepresentedCountry struct { GeoNameID uint `json:"geoname_id,omitempty"` IsoCode string `json:"iso_code,omitempty"` Names map[string]string `json:"names,omitempty"` Type string `json:"type,omitempty"` } `json:"represented_country,omitempty"` Subdivision []struct { Confidence int `json:"confidence,omitempty"` GeoNameId uint `json:"geoname_id,omitempty"` IsoCode string `json:"iso_code,omitempty"` Names map[string]string `json:"names,omitempty"` } `json:"subdivisions,omitempty"` Traits struct { AutonomousSystemNumber int `json:"autonomous_system_number,omitempty"` AutonomousSystemOrganization string `json:"autonomous_system_organization,omitempty"` Domain string `json:"domain,omitempty"` IsAnonymousProxy bool `json:"is_anonymous_proxy,omitempty"` IsSatelliteProvider bool `json:"is_satellite_provider,omitempty"` Isp string `json:"isp,omitempty"` IpAddress string `json:"ip_address,omitempty"` Organization string `json:"organization,omitempty"` UserType string `json:"user_type,omitempty"` } `json:"traits,omitempty"` MaxMind struct { QueriesRemaining int `json:"queries_remaining,omitempty"` } `json:"maxmind,omitempty"` } func mustGetTestCountry() *Country { td, err := ioutil.ReadFile("testdata/response.json") if err != nil { panic(err) } c := new(Country) if err := json.Unmarshal(td, c); err != nil { panic(err) } return c } // TableStoreSlice represents a collection type for DB table store // Generated via tableToStruct. type TableStoreSlice []*TableStore // TableStore represents a type for DB table store // Generated via tableToStruct. type TableStore struct { StoreID int64 `db:"store_id" json:",omitempty"` // store_id smallint(5) unsigned NOT NULL PRI auto_increment Code string `db:"code" json:",omitempty"` // code varchar(32) NULL UNI WebsiteID int64 `db:"website_id" json:",omitempty"` // website_id smallint(5) unsigned NOT NULL MUL DEFAULT '0' GroupID int64 `db:"group_id" json:",omitempty"` // group_id smallint(5) unsigned NOT NULL MUL DEFAULT '0' Name string `db:"name" json:",omitempty"` // name varchar(255) NOT NULL SortOrder int64 `db:"sort_order" json:",omitempty"` // sort_order smallint(5) unsigned NOT NULL DEFAULT '0' IsActive bool `db:"is_active" json:",omitempty"` // is_active smallint(5) unsigned NOT NULL MUL DEFAULT '0' } func getTestStores() TableStoreSlice { return TableStoreSlice{ &TableStore{StoreID: 0, Code: "admin", WebsiteID: 0, GroupID: 0, Name: "Admin", SortOrder: 0, IsActive: true}, &TableStore{StoreID: 5, Code: "au", WebsiteID: 2, GroupID: 3, Name: "Australia", SortOrder: 10, IsActive: true}, &TableStore{StoreID: 1, Code: "de", WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true}, &TableStore{StoreID: 4, Code: "uk", WebsiteID: 1, GroupID: 2, Name: "UK", SortOrder: 10, IsActive: true}, &TableStore{StoreID: 2, Code: "at", WebsiteID: 1, GroupID: 1, Name: "Österreich", SortOrder: 20, IsActive: true}, &TableStore{StoreID: 6, Code: "nz", WebsiteID: 2, GroupID: 3, Name: "Kiwi", SortOrder: 30, IsActive: true}, &TableStore{IsActive: false, StoreID: 3, Code: "ch", WebsiteID: 1, GroupID: 1, Name: "Schweiz", SortOrder: 30}, } } func newServiceComplexParallelTest(t *testing.T, level2 objcache.NewStorageFn, so *objcache.ServiceOptions) { if so == nil { so = newSrvOpt(gobCodec{}, Country{}, TableStoreSlice{}) } p, err := objcache.NewService(objcache.NewBlackHoleClient(nil), level2, so) assert.NoError(t, err) defer func() { assert.NoError(t, p.Close()) }() // to detect race conditions run with -race ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) defer cancel() eg, _ := errgroup.WithContext(ctx) eg.Go(testCountry(p, "country_one")) eg.Go(testStoreSlice(p, "stores_one")) eg.Go(testCountry(p, "country_two")) eg.Go(testStoreSlice(p, "stores_two")) eg.Go(testStoreSlice(p, "stores_three")) eg.Go(testCountry(p, "country_three")) assert.NoError(t, eg.Wait()) } func newTestServiceDelete(t *testing.T, level2 objcache.NewStorageFn) { p, err := objcache.NewService(objcache.NewBlackHoleClient(nil), level2, newSrvOpt(JSONCodec{})) assert.NoError(t, err) defer func() { assert.NoError(t, p.Close()) }() t.Run("single key", func(t *testing.T) { err = p.Set(context.TODO(), "bc_delete", 1970, 0) assert.NoError(t, err) var bcInt int err = p.Get(context.TODO(), "bc_delete", &bcInt) assert.NoError(t, err) assert.Exactly(t, 1970, bcInt) err = p.Delete(context.TODO(), "bc_delete") assert.NoError(t, err) bcInt = 0 err = p.Get(context.TODO(), "bc_delete", &bcInt) assert.NoError(t, err, "%+v", err) assert.Exactly(t, 0, bcInt) }) t.Run("multiple keys", func(t *testing.T) { bcInt1 := 1971 bcInt2 := 1972 keys := []string{"bc_delete1", "bc_delete2"} vals := []interface{}{&bcInt1, &bcInt2} err = p.SetMulti(context.TODO(), keys, vals, nil) assert.NoError(t, err) bcInt1 = 0 bcInt2 = 0 err = p.GetMulti(context.TODO(), keys, vals) assert.NoError(t, err, "\n%+v", err) assert.Exactly(t, 1971, bcInt1) assert.Exactly(t, 1972, bcInt2) err = p.Delete(context.TODO(), "bc_delete1", "bc_delete2") assert.NoError(t, err) bcInt1 = 0 bcInt2 = 0 err = p.GetMulti(context.TODO(), keys, vals) assert.NoError(t, err, "%+v", err) assert.Exactly(t, 0, bcInt1) assert.Exactly(t, 0, bcInt2) }) } func testExpiration(t *testing.T, cb func(), level2 objcache.NewStorageFn, so *objcache.ServiceOptions) { p, err := objcache.NewService(nil, level2, so) if err != nil { t.Fatal(err) } defer func() { assert.NoError(t, p.Close()) }() key := strs.RandAlnum(30) if err := p.Set(context.TODO(), key, math.Pi, time.Second); err != nil { t.Fatalf("Key %q Error: %s", key, err) } var newVal float64 err = p.Get(context.TODO(), key, &newVal) assert.NoError(t, err, "%+v", err) assert.Exactly(t, math.Pi, newVal) cb() newVal = 0 err = p.Get(context.TODO(), key, &newVal) assert.NoError(t, err, "%+v", err) assert.Empty(t, newVal) } <|start_filename|>sql/ddl/replication.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ddl import ( "io" "strconv" "strings" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/dml" ) // MasterStatus provides status information about the binary log files of the // master. It requires either the SUPER or REPLICATION CLIENT privilege. Once a // MasterStatus pointer variable has been created it can be reused multiple // times. type MasterStatus struct { File string Position uint BinlogDoDB string BinlogIgnoreDB string // ExecutedGTIDSet: When global transaction IDs are in use, ExecutedGTIDSet // shows the set of GTIDs for transactions that have been executed on the // master. This is the same as the value for the gtid_executed system variable // on this server, as well as the value for ExecutedGTIDSet in the output of // SHOW SLAVE STATUS on this server. ExecutedGTIDSet string } // ToSQL implements dml.QueryBuilder interface to assemble a SQL string and its // arguments for query execution. func (ms MasterStatus) ToSQL() (string, []interface{}, error) { return "SHOW MASTER STATUS", nil, nil } // MapColumns implements dml.ColumnMapper interface to scan a row returned from // a database query. func (ms *MasterStatus) MapColumns(rc *dml.ColumnMap) error { for rc.Next(5) { switch col := rc.Column(); col { case "File", "0": rc.String(&ms.File) case "Position", "1": rc.Uint(&ms.Position) case "Binlog_Do_DB", "2": rc.String(&ms.BinlogDoDB) case "Binlog_Ignore_DB", "3": rc.String(&ms.BinlogIgnoreDB) case "Executed_Gtid_Set", "4": rc.String(&ms.ExecutedGTIDSet) default: return errors.NotFound.Newf("[ddl] Column %q not found in SHOW MASTER STATUS", col) } } return errors.WithStack(rc.Err()) } // Compare compares with another MasterStatus. Returns 1 if left hand side is // bigger, 0 if both are equal and -1 if right hand side is bigger. func (ms MasterStatus) Compare(other MasterStatus) int { switch { // First compare binlog name case ms.File > other.File: return 1 case ms.File < other.File: return -1 // Same binlog file, compare position case ms.Position > other.Position: return 1 case ms.Position < other.Position: return -1 } return 0 } // String converts the file name and the position to a string, separated by a // semi-colon. func (ms MasterStatus) String() string { if ms.File == "" { return "" } var str strings.Builder str.WriteString(ms.File) str.WriteByte(';') str.WriteString(strconv.FormatUint(uint64(ms.Position), 10)) return str.String() } var semicolon = []byte(`;`) // WriteTo implements io.WriterTo and writes the current position and file name // to w. func (ms MasterStatus) WriteTo(w io.Writer) (n int64, err error) { if ms.File == "" { return } n2, _ := w.Write([]byte(ms.File)) n += int64(n2) n2, _ = w.Write(semicolon) n += int64(n2) var buf [16]byte n2, _ = w.Write(strconv.AppendUint(buf[:0], uint64(ms.Position), 10)) n += int64(n2) return } // FromString parses as string in the format: mysql-bin.000002;236423 means // filename;position. func (ms *MasterStatus) FromString(str string) error { c := strings.IndexByte(str, ';') if c < 1 { return errors.NotFound.Newf("[ddl] MasterStatus FromString: Delimiter semi-colon not found.") } pos, err := strconv.ParseUint(str[c+1:], 10, 32) if err != nil { return errors.NotValid.Newf("[ddl] MasterStatus FromString: %s", err) } ms.File = str[:c] ms.Position = uint(pos) return nil } <|start_filename|>sql/urlvalues/values_proto_test.go<|end_filename|> // +build csall proto package urlvalues import ( "testing" "github.com/corestoreio/pkg/util/assert" ) func TestProtoToValues(t *testing.T) { vals := ProtoToValues(nil, &ProtoKeyValues{ Data: []*ProtoKeyValue{ {Key: "a", Value: []string{"b"}}, }, }) assert.Exactly(t, Values{"a": []string{"b"}}, vals) } func TestValuesToProto(t *testing.T) { pkv := ValuesToProto(Values{"a": []string{"b"}}) assert.Exactly(t, &ProtoKeyValues{ Data: []*ProtoKeyValue{ {Key: "a", Value: []string{"b"}}, }, }, pkv) } <|start_filename|>sql/dml/dml_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml_test import ( "database/sql" "encoding/json" "fmt" "reflect" "strings" "testing" "time" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) var now = func() time.Time { return time.Date(2006, 1, 2, 15, 4, 5, 02, time.FixedZone("hardcoded", -7)) } func init() { // Freeze time in package log log.Now = now null.MustSetJSONMarshaler(json.Marshal, json.Unmarshal) } var _ dml.ColumnMapper = (*dmlPerson)(nil) type dmlPerson struct { ID int64 Name string Email null.String Key null.String StoreID int64 CreatedAt time.Time TotalIncome float64 } func (p *dmlPerson) AssignLastInsertID(id int64) { p.ID = id } func (p *dmlPerson) MapColumns(cm *dml.ColumnMap) error { for cm.Next(7) { switch c := cm.Column(); c { case "id", "0": cm.Int64(&p.ID) case "name", "name2", "1": // name2 used in TestWithLogger_WithCTE cm.String(&p.Name) case "email", "email2", "2": // email2 used in TestWithLogger_WithCTE cm.NullString(&p.Email) case "key", "3": cm.NullString(&p.Key) case "store_id", "4": cm.Int64(&p.StoreID) case "created_at", "5": cm.Time(&p.CreatedAt) case "total_income", "6": cm.Float64(&p.TotalIncome) default: return errors.NotFound.Newf("[dml_test] dmlPerson Column %q not found", c) } } return cm.Err() } func createRealSession(t testing.TB, opts ...dml.ConnPoolOption) *dml.ConnPool { dsn := dmltest.MustGetDSN(t) cxn, err := dml.NewConnPool( append([]dml.ConnPoolOption{dml.WithDSN(dsn)}, opts...)..., ) if err != nil { t.Fatal(err) } return cxn } func installFixtures(t testing.TB, db *sql.DB) { // see also test case "LoadUint64 max Uint64 found" sqlToRun := []string{ "DROP TABLE IF EXISTS `dml_people`", fmt.Sprintf(` CREATE TABLE dml_people ( id bigint(8) unsigned NOT NULL auto_increment PRIMARY KEY, name varchar(255) NOT NULL, email varchar(255), %s varchar(255), store_id smallint(5) unsigned DEFAULT 0 COMMENT 'Store Id', created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Created At', total_income decimal(12,4) NOT NULL DEFAULT 0.0000 COMMENT 'Used as float64', avg_income decimal(12,5) COMMENT 'Used as Decimal' ) `, "`key`"), "INSERT INTO dml_people (name,email,avg_income) VALUES ('<NAME>', '<EMAIL>',333.66677)", "INSERT INTO dml_people (name,email) VALUES ('Dmitri', '<EMAIL>')", "INSERT INTO `dml_people` (id,name,email) VALUES (18446744073700551613,'Cyrill', '<EMAIL>')", } for _, sqlStr := range sqlToRun { _, err := db.Exec(sqlStr) assert.NoError(t, err, "With SQL statement: %q", sqlStr) } } // compareToSQL compares a SQL object with a placeholder string and an optional // interpolated string. This function also exists in file dml_public_test.go to // avoid import cycles when using a single package dedicated for testing. func compareToSQL( t testing.TB, qb dml.QueryBuilder, wantErrKind errors.Kind, wantSQLPlaceholders, wantSQLInterpolated string, wantArgs ...interface{}, ) { sqlStr, args, err := qb.ToSQL() if wantErrKind.Empty() { assert.NoError(t, err) } else { assert.ErrorIsKind(t, wantErrKind, err) } if wantSQLPlaceholders != "" { assert.Exactly(t, wantSQLPlaceholders, sqlStr, "Placeholder SQL strings do not match") assert.Exactly(t, wantArgs, args, "Placeholder Arguments do not match") } if wantSQLInterpolated == "" { return } if dmlArgs, ok := qb.(*dml.DBR); ok { prev := dmlArgs.Options qb = dmlArgs.Interpolate() defer func() { dmlArgs.Options = prev; qb = dmlArgs }() } sqlStr, args, err = qb.ToSQL() // Call with enabled interpolation assert.Nil(t, args, "DBR should be nil when the SQL string gets interpolated") if wantErrKind.Empty() { assert.NoError(t, err) } else { assert.ErrorIsKind(t, wantErrKind, err) } assert.Exactly(t, wantSQLInterpolated, sqlStr, "Interpolated SQL strings do not match") } func ifNotEqualPanic(have, want interface{}, msg ...string) { // The reason for this function is that I have no idea why testing.T is // blocking inside the bgwork.Wait function. if !reflect.DeepEqual(have, want) { panic(fmt.Sprintf("%q\nHave: %#v\nWant: %#v\n\n", strings.Join(msg, ""), have, want)) } } func ifErrPanic(err error) { if err != nil { panic(fmt.Sprintf("%+v", err)) } } func notEqualPointers(t *testing.T, o1, o2 interface{}, msgAndArgs ...interface{}) { p1 := reflect.ValueOf(o1) p2 := reflect.ValueOf(o2) if len(msgAndArgs) == 0 { msgAndArgs = []interface{}{"Pointers for type o1:%T o2:%T should not be equal", o1, o2} } assert.NotEqual(t, p1.Pointer(), p2.Pointer(), msgAndArgs...) } <|start_filename|>sql/dml/delete.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "github.com/corestoreio/errors" ) // Delete contains the clauses for a DELETE statement. // // InnoDB Tables: If you are deleting many rows from a large table, you may // exceed the lock table size for an InnoDB table. To avoid this problem, or // simply to minimize the time that the table remains locked, the following // strategy (which does not use DELETE at all) might be helpful: // // Select the rows not to be deleted into an empty table that has the same // structure as the original table: // INSERT INTO t_copy SELECT * FROM t WHERE ... ; // Use RENAME TABLE to atomically move the original table out of the way and // rename the copy to the original name: // RENAME TABLE t TO t_old, t_copy TO t; // Drop the original table: // DROP TABLE t_old; // No other sessions can access the tables involved while RENAME TABLE executes, // so the rename operation is not subject to concurrency problems. type Delete struct { BuilderBase BuilderConditional // MultiTables specifies the additional tables to delete from. Use function // `FromTables` to conveniently set it. MultiTables ids // Returning allows from MariaDB 10.0.5, it is possible to return a // resultset of the deleted rows for a single table to the client by using // the syntax DELETE ... RETURNING select_expr [, select_expr2 ...]] Any of // SQL expression that can be calculated from a single row fields is // allowed. Subqueries are allowed. The AS keyword is allowed, so it is // possible to use aliases. The use of aggregate functions is not allowed. // RETURNING cannot be used in multi-table DELETEs. Returning *Select } // NewDelete creates a new Delete object. func NewDelete(from string) *Delete { return &Delete{ BuilderBase: BuilderBase{ Table: MakeIdentifier(from), }, BuilderConditional: BuilderConditional{ Wheres: make(Conditions, 0, 2), }, } } // FromTables specifies additional tables to delete from besides the default table. func (b *Delete) FromTables(tables ...string) *Delete { // DELETE [LOW_PRIORITY] [QUICK] [IGNORE] // tbl_name[.*] [, tbl_name[.*]] ... <-- MultiTables/FromTables // FROM table_references //[WHERE where_condition] for _, t := range tables { b.MultiTables = append(b.MultiTables, MakeIdentifier(t)) } return b } // Join creates an INNER join construct. By default, the onConditions are glued // together with AND. Same Source and Target Table: Until MariaDB 10.3.1, // deleting from a table with the same source and target was not possible. From // MariaDB 10.3.1, this is now possible. For example: // DELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0); func (b *Delete) Join(table id, onConditions ...*Condition) *Delete { b.join("INNER", table, onConditions...) return b } // LeftJoin creates a LEFT join construct. By default, the onConditions are // glued together with AND. func (b *Delete) LeftJoin(table id, onConditions ...*Condition) *Delete { b.join("LEFT", table, onConditions...) return b } // RightJoin creates a RIGHT join construct. By default, the onConditions are // glued together with AND. func (b *Delete) RightJoin(table id, onConditions ...*Condition) *Delete { b.join("RIGHT", table, onConditions...) return b } // OuterJoin creates an OUTER join construct. By default, the onConditions are // glued together with AND. func (b *Delete) OuterJoin(table id, onConditions ...*Condition) *Delete { b.join("OUTER", table, onConditions...) return b } // CrossJoin creates a CROSS join construct. By default, the onConditions are // glued together with AND. func (b *Delete) CrossJoin(table id, onConditions ...*Condition) *Delete { b.join("CROSS", table, onConditions...) return b } // Alias sets an alias for the table name. func (b *Delete) Alias(alias string) *Delete { b.Table.Aliased = alias return b } // Unsafe see BuilderBase.IsUnsafe which weakens security when building the SQL // string. This function must be called before calling any other function. func (b *Delete) Unsafe() *Delete { b.IsUnsafe = true return b } // Where appends a WHERE clause to the statement whereSQLOrMap can be a string // or map. If it'ab a string, args wil replaces any places holders. func (b *Delete) Where(wf ...*Condition) *Delete { b.Wheres = append(b.Wheres, wf...) return b } // OrderBy appends columns to the ORDER BY statement for ascending sorting. A // column gets always quoted if it is a valid identifier otherwise it will be // treated as an expression. When you use ORDER BY or GROUP BY to sort a column // in a DELETE, the server sorts arguments using only the initial number of // bytes indicated by the max_sort_length system variable. // A column name can also contain the suffix words " ASC" or " DESC" to indicate // the sorting. This avoids using the method OrderByDesc when sorting certain // columns descending. func (b *Delete) OrderBy(columns ...string) *Delete { b.OrderBys = b.OrderBys.AppendColumns(b.IsUnsafe, columns...) return b } // OrderByDesc appends columns to the ORDER BY statement for descending sorting. // A column gets always quoted if it is a valid identifier otherwise it will be // treated as an expression. When you use ORDER BY or GROUP BY to sort a column // in a DELETE, the server sorts arguments using only the initial number of // bytes indicated by the max_sort_length system variable. func (b *Delete) OrderByDesc(columns ...string) *Delete { b.OrderBys = b.OrderBys.AppendColumns(b.IsUnsafe, columns...).applySort(len(columns), sortDescending) return b } // Limit sets a LIMIT clause for the statement; overrides any existing LIMIT func (b *Delete) Limit(limit uint64) *Delete { b.LimitCount = limit b.LimitValid = true return b } // ToSQL generates the SQL string and might caches it internally, if not // disabled. The returned interface slice is always nil. func (b *Delete) ToSQL() (string, []interface{}, error) { rawSQL, err := b.buildToSQL(b) if err != nil { return "", nil, errors.WithStack(err) } return rawSQL, nil, nil } // ToSQL serialized the Delete to a SQL string // It returns the string with placeholders and a slice of query arguments func (b *Delete) toSQL(w *bytes.Buffer, placeHolders []string) (_ []string, err error) { if b.Table.Name == "" { return nil, errors.Empty.Newf("[dml] Delete: Table is missing") } w.WriteString("DELETE ") for i, mt := range b.MultiTables { if i == 0 { if b.Table.Aliased != "" { Quoter.WriteIdentifier(w, b.Table.Aliased) } else { Quoter.WriteIdentifier(w, b.Table.Name) } w.WriteByte(',') } if i > 0 { w.WriteByte(',') } placeHolders, err = mt.writeQuoted(w, placeHolders) if err != nil { return nil, errors.WithStack(err) } } if len(b.MultiTables) > 0 { w.WriteByte(' ') if b.Returning != nil { return nil, errors.NotAllowed.Newf("[dml] MariaDB does not support RETURNING in multi-table DELETEs") } } w.WriteString("FROM ") placeHolders, err = b.Table.writeQuoted(w, placeHolders) if err != nil { return nil, errors.WithStack(err) } for _, f := range b.Joins { w.WriteByte(' ') w.WriteString(f.JoinType) w.WriteString(" JOIN ") if placeHolders, err = f.Table.writeQuoted(w, placeHolders); err != nil { return nil, errors.WithStack(err) } if placeHolders, err = f.On.write(w, 'j', placeHolders, b.isWithDBR); err != nil { return nil, errors.WithStack(err) } } placeHolders, err = b.Wheres.write(w, 'w', placeHolders, b.isWithDBR) if err != nil { return nil, errors.WithStack(err) } sqlWriteOrderBy(w, b.OrderBys, false) sqlWriteLimitOffset(w, b.LimitValid, false, 0, b.LimitCount) if b.Returning != nil { w.WriteString(" RETURNING ") placeHolders, err = b.Returning.toSQL(w, placeHolders) if err != nil { return nil, errors.WithStack(err) } } return placeHolders, nil } // Clone creates a clone of the current object, leaving fields DB and Log // untouched. func (b *Delete) Clone() *Delete { if b == nil { return nil } c := *b c.BuilderBase = b.BuilderBase.Clone() c.BuilderConditional = b.BuilderConditional.Clone() c.MultiTables = b.MultiTables.Clone() c.Returning = b.Returning.Clone() return &c } <|start_filename|>sql/ddl/tables_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ddl_test import ( "context" "database/sql" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func TestNewTableServicePanic(t *testing.T) { defer func() { if r := recover(); r != nil { err := r.(error) assert.ErrorIsKind(t, errors.NotValid, err) } else { t.Error("Expecting a panic") } }() _ = ddl.MustNewTables( ddl.WithCreateTable(context.TODO(), ""), ) } func TestTables_Upsert_Insert(t *testing.T) { ts := ddl.MustNewTables() t.Run("Insert OK", func(t *testing.T) { assert.NoError(t, ts.Upsert(ddl.NewTable("test1"))) assert.Equal(t, 1, ts.Len()) }) } func TestTables_DeleteFromCache(t *testing.T) { ts := ddl.MustNewTables(ddl.WithCreateTable(context.TODO(), "a3", "", "b5", "", "c7", "")) t.Run("Delete One", func(t *testing.T) { ts.DeleteFromCache("b5") assert.Exactly(t, 2, ts.Len()) }) t.Run("Delete All does nothing", func(t *testing.T) { ts.DeleteFromCache() assert.Exactly(t, 2, ts.Len()) }) } func TestTables_DeleteAllFromCache(t *testing.T) { ts := ddl.MustNewTables(ddl.WithCreateTable(context.TODO(), "a3", "", "b5", "", "c7", "")) ts.DeleteAllFromCache() assert.Exactly(t, 0, ts.Len()) } func TestTables_Truncate(t *testing.T) { db, mock := dmltest.MockDB(t) defer dmltest.MockClose(t, db, mock) mock.MatchExpectationsInOrder(false) // because we're dealing with a table map, hence tables truncates are random. mock.ExpectExec("SET foreign_key_checks = 0;").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("TRUNCATE TABLE `a3`").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("TRUNCATE TABLE `b5`").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("TRUNCATE TABLE `c7`").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("SET foreign_key_checks = 1;").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) ctx := context.TODO() ts := ddl.MustNewTables(ddl.WithCreateTable(ctx, "a3", "", "b5", "", "c7", "")) _ = ts.Options(ddl.WithConnPool(db)) err := ts.Truncate(ctx, ddl.Options{}) assert.NoError(t, err) } func TestTables_Optimize(t *testing.T) { t.Run("ok", func(t *testing.T) { db, mock := dmltest.MockDB(t) defer dmltest.MockClose(t, db, mock) mock.ExpectExec("OPTIMIZE TABLE `a3`,`b5`,`c7`").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) ctx := context.TODO() ts := ddl.MustNewTables(ddl.WithCreateTable(ctx, "a3", "", "b5", "", "c7", "")) _ = ts.Options(ddl.WithConnPool(db)) err := ts.Optimize(ctx, ddl.Options{}) assert.NoError(t, err) }) t.Run("wait", func(t *testing.T) { db, mock := dmltest.MockDB(t) defer dmltest.MockClose(t, db, mock) mock.ExpectExec("OPTIMIZE TABLE `a3`,`b5`,`c7` WAIT 1").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) ctx := context.TODO() ts := ddl.MustNewTables(ddl.WithCreateTable(ctx, "a3", "", "b5", "", "c7", "")) _ = ts.Options(ddl.WithConnPool(db)) err := ts.Optimize(ctx, ddl.Options{Wait: time.Second}) assert.NoError(t, err) }) t.Run("nowait", func(t *testing.T) { db, mock := dmltest.MockDB(t) defer dmltest.MockClose(t, db, mock) mock.ExpectExec("OPTIMIZE TABLE `a3`,`b5`,`c7` NOWAIT").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) ctx := context.TODO() ts := ddl.MustNewTables(ddl.WithCreateTable(ctx, "a3", "", "b5", "", "c7", "")) _ = ts.Options(ddl.WithConnPool(db)) err := ts.Optimize(ctx, ddl.Options{Nowait: true}) assert.NoError(t, err) }) } func TestTables_Lock(t *testing.T) { dbc, mock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, mock) ctx := context.TODO() ts := ddl.MustNewTables(ddl.WithCreateTable(ctx, "store_website", "", "store_group", "", "store", "", "x910cms_block", "")) _ = ts.Options(ddl.WithConnPool(dbc)) // set connection after call to WithCreateTable to avoid SELECT FROM information_schema for _, sqlStr := range [...]string{ "LOCK TABLES `store_website` READ", "LOCK TABLES `store_website` READ ,`store_group` WRITE", "LOCK TABLES `store_website` AS `sw` READ ,`store_group` AS `sg` READ LOCAL", "LOCK TABLES `store_website` AS `sw` LOW_PRIORITY WRITE ,`store_group` AS `sg` WRITE CONCURRENT", "LOCK TABLES `store_website` READ ,`store_group` WRITE WAIT 1", "LOCK TABLES `store_website` READ ,`store_group` WRITE NOWAIT", } { mock.ExpectExec(sqlStr).WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("UNLOCK TABLES").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) } runner := func(o ddl.Options, tl []ddl.TableLock) func(*testing.T) { return func(t *testing.T) { var called int err := ts.Lock(ctx, o, tl, func(conn *dml.Conn) error { called++ return nil }) assert.NoError(t, err) assert.Exactly(t, 1, called) } } t.Run("one table lock read", runner(ddl.Options{}, []ddl.TableLock{ {Name: "store_website", LockTypeREAD: true}, })) t.Run("two tables lock read,write", runner(ddl.Options{}, []ddl.TableLock{ {Name: "store_website", LockTypeREAD: true}, {Name: "store_group", LockTypeWRITE: true}, })) t.Run("two tables with aliases lock read,read local", runner(ddl.Options{}, []ddl.TableLock{ {Name: "store_website", Alias: "sw", LockTypeREAD: true}, {Name: "store_group", Alias: "sg", LockTypeREADLOCAL: true}, })) t.Run("two tables with aliases lock low prio,write concurrent", runner(ddl.Options{}, []ddl.TableLock{ {Name: "store_website", Alias: "sw", LockTypeLowPriorityWrite: true}, {Name: "store_group", Alias: "sg", LockTypeWriteConcurrent: true}, })) t.Run("two tables lock read,write, wait", runner(ddl.Options{Wait: time.Second}, []ddl.TableLock{ {Name: "store_website", LockTypeREAD: true}, {Name: "store_group", LockTypeWRITE: true}, })) t.Run("two tables lock read,write, nowait", runner(ddl.Options{Nowait: true}, []ddl.TableLock{ {Name: "store_website", LockTypeREAD: true}, {Name: "store_group", LockTypeWRITE: true}, })) mock.ExpectExec("LOCK TABLES `x910cms_block` READ").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("UNLOCK TABLES").WithArgs().WillReturnResult(sqlmock.NewResult(0, 0)) t.Run("one table lock read, returns error", func(t *testing.T) { err := ts.Lock(ctx, ddl.Options{}, []ddl.TableLock{ {Name: "x910cms_block", LockTypeREAD: true}, }, func(conn *dml.Conn) error { return errors.Fatal.Newf("Upsssss") }) assert.ErrorIsKind(t, errors.Fatal, err) }) } func TestTables_Upsert_Update(t *testing.T) { ts := ddl.MustNewTables(ddl.WithCreateTable(context.TODO(), "a3", "", "b5", "", "c7", "")) t.Run("One", func(t *testing.T) { _ = ts.Upsert(ddl.NewTable("x5")) assert.Exactly(t, 4, ts.Len()) tb, err := ts.Table("x5") assert.NoError(t, err, "%+v", err) assert.Exactly(t, `x5`, tb.Name) }) } func TestTables_MustTable(t *testing.T) { defer func() { if r := recover(); r != nil { err := r.(error) assert.ErrorIsKind(t, errors.NotValid, err) } else { t.Error("Expecting a panic") } }() ts := ddl.MustNewTables(ddl.WithCreateTable(context.TODO(), "a3")) tbl := ts.MustTable("a3") assert.NotNil(t, tbl) tbl = ts.MustTable("a44") assert.Nil(t, tbl) } func TestWithTableNames(t *testing.T) { ts := ddl.MustNewTables(ddl.WithCreateTable(context.TODO(), "a3", "", "b5", "", "c7", "")) t.Run("Ok", func(t *testing.T) { assert.Exactly(t, "a3", ts.MustTable("a3").Name) assert.Exactly(t, "b5", ts.MustTable("b5").Name) assert.Exactly(t, "c7", ts.MustTable("c7").Name) }) t.Run("Invalid Identifier", func(t *testing.T) { err := ts.Options(ddl.WithCreateTable(context.TODO(), "x1", "")) assert.ErrorIsKind(t, errors.NotValid, err) assert.Contains(t, err.Error(), `identifier "x\uf8ff1" (Case 2)`) }) } func TestWithCreateTable_IsView(t *testing.T) { ts := ddl.MustNewTables(ddl.WithCreateTable(context.TODO(), "view_a3", "", "b5_view", "", "c7", "CREATEA VIEW `c7` ...", "d2", "")) t.Run("IsView", func(t *testing.T) { assert.True(t, ts.MustTable("view_a3").IsView()) assert.True(t, ts.MustTable("b5_view").IsView()) assert.True(t, ts.MustTable("c7").IsView()) assert.False(t, ts.MustTable("d2").IsView()) }) } func TestWithCreateTable_Mock_DoesNotCreateTable(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) rows := sqlmock.NewRows([]string{"TABLE_NAME", "COLUMN_NAME", "ORDINAL_POSITION", "COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE", "COLUMN_KEY", "EXTRA", "COLUMN_COMMENT"}). FromCSVString( `"admin_user","user_id",1,0,"NO","int",0,10,0,"int(10) unsigned","PRI","auto_increment","User ID" "admin_user","firsname",2,NULL,"YES","varchar",32,0,0,"varchar(32)","","","User First Name" "admin_user","modified",8,"CURRENT_TIMESTAMP","NO","timestamp",0,0,0,"timestamp","","on update CURRENT_TIMESTAMP","User Modified Time" `) dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE\\(\\) AND TABLE_NAME.+"). WillReturnRows(rows) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTable(context.TODO(), "admin_user", "CREATE BUGGY TABLE"), ) assert.NoError(t, err, "%+v", err) table := tm0.MustTable("admin_user") assert.Exactly(t, []string{"user_id", "firsname", "modified"}, table.Columns.FieldNames()) // t.Log(table.Columns.GoString()) } func TestWithCreateTable_Mock_DoesCreateTable(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("CREATE TABLE `admin_user` ( user_id int(10), PRIMARY KEY (user_id))")). WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE\\(\\) AND TABLE_NAME.+"). WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME", "COLUMN_NAME", "ORDINAL_POSITION", "COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE", "COLUMN_KEY", "EXTRA", "COLUMN_COMMENT"}). FromCSVString(`"admin_user","user_id",1,0,"NO","int",0,10,0,"int(10) unsigned","PRI","auto_increment","User ID" "admin_user","firsname",2,NULL,"YES","varchar",32,0,0,"varchar(32)","","","User First Name" "admin_user","modified",8,"CURRENT_TIMESTAMP","NO","timestamp",0,0,0,"timestamp","","on update CURRENT_TIMESTAMP","User Modified Time" `)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTable(context.TODO(), "admin_user", "CREATE TABLE `admin_user` ( user_id int(10), PRIMARY KEY (user_id))"), ) assert.NoError(t, err, "%+v", err) table := tm0.MustTable("admin_user") assert.Exactly(t, []string{"user_id", "firsname", "modified"}, table.Columns.FieldNames()) // t.Log(table.Columns.GoString()) } func TestWithCreateTableFromFile(t *testing.T) { t.Run("case01 load one file one table correctly", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("CREATE TABLE `core_config_data` ( `config_id` int(10) )")). WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE\\(\\) AND TABLE_NAME.+"). WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME", "COLUMN_NAME", "ORDINAL_POSITION", "COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE", "COLUMN_KEY", "EXTRA", "COLUMN_COMMENT"}). FromCSVString(`"core_config_data","config_id",1,0,"NO","int",0,10,0,"int(10)","","","" `)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTableFromFile(context.TODO(), "testdata/case01_*", "core_config_data"), ) assert.NoError(t, err, "%+v", err) table := tm0.MustTable("core_config_data") assert.Exactly(t, []string{"config_id"}, table.Columns.FieldNames()) }) t.Run("case02 not a CREATE stmt and fails", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTableFromFile(context.TODO(), "testdata/case02_*", "core_config_data"), ) assert.ErrorIsKind(t, errors.NotAllowed, err) assert.Nil(t, tm0) }) t.Run("case03 table name not found in file name", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTableFromFile(context.TODO(), "testdata/case03_*", "core_config_data"), ) assert.ErrorIsKind(t, errors.Mismatch, err) assert.Nil(t, tm0) }) t.Run("case04 table name not found in file content", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTableFromFile(context.TODO(), "testdata/case04_*", "core_config_data"), ) assert.ErrorIsKind(t, errors.NotAllowed, err) assert.Nil(t, tm0) }) t.Run("case05 load two files two tables correctly", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("CREATE TABLE `core_config_data` ( `config_id` int(10) )")). WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("CREATE TABLE `admin_user` ( `id` int(10) )")). WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE\\(\\) AND TABLE_NAME.+"). WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME", "COLUMN_NAME", "ORDINAL_POSITION", "COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE", "COLUMN_KEY", "EXTRA", "COLUMN_COMMENT"}). FromCSVString(`"core_config_data","config_id",1,0,"NO","int",0,10,0,"int(10)","","","" "admin_user","id",1,0,"NO","int",0,10,0,"int(10)","","","" `)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithCreateTableFromFile(context.TODO(), "testdata/case05_*", "core_config_data", "admin_user"), ) assert.NoError(t, err, "%+v", err) assert.Exactly(t, []string{"config_id"}, tm0.MustTable("core_config_data").Columns.FieldNames()) assert.Exactly(t, []string{"id"}, tm0.MustTable("admin_user").Columns.FieldNames()) }) } func TestWithDropTable(t *testing.T) { t.Run("not previously registered", func(t *testing.T) { t.Run("with DISABLE_FOREIGN_KEY_CHECKS", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec(`SET FOREIGN_KEY_CHECKS=0`).WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec("DROP TABLE IF EXISTS `admin_user`").WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec("DROP TABLE IF EXISTS `admin_role`").WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec("DROP VIEW IF EXISTS `view_admin_perm`").WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec(`SET FOREIGN_KEY_CHECKS=1`).WillReturnResult(sqlmock.NewResult(0, 0)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithDropTable(context.TODO(), "DISABLE_FOREIGN_KEY_CHECKS", "admin_user", "admin_role", "view_admin_perm"), ) assert.NoError(t, err, "%+v", err) _ = tm0 }) t.Run("with DISABLE_FOREIGN_KEY_CHECKS, invalid identifier", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec(`SET FOREIGN_KEY_CHECKS=0`).WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec(`SET FOREIGN_KEY_CHECKS=1`).WillReturnResult(sqlmock.NewResult(0, 0)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithDropTable(context.TODO(), "DISABLE_FOREIGN_KEY_CHECKS", "admin_user"), ) assert.Nil(t, tm0) assert.ErrorIsKind(t, errors.NotValid, err) }) t.Run("without DISABLE_FOREIGN_KEY_CHECKS", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec("DROP TABLE IF EXISTS `admin_user`").WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec("DROP TABLE IF EXISTS `admin_role`").WillReturnResult(sqlmock.NewResult(0, 0)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithDropTable(context.TODO(), "", "admin_user", "admin_role"), ) assert.NoError(t, err, "%+v", err) _ = tm0 }) }) t.Run("previously registered at Tables", func(t *testing.T) { t.Run("with DISABLE_FOREIGN_KEY_CHECKS", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) dbMock.ExpectExec(`SET FOREIGN_KEY_CHECKS=0`).WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec("DROP TABLE IF EXISTS `admin_user`").WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec("DROP TABLE IF EXISTS `admin_role`").WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectExec(`SET FOREIGN_KEY_CHECKS=1`).WillReturnResult(sqlmock.NewResult(0, 0)) tm0, err := ddl.NewTables( ddl.WithDB(dbc.DB), ddl.WithTable("admin_user"), ddl.WithTable("admin_role"), ddl.WithDropTable(context.TODO(), "DISABLE_FOREIGN_KEY_CHECKS", "admin_user", "admin_role"), ) assert.NoError(t, err, "%+v", err) _ = tm0 }) }) } func TestWithCreateTable_FromQuery(t *testing.T) { t.Run("create table fails", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) xErr := errors.AlreadyClosed.Newf("Connection already closed") dbMock.ExpectExec(dmltest.SQLMockQuoteMeta("CREATE TABLE `testTable` AS SELECT * FROM catalog_product_entity")).WillReturnError(xErr) tbls, err := ddl.NewTables(ddl.WithDB(dbc.DB), ddl.WithCreateTable(context.TODO(), "testTable", "CREATE TABLE `testTable` AS SELECT * FROM catalog_product_entity")) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.AlreadyClosed, err) }) t.Run("load columns fails", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) xErr := errors.AlreadyClosed.Newf("Connection already closed") dbMock. ExpectExec(dmltest.SQLMockQuoteMeta("CREATE TABLE `testTable` AS SELECT * FROM catalog_product_entity")). WillReturnResult(sqlmock.NewResult(0, 0)) dbMock.ExpectQuery("SELEC.+\\s+FROM\\s+information_schema\\.COLUMNS").WillReturnError(xErr) tbls, err := ddl.NewTables(ddl.WithDB(dbc.DB), ddl.WithCreateTable(context.TODO(), "testTable", "CREATE TABLE `testTable` AS SELECT * FROM catalog_product_entity")) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.AlreadyClosed, err) }) } func newCCD(db *sql.DB) *ddl.Tables { return ddl.MustNewTables( ddl.WithDB(db), ddl.WithTable( "core_config_data", &ddl.Column{Field: `config_id`, ColumnType: `int(10) unsigned`, Null: `NO`, Key: `PRI`, Extra: `auto_increment`}, &ddl.Column{Field: `scope`, ColumnType: `varchar(8)`, Null: `NO`, Key: `MUL`, Default: null.MakeString(`default`), Extra: ""}, &ddl.Column{Field: `scope_id`, ColumnType: `int(11)`, Null: `NO`, Key: "", Default: null.MakeString(`0`), Extra: ""}, &ddl.Column{Field: `path`, ColumnType: `varchar(255)`, Null: `NO`, Key: "", Default: null.MakeString(`general`), Extra: ""}, &ddl.Column{Field: `value`, ColumnType: `text`, Null: `YES`, Key: ``, Extra: ""}, ), ) } func TestTables_Validate(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) tbls := newCCD(dbc.DB) t.Run("context timeout", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() err := tbls.Validate(ctx) err = errors.Cause(err) assert.EqualError(t, err, "context canceled") }) t.Run("Validation OK", func(t *testing.T) { dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) err := tbls.Validate(context.Background()) assert.NoError(t, err, "Validation should succeed") }) t.Run("mismatch field name", func(t *testing.T) { tbls.MustTable("core_config_data").Columns[0].Field = "configID" dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) err := tbls.Validate(context.Background()) assert.ErrorIsKind(t, errors.Mismatch, err) assert.EqualError(t, err, "[ddl] Table \"core_config_data\" with column name \"configID\" at index 0 does not match database column name \"config_id\"") tbls.MustTable("core_config_data").Columns[0].Field = "config_id" }) t.Run("mismatch column type", func(t *testing.T) { tbls.MustTable("core_config_data").Columns[0].ColumnType = "varchar(XX)" dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) err := tbls.Validate(context.Background()) assert.ErrorIsKind(t, errors.Mismatch, err) assert.EqualError(t, err, "[ddl] Table \"core_config_data\" with Go column name \"config_id\" does not match MySQL column type. MySQL: \"int(10) unsigned\" Go: \"varchar(XX)\".") tbls.MustTable("core_config_data").Columns[0].ColumnType = "int(10) unsigned" }) t.Run("mismatch null property", func(t *testing.T) { tbls.MustTable("core_config_data").Columns[0].Null = "YES" dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) err := tbls.Validate(context.Background()) assert.ErrorIsKind(t, errors.Mismatch, err) assert.EqualError(t, err, "[ddl] Table \"core_config_data\" with column name \"config_id\" does not match MySQL null types. MySQL: \"NO\" Go: \"YES\"") tbls.MustTable("core_config_data").Columns[0].Null = "NO" }) t.Run("too many tables", func(t *testing.T) { tbls := ddl.MustNewTables( ddl.WithTable("core_config_data", &ddl.Column{Field: `config_id`, ColumnType: `int(10) unsigned`, Null: `NO`, Key: `PRI`, Extra: `auto_increment`}, ), ddl.WithTable("customer_entity", &ddl.Column{Field: `config_id`, ColumnType: `int(10) unsigned`, Null: `NO`, Key: `PRI`, Extra: `auto_increment`}, ), ddl.WithDB(dbc.DB), ) dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) err := tbls.Validate(context.Background()) assert.ErrorIsKind(t, errors.Mismatch, err) assert.EqualError(t, err, "[ddl] Tables count 2 does not match table count 1 in database.") }) t.Run("less columns", func(t *testing.T) { dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns_less.csv"))) err := tbls.Validate(context.Background()) assert.ErrorIsKind(t, errors.Mismatch, err) assert.EqualError(t, err, "[ddl] Table \"core_config_data\" has more columns (count 5) than its object (column count 4) in the database.") }) t.Run("more columns", func(t *testing.T) { dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns_more.csv"))) err := tbls.Validate(context.Background()) assert.NoError(t, err) }) } func TestWithLoadTables(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) ctx := context.TODO() t.Run("one table", func(t *testing.T) { dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE.+TABLE_NAME IN.+"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) dbMock.ExpectQuery("SELECT.+FROM information_schema.TABLES WHERE.+TABLE_NAME IN.+"). WithArgs(). // no args because interpolation due to valid identifier WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_tables.csv"))) tbls, err := ddl.NewTables(ddl.WithLoadTables(ctx, dbc.DB, "core_config_data")) assert.NoError(t, err) tbl := tbls.MustTable("core_config_data") assert.Exactly(t, "Config Data", tbl.TableComment) assert.False(t, tbl.IsView()) }) t.Run("multiple tables", func(t *testing.T) { dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE.+DATABASE\\(\\) ORDER.+"). WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv"))) dbMock.ExpectQuery("SELECT.+FROM information_schema.TABLES WHERE.+DATABASE\\(\\) ORDER.+"). WithArgs(). // no args because interpolation due to valid identifier WillReturnRows( dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_tables.csv"))) tbls, err := ddl.NewTables(ddl.WithLoadTables(ctx, dbc.DB)) // loads all tables in a DB assert.NoError(t, err) tbl := tbls.MustTable("core_config_data") assert.Exactly(t, "Config Data", tbl.TableComment) assert.False(t, tbl.IsView()) }) } func TestWithQueryDBR(t *testing.T) { p, err := dml.NewConnPool() assert.NoError(t, err) ts := ddl.MustNewTables(ddl.WithConnPool(p)) err = ts.Options(ddl.WithQueryDBR(map[string]dml.QueryBuilder{ "key1": dml.NewSelect("*").From("a1"), })) assert.NoError(t, err) assert.Exactly(t, map[string]string{"key1": "SELECT * FROM `a1`"}, ts.ConnPool.CachedQueries()) sqlStr, _, err := ts.ConnPool.WithCacheKey("key1").ToSQL() assert.NoError(t, err) assert.Exactly(t, "SELECT * FROM `a1`", sqlStr) } <|start_filename|>sql/dml/interpolate_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "database/sql" "database/sql/driver" "fmt" "testing" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) var ( _ fmt.Stringer = (*ip)(nil) _ QueryBuilder = (*ip)(nil) ) func TestExpandPlaceHolders(t *testing.T) { cp, err := NewConnPool() assert.NoError(t, err) t.Run("MisMatch", func(t *testing.T) { a := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN (?)")).ExpandPlaceHolders() compareToSQL2(t, a, errors.NoKind, "SELECT * FROM `table` WHERE id IN (?)") }) t.Run("MisMatch length reps", func(t *testing.T) { a := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN ?")).ExpandPlaceHolders().TestWithArgs([]int64{1, 2}, []string{"d", "3"}) compareToSQL2(t, a, errors.Mismatch, "") }) t.Run("MisMatch qMarks", func(t *testing.T) { a := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN(!)")).ExpandPlaceHolders().TestWithArgs(3) compareToSQL2(t, a, errors.Mismatch, "") }) t.Run("one arg with one value", func(t *testing.T) { a := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN (?)")).ExpandPlaceHolders().TestWithArgs(1) compareToSQL2(t, a, errors.NoKind, "SELECT * FROM `table` WHERE id IN (?)", int64(1)) }) t.Run("one arg with three values", func(t *testing.T) { a := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN ?")).ExpandPlaceHolders().TestWithArgs([]int64{11, 3, 5}) compareToSQL2(t, a, errors.NoKind, "SELECT * FROM `table` WHERE id IN (?,?,?)", int64(11), int64(3), int64(5)) }) t.Run("multi 3,5 times replacement", func(t *testing.T) { a := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN ? AND name IN ?")).ExpandPlaceHolders(). TestWithArgs([]int64{5, 7, 9}, []string{"a", "b", "c", "d", "e"}) compareToSQL2(t, a, errors.NoKind, "SELECT * FROM `table` WHERE id IN (?,?,?) AND name IN (?,?,?,?,?)", int64(5), int64(7), int64(9), "a", "b", "c", "d", "e", ) }) } func TestInterpolate_Nil(t *testing.T) { t.Run("one nil", func(t *testing.T) { ip := Interpolate("SELECT * FROM x WHERE a = ?").Null() assert.Exactly(t, "SELECT * FROM x WHERE a = NULL", ip.String()) ip = Interpolate("SELECT * FROM x WHERE a = ?").Null() assert.Exactly(t, "SELECT * FROM x WHERE a = NULL", ip.String()) }) t.Run("two nil", func(t *testing.T) { ip := Interpolate("SELECT * FROM x WHERE a BETWEEN ? AND ?").Null().Null() assert.Exactly(t, "SELECT * FROM x WHERE a BETWEEN NULL AND NULL", ip.String()) ip = Interpolate("SELECT * FROM x WHERE a BETWEEN ? AND ?").Null().Null() assert.Exactly(t, "SELECT * FROM x WHERE a BETWEEN NULL AND NULL", ip.String()) }) t.Run("one nil between two values", func(t *testing.T) { ip := Interpolate("SELECT * FROM x WHERE a BETWEEN ? AND ? OR Y=?").Int(1).Null().Str("X") assert.Exactly(t, "SELECT * FROM x WHERE a BETWEEN 1 AND NULL OR Y='X'", ip.String()) }) } func TestInterpolate_AllTypes(t *testing.T) { sqlStr, args, err := Interpolate(`SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?`). Null(). Unsafe(`Unsafe`). Int(2). Ints(3, 4). Int64(5). Int64s(6, 7). Uint64(8). Uint64s(9, 10). Float64(11.1). Float64s(12.12, 13.13). Str("14"). Strs("15", "16"). Bool(true). Bools(false, true, false). Bytes([]byte(`17-18`)). BytesSlice([]byte(`19-20`), nil, []byte(`21`)). Time(now()). Times(now(), now()). NullString(null.MakeString("22")). NullStrings(null.MakeString("23"), null.String{}, null.MakeString("24")). NullFloat64(null.MakeFloat64(25.25)). NullFloat64s(null.MakeFloat64(26.26), null.Float64{}, null.MakeFloat64(27.27)). NullInt64(null.MakeInt64(28)). NullInt64s(null.MakeInt64(29), null.Int64{}, null.MakeInt64(30)). NullBool(null.MakeBool(true)). NullBools(null.MakeBool(true), null.Bool{}, null.MakeBool(false)). NullTime(null.MakeTime(now())). NullTimes(null.MakeTime(now()), null.Time{}, null.MakeTime(now())). ToSQL() assert.NoError(t, err) assert.Nil(t, args) assert.Exactly(t, "SELECT NULL,'Unsafe',2,(3,4),5,(6,7),8,(9,10),11.1,(12.12,13.13),'14',('15','16'),1,(0,1,0),'17-18',('19-20',NULL,'21'),'2006-01-02 15:04:05',('2006-01-02 15:04:05','2006-01-02 15:04:05'),'22',('23',NULL,'24'),25.25,(26.26,NULL,27.27),28,(29,NULL,30),1,(1,NULL,0),'2006-01-02 15:04:05',('2006-01-02 15:04:05',NULL,'2006-01-02 15:04:05')", sqlStr) } func TestInterpolate_Errors(t *testing.T) { t.Run("non utf8", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ?").Str(string([]byte{0x34, 0xFF, 0xFE})), errors.NotValid, "", ) }) t.Run("too few qmarks", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ?").Int(3).Int(4), errors.Mismatch, "", ) }) t.Run("too many qmarks", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? OR b = ? or c = ?").Ints(3, 4), errors.Mismatch, "", ) }) t.Run("way too many qmarks", func(t *testing.T) { _, _, err := Interpolate("SELECT * FROM x WHERE a IN ? OR b = ? OR c = ? AND d = ?").Ints(3, 4).Int64(2).ToSQL() assert.ErrorIsKind(t, errors.Mismatch, err) }) t.Run("print error into String", func(t *testing.T) { ip := Interpolate("SELECT * FROM x WHERE a IN (?) AND b BETWEEN ? AND ? AND c = ? AND d IN (?,?)"). Int64(3).Int64(-3). Uint64(7). Float64s(3.5, 4.4995) assert.Exactly(t, "[dml] Number of place holders (6) vs number of arguments (4) do not match.", ip.String()) }) } type argValUint16 uint16 func (u argValUint16) Value() (driver.Value, error) { if u > 0 { return nil, errors.Aborted.Newf("Not in the mood today") } return uint16(0), nil } func TestInterpolate_ArgValue(t *testing.T) { aInt := null.MakeInt64(4711) aStr := null.MakeString("Goph'er") aFlo := null.MakeFloat64(2.7182818) aTim := null.MakeTime(Now.UTC()) aBoo := null.MakeBool(true) aByt := driverValueBytes(`BytyGophe'r`) var aNil driverValueBytes t.Run("equal", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ? AND c = ? AND d = ? AND e = ? AND f = ? AND g = ? AND h = ?"). DriverValues(aInt). DriverValues(aStr). DriverValues(aFlo). DriverValues(aTim). DriverValues(aBoo). DriverValues(aByt). DriverValues(aNil). DriverValues(aNil), errors.NoKind, "SELECT * FROM x WHERE a = 4711 AND b = 'Goph\\'er' AND c = 2.7182818 AND d = '2006-01-02 19:04:05' AND e = 1 AND f = 'BytyGophe\\'r' AND g = NULL AND h = NULL", ) }) t.Run("in", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b IN ? AND c IN ? AND d IN ? AND e IN ? AND f IN ?"). DriverValue(aInt, aInt).DriverValue(aStr, aStr).DriverValue(aFlo, aFlo). DriverValue(aTim, aTim).DriverValue(aBoo, aBoo).DriverValue(aByt, aByt), errors.NoKind, "SELECT * FROM x WHERE a IN (4711,4711) AND b IN ('Goph\\'er','Goph\\'er') AND c IN (2.7182818,2.7182818) AND d IN ('2006-01-02 19:04:05','2006-01-02 19:04:05') AND e IN (1,1) AND f IN ('BytyGophe\\'r','BytyGophe\\'r')", ) }) t.Run("type not supported", func(t *testing.T) { _, _, err := Interpolate("SELECT * FROM x WHERE a = ?").DriverValues(argValUint16(0)).ToSQL() assert.ErrorIsKind(t, errors.NotSupported, err) }) t.Run("valuer error", func(t *testing.T) { _, _, err := Interpolate("SELECT * FROM x WHERE a = ?").DriverValues(argValUint16(1)).ToSQL() assert.ErrorIsKind(t, errors.Aborted, err) }) } func TestInterpolate_Reset(t *testing.T) { t.Run("call twice with different arguments", func(t *testing.T) { ip := Interpolate("SELECT * FROM x WHERE a IN ? AND b BETWEEN ? AND ? AND c = ? AND d IN ?"). Ints(1, -2). Int64(3).Int64(-3). Uint64(7). Float64s(3.5, 4.4995) assert.Exactly(t, "SELECT * FROM x WHERE a IN (1,-2) AND b BETWEEN 3 AND -3 AND c = 7 AND d IN (3.5,4.4995)", ip.String()) ip.Reset(). Ints(10, -20). Int64(30).Int64(-30). Uint64(70). Float64s(30.5, 40.4995) assert.Exactly(t, "SELECT * FROM x WHERE a IN (10,-20) AND b BETWEEN 30 AND -30 AND c = 70 AND d IN (30.5,40.4995)", ip.String()) }) } func TestInterpolate_Int64(t *testing.T) { t.Run("equal named params", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = (:ArgX) AND b > @ArgY"). Named( sql.Named(":ArgX", 3), sql.Named("@ArgY", 3.14159), ), errors.NoKind, "SELECT * FROM x WHERE a = (3) AND b > 3.14159", ) }) t.Run("equal", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ? AND c = ?"). Int64(1).Int64(-2).Int64(3), errors.NoKind, "SELECT * FROM x WHERE a = 1 AND b = -2 AND c = 3", ) }) t.Run("in", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ?").Int64s(1, -2, 3, 4, 5, 6, 7, 8, 9, 10), errors.NoKind, "SELECT * FROM x WHERE a IN (1,-2,3,4,5,6,7,8,9,10)", ) }) t.Run("in and equal", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ? AND c = ? AND h = ? AND i = ? AND j = ? AND k = ? AND m IN ? OR n = ?"). Int64(1). Int64(-2). Int64(3). Int64(4). Int64(5). Int64(6). Int64(11). Int64s(12, 13). Int64(-14), errors.NoKind, `SELECT * FROM x WHERE a = 1 AND b = -2 AND c = 3 AND h = 4 AND i = 5 AND j = 6 AND k = 11 AND m IN (12,13) OR n = -14`, ) }) } func TestInterpolate_Bools(t *testing.T) { t.Run("single args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ?").Bool(true).Bool(false), errors.NoKind, "SELECT * FROM x WHERE a = 1 AND b = 0", ) }) t.Run("IN args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b = ? OR c = ?"). Bools(true, false).Bool(true).Bool(false), errors.NoKind, "SELECT * FROM x WHERE a IN (1,0) AND b = 1 OR c = 0", ) }) } func TestInterpolate_Bytes(t *testing.T) { b1 := []byte(`Go`) b2 := []byte(`Further`) t.Run("UTF8 valid: single args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ?").Bytes(b1).Bytes(b2), errors.NoKind, "SELECT * FROM x WHERE a = 'Go' AND b = 'Further'", ) }) t.Run("UTF8 valid: IN args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ?").BytesSlice(b1, b2), errors.NoKind, "SELECT * FROM x WHERE a IN ('Go','Further')", ) }) t.Run("empty arg triggers no error", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ?").BytesSlice(), errors.NoKind, "SELECT * FROM x WHERE a IN ()", ) }) t.Run("Binary to hex", func(t *testing.T) { bin := []byte{66, 250, 67} compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ?").Bytes(bin), errors.NoKind, "SELECT * FROM x WHERE a = 0x42fa43", ) }) } func TestInterpolate_Time(t *testing.T) { t1 := now() t2 := now().Add(time.Minute) t.Run("single args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ?").Time(t1).Time(t2), errors.NoKind, "SELECT * FROM x WHERE a = '2006-01-02 15:04:05' AND b = '2006-01-02 15:05:05'", ) }) t.Run("IN args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ?").Times(t1, t2), errors.NoKind, "SELECT * FROM x WHERE a IN ('2006-01-02 15:04:05','2006-01-02 15:05:05')", ) }) t.Run("empty arg", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? ?").Times(), errors.Mismatch, "", ) }) } func TestInterpolate_Floats(t *testing.T) { t.Run("single args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ?").Float64(3.14159).Float64(2.7182818), errors.NoKind, "SELECT * FROM x WHERE a = 3.14159 AND b = 2.7182818", ) }) t.Run("IN args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b = ?").Float64s(3.14159, 2.7182818).Float64(0.815), errors.NoKind, "SELECT * FROM x WHERE a IN (3.14159,2.7182818) AND b = 0.815", ) }) t.Run("IN args reverse", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE b = ? AND a IN ?").Float64(0.815).Float64s(3.14159, 2.7182818), errors.NoKind, "SELECT * FROM x WHERE b = 0.815 AND a IN (3.14159,2.7182818)", ) }) } func TestInterpolate_Slices_Strings_Between(t *testing.T) { t.Run("BETWEEN at the end", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b IN ? AND c NOT IN ? AND d BETWEEN ? AND ?"). Ints(1).Ints(1, 2, 3).Int64s(5, 6, 7).Str("wat").Str("ok"), errors.NoKind, "SELECT * FROM x WHERE a IN (1) AND b IN (1,2,3) AND c NOT IN (5,6,7) AND d BETWEEN 'wat' AND 'ok'", ) }) t.Run("BETWEEN in the middle", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b IN ? AND d BETWEEN ? AND ? AND c NOT IN ?"). Ints(1).Ints(1, 2, 3).Str("wat").Str("ok").Int64s(5, 6, 7), errors.NoKind, "SELECT * FROM x WHERE a IN (1) AND b IN (1,2,3) AND d BETWEEN 'wat' AND 'ok' AND c NOT IN (5,6,7)", ) }) t.Run("single args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ? AND c = ?").Str("a'b").Str("c`d").Str("\"hello's \\ world\" \n\r\x00\x1a"), errors.NoKind, "SELECT * FROM x WHERE a = 'a\\'b' AND b = 'c`d' AND c = '\\\"hello\\'s \\\\ world\\\" \\n\\r\\x00\\x1a'", ) }) t.Run("IN args", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b = ?").Strs("a'b", "c`d").Strs("1' or '1' = '1'))/*"), errors.NoKind, "SELECT * FROM x WHERE a IN ('a\\'b','c`d') AND b = ('1\\' or \\'1\\' = \\'1\\'))/*')", ) }) t.Run("empty args triggers incorrect interpolation of values", func(t *testing.T) { sl := make([]string, 0, 2) compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a IN ? AND b = ? OR c = ?").Strs("a", "b").Str("c").Strs(sl...), errors.NoKind, "SELECT * FROM x WHERE a IN ('a','b') AND b = 'c' OR c = ()", ) }) t.Run("multiple slices", func(t *testing.T) { compareToSQL2(t, Interpolate("SELECT * FROM x WHERE a = ? AND b = ? AND c = ? AND d = ? AND e = ?"). Ints(1). Ints(1, 2, 3). Int64s(5, 6, 7). Strs("wat", "ok"). Int(8), errors.NoKind, "SELECT * FROM x WHERE a = (1) AND b = (1,2,3) AND c = (5,6,7) AND d = ('wat','ok') AND e = 8", ) }) } func TestInterpolate_Different(t *testing.T) { ifs := func(vals ...interface{}) []interface{} { return vals } tests := []struct { sql string argsIn []interface{} expSQL string errKind errors.Kind }{ // NULL { "SELECT * FROM x WHERE a = ?", ifs(nil), "SELECT * FROM x WHERE a = NULL", errors.NoKind, }, // integers { `SELECT * FROM x WHERE a = ? AND b = ?`, ifs(1, -2), `SELECT * FROM x WHERE a = 1 AND b = -2`, errors.NoKind, }, { `SELECT * FROM x WHERE a IN ?`, ifs([]int{1, -2, 3, 4, 5, 6, 7, 8, 9, 10}), `SELECT * FROM x WHERE a IN (1,-2,3,4,5,6,7,8,9,10)`, errors.NoKind, }, { `SELECT * FROM x WHERE a IN ?`, ifs([]int64{1, -2, 3, 4, 5, 6, 7, 8, 9, 10}), `SELECT * FROM x WHERE a IN (1,-2,3,4,5,6,7,8,9,10)`, errors.NoKind, }, // boolean { "SELECT * FROM x WHERE a = ? AND b = ?", ifs(true, false), "SELECT * FROM x WHERE a = 1 AND b = 0", errors.NoKind, }, { "SELECT * FROM x WHERE a IN ?", ifs([]bool{true, false}), "SELECT * FROM x WHERE a IN (1,0)", errors.NoKind, }, // floats { "SELECT * FROM x WHERE a = ? AND b = ?", ifs(0.15625, 3.14159), "SELECT * FROM x WHERE a = 0.15625 AND b = 3.14159", errors.NoKind, }, { "SELECT * FROM x WHERE a IN ?", ifs([]float64{0.15625, 3.14159}), "SELECT * FROM x WHERE a IN (0.15625,3.14159)", errors.NoKind, }, { "SELECT * FROM x WHERE a = ? AND b = ? and C = ?", ifs([]float64{0.15625, 3.14159}), "", errors.Mismatch, }, { `SELECT * FROM x WHERE a IN ?`, ifs([]float64{1.1, -2.2, 3.3}), `SELECT * FROM x WHERE a IN (1.1,-2.2,3.3)`, errors.NoKind, }, // strings { `SELECT * FROM x WHERE a = ? AND b = ?`, ifs("hello", "\"hello's \\ world\" \n\r\x00\x1a"), `SELECT * FROM x WHERE a = 'hello' AND b = '\"hello\'s \\ world\" \n\r\x00\x1a'`, errors.NoKind, }, { `SELECT * FROM x WHERE a IN ?`, ifs([]string{"a'a", "bb"}), `SELECT * FROM x WHERE a IN ('a\'a','bb')`, errors.NoKind, }, { `SELECT * FROM x WHERE a IN ?`, ifs([]string{"a'a", "bb"}), `SELECT * FROM x WHERE a IN ('a\'a','bb')`, errors.NoKind, }, // slices { "SELECT * FROM x WHERE a = ? AND b = ? AND c = ? AND d = ?", ifs(1, []int{1, 2, 3}, []int{5, 6, 7}, []string{"wat", "ok"}), "SELECT * FROM x WHERE a = 1 AND b = (1,2,3) AND c = (5,6,7) AND d = ('wat','ok')", errors.NoKind, }, // ////// TODO valuers ////{"SELECT * FROM x WHERE a = ? AND b = ?", //// args{myString{true, "wat"}, myString{false, "fry"}}, //// "SELECT * FROM x WHERE a = 'wat' AND b = NULL", nil}, // errors { "SELECT * FROM x WHERE a = ? AND b = ?", ifs(int64(1)), "", errors.Mismatch, }, { "SELECT * FROM x WHERE", ifs(1), "", errors.Mismatch, }, { "SELECT * FROM x WHERE a = ?", ifs(string([]byte{0x34, 0xFF, 0xFE})), "", errors.NotValid, }, // String() without arguments is equal to empty interface in the previous version. {"SELECT 'hello", ifs(""), "", errors.Mismatch}, {`SELECT "hello`, ifs(""), "", errors.Mismatch}, {`SELECT ? "hello`, ifs(""), "SELECT '' 'hello", errors.NoKind}, // preprocessing {"SELECT '?'", nil, "SELECT '?'", errors.NoKind}, {"SELECT `?`", nil, "SELECT `?`", errors.NoKind}, {"SELECT [?]", nil, "SELECT `?`", errors.NoKind}, {"SELECT [?]", nil, "SELECT `?`", errors.NoKind}, {"SELECT [name] FROM [user]", nil, "SELECT `name` FROM `user`", errors.NoKind}, {"SELECT [u.name] FROM [user] [u]", nil, "SELECT `u`.`name` FROM `user` `u`", errors.NoKind}, {"SELECT [u.na`me] FROM [user] [u]", nil, "SELECT `u`.`na``me` FROM `user` `u`", errors.NoKind}, {"SELECT * FROM [user] WHERE [name] = '[nick]'", nil, "SELECT * FROM `user` WHERE `name` = '[nick]'", errors.NoKind}, {`SELECT * FROM [user] WHERE [name] = "nick[]"`, nil, "SELECT * FROM `user` WHERE `name` = 'nick[]'", errors.NoKind}, {"SELECT * FROM [user] WHERE [name] = 'Hello`s World'", nil, "SELECT * FROM `user` WHERE `name` = 'Hello`s World'", errors.NoKind}, } for _, test := range tests { str, _, err := Interpolate(test.sql).Unsafe(test.argsIn...).ToSQL() if !test.errKind.Empty() { if !test.errKind.Match(err) { isErr := test.errKind.Match(err) t.Errorf("IDX %q\ngot error: %v\nwant: %t", test.sql, err, isErr) } } // assert.NoError(t, err, "IDX %d", i) if str != test.expSQL { t.Errorf("IDX %q\ngot: %v\nwant: %v\nError: %+v", test.sql, str, test.expSQL, err) } } } func TestInterpolate_MultipleSingleQuotes(t *testing.T) { const rawSQL = "DELETE FROM `tableA` WHERE (`colA` >= 3.14159) AND (`colB` IN ?) AND (`colC` = 'He\\'llo') ORDER BY `id` LIMIT 10" str, args, err := Interpolate(rawSQL).Unsafe([]float64{3.1, 2.4}).ToSQL() assert.NoError(t, err) assert.Nil(t, args) assert.Exactly(t, "DELETE FROM `tableA` WHERE (`colA` >= 3.14159) AND (`colB` IN (3.1,2.4)) AND (`colC` = 'He\\'llo') ORDER BY `id` LIMIT 10", str) } func TestExtractNamedArgs(t *testing.T) { runner := func(haveSQL, wantSQL string, wantQualifiedColumns ...string) func(*testing.T) { return func(t *testing.T) { gotSQL, qualifiedColumns, _ := extractReplaceNamedArgs(haveSQL, nil) assert.Exactly(t, wantSQL, string(gotSQL)) assert.Exactly(t, wantQualifiedColumns, qualifiedColumns) } } t.Run("colon in comment", runner( "/*ID$:RANJID1*/SELECT SQL_NO_CACHE * FROM `dml_people` WHERE (`name` = :name)", // in comment, a bug "/*ID$?*/SELECT SQL_NO_CACHE * FROM `dml_people` WHERE (`name` = ?)", // BUG fix later namedArgStartStr+"RANJID1", namedArgStartStr+"name", )) t.Run("one", runner( "SELECT 1 AS `n`, CAST(:abc AS CHAR(20)) AS `str`", "SELECT 1 AS `n`, CAST(? AS CHAR(20)) AS `str`", namedArgStartStr+"abc", )) t.Run("one in bracket", runner( "SELECT 1 AS `n`, CAST((:abc) AS CHAR(20)) AS `str`", "SELECT 1 AS `n`, CAST((?) AS CHAR(20)) AS `str`", namedArgStartStr+"abc", )) t.Run("qualified one in bracket", runner( "SELECT 1 AS `n`, CAST((:xx.abc) AS CHAR(20)) AS `str`", "SELECT 1 AS `n`, CAST((?) AS CHAR(20)) AS `str`", namedArgStartStr+"xx.abc", )) t.Run("none", runner( "SELECT 1 AS `n`, CAST(abc AS CHAR(20)) AS `str`", "SELECT 1 AS `n`, CAST(abc AS CHAR(20)) AS `str`", )) t.Run("two same", runner( "SELECT 1 AS `n`, CAST(:abc AS CHAR(20)) AS `str`, CAST(:abc AS INT(20)) AS `intstr`", "SELECT 1 AS `n`, CAST(? AS CHAR(20)) AS `str`, CAST(? AS INT(20)) AS `intstr`", namedArgStartStr+"abc", namedArgStartStr+"abc", )) t.Run("two different", runner( "SELECT 1 AS `n`, CAST(:abc2 AS CHAR(20)) AS `str`, CAST(:abc1 AS INT(20)) AS `intstr`", "SELECT 1 AS `n`, CAST(? AS CHAR(20)) AS `str`, CAST(? AS INT(20)) AS `intstr`", namedArgStartStr+"abc2", namedArgStartStr+"abc1", )) t.Run("emoji and non-emoji with error", runner( "SELECT 1 AS `n`, CAST(:a😱bc AS CHAR(20)) AS `str`, CAST(:abc AS INT(20)) AS `intstr`", "SELECT 1 AS `n`, CAST(? AS CHAR(20)) AS `str`, CAST(?c AS INT(20)) AS `intstr`", namedArgStartStr+"a😱bc", namedArgStartStr+"ab", )) t.Run("emoji only with incorrect SQL", runner( "SELECT 1 AS `n`, (:👨‍👨‍) AS `str`, (:🔜) AS `intstr`", "SELECT 1 AS `n`, (?\u200d👨\u200d) AS `str`, (?) AS `intstr`", namedArgStartStr+"👨", namedArgStartStr+"🔜", )) t.Run("colon only", runner( "SELECT : AS `n`", "SELECT ? AS `n`", )) t.Run("with number", runner( "SELECT (:x32)", "SELECT (?)", namedArgStartStr+"x32", )) t.Run("date as argument short", runner( "CASE WHEN date_start <= '2009-11-11 00:00:00'", "CASE WHEN date_start <= '2009-11-11 00:00:00'", )) t.Run("date as argument long", runner( "CASE WHEN date_start <= '2009-11-11 00:00:00' AND date_end >= '2009-11-12 00:00:00' THEN `open` WHEN date_start > '2009-11-11 00:00:00' AND date_end > '2009-11-12 00:00:00' THEN `upcoming` ELSE `closed` END", "CASE WHEN date_start <= '2009-11-11 00:00:00' AND date_end >= '2009-11-12 00:00:00' THEN `open` WHEN date_start > '2009-11-11 00:00:00' AND date_end > '2009-11-12 00:00:00' THEN `upcoming` ELSE `closed` END", )) t.Run("single quote escaped", runner( "date_start = 'It\\'s xmas' ORDER BY X", "date_start = 'It\\'s xmas' ORDER BY X", )) } func Test_expandPlaceHolderTuples(t *testing.T) { runner := func(sql string, argCount int, wantErr errors.Kind, wantSQL string) func(*testing.T) { return func(t *testing.T) { var buf bytes.Buffer haveErr := expandPlaceHolderTuples(&buf, []byte(sql), argCount) if wantErr.Empty() { assert.NoError(t, haveErr) assert.Exactly(t, wantSQL, buf.String()) } else { assert.ErrorIsKind(t, wantErr, haveErr) } } } t.Run("valid 12 args", runner( " WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN /*TUPLES=004*/)", 12, errors.NoKind, " WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN ((?,?,?,?),(?,?,?,?),(?,?,?,?)))", )) t.Run("4 tuples 0 args", runner( " WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN /*TUPLES=004*/)", 0, errors.NoKind, " WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN /*TUPLES=004*/)", )) t.Run("invalid 1", runner( " WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN /*TUPLES=004*/)", 1, errors.NotValid, "", )) t.Run("no tuple count", runner( " WHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN /*TUPLES=*/)", 1, errors.NotValid, "", )) t.Run("valid 1 arg", runner( " WHERE ((`entity_id`) IN /*TUPLES=001*/)", 1, errors.NoKind, " WHERE ((`entity_id`) IN ((?)))", )) } <|start_filename|>sql/dml/connection_callback_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml_test import ( "bytes" "context" "database/sql/driver" "fmt" "sync/atomic" "testing" "github.com/corestoreio/pkg/util/conv" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/util/assert" ) func TestDriverCallBack(t *testing.T) { // Test assumes that the table dml_people does still exists. counter := new(int32) buf := new(bytes.Buffer) dbc := dmltest.MustConnectDB(t, // dbc == database connection dml.ConnPoolOption{ UniqueIDFn: func() string { return fmt.Sprintf("RANJID%d", atomic.AddInt32(counter, 1)) }, }, dml.WithDriverCallBack(func(fnName string) func(error, string, []driver.NamedValue) error { start := now() return func(err error, query string, namedArgs []driver.NamedValue) error { fmt.Fprintf(buf, "%q Took: %s\n", fnName, now().Sub(start)) if err != nil { fmt.Fprintf(buf, "Error: %s\n", err) } if query != "" { fmt.Fprintf(buf, "Query: %q\n", query) } if len(namedArgs) > 0 { fmt.Fprintf(buf, "NamedArgs: %#v\n", namedArgs) } fmt.Fprint(buf, "\n") return err } }), ) installFixtures(t, dbc.DB) ctx := context.Background() selSQL := dml.NewSelect("*").From("dml_people").Where(dml.Column("name").PlaceHolder()) err := dbc.RegisterByQueryBuilder(map[string]dml.QueryBuilder{ "sel1c": selSQL, "sel1nc": selSQL.Clone().SQLNoCache(), "up": dml.NewUpdate("dml_people").AddClauses(dml.Column("name").PlaceHolder()), }) assert.NoError(t, err) assert.Exactly(t, []string{ "sel1c", "/*$ID$RANJID1*/SELECT * FROM `dml_people` WHERE (`name` = ?)", "sel1nc", "/*$ID$RANJID2*/SELECT SQL_NO_CACHE * FROM `dml_people` WHERE (`name` = ?)", "up", "/*$ID$RANJID3*/UPDATE `dml_people` SET `name`=?", }, conv.ToStringSlice(dbc.CachedQueries())) var ppl dmlPerson _, err = dbc.WithCacheKey("sel1c").Load(ctx, &ppl, "Bernd") assert.NoError(t, err) _, err = dbc.WithCacheKey("sel1nc").Interpolate().Load(context.Background(), &ppl, "Das Brot") assert.NoError(t, err) con, err := dbc.Conn(ctx) assert.NoError(t, err) up := dbc.WithCacheKey("up") _, err = up.ExecContext(ctx, "Hugo") assert.NoError(t, err) _, err = up.Interpolate().ExecContext(ctx, "Bernie") assert.NoError(t, err) assert.NoError(t, con.Close()) dmltest.Close(t, dbc) assert.MatchesGolden(t, "testdata/TestDriverCallBack.want.txt", buf.Bytes(), false, func(goldenData []byte) []byte { return bytes.ReplaceAll(goldenData, []byte(`{{SCHEMA}}`), []byte(dbc.Schema())) }) } <|start_filename|>sql/dml/interfaces.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" ) // Preparer prepares a query in the server. The underlying type can be either a // *sql.DB (connection pool), a *sql.Conn (a single dedicated database session) // or a *sql.Tx (an in-progress database transaction). type Preparer interface { // PrepareContext - the provided context is used for the preparation of the // statement, not for the execution of the statement. // PrepareContext creates a prepared statement for later queries or // executions. Multiple queries or executions may be run concurrently from // the returned statement. The caller must call the statement's Close method // when the statement is no longer needed. PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) } // Execer can execute a non-returning query. The underlying type can be either a // *sql.DB (connection pool), a *sql.Conn (a single dedicated database session) // or a *sql.Tx (an in-progress database transaction). type Execer interface { // ExecContext executes a query that doesn't return rows. ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) } // StmtExecer executes a prepared statement. type StmtExecer interface { // ExecContext executes a query that doesn't return rows. ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) } // Querier can execute a returning query. The underlying type can be either a // *sql.DB (connection pool), a *sql.Conn (a single dedicated database session) // or a *sql.Tx (an in-progress database transaction). type Querier interface { // QueryContext executes a query that returns rows, typically a SELECT. The // args are for any placeholder parameters in the query. QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) } // StmtQuerier executes a prepared statement query. type StmtQuerier interface { // QueryContext executes a query that returns rows, typically a SELECT. The // args are for any placeholder parameters in the query. QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error) } // QueryExecPreparer can execute a returning query and prepare a returning query. // The underlying type can be either a *sql.DB (connection pool), a *sql.Conn (a // single dedicated database session) or a *sql.Tx (an in-progress database // transaction). // ExecPreparer a composite interface which can execute and prepare a query. The // underlying type can be either a *sql.DB (connection pool), a *sql.Conn (a // single dedicated database session) or a *sql.Tx (an in-progress database // transaction). type QueryExecPreparer interface { Preparer Querier Execer QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row } type ioCloser interface { Close() error } <|start_filename|>sql/dml/dbr_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "database/sql" "testing" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func toIFaceSlice(args ...interface{}) []interface{} { for i, a := range args { if a == nil { args[i] = internalNULLNIL{} } } return args } func TestArguments_Interfaces(t *testing.T) { container := make([]interface{}, 0, 48) t.Run("no slices, nulls valid", func(t *testing.T) { args := toIFaceSlice( nil, -1, int64(1), uint64(2), 3.1, true, "eCom1", []byte(`eCom2`), now(), null.MakeString("eCom3"), null.MakeInt64(4), null.MakeFloat64(2.7), null.MakeBool(true), null.MakeTime(now())) assert.Exactly(t, []interface{}{ nil, int64(-1), int64(1), int64(2), 3.1, true, "eCom1", []uint8{0x65, 0x43, 0x6f, 0x6d, 0x32}, now(), "eCom3", int64(4), 2.7, true, now(), }, expandInterfaces(args)) container = container[:0] }) t.Run("no slices, nulls invalid", func(t *testing.T) { args := toIFaceSlice( nil, -1, int64(1), uint64(2), 3.1, true, "eCom1", []byte(`eCom2`), now(), null.String{}, null.Int64{}, null.Float64{}, null.Bool{}, null.Time{}) assert.Exactly(t, []interface{}{ nil, int64(-1), int64(1), int64(2), 3.1, true, "eCom1", []uint8{0x65, 0x43, 0x6f, 0x6d, 0x32}, now(), nil, nil, nil, nil, nil, }, expandInterfaces(args)) container = container[:0] }) t.Run("slices, nulls valid", func(t *testing.T) { args := toIFaceSlice( nil, []int{-1, -2}, []int64{1, 2}, []uint{568, 766}, []uint64{2}, []float64{1.2, 3.1}, []bool{false, true}, []string{"eCom1", "eCom11"}, [][]byte{[]byte(`eCom2`)}, []time.Time{now(), now()}, []null.String{null.MakeString("eCom3"), null.MakeString("eCom3")}, []null.Int64{null.MakeInt64(4), null.MakeInt64(4)}, []null.Float64{null.MakeFloat64(2.7), null.MakeFloat64(2.7)}, []null.Bool{null.MakeBool(true)}, []null.Time{null.MakeTime(now()), null.MakeTime(now())}) assert.Exactly(t, []interface{}{ nil, int64(-1), int64(-2), int64(1), int64(2), int64(568), int64(766), int64(2), 1.2, 3.1, false, true, "eCom1", "eCom11", []uint8{0x65, 0x43, 0x6f, 0x6d, 0x32}, now(), now(), "eCom3", "eCom3", int64(4), int64(4), 2.7, 2.7, true, now(), now(), }, expandInterfaces(args)) }) t.Run("returns nil interface", func(t *testing.T) { assert.Nil(t, expandInterfaces([]interface{}{}), "args.expandInterfaces() must return nil") }) } func TestArguments_DriverValue(t *testing.T) { t.Run("Driver.Values supported types", func(t *testing.T) { args := toIFaceSlice( driverValueNil(0), driverValueBytes(nil), null.MakeInt64(3), null.MakeFloat64(2.7), null.MakeBool(true), driverValueBytes(`Invoice`), null.MakeString("Creditmemo"), nowSentinel{}, null.MakeTime(now()), ) assert.Exactly(t, []interface{}{ nil, []uint8(nil), int64(3), 2.7, true, []uint8{0x49, 0x6e, 0x76, 0x6f, 0x69, 0x63, 0x65}, "Creditmemo", "2006-01-02 19:04:05", now(), }, expandInterfaces(args)) }) t.Run("Driver.Value supported types", func(t *testing.T) { args := toIFaceSlice( driverValueNil(0), driverValueBytes(nil), null.MakeInt64(3), null.MakeFloat64(2.7), null.MakeBool(true), driverValueBytes(`Invoice`), null.MakeString("Creditmemo"), nowSentinel{}, null.MakeTime(now())) assert.Exactly(t, []interface{}{ nil, []uint8(nil), int64(3), 2.7, true, []uint8{0x49, 0x6e, 0x76, 0x6f, 0x69, 0x63, 0x65}, "Creditmemo", "2006-01-02 19:04:05", now(), }, expandInterfaces(args)) }) t.Run("Driver.Values panics because not supported", func(t *testing.T) { _, err := driverValue(nil, driverValueNotSupported(4)) assert.ErrorIsKind(t, errors.NotSupported, err) }) t.Run("Driver.Values panics because Value error", func(t *testing.T) { _, err := driverValue(nil, driverValueError(0)) assert.ErrorIsKind(t, errors.Fatal, err) }) } func TestArguments_WriteTo(t *testing.T) { t.Run("no slices, nulls valid", func(t *testing.T) { args := toIFaceSlice( nil, -1, int64(1), uint64(2), 3.1, true, "eCom1", []byte(`eCom2`), now(), null.MakeString("eCom3"), null.MakeInt64(4), null.MakeFloat64(2.7), null.MakeBool(true), null.MakeTime(now())) var buf bytes.Buffer assert.NoError(t, writeInterfaces(&buf, args)) assert.Exactly(t, "(NULL,-1,1,2,3.1,1,'eCom1','eCom2','2006-01-02 15:04:05','eCom3',4,2.7,1,'2006-01-02 15:04:05')", buf.String()) }) t.Run("no slices, nulls invalid", func(t *testing.T) { args := toIFaceSlice( nil, -1, int64(1), uint64(2), 3.1, true, "eCom1", []byte(`eCom2`), now(), null.String{}, null.Int64{}, null.Float64{}, null.Bool{}, null.Time{}) var buf bytes.Buffer assert.NoError(t, writeInterfaces(&buf, args)) assert.Exactly(t, "(NULL,-1,1,2,3.1,1,'eCom1','eCom2','2006-01-02 15:04:05',NULL,NULL,NULL,NULL,NULL)", buf.String()) }) t.Run("slices, nulls valid", func(t *testing.T) { args := toIFaceSlice( nil, []int{-1, -2}, []int64{1, 2}, []uint{568, 766}, []uint64{2}, []float64{1.2, 3.1}, []bool{false, true}, []string{"eCom1", "eCom11"}, [][]byte{[]byte(`eCom2`)}, []time.Time{now(), now()}, []null.String{null.MakeString("eCom3"), null.MakeString("eCom3")}, []null.Int64{null.MakeInt64(4), null.MakeInt64(4)}, []null.Float64{null.MakeFloat64(2.7), null.MakeFloat64(2.7)}, []null.Bool{null.MakeBool(true)}, []null.Time{null.MakeTime(now()), null.MakeTime(now())}) var buf bytes.Buffer assert.NoError(t, writeInterfaces(&buf, args)) assert.Exactly(t, "(NULL,(-1,-2),(1,2),(568,766),(2),(1.2,3.1),(0,1),('eCom1','eCom11'),('eCom2'),('2006-01-02 15:04:05','2006-01-02 15:04:05'),('eCom3','eCom3'),(4,4),(2.7,2.7),(1),('2006-01-02 15:04:05','2006-01-02 15:04:05'))", buf.String(), "%q", buf.String()) }) t.Run("non-utf8 string", func(t *testing.T) { args := toIFaceSlice("\xc0\x80") var buf bytes.Buffer err := writeInterfaces(&buf, args) assert.Empty(t, buf.String(), "Buffer should be empty") assert.ErrorIsKind(t, errors.NotValid, err) }) t.Run("non-utf8 strings", func(t *testing.T) { args := toIFaceSlice([]string{"Go", "\xc0\x80"}) var buf bytes.Buffer err := writeInterfaces(&buf, args) assert.Exactly(t, `('Go',)`, buf.String()) assert.ErrorIsKind(t, errors.NotValid, err) }) t.Run("non-utf8 NullStrings", func(t *testing.T) { args := toIFaceSlice([]null.String{null.MakeString("Go2"), null.MakeString("Hello\xc0\x80World")}) var buf bytes.Buffer err := writeInterfaces(&buf, args) assert.Exactly(t, "('Go2',)", buf.String()) assert.ErrorIsKind(t, errors.NotValid, err) }) t.Run("non-utf8 NullString", func(t *testing.T) { args := toIFaceSlice(null.MakeString("Hello\xc0\x80World")) var buf bytes.Buffer err := writeInterfaces(&buf, args) assert.Empty(t, buf.String()) assert.ErrorIsKind(t, errors.NotValid, err) }) t.Run("bytes as binary", func(t *testing.T) { args := toIFaceSlice([][]byte{[]byte("\xc0\x80")}) var buf bytes.Buffer assert.NoError(t, writeInterfaces(&buf, args)) assert.Exactly(t, `(0xc080)`, buf.String()) }) t.Run("bytesSlice as binary", func(t *testing.T) { args := toIFaceSlice([][]byte{[]byte(`Rusty`), []byte("Go\xc0\x80")}) var buf bytes.Buffer assert.NoError(t, writeInterfaces(&buf, args)) assert.Exactly(t, "('Rusty',0x476fc080)", buf.String()) }) t.Run("should panic because unknown field type", func(t *testing.T) { var buf bytes.Buffer assert.ErrorIsKind(t, errors.NotSupported, writeInterfaceValue(complex64(1), &buf, 0)) assert.Empty(t, buf.String(), "buffer should be empty") }) } func TestArguments_HasNamedArgs(t *testing.T) { // TODO fix test resp. hasNamedArgs t.Run("hasNamedArgs in expression", func(t *testing.T) { p := &dmlPerson{ Name: "a'bc", } a := NewSelect(). AddColumnsConditions( Expr("?").Alias("n").Int64(1), Expr("CAST(:name AS CHAR(20))").Alias("str"), ).WithDBR(dbMock{}).TestWithArgs(Qualify("", p)) _, _, err := a.ToSQL() assert.NoError(t, err) // assert.Exactly(t, uint8(2), a.hasNamedArgs) }) t.Run("hasNamedArgs in condition, no args", func(t *testing.T) { a := NewSelect("a", "b").From("c").Where( Column("id").Greater().PlaceHolder(), Column("email").Like().NamedArg("ema1l")).WithDBR(dbMock{}) _, _, err := a.ToSQL() assert.NoError(t, err) // assert.Exactly(t, uint8(0), a.hasNamedArgs) }) t.Run("hasNamedArgs in condition, with args", func(t *testing.T) { a := NewSelect("a", "b").From("c").Where( Column("id").Greater().PlaceHolder(), Column("email").Like().NamedArg("ema1l")).WithDBR(dbMock{}).TestWithArgs("<EMAIL>") _, _, err := a.ToSQL() assert.NoError(t, err) // assert.Exactly(t, uint8(1), a.hasNamedArgs) }) t.Run("hasNamedArgs none", func(t *testing.T) { a := NewSelect("a", "b").From("c").Where( Column("id").Greater().Int(221), Column("email").Like().Str("<EMAIL>")).WithDBR(dbMock{}) _, _, err := a.ToSQL() assert.NoError(t, err) // assert.Exactly(t, uint8(0), a.hasNamedArgs) }) } func TestArguments_NextUnnamedArg(t *testing.T) { t.Run("three occurrences", func(t *testing.T) { args := toIFaceSlice(sql.Named("colZ", int64(3)), uint64(6), sql.Named("colB", 2.2), "c", sql.Named("colA", []string{"a", "b"})) dbr := &DBR{} var nextUnnamedArgPos int a, nextUnnamedArgPos, ok := dbr.nextUnnamedArg(nextUnnamedArgPos, args) assert.True(t, ok, "Should find an unnamed argument") assert.Exactly(t, uint64(6), a) a, nextUnnamedArgPos, ok = dbr.nextUnnamedArg(nextUnnamedArgPos, args) assert.True(t, ok, "Should find an unnamed argument") assert.Exactly(t, "c", a) a, nextUnnamedArgPos, ok = dbr.nextUnnamedArg(nextUnnamedArgPos, args) assert.False(t, ok, "Should NOT find an unnamed argument") assert.Exactly(t, nil, a) args = args[:0] args = append(args, 3.14159, sql.Named("price", 2.7182), now()) nextUnnamedArgPos = 0 a, nextUnnamedArgPos, ok = dbr.nextUnnamedArg(nextUnnamedArgPos, args) assert.True(t, ok, "Should find an unnamed argument") assert.Exactly(t, 3.14159, a) a, nextUnnamedArgPos, ok = dbr.nextUnnamedArg(nextUnnamedArgPos, args) assert.True(t, ok, "Should find an unnamed argument") assert.Exactly(t, now(), a) a, _, ok = dbr.nextUnnamedArg(nextUnnamedArgPos, args) assert.False(t, ok, "Should NOT find an unnamed argument") assert.Exactly(t, nil, a) }) t.Run("zero occurrences", func(t *testing.T) { args := toIFaceSlice(sql.Named("colZ", int64(3)), sql.Named("colB", 2.2), sql.Named("colA", []string{"a", "b"})) dbr := &DBR{} a, _, ok := dbr.nextUnnamedArg(0, args) assert.False(t, ok, "Should NOT find an unnamed argument") assert.Exactly(t, nil, a) a, _, ok = dbr.nextUnnamedArg(0, args) assert.False(t, ok, "Should NOT find an unnamed argument") assert.Exactly(t, nil, a) }) } func TestDBR_OrderByLimit(t *testing.T) { t.Run("WithoutArgs", func(t *testing.T) { a := NewSelect("a", "b").From("c").Where( Column("id").Greater().Int(221), Column("email").Like().Str("<EMAIL>")).WithDBR(dbMock{}).Limit(44, 55) t.Run("ASC", func(t *testing.T) { a.OrderBy("email", "id") compareToSQL2(t, a, errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` > 221) AND (`email` LIKE '<EMAIL>') ORDER BY `email`, `id` LIMIT 44,55", ) }) t.Run("DESC", func(t *testing.T) { a.OrderBys = a.OrderBys[:1] a.OrderByDesc("firstname") compareToSQL2(t, a, errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` > 221) AND (`email` LIKE '<EMAIL>') ORDER BY `email`, `firstname` DESC LIMIT 44,55", ) }) }) t.Run("WithDBR", func(t *testing.T) { a := NewSelect("a", "b").From("c").Where( Column("id").Greater().PlaceHolder(), Column("email").Like().Str("<EMAIL>")).WithDBR(dbMock{}).Limit(44, 55) t.Run("ASC", func(t *testing.T) { a.OrderBy("email", "id") compareToSQL2(t, a, errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` > ?) AND (`email` LIKE '<EMAIL>') ORDER BY `email`, `id` LIMIT 44,55", ) }) t.Run("DESC", func(t *testing.T) { a.OrderBys = a.OrderBys[:1] a.OrderByDesc("firstname") compareToSQL2(t, a, errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` > ?) AND (`email` LIKE '<EMAIL>') ORDER BY `email`, `firstname` DESC LIMIT 44,55", ) }) }) } func TestDBR_PreGeneratedQueries(t *testing.T) { cp, err := NewConnPool() assert.NoError(t, err) sel := NewSelect("a", "b").From("c").Where( Column("id").Greater().PlaceHolder(), Column("email").Like().PlaceHolder(), ) sel2 := sel.Clone() sel2.Wheres = sel2.Wheres[:1] sel2.Wheres[0] = Column("id").Less().PlaceHolder() err = cp.RegisterByQueryBuilder(map[string]QueryBuilder{ "id_greater": sel, "id_less": sel2, }) assert.NoError(t, err) // modify SQL compareToSQL2(t, cp.WithCacheKey("id_greater"), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` > ?) AND (`email` LIKE ?)", ) compareToSQL2(t, cp.WithCacheKey("id_less"), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` < ?)", ) compareToSQL2(t, cp.WithCacheKey("id_not_found"), errors.NotFound, "") } func TestExecValidateOneAffectedRow(t *testing.T) { t.Run("success", func(t *testing.T) { m := mockSQLRes{int64: 1} err := ExecValidateOneAffectedRow(m, nil) assert.NoError(t, err) }) t.Run("RowsAffected fails", func(t *testing.T) { m := mockSQLRes{int64: 1, error: errors.ConnectionFailed.Newf("ups")} err := ExecValidateOneAffectedRow(m, nil) assert.ErrorIsKind(t, errors.ConnectionFailed, err) }) t.Run("mismatch", func(t *testing.T) { m := mockSQLRes{int64: 2} err := ExecValidateOneAffectedRow(m, nil) assert.ErrorIsKind(t, errors.NotValid, err) }) t.Run("first error", func(t *testing.T) { m := mockSQLRes{int64: 2} err := ExecValidateOneAffectedRow(m, errors.AlreadyInUse.Newf("uppps")) assert.ErrorIsKind(t, errors.AlreadyInUse, err) }) } type mockSQLRes struct { int64 error } func (mockSQLRes) LastInsertId() (int64, error) { panic("implement me") } func (m mockSQLRes) RowsAffected() (int64, error) { return m.int64, m.error } func TestDBRValidateMinAffectedRow(t *testing.T) { dbr := &DBR{} DBRValidateMinAffectedRow(2)(dbr) err := dbr.ResultCheckFn("TableName", 0, StaticSQLResult{Rows: 2}, nil) assert.NoError(t, err) err = dbr.ResultCheckFn("TableName", 0, StaticSQLResult{Rows: 1}, nil) assert.ErrorIsKind(t, errors.NotValid, err) } <|start_filename|>sql/dml/benchmark_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" "testing" "time" ) var ( benchmarkGlobalVals []interface{} benchmarkSelectStr string ) // BenchmarkSelect_Rows-4 1000000 2276 ns/op 4344 B/op 12 allocs/op git commit 609db6db // BenchmarkSelect_Rows-4 500000 2919 ns/op 5411 B/op 18 allocs/op // BenchmarkSelect_Rows-4 500000 2504 ns/op 4239 B/op 17 allocs/op func BenchmarkSelect_Rows(b *testing.B) { tables := []string{"eav_attribute"} ctx := context.TODO() b.ResetTimer() for i := 0; i < b.N; i++ { sel := NewSelect("TABLE_NAME", "COLUMN_NAME", "ORDINAL_POSITION", "COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE", "CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION", "NUMERIC_SCALE", "COLUMN_TYPE", "COLUMN_KEY", "EXTRA", "COLUMN_COMMENT").From("information_schema.COLUMNS"). Where(Expr(`TABLE_SCHEMA=DATABASE()`)) sel.Where(Column("TABLE_NAME").In().PlaceHolder()) rows, err := sel.WithDBR(dbMock{}).QueryContext(ctx, tables) if err != nil { b.Fatalf("%+v", err) } if rows == nil { b.Fatal("Query should not be nil") } } } // BenchmarkSelectBasicSQL-4 500000 2542 ns/op 1512 B/op 18 allocs/op // BenchmarkSelectBasicSQL-4 1000000 2395 ns/op 1664 B/op 17 allocs/op <== arg value ? // BenchmarkSelectBasicSQL-4 500000 3060 ns/op 2089 B/op 22 allocs/op <== Builder Structs // BenchmarkSelectBasicSQL-4 200000 9266 ns/op 5875 B/op 18 allocs/op <== arg union // BenchmarkSelectBasicSQL-4 500000 3385 ns/op 3698 B/op 19 allocs/op // BenchmarkSelectBasicSQL-4 500000 3216 ns/op 3281 B/op 20 allocs/op <= union type struct, large // BenchmarkSelectBasicSQL-4 500000 2937 ns/op 2281 B/op 20 allocs/op no pointers // BenchmarkSelectBasicSQL-4 500000 2849 ns/op 2257 B/op 18 allocs/op func BenchmarkSelectBasicSQL(b *testing.B) { // Do some allocations outside the loop so they don't affect the results aVal := []int64{1, 2, 3} b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = NewSelect("something_id", "user_id", "other"). From("some_table"). Where( Expr("d = ? OR e = ?").Int64(1).Str("wat"), Column("a").In().Int64s(aVal...), ). OrderByDesc("id"). Paginate(1, 20). ToSQL() if err != nil { b.Fatalf("%+v", err) } } } // Type Condition is not a pointer. The GC pressure is much less but the program // is a bit slower due to copying. // BenchmarkSelectExcessConditions-4 200000 7055 ns/op 4984 B/op 26 allocs/op // BenchmarkSelectExcessConditions-4 200000 7118 ns/op 4984 B/op 26 allocs/op // The next line gives the results for the implementation when using type // Condition as a pointer. We have more allocs, more pressure on the GC but it's // a bit faster. // BenchmarkSelectExcessConditions-4 200000 6297 ns/op 4920 B/op 35 allocs/op // For now we stick with the pointers. Reason: the SQL statements are getting // usually only created once and not in a loop. func BenchmarkSelectExcessConditions(b *testing.B) { i64Vals := []int64{1, 2, 3} b.ResetTimer() var err error for i := 0; i < b.N; i++ { benchmarkSelectStr, benchmarkGlobalVals, err = NewSelect("entity_id", "name", "q.total_sum"). FromAlias("customer", "c"). Join(MakeIdentifier("quote").Alias("q"), Column("c.entity_id").Column("q.customer_id"), Column("c.group_id").Column("q.group_id"), Column("c.shop_id").NotEqual().PlaceHolders(10), ). Where( Expr("d = ? OR e = ?").Int64(1).Str("wat"), Column("a").In().PlaceHolder(), Column("q.product_id").In().Int64s(i64Vals...), Column("q.sub_total").NotBetween().Float64s(3.141, 6.2831), Column("q.qty").GreaterOrEqual().PlaceHolder(), Column("q.coupon_code").SpaceShip().Str("400EA8BBE4"), ). OrderByDesc("id"). Paginate(1, 20). ToSQL() if err != nil { b.Fatalf("%+v", err) } } } func BenchmarkSelectFullSQL(b *testing.B) { sqlObj := NewSelect("a", "b", "z", "y", "x").From("c"). Distinct(). Where( Expr("`d` = ? OR `e` = ?").Int64(1).Str("wat"), Column("f").Int64(2), Column("x").Str("hi"), Column("g").Int64(3), Column("h").In().Ints(1, 2, 3), ). GroupBy("ab").GroupBy("ii").GroupBy("iii"). Having(Expr("j = k"), Column("jj").Int64(1)). Having(Column("jjj").Int64(2)). OrderBy("l1").OrderBy("l2").OrderBy("l3"). Limit(8, 7) sqlObjDBR := sqlObj.WithDBR(nil) b.ResetTimer() b.ReportAllocs() // BenchmarkSelectFullSQL/NewSelect-4 300000 5849 ns/op 3649 B/op 38 allocs/op // BenchmarkSelectFullSQL/NewSelect-4 200000 6307 ns/op 4922 B/op 45 allocs/op <== builder structs // BenchmarkSelectFullSQL/NewSelect-4 200000 7084 ns/op 8212 B/op 44 allocs/op <== DBR // BenchmarkSelectFullSQL/NewSelect-4 200000 6449 ns/op 5515 B/op 44 allocs/op no pointers // BenchmarkSelectFullSQL/NewSelect-4 200000 6268 ns/op 5443 B/op 37 allocs/op // BenchmarkSelectFullSQL/NewSelect-4 342667 3497 ns/op 3672 B/op 29 allocs/op b.Run("NewSelect", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = NewSelect("a", "b", "z", "y", "x").From("c"). Distinct(). Where( Expr("`d` = ? OR `e` = ?").Int64(1).Str("wat"), Column("f").Int64(2), Column("x").Str("hi"), Column("g").Int64(3), Column("h").In().Ints(1, 2, 3), ). GroupBy("ab").GroupBy("ii").GroupBy("iii"). Having(Expr("j = k"), Column("jj").Int64(1)). Having(Column("jjj").Int64(2)). OrderBy("l1").OrderBy("l2").OrderBy("l3"). Limit(8, 7). ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("ToSQL Interpolate Cache", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = sqlObjDBR.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) } func BenchmarkSelect_Large_IN(b *testing.B) { // This tests simulates selecting many varchar attribute values for specific products. entityIDs := make([]int64, 1024) for i := 0; i < 1024; i++ { entityIDs[i] = int64(i + 1600) } b.ResetTimer() b.ReportAllocs() b.Run("SQL", func(b *testing.B) { for i := 0; i < b.N; i++ { sel := NewSelect("entity_id", "attribute_id", "value"). From("catalog_product_entity_varchar"). Where(Column("entity_type_id").Int64(4)). Where(Column("entity_id").In().Int64s(entityIDs...)). Where(Column("attribute_id").In().Int64s(174, 175)). Where(Column("store_id").Int(0)) var err error benchmarkSelectStr, benchmarkGlobalVals, err = sel.ToSQL() if err != nil { b.Fatalf("%+v", err) } if benchmarkGlobalVals != nil { b.Fatal("Args should be nil") } } }) b.Run("interpolate", func(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { sel := NewSelect("entity_id", "attribute_id", "value"). From("catalog_product_entity_varchar"). Where(Column("entity_type_id").PlaceHolder()). Where(Column("entity_id").In().PlaceHolder()). Where(Column("attribute_id").In().PlaceHolder()). Where(Column("store_id").PlaceHolder()) var err error benchmarkSelectStr, benchmarkGlobalVals, err = sel.WithDBR(dbMock{}). Interpolate(). testWithArgs(4, entityIDs, []int64{174, 175}, 0). ToSQL() if err != nil { b.Fatalf("%+v", err) } if benchmarkGlobalVals != nil { b.Fatal("Args should be nil") } } }) b.Run("interpolate named", func(b *testing.B) { for i := 0; i < b.N; i++ { sel := NewSelect("entity_id", "attribute_id", "value"). From("catalog_product_entity_varchar"). Where(Column("entity_type_id").NamedArg("EntityTypeId")). Where(Column("entity_id").In().NamedArg("EntityId")). Where(Column("attribute_id").In().NamedArg("AttributeId")). Where(Column("store_id").NamedArg("StoreId")) var err error benchmarkSelectStr, benchmarkGlobalVals, err = sel.WithDBR(dbMock{}).Interpolate().testWithArgs( sql.Named("EntityTypeId", int64(4)), sql.Named("EntityId", entityIDs), sql.Named("AttributeId", []int64{174, 175}), sql.Named("StoreId", 0), ).ToSQL() if err != nil { b.Fatalf("%+v", err) } if benchmarkGlobalVals != nil { b.Fatal("Args should be nil") } } }) b.Run("interpolate optimized", func(b *testing.B) { sel := NewSelect("entity_id", "attribute_id", "value"). From("catalog_product_entity_varchar"). Where(Column("entity_type_id").PlaceHolder()). Where(Column("entity_id").In().PlaceHolder()). Where(Column("attribute_id").In().PlaceHolder()). Where(Column("store_id").PlaceHolder()) selA := sel.WithDBR(dbMock{}).Interpolate() b.ResetTimer() for i := 0; i < b.N; i++ { var err error // the generated string benchmarkSelectStr is 5300 characters long benchmarkSelectStr, benchmarkGlobalVals, err = selA.testWithArgs(4, entityIDs, []int64{174, 175}, 0).ToSQL() if err != nil { b.Fatalf("%+v", err) } if benchmarkGlobalVals != nil { b.Fatal("Args should be nil") } selA.Reset() } }) } func BenchmarkSelect_ComplexAddColumns(b *testing.B) { var haveSQL string b.ResetTimer() for i := 0; i < b.N; i++ { var args []interface{} var err error haveSQL, args, err = NewSelect(). AddColumns(" entity_id , value"). AddColumns("cpev.entity_type_id", "cpev.attribute_id"). AddColumnsAliases("(cpev.id*3)", "weirdID"). AddColumnsAliases("cpev.value", "value2nd"). FromAlias("catalog_product_entity_varchar", "cpev"). Where(Column("entity_type_id").Int64(4)). Where(Column("attribute_id").In().Int64s(174, 175)). Where(Column("store_id").Int64(0)). ToSQL() if err != nil { b.Fatalf("%+v", err) } benchmarkGlobalVals = args } _ = haveSQL // b.Logf("%s", haveSQL) /* SELECT entity_id, value, `cpev`.`entity_type_id`, `cpev`.`attribute_id`, ( cpev.id * 3 ) AS `weirdID`, `cpev`.`value` AS `value2nd` FROM `catalog_product_entity_varchar` AS `cpev` WHERE ( `entity_type_id` = ? ) AND ( `attribute_id` IN ? ) AND ( `store_id` = ? ) */ } // BenchmarkSelect_SQLCase-4 500000 3451 ns/op 2032 B/op 21 allocs/op // BenchmarkSelect_SQLCase-4 500000 3690 ns/op 2849 B/op 24 allocs/op // BenchmarkSelect_SQLCase-4 300000 3784 ns/op 2433 B/op 26 allocs/op func BenchmarkSelect_SQLCase(b *testing.B) { start := time.Unix(1257894000, 0) end := time.Unix(1257980400, 0) pid := []int{4711, 815, 42} var haveSQL string b.ResetTimer() for i := 0; i < b.N; i++ { var err error haveSQL, benchmarkGlobalVals, err = NewSelect(). AddColumns("price", "sku", "name"). AddColumnsConditions( SQLCase("", "`closed`", "date_start <= ? AND date_end >= ?", "`open`", "date_start > ? AND date_end > ?", "`upcoming`", ).Alias("is_on_sale").Time(start).Time(end).Time(start).Time(end), ). From("catalog_promotions"). Where( Column("promotion_id"). NotIn(). Ints(pid...), ). ToSQL() if err != nil { b.Fatalf("%+v", err) } } _ = haveSQL } func BenchmarkDeleteSQL(b *testing.B) { b.Run("NewDelete", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error _, benchmarkGlobalVals, err = NewDelete("alpha").Where(Column("a").Str("b")).Limit(1).OrderBy("id").ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) sqlObj := NewDelete("alpha").Where(Column("a").Str("b")).Limit(1).OrderBy("id") b.Run("ToSQL no cache", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = sqlObj.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) sqlObjDBR := sqlObj.WithDBR(nil) b.Run("ToSQL with cache", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = sqlObjDBR.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) } func BenchmarkInsertValuesSQL(b *testing.B) { b.Run("NewInsert", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = NewInsert("alpha"). AddColumns("something_id", "user_id", "other"). WithDBR(dbMock{}).testWithArgs(1, 2, true).ToSQL() if err != nil { b.Fatal(err) } } }) b.Run("ToSQL no cache", func(b *testing.B) { sqlObj := NewInsert("alpha").AddColumns("something_id", "user_id", "other") b.ResetTimer() for i := 0; i < b.N; i++ { var err error sqlObjA := sqlObj.WithDBR(dbMock{}).testWithArgs(1, 2, true) benchmarkSelectStr, benchmarkGlobalVals, err = sqlObjA.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("ToSQL with cache", func(b *testing.B) { sqlObj := NewInsert("alpha").AddColumns("something_id", "user_id", "other") delA := sqlObj.WithDBR(dbMock{}) b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = delA.testWithArgs(1, 2, true).ToSQL() if err != nil { b.Fatalf("%+v", err) } delA.Reset() } }) } func BenchmarkInsertRecordsSQL(b *testing.B) { obj := someRecord{SomethingID: 1, UserID: 99, Other: false} insA := NewInsert("alpha"). AddColumns("something_id", "user_id", "other"). WithDBR(dbMock{}) b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = insA.testWithArgs(Qualify("", obj)).ToSQL() if err != nil { b.Fatal(err) } insA.Reset() } } func BenchmarkRepeat(b *testing.B) { cp, err := NewConnPool() if err != nil { b.Fatal(err) } b.Run("multi", func(b *testing.B) { const want = "SELECT * FROM `table` WHERE id IN (?,?,?,?) AND name IN (?,?,?,?,?) AND status = ?" dbr := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN ? AND name IN ? AND status = ?")). ExpandPlaceHolders(). testWithArgs([]int{5, 7, 9, 11}, []string{"a", "b", "c", "d", "e"}, 22) b.ResetTimer() for i := 0; i < b.N; i++ { s, _, err := dbr.ToSQL() if err != nil { b.Fatalf("%+v", err) } if s != want { b.Fatalf("\nHave: %q\nWant: %q", s, want) } } }) b.Run("single", func(b *testing.B) { const want = "SELECT * FROM `table` WHERE id IN (?,?,?,?)" dbr := cp.WithQueryBuilder(QuerySQL("SELECT * FROM `table` WHERE id IN ?")). ExpandPlaceHolders(). testWithArgs([]int{9, 8, 7, 6}) b.ResetTimer() for i := 0; i < b.N; i++ { s, _, err := dbr.ToSQL() if err != nil { b.Fatalf("%+v", err) } if s != want { b.Fatalf("\nHave: %q\nWant: %q", s, want) } } }) } func BenchmarkQuoteAs(b *testing.B) { const want = "`e`.`entity_id` AS `ee`" b.ResetTimer() for i := 0; i < b.N; i++ { if have := Quoter.NameAlias("e.entity_id", "ee"); have != want { b.Fatalf("Have %s\nWant %s\n", have, want) } } } func BenchmarkQuoteQuote(b *testing.B) { const want = "`databaseName`.`tableName`" b.ReportAllocs() b.ResetTimer() b.Run("Worse Case", func(b *testing.B) { for i := 0; i < b.N; i++ { if have := Quoter.QualifierName("database`Name", "table`Name"); have != want { b.Fatalf("Have %s\nWant %s\n", have, want) } } }) b.Run("Best Case", func(b *testing.B) { for i := 0; i < b.N; i++ { if have := Quoter.QualifierName("databaseName", "tableName"); have != want { b.Fatalf("Have %s\nWant %s\n", have, want) } } }) } var benchmarkIfNull *Condition func BenchmarkIfNull(b *testing.B) { runner := func(want string, have ...string) func(*testing.B) { return func(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { var alias string if lh := len(have); lh%2 == 1 && lh > 1 { alias = have[lh-1] have = have[:lh-1] } ifn := SQLIfNull(have...) if alias != "" { ifn = ifn.Alias(alias) } benchmarkIfNull = ifn } } } b.Run("3 args expression right", runner( "IFNULL(`c2`,(1/0)) AS `alias`", "c2", "1/0", "alias", )) b.Run("3 args no qualifier", runner( "IFNULL(`c1`,`c2`) AS `alias`", "c1", "c2", "alias", )) b.Run("3 args with qualifier", runner( "IFNULL(`t1`.`c1`,`t2`.`c2`) AS `alias`", "t1.c1", "t2.c2", "alias", )) b.Run("4 args", runner( "IFNULL(`t1`.`c1`,`t2`.`c2`)", "t1", "c1", "t2", "c2", )) b.Run("5 args", runner( "IFNULL(`t1`.`c1`,`t2`.`c2`) AS `alias`", "t1", "c1", "t2", "c2", "ali`as", )) } func BenchmarkUnion(b *testing.B) { newUnion5 := func() *Union { // not valid SQL return NewUnion( NewSelect().AddColumns("t.value", "t.attribute_id").AddColumnsAliases("'varchar'", "col_type").FromAlias("catalog_product_entity_varchar", "t"). Where(Column("entity_id").Int64(1561), Column("store_id").In().Int64s(1, 0)). OrderByDesc("t.varchar_store_id"), NewSelect().AddColumns("t.value", "t.attribute_id").AddColumnsAliases("'int'", "col_type").FromAlias("catalog_product_entity_int", "t"). Where(Column("entity_id").Int64(1561), Column("store_id").In().Int64s(1, 0)). OrderByDesc("t.int_store_id"), NewSelect().AddColumns("t.value", "t.attribute_id").AddColumnsAliases("'decimal'", "col_type").FromAlias("catalog_product_entity_decimal", "t"). Where(Column("entity_id").Int64(1561), Column("store_id").In().Int64s(1, 0)). OrderByDesc("t.decimal_store_id"), NewSelect().AddColumns("t.value", "t.attribute_id").AddColumnsAliases("'datetime'", "col_type").FromAlias("catalog_product_entity_datetime", "t"). Where(Column("entity_id").Int64(1561), Column("store_id").In().Int64s(1, 0)). OrderByDesc("t.datetime_store_id"), NewSelect().AddColumns("t.value", "t.attribute_id").AddColumnsAliases("'text'", "col_type").FromAlias("catalog_product_entity_text", "t"). Where(Column("entity_id").Int64(1561), Column("store_id").In().Int64s(1, 0)). OrderByDesc("t.text_store_id"), ). All(). OrderBy("a"). OrderByDesc("b").PreserveResultSet() } newUnionTpl := func() *Union { return NewUnion( NewSelect().AddColumns("t.value", "t.attribute_id").AddColumnsAliases("'{column}'", "col_type").FromAlias("catalog_product_entity_{type}", "t"). Where(Column("entity_id").Int64(1561), Column("store_id").In().Int64s(1, 0)). OrderByDesc("t.{column}_store_id"), ). StringReplace("{type}", "varchar", "int", "decimal", "datetime", "text"). StringReplace("{column}", "varcharX", "intX", "decimalX", "datetimeX", "textX"). PreserveResultSet(). All(). OrderByDesc("col_type") } b.Run("5 SELECTs", func(b *testing.B) { u := newUnion5() b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = u.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("5 SELECTs not cached", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = newUnion5().ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("5 SELECTs WithDBR", func(b *testing.B) { u := newUnion5().WithDBR(dbMock{}) b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = u.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("Template", func(b *testing.B) { u := newUnionTpl() b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = u.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("Template not cached", func(b *testing.B) { for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = newUnionTpl().ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) b.Run("Template interpolated", func(b *testing.B) { u := newUnionTpl().WithDBR(nil) b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = u.ToSQL() if err != nil { b.Fatalf("%+v", err) } } }) } func BenchmarkUpdateValuesSQL(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { var err error benchmarkSelectStr, benchmarkGlobalVals, err = NewUpdate("alpha"). AddClauses( Column("something_id").Int64(1), ).Where( Column("id").Int64(1), ).ToSQL() if err != nil { b.Fatalf("%+v", err) } } } <|start_filename|>sql/dmltype/strings.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dmltype import ( "bytes" "database/sql/driver" "encoding/csv" "regexp" "strings" "github.com/corestoreio/errors" ) // CSV represents an unmerged slice of strings. You can use package // slices.String for further modifications of this slice type. It also // implements Text Marshalers for usage in dml.ColumnMap.Text. type CSV []string // quoteEscapeRegex is the regex to match escaped characters in a string. var quoteEscapeRegex = regexp.MustCompile(`([^\\]([\\]{2})*)\\"`) // todo implement column mapper // Scan satisfies the sql.Scanner interface for CSV. func (l *CSV) Scan(src interface{}) error { var str string switch t := src.(type) { case []byte: str = string(t) case string: str = t default: return errors.NotValid.Newf("[dmltype] CSV.Scan Unknown type or not yet implemented: %#v", src) } // change quote escapes for csv parser str = quoteEscapeRegex.ReplaceAllString(str, `$1""`) str = strings.Replace(str, `\\`, `\`, -1) // remove braces str = str[1 : len(str)-1] // bail if only one if len(str) == 0 { *l = CSV([]string{}) return nil } // parse with csv reader cr := csv.NewReader(strings.NewReader(str)) slice, err := cr.Read() if err != nil { return errors.NotValid.Newf("[dmltype] CSV.Scan CSV read error: %s", err) } *l = CSV(slice) return nil } func (l CSV) MarshalText() (text []byte, err error) { return l.Bytes(), nil } func (l *CSV) UnmarshalText(text []byte) error { return l.Scan(text) } // Value satisfies the driver.Valuer interface for CSV. func (l CSV) Value() (driver.Value, error) { return string(l.Bytes()), nil } func (l CSV) Bytes() []byte { buf := bytes.NewBuffer(make([]byte, 0, 128)) buf.WriteByte('{') for i, s := range l { if i > 0 { buf.WriteByte(',') } buf.WriteByte('"') buf.WriteString(strings.Replace(strings.Replace(s, `\`, `\\\`, -1), `"`, `\"`, -1)) // optimize this buf.WriteByte('"') } buf.WriteByte('}') return buf.Bytes() } <|start_filename|>storage/objcache/redis.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 redis csall package objcache import ( "context" gourl "net/url" "strconv" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/net/url" "github.com/gomodule/redigo/redis" ) // RedisOption applies several options for the Redis client. type RedisOption struct { KeyPrefix string } // NewRedisClient connects to the Redis server and does a ping to check if the // connection works correctly. func NewRedisClient(pool *redis.Pool, ro *RedisOption) NewStorageFn { return func() (Storager, error) { w := makeRedisWrapper(pool, ro) w.ping = true if err := doPing(w); err != nil { return nil, errors.WithStack(err) } return w, nil } } func parseDuration(keys []string, ds []*time.Duration, params gourl.Values) (err error) { i := 0 for ; i < len(keys) && err == nil; i++ { if p := params.Get(keys[i]); p != "" { *(ds[i]), err = time.ParseDuration(p) } } if err != nil { err = errors.NotValid.New(err, "[objcache] NewRedisByURLClient Parameter %q with value %q is invalid", keys[i], params.Get(keys[i])) } return err } func parseInt(keys []string, ds []*int, params gourl.Values) (err error) { i := 0 for ; i < len(keys) && err == nil; i++ { if p := params.Get(keys[i]); p != "" { *(ds[i]), err = strconv.Atoi(p) } } if err != nil { err = errors.NotValid.New(err, "[objcache] NewRedisByURLClient Parameter %q with value %q is invalid", keys[i], params.Get(keys[i])) } return err } // NewRedisByURLClient connects to a Redis server at the given URL using the HTTP URI // scheme. URLs should follow the draft IANA specification for the scheme // (https://www.iana.org/assignments/uri-schemes/prov/redis). This option // function sets the connection as cache backend to the Service. // // On error, while parsing the rawURL, this function will leak sensitive data, // for now. // // For example: // redis://localhost:6379/?db=3 // redis://localhost:6379/?max_active=50&max_idle=5&idle_timeout=10s&max_conn_lifetime=1m&key_prefix=xcache_ func NewRedisByURLClient(rawURL string) NewStorageFn { return func() (Storager, error) { addr, _, password, params, err := url.ParseConnection(rawURL) if err != nil { return nil, errors.Wrapf(err, "[objcache] Redis error parsing URL %q", rawURL) } pool := &redis.Pool{ Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", addr) if err != nil { return nil, errors.Fatal.New(err, "[objcache] Redis Dial failed") } if password != "" { if _, err := c.Do("AUTH", password); err != nil { c.Close() return nil, errors.Unauthorized.New(err, "[objcache] Redis AUTH failed") } } if _, err := c.Do("SELECT", params.Get("db")); err != nil { c.Close() return nil, errors.Fatal.New(err, "[objcache] Redis DB select failed") } return c, nil }, } // add some more params if missing err = parseDuration([]string{ "max_conn_lifetime", "idle_timeout", }, []*time.Duration{ &pool.MaxConnLifetime, &pool.IdleTimeout, }, params) if err != nil { return nil, errors.WithStack(err) } err = parseInt([]string{ "max_idle", "max_active", }, []*int{ &pool.MaxIdle, &pool.MaxActive, }, params) if err != nil { return nil, errors.WithStack(err) } // if params.Get("tls") == "1" { // o.TLSConfig = &tls.Config{ServerName: o.Addr} // TODO check if might be wrong the Addr, // } return NewRedisClient(pool, &RedisOption{ KeyPrefix: params.Get("key_prefix"), })() } } func doPing(w redisWrapper) error { if !w.ping { return nil } conn := w.Pool.Get() defer conn.Close() pong, err := redis.String(conn.Do("PING")) if err != nil && err != redis.ErrNil { return errors.Fatal.Newf("[objcache] Redis Ping failed: %s", err) } if pong != "PONG" { return errors.ConnectionFailed.Newf("[objcache] Redis Ping not Pong: %#v", pong) } return nil } func makeRedisWrapper(rp *redis.Pool, ro *RedisOption) redisWrapper { return redisWrapper{ Pool: rp, // ipf: &sync.Pool{ // New: func() interface{} { // ifs := make([]interface{}, 0, 10) // return &ifs // }, // }, keyPrefix: ro.KeyPrefix, } } type redisWrapper struct { *redis.Pool ping bool keyPrefix string // ifp *sync.Pool } func (w redisWrapper) Set(_ context.Context, keys []string, values [][]byte, expirations []time.Duration) (err error) { conn := w.Pool.Get() defer func() { if err2 := conn.Close(); err == nil && err2 != nil { err = err2 } }() args := make([]interface{}, 0, len(keys)*3) for i, key := range keys { e := expirations[i].Seconds() // e = expires in x seconds if e < 1 { args = append(args, key, values[i]) } else { if _, err2 := conn.Do("SETEX", key, e, values[i]); err2 != nil { err = errors.Wrapf(err2, "[objcache] With key %q", key) return } } } if la := len(args); la > 0 && la%2 == 0 { if _, err2 := conn.Do("MSET", args...); err2 != nil { err = errors.Wrapf(err2, "[objcache] With keys %v", keys) return } } return err } func (w redisWrapper) Get(_ context.Context, keys []string) (values [][]byte, err error) { conn := w.Pool.Get() defer func() { if err2 := conn.Close(); err == nil && err2 != nil { err = err2 } }() if len(keys) == 1 { var val []byte val, err = redis.Bytes(conn.Do("GET", keys[0])) if err != nil { if err == redis.ErrNil { err = nil val = nil } else { return nil, errors.Wrapf(err, "[objcache] With keys %v", keys) } } values = append(values, val) return } values, err = redis.ByteSlices(conn.Do("MGET", strSliceToIFaces(nil, keys)...)) if err != nil { err = errors.Wrapf(err, "[objcache] With keys %v", keys) return } if lk, lv := len(keys), len(values); lk != lv { err = errors.Mismatch.Newf("[objcache] Length of keys (%d) does not match length of returned bytes (%d). Keys: %v", lk, lv, keys) } return } func strSliceToIFaces(ret []interface{}, sl []string) []interface{} { // TODO use a sync.Pool but write before hand appropriate concurrent running benchmarks if ret == nil { ret = make([]interface{}, 0, len(sl)) } for _, s := range sl { ret = append(ret, s) } return ret } func (w redisWrapper) Delete(_ context.Context, keys []string) (err error) { conn := w.Pool.Get() defer func() { if err2 := conn.Close(); err == nil && err2 != nil { err = err2 } }() if _, err = conn.Do("DEL", strSliceToIFaces(nil, keys)...); err != nil { err = errors.Wrapf(err, "[objcache] With keys %v", keys) } return } func (w redisWrapper) Truncate(ctx context.Context) (err error) { // TODO flush redis by key prefix return nil } func (w redisWrapper) Close() error { return w.Pool.Close() } <|start_filename|>sql/mycanal/canal.go<|end_filename|> package mycanal import ( "bytes" "context" "crypto/tls" "database/sql" "fmt" "net" "regexp" "sync" "sync/atomic" "time" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/config" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/myreplicator" "github.com/corestoreio/pkg/store/scope" "golang.org/x/sync/singleflight" "github.com/corestoreio/pkg/util/conv" "github.com/go-sql-driver/mysql" simysql "github.com/siddontang/go-mysql/mysql" ) // Use flavor for different MySQL versions, const ( MySQLFlavor = "mysql" MariaDBFlavor = "mariadb" ) // Configuration paths for config.Service const ( ConfigPathBackendPosition = `sql/mycanal/master_position` ConfigPathIncludeTableRegex = `sql/mycanal/include_table_regex` ConfigPathExcludeTableRegex = `sql/mycanal/exclude_table_regex` ConfigPathBinlogStartFile = `sql/mycanal/binlog_start_file` ConfigPathBinlogStartPosition = `sql/mycanal/binlog_start_position` ConfigPathBinlogSlaveID = `sql/mycanal/binlog_slave_id` ConfigPathServerFlavor = `sql/mycanal/server_flavor` ) // Canal can sync your MySQL data. MySQL must use the binlog format ROW. type Canal struct { opts Options configPathBackendPosition *config.Path // mclose acts only during the call to Close(). mclose sync.Mutex // DSN contains the parsed DSN dsn *mysql.Config cfgScope config.Scoped // required syncer *myreplicator.BinlogSyncer masterMu sync.RWMutex masterStatus ddl.MasterStatus masterGTID simysql.GTIDSet masterLastSaveTime time.Time masterWarningConfigSetIsNilLogged bool rsMu sync.RWMutex // the empty map key declares event handler for all tables, filtered by the regexes. // Otherwise an event handler is only registered for a specific table. rsHandlers map[string][]RowsEventHandler // dbcp is a database connection pool dbcp *dml.ConnPool // Tables contains the overall SQL table cache. If a table gets modified // during runtime of this program then somehow we must clear the cache to // reload the table structures. tables *ddl.Tables // tableSFG takes to only execute one SQL query per table in parallel // situations. No need for a pointer because Canal is already a pointer. So // simple embedding. tableSFG singleflight.Group tableLock sync.RWMutex tableAllowedCache map[string]bool includeTableRegex []*regexp.Regexp excludeTableRegex []*regexp.Regexp closed *int32 wg sync.WaitGroup } // DBConFactory creates a new database connection. type DBConFactory func(dsn string) (*dml.ConnPool, error) // WithMySQL adds the database/sql.DB driver including a ping to the database // from the provided DSN. func WithMySQL() DBConFactory { return func(dsn string) (*dml.ConnPool, error) { dbc, err := dml.NewConnPool(dml.WithDSN(dsn), dml.WithVerifyConnection()) return dbc, errors.WithStack(err) } } // WithDB allows to set your own DB connection. func WithDB(db *sql.DB) DBConFactory { return func(_ string) (*dml.ConnPool, error) { if err := db.Ping(); err != nil { return nil, errors.WithStack(err) } dbc, err := dml.NewConnPool(dml.WithDB(db)) return dbc, errors.WithStack(err) } } func withIncludeTables(regexes []string) func(c *Canal) error { return func(c *Canal) error { if len(regexes) == 0 { return nil } c.tableLock.Lock() defer c.tableLock.Unlock() c.includeTableRegex = make([]*regexp.Regexp, len(regexes)) for i, val := range regexes { reg, err := regexp.Compile(val) if err != nil { return errors.WithStack(err) } c.includeTableRegex[i] = reg } return nil } } func withExcludeTables(regexes []string) func(c *Canal) error { return func(c *Canal) error { if len(regexes) == 0 { return nil } c.tableLock.Lock() defer c.tableLock.Unlock() c.excludeTableRegex = make([]*regexp.Regexp, len(regexes)) for i, val := range regexes { reg, err := regexp.Compile(val) if err != nil { return errors.WithStack(err) } c.excludeTableRegex[i] = reg } return nil } } // withUpdateBinlogStart enables to start from a specific position or just start // from the current master position. See startSyncBinlog func withUpdateBinlogStart(c *Canal) error { if c.opts.BinlogStartFile != "" && c.opts.BinlogStartPosition > 0 { c.masterStatus.File = c.opts.BinlogStartFile c.masterStatus.Position = uint(c.opts.BinlogStartPosition) return nil } if c.opts.MasterStatusQueryTimeout == 0 { c.opts.MasterStatusQueryTimeout = time.Second * 20 } var ms ddl.MasterStatus ctx, cancel := context.WithTimeout(context.Background(), c.opts.MasterStatusQueryTimeout) defer cancel() if _, err := c.dbcp.WithQueryBuilder(&ms).Load(ctx, &ms); err != nil { return errors.WithStack(err) } c.masterStatus = ms return nil } // withPrepareSyncer creates its own database connection. func withPrepareSyncer(c *Canal) error { host, port, err := net.SplitHostPort(c.dsn.Addr) if err != nil { return errors.Wrapf(err, "[mycanal] withPrepareSyncer SplitHostPort %q", c.dsn.Addr) } if c.opts.BinlogSlaveId == 0 { c.opts.BinlogSlaveId = 100 } cfg := myreplicator.BinlogSyncerConfig{ ServerID: uint32(c.opts.BinlogSlaveId), Flavor: c.opts.Flavor, Host: host, Port: uint16(conv.ToUint(port)), User: c.dsn.User, Password: <PASSWORD>, Log: c.opts.Log, TLSConfig: c.opts.TLSConfig, MaxReconnectAttempts: c.opts.MaxReconnectAttempts, } c.syncer = myreplicator.NewBinlogSyncer(&cfg) return nil } func withCheckBinlogRowFormat(c *Canal) error { const varName = "binlog_format" ctx := context.Background() v := ddl.NewVariables(varName) if _, err := c.dbcp.WithQueryBuilder(v).Load(ctx, v); err != nil { return errors.WithStack(err) } if !v.EqualFold(varName, "ROW") { return errors.NotSupported.Newf("[mycanal] binlog variable %q must have the configured ROW format, but got %q. ROW means: Records events affecting individual table rows.", varName, v.Data[varName]) } return nil } // Options provides multiple options for NewCanal. Part of those options can get // loaded via config.Scoped. type Options struct { // ConfigScoped defines the configuration to load the following fields from. // If not set the data won't be loaded. ConfigScoped config.Scoped // ConfigSet used to persists the master position of the binlog stream. ConfigSet config.Setter Log log.Logger TLSConfig *tls.Config // Needs some rework // IncludeTableRegex defines the regex which matches the allowed table // names. Default state of WithIncludeTables is empty, this will include all // tables. IncludeTableRegex []string // ExcludeTableRegex defines the regex which matches the excluded table // names. Default state of WithExcludeTables is empty, ignores exluding and // includes all tables. ExcludeTableRegex []string // Set to change the maximum number of attempts to re-establish a broken // connection MaxReconnectAttempts int BinlogStartFile string BinlogStartPosition uint64 BinlogSlaveId uint64 // Flavor defines if `mariadb` or `mysql` should be used. Defaults to // `mariadb`. Flavor string MasterStatusQueryTimeout time.Duration // OnClose runs before the database connection gets closed and after the // syncer has been closed. The syncer does not "see" the changes comming // from the queries executed in the call back. OnClose func(*dml.ConnPool) error } func (o *Options) loadFromConfigService() (err error) { defer func() { switch o.Flavor { case MySQLFlavor: o.Flavor = MySQLFlavor default: o.Flavor = MariaDBFlavor } }() if o.Log == nil { o.Log = log.BlackHole{} } if !o.ConfigScoped.IsValid() { return nil } if o.IncludeTableRegex == nil { v := o.ConfigScoped.Get(scope.Default, ConfigPathIncludeTableRegex) if o.IncludeTableRegex, err = v.Strs(o.IncludeTableRegex...); err != nil { err = errors.WithStack(err) return } } if o.ExcludeTableRegex == nil { v := o.ConfigScoped.Get(scope.Default, ConfigPathExcludeTableRegex) if o.ExcludeTableRegex, err = v.Strs(o.ExcludeTableRegex...); err != nil { err = errors.WithStack(err) return } } if o.BinlogStartFile == "" { v := o.ConfigScoped.Get(scope.Default, ConfigPathBinlogStartFile) o.BinlogStartFile = v.UnsafeStr() } if o.BinlogStartPosition == 0 { v := o.ConfigScoped.Get(scope.Default, ConfigPathBinlogStartPosition) o.BinlogStartPosition = v.UnsafeUint64() } if o.BinlogSlaveId == 0 { v := o.ConfigScoped.Get(scope.Default, ConfigPathBinlogSlaveID) o.BinlogSlaveId = v.UnsafeUint64() } if o.Flavor == "" { v := o.ConfigScoped.Get(scope.Default, ConfigPathServerFlavor) o.Flavor = v.UnsafeStr() } return nil } // NewCanal creates a new canal object to start reading the MySQL binary log. // The DSN is need to setup two different connections. One connection for // reading the binary stream and the 2nd connection to execute queries. The 2nd // argument `db` gets used to executed the queries, like setting variables or // getting table information. Default database flavor is `mariadb`. // export CS_DSN='root:PASSWORD@tcp(localhost:3306)/DATABASE_NAME func NewCanal(dsn string, db DBConFactory, opt *Options) (*Canal, error) { pDSN, err := mysql.ParseDSN(dsn) if err != nil { return nil, errors.WithStack(err) } if err := opt.loadFromConfigService(); err != nil { return nil, errors.WithStack(err) } c := &Canal{ opts: *opt, configPathBackendPosition: config.MustMakePath(ConfigPathBackendPosition), dsn: pDSN, closed: new(int32), tables: ddl.MustNewTables(), } atomic.StoreInt32(c.closed, 0) c.tables.Schema = c.dsn.DBName c.dbcp, err = db(dsn) if err != nil { return nil, errors.WithStack(err) } if err := c.tables.Options(ddl.WithConnPool(c.dbcp)); err != nil { return nil, errors.WithStack(err) } initOptFn := [...]func(c *Canal) error{ withUpdateBinlogStart, withPrepareSyncer, withCheckBinlogRowFormat, withIncludeTables(opt.IncludeTableRegex), withExcludeTables(opt.ExcludeTableRegex), } for _, optFn := range initOptFn { if err := optFn(c); err != nil { return nil, errors.WithStack(err) } } c.tableLock.Lock() if c.includeTableRegex != nil || c.excludeTableRegex != nil { c.tableAllowedCache = make(map[string]bool) } c.tableLock.Unlock() return c, nil } // TODO continue sync from last stored master position func (c *Canal) masterSave(fileName string, pos uint) error { c.masterMu.Lock() defer c.masterMu.Unlock() c.masterStatus.File = fileName c.masterStatus.Position = pos now := time.Now() if now.Sub(c.masterLastSaveTime) < time.Second { return nil } if c.opts.ConfigSet == nil { if !c.masterWarningConfigSetIsNilLogged && c.opts.Log.IsInfo() { c.masterWarningConfigSetIsNilLogged = true c.opts.Log.Info("mycanal.masterSave.config.setter", log.Bool("config_setter_is_nil", true), log.String("database", c.dsn.DBName), log.Stringer("master_status", c.masterStatus)) } return nil } var buf bytes.Buffer _, _ = c.masterStatus.WriteTo(&buf) if err := c.opts.ConfigSet.Set(c.configPathBackendPosition, buf.Bytes()); err != nil { if c.opts.Log.IsInfo() { c.opts.Log.Info("mycanal.masterSave.error", log.Time("master_last_save_time", c.masterLastSaveTime), log.Err(err), log.String("database", c.dsn.DBName), log.Stringer("master_status", c.masterStatus)) } return errors.WithStack(err) } c.masterLastSaveTime = now return nil } // SyncedPosition returns the current synced position as retrieved from the SQl // server. func (c *Canal) SyncedPosition() ddl.MasterStatus { c.masterMu.RLock() defer c.masterMu.RUnlock() return c.masterStatus } // Start starts the sync process in the background as a goroutine. You can stop // the goroutine via the context. func (c *Canal) Start(ctx context.Context) error { go c.run(ctx) return nil } // run gets executed in its own goroutine func (c *Canal) run(ctx context.Context) { // refactor for better error handling defer c.wg.Done() c.wg.Add(1) if err := c.startSyncBinlog(ctx); err != nil { if !c.isClosed() && c.opts.Log.IsInfo() { c.opts.Log.Info("[mycanal] Canal start has encountered a sync binlog error", log.Err(err)) } } } func (c *Canal) isClosed() bool { return atomic.LoadInt32(c.closed) == int32(1) } // Close closes all underlying connections func (c *Canal) Close() error { c.mclose.Lock() defer c.mclose.Unlock() if c.isClosed() { return nil } atomic.StoreInt32(c.closed, 1) if c.syncer != nil { if err := c.syncer.Close(); err != nil { return errors.WithStack(err) } c.syncer = nil } if err := c.opts.OnClose(c.dbcp); err != nil { return errors.WithStack(err) } if err := c.dbcp.Close(); err != nil { return errors.WithStack(err) } c.wg.Wait() return nil } func (c *Canal) isTableAllowed(tblName string) bool { // no filter, return true if c.tableAllowedCache == nil { return true } c.tableLock.RLock() isAllowed, ok := c.tableAllowedCache[tblName] c.tableLock.RUnlock() if ok { // cache hit return isAllowed } matchFlag := false // check include if c.includeTableRegex != nil { for _, reg := range c.includeTableRegex { if reg.MatchString(tblName) { matchFlag = true break } } } // check exclude if matchFlag && c.excludeTableRegex != nil { for _, reg := range c.excludeTableRegex { if reg.MatchString(tblName) { matchFlag = false break } } } c.tableLock.Lock() c.tableAllowedCache[tblName] = matchFlag c.tableLock.Unlock() return matchFlag } type errTableNotAllowed string func (t errTableNotAllowed) ErrorKind() errors.Kind { return errors.NotAllowed } func (t errTableNotAllowed) Error() string { return fmt.Sprintf("[mycanal] Table %q is not allowed", string(t)) } // FindTable tries to find a table by its ID. If the table cannot be found by // the first search, it will add the table to the internal map and performs a // column load from the information_schema and then returns the fully defined // table. Only tables which are found in the database name of the DSN get // loaded. func (c *Canal) FindTable(ctx context.Context, tableName string) (*ddl.Table, error) { if !c.isTableAllowed(tableName) { return nil, errTableNotAllowed(tableName) } t, err := c.tables.Table(tableName) if err == nil { return t, nil } if !errors.NotFound.Match(err) { return nil, errors.WithStack(err) } val, err, _ := c.tableSFG.Do(tableName, func() (interface{}, error) { if err := c.tables.Options(ddl.WithCreateTable(ctx, tableName, "")); err != nil { return nil, errors.WithStack(err) } t, err = c.tables.Table(tableName) if err != nil { return nil, errors.WithStack(err) } return t, nil }) if err != nil { return nil, errors.WithStack(err) } return val.(*ddl.Table), nil } // ClearTableCache clear table cache func (c *Canal) ClearTableCache(db string, table string) { c.tables.DeleteAllFromCache() } // CheckBinlogRowImage checks MySQL binlog row image, must be in FULL, MINIMAL, NOBLOB func (c *Canal) CheckBinlogRowImage(ctx context.Context, image string) error { // need to check MySQL binlog row image? full, minimal or noblob? // now only log. // TODO what about MariaDB? const varName = "binlog_row_image" if c.opts.Flavor == MySQLFlavor { v := ddl.NewVariables(varName) if _, err := c.dbcp.WithQueryBuilder(v).Load(ctx, v); err != nil { return errors.WithStack(err) } // MySQL has binlog row image from 5.6, so older will return empty if v.EqualFold(varName, image) { return errors.NotSupported.Newf("[mycanal] MySQL uses %q binlog row image, but we want %q", v.Data[varName], image) } } return nil } <|start_filename|>sql/dmlgen/dmltestgenerated4/db_part_query_gen.go<|end_filename|> // Code generated by corestoreio/pkg/util/codegen. DO NOT EDIT. // Generated by sql/dmlgen. DO NOT EDIT. package dmltestgenerated4 import ( "context" "database/sql" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/storage/null" ) // TableName constants define the names of all tables. const ( TableNameCoreConfiguration = "core_configuration" TableNameSalesOrderStatusState = "sales_order_status_state" TableNameViewCustomerAutoIncrement = "view_customer_auto_increment" ) // Columns struct provides for all tables the name of the columns. Allows type // safety. var Columns = struct { CoreConfiguration struct { ConfigID string Scope string ScopeID string Expires string Path string Value string VersionTs string VersionTe string } SalesOrderStatusState struct { Status string State string IsDefault string VisibleOnFront string } ViewCustomerAutoIncrement struct { CeEntityID string Email string Firstname string Lastname string City string } }{ CoreConfiguration: struct { ConfigID string Scope string ScopeID string Expires string Path string Value string VersionTs string VersionTe string }{ ConfigID: "config_id", Scope: "scope", ScopeID: "scope_id", Expires: "expires", Path: "path", Value: "value", VersionTs: "version_ts", VersionTe: "version_te", }, SalesOrderStatusState: struct { Status string State string IsDefault string VisibleOnFront string }{ Status: "status", State: "state", IsDefault: "is_default", VisibleOnFront: "visible_on_front", }, ViewCustomerAutoIncrement: struct { CeEntityID string Email string Firstname string Lastname string City string }{ CeEntityID: "ce_entity_id", Email: "email", Firstname: "firstname", Lastname: "lastname", City: "city", }, } var dbmEmptyOpts = []dml.DBRFunc{func(dbr *dml.DBR) { // do nothing because Clone gets called automatically }} func dbmNoopResultCheckFn(_ sql.Result, err error) error { return err } // Event functions are getting dispatched during before or after handling a // collection or an entity. // Context is always non-nil but either collection or entity pointer will be set. type ( EventCoreConfigurationFn func(context.Context, *CoreConfigurations, *CoreConfiguration) error EventSalesOrderStatusStateFn func(context.Context, *SalesOrderStatusStates, *SalesOrderStatusState) error EventViewCustomerAutoIncrementFn func(context.Context, *ViewCustomerAutoIncrements, *ViewCustomerAutoIncrement) error ) // DBMOption provides various options to the DBM object. type DBMOption struct { TableOptions []ddl.TableOption // gets applied at the beginning TableOptionsAfter []ddl.TableOption // gets applied at the end InitSelectFn func(*dml.Select) *dml.Select InitUpdateFn func(*dml.Update) *dml.Update InitDeleteFn func(*dml.Delete) *dml.Delete InitInsertFn func(*dml.Insert) *dml.Insert eventCoreConfigurationFunc [dml.EventFlagMax][]EventCoreConfigurationFn eventSalesOrderStatusStateFunc [dml.EventFlagMax][]EventSalesOrderStatusStateFn eventViewCustomerAutoIncrementFunc [dml.EventFlagMax][]EventViewCustomerAutoIncrementFn } // AddEventCoreConfiguration adds a specific defined event call back to the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventCoreConfiguration(event dml.EventFlag, fn EventCoreConfigurationFn) *DBMOption { o.eventCoreConfigurationFunc[event] = append(o.eventCoreConfigurationFunc[event], fn) return o } // AddEventSalesOrderStatusState adds a specific defined event call back to the // DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventSalesOrderStatusState(event dml.EventFlag, fn EventSalesOrderStatusStateFn) *DBMOption { o.eventSalesOrderStatusStateFunc[event] = append(o.eventSalesOrderStatusStateFunc[event], fn) return o } // AddEventViewCustomerAutoIncrement adds a specific defined event call back to // the DBM. // It panics if the event argument is larger than dml.EventFlagMax. func (o *DBMOption) AddEventViewCustomerAutoIncrement(event dml.EventFlag, fn EventViewCustomerAutoIncrementFn) *DBMOption { o.eventViewCustomerAutoIncrementFunc[event] = append(o.eventViewCustomerAutoIncrementFunc[event], fn) return o } // DBM defines the DataBaseManagement object for the tables core_configuration, // sales_order_status_state, view_customer_auto_increment type DBM struct { *ddl.Tables option DBMOption } func (dbm DBM) eventCoreConfigurationFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *CoreConfigurations, e *CoreConfiguration) error { if len(dbm.option.eventCoreConfigurationFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventCoreConfigurationFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventSalesOrderStatusStateFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *SalesOrderStatusStates, e *SalesOrderStatusState) error { if len(dbm.option.eventSalesOrderStatusStateFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventSalesOrderStatusStateFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } func (dbm DBM) eventViewCustomerAutoIncrementFunc(ctx context.Context, ef dml.EventFlag, skipEvents bool, ec *ViewCustomerAutoIncrements, e *ViewCustomerAutoIncrement) error { if len(dbm.option.eventViewCustomerAutoIncrementFunc[ef]) == 0 || skipEvents { return nil } for _, fn := range dbm.option.eventViewCustomerAutoIncrementFunc[ef] { if err := fn(ctx, ec, e); err != nil { return errors.WithStack(err) } } return nil } // NewDBManager returns a goified version of the MySQL/MariaDB table schema for // the tables: core_configuration, sales_order_status_state, // view_customer_auto_increment Auto generated by dmlgen. func NewDBManager(ctx context.Context, dbmo *DBMOption) (*DBM, error) { tbls, err := ddl.NewTables(append([]ddl.TableOption{ddl.WithCreateTable(ctx, TableNameCoreConfiguration, "", TableNameSalesOrderStatusState, "", TableNameViewCustomerAutoIncrement, "")}, dbmo.TableOptions...)...) if err != nil { return nil, errors.WithStack(err) } if dbmo.InitSelectFn == nil { dbmo.InitSelectFn = func(s *dml.Select) *dml.Select { return s } } if dbmo.InitUpdateFn == nil { dbmo.InitUpdateFn = func(s *dml.Update) *dml.Update { return s } } if dbmo.InitDeleteFn == nil { dbmo.InitDeleteFn = func(s *dml.Delete) *dml.Delete { return s } } if dbmo.InitInsertFn == nil { dbmo.InitInsertFn = func(s *dml.Insert) *dml.Insert { return s } } err = tbls.Options( ddl.WithQueryDBR(map[string]dml.QueryBuilder{ "CoreConfigurationsSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameCoreConfiguration).Select("*")), "CoreConfigurationsSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCoreConfiguration).Select("*")).Where( dml.Column(`config_id`).In().PlaceHolder(), ), "CoreConfigurationSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameCoreConfiguration).Select("*")).Where( dml.Column(`config_id`).Equal().PlaceHolder(), ), "CoreConfigurationUpdateByPK": dbmo.InitUpdateFn(tbls.MustTable(TableNameCoreConfiguration).Update().Where( dml.Column(`config_id`).Equal().PlaceHolder(), )), "CoreConfigurationDeleteByPK": dbmo.InitDeleteFn(tbls.MustTable(TableNameCoreConfiguration).Delete().Where( dml.Column(`config_id`).In().PlaceHolder(), )), "CoreConfigurationInsert": dbmo.InitInsertFn(tbls.MustTable(TableNameCoreConfiguration).Insert()), "CoreConfigurationUpsertByPK": dbmo.InitInsertFn(tbls.MustTable(TableNameCoreConfiguration).Insert()).OnDuplicateKey(), "SalesOrderStatusStatesSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameSalesOrderStatusState).Select("*")), "SalesOrderStatusStatesSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameSalesOrderStatusState).Select("*")).Where( dml.Columns(`status`, `state`).In().Tuples(), ), "SalesOrderStatusStateSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameSalesOrderStatusState).Select("*")).Where( dml.Columns(`status`, `state`).Equal().Tuples(), ), "ViewCustomerAutoIncrementsSelectAll": dbmo.InitSelectFn(tbls.MustTable(TableNameViewCustomerAutoIncrement).Select("*")), "ViewCustomerAutoIncrementsSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameViewCustomerAutoIncrement).Select("*")).Where( dml.Column(`ce_entity_id`).In().PlaceHolder(), ), "ViewCustomerAutoIncrementSelectByPK": dbmo.InitSelectFn(tbls.MustTable(TableNameViewCustomerAutoIncrement).Select("*")).Where( dml.Column(`ce_entity_id`).Equal().PlaceHolder(), ), }), ) if err != nil { return nil, err } if err := tbls.Options(dbmo.TableOptionsAfter...); err != nil { return nil, err } return &DBM{Tables: tbls, option: *dbmo}, nil } // CoreConfiguration represents a single row for DB table core_configuration. // Auto generated. // Table comment: Config Data type CoreConfiguration struct { ConfigID uint32 `max_len:"10"` // config_id int(10) unsigned NOT NULL PRI auto_increment "Id" Scope string `max_len:"8"` // scope varchar(8) NOT NULL MUL DEFAULT ''default'' "Scope" ScopeID int32 `max_len:"10"` // scope_id int(11) NOT NULL DEFAULT '0' "Scope Id" Expires null.Time // expires datetime NULL DEFAULT 'NULL' "Value expiration time" Path string `max_len:"255"` // path varchar(255) NOT NULL "Path" Value null.String `max_len:"65535"` // value text NULL DEFAULT 'NULL' "Value" VersionTs time.Time // version_ts timestamp(6) NOT NULL STORED GENERATED "Timestamp Start Versioning" VersionTe time.Time // version_te timestamp(6) NOT NULL PRI STORED GENERATED "Timestamp End Versioning" } // AssignLastInsertID updates the increment ID field with the last inserted ID // from an INSERT operation. Implements dml.InsertIDAssigner. Auto generated. func (e *CoreConfiguration) AssignLastInsertID(id int64) { e.ConfigID = uint32(id) } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *CoreConfiguration) MapColumns(cm *dml.ColumnMap) error { for cm.Next(8) { switch c := cm.Column(); c { case "config_id", "0": cm.Uint32(&e.ConfigID) case "scope", "1": cm.String(&e.Scope) case "scope_id", "2": cm.Int32(&e.ScopeID) case "expires", "3": cm.NullTime(&e.Expires) case "path", "4": cm.String(&e.Path) case "value", "5": cm.NullString(&e.Value) case "version_ts", "6": cm.Time(&e.VersionTs) case "version_te", "7": cm.Time(&e.VersionTe) default: return errors.NotFound.Newf("[dmltestgenerated4] CoreConfiguration Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *CoreConfiguration) Load(ctx context.Context, dbm *DBM, primaryKey uint32, opts ...dml.DBRFunc) (err error) { if e == nil { return errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("CoreConfigurationSelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } func (e *CoreConfiguration) Delete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationDeleteByPK", opts...).ExecContext(ctx, e.ConfigID); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CoreConfiguration) Update(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationUpdateByPK", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CoreConfiguration) Insert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationInsert", opts...).ExecContext(ctx, e); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } func (e *CoreConfiguration) Upsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if e == nil { return nil, errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", e)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, nil, e); err != nil { return nil, errors.WithStack(err) } return res, nil } // IsSet returns true if the entity has non-empty primary keys. func (e *CoreConfiguration) IsSet() bool { return e.ConfigID > 0 } // CoreConfigurations represents a collection type for DB table // core_configuration // Not thread safe. Auto generated. type CoreConfigurations struct { Data []*CoreConfiguration `json:"data,omitempty"` } // NewCoreConfigurations creates a new initialized collection. Auto generated. func NewCoreConfigurations() *CoreConfigurations { return &CoreConfigurations{ Data: make([]*CoreConfiguration, 0, 5), } } // AssignLastInsertID traverses through the slice and sets an incrementing new ID // to each entity. func (cc *CoreConfigurations) AssignLastInsertID(id int64) { for i := 0; i < len(cc.Data); i++ { cc.Data[i].AssignLastInsertID(id + int64(i)) } } func (cc *CoreConfigurations) scanColumns(cm *dml.ColumnMap, e *CoreConfiguration) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *CoreConfigurations) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Data = cc.Data[:0] } var e CoreConfiguration if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "config_id": cm = cm.Uint32s(cc.ConfigIDs()...) default: return errors.NotFound.Newf("[dmltestgenerated4] CoreConfigurations Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated4] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *CoreConfigurations) DBLoad(ctx context.Context, dbm *DBM, pkIDs []uint32, opts ...dml.DBRFunc) (err error) { if cc == nil { return errors.NotValid.Newf("CoreConfiguration can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs ConfigID into the context as value to search for a cache entry in the event function. if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("CoreConfigurationsSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("CoreConfigurationsSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } func (cc *CoreConfigurations) DBDelete(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if cc == nil { return nil, errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeDelete, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationDeleteByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterDelete, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *CoreConfigurations) DBUpdate(ctx context.Context, dbm *DBM, resCheckFn func(sql.Result, error) error, opts ...dml.DBRFunc) (err error) { if cc == nil { return errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpdate, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if len(opts) == 0 { opts = dbmEmptyOpts } if resCheckFn == nil { resCheckFn = dbmNoopResultCheckFn } dbrStmt, err := dbm.ConnPool.WithCacheKey("CoreConfigurationUpdateByPK", opts...).Prepare(ctx) if err != nil { return errors.WithStack(err) } for _, c := range cc.Data { if err := resCheckFn(dbrStmt.ExecContext(ctx, c)); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpdate, qo.SkipEvents, cc, nil)) } func (cc *CoreConfigurations) DBInsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if cc == nil { return nil, errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeInsert, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationInsert", opts...).ExecContext(ctx, cc); err != nil { return nil, errors.WithStack(err) } if err = errors.WithStack(dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterInsert, qo.SkipEvents, cc, nil)); err != nil { return nil, errors.WithStack(err) } return res, nil } func (cc *CoreConfigurations) DBUpsert(ctx context.Context, dbm *DBM, opts ...dml.DBRFunc) (res sql.Result, err error) { if cc == nil { return nil, errors.NotValid.Newf("CoreConfigurations can't be nil") } qo := dml.FromContextQueryOptions(ctx) if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagBeforeUpsert, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } if res, err = dbm.ConnPool.WithCacheKey("CoreConfigurationUpsertByPK", opts...).ExecContext(ctx, dml.Qualify("", cc)); err != nil { return nil, errors.WithStack(err) } if err = dbm.eventCoreConfigurationFunc(ctx, dml.EventFlagAfterUpsert, qo.SkipEvents, cc, nil); err != nil { return nil, errors.WithStack(err) } return res, nil } // Each will run function f on all items in []* CoreConfiguration . Auto // generated via dmlgen. func (cc *CoreConfigurations) Each(f func(*CoreConfiguration)) *CoreConfigurations { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // ConfigIDs returns a slice with the data or appends it to a slice. // Auto generated. func (cc *CoreConfigurations) ConfigIDs(ret ...uint32) []uint32 { if cc == nil { return nil } if ret == nil { ret = make([]uint32, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.ConfigID) } return ret } // SalesOrderStatusState represents a single row for DB table // sales_order_status_state. Auto generated. // Table comment: Sales Order Status Table type SalesOrderStatusState struct { Status string // status varchar(32) NOT NULL PRI "Status" State string // state varchar(32) NOT NULL PRI "Label" IsDefault bool // is_default smallint(5) unsigned NOT NULL DEFAULT '0' "Is Default" VisibleOnFront uint16 // visible_on_front smallint(5) unsigned NOT NULL DEFAULT '0' "Visible on front" } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *SalesOrderStatusState) MapColumns(cm *dml.ColumnMap) error { for cm.Next(4) { switch c := cm.Column(); c { case "status", "0": cm.String(&e.Status) case "state", "1": cm.String(&e.State) case "is_default", "2": cm.Bool(&e.IsDefault) case "visible_on_front", "3": cm.Uint16(&e.VisibleOnFront) default: return errors.NotFound.Newf("[dmltestgenerated4] SalesOrderStatusState Column %q not found", c) } } return errors.WithStack(cm.Err()) } type SalesOrderStatusStateLoadArgs struct { _Named_Fields_Required struct{} Status string State string } func (e *SalesOrderStatusState) Load(ctx context.Context, dbm *DBM, arg SalesOrderStatusStateLoadArgs, opts ...dml.DBRFunc) (err error) { if e == nil { return errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs arg.Status,arg.State into the context as value to search for a cache entry in the event function. if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("SalesOrderStatusStateSelectByPK", opts...).Load(ctx, e, arg.Status, arg.State); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } // IsSet returns true if the entity has non-empty primary keys. func (e *SalesOrderStatusState) IsSet() bool { return e.Status != "" && e.State != "" } // SalesOrderStatusStates represents a collection type for DB table // sales_order_status_state // Not thread safe. Auto generated. type SalesOrderStatusStates struct { Data []*SalesOrderStatusState `json:"data,omitempty"` } // NewSalesOrderStatusStates creates a new initialized collection. Auto // generated. func NewSalesOrderStatusStates() *SalesOrderStatusStates { return &SalesOrderStatusStates{ Data: make([]*SalesOrderStatusState, 0, 5), } } func (cc *SalesOrderStatusStates) scanColumns(cm *dml.ColumnMap, e *SalesOrderStatusState) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *SalesOrderStatusStates) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Data = cc.Data[:0] } var e SalesOrderStatusState if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) case dml.ColumnMapCollectionReadSet: for cm.Next(0) { switch c := cm.Column(); c { case "status": cm = cm.Strings(cc.Statuss()...) case "state": cm = cm.Strings(cc.States()...) default: return errors.NotFound.Newf("[dmltestgenerated4] SalesOrderStatusStates Column %q not found", c) } } // end for cm.Next default: return errors.NotSupported.Newf("[dmltestgenerated4] Unknown Mode: %q", string(m)) } return cm.Err() } type SalesOrderStatusStatesDBLoadArgs struct { _Named_Fields_Required struct{} Status string State string } func (cc *SalesOrderStatusStates) DBLoad(ctx context.Context, dbm *DBM, pkIDs []SalesOrderStatusStatesDBLoadArgs, opts ...dml.DBRFunc) (err error) { if cc == nil { return errors.NotValid.Newf("SalesOrderStatusState can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs Status,State into the context as value to search for a cache entry in the event function. if err = dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } cacheKey := "SalesOrderStatusStatesSelectAll" var args []interface{} if len(pkIDs) > 0 { args = make([]interface{}, 0, len(pkIDs)*2) for _, pk := range pkIDs { args = append(args, pk.Status) args = append(args, pk.State) } cacheKey = "SalesOrderStatusStatesSelectByPK" } if _, err = dbm.ConnPool.WithCacheKey(cacheKey, opts...).Load(ctx, cc, args...); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventSalesOrderStatusStateFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } // Each will run function f on all items in []* SalesOrderStatusState . Auto // generated via dmlgen. func (cc *SalesOrderStatusStates) Each(f func(*SalesOrderStatusState)) *SalesOrderStatusStates { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } // Statuss returns a slice with the data or appends it to a slice. // Auto generated. func (cc *SalesOrderStatusStates) Statuss(ret ...string) []string { if cc == nil { return nil } if ret == nil { ret = make([]string, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.Status) } return ret } // States returns a slice with the data or appends it to a slice. // Auto generated. func (cc *SalesOrderStatusStates) States(ret ...string) []string { if cc == nil { return nil } if ret == nil { ret = make([]string, 0, len(cc.Data)) } for _, e := range cc.Data { ret = append(ret, e.State) } return ret } // ViewCustomerAutoIncrement represents a single row for DB table // view_customer_auto_increment. Auto generated. // Table comment: VIEW type ViewCustomerAutoIncrement struct { CeEntityID uint32 // ce_entity_id int(10) unsigned NOT NULL DEFAULT '0' "Entity ID" Email null.String // email varchar(255) NULL DEFAULT 'NULL' "Email" Firstname string // firstname varchar(255) NOT NULL "First Name" Lastname string // lastname varchar(255) NOT NULL "Last Name" City string // city varchar(255) NOT NULL "City" } // MapColumns implements interface ColumnMapper only partially. Auto generated. func (e *ViewCustomerAutoIncrement) MapColumns(cm *dml.ColumnMap) error { for cm.Next(5) { switch c := cm.Column(); c { case "ce_entity_id", "0": cm.Uint32(&e.CeEntityID) case "email", "1": cm.NullString(&e.Email) case "firstname", "2": cm.String(&e.Firstname) case "lastname", "3": cm.String(&e.Lastname) case "city", "4": cm.String(&e.City) default: return errors.NotFound.Newf("[dmltestgenerated4] ViewCustomerAutoIncrement Column %q not found", c) } } return errors.WithStack(cm.Err()) } func (e *ViewCustomerAutoIncrement) Load(ctx context.Context, dbm *DBM, primaryKey uint32, opts ...dml.DBRFunc) (err error) { if e == nil { return errors.NotValid.Newf("ViewCustomerAutoIncrement can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs primaryKey into the context as value to search for a cache entry in the event function. if err = dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, nil, e); err != nil { return errors.WithStack(err) } if e.IsSet() { return nil // might return data from cache } if _, err = dbm.ConnPool.WithCacheKey("ViewCustomerAutoIncrementSelectByPK", opts...).Load(ctx, e, primaryKey); err != nil { return errors.WithStack(err) } return errors.WithStack(dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, nil, e)) } // IsSet returns true if the entity has non-empty primary keys. func (e *ViewCustomerAutoIncrement) IsSet() bool { return e.CeEntityID > 0 } // ViewCustomerAutoIncrements represents a collection type for DB table // view_customer_auto_increment // Not thread safe. Auto generated. type ViewCustomerAutoIncrements struct { Data []*ViewCustomerAutoIncrement `json:"data,omitempty"` } // NewViewCustomerAutoIncrements creates a new initialized collection. Auto // generated. func NewViewCustomerAutoIncrements() *ViewCustomerAutoIncrements { return &ViewCustomerAutoIncrements{ Data: make([]*ViewCustomerAutoIncrement, 0, 5), } } func (cc *ViewCustomerAutoIncrements) scanColumns(cm *dml.ColumnMap, e *ViewCustomerAutoIncrement) error { if err := e.MapColumns(cm); err != nil { return errors.WithStack(err) } // this function might get extended. return nil } // MapColumns implements dml.ColumnMapper interface. Auto generated. func (cc *ViewCustomerAutoIncrements) MapColumns(cm *dml.ColumnMap) error { switch m := cm.Mode(); m { case dml.ColumnMapEntityReadAll, dml.ColumnMapEntityReadSet: for _, e := range cc.Data { if err := cc.scanColumns(cm, e); err != nil { return errors.WithStack(err) } } case dml.ColumnMapScan: if cm.Count == 0 { cc.Data = cc.Data[:0] } var e ViewCustomerAutoIncrement if err := cc.scanColumns(cm, &e); err != nil { return errors.WithStack(err) } cc.Data = append(cc.Data, &e) default: return errors.NotSupported.Newf("[dmltestgenerated4] Unknown Mode: %q", string(m)) } return cm.Err() } func (cc *ViewCustomerAutoIncrements) DBLoad(ctx context.Context, dbm *DBM, pkIDs []uint32, opts ...dml.DBRFunc) (err error) { if cc == nil { return errors.NotValid.Newf("ViewCustomerAutoIncrement can't be nil") } qo := dml.FromContextQueryOptions(ctx) // put the IDs CeEntityID into the context as value to search for a cache entry in the event function. if err = dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagBeforeSelect, qo.SkipEvents, cc, nil); err != nil { return errors.WithStack(err) } if cc.Data != nil { return nil // might return data from cache } if len(pkIDs) > 0 { if _, err = dbm.ConnPool.WithCacheKey("ViewCustomerAutoIncrementsSelectByPK", opts...).Load(ctx, cc, pkIDs); err != nil { return errors.WithStack(err) } } else { if _, err = dbm.ConnPool.WithCacheKey("ViewCustomerAutoIncrementsSelectAll", opts...).Load(ctx, cc); err != nil { return errors.WithStack(err) } } return errors.WithStack(dbm.eventViewCustomerAutoIncrementFunc(ctx, dml.EventFlagAfterSelect, qo.SkipEvents, cc, nil)) } // Each will run function f on all items in []* ViewCustomerAutoIncrement . Auto // generated via dmlgen. func (cc *ViewCustomerAutoIncrements) Each(f func(*ViewCustomerAutoIncrement)) *ViewCustomerAutoIncrements { if cc == nil { return nil } for i := range cc.Data { f(cc.Data[i]) } return cc } <|start_filename|>sql/dmlgen/dmlgen_pub_test.go<|end_filename|> // Copyright 2015-2017, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dmlgen_test import ( "context" "io" "io/ioutil" "os" "strings" "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dmlgen" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" "github.com/corestoreio/pkg/util/codegen" "github.com/corestoreio/pkg/util/strs" ) /* SELECT concat('col_', replace( replace( replace( replace(COLUMN_TYPE, '(', '_') , ')', '') , ' ', '_') , ',', '_') ) AS ColName, COLUMN_TYPE, IF(IS_NULLABLE = 'NO', 'NOT NULL', ''), ' DEFAULT', COLUMN_DEFAULT, ',' FROM information_schema.COLUMNS WHERE table_schema = 'magento22' AND column_type IN (SELECT column_type FROM information_schema.`COLUMNS` GROUP BY column_type) GROUP BY COLUMN_TYPE ORDER BY COLUMN_TYPE */ func writeFile(t *testing.T, outFile string, wFn func(io.Writer, io.Writer) error) { testF := ioutil.Discard if strings.HasSuffix(outFile, ".go") { testFile := strings.Replace(outFile, ".go", "_test.go", 1) ft, err := os.Create(testFile) assert.NoError(t, err) defer dmltest.Close(t, ft) testF = ft } f, err := os.Create(outFile) assert.NoError(t, err) defer dmltest.Close(t, f) err = wFn(f, testF) if err != nil { if fe, ok := err.(*codegen.FormatError); ok { t.Errorf("Formatting failed: %s\n%s", fe.Error(), fe.Code) return } } assert.NoError(t, err, "%+v", err) } // TestNewGenerator_Protobuf_Json writes a Go and Proto file to the // dmltestgenerated directory for manual review for different tables. This test // also analyzes the foreign keys pointing to customer_entity. func TestNewGenerator_Protobuf_Json(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "testdata/testAll_*.sql", &dmltest.SQLDumpOptions{DSN: db.DSN()}).Deferred() ctx := context.Background() g, err := dmlgen.NewGenerator("github.com/corestoreio/pkg/sql/dmlgen/dmltestgenerated", dmlgen.WithBuildTags("!ignore", "!ignored"), dmlgen.WithProtobuf(&dmlgen.SerializerConfig{}), dmlgen.WithTablesFromDB(ctx, db, "dmlgen_types", "core_configuration", "customer_entity", "customer_address_entity", "catalog_product_index_eav_decimal_idx", "sales_order_status_state", "view_customer_no_auto_increment", "view_customer_auto_increment", ), dmlgen.WithTableConfig( "customer_entity", &dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, PrivateFields: []string{"password_hash"}, }), dmlgen.WithTableConfig( "customer_address_entity", &dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, }), dmlgen.WithTableConfig("catalog_product_index_eav_decimal_idx", &dmlgen.TableConfig{}), dmlgen.WithTableConfig("sales_order_status_state", &dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, }), dmlgen.WithTableConfig("view_customer_no_auto_increment", &dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, }), dmlgen.WithTableConfig("view_customer_auto_increment", &dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, }), dmlgen.WithTableConfig( "core_configuration", &dmlgen.TableConfig{ Encoders: []string{"easyjson", "protobuf"}, CustomStructTags: []string{ "path", `json:"x_path" xml:"y_path" max_len:"255"`, "scope_id", `json:"scope_id" xml:"scope_id"`, }, StructTags: []string{"json", "max_len"}, ColumnAliases: map[string][]string{ "path": {"storage_location", "config_directory"}, }, UniquifiedColumns: []string{"path"}, }), dmlgen.WithTable("core_configuration", ddl.Columns{ &ddl.Column{Field: "path", Pos: 5, Default: null.MakeString("'general'"), Null: "NO", DataType: "varchar", CharMaxLength: null.MakeInt64(255), ColumnType: "varchar(255)", Comment: "Config Path overwritten"}, }, "overwrite"), dmlgen.WithTableConfig( "dmlgen_types", &dmlgen.TableConfig{ Encoders: []string{"easyjson", "protobuf"}, StructTags: []string{"json", "protobuf", "max_len"}, UniquifiedColumns: []string{"col_varchar_100", "price_a_12_4", "col_int_1", "col_int_2", "has_smallint_5", "col_date_2"}, Comment: "Just another comment.", }), dmlgen.WithForeignKeyRelationships(ctx, db.DB, dmlgen.ForeignKeyOptions{ ExcludeRelationships: []string{"customer_address_entity.parent_id", "customer_entity.entity_id"}, }, ), dmlgen.WithCustomCode("pseudo.MustNewService.Option", ` pseudo.WithTagFakeFunc("dmltestgenerated.CustomerAddressEntity.ParentID", func(maxLen int) interface{} { return nil }), pseudo.WithTagFakeFunc("col_date1", func(maxLen int) interface{} { if ps.Intn(1000)%3 == 0 { return nil } return ps.Dob18() }), pseudo.WithTagFakeFunc("col_date2", func(maxLen int) interface{} { t,_ := ps.Dob18().MarshalText() return t }), pseudo.WithTagFakeFunc("col_decimal101", func(maxLen int) interface{} { return fmt.Sprintf("%.1f", ps.Price()) }), pseudo.WithTagFakeFunc("price_b124", func(maxLen int) interface{} { return fmt.Sprintf("%.4f", ps.Price()) }), pseudo.WithTagFakeFunc("col_decimal123", func(maxLen int) interface{} { return fmt.Sprintf("%.3f", ps.Float64()) }), pseudo.WithTagFakeFunc("col_decimal206", func(maxLen int) interface{} { return fmt.Sprintf("%.6f", ps.Float64()) }), pseudo.WithTagFakeFunc("col_decimal2412", func(maxLen int) interface{} { return fmt.Sprintf("%.12f", ps.Float64()) }), pseudo.WithTagFakeFuncAlias( "col_decimal124", "price_b124", "price_a124", "price_b124", "col_float", "col_decimal206", ), `), ) assert.NoError(t, err) g.ImportPathsTesting = append(g.ImportPathsTesting, "fmt") // only needed for pseudo functional options. g.TestSQLDumpGlobPath = "../testdata/testAll_*_tables.sql" writeFile(t, "dmltestgenerated/output_gen.go", g.GenerateGo) g.Package = "dmltestgeneratedpb" g.PackageSerializer = "./dmltestgeneratedpb" writeFile(t, "dmltestgenerated/output_gen.proto", g.GenerateSerializer) // Generates for all proto files the Go source code. assert.NoError(t, dmlgen.RunProtoc("./dmltestgenerated", &dmlgen.ProtocOptions{ GoOutPath: "./dmltestgenerated/", GoSourceRelative: false, })) assert.NoError(t, dmlgen.GenerateJSON("./dmltestgenerated", "", nil)) } func TestInfoSchemaForeignKeys(t *testing.T) { t.Skip("One time test. Use when needed to regenerate the code") db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) ts, err := dmlgen.NewGenerator("dmltestgenerated", dmlgen.WithTableConfig("KEY_COLUMN_USAGE", &dmlgen.TableConfig{ Encoders: []string{"json", "binary"}, UniquifiedColumns: []string{"TABLE_NAME", "COLUMN_NAME"}, }), dmlgen.WithTablesFromDB(context.Background(), db, "KEY_COLUMN_USAGE"), ) assert.NoError(t, err) writeFile(t, "dmltestgenerated/KEY_COLUMN_USAGE_gen.go", ts.GenerateGo) } func TestWithCustomStructTags(t *testing.T) { t.Run("unbalanced should panic", func(t *testing.T) { defer func() { if r := recover(); r != nil { if err, ok := r.(error); ok { assert.True(t, errors.Fatal.Match(err), "%s", err) } else { t.Errorf("Panic should contain an error but got:\n%+v", r) } } else { t.Error("Expecting a panic but got nothing") } }() tbl, err := dmlgen.NewGenerator("dmltestgenerated", dmlgen.WithTable("table", ddl.Columns{&ddl.Column{Field: "config_id"}}), dmlgen.WithTableConfig("table", &dmlgen.TableConfig{ CustomStructTags: []string{"unbalanced"}, }), ) assert.Nil(t, tbl) assert.NoError(t, err) }) t.Run("table not found", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("tableNOTFOUND", &dmlgen.TableConfig{ CustomStructTags: []string{"column", "db:..."}, }), ) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.NotFound, err) }) } func TestWithStructTags(t *testing.T) { t.Run("table not found", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("tableNOTFOUND", &dmlgen.TableConfig{ StructTags: []string{"unbalanced"}, }), ) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.NotFound, err) }) t.Run("struct tag not supported", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("core_configuration", &dmlgen.TableConfig{ StructTags: []string{"hjson"}, }), dmlgen.WithTable("core_configuration", ddl.Columns{ &ddl.Column{Field: "config_id"}, }), ) assert.Nil(t, tbls) assert.True(t, errors.NotSupported.Match(err), "%+v", err) }) t.Run("al available struct tags", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("core_configuration", &dmlgen.TableConfig{ StructTags: []string{"bson", "db", "env", "json", "toml", "yaml", "xml"}, }), dmlgen.WithTable("core_configuration", ddl.Columns{ &ddl.Column{Field: "config_id"}, }), ) assert.NoError(t, err) have := tbls.Tables["core_configuration"].Table.Columns.ByField("config_id").GoString() assert.Exactly(t, "&ddl.Column{Field: \"config_id\", StructTag: \"bson:\\\"config_id,omitempty\\\" db:\\\"config_id\\\" env:\\\"config_id\\\" json:\\\"config_id,omitempty\\\" toml:\\\"config_id\\\" yaml:\\\"config_id,omitempty\\\" xml:\\\"config_id,omitempty\\\"\", }", have) }) } func TestWithColumnAliases(t *testing.T) { t.Run("table not found", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("tableNOTFOUND", &dmlgen.TableConfig{ ColumnAliases: map[string][]string{"column": {"alias"}}, }), ) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.NotFound, err) }) t.Run("column not found", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("tableNOTFOUND", &dmlgen.TableConfig{ ColumnAliases: map[string][]string{"scope_id": {"scopeID"}}, }), dmlgen.WithTable("core_configuration", ddl.Columns{ &ddl.Column{Field: "config_id"}, }), ) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.NotFound, err) }) } func TestWithUniquifiedColumns(t *testing.T) { t.Run("column not found", func(t *testing.T) { tbls, err := dmlgen.NewGenerator("test", dmlgen.WithTableConfig("core_configuration", &dmlgen.TableConfig{ UniquifiedColumns: []string{"scope_id", "scopeID"}, }), dmlgen.WithTable("core_configuration", ddl.Columns{ &ddl.Column{Field: "config_id"}, }), ) assert.Nil(t, tbls) assert.ErrorIsKind(t, errors.NotFound, err) }) } func TestNewGenerator_NoDB(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "testdata/testAll_*.sql", &dmltest.SQLDumpOptions{DSN: db.DSN()}).Deferred() ctx := context.Background() ts, err := dmlgen.NewGenerator("github.com/corestoreio/pkg/sql/dmlgen/dmltestgenerated2", dmlgen.WithTablesFromDB(ctx, db, "core_configuration", "sales_order_status_state", "view_customer_auto_increment", ), dmlgen.WithTableConfigDefault(dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, FeaturesExclude: dmlgen.FeatureDB | dmlgen.FeatureCollectionUniquifiedGetters, }), dmlgen.WithTableConfig("view_customer_auto_increment", &dmlgen.TableConfig{ StructTags: []string{"yaml"}, FeaturesInclude: dmlgen.FeatureCollectionFilter | dmlgen.FeatureCollectionEach, }), ) assert.NoError(t, err) ts.ImportPathsTesting = append(ts.ImportPathsTesting, "fmt") // only needed for pseudo functional options. ts.TestSQLDumpGlobPath = "../testdata/testAll_*_tables.sql" writeFile(t, "dmltestgenerated2/no_db_gen.go", ts.GenerateGo) } func TestNewGenerator_ReversedForeignKeys(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "testdata/testAll_*.sql", &dmltest.SQLDumpOptions{DSN: db.DSN()}).Deferred() ctx := context.Background() ts, err := dmlgen.NewGenerator("github.com/corestoreio/pkg/sql/dmlgen/dmltestgenerated3", dmlgen.WithTablesFromDB(ctx, db, "store", "store_group", "store_website", "customer_entity", "customer_address_entity", "catalog_category_entity", "sequence_catalog_category", ), dmlgen.WithTableConfigDefault(dmlgen.TableConfig{ Encoders: []string{"json", "protobuf"}, StructTags: []string{"max_len"}, FeaturesInclude: dmlgen.FeatureEntityStruct | dmlgen.FeatureCollectionStruct | dmlgen.FeatureEntityRelationships, }), // Just an empty TableConfig to trigger the default config update for // this table. Hacky for now. dmlgen.WithTableConfig("customer_address_entity", &dmlgen.TableConfig{}), dmlgen.WithTableConfig("customer_entity", &dmlgen.TableConfig{ FieldMapFn: func(dbIdentifier string) (fieldName string) { switch dbIdentifier { case "customer_address_entity": return "Address" } return strs.ToGoCamelCase(dbIdentifier) }, }), dmlgen.WithTableConfig("store", &dmlgen.TableConfig{ CustomStructTags: []string{ "store_website", `json:"-"`, "store_group", `json:"-"`, }, }), dmlgen.WithForeignKeyRelationships(ctx, db.DB, dmlgen.ForeignKeyOptions{ // IncludeRelationShips: []string{"what are the names?"}, ExcludeRelationships: []string{ "store_website.website_id", "customer_entity.website_id", "store.store_id", "customer_entity.store_id", "customer_entity.store_id", "store.store_id", "customer_entity.website_id", "store_website.website_id", "customer_address_entity.parent_id", "customer_entity.entity_id", }, }, ), ) assert.NoError(t, err) ts.ImportPathsTesting = append(ts.ImportPathsTesting, "fmt") // only needed for pseudo functional options. ts.TestSQLDumpGlobPath = "../testdata/testAll_*_tables.sql" writeFile(t, "dmltestgenerated3/rev_fk_gen.go", ts.GenerateGo) } func TestNewGenerator_MToMForeignKeys(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "testdata/testAll_*.sql", &dmltest.SQLDumpOptions{DSN: db.DSN()}).Deferred() ctx := context.Background() ts, err := dmlgen.NewGenerator("github.com/corestoreio/pkg/sql/dmlgen/dmltestgeneratedMToM", dmlgen.WithTablesFromDB(ctx, db, "athlete_team_member", "athlete_team", "athlete", "customer_entity", "customer_address_entity", ), dmlgen.WithTableConfigDefault(dmlgen.TableConfig{ StructTags: []string{"max_len"}, FeaturesInclude: dmlgen.FeatureEntityStruct | dmlgen.FeatureCollectionStruct | dmlgen.FeatureEntityRelationships | dmlgen.FeatureDB, }), // Just an empty TableConfig to trigger the default config update for // this table. Hacky for now. dmlgen.WithTableConfig("athlete_team", &dmlgen.TableConfig{}), dmlgen.WithTableConfig("athlete", &dmlgen.TableConfig{}), dmlgen.WithTableConfig("customer_entity", &dmlgen.TableConfig{ FieldMapFn: func(dbIdentifier string) (fieldName string) { switch dbIdentifier { case "customer_address_entity": return "Address" } return strs.ToGoCamelCase(dbIdentifier) }, }), dmlgen.WithForeignKeyRelationships(ctx, db.DB, dmlgen.ForeignKeyOptions{ // IncludeRelationShips: []string{"what are the names?"}, ExcludeRelationships: []string{ //"athlete.athlete_id", "athlete_team_member.athlete_id", "athlete_team.team_id", "athlete_team_member.team_id", //"athlete_team.team_id", "athlete.athlete_id", "athlete_team_member.*", "*.*", // do not print relations for the relation table itself. "customer_address_entity.parent_id", "customer_entity.entity_id", }, }, ), ) assert.NoError(t, err) ts.ImportPathsTesting = append(ts.ImportPathsTesting, "fmt") // only needed for pseudo functional options. ts.TestSQLDumpGlobPath = "../testdata/testAll_*_tables.sql" writeFile(t, "dmltestgeneratedMToM/fkm2n_gen.go", ts.GenerateGo) } func TestNewGenerator_DB_Partial_SQL_Queries(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "testdata/testAll_*.sql", &dmltest.SQLDumpOptions{DSN: db.DSN()}).Deferred() ctx := context.Background() ts, err := dmlgen.NewGenerator("github.com/corestoreio/pkg/sql/dmlgen/dmltestgenerated4", dmlgen.WithTablesFromDB(ctx, db, "core_configuration", "sales_order_status_state", "view_customer_auto_increment", ), dmlgen.WithTableConfigDefault(dmlgen.TableConfig{ StructTags: []string{"max_len"}, FeaturesInclude: dmlgen.FeatureEntityStruct | dmlgen.FeatureCollectionStruct | dmlgen.FeatureDBTableColumnNames | dmlgen.FeatureDB | dmlgen.FeatureDBMapColumns | dmlgen.FeatureDBSelect | dmlgen.FeatureCollectionEach, }), dmlgen.WithTableConfig("core_configuration", &dmlgen.TableConfig{ FeaturesInclude: dmlgen.FeatureDBInsert | dmlgen.FeatureDBUpsert | dmlgen.FeatureDBDelete | dmlgen.FeatureDBUpdate, }), ) assert.NoError(t, err) ts.ImportPathsTesting = append(ts.ImportPathsTesting, "fmt") // only needed for pseudo functional options. ts.TestSQLDumpGlobPath = "../testdata/testAll_*_tables.sql" writeFile(t, "dmltestgenerated4/db_part_query_gen.go", ts.GenerateGo) } func TestCustomerEntity_Relations(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "testdata/testCust_*.sql", &dmltest.SQLDumpOptions{DSN: db.DSN()}).Deferred() featuresInclude := dmlgen.FeatureDB | dmlgen.FeatureEntityStruct | dmlgen.FeatureCollectionStruct | dmlgen.FeatureDBSelect | dmlgen.FeatureDBUpdate | dmlgen.FeatureDBUpsert | dmlgen.FeatureDBInsert | dmlgen.FeatureDBDelete | dmlgen.FeatureEntityRelationships | dmlgen.FeatureCollectionEach | dmlgen.FeatureCollectionClear ctx := context.Background() g, err := dmlgen.NewGenerator("github.com/corestoreio/pkg/sql/dmlgen/dmltestgenerated5", dmlgen.WithTablesFromDB(ctx, db, "customer_entity", "customer_address_entity", "customer_entity_varchar", "customer_entity_int", ), dmlgen.WithForeignKeyRelationships(ctx, db.DB, dmlgen.ForeignKeyOptions{ ExcludeRelationships: []string{ "customer_address_entity.parent_id", "customer_entity.entity_id", "customer_entity_int.*", "*.*", "customer_entity_varchar.*", "*.*", }, }), dmlgen.WithTableConfig( "customer_entity", &dmlgen.TableConfig{ StructTags: []string{"max_len"}, PrivateFields: []string{"password_hash"}, FeaturesInclude: featuresInclude, }), dmlgen.WithTableConfig( "customer_address_entity", &dmlgen.TableConfig{ StructTags: []string{"max_len"}, FeaturesInclude: featuresInclude, }), dmlgen.WithCustomCode("pseudo.MustNewService.Option", ` pseudo.WithTagFakeFunc("dmltestgenerated.CustomerAddressEntity.ParentID", func(maxLen int) interface{} { return nil }), `), ) assert.NoError(t, err) g.ImportPathsTesting = append(g.ImportPathsTesting, "fmt") // only needed for pseudo functional options. g.TestSQLDumpGlobPath = "../testdata/testCust_*_tables.sql" writeFile(t, "dmltestgenerated5/tables_gen.go", g.GenerateGo) } <|start_filename|>storage/objcache/options_tags_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 objcache_test import ( "encoding/gob" "encoding/json" "io" "os" "testing" "github.com/corestoreio/pkg/storage/objcache" ) var _ objcache.Codecer = (*JSONCodec)(nil) type JSONCodec struct{} func (c JSONCodec) NewEncoder(w io.Writer) objcache.Encoder { return json.NewEncoder(w) } func (c JSONCodec) NewDecoder(r io.Reader) objcache.Decoder { return json.NewDecoder(r) } var _ objcache.Codecer = gobCodec{} type gobCodec struct{} func (c gobCodec) NewEncoder(w io.Writer) objcache.Encoder { return gob.NewEncoder(w) } func (c gobCodec) NewDecoder(r io.Reader) objcache.Decoder { return gob.NewDecoder(r) } func TestWithSimpleSlowCacheMap_Delete(t *testing.T) { t.Parallel() newTestServiceDelete(t, objcache.NewCacheSimpleInmemory) } func lookupRedisEnv(t testing.TB) string { redConURL := os.Getenv("CS_REDIS_TEST") if redConURL == "" { t.Skip(`Skipping live test because environment CS_REDIS_TEST variable not found. export CS_REDIS_TEST="redis://12172.16.31.10:6379/?db=3" `) } return redConURL } <|start_filename|>sql/dml/stmt.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" "github.com/corestoreio/errors" ) type stmtWrapper struct { stmt interface { ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error) QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row ioCloser } } func (sw stmtWrapper) PrepareContext(_ context.Context, _ string) (*sql.Stmt, error) { return nil, errors.NotImplemented.Newf("[dml] A *sql.Stmt cannot prepare anything") } func (sw stmtWrapper) ExecContext(ctx context.Context, _ string, args ...interface{}) (sql.Result, error) { return sw.stmt.ExecContext(ctx, args...) } func (sw stmtWrapper) QueryContext(ctx context.Context, _ string, args ...interface{}) (*sql.Rows, error) { return sw.stmt.QueryContext(ctx, args...) } func (sw stmtWrapper) QueryRowContext(ctx context.Context, _ string, args ...interface{}) *sql.Row { return sw.stmt.QueryRowContext(ctx, args...) } func (sw stmtWrapper) Close() error { return sw.stmt.Close() } // Stmt wraps a *sql.Stmt (a prepared statement) with a specific SQL query. To // create a Stmt call the Prepare function of a specific DML type. Stmt is not // yet safe for concurrent use, despite the underlying *sql.Stmt is. Don't // forget to call Close! type Stmt struct { Stmt *sql.Stmt } // Close closes the statement in the database and frees its resources. func (st *Stmt) Close() error { return st.Stmt.Close() } <|start_filename|>sql/dml/delete_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml_test import ( "context" "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func TestDelete_Prepare(t *testing.T) { t.Run("ToSQL Error", func(t *testing.T) { compareToSQL(t, dml.NewDelete("").Where(dml.Column("a").Int64(1)), errors.Empty, "", "") }) t.Run("Prepare Error", func(t *testing.T) { d := &dml.Delete{ BuilderBase: dml.BuilderBase{ Table: dml.MakeIdentifier("table"), }, } ddbr := d.WithDBR(dbMock{ error: errors.AlreadyClosed.Newf("Who closed myself?"), }) d.Where(dml.Column("a").Int(1)) stmt, err := ddbr.Prepare(context.TODO()) assert.Nil(t, stmt) assert.ErrorIsKind(t, errors.AlreadyClosed, err) }) t.Run("ExecArgs One Row", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("DELETE FROM `customer_entity` WHERE (`email` = ?) AND (`group_id` = ?)")) prep.ExpectExec().WithArgs("a@b.c", 33).WillReturnResult(sqlmock.NewResult(0, 1)) prep.ExpectExec().WithArgs("x@y.z", 44).WillReturnResult(sqlmock.NewResult(0, 2)) stmt, err := dbc.WithQueryBuilder(dml.NewDelete("customer_entity"). Where(dml.Column("email").PlaceHolder(), dml.Column("group_id").PlaceHolder())). Prepare(context.TODO()) assert.NoError(t, err, "failed creating a prepared statement") defer dmltest.Close(t, stmt) tests := []struct { email string groupID int affRows int64 }{ {"a@b.c", 33, 1}, {"x@y.z", 44, 2}, } for i, test := range tests { res, err := stmt.ExecContext(context.TODO(), test.email, test.groupID) if err != nil { t.Fatalf("Index %d => %+v", i, err) } ra, err := res.RowsAffected() if err != nil { t.Fatalf("Result index %d with error: %s", i, err) } assert.Exactly(t, test.affRows, ra, "Index %d has different RowsAffected", i) stmt.Reset() } }) t.Run("ExecRecord One Row", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("DELETE FROM `dml_person` WHERE (`name` = ?) AND (`email` = ?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>").WillReturnResult(sqlmock.NewResult(0, 4)) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>").WillReturnResult(sqlmock.NewResult(0, 5)) stmt, err := dbc.WithQueryBuilder(dml.NewDelete("dml_person"). Where(dml.Column("name").PlaceHolder(), dml.Column("email").PlaceHolder())). Prepare(context.TODO()) assert.NoError(t, err, "failed creating a prepared statement") defer func() { assert.NoError(t, stmt.Close(), "Close on a prepared statement") }() tests := []struct { name string email string insertID int64 }{ {"<NAME>", "<EMAIL>", 4}, {"<NAME>", "<EMAIL>", 5}, } for i, test := range tests { p := &dmlPerson{ Name: test.name, Email: null.MakeString(test.email), } res, err := stmt.ExecContext(context.TODO(), dml.Qualify("", p)) if err != nil { t.Fatalf("Index %d => %+v", i, err) } lid, err := res.RowsAffected() if err != nil { t.Fatalf("Result index %d with error: %s", i, err) } assert.Exactly(t, test.insertID, lid, "Index %d has different RowsAffected", i) } }) t.Run("ExecContext", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("DELETE FROM `dml_person` WHERE (`name` = ?) AND (`email` = ?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>").WillReturnResult(sqlmock.NewResult(0, 4)) stmt, err := dbc.WithQueryBuilder(dml.NewDelete("dml_person"). Where(dml.Column("name").PlaceHolder(), dml.Column("email").PlaceHolder())). Prepare(context.TODO()) assert.NoError(t, err, "failed creating a prepared statement") defer func() { assert.NoError(t, stmt.Close(), "Close on a prepared statement") }() res, err := stmt.ExecContext(context.TODO(), "<NAME>", "<EMAIL>") assert.NoError(t, err, "failed to execute ExecContext") lid, err := res.RowsAffected() if err != nil { t.Fatal(err) } assert.Exactly(t, int64(4), lid, "Different RowsAffected") }) } func TestDelete_Join(t *testing.T) { del1 := dml.NewDelete("customer_entity").Alias("ce"). FromTables("customer_address", "customer_company"). Join( dml.MakeIdentifier("customer_company").Alias("cc"), dml.Columns("ce.entity_id", "cc.customer_id"), ). RightJoin( dml.MakeIdentifier("customer_address").Alias("ca"), dml.Columns("ce.entity_id", "ca.parent_id"), ). Where( dml.Column("ce.created_at").Less().PlaceHolder(), ) t.Run("JOIN USING with alias", func(t *testing.T) { compareToSQL(t, del1, errors.NoKind, "DELETE `ce`,`customer_address`,`customer_company` FROM `customer_entity` AS `ce` INNER JOIN `customer_company` AS `cc` USING (`ce.entity_id`,`cc.customer_id`) RIGHT JOIN `customer_address` AS `ca` USING (`ce.entity_id`,`ca.parent_id`) WHERE (`ce`.`created_at` < ?)", "", ) }) t.Run("JOIN USING with alias WithDBR", func(t *testing.T) { compareToSQL(t, del1.WithDBR(dbMock{}).TestWithArgs(now()), errors.NoKind, "DELETE `ce`,`customer_address`,`customer_company` FROM `customer_entity` AS `ce` INNER JOIN `customer_company` AS `cc` USING (`ce.entity_id`,`cc.customer_id`) RIGHT JOIN `customer_address` AS `ca` USING (`ce.entity_id`,`ca.parent_id`) WHERE (`ce`.`created_at` < ?)", "DELETE `ce`,`customer_address`,`customer_company` FROM `customer_entity` AS `ce` INNER JOIN `customer_company` AS `cc` USING (`ce.entity_id`,`cc.customer_id`) RIGHT JOIN `customer_address` AS `ca` USING (`ce.entity_id`,`ca.parent_id`) WHERE (`ce`.`created_at` < '2006-01-02 15:04:05')", now(), ) }) t.Run("LeftJoin USING without alias", func(t *testing.T) { del := dml.NewDelete("customer_entity"). FromTables("customer_address"). LeftJoin( dml.MakeIdentifier("customer_address").Alias("ca"), dml.Columns("ce.entity_id", "ca.parent_id"), ). Where( dml.Column("ce.created_at").Less().PlaceHolder(), ) compareToSQL(t, del, errors.NoKind, "DELETE `customer_entity`,`customer_address` FROM `customer_entity` LEFT JOIN `customer_address` AS `ca` USING (`ce.entity_id`,`ca.parent_id`) WHERE (`ce`.`created_at` < ?)", "", ) }) t.Run("OuterJoin USING without alias", func(t *testing.T) { del := dml.NewDelete("customer_entity"). FromTables("customer_address"). OuterJoin( dml.MakeIdentifier("customer_address").Alias("ca"), dml.Columns("ce.entity_id", "ca.parent_id"), ) compareToSQL(t, del, errors.NoKind, "DELETE `customer_entity`,`customer_address` FROM `customer_entity` OUTER JOIN `customer_address` AS `ca` USING (`ce.entity_id`,`ca.parent_id`)", "", ) }) t.Run("JOIN USING without FromTables", func(t *testing.T) { del := dml.NewDelete("customer_entity"). CrossJoin( dml.MakeIdentifier("customer_address").Alias("ca"), dml.Column("ce.entity_id").Equal().Column("ca.parent_id"), ). Where( dml.Column("ce.created_at").Less().PlaceHolder(), ) compareToSQL(t, del, errors.NoKind, "DELETE FROM `customer_entity` CROSS JOIN `customer_address` AS `ca` ON (`ce`.`entity_id` = `ca`.`parent_id`) WHERE (`ce`.`created_at` < ?)", "", ) }) } func TestDelete_Returning(t *testing.T) { t.Run("not allowed", func(t *testing.T) { del := dml.NewDelete("customer_entity"). FromTables("customer_address"). OuterJoin( dml.MakeIdentifier("customer_address").Alias("ca"), dml.Columns("ce.entity_id", "ca.parent_id"), ) del.Returning = dml.NewSelect() compareToSQL(t, del, errors.NotAllowed, "", "", ) }) t.Run("return delete rows", func(t *testing.T) { del := dml.NewDelete("customer_entity"). Where( dml.Column("ce.entity_id").GreaterOrEqual().PlaceHolder(), ) del.Returning = dml.NewSelect("entity_id", "created_at").From("customer_entity") compareToSQL(t, del, errors.NoKind, "DELETE FROM `customer_entity` WHERE (`ce`.`entity_id` >= ?) RETURNING SELECT `entity_id`, `created_at` FROM `customer_entity`", "", ) }) } func TestDelete_Clone(t *testing.T) { dbc, dbMock := dmltest.MockDB(t, dml.WithLogger(log.BlackHole{}, func() string { return "uniqueID" })) defer dmltest.MockClose(t, dbc, dbMock) t.Run("nil", func(t *testing.T) { var d *dml.Delete d2 := d.Clone() assert.Nil(t, d) assert.Nil(t, d2) }) t.Run("non-nil", func(t *testing.T) { d := dml.NewDelete("dml_people").Alias("dmlPpl").FromTables("a1", "b2"). Where( dml.Column("id").PlaceHolder(), ).OrderBy("id") d2 := d.Clone() notEqualPointers(t, d, d2) notEqualPointers(t, d, d2) notEqualPointers(t, d.BuilderConditional.Wheres, d2.BuilderConditional.Wheres) notEqualPointers(t, d.BuilderConditional.OrderBys, d2.BuilderConditional.OrderBys) notEqualPointers(t, d.MultiTables, d2.MultiTables) // assert.Exactly(t, d.DB, d2.DB) }) } <|start_filename|>sql/dml/with_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "database/sql" "testing" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/errors" ) func TestWith_Placeholder(t *testing.T) { t.Run("placeholder DBR", func(t *testing.T) { cte := NewWith( WithCTE{ Name: "cte", Columns: []string{"n"}, Union: NewUnion( NewSelect("a").AddColumnsAliases("d", "b").From("tableAD").Where(Column("b").PlaceHolder()), NewSelect("a", "b").From("tableAB").Where(Column("b").Like().NamedArg("nArg2")), ).All(), }, ). Recursive(). Select(NewSelect().Star().From("cte").Where(Column("a").GreaterOrEqual().PlaceHolder())) compareToSQL(t, cte.WithDBR(dbMock{}).TestWithArgs(sql.Named("nArg2", "hello%"), null.MakeString("arg1"), 2.7182), errors.NoKind, "WITH RECURSIVE `cte` (`n`) AS ((SELECT `a`, `d` AS `b` FROM `tableAD` WHERE (`b` = ?))\nUNION ALL\n(SELECT `a`, `b` FROM `tableAB` WHERE (`b` LIKE ?)))\nSELECT * FROM `cte` WHERE (`a` >= ?)", "WITH RECURSIVE `cte` (`n`) AS ((SELECT `a`, `d` AS `b` FROM `tableAD` WHERE (`b` = 'arg1'))\nUNION ALL\n(SELECT `a`, `b` FROM `tableAB` WHERE (`b` LIKE 'hello%')))\nSELECT * FROM `cte` WHERE (`a` >= 2.7182)", "arg1", "hello%", 2.7182, ) }) } func TestWith_ToSQL(t *testing.T) { t.Run("Find best and worst month With cache", func(t *testing.T) { /* WITH sales_by_month(month, total) AS -- first CTE: one row per month, with amount sold on all days of month (SELECT Month(day_of_sale),Sum(amount) FROM sales_days WHERE Year(day_of_sale) = 2015 GROUP BY Month(day_of_sale)), best_month(month, total, award) AS -- second CTE: best month (SELECT month, total, "best" FROM sales_by_month WHERE total = (SELECT Max(total) FROM sales_by_month)), worst_month(month, total, award) AS -- 3rd CTE: worst month (SELECT month, total, "worst" FROM sales_by_month WHERE total = (SELECT Min(total) FROM sales_by_month)) -- Now show best and worst: SELECT * FROM best_month UNION ALL SELECT * FROM worst_month; */ cte := NewWith( WithCTE{ Name: "sales_by_month", Columns: []string{"month", "total"}, Select: NewSelect().Unsafe().AddColumns("Month(day_of_sale)", "Sum(amount)"). From("sales_days"). Where(Expr("Year(day_of_sale) = ?").Int(2015)). GroupBy("Month(day_of_sale))"), }, WithCTE{ Name: "best_month", Columns: []string{"month", "total", "award"}, Select: NewSelect().AddColumns("month", "total").AddColumnsConditions(Expr(`"best"`)).From("sales_by_month"). Where( Column("total").Equal().Sub(NewSelect().AddColumnsConditions(Expr("Max(total)")).From("sales_by_month"))), }, WithCTE{ Name: "worst_month", Columns: []string{"month", "total", "award"}, Select: NewSelect().AddColumns("month", "total").AddColumnsConditions(Expr(`"worst"`)).From("sales_by_month"). Where( Column("total").Equal().Sub(NewSelect().AddColumnsConditions(Expr("Min(total)")).From("sales_by_month"))), }, ).Union(NewUnion( NewSelect().Star().From("best_month"), NewSelect().Star().From("worst_month"), ).All()) compareToSQL(t, cte, errors.NoKind, "WITH `sales_by_month` (`month`,`total`) AS (SELECT Month(day_of_sale), Sum(amount) FROM `sales_days` WHERE (Year(day_of_sale) = 2015) GROUP BY Month(day_of_sale))),\n`best_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"best\" FROM `sales_by_month` WHERE (`total` = (SELECT Max(total) FROM `sales_by_month`))),\n`worst_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"worst\" FROM `sales_by_month` WHERE (`total` = (SELECT Min(total) FROM `sales_by_month`)))\n(SELECT * FROM `best_month`)\nUNION ALL\n(SELECT * FROM `worst_month`)", "WITH `sales_by_month` (`month`,`total`) AS (SELECT Month(day_of_sale), Sum(amount) FROM `sales_days` WHERE (Year(day_of_sale) = 2015) GROUP BY Month(day_of_sale))),\n`best_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"best\" FROM `sales_by_month` WHERE (`total` = (SELECT Max(total) FROM `sales_by_month`))),\n`worst_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"worst\" FROM `sales_by_month` WHERE (`total` = (SELECT Min(total) FROM `sales_by_month`)))\n(SELECT * FROM `best_month`)\nUNION ALL\n(SELECT * FROM `worst_month`)", ) // call it twice compareToSQL(t, cte, errors.NoKind, "WITH `sales_by_month` (`month`,`total`) AS (SELECT Month(day_of_sale), Sum(amount) FROM `sales_days` WHERE (Year(day_of_sale) = 2015) GROUP BY Month(day_of_sale))),\n`best_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"best\" FROM `sales_by_month` WHERE (`total` = (SELECT Max(total) FROM `sales_by_month`))),\n`worst_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"worst\" FROM `sales_by_month` WHERE (`total` = (SELECT Min(total) FROM `sales_by_month`)))\n(SELECT * FROM `best_month`)\nUNION ALL\n(SELECT * FROM `worst_month`)", "WITH `sales_by_month` (`month`,`total`) AS (SELECT Month(day_of_sale), Sum(amount) FROM `sales_days` WHERE (Year(day_of_sale) = 2015) GROUP BY Month(day_of_sale))),\n`best_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"best\" FROM `sales_by_month` WHERE (`total` = (SELECT Max(total) FROM `sales_by_month`))),\n`worst_month` (`month`,`total`,`award`) AS (SELECT `month`, `total`, \"worst\" FROM `sales_by_month` WHERE (`total` = (SELECT Min(total) FROM `sales_by_month`)))\n(SELECT * FROM `best_month`)\nUNION ALL\n(SELECT * FROM `worst_month`)", ) }) } <|start_filename|>sql/dml/select_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "context" "database/sql" "fmt" "testing" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func TestSelect_BasicToSQL(t *testing.T) { t.Run("no table no args", func(t *testing.T) { sel := NewSelect().AddColumnsConditions(Expr("1").Alias("n")).AddColumnsAliases("abc", "str") compareToSQL2(t, sel, errors.NoKind, "SELECT 1 AS `n`, `abc` AS `str`", ) }) t.Run("no table with args", func(t *testing.T) { sel := NewSelect(). AddColumnsConditions( Expr("?").Alias("n").Int64(1), Expr("CAST(? AS CHAR(20))").Alias("str").Str("a'bc"), ) compareToSQL2(t, sel, errors.NoKind, "SELECT 1 AS `n`, CAST('a\\'bc' AS CHAR(20)) AS `str`", ) }) t.Run("no table with placeholders Args as Records", func(t *testing.T) { p := &dmlPerson{ Name: "a'bc", } sel := NewSelect(). AddColumnsConditions( Expr("?").Alias("n").Int64(1), Expr("CAST(:name AS CHAR(20))").Alias("str"), ).WithDBR(dbMock{}).TestWithArgs(Qualify("", p)) compareToSQL(t, sel, errors.NoKind, "SELECT 1 AS `n`, CAST(? AS CHAR(20)) AS `str`", "SELECT 1 AS `n`, CAST('a\\'bc' AS CHAR(20)) AS `str`", "a'bc", ) }) t.Run("two cols, one table, one condition", func(t *testing.T) { sel := NewSelect("a", "b").From("c").Where(Column("id").Equal().Int(1)) compareToSQL2(t, sel, errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` = 1)", ) }) t.Run("place holders", func(t *testing.T) { sel := NewSelect("a", "b").From("c").Where( Column("id").Greater().PlaceHolder(), Column("email").Like().NamedArg("ema1l"), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`id` > ?) AND (`email` LIKE ?)", ) assert.Exactly(t, []string{"id", ":ema1l"}, sel.qualifiedColumns) }) t.Run("column right expression without arguments", func(t *testing.T) { compareToSQL2(t, NewSelect("sku", "name").From("products").Where( Column("id").NotBetween().Ints(4, 7), Column("name").NotEqual().Expr("CONCAT('Canon','E0S 5D Mark III')"), ), errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` NOT BETWEEN 4 AND 7) AND (`name` != CONCAT('Canon','E0S 5D Mark III'))", ) }) t.Run("column right expression with one argument", func(t *testing.T) { compareToSQL2(t, NewSelect("sku", "name").From("products").Where( Column("id").NotBetween().Ints(4, 7), Column("name").Like().Expr("CONCAT('Canon',?,'E0S 7D Mark VI')").Str("Camera"), ), errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` NOT BETWEEN 4 AND 7) AND (`name` LIKE CONCAT('Canon','Camera','E0S 7D Mark VI'))", ) }) t.Run("column right expression with slice argument (wrong SQL code)", func(t *testing.T) { sel := NewSelect("sku", "name").From("products").Where( Column("id").NotBetween().Ints(4, 7), Column("name").NotLike().Expr("CONCAT('Canon',?,'E0S 8D Mark VII')").Strs("Camera", "Photo", "Flash"), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` NOT BETWEEN 4 AND 7) AND (`name` NOT LIKE CONCAT('Canon',('Camera','Photo','Flash'),'E0S 8D Mark VII'))", ) }) t.Run("column right expression with slice argument (correct SQL code)", func(t *testing.T) { sel := NewSelect("sku", "name").From("products").Where( Column("id").NotBetween().Ints(4, 7), Column("name").NotLike().Expr("CONCAT('Canon',?,?,?,'E0S 8D Mark VII')").Str("Camera").Str("Photo").Str("Flash"), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` NOT BETWEEN 4 AND 7) AND (`name` NOT LIKE CONCAT('Canon','Camera','Photo','Flash','E0S 8D Mark VII'))", ) }) t.Run("column left and right expression without arguments", func(t *testing.T) { sel := NewSelect("sku", "name").From("products").Where( Column("id").NotBetween().Ints(4, 7), Column("name").NotEqual().Expr("CONCAT('Canon','E0S 5D Mark III')"), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` NOT BETWEEN 4 AND 7) AND (`name` != CONCAT('Canon','E0S 5D Mark III'))", ) }) t.Run("IN with expand", func(t *testing.T) { sel := NewSelect("sku", "name").From("products").Where( Column("id").In().PlaceHolder(), Column("name").NotIn().PlaceHolder(), ) selA := sel.WithDBR(dbMock{}).ExpandPlaceHolders() compareToSQL(t, selA.TestWithArgs([]int{3, 4, 5}, []null.String{null.MakeString("A1"), {}, null.MakeString("A2")}), errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` IN (?,?,?)) AND (`name` NOT IN (?,?,?))", "", int64(3), int64(4), int64(5), "A1", nil, "A2", ) compareToSQL(t, selA.TestWithArgs([]int{3, 4, 5, 6, 7}, []null.String{{}, null.MakeString("A2")}), errors.NoKind, "SELECT `sku`, `name` FROM `products` WHERE (`id` IN (?,?,?,?,?)) AND (`name` NOT IN (?,?))", "", int64(3), int64(4), int64(5), int64(6), int64(7), nil, "A2", ) }) t.Run("IN with PlaceHolders", func(t *testing.T) { sel := NewSelect("email").From("tableX").Where(Column("id").In().PlaceHolders(2)) compareToSQL2(t, sel, errors.NoKind, "SELECT `email` FROM `tableX` WHERE (`id` IN (?,?))", ) sel = NewSelect("email").From("tableX").Where(Column("id").In().PlaceHolders(1)) compareToSQL2(t, sel, errors.NoKind, "SELECT `email` FROM `tableX` WHERE (`id` IN (?))", ) sel = NewSelect("email").From("tableX").Where(Column("id").In().PlaceHolders(0)) compareToSQL2(t, sel, errors.NoKind, "SELECT `email` FROM `tableX` WHERE (`id` IN ())", ) sel = NewSelect("email").From("tableX").Where(Column("id").In().PlaceHolders(-10)) compareToSQL2(t, sel, errors.NoKind, "SELECT `email` FROM `tableX` WHERE (`id` IN ())", ) }) } func TestSelect_FullToSQL(t *testing.T) { sel := NewSelect("a", "b"). Distinct(). FromAlias("c", "cc"). Where( ParenthesisOpen(), Column("d").Int(1), Column("e").Str("wat").Or(), ParenthesisClose(), Column("f").Int(2), Column("g").Int(3), Column("h").In().Int64s(4, 5, 6), ). GroupBy("ab"). Having( ParenthesisOpen(), Column("m").Int(33), Column("n").Str("wh3r3").Or(), ParenthesisClose(), Expr("j = k"), ). OrderBy("l"). Limit(8, 7) compareToSQL2(t, sel, errors.NoKind, "SELECT DISTINCT `a`, `b` FROM `c` AS `cc` WHERE ((`d` = 1) OR (`e` = 'wat')) AND (`f` = 2) AND (`g` = 3) AND (`h` IN (4,5,6)) GROUP BY `ab` HAVING ((`m` = 33) OR (`n` = 'wh3r3')) AND (j = k) ORDER BY `l` LIMIT 8,7", ) } func TestSelect_ComplexExpr(t *testing.T) { t.Run("two args in one condition", func(t *testing.T) { sel := NewSelect("a", "b", "z", "y", "x").From("c"). Distinct(). Where(Expr("`d` = ? OR `e` = ?").Int64(1).Str("wat")). Where( Column("g").Int(3), Column("h").In().Int64s(1, 2, 3), ). GroupBy("ab").GroupBy("ii").GroupBy("iii"). Having(Expr("j = k"), Column("jj").Int64(1)). Having(Column("jjj").Int64(2)). OrderBy("l1").OrderBy("l2").OrderBy("l3"). Limit(8, 7) compareToSQL2(t, sel, errors.NoKind, "SELECT DISTINCT `a`, `b`, `z`, `y`, `x` FROM `c` WHERE (`d` = 1 OR `e` = 'wat') AND (`g` = 3) AND (`h` IN (1,2,3)) GROUP BY `ab`, `ii`, `iii` HAVING (j = k) AND (`jj` = 1) AND (`jjj` = 2) ORDER BY `l1`, `l2`, `l3` LIMIT 8,7", // int64(1), "wat", int64(3), int64(1), int64(2), int64(3), int64(1), int64(2), ) }) } func TestSelect_OrderByRandom_Strings(t *testing.T) { t.Run("simple select", func(t *testing.T) { compareToSQL2(t, NewSelect("id", "first_name", "last_name"). From("dml_fake_person"). OrderByRandom("id", 25), errors.NoKind, "SELECT `id`, `first_name`, `last_name` FROM `dml_fake_person` JOIN (SELECT `id` FROM `dml_fake_person` WHERE (RAND() < (SELECT ((25 / COUNT(*)) * 10) FROM `dml_fake_person`)) ORDER BY RAND() LIMIT 0,25) AS `randdml_fake_person` USING (`id`)", ) }) t.Run("WHERE condition", func(t *testing.T) { compareToSQL2(t, NewSelect("id", "first_name", "last_name"). From("dml_fake_person"). Where(Column("id").LessOrEqual().Int(30)). OrderByRandom("id", 25), errors.NoKind, "SELECT `id`, `first_name`, `last_name` FROM `dml_fake_person` JOIN (SELECT `id` FROM `dml_fake_person` WHERE (RAND() < (SELECT ((25 / COUNT(*)) * 10) FROM `dml_fake_person` WHERE (`id` <= 30))) AND (`id` <= 30) ORDER BY RAND() LIMIT 0,25) AS `randdml_fake_person` USING (`id`) WHERE (`id` <= 30)", ) }) t.Run("one join", func(t *testing.T) { sqlObj := NewSelect("p1.*", "p2.*").FromAlias("dml_people", "p1"). Distinct().StraightJoin().SQLNoCache(). Join( MakeIdentifier("dml_people").Alias("p2"), Expr("`p2`.`id` = `p1`.`id`"), Column("p1.id").Int(142), ).OrderByRandom("id", 100) compareToSQL2(t, sqlObj, errors.NoKind, "SELECT DISTINCT STRAIGHT_JOIN SQL_NO_CACHE `p1`.*, `p2`.* FROM `dml_people` AS `p1` INNER JOIN `dml_people` AS `p2` ON (`p2`.`id` = `p1`.`id`) AND (`p1`.`id` = 142) JOIN (SELECT `id` FROM `dml_people` WHERE (RAND() < (SELECT ((100 / COUNT(*)) * 10) FROM `dml_people`)) ORDER BY RAND() LIMIT 0,100) AS `randdml_people` USING (`id`)", ) }) } func TestSelect_OrderByRandom_Integration(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) t.Run("Load IDs", func(t *testing.T) { ids, err := s.WithQueryBuilder( NewSelect("id").From("dml_people").OrderByRandom("id", 10), ).LoadUint64s(context.TODO(), nil) assert.NoError(t, err) assert.Len(t, ids, 2) }) // TODO test this when in a column is one row NULL ... then it should fail scanning } func TestSelect_Paginate(t *testing.T) { t.Run("asc", func(t *testing.T) { compareToSQL2(t, NewSelect("a", "b"). From("c"). Where(Column("d").Int(1)). Paginate(3, 30). OrderBy("id"), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`d` = 1) ORDER BY `id` LIMIT 60,30", ) }) t.Run("desc", func(t *testing.T) { compareToSQL2(t, NewSelect("a", "b"). From("c"). Where(Column("d").Int(1)). Paginate(1, 20). OrderByDesc("id"), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`d` = 1) ORDER BY `id` DESC LIMIT 0,20", ) }) } func TestSelect_WithoutWhere(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c"), errors.NoKind, "SELECT `a`, `b` FROM `c`", ) } func TestSelect_MultiHavingSQL(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c"). Where(Column("p").Int(1)). GroupBy("z").Having(Column("z`z").Int(2), Column("y").Int(3)), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`p` = 1) GROUP BY `z` HAVING (`zz` = 2) AND (`y` = 3)", ) } func TestSelect_MultiOrderSQL(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c").OrderBy("name").OrderByDesc("id"), errors.NoKind, "SELECT `a`, `b` FROM `c` ORDER BY `name`, `id` DESC", ) } func TestSelect_OrderByDeactivated(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c").OrderBy("name").OrderByDeactivated(), errors.NoKind, "SELECT `a`, `b` FROM `c` ORDER BY NULL", ) } func TestSelect_ConditionColumn(t *testing.T) { // TODO rewrite test to use every type which implements interface Argument and every operator runner := func(wf *Condition, wantSQL string) func(*testing.T) { return func(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c").Where(wf), errors.NoKind, wantSQL, ) } } t.Run("single int64", runner( Column("d").Int64(33), "SELECT `a`, `b` FROM `c` WHERE (`d` = 33)", )) t.Run("IN int64", runner( Column("d").In().Int64s(33, 44), "SELECT `a`, `b` FROM `c` WHERE (`d` IN (33,44))", )) t.Run("single float64", runner( Column("d").Float64(33.33), "SELECT `a`, `b` FROM `c` WHERE (`d` = 33.33)", )) t.Run("IN float64", runner( Column("d").In().Float64s(33.44, 44.33), "SELECT `a`, `b` FROM `c` WHERE (`d` IN (33.44,44.33))", )) t.Run("NOT IN float64", runner( Column("d").NotIn().Float64s(33.1, 44.2), "SELECT `a`, `b` FROM `c` WHERE (`d` NOT IN (33.1,44.2))", )) t.Run("single int", runner( Column("d").Equal().Int(33), "SELECT `a`, `b` FROM `c` WHERE (`d` = 33)", )) t.Run("IN int", runner( Column("d").In().Ints(33, 44), "SELECT `a`, `b` FROM `c` WHERE (`d` IN (33,44))", )) t.Run("single string", runner( Column("d").Str("w"), "SELECT `a`, `b` FROM `c` WHERE (`d` = 'w')", )) t.Run("IN string", runner( Column("d").In().Strs("x", "y"), "SELECT `a`, `b` FROM `c` WHERE (`d` IN ('x','y'))", )) t.Run("BETWEEN int64", runner( Column("d").Between().Int64s(5, 6), "SELECT `a`, `b` FROM `c` WHERE (`d` BETWEEN 5 AND 6)", )) t.Run("NOT BETWEEN int64", runner( Column("d").NotBetween().Int64s(5, 6), "SELECT `a`, `b` FROM `c` WHERE (`d` NOT BETWEEN 5 AND 6)", )) t.Run("LIKE string", runner( Column("d").Like().Str("x%"), "SELECT `a`, `b` FROM `c` WHERE (`d` LIKE 'x%')", )) t.Run("NOT LIKE string", runner( Column("d").NotLike().Str("x%"), "SELECT `a`, `b` FROM `c` WHERE (`d` NOT LIKE 'x%')", )) t.Run("Less float64", runner( Column("d").Less().Float64(5.1), "SELECT `a`, `b` FROM `c` WHERE (`d` < 5.1)", )) t.Run("Greater float64", runner( Column("d").Greater().Float64(5.1), "SELECT `a`, `b` FROM `c` WHERE (`d` > 5.1)", )) t.Run("LessOrEqual float64", runner( Column("d").LessOrEqual().Float64(5.1), "SELECT `a`, `b` FROM `c` WHERE (`d` <= 5.1)", )) t.Run("GreaterOrEqual float64", runner( Column("d").GreaterOrEqual().Float64(5.1), "SELECT `a`, `b` FROM `c` WHERE (`d` >= 5.1)", )) } func TestSelect_Null(t *testing.T) { t.Run("col is null", func(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c").Where(Column("r").Null()), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`r` IS NULL)", ) }) t.Run("col is not null", func(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c").Where(Column("r").NotNull()), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`r` IS NOT NULL)", ) }) t.Run("complex", func(t *testing.T) { compareToSQL2(t, NewSelect("a", "b").From("c"). Where( Column("r").Null(), Column("d").Int(3), Column("ab").Null(), Column("w").NotNull(), ), errors.NoKind, "SELECT `a`, `b` FROM `c` WHERE (`r` IS NULL) AND (`d` = 3) AND (`ab` IS NULL) AND (`w` IS NOT NULL)", ) }) } func TestSelect_WhereNULL(t *testing.T) { t.Run("one nil", func(t *testing.T) { compareToSQL2(t, NewSelect("a").From("b").Where(Column("a")), errors.NoKind, "SELECT `a` FROM `b` WHERE (`a` IS NULL)", ) }) t.Run("no values", func(t *testing.T) { compareToSQL2(t, NewSelect("a").From("b").Where(Column("a").PlaceHolder()), errors.NoKind, "SELECT `a` FROM `b` WHERE (`a` = ?)", ) }) t.Run("empty Ints trigger invalid SQL", func(t *testing.T) { var iVal []int compareToSQL2(t, NewSelect("a").From("b").Where(Column("a").In().Ints(iVal...)), errors.NoKind, "SELECT `a` FROM `b` WHERE (`a` IN ())", ) }) t.Run("Map nil arg", func(t *testing.T) { s := NewSelect("a").From("b"). Where( Column("a"), Column("b").Bool(false), Column("c").Null(), Column("d").NotNull(), ) compareToSQL2(t, s, errors.NoKind, "SELECT `a` FROM `b` WHERE (`a` IS NULL) AND (`b` = 0) AND (`c` IS NULL) AND (`d` IS NOT NULL)", ) }) } func TestSelect_Varieties(t *testing.T) { // This would be incorrect SQL! compareToSQL2(t, NewSelect("id, name, email").From("users"), errors.NoKind, "SELECT `id, name, email` FROM `users`", ) // With unsafe it still gets quoted because unsafe has been applied after // the column names has been added. compareToSQL2(t, NewSelect("id, name, email").Unsafe().From("users"), errors.NoKind, "SELECT `id, name, email` FROM `users`", ) // correct way to handle it compareToSQL2(t, NewSelect("id", "name", "email").From("users"), errors.NoKind, "SELECT `id`, `name`, `email` FROM `users`", ) } func TestSelect_Load_Slice_Scanner(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) var people dmlPersons count, err := s.WithQueryBuilder(NewSelect("id", "name", "email").From("dml_people").OrderBy("id")).Load(context.TODO(), &people) assert.NoError(t, err) assert.Exactly(t, uint64(2), count) assert.Exactly(t, len(people.Data), 2) if len(people.Data) == 2 { // Make sure that the Ids are isSet. It'ab possible (maybe?) that different DBs isSet ids differently so // don't assume they're 1 and 2. assert.True(t, people.Data[0].ID > 0) assert.True(t, people.Data[1].ID > people.Data[0].ID) assert.Exactly(t, "<NAME>", people.Data[0].Name) assert.True(t, people.Data[0].Email.Valid) assert.Exactly(t, "<EMAIL>", people.Data[0].Email.Data) assert.Exactly(t, "Dmitri", people.Data[1].Name) assert.True(t, people.Data[1].Email.Valid) assert.Exactly(t, "<EMAIL>", people.Data[1].Email.Data) } } func TestSelect_Load_Rows(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) t.Run("found", func(t *testing.T) { var person dmlPerson _, err := s.WithQueryBuilder(NewSelect("id", "name", "email").From("dml_people"). Where(Column("email").Str("<EMAIL>"))).Load(context.TODO(), &person) assert.NoError(t, err) assert.True(t, person.ID > 0) assert.Exactly(t, "<NAME>", person.Name) assert.True(t, person.Email.Valid) assert.Exactly(t, "<EMAIL>", person.Email.Data) }) t.Run("not found", func(t *testing.T) { var person2 dmlPerson count, err := s.WithQueryBuilder(NewSelect("id", "name", "email").From("dml_people"). Where(Column("email").Str("<EMAIL>"))).Load(context.TODO(), &person2) assert.NoError(t, err) assert.Exactly(t, dmlPerson{}, person2) assert.Empty(t, count, "Should have no rows loaded") }) } func TestSelectBySQL_Load_Slice(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) t.Run("single slice item", func(t *testing.T) { var people dmlPersons count, err := s.WithQueryBuilder(QuerySQL("SELECT `name` FROM `dml_people` WHERE `email` = ?")). Load(context.TODO(), &people, "<EMAIL>") assert.NoError(t, err) assert.Exactly(t, uint64(1), count) if len(people.Data) == 1 { assert.Exactly(t, "<NAME>", people.Data[0].Name) assert.Exactly(t, uint64(0), people.Data[0].ID) // not set assert.Exactly(t, false, people.Data[0].Email.Valid) // not set assert.Exactly(t, "", people.Data[0].Email.Data) // not set } }) t.Run("IN Clause (multiple args,interpolate)", func(t *testing.T) { ids, err := s.WithQueryBuilder(NewSelect("id").From("dml_people"). Where(Column("id").In().Int64s(1, 2, 3))).LoadInt64s(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []int64{1, 2}, ids) }) t.Run("IN Clause (single args,interpolate)", func(t *testing.T) { ids, err := s.WithQueryBuilder(NewSelect("id").From("dml_people"). Where(Column("id").In().Int64s(2))).LoadInt64s(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []int64{2}, ids) }) t.Run("NOT IN Clause (multiple args)", func(t *testing.T) { ids, err := NewSelect("id").From("dml_people"). Where(Column("id").NotIn().Int64s(2, 3)).WithDBR(s.DB).LoadInt64s(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []int64{1}, ids) }) t.Run("Scan string into arg UINT returns error", func(t *testing.T) { var people dmlPersons rc, err := NewSelect().AddColumnsAliases("email", "id", "name", "email").From("dml_people"). WithDBR(s.DB).Load(context.TODO(), &people) assert.EqualError(t, err, "[dml] DBR.Load failed with queryID \"\" and ColumnMapper *dml.dmlPersons: [dml] Column \"id\": strconv.ParseUint: parsing \"<EMAIL>\": invalid syntax") assert.EqualError(t, errors.Cause(err), "strconv.ParseUint: parsing \"<EMAIL>\": invalid syntax") assert.Empty(t, rc) }) } func TestSelect_LoadType_Single(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) t.Run("LoadNullString", func(t *testing.T) { name, found, err := NewSelect("name").From("dml_people").Where(Column("email").PlaceHolder()). WithDBR(s.DB).LoadNullString(context.TODO(), "<EMAIL>") assert.NoError(t, err) assert.True(t, found) assert.Exactly(t, null.MakeString("<NAME>"), name) }) t.Run("LoadNullString too many columns", func(t *testing.T) { name, found, err := NewSelect("name", "email").From("dml_people").Where(Expr("email = '<EMAIL>'")). WithDBR(s.DB).LoadNullString(context.TODO()) assert.Error(t, err) assert.False(t, found) assert.Empty(t, name.Data) }) t.Run("LoadNullString not found", func(t *testing.T) { name, found, err := NewSelect("name").From("dml_people").Where(Expr("email = '<EMAIL>'")). WithDBR(s.DB).LoadNullString(context.TODO()) assert.NoError(t, err) assert.False(t, found) assert.Exactly(t, null.String{}, name) }) t.Run("LoadNullInt64", func(t *testing.T) { id, found, err := NewSelect("id").From("dml_people").Limit(0, 1).WithDBR(s.DB).LoadNullInt64(context.TODO()) assert.NoError(t, err) assert.True(t, found) assert.True(t, id.Int64 > 0) }) t.Run("LoadNullInt64 too many columns", func(t *testing.T) { id, found, err := NewSelect("id", "email").From("dml_people").Limit(0, 1).WithDBR(s.DB).LoadNullInt64(context.TODO()) assert.Error(t, err) assert.False(t, found) assert.Exactly(t, null.Int64{}, id) }) t.Run("LoadNullInt64 not found", func(t *testing.T) { id, found, err := NewSelect("id").From("dml_people").Where(Expr("id=236478326")).WithDBR(s.DB).LoadNullInt64(context.TODO()) assert.NoError(t, err) assert.False(t, found) assert.Exactly(t, null.Int64{}, id) }) t.Run("LoadNullUint64", func(t *testing.T) { id, found, err := NewSelect("id").From("dml_people").Limit(0, 1).WithDBR(s.DB).LoadNullUint64(context.TODO()) assert.NoError(t, err) assert.True(t, found) assert.True(t, id.Uint64 > 0) }) t.Run("LoadNullUint64 too many columns", func(t *testing.T) { id, found, err := NewSelect("id", "email").From("dml_people").Limit(0, 1).WithDBR(s.DB).LoadNullUint64(context.TODO()) assert.Error(t, err) assert.False(t, found) assert.Exactly(t, null.Uint64{}, id) }) t.Run("LoadNullUint64 not found", func(t *testing.T) { id, found, err := NewSelect("id").From("dml_people").Where(Expr("id=236478326")).WithDBR(s.DB).LoadNullUint64(context.TODO()) assert.NoError(t, err) assert.False(t, found) assert.Exactly(t, null.Uint64{}, id) }) t.Run("LoadNullFloat64", func(t *testing.T) { id, found, err := NewSelect("id").From("dml_people").Limit(0, 1).WithDBR(s.DB).LoadNullFloat64(context.TODO()) assert.NoError(t, err) assert.True(t, found) assert.True(t, id.Float64 > 0) }) t.Run("LoadNullFloat64 too many columns", func(t *testing.T) { id, found, err := NewSelect("id", "email").From("dml_people").Limit(0, 1).WithDBR(s.DB).LoadNullFloat64(context.TODO()) assert.Error(t, err) assert.False(t, found) assert.Exactly(t, null.Float64{}, id) }) t.Run("LoadNullFloat64 not found", func(t *testing.T) { id, found, err := NewSelect("id").From("dml_people").Where(Expr("id=236478326")).WithDBR(s.DB).LoadNullFloat64(context.TODO()) assert.NoError(t, err) assert.False(t, found) assert.Exactly(t, null.Float64{}, id) }) t.Run("LoadDecimal", func(t *testing.T) { income, found, err := NewSelect("avg_income").From("dml_people").Where(Column("email").Like().Str(`<EMAIL>`)). WithDBR(s.DB).LoadDecimal(context.TODO()) assert.NoError(t, err) assert.True(t, found) assert.Exactly(t, null.MakeDecimalInt64(33366677, 5), income) }) } func TestSelect_WithArgs_LoadUint64(t *testing.T) { s := createRealSessionWithFixtures(t, &installFixturesConfig{ AddPeopleWithMaxUint64: true, }) defer testCloser(t, s) // Despite it seems that Go can support large uint64 values ... the down side is that // the byte encoded uint64 gets transferred as a string and MySQL/MariaDB must convert that // string into a bigint. const bigID uint64 = 18446744073700551613 // see also file dml_test.go MaxUint64 sel := NewSelect("id").From("dml_people").Where(Column("id").Uint64(bigID)) t.Run("MaxUint64 prepared stmt o:equal", func(t *testing.T) { id, found, err := sel.WithDBR(s.DB).LoadNullUint64(context.TODO()) assert.NoError(t, err) assert.True(t, found) assert.Exactly(t, null.MakeUint64(bigID), id) }) t.Run("MaxUint64 interpolated o:equal", func(t *testing.T) { id, found, err := sel.WithDBR(s.DB).Interpolate().LoadNullUint64(context.TODO()) assert.NoError(t, err) assert.True(t, found) assert.Exactly(t, null.MakeUint64(bigID), id) }) } func TestSelect_WithArgs_LoadType_Slices(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) t.Run("LoadStrings", func(t *testing.T) { names, err := NewSelect("name").From("dml_people").WithDBR(s.DB).LoadStrings(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []string{"<NAME>", "Dmitri"}, names) }) t.Run("LoadStrings too many columns", func(t *testing.T) { vals, err := NewSelect("name", "email").From("dml_people").WithDBR(s.DB).LoadStrings(context.TODO(), nil) assert.Error(t, err) assert.Exactly(t, []string(nil), vals) }) t.Run("LoadStrings not found", func(t *testing.T) { names, err := NewSelect("name").From("dml_people").Where(Expr("name ='jdhsjdf'")).WithDBR(s.DB).LoadStrings(context.TODO(), nil) assert.NoError(t, err) assert.Nil(t, names) }) t.Run("LoadInt64s", func(t *testing.T) { names, err := NewSelect("id").From("dml_people").WithDBR(s.DB).LoadInt64s(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []int64{1, 2}, names) }) t.Run("LoadInt64s too many columns", func(t *testing.T) { vals, err := NewSelect("id", "email").From("dml_people").WithDBR(s.DB).LoadInt64s(context.TODO(), nil) assert.Error(t, err) assert.Exactly(t, []int64(nil), vals) }) t.Run("LoadInt64s not found", func(t *testing.T) { names, err := NewSelect("id").From("dml_people").Where(Expr("name ='jdhsjdf'")).WithDBR(s.DB).LoadInt64s(context.TODO(), nil) assert.NoError(t, err) assert.Nil(t, names) }) t.Run("LoadUint64s", func(t *testing.T) { names, err := NewSelect("id").From("dml_people").WithDBR(s.DB).LoadUint64s(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []uint64{1, 2}, names) }) t.Run("LoadUint64s too many columns", func(t *testing.T) { vals, err := NewSelect("id", "email").From("dml_people").WithDBR(s.DB).LoadUint64s(context.TODO(), nil) assert.Error(t, err) assert.Exactly(t, []uint64(nil), vals) }) t.Run("LoadUint64s not found", func(t *testing.T) { names, err := NewSelect("id").From("dml_people").Where(Expr("name ='jdhsjdf'")).WithDBR(s.DB).LoadUint64s(context.TODO(), nil) assert.NoError(t, err) assert.Nil(t, names) }) t.Run("LoadFloat64s", func(t *testing.T) { names, err := NewSelect("id").From("dml_people").WithDBR(s.DB).LoadFloat64s(context.TODO(), nil) assert.NoError(t, err) assert.Exactly(t, []float64{1, 2}, names) }) t.Run("LoadFloat64s too many columns", func(t *testing.T) { vals, err := NewSelect("id", "email").From("dml_people").WithDBR(s.DB).LoadFloat64s(context.TODO(), nil) assert.Error(t, err) assert.Exactly(t, []float64(nil), vals) }) t.Run("LoadFloat64s not found", func(t *testing.T) { names, err := NewSelect("id").From("dml_people").Where(Expr("name ='jdhsjdf'")).WithDBR(s.DB).LoadFloat64s(context.TODO(), nil) assert.NoError(t, err) assert.Nil(t, names) }) } func TestSelect_Join(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) t.Run("inner, distinct, no cache, high prio", func(t *testing.T) { sqlObj := NewSelect("p1.*", "p2.*").FromAlias("dml_people", "p1"). Distinct().StraightJoin().SQLNoCache(). Join( MakeIdentifier("dml_people").Alias("p2"), Expr("`p2`.`id` = `p1`.`id`"), Column("p1.id").Int(42), ) compareToSQL2(t, sqlObj, errors.NoKind, "SELECT DISTINCT STRAIGHT_JOIN SQL_NO_CACHE `p1`.*, `p2`.* FROM `dml_people` AS `p1` INNER JOIN `dml_people` AS `p2` ON (`p2`.`id` = `p1`.`id`) AND (`p1`.`id` = 42)", ) }) t.Run("inner", func(t *testing.T) { sqlObj := NewSelect("p1.*", "p2.*").FromAlias("dml_people", "p1"). Join( MakeIdentifier("dml_people").Alias("p2"), Expr("`p2`.`id` = `p1`.`id`"), Column("p1.id").Int(42), ) compareToSQL2(t, sqlObj, errors.NoKind, "SELECT `p1`.*, `p2`.* FROM `dml_people` AS `p1` INNER JOIN `dml_people` AS `p2` ON (`p2`.`id` = `p1`.`id`) AND (`p1`.`id` = 42)", ) }) t.Run("left", func(t *testing.T) { sqlObj := NewSelect("p1.*", "p2.name").FromAlias("dml_people", "p1"). LeftJoin( MakeIdentifier("dml_people").Alias("p2"), Expr("`p2`.`id` = `p1`.`id`"), Column("p1.id").Int(42), ) compareToSQL2(t, sqlObj, errors.NoKind, "SELECT `p1`.*, `p2`.`name` FROM `dml_people` AS `p1` LEFT JOIN `dml_people` AS `p2` ON (`p2`.`id` = `p1`.`id`) AND (`p1`.`id` = 42)", ) }) t.Run("right", func(t *testing.T) { sqlObj := NewSelect("p1.*").FromAlias("dml_people", "p1"). AddColumnsAliases("p2.name", "p2Name", "p2.email", "p2Email", "id", "internalID"). RightJoin( MakeIdentifier("dml_people").Alias("p2"), Expr("`p2`.`id` = `p1`.`id`"), ) compareToSQL2(t, sqlObj, errors.NoKind, "SELECT `p1`.*, `p2`.`name` AS `p2Name`, `p2`.`email` AS `p2Email`, `id` AS `internalID` FROM `dml_people` AS `p1` RIGHT JOIN `dml_people` AS `p2` ON (`p2`.`id` = `p1`.`id`)", ) }) t.Run("using", func(t *testing.T) { sqlObj := NewSelect("p1.*").FromAlias("dml_people", "p1"). AddColumnsAliases("p2.name", "p2Name", "p2.email", "p2Email"). RightJoin( MakeIdentifier("dml_people").Alias("p2"), Columns("id", "email"), ) compareToSQL2(t, sqlObj, errors.NoKind, "SELECT `p1`.*, `p2`.`name` AS `p2Name`, `p2`.`email` AS `p2Email` FROM `dml_people` AS `p1` RIGHT JOIN `dml_people` AS `p2` USING (`id`,`email`)", ) }) } func TestSelect_Locks(t *testing.T) { t.Run("LOCK IN SHARE MODE", func(t *testing.T) { s := NewSelect("p1.*"). AddColumnsAliases("p2.name", "p2Name", "p2.email", "p2Email"). FromAlias("dml_people", "p1").LockInShareMode() compareToSQL2(t, s, errors.NoKind, "SELECT `p1`.*, `p2`.`name` AS `p2Name`, `p2`.`email` AS `p2Email` FROM `dml_people` AS `p1` LOCK IN SHARE MODE", ) }) t.Run("FOR UPDATE", func(t *testing.T) { s := NewSelect("p1.*"). AddColumnsAliases("p2.name", "p2Name", "p2.email", "p2Email"). FromAlias("dml_people", "p1").ForUpdate() compareToSQL2(t, s, errors.NoKind, "SELECT `p1`.*, `p2`.`name` AS `p2Name`, `p2`.`email` AS `p2Email` FROM `dml_people` AS `p1` FOR UPDATE", ) }) } func TestSelect_Columns(t *testing.T) { t.Run("AddColumns, multiple args", func(t *testing.T) { s := NewSelect("a", "b") s.FromAlias("tableA", "tA") s.AddColumns("d,e, f", "g", "h", "i,j ,k") compareToSQL2(t, s, errors.NoKind, "SELECT `a`, `b`, `d,e, f`, `g`, `h`, `i,j ,k` FROM `tableA` AS `tA`", ) }) t.Run("AddColumns, each column itself", func(t *testing.T) { s := NewSelect("a", "b") s.FromAlias("tableA", "tA") s.AddColumns("d", "e", "f") compareToSQL2(t, s, errors.NoKind, "SELECT `a`, `b`, `d`, `e`, `f` FROM `tableA` AS `tA`", ) }) t.Run("AddColumnsAliases Expression Quoted", func(t *testing.T) { s := NewSelect().From("t3"). AddColumnsAliases("x", "u", "y", "v"). AddColumnsAliases("SUM(price)", "total_price") compareToSQL2(t, s, errors.NoKind, "SELECT `x` AS `u`, `y` AS `v`, `SUM(price)` AS `total_price` FROM `t3`", ) }) t.Run("AddColumns+AddColumnsConditions", func(t *testing.T) { s := NewSelect().From("t3"). AddColumns("t3.name", "sku"). AddColumnsConditions(Expr("SUM(price)").Alias("total_price")) compareToSQL2(t, s, errors.NoKind, "SELECT `t3`.`name`, `sku`, SUM(price) AS `total_price` FROM `t3`", ) }) t.Run("AddColumnsAliases multi", func(t *testing.T) { s := NewSelect().From("t3"). AddColumnsAliases("t3.name", "t3Name", "t3.sku", "t3SKU") compareToSQL2(t, s, errors.NoKind, "SELECT `t3`.`name` AS `t3Name`, `t3`.`sku` AS `t3SKU` FROM `t3`", ) }) t.Run("AddColumnsAliases imbalanced", func(t *testing.T) { defer func() { if r := recover(); r != nil { if err, ok := r.(error); ok { assert.ErrorIsKind(t, errors.Mismatch, err) } else { t.Errorf("Panic should contain an error but got:\n%+v", r) } } else { t.Error("Expecting a panic but got nothing") } }() NewSelect().From("t3"). AddColumnsAliases("t3.name", "t3Name", "t3.sku") }) t.Run("AddColumnsConditions", func(t *testing.T) { s := NewSelect().FromAlias("sales_bestsellers_aggregated_daily", "t3"). AddColumnsConditions(Expr("DATE_FORMAT(t3.period, '%Y-%m-01')").Alias("period")) compareToSQL2(t, s, errors.NoKind, "SELECT DATE_FORMAT(t3.period, '%Y-%m-01') AS `period` FROM `sales_bestsellers_aggregated_daily` AS `t3`", ) }) t.Run("AddColumns with expression incorrect", func(t *testing.T) { s := NewSelect().AddColumns(" `t.value`", "`t`.`attribute_id`", "t.{column} AS `col_type`").FromAlias("catalog_product_entity_{type}", "t") compareToSQL2(t, s, errors.NoKind, "SELECT ` t`.`value`, `t`.`attribute_id`, `t`.`{column} AS col_type` FROM `catalog_product_entity_{type}` AS `t`", ) }) t.Run("AddColumnsConditions fails on interpolation", func(t *testing.T) { s := NewSelect().From("t3"). AddColumns("t3.name", "sku"). AddColumnsConditions(Expr("SUM(price)+?-?").Float64(3.14159).Alias("total_price")) compareToSQL2(t, s, errors.Mismatch, "") }) } func TestSelect_SubSelect(t *testing.T) { sub := NewSelect().From("catalog_category_product"). AddColumns("entity_id").Where(Column("category_id").Int64(234)) runner := func(op Op, wantSQL string) func(*testing.T) { c := Column("entity_id").Sub(sub) c.Operator = op return func(t *testing.T) { s := NewSelect("sku", "type_id"). From("catalog_product_entity"). Where(c) compareToSQL2(t, s, errors.NoKind, wantSQL) } } t.Run("IN", runner(In, "SELECT `sku`, `type_id` FROM `catalog_product_entity` WHERE (`entity_id` IN (SELECT `entity_id` FROM `catalog_category_product` WHERE (`category_id` = 234)))", )) t.Run("EXISTS", runner(Exists, "SELECT `sku`, `type_id` FROM `catalog_product_entity` WHERE (`entity_id` EXISTS (SELECT `entity_id` FROM `catalog_category_product` WHERE (`category_id` = 234)))", )) t.Run("NOT EXISTS", runner(NotExists, "SELECT `sku`, `type_id` FROM `catalog_product_entity` WHERE (`entity_id` NOT EXISTS (SELECT `entity_id` FROM `catalog_category_product` WHERE (`category_id` = 234)))", )) t.Run("NOT EQUAL", runner(NotEqual, "SELECT `sku`, `type_id` FROM `catalog_product_entity` WHERE (`entity_id` != (SELECT `entity_id` FROM `catalog_category_product` WHERE (`category_id` = 234)))", )) t.Run("NOT EQUAL", runner(Equal, "SELECT `sku`, `type_id` FROM `catalog_product_entity` WHERE (`entity_id` = (SELECT `entity_id` FROM `catalog_category_product` WHERE (`category_id` = 234)))", )) } func TestSelect_Subselect_Complex(t *testing.T) { /* Something like: SELECT `t1`.`store_id`, `t1`.`product_id`, `t1`.`product_name`, `t1`.`product_price`, `t1`.`qty_ordered` FROM ( SELECT `t2`.`store_id`, `t2`.`product_id`, `t2`.`product_name`, `t2`.`product_price`, `t2`.`total_qty` AS `qty_ordered` FROM ( SELECT `t3`.`store_id`, `t3`.`product_id`, `t3`.`product_name`, AVG(`t3`.`product_price`) as `avg_price`, SUM(t3.qty_ordered) AS `total_qty` FROM `sales_bestsellers_aggregated_daily` AS `t3` GROUP BY `t3`.`store_id`, Date_format(t3.period, '%Y-%m-01'), `t3`.`product_id` ORDER BY `t3`.`store_id` ASC, Date_format(t3.period, '%Y-%m-01'), `total_qty` DESC ) AS `t2` ) AS `t1` */ t.Run("without args", func(t *testing.T) { sel3 := NewSelect().FromAlias("sales_bestsellers_aggregated_daily", "t3"). Unsafe(). AddColumnsConditions(Expr("DATE_FORMAT(t3.period, '%Y-%m-01')").Alias("period")). AddColumns("`t3`.`store_id`,`t3`.`product_id`,`t3`.`product_name`"). AddColumnsConditions( Expr("AVG(`t3`.`product_price`)").Alias("avg_price"), Expr("SUM(t3.qty_ordered)").Alias("total_qty"), ). GroupBy("t3.store_id"). GroupBy("DATE_FORMAT(t3.period, '%Y-%m-01')"). GroupBy("t3.product_id", "t3.product_name"). OrderBy("t3.store_id"). OrderBy("DATE_FORMAT(t3.period, '%Y-%m-01')"). OrderByDesc("total_qty") sel2 := NewSelectWithDerivedTable(sel3, "t2"). AddColumns("t2.period", "t2.store_id", "t2.product_id", "t2.product_name", "t2.avg_price"). AddColumnsAliases("`t2`.`total_qty`", "`qty_ordered`") sel1 := NewSelectWithDerivedTable(sel2, "t1"). AddColumns("t1.period", "t1.store_id", "t1.product_id", "t1.product_name", "t1.avg_price", "t1.qty_ordered"). OrderBy("`t1`.period", "`t1`.product_id") compareToSQL2(t, sel1, errors.NoKind, "SELECT `t1`.`period`, `t1`.`store_id`, `t1`.`product_id`, `t1`.`product_name`, `t1`.`avg_price`, `t1`.`qty_ordered` FROM (SELECT `t2`.`period`, `t2`.`store_id`, `t2`.`product_id`, `t2`.`product_name`, `t2`.`avg_price`, `t2`.`total_qty` AS `qty_ordered` FROM (SELECT DATE_FORMAT(t3.period, '%Y-%m-01') AS `period`, `t3`.`store_id`,`t3`.`product_id`,`t3`.`product_name`, AVG(`t3`.`product_price`) AS `avg_price`, SUM(t3.qty_ordered) AS `total_qty` FROM `sales_bestsellers_aggregated_daily` AS `t3` GROUP BY `t3`.`store_id`, DATE_FORMAT(t3.period, '%Y-%m-01'), `t3`.`product_id`, `t3`.`product_name` ORDER BY `t3`.`store_id`, DATE_FORMAT(t3.period, '%Y-%m-01'), `total_qty` DESC) AS `t2`) AS `t1` ORDER BY `t1`.`period`, `t1`.`product_id`", ) }) t.Run("with args", func(t *testing.T) { // Full valid query which works in a M1 and M2 database. sel3 := NewSelect().FromAlias("sales_bestsellers_aggregated_daily", "t3"). Unsafe(). AddColumnsConditions(Expr("DATE_FORMAT(t3.period, '%Y-%m-01')").Alias("period")). AddColumns("`t3`.`store_id`,`t3`.`product_id`,`t3`.`product_name`"). AddColumnsConditions( Expr("AVG(`t3`.`product_price`)").Alias("avg_price"), Expr("SUM(t3.qty_ordered)+?").Alias("total_qty").Float64(3.141), ). GroupBy("t3.store_id"). GroupBy("DATE_FORMAT(t3.period, '%Y-%m-01')"). GroupBy("t3.product_id", "t3.product_name"). Having(Expr("COUNT(*)>?").Int(3)). OrderBy("t3.store_id"). OrderBy("DATE_FORMAT(t3.period, '%Y-%m-01')"). OrderByDesc("total_qty"). Where(Column("t3.store_id").In().Int64s(2, 3, 4)) sel2 := NewSelectWithDerivedTable(sel3, "t2"). AddColumns("t2.period", "t2.store_id", "t2.product_id", "t2.product_name", "t2.avg_price"). AddColumnsAliases("t2.total_qty", "qty_ordered") sel1 := NewSelectWithDerivedTable(sel2, "t1"). AddColumns("t1.period", "t1.store_id", "t1.product_id", "t1.product_name", "t1.avg_price", "t1.qty_ordered"). OrderBy("`t1`.period", "`t1`.product_id") compareToSQL2(t, sel1, errors.NoKind, "SELECT `t1`.`period`, `t1`.`store_id`, `t1`.`product_id`, `t1`.`product_name`, `t1`.`avg_price`, `t1`.`qty_ordered` FROM (SELECT `t2`.`period`, `t2`.`store_id`, `t2`.`product_id`, `t2`.`product_name`, `t2`.`avg_price`, `t2`.`total_qty` AS `qty_ordered` FROM (SELECT DATE_FORMAT(t3.period, '%Y-%m-01') AS `period`, `t3`.`store_id`,`t3`.`product_id`,`t3`.`product_name`, AVG(`t3`.`product_price`) AS `avg_price`, SUM(t3.qty_ordered)+3.141 AS `total_qty` FROM `sales_bestsellers_aggregated_daily` AS `t3` WHERE (`t3`.`store_id` IN (2,3,4)) GROUP BY `t3`.`store_id`, DATE_FORMAT(t3.period, '%Y-%m-01'), `t3`.`product_id`, `t3`.`product_name` HAVING (COUNT(*)>3) ORDER BY `t3`.`store_id`, DATE_FORMAT(t3.period, '%Y-%m-01'), `total_qty` DESC) AS `t2`) AS `t1` ORDER BY `t1`.`period`, `t1`.`product_id`", ) }) } func TestSelect_Subselect_Compact(t *testing.T) { sel2 := NewSelect().FromAlias("sales_bestsellers_aggregated_daily", "t3"). AddColumns("`t3`.`product_name`"). Where(Column("t3.store_id").In().Int64s(2, 3, 4)). GroupBy("t3.store_id"). Having(Expr("COUNT(*)>?").Int(5)) sel := NewSelectWithDerivedTable(sel2, "t2"). AddColumns("t2.product_name"). Where(Column("t2.floatcol").Equal().Float64(3.14159)) compareToSQL2(t, sel, errors.NoKind, "SELECT `t2`.`product_name` FROM (SELECT `t3`.`product_name` FROM `sales_bestsellers_aggregated_daily` AS `t3` WHERE (`t3`.`store_id` IN (2,3,4)) GROUP BY `t3`.`store_id` HAVING (COUNT(*)>5)) AS `t2` WHERE (`t2`.`floatcol` = 3.14159)", ) } func TestSelect_ParenthesisOpen_Close(t *testing.T) { t.Run("beginning of WHERE", func(t *testing.T) { sel := NewSelect("a", "b"). FromAlias("c", "cc"). Where( ParenthesisOpen(), Column("d").Int(1), Column("e").Str("wat").Or(), ParenthesisClose(), Column("f").Float64(2.7182), ). GroupBy("ab"). Having( ParenthesisOpen(), Column("m").Int(33), Column("n").Str("wh3r3").Or(), ParenthesisClose(), Expr("j = k"), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `a`, `b` FROM `c` AS `cc` WHERE ((`d` = 1) OR (`e` = 'wat')) AND (`f` = 2.7182) GROUP BY `ab` HAVING ((`m` = 33) OR (`n` = 'wh3r3')) AND (j = k)", ) }) t.Run("end of WHERE", func(t *testing.T) { sel := NewSelect("a", "b"). FromAlias("c", "cc"). Where( Column("f").Float64(2.7182), ParenthesisOpen(), Column("d").Int(1), Column("e").Str("wat").Or(), ParenthesisClose(), ). GroupBy("ab"). Having( Expr("j = k"), ParenthesisOpen(), Column("m").Int(33), Column("n").Str("wh3r3").Or(), ParenthesisClose(), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `a`, `b` FROM `c` AS `cc` WHERE (`f` = 2.7182) AND ((`d` = 1) OR (`e` = 'wat')) GROUP BY `ab` HAVING (j = k) AND ((`m` = 33) OR (`n` = 'wh3r3'))", ) }) t.Run("middle of WHERE", func(t *testing.T) { sel := NewSelect("a", "b"). FromAlias("c", "cc"). Where( Column("f").Float64(2.7182), ParenthesisOpen(), Column("d").Int(1), Column("e").Str("wat").Or(), ParenthesisClose(), Column("p").Float64(3.141592), ). GroupBy("ab"). Having( Expr("j = k"), ParenthesisOpen(), Column("m").Int(33), Column("n").Str("wh3r3").Or(), ParenthesisClose(), Column("q").NotNull(), ) compareToSQL2(t, sel, errors.NoKind, "SELECT `a`, `b` FROM `c` AS `cc` WHERE (`f` = 2.7182) AND ((`d` = 1) OR (`e` = 'wat')) AND (`p` = 3.141592) GROUP BY `ab` HAVING (j = k) AND ((`m` = 33) OR (`n` = 'wh3r3')) AND (`q` IS NOT NULL)", ) }) } func TestSelect_Count(t *testing.T) { t.Run("written count star gets quoted", func(t *testing.T) { compareToSQL2(t, NewSelect("count(*)").From("dml_people"), errors.NoKind, "SELECT `count(*)` FROM `dml_people`", ) }) t.Run("written count star gets not quoted Unsafe", func(t *testing.T) { compareToSQL2(t, NewSelect().Unsafe().AddColumns("count(*)").From("dml_people"), errors.NoKind, "SELECT count(*) FROM `dml_people`", ) }) t.Run("func count star", func(t *testing.T) { s := NewSelect("a", "b").Count().From("dml_people") compareToSQL2(t, s, errors.NoKind, "SELECT COUNT(*) AS `counted` FROM `dml_people`", ) }) } func TestSelect_DisableBuildCache(t *testing.T) { sel := NewSelect("a", "b"). Distinct(). FromAlias("c", "cc"). Where( ParenthesisOpen(), Column("d").PlaceHolder(), Column("e").Str("wat").Or(), ParenthesisClose(), Column("f").Int(2), Column("g").Int(3), Column("h").In().Int64s(4, 5, 6), ). GroupBy("ab"). Having( ParenthesisOpen(), Column("m").Int(33), Column("n").Str("wh3r3").Or(), ParenthesisClose(), Expr("j = k"), ). OrderBy("l"). Limit(8, 7) const run1 = "SELECT DISTINCT `a`, `b` FROM `c` AS `cc` WHERE ((`d` = ?) OR (`e` = 'wat')) AND (`f` = 2) AND (`g` = 3) AND (`h` IN (4,5,6)) GROUP BY `ab` HAVING ((`m` = 33) OR (`n` = 'wh3r3')) AND (j = k) ORDER BY `l` LIMIT 8,7" const run2 = "SELECT DISTINCT `a`, `b` FROM `c` AS `cc` WHERE ((`d` = ?) OR (`e` = 'wat')) AND (`f` = 2) AND (`g` = 3) AND (`h` IN (4,5,6)) AND (`added_col` = 3.14159) GROUP BY `ab` HAVING ((`m` = 33) OR (`n` = 'wh3r3')) AND (j = k) ORDER BY `l` LIMIT 8,7" compareToSQL(t, sel.WithDBR(dbMock{}).TestWithArgs(87654), errors.NoKind, run1, "SELECT DISTINCT `a`, `b` FROM `c` AS `cc` WHERE ((`d` = 87654) OR (`e` = 'wat')) AND (`f` = 2) AND (`g` = 3) AND (`h` IN (4,5,6)) GROUP BY `ab` HAVING ((`m` = 33) OR (`n` = 'wh3r3')) AND (j = k) ORDER BY `l` LIMIT 8,7", int64(87654)) sel.Where( Column("added_col").Float64(3.14159), ) compareToSQL(t, sel.WithDBR(dbMock{}).TestWithArgs(87654), errors.NoKind, run2, "", int64(87654)) // key2 still applies to the next 2 calls compareToSQL(t, sel.WithDBR(dbMock{}).TestWithArgs(87654), errors.NoKind, run2, "", int64(87654)) compareToSQL(t, sel.WithDBR(dbMock{}).TestWithArgs(87654), errors.NoKind, run2, "SELECT DISTINCT `a`, `b` FROM `c` AS `cc` WHERE ((`d` = 87654) OR (`e` = 'wat')) AND (`f` = 2) AND (`g` = 3) AND (`h` IN (4,5,6)) AND (`added_col` = 3.14159) GROUP BY `ab` HAVING ((`m` = 33) OR (`n` = 'wh3r3')) AND (j = k) ORDER BY `l` LIMIT 8,7", int64(87654)) } func TestSelect_NamedArguments(t *testing.T) { sel := NewSelect("config_id", "value"). From("core_config_data"). Where( Column("config_id1").Less().NamedArg(":configID"), Column("config_id2").Greater().NamedArg("configID"), Column("scope_id").Greater().Int(5), Column("value").Like().PlaceHolder(), ) selDBR := sel.WithDBR(dbMock{}) t.Run("With ID 3", func(t *testing.T) { compareToSQL2(t, selDBR.TestWithArgs(sql.Named("configID", 3), "GopherValue"), errors.NoKind, "SELECT `config_id`, `value` FROM `core_config_data` WHERE (`config_id1` < ?) AND (`config_id2` > ?) AND (`scope_id` > 5) AND (`value` LIKE ?)", int64(3), int64(3), "GopherValue", ) assert.Exactly(t, []string{":configID", ":configID", "value"}, sel.qualifiedColumns, "qualifiedColumns should match") }) t.Run("With ID 6", func(t *testing.T) { // Here positions are switched compareToSQL2(t, selDBR.TestWithArgs("G0pherValue", sql.Named("configID", 6)), errors.NoKind, "SELECT `config_id`, `value` FROM `core_config_data` WHERE (`config_id1` < ?) AND (`config_id2` > ?) AND (`scope_id` > 5) AND (`value` LIKE ?)", int64(6), int64(6), "G0pherValue", ) assert.Exactly(t, []string{":configID", ":configID", "value"}, sel.qualifiedColumns, "qualifiedColumns should match") }) } func TestSelect_SetRecord(t *testing.T) { p := &dmlPerson{ ID: 6666, Name: "<NAME>", Email: null.MakeString("<EMAIL>"), } p2 := &dmlPerson{ Dob: 1970, } t.Run("multiple args from record", func(t *testing.T) { sel := NewSelect("a", "b"). FromAlias("dml_person", "dp"). Join(MakeIdentifier("dml_group").Alias("dg"), Column("dp.id").PlaceHolder()). Where( Column("dg.dob").Greater().PlaceHolder(), Column("dg.size").Less().NamedArg("dbSIZE"), Column("age").Less().Int(56), ParenthesisOpen(), Column("dp.name").PlaceHolder(), Column("e").Str("wat").Or(), ParenthesisClose(), Column("f").LessOrEqual().Int(2), Column("g").Greater().Int(3), Column("h").In().Int64s(4, 5, 6), ). GroupBy("ab"). Having( Column("dp.email").PlaceHolder(), Column("n").Str("wh3r3"), ). OrderBy("l"). WithDBR(dbMock{}).TestWithArgs(Qualify("dp", p), Qualify("dg", p2), sql.Named("dbSIZE", uint(201801))) compareToSQL2(t, sel, errors.NoKind, "SELECT `a`, `b` FROM `dml_person` AS `dp` INNER JOIN `dml_group` AS `dg` ON (`dp`.`id` = ?) WHERE (`dg`.`dob` > ?) AND (`dg`.`size` < ?) AND (`age` < 56) AND ((`dp`.`name` = ?) OR (`e` = 'wat')) AND (`f` <= 2) AND (`g` > 3) AND (`h` IN (4,5,6)) GROUP BY `ab` HAVING (`dp`.`email` = ?) AND (`n` = 'wh3r3') ORDER BY `l`", int64(6666), int64(1970), int64(201801), "<NAME>", "<EMAIL>", ) }) t.Run("single arg JOIN", func(t *testing.T) { sel := NewSelect("a").FromAlias("dml_people", "dp"). Join(MakeIdentifier("dml_group").Alias("dg"), Column("dp.id").PlaceHolder(), Column("dg.name").Strs("XY%")). OrderBy("id").WithDBR(dbMock{}).TestWithArgs(Qualify("dp", p)) compareToSQL2(t, sel, errors.NoKind, "SELECT `a` FROM `dml_people` AS `dp` INNER JOIN `dml_group` AS `dg` ON (`dp`.`id` = ?) AND (`dg`.`name` = ('XY%')) ORDER BY `id`", int64(6666), ) }) t.Run("single arg WHERE", func(t *testing.T) { sel := NewSelect("a").From("dml_people"). Where( Column("id").PlaceHolder(), ). OrderBy("id").WithDBR(dbMock{}).TestWithArgs(Qualify("", p)) compareToSQL2(t, sel, errors.NoKind, "SELECT `a` FROM `dml_people` WHERE (`id` = ?) ORDER BY `id`", int64(6666), ) }) // t.Run("Warning when nothing got matched", func(t *testing.T) { // sel := NewSelect("a").From("dml_people"). // Where( // Column("id").PlaceHolder(), // ). // WithRecords(Qualify("dml", p)).OrderBy("id") // // compareToSQL2(t, sel, errors.Mismatch.Match, <-- TODO implement // "SELECT `a` FROM `dml_people` WHERE (`id` = ?) ORDER BY `id`", // ) //}) t.Run("HAVING", func(t *testing.T) { sel := NewSelect("a").From("dml_people"). Having( Column("id").PlaceHolder(), Column("name").Like().PlaceHolder(), ). OrderBy("id").WithDBR(dbMock{}).TestWithArgs(Qualify("", p)) compareToSQL2(t, sel, errors.NoKind, "SELECT `a` FROM `dml_people` HAVING (`id` = ?) AND (`name` LIKE ?) ORDER BY `id`", int64(6666), "<NAME>", ) }) t.Run("slice as record", func(t *testing.T) { persons := &dmlPersons{ Data: []*dmlPerson{ {ID: 33, Name: "<NAME>", Email: null.MakeString("<EMAIL>")}, {ID: 44, Name: "<NAME>", Email: null.MakeString("<EMAIL>")}, {ID: 55, Name: "<NAME>", Email: null.MakeString("<EMAIL>")}, }, } t.Run("one column in WHERE", func(t *testing.T) { compareToSQL2(t, NewSelect("name", "email").From("dml_person"). Where( Column("id").In().PlaceHolder(), ). WithDBR(dbMock{}).TestWithArgs(Qualify("", persons)), errors.NoKind, "SELECT `name`, `email` FROM `dml_person` WHERE (`id` IN ?)", int64(33), int64(44), int64(55), ) }) t.Run("two columns in WHERE", func(t *testing.T) { compareToSQL2(t, NewSelect("name", "email").From("dml_person"). Where( Column("name").In().PlaceHolder(), Column("email").In().PlaceHolder(), ). WithDBR(dbMock{}).TestWithArgs(Qualify("", persons)), errors.NoKind, "SELECT `name`, `email` FROM `dml_person` WHERE (`name` IN ?) AND (`email` IN ?)", // "SELECT `name`, `email` FROM `dml_person` WHERE (`name` IN ('<NAME>','<NAME>','<NAME>')) AND (`email` IN ('<EMAIL>','<EMAIL>','<EMAIL>'))", "<NAME>", "<NAME>", "<NAME>", "<EMAIL>", "<EMAIL>", "<EMAIL>", ) }) t.Run("three columns in WHERE", func(t *testing.T) { compareToSQL2(t, NewSelect("name", "email").From("dml_person"). Where( Column("email").In().PlaceHolder(), Column("name").In().PlaceHolder(), Column("id").In().PlaceHolder(), ). WithDBR(dbMock{}).TestWithArgs(Qualify("", persons)), errors.NoKind, "SELECT `name`, `email` FROM `dml_person` WHERE (`email` IN ?) AND (`name` IN ?) AND (`id` IN ?)", //"SELECT `name`, `email` FROM `dml_person` WHERE (`email` IN ('<EMAIL>','<EMAIL>','<EMAIL>')) AND (`name` IN ('<NAME>','<NAME>','<NAME>')) AND (`id` IN (33,44,55))", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<NAME>", "<NAME>", "<NAME>", int64(33), int64(44), int64(55), ) }) }) } func TestSelect_DBR_Load_Functions(t *testing.T) { s := createRealSessionWithFixtures(t, nil) defer testCloser(t, s) inA := NewInsert("dml_null_types").AddColumns("string_val", "int64_val", "float64_val", "time_val", "bool_val", "decimal_val").WithDBR(s.DB) res, err := inA.ExecContext(context.Background(), "A1", 11, 11.11, now(), true, 11.111, nil, nil, nil, nil, nil, nil, "A2", 22, 22.22, now(), false, 22.222, nil, nil, nil, nil, nil, nil, "-A3", -33, -33.33, now(), true, -33.333, ) assert.NoError(t, err) lid, err := res.LastInsertId() assert.NoError(t, err) assert.Exactly(t, int64(1), lid) t.Run("LoadFloat64s all rows", func(t *testing.T) { var vals []float64 vals, err := NewSelect("float64_val").From("dml_null_types").OrderBy("id").WithDBR(s.DB).LoadFloat64s(context.Background(), vals) assert.NoError(t, err) assert.Exactly(t, []float64{11.11, 22.22, -33.33}, vals) }) t.Run("LoadFloat64s IN with one arg", func(t *testing.T) { var vals []float64 vals, err := NewSelect("float64_val").From("dml_null_types").Where( Column("int64_val").In().PlaceHolders(1), // do not interpolate because we want a prepare statement ).WithDBR(s.DB).LoadFloat64s(context.Background(), vals, []int{11}) assert.NoError(t, err) // the mariaDB field type of float64_val is float and go-sql-driver/mysql // converts it to float32 as we use internally null.Float64 we must convert // float32 to float64 and so loose precision. If the mariaDB field type of // field float64_val would be double, then we have float64. assert.Exactly(t, "11.11", fmt.Sprintf("%.2f", vals[0])) }) t.Run("LoadInt64s", func(t *testing.T) { var vals []int64 vals, err := NewSelect("int64_val").From("dml_null_types").OrderBy("id").WithDBR(s.DB).LoadInt64s(context.Background(), vals) assert.NoError(t, err) assert.Exactly(t, []int64{11, 22, -33}, vals) }) t.Run("LoadUint64s", func(t *testing.T) { var vals []uint64 vals, err := NewSelect("int64_val").From("dml_null_types").Where(Column("int64_val").GreaterOrEqual().Int(0)).OrderBy("id"). WithDBR(s.DB).LoadUint64s(context.Background(), vals) assert.NoError(t, err) assert.Exactly(t, []uint64{11, 22}, vals) }) t.Run("LoadStrings found", func(t *testing.T) { var vals []string vals, err := NewSelect("string_val").From("dml_null_types").OrderBy("id").WithDBR(s.DB).LoadStrings(context.Background(), vals) assert.NoError(t, err) assert.Exactly(t, []string{"A1", "A2", "-A3"}, vals) }) t.Run("LoadStrings not found", func(t *testing.T) { var vals []string vals, err := NewSelect("string_val").From("dml_null_types").Where( Column("int64_val").Equal().Int64(-34), ).OrderBy("id").WithDBR(s.DB).LoadStrings(context.Background(), vals) assert.NoError(t, err) assert.Exactly(t, []string(nil), vals) }) } <|start_filename|>sql/dmlgen/tests.go<|end_filename|> package dmlgen import ( "fmt" "strconv" "github.com/corestoreio/pkg/util/codegen" ) func (g *Generator) fnTestMainOther(testGen *codegen.Go, tbls tables) { // Test Header lenBefore := testGen.Len() var codeWritten int testGen.Pln(`func TestNewDBManagerNonDB_` + tbls.nameID() + `(t *testing.T) {`) { testGen.Pln(`ps := pseudo.MustNewService(0, &pseudo.Options{Lang: "de",MaxFloatDecimals:6})`) // If some features haven't been enabled, then there are no tests so // assign ps to underscore to avoid the unused variable error. // Alternatively figure out how not to print the whole test function at // all. testGen.Pln(`_ = ps`) for _, t := range tbls { codeWritten += t.generateTestOther(testGen, g) } } testGen.Pln(`}`) // end TestNewDBManager if codeWritten == 0 { testGen.Truncate(lenBefore) } } func (g *Generator) fnTestMainDB(testGen *codegen.Go, tbls tables) { if !tbls.hasFeature(g, FeatureDB) { return } // Test Header testGen.Pln(`func TestNewDBManagerDB_` + tbls.nameID() + `(t *testing.T) {`) { testGen.Pln(`db := dmltest.MustConnectDB(t)`) testGen.Pln(`defer dmltest.Close(t, db)`) if g.TestSQLDumpGlobPath != "" { testGen.Pln(`defer dmltest.SQLDumpLoad(t,`, strconv.Quote(g.TestSQLDumpGlobPath), `, &dmltest.SQLDumpOptions{ SkipDBCleanup: true, }).Deferred()`) } testGen.Pln(`ctx, cancel := context.WithTimeout(context.Background(), time.Minute*2)`) testGen.Pln(`defer cancel()`) testGen.Pln(`tbls, err := NewDBManager(ctx, &DBMOption{TableOptions: []ddl.TableOption{ddl.WithConnPool(db)}} )`) testGen.Pln(`assert.NoError(t, err)`) testGen.Pln(`tblNames := tbls.Tables.Tables()`) testGen.Pln(`sort.Strings(tblNames)`) testGen.Pln(`assert.Exactly(t, `, fmt.Sprintf("%#v", g.sortedTableNames()), `, tblNames)`) testGen.Pln(`err = tbls.Validate(ctx)`) testGen.Pln(`assert.NoError(t, err)`) testGen.Pln(`var ps *pseudo.Service`) testGen.Pln(`ps = pseudo.MustNewService(0, &pseudo.Options{Lang: "de",MaxFloatDecimals:6},`) testGen.In() testGen.Pln(`pseudo.WithTagFakeFunc("website_id", func(maxLen int) interface{} {`) testGen.Pln(` return 1`) testGen.Pln(`}),`) testGen.Pln(`pseudo.WithTagFakeFunc("store_id", func(maxLen int) interface{} {`) testGen.Pln(` return 1`) testGen.Pln(`}),`) if fn, ok := g.customCode["pseudo.MustNewService.Option"]; ok { fn(g, nil, testGen) } testGen.Out() testGen.Pln(`)`) for _, t := range tbls { t.generateTestDB(testGen) } // end for tables } testGen.C(`Uncomment the next line for debugging to see all the queries.`) testGen.Pln(`// t.Logf("queries: %#v", tbls.ConnPool.CachedQueries())`) testGen.Pln(`}`) // end TestNewDBManager } <|start_filename|>sql/dmlgen/dmltestgenerated/output_gen_test.go<|end_filename|> // Code generated by corestoreio/pkg/util/codegen. DO NOT EDIT. // Generated by sql/dmlgen. DO NOT EDIT. // +build !ignore // +build !ignored package dmltestgenerated import ( "context" "fmt" "sort" "testing" "time" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/util/assert" "github.com/corestoreio/pkg/util/pseudo" ) func TestNewDBManagerNonDB_e0543bebb1223430cb42e7b7dd2109cd(t *testing.T) { ps := pseudo.MustNewService(0, &pseudo.Options{Lang: "de", MaxFloatDecimals: 6}) _ = ps t.Run("CatalogProductIndexEAVDecimalIDX_Empty", func(t *testing.T) { e := new(CatalogProductIndexEAVDecimalIDX) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, CatalogProductIndexEAVDecimalIDX{}) }) t.Run("CatalogProductIndexEAVDecimalIDX_Copy", func(t *testing.T) { e := new(CatalogProductIndexEAVDecimalIDX) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("CatalogProductIndexEAVDecimalIDXes_Validate", func(t *testing.T) { c := CatalogProductIndexEAVDecimalIDXes{Data: []*CatalogProductIndexEAVDecimalIDX{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("CoreConfiguration_Empty", func(t *testing.T) { e := new(CoreConfiguration) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, CoreConfiguration{}) }) t.Run("CoreConfiguration_Copy", func(t *testing.T) { e := new(CoreConfiguration) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("CoreConfigurations_Validate", func(t *testing.T) { c := CoreConfigurations{Data: []*CoreConfiguration{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("CustomerAddressEntity_Empty", func(t *testing.T) { e := new(CustomerAddressEntity) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, CustomerAddressEntity{}) }) t.Run("CustomerAddressEntity_Copy", func(t *testing.T) { e := new(CustomerAddressEntity) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("CustomerAddressEntities_Validate", func(t *testing.T) { c := CustomerAddressEntities{Data: []*CustomerAddressEntity{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("CustomerEntity_Empty", func(t *testing.T) { e := new(CustomerEntity) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, CustomerEntity{}) }) t.Run("CustomerEntity_Copy", func(t *testing.T) { e := new(CustomerEntity) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("CustomerEntities_Validate", func(t *testing.T) { c := CustomerEntities{Data: []*CustomerEntity{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("DmlgenTypes_Empty", func(t *testing.T) { e := new(DmlgenTypes) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, DmlgenTypes{}) }) t.Run("DmlgenTypes_Copy", func(t *testing.T) { e := new(DmlgenTypes) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("DmlgenTypesCollection_Validate", func(t *testing.T) { c := DmlgenTypesCollection{Data: []*DmlgenTypes{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("SalesOrderStatusState_Empty", func(t *testing.T) { e := new(SalesOrderStatusState) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, SalesOrderStatusState{}) }) t.Run("SalesOrderStatusState_Copy", func(t *testing.T) { e := new(SalesOrderStatusState) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("SalesOrderStatusStates_Validate", func(t *testing.T) { c := SalesOrderStatusStates{Data: []*SalesOrderStatusState{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("ViewCustomerAutoIncrement_Empty", func(t *testing.T) { e := new(ViewCustomerAutoIncrement) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, ViewCustomerAutoIncrement{}) }) t.Run("ViewCustomerAutoIncrement_Copy", func(t *testing.T) { e := new(ViewCustomerAutoIncrement) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("ViewCustomerAutoIncrements_Validate", func(t *testing.T) { c := ViewCustomerAutoIncrements{Data: []*ViewCustomerAutoIncrement{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) t.Run("ViewCustomerNoAutoIncrement_Empty", func(t *testing.T) { e := new(ViewCustomerNoAutoIncrement) assert.NoError(t, ps.FakeData(e)) e.Empty() assert.Exactly(t, *e, ViewCustomerNoAutoIncrement{}) }) t.Run("ViewCustomerNoAutoIncrement_Copy", func(t *testing.T) { e := new(ViewCustomerNoAutoIncrement) assert.NoError(t, ps.FakeData(e)) e2 := e.Copy() assert.Exactly(t, e, e2) assert.NoError(t, ps.FakeData(e)) assert.NotEqual(t, e, e2) }) t.Run("ViewCustomerNoAutoIncrements_Validate", func(t *testing.T) { c := ViewCustomerNoAutoIncrements{Data: []*ViewCustomerNoAutoIncrement{nil}} assert.True(t, errors.NotValid.Match(c.Validate())) }) } func TestNewDBManagerDB_e0543bebb1223430cb42e7b7dd2109cd(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "../testdata/testAll_*_tables.sql", &dmltest.SQLDumpOptions{ SkipDBCleanup: true, }).Deferred() ctx, cancel := context.WithTimeout(context.Background(), time.Minute*2) defer cancel() tbls, err := NewDBManager(ctx, &DBMOption{TableOptions: []ddl.TableOption{ddl.WithConnPool(db)}}) assert.NoError(t, err) tblNames := tbls.Tables.Tables() sort.Strings(tblNames) assert.Exactly(t, []string{"catalog_product_index_eav_decimal_idx", "core_configuration", "customer_address_entity", "customer_entity", "dmlgen_types", "sales_order_status_state", "view_customer_auto_increment", "view_customer_no_auto_increment"}, tblNames) err = tbls.Validate(ctx) assert.NoError(t, err) var ps *pseudo.Service ps = pseudo.MustNewService(0, &pseudo.Options{Lang: "de", MaxFloatDecimals: 6}, pseudo.WithTagFakeFunc("website_id", func(maxLen int) interface{} { return 1 }), pseudo.WithTagFakeFunc("store_id", func(maxLen int) interface{} { return 1 }), pseudo.WithTagFakeFunc("dmltestgenerated.CustomerAddressEntity.ParentID", func(maxLen int) interface{} { return nil }), pseudo.WithTagFakeFunc("col_date1", func(maxLen int) interface{} { if ps.Intn(1000)%3 == 0 { return nil } return ps.Dob18() }), pseudo.WithTagFakeFunc("col_date2", func(maxLen int) interface{} { t, _ := ps.Dob18().MarshalText() return t }), pseudo.WithTagFakeFunc("col_decimal101", func(maxLen int) interface{} { return fmt.Sprintf("%.1f", ps.Price()) }), pseudo.WithTagFakeFunc("price_b124", func(maxLen int) interface{} { return fmt.Sprintf("%.4f", ps.Price()) }), pseudo.WithTagFakeFunc("col_decimal123", func(maxLen int) interface{} { return fmt.Sprintf("%.3f", ps.Float64()) }), pseudo.WithTagFakeFunc("col_decimal206", func(maxLen int) interface{} { return fmt.Sprintf("%.6f", ps.Float64()) }), pseudo.WithTagFakeFunc("col_decimal2412", func(maxLen int) interface{} { return fmt.Sprintf("%.12f", ps.Float64()) }), pseudo.WithTagFakeFuncAlias( "col_decimal124", "price_b124", "price_a124", "price_b124", "col_float", "col_decimal206", ), ) t.Run("CatalogProductIndexEAVDecimalIDX_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCatalogProductIndexEAVDecimalIDX) selOneRow := tbl.Select("*").Where() selTenRows := tbl.Select("*").Where() selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) // this table/view does not support auto_increment entCol := NewCatalogProductIndexEAVDecimalIDXes() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) }) t.Run("CoreConfiguration_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCoreConfiguration) selOneRow := tbl.Select("*").Where( dml.Column("config_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("config_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(CoreConfiguration) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.CoreConfiguration_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(CoreConfiguration) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.ConfigID, entOut.ConfigID, "IDX%d: ConfigID should match", lID) assert.ExactlyLength(t, 8, &entIn.Scope, &entOut.Scope, "IDX%d: Scope should match", lID) assert.Exactly(t, entIn.ScopeID, entOut.ScopeID, "IDX%d: ScopeID should match", lID) assert.ExactlyLength(t, 255, &entIn.Path, &entOut.Path, "IDX%d: Path should match", lID) assert.ExactlyLength(t, 65535, &entIn.Value, &entOut.Value, "IDX%d: Value should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewCoreConfigurations() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: CoreConfigurations ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("CustomerAddressEntity_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCustomerAddressEntity) selOneRow := tbl.Select("*").Where( dml.Column("entity_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("entity_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(CustomerAddressEntity) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.CustomerAddressEntity_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(CustomerAddressEntity) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.EntityID, entOut.EntityID, "IDX%d: EntityID should match", lID) assert.ExactlyLength(t, 50, &entIn.IncrementID, &entOut.IncrementID, "IDX%d: IncrementID should match", lID) assert.Exactly(t, entIn.ParentID, entOut.ParentID, "IDX%d: ParentID should match", lID) assert.Exactly(t, entIn.IsActive, entOut.IsActive, "IDX%d: IsActive should match", lID) assert.ExactlyLength(t, 255, &entIn.City, &entOut.City, "IDX%d: City should match", lID) assert.ExactlyLength(t, 255, &entIn.Company, &entOut.Company, "IDX%d: Company should match", lID) assert.ExactlyLength(t, 255, &entIn.CountryID, &entOut.CountryID, "IDX%d: CountryID should match", lID) assert.ExactlyLength(t, 255, &entIn.Firstname, &entOut.Firstname, "IDX%d: Firstname should match", lID) assert.ExactlyLength(t, 255, &entIn.Lastname, &entOut.Lastname, "IDX%d: Lastname should match", lID) assert.ExactlyLength(t, 255, &entIn.Postcode, &entOut.Postcode, "IDX%d: Postcode should match", lID) assert.ExactlyLength(t, 255, &entIn.Region, &entOut.Region, "IDX%d: Region should match", lID) assert.ExactlyLength(t, 65535, &entIn.Street, &entOut.Street, "IDX%d: Street should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewCustomerAddressEntities() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: CustomerAddressEntities ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("CustomerEntity_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCustomerEntity) selOneRow := tbl.Select("*").Where( dml.Column("entity_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("entity_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(CustomerEntity) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.CustomerEntity_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(CustomerEntity) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.EntityID, entOut.EntityID, "IDX%d: EntityID should match", lID) assert.Exactly(t, entIn.WebsiteID, entOut.WebsiteID, "IDX%d: WebsiteID should match", lID) assert.ExactlyLength(t, 255, &entIn.Email, &entOut.Email, "IDX%d: Email should match", lID) assert.Exactly(t, entIn.GroupID, entOut.GroupID, "IDX%d: GroupID should match", lID) assert.Exactly(t, entIn.StoreID, entOut.StoreID, "IDX%d: StoreID should match", lID) assert.Exactly(t, entIn.IsActive, entOut.IsActive, "IDX%d: IsActive should match", lID) assert.ExactlyLength(t, 255, &entIn.CreatedIn, &entOut.CreatedIn, "IDX%d: CreatedIn should match", lID) assert.ExactlyLength(t, 255, &entIn.Firstname, &entOut.Firstname, "IDX%d: Firstname should match", lID) assert.ExactlyLength(t, 255, &entIn.Lastname, &entOut.Lastname, "IDX%d: Lastname should match", lID) assert.ExactlyLength(t, 128, &entIn.passwordHash, &entOut.passwordHash, "IDX%d: passwordHash should match", lID) assert.ExactlyLength(t, 128, &entIn.RpToken, &entOut.RpToken, "IDX%d: RpToken should match", lID) assert.Exactly(t, entIn.DefaultBilling, entOut.DefaultBilling, "IDX%d: DefaultBilling should match", lID) assert.Exactly(t, entIn.DefaultShipping, entOut.DefaultShipping, "IDX%d: DefaultShipping should match", lID) assert.Exactly(t, entIn.Gender, entOut.Gender, "IDX%d: Gender should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewCustomerEntities() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: CustomerEntities ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("DmlgenTypes_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameDmlgenTypes) selOneRow := tbl.Select("*").Where( dml.Column("id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(DmlgenTypes) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.DmlgenTypes_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(DmlgenTypes) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.ID, entOut.ID, "IDX%d: ID should match", lID) assert.Exactly(t, entIn.ColBigint1, entOut.ColBigint1, "IDX%d: ColBigint1 should match", lID) assert.Exactly(t, entIn.ColBigint2, entOut.ColBigint2, "IDX%d: ColBigint2 should match", lID) assert.Exactly(t, entIn.ColBigint3, entOut.ColBigint3, "IDX%d: ColBigint3 should match", lID) assert.Exactly(t, entIn.ColBigint4, entOut.ColBigint4, "IDX%d: ColBigint4 should match", lID) assert.ExactlyLength(t, 65535, &entIn.ColBlob, &entOut.ColBlob, "IDX%d: ColBlob should match", lID) assert.Exactly(t, entIn.ColDecimal101, entOut.ColDecimal101, "IDX%d: ColDecimal101 should match", lID) assert.Exactly(t, entIn.ColDecimal124, entOut.ColDecimal124, "IDX%d: ColDecimal124 should match", lID) assert.Exactly(t, entIn.PriceA124, entOut.PriceA124, "IDX%d: PriceA124 should match", lID) assert.Exactly(t, entIn.PriceB124, entOut.PriceB124, "IDX%d: PriceB124 should match", lID) assert.Exactly(t, entIn.ColDecimal123, entOut.ColDecimal123, "IDX%d: ColDecimal123 should match", lID) assert.Exactly(t, entIn.ColDecimal206, entOut.ColDecimal206, "IDX%d: ColDecimal206 should match", lID) assert.Exactly(t, entIn.ColDecimal2412, entOut.ColDecimal2412, "IDX%d: ColDecimal2412 should match", lID) assert.Exactly(t, entIn.ColInt1, entOut.ColInt1, "IDX%d: ColInt1 should match", lID) assert.Exactly(t, entIn.ColInt2, entOut.ColInt2, "IDX%d: ColInt2 should match", lID) assert.Exactly(t, entIn.ColInt3, entOut.ColInt3, "IDX%d: ColInt3 should match", lID) assert.Exactly(t, entIn.ColInt4, entOut.ColInt4, "IDX%d: ColInt4 should match", lID) assert.ExactlyLength(t, 4294967295, &entIn.ColLongtext1, &entOut.ColLongtext1, "IDX%d: ColLongtext1 should match", lID) assert.ExactlyLength(t, 4294967295, &entIn.ColLongtext2, &entOut.ColLongtext2, "IDX%d: ColLongtext2 should match", lID) assert.ExactlyLength(t, 16777215, &entIn.ColMediumblob, &entOut.ColMediumblob, "IDX%d: ColMediumblob should match", lID) assert.ExactlyLength(t, 16777215, &entIn.ColMediumtext1, &entOut.ColMediumtext1, "IDX%d: ColMediumtext1 should match", lID) assert.ExactlyLength(t, 16777215, &entIn.ColMediumtext2, &entOut.ColMediumtext2, "IDX%d: ColMediumtext2 should match", lID) assert.Exactly(t, entIn.ColSmallint1, entOut.ColSmallint1, "IDX%d: ColSmallint1 should match", lID) assert.Exactly(t, entIn.ColSmallint2, entOut.ColSmallint2, "IDX%d: ColSmallint2 should match", lID) assert.Exactly(t, entIn.ColSmallint3, entOut.ColSmallint3, "IDX%d: ColSmallint3 should match", lID) assert.Exactly(t, entIn.ColSmallint4, entOut.ColSmallint4, "IDX%d: ColSmallint4 should match", lID) assert.Exactly(t, entIn.HasSmallint5, entOut.HasSmallint5, "IDX%d: HasSmallint5 should match", lID) assert.Exactly(t, entIn.IsSmallint5, entOut.IsSmallint5, "IDX%d: IsSmallint5 should match", lID) assert.ExactlyLength(t, 65535, &entIn.ColText, &entOut.ColText, "IDX%d: ColText should match", lID) assert.Exactly(t, entIn.ColTinyint1, entOut.ColTinyint1, "IDX%d: ColTinyint1 should match", lID) assert.ExactlyLength(t, 1, &entIn.ColVarchar1, &entOut.ColVarchar1, "IDX%d: ColVarchar1 should match", lID) assert.ExactlyLength(t, 100, &entIn.ColVarchar100, &entOut.ColVarchar100, "IDX%d: ColVarchar100 should match", lID) assert.ExactlyLength(t, 16, &entIn.ColVarchar16, &entOut.ColVarchar16, "IDX%d: ColVarchar16 should match", lID) assert.ExactlyLength(t, 21, &entIn.ColChar1, &entOut.ColChar1, "IDX%d: ColChar1 should match", lID) assert.ExactlyLength(t, 17, &entIn.ColChar2, &entOut.ColChar2, "IDX%d: ColChar2 should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewDmlgenTypesCollection() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: DmlgenTypesCollection ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("SalesOrderStatusState_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameSalesOrderStatusState) selOneRow := tbl.Select("*").Where() selTenRows := tbl.Select("*").Where() selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) // this table/view does not support auto_increment entCol := NewSalesOrderStatusStates() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) }) t.Run("ViewCustomerAutoIncrement_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameViewCustomerAutoIncrement) selOneRow := tbl.Select("*").Where() selTenRows := tbl.Select("*").Where() selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) // this table/view does not support auto_increment entCol := NewViewCustomerAutoIncrements() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) }) t.Run("ViewCustomerNoAutoIncrement_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameViewCustomerNoAutoIncrement) selOneRow := tbl.Select("*").Where() selTenRows := tbl.Select("*").Where() selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) // this table/view does not support auto_increment entCol := NewViewCustomerNoAutoIncrements() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) }) // Uncomment the next line for debugging to see all the queries. // t.Logf("queries: %#v", tbls.ConnPool.CachedQueries()) } <|start_filename|>sql/dmlgen/dmltestgenerated4/db_part_query_gen_test.go<|end_filename|> // Code generated by corestoreio/pkg/util/codegen. DO NOT EDIT. // Generated by sql/dmlgen. DO NOT EDIT. package dmltestgenerated4 import ( "context" "sort" "testing" "time" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/util/assert" "github.com/corestoreio/pkg/util/pseudo" ) func TestNewDBManagerDB_48a8450c0b62e880b2d40acd0bbbd0dc(t *testing.T) { db := dmltest.MustConnectDB(t) defer dmltest.Close(t, db) defer dmltest.SQLDumpLoad(t, "../testdata/testAll_*_tables.sql", &dmltest.SQLDumpOptions{ SkipDBCleanup: true, }).Deferred() ctx, cancel := context.WithTimeout(context.Background(), time.Minute*2) defer cancel() tbls, err := NewDBManager(ctx, &DBMOption{TableOptions: []ddl.TableOption{ddl.WithConnPool(db)}}) assert.NoError(t, err) tblNames := tbls.Tables.Tables() sort.Strings(tblNames) assert.Exactly(t, []string{"core_configuration", "sales_order_status_state", "view_customer_auto_increment"}, tblNames) err = tbls.Validate(ctx) assert.NoError(t, err) var ps *pseudo.Service ps = pseudo.MustNewService(0, &pseudo.Options{Lang: "de", MaxFloatDecimals: 6}, pseudo.WithTagFakeFunc("website_id", func(maxLen int) (interface{}, error) { return 1, nil }), pseudo.WithTagFakeFunc("store_id", func(maxLen int) (interface{}, error) { return 1, nil }), ) t.Run("CoreConfiguration_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameCoreConfiguration) selOneRow := tbl.Select("*").Where( dml.Column("config_id").Equal().PlaceHolder(), ) selTenRows := tbl.Select("*").Where( dml.Column("config_id").LessOrEqual().Int(10), ) selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) entINSERTStmtA := tbls.ConnPool.WithPrepare(ctx, tbl.Insert().BuildValues()) for i := 0; i < 9; i++ { entIn := new(CoreConfiguration) assert.NoError(t, ps.FakeData(entIn), "Error at index %d", i) lID := dmltest.CheckLastInsertID(t, "Error: TestNewTables.CoreConfiguration_Entity")(entINSERTStmtA.ExecContext(ctx, dml.Qualify("", entIn))) entINSERTStmtA.Reset() entOut := new(CoreConfiguration) rowCount, err := selOneRowDBR.Load(ctx, entOut, lID) assert.NoError(t, err) assert.Exactly(t, uint64(1), rowCount, "IDX%d: RowCount did not match", i) assert.Exactly(t, entIn.ConfigID, entOut.ConfigID, "IDX%d: ConfigID should match", lID) assert.ExactlyLength(t, 8, &entIn.Scope, &entOut.Scope, "IDX%d: Scope should match", lID) assert.Exactly(t, entIn.ScopeID, entOut.ScopeID, "IDX%d: ScopeID should match", lID) assert.ExactlyLength(t, 255, &entIn.Path, &entOut.Path, "IDX%d: Path should match", lID) assert.ExactlyLength(t, 65535, &entIn.Value, &entOut.Value, "IDX%d: Value should match", lID) } dmltest.Close(t, entINSERTStmtA) entCol := NewCoreConfigurations() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) colInsertDBR := tbls.ConnPool.WithQueryBuilder(tbl.Insert().Replace().SetRowCount(len(entCol.Data)).BuildValues()) lID := dmltest.CheckLastInsertID(t, "Error: CoreConfigurations ")(colInsertDBR.ExecContext(ctx, dml.Qualify("", entCol))) t.Logf("Last insert ID into: %d", lID) }) t.Run("SalesOrderStatusState_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameSalesOrderStatusState) selOneRow := tbl.Select("*").Where() selTenRows := tbl.Select("*").Where() selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) // this table/view does not support auto_increment entCol := NewSalesOrderStatusStates() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) }) t.Run("ViewCustomerAutoIncrement_Entity", func(t *testing.T) { tbl := tbls.MustTable(TableNameViewCustomerAutoIncrement) selOneRow := tbl.Select("*").Where() selTenRows := tbl.Select("*").Where() selOneRowDBR := tbls.ConnPool.WithPrepare(ctx, selOneRow) defer selOneRowDBR.Close() selTenRowsDBR := tbls.ConnPool.WithQueryBuilder(selTenRows) // this table/view does not support auto_increment entCol := NewViewCustomerAutoIncrements() rowCount, err := selTenRowsDBR.Load(ctx, entCol) assert.NoError(t, err) t.Logf("Collection load rowCount: %d", rowCount) }) // Uncomment the next line for debugging to see all the queries. // t.Logf("queries: %#v", tbls.ConnPool.CachedQueries()) } <|start_filename|>sql/dml/update_pub_test.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 dml_test import ( "context" "database/sql" "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/corestoreio/errors" "github.com/corestoreio/log" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/dmltest" "github.com/corestoreio/pkg/storage/null" "github.com/corestoreio/pkg/util/assert" ) func TestUpdate_WithArgs(t *testing.T) { t.Run("no columns provided", func(t *testing.T) { mu := dml.NewUpdate("catalog_product_entity").Where(dml.Column("entity_id").In().PlaceHolder()) res, err := mu.WithDBR(dbMock{}).ExecContext(context.TODO()) assert.Nil(t, res) assert.ErrorIsKind(t, errors.Empty, err) }) t.Run("alias mismatch Exec", func(t *testing.T) { res, err := dml.NewUpdate("catalog_product_entity"). AddColumns("sku", "updated_at"). Where(dml.Column("entity_id").In().PlaceHolder()).WithDBR(dbMock{ prepareFn: func(query string) (*sql.Stmt, error) { return nil, nil }, }).WithQualifiedColumnsAliases("update_sku").ExecContext(context.TODO(), dml.Qualify("", nil)) assert.Nil(t, res) assert.ErrorIsKind(t, errors.Mismatch, err) }) t.Run("alias mismatch Prepare", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) _ = dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("UPDATE `catalog_product_entity` SET `sku`=?, `updated_at`=? WHERE (`entity_id` IN ?)")) ctx := context.Background() dbr := dbc.WithPrepare(ctx, dml.NewUpdate("catalog_product_entity"). AddColumns("sku", "updated_at"). Where(dml.Column("entity_id").In().PlaceHolder())) assert.NoError(t, dbr.PreviousError()) defer dmltest.Close(t, dbr) p := &dmlPerson{ ID: 1, Name: "Alf", Email: null.MakeString("alf@m') -- el.mac"), } res, err := dbr.WithQualifiedColumnsAliases("update_sku").ExecContext(context.TODO(), dml.Qualify("", p)) assert.ErrorIsKind(t, errors.Mismatch, err) assert.Nil(t, res, "No result is expected") }) t.Run("empty Records and RecordChan", func(t *testing.T) { mu := dml.NewUpdate("catalog_product_entity").AddColumns("sku", "updated_at"). Where(dml.Column("entity_id").In().PlaceHolder()).WithDBR(dbMock{ error: errors.AlreadyClosed.Newf("Who closed myself?"), }) res, err := mu.ExecContext(context.TODO()) assert.Nil(t, res) assert.ErrorIsKind(t, errors.AlreadyClosed, err) }) t.Run("prepared success", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) records := []*dmlPerson{ { ID: 1, Name: "Alf", Email: null.MakeString("alf@m') -- el.mac"), }, { ID: 2, Name: "John", Email: null.MakeString("<EMAIL>"), }, } // interpolate must get ignored prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("UPDATE `customer_entity` AS `ce` SET `name`=?, `email`=? WHERE (`id` = ?)")) prep.ExpectExec().WithArgs("Alf", "alf@m') -- el.mac", 1).WillReturnResult(sqlmock.NewResult(0, 1)) prep.ExpectExec().WithArgs("John", "<EMAIL>", 2).WillReturnResult(sqlmock.NewResult(0, 1)) stmt := dbc.WithPrepare(context.TODO(), dml.NewUpdate("customer_entity").Alias("ce"). AddColumns("name", "email"). Where(dml.Column("id").Equal().PlaceHolder())) defer dmltest.Close(t, stmt) for i, record := range records { results, err := stmt.ExecContext(context.TODO(), dml.Qualify("ce", record)) assert.NoError(t, err) aff, err := results.RowsAffected() if err != nil { t.Fatalf("Result index %d with error: %s", i, err) } assert.Exactly(t, int64(1), aff) } }) t.Run("ExecContext no record", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("UPDATE `customer_entity` AS `ce` SET `name`=?, `email`=? WHERE (`id` = ?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>", 3456).WillReturnResult(sqlmock.NewResult(0, 9)) stmt := dbc.WithPrepare(context.TODO(), dml.NewUpdate("customer_entity").Alias("ce"). AddColumns("name", "email"). Where(dml.Column("id").Equal().PlaceHolder())) defer dmltest.Close(t, stmt) res, err := stmt.ExecContext(context.TODO(), "<NAME>", "<EMAIL>", 3456) assert.NoError(t, err, "failed to execute ExecContext") ra, err := res.RowsAffected() if err != nil { t.Fatal(err) } assert.Exactly(t, int64(9), ra, "Different LastInsertIDs") }) t.Run("ExecContext Records in final args", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("UPDATE `customer_entity` AS `ce` SET `name`=?, `email`=? WHERE (`id` = ?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>", 3456).WillReturnResult(sqlmock.NewResult(0, 9)) stmt := dbc.WithPrepare(context.TODO(), dml.NewUpdate("customer_entity").Alias("ce"). AddColumns("name", "email"). Where(dml.Column("id").Equal().PlaceHolder())) defer dmltest.Close(t, stmt) p := &dmlPerson{ ID: 3456, Name: "<NAME>", Email: null.MakeString("<EMAIL>"), StoreID: 3, } res, err := stmt.ExecContext(context.TODO(), dml.Qualify("", p)) assert.NoError(t, err, "failed to execute ExecContext") ra, err := res.RowsAffected() if err != nil { t.Fatal(err) } assert.Exactly(t, int64(9), ra, "Different LastInsertIDs") }) t.Run("ExecArgs One Row", func(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) defer dmltest.MockClose(t, dbc, dbMock) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta("UPDATE `customer_entity` AS `ce` SET `name`=?, `email`=? WHERE (`id` = ?)")) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>", 3456).WillReturnResult(sqlmock.NewResult(0, 11)) prep.ExpectExec().WithArgs("<NAME>", "<EMAIL>", 3457).WillReturnResult(sqlmock.NewResult(0, 21)) stmt := dbc.WithPrepare(context.TODO(), dml.NewUpdate("customer_entity").Alias("ce"). AddColumns("name", "email"). Where(dml.Column("id").Equal().PlaceHolder())) defer dmltest.Close(t, stmt) tests := []struct { name string email string id int rowsAffected int64 }{ {"<NAME>", "<EMAIL>", 3456, 11}, {"<NAME>", "<EMAIL>", 3457, 21}, } for i, test := range tests { res, err := stmt.ExecContext(context.TODO(), test.name, test.email, test.id) if err != nil { t.Fatalf("Index %d => %+v", i, err) } ra, err := res.RowsAffected() if err != nil { t.Fatalf("Result index %d with error: %s", i, err) } assert.Exactly(t, test.rowsAffected, ra, "Index %d has different LastInsertIDs", i) stmt.Reset() } }) } // Make sure that type salesInvoice implements interface. var _ dml.ColumnMapper = (*salesInvoice)(nil) // salesInvoice represents just a demo record. type salesInvoice struct { EntityID int64 // Auto Increment State string // processing, pending, shipped, StoreID int64 CustomerID int64 GrandTotal null.Float64 } func (so *salesInvoice) MapColumns(cm *dml.ColumnMap) error { for cm.Next(6) { switch c := cm.Column(); c { case "entity_id", "0": cm.Int64(&so.EntityID) case "state", "1": cm.String(&so.State) case "store_id", "2": cm.Int64(&so.StoreID) case "customer_id", "3": cm.Int64(&so.CustomerID) case "alias_customer_id", "4": // Here can be a special treatment implemented like encoding to JSON // or encryption cm.Int64(&so.CustomerID) case "grand_total", "5": cm.NullFloat64(&so.GrandTotal) default: return errors.NotFound.Newf("[dml_test] Column %q not found", c) } } return cm.Err() } func TestArguments_WithQualifiedColumnsAliases(t *testing.T) { dbc, dbMock := dmltest.MockDB(t) prep := dbMock.ExpectPrepare(dmltest.SQLMockQuoteMeta( "UPDATE `sales_invoice` SET `state`=?, `customer_id`=?, `grand_total`=? WHERE (`shipping_method` IN ('DHL','UPS')) AND (`entity_id` = ?)", )) prep.ExpectExec().WithArgs( "pending", int64(5678), 31.41459, 21). WillReturnResult(sqlmock.NewResult(0, 1)) prep.ExpectExec().WithArgs( "processing", int64(8912), nil, 32). WillReturnResult(sqlmock.NewResult(0, 1)) // </ignore_this> // Our objects which should update the columns in the database table // `sales_invoice`. collection := []*salesInvoice{ {21, "pending", 5, 5678, null.MakeFloat64(31.41459)}, {32, "processing", 7, 8912, null.Float64{}}, } // Create the multi update statement stmt := dbc.WithPrepare(context.TODO(), dml.NewUpdate("sales_invoice"). AddColumns("state", "customer_id", "grand_total"). Where( dml.Column("shipping_method").In().Strs("DHL", "UPS"), // For all clauses the same restriction dml.Column("entity_id").PlaceHolder(), // Int64() acts as a place holder )) stmtExec := stmt.WithQualifiedColumnsAliases("state", "alias_customer_id", "grand_total", "entity_id") for i, record := range collection { results, err := stmtExec.ExecContext(context.TODO(), dml.Qualify("sales_invoice", record)) assert.NoError(t, err) ra, err := results.RowsAffected() assert.NoError(t, err, "Index %d", i) assert.Exactly(t, int64(1), ra, "Index %d", i) stmtExec.Reset() } dbMock.ExpectClose() dmltest.Close(t, dbc) assert.NoError(t, dbMock.ExpectationsWereMet()) } func TestUpdate_BindRecord(t *testing.T) { ce := &categoryEntity{ EntityID: 678, AttributeSetID: 6, ParentID: "p456", Path: null.MakeString("3/4/5"), } t.Run("1 WHERE", func(t *testing.T) { u := dml.NewUpdate("catalog_category_entity"). AddColumns("attribute_set_id", "parent_id", "path"). Where(dml.Column("entity_id").Greater().PlaceHolder()). WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", ce)) compareToSQL(t, u, errors.NoKind, "UPDATE `catalog_category_entity` SET `attribute_set_id`=?, `parent_id`=?, `path`=? WHERE (`entity_id` > ?)", "UPDATE `catalog_category_entity` SET `attribute_set_id`=6, `parent_id`='p456', `path`='3/4/5' WHERE (`entity_id` > 678)", int64(6), "p456", "3/4/5", int64(678), ) }) t.Run("2 WHERE", func(t *testing.T) { u := dml.NewUpdate("catalog_category_entity"). AddColumns("attribute_set_id", "parent_id", "path"). Where( dml.Column("x").In().Int64s(66, 77), dml.Column("entity_id").Greater().PlaceHolder(), ).WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", ce)) compareToSQL(t, u, errors.NoKind, "UPDATE `catalog_category_entity` SET `attribute_set_id`=?, `parent_id`=?, `path`=? WHERE (`x` IN (66,77)) AND (`entity_id` > ?)", "UPDATE `catalog_category_entity` SET `attribute_set_id`=6, `parent_id`='p456', `path`='3/4/5' WHERE (`x` IN (66,77)) AND (`entity_id` > 678)", int64(6), "p456", "3/4/5", int64(678), ) }) t.Run("3 WHERE", func(t *testing.T) { u := dml.NewUpdate("catalog_category_entity"). AddColumns("attribute_set_id", "parent_id", "path"). Where( dml.Column("entity_id").Greater().PlaceHolder(), dml.Column("x").In().Int64s(66, 77), dml.Column("y").Greater().Int64(99), ).WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", ce)) compareToSQL(t, u, errors.NoKind, "UPDATE `catalog_category_entity` SET `attribute_set_id`=?, `parent_id`=?, `path`=? WHERE (`entity_id` > ?) AND (`x` IN (66,77)) AND (`y` > 99)", "UPDATE `catalog_category_entity` SET `attribute_set_id`=6, `parent_id`='p456', `path`='3/4/5' WHERE (`entity_id` > 678) AND (`x` IN (66,77)) AND (`y` > 99)", int64(6), "p456", "3/4/5", int64(678), ) }) t.Run("with alias table name", func(t *testing.T) { // A fictional table statement which already reflects future JOIN // implementation. u := dml.NewUpdate("catalog_category_entity").Alias("ce"). AddColumns("attribute_set_id", "parent_id", "path"). Where( dml.Column("ce.entity_id").Greater().PlaceHolder(), // 678 dml.Column("cpe.entity_id").In().Int64s(66, 77), dml.Column("cpei.attribute_set_id").Equal().PlaceHolder(), // 6 ).WithDBR(dbMock{}).TestWithArgs(dml.Qualify("", ce), dml.Qualify("cpei", ce)) compareToSQL(t, u, errors.NoKind, "UPDATE `catalog_category_entity` AS `ce` SET `attribute_set_id`=?, `parent_id`=?, `path`=? WHERE (`ce`.`entity_id` > ?) AND (`cpe`.`entity_id` IN (66,77)) AND (`cpei`.`attribute_set_id` = ?)", "UPDATE `catalog_category_entity` AS `ce` SET `attribute_set_id`=6, `parent_id`='p456', `path`='3/4/5' WHERE (`ce`.`entity_id` > 678) AND (`cpe`.`entity_id` IN (66,77)) AND (`cpei`.`attribute_set_id` = 6)", int64(6), "p456", "3/4/5", int64(678), int64(6), ) }) } func TestUpdate_Clone(t *testing.T) { dbc, dbMock := dmltest.MockDB(t, dml.WithLogger(log.BlackHole{}, func() string { return "uniqueID" })) defer dmltest.MockClose(t, dbc, dbMock) t.Run("nil", func(t *testing.T) { var d *dml.Update d2 := d.Clone() assert.Nil(t, d) assert.Nil(t, d2) }) t.Run("non-nil", func(t *testing.T) { d := dml.NewUpdate("catalog_category_entity").Alias("ce"). AddColumns("attribute_set_id", "parent_id", "path"). Where( dml.Column("ce.entity_id").Greater().PlaceHolder(), // 678 dml.Column("cpe.entity_id").In().Int64s(66, 77), dml.Column("cpei.attribute_set_id").Equal().PlaceHolder(), // 6 ) d2 := d.Clone() notEqualPointers(t, d, d2) notEqualPointers(t, d, d2) notEqualPointers(t, d.BuilderConditional.Wheres, d2.BuilderConditional.Wheres) notEqualPointers(t, d.SetClauses, d2.SetClauses) // assert.Exactly(t, d.db, d2.db) // how to test this? }) } <|start_filename|>sql/mycanal/canal_main.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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 ignore // This tool helps you debugging and understanding the binary log. package main import ( "context" "flag" "fmt" "os" "strconv" "sync" "time" "github.com/corestoreio/log" "github.com/corestoreio/log/logw" "github.com/corestoreio/pkg/sql/ddl" "github.com/corestoreio/pkg/sql/dml" "github.com/corestoreio/pkg/sql/mycanal" "github.com/corestoreio/pkg/util/conv" "github.com/jroimartin/gocui" ) var _ mycanal.RowsEventHandler = (*genericEventDump)(nil) type genericEventDump struct { g *gocui.Gui } func (ge *genericEventDump) Do(_ context.Context, action string, table *ddl.Table, rows [][]interface{}) error { ge.g.Update(func(g *gocui.Gui) error { vr, err := g.View("right") if err != nil { return err } _, err = fmt.Fprintf(vr, "%q => %q\n", action, table.Name) cols := table.Columns maxLen := 0 for _, c := range cols { if l := len(c.Field); l > maxLen { maxLen = l } } for _, row := range rows { for ci, cell := range row { _, err = fmt.Fprintf(vr, "%-"+strconv.FormatInt(int64(maxLen), 10)+"s: %T %q\n", cols[ci].Field, cell, conv.ToString(cell)) } fmt.Fprint(vr, "\n") } fmt.Fprint(vr, "=======================================\n") return err }) return nil } func (ge *genericEventDump) Complete(_ context.Context) error { return nil // errors.NewFatalf("[test] What is incomplete?") } func (ge *genericEventDump) String() string { return "genericEventDump" } // this program creates a terminal UI with two panels. on the left you see the // debug logging outout and on the right panel you see the incoming binary log // data. Use Ctrl+C to exit the program. During exit it will panic to print the last log entries from the log buffer. func main() { // export CS_DSN=mysql://root:PASSWORD@localhost:3306/DATABASE_NAME?BinlogSlaveId=100 var masterStatusFile string var masterStatusPosition uint flag.StringVar(&masterStatusFile, "master_file", "", "File name from the SHOW MASTER STATUS command") flag.UintVar(&masterStatusPosition, "master_pos", 4, "Position from the SHOW MASTER STATUS command") flag.Parse() logBuf := new(log.MutexBuffer) syncLog := logw.NewLog( logw.WithWriter(logBuf), logw.WithLevel(logw.LevelDebug), ) c, err := mycanal.NewCanal(os.Getenv(dml.EnvDSN), mycanal.WithMySQL(), &mycanal.Options{ Log: syncLog, OnClose: func(db *dml.ConnPool) (err error) { return nil }, }) mustCheckErr(err) ctx, cancel := context.WithCancel(context.Background()) g, err := gocui.NewGui(gocui.OutputNormal) mustCheckErr(err) defer g.Close() c.RegisterRowsEventHandler(nil, &genericEventDump{g: g}) g.SetManagerFunc(func(g *gocui.Gui) error { maxX, maxY := g.Size() if v, err := g.SetView("left", 0, 0, maxX/2-1-10, maxY-1); err != nil && err != gocui.ErrUnknownView { return err } else { v.Wrap = true v.Autoscroll = true } if v, err := g.SetView("right", maxX/2-10, 0, maxX-1, maxY-1); err != nil && err != gocui.ErrUnknownView { return err } else { v.Wrap = true v.Autoscroll = true } g.SetCurrentView("right") return nil }) mustCheckErr(g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error { cancel() if err := c.Close(); err != nil { return err } return gocui.ErrQuit })) mustCheckErr(g.SetKeybinding("right", gocui.KeyCtrlW, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error { v.Clear() return nil })) var wg sync.WaitGroup go func() { defer wg.Done() wg.Add(1) for { select { case <-ctx.Done(): return case <-time.After(750 * time.Millisecond): g.Update(func(g *gocui.Gui) error { vl, err := g.View("left") if err != nil { return err } _, err = logBuf.WriteTo(vl) return err }) } } }() go func() { defer wg.Done() wg.Add(1) if err := c.Start(ctx); err != nil { panic("binlog_main_streamer.GetEvent.error " + err.Error()) } // todo terminate this goroutine }() if err := g.MainLoop(); err != nil && err != gocui.ErrQuit { panic(fmt.Sprintf("%+v", err)) } wg.Wait() // we have to panic here to show the following output, when using println // gocui would just clear the screen and the output is gone. panic("All goroutines terminated.\nDEBUG BUFFER\n" + logBuf.String()) } func mustCheckErr(err error) { if err != nil { panic(fmt.Sprintf("%+v", err)) } } <|start_filename|>sql/dml/expression.go<|end_filename|> // Copyright 2015-present, Cyrill @ <EMAIL> and the CoreStore contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License at distributed on an "AS IS" BASIS, // WITHOUT 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 dml import ( "bytes" "strings" "github.com/corestoreio/errors" "github.com/corestoreio/pkg/util/bufferpool" ) // write writes the strings into `w` and correctly handles the place holder // repetition depending on the number of arguments. func writeExpression(w *bytes.Buffer, expression string, args []interface{}) (phCount int, err error) { phCount = strings.Count(expression, placeHolderStr) if phCount == 0 || len(args) == 0 { // fast path _, err = w.WriteString(expression) } else { err = writeInterpolate(w, expression, args) } return } // SQLIfNull creates an IFNULL expression. Argument count can be either 1, 2 or // 4. A single expression can contain a qualified or unqualified identifier. See // the examples. // // IFNULL(expr1,expr2) If expr1 is not NULL, IFNULL() returns expr1; otherwise // it returns expr2. IFNULL() returns a numeric or string value, depending on // the context in which it is used. func SQLIfNull(expression ...string) *Condition { return &Condition{ Left: sqlIfNull(expression), IsLeftExpression: true, } } func sqlIfNull(expression []string) string { buf := bufferpool.Get() // way faster than strings.Builder switch len(expression) { case 1: sqlIfNullQuote2(buf, expression[0], sqlStrNullUC) case 2: // Input: dml.SQLIfNull(col1,col2) // Output: IFNULL(`col1`, `col2`) // Input: dml.SQLIfNull(expr1,expr2) // Output: IFNULL(expr1, expr1) sqlIfNullQuote2(buf, expression...) case 4: // Input: dml.SQLIfNull(table1,col1,table2,col2) // Output: IFNULL(`table1`.`col1`, `table2`.`col2`) sqlIfNullQuote4(buf, expression...) default: panic(errors.NotValid.Newf("[dml] Invalid number of arguments. Max 4 arguments allowed, got: %v", expression)) } ret := buf.String() bufferpool.Put(buf) return ret } func sqlIfNullQuote2(w *bytes.Buffer, expressionAlias ...string) { w.WriteString("IFNULL(") if isValidIdentifier(expressionAlias[0]) == 0 { Quoter.WriteIdentifier(w, expressionAlias[0]) } else { w.WriteString(expressionAlias[0]) } w.WriteByte(',') if isValidIdentifier(expressionAlias[1]) == 0 { Quoter.WriteIdentifier(w, expressionAlias[1]) } else { w.WriteString(expressionAlias[1]) } w.WriteByte(')') } func sqlIfNullQuote4(w *bytes.Buffer, qualifierName ...string) { w.WriteString("IFNULL(") Quoter.writeQualifierName(w, qualifierName[0], qualifierName[1]) w.WriteByte(',') Quoter.writeQualifierName(w, qualifierName[2], qualifierName[3]) w.WriteByte(')') } // SQLIf writes a SQL IF() expression. // IF(expr1,expr2,expr3) // If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; // otherwise it returns expr3. IF() returns a numeric or string value, depending // on the context in which it is used. // Returns a []string. func SQLIf(expression, true, false string) *Condition { return &Condition{ Left: "IF((" + expression + "), " + true + ", " + false + ")", IsLeftExpression: 2 > 1, } } // SQLCase generates a CASE ... WHEN ... THEN ... ELSE ... END statement. // `value` argument can be empty. defaultValue used in the ELSE part can also be // empty and then won't get written. `compareResult` must be a balanced sliced // where index `i` represents the case part and index `i+1` the result. // If the slice is imbalanced the function assumes that the last item of compareResult // should be printed as an alias. // https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case func SQLCase(value, defaultValue string, compareResult ...string) *Condition { return &Condition{ Left: sqlCase(value, defaultValue, compareResult...), IsLeftExpression: true, } } func sqlCase(value, defaultValue string, compareResult ...string) string { if len(compareResult) < 2 { panic(errors.Fatal.Newf("[dml] SQLCase error incorrect length for compareResult: %v", compareResult)) } buf := bufferpool.Get() useAlias := len(compareResult)%2 == 1 lcr := len(compareResult) if useAlias { lcr-- buf.WriteByte('(') } buf.WriteString("CASE ") buf.WriteString(value) for i := 0; i < lcr; i += 2 { buf.WriteString(" WHEN ") buf.WriteString(compareResult[i]) buf.WriteString(" THEN ") buf.WriteString(compareResult[i+1]) } if defaultValue != "" { buf.WriteString(" ELSE ") buf.WriteString(defaultValue) } buf.WriteString(" END") if useAlias { buf.WriteByte(')') buf.WriteString(" AS ") Quoter.quote(buf, compareResult[len(compareResult)-1]) } e := buf.String() bufferpool.Put(buf) return e }
windhooked/corestoreio
<|start_filename|>src/main/java/org/jenkinsci/remoting/protocol/NetworkLayer.java<|end_filename|> /* * The MIT License * * Copyright (c) 2016, CloudBees, Inc., <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.remoting.protocol; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.OverrideMustInvoke; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.jenkinsci.remoting.util.ByteBufferQueue; /** * The lowest {@link ProtocolLayer} in a {@link ProtocolStack}. This layer is responsible for sending the output of * the protocol * to the recipient and injecting the input from the recipient into the protocol stack. * * @since 3.0 */ public abstract class NetworkLayer implements ProtocolLayer, ProtocolLayer.Send { /** * Our logger. */ private static final Logger LOGGER = Logger.getLogger(NetworkLayer.class.getName()); /** * The standard capacity for {@link ByteBuffer}s. */ private static final int CAPACITY = 8192; /** * Our {@link IOHub}. */ @NonNull private final IOHub ioHub; /** * The send queue of any data requested to send before a call to {@link #start()}. * In theory this should not be needed as the network layer will be the first layer to be * {@link ProtocolLayer#start()} * but it can simplify the other layer implementations if they can queue up data to output in their call to * {@link ProtocolLayer#init(ProtocolStack.Ptr)} which is what this queue facilitates. */ private ByteBufferQueue sendQueue; /** * The receive queue of any data received before a call to {@link #start()}. * Depending on how the network layer is implemented, we may start receiving data any time after * {@link #NetworkLayer(IOHub)} but we are not allowed to deliver it until after {@link #start()}. */ private ByteBufferQueue recvQueue; /** * Our {@link ProtocolStack.Ptr}. */ private ProtocolStack<?>.Ptr ptr; /** * Constructor. * * @param ioHub the {@link IOHub} that we use. */ public NetworkLayer(@NonNull IOHub ioHub) { this.ioHub = ioHub; this.recvQueue = new ByteBufferQueue(CAPACITY); this.sendQueue = new ByteBufferQueue(CAPACITY); } /** * {@inheritDoc} */ @Override public final void doSend(@NonNull ByteBuffer data) throws IOException { ByteBufferQueue sendQueue = this.sendQueue; if (ptr == null) { sendQueue.put(data); } else { if (sendQueue != null && sendQueue.hasRemaining()) { sendQueue.put(data); flushSendQueue(); } else { write(data); } } } /** * SPI: Perform the actual write to the recipient. This method should be non-blocking. The data should be enqueued * and written in the order of calls to write()}. * * @param data the data received. Any data consumed from the {@link ByteBuffer} can be assumed as processed. * Any data not consumed from the {@link ByteBuffer} will be the responsibility of the caller * to resubmit in subsequent calls. * @throws IOException if something goes wrong */ protected abstract void write(@NonNull ByteBuffer data) throws IOException; /** * SPI: Performed the handling of te actual read from the recipient. * * @param data the data received. Any data consumed from the {@link ByteBuffer} can be assumed as processed. * Any data not consumed from the {@link ByteBuffer} will be the responsibility of the caller * to resubmit in subsequent calls. * @throws IOException if something goes wrong */ protected final void onRead(ByteBuffer data) throws IOException { ByteBufferQueue recvQueue = this.recvQueue; if (ptr == null) { recvQueue.put(data); } else { if (recvQueue != null && recvQueue.hasRemaining()) { recvQueue.put(data); flushRecvQueue(); } else { ptr.onRecv(data); } } } /** * SPI: Notify that the connection with the recipient is closed. */ @OverrideMustInvoke protected final void onRecvClosed() { if (ptr == null) { throw new IllegalStateException("Not initialized"); } else { if (ptr.isRecvOpen()) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "[{0}] RECV Closed", ptr.stack().name()); } try { ptr.onRecvClosed(new ClosedChannelException()); } catch (IOException e) { // ignore } } } } /** * Request the recv side to be closed. */ public abstract void doCloseRecv(); /** * SPI: Check if the recipient is open. * * @return {@code true} if the recipient is open. */ protected final boolean isRecvOpen() { if (ptr == null) { throw new IllegalStateException("Not initialized"); } return ptr.isRecvOpen(); } /** * Flush the receive queue. * * @throws IOException if something goes wrong. */ private void flushRecvQueue() throws IOException { if (recvQueue == null) { return; } ByteBuffer tmp = recvQueue.newByteBuffer(); while (recvQueue.hasRemaining()) { tmp.clear(); recvQueue.get(tmp); tmp.flip(); ptr.onRecv(tmp); } recvQueue = null; } /** * Flush the send queue. * * @throws IOException if something goes wrong. */ private void flushSendQueue() throws IOException { if (sendQueue == null) { return; } ByteBuffer tmp = sendQueue.newByteBuffer(); while (sendQueue.hasRemaining()) { tmp.clear(); sendQueue.get(tmp); tmp.flip(); while (tmp.hasRemaining()) { try { write(tmp); } catch (IOException e) { // store what ever we know was not written tmp.compact(); sendQueue.unget(tmp); throw e; } } } sendQueue = null; } /** * {@inheritDoc} */ @Override public final void init(@NonNull ProtocolStack<?>.Ptr ptr) throws IOException { if (this.ptr != null && this.ptr != ptr) { throw new IllegalStateException("Already initialized"); } this.ptr = ptr; } /** * {@inheritDoc} */ @Override @OverrideMustInvoke public void start() throws IOException { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "[{0}] Starting", ptr.stack().name()); } try { flushRecvQueue(); flushSendQueue(); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "[{0}] Started", ptr.stack().name()); } } catch (IOException e) { if (LOGGER.isLoggable(Level.FINEST)) { LogRecord record = new LogRecord(Level.FINEST, "[{0}] Could not complete start"); record.setParameters(new Object[]{ptr.stack().name()}); record.setThrown(e); LOGGER.log(record); } throw e; } } /** * Gets the {@link IOHub} that we are using. * * @return the {@link IOHub} that we are using. */ @NonNull public IOHub getIoHub() { return ioHub; } /** * SPI: Acquired a new {@link ByteBuffer} optimally sized for network read/write operations. * * @return a new {@link ByteBuffer}. */ protected ByteBuffer acquire() { return ioHub.acquire(CAPACITY); } /** * SPI: Returns a previously acquired {@link ByteBuffer} to the pool. * * @param buffer the {@link ByteBuffer}. */ protected void release(ByteBuffer buffer) { ioHub.release(buffer); } /** * SPI: Creates a new {@link ByteBuffer} optimally sized for network read/write operations. * * @return a new {@link ByteBuffer} optimally sized for network read/write operations. */ protected ByteBufferQueue newByteBufferQueue() { return new ByteBufferQueue(CAPACITY); } /** * Returns the {@link ProtocolStack} instance that we belong to. * * @return the {@link ProtocolStack} instance that we belong to. */ protected ProtocolStack<?> stack() { return ptr == null ? null : ptr.stack(); } } <|start_filename|>src/test/java/org/jenkinsci/remoting/protocol/cert/SSLContextRule.java<|end_filename|> /* * The MIT License * * Copyright (c) 2016, <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.remoting.protocol.cert; import static org.junit.Assume.assumeNoException; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509ExtendedTrustManager; import org.jenkinsci.remoting.util.VersionNumber; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class SSLContextRule implements TestRule { private final List<KeyWithChain> keys; private final List<X509CertificateRule> certificates; private final String id; private SSLContext context; private boolean validityChecking; public SSLContextRule() { this(""); } public SSLContextRule(String id) { this.keys = new ArrayList<>(); this.certificates = new ArrayList<>(); this.id = id; } private static KeyStore createKeyStore(@CheckForNull List<X509CertificateRule> certificates, @CheckForNull List<KeyWithChain> keys, @NonNull char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); int id = 1; store.load(null, password); if (certificates != null) { for (X509CertificateRule certificate : certificates) { store.setCertificateEntry("cert-" + id, certificate.certificate()); id++; } } if (keys != null) { for (KeyWithChain key : keys) { Certificate[] chain = new Certificate[key.chain.length]; for (int i = 0; i < key.chain.length; i++) { chain[i] = key.chain[i].certificate(); } try { store.setKeyEntry("alias-" + id, key.key.getPrivate(), password, chain); } catch (KeyStoreException e) { if (new VersionNumber(System.getProperty("java.specification.version")).isNewerThanOrEqualTo(new VersionNumber("11")) && e.getMessage().contains("Certificate chain is not valid")) { assumeNoException("TODO: needs triage", e); } } id++; } } return store; } private static <TYPE, SUBTYPE extends TYPE> SUBTYPE findFirst(Class<SUBTYPE> type, TYPE... options) { if (options == null) { return null; } for (TYPE option : options) { if (type.isInstance(option)) { return type.cast(option); } } return null; } public SSLContextRule as(RSAKeyPairRule key, X509CertificateRule... chain) { this.keys.add(new KeyWithChain(key, chain)); return this; } public SSLContextRule trusting(X509CertificateRule certificate) { this.certificates.add(certificate); return this; } public SSLContextRule withValidityChecking() { this.validityChecking = true; return this; } public SSLContextRule withoutValidityChecking() { this.validityChecking = false; return this; } public SSLContext context() { return context; } public String getProtocol() { return context.getProtocol(); } public Provider getProvider() { return context.getProvider(); } public SSLSocketFactory getSocketFactory() { return context.getSocketFactory(); } public SSLServerSocketFactory getServerSocketFactory() { return context.getServerSocketFactory(); } public SSLEngine createSSLEngine() { return context.createSSLEngine(); } public SSLEngine createSSLEngine(String s, int i) { return context.createSSLEngine(s, i); } public SSLSessionContext getServerSessionContext() { return context.getServerSessionContext(); } public SSLSessionContext getClientSessionContext() { return context.getClientSessionContext(); } public SSLParameters getDefaultSSLParameters() { return context.getDefaultSSLParameters(); } public SSLParameters getSupportedSSLParameters() { return context.getSupportedSSLParameters(); } @Override public Statement apply(final Statement base, Description description) { Skip skip = description.getAnnotation(Skip.class); if (skip != null && (skip.value().length == 0 || Arrays.asList(skip.value()).contains(id))) { return base; } return new Statement() { @Override public void evaluate() throws Throwable { context = SSLContext.getInstance("TLS"); char[] password = "password".toCharArray(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(createKeyStore(null, keys, password), password); KeyManager[] keyManagers = kmf.getKeyManagers(); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(createKeyStore(certificates, null, password)); TrustManager[] trustManagers = new TrustManager[1]; trustManagers[0] = validityChecking ? new ValidityCheckingX509ExtendedTrustManager( findFirst(X509ExtendedTrustManager.class, tmf.getTrustManagers())) : findFirst( X509ExtendedTrustManager.class, tmf.getTrustManagers()); context.init(keyManagers, trustManagers, null); try { base.evaluate(); } finally { context = null; } } }; } /** * Indicate the the rule should be skipped for the annotated tests. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface Skip { String[] value() default {}; } private static class KeyWithChain { private final RSAKeyPairRule key; private final X509CertificateRule[] chain; public KeyWithChain(RSAKeyPairRule key, X509CertificateRule... chain) { this.key = key; this.chain = chain; } } } <|start_filename|>src/main/java/hudson/remoting/FileSystemJarCache.java<|end_filename|> package hudson.remoting; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.attribute.FileTime; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.jcip.annotations.GuardedBy; import org.jenkinsci.remoting.util.PathUtils; /** * {@link JarCache} that stores files in a single directory. * * @author <NAME> * @since 2.24 */ public class FileSystemJarCache extends JarCacheSupport { public final File rootDir; private final boolean touch; /** * We've reported these checksums as present on this side. */ private final Set<Checksum> notified = Collections.synchronizedSet(new HashSet<>()); /** * Cache of computer checksums for cached jars. */ @GuardedBy("itself") private final Map<String, Checksum> checksumsByPath = new HashMap<>(); //TODO: Create new IOException constructor /** * @param rootDir * Root directory. * @param touch * True to touch the cached jar file that's used. This enables external LRU based cache * eviction at the expense of increased I/O. * @throws IllegalArgumentException * Root directory is {@code null} or not writable. */ public FileSystemJarCache(@NonNull File rootDir, boolean touch) { this.rootDir = rootDir; this.touch = touch; if (rootDir==null) throw new IllegalArgumentException("Root directory is null"); try { Files.createDirectories(rootDir.toPath()); } catch (IOException ex) { throw new IllegalArgumentException("Root directory not writable: " + rootDir, ex); } } @Override public String toString() { return String.format("FileSystem JAR Cache: path=%s, touch=%s", rootDir, touch); } @Override protected URL lookInCache(Channel channel, long sum1, long sum2) throws IOException, InterruptedException { File jar = map(sum1, sum2); if (jar.exists()) { LOGGER.log(Level.FINER, () -> String.format("Jar file cache hit %16X%16X",sum1,sum2)); if (touch) { Files.setLastModifiedTime(PathUtils.fileToPath(jar), FileTime.fromMillis(System.currentTimeMillis())); } if (notified.add(new Checksum(sum1,sum2))) { getJarLoader(channel).notifyJarPresence(sum1,sum2); } return jar.toURI().toURL(); } return null; } @Override @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "The file path is a generated value based on server supplied data.") protected URL retrieve(Channel channel, long sum1, long sum2) throws IOException, InterruptedException { Checksum expected = new Checksum(sum1, sum2); File target = map(sum1, sum2); if (target.exists()) { Checksum actual = fileChecksum(target); if (expected.equals(actual)) { LOGGER.fine(String.format("Jar file already exists: %s", expected)); return target.toURI().toURL(); } LOGGER.warning(String.format( "Cached file checksum mismatch: %s%nExpected: %s%n Actual: %s", target.getAbsolutePath(), expected, actual )); Files.delete(PathUtils.fileToPath(target)); synchronized (checksumsByPath) { checksumsByPath.remove(target.getCanonicalPath()); } } try { File tmp = createTempJar(target); try { try (RemoteOutputStream o = new RemoteOutputStream(new FileOutputStream(tmp))) { LOGGER.log(Level.FINE, () -> String.format("Retrieving jar file %16X%16X", sum1, sum2)); getJarLoader(channel).writeJarTo(sum1, sum2, o); } // Verify the checksum of the download. Checksum actual = Checksum.forFile(tmp); if (!expected.equals(actual)) { throw new IOException(String.format( "Incorrect checksum of retrieved jar: %s%nExpected: %s%nActual: %s", tmp.getAbsolutePath(), expected, actual)); } if (!tmp.renameTo(target)) { if (!target.exists()) { throw new IOException("Unable to create " + target + " from " + tmp); } // Even if we fail to rename, we are OK as long as the target actually exists at // this point. This can happen if two FileSystemJarCache instances share the // same cache dir. // // Verify the checksum to be sure the target is correct. actual = fileChecksum(target); if (!expected.equals(actual)) { throw new IOException(String.format( "Incorrect checksum of previous jar: %s%nExpected: %s%nActual: %s", target.getAbsolutePath(), expected, actual)); } } return target.toURI().toURL(); } finally { Files.deleteIfExists(PathUtils.fileToPath(tmp)); } } catch (IOException e) { throw new IOException("Failed to write to "+target, e); } } /** * Get file checksum calculating it or retrieving from cache. */ private Checksum fileChecksum(File file) throws IOException { String location = file.getCanonicalPath(); // When callers all request the checksum of a large jar, the first thread // will calculate the checksum and the other treads will be blocked here // until calculated to be picked up from cache right away. synchronized (checksumsByPath) { Checksum checksum = checksumsByPath.get(location); if (checksum != null) return checksum; checksum = Checksum.forFile(file); checksumsByPath.put(location, checksum); return checksum; } } @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "This path exists within a temp directory so the potential traversal is limited.") /*package for testing*/ File createTempJar(@NonNull File target) throws IOException { File parent = target.getParentFile(); Files.createDirectories(parent.toPath()); return File.createTempFile(target.getName(), "tmp", parent); } /** * Map to the cache jar file name. */ File map(long sum1, long sum2) { return new File(rootDir,String.format("%02X/%014X%016X.jar", (int)(sum1>>>(64-8)), sum1&0x00FFFFFFFFFFFFFFL, sum2)); } private static final Logger LOGGER = Logger.getLogger(FileSystemJarCache.class.getName()); }
Dohbedoh/remoting
<|start_filename|>templates/errors/500.html<|end_filename|> {% extends "base-site-fullscreen.html" %} {% block title %} Error 404 {% endblock %} {% block content %} <div class="login-page"> <div class="content"> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="header-text text-center"> <h2 class="card-title"> Error 500 </h2> <hr /> <h4 class="card-subtitle"> Server Error - <a href="/">Home</a> </h4> </div> </div> </div> </div> </div> {% include 'site_template/footer-fullscreen.html' %} </div> {% endblock content %} {% block javascripts %} <script> $(document).ready(function() { demo.checkFullPageBackgroundImage(); setTimeout(function() { // after 1000 ms we add the class animated to the login/register card $('.card').removeClass('card-hidden'); }, 700) }); </script> {% endblock %}
DouglasBragaDev2/PredicaoIrisFlowerFlask
<|start_filename|>app/src/main/java/com/gzsll/hupu/otto/UpdateContentPageEvent.java<|end_filename|> package com.gzsll.hupu.otto; /** * Created by sll on 2016/6/3. */ public class UpdateContentPageEvent { private int page; private int totalPage; public UpdateContentPageEvent(int page, int totalPage) { this.page = page; this.totalPage = totalPage; } public int getPage() { return page; } public int getTotalPage() { return totalPage; } } <|start_filename|>app/src/main/java/com/gzsll/hupu/otto/ChangeThemeEvent.java<|end_filename|> package com.gzsll.hupu.otto; /** * Created by sll on 2015/9/11. */ public class ChangeThemeEvent { } <|start_filename|>GreenDaoGenerator/src/main/java/com/gzsll/hupu/greendao/GreenDaoGenerator.java<|end_filename|> package com.gzsll.hupu.greendao; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; import java.io.File; public class GreenDaoGenerator { public static final int VERSION = 53; public static final String GREEN_DAO_CODE_PATH = "../TLint/app/src/main/java"; public static void main(String[] args) throws Exception { Schema schema = new Schema(VERSION, "com.gzsll.hupu.db"); Entity forum = schema.addEntity("Forum"); forum.addIdProperty(); forum.addStringProperty("fid"); forum.addStringProperty("name"); forum.addStringProperty("logo"); forum.addStringProperty("description"); forum.addStringProperty("backImg"); forum.addStringProperty("forumId"); forum.addStringProperty("categoryName"); forum.addIntProperty("weight"); Entity user = schema.addEntity("User"); user.addIdProperty(); user.addStringProperty("userName"); user.addStringProperty("uid"); user.addStringProperty("token"); user.addStringProperty("icon"); user.addIntProperty("sex"); user.addStringProperty("cookie"); user.addStringProperty("registerTime"); user.addStringProperty("location"); user.addStringProperty("school"); user.addStringProperty("threadUrl"); user.addStringProperty("postUrl"); user.addStringProperty("nickNameUrl"); Entity thread = schema.addEntity("Thread"); thread.addStringProperty("tid"); thread.addStringProperty("title"); thread.addStringProperty("puid"); thread.addStringProperty("fid"); thread.addStringProperty("replies"); thread.addStringProperty("userName"); thread.addStringProperty("time"); thread.addStringProperty("forumName"); thread.addIntProperty("lightReply"); thread.addIntProperty("type"); Entity threadInfo = schema.addEntity("ThreadInfo"); threadInfo.addStringProperty("tid"); threadInfo.addStringProperty("pid"); threadInfo.addIntProperty("page"); threadInfo.addStringProperty("nopic"); threadInfo.addIntProperty("postAuthorPuid"); threadInfo.addStringProperty("time"); threadInfo.addStringProperty("userImg"); threadInfo.addStringProperty("author_puid"); threadInfo.addStringProperty("username"); threadInfo.addStringProperty("fid"); threadInfo.addStringProperty("visits"); threadInfo.addStringProperty("recommend_num"); threadInfo.addStringProperty("via"); threadInfo.addStringProperty("update_info"); threadInfo.addStringProperty("content"); threadInfo.addStringProperty("title"); threadInfo.addIntProperty("totalPage"); threadInfo.addStringProperty("forumName"); Entity reply = schema.addEntity("ThreadReply"); reply.addStringProperty("tid"); reply.addStringProperty("pid"); reply.addStringProperty("puid"); reply.addStringProperty("via"); reply.addStringProperty("content"); reply.addStringProperty("create_time"); reply.addStringProperty("update_info"); reply.addIntProperty("light_count"); reply.addIntProperty("user_banned"); reply.addIntProperty("floor"); reply.addStringProperty("time"); reply.addStringProperty("userName"); reply.addStringProperty("userImg"); reply.addStringProperty("smallcontent"); reply.addStringProperty("togglecontent"); reply.addIntProperty("index"); reply.addBooleanProperty("isLight"); reply.addStringProperty("quoteHeader"); reply.addStringProperty("quoteContent"); reply.addStringProperty("quoteToggle"); reply.addIntProperty("pageIndex"); Entity readThread = schema.addEntity("ReadThread"); readThread.addIdProperty(); readThread.addStringProperty("tid"); Entity image = schema.addEntity("ImageCache"); image.addIdProperty(); image.addStringProperty("url"); image.addStringProperty("path"); File f = new File(GREEN_DAO_CODE_PATH); if (!f.exists()) { f.mkdirs(); } new DaoGenerator().generateAll(schema, f.getAbsolutePath()); } } <|start_filename|>app/src/main/java/com/gzsll/hupu/otto/AccountChangeEvent.java<|end_filename|> package com.gzsll.hupu.otto; /** * Created by sll on 2015/11/23. * 账号变化(增加或者删除) */ public class AccountChangeEvent { } <|start_filename|>app/src/main/java/com/gzsll/hupu/ui/BaseView.java<|end_filename|> package com.gzsll.hupu.ui; /** * Created by sll on 2016/3/9. */ public interface BaseView { } <|start_filename|>app/src/main/java/com/gzsll/hupu/otto/MessageReadEvent.java<|end_filename|> package com.gzsll.hupu.otto; /** * Created by sll on 2016/3/13. */ public class MessageReadEvent { } <|start_filename|>app/src/main/java/com/gzsll/hupu/ui/login/LoginContract.java<|end_filename|> package com.gzsll.hupu.ui.login; import com.gzsll.hupu.ui.BasePresenter; import com.gzsll.hupu.ui.BaseView; /** * Created by sll on 2016/5/11. */ public interface LoginContract { interface View extends BaseView { void showLoading(); void hideLoading(); void showUserNameError(String error); void showPassWordError(String error); void loginSuccess(); } interface Presenter extends BasePresenter<View> { void login(String userName, String passWord); } } <|start_filename|>app/src/main/java/com/gzsll/hupu/otto/LoginSuccessEvent.java<|end_filename|> package com.gzsll.hupu.otto; /** * Created by sll on 2015/3/9. */ public class LoginSuccessEvent { } <|start_filename|>app/src/main/java/com/gzsll/hupu/otto/GetHuPuSignEvent.java<|end_filename|> package com.gzsll.hupu.otto; /** * Created by sll on 2016/5/24. */ public class GetHuPuSignEvent { }
ajaxsun/TLint-masters
<|start_filename|>src/ReinhardLocal.cpp<|end_filename|> // ReinhardLocal.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include <string.h> #include <iostream> #include <cstdio> #include <algorithm> #include <omp.h> #include <vector> #include "ReinhardLocal.h" #include "opencl/reinhardLocal.h" using namespace hdr; ReinhardLocal::ReinhardLocal(float _key, float _sat, float _epsilon, float _phi) : Filter() { m_name = "ReinhardLocal"; key = _key; sat = _sat; epsilon = _epsilon; phi = _phi; num_mipmaps = 8; } bool ReinhardLocal::setupOpenCL(cl_context_properties context_prop[], const Params& params) { char flags[1024]; sprintf(flags, "-cl-fast-relaxed-math -D NUM_CHANNELS=%d -D WIDTH=%d -D HEIGHT=%d -D NUM_MIPMAPS=%d -D KEY=%f -D SAT=%f -D EPSILON=%f -D PHI=%f -D BUGGY_CL_GL=%d", NUM_CHANNELS, img_size.x, img_size.y, num_mipmaps, key, sat, epsilon, phi, BUGGY_CL_GL); if (!initCL(context_prop, params, reinhardLocal_kernel, flags)) { return false; } cl_int err; /////////////////////////////////////////////////////////////////kernels //computes the log average luminance of the image kernels["computeLogAvgLum"] = clCreateKernel(m_program, "computeLogAvgLum", &err); CHECK_ERROR_OCL(err, "creating computeLogAvgLum kernel", return false); //computes the next mipmap level of the provided data kernels["channel_mipmap"] = clCreateKernel(m_program, "channel_mipmap", &err); CHECK_ERROR_OCL(err, "creating channel_mipmap kernel", return false); //this kernel computes log average luminance of the image kernels["finalReduc"] = clCreateKernel(m_program, "finalReduc", &err); CHECK_ERROR_OCL(err, "creating finalReduc kernel", return false); //computes the operation to be applied to each pixel kernels["reinhardLocal"] = clCreateKernel(m_program, "reinhardLocal", &err); CHECK_ERROR_OCL(err, "creating reinhardLocal kernel", return false); //performs the actual tonemapping using the Ld_array computed in the previous function kernels["tonemap"] = clCreateKernel(m_program, "tonemap", &err); CHECK_ERROR_OCL(err, "creating tonemap kernel", return false); /////////////////////////////////////////////////////////////////kernel sizes reportStatus("\nKernels:"); kernel2DSizes("computeLogAvgLum"); kernel2DSizes("channel_mipmap"); kernel2DSizes("reinhardLocal"); kernel2DSizes("tonemap"); reportStatus("---------------------------------Kernel finalReduc:"); int num_wg = (global_sizes["computeLogAvgLum"][0]*global_sizes["computeLogAvgLum"][1]) /(local_sizes["computeLogAvgLum"][0]*local_sizes["computeLogAvgLum"][1]); reportStatus("Number of work groups in computeLogAvgLum: %lu", num_wg); size_t* local = (size_t*) calloc(2, sizeof(size_t)); size_t* global = (size_t*) calloc(2, sizeof(size_t)); local[0] = num_wg; //workgroup size for normal kernels global[0] = num_wg; local_sizes["finalReduc"] = local; global_sizes["finalReduc"] = global; reportStatus("Kernel sizes: Local=%lu Global=%lu", local[0], global[0]); /////////////////////////////////////////////////////////////////allocating memory //initialising information regarding all mipmap levels m_width = (int*) calloc(num_mipmaps, sizeof(int)); m_height = (int*) calloc(num_mipmaps, sizeof(int)); m_offset = (int*) calloc(num_mipmaps, sizeof(int)); m_offset[0] = 0; m_width[0] = img_size.x; m_height[0] = img_size.y; for (int level=1; level<num_mipmaps; level++) { m_width[level] = m_width[level-1]/2; m_height[level] = m_height[level-1]/2; m_offset[level] = m_offset[level-1] + m_width[level-1]*m_height[level-1]; } mems["lumMips"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y*2, NULL, &err); CHECK_ERROR_OCL(err, "creating logLum_Mip1 memory", return false); mems["m_width"] = clCreateBuffer(m_clContext, CL_MEM_COPY_HOST_PTR, sizeof(int)*num_mipmaps, m_width, &err); CHECK_ERROR_OCL(err, "creating m_width memory", return false); mems["m_height"] = clCreateBuffer(m_clContext, CL_MEM_COPY_HOST_PTR, sizeof(int)*num_mipmaps, m_height, &err); CHECK_ERROR_OCL(err, "creating m_height memory", return false); mems["m_offset"] = clCreateBuffer(m_clContext, CL_MEM_COPY_HOST_PTR, sizeof(int)*num_mipmaps, m_offset, &err); CHECK_ERROR_OCL(err, "creating m_offset memory", return false); mems["logAvgLum"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*num_wg, NULL, &err); CHECK_ERROR_OCL(err, "creating logAvgLum memory", return false); mems["Ld_array"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y, NULL, &err); CHECK_ERROR_OCL(err, "creating Ld_array memory", return false); if (params.opengl) { mem_images[0] = clCreateFromGLTexture2D(m_clContext, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, in_tex, &err); CHECK_ERROR_OCL(err, "creating gl input texture", return false); mem_images[1] = clCreateFromGLTexture2D(m_clContext, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, out_tex, &err); CHECK_ERROR_OCL(err, "creating gl output texture", return false); } else { cl_image_format format; format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT8; mem_images[0] = clCreateImage2D(m_clContext, CL_MEM_READ_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating input image memory", return false); mem_images[1] = clCreateImage2D(m_clContext, CL_MEM_WRITE_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating output image memory", return false); } /////////////////////////////////////////////////////////////////setting kernel arguements err = clSetKernelArg(kernels["computeLogAvgLum"], 0, sizeof(cl_mem), &mem_images[0]); err = clSetKernelArg(kernels["computeLogAvgLum"], 1, sizeof(cl_mem), &mems["lumMips"]); err = clSetKernelArg(kernels["computeLogAvgLum"], 2, sizeof(cl_mem), &mems["logAvgLum"]); err = clSetKernelArg(kernels["computeLogAvgLum"], 3, sizeof(float*)*local_sizes["computeLogAvgLum"][0]*local_sizes["computeLogAvgLum"][1], NULL); CHECK_ERROR_OCL(err, "setting computeLogAvgLum arguments", return false); err = clSetKernelArg(kernels["channel_mipmap"], 0, sizeof(cl_mem), &mems["lumMips"]); CHECK_ERROR_OCL(err, "setting channel_mipmap arguments", return false); err = clSetKernelArg(kernels["finalReduc"], 0, sizeof(cl_mem), &mems["logAvgLum"]); err = clSetKernelArg(kernels["finalReduc"], 1, sizeof(unsigned int), &num_wg); CHECK_ERROR_OCL(err, "setting finalReduc arguments", return false); err = clSetKernelArg(kernels["reinhardLocal"], 0, sizeof(cl_mem), &mems["Ld_array"]); err = clSetKernelArg(kernels["reinhardLocal"], 1, sizeof(cl_mem), &mems["lumMips"]); err = clSetKernelArg(kernels["reinhardLocal"], 2, sizeof(cl_mem), &mems["m_width"]); err = clSetKernelArg(kernels["reinhardLocal"], 3, sizeof(cl_mem), &mems["m_offset"]); err = clSetKernelArg(kernels["reinhardLocal"], 4, sizeof(cl_mem), &mems["logAvgLum"]); CHECK_ERROR_OCL(err, "setting reinhardLocal arguments", return false); err = clSetKernelArg(kernels["tonemap"], 0, sizeof(cl_mem), &mem_images[0]); err = clSetKernelArg(kernels["tonemap"], 1, sizeof(cl_mem), &mem_images[1]); err = clSetKernelArg(kernels["tonemap"], 2, sizeof(cl_mem), &mems["Ld_array"]); CHECK_ERROR_OCL(err, "setting tonemap arguments", return false); reportStatus("\n\n"); return true; } double ReinhardLocal::runCLKernels(bool recomputeMapping) { double start = omp_get_wtime(); cl_int err; if (recomputeMapping) { err = clEnqueueNDRangeKernel(m_queue, kernels["computeLogAvgLum"], 2, NULL, global_sizes["computeLogAvgLum"], local_sizes["computeLogAvgLum"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing computeLogAvgLum kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["finalReduc"], 1, NULL, &global_sizes["finalReduc"][0], &local_sizes["finalReduc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing finalReduc kernel", return false); //creating mipmaps for (int level=1; level<num_mipmaps; level++) { err = clSetKernelArg(kernels["channel_mipmap"], 1, sizeof(int), &m_width[level-1]); err = clSetKernelArg(kernels["channel_mipmap"], 2, sizeof(int), &m_offset[level-1]); err = clSetKernelArg(kernels["channel_mipmap"], 3, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["channel_mipmap"], 4, sizeof(int), &m_height[level]); err = clSetKernelArg(kernels["channel_mipmap"], 5, sizeof(int), &m_offset[level]); CHECK_ERROR_OCL(err, "setting channel_mipmap arguments", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["channel_mipmap"], 2, NULL, global_sizes["channel_mipmap"], local_sizes["channel_mipmap"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing channel_mipmap kernel", return false); } err = clEnqueueNDRangeKernel(m_queue, kernels["reinhardLocal"], 2, NULL, global_sizes["reinhardLocal"], local_sizes["reinhardLocal"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing reinhardLocal kernel", return false); } err = clEnqueueNDRangeKernel(m_queue, kernels["tonemap"], 2, NULL, global_sizes["tonemap"], local_sizes["tonemap"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing tonemap kernel", return false); err = clFinish(m_queue); CHECK_ERROR_OCL(err, "running kernels", return false); return omp_get_wtime() - start; } bool ReinhardLocal::cleanupOpenCL() { clReleaseMemObject(mem_images[0]); clReleaseMemObject(mem_images[1]); clReleaseMemObject(mems["Ld_array"]); clReleaseMemObject(mems["lumMips"]); clReleaseMemObject(mems["m_width"]); clReleaseMemObject(mems["m_height"]); clReleaseMemObject(mems["m_offset"]); clReleaseMemObject(mems["logAvgLum"]); clReleaseKernel(kernels["computeLogAvgLum"]); clReleaseKernel(kernels["channel_mipmap"]); clReleaseKernel(kernels["finalReduc"]); clReleaseKernel(kernels["reinhardLocal"]); clReleaseKernel(kernels["tonemap"]); releaseCL(); return true; } bool ReinhardLocal::runReference(uchar* input, uchar* output) { // Check for cached result if (m_reference.data) { memcpy(output, m_reference.data, img_size.x*img_size.y*NUM_CHANNELS); reportStatus("Finished reference (cached)"); return true; } reportStatus("Running reference"); float** mipmap_pyramid = (float**) calloc(num_mipmaps, sizeof(float*)); //the complete mipmap pyramid int2* mipmap_sizes = (int2*) calloc(num_mipmaps, sizeof(int2)); //width and height of each of the mipmap mipmap_sizes[0] = img_size; float logAvgLum = 0.f; float lum = 0.f; int2 pos; mipmap_pyramid[0] = (float*) calloc(img_size.x*img_size.y, sizeof(float)); for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { lum = getPixelLuminance(input, img_size, pos); mipmap_pyramid[0][pos.x + pos.y*img_size.x] = lum; logAvgLum += log(lum + 0.000001); } } logAvgLum = exp(logAvgLum/((float)(img_size.x*img_size.y))); float factor = key/logAvgLum; float scale_sq[num_mipmaps-1]; float k[num_mipmaps-1]; //product of multiple constants for (int i=1; i<num_mipmaps; i++) { mipmap_pyramid[i] = mipmap(mipmap_pyramid[i-1], mipmap_sizes[i-1]); mipmap_sizes[i] = (int2){mipmap_sizes[i-1].x/2, mipmap_sizes[i-1].y/2}; k[i] = pow(2.f, phi)*key/pow(pow(2, i-1), 2); } int2 centre; int2 surround; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { float local_logAvgLum = 0.f; surround.x = pos.x; surround.y = pos.y; float v, centre_logAvgLum, surround_logAvgLum, cs_diff; for (int i=0; i<num_mipmaps-1; i++) { centre.x = surround.x; centre.y = surround.y; surround.x = centre.x/2; surround.y = centre.y/2; centre_logAvgLum = getValue(mipmap_pyramid[i], mipmap_sizes[i], centre)*factor; surround_logAvgLum = getValue(mipmap_pyramid[i+1], mipmap_sizes[i+1], surround)*factor; cs_diff = centre_logAvgLum - surround_logAvgLum; cs_diff = cs_diff >= 0 ? cs_diff : -cs_diff; v = cs_diff/(k[i] + centre_logAvgLum); if (v > epsilon) { local_logAvgLum = centre_logAvgLum; break; } else local_logAvgLum = surround_logAvgLum; } float3 rgb, xyz; rgb.x = getPixel(input, img_size, pos, 0); rgb.y = getPixel(input, img_size, pos, 1); rgb.z = getPixel(input, img_size, pos, 2); xyz = RGBtoXYZ(rgb); float Ld = xyz.y*factor/(1.f + local_logAvgLum); rgb.x = (pow(rgb.x/xyz.y, sat) * Ld)*PIXEL_RANGE; rgb.y = (pow(rgb.y/xyz.y, sat) * Ld)*PIXEL_RANGE; rgb.z = (pow(rgb.z/xyz.y, sat) * Ld)*PIXEL_RANGE; setPixel(output, img_size, pos, 0, rgb.x); setPixel(output, img_size, pos, 1, rgb.y); setPixel(output, img_size, pos, 2, rgb.z); } } reportStatus("Finished reference"); // Cache result m_reference.width = img_size.x; m_reference.height = img_size.y; m_reference.data = new uchar[img_size.x*img_size.y*NUM_CHANNELS]; memcpy(m_reference.data, output, img_size.x*img_size.y*NUM_CHANNELS); return true; } <|start_filename|>android/src/com/uob/achohan/hdr/CustomSpinnerAdapter.java<|end_filename|> package com.uob.achohan.hdr; import java.util.List; import android.app.Activity; 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; public class CustomSpinnerAdapter extends ArrayAdapter<String> { Context context; int layoutResID; String[] spinnerData; public CustomSpinnerAdapter(Context context, int layoutResourceID, String[] spinnerDataList) { super(context, layoutResourceID, spinnerDataList); this.context=context; this.layoutResID=layoutResourceID; this.spinnerData=spinnerDataList; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub return getCustomView(position, convertView, parent); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub return getCustomView(position, convertView, parent); } public View getCustomView(int position, View convertView, ViewGroup parent) { View row=convertView; TextView optionName; if(row==null) { LayoutInflater inflater=((Activity)context).getLayoutInflater(); row=inflater.inflate(layoutResID, parent, false); optionName = (TextView)row.findViewById(R.id.text_main_name); row.setTag(optionName); } else optionName = (TextView)row.getTag(); String spinnerItem = spinnerData[position]; optionName.setText(spinnerItem); return row; } } <|start_filename|>android/jni/Android.mk<|end_filename|> # Android.mk (HDR) # Copyright (c) 2014, <NAME>, # University of Bristol. All rights reserved. # # This program is provided under a three-clause BSD license. For full # license terms please see the LICENSE file distributed with this # source code. LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) SRC_PATH := ../../src LOCAL_CFLAGS += -I$(SRC_PATH) -g -Wno-deprecated-declarations LOCAL_CFLAGS += -DSHOW_REFERENCE_PROGRESS=1 LOCAL_CFLAGS += -fopenmp LOCAL_LDFLAGS += -fopenmp LOCAL_MODULE := hdr LOCAL_SRC_FILES := hdr.cpp \ $(SRC_PATH)/Filter.cpp \ $(SRC_PATH)/HistEq.cpp \ $(SRC_PATH)/GradDom.cpp \ $(SRC_PATH)/ReinhardLocal.cpp \ $(SRC_PATH)/ReinhardGlobal.cpp LOCAL_LDLIBS := -landroid -llog -ljnigraphics -lOpenCL -lEGL -lGLESv2 LOCAL_STATIC_LIBRARIES := android_native_app_glue include $(BUILD_SHARED_LIBRARY) $(call import-module,android/native_app_glue) <|start_filename|>src/Filter.h<|end_filename|> // Filter.h (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #pragma once #include <map> #include <math.h> #include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdarg.h> #include <CL/cl.h> #include <CL/cl_gl.h> #include <omp.h> #ifdef __ANDROID_API__ #include <GLES/gl.h> #define BUGGY_CL_GL 1 //consult the read-me #else #include <GL/gl.h> #define BUGGY_CL_GL 0 #endif #define METHOD_REFERENCE (1<<1) #define METHOD_OPENCL (1<<2) #define PIXEL_RANGE 255 //8-bit #define NUM_CHANNELS 4 //RGBA #define CHECK_ERROR_OCL(err, op, action) \ if (err != CL_SUCCESS) { \ reportStatus("Error during operation '%s' (%d)", op, err); \ releaseCL(); \ action; \ } namespace hdr { typedef unsigned char uchar; typedef struct { int x, y; } int2; typedef struct { uchar* data; size_t width, height; } Image; typedef struct { float x; float y; float z; } float3; class Filter { public: typedef struct _Params_ { cl_device_type type; cl_uint platformIndex, deviceIndex; bool opengl, verify; _Params_() { type = CL_DEVICE_TYPE_ALL; opengl = false; deviceIndex = 0; platformIndex = 0; verify = false; } } Params; public: Filter(); virtual ~Filter(); virtual void clearReferenceCache(); virtual const char* getName() const; //initialise OpenCL kernels and memory objects and anything else which remains the same for each frame in the stream virtual bool setupOpenCL(cl_context_properties context_prop[], const Params& params) = 0; //acquire OpenGL objects, execute kernels and release the objects again virtual bool runOpenCL(bool recomputeMapping=true); //transfer data from input to the GPU, execute kernels and read the output from the GPU virtual bool runOpenCL(uchar* input, uchar* output, bool recomputeMapping=true); //execute the OpenCL kernels virtual double runCLKernels(bool recomputeMapping) = 0; //release all the kernels and memory objects virtual bool cleanupOpenCL() = 0; virtual bool runReference(uchar* input, uchar* output) = 0; //compute kernel sizes depending on the hardware being used virtual bool kernel1DSizes(const char* kernel_name); virtual bool kernel2DSizes(const char* kernel_name); //set image properties virtual void setImageSize(int width, int height); virtual void setImageTextures(GLuint input_texture, GLuint output_texture); virtual void setStatusCallback(int (*callback)(const char*, va_list args)); protected: const char *m_name; Image m_reference; int (*m_statusCallback)(const char*, va_list args); void reportStatus(const char *format, ...) const; virtual bool verify(uchar* input, uchar* output, float tolerance=1.f, float maxErrorPercent=0.05); cl_device_id m_device; cl_context m_clContext; cl_command_queue m_queue; cl_program m_program; cl_mem mem_images[2]; size_t max_cu; //max compute units std::map<std::string, cl_mem> mems; std::map<std::string, cl_kernel> kernels; std::map<std::string, size_t*> local_sizes; std::map<std::string, size_t*> global_sizes; int2 img_size; GLuint in_tex; GLuint out_tex; bool initCL(cl_context_properties context_prop[], const Params& params, const char *source, const char *options); void releaseCL(); }; //timing utils double getCurrentTime(); //image utils float* mipmap(float* input, int2 input_size, int level=1); float clamp(float x, float min, float max); float getPixelLuminance(uchar* image, int2 image_size, int2 pixel_pos); float getValue(float* data, int2 size, int2 pos); float getPixel(uchar* data, int2 img_size, int2 pixel_pos, int c); void setPixel(uchar* data, int2 img_size, int2 pixel_pos, int c, float value); //pixel conversion float3 RGBtoHSV(float3 rgb); float3 HSVtoRGB(float3 hsv); float3 RGBtoXYZ(float3 rgb); float3 XYZtoRGB(float3 xyz); } <|start_filename|>android/src/com/uob/achohan/hdr/MyGLSurfaceView.java<|end_filename|> // MyGLSurfaceView.java (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. package com.uob.achohan.hdr; import android.content.Context; import android.graphics.Point; import android.hardware.Camera.Size; import android.opengl.GLSurfaceView; import android.util.AttributeSet; import android.view.SurfaceHolder; /** * A view container where OpenGL ES graphics can be drawn on screen. * This view can also be used to capture touch events, such as a user * interacting with drawn objects. */ public class MyGLSurfaceView extends GLSurfaceView { private final MyGLRenderer mRenderer; public MyGLSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); mRenderer = new MyGLRenderer(this); setEGLContextClientVersion (2); setRenderer(mRenderer); setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } public void surfaceCreated ( SurfaceHolder holder ) { super.surfaceCreated ( holder ); } public void surfaceDestroyed ( SurfaceHolder holder ) { mRenderer.close(); super.surfaceDestroyed ( holder ); } public void surfaceChanged ( SurfaceHolder holder, int format, int w, int h ) { super.surfaceChanged ( holder, format, w, h ); } public void setDisplayDim(Point displayDim) { mRenderer.setDisplayDim(displayDim); } public void setHDR(int option) { switch(option) { case 0: mRenderer.setHDR(true); break; case 1: mRenderer.setHDR(false); break; } } } <|start_filename|>android/jni/Application.mk<|end_filename|> # Application.mk (HDR) # Copyright (c) 2014, <NAME>, # University of Bristol. All rights reserved. # # This program is provided under a three-clause BSD license. For full # license terms please see the LICENSE file distributed with this # source code. APP_ABI := armeabi-v7a APP_PLATFORM := android-19 APP_STL := gnustl_static <|start_filename|>src/HistEq.h<|end_filename|> // HistEq.h (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "Filter.h" namespace hdr { class HistEq : public Filter { public: HistEq(); virtual bool setupOpenCL(cl_context_properties context_prop[], const Params& params); virtual double runCLKernels(bool recomputeMapping); virtual bool cleanupOpenCL(); virtual bool runReference(uchar* input, uchar* output); }; } <|start_filename|>src/ReinhardGlobal.cpp<|end_filename|> // ReinhardGlobal.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "ReinhardGlobal.h" #include "opencl/reinhardGlobal.h" using namespace hdr; ReinhardGlobal::ReinhardGlobal(float _key, float _sat) : Filter() { m_name = "ReinhardGlobal"; key = _key; sat = _sat; } bool ReinhardGlobal::setupOpenCL(cl_context_properties context_prop[], const Params& params) { char flags[1024]; sprintf(flags, "-cl-fast-relaxed-math -D NUM_CHANNELS=%d -D WIDTH=%d -D HEIGHT=%d -D KEY=%f -D SAT=%f -D BUGGY_CL_GL=%d", NUM_CHANNELS, img_size.x, img_size.y, key, sat, BUGGY_CL_GL); if (!initCL(context_prop, params, reinhardGlobal_kernel, flags)) return false; cl_int err; /////////////////////////////////////////////////////////////////kernels //this kernel computes log average luminance of the image kernels["computeLogAvgLum"] = clCreateKernel(m_program, "computeLogAvgLum", &err); CHECK_ERROR_OCL(err, "creating computeLogAvgLum kernel", return false); //this kernel computes log average luminance of the image kernels["finalReduc"] = clCreateKernel(m_program, "finalReduc", &err); CHECK_ERROR_OCL(err, "creating finalReduc kernel", return false); //performs the reinhard global tone mapping operator kernels["reinhardGlobal"] = clCreateKernel(m_program, "reinhardGlobal", &err); CHECK_ERROR_OCL(err, "creating reinhardGlobal kernel", return false); /////////////////////////////////////////////////////////////////kernel sizes reportStatus("\nKernels:"); kernel2DSizes("computeLogAvgLum"); kernel2DSizes("reinhardGlobal"); reportStatus("---------------------------------Kernel finalReduc:"); int num_wg = (global_sizes["computeLogAvgLum"][0]*global_sizes["computeLogAvgLum"][1]) /(local_sizes["computeLogAvgLum"][0]*local_sizes["computeLogAvgLum"][1]); reportStatus("Number of work groups in computeLogAvgLum: %lu", num_wg); size_t* local = (size_t*) calloc(2, sizeof(size_t)); size_t* global = (size_t*) calloc(2, sizeof(size_t)); local[0] = num_wg; //workgroup size for normal kernels global[0] = num_wg; local_sizes["finalReduc"] = local; global_sizes["finalReduc"] = global; reportStatus("Kernel sizes: Local=%lu Global=%lu", local[0], global[0]); /////////////////////////////////////////////////////////////////allocating memory mems["logAvgLum"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*num_wg, NULL, &err); CHECK_ERROR_OCL(err, "creating logAvgLum memory", return false); mems["Lwhite"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*num_wg, NULL, &err); CHECK_ERROR_OCL(err, "creating Lwhite memory", return false); if (params.opengl) { mem_images[0] = clCreateFromGLTexture2D(m_clContext, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, in_tex, &err); CHECK_ERROR_OCL(err, "creating gl input texture", return false); mem_images[1] = clCreateFromGLTexture2D(m_clContext, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, out_tex, &err); CHECK_ERROR_OCL(err, "creating gl output texture", return false); } else { cl_image_format format; format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT8; mem_images[0] = clCreateImage2D(m_clContext, CL_MEM_READ_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating input image memory", return false); mem_images[1] = clCreateImage2D(m_clContext, CL_MEM_WRITE_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating output image memory", return false); } /////////////////////////////////////////////////////////////////setting kernel arguements err = clSetKernelArg(kernels["computeLogAvgLum"], 0, sizeof(cl_mem), &mem_images[0]); err = clSetKernelArg(kernels["computeLogAvgLum"], 1, sizeof(cl_mem), &mems["logAvgLum"]); err = clSetKernelArg(kernels["computeLogAvgLum"], 2, sizeof(cl_mem), &mems["Lwhite"]); err = clSetKernelArg(kernels["computeLogAvgLum"], 3, sizeof(float*)*local_sizes["computeLogAvgLum"][0]*local_sizes["computeLogAvgLum"][1], NULL); err = clSetKernelArg(kernels["computeLogAvgLum"], 4, sizeof(float*)*local_sizes["computeLogAvgLum"][0]*local_sizes["computeLogAvgLum"][1], NULL); CHECK_ERROR_OCL(err, "setting computeLogAvgLum arguments", return false); err = clSetKernelArg(kernels["finalReduc"], 0, sizeof(cl_mem), &mems["logAvgLum"]); err = clSetKernelArg(kernels["finalReduc"], 1, sizeof(cl_mem), &mems["Lwhite"]); err = clSetKernelArg(kernels["finalReduc"], 2, sizeof(unsigned int), &num_wg); CHECK_ERROR_OCL(err, "setting finalReduc arguments", return false); err = clSetKernelArg(kernels["reinhardGlobal"], 0, sizeof(cl_mem), &mem_images[0]); err = clSetKernelArg(kernels["reinhardGlobal"], 1, sizeof(cl_mem), &mem_images[1]); err = clSetKernelArg(kernels["reinhardGlobal"], 2, sizeof(cl_mem), &mems["logAvgLum"]); err = clSetKernelArg(kernels["reinhardGlobal"], 3, sizeof(cl_mem), &mems["Lwhite"]); CHECK_ERROR_OCL(err, "setting globalTMO arguments", return false); reportStatus("\n"); return true; } double ReinhardGlobal::runCLKernels(bool recomputeMapping) { double start = omp_get_wtime(); cl_int err; err = clEnqueueNDRangeKernel(m_queue, kernels["computeLogAvgLum"], 2, NULL, global_sizes["computeLogAvgLum"], local_sizes["computeLogAvgLum"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing computeLogAvgLum kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["finalReduc"], 1, NULL, &global_sizes["finalReduc"][0], &local_sizes["finalReduc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing finalReduc kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["reinhardGlobal"], 2, NULL, global_sizes["reinhardGlobal"], local_sizes["reinhardGlobal"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing transfer_data kernel", return false); err = clFinish(m_queue); CHECK_ERROR_OCL(err, "running kernels", return false); return omp_get_wtime() - start; } bool ReinhardGlobal::cleanupOpenCL() { clReleaseMemObject(mem_images[0]); clReleaseMemObject(mem_images[1]); clReleaseMemObject(mems["Lwhite"]); clReleaseMemObject(mems["logAvgLum"]); clReleaseKernel(kernels["computeLogAvgLum"]); clReleaseKernel(kernels["finalReduc"]); clReleaseKernel(kernels["reinhardGlobal"]); releaseCL(); return true; } bool ReinhardGlobal::runReference(uchar* input, uchar* output) { // Check for cached result if (m_reference.data) { memcpy(output, m_reference.data, img_size.x*img_size.y*NUM_CHANNELS); reportStatus("Finished reference (cached)"); return true; } reportStatus("Running reference"); float logAvgLum = 0.f; float Lwhite = 0.f; //smallest luminance that'll be mapped to pure white int2 pos; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { float lum = getPixelLuminance(input, img_size, pos); logAvgLum += log(lum + 0.000001); if (lum > Lwhite) Lwhite = lum; } } logAvgLum = exp(logAvgLum/(img_size.x*img_size.y)); //Global Tone-mapping operator for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { float3 rgb, xyz; rgb.x = getPixel(input, img_size, pos, 0); rgb.y = getPixel(input, img_size, pos, 1); rgb.z = getPixel(input, img_size, pos, 2); xyz = RGBtoXYZ(rgb); float L = (key/logAvgLum) * xyz.y; float Ld = (L * (1.f + L/(Lwhite * Lwhite)) )/(1.f + L); rgb.x = pow(rgb.x/xyz.y, sat) * Ld; rgb.y = pow(rgb.y/xyz.y, sat) * Ld; rgb.z = pow(rgb.z/xyz.y, sat) * Ld; setPixel(output, img_size, pos, 0, rgb.x*PIXEL_RANGE); setPixel(output, img_size, pos, 1, rgb.y*PIXEL_RANGE); setPixel(output, img_size, pos, 2, rgb.z*PIXEL_RANGE); } } reportStatus("Finished reference"); // Cache result m_reference.width = img_size.x; m_reference.height = img_size.y; m_reference.data = new uchar[img_size.x*img_size.y*NUM_CHANNELS]; memcpy(m_reference.data, output, img_size.x*img_size.y*NUM_CHANNELS); return true; } <|start_filename|>android/jni/hdr.cpp<|end_filename|> // hdr.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include <stdint.h> #include <jni.h> #include <android/bitmap.h> #include <android/native_window.h> // requires ndk r5 or newer #include <android/native_window_jni.h> // requires ndk r5 or newer #include "hdr.h" #include "logger.h" #define LOG_TAG "hdr" JNIEXPORT void JNICALL Java_com_uob_achohan_hdr_MyGLRenderer_initCL(JNIEnv* jenv, jobject obj, jint width, jint height, jint in_tex, jint out_tex) { filter = new ReinhardGlobal(0.18f, 1.1f); filter->setStatusCallback(updateStatus); EGLDisplay mEglDisplay; EGLContext mEglContext; if ((mEglDisplay = eglGetCurrentDisplay()) == EGL_NO_DISPLAY) { status("eglGetCurrentDisplay() returned error %d", eglGetError()); } if ((mEglContext = eglGetCurrentContext()) == EGL_NO_CONTEXT) { status("eglGetCurrentContext() returned error %d", eglGetError()); } cl_prop[0] = CL_GL_CONTEXT_KHR; cl_prop[1] = (cl_context_properties) mEglContext; cl_prop[2] = CL_EGL_DISPLAY_KHR; cl_prop[3] = (cl_context_properties) mEglDisplay; cl_prop[4] = CL_CONTEXT_PLATFORM; cl_prop[6] = 0; params.opengl = true; filter->setImageSize(width, height); filter->setImageTextures(in_tex, out_tex); filter->setupOpenCL(cl_prop, params); return; } JNIEXPORT void JNICALL Java_com_uob_achohan_hdr_MyGLRenderer_processFrame(JNIEnv* jenv, jobject obj, jboolean recomputeMapping) { filter->runOpenCL(recomputeMapping); } JNIEXPORT void JNICALL Java_com_uob_achohan_hdr_MyGLRenderer_killCL(JNIEnv* jenv, jobject obj) { filter->cleanupOpenCL(); } int updateStatus(const char *format, va_list args) { // Generate message size_t sz = vsnprintf(NULL, 0, format, args) + 1; char *msg = (char*)malloc(sz); vsprintf(msg, format, args); __android_log_print(ANDROID_LOG_DEBUG, "hdr", "%s", msg); free(msg); return 0; } // Variadic argument wrapper for updateStatus void status(const char *fmt, ...) { va_list args; va_start(args, fmt); updateStatus(fmt, args); va_end(args); } <|start_filename|>android/jni/hdr.h<|end_filename|> // hdr.h (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #ifndef JNIAPI_H #define JNIAPI_H #include <pthread.h> #include <EGL/egl.h> // requires ndk r5 or newer #include <GLES/gl.h> #include <CL/cl.h> #include <CL/cl_gl.h> #include "HistEq.h" #include "ReinhardLocal.h" #include "ReinhardGlobal.h" #include "GradDom.h" using namespace hdr; extern "C" { // Variadic argument wrapper for updateStatus void status(const char *fmt, ...); int updateStatus(const char *format, va_list args); Filter* filter; Filter::Params params; cl_context_properties cl_prop[7]; JNIEXPORT void JNICALL Java_com_uob_achohan_hdr_MyGLRenderer_initCL(JNIEnv* jenv, jobject obj, jint width, jint height, jint in_tex, jint out_tex); JNIEXPORT void JNICALL Java_com_uob_achohan_hdr_MyGLRenderer_processFrame(JNIEnv* jenv, jobject obj, jboolean recomputeMapping); JNIEXPORT void JNICALL Java_com_uob_achohan_hdr_MyGLRenderer_killCL(JNIEnv* jenv, jobject obj); }; #endif // JNIAPI_H <|start_filename|>linux/Makefile<|end_filename|> EXE=hdr SRCDIR=../src OBJDIR=obj SUFFIXES += .d JPGINC = -I/usr/include/ JPGDIR = /usr/include/x86_64-linux-gnu/ JPGLIBd = -L$(JPGDIR) -ljpeg INCS = $(JPGINC) LIBS = $(JPGLIBd) CXX = g++ CXXFLAGS = -I$(SRCDIR) -O2 -fopenmp -DCL_USE_DEPRECATED_OPENCL_1_1_APIS LDFLAGS = -lOpenCL -lSDL2_image -lGL MODULES = Filter HistEq ReinhardGlobal ReinhardLocal GradDom OBJECTS = $(MODULES:%=$(OBJDIR)/%.o) SOURCES = $(MODULES:%=$(SRCDIR)/%.cpp) DEPFILES = $(MODULES:%=$(OBJDIR)/%.d) all: prebuild $(OBJDIR) $(EXE) $(EXE): $(OBJECTS) hdr.cpp $(CXX) $(CXXFLAGS) $^ $(LDFLAGS) $(INCS) $(LIBS) -o $@ prebuild: $(MAKE) -C ../src/opencl -f $(shell pwd)/Makefile prebuild_opencl prebuild_opencl: ./stringify_kernels.sh $(OBJDIR)/%.d: $(SRCDIR)/%.cpp $(OBJDIR) $(CXX) $(CXXFLAGS) $(INCS) $(LIBS) -MM -MT $(patsubst $(SRCDIR)/%.cpp,$(OBJDIR)/%.o,$<) $< -MF $@ 2>/dev/null $(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(CXX) $(CXXFLAGS) $(INCS) $(LIBS) -o $@ -c $< $(OBJDIR): mkdir -p $(OBJDIR) clean: rm -rf $(OBJDIR) $(EXE) ../src/opencl/*.h .PHONY: clean ifeq (0, $(words $(findstring $(MAKECMDGOALS), clean opencl halide))) -include $(DEPFILES) endif <|start_filename|>src/GradDom.cpp<|end_filename|> // GradDom.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include <string.h> #include <iostream> #include <cstdio> #include <algorithm> #include <omp.h> #include <vector> #include "GradDom.h" #include "opencl/gradDom.h" using namespace hdr; GradDom::GradDom(float _adjust_alpha, float _beta, float _sat) : Filter() { m_name = "GradDom"; adjust_alpha = _adjust_alpha; beta = _beta; sat = _sat; } bool GradDom::setupOpenCL(cl_context_properties context_prop[], const Params& params) { //get the number of mipmaps needed for the image of this size num_mipmaps = 0; for (int x=img_size.x, y=img_size.y ; x >= 32 && y >= 32; y/=2, x/=2) num_mipmaps++; char flags[1024]; sprintf(flags, "-cl-fast-relaxed-math -D WIDTH=%d -D HEIGHT=%d -D NUM_MIPMAPS=%d -D ADJUST_ALPHA=%f -D BETA=%f -D SAT=%f -D BUGGY_CL_GL=%d", img_size.x, img_size.y, num_mipmaps, adjust_alpha, beta, sat, BUGGY_CL_GL); if (!initCL(context_prop, params, gradDom_kernel, flags)) return false; cl_int err; /////////////////////////////////////////////////////////////////kernels //this kernel computes log average luminance of the image kernels["computeLogLum"] = clCreateKernel(m_program, "computeLogLum", &err); CHECK_ERROR_OCL(err, "creating computeLogLum kernel", return false); //this kernel computes all the mipmap levels of the luminance kernels["channel_mipmap"] = clCreateKernel(m_program, "channel_mipmap", &err); CHECK_ERROR_OCL(err, "creating channel_mipmap kernel", return false); //this kernel generates gradient magnitude at each of the mipmap levels kernels["gradient_mag"] = clCreateKernel(m_program, "gradient_mag", &err); CHECK_ERROR_OCL(err, "creating gradient_mag kernel", return false); //computes the partial reduction of a given array kernels["partialReduc"] = clCreateKernel(m_program, "partialReduc", &err); CHECK_ERROR_OCL(err, "creating partialReduc kernel", return false); //computes the final reduction of a given array kernels["finalReduc"] = clCreateKernel(m_program, "finalReduc", &err); CHECK_ERROR_OCL(err, "creating finalReduc kernel", return false); //computes attenuation function of the coarsest level mipmap kernels["coarsest_level_attenfunc"] = clCreateKernel(m_program, "coarsest_level_attenfunc", &err); CHECK_ERROR_OCL(err, "creating coarsest_level_attenfunc kernel", return false); //computes attenuation function of a given mipmap kernels["atten_func"] = clCreateKernel(m_program, "atten_func", &err); CHECK_ERROR_OCL(err, "creating atten_func kernel", return false); //finds gradients in x and y direction and attenuates them using the previously computed attenuation function kernels["grad_atten"] = clCreateKernel(m_program, "grad_atten", &err); CHECK_ERROR_OCL(err, "creating grad_atten kernel", return false); //computes the divergence field of the attenuated gradients kernels["divG"] = clCreateKernel(m_program, "divG", &err); CHECK_ERROR_OCL(err, "creating divG kernel", return false); /////////////////////////////////////////////////////////////////kernel sizes kernel2DSizes("computeLogLum"); kernel2DSizes("channel_mipmap"); kernel2DSizes("gradient_mag"); kernel1DSizes("partialReduc"); kernel1DSizes("coarsest_level_attenfunc"); kernel2DSizes("atten_func"); kernel2DSizes("grad_atten"); kernel2DSizes("divG"); reportStatus("---------------------------------Kernel finalReduc:"); int num_wg = (global_sizes["partialReduc"][0]) /(local_sizes["partialReduc"][0]); reportStatus("Number of work groups in partialReduc: %lu", num_wg); size_t* local = (size_t*) calloc(2, sizeof(size_t)); size_t* global = (size_t*) calloc(2, sizeof(size_t)); local[0] = num_wg; //workgroup size for normal kernels global[0] = num_wg; local_sizes["finalReduc"] = local; global_sizes["finalReduc"] = global; reportStatus("Kernel sizes: Local=%lu Global=%lu", local[0], global[0]); /////////////////////////////////////////////////////////////////allocating memory //initialising information regarding all mipmap levels m_width = (int*) calloc(num_mipmaps, sizeof(int)); m_height = (int*) calloc(num_mipmaps, sizeof(int)); m_offset = (int*) calloc(num_mipmaps, sizeof(int)); m_divider = (float*) calloc(num_mipmaps, sizeof(float)); m_offset[0] = 0; m_width[0] = img_size.x; m_height[0] = img_size.y; m_divider[0] = 2; for (int level=1; level<num_mipmaps; level++) { m_width[level] = m_width[level-1]/2; m_height[level] = m_height[level-1]/2; m_offset[level] = m_offset[level-1] + m_width[level-1]*m_height[level-1]; m_divider[level] = pow(2, level+1); } //initialise memory objects //TODO: this can be further optmised by reusing the same memory again mems["logLum_Mips"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y*2, NULL, &err); CHECK_ERROR_OCL(err, "creating logLum_Mips memory", return false); mems["gradient_Mips"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y*2, NULL, &err); CHECK_ERROR_OCL(err, "creating gradient_Mips memory", return false); mems["attenfunc_Mips"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y*2, NULL, &err); CHECK_ERROR_OCL(err, "creating attenfunc_Mips memory", return false); mems["gradient_PartialSum"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*num_wg, NULL, &err); CHECK_ERROR_OCL(err, "creating gradient_PartialSum memory", return false); mems["k_alphas"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*num_mipmaps, NULL, &err); CHECK_ERROR_OCL(err, "creating k_alphas memory", return false); mems["atten_grad_x"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y, NULL, &err); CHECK_ERROR_OCL(err, "creating atten_grad_x memory", return false); mems["atten_grad_y"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y, NULL, &err); CHECK_ERROR_OCL(err, "creating atten_grad_y memory", return false); mems["div_grad"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y, NULL, &err); CHECK_ERROR_OCL(err, "creating div_grad memory", return false); if (params.opengl) { mem_images[0] = clCreateFromGLTexture2D(m_clContext, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, in_tex, &err); CHECK_ERROR_OCL(err, "creating gl input texture", return false); mem_images[1] = clCreateFromGLTexture2D(m_clContext, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, out_tex, &err); CHECK_ERROR_OCL(err, "creating gl output texture", return false); } else { cl_image_format format; format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT8; mem_images[0] = clCreateImage2D(m_clContext, CL_MEM_READ_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating input image memory", return false); mem_images[1] = clCreateImage2D(m_clContext, CL_MEM_WRITE_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating output image memory", return false); } /////////////////////////////////////////////////////////////////setting kernel arguements err = clSetKernelArg(kernels["computeLogLum"], 0, sizeof(cl_mem), &mem_images[0]); err = clSetKernelArg(kernels["computeLogLum"], 1, sizeof(cl_mem), &mems["logLum_Mips"]); CHECK_ERROR_OCL(err, "setting computeLogLum arguments", return false); err = clSetKernelArg(kernels["channel_mipmap"], 0, sizeof(cl_mem), &mems["logLum_Mips"]); CHECK_ERROR_OCL(err, "setting channel_mipmap arguments", return false); err = clSetKernelArg(kernels["gradient_mag"], 0, sizeof(cl_mem), &mems["logLum_Mips"]); err = clSetKernelArg(kernels["gradient_mag"], 1, sizeof(cl_mem), &mems["gradient_Mips"]); CHECK_ERROR_OCL(err, "setting gradient_mag arguments", return false); err = clSetKernelArg(kernels["partialReduc"], 0, sizeof(cl_mem), &mems["gradient_Mips"]); err = clSetKernelArg(kernels["partialReduc"], 1, sizeof(cl_mem), &mems["gradient_PartialSum"]); err = clSetKernelArg(kernels["partialReduc"], 2, sizeof(float)*local_sizes["partialReduc"][0], NULL); CHECK_ERROR_OCL(err, "setting partialReduc arguments", return false); err = clSetKernelArg(kernels["finalReduc"], 0, sizeof(cl_mem), &mems["gradient_PartialSum"]); err = clSetKernelArg(kernels["finalReduc"], 1, sizeof(cl_mem), &mems["k_alphas"]); err = clSetKernelArg(kernels["finalReduc"], 5, sizeof(unsigned int), &num_wg); CHECK_ERROR_OCL(err, "setting finalReduc arguments", return false); err = clSetKernelArg(kernels["coarsest_level_attenfunc"], 0, sizeof(cl_mem), &mems["gradient_Mips"]); err = clSetKernelArg(kernels["coarsest_level_attenfunc"], 1, sizeof(cl_mem), &mems["attenfunc_Mips"]); err = clSetKernelArg(kernels["coarsest_level_attenfunc"], 2, sizeof(cl_mem), &mems["k_alphas"]); err = clSetKernelArg(kernels["coarsest_level_attenfunc"], 3, sizeof(int), &m_width[num_mipmaps-1]); err = clSetKernelArg(kernels["coarsest_level_attenfunc"], 4, sizeof(int), &m_height[num_mipmaps-1]); err = clSetKernelArg(kernels["coarsest_level_attenfunc"], 5, sizeof(int), &m_offset[num_mipmaps-1]); CHECK_ERROR_OCL(err, "setting coarsest_level_attenfunc arguments", return false); err = clSetKernelArg(kernels["atten_func"], 0, sizeof(cl_mem), &mems["gradient_Mips"]); err = clSetKernelArg(kernels["atten_func"], 1, sizeof(cl_mem), &mems["attenfunc_Mips"]); err = clSetKernelArg(kernels["atten_func"], 2, sizeof(cl_mem), &mems["k_alphas"]); CHECK_ERROR_OCL(err, "setting atten_func arguments", return false); err = clSetKernelArg(kernels["grad_atten"], 0, sizeof(cl_mem), &mems["atten_grad_x"]); err = clSetKernelArg(kernels["grad_atten"], 1, sizeof(cl_mem), &mems["atten_grad_y"]); err = clSetKernelArg(kernels["grad_atten"], 2, sizeof(cl_mem), &mems["logLum_Mips"]); err = clSetKernelArg(kernels["grad_atten"], 3, sizeof(cl_mem), &mems["attenfunc_Mips"]); CHECK_ERROR_OCL(err, "setting grad_atten arguments", return false); err = clSetKernelArg(kernels["divG"], 0, sizeof(cl_mem), &mems["atten_grad_x"]); err = clSetKernelArg(kernels["divG"], 1, sizeof(cl_mem), &mems["atten_grad_y"]); err = clSetKernelArg(kernels["divG"], 2, sizeof(cl_mem), &mems["div_grad"]); CHECK_ERROR_OCL(err, "setting divG arguments", return false); reportStatus("\n\n"); return true; } double GradDom::runCLKernels(bool recomputeMapping) { double start = omp_get_wtime(); cl_int err; if (recomputeMapping) { err = clEnqueueNDRangeKernel(m_queue, kernels["computeLogLum"], 2, NULL, global_sizes["computeLogLum"], local_sizes["computeLogLum"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing computeLogLum kernel", return false); //compute the gradient magniute of mipmap level 0 err = clSetKernelArg(kernels["gradient_mag"], 2, sizeof(int), &m_width[0]); err = clSetKernelArg(kernels["gradient_mag"], 3, sizeof(int), &m_height[0]); err = clSetKernelArg(kernels["gradient_mag"], 4, sizeof(int), &m_offset[0]); err = clSetKernelArg(kernels["gradient_mag"], 5, sizeof(float), &m_divider[0]); err = clEnqueueNDRangeKernel(m_queue, kernels["gradient_mag"], 2, NULL, global_sizes["gradient_mag"], local_sizes["gradient_mag"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing gradient_mag kernel", return false); err = clSetKernelArg(kernels["partialReduc"], 3, sizeof(int), &m_width[0]); err = clSetKernelArg(kernels["partialReduc"], 4, sizeof(int), &m_height[0]); err = clSetKernelArg(kernels["partialReduc"], 5, sizeof(int), &m_offset[0]); err = clEnqueueNDRangeKernel(m_queue, kernels["partialReduc"], 1, NULL, &global_sizes["partialReduc"][0], &local_sizes["partialReduc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "setting partialReduc arguments", return false); int level = 0; err = clSetKernelArg(kernels["finalReduc"], 2, sizeof(int), &level); err = clSetKernelArg(kernels["finalReduc"], 3, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["finalReduc"], 4, sizeof(int), &m_height[level]); err = clEnqueueNDRangeKernel(m_queue, kernels["finalReduc"], 1, NULL, &global_sizes["finalReduc"][0], &local_sizes["finalReduc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing finalReduc kernel", return false); //creating mipmaps and their gradient magnitudes for (int level=1; level<num_mipmaps; level++) { err = clSetKernelArg(kernels["channel_mipmap"], 1, sizeof(int), &m_width[level-1]); err = clSetKernelArg(kernels["channel_mipmap"], 2, sizeof(int), &m_offset[level-1]); err = clSetKernelArg(kernels["channel_mipmap"], 3, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["channel_mipmap"], 4, sizeof(int), &m_height[level]); err = clSetKernelArg(kernels["channel_mipmap"], 5, sizeof(int), &m_offset[level]); err = clEnqueueNDRangeKernel(m_queue, kernels["channel_mipmap"], 2, NULL, global_sizes["channel_mipmap"], local_sizes["channel_mipmap"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing channel_mipmap kernel", return false); err = clSetKernelArg(kernels["gradient_mag"], 2, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["gradient_mag"], 3, sizeof(int), &m_height[level]); err = clSetKernelArg(kernels["gradient_mag"], 4, sizeof(int), &m_offset[level]); err = clSetKernelArg(kernels["gradient_mag"], 5, sizeof(float), &m_divider[level]); err = clEnqueueNDRangeKernel(m_queue, kernels["gradient_mag"], 2, NULL, global_sizes["gradient_mag"], local_sizes["gradient_mag"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing gradient_mag kernel", return false); err = clSetKernelArg(kernels["partialReduc"], 3, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["partialReduc"], 4, sizeof(int), &m_height[level]); err = clSetKernelArg(kernels["partialReduc"], 5, sizeof(int), &m_offset[level]); err = clEnqueueNDRangeKernel(m_queue, kernels["partialReduc"], 1, NULL, &global_sizes["partialReduc"][0], &local_sizes["partialReduc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "setting partialReduc arguments", return false); err = clSetKernelArg(kernels["finalReduc"], 2, sizeof(int), &level); err = clSetKernelArg(kernels["finalReduc"], 3, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["finalReduc"], 4, sizeof(int), &m_height[level]); err = clEnqueueNDRangeKernel(m_queue, kernels["finalReduc"], 1, NULL, &global_sizes["finalReduc"][0], &local_sizes["finalReduc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing finalReduc kernel", return false); } //attenuation function of mipmap at level num_mipmaps-1 err = clEnqueueNDRangeKernel(m_queue, kernels["coarsest_level_attenfunc"], 1, NULL, &global_sizes["coarsest_level_attenfunc"][0], &local_sizes["coarsest_level_attenfunc"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing coarsest_level_attenfunc kernel", return false); for (int level=num_mipmaps-2; level>-1; level--) { err = clSetKernelArg(kernels["atten_func"], 3, sizeof(int), &m_width[level]); err = clSetKernelArg(kernels["atten_func"], 4, sizeof(int), &m_height[level]); err = clSetKernelArg(kernels["atten_func"], 5, sizeof(int), &m_offset[level]); err = clSetKernelArg(kernels["atten_func"], 6, sizeof(int), &m_width[level+1]); err = clSetKernelArg(kernels["atten_func"], 7, sizeof(int), &m_height[level+1]); err = clSetKernelArg(kernels["atten_func"], 8, sizeof(int), &m_offset[level+1]); err = clSetKernelArg(kernels["atten_func"], 9, sizeof(int), &level); err = clEnqueueNDRangeKernel(m_queue, kernels["atten_func"], 2, NULL, global_sizes["atten_func"], local_sizes["atten_func"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing atten_func kernel", return false); } err = clEnqueueNDRangeKernel(m_queue, kernels["grad_atten"], 2, NULL, global_sizes["grad_atten"], local_sizes["grad_atten"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing grad_atten kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["divG"], 2, NULL, global_sizes["divG"], local_sizes["divG"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing divG kernel", return false); } err = clFinish(m_queue); CHECK_ERROR_OCL(err, "running kernels", return false); return omp_get_wtime() - start; } bool GradDom::cleanupOpenCL() { clReleaseMemObject(mem_images[0]); clReleaseMemObject(mem_images[1]); clReleaseMemObject(mems["logLum_Mips"]); clReleaseMemObject(mems["gradient_Mips"]); clReleaseMemObject(mems["attenfunc_Mips"]); clReleaseMemObject(mems["gradient_PartialSum"]); clReleaseMemObject(mems["k_alphas"]); clReleaseMemObject(mems["atten_grad_x"]); clReleaseMemObject(mems["atten_grad_y"]); clReleaseMemObject(mems["div_grad"]); clReleaseKernel(kernels["computeLogLum"]); clReleaseKernel(kernels["channel_mipmap"]); clReleaseKernel(kernels["gradient_mag"]); clReleaseKernel(kernels["partialReduc"]); clReleaseKernel(kernels["finalReduc"]); clReleaseKernel(kernels["coarsest_level_attenfunc"]); clReleaseKernel(kernels["atten_func"]); clReleaseKernel(kernels["grad_atten"]); clReleaseKernel(kernels["divG"]); releaseCL(); return true; } float* GradDom::attenuate_func(float* lum) { int k = 0; int2 k_dim = img_size; //width and height of the level k in the pyramid float* k_lum = lum; float k_av_grad = 0.f; float* k_gradient; std::vector<float*> pyramid; std::vector<float> av_grads; std::vector<std::pair<unsigned int, unsigned int> > pyramid_sizes; for ( ; k_dim.x >= 32 && k_dim.y >= 32; k_dim.y/=2, k_dim.x/=2, k++) { //computing gradient magnitude using central differences at level k k_av_grad = 0.f; k_gradient = (float*) calloc(k_dim.x*k_dim.y, sizeof(float)); for (int y = 0; y < k_dim.y; y++) { for (int x = 0; x < k_dim.x; x++) { int x_west = clamp(x-1, 0, k_dim.x-1); int x_east = clamp(x+1, 0, k_dim.x-1); int y_north = clamp(y-1, 0, k_dim.y-1); int y_south = clamp(y+1, 0, k_dim.y-1); float x_grad = (k_lum[x_west + y*k_dim.x] - k_lum[x_east + y*k_dim.x])/pow(2.f, k+1); float y_grad = (k_lum[x + y_south*k_dim.x] - k_lum[x + y_north*k_dim.x])/pow(2.f, k+1); k_gradient[x + y*k_dim.x] = sqrt(pow(x_grad, 2) + pow(y_grad, 2)); k_av_grad += k_gradient[x + y*k_dim.x]; } } pyramid.push_back(k_gradient); pyramid_sizes.push_back(std::pair< unsigned int, unsigned int >(k_dim.x, k_dim.y)); av_grads.push_back(adjust_alpha*exp(k_av_grad/((float)k_dim.x*k_dim.y))); k_lum = mipmap(k_lum, k_dim); } //computing attenuation functions k_gradient = pyramid.back(); k_dim.x = pyramid_sizes.back().first; k_dim.y = pyramid_sizes.back().second; float k_alpha = av_grads.back(); float* k_atten_func; k--; //attenuation function for the coarsest level k_atten_func = (float*) calloc(k_dim.x*k_dim.y, sizeof(float)); for (int y = 0; y < k_dim.y; y++) { for (int x = 0; x < k_dim.x; x++) { k_atten_func[x + y*k_dim.x] = (k_alpha/k_gradient[x + y*k_dim.x])*pow(k_gradient[x + y*k_dim.x]/k_alpha, beta); } } pyramid.pop_back(); pyramid_sizes.pop_back(); av_grads.pop_back(); while (! pyramid.empty()) { float* k1_atten_func = k_atten_func; int k1_width = k_dim.x; int k1_height = k_dim.y; k_gradient = pyramid.back(); k_dim.x = pyramid_sizes.back().first; k_dim.y = pyramid_sizes.back().second; float k_alpha = av_grads.back(); float k_xy_scale_factor; float k_xy_atten_func; k--; //attenuation function for this level k_atten_func = (float*) calloc(k_dim.x*k_dim.y, sizeof(float)); for (int y = 0; y < k_dim.y; y++) { for (int x = 0; x < k_dim.x; x++) { if (k_gradient[x + y*k_dim.x] != 0) { int k1_x = x/2, k1_y = y/2; //x and y value of the coarser grid //neighbours need to be left or right dependent on where we are int n_x = (x & 1) ? 1 : -1; int n_y = (y & 1) ? 1 : -1; //this stops us from going out of bounds if ((k1_x + n_x) < 0) n_x = 0; if ((k1_y + n_y) < 0) n_y = 0; if ((k1_x + n_x) >= k1_width) n_x = 0; if ((k1_y + n_y) >= k1_height) n_y = 0; if (k1_x == k1_width) k1_x -= 1; if (k1_y == k1_height) k1_y -= 1; k_xy_atten_func = 9.0*k1_atten_func[k1_x + k1_y *k1_width] + 3.0*k1_atten_func[k1_x+n_x + k1_y *k1_width] + 3.0*k1_atten_func[k1_x + (k1_y+n_y) *k1_width] + 1.0*k1_atten_func[k1_x+n_x + (k1_y+n_y) *k1_width]; k_xy_scale_factor = (k_alpha/k_gradient[x + y*k_dim.x])*pow(k_gradient[x + y*k_dim.x]/k_alpha, beta); } else k_xy_scale_factor = 0.f; k_atten_func[x + y*k_dim.x] = (1.f/16.f)*(k_xy_atten_func)*k_xy_scale_factor; } } pyramid.pop_back(); pyramid_sizes.pop_back(); av_grads.pop_back(); } return k_atten_func; } float* GradDom::poissonSolver(float* lum, float* div_grad, float convergenceCriteria) { float* prev_dr = (float*) calloc(img_size.y*img_size.x, sizeof(float)); int* converged = (int*) calloc(img_size.y*img_size.x, sizeof(int)); for (int y = 0; y < img_size.y; y++) { for (int x = 0; x < img_size.x; x++) { prev_dr[x + y*img_size.x] = lum[x+y*img_size.x]; converged[x + y*img_size.x] = 0; } } float* new_dr = (float*) calloc(img_size.y*img_size.x, sizeof(float)); float diff; int converged_pixels = 0; while (converged_pixels < 0.9*img_size.x*img_size.y) { diff = 0; for (int y = 0; y < img_size.y; y++) { for (int x = 0; x < img_size.x; x++) { if (converged[x + y*img_size.x] != 1) { float prev = ((x-1 >= 0) ? prev_dr[x-1 + y*img_size.x] : 0) + ((x+1 <= img_size.x-1) ? prev_dr[x+1 + y*img_size.x] : 0) + ((y-1 >= 0) ? prev_dr[x + (y-1)*img_size.x] : 0) + ((y+1 <= img_size.y-1) ? prev_dr[x + (y+1)*img_size.x] : 0); new_dr[x + y*img_size.x] = 0.25f*(prev - div_grad[x + y*img_size.x]); diff = new_dr[x + y*img_size.x] - prev_dr[x + y*img_size.x]; diff = (diff >= 0) ? diff : -diff; if (diff < convergenceCriteria) { converged_pixels++; converged[x + y*img_size.x] = 1; } } } } //printf("%d, %d\n", converged_pixels, img_size.x*img_size.y); float* swap = prev_dr; prev_dr = new_dr; new_dr = swap; } return new_dr; } bool GradDom::runReference(uchar* input, uchar* output) { // Check for cached result if (m_reference.data) { memcpy(output, m_reference.data, img_size.x*img_size.y*NUM_CHANNELS); reportStatus("Finished reference (cached)"); return true; } reportStatus("Running reference"); //computing logarithmic luminace of the image float* lum = (float*) calloc(img_size.x * img_size.y, sizeof(float)); //logarithm luminance int2 pos; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { lum[pos.x + pos.y*img_size.x] = log(getPixelLuminance(input, img_size, pos) + 0.000001); } } //computing the attenuation function which will then be multiplied by luminance gradient to acheive attenuated gradient float* att_func = attenuate_func(lum); //o(x,y) //luminance gradient in forward direction for x and y float* grad_x = (float*) calloc(img_size.x * img_size.y, sizeof(float)); //H(x,y) float* grad_y = (float*) calloc(img_size.x * img_size.y, sizeof(float)); //H(x,y) for (int y = 0; y < img_size.y; y++) { for (int x = 0; x < img_size.x; x++) { grad_x[x + y*img_size.x] = (x < img_size.x-1) ? (lum[x+1 + y*img_size.x] - lum[x + y*img_size.x]) : 0; grad_y[x + y*img_size.x] = (y < img_size.y-1) ? (lum[x + (y+1)*img_size.x] - lum[x + y*img_size.x]) : 0; } } //attenuated gradient achieved by using the previously computed attenuation function float* att_grad_x = (float*) calloc(img_size.y * img_size.x, sizeof(float)); //G(x,y) float* att_grad_y = (float*) calloc(img_size.y * img_size.x, sizeof(float)); //G(x,y) for (int y = 0; y < img_size.y; y++) { for (int x = 0; x < img_size.x; x++) { att_grad_x[x + y*img_size.x] = grad_x[x + y*img_size.x] * att_func[x + y*img_size.x]; att_grad_y[x + y*img_size.x] = grad_y[x + y*img_size.x] * att_func[x + y*img_size.x]; } } //divG(x,y) float* div_grad = (float*) calloc(img_size.y * img_size.x, sizeof(float)); div_grad[0] = 0; for (int x = 1; x < img_size.x; x++) { div_grad[x] = att_grad_x[x] - att_grad_x[x-1]; } for (int y = 1; y < img_size.y; y++) { div_grad[y*img_size.x] = att_grad_y[y*img_size.x] - att_grad_y[(y-1)*img_size.x]; for (int x = 1; x < img_size.x; x++) { div_grad[x + y*img_size.x] = (att_grad_x[x + y*img_size.x] - att_grad_x[(x-1) + y*img_size.x]) + (att_grad_y[x + y*img_size.x] - att_grad_y[x + (y-1)*img_size.x]); } } float* new_dr = poissonSolver(lum, div_grad); float3 rgb; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { //printf("%f, %f\n", lum[x + y*img_size.x], new_dr[x+y*img_size.x]); rgb.x = pow(getPixel(input, img_size, pos, 0)/exp(lum[pos.x + pos.y*img_size.x]), sat)*exp(new_dr[pos.x + pos.y*img_size.x]); rgb.y = pow(getPixel(input, img_size, pos, 1)/exp(lum[pos.x + pos.y*img_size.x]), sat)*exp(new_dr[pos.x + pos.y*img_size.x]); rgb.z = pow(getPixel(input, img_size, pos, 2)/exp(lum[pos.x + pos.y*img_size.x]), sat)*exp(new_dr[pos.x + pos.y*img_size.x]); setPixel(output, img_size, pos, 0, rgb.x); setPixel(output, img_size, pos, 1, rgb.y); setPixel(output, img_size, pos, 2, rgb.z); } } reportStatus("Finished reference"); // Cache result m_reference.width = img_size.x; m_reference.height = img_size.y; m_reference.data = new uchar[img_size.x*img_size.y*NUM_CHANNELS]; memcpy(m_reference.data, output, img_size.x*img_size.y*NUM_CHANNELS); return true; } <|start_filename|>src/Filter.cpp<|end_filename|> // Filter.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include <stddef.h> #include <stdlib.h> #include <sys/time.h> #include <iostream> #include <exception> #include <stdexcept> #include "Filter.h" namespace hdr { Filter::Filter() { m_statusCallback = NULL; m_clContext = 0; m_queue = 0; m_program = 0; m_reference.data = NULL; } Filter::~Filter() { clearReferenceCache(); } void Filter::clearReferenceCache() { if (m_reference.data) { delete[] m_reference.data; m_reference.data = NULL; } } const char* Filter::getName() const { return m_name; } bool Filter::initCL(cl_context_properties context_prop[], const Params& params, const char *source, const char *options) { // Ensure no existing context releaseCL(); cl_int err; cl_uint numPlatforms, numDevices; cl_platform_id platform, platforms[params.platformIndex+1]; err = clGetPlatformIDs(params.platformIndex+1, platforms, &numPlatforms); CHECK_ERROR_OCL(err, "getting platforms", return false); if (params.platformIndex >= numPlatforms) { reportStatus("Platform index %d out of range (%d platforms found)", params.platformIndex, numPlatforms); return false; } platform = platforms[params.platformIndex]; cl_device_id devices[params.deviceIndex+1]; err = clGetDeviceIDs(platform, params.type, params.deviceIndex+1, devices, &numDevices); CHECK_ERROR_OCL(err, "getting devices", return false); if (params.deviceIndex >= numDevices) { reportStatus("Device index %d out of range (%d devices found)", params.deviceIndex, numDevices); return false; } m_device = devices[params.deviceIndex]; char name[64]; clGetDeviceInfo(m_device, CL_DEVICE_NAME, 64, name, NULL); reportStatus("Using device: %s", name); cl_ulong device_size; clGetDeviceInfo(m_device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(device_size), &device_size, NULL); reportStatus("CL_DEVICE_GLOBAL_MEM_SIZE: %lu bytes", device_size); clGetDeviceInfo(m_device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(device_size), &device_size, NULL); reportStatus("CL_DEVICE_LOCAL_MEM_SIZE: %lu bytes", device_size); clGetDeviceInfo(m_device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(size_t), &max_cu, NULL); reportStatus("CL_DEVICE_MAX_COMPUTE_UNITS: %lu", max_cu); if (params.opengl) context_prop[5] = (cl_context_properties) platform; m_clContext = clCreateContext(context_prop, 1, &m_device, NULL, NULL, &err); CHECK_ERROR_OCL(err, "creating context", return false); m_queue = clCreateCommandQueue(m_clContext, m_device, 0, &err); CHECK_ERROR_OCL(err, "creating command queue", return false); m_program = clCreateProgramWithSource(m_clContext, 1, &source, NULL, &err); CHECK_ERROR_OCL(err, "creating program", return false); err = clBuildProgram(m_program, 1, &m_device, options, NULL, NULL); if (err == CL_BUILD_PROGRAM_FAILURE) { size_t sz; clGetProgramBuildInfo( m_program, m_device, CL_PROGRAM_BUILD_LOG, 0, NULL, &sz); char *log = (char*)malloc(++sz); clGetProgramBuildInfo( m_program, m_device, CL_PROGRAM_BUILD_LOG, sz, log, NULL); reportStatus(log); free(log); } CHECK_ERROR_OCL(err, "building program", return false); reportStatus("OpenCL context initialised."); return true; } void Filter::releaseCL() { if (m_program) { clReleaseProgram(m_program); m_program = 0; } if (m_queue) { clReleaseCommandQueue(m_queue); m_queue = 0; } if (m_clContext) { clReleaseContext(m_clContext); m_clContext = 0; } } bool Filter::runOpenCL(bool recomputeMapping) { cl_int err; err = clEnqueueAcquireGLObjects(m_queue, 2, &mem_images[0], 0, 0, 0); CHECK_ERROR_OCL(err, "acquiring GL objects", return false); double runTime = runCLKernels(recomputeMapping); err = clEnqueueReleaseGLObjects(m_queue, 2, &mem_images[0], 0, 0, 0); CHECK_ERROR_OCL(err, "releasing GL objects", return false); reportStatus("Finished OpenCL kernels in %lf ms", runTime*1000); return true; } bool Filter::runOpenCL(uchar* input, uchar* output, bool recomputeMapping) { cl_int err; const size_t origin[] = {0, 0, 0}; const size_t region[] = {img_size.x, img_size.y, 1}; err = clEnqueueWriteImage(m_queue, mem_images[0], CL_TRUE, origin, region, sizeof(uchar)*img_size.x*NUM_CHANNELS, 0, input, 0, NULL, NULL); CHECK_ERROR_OCL(err, "writing image memory", return false); double runTime = runCLKernels(recomputeMapping); err = clEnqueueReadImage(m_queue, mem_images[1], CL_TRUE, origin, region, sizeof(uchar)*img_size.x*NUM_CHANNELS, 0, output, 0, NULL, NULL); CHECK_ERROR_OCL(err, "reading image memory", return false); reportStatus("Finished OpenCL kernel"); // Verification bool passed = verify(input, output); reportStatus( "Finished in %lf ms (verification %s)", runTime*1000, passed ? "passed" : "failed"); return passed; } void Filter::reportStatus(const char *format, ...) const { if (m_statusCallback) { va_list args; va_start(args, format); m_statusCallback(format, args); va_end(args); } } void Filter::setStatusCallback(int (*callback)(const char*, va_list args)) { m_statusCallback = callback; } bool Filter::verify(uchar* input, uchar* output, float tolerance, float maxErrorPercent) { // compute reference image uchar* ref = (uchar*) calloc(img_size.x*img_size.y*NUM_CHANNELS, sizeof(uchar)); runReference(input, ref); // compare pixels int errors = 0; const int maxErrors = img_size.x*img_size.y*maxErrorPercent; int2 pos; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { for (int c = 0; c < NUM_CHANNELS; c++) { float r = getPixel(ref, img_size, pos, c); float o = getPixel(output, img_size, pos, c); float diff = r - o; diff = diff >= 0 ? diff : -diff; if (diff > tolerance) { // Only report first few errors if (errors < maxErrors) { reportStatus("Mismatch at (%d,%d,%d): %f vs %f", pos.x, pos.y, c, r, o); } if (++errors == maxErrors) { reportStatus("Supressing further errors"); } } } } } free(ref); return errors == 0; } bool Filter::kernel1DSizes(const char* kernel_name) { reportStatus("---------------------------------Kernel %s:", kernel_name); cl_int err; size_t max_wg_size; //max workgroup size for the kernel err = clGetKernelWorkGroupInfo (kernels[kernel_name], m_device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &max_wg_size, NULL); CHECK_ERROR_OCL(err, "getting CL_KERNEL_WORK_GROUP_SIZE", return false); reportStatus("CL_KERNEL_WORK_GROUP_SIZE: %lu", max_wg_size); size_t preferred_wg_size; //workgroup size should be a multiple of this err = clGetKernelWorkGroupInfo (kernels[kernel_name], m_device, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), &preferred_wg_size, NULL); CHECK_ERROR_OCL(err, "getting CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE", return false); reportStatus("CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE: %lu", preferred_wg_size); size_t* local = (size_t*) calloc(2, sizeof(size_t)); size_t* global = (size_t*) calloc(2, sizeof(size_t)); local[0] = preferred_wg_size; //workgroup size for normal kernels global[0] = preferred_wg_size*max_cu; local_sizes[kernel_name] = local; global_sizes[kernel_name] = global; reportStatus("Kernel sizes: Local=%lu Global=%lu", local[0], global[0]); } bool Filter::kernel2DSizes(const char* kernel_name) { reportStatus("---------------------------------Kernel %s:", kernel_name); cl_int err; size_t max_wg_size; //max workgroup size for the kernel err = clGetKernelWorkGroupInfo (kernels[kernel_name], m_device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &max_wg_size, NULL); CHECK_ERROR_OCL(err, "getting CL_KERNEL_WORK_GROUP_SIZE", return false); reportStatus("CL_KERNEL_WORK_GROUP_SIZE: %lu", max_wg_size); size_t preferred_wg_size; //workgroup size should be a multiple of this err = clGetKernelWorkGroupInfo (kernels[kernel_name], m_device, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), &preferred_wg_size, NULL); CHECK_ERROR_OCL(err, "getting CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE", return false); reportStatus("CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE: %lu", preferred_wg_size); size_t* local = (size_t*) calloc(2, sizeof(size_t)); size_t* global = (size_t*) calloc(2, sizeof(size_t)); int i=0; local[0] = 1; local[1] = 1; while (local[0]*local[1] <= preferred_wg_size) { local[i%2] *= 2; i++; } if (local[0]*local[1] > max_wg_size) { local[i%2] /= 2; } global[0] = local[0]*max_cu; global[1] = local[1]*max_cu; global[0] = ceil((float)global[0]/(float)local[0])*local[0]; global[1] = ceil((float)global[1]/(float)local[1])*local[1]; local_sizes[kernel_name] = local; global_sizes[kernel_name] = global; reportStatus("Kernel sizes: Local=(%lu, %lu) Global=(%lu, %lu)", local[0], local[1], global[0], global[1]); } ///////////////// // Image utils // ///////////////// void Filter::setImageSize(int width, int height) { img_size.x = width; img_size.y = height; } void Filter::setImageTextures(GLuint input_texture, GLuint output_texture) { in_tex = input_texture; out_tex = output_texture; } float* mipmap(float* input, int2 size, int level) { int scale_factor = pow(2, level); int m_width = size.x/scale_factor; int m_height = size.y/scale_factor; float* result = (float*) calloc(m_width*m_height, sizeof(float)); for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { int _x = scale_factor*x; int _y = scale_factor*y; result[x + y*m_width] = (input[_x + _y*size.x] + input[_x+1 + _y*size.x] + input[_x + (_y+1)*size.x] + input[(_x+1) + (_y+1)*size.x])/4.f; } } return result; } float clamp(float x, float min, float max) { return x < min ? min : x > max ? max : x; } float getValue(float* data, int2 size, int2 pos) { int _x = clamp(pos.x, 0, size.x-1); int _y = clamp(pos.y, 0, size.y-1); return data[_x + _y*size.x]; } float getPixel(uchar* data, int2 image_size, int2 pixel_pos, int c) { int _x = clamp(pixel_pos.x, 0, image_size.x-1); int _y = clamp(pixel_pos.y, 0, image_size.y-1); return ((float) data[(_x + _y*image_size.x)*NUM_CHANNELS + c]); } void setPixel(uchar* data, int2 image_size, int2 pixel_pos, int c, float value) { int _x = clamp(pixel_pos.x, 0, image_size.x-1); int _y = clamp(pixel_pos.y, 0, image_size.y-1); data[(_x + _y*image_size.x)*NUM_CHANNELS + c] = clamp(value, 0.f, PIXEL_RANGE*1.f); } float getPixelLuminance(uchar* image, int2 image_size, int2 pixel_pos) { float3 pixel_val = {getPixel(image, image_size, pixel_pos, 0), getPixel(image, image_size, pixel_pos, 1), getPixel(image, image_size, pixel_pos, 2)}; return pixel_val.x*0.2126 + pixel_val.y*0.7152 + pixel_val.z*0.0722; } float3 RGBtoHSV(float3 rgb) { float r = rgb.x; float g = rgb.y; float b = rgb.z; float min, max, delta; min = std::min(std::min(r, g), b); max = std::max(std::max(r, g), b); float3 hsv; hsv.z = max; //Brightness delta = max - min; if(max != 0) hsv.y = delta/max;//Saturation else { // r = g = b = 0 //Saturation = 0, Value is undefined hsv.y = 0; hsv.x = -1; return hsv; } //Hue if(r == max) hsv.x = (g-b)/delta; else if(g == max) hsv.x = (b-r)/delta + 2; else hsv.x = (r-g)/delta + 4; hsv.x *= 60; if( hsv.x < 0 ) hsv.x += 360; return hsv; } float3 HSVtoRGB(float3 hsv) { int i; float h = hsv.x; float s = hsv.y; float v = hsv.z; float f, p, q, t; float3 rgb; if( s == 0 ) { // achromatic (grey) rgb.x = rgb.y = rgb.z = v; return rgb; } h /= 60; // sector 0 to 5 i = floor( h ); f = h - i; // factorial part of h p = v * ( 1 - s ); q = v * ( 1 - s * f ); t = v * ( 1 - s * ( 1 - f ) ); switch( i ) { case 0: rgb.x = v; rgb.y = t; rgb.z = p; break; case 1: rgb.x = q; rgb.y = v; rgb.z = p; break; case 2: rgb.x = p; rgb.y = v; rgb.z = t; break; case 3: rgb.x = p; rgb.y = q; rgb.z = v; break; case 4: rgb.x = t; rgb.y = p; rgb.z = v; break; default: // case 5: rgb.x = v; rgb.y = p; rgb.z = q; break; } return rgb; } float3 RGBtoXYZ(float3 rgb) { float3 xyz; xyz.x = rgb.x*0.4124 + rgb.y*0.3576 + rgb.z*0.1805; xyz.y = rgb.x*0.2126 + rgb.y*0.7152 + rgb.z*0.0722; xyz.z = rgb.x*0.0193 + rgb.y*0.1192 + rgb.z*0.9505; return xyz; } float3 XYZtoRGB(float3 xyz) { float3 rgb; rgb.x = xyz.x*3.240479 - xyz.y*1.53715 - xyz.z*0.498535; rgb.y = - xyz.x*0.969256 + xyz.y*1.875991 + xyz.z*0.041556; rgb.z = xyz.x*0.055648 - xyz.y*0.204043 + xyz.z*1.057311; return rgb; } float weight(float luminance) { if (luminance < 0.5) return luminance*2.0; else return (1.0 - luminance)*2.0; } ////////////////// // Timing utils // ////////////////// double getCurrentTime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_usec + tv.tv_sec*1e6; } } <|start_filename|>src/HistEq.cpp<|end_filename|> // HistEq.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include <string.h> #include <cstdio> #include <algorithm> #include <omp.h> #include "HistEq.h" #include "opencl/histEq.h" using namespace hdr; HistEq::HistEq() : Filter() { m_name = "HistEq"; } bool HistEq::setupOpenCL(cl_context_properties context_prop[], const Params& params) { char flags[1024]; int hist_size = PIXEL_RANGE+1; sprintf(flags, "-cl-fast-relaxed-math -D PIXEL_RANGE=%d -D HIST_SIZE=%d -D NUM_CHANNELS=%d -D WIDTH=%d -D HEIGHT=%d -D BUGGY_CL_GL=%d", PIXEL_RANGE, hist_size, NUM_CHANNELS, img_size.x, img_size.y, BUGGY_CL_GL); if (!initCL(context_prop, params, histEq_kernel, flags)) return false; /////////////////////////////////////////////////////////////////kernels cl_int err; kernels["transfer_data"] = clCreateKernel(m_program, "transfer_data", &err); CHECK_ERROR_OCL(err, "creating transfer_data kernel", return false); //compute partial histogram kernels["partial_hist"] = clCreateKernel(m_program, "partial_hist", &err); CHECK_ERROR_OCL(err, "creating partial_hist kernel", return false); //merge partial histograms kernels["merge_hist"] = clCreateKernel(m_program, "merge_hist", &err); CHECK_ERROR_OCL(err, "creating merge_hist kernel", return false); //compute cdf of brightness histogram kernels["hist_cdf"] = clCreateKernel(m_program, "hist_cdf", &err); CHECK_ERROR_OCL(err, "creating hist_cdf kernel", return false); //perfrom histogram equalisation to the original image kernels["hist_eq"] = clCreateKernel(m_program, "histogram_equalisation", &err); CHECK_ERROR_OCL(err, "creating histogram_equalisation kernel", return false); /////////////////////////////////////////////////////////////////kernel sizes kernel2DSizes("transfer_data"); kernel1DSizes("partial_hist"); //number of workgroups in transfer_data kernel int num_wg = (global_sizes["partial_hist"][0])/(local_sizes["partial_hist"][0]); reportStatus("Number of work groups in partial_hist: %lu", num_wg); //merge_hist kernel size reportStatus("---------------------------------Kernel merge_hist:"); local_sizes["merge_hist"] = (size_t*) calloc(2, sizeof(size_t)); global_sizes["merge_hist"] = (size_t*) calloc(2, sizeof(size_t)); local_sizes["merge_hist"][0] = hist_size; global_sizes["merge_hist"][0] = hist_size; reportStatus("Kernel sizes: Local=%lu Global=%lu", global_sizes["merge_hist"][0], local_sizes["merge_hist"][0]); kernel1DSizes("hist_cdf"); kernel2DSizes("hist_eq"); /////////////////////////////////////////////////////////////////allocating memory mems["partial_hist"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(unsigned int)*hist_size*num_wg, NULL, &err); CHECK_ERROR_OCL(err, "creating histogram memory", return false); mems["merge_hist"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(unsigned int)*hist_size, NULL, &err); CHECK_ERROR_OCL(err, "creating merge_hist memory", return false); mems["image"] = clCreateBuffer(m_clContext, CL_MEM_READ_WRITE, sizeof(float)*img_size.x*img_size.y*NUM_CHANNELS, NULL, &err); CHECK_ERROR_OCL(err, "creating image memory", return false); if (params.opengl) { mem_images[0] = clCreateFromGLTexture2D(m_clContext, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, in_tex, &err); CHECK_ERROR_OCL(err, "creating gl input texture", return false); mem_images[1] = clCreateFromGLTexture2D(m_clContext, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, out_tex, &err); CHECK_ERROR_OCL(err, "creating gl output texture", return false); } else { cl_image_format format; format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT8; mem_images[0] = clCreateImage2D(m_clContext, CL_MEM_READ_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating input image memory", return false); mem_images[1] = clCreateImage2D(m_clContext, CL_MEM_WRITE_ONLY, &format, img_size.x, img_size.y, 0, NULL, &err); CHECK_ERROR_OCL(err, "creating output image memory", return false); } /////////////////////////////////////////////////////////////////setting kernel arguements err = clSetKernelArg(kernels["transfer_data"], 0, sizeof(cl_mem), &mem_images[0]); err |= clSetKernelArg(kernels["transfer_data"], 1, sizeof(cl_mem), &mems["image"]); CHECK_ERROR_OCL(err, "setting transfer_data arguments", return false); err = clSetKernelArg(kernels["partial_hist"], 0, sizeof(cl_mem), &mems["image"]); err |= clSetKernelArg(kernels["partial_hist"], 1, sizeof(cl_mem), &mems["partial_hist"]); CHECK_ERROR_OCL(err, "setting partial_hist arguments", return false); err = clSetKernelArg(kernels["merge_hist"], 0, sizeof(cl_mem), &mems["partial_hist"]); err |= clSetKernelArg(kernels["merge_hist"], 1, sizeof(cl_mem), &mems["merge_hist"]); err |= clSetKernelArg(kernels["merge_hist"], 2, sizeof(unsigned int), &num_wg); CHECK_ERROR_OCL(err, "setting merge_hist arguments", return false); err = clSetKernelArg(kernels["hist_cdf"], 0, sizeof(cl_mem), &mems["merge_hist"]); CHECK_ERROR_OCL(err, "setting hist_cdf arguments", return false); err = clSetKernelArg(kernels["hist_eq"], 0, sizeof(cl_mem), &mems["image"]); err |= clSetKernelArg(kernels["hist_eq"], 1, sizeof(cl_mem), &mem_images[1]); err |= clSetKernelArg(kernels["hist_eq"], 2, sizeof(cl_mem), &mems["merge_hist"]); CHECK_ERROR_OCL(err, "setting histogram_equalisation arguments", return false); return true; } double HistEq::runCLKernels(bool recomputeMapping) { cl_int err; double start = omp_get_wtime(); err = clEnqueueNDRangeKernel(m_queue, kernels["transfer_data"], 2, NULL, global_sizes["transfer_data"], local_sizes["transfer_data"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing transfer_data kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["partial_hist"], 1, NULL, &global_sizes["partial_hist"][0], &local_sizes["partial_hist"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing partial_hist kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["merge_hist"], 1, NULL, &global_sizes["merge_hist"][0], &local_sizes["merge_hist"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing merge_hist kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["hist_cdf"], 1, NULL, &global_sizes["hist_cdf"][0], &local_sizes["hist_cdf"][0], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing hist_cdf kernel", return false); err = clEnqueueNDRangeKernel(m_queue, kernels["hist_eq"], 2, NULL, global_sizes["hist_eq"], local_sizes["hist_eq"], 0, NULL, NULL); CHECK_ERROR_OCL(err, "enqueuing histogram_equalisation kernel", return false); err = clFinish(m_queue); CHECK_ERROR_OCL(err, "running kernels", return false); return omp_get_wtime() - start; } bool HistEq::cleanupOpenCL() { clReleaseMemObject(mem_images[0]); clReleaseMemObject(mem_images[1]); clReleaseMemObject(mems["image"]); clReleaseMemObject(mems["merge_hist"]); clReleaseMemObject(mems["partial_hist"]); clReleaseKernel(kernels["transfer_data"]); clReleaseKernel(kernels["partial_hist"]); clReleaseKernel(kernels["merge_hist"]); clReleaseKernel(kernels["hist_cdf"]); clReleaseKernel(kernels["hist_eq"]); releaseCL(); return true; } bool HistEq::runReference(uchar* input, uchar* output) { // Check for cached result if (m_reference.data) { memcpy(output, m_reference.data, img_size.x*img_size.y*NUM_CHANNELS); reportStatus("Finished reference (cached)"); return true; } const int hist_size = PIXEL_RANGE+1; unsigned int brightness_hist[hist_size] = {0}; int brightness; float red, green, blue; reportStatus("Running reference"); int2 pos; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { red = getPixel(input, img_size, pos, 0); green = getPixel(input, img_size, pos, 1); blue = getPixel(input, img_size, pos, 2); brightness = std::max(std::max(red, green), blue); brightness_hist[brightness] ++; } } for (int i = 1; i < hist_size; i++) { brightness_hist[i] += brightness_hist[i-1]; } float3 rgb; float3 hsv; for (pos.y = 0; pos.y < img_size.y; pos.y++) { for (pos.x = 0; pos.x < img_size.x; pos.x++) { rgb.x = getPixel(input, img_size, pos, 0); rgb.y = getPixel(input, img_size, pos, 1); rgb.z = getPixel(input, img_size, pos, 2); hsv = RGBtoHSV(rgb); //Convert to HSV to get Hue and Saturation hsv.z = ((hist_size-1)*(brightness_hist[(int)hsv.z] - brightness_hist[0])) /(img_size.x*img_size.y - brightness_hist[0]); rgb = HSVtoRGB(hsv); //Convert back to RGB with the modified brightness for V setPixel(output, img_size, pos, 0, rgb.x); setPixel(output, img_size, pos, 1, rgb.y); setPixel(output, img_size, pos, 2, rgb.z); } } reportStatus("Finished reference"); // Cache result m_reference.width = img_size.y; m_reference.height = img_size.x; m_reference.data = new uchar[img_size.x*img_size.y*NUM_CHANNELS]; memcpy(m_reference.data, output, img_size.x*img_size.y*NUM_CHANNELS); return true; } <|start_filename|>src/ReinhardLocal.h<|end_filename|> // ReinhardLocal.h (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "Filter.h" namespace hdr { class ReinhardLocal : public Filter { public: ReinhardLocal(float _key=0.18f, float _sat=1.6f, float _epsilon=0.05, float _phi=8.0); virtual bool setupOpenCL(cl_context_properties context_prop[], const Params& params); virtual double runCLKernels(bool recomputeMapping); virtual bool cleanupOpenCL(); virtual bool runReference(uchar* input, uchar* output); protected: float key; //increase this to allow for more contrast in the darker regions float sat; //increase this for more colourful pictures float epsilon; //serves as an edge enhancing parameter float phi; //similar to epsilon, however the effects are only noticeable on smaller scales //information regarding all mipmap levels int num_mipmaps; int* m_width; //at index i this contains the width of the mipmap at index i int* m_height; //at index i this contains the height of the mipmap at index i int* m_offset; //at index i this contains the start point to store the mipmap at level i }; } <|start_filename|>src/ReinhardGlobal.h<|end_filename|> // ReinhardGlobal.h (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "Filter.h" namespace hdr { class ReinhardGlobal : public Filter { public: ReinhardGlobal(float _key=0.18f, float _sat=1.6f); virtual bool setupOpenCL(cl_context_properties context_prop[], const Params& params); virtual double runCLKernels(bool recomputeMapping); virtual bool cleanupOpenCL(); virtual bool runReference(uchar* input, uchar* output); protected: float key; //increase this to allow for more contrast in the darker regions float sat; //increase this for more colourful pictures }; } <|start_filename|>src/GradDom.h<|end_filename|> // GradDom.h (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "Filter.h" namespace hdr { class GradDom : public Filter { public: GradDom(float _adjust_alpha=0.1f, float _beta=0.85f, float _sat=0.5f); virtual bool setupOpenCL(cl_context_properties context_prop[], const Params& params); virtual double runCLKernels(bool recomputeMapping); virtual bool cleanupOpenCL(); virtual bool runReference(uchar* input, uchar* output); //computes the attenuation function for the gradients float* attenuate_func(float* lum); //solves the poisson equation to derive a new compressed dynamic range float* poissonSolver(float* lum, float* div_grad, float terminationCriterea=0.0005); protected: float adjust_alpha; //to adjust the gradients at each mipmap level. gradients smaller than alpha are slightly magnified float beta; //used to attenuate larger gradients float sat; //increase this for more colourful pictures //information regarding all mipmap levels int num_mipmaps; int* m_width; //at index i this contains the width of the mipmap at index i int* m_height; //at index i this contains the height of the mipmap at index i int* m_offset; //at index i this contains the start point to store the mipmap at level i float* m_divider; //at index i this contains the value the pixels of gradient magnitude are going to be divided by }; } <|start_filename|>android/src/com/uob/achohan/hdr/DrawerItem.java<|end_filename|> package com.uob.achohan.hdr; public class DrawerItem { String item; String[] options; public DrawerItem(String itemName, String[] choices) { item = itemName; options = choices; } public String getItemName() { return item; } public String[] getOptions() { return options; } } <|start_filename|>android/src/com/uob/achohan/hdr/MyGLRenderer.java<|end_filename|> // MyGLRenderer.java (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. package com.uob.achohan.hdr; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.List; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL10; import android.graphics.Point; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.Camera.Size; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.util.Log; /** * Provides drawing instructions for a GLSurfaceView object. This class * must override the OpenGL ES drawing lifecycle methods: * <ul> * <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceCreated}</li> * <li>{@link android.opengl.GLSurfaceView.Renderer#onDrawFrame}</li> * <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceChanged}</li> * </ul> */ public class MyGLRenderer implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener { private final String TAG = "hdr"; private final String vss = "attribute vec2 vPosition;\n" + "attribute vec2 vTexCoord;\n" + "varying vec2 texCoord;\n" + "void main() {\n" + " texCoord = vTexCoord;\n" + " gl_Position = vec4 ( vPosition.x, vPosition.y, 0.0, 1.0 );\n" + "}"; private final String camera_fss = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "uniform samplerExternalOES sTexture;\n" + "varying vec2 texCoord;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, texCoord);\n" + " //gl_FragColor = vec4(0, 0.75, 0, 1);\n" + "}"; private final String texture_fss = "precision mediump float;\n" + "uniform sampler2D sTexture;\n" + "varying vec2 texCoord;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, texCoord);\n" + "}"; private int[] hTex; private int[] glTextures; private int display_texture; private IntBuffer targetFramebuffer; private FloatBuffer vertexCoord; private FloatBuffer cameraTexCoord; private FloatBuffer openclTexCoord; private int hProgram; private int displayTextureProgram; private Camera mCamera; private SurfaceTexture mSTexture; private boolean mUpdateST = false; private ByteBuffer cameraBuffer; private MyGLSurfaceView mView; EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; //switch between HDR and Raw camera feed private boolean process_HDR; //Sizes private Point camera_res; //resolution of the camera image being captured private Point display_dim; //dimensions of the Android display. OpenGL viewport should be set to this //information about recomputing intervals private float recomputeInterval = 0.5f; //how often to recompute mappings in seconds private long lastRecomputeTime = System.currentTimeMillis(); //last time when mappings were computed private boolean recomputeMapping=true; //whether to compute mappings at next frame or not //computing FPS private int frames = 0; //number of frames in the second private long lastFPScomputeTime = System.nanoTime(); //time since last FPS was computed MyGLRenderer (MyGLSurfaceView view) { mView = view; float[] vertexCoordTmp = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f}; float[] textureCoordTmp = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f }; float[] openclCoordTmp = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }; vertexCoord = ByteBuffer.allocateDirect(12*4).order(ByteOrder.nativeOrder()).asFloatBuffer(); vertexCoord.put(vertexCoordTmp); vertexCoord.position(0); cameraTexCoord = ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer(); cameraTexCoord.put(textureCoordTmp); cameraTexCoord.position(0); openclTexCoord = ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer(); openclTexCoord.put(openclCoordTmp); openclTexCoord.position(0); } public void onSurfaceCreated (GL10 unused, EGLConfig config) { mCamera = Camera.open(); Camera.Parameters param = mCamera.getParameters(); /*List<Size> psize = param.getSupportedPictureSizes(); //get supported picture sizes if ( psize.size() > 0 ) { for (int i = 0; i < psize.size(); i++ ) { Log.d(TAG, psize.get(i).width + "x" + psize.get(i).height); } }*/ camera_res = new Point(1280, 720); param.setPictureSize(camera_res.x, camera_res.y); mCamera.setParameters(param); Log.d(TAG, "Camera Resoultion: " + mCamera.getParameters().getPictureSize().width + "x" + mCamera.getParameters().getPictureSize().height); initTex(); mSTexture = new SurfaceTexture (hTex[0]); mSTexture.setOnFrameAvailableListener(this); try { mCamera.setPreviewTexture(mSTexture); } catch ( IOException ioe ) { } initCL(camera_res.x, camera_res.y, glTextures[0], glTextures[1]); GLES20.glClearColor (1.0f, 1.0f, 0.0f, 1.0f); hProgram = loadShader(vss, camera_fss); displayTextureProgram = loadShader(vss, texture_fss); cameraBuffer = ByteBuffer.allocate(camera_res.y*camera_res.x*4); } public void onDrawFrame ( GL10 unused ) { int displayTexture=0; cameraToTexture(); displayTexture = applyHDRonTexture(); renderFromTexture(displayTexture); logFrame(); } public void onSurfaceChanged ( GL10 unused, int width, int height ) { GLES20.glViewport( 0, 0, width, height); Camera.Parameters param = mCamera.getParameters(); List<Size> psize = param.getSupportedPreviewSizes(); if ( psize.size() > 0 ) { int i; for ( i = 0; i < psize.size(); i++ ) { if ( psize.get(i).width < width || psize.get(i).height < height ) break; } if ( i > 0 ) i--; param.setPreviewSize(psize.get(i).width, psize.get(i).height); } mCamera.setParameters(param); mCamera.startPreview(); } //converts information from the Camera Texture to an OpenGL 2D texture private int cameraToTexture() { GLES20.glClear( GLES20.GL_COLOR_BUFFER_BIT ); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, targetFramebuffer.get(0)); int fbret = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER); if (fbret != GLES20.GL_FRAMEBUFFER_COMPLETE) { Log.d(TAG, "unable to bind fbo" + fbret); } GLES20.glViewport(0, 0, camera_res.x, camera_res.y); GLES20.glClear( GLES20.GL_COLOR_BUFFER_BIT ); synchronized(this) { if (mUpdateST) { mSTexture.updateTexImage(); mUpdateST = false; } } GLES20.glUseProgram(hProgram); int ph = GLES20.glGetAttribLocation(hProgram, "vPosition"); int tch = GLES20.glGetAttribLocation (hProgram, "vTexCoord"); int th = GLES20.glGetUniformLocation (hProgram, "sTexture"); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, hTex[0]); GLES20.glUniform1i(th, 0); GLES20.glVertexAttribPointer(ph, 2, GLES20.GL_FLOAT, false, 4*3, vertexCoord); GLES20.glVertexAttribPointer(tch, 2, GLES20.GL_FLOAT, false, 4*2, cameraTexCoord); GLES20.glEnableVertexAttribArray(ph); GLES20.glEnableVertexAttribArray(tch); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, glTextures[0]); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glFinish(); return glTextures[0]; } //applies HDR on the texture private int applyHDRonTexture() { if (process_HDR) { processFrame(recomputeMapping); return glTextures[1]; } return glTextures[0]; } //displays the result of OpenCL filters private void renderFromTexture(int displayTexture) { GLES20.glViewport(0, 0, display_dim.x, display_dim.y); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); GLES20.glUseProgram(displayTextureProgram); int ph = GLES20.glGetAttribLocation(displayTextureProgram, "vPosition"); int tch = GLES20.glGetAttribLocation(displayTextureProgram, "vTexCoord"); int th = GLES20.glGetUniformLocation(displayTextureProgram, "sTexture"); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, displayTexture); GLES20.glUniform1i(th, 0); GLES20.glVertexAttribPointer(ph, 2, GLES20.GL_FLOAT, false, 4*3, vertexCoord); GLES20.glVertexAttribPointer(tch, 2, GLES20.GL_FLOAT, true, 4*2, openclTexCoord); GLES20.glEnableVertexAttribArray(ph); GLES20.glEnableVertexAttribArray(tch); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glFinish(); } //initialise all the required textures private void initTex() { hTex = new int[1]; glTextures = new int[2]; GLES20.glGenTextures ( 1, hTex, 0 ); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, hTex[0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); GLES20.glGenTextures ( 2, glTextures, 0 ); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, glTextures[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_LINEAR_MIPMAP_NEAREST); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, camera_res.x, camera_res.y, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, glTextures[1]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, camera_res.x, camera_res.y, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); targetFramebuffer = IntBuffer.allocate(1); GLES20.glGenFramebuffers(1, targetFramebuffer); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, targetFramebuffer.get(0)); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, glTextures[0], 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); } public synchronized void onFrameAvailable ( SurfaceTexture st ) { mUpdateST = true; mView.requestRender(); } private static int loadShader ( String vertex_shader, String fragment_shader ) { int vshader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER); GLES20.glShaderSource(vshader, vertex_shader); GLES20.glCompileShader(vshader); int[] compiled = new int[1]; GLES20.glGetShaderiv(vshader, GLES20.GL_COMPILE_STATUS, compiled, 0); if (compiled[0] == 0) { Log.e("Shader", "Could not compile vshader"); Log.v("Shader", "Could not compile vshader:"+GLES20.glGetShaderInfoLog(vshader)); GLES20.glDeleteShader(vshader); vshader = 0; } int fshader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER); GLES20.glShaderSource(fshader, fragment_shader); GLES20.glCompileShader(fshader); GLES20.glGetShaderiv(fshader, GLES20.GL_COMPILE_STATUS, compiled, 0); if (compiled[0] == 0) { Log.e("Shader", "Could not compile fshader"); Log.v("Shader", "Could not compile fshader:"+GLES20.glGetShaderInfoLog(fshader)); GLES20.glDeleteShader(fshader); fshader = 0; } int program = GLES20.glCreateProgram(); GLES20.glAttachShader(program, vshader); GLES20.glAttachShader(program, fshader); GLES20.glLinkProgram(program); return program; } private void deleteTex() { GLES20.glDeleteTextures (1, hTex, 0); } public void close() { mUpdateST = false; mSTexture.release(); mCamera.stopPreview(); mCamera.release(); killCL(); deleteTex(); } public void logFrame() { //check whether to recompute mappings at next frame or not if(System.currentTimeMillis() - lastRecomputeTime >= recomputeInterval*1000) { recomputeMapping = true; lastRecomputeTime = System.currentTimeMillis(); } else recomputeMapping = false; //work out FPS frames++; if(System.nanoTime() - lastFPScomputeTime >= 1000000000) { Log.d(TAG, "FPS: " + frames); frames = 0; lastFPScomputeTime = System.nanoTime(); } } //setters public void setDisplayDim(Point displayDim) { display_dim = displayDim; } public void setHDR(boolean process) { process_HDR = process; } /////////////////////////////////////////////////////////////////////////////////////////JNI public void updateStatus(String text) { Log.d(TAG, text); } public static native void initCL(int width, int height, int input_texid, int output_texid); public static native void processFrame(boolean recomputeMapping); public static native void killCL(); static { System.loadLibrary("hdr"); } } <|start_filename|>android/src/com/uob/achohan/hdr/HDR.java<|end_filename|> // HDR.java (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. package com.uob.achohan.hdr; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.hardware.Camera; import android.graphics.Point; import android.hardware.Camera.Size; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class HDR extends Activity { private MyGLSurfaceView mView; private WakeLock mWL; private final String TAG = "hdr"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWL = ((PowerManager)getSystemService (Context.POWER_SERVICE)).newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock"); mWL.acquire(); setContentView(R.layout.main); Display display = getWindowManager().getDefaultDisplay(); Point displayDim = new Point(); display.getSize(displayDim); final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout); final ListView navList = (ListView) findViewById(R.id.drawer); List<DrawerItem> dataList = new ArrayList<DrawerItem>(); dataList.add(new DrawerItem("HDR", new String[]{"On", "Off"})); CustomDrawerAdapter adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item, dataList); navList.setAdapter(adapter); navList.setOnItemClickListener(new ListView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){ drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){ @Override public void onDrawerClosed(View drawerView){ super.onDrawerClosed(drawerView); } }); drawer.closeDrawer(navList); } }); mView = (MyGLSurfaceView) findViewById(R.id.surfaceviewclass); mView.setDisplayDim(displayDim); } @Override protected void onPause() { if ( mWL.isHeld() ) mWL.release(); mView.onPause(); super.onPause(); } @Override protected void onResume() { super.onResume(); mView.onResume(); mWL.acquire(); } public void changeConfig(int item, int option) { Log.d(TAG, "item " + item + " pos " + option); if (item == 0) mView.setHDR(option); } } <|start_filename|>linux/hdr.cpp<|end_filename|> // hdr.cpp (HDR) // Copyright (c) 2014, <NAME>, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <exception> #include <stdexcept> #include <sys/stat.h> #include <stdlib.h> #include <sys/types.h> #include <dirent.h> #include "jpeglib.h" #include <SDL2/SDL_image.h> #include "ReinhardGlobal.h" #include "ReinhardLocal.h" #include "GradDom.h" #include "HistEq.h" #define PIXEL_RANGE 255 #define NUM_CHANNELS 4 using namespace hdr; using namespace std; struct _options_ { map<string, Filter*> filters; map<string, unsigned int> methods; _options_() { filters["histEq"] = new HistEq(); filters["reinhardGlobal"] = new ReinhardGlobal(); filters["reinhardLocal"] = new ReinhardLocal(); filters["gradDom"] = new GradDom(); methods["reference"] = METHOD_REFERENCE; methods["opencl"] = METHOD_OPENCL; } } Options; void clinfo(); void printUsage(); int updateStatus(const char *format, va_list args); void checkError(const char* message, int err); bool is_dir(const char* path); bool hasEnding (string const &fullString, string const &ending); Image readJPG(const char* filePath); void writeJPG(Image &image, const char* filePath); int main(int argc, char *argv[]) { Filter *filter = NULL; Filter::Params params; unsigned int method = 0; string image_path; // Parse arguments for (int i = 1; i < argc; i++) { if (!filter && (Options.filters.find(argv[i]) != Options.filters.end())) { //tonemap filter filter = Options.filters[argv[i]]; } else if (!method && Options.methods.find(argv[i]) != Options.methods.end()) { method = Options.methods[argv[i]]; //implementation method } else if (!strcmp(argv[i], "-cldevice")) { //run on the given device ++i; if (i >= argc) { cout << "Platform/device index required with -cldevice." << endl; exit(1); } char *next; params.platformIndex = strtoul(argv[i], &next, 10); if (strlen(next) == 0 || next[0] != ':') { cout << "Invalid platform/device index." << endl; exit(1); } params.deviceIndex = strtoul(++next, &next, 10); if (strlen(next) != 0) { cout << "Invalid platform/device index." << endl; exit(1); } } else if (!strcmp(argv[i], "-image")) { //apply filter on the given image ++i; if (i >= argc) { cout << "Invalid image path with -image." << endl; exit(1); } image_path = argv[i]; } else if (!strcmp(argv[i], "-clinfo")) { clinfo(); exit(0); } } if (filter == NULL || method == 0) { //invalid arguments printUsage(); exit(1); } if (image_path == "") image_path = "../test_images/lena-300x300.jpg"; Image input = readJPG(image_path.c_str()); // Run filter filter->setStatusCallback(updateStatus); Image output = {(uchar*) calloc(input.width*input.height*NUM_CHANNELS, sizeof(uchar)), input.width, input.height}; std::cout << "--------------------------------Tonemapping using " << filter->getName() << std::endl; filter->setImageSize(input.width, input.height); switch (method) { case METHOD_REFERENCE: filter->runReference(input.data, output.data); break; case METHOD_OPENCL: filter->setupOpenCL(NULL, params); filter->runOpenCL(input.data, output.data); filter->cleanupOpenCL(); break; default: assert(false && "Invalid method."); } //Save the file int lastindex; if (is_dir(image_path.c_str())) image_path = image_path.substr(0, image_path.find_last_of("/")); else image_path = image_path.substr(0, image_path.find_last_of(".")); string image_name = image_path.substr(image_path.find_last_of("/")+1, 100); string output_path = "../output_images/" + image_name + "_"; output_path = output_path + filter->getName() + ".jpg"; writeJPG(output, output_path.c_str()); return 0; } Image readJPG(const char* filePath) { SDL_Surface *input = IMG_Load(filePath); if (!input) throw std::runtime_error("Problem opening input file"); uchar* udata = (uchar*) input->pixels; uchar* data = (uchar*) calloc(NUM_CHANNELS*(input->w * input->h), sizeof(uchar)); for (int y = 0; y < input->h; y++) { for (int x = 0; x < input->w; x++) { for (int j=0; j<3; j++) { data[(x + y*input->w)*NUM_CHANNELS + j] = (uchar)udata[(x + y*input->w)*3 + j]; } data[(x + y*input->w)*NUM_CHANNELS + 3] = 0; } } Image image = {data, input->w, input->h}; free(input); return image; } void writeJPG(Image &img, const char* filePath) { FILE *outfile = fopen(filePath, "wb"); if (!outfile) throw std::runtime_error("Problem opening output file"); struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = img.width; cinfo.image_height = img.height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); /*set the quality [0..100] */ jpeg_set_quality (&cinfo, 75, true); jpeg_start_compress(&cinfo, true); uchar* charImageData = (uchar*) calloc(3*img.width*img.height, sizeof(uchar)); int2 pos; int2 img_size = (int2){img.width, img.height}; for (pos.y = 0; pos.y < img.height; pos.y++) { for (pos.x = 0; pos.x < img.width; pos.x++) { for (int i=0; i < 3; i++) charImageData[(pos.x + pos.y*img.width)*3 + i] = getPixel(img.data, img_size, pos, i); } } JSAMPROW row_pointer; /* pointer to a single row */ while (cinfo.next_scanline < cinfo.image_height) { row_pointer = (JSAMPROW) &charImageData[cinfo.next_scanline*cinfo.input_components*img.width]; jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); } void clinfo() { #define MAX_PLATFORMS 8 #define MAX_DEVICES 8 #define MAX_NAME 256 cl_uint numPlatforms, numDevices; cl_platform_id platforms[MAX_PLATFORMS]; cl_device_id devices[MAX_DEVICES]; char name[MAX_NAME]; cl_int err; err = clGetPlatformIDs(MAX_PLATFORMS, platforms, &numPlatforms); checkError("Error retrieving platforms\n", err); if (numPlatforms == 0) { cout << "No platforms found." << endl; return; } for (int p = 0; p < numPlatforms; p++) { clGetPlatformInfo(platforms[p], CL_PLATFORM_NAME, MAX_NAME, name, NULL); cout << endl << "Platform " << p << ": " << name << endl; err = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, MAX_DEVICES, devices, &numDevices); checkError("Error retrieving devices\n", err); if (numDevices == 0) { cout << "No devices found." << endl; continue; } for (int d = 0; d < numDevices; d++) { clGetDeviceInfo(devices[d], CL_DEVICE_NAME, MAX_NAME, name, NULL); cout << "-> Device " << d << ": " << name << endl; } } cout << endl; } void printUsage() { cout << endl << "Usage: hdr FILTER METHOD [-image PATH] [-cldevice P:D]"; cout << endl << " hdr -clinfo" << endl; cout << endl << "Where FILTER is one of:" << endl; map<string, Filter*>::iterator fItr; for (fItr = Options.filters.begin(); fItr != Options.filters.end(); fItr++) { cout << "\t" << fItr->first << endl; } cout << endl << "Where METHOD is one of:" << endl; map<string, unsigned int>::iterator mItr; for (mItr = Options.methods.begin(); mItr != Options.methods.end(); mItr++) { cout << "\t" << mItr->first << endl; } cout << endl << "If specifying an OpenCL device with -cldevice, " << endl << "P and D correspond to the platform and device " << endl << "indices reported by running -clinfo." << endl; cout << endl; } int updateStatus(const char *format, va_list args) { vprintf(format, args); printf("\n"); return 0; } void checkError(const char* message, int err) { if (err != CL_SUCCESS) { printf("%s %d\n", message, err); exit(1); } } bool is_dir(const char* path) { struct stat buf; stat(path, &buf); return S_ISDIR(buf.st_mode); } bool hasEnding (string const &fullString, string const &ending) { if (fullString.length() >= ending.length()) { return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } } <|start_filename|>android/src/com/uob/achohan/hdr/CustomDrawerAdapter.java<|end_filename|> package com.uob.achohan.hdr; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> { Context context; List<DrawerItem> drawerItemList; int layoutResID; public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerItem> listItems) { super(context, layoutResourceID, listItems); this.context = context; this.drawerItemList = listItems; this.layoutResID = layoutResourceID; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub DrawerItemHolder drawerHolder; View view = convertView; if (view == null) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); drawerHolder = new DrawerItemHolder(); view = inflater.inflate(layoutResID, parent, false); drawerHolder.spinnerLayout = (LinearLayout) view.findViewById(R.layout.custom_drawer_item); drawerHolder.itemName = (TextView) view.findViewById(R.id.drawerText); drawerHolder.spinner = (Spinner) view.findViewById(R.id.drawerSpinner); view.setTag(drawerHolder); } else drawerHolder = (DrawerItemHolder) view.getTag(); DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position); CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(context, R.layout.custom_spinner_item, dItem.getOptions()); drawerHolder.spinner.setAdapter(adapter); drawerHolder.itemName.setText(dItem.getItemName()); drawerHolder.spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int spinner_item, long arg3) { selectedItem(position, spinner_item); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); setDefaultValues(drawerHolder.spinner, position); return view; } private void selectedItem(int property_modified, int chosen_option) { ((HDR) context).changeConfig(property_modified, chosen_option); } private void setDefaultValues(Spinner spinner, int position) { if (position == 0) spinner.setSelection(0); if (position == 1) spinner.setSelection(0); if (position == 2) spinner.setSelection(0); if (position == 3) spinner.setSelection(0); if (position == 4) spinner.setSelection(2); } private static class DrawerItemHolder { TextView itemName; LinearLayout spinnerLayout; Spinner spinner; } }
amirchohan/HDR
<|start_filename|>src/main/java/com/coveo/FMT.java<|end_filename|> package com.coveo; import com.google.common.base.Charsets; import com.google.common.io.CharSink; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; /** * FMT class. * * @author guisim * @version $Id: $Id */ @Mojo(name = "format", defaultPhase = LifecyclePhase.PROCESS_SOURCES, threadSafe = true) public class FMT extends AbstractFMT { /** * Hook called when the processd file is not compliant with the formatter. * * @param file the file that is not compliant * @param formatted the corresponding formatted of the file. */ @Override protected void onNonComplyingFile(File file, String formatted) throws IOException { CharSink sink = Files.asCharSink(file, Charsets.UTF_8); sink.write(formatted); } /** * Provides the name of the label used when a non-formatted file is found. * * @return the label to use in the log */ @Override protected String getProcessingLabel() { return "reformatted"; } } <|start_filename|>src/main/java/com/coveo/Check.java<|end_filename|> package com.coveo; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.String.format; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; /** * Check mojo that will ensure all files are formatted. If some files are not formatted, an * exception is thrown. */ @Mojo(name = "check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) public class Check extends AbstractFMT { /** Flag to display or not the files that are not compliant. */ @Parameter(defaultValue = "true", property = "displayFiles") private boolean displayFiles; /** Limit the number of non-complying files to display */ @Parameter(defaultValue = "100", property = "displayLimit") private int displayLimit; /** List of unformatted files. */ private List<String> filesNotFormatted = new ArrayList<String>(); /** * Post Execute action. It is called at the end of the execute method. Subclasses can add extra * checks. * * @param filesProcessed the list of processed files by the formatter * @param nonComplyingFiles the number of files that are not compliant * @throws MojoFailureException if there is an exception */ @Override protected void postExecute(List<String> filesProcessed, int nonComplyingFiles) throws MojoFailureException { if (nonComplyingFiles > 0) { String message = "Found " + nonComplyingFiles + " non-complying files, failing build"; getLog().error(message); getLog().error("To fix formatting errors, run \"mvn com.coveo:fmt-maven-plugin:format\""); // do not support limit < 1 displayLimit = max(1, displayLimit); // Display first displayLimit files not formatted if (displayFiles) { for (String path : filesNotFormatted.subList(0, min(displayLimit, filesNotFormatted.size()))) { getLog().error("Non complying file: " + path); } if (nonComplyingFiles > displayLimit) { getLog().error(format("... and %d more files.", nonComplyingFiles - displayLimit)); } } throw new MojoFailureException(message); } } /** * Hook called when the processd file is not compliant with the formatter. * * @param file the file that is not compliant * @param formatted the corresponding formatted of the file. */ @Override protected void onNonComplyingFile(final File file, final String formatted) throws IOException { filesNotFormatted.add(file.getAbsolutePath()); } /** * Provides the name of the label used when a non-formatted file is found. * * @return the label to use in the log */ @Override protected String getProcessingLabel() { return "non-complying"; } } <|start_filename|>src/test/resources/importunused/src/main/java/HelloWorld1.java<|end_filename|> package notestsource.src.main.java; import static com.google.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.common.base.Preconditions; import java.util.List; import java.util.Set; import javax.annotations.Nullable; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; public class HelloWorld1 { <T> void check(@Nullable List<T> x) { Preconditions.checkNodeNull(x); } void f() { List<String> xs = null; assertThat(xs).isNull(); try { check(xs); fail(); } catch (NullPointerException e) { } } }
sormuras/fmt-maven-plugin