<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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 for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <cstring>
#include <typeinfo>
#include <pficommon/lang/shared_ptr.h>
#include <pficommon/lang/cast.h>

namespace jubatus {
namespace exception {

namespace detail {
std::string demangle_symbol(const char *symbol);
}

class error_info_base {
public:
  virtual bool splitter() const
  {
    return false;
  }

  virtual std::string tag_typeid_name() const = 0;
  virtual std::string as_string() const = 0;

  virtual ~error_info_base() throw()
  {}
};

template <class Tag, class V>
class error_info;

template <class Tag, class V>
inline std::string to_string(const error_info<Tag, V>& info)
{
  return pfi::lang::lexical_cast<std::string, V>(info.value());
}

template<>
class error_info<struct error_splitter_, void> : public error_info_base {
public:
  bool splitter() const
  {
    return true;
  }

  std::string tag_typeid_name() const
  {
    return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());
  }

  std::string as_string() const
  {
    // USE splitter or tag_typeid_name
    return "-splitter-";
  }
};

template <class Tag, class V>
class error_info : public error_info_base {
public:
  typedef V value_type;
  error_info(value_type v);
  ~error_info() throw();

  std::string tag_typeid_name() const;
  std::string as_string() const;

  value_type value() const
  {
    return value_;
  }

private:
  value_type value_;
};

template <class Tag, class V>
inline error_info<Tag, V>::error_info(value_type v)
  : value_(v)
{
}

template <class Tag, class V>
inline error_info<Tag, V>::~error_info() throw()
{
}

template <class Tag, class V>
inline std::string error_info<Tag, V>::tag_typeid_name() const
{
  return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());
}

template <class Tag, class V>
inline std::string error_info<Tag, V>::as_string() const
{
  return to_string(*this);
}

} // exception
} // jubatus
<commit_msg>Add pragma_once to common/exception_info.hpp<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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 for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#pragma once

#include <cstring>
#include <typeinfo>
#include <pficommon/lang/shared_ptr.h>
#include <pficommon/lang/cast.h>

namespace jubatus {
namespace exception {

namespace detail {
std::string demangle_symbol(const char *symbol);
}

class error_info_base {
public:
  virtual bool splitter() const
  {
    return false;
  }

  virtual std::string tag_typeid_name() const = 0;
  virtual std::string as_string() const = 0;

  virtual ~error_info_base() throw()
  {}
};

template <class Tag, class V>
class error_info;

template <class Tag, class V>
inline std::string to_string(const error_info<Tag, V>& info)
{
  return pfi::lang::lexical_cast<std::string, V>(info.value());
}

template<>
class error_info<struct error_splitter_, void> : public error_info_base {
public:
  bool splitter() const
  {
    return true;
  }

  std::string tag_typeid_name() const
  {
    return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());
  }

  std::string as_string() const
  {
    // USE splitter or tag_typeid_name
    return "-splitter-";
  }
};

template <class Tag, class V>
class error_info : public error_info_base {
public:
  typedef V value_type;
  error_info(value_type v);
  ~error_info() throw();

  std::string tag_typeid_name() const;
  std::string as_string() const;

  value_type value() const
  {
    return value_;
  }

private:
  value_type value_;
};

template <class Tag, class V>
inline error_info<Tag, V>::error_info(value_type v)
  : value_(v)
{
}

template <class Tag, class V>
inline error_info<Tag, V>::~error_info() throw()
{
}

template <class Tag, class V>
inline std::string error_info<Tag, V>::tag_typeid_name() const
{
  return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());
}

template <class Tag, class V>
inline std::string error_info<Tag, V>::as_string() const
{
  return to_string(*this);
}

} // exception
} // jubatus
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2016 gRPC authors.
 *
 * 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 <map>

#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/php_generator_helpers.h"

using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;

namespace grpc_php_generator {
namespace {

grpc::string ConvertToPhpNamespace(const grpc::string& name) {
  std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
  std::ostringstream oss;
  for (unsigned int i = 0; i < tokens.size(); i++) {
    oss << (i == 0 ? "" : "\\")
        << grpc_generator::CapitalizeFirstLetter(tokens[i]);
  }
  return oss.str();
}

grpc::string PackageName(const FileDescriptor* file) {
  if (file->options().has_php_namespace()) {
    return file->options().php_namespace();
  } else {
    return ConvertToPhpNamespace(file->package());
  }
}

grpc::string MessageIdentifierName(const grpc::string& name,
                                   const FileDescriptor* file) {
  std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
  std::ostringstream oss;
  oss << PackageName(file) << "\\"
      << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
  return oss.str();
}

void PrintMethod(const MethodDescriptor* method, Printer* out) {
  const Descriptor* input_type = method->input_type();
  const Descriptor* output_type = method->output_type();
  map<grpc::string, grpc::string> vars;
  vars["service_name"] = method->service()->full_name();
  vars["name"] = method->name();
  vars["input_type_id"] =
      MessageIdentifierName(input_type->full_name(), input_type->file());
  vars["output_type_id"] =
      MessageIdentifierName(output_type->full_name(), output_type->file());

  out->Print("/**\n");
  out->Print(GetPHPComments(method, " *").c_str());
  if (method->client_streaming()) {
    out->Print(vars,
               " * @param array $$metadata metadata\n"
               " * @param array $$options call options\n */\n"
               "public function $name$($$metadata = [], "
               "$$options = []) {\n");
    out->Indent();
    out->Indent();
    if (method->server_streaming()) {
      out->Print("return $$this->_bidiRequest(");
    } else {
      out->Print("return $$this->_clientStreamRequest(");
    }
    out->Print(vars,
               "'/$service_name$/$name$',\n"
               "['\\$output_type_id$','decode'],\n"
               "$$metadata, $$options);\n");
  } else {
    out->Print(vars,
               " * @param \\$input_type_id$ $$argument input argument\n"
               " * @param array $$metadata metadata\n"
               " * @param array $$options call options\n */\n"
               "public function $name$(\\$input_type_id$ $$argument,\n"
               "  $$metadata = [], $$options = []) {\n");
    out->Indent();
    out->Indent();
    if (method->server_streaming()) {
      out->Print("return $$this->_serverStreamRequest(");
    } else {
      out->Print("return $$this->_simpleRequest(");
    }
    out->Print(vars,
               "'/$service_name$/$name$',\n"
               "$$argument,\n"
               "['\\$output_type_id$', 'decode'],\n"
               "$$metadata, $$options);\n");
  }
  out->Outdent();
  out->Outdent();
  out->Print("}\n\n");
}

// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service,
                  const grpc::string& class_suffix, Printer* out) {
  map<grpc::string, grpc::string> vars;
  out->Print("/**\n");
  out->Print(GetPHPComments(service, " *").c_str());
  out->Print(" */\n");
  vars["name"] = GetPHPServiceClassname(service, class_suffix);
  out->Print(vars, "class $name$ extends \\Grpc\\BaseStub {\n\n");
  out->Indent();
  out->Indent();
  out->Print(
      "/**\n * @param string $$hostname hostname\n"
      " * @param array $$opts channel options\n"
      " * @param \\Grpc\\Channel $$channel (optional) re-use channel "
      "object\n */\n"
      "public function __construct($$hostname, $$opts, "
      "$$channel = null) {\n");
  out->Indent();
  out->Indent();
  out->Print("parent::__construct($$hostname, $$opts, $$channel);\n");
  out->Outdent();
  out->Outdent();
  out->Print("}\n\n");
  for (int i = 0; i < service->method_count(); i++) {
    grpc::string method_name =
        grpc_generator::LowercaseFirstLetter(service->method(i)->name());
    PrintMethod(service->method(i), out);
  }
  out->Outdent();
  out->Outdent();
  out->Print("}\n");
}
}  // namespace

grpc::string GenerateFile(const FileDescriptor* file,
                          const ServiceDescriptor* service,
                          const grpc::string& class_suffix) {
  grpc::string output;
  {
    StringOutputStream output_stream(&output);
    Printer out(&output_stream, '$');

    out.Print("<?php\n");
    out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");

    grpc::string leading_comments = GetPHPComments(file, "//");
    if (!leading_comments.empty()) {
      out.Print("// Original file comments:\n");
      out.PrintRaw(leading_comments.c_str());
    }

    map<grpc::string, grpc::string> vars;
    grpc::string php_namespace = PackageName(file);
    vars["package"] = php_namespace;
    out.Print(vars, "namespace $package$;\n\n");

    PrintService(service, class_suffix, &out);
  }
  return output;
}

}  // namespace grpc_php_generator
<commit_msg>update php plugin with protobuf 3.5.0<commit_after>/*
 *
 * Copyright 2016 gRPC authors.
 *
 * 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 <map>

#include <google/protobuf/compiler/php/php_generator.h>
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/php_generator_helpers.h"

using google::protobuf::compiler::php::GeneratedClassName;
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;

namespace grpc_php_generator {
namespace {

grpc::string ConvertToPhpNamespace(const grpc::string& name) {
  std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
  std::ostringstream oss;
  for (unsigned int i = 0; i < tokens.size(); i++) {
    oss << (i == 0 ? "" : "\\")
        << grpc_generator::CapitalizeFirstLetter(tokens[i]);
  }
  return oss.str();
}

grpc::string PackageName(const FileDescriptor* file) {
  if (file->options().has_php_namespace()) {
    return file->options().php_namespace();
  } else {
    return ConvertToPhpNamespace(file->package());
  }
}

grpc::string MessageIdentifierName(const grpc::string& name,
                                   const FileDescriptor* file) {
  std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
  std::ostringstream oss;
  if (PackageName(file) != "") {
    oss << PackageName(file) << "\\";
  }
  oss << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
  return oss.str();
}

void PrintMethod(const MethodDescriptor* method, Printer* out) {
  const Descriptor* input_type = method->input_type();
  const Descriptor* output_type = method->output_type();
  map<grpc::string, grpc::string> vars;
  vars["service_name"] = method->service()->full_name();
  vars["name"] = method->name();
  vars["input_type_id"] =
      MessageIdentifierName(GeneratedClassName(input_type), input_type->file());
  vars["output_type_id"] = MessageIdentifierName(
      GeneratedClassName(output_type), output_type->file());

  out->Print("/**\n");
  out->Print(GetPHPComments(method, " *").c_str());
  if (method->client_streaming()) {
    out->Print(vars,
               " * @param array $$metadata metadata\n"
               " * @param array $$options call options\n */\n"
               "public function $name$($$metadata = [], "
               "$$options = []) {\n");
    out->Indent();
    out->Indent();
    if (method->server_streaming()) {
      out->Print("return $$this->_bidiRequest(");
    } else {
      out->Print("return $$this->_clientStreamRequest(");
    }
    out->Print(vars,
               "'/$service_name$/$name$',\n"
               "['\\$output_type_id$','decode'],\n"
               "$$metadata, $$options);\n");
  } else {
    out->Print(vars,
               " * @param \\$input_type_id$ $$argument input argument\n"
               " * @param array $$metadata metadata\n"
               " * @param array $$options call options\n */\n"
               "public function $name$(\\$input_type_id$ $$argument,\n"
               "  $$metadata = [], $$options = []) {\n");
    out->Indent();
    out->Indent();
    if (method->server_streaming()) {
      out->Print("return $$this->_serverStreamRequest(");
    } else {
      out->Print("return $$this->_simpleRequest(");
    }
    out->Print(vars,
               "'/$service_name$/$name$',\n"
               "$$argument,\n"
               "['\\$output_type_id$', 'decode'],\n"
               "$$metadata, $$options);\n");
  }
  out->Outdent();
  out->Outdent();
  out->Print("}\n\n");
}

// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service,
                  const grpc::string& class_suffix, Printer* out) {
  map<grpc::string, grpc::string> vars;
  out->Print("/**\n");
  out->Print(GetPHPComments(service, " *").c_str());
  out->Print(" */\n");
  vars["name"] = GetPHPServiceClassname(service, class_suffix);
  out->Print(vars, "class $name$ extends \\Grpc\\BaseStub {\n\n");
  out->Indent();
  out->Indent();
  out->Print(
      "/**\n * @param string $$hostname hostname\n"
      " * @param array $$opts channel options\n"
      " * @param \\Grpc\\Channel $$channel (optional) re-use channel "
      "object\n */\n"
      "public function __construct($$hostname, $$opts, "
      "$$channel = null) {\n");
  out->Indent();
  out->Indent();
  out->Print("parent::__construct($$hostname, $$opts, $$channel);\n");
  out->Outdent();
  out->Outdent();
  out->Print("}\n\n");
  for (int i = 0; i < service->method_count(); i++) {
    grpc::string method_name =
        grpc_generator::LowercaseFirstLetter(service->method(i)->name());
    PrintMethod(service->method(i), out);
  }
  out->Outdent();
  out->Outdent();
  out->Print("}\n");
}
}  // namespace

grpc::string GenerateFile(const FileDescriptor* file,
                          const ServiceDescriptor* service,
                          const grpc::string& class_suffix) {
  grpc::string output;
  {
    StringOutputStream output_stream(&output);
    Printer out(&output_stream, '$');

    out.Print("<?php\n");
    out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");

    grpc::string leading_comments = GetPHPComments(file, "//");
    if (!leading_comments.empty()) {
      out.Print("// Original file comments:\n");
      out.PrintRaw(leading_comments.c_str());
    }

    map<grpc::string, grpc::string> vars;
    grpc::string php_namespace = PackageName(file);
    vars["package"] = php_namespace;
    out.Print(vars, "namespace $package$;\n\n");

    PrintService(service, class_suffix, &out);
  }
  return output;
}

}  // namespace grpc_php_generator
<|endoftext|>


<commit_before>#include <syslog.h>

#include "EventLoop.h"
#include "ControlServer.h"
#include "CMUXManager.h"

int main(int argc, char *argv[]) {
  openlog("cmuxcontrold", LOG_PERROR | LOG_PID, LOG_DAEMON);

  syslog(LOG_INFO, "CMUX Control Daemon started");

  EventLoop loop;
  CMUXManager manager(&loop);
  ControlServer control(&loop);
  loop.addWatcher(&control);

  return loop.exec();
}
<commit_msg>Properly daemonize cmuxcontrold.<commit_after>#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>

#include "EventLoop.h"
#include "ControlServer.h"
#include "CMUXManager.h"

static int parse_opts(int argc, char **argv, int *daemon, char **pidfile) {
  int ch;

  *daemon = 0;
  *pidfile = 0;

  while((ch = getopt(argc, argv, "dp:")) != -1) {
    switch(ch) {
      case 'd':
        *daemon = 1;

        break;

      case 'p':
        *pidfile = optarg;

        break;

      case '?':
      case ':':
        return 0;
    }
  }

  return 1;
}

static int daemonize(void) {
  pid_t pid = fork();
  if(pid == -1)
    return 0;

  if(pid > 0)
    _exit(0);

  setsid();
  umask(0);
  chdir("/");
  int null = open("/dev/null", O_RDWR);
  dup2(STDIN_FILENO, null);
  dup2(STDOUT_FILENO, null);
  dup2(STDERR_FILENO, null);
  close(null);

  pid = fork();
  if(pid == -1)
    return 0;

  if(pid > 0)
    _exit(0);

  return 1;
}

int main(int argc, char *argv[]) {
  int daemon;
  char *pidfile;
  if(!parse_opts(argc, argv, &daemon, &pidfile))
    return 1;

  if(daemon) {
    if(!daemonize())
      return 1;

    openlog("cmuxcontrold", LOG_PID, LOG_DAEMON);

  } else {
    openlog("cmuxcontrold", LOG_PERROR | LOG_PID, LOG_DAEMON);
  }

  if(pidfile) {
    FILE *file = fopen(pidfile, "w");
    if(file == NULL) {
      syslog(LOG_CRIT, "unable to create pidfile: %s", strerror(errno));

      return 1;
    }

    fprintf(file, "%d\n", getpid());
    fclose(file);
  }

  syslog(LOG_INFO, "CMUX Control Daemon started");

  EventLoop loop;
  CMUXManager manager(&loop);
  ControlServer control(&loop);
  loop.addWatcher(&control);

  return loop.exec();
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/browser/extensions/theme_preview_infobar_delegate.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(
    TabContents* tab_contents, const std::string& name,
    const std::string& previous_theme_id)
         : ConfirmInfoBarDelegate(tab_contents),
           profile_(tab_contents->profile()), name_(name),
           previous_theme_id_(previous_theme_id) {
}

void ThemePreviewInfobarDelegate::InfoBarClosed() {
  delete this;
}

std::wstring ThemePreviewInfobarDelegate::GetMessageText() const {
  return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL,
                               UTF8ToWide(name_));
}

SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {
  // TODO(aa): Reply with the theme's icon, but this requires reading it
  // asynchronously from disk.
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_THEME);
}

ThemePreviewInfobarDelegate*
    ThemePreviewInfobarDelegate::AsThemePreviewInfobarDelegate() {
  return this;
}

int ThemePreviewInfobarDelegate::GetButtons() const {
  return BUTTON_CANCEL;
}

std::wstring ThemePreviewInfobarDelegate::GetButtonLabel(
    ConfirmInfoBarDelegate::InfoBarButton button) const {
  switch (button) {
    case BUTTON_CANCEL: {
      // TODO(aa): Reusing IDS_UNDO is hack to get around string freeze. This
      // should be changed back to IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON at some
      // point.
      std::wstring undo_text = l10n_util::GetString(IDS_UNDO);
      undo_text.erase(std::remove(undo_text.begin(), undo_text.end(), L'&'),
                      undo_text.end());
      return undo_text;
    }
    default:
      return L"";
  }
}

bool ThemePreviewInfobarDelegate::Cancel() {
  if (!previous_theme_id_.empty()) {
    ExtensionsService* service = profile_->GetExtensionsService();
    if (service) {
      Extension* previous_theme = service->GetExtensionById(previous_theme_id_);
      if (previous_theme) {
        profile_->SetTheme(previous_theme);
        return true;
      }
    }
  }

  profile_->ClearTheme();
  return true;
}
<commit_msg>Use IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON instead of IDS_UNDO since 3.0 shipped.<commit_after>// Copyright (c) 2009 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/browser/extensions/theme_preview_infobar_delegate.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(
    TabContents* tab_contents, const std::string& name,
    const std::string& previous_theme_id)
         : ConfirmInfoBarDelegate(tab_contents),
           profile_(tab_contents->profile()), name_(name),
           previous_theme_id_(previous_theme_id) {
}

void ThemePreviewInfobarDelegate::InfoBarClosed() {
  delete this;
}

std::wstring ThemePreviewInfobarDelegate::GetMessageText() const {
  return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL,
                               UTF8ToWide(name_));
}

SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {
  // TODO(aa): Reply with the theme's icon, but this requires reading it
  // asynchronously from disk.
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_THEME);
}

ThemePreviewInfobarDelegate*
    ThemePreviewInfobarDelegate::AsThemePreviewInfobarDelegate() {
  return this;
}

int ThemePreviewInfobarDelegate::GetButtons() const {
  return BUTTON_CANCEL;
}

std::wstring ThemePreviewInfobarDelegate::GetButtonLabel(
    ConfirmInfoBarDelegate::InfoBarButton button) const {
  switch (button) {
    case BUTTON_CANCEL: {
      return l10n_util::GetString(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON);
    }
    default:
      return L"";
  }
}

bool ThemePreviewInfobarDelegate::Cancel() {
  if (!previous_theme_id_.empty()) {
    ExtensionsService* service = profile_->GetExtensionsService();
    if (service) {
      Extension* previous_theme = service->GetExtensionById(previous_theme_id_);
      if (previous_theme) {
        profile_->SetTheme(previous_theme);
        return true;
      }
    }
  }

  profile_->ClearTheme();
  return true;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Till Adam <adam@kde.org>                        *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/
#include <QDebug>

#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"

#include "append.h"
#include "response.h"

using namespace Akonadi;

Append::Append()
    : Handler(), m_size(-1)
{
}

Append::~Append()
{
}

static QDateTime parseDateTime( const QByteArray & s )
{
    // Syntax:
    // date-time      = DQUOTE date-day-fixed "-" date-month "-" date-year
    //                  SP time SP zone DQUOTE
    // date-day-fixed = (SP DIGIT) / 2DIGIT
    //                    ; Fixed-format version of date-day
    // date-month     = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
    //                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
    // date-year      = 4DIGIT
    // time           = 2DIGIT ":" 2DIGIT ":" 2DIGIT
    //                    ; Hours minutes seconds
    // zone           = ("+" / "-") 4DIGIT
    //                    ; Signed four-digit value of hhmm representing
    //                    ; hours and minutes east of Greenwich (that is,
    //                    ; the amount that the given time differs from
    //                    ; Universal Time).  Subtracting the timezone
    //                    ; from the given time will give the UT form.
    //                    ; The Universal Time zone is "+0000".
    // Example : "28-May-2006 01:03:35 +0200"
    // Position: 0123456789012345678901234567
    //                     1         2
    QDateTime dateTime;
    bool ok = true;
    const int day = ( s[1] == ' ' ? s[2] - '0' // single digit day
                                  : s.mid( 1, 2 ).toInt( &ok ) );
    if ( !ok ) return dateTime;
    const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" );
    int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() );
    if ( month == -1 ) return dateTime;
    month = month / 3 + 1;
    const int year = s.mid( 8, 4 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int hours = s.mid( 13, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int minutes = s.mid( 16, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int seconds = s.mid( 19, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int tzhh = s.mid( 23, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int tzmm = s.mid( 25, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    int tzsecs = tzhh*60*60 + tzmm*60;
    if ( s[22] == '-' ) tzsecs = -tzsecs;
    const QDate date( year, month, day );
    const QTime time( hours, minutes, seconds );
    dateTime = QDateTime( date, time, Qt::UTC );
    if ( !dateTime.isValid() ) return dateTime;
    dateTime.addSecs( -tzsecs );
    return dateTime;
}

bool Akonadi::Append::handleContinuation( const QByteArray& line )
{
    m_data += line;
    m_size -= line.size();
    if ( !allDataRead() )
        return false;
    commit();
    deleteLater();
    return true;
}

bool Akonadi::Append::handleLine(const QByteArray& line )
{
    if ( inContinuation() )
        return handleContinuation( line );

    // Arguments:  mailbox name
    //        OPTIONAL flag parenthesized list
    //        OPTIONAL date/time string
    //        message literal
    //
    // Syntax:
    // append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP literal

    const int startOfCommand = line.indexOf( ' ' ) + 1;
    const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
    const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1;
    m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) );

    // parse optional flag parenthesized list
    // Syntax:
    // flag-list      = "(" [flag *(SP flag)] ")"
    // flag           = "\Answered" / "\Flagged" / "\Deleted" / "\Seen" /
    //                  "\Draft" / flag-keyword / flag-extension
    //                    ; Does not include "\Recent"
    // flag-extension = "\" atom
    // flag-keyword   = atom
    int startOfDateTime = startOfFlags;
    if ( line[startOfFlags] == '(' ) {
        startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2;
        m_flags = line.mid( startOfFlags + 1,
                            startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' ');
    }
    m_flags.append( "\\Recent" ); // the Recent flag always has to be set

    // parse optional date/time string
    int startOfLiteral = startOfDateTime;
    if ( line[startOfDateTime] == '"' ) {
        startOfLiteral = line.indexOf( '{', startOfDateTime + 1 );
        m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) );
        // FIXME Should we return an error if m_dateTime is invalid?
    }
    // if date/time is not given then it will be set to the current date/time
    // by the database

    // finally parse the message literal
    const int startOfSize = startOfLiteral + 1;
    m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt();

    if ( !allDataRead() )
        return startContinuation();

    // otherwise it's a 0-size put, so we're done
    commit();
    deleteLater();
    return true;
}

void Akonadi::Append::commit()
{
    Response response;

    DataStore *db = connection()->storageBackend();
    Location l = db->locationByRawMailbox( m_mailbox );
    MimeType mimeType(0, "message/rfc822" );
    int itemId = 0;
    bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, &itemId );
    response.setTag( tag() );
    if ( !ok ) {
        response.setTag( tag() );
        response.setFailure();
        response.setString( "Append failed" );
        emit responseAvailable( response );
        return;
    }

    // set message flags
    ok = db->appendItemFlags( itemId, m_flags );
    // TODO handle failure

    // the message was appended; now we have to update the counts
    const int existsChange = +1;
    const int recentChange = +1;
    int unseenChange = 0;
    if ( !m_flags.contains( "\\Seen" ) )
        unseenChange = +1;
    // int firstUnseen = ?; // can't be updated atomically, so we probably have to
                            // recalculate it each time it's needed
    ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange );
    // TODO handle failure by removing the message again from the db

    // TODO if the mailbox is currently selected, the normal new message
    //      actions SHOULD occur.  Specifically, the server SHOULD notify the
    //      client immediately via an untagged EXISTS response.

    response.setTag( tag() );
    response.setSuccess();
    response.setString( "Append completed" );
    emit responseAvailable( response );
}

bool Akonadi::Append::inContinuation( ) const
{
    return m_size > -1;
}

bool Akonadi::Append::allDataRead( ) const
{
    m_size == 0;
}

bool Akonadi::Append::startContinuation()
{
    Response response;
    response.setContinuation();
    response.setString( "Ready for literal data" );
    emit responseAvailable( response );
    return false;
}
<commit_msg>I guess that's what was meant.<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Till Adam <adam@kde.org>                        *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/
#include <QDebug>

#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"

#include "append.h"
#include "response.h"

using namespace Akonadi;

Append::Append()
    : Handler(), m_size(-1)
{
}

Append::~Append()
{
}

static QDateTime parseDateTime( const QByteArray & s )
{
    // Syntax:
    // date-time      = DQUOTE date-day-fixed "-" date-month "-" date-year
    //                  SP time SP zone DQUOTE
    // date-day-fixed = (SP DIGIT) / 2DIGIT
    //                    ; Fixed-format version of date-day
    // date-month     = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
    //                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
    // date-year      = 4DIGIT
    // time           = 2DIGIT ":" 2DIGIT ":" 2DIGIT
    //                    ; Hours minutes seconds
    // zone           = ("+" / "-") 4DIGIT
    //                    ; Signed four-digit value of hhmm representing
    //                    ; hours and minutes east of Greenwich (that is,
    //                    ; the amount that the given time differs from
    //                    ; Universal Time).  Subtracting the timezone
    //                    ; from the given time will give the UT form.
    //                    ; The Universal Time zone is "+0000".
    // Example : "28-May-2006 01:03:35 +0200"
    // Position: 0123456789012345678901234567
    //                     1         2
    QDateTime dateTime;
    bool ok = true;
    const int day = ( s[1] == ' ' ? s[2] - '0' // single digit day
                                  : s.mid( 1, 2 ).toInt( &ok ) );
    if ( !ok ) return dateTime;
    const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" );
    int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() );
    if ( month == -1 ) return dateTime;
    month = month / 3 + 1;
    const int year = s.mid( 8, 4 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int hours = s.mid( 13, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int minutes = s.mid( 16, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int seconds = s.mid( 19, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int tzhh = s.mid( 23, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    const int tzmm = s.mid( 25, 2 ).toInt( &ok );
    if ( !ok ) return dateTime;
    int tzsecs = tzhh*60*60 + tzmm*60;
    if ( s[22] == '-' ) tzsecs = -tzsecs;
    const QDate date( year, month, day );
    const QTime time( hours, minutes, seconds );
    dateTime = QDateTime( date, time, Qt::UTC );
    if ( !dateTime.isValid() ) return dateTime;
    dateTime.addSecs( -tzsecs );
    return dateTime;
}

bool Akonadi::Append::handleContinuation( const QByteArray& line )
{
    m_data += line;
    m_size -= line.size();
    if ( !allDataRead() )
        return false;
    commit();
    deleteLater();
    return true;
}

bool Akonadi::Append::handleLine(const QByteArray& line )
{
    if ( inContinuation() )
        return handleContinuation( line );

    // Arguments:  mailbox name
    //        OPTIONAL flag parenthesized list
    //        OPTIONAL date/time string
    //        message literal
    //
    // Syntax:
    // append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP literal

    const int startOfCommand = line.indexOf( ' ' ) + 1;
    const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
    const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1;
    m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) );

    // parse optional flag parenthesized list
    // Syntax:
    // flag-list      = "(" [flag *(SP flag)] ")"
    // flag           = "\Answered" / "\Flagged" / "\Deleted" / "\Seen" /
    //                  "\Draft" / flag-keyword / flag-extension
    //                    ; Does not include "\Recent"
    // flag-extension = "\" atom
    // flag-keyword   = atom
    int startOfDateTime = startOfFlags;
    if ( line[startOfFlags] == '(' ) {
        startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2;
        m_flags = line.mid( startOfFlags + 1,
                            startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' ');
    }
    m_flags.append( "\\Recent" ); // the Recent flag always has to be set

    // parse optional date/time string
    int startOfLiteral = startOfDateTime;
    if ( line[startOfDateTime] == '"' ) {
        startOfLiteral = line.indexOf( '{', startOfDateTime + 1 );
        m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) );
        // FIXME Should we return an error if m_dateTime is invalid?
    }
    // if date/time is not given then it will be set to the current date/time
    // by the database

    // finally parse the message literal
    const int startOfSize = startOfLiteral + 1;
    m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt();

    if ( !allDataRead() )
        return startContinuation();

    // otherwise it's a 0-size put, so we're done
    commit();
    deleteLater();
    return true;
}

void Akonadi::Append::commit()
{
    Response response;

    DataStore *db = connection()->storageBackend();
    Location l = db->locationByRawMailbox( m_mailbox );
    MimeType mimeType(0, "message/rfc822" );
    int itemId = 0;
    bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, &itemId );
    response.setTag( tag() );
    if ( !ok ) {
        response.setTag( tag() );
        response.setFailure();
        response.setString( "Append failed" );
        emit responseAvailable( response );
        return;
    }

    // set message flags
    ok = db->appendItemFlags( itemId, m_flags );
    // TODO handle failure

    // the message was appended; now we have to update the counts
    const int existsChange = +1;
    const int recentChange = +1;
    int unseenChange = 0;
    if ( !m_flags.contains( "\\Seen" ) )
        unseenChange = +1;
    // int firstUnseen = ?; // can't be updated atomically, so we probably have to
                            // recalculate it each time it's needed
    ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange );
    // TODO handle failure by removing the message again from the db

    // TODO if the mailbox is currently selected, the normal new message
    //      actions SHOULD occur.  Specifically, the server SHOULD notify the
    //      client immediately via an untagged EXISTS response.

    response.setTag( tag() );
    response.setSuccess();
    response.setString( "Append completed" );
    emit responseAvailable( response );
}

bool Akonadi::Append::inContinuation( ) const
{
    return m_size > -1;
}

bool Akonadi::Append::allDataRead( ) const
{
    return ( m_size == 0 );
}

bool Akonadi::Append::startContinuation()
{
    Response response;
    response.setContinuation();
    response.setString( "Ready for literal data" );
    emit responseAvailable( response );
    return false;
}
<|endoftext|>


<commit_before>/* medDatabaseExporter.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Tue Jan 19 13:42:53 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Thu Feb  4 11:36:11 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 3
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medDatabaseExporter.h"

#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataWriter.h>
#include <dtkCore/dtkAbstractDataFactory.h>

class medDatabaseExporterPrivate
{
public:
    dtkAbstractData *data;
    QString          filename;
};

medDatabaseExporter::medDatabaseExporter(dtkAbstractData *data, const QString &filename) : medJobItem(), d(new medDatabaseExporterPrivate)
{
    d->data     = data;
    d->filename = filename;
}

medDatabaseExporter::~medDatabaseExporter(void)
{
    delete d;

    d = NULL;
}

void medDatabaseExporter::run(void)
{
    if (!d->data) {
        emit showError(this, "Cannot export data", 3000);
        return;
    }

    if (d->filename.isEmpty()) {
        emit showError(this, "File name is empty", 3000);
        return;
    }

    QList<QString> writers = dtkAbstractDataFactory::instance()->writers();

    for (int i=0; i<writers.size(); i++)
    {
        dtkAbstractDataWriter *dataWriter = dtkAbstractDataFactory::instance()->writer(writers[i]);

        if (! dataWriter->handled().contains(d->data->identifier()))
            continue;

        dataWriter->setData (d->data);

        if (dataWriter->canWrite( d->filename )) {
            if (dataWriter->write( d->filename )) {
                dataWriter->deleteLater();
                break;
            }
        }
    }
}
<commit_msg>Smart pointing what should be smart pointed<commit_after>/* medDatabaseExporter.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Tue Jan 19 13:42:53 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Thu Feb  4 11:36:11 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 3
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medDatabaseExporter.h"

#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataWriter.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkSmartPointer.h>

class medDatabaseExporterPrivate
{
public:
    dtkSmartPointer<dtkAbstractData> data;
    QString          filename;
};

medDatabaseExporter::medDatabaseExporter(dtkAbstractData *data, const QString &filename) : medJobItem(), d(new medDatabaseExporterPrivate)
{
    d->data     = data;
    d->filename = filename;
}

medDatabaseExporter::~medDatabaseExporter(void)
{
    delete d;

    d = NULL;
}

void medDatabaseExporter::run(void)
{
    if (d->data.isNull()) {
        emit showError(this, "Cannot export data", 3000);
        return;
    }

    if (d->filename.isEmpty()) {
        emit showError(this, "File name is empty", 3000);
        return;
    }

    QList<QString> writers = dtkAbstractDataFactory::instance()->writers();
    bool written = false;
    for (int i=0; i<writers.size(); i++)
    {
        dtkSmartPointer<dtkAbstractDataWriter> dataWriter = dtkAbstractDataFactory::instance()->writerSmartPointer(writers[i]);

        if (! dataWriter->handled().contains(d->data->identifier()))
            continue;

        dataWriter->setData (d->data);

        if (dataWriter->canWrite( d->filename )) {
            if (dataWriter->write( d->filename )) {
                written = true;
                break;
            }
        }
    }

    if (!written) {
        emit showError(this, tr("Could not find suitable writer for file: ") + d->filename, 3000);
    }
}
<|endoftext|>


<commit_before>/*
   A central Playground object to manage a set of PulseSensors.
   See https://www.pulsesensor.com to get started.

   Copyright World Famous Electronics LLC - see LICENSE
   Contributors:
     Joel Murphy, https://pulsesensor.com
     Yury Gitman, https://pulsesensor.com
     Bradford Needham, @bneedhamia, https://bluepapertech.com

   Licensed under the MIT License, a copy of which
   should have been included with this software.

   This software is not intended for medical use.
*/
#include <PulseSensorPlayground.h>

// Define the "this" pointer for the ISR
PulseSensorPlayground *PulseSensorPlayground::OurThis;

PulseSensorPlayground::PulseSensorPlayground(int numberOfSensors) {
  // Save a static pointer to our playground so the ISR can read it.
  OurThis = this;

  // Dynamically create the array to minimize ram usage.
  SensorCount = (byte) numberOfSensors;
  Sensors = new PulseSensor[SensorCount];

#if PULSE_SENSOR_TIMING_ANALYSIS
  // We want sample timing analysis, so we construct it.
  pTiming = new PulseSensorTimingStatistics(MICROS_PER_READ, 500 * 30L);
#endif // PULSE_SENSOR_TIMING_ANALYSIS
}

boolean PulseSensorPlayground::PulseSensorPlayground::begin() {

  for (int i = 0; i < SensorCount; ++i) {
    Sensors[i].initializeLEDs();
  }

  // Note the time, for non-interrupt sampling and for timing statistics.
  NextSampleMicros = micros() + MICROS_PER_READ;

  SawNewSample = false;
	Paused = false;

#if PULSE_SENSOR_MEMORY_USAGE
  // Report the RAM usage and hang.
  printMemoryUsage();
  for (;;);
#endif // PULSE_SENSOR_MEMORY_USAGE

  // Lastly, set up and turn on the interrupts.

  if (UsingInterrupts) {
    if (!PulseSensorPlaygroundSetupInterrupt()) {
			Stream *pOut = SerialOutput.getSerial();
		  if (pOut) {
		    pOut->print(F("Interrupts not supported on this platform\n"));
			}
      // The user requested interrupts, but they aren't supported. Say so.
			Paused = true;
      return false;
    }
  }

  return true;
}

void PulseSensorPlayground::analogInput(int inputPin, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].analogInput(inputPin);
}

void PulseSensorPlayground::blinkOnPulse(int blinkPin, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].blinkOnPulse(blinkPin);
}

void PulseSensorPlayground::fadeOnPulse(int fadePin, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].fadeOnPulse(fadePin);
}

boolean PulseSensorPlayground::sawNewSample() {
  /*
     If using interrupts, this function reads and clears the
     'saw a sample' flag that is set by the ISR.

     When not using interrupts, this function sees whether it's time
     to sample and, if so, reads the sample and processes it.

		 First, check to see if the sketch has paused the Pulse Sensor sampling
  */

  if (UsingInterrupts) {
    // Disable interrupts to avoid a race with the ISR.
    DISABLE_PULSE_SENSOR_INTERRUPTS;
    boolean sawOne = SawNewSample;
    SawNewSample = false;
    ENABLE_PULSE_SENSOR_INTERRUPTS;

    return sawOne;
  }else{
		if(Paused){
			SawNewSample = false;
			return false;
		}
	}

  // Time the sample as close as you can when not using interrupts

  unsigned long nowMicros = micros();
  if ((long) (NextSampleMicros - nowMicros) > 0L) {
    return false;  // not time yet.
  }
  NextSampleMicros = nowMicros + MICROS_PER_READ;

#if PULSE_SENSOR_TIMING_ANALYSIS
  if (pTiming->recordSampleTime() <= 0) {
    pTiming->outputStatistics(SerialOutput.getSerial());
    for (;;); // Hang because we've disturbed the timing.
  }
#endif // PULSE_SENSOR_TIMING_ANALYSIS

  // Act as if the ISR was called.
  onSampleTime();

  SawNewSample = false;
  return true;
}

void PulseSensorPlayground::onSampleTime() {
  // Typically called from the ISR.

  /*
     Read the voltage from each PulseSensor.
     We do this separately from processing the voltages
     to minimize jitter in acquiring the signal.
  */
  for (int i = 0; i < SensorCount; ++i) {
    Sensors[i].readNextSample();
  }

  // Process those voltages.
  for (int i = 0; i < SensorCount; ++i) {
    Sensors[i].processLatestSample();
    Sensors[i].updateLEDs();
  }

  // Set the flag that says we've read a sample since the Sketch checked.
  SawNewSample = true;
 }

int PulseSensorPlayground::getLatestSample(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getLatestSample();
}

int PulseSensorPlayground::getBeatsPerMinute(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getBeatsPerMinute();
}

int PulseSensorPlayground::getInterBeatIntervalMs(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getInterBeatIntervalMs();
}

boolean PulseSensorPlayground::sawStartOfBeat(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return false; // out of range.
  }
  return Sensors[sensorIndex].sawStartOfBeat();
}

boolean PulseSensorPlayground::isInsideBeat(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return false; // out of range.
  }
  return Sensors[sensorIndex].isInsideBeat();
}

void PulseSensorPlayground::setSerial(Stream &output) {
  SerialOutput.setSerial(output);
}

void PulseSensorPlayground::setOutputType(byte outputType) {
  SerialOutput.setOutputType(outputType);
}

void PulseSensorPlayground::setThreshold(int threshold, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].setThreshold(threshold);
}

void PulseSensorPlayground::outputSample() {
  SerialOutput.outputSample(Sensors, SensorCount);
}

void PulseSensorPlayground::outputBeat(int sensorIndex) {
  SerialOutput.outputBeat(Sensors, SensorCount, sensorIndex);
}

void PulseSensorPlayground::outputToSerial(char s, int d) {
  SerialOutput.outputToSerial(s,d);
}

int PulseSensorPlayground::getPulseAmplitude(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getPulseAmplitude();
}

unsigned long PulseSensorPlayground::getLastBeatTime(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getLastBeatTime();
}

boolean PulseSensorPlayground::isPaused() {
	return Paused;
}

boolean PulseSensorPlayground::pause() {
	if (UsingInterrupts) {
    if (!PulseSensorPlaygroundDisableInterrupt()) {
			Stream *pOut = SerialOutput.getSerial();
		  if (pOut) {
		    pOut->print(F("Could not pause Pulse Sensor\n"));
			}
      return false;
    }else{
			// DOING THIS HERE BECAUSE IT COULD GET CHOMPED IF WE DO IN resume BELOW
			for(int i=0; i<SensorCount; i++){
				Sensors[i].resetVariables();
			}
			Paused = true;
			return true;
		}
	}else{
		// do something here?
		Paused = true;
		return true;
	}
}

boolean PulseSensorPlayground::resume() {
	if (UsingInterrupts) {
    if (!PulseSensorPlaygroundEnableInterrupt()) {
			Stream *pOut = SerialOutput.getSerial();
		  if (pOut) {
		    pOut->print(F("Could not resume Pulse Sensor\n"));
			}
      return false;
    }else{
			Paused = false;
			return true;
		}
	}else{
		// do something here?
		Paused = false;
		return true;
	}
}

#if PULSE_SENSOR_MEMORY_USAGE
void PulseSensorPlayground::printMemoryUsage() {
  char stack = 1;
  extern char *__data_start;
  extern char *__data_end;
  extern char *__bss_start;
  extern char *__bss_end;
  extern char *__heap_start;
  extern char *__heap_end;

  int	data_size	=	(int)&__data_end - (int)&__data_start;
  int	bss_size	=	(int)&__bss_end - (int)&__data_end;
  int	heap_end	=	(int)&stack - (int)&__malloc_margin;
  int	heap_size	=	heap_end - (int)&__bss_end;
  int	stack_size	=	RAMEND - (int)&stack + 1;
  int	available	=	(RAMEND - (int)&__data_start + 1);
  available	-=	data_size + bss_size + heap_size + stack_size;

  Stream *pOut = SerialOutput.getSerial();
  if (pOut) {
    pOut->print(F("data "));
    pOut->println(data_size);
    pOut->print(F("bss "));
    pOut->println(bss_size);
    pOut->print(F("heap "));
    pOut->println(heap_size);
    pOut->print(F("stack "));
    pOut->println(stack_size);
    pOut->print(F("total "));
    pOut->println(data_size + bss_size + heap_size + stack_size);
  }
}
#endif // PULSE_SENSOR_MEMORY_USAGE
<commit_msg>added reset variables in pause() when not using interrupts<commit_after>/*
   A central Playground object to manage a set of PulseSensors.
   See https://www.pulsesensor.com to get started.

   Copyright World Famous Electronics LLC - see LICENSE
   Contributors:
     Joel Murphy, https://pulsesensor.com
     Yury Gitman, https://pulsesensor.com
     Bradford Needham, @bneedhamia, https://bluepapertech.com

   Licensed under the MIT License, a copy of which
   should have been included with this software.

   This software is not intended for medical use.
*/
#include <PulseSensorPlayground.h>

// Define the "this" pointer for the ISR
PulseSensorPlayground *PulseSensorPlayground::OurThis;

PulseSensorPlayground::PulseSensorPlayground(int numberOfSensors) {
  // Save a static pointer to our playground so the ISR can read it.
  OurThis = this;

  // Dynamically create the array to minimize ram usage.
  SensorCount = (byte) numberOfSensors;
  Sensors = new PulseSensor[SensorCount];

#if PULSE_SENSOR_TIMING_ANALYSIS
  // We want sample timing analysis, so we construct it.
  pTiming = new PulseSensorTimingStatistics(MICROS_PER_READ, 500 * 30L);
#endif // PULSE_SENSOR_TIMING_ANALYSIS
}

boolean PulseSensorPlayground::PulseSensorPlayground::begin() {

  for (int i = 0; i < SensorCount; ++i) {
    Sensors[i].initializeLEDs();
  }

  // Note the time, for non-interrupt sampling and for timing statistics.
  NextSampleMicros = micros() + MICROS_PER_READ;

  SawNewSample = false;
	Paused = false;

#if PULSE_SENSOR_MEMORY_USAGE
  // Report the RAM usage and hang.
  printMemoryUsage();
  for (;;);
#endif // PULSE_SENSOR_MEMORY_USAGE

  // Lastly, set up and turn on the interrupts.

  if (UsingInterrupts) {
    if (!PulseSensorPlaygroundSetupInterrupt()) {
			Stream *pOut = SerialOutput.getSerial();
		  if (pOut) {
		    pOut->print(F("Interrupts not supported on this platform\n"));
			}
      // The user requested interrupts, but they aren't supported. Say so.
			Paused = true;
      return false;
    }
  }

  return true;
}

void PulseSensorPlayground::analogInput(int inputPin, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].analogInput(inputPin);
}

void PulseSensorPlayground::blinkOnPulse(int blinkPin, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].blinkOnPulse(blinkPin);
}

void PulseSensorPlayground::fadeOnPulse(int fadePin, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].fadeOnPulse(fadePin);
}

boolean PulseSensorPlayground::sawNewSample() {
  /*
     If using interrupts, this function reads and clears the
     'saw a sample' flag that is set by the ISR.

     When not using interrupts, this function sees whether it's time
     to sample and, if so, reads the sample and processes it.

		 First, check to see if the sketch has paused the Pulse Sensor sampling
  */

  if (UsingInterrupts) {
    // Disable interrupts to avoid a race with the ISR.
    DISABLE_PULSE_SENSOR_INTERRUPTS;
    boolean sawOne = SawNewSample;
    SawNewSample = false;
    ENABLE_PULSE_SENSOR_INTERRUPTS;

    return sawOne;
  }else{
		if(Paused){
			SawNewSample = false;
			return false;
		}
	}

  // Time the sample as close as you can when not using interrupts

  unsigned long nowMicros = micros();
  if ((long) (NextSampleMicros - nowMicros) > 0L) {
    return false;  // not time yet.
  }
  NextSampleMicros = nowMicros + MICROS_PER_READ;

#if PULSE_SENSOR_TIMING_ANALYSIS
  if (pTiming->recordSampleTime() <= 0) {
    pTiming->outputStatistics(SerialOutput.getSerial());
    for (;;); // Hang because we've disturbed the timing.
  }
#endif // PULSE_SENSOR_TIMING_ANALYSIS

  // Act as if the ISR was called.
  onSampleTime();

  SawNewSample = false;
  return true;
}

void PulseSensorPlayground::onSampleTime() {
  // Typically called from the ISR.

  /*
     Read the voltage from each PulseSensor.
     We do this separately from processing the voltages
     to minimize jitter in acquiring the signal.
  */
  for (int i = 0; i < SensorCount; ++i) {
    Sensors[i].readNextSample();
  }

  // Process those voltages.
  for (int i = 0; i < SensorCount; ++i) {
    Sensors[i].processLatestSample();
    Sensors[i].updateLEDs();
  }

  // Set the flag that says we've read a sample since the Sketch checked.
  SawNewSample = true;
 }

int PulseSensorPlayground::getLatestSample(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getLatestSample();
}

int PulseSensorPlayground::getBeatsPerMinute(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getBeatsPerMinute();
}

int PulseSensorPlayground::getInterBeatIntervalMs(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getInterBeatIntervalMs();
}

boolean PulseSensorPlayground::sawStartOfBeat(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return false; // out of range.
  }
  return Sensors[sensorIndex].sawStartOfBeat();
}

boolean PulseSensorPlayground::isInsideBeat(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return false; // out of range.
  }
  return Sensors[sensorIndex].isInsideBeat();
}

void PulseSensorPlayground::setSerial(Stream &output) {
  SerialOutput.setSerial(output);
}

void PulseSensorPlayground::setOutputType(byte outputType) {
  SerialOutput.setOutputType(outputType);
}

void PulseSensorPlayground::setThreshold(int threshold, int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return; // out of range.
  }
  Sensors[sensorIndex].setThreshold(threshold);
}

void PulseSensorPlayground::outputSample() {
  SerialOutput.outputSample(Sensors, SensorCount);
}

void PulseSensorPlayground::outputBeat(int sensorIndex) {
  SerialOutput.outputBeat(Sensors, SensorCount, sensorIndex);
}

void PulseSensorPlayground::outputToSerial(char s, int d) {
  SerialOutput.outputToSerial(s,d);
}

int PulseSensorPlayground::getPulseAmplitude(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getPulseAmplitude();
}

unsigned long PulseSensorPlayground::getLastBeatTime(int sensorIndex) {
  if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
    return -1; // out of range.
  }
  return Sensors[sensorIndex].getLastBeatTime();
}

boolean PulseSensorPlayground::isPaused() {
	return Paused;
}

boolean PulseSensorPlayground::pause() {
	if (UsingInterrupts) {
    if (!PulseSensorPlaygroundDisableInterrupt()) {
			Stream *pOut = SerialOutput.getSerial();
		  if (pOut) {
		    pOut->print(F("Could not pause Pulse Sensor\n"));
			}
      return false;
    }else{
			// DOING THIS HERE BECAUSE IT COULD GET CHOMPED IF WE DO IN resume BELOW
			for(int i=0; i<SensorCount; i++){
				Sensors[i].resetVariables();
			}
			Paused = true;
			return true;
		}
	}else{
		// do something here?
		for(int i=0; i<SensorCount; i++){
			Sensors[i].resetVariables();
		}
		Paused = true;
		return true;
	}
}

boolean PulseSensorPlayground::resume() {
	if (UsingInterrupts) {
    if (!PulseSensorPlaygroundEnableInterrupt()) {
			Stream *pOut = SerialOutput.getSerial();
		  if (pOut) {
		    pOut->print(F("Could not resume Pulse Sensor\n"));
			}
      return false;
    }else{
			Paused = false;
			return true;
		}
	}else{
		// do something here?
		Paused = false;
		return true;
	}
}

#if PULSE_SENSOR_MEMORY_USAGE
void PulseSensorPlayground::printMemoryUsage() {
  char stack = 1;
  extern char *__data_start;
  extern char *__data_end;
  extern char *__bss_start;
  extern char *__bss_end;
  extern char *__heap_start;
  extern char *__heap_end;

  int	data_size	=	(int)&__data_end - (int)&__data_start;
  int	bss_size	=	(int)&__bss_end - (int)&__data_end;
  int	heap_end	=	(int)&stack - (int)&__malloc_margin;
  int	heap_size	=	heap_end - (int)&__bss_end;
  int	stack_size	=	RAMEND - (int)&stack + 1;
  int	available	=	(RAMEND - (int)&__data_start + 1);
  available	-=	data_size + bss_size + heap_size + stack_size;

  Stream *pOut = SerialOutput.getSerial();
  if (pOut) {
    pOut->print(F("data "));
    pOut->println(data_size);
    pOut->print(F("bss "));
    pOut->println(bss_size);
    pOut->print(F("heap "));
    pOut->println(heap_size);
    pOut->print(F("stack "));
    pOut->println(stack_size);
    pOut->print(F("total "));
    pOut->println(data_size + bss_size + heap_size + stack_size);
  }
}
#endif // PULSE_SENSOR_MEMORY_USAGE
<|endoftext|>


<commit_before><commit_msg>Oops, forgot to add -s to the options spec.<commit_after><|endoftext|>


<commit_before>/*
*
*  Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library 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 for more details.
*
*  Further, this software is distributed without any warranty that it is
*  free of the rightful claim of any third person regarding infringement
*  or the like.  Any license provided herein, whether implied or
*  otherwise, applies only to this software file.  Patent licenses, if
*  any, provided herein do not apply to combinations of this program with
*  other software, or any other product whatsoever.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
*  Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
*  28359 Bremen, Germany or:
*
*  http://www.mevis.de
*
*/

//----------------------------------------------------------------------------------
/*!
// \file    PythonQtStdDecorators.cpp
// \author  Florian Link
// \author  Last changed by $Author: florian $
// \date    2007-04
*/
//----------------------------------------------------------------------------------

#include "PythonQtStdDecorators.h"
#include "PythonQt.h"
#include "PythonQtClassInfo.h"
#include <QCoreApplication>

bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
  QByteArray signalTmp;
  char first = signal.at(0);
  if (first>='0' && first<='9') {
    signalTmp = signal;
  } else {
    signalTmp = "2" + signal;
  }

  if (sender) {
    return PythonQt::self()->addSignalHandler(sender, signalTmp, callable);
  } else {
    return false;
  }
}

bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
  bool r = false;
  if (sender && receiver) {
    QByteArray signalTmp;
    char first = signal.at(0);
    if (first>='0' && first<='9') {
      signalTmp = signal;
    } else {
      signalTmp = "2" + signal;
    }

    QByteArray slotTmp;
    first = slot.at(0);
    if (first>='0' && first<='9') {
      slotTmp = slot;
    } else {
      slotTmp = "1" + slot;
    }
    r = QObject::connect(sender, signalTmp, receiver, slotTmp);
  }
  return r;
}

bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
  QByteArray signalTmp;
  char first = signal.at(0);
  if (first>='0' && first<='9') {
    signalTmp = signal;
  } else {
    signalTmp = "2" + signal;
  }
  if (sender) {
    return PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);
  } else {
    return false;
  }
}

bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
  bool r = false;
  if (sender && receiver) {
    QByteArray signalTmp;
    char first = signal.at(0);
    if (first>='0' && first<='9') {
      signalTmp = signal;
    } else {
      signalTmp = "2" + signal;
    }

    QByteArray slotTmp;
    first = slot.at(0);
    if (first>='0' && first<='9') {
      slotTmp = slot;
    } else {
      slotTmp = "1" + slot;
    }

    r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);
  }
  return r;
}

QObject* PythonQtStdDecorators::parent(QObject* o) {
  return o->parent();
}

void PythonQtStdDecorators::setParent(QObject* o, QObject* parent)
{
  o->setParent(parent);
}

const QObjectList* PythonQtStdDecorators::children(QObject* o)
{
  return &o->children();
}

bool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)
{
  return o->setProperty(name, value);
}

QVariant PythonQtStdDecorators::property(QObject* o, const char* name)
{
  return o->property(name);
}

QString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)
{
  return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);
}

QObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)
{
  const QMetaObject* meta = NULL;
  const char* typeName = NULL;

  if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
    meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
  } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
    meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
  } else if (PyString_Check(type)) {
    typeName = PyString_AsString(type);
  }

  if (!typeName && !meta)
    return NULL;

  return findChild(parent, typeName, meta, name);
}

QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)
{
  const QMetaObject* meta = NULL;
  const char* typeName = NULL;

  if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
    meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
  } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
    meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
  } else if (PyString_Check(type)) {
    typeName = PyString_AsString(type);
  }

  QList<QObject*> list;

  if (!typeName && !meta)
    return list;

  findChildren(parent, typeName, meta, name, list);

  return list;
}

QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)
{
  const QMetaObject* meta = NULL;
  const char* typeName = NULL;

  if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
    meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
  } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
    meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
  } else if (PyString_Check(type)) {
    typeName = PyString_AsString(type);
  }

  QList<QObject*> list;

  if (!typeName && !meta)
    return list;

  findChildren(parent, typeName, meta, regExp, list);

  return list;
}

QObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)
{
  const QObjectList &children = parent->children();

  int i;
  for (i = 0; i < children.size(); ++i) {
    QObject* obj = children.at(i);

    if (!obj)
      return NULL;

    // Skip if the name doesn't match.
    if (!name.isNull() && obj->objectName() != name)
      continue;

    if ((typeName && obj->inherits(typeName)) ||
      (meta && meta->cast(obj)))
      return obj;
  }

  for (i = 0; i < children.size(); ++i) {
    QObject* obj = findChild(children.at(i), typeName, meta, name);

    if (obj != NULL)
      return obj;
  }

  return NULL;
}

int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)
{
  const QObjectList& children = parent->children();
  int i;

  for (i = 0; i < children.size(); ++i) {
    QObject* obj = children.at(i);

    if (!obj)
      return -1;

    // Skip if the name doesn't match.
    if (!name.isNull() && obj->objectName() != name)
      continue;

    if ((typeName && obj->inherits(typeName)) ||
      (meta && meta->cast(obj))) {
        list += obj;
    }

    if (findChildren(obj, typeName, meta, name, list) < 0)
      return -1;
  }

  return 0;
}

int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)
{
  const QObjectList& children = parent->children();
  int i;

  for (i = 0; i < children.size(); ++i) {
    QObject* obj = children.at(i);

    if (!obj)
      return -1;

    // Skip if the name doesn't match.
    if (regExp.indexIn(obj->objectName()) == -1)
      continue;

    if ((typeName && obj->inherits(typeName)) ||
      (meta && meta->cast(obj))) {
        list += obj;
    }

    if (findChildren(obj, typeName, meta, regExp, list) < 0)
      return -1;
  }

  return 0;
}
<commit_msg>added error printing for connect/disconnect<commit_after>/*
*
*  Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library 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 for more details.
*
*  Further, this software is distributed without any warranty that it is
*  free of the rightful claim of any third person regarding infringement
*  or the like.  Any license provided herein, whether implied or
*  otherwise, applies only to this software file.  Patent licenses, if
*  any, provided herein do not apply to combinations of this program with
*  other software, or any other product whatsoever.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
*  Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
*  28359 Bremen, Germany or:
*
*  http://www.mevis.de
*
*/

//----------------------------------------------------------------------------------
/*!
// \file    PythonQtStdDecorators.cpp
// \author  Florian Link
// \author  Last changed by $Author: florian $
// \date    2007-04
*/
//----------------------------------------------------------------------------------

#include "PythonQtStdDecorators.h"
#include "PythonQt.h"
#include "PythonQtClassInfo.h"
#include <QCoreApplication>

bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
  bool result = false;
  QByteArray signalTmp;
  char first = signal.at(0);
  if (first>='0' && first<='9') {
    signalTmp = signal;
  } else {
    signalTmp = "2" + signal;
  }

  if (sender) {
    result = PythonQt::self()->addSignalHandler(sender, signalTmp, callable);
    if (!result) {
      if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {
        qWarning("PythonQt: QObject::connect() signal '%s' does not exist on %s", signal.constData(), sender->metaObject()->className());
      }
    }
  }
  return result;
}

bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
  bool r = false;
  if (sender && receiver) {
    QByteArray signalTmp;
    char first = signal.at(0);
    if (first>='0' && first<='9') {
      signalTmp = signal;
    } else {
      signalTmp = "2" + signal;
    }

    QByteArray slotTmp;
    first = slot.at(0);
    if (first>='0' && first<='9') {
      slotTmp = slot;
    } else {
      slotTmp = "1" + slot;
    }
    r = QObject::connect(sender, signalTmp, receiver, slotTmp);
  }
  return r;
}

bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
  bool result = false;
  QByteArray signalTmp;
  char first = signal.at(0);
  if (first>='0' && first<='9') {
    signalTmp = signal;
  } else {
    signalTmp = "2" + signal;
  }
  if (sender) {
    result = PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);
    if (!result) {
      if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {
        qWarning("PythonQt: QObject::disconnect() signal '%s' does not exist on %s", signal.constData(), sender->metaObject()->className());
      }
    }
  }
  return result;
}

bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
  bool r = false;
  if (sender && receiver) {
    QByteArray signalTmp;
    char first = signal.at(0);
    if (first>='0' && first<='9') {
      signalTmp = signal;
    } else {
      signalTmp = "2" + signal;
    }

    QByteArray slotTmp;
    first = slot.at(0);
    if (first>='0' && first<='9') {
      slotTmp = slot;
    } else {
      slotTmp = "1" + slot;
    }

    r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);
  }
  return r;
}

QObject* PythonQtStdDecorators::parent(QObject* o) {
  return o->parent();
}

void PythonQtStdDecorators::setParent(QObject* o, QObject* parent)
{
  o->setParent(parent);
}

const QObjectList* PythonQtStdDecorators::children(QObject* o)
{
  return &o->children();
}

bool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)
{
  return o->setProperty(name, value);
}

QVariant PythonQtStdDecorators::property(QObject* o, const char* name)
{
  return o->property(name);
}

QString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)
{
  return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);
}

QObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)
{
  const QMetaObject* meta = NULL;
  const char* typeName = NULL;

  if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
    meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
  } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
    meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
  } else if (PyString_Check(type)) {
    typeName = PyString_AsString(type);
  }

  if (!typeName && !meta)
    return NULL;

  return findChild(parent, typeName, meta, name);
}

QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)
{
  const QMetaObject* meta = NULL;
  const char* typeName = NULL;

  if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
    meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
  } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
    meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
  } else if (PyString_Check(type)) {
    typeName = PyString_AsString(type);
  }

  QList<QObject*> list;

  if (!typeName && !meta)
    return list;

  findChildren(parent, typeName, meta, name, list);

  return list;
}

QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)
{
  const QMetaObject* meta = NULL;
  const char* typeName = NULL;

  if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
    meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
  } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
    meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
  } else if (PyString_Check(type)) {
    typeName = PyString_AsString(type);
  }

  QList<QObject*> list;

  if (!typeName && !meta)
    return list;

  findChildren(parent, typeName, meta, regExp, list);

  return list;
}

QObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)
{
  const QObjectList &children = parent->children();

  int i;
  for (i = 0; i < children.size(); ++i) {
    QObject* obj = children.at(i);

    if (!obj)
      return NULL;

    // Skip if the name doesn't match.
    if (!name.isNull() && obj->objectName() != name)
      continue;

    if ((typeName && obj->inherits(typeName)) ||
      (meta && meta->cast(obj)))
      return obj;
  }

  for (i = 0; i < children.size(); ++i) {
    QObject* obj = findChild(children.at(i), typeName, meta, name);

    if (obj != NULL)
      return obj;
  }

  return NULL;
}

int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)
{
  const QObjectList& children = parent->children();
  int i;

  for (i = 0; i < children.size(); ++i) {
    QObject* obj = children.at(i);

    if (!obj)
      return -1;

    // Skip if the name doesn't match.
    if (!name.isNull() && obj->objectName() != name)
      continue;

    if ((typeName && obj->inherits(typeName)) ||
      (meta && meta->cast(obj))) {
        list += obj;
    }

    if (findChildren(obj, typeName, meta, name, list) < 0)
      return -1;
  }

  return 0;
}

int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)
{
  const QObjectList& children = parent->children();
  int i;

  for (i = 0; i < children.size(); ++i) {
    QObject* obj = children.at(i);

    if (!obj)
      return -1;

    // Skip if the name doesn't match.
    if (regExp.indexIn(obj->objectName()) == -1)
      continue;

    if ((typeName && obj->inherits(typeName)) ||
      (meta && meta->cast(obj))) {
        list += obj;
    }

    if (findChildren(obj, typeName, meta, regExp, list) < 0)
      return -1;
  }

  return 0;
}
<|endoftext|>