<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/autofill_messages.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFormElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h"
#include "webkit/glue/form_data.h"
#include "webkit/glue/web_io_operators.h"

using webkit_glue::FormData;
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebURLError;

typedef RenderViewTest FormAutocompleteTest;

// Tests that submitting a form generates a FormSubmitted message
// with the form fields.
TEST_F(FormAutocompleteTest, NormalFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  AutofillHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(2U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name);
  EXPECT_EQ(WebString("Rick"), form_field.value);

  form_field = forms.a.fields[1];
  EXPECT_EQ(WebString("lname"), form_field.name);
  EXPECT_EQ(WebString("Deckard"), form_field.value);
}

// Tests that submitting a form that has autocomplete="off" does not generate a
// FormSubmitted message.
TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm' autocomplete='off'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID));
}

// Tests that fields with autocomplete off are not submitted.
TEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard' autocomplete='off'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  AutofillHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(1U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name);
  EXPECT_EQ(WebString("Rick"), form_field.value);
}

// Tests that submitting a form that has been dynamically set as autocomplete
// off does not generate a FormSubmitted message.
// http://crbug.com/36520
// TODO(jcampan): Waiting on WebKit bug 35823.
TEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) {
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  WebKit::WebElement element =
      GetMainFrame()->document().getElementById(WebKit::WebString("myForm"));
  ASSERT_FALSE(element.isNull());
  WebKit::WebFormElement form = element.to<WebKit::WebFormElement>();
  EXPECT_TRUE(form.autoComplete());

  // Dynamically mark the form as autocomplete off.
  ExecuteJavaScript("document.getElementById('myForm').autocomplete='off';");
  ProcessPendingMessages();
  EXPECT_FALSE(form.autoComplete());

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID));
}
<commit_msg>Fix failing autofill test<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/autofill_messages.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFormElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h"
#include "webkit/glue/form_data.h"
#include "webkit/glue/web_io_operators.h"

using webkit_glue::FormData;
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebURLError;

typedef RenderViewTest FormAutocompleteTest;

// Tests that submitting a form generates a FormSubmitted message
// with the form fields.
TEST_F(FormAutocompleteTest, NormalFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  AutofillHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(2U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name);
  EXPECT_EQ(WebString("Rick"), form_field.value);

  form_field = forms.a.fields[1];
  EXPECT_EQ(WebString("lname"), form_field.name);
  EXPECT_EQ(WebString("Deckard"), form_field.value);
}

// Tests that submitting a form that has autocomplete="off" does not generate a
// FormSubmitted message.
TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm' autocomplete='off'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID));
}

// Tests that fields with autocomplete off are not submitted.
TEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {
  // Load a form.
  LoadHTML("<form id='myForm'>"
           "<input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard' autocomplete='off'/>"
           "</form>");

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID);
  ASSERT_TRUE(message != NULL);

  Tuple1<FormData> forms;
  AutofillHostMsg_FormSubmitted::Read(message, &forms);
  ASSERT_EQ(1U, forms.a.fields.size());

  webkit_glue::FormField& form_field = forms.a.fields[0];
  EXPECT_EQ(WebString("fname"), form_field.name);
  EXPECT_EQ(WebString("Rick"), form_field.value);
}

// Tests that submitting a form that has been dynamically set as autocomplete
// off does not generate a FormSubmitted message.
// http://crbug.com/36520
TEST_F(FormAutocompleteTest, DynamicAutoCompleteOffFormSubmit) {
  LoadHTML("<form id='myForm'><input name='fname' value='Rick'/>"
           "<input name='lname' value='Deckard'/></form>");

  WebKit::WebElement element =
      GetMainFrame()->document().getElementById(WebKit::WebString("myForm"));
  ASSERT_FALSE(element.isNull());
  WebKit::WebFormElement form = element.to<WebKit::WebFormElement>();
  EXPECT_TRUE(form.autoComplete());

  // Dynamically mark the form as autocomplete off.
  ExecuteJavaScript("document.getElementById('myForm')."
                    "setAttribute('autocomplete', 'off');");
  ProcessPendingMessages();
  EXPECT_FALSE(form.autoComplete());

  // Submit the form.
  ExecuteJavaScript("document.getElementById('myForm').submit();");
  ProcessPendingMessages();

  // No FormSubmitted message should have been sent.
  EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(
      AutofillHostMsg_FormSubmitted::ID));
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/service_worker/service_worker_provider_host.h"

#include "base/stl_util.h"
#include "content/browser/message_port_message_filter.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_request_handler.h"
#include "content/browser/service_worker/service_worker_controllee_request_handler.h"
#include "content/browser/service_worker/service_worker_dispatcher_host.h"
#include "content/browser/service_worker/service_worker_handle.h"
#include "content/browser/service_worker/service_worker_registration_handle.h"
#include "content/browser/service_worker/service_worker_utils.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/resource_request_body.h"
#include "content/common/service_worker/service_worker_messages.h"

namespace content {

static const int kDocumentMainThreadId = 0;

ServiceWorkerProviderHost::ServiceWorkerProviderHost(
    int process_id, int provider_id,
    base::WeakPtr<ServiceWorkerContextCore> context,
    ServiceWorkerDispatcherHost* dispatcher_host)
    : process_id_(process_id),
      provider_id_(provider_id),
      context_(context),
      dispatcher_host_(dispatcher_host),
      allow_association_(true) {
}

ServiceWorkerProviderHost::~ServiceWorkerProviderHost() {
  // Clear docurl so the deferred activation of a waiting worker
  // won't associate the new version with a provider being destroyed.
  document_url_ = GURL();
  if (controlling_version_.get())
    controlling_version_->RemoveControllee(this);
  if (associated_registration_.get()) {
    DecreaseProcessReference(associated_registration_->pattern());
    associated_registration_->RemoveListener(this);
  }
  for (std::vector<GURL>::iterator it = associated_patterns_.begin();
       it != associated_patterns_.end(); ++it) {
    DecreaseProcessReference(*it);
  }
}

void ServiceWorkerProviderHost::OnRegistrationFailed(
    ServiceWorkerRegistration* registration) {
  DCHECK_EQ(associated_registration_.get(), registration);
  DisassociateRegistration();
}

void ServiceWorkerProviderHost::SetDocumentUrl(const GURL& url) {
  DCHECK(!url.has_ref());
  document_url_ = url;
}

void ServiceWorkerProviderHost::SetControllerVersionAttribute(
    ServiceWorkerVersion* version) {
  if (version == controlling_version_.get())
    return;

  scoped_refptr<ServiceWorkerVersion> previous_version = controlling_version_;
  controlling_version_ = version;
  if (version)
    version->AddControllee(this);
  if (previous_version.get())
    previous_version->RemoveControllee(this);

  if (!dispatcher_host_)
    return;  // Could be NULL in some tests.

  dispatcher_host_->Send(new ServiceWorkerMsg_SetControllerServiceWorker(
      kDocumentMainThreadId, provider_id(), CreateHandleAndPass(version)));
}

bool ServiceWorkerProviderHost::SetHostedVersionId(int64 version_id) {
  if (!context_)
    return true;  // System is shutting down.
  if (active_version())
    return false;  // Unexpected bad message.

  ServiceWorkerVersion* live_version = context_->GetLiveVersion(version_id);
  if (!live_version)
    return true;  // Was deleted before it got started.

  ServiceWorkerVersionInfo info = live_version->GetInfo();
  if (info.running_status != ServiceWorkerVersion::STARTING ||
      info.process_id != process_id_) {
    // If we aren't trying to start this version in our process
    // something is amiss.
    return false;
  }

  running_hosted_version_ = live_version;
  return true;
}

void ServiceWorkerProviderHost::AssociateRegistration(
    ServiceWorkerRegistration* registration) {
  DCHECK(CanAssociateRegistration(registration));
  if (associated_registration_.get())
    DecreaseProcessReference(associated_registration_->pattern());
  IncreaseProcessReference(registration->pattern());

  if (dispatcher_host_) {
    ServiceWorkerRegistrationHandle* handle =
        dispatcher_host_->GetOrCreateRegistrationHandle(
            provider_id(), registration);

    ServiceWorkerVersionAttributes attrs;
    attrs.installing = handle->CreateServiceWorkerHandleAndPass(
        registration->installing_version());
    attrs.waiting = handle->CreateServiceWorkerHandleAndPass(
        registration->waiting_version());
    attrs.active = handle->CreateServiceWorkerHandleAndPass(
        registration->active_version());

    dispatcher_host_->Send(new ServiceWorkerMsg_AssociateRegistration(
        kDocumentMainThreadId, provider_id(), handle->GetObjectInfo(), attrs));
  }

  associated_registration_ = registration;
  associated_registration_->AddListener(this);
  SetControllerVersionAttribute(registration->active_version());
}

void ServiceWorkerProviderHost::DisassociateRegistration() {
  if (!associated_registration_.get())
    return;
  DecreaseProcessReference(associated_registration_->pattern());
  associated_registration_->RemoveListener(this);
  associated_registration_ = NULL;
  SetControllerVersionAttribute(NULL);

  if (dispatcher_host_) {
    dispatcher_host_->Send(new ServiceWorkerMsg_DisassociateRegistration(
        kDocumentMainThreadId, provider_id()));
  }
}

scoped_ptr<ServiceWorkerRequestHandler>
ServiceWorkerProviderHost::CreateRequestHandler(
    ResourceType resource_type,
    base::WeakPtr<storage::BlobStorageContext> blob_storage_context,
    scoped_refptr<ResourceRequestBody> body) {
  if (IsHostToRunningServiceWorker()) {
    return scoped_ptr<ServiceWorkerRequestHandler>(
        new ServiceWorkerContextRequestHandler(
            context_, AsWeakPtr(), blob_storage_context, resource_type));
  }
  if (ServiceWorkerUtils::IsMainResourceType(resource_type) ||
      active_version()) {
    return scoped_ptr<ServiceWorkerRequestHandler>(
        new ServiceWorkerControlleeRequestHandler(
            context_, AsWeakPtr(), blob_storage_context, resource_type, body));
  }
  return scoped_ptr<ServiceWorkerRequestHandler>();
}

bool ServiceWorkerProviderHost::CanAssociateRegistration(
    ServiceWorkerRegistration* registration) {
  if (!context_)
    return false;
  if (running_hosted_version_.get())
    return false;
  if (!registration || associated_registration_.get() || !allow_association_)
    return false;
  return true;
}

void ServiceWorkerProviderHost::PostMessage(
    const base::string16& message,
    const std::vector<int>& sent_message_port_ids) {
  if (!dispatcher_host_)
    return;  // Could be NULL in some tests.

  std::vector<int> new_routing_ids;
  dispatcher_host_->message_port_message_filter()->
      UpdateMessagePortsWithNewRoutes(sent_message_port_ids,
                                      &new_routing_ids);

  dispatcher_host_->Send(
      new ServiceWorkerMsg_MessageToDocument(
          kDocumentMainThreadId, provider_id(),
          message,
          sent_message_port_ids,
          new_routing_ids));
}

void ServiceWorkerProviderHost::AddScopedProcessReferenceToPattern(
    const GURL& pattern) {
  associated_patterns_.push_back(pattern);
  IncreaseProcessReference(pattern);
}

ServiceWorkerObjectInfo ServiceWorkerProviderHost::CreateHandleAndPass(
    ServiceWorkerVersion* version) {
  ServiceWorkerObjectInfo info;
  if (context_ && version) {
    scoped_ptr<ServiceWorkerHandle> handle =
        ServiceWorkerHandle::Create(context_,
                                    dispatcher_host_,
                                    kDocumentMainThreadId,
                                    provider_id_,
                                    version);
    info = handle->GetObjectInfo();
    dispatcher_host_->RegisterServiceWorkerHandle(handle.Pass());
  }
  return info;
}

void ServiceWorkerProviderHost::IncreaseProcessReference(
    const GURL& pattern) {
  if (context_ && context_->process_manager()) {
    context_->process_manager()->AddProcessReferenceToPattern(
        pattern, process_id_);
  }
}

void ServiceWorkerProviderHost::DecreaseProcessReference(
    const GURL& pattern) {
  if (context_ && context_->process_manager()) {
    context_->process_manager()->RemoveProcessReferenceFromPattern(
        pattern, process_id_);
  }
}

bool ServiceWorkerProviderHost::IsContextAlive() {
  return context_ != NULL;
}

}  // namespace content
<commit_msg>[ServiceWorker] Don't send fetch event to the ServiceWorker if the page is not controled by it yet.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/service_worker/service_worker_provider_host.h"

#include "base/stl_util.h"
#include "content/browser/message_port_message_filter.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_request_handler.h"
#include "content/browser/service_worker/service_worker_controllee_request_handler.h"
#include "content/browser/service_worker/service_worker_dispatcher_host.h"
#include "content/browser/service_worker/service_worker_handle.h"
#include "content/browser/service_worker/service_worker_registration_handle.h"
#include "content/browser/service_worker/service_worker_utils.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/common/resource_request_body.h"
#include "content/common/service_worker/service_worker_messages.h"

namespace content {

static const int kDocumentMainThreadId = 0;

ServiceWorkerProviderHost::ServiceWorkerProviderHost(
    int process_id, int provider_id,
    base::WeakPtr<ServiceWorkerContextCore> context,
    ServiceWorkerDispatcherHost* dispatcher_host)
    : process_id_(process_id),
      provider_id_(provider_id),
      context_(context),
      dispatcher_host_(dispatcher_host),
      allow_association_(true) {
}

ServiceWorkerProviderHost::~ServiceWorkerProviderHost() {
  // Clear docurl so the deferred activation of a waiting worker
  // won't associate the new version with a provider being destroyed.
  document_url_ = GURL();
  if (controlling_version_.get())
    controlling_version_->RemoveControllee(this);
  if (associated_registration_.get()) {
    DecreaseProcessReference(associated_registration_->pattern());
    associated_registration_->RemoveListener(this);
  }
  for (std::vector<GURL>::iterator it = associated_patterns_.begin();
       it != associated_patterns_.end(); ++it) {
    DecreaseProcessReference(*it);
  }
}

void ServiceWorkerProviderHost::OnRegistrationFailed(
    ServiceWorkerRegistration* registration) {
  DCHECK_EQ(associated_registration_.get(), registration);
  DisassociateRegistration();
}

void ServiceWorkerProviderHost::SetDocumentUrl(const GURL& url) {
  DCHECK(!url.has_ref());
  document_url_ = url;
}

void ServiceWorkerProviderHost::SetControllerVersionAttribute(
    ServiceWorkerVersion* version) {
  if (version == controlling_version_.get())
    return;

  scoped_refptr<ServiceWorkerVersion> previous_version = controlling_version_;
  controlling_version_ = version;
  if (version)
    version->AddControllee(this);
  if (previous_version.get())
    previous_version->RemoveControllee(this);

  if (!dispatcher_host_)
    return;  // Could be NULL in some tests.

  dispatcher_host_->Send(new ServiceWorkerMsg_SetControllerServiceWorker(
      kDocumentMainThreadId, provider_id(), CreateHandleAndPass(version)));
}

bool ServiceWorkerProviderHost::SetHostedVersionId(int64 version_id) {
  if (!context_)
    return true;  // System is shutting down.
  if (active_version())
    return false;  // Unexpected bad message.

  ServiceWorkerVersion* live_version = context_->GetLiveVersion(version_id);
  if (!live_version)
    return true;  // Was deleted before it got started.

  ServiceWorkerVersionInfo info = live_version->GetInfo();
  if (info.running_status != ServiceWorkerVersion::STARTING ||
      info.process_id != process_id_) {
    // If we aren't trying to start this version in our process
    // something is amiss.
    return false;
  }

  running_hosted_version_ = live_version;
  return true;
}

void ServiceWorkerProviderHost::AssociateRegistration(
    ServiceWorkerRegistration* registration) {
  DCHECK(CanAssociateRegistration(registration));
  if (associated_registration_.get())
    DecreaseProcessReference(associated_registration_->pattern());
  IncreaseProcessReference(registration->pattern());

  if (dispatcher_host_) {
    ServiceWorkerRegistrationHandle* handle =
        dispatcher_host_->GetOrCreateRegistrationHandle(
            provider_id(), registration);

    ServiceWorkerVersionAttributes attrs;
    attrs.installing = handle->CreateServiceWorkerHandleAndPass(
        registration->installing_version());
    attrs.waiting = handle->CreateServiceWorkerHandleAndPass(
        registration->waiting_version());
    attrs.active = handle->CreateServiceWorkerHandleAndPass(
        registration->active_version());

    dispatcher_host_->Send(new ServiceWorkerMsg_AssociateRegistration(
        kDocumentMainThreadId, provider_id(), handle->GetObjectInfo(), attrs));
  }

  associated_registration_ = registration;
  associated_registration_->AddListener(this);
  SetControllerVersionAttribute(registration->active_version());
}

void ServiceWorkerProviderHost::DisassociateRegistration() {
  if (!associated_registration_.get())
    return;
  DecreaseProcessReference(associated_registration_->pattern());
  associated_registration_->RemoveListener(this);
  associated_registration_ = NULL;
  SetControllerVersionAttribute(NULL);

  if (dispatcher_host_) {
    dispatcher_host_->Send(new ServiceWorkerMsg_DisassociateRegistration(
        kDocumentMainThreadId, provider_id()));
  }
}

scoped_ptr<ServiceWorkerRequestHandler>
ServiceWorkerProviderHost::CreateRequestHandler(
    ResourceType resource_type,
    base::WeakPtr<storage::BlobStorageContext> blob_storage_context,
    scoped_refptr<ResourceRequestBody> body) {
  if (IsHostToRunningServiceWorker()) {
    return scoped_ptr<ServiceWorkerRequestHandler>(
        new ServiceWorkerContextRequestHandler(
            context_, AsWeakPtr(), blob_storage_context, resource_type));
  }
  if (ServiceWorkerUtils::IsMainResourceType(resource_type) ||
      controlling_version()) {
    return scoped_ptr<ServiceWorkerRequestHandler>(
        new ServiceWorkerControlleeRequestHandler(
            context_, AsWeakPtr(), blob_storage_context, resource_type, body));
  }
  return scoped_ptr<ServiceWorkerRequestHandler>();
}

bool ServiceWorkerProviderHost::CanAssociateRegistration(
    ServiceWorkerRegistration* registration) {
  if (!context_)
    return false;
  if (running_hosted_version_.get())
    return false;
  if (!registration || associated_registration_.get() || !allow_association_)
    return false;
  return true;
}

void ServiceWorkerProviderHost::PostMessage(
    const base::string16& message,
    const std::vector<int>& sent_message_port_ids) {
  if (!dispatcher_host_)
    return;  // Could be NULL in some tests.

  std::vector<int> new_routing_ids;
  dispatcher_host_->message_port_message_filter()->
      UpdateMessagePortsWithNewRoutes(sent_message_port_ids,
                                      &new_routing_ids);

  dispatcher_host_->Send(
      new ServiceWorkerMsg_MessageToDocument(
          kDocumentMainThreadId, provider_id(),
          message,
          sent_message_port_ids,
          new_routing_ids));
}

void ServiceWorkerProviderHost::AddScopedProcessReferenceToPattern(
    const GURL& pattern) {
  associated_patterns_.push_back(pattern);
  IncreaseProcessReference(pattern);
}

ServiceWorkerObjectInfo ServiceWorkerProviderHost::CreateHandleAndPass(
    ServiceWorkerVersion* version) {
  ServiceWorkerObjectInfo info;
  if (context_ && version) {
    scoped_ptr<ServiceWorkerHandle> handle =
        ServiceWorkerHandle::Create(context_,
                                    dispatcher_host_,
                                    kDocumentMainThreadId,
                                    provider_id_,
                                    version);
    info = handle->GetObjectInfo();
    dispatcher_host_->RegisterServiceWorkerHandle(handle.Pass());
  }
  return info;
}

void ServiceWorkerProviderHost::IncreaseProcessReference(
    const GURL& pattern) {
  if (context_ && context_->process_manager()) {
    context_->process_manager()->AddProcessReferenceToPattern(
        pattern, process_id_);
  }
}

void ServiceWorkerProviderHost::DecreaseProcessReference(
    const GURL& pattern) {
  if (context_ && context_->process_manager()) {
    context_->process_manager()->RemoveProcessReferenceFromPattern(
        pattern, process_id_);
  }
}

bool ServiceWorkerProviderHost::IsContextAlive() {
  return context_ != NULL;
}

}  // namespace content
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/format.hpp"

#include "OP/OP_Director.h"
#include "PRM/PRM_Default.h"
#include "PRM/PRM_Template.h"

#include "IECore/CompoundObject.h"
#include "IECore/TransformationMatrixData.h"
#include "IECore/VectorTypedData.h"

#include "Convert.h"
#include "ToHoudiniAttribConverter.h"
#include "SOP_InterpolatedCacheReader.h"

using namespace IECore;
using namespace IECoreHoudini;

static PRM_Name parameterNames[] = {
	PRM_Name( "cacheSequence", "Cache Sequence" ),
	PRM_Name( "objectFixes", "Object Prefix/Suffix" ),
	PRM_Name( "attributeFixes", "Attribute Prefix/Suffix" ),
	PRM_Name( "transformAttribute", "Transform Attribute" ),
	PRM_Name( "frameMultiplier", "Frame Multiplier" ),
};

static PRM_Default frameMultiplierDefault( 1 );

PRM_Template SOP_InterpolatedCacheReader::parameters[] = {
	PRM_Template( PRM_FILE, 1, &parameterNames[0] ),
	PRM_Template( PRM_STRING, 2, &parameterNames[1] ),
	PRM_Template( PRM_STRING, 2, &parameterNames[2] ),
	PRM_Template( PRM_STRING, 1, &parameterNames[3] ),
	PRM_Template( PRM_INT, 1, &parameterNames[4], &frameMultiplierDefault ),
	PRM_Template(),
};

SOP_InterpolatedCacheReader::SOP_InterpolatedCacheReader( OP_Network *net, const char *name, OP_Operator *op )
	: SOP_Node( net, name, op ), m_cache( 0 ), m_cacheFileName(), m_frameMultiplier( -1 )
{
	flags().setTimeDep( true );
}

SOP_InterpolatedCacheReader::~SOP_InterpolatedCacheReader()
{
}

OP_Node *SOP_InterpolatedCacheReader::create( OP_Network *net, const char *name, OP_Operator *op )
{
	return new SOP_InterpolatedCacheReader( net, name, op );
}

OP_ERROR SOP_InterpolatedCacheReader::cookMySop( OP_Context &context )
{
	flags().setTimeDep( true );

	if ( lockInputs( context ) >= UT_ERROR_ABORT )
	{
		return error();
	}

	gdp->stashAll();

	float time = context.getTime();
	float frame = context.getFloatFrame();

	UT_String paramVal;

	evalString( paramVal, "cacheSequence", 0, time );
	std::string cacheFileName = paramVal.toStdString();

	evalString( paramVal, "objectFixes", 0, time );
	std::string objectPrefix = paramVal.toStdString();
	evalString( paramVal, "objectFixes", 1, time );
	std::string objectSuffix = paramVal.toStdString();

	evalString( paramVal, "attributeFixes", 0, time );
	std::string attributePrefix = paramVal.toStdString();
	evalString( paramVal, "attributeFixes", 1, time );
	std::string attributeSuffix = paramVal.toStdString();

	evalString( paramVal, "transformAttribute", 0, time );
	std::string transformAttribute = paramVal.toStdString();

	int frameMultiplier = evalInt( "frameMultiplier", 0, time );

	// create the InterpolatedCache
	if ( cacheFileName.compare( m_cacheFileName ) != 0 || frameMultiplier != m_frameMultiplier )
	{
		try
		{
			float fps = OPgetDirector()->getChannelManager()->getSamplesPerSec();
			OversamplesCalculator calc( fps, 1, (int)fps * frameMultiplier );
			m_cache = new InterpolatedCache( cacheFileName, InterpolatedCache::Linear, calc );
		}
		catch ( IECore::InvalidArgumentException e )
		{
			addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
			unlockInputs();
			return error();
		}

		m_cacheFileName = cacheFileName;
		m_frameMultiplier = frameMultiplier;
	}

	if ( !m_cache )
	{
		addWarning( SOP_MESSAGE, "SOP_InterpolatedCacheReader: Cache Sequence not found" );
		unlockInputs();
		return error();
	}

	std::vector<InterpolatedCache::ObjectHandle> objects;
	std::vector<InterpolatedCache::AttributeHandle> attrs;

	try
	{
		m_cache->objects( frame, objects );
	}
	catch ( IECore::Exception e )
	{
		addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
		unlockInputs();
		return error();
	}

	duplicatePointSource( 0, context );

	for ( GA_GroupTable::iterator<GA_ElementGroup> it=gdp->pointGroups().beginTraverse(); !it.atEnd(); ++it )
	{
		GA_PointGroup *group = (GA_PointGroup*)it.group();
		if ( group->getInternal() || group->isEmpty() )
		{
			continue;
		}

		// match GA_PointGroup name to InterpolatedCache::ObjectHandle
		std::string searchName = objectPrefix + group->getName().toStdString() + objectSuffix;
		std::vector<InterpolatedCache::ObjectHandle>::iterator oIt = find( objects.begin(), objects.end(), searchName );
		if ( oIt == objects.end() )
		{
			continue;
		}

		CompoundObjectPtr attributes = 0;

		try
		{
			m_cache->attributes( frame, *oIt, attrs );
			attributes = m_cache->read( frame, *oIt );
		}
		catch ( IECore::Exception e )
		{
			addError( SOP_ATTRIBUTE_INVALID, e.what() );
			unlockInputs();
			return error();
		}

		const CompoundObject::ObjectMap &attributeMap = attributes->members();

		GA_Range pointRange = gdp->getPointRange( group );

		// transfer the InterpolatedCache::Attributes onto the GA_PointGroup
		/// \todo: this does not account for detail, prim, or vertex attribs...
		for ( CompoundObject::ObjectMap::const_iterator aIt=attributeMap.begin(); aIt != attributeMap.end(); aIt++ )
		{
			const Data *data = IECore::runTimeCast<const Data>( aIt->second );
			if ( !data )
			{
				continue;
			}

			ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( data );
			if ( !converter )
 			{
 				continue;
 			}

			// strip the prefix/suffix from the GA_Attribute name
			std::string attrName = aIt->first.value();
			size_t prefixLength = attributePrefix.length();
			if ( prefixLength && ( search( attrName.begin(), attrName.begin()+prefixLength, attributePrefix.begin(), attributePrefix.end() ) == attrName.begin() ) )
			{
				attrName.erase( attrName.begin(), attrName.begin() + prefixLength );
			}

			size_t suffixLength = attributeSuffix.length();
			if ( suffixLength && ( search( attrName.end() - suffixLength, attrName.end(), attributeSuffix.begin(), attributeSuffix.end() ) == ( attrName.end() - suffixLength ) ) )
			{
				attrName.erase( attrName.end() - suffixLength, attrName.end() );
			}

			if ( attrName == "P" )
			{
				const V3fVectorData *positions = IECore::runTimeCast<const V3fVectorData>( data );
				if ( !positions )
				{
					continue;
				}

				size_t index = 0;
				size_t entries = pointRange.getEntries();
				const std::vector<Imath::V3f> &pos = positions->readable();

				// Attempting to account for the vertex difference between an IECore::CurvesPrimitive and Houdini curves.
				// As Houdini implicitly triples the endpoints of a curve, a cache generated from a single CurvesPrimitive
				// will have exactly four extra vertices. In this case, we adjust the cache by ignoring the first two and
				// last two V3fs. In all other cases, we report a warning and don't apply the cache to these points.
				if ( pos.size() - 4 == entries )
				{
					index = 2;
				}
				else if ( pos.size() != entries )
				{
					addWarning( SOP_ATTRIBUTE_INVALID, ( boost::format( "Geometry/Cache mismatch: %s contains %d points, while cache expects %d." ) % group->getName().toStdString() % entries % pos.size() ).str().c_str() );
					continue;
				}

				/// \todo: try multi-threading this with a GA_SplittableRange
				for ( GA_Iterator it=pointRange.begin(); !it.atEnd(); ++it, ++index )
				{
					gdp->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[index] ) );
				}

			}
			else
			{
				converter->convert( attrName, gdp, pointRange );
			}
		}

		// if transformAttribute is specified, use to to transform the points
		if ( transformAttribute != "" )
		{
			const TransformationMatrixdData *transform = attributes->member<TransformationMatrixdData>( transformAttribute );
			if ( transform )
			{
				transformPoints<double>( transform->readable(), pointRange );
			}
			else
			{
				const TransformationMatrixfData *transform = attributes->member<TransformationMatrixfData>( transformAttribute );
				if ( transform )
				{
					transformPoints<float>( transform->readable(), pointRange );
				}
			}
		}
	}

	unlockInputs();
	return error();
}

template<typename T>
void SOP_InterpolatedCacheReader::transformPoints( const IECore::TransformationMatrix<T> &transform, const GA_Range &range )
{
	UT_Matrix4T<T> matrix = IECore::convert<UT_Matrix4T<T> >( transform.transform() );

	/// \todo: try multi-threading this with a GA_SplittableRange
	for ( GA_Iterator it=range.begin(); !it.atEnd(); ++it )
	{
		gdp->setPos3( it.getOffset(), gdp->getPos3( it.getOffset() ) * matrix );
	}
}
<commit_msg>added todos<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/format.hpp"

#include "OP/OP_Director.h"
#include "PRM/PRM_Default.h"
#include "PRM/PRM_Template.h"

#include "IECore/CompoundObject.h"
#include "IECore/TransformationMatrixData.h"
#include "IECore/VectorTypedData.h"

#include "Convert.h"
#include "ToHoudiniAttribConverter.h"
#include "SOP_InterpolatedCacheReader.h"

using namespace IECore;
using namespace IECoreHoudini;

static PRM_Name parameterNames[] = {
	PRM_Name( "cacheSequence", "Cache Sequence" ),
	PRM_Name( "objectFixes", "Object Prefix/Suffix" ),
	PRM_Name( "attributeFixes", "Attribute Prefix/Suffix" ),
	PRM_Name( "transformAttribute", "Transform Attribute" ),
	PRM_Name( "frameMultiplier", "Frame Multiplier" ),
};

static PRM_Default frameMultiplierDefault( 1 );

PRM_Template SOP_InterpolatedCacheReader::parameters[] = {
	PRM_Template( PRM_FILE, 1, &parameterNames[0] ),
	PRM_Template( PRM_STRING, 2, &parameterNames[1] ),
	PRM_Template( PRM_STRING, 2, &parameterNames[2] ),
	PRM_Template( PRM_STRING, 1, &parameterNames[3] ),
	PRM_Template( PRM_INT, 1, &parameterNames[4], &frameMultiplierDefault ),
	PRM_Template(),
};

SOP_InterpolatedCacheReader::SOP_InterpolatedCacheReader( OP_Network *net, const char *name, OP_Operator *op )
	: SOP_Node( net, name, op ), m_cache( 0 ), m_cacheFileName(), m_frameMultiplier( -1 )
{
	flags().setTimeDep( true );
}

SOP_InterpolatedCacheReader::~SOP_InterpolatedCacheReader()
{
}

OP_Node *SOP_InterpolatedCacheReader::create( OP_Network *net, const char *name, OP_Operator *op )
{
	return new SOP_InterpolatedCacheReader( net, name, op );
}

OP_ERROR SOP_InterpolatedCacheReader::cookMySop( OP_Context &context )
{
	flags().setTimeDep( true );

	if ( lockInputs( context ) >= UT_ERROR_ABORT )
	{
		return error();
	}

	gdp->stashAll();

	float time = context.getTime();
	float frame = context.getFloatFrame();

	UT_String paramVal;

	evalString( paramVal, "cacheSequence", 0, time );
	std::string cacheFileName = paramVal.toStdString();

	evalString( paramVal, "objectFixes", 0, time );
	std::string objectPrefix = paramVal.toStdString();
	evalString( paramVal, "objectFixes", 1, time );
	std::string objectSuffix = paramVal.toStdString();

	evalString( paramVal, "attributeFixes", 0, time );
	std::string attributePrefix = paramVal.toStdString();
	evalString( paramVal, "attributeFixes", 1, time );
	std::string attributeSuffix = paramVal.toStdString();

	evalString( paramVal, "transformAttribute", 0, time );
	std::string transformAttribute = paramVal.toStdString();

	int frameMultiplier = evalInt( "frameMultiplier", 0, time );

	// create the InterpolatedCache
	if ( cacheFileName.compare( m_cacheFileName ) != 0 || frameMultiplier != m_frameMultiplier )
	{
		try
		{
			float fps = OPgetDirector()->getChannelManager()->getSamplesPerSec();
			/// \todo: expose samplesPerFrame as a parameter
			OversamplesCalculator calc( fps, 1, (int)fps * frameMultiplier );
			/// \todo: expose interpolation type as a parameter
			m_cache = new InterpolatedCache( cacheFileName, InterpolatedCache::Linear, calc );
		}
		catch ( IECore::InvalidArgumentException e )
		{
			addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
			unlockInputs();
			return error();
		}

		m_cacheFileName = cacheFileName;
		m_frameMultiplier = frameMultiplier;
	}

	if ( !m_cache )
	{
		addWarning( SOP_MESSAGE, "SOP_InterpolatedCacheReader: Cache Sequence not found" );
		unlockInputs();
		return error();
	}

	std::vector<InterpolatedCache::ObjectHandle> objects;
	std::vector<InterpolatedCache::AttributeHandle> attrs;

	try
	{
		m_cache->objects( frame, objects );
	}
	catch ( IECore::Exception e )
	{
		addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
		unlockInputs();
		return error();
	}

	duplicatePointSource( 0, context );

	for ( GA_GroupTable::iterator<GA_ElementGroup> it=gdp->pointGroups().beginTraverse(); !it.atEnd(); ++it )
	{
		GA_PointGroup *group = (GA_PointGroup*)it.group();
		if ( group->getInternal() || group->isEmpty() )
		{
			continue;
		}

		// match GA_PointGroup name to InterpolatedCache::ObjectHandle
		std::string searchName = objectPrefix + group->getName().toStdString() + objectSuffix;
		std::vector<InterpolatedCache::ObjectHandle>::iterator oIt = find( objects.begin(), objects.end(), searchName );
		if ( oIt == objects.end() )
		{
			continue;
		}

		CompoundObjectPtr attributes = 0;

		try
		{
			m_cache->attributes( frame, *oIt, attrs );
			attributes = m_cache->read( frame, *oIt );
		}
		catch ( IECore::Exception e )
		{
			addError( SOP_ATTRIBUTE_INVALID, e.what() );
			unlockInputs();
			return error();
		}

		const CompoundObject::ObjectMap &attributeMap = attributes->members();

		GA_Range pointRange = gdp->getPointRange( group );

		// transfer the InterpolatedCache::Attributes onto the GA_PointGroup
		/// \todo: this does not account for detail, prim, or vertex attribs...
		for ( CompoundObject::ObjectMap::const_iterator aIt=attributeMap.begin(); aIt != attributeMap.end(); aIt++ )
		{
			const Data *data = IECore::runTimeCast<const Data>( aIt->second );
			if ( !data )
			{
				continue;
			}

			ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( data );
			if ( !converter )
 			{
 				continue;
 			}

			// strip the prefix/suffix from the GA_Attribute name
			std::string attrName = aIt->first.value();
			size_t prefixLength = attributePrefix.length();
			if ( prefixLength && ( search( attrName.begin(), attrName.begin()+prefixLength, attributePrefix.begin(), attributePrefix.end() ) == attrName.begin() ) )
			{
				attrName.erase( attrName.begin(), attrName.begin() + prefixLength );
			}

			size_t suffixLength = attributeSuffix.length();
			if ( suffixLength && ( search( attrName.end() - suffixLength, attrName.end(), attributeSuffix.begin(), attributeSuffix.end() ) == ( attrName.end() - suffixLength ) ) )
			{
				attrName.erase( attrName.end() - suffixLength, attrName.end() );
			}

			if ( attrName == "P" )
			{
				const V3fVectorData *positions = IECore::runTimeCast<const V3fVectorData>( data );
				if ( !positions )
				{
					continue;
				}

				size_t index = 0;
				size_t entries = pointRange.getEntries();
				const std::vector<Imath::V3f> &pos = positions->readable();

				// Attempting to account for the vertex difference between an IECore::CurvesPrimitive and Houdini curves.
				// As Houdini implicitly triples the endpoints of a curve, a cache generated from a single CurvesPrimitive
				// will have exactly four extra vertices. In this case, we adjust the cache by ignoring the first two and
				// last two V3fs. In all other cases, we report a warning and don't apply the cache to these points.
				if ( pos.size() - 4 == entries )
				{
					index = 2;
				}
				else if ( pos.size() != entries )
				{
					addWarning( SOP_ATTRIBUTE_INVALID, ( boost::format( "Geometry/Cache mismatch: %s contains %d points, while cache expects %d." ) % group->getName().toStdString() % entries % pos.size() ).str().c_str() );
					continue;
				}

				/// \todo: try multi-threading this with a GA_SplittableRange
				for ( GA_Iterator it=pointRange.begin(); !it.atEnd(); ++it, ++index )
				{
					gdp->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[index] ) );
				}

			}
			else
			{
				converter->convert( attrName, gdp, pointRange );
			}
		}

		// if transformAttribute is specified, use to to transform the points
		if ( transformAttribute != "" )
		{
			const TransformationMatrixdData *transform = attributes->member<TransformationMatrixdData>( transformAttribute );
			if ( transform )
			{
				transformPoints<double>( transform->readable(), pointRange );
			}
			else
			{
				const TransformationMatrixfData *transform = attributes->member<TransformationMatrixfData>( transformAttribute );
				if ( transform )
				{
					transformPoints<float>( transform->readable(), pointRange );
				}
			}
		}
	}

	unlockInputs();
	return error();
}

template<typename T>
void SOP_InterpolatedCacheReader::transformPoints( const IECore::TransformationMatrix<T> &transform, const GA_Range &range )
{
	UT_Matrix4T<T> matrix = IECore::convert<UT_Matrix4T<T> >( transform.transform() );

	/// \todo: try multi-threading this with a GA_SplittableRange
	for ( GA_Iterator it=range.begin(); !it.atEnd(); ++it )
	{
		gdp->setPos3( it.getOffset(), gdp->getPos3( it.getOffset() ) * matrix );
	}
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHoverWidget.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkHoverWidget.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkWidgetCallbackMapper.h"
#include "vtkWidgetEvent.h"
#include "vtkWidgetEventTranslator.h"
#include "vtkObjectFactory.h"
#include "vtkCallbackCommand.h"

vtkCxxRevisionMacro(vtkHoverWidget, "1.1");
vtkStandardNewMacro(vtkHoverWidget);

//-------------------------------------------------------------------------
vtkHoverWidget::vtkHoverWidget()
{
  this->WidgetState = Start;
  this->TimerDuration = 250;

  // Okay, define the events for this widget
  this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent,
                                          vtkWidgetEvent::Move,
                                          this, vtkHoverWidget::MoveAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::TimerEvent,
                                          vtkWidgetEvent::TimedOut,
                                          this, vtkHoverWidget::HoverAction);
}

//-------------------------------------------------------------------------
vtkHoverWidget::~vtkHoverWidget()
{
}

//----------------------------------------------------------------------
void vtkHoverWidget::SetEnabled(int enabling)
{
  if ( enabling ) //----------------
    {
    vtkDebugMacro(<<"Enabling widget");

    if ( this->Enabled ) //already enabled, just return
      {
      return;
      }

    if ( ! this->Interactor )
      {
      vtkErrorMacro(<<"The interactor must be set prior to enabling the widget");
      return;
      }

    // We're ready to enable
    this->Enabled = 1;

    // listen for the events found in the EventTranslator
    this->EventTranslator->AddEventsToInteractor(this->Interactor,
                                                 this->EventCallbackCommand,this->Priority);

    // Start off the timer
    this->TimerId = this->Interactor->CreateTimer(VTKI_TIMER_FIRST,this->TimerDuration);
    this->WidgetState = vtkHoverWidget::Timing;

    this->InvokeEvent(vtkCommand::EnableEvent,NULL);
    }

  else //disabling------------------
    {
    vtkDebugMacro(<<"Disabling widget");

    if ( ! this->Enabled ) //already disabled, just return
      {
      return;
      }

    this->Enabled = 0;

    this->Interactor->RemoveObserver(this->EventCallbackCommand);

    this->InvokeEvent(vtkCommand::DisableEvent,NULL);
    }
}

//-------------------------------------------------------------------------
void vtkHoverWidget::MoveAction(vtkAbstractWidget *w)
{
  vtkHoverWidget *self = reinterpret_cast<vtkHoverWidget*>(w);
  if ( self->WidgetState == vtkHoverWidget::Timing )
    {
    self->Interactor->DestroyTimer(self->TimerId);
    }
  else //we have timed out, on this move we restart the timer
    {
    self->WidgetState = vtkHoverWidget::Timing;
    self->SubclassEndHoverAction();
    self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL);
    }
  self->TimerId = self->Interactor->CreateTimer(VTKI_TIMER_FIRST,self->TimerDuration);
}

//-------------------------------------------------------------------------
void vtkHoverWidget::HoverAction(vtkAbstractWidget *w)
{
  vtkHoverWidget *self = reinterpret_cast<vtkHoverWidget*>(w);
  int timerId = *(reinterpret_cast<int*>(self->CallData));

  // If this is the timer event we are waiting for...
  if ( timerId == self->TimerId && self->WidgetState == vtkHoverWidget::Timing )
    {
    self->Interactor->DestroyTimer(self->TimerId);
    self->WidgetState = vtkHoverWidget::TimedOut;
    self->SubclassHoverAction();
    self->InvokeEvent(vtkCommand::TimerEvent,NULL);
    self->EventCallbackCommand->SetAbortFlag(1); //no one else gets this timer
    }
}

//-------------------------------------------------------------------------
void vtkHoverWidget::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Timer Duration: " << this->TimerDuration << "\n";
}
<commit_msg>ENH:Modified to reflect timer changes to vtkRenderWindowInteractor<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHoverWidget.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkHoverWidget.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkWidgetCallbackMapper.h"
#include "vtkWidgetEvent.h"
#include "vtkWidgetEventTranslator.h"
#include "vtkObjectFactory.h"
#include "vtkCallbackCommand.h"

vtkCxxRevisionMacro(vtkHoverWidget, "1.2");
vtkStandardNewMacro(vtkHoverWidget);

//-------------------------------------------------------------------------
vtkHoverWidget::vtkHoverWidget()
{
  this->WidgetState = Start;
  this->TimerDuration = 250;

  // Okay, define the events for this widget
  this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent,
                                          vtkWidgetEvent::Move,
                                          this, vtkHoverWidget::MoveAction);
  this->CallbackMapper->SetCallbackMethod(vtkCommand::TimerEvent,
                                          vtkWidgetEvent::TimedOut,
                                          this, vtkHoverWidget::HoverAction);
}

//-------------------------------------------------------------------------
vtkHoverWidget::~vtkHoverWidget()
{
}

//----------------------------------------------------------------------
void vtkHoverWidget::SetEnabled(int enabling)
{
  if ( enabling ) //----------------
    {
    vtkDebugMacro(<<"Enabling widget");

    if ( this->Enabled ) //already enabled, just return
      {
      return;
      }

    if ( ! this->Interactor )
      {
      vtkErrorMacro(<<"The interactor must be set prior to enabling the widget");
      return;
      }

    // We're ready to enable
    this->Enabled = 1;

    // listen for the events found in the EventTranslator
    this->EventTranslator->AddEventsToInteractor(this->Interactor,
                                                 this->EventCallbackCommand,this->Priority);

    // Start off the timer
    this->TimerId = this->Interactor->CreateRepeatingTimer(this->TimerDuration);
    this->WidgetState = vtkHoverWidget::Timing;

    this->InvokeEvent(vtkCommand::EnableEvent,NULL);
    }

  else //disabling------------------
    {
    vtkDebugMacro(<<"Disabling widget");

    if ( ! this->Enabled ) //already disabled, just return
      {
      return;
      }

    this->Enabled = 0;

    this->Interactor->RemoveObserver(this->EventCallbackCommand);

    this->InvokeEvent(vtkCommand::DisableEvent,NULL);
    }
}

//-------------------------------------------------------------------------
void vtkHoverWidget::MoveAction(vtkAbstractWidget *w)
{
  vtkHoverWidget *self = reinterpret_cast<vtkHoverWidget*>(w);
  if ( self->WidgetState == vtkHoverWidget::Timing )
    {
    self->Interactor->DestroyTimer(self->TimerId);
    }
  else //we have timed out, on this move we restart the timer
    {
    self->WidgetState = vtkHoverWidget::Timing;
    self->SubclassEndHoverAction();
    self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL);
    }
  self->TimerId = self->Interactor->CreateRepeatingTimer(self->TimerDuration);
}

//-------------------------------------------------------------------------
void vtkHoverWidget::HoverAction(vtkAbstractWidget *w)
{
  vtkHoverWidget *self = reinterpret_cast<vtkHoverWidget*>(w);
  int timerId = *(reinterpret_cast<int*>(self->CallData));

  // If this is the timer event we are waiting for...
  if ( timerId == self->TimerId && self->WidgetState == vtkHoverWidget::Timing )
    {
    self->Interactor->DestroyTimer(self->TimerId);
    self->WidgetState = vtkHoverWidget::TimedOut;
    self->SubclassHoverAction();
    self->InvokeEvent(vtkCommand::TimerEvent,NULL);
    self->EventCallbackCommand->SetAbortFlag(1); //no one else gets this timer
    }
}

//-------------------------------------------------------------------------
void vtkHoverWidget::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Timer Duration: " << this->TimerDuration << "\n";
}
<|endoftext|>


<commit_before>/***
  *  Project: Woo Matrix Library
  *
  *  File: matrix.hpp
  *  Created: Dec 03, 2012
  *  Modified: Tue 04 Dec 2012 10:18:38 PM PST
  *
  *  Author: Abhinav Sarje <asarje@lbl.gov>
  */

#include <vector>
#include <cstring>
#include <iostream>

namespace woo {

	template <typename value_type> class ColumnIterator;
	template <typename value_type> class RowIterator;

//	typedef ColumnIterator col_iterator;
//	typedef RowIterator row_iterator;
	// how to define const iterators ...
	//typedef const ColumnIterator const_col_iterator;
	//typedef const RowIterator const_row_iterator;

	template <typename value_type>
	class Matrix {
		protected:
			value_type *mat_;
			unsigned int num_dims_;				// number of dimensions
			std::vector<unsigned int> dims_;	// values of dimensions
			unsigned int capacity_;

		public:
			// default constructor: matrix size not known
			Matrix(): mat_(NULL), num_dims_(0) {
			} // Matrix()

			// generic constructor
			//Matrix(unsigned int num_dims, const std::vector<unsigned int>& dims):
			Matrix(unsigned int num_dims):
					mat_(NULL), num_dims_(num_dims), capacity_(0) {
			} // Matrix()

			void init(const std::vector<unsigned int>& dims) {
				if(dims.size() != num_dims_) {
					std::cerr << "error: number of dimensions does not match list of dimension values"
								<< std::endl;
					return;
				} // if
				dims_.clear();
				unsigned int total_elems = 1;
				for(unsigned int i = 0; i < num_dims_; ++ i) {
					dims_.push_back(dims[i]);
					total_elems *= dims[i];
				} // for
				unsigned int size = 256;
				while(true) {
					if(total_elems < size) {
						total_elems = size;
						break;
					} // if
					size *= 2;
				} // while
				capacity_ = total_elems;
				mat_ = new (std::nothrow) value_type[total_elems];
				if(mat_ == NULL) {
					std::cerr << "error: failed to allocate memory for the matrix" << std::endl;
					return;
				} // if
				memset(mat_, 0, total_elems * sizeof(value_type));
			} // init()

			//Matrix(unsigned int rows, unsigned int cols):
			//	num_dims_(2) {
			//		std::vector<unsigned int> dims;
			//		dims.push_back(rows);
			//		dims.push_back(cols);
			//		Matrix(2, dims);
			//} //Matrix()

			// destructor
			~Matrix() {
				if(mat_ != NULL) delete[] mat_;
			} // ~Matrix()

			// a few accessors
			unsigned int dims() const { return num_dims_; }
			unsigned int dim_size(unsigned int i) const { return dims_[i]; }
			unsigned int capacity() const { return capacity_; }

	}; // class Matrix

	template <typename value_type>
	class Matrix2D : public Matrix <value_type> {
		public:

			typedef ColumnIterator<value_type> col_iterator;
			typedef RowIterator<value_type> row_iterator;

			friend class ColumnIterator<value_type>;
			friend class RowIterator<value_type>;

			class IndexType {
				public:
					IndexType(): num_(0), idx_(0) { }
					IndexType(int a, int b): num_(a), idx_(b) { }
					~IndexType() { }

					int num_;		// column/row number
					int idx_;		// index within the column/row
			}; // class IndexType

			typedef IndexType index_type;
			static const index_type end_index;
			static const index_type begin_index;

			// constructor
			Matrix2D(unsigned int rows, unsigned int cols):
				Matrix<value_type>(2) {
				num_rows_ = rows;
				num_cols_ = cols;
				std::vector<unsigned int> dims;
				dims.push_back(num_rows_);
				dims.push_back(num_cols_);
				this->init(dims);
			} // Matrix()

			// iterator to column
			col_iterator column(unsigned int i) {
				if(i <= 0) {
					col_iterator start_col(0, num_rows_, num_cols_, this);
					return start_col;
				} // if
				if(i >= num_cols_) {
					col_iterator end_col(num_cols_ - 1, num_rows_, num_cols_, this);
					return end_col;
				} // if
				col_iterator col(i, num_rows_, num_cols_, this);
				return col;
			} // column()

			// accessors

			unsigned int num_cols() const { return num_cols_; }
			unsigned int num_rows() const { return num_rows_; }

			// access (i, j)-th element
			value_type& operator()(unsigned int i, unsigned int j) {
				return this->mat_[num_cols_ * i + j];
			} // operator()()

			// insert stuff
			bool insert_row(unsigned int i, const std::vector<value_type>& row) { }
			bool insert_col(unsigned int i, const std::vector<value_type>& col) { }

		private:
			unsigned int num_cols_;		// number of columns = row size
			unsigned int num_rows_;		// number of rows = col size

	}; // class Matrix2D

	// begin and end index_type constants
	template<> const Matrix2D<float>::index_type Matrix2D<float>::begin_index(0, 0);
	template<> const Matrix2D<float>::index_type Matrix2D<float>::end_index(-1, -1);
	template<> const Matrix2D<double>::index_type Matrix2D<double>::begin_index(0, 0);
	template<> const Matrix2D<double>::index_type Matrix2D<double>::end_index(-1, -1);
	template<> const Matrix2D<int>::index_type Matrix2D<int>::begin_index(0, 0);
	template<> const Matrix2D<int>::index_type Matrix2D<int>::end_index(-1, -1);
	template<> const Matrix2D<unsigned int>::index_type Matrix2D<unsigned int>::begin_index(0, 0);
	template<> const Matrix2D<unsigned int>::index_type Matrix2D<unsigned int>::end_index(-1, -1);
	template<> const Matrix2D<long int>::index_type Matrix2D<long int>::begin_index(0, 0);
	template<> const Matrix2D<long int>::index_type Matrix2D<long int>::end_index(-1, -1);
	template<> const Matrix2D<unsigned long int>::index_type Matrix2D<unsigned long int>::begin_index(0, 0);
	template<> const Matrix2D<unsigned long int>::index_type Matrix2D<unsigned long int>::end_index(-1, -1);

	/* a generic iterator */
	template <typename value_type>
	class DimensionIterator {
		public:

			//DimensionIterator() { DimensionIterator(0, 0, 0, NULL); }
			DimensionIterator(unsigned int d, unsigned int size, unsigned int i, value_type* mat):
				dim_num_(d), dim_size_(size), dim_index_(i), dim_pointer_(mat) { }
			~DimensionIterator() { }

			virtual void operator++() { }
			virtual void operator--() { }

		protected:

			unsigned int dim_num_;			// dimension number
			unsigned int dim_size_;			// size of the dimension
			unsigned int dim_index_;		// index of the current dimension vector
			value_type* dim_pointer_;		// pointer to current dimension vector

	}; // class DimensionIterator

	/* column vector for Matrix2D */
	template <typename value_type>
	class ColumnIterator : public DimensionIterator <value_type> {
		public:

			/* create an iterator pointing to column 0 */
			ColumnIterator() {
				DimensionIterator<value_type>(1, 0);
				index_.num_ = 0;
				index_.idx_ = 0;
			} // ColumnIterator()

			ColumnIterator(unsigned int i, unsigned int num_rows, unsigned int num_cols,
							Matrix2D<value_type>* mat):
				DimensionIterator<value_type>(1, num_rows, i, mat->mat_) {
				parent_mat_ = mat;
				index_.num_ = i;
				index_.idx_ = 0;
			} // ColumnIterator()

			/* increment to next column */
			void operator++() {		// next column
				if(index_.num_ == parent_mat_->num_rows_ - 1) {
					index_ = Matrix2D<value_type>::end_index;
					this->dim_pointer_ = NULL;
				} else {
					++ index_.num_;
					index_.idx_ = 0;
					unsigned int index = index_.idx_ * parent_mat_->num_cols_ + index_.num_;
					this->dim_pointer_ = &(parent_mat_->mat_[index]);
				} // if-else
			} // operator++()

			/* decrement to previous column */
			void operator--() {		// previous column
				if(index_.num_ != 0) {
					-- index_.num_;
					index_.idx_ = 0;
					unsigned int index = index_.idx_ * parent_mat_->num_cols_ + index_.num_;
					this->dim_pointer_ = &(parent_mat_->mat_[index]);
				} // if-else
			} // operator--()

			/* assign a pointer to the iterator */
			void operator=(value_type* pointer) {
				this->dim_pointer_ = pointer;
				// what about index_ ?
			} // operator=()

			/* return the i-th element of current column */
			value_type& operator[](unsigned int i) {
				if(i >= parent_mat_->num_rows_) return NULL;
				index_.idx_ = i;
				return parent_mat_->mat_[index_.idx_ * parent_mat_->num_cols_ + index_.num_];
			} // operator[]()

			/* return the value of current column's current index */
			value_type value() {
				unsigned int index = index_.idx_ * parent_mat_->num_cols_ + index_.num_;
				return parent_mat_->mat_[index];
			} // value()

		private:
			Matrix2D<value_type>* parent_mat_;					// is iterator of this object
			typename Matrix2D<value_type>::index_type index_;	// index in matrix

	}; // class ColumnIterator

	/* row iterator for Matrix2D */
	template <typename value_type>
	class RowIterator : public Matrix<value_type>::DimensionIterator {
		public:
			RowIterator() {
			} // RowIterator()

			void operator++() {
			} // operator++()

			void operator--() {
			} // operator--()

			void operator=(value_type* pointer) {
			} // operator=()
	}; // class ColumnIterator

} // namespace woo
<commit_msg>column iterator seems to be working fine<commit_after>/***
  *  Project: Woo Matrix Library
  *
  *  File: matrix.hpp
  *  Created: Dec 03, 2012
  *  Modified: Wed 05 Dec 2012 11:33:45 AM PST
  *
  *  Author: Abhinav Sarje <asarje@lbl.gov>
  */

#include <vector>
#include <cstring>
#include <iostream>

namespace woo {

	template <typename value_type> class ColumnIterator;
	template <typename value_type> class RowIterator;

//	typedef ColumnIterator col_iterator;
//	typedef RowIterator row_iterator;
	// how to define const iterators ...
	//typedef const ColumnIterator const_col_iterator;
	//typedef const RowIterator const_row_iterator;

	template <typename value_type>
	class Matrix {
		protected:
			value_type *mat_;
			unsigned int num_dims_;				// number of dimensions
			std::vector<unsigned int> dims_;	// values of dimensions
			unsigned int capacity_;

		public:
			// default constructor: matrix size not known
			Matrix(): mat_(NULL), num_dims_(0) {
			} // Matrix()

			// generic constructor
			//Matrix(unsigned int num_dims, const std::vector<unsigned int>& dims):
			Matrix(unsigned int num_dims):
					mat_(NULL), num_dims_(num_dims), capacity_(0) {
			} // Matrix()

			void init(const std::vector<unsigned int>& dims) {
				if(dims.size() != num_dims_) {
					std::cerr << "error: number of dimensions does not match list of dimension values"
								<< std::endl;
					return;
				} // if
				dims_.clear();
				unsigned int total_elems = 1;
				for(unsigned int i = 0; i < num_dims_; ++ i) {
					dims_.push_back(dims[i]);
					total_elems *= dims[i];
				} // for
				unsigned int size = 256;
				while(true) {
					if(total_elems <= size) {
						total_elems = size;
						break;
					} // if
					size *= 2;
				} // while
				capacity_ = total_elems;
				mat_ = new (std::nothrow) value_type[total_elems];
				if(mat_ == NULL) {
					std::cerr << "error: failed to allocate memory for the matrix" << std::endl;
					return;
				} // if
				memset(mat_, 0, total_elems * sizeof(value_type));
			} // init()

			// destructor
			~Matrix() {
				if(mat_ != NULL) delete[] mat_;
			} // ~Matrix()

			// a few accessors
			unsigned int dims() const { return num_dims_; }
			unsigned int dim_size(unsigned int i) const { return dims_[i]; }
			unsigned int capacity() const { return capacity_; }

	}; // class Matrix

	template <typename value_type>
	class Matrix2D : public Matrix <value_type> {
		public:

			typedef ColumnIterator<value_type> col_iterator;
			typedef RowIterator<value_type> row_iterator;

			friend class ColumnIterator<value_type>;
			friend class RowIterator<value_type>;

			class IndexType {
				public:
					IndexType(): num_(0), idx_(0) { }
					IndexType(int a, int b): num_(a), idx_(b) { }
					~IndexType() { }

					bool operator==(IndexType other) {
						return (other.num_ == num_ && other.idx_ == idx_);
					} // operator==()

					int num_;		// column/row number
					int idx_;		// index within the column/row
			}; // class IndexType

			typedef IndexType index_type;
			static const index_type end_index;
			static const index_type begin_index;

			// constructor
			Matrix2D(unsigned int rows, unsigned int cols):
				Matrix<value_type>(2) {
				num_rows_ = rows;
				num_cols_ = cols;
				std::vector<unsigned int> dims;
				dims.push_back(num_rows_);
				dims.push_back(num_cols_);
				this->init(dims);
			} // Matrix()

			// iterator to column
			col_iterator column(unsigned int i) {
				if(i <= 0) {
					col_iterator start_col(0, num_rows_, num_cols_, this);
					return start_col;
				} // if
				if(i >= num_cols_) {
					col_iterator end_col(num_cols_ - 1, num_rows_, num_cols_, this);
					return end_col;
				} // if
				col_iterator col(i, num_rows_, num_cols_, this);
				return col;
			} // column()

			// iterator to first column
			col_iterator begin() {
				col_iterator start_col(0, num_rows_, num_cols_, this);
				return start_col;
			} // begin()

			// iterator to column after last (end_index)
			col_iterator end() {
				col_iterator end_col(num_cols_, num_rows_, num_cols_, this);
				return end_col;
			} // end()

			// accessors

			unsigned int num_cols() const { return num_cols_; }
			unsigned int num_rows() const { return num_rows_; }
			unsigned int size() const { return num_cols_ * num_rows_; }

			// access (i, j)-th element
			value_type& operator()(unsigned int i, unsigned int j) {
				return this->mat_[num_cols_ * i + j];
			} // operator()()

			// insert stuff
			bool insert_row(unsigned int i, const std::vector<value_type>& row) { }
			bool insert_col(unsigned int i, const std::vector<value_type>& col) { }

		private:
			unsigned int num_cols_;		// number of columns = row size
			unsigned int num_rows_;		// number of rows = col size

	}; // class Matrix2D

	// begin and end index_type constants
	template<> const Matrix2D<float>::index_type Matrix2D<float>::begin_index(0, 0);
	template<> const Matrix2D<float>::index_type Matrix2D<float>::end_index(-1, -1);
	template<> const Matrix2D<double>::index_type Matrix2D<double>::begin_index(0, 0);
	template<> const Matrix2D<double>::index_type Matrix2D<double>::end_index(-1, -1);
	template<> const Matrix2D<int>::index_type Matrix2D<int>::begin_index(0, 0);
	template<> const Matrix2D<int>::index_type Matrix2D<int>::end_index(-1, -1);
	template<> const Matrix2D<unsigned int>::index_type Matrix2D<unsigned int>::begin_index(0, 0);
	template<> const Matrix2D<unsigned int>::index_type Matrix2D<unsigned int>::end_index(-1, -1);
	template<> const Matrix2D<long int>::index_type Matrix2D<long int>::begin_index(0, 0);
	template<> const Matrix2D<long int>::index_type Matrix2D<long int>::end_index(-1, -1);
	template<> const Matrix2D<unsigned long int>::index_type Matrix2D<unsigned long int>::begin_index(0, 0);
	template<> const Matrix2D<unsigned long int>::index_type Matrix2D<unsigned long int>::end_index(-1, -1);

	/* a generic iterator */
	template <typename value_type>
	class DimensionIterator {
		public:

			//DimensionIterator() { DimensionIterator(0, 0, 0, NULL); }
			DimensionIterator(unsigned int d, unsigned int size, unsigned int i, value_type* mat):
				dim_num_(d), dim_size_(size), dim_index_(i), dim_pointer_(mat) { }
			~DimensionIterator() { }

			virtual void operator++() { }
			virtual void operator--() { }

		protected:

			unsigned int dim_num_;			// dimension number
			unsigned int dim_size_;			// size of the dimension
			unsigned int dim_index_;		// index of the current dimension vector
			value_type* dim_pointer_;		// pointer to current dimension vector

	}; // class DimensionIterator

	/* column vector for Matrix2D */
	template <typename value_type>
	class ColumnIterator : public DimensionIterator <value_type> {
		private:
			Matrix2D<value_type>* parent_mat_;					// is iterator of this object
			typename Matrix2D<value_type>::index_type index_;	// index in matrix

		public:
			/* create an iterator pointing to column 0 */
			ColumnIterator() {
				DimensionIterator<value_type>(1, 0);
				index_.num_ = 0;
				index_.idx_ = 0;
			} // ColumnIterator()

			ColumnIterator(unsigned int i, unsigned int num_rows, unsigned int num_cols,
							Matrix2D<value_type>* mat):
				DimensionIterator<value_type>(1, num_rows, i, mat->mat_) {
				parent_mat_ = mat;
				if(i >= num_cols) {
					index_ = Matrix2D<value_type>::end_index;
				} else {
					index_.num_ = i;
					index_.idx_ = 0;
				} // if-else
			} // ColumnIterator()

			/* increment to next column */
			void operator++() {		// next column
				if(index_ == Matrix2D<value_type>::end_index) {
					// do nothing
				} else if(index_.num_ == parent_mat_->num_rows_ - 1) {
					index_ = Matrix2D<value_type>::end_index;
					this->dim_pointer_ = NULL;
				} else {
					++ index_.num_;
					index_.idx_ = 0;
					unsigned int index = index_.idx_ * parent_mat_->num_cols_ + index_.num_;
					this->dim_pointer_ = &(parent_mat_->mat_[index]);
				} // if-else
			} // operator++()

			/* decrement to previous column */
			void operator--() {		// previous column
				if(index_ == Matrix2D<value_type>::end_index) {
					index_.num_ = parent_mat_->num_cols_ - 1;
				} else if(index_.num_ == 0) {
					index_ = Matrix2D<value_type>::begin_index;
				} else if(index_.num_ != 0) {
					-- index_.num_;
				} // if-else
				index_.idx_ = 0;
				unsigned int index = index_.idx_ * parent_mat_->num_cols_ + index_.num_;
				this->dim_pointer_ = &(parent_mat_->mat_[index]);
			} // operator--()

			/* assign a pointer to the iterator */
			void operator=(value_type* pointer) {
				this->dim_pointer_ = pointer;
				// what about index_ ?
			} // operator=()

			/* return the i-th element of current column */
			value_type& operator[](unsigned int i) {
				if(i >= parent_mat_->num_rows_) {
					return parent_mat_->mat_[(parent_mat_->num_rows_ - 1) * parent_mat_->num_cols_ +
												parent_mat_->num_rows_ - 1];
				} // if
			//	index_.idx_ = i;
				return parent_mat_->mat_[i * parent_mat_->num_cols_ + index_.num_];
			} // operator[]()

			/* comparison operators */

			bool operator==(ColumnIterator other) {
				return (other.index_ == index_ && other.parent_mat_ == parent_mat_);
			} // operator==()

			bool operator!=(ColumnIterator other) {
				return !(other.index_ == index_ && other.parent_mat_ == parent_mat_);
			} // operator!=()

			/* return the value of current column's current index */
			value_type value() const {
				unsigned int index = index_.idx_ * parent_mat_->num_cols_ + index_.num_;
				return parent_mat_->mat_[index];
			} // value()

			unsigned int size() const { return parent_mat_->num_rows_; }

	}; // class ColumnIterator

	/* row iterator for Matrix2D */
	template <typename value_type>
	class RowIterator : public Matrix<value_type>::DimensionIterator {
		public:
			RowIterator() {
			} // RowIterator()

			void operator++() {
			} // operator++()

			void operator--() {
			} // operator--()

			void operator=(value_type* pointer) {
			} // operator=()
	}; // class ColumnIterator

} // namespace woo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: svdomedia.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDOMEDIA_HXX
#define _SVDOMEDIA_HXX

#include <svx/svdorect.hxx>
#include <avmedia/mediaitem.hxx>
#include "svx/svxdllapi.h"

class Graphic;

namespace sdr { namespace contact { class ViewContactOfSdrMediaObj; } }

// ---------------
// - SdrMediaObj -
// ---------------

class SVX_DLLPUBLIC SdrMediaObj : public SdrRectObj
{
    friend class ::sdr::contact::ViewContactOfSdrMediaObj;

public:

                                    TYPEINFO();

                                    SdrMediaObj();
                                    SdrMediaObj( const Rectangle& rRect );

        virtual                     ~SdrMediaObj();

        virtual FASTBOOL            HasTextEdit() const;

        virtual void                TakeObjInfo(SdrObjTransformInfoRec& rInfo) const;
        virtual UINT16              GetObjIdentifier() const;
        virtual sal_Bool            DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;

        virtual void                TakeObjNameSingul(String& rName) const;
        virtual void                TakeObjNamePlural(String& rName) const;

        virtual void                operator=(const SdrObject& rObj);

public:

        void                        setURL( const ::rtl::OUString& rURL );
        const ::rtl::OUString&      getURL() const;

        void                        setMediaProperties( const ::avmedia::MediaItem& rState );
        const ::avmedia::MediaItem& getMediaProperties() const;

        bool                        hasPreferredSize() const;
        Size                        getPreferredSize() const;

        const Graphic&              getGraphic() const;
        void                        setGraphic( const Graphic* pGraphic = NULL );

protected:

        virtual void                mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState );

private:

        virtual ::sdr::contact::ViewContact* CreateObjectSpecificViewContact();

        ::avmedia::MediaItem        maMediaProperties;
        ::std::auto_ptr< Graphic >  mapGraphic;
};

#endif //_SVDOMEDIA_HXX
<commit_msg>INTEGRATION: CWS aw033 (1.2.76); FILE MERGED 2008/05/14 13:57:34 aw 1.2.76.2: RESYNC: (1.2-1.3); FILE MERGED 2008/01/22 12:29:04 aw 1.2.76.1: adaptions and 1st stripping<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: svdomedia.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDOMEDIA_HXX
#define _SVDOMEDIA_HXX

#include <svx/svdorect.hxx>
#include <avmedia/mediaitem.hxx>
#include "svx/svxdllapi.h"

class Graphic;

namespace sdr { namespace contact { class ViewContactOfSdrMediaObj; } }

// ---------------
// - SdrMediaObj -
// ---------------

class SVX_DLLPUBLIC SdrMediaObj : public SdrRectObj
{
    friend class ::sdr::contact::ViewContactOfSdrMediaObj;

public:

                                    TYPEINFO();

                                    SdrMediaObj();
                                    SdrMediaObj( const Rectangle& rRect );

        virtual                     ~SdrMediaObj();

        virtual FASTBOOL            HasTextEdit() const;

        virtual void                TakeObjInfo(SdrObjTransformInfoRec& rInfo) const;
        virtual UINT16              GetObjIdentifier() const;

        virtual void                TakeObjNameSingul(String& rName) const;
        virtual void                TakeObjNamePlural(String& rName) const;

        virtual void                operator=(const SdrObject& rObj);

public:

        void                        setURL( const ::rtl::OUString& rURL );
        const ::rtl::OUString&      getURL() const;

        void                        setMediaProperties( const ::avmedia::MediaItem& rState );
        const ::avmedia::MediaItem& getMediaProperties() const;

        bool                        hasPreferredSize() const;
        Size                        getPreferredSize() const;

        const Graphic&              getGraphic() const;
        void                        setGraphic( const Graphic* pGraphic = NULL );

protected:

        virtual void                mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState );

private:

        virtual ::sdr::contact::ViewContact* CreateObjectSpecificViewContact();

        ::avmedia::MediaItem        maMediaProperties;
        ::std::auto_ptr< Graphic >  mapGraphic;
};

#endif //_SVDOMEDIA_HXX
<|endoftext|>


<commit_before>/* Copyright 2017 R. Thomas
 * Copyright 2017 Quarkslab
 *
 * 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 "LIEF/logging.hpp"
#include "LIEF/version.h"
#include "pyLIEF.hpp"
#include "pyAbstract.hpp"

#if defined(LIEF_ELF_SUPPORT)
  #include "ELF/pyELF.hpp"
#endif

#if defined(LIEF_PE_SUPPORT)
  #include "PE/pyPE.hpp"
#endif

#if defined(LIEF_MACHO_SUPPORT)
  #include "MachO/pyMachO.hpp"
#endif

#if defined(LIEF_OAT_SUPPORT)
  #include "OAT/pyOAT.hpp"
#endif

#if defined(LIEF_VDEX_SUPPORT)
  #include "VDEX/pyVDEX.hpp"
#endif

#if defined(LIEF_DEX_SUPPORT)
  #include "DEX/pyDEX.hpp"
#endif

#if defined(LIEF_ART_SUPPORT)
  #include "ART/pyART.hpp"
#endif

#include "platforms/android/pyAndroid.hpp"

py::module LIEF_module("lief", "Python API for LIEF");

PYBIND11_MODULE(lief, LIEF_module) {

  LIEF_module.attr("__version__")   = py::str(LIEF_VERSION);
  LIEF_module.attr("__tag__")       = py::str(LIEF_TAG);
  LIEF_module.attr("__is_tagged__") = py::bool_(LIEF_TAGGED);

  init_LIEF_Object_class(LIEF_module);

  init_LIEF_iterators(LIEF_module);

  init_LIEF_Logger(LIEF_module);

  // Init custom LIEF exceptions
  init_LIEF_exceptions(LIEF_module);

  // Init the LIEF module
  LIEF::init_python_module(LIEF_module);

  init_hash_functions(LIEF_module);

  // Init the ELF module
#if defined(LIEF_ELF_SUPPORT)
  LIEF::ELF::init_python_module(LIEF_module);
#endif

  // Init the PE module
#if defined(LIEF_PE_SUPPORT)
  LIEF::PE::init_python_module(LIEF_module);
#endif

  // Init the MachO  module
#if defined(LIEF_MACHO_SUPPORT)
  LIEF::MachO::init_python_module(LIEF_module);
#endif

// Init the OAT  module
#if defined(LIEF_OAT_SUPPORT)
  LIEF::OAT::init_python_module(LIEF_module);
#endif

// Init the VDEX module
#if defined(LIEF_VDEX_SUPPORT)
  LIEF::VDEX::init_python_module(LIEF_module);
#endif

// Init the DEX module
#if defined(LIEF_DEX_SUPPORT)
  LIEF::DEX::init_python_module(LIEF_module);
#endif

// Init the ART module
#if defined(LIEF_ART_SUPPORT)
  LIEF::ART::init_python_module(LIEF_module);
#endif

  LIEF::Android::init_python_module(LIEF_module);

  // Init util functions
  init_utils_functions(LIEF_module);

#if defined(LIEF_JSON_SUPPORT)
  init_json_functions(LIEF_module);
#endif

}
<commit_msg>Fix module entry point declaration<commit_after>/* Copyright 2017 R. Thomas
 * Copyright 2017 Quarkslab
 *
 * 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 "LIEF/logging.hpp"
#include "LIEF/version.h"
#include "pyLIEF.hpp"
#include "pyAbstract.hpp"

#if defined(LIEF_ELF_SUPPORT)
  #include "ELF/pyELF.hpp"
#endif

#if defined(LIEF_PE_SUPPORT)
  #include "PE/pyPE.hpp"
#endif

#if defined(LIEF_MACHO_SUPPORT)
  #include "MachO/pyMachO.hpp"
#endif

#if defined(LIEF_OAT_SUPPORT)
  #include "OAT/pyOAT.hpp"
#endif

#if defined(LIEF_VDEX_SUPPORT)
  #include "VDEX/pyVDEX.hpp"
#endif

#if defined(LIEF_DEX_SUPPORT)
  #include "DEX/pyDEX.hpp"
#endif

#if defined(LIEF_ART_SUPPORT)
  #include "ART/pyART.hpp"
#endif

#include "platforms/android/pyAndroid.hpp"

PYBIND11_MODULE(lief, LIEF_module) {

  LIEF_module.attr("__version__")   = py::str(LIEF_VERSION);
  LIEF_module.attr("__tag__")       = py::str(LIEF_TAG);
  LIEF_module.attr("__is_tagged__") = py::bool_(LIEF_TAGGED);
  LIEF_module.doc() = "Python API for LIEF";

  init_LIEF_Object_class(LIEF_module);

  init_LIEF_iterators(LIEF_module);

  init_LIEF_Logger(LIEF_module);

  // Init custom LIEF exceptions
  init_LIEF_exceptions(LIEF_module);

  // Init the LIEF module
  LIEF::init_python_module(LIEF_module);

  init_hash_functions(LIEF_module);

  // Init the ELF module
#if defined(LIEF_ELF_SUPPORT)
  LIEF::ELF::init_python_module(LIEF_module);
#endif

  // Init the PE module
#if defined(LIEF_PE_SUPPORT)
  LIEF::PE::init_python_module(LIEF_module);
#endif

  // Init the MachO  module
#if defined(LIEF_MACHO_SUPPORT)
  LIEF::MachO::init_python_module(LIEF_module);
#endif

// Init the OAT  module
#if defined(LIEF_OAT_SUPPORT)
  LIEF::OAT::init_python_module(LIEF_module);
#endif

// Init the VDEX module
#if defined(LIEF_VDEX_SUPPORT)
  LIEF::VDEX::init_python_module(LIEF_module);
#endif

// Init the DEX module
#if defined(LIEF_DEX_SUPPORT)
  LIEF::DEX::init_python_module(LIEF_module);
#endif

// Init the ART module
#if defined(LIEF_ART_SUPPORT)
  LIEF::ART::init_python_module(LIEF_module);
#endif

  LIEF::Android::init_python_module(LIEF_module);

  // Init util functions
  init_utils_functions(LIEF_module);

#if defined(LIEF_JSON_SUPPORT)
  init_json_functions(LIEF_module);
#endif

}
<|endoftext|>