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 "SkJSONCanvas.h"
12 #include "../Request.h"
13 #include "../Response.h"
14 
15 using namespace Response;
16 
canHandle(const char * method,const char * url)17 bool InfoHandler::canHandle(const char* method, const char* url) {
18     const char* kBaseName = "/info";
19     return 0 == strcmp(method, MHD_HTTP_METHOD_GET) &&
20            0 == strncmp(url, kBaseName, strlen(kBaseName));
21 }
22 
handle(Request * request,MHD_Connection * connection,const char * url,const char * method,const char * upload_data,size_t * upload_data_size)23 int InfoHandler::handle(Request* request, MHD_Connection* connection,
24                         const char* url, const char* method,
25                         const char* upload_data, size_t* upload_data_size) {
26     SkTArray<SkString> commands;
27     SkStrSplit(url, "/", &commands);
28 
29     if (!request->fPicture.get() || commands.count() > 2) {
30         return MHD_NO;
31     }
32 
33     // drawTo
34     SkAutoTUnref<SkSurface> surface(request->createCPUSurface());
35     SkCanvas* canvas = surface->getCanvas();
36 
37     int n;
38     // /info or /info/N
39     if (commands.count() == 1) {
40         n = request->fDebugCanvas->getSize() - 1;
41     } else {
42         sscanf(commands[1].c_str(), "%d", &n);
43     }
44 
45     // TODO this is really slow and we should cache the matrix and clip
46     request->fDebugCanvas->drawTo(canvas, n);
47 
48     // make some json
49     SkMatrix vm = request->fDebugCanvas->getCurrentMatrix();
50     SkIRect clip = request->fDebugCanvas->getCurrentClip();
51     Json::Value info(Json::objectValue);
52     info["ViewMatrix"] = SkJSONCanvas::MakeMatrix(vm);
53     info["ClipRect"] = SkJSONCanvas::MakeIRect(clip);
54 
55     std::string json = Json::FastWriter().write(info);
56 
57     // We don't want the null terminator so strlen is correct
58     SkAutoTUnref<SkData> data(SkData::NewWithCopy(json.c_str(), strlen(json.c_str())));
59     return SendData(connection, data, "application/json");
60 }
61 
62