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 "UrlHandler.h"
9
10 #include "microhttpd.h"
11 #include "../Request.h"
12 #include "../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"); SkDrawCommand::MakeJsonColor(writer, target);
56
57 bool changed = false;
58 for (int i = n + 1; i < n + count; ++i) {
59 int index = i % count;
60 if (index == 0) {
61 // reset canvas for wraparound
62 canvas->restoreToCount(saveCount);
63 canvas->clear(SK_ColorWHITE);
64 saveCount = canvas->save();
65 }
66 request->fDebugCanvas->getDrawCommandAt(index)->execute(canvas);
67 SkColor current = request->getPixel(x, y);
68 if (current != target) {
69 writer.appendName("endColor"); SkDrawCommand::MakeJsonColor(writer, current);
70 writer.appendS32("endOp", index);
71 changed = true;
72 break;
73 }
74 }
75 if (!changed) {
76 writer.appendName("endColor"); SkDrawCommand::MakeJsonColor(writer, target);
77 writer.appendS32("endOp", n);
78 }
79 canvas->restoreToCount(saveCount);
80
81 writer.endObject(); // root
82 writer.flush();
83 return SendData(connection, stream.detachAsData().get(), "application/json");
84 }
85