1/*
2 * Copyright 2013 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 "SkLua.h"
9#include "SkLuaCanvas.h"
10#include "SkPicture.h"
11#include "SkCommandLineFlags.h"
12#include "SkGraphics.h"
13#include "SkStream.h"
14#include "SkData.h"
15#include "picture_utils.h"
16#include "SkOSFile.h"
17#include "SkImageDecoder.h"
18
19#include <stdlib.h>
20
21extern "C" {
22    #include "lua.h"
23    #include "lualib.h"
24    #include "lauxlib.h"
25}
26
27static const char gStartCanvasFunc[] = "sk_scrape_startcanvas";
28static const char gEndCanvasFunc[] = "sk_scrape_endcanvas";
29static const char gAccumulateFunc[] = "sk_scrape_accumulate";
30static const char gSummarizeFunc[] = "sk_scrape_summarize";
31
32// Example usage for the modulo flag:
33// for i in {0..5}; do lua_pictures --skpPath SKP_PATH -l YOUR_SCRIPT --modulo $i 6 &; done
34DEFINE_string(modulo, "", "[--modulo <remainder> <divisor>]: only run tests for which "
35              "testIndex %% divisor == remainder.");
36DEFINE_string2(skpPath, r, "", "Read this .skp file or .skp files from this dir");
37DEFINE_string2(luaFile, l, "", "File containing lua script to run");
38DEFINE_string2(headCode, s, "", "Optional lua code to call at beginning");
39DEFINE_string2(tailFunc, s, "", "Optional lua function to call at end");
40DEFINE_bool2(quiet, q, false, "Silence all non-error related output");
41
42static SkPicture* load_picture(const char path[]) {
43    SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(path));
44    SkPicture* pic = nullptr;
45    if (stream.get()) {
46        pic = SkPicture::CreateFromStream(stream.get());
47    }
48    return pic;
49}
50
51static void call_canvas(lua_State* L, SkLuaCanvas* canvas,
52                        const char pictureFile[], const char funcName[]) {
53    lua_getglobal(L, funcName);
54    if (!lua_isfunction(L, -1)) {
55        int t = lua_type(L, -1);
56        SkDebugf("--- expected %s function %d, ignoring.\n", funcName, t);
57        lua_settop(L, -2);
58    } else {
59        canvas->pushThis();
60        lua_pushstring(L, pictureFile);
61        if (lua_pcall(L, 2, 0, 0) != LUA_OK) {
62            SkDebugf("lua err: %s\n", lua_tostring(L, -1));
63        }
64    }
65}
66
67int tool_main(int argc, char** argv);
68int tool_main(int argc, char** argv) {
69    SkCommandLineFlags::SetUsage("apply lua script to .skp files.");
70    SkCommandLineFlags::Parse(argc, argv);
71
72    if (FLAGS_skpPath.isEmpty()) {
73        SkDebugf(".skp files or directories are required.\n");
74        exit(-1);
75    }
76    if (FLAGS_luaFile.isEmpty()) {
77        SkDebugf("missing luaFile(s)\n");
78        exit(-1);
79    }
80
81    const char* summary = gSummarizeFunc;
82    if (!FLAGS_tailFunc.isEmpty()) {
83        summary = FLAGS_tailFunc[0];
84    }
85
86    SkAutoGraphics ag;
87    SkLua L(summary);
88
89    for (int i = 0; i < FLAGS_luaFile.count(); ++i) {
90        SkAutoDataUnref data(SkData::NewFromFileName(FLAGS_luaFile[i]));
91        if (nullptr == data.get()) {
92            data.reset(SkData::NewEmpty());
93        }
94        if (!FLAGS_quiet) {
95            SkDebugf("loading %s...\n", FLAGS_luaFile[i]);
96        }
97        if (!L.runCode(data->data(), data->size())) {
98            SkDebugf("failed to load luaFile %s\n", FLAGS_luaFile[i]);
99            exit(-1);
100        }
101    }
102
103    if (!FLAGS_headCode.isEmpty()) {
104        L.runCode(FLAGS_headCode[0]);
105    }
106
107    int moduloRemainder = -1;
108    int moduloDivisor = -1;
109    SkString moduloStr;
110
111    if (FLAGS_modulo.count() == 2) {
112        moduloRemainder = atoi(FLAGS_modulo[0]);
113        moduloDivisor = atoi(FLAGS_modulo[1]);
114        if (moduloRemainder < 0 || moduloDivisor <= 0 || moduloRemainder >= moduloDivisor) {
115            SkDebugf("invalid modulo values.\n");
116            return -1;
117        }
118    }
119
120    for (int i = 0; i < FLAGS_skpPath.count(); i ++) {
121        SkTArray<SkString> paths;
122        if (sk_isdir(FLAGS_skpPath[i])) {
123            // Add all .skp in this directory.
124            const SkString directory(FLAGS_skpPath[i]);
125            SkString filename;
126            SkOSFile::Iter iter(FLAGS_skpPath[i], "skp");
127            while(iter.next(&filename)) {
128                paths.push_back() = SkOSPath::Join(directory.c_str(), filename.c_str());
129            }
130        } else {
131            // Add this as an .skp itself.
132            paths.push_back() = FLAGS_skpPath[i];
133        }
134
135        for (int i = 0; i < paths.count(); i++) {
136            if (moduloRemainder >= 0) {
137                if ((i % moduloDivisor) != moduloRemainder) {
138                    continue;
139                }
140                moduloStr.printf("[%d.%d] ", i, moduloDivisor);
141            }
142            const char* path = paths[i].c_str();
143            if (!FLAGS_quiet) {
144                SkDebugf("scraping %s %s\n", path, moduloStr.c_str());
145            }
146
147            SkAutoTUnref<SkPicture> pic(load_picture(path));
148            if (pic.get()) {
149                SkAutoTUnref<SkLuaCanvas> canvas(
150                                    new SkLuaCanvas(SkScalarCeilToInt(pic->cullRect().width()),
151                                                    SkScalarCeilToInt(pic->cullRect().height()),
152                                                    L.get(), gAccumulateFunc));
153
154                call_canvas(L.get(), canvas.get(), path, gStartCanvasFunc);
155                canvas->drawPicture(pic);
156                call_canvas(L.get(), canvas.get(), path, gEndCanvasFunc);
157
158            } else {
159                SkDebugf("failed to load\n");
160            }
161        }
162    }
163    return 0;
164}
165
166#if !defined SK_BUILD_FOR_IOS
167int main(int argc, char * const argv[]) {
168    return tool_main(argc, (char**) argv);
169}
170#endif
171