root/lang/cplusplus/twitter-v8/shell.cc @ 18820

Revision 18820, 9.0 kB (checked in by mattn, 6 years ago)

wassr追加

Line 
1// Copyright 2008 Google Inc. All Rights Reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include <v8.h>
29#include <cstring>
30#include <cstdio>
31#include <cstdlib>
32#include <locale.h>
33#include "twitter.h"
34#include "wassr.h"
35
36void RunShell(v8::Handle<v8::Context> context);
37bool ExecuteString(v8::Handle<v8::String> source,
38                   v8::Handle<v8::Value> name,
39                   bool print_result);
40v8::Handle<v8::Value> Print(const v8::Arguments& args);
41v8::Handle<v8::Value> Load(const v8::Arguments& args);
42v8::Handle<v8::Value> Quit(const v8::Arguments& args);
43v8::Handle<v8::Value> Version(const v8::Arguments& args);
44v8::Handle<v8::String> ReadFile(const char* name);
45void ProcessRuntimeFlags(int argc, char* argv[]);
46
47int main(int argc, char* argv[]) {
48  setlocale(LC_CTYPE, "");
49
50  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
51  v8::HandleScope handle_scope;
52  // Create a template for the global object.
53  v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
54  // Bind the global 'print' function to the C++ Print callback.
55  global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
56  // Bind the global 'load' function to the C++ Load callback.
57  global->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load));
58  // Bind the 'quit' function
59  global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit));
60  // Bind the 'version' function
61  global->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version));
62
63  // twitter
64  v8::Local<v8::FunctionTemplate> twitter_ft = v8::FunctionTemplate::New();
65  v8::Local<v8::Template> twitter_pt = twitter_ft->PrototypeTemplate();
66  twitter_pt->Set("friendsTimeline", v8::FunctionTemplate::New(TwitterFriendsTimeline));
67  twitter_pt->Set("userTimeline", v8::FunctionTemplate::New(TwitterUserTimeline));
68  twitter_pt->Set("publicTimeline", v8::FunctionTemplate::New(TwitterPublicTimeline));
69  twitter_pt->Set("updateStatus", v8::FunctionTemplate::New(TwitterUpdateStatus));
70  v8::Local<v8::ObjectTemplate> twitter_it = twitter_ft->InstanceTemplate();
71  twitter_it->Set(v8::String::New("username"), v8::String::New(""));
72  twitter_it->Set(v8::String::New("password"), v8::String::New(""));
73  global->Set(v8::String::New("Twitter"), twitter_ft);
74
75  // wassr
76  v8::Local<v8::FunctionTemplate> wassr_ft = v8::FunctionTemplate::New();
77  v8::Local<v8::Template> wassr_pt = wassr_ft->PrototypeTemplate();
78  wassr_pt->Set("friendsTimeline", v8::FunctionTemplate::New(WassrFriendsTimeline));
79  wassr_pt->Set("userTimeline", v8::FunctionTemplate::New(WassrUserTimeline));
80  wassr_pt->Set("publicTimeline", v8::FunctionTemplate::New(WassrPublicTimeline));
81  wassr_pt->Set("updateStatus", v8::FunctionTemplate::New(WassrUpdateStatus));
82  v8::Local<v8::ObjectTemplate> wassr_it = wassr_ft->InstanceTemplate();
83  wassr_it->Set(v8::String::New("username"), v8::String::New(""));
84  wassr_it->Set(v8::String::New("password"), v8::String::New(""));
85  global->Set(v8::String::New("Wassr"), wassr_ft);
86
87  // Create a new execution environment containing the built-in
88  // functions
89  v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
90  // Enter the newly created execution environment.
91  v8::Context::Scope context_scope(context);
92  bool run_shell = (argc == 1);
93  for (int i = 1; i < argc; i++) {
94    const char* str = argv[i];
95    if (strcmp(str, "--shell") == 0) {
96      run_shell = true;
97    } else if (strncmp(str, "--", 2) == 0) {
98      printf("Warning: unknown flag %s.\n", str);
99    } else {
100      // Use all other arguments as names of files to load and run.
101      v8::HandleScope handle_scope;
102      v8::Handle<v8::String> file_name = v8::String::New(str);
103      v8::Handle<v8::String> source = ReadFile(str);
104      if (source.IsEmpty()) {
105        printf("Error reading '%s'\n", str);
106        return 1;
107      }
108      if (!ExecuteString(source, file_name, false))
109        return 1;
110    }
111  }
112
113  if (run_shell) RunShell(context);
114  return 0;
115}
116
117
118// The callback that is invoked by v8 whenever the JavaScript 'print'
119// function is called.  Prints its arguments on stdout separated by
120// spaces and ending with a newline.
121v8::Handle<v8::Value> Print(const v8::Arguments& args) {
122  bool first = true;
123  for (int i = 0; i < args.Length(); i++) {
124    v8::HandleScope handle_scope;
125    if (first) {
126      first = false;
127    } else {
128      printf(" ");
129    }
130    v8::String::Value str(args[i]);
131    printf("%S", *str);
132  }
133  printf("\n");
134  return v8::Undefined();
135}
136
137
138// The callback that is invoked by v8 whenever the JavaScript 'load'
139// function is called.  Loads, compiles and executes its argument
140// JavaScript file.
141v8::Handle<v8::Value> Load(const v8::Arguments& args) {
142  for (int i = 0; i < args.Length(); i++) {
143    v8::HandleScope handle_scope;
144    v8::String::AsciiValue file(args[i]);
145    v8::Handle<v8::String> source = ReadFile(*file);
146    if (source.IsEmpty()) {
147      return v8::ThrowException(v8::String::New("Error loading file"));
148    }
149    ExecuteString(source, v8::String::New(*file), false);
150  }
151  return v8::Undefined();
152}
153
154
155// The callback that is invoked by v8 whenever the JavaScript 'quit'
156// function is called.  Quits.
157v8::Handle<v8::Value> Quit(const v8::Arguments& args) {
158  // If not arguments are given args[0] will yield undefined which
159  // converts to the integer value 0.
160  int exit_code = args[0]->Int32Value();
161  exit(exit_code);
162  return v8::Undefined();
163}
164
165
166v8::Handle<v8::Value> Version(const v8::Arguments& args) {
167  return v8::String::New(v8::V8::GetVersion());
168}
169
170
171// Reads a file into a v8 string.
172v8::Handle<v8::String> ReadFile(const char* name) {
173  FILE* file = fopen(name, "rb");
174  if (file == NULL) return v8::Handle<v8::String>();
175
176  fseek(file, 0, SEEK_END);
177  int size = ftell(file);
178  rewind(file);
179
180  char* chars = new char[size + 1];
181  chars[size] = '\0';
182  for (int i = 0; i < size;) {
183    int read = fread(&chars[i], 1, size - i, file);
184    i += read;
185  }
186  fclose(file);
187  v8::Handle<v8::String> result = v8::String::New(chars, size);
188  delete[] chars;
189  return result;
190}
191
192
193// The read-eval-execute loop of the shell.
194void RunShell(v8::Handle<v8::Context> context) {
195  printf("V8 version %s\n", v8::V8::GetVersion());
196  static const int kBufferSize = 256;
197  while (true) {
198    char buffer[kBufferSize];
199    printf("> ");
200    char* str = fgets(buffer, kBufferSize, stdin);
201    if (str == NULL) break;
202    v8::HandleScope handle_scope;
203    ExecuteString(v8::String::New(str), v8::Undefined(), true);
204  }
205  printf("\n");
206}
207
208
209// Executes a string within the current v8 context.
210bool ExecuteString(v8::Handle<v8::String> source,
211                   v8::Handle<v8::Value> name,
212                   bool print_result) {
213  v8::HandleScope handle_scope;
214  v8::TryCatch try_catch;
215  v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
216  if (script.IsEmpty()) {
217    // Print errors that happened during compilation.
218    v8::String::AsciiValue error(try_catch.Exception());
219    printf("%s\n", *error);
220    return false;
221  } else {
222    v8::Handle<v8::Value> result = script->Run();
223    if (result.IsEmpty()) {
224      // Print errors that happened during execution.
225      v8::String::AsciiValue error(try_catch.Exception());
226      printf("%s\n", *error);
227      return false;
228    } else {
229      if (print_result && !result->IsUndefined()) {
230        // If all went well and the result wasn't undefined then print
231        // the returned value.
232        v8::String::AsciiValue str(result);
233        printf("%s\n", *str);
234      }
235      return true;
236    }
237  }
238}
Note: See TracBrowser for help on using the browser.