File: scriptable_view.cc

package info (click to toggle)
google-gadgets 0.11.2-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 16,820 kB
  • ctags: 20,323
  • sloc: cpp: 116,722; ansic: 18,000; sh: 9,269; makefile: 2,676; xml: 2,138; lex: 459
file content (318 lines) | stat: -rw-r--r-- 11,180 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
  Copyright 2008 Google Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "scriptable_view.h"

#include <string>
#include "common.h"
#include "gadget_consts.h"
#include "logger.h"
#include "content_item.h"
#include "details_view_data.h"
#include "elements.h"
#include "basic_element.h"
#include "scriptable_image.h"
#include "scriptable_event.h"
#include "image_interface.h"
#include "file_manager_interface.h"
#include "file_manager_factory.h"
#include "script_context_interface.h"
#include "unicode_utils.h"
#include "xml_dom.h"
#include "xml_parser_interface.h"
#include "xml_http_request_interface.h"
#include "xml_utils.h"
#include "string_utils.h"
#include "permissions.h"
#include "system_utils.h"
#include "small_object.h"

namespace ggadget {

class ScriptableView::Impl : public SmallObject<> {
 public:
  class GlobalObject : public ScriptableHelperNativeOwnedDefault {
   public:
    DEFINE_CLASS_ID(0x23840d38ed164ab2, ScriptableInterface);
    virtual bool IsStrict() const { return false; }
  };

  Impl(ScriptableView *owner, View *view, ScriptableInterface *prototype,
       ScriptContextInterface *script_context)
    : owner_(owner),
      view_(view),
      script_context_(script_context) {
    ASSERT(view_);

    if (prototype)
      global_object_.SetInheritsFrom(prototype);

    if (script_context_) {
      script_context_->SetGlobalObject(&global_object_);
      script_context_->RegisterClass("DOMDocument",
          NewSlot(this, &Impl::CreateDOMDocument));
      script_context_->RegisterClass("XMLHttpRequest",
          NewSlot(view->GetGadget(), &Gadget::CreateXMLHttpRequest));
      script_context_->RegisterClass("DetailsView",
          NewSlot(DetailsViewData::CreateInstance));
      script_context_->RegisterClass("ContentItem",
          NewSlot(ContentItem::CreateInstance, view_));

      // Old "utils" global object, for backward compatibility.
      utils_.RegisterMethod("loadImage",
                            NewSlot(this, &Impl::LoadScriptableImage));
      utils_.RegisterMethod("setTimeout",
                            NewSlot(this, &Impl::SetTimeout));
      utils_.RegisterMethod("clearTimeout",
                            NewSlot(view_, &View::ClearTimeout));
      utils_.RegisterMethod("setInterval",
                            NewSlot(this, &Impl::SetInterval));
      utils_.RegisterMethod("clearInterval",
                            NewSlot(view_, &View::ClearInterval));
      utils_.RegisterMethod("alert",
                            NewSlot(view_, &View::Alert));
      utils_.RegisterMethod("confirm",
                            NewSlot(view_, &View::Confirm));
      utils_.RegisterMethod("prompt",
                            NewSlot(view_, &View::Prompt));

      script_context_->AssignFromNative(NULL, "", "utils", Variant(&utils_));

      // Execute common.js to initialize global constants and compatibility
      // adapters.
      std::string common_js_contents;
      if (GetGlobalFileManager()->ReadFile(kCommonJS, &common_js_contents)) {
        std::string path = GetGlobalFileManager()->GetFullPath(kCommonJS);
        script_context_->Execute(common_js_contents.c_str(), path.c_str(), 1);
      } else {
        LOG("Failed to load %s.", kCommonJS);
      }
    }
  }

  ~Impl() {
    SimpleEvent e(Event::EVENT_CLOSE);
    view_->OnOtherEvent(e);
  }

  void DoRegister() {
    DLOG("Register ScriptableView properties.");

    view_->SetScriptable(owner_);
    view_->RegisterProperties(global_object_.GetRegisterable());

    // Register view.event property here, because we need set owner_ into
    // ScriptableEvent if its SrcElement is NULL.
    owner_->RegisterProperty("event", NewSlot(this, &Impl::GetEvent), NULL);
    global_object_.RegisterProperty("event", NewSlot(this, &Impl::GetEvent),
                                    NULL);

    global_object_.RegisterConstant("view", owner_);
    global_object_.SetDynamicPropertyHandler(
        NewSlot(this, &Impl::GetElementByNameVariant), NULL);
  }

  ScriptableEvent *GetEvent() {
    ScriptableEvent *event = view_->GetEvent();
    if (event && event->GetSrcElement() == NULL)
      event->SetSrcElement(owner_);
    return event;
  }

  int SetTimeout(Slot *slot, int timeout) {
    Slot0<void> *callback = slot ? new SlotProxy0<void>(slot) : NULL;
    return view_->SetTimeout(callback, timeout);
  }

  int SetInterval(Slot *slot, int interval) {
    Slot0<void> *callback = slot ? new SlotProxy0<void>(slot) : NULL;
    return view_->SetInterval(callback, interval);
  }

  ScriptableImage *LoadScriptableImage(const Variant &image_src) {
    ImageInterface *image = view_->LoadImage(image_src, false);
    return image ? new ScriptableImage(image) : NULL;
  }

  Variant GetElementByNameVariant(const char *name) {
    BasicElement *result = view_->GetElementByName(name);
    return result ? Variant(result) : Variant();
  }

  bool InitFromXML(const std::string &xml, const char *filename) {
    DOMDocumentInterface *xmldoc = GetXMLParser()->CreateDOMDocument();
    xmldoc->Ref();
    Gadget *gadget = view_->GetGadget();
    bool success = false;
    if (gadget) {
      success = gadget->ParseLocalizedXML(xml, filename, xmldoc);
    } else {
      // For unittest. Parse without encoding fallback and localization.
      success = GetXMLParser()->ParseContentIntoDOM(xml, NULL, filename,
                                                    NULL, NULL, NULL,
                                                    xmldoc, NULL, NULL);
    }
    if (!success) {
      xmldoc->Unref();
      return false;
    }

    DOMElementInterface *view_element = xmldoc->GetDocumentElement();
    if (!view_element ||
        GadgetStrCmp(view_element->GetTagName().c_str(), kViewTag) != 0) {
      LOG("No valid root element in view file: %s", filename);
      xmldoc->Unref();
      return false;
    }

    view_->EnableEvents(false);
    SetupScriptableProperties(owner_, script_context_, view_element, filename);

    Elements *children = view_->GetChildren();
    for (const DOMNodeInterface *child = view_element->GetFirstChild();
         child; child = child->GetNextSibling()) {
      if (child->GetNodeType() == DOMNodeInterface::ELEMENT_NODE) {
        InsertElementFromDOM(children, script_context_,
                             down_cast<const DOMElementInterface *>(child),
                             NULL, filename);
      }
    }

    // Call layout here to make sure all elements' initial layout is correct
    // prior to running any script code.
    view_->Layout();
    view_->EnableEvents(true);

    if (script_context_ && !HandleAllScriptElements(view_element, filename)) {
      // Don't load the gadget if any script file can't be loaded.
      xmldoc->Unref();
      return false;
    }

    ASSERT(xmldoc->GetRefCount() == 1);
    xmldoc->Unref();

    // Fire "onopen" event here, to make sure that it's only fired once.
    view_->OnOtherEvent(SimpleEvent(Event::EVENT_OPEN));
    // Fire "onsize" event here. Some gadgets rely on it to initialize
    // view layout.
    view_->OnOtherEvent(SimpleEvent(Event::EVENT_SIZE));
    return true;
  }

  bool HandleScriptElement(const DOMElementInterface *xml_element,
                           const char *filename) {
    int lineno = xml_element->GetRow();
    std::string script;
    std::string src = GetAttributeGadgetCase(xml_element, kSrcAttr);

    if (!src.empty()) {
      if (strncmp(kGlobalResourcePrefix, src.c_str(),
                  sizeof(kGlobalResourcePrefix) - 1) == 0) {
        if (!GetGlobalFileManager()->ReadFile(src.c_str(), &script))
          return false;
      } else if (!view_->GetFileManager()->ReadFile(src.c_str(), &script)) {
        return false;
      }
        
      filename = src.c_str();
      lineno = 1;
      std::string temp;
      if (DetectAndConvertStreamToUTF8(script, &temp, NULL))
        script = temp;
    } else {
      // Uses the Windows version convention, that inline scripts should be
      // quoted in comments.
      for (const DOMNodeInterface *child = xml_element->GetFirstChild();
           child; child = child->GetNextSibling()) {
        if (child->GetNodeType() == DOMNodeInterface::COMMENT_NODE) {
          script = child->GetTextContent();
          break;
        } else if (child->GetNodeType() != DOMNodeInterface::TEXT_NODE ||
                   !TrimString(child->GetTextContent()).empty()) {
          // Other contents are not allowed under <script></script>.
          LOG("%s:%d:%d: This content is not allowed in script element",
              filename, child->GetRow(), child->GetColumn());
        }
      }
    }

    if (!script.empty())
      script_context_->Execute(script.c_str(), filename, lineno);
    return true;
  }

  bool HandleAllScriptElements(const DOMElementInterface *xml_element,
                               const char *filename) {
    for (const DOMNodeInterface *child = xml_element->GetFirstChild();
         child; child = child->GetNextSibling()) {
      if (child->GetNodeType() == DOMNodeInterface::ELEMENT_NODE) {
        const DOMElementInterface *child_ele =
            down_cast<const DOMElementInterface *>(child);
        bool result;
        if (GadgetStrCmp(child_ele->GetTagName().c_str(), kScriptTag) == 0) {
          result = HandleScriptElement(child_ele, filename);
        } else {
          result = HandleAllScriptElements(child_ele, filename);
        }
        if (!result)
          return false;
      }
    }
    return true;
  }

  // Create a customized DOMDocument object with optional "load()" method,
  // for microsoft compatibility.
  DOMDocumentInterface *CreateDOMDocument() {
    const Permissions *permissions = view_->GetGadget()->GetPermissions();
    return ::ggadget::CreateDOMDocument(
        GetXMLParser(),
        permissions->IsRequiredAndGranted(Permissions::NETWORK),
        permissions->IsRequiredAndGranted(Permissions::FILE_READ));
  }

  ScriptableView *owner_;
  View *view_;
  ScriptContextInterface *script_context_;

  NativeOwnedScriptable<UINT64_C(0x364d74f3646848ce)> utils_;
  GlobalObject global_object_;
};

ScriptableView::ScriptableView(View *view, ScriptableInterface *prototype,
                               ScriptContextInterface *script_context)
  : impl_(new Impl(this, view, prototype, script_context)) {
}

ScriptableView::~ScriptableView() {
  delete impl_;
  impl_ = NULL;
}

bool ScriptableView::InitFromXML(const std::string &xml, const char *filename) {
  return impl_->InitFromXML(xml, filename);
}

View *ScriptableView::view() {
  return impl_->view_;
}

void ScriptableView::DoRegister() {
  impl_->DoRegister();
}

} // namespace ggadget