1 /*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "tools/skiaserve/urlhandlers/UrlHandler.h"
9
10 #include "microhttpd.h"
11 #include "tools/skiaserve/Request.h"
12 #include "tools/skiaserve/Response.h"
13
14 using namespace Response;
15
canHandle(const char * method,const char * url)16 bool BreakHandler::canHandle(const char* method, const char* url) {
17 static const char* kBasePath = "/break";
18 return 0 == strcmp(method, MHD_HTTP_METHOD_GET) &&
19 0 == strncmp(url, kBasePath, strlen(kBasePath));
20 }
21
handle(Request * request,MHD_Connection * connection,const char * url,const char * method,const char * upload_data,size_t * upload_data_size)22 int BreakHandler::handle(Request* request, MHD_Connection* connection,
23 const char* url, const char* method,
24 const char* upload_data, size_t* upload_data_size) {
25 SkTArray<SkString> commands;
26 SkStrSplit(url, "/", &commands);
27
28 if (!request->hasPicture() || commands.count() != 4) {
29 return MHD_NO;
30 }
31
32 // /break/<n>/<x>/<y>
33 int n;
34 sscanf(commands[1].c_str(), "%d", &n);
35 int x;
36 sscanf(commands[2].c_str(), "%d", &x);
37 int y;
38 sscanf(commands[3].c_str(), "%d", &y);
39
40 int count = request->fDebugCanvas->getSize();
41 SkASSERT(n < count);
42
43 SkCanvas* canvas = request->getCanvas();
44 canvas->clear(SK_ColorWHITE);
45 int saveCount = canvas->save();
46 for (int i = 0; i <= n; ++i) {
47 request->fDebugCanvas->getDrawCommandAt(i)->execute(canvas);
48 }
49 SkColor target = request->getPixel(x, y);
50
51 SkDynamicMemoryWStream stream;
52 SkJSONWriter writer(&stream, SkJSONWriter::Mode::kFast);
53 writer.beginObject(); // root
54
55 writer.appendName("startColor");
56 DrawCommand::MakeJsonColor(writer, target);
57
58 bool changed = false;
59 for (int i = n + 1; i < n + count; ++i) {
60 int index = i % count;
61 if (index == 0) {
62 // reset canvas for wraparound
63 canvas->restoreToCount(saveCount);
64 canvas->clear(SK_ColorWHITE);
65 saveCount = canvas->save();
66 }
67 request->fDebugCanvas->getDrawCommandAt(index)->execute(canvas);
68 SkColor current = request->getPixel(x, y);
69 if (current != target) {
70 writer.appendName("endColor");
71 DrawCommand::MakeJsonColor(writer, current);
72 writer.appendS32("endOp", index);
73 changed = true;
74 break;
75 }
76 }
77 if (!changed) {
78 writer.appendName("endColor");
79 DrawCommand::MakeJsonColor(writer, target);
80 writer.appendS32("endOp", n);
81 }
82 canvas->restoreToCount(saveCount);
83
84 writer.endObject(); // root
85 writer.flush();
86 return SendData(connection, stream.detachAsData().get(), "application/json");
87 }
88