<commit_before>#include <QMessageBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QPushButton>
#include <QDesktopServices>
#include <QDebug>
#include <climits>

#include "utils/utils.h"
#include "progress-dialog.h"
#include "seafile-applet.h"
#include "transfer-mgr.h"

namespace
{
const char* kQueryIndexUrl = "idx_progress";
} // namespace

FileBrowserProgressDialog::FileBrowserProgressDialog(FileNetworkTask *task, QWidget *parent)
        : QProgressDialog(parent),
          task_(task),
          progress_request_(NULL),
          index_progress_timer_(new QTimer(this)),
          task_finished_(false)
{
    initUI();
    initTaskInfo();

    connect(index_progress_timer_, SIGNAL(timeout()), this, SLOT(onQueryUpdate()));

    connect(task_, SIGNAL(progressUpdate(qint64, qint64)),
            this, SLOT(onProgressUpdate(qint64, qint64)));
    connect(task_, SIGNAL(nameUpdate(QString)),
            this, SLOT(onCurrentNameUpdate(QString)));
    connect(task_, SIGNAL(finished(bool)), this, SLOT(onTaskFinished(bool)));
    connect(task_, SIGNAL(retried(int)), this, SLOT(initTaskInfo()));
    connect(this, SIGNAL(canceled()), this, SLOT(cancel()));

    if (task_->type() == FileNetworkTask::Upload) {
        FileUploadTask *upload_task = (FileUploadTask *)task_;
        connect(upload_task, SIGNAL(oneFileFailed(const QString&, bool)),
                this, SLOT(onOneFileUploadFailed(const QString&, bool)));
    }
}

void FileBrowserProgressDialog::initUI()
{
    setWindowModality(Qt::NonModal);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowIcon(QIcon(":/images/seafile.png"));

    QVBoxLayout *layout_ = new QVBoxLayout;
    progress_bar_ = new QProgressBar;
    description_label_ = new QLabel;

    layout_->addWidget(description_label_);
    layout_->addWidget(progress_bar_);

    QHBoxLayout *hlayout_ = new QHBoxLayout;
    more_details_label_ = new QLabel;
    more_details_label_->setText(tr("Pending"));
    cancel_button_ = new QPushButton(tr("Cancel"));
    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    hlayout_->addWidget(more_details_label_);
    hlayout_->addWidget(spacer);
    hlayout_->addWidget(cancel_button_);
    hlayout_->setContentsMargins(-1, 0, -1, 6);
    layout_->setContentsMargins(-1, 0, -1, 6);
    layout_->addLayout(hlayout_);

    setLayout(layout_);
    setLabel(description_label_);
    setBar(progress_bar_);
    setCancelButton(cancel_button_);
}

FileBrowserProgressDialog::~FileBrowserProgressDialog()
{
    if (progress_request_ != NULL)
        progress_request_->deleteLater();
}

void FileBrowserProgressDialog::initTaskInfo()
{
    task_finished_ = false;
    if (task_->canceled()) {
        return;
    }
    QString title, label;
    if (task_->type() == FileNetworkTask::Upload) {
        title = tr("Upload");
        label = tr("Uploading %1");
    } else {
        title = tr("Download");
        label = tr("Downloading %1");
    }
    setWindowTitle(title);
    setLabelText(label.arg(QFileInfo(task_->localFilePath()).fileName()));

    more_details_label_->setText("");

    setMaximum(0);
    setValue(0);
}

void FileBrowserProgressDialog::onCurrentNameUpdate(QString current_name)
{
    QString label = tr("Uploading %1");
    setLabelText(label.arg(current_name));
}

void FileBrowserProgressDialog::onProgressUpdate(qint64 processed_bytes, qint64 total_bytes)
{
    // Skip the updates if the task has been cancelled, because we may already
    // have already rejected this dialog.
    if (task_->canceled()) {
        return;
    }
    // if the value is less than the maxmium, this dialog will close itself
    // add this guard for safety
    if (processed_bytes >= total_bytes)
        total_bytes = processed_bytes + 1;

    if (total_bytes > INT_MAX) {
        if (maximum() != INT_MAX)
            setMaximum(INT_MAX);

        // Avoid overflow
        double progress = double(processed_bytes) * INT_MAX / total_bytes;
        setValue((int)progress);
    } else {
        if (maximum() != total_bytes)
            setMaximum(total_bytes);

        setValue(processed_bytes);
    }

    more_details_label_->setText(tr("%1 of %2")
                            .arg(::readableFileSizeV2(processed_bytes))
                            .arg(::readableFileSizeV2(total_bytes)));
}

void FileBrowserProgressDialog::onTaskFinished(bool success)
{
    task_finished_ = true;
    // printf ("FileBrowserProgressDialog: onTaskFinished\n");
    if (task_->canceled()) {
        return;
    }

    cancel_button_->setVisible(false);

    // When this "onTaskFinished" slot is called, the task may NOT
    // have really finished yet, i.e. if we configured "async save" on
    // server, we need to query the async save progress and only close
    // the dialog after the async save is done.
    //
    // TODO: Right now the async save progress query is implemented
    // here, but ideally it should be implemented inside the
    // ReliablePostFileTask class for better encapsulation.
    progerss_id_ = task_->oid();

    //https://dev.seafile.com/seafhttp/upload-api/b7443978-42cf-4cc6-87bf-add0fc7ad6e3
    //https://dev.seafile.com/seafhttp/idx_progress
    progress_url_ = ::urlJoin(QUrl(task_->url().toString(QUrl::PrettyDecoded).
                                   section("upload", 0, 0)), kQueryIndexUrl);
    if (success) {
        // printf ("progress dialog: task success\n");

        //Judge "-" as a task id or a file id
        //Compatible with new and old server versions
        if (progerss_id_.contains("-")) {
            onQueryUpdate();
            index_progress_timer_->start(3000);
        } else {
            accept();
        }
    } else {
        // printf ("progress dialog: task failed\n");
        reject();
    }
}

void FileBrowserProgressDialog::onQueryUpdate()
{
    if (progress_request_) {
        progress_request_->deleteLater();
        progress_request_ = NULL;
    }

    progress_request_ = new GetIndexProgressRequest(progress_url_, progerss_id_);
    connect(progress_request_, SIGNAL(success(const ServerIndexProgress&)),
            this, SLOT(onQuerySuccess(const ServerIndexProgress&)));
    connect(progress_request_, SIGNAL(failed(const ApiError& error)),
            this, SLOT(onQueryFailed(const ApiError& error)));

    progress_request_->send();
}

void FileBrowserProgressDialog::onQuerySuccess(const ServerIndexProgress &result)
{
    setLabelText(tr("Saving"));
    more_details_label_->setText(tr("%1 of %2")
                            .arg(::readableFileSizeV2(result.indexed))
                            .arg(::readableFileSizeV2(result.total)));
    if (result.status == 0) {
        index_progress_timer_->stop();
        accept();
    } else if (result.status == -1) {
        index_progress_timer_->stop();
        seafApplet->warningBox(tr("File save failed"), this);
        reject();
    }
}

void FileBrowserProgressDialog::onQueryFailed(const ApiError& error)
{
    qWarning("get index progress request error: %s", error.toString().toUtf8().data());
    // when occour http error stop index_progress_timer.
    if (error.type() == ApiError::HTTP_ERROR) {
        seafApplet->warningBox(tr("Index progress request error %1").arg(error.httpErrorCode()));
        index_progress_timer_->stop();
    }
}

void FileBrowserProgressDialog::cancel()
{
    if (task_finished_ || task_->canceled()) {
        return;
    }
    if (task_->type() == FileNetworkTask::Upload) {
        task_->cancel();
    } else {
        // For download tasks we need to go through the transfer manager
        TransferManager::instance()->cancelDownload(task_->repoId(), task_->path());
    }
    reject();
}

void FileBrowserProgressDialog::onOneFileUploadFailed(const QString &filename,
                                                      bool single_file)
{
    if (task_->canceled()) {
        return;
    }

    FileUploadTask *upload_task = (FileUploadTask *)task_;

    QString msg =
        tr("Failed to upload file \"%1\", do you want to retry?").arg(filename);
    ActionOnFailure choice = retryOrSkipOrAbort(msg, single_file);

    switch (choice) {
        case ActionRetry:
            upload_task->continueWithFailedFile(true);
            break;
        case ActionSkip:
            upload_task->continueWithFailedFile(false);
            break;
        case ActionAbort:
            cancel();
            break;
    }
}

FileBrowserProgressDialog::ActionOnFailure
FileBrowserProgressDialog::retryOrSkipOrAbort(const QString& msg, bool single_file)
{
    QMessageBox box(this);
    box.setText(msg);
    box.setWindowTitle(getBrand());
    box.setIcon(QMessageBox::Question);

    QPushButton *yes_btn = box.addButton(tr("Retry"), QMessageBox::YesRole);
    QPushButton *no_btn = nullptr;
    if (!single_file) {
        // If this is single file upload/update, we only show "retry" and
        // "abort".
        no_btn = box.addButton(tr("Skip"), QMessageBox::NoRole);
    }
    box.addButton(tr("Abort"), QMessageBox::RejectRole);

    box.setDefaultButton(yes_btn);
    box.exec();
    QAbstractButton *btn = box.clickedButton();
    if (btn == yes_btn) {
        return ActionRetry;
    } else if (btn == no_btn) {
        return ActionSkip;
    }

    return ActionAbort;
}
<commit_msg>change after review<commit_after>#include <QMessageBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QPushButton>
#include <QDesktopServices>
#include <QDebug>
#include <climits>

#include "utils/utils.h"
#include "progress-dialog.h"
#include "seafile-applet.h"
#include "transfer-mgr.h"

namespace
{
const char* kQueryIndexUrl = "idx_progress";
} // namespace

FileBrowserProgressDialog::FileBrowserProgressDialog(FileNetworkTask *task, QWidget *parent)
        : QProgressDialog(parent),
          task_(task),
          progress_request_(NULL),
          index_progress_timer_(new QTimer(this)),
          task_finished_(false)
{
    initUI();
    initTaskInfo();

    connect(index_progress_timer_, SIGNAL(timeout()), this, SLOT(onQueryUpdate()));

    connect(task_, SIGNAL(progressUpdate(qint64, qint64)),
            this, SLOT(onProgressUpdate(qint64, qint64)));
    connect(task_, SIGNAL(nameUpdate(QString)),
            this, SLOT(onCurrentNameUpdate(QString)));
    connect(task_, SIGNAL(finished(bool)), this, SLOT(onTaskFinished(bool)));
    connect(task_, SIGNAL(retried(int)), this, SLOT(initTaskInfo()));
    connect(this, SIGNAL(canceled()), this, SLOT(cancel()));

    if (task_->type() == FileNetworkTask::Upload) {
        FileUploadTask *upload_task = (FileUploadTask *)task_;
        connect(upload_task, SIGNAL(oneFileFailed(const QString&, bool)),
                this, SLOT(onOneFileUploadFailed(const QString&, bool)));
    }
}

void FileBrowserProgressDialog::initUI()
{
    setWindowModality(Qt::NonModal);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowIcon(QIcon(":/images/seafile.png"));

    QVBoxLayout *layout_ = new QVBoxLayout;
    progress_bar_ = new QProgressBar;
    description_label_ = new QLabel;

    layout_->addWidget(description_label_);
    layout_->addWidget(progress_bar_);

    QHBoxLayout *hlayout_ = new QHBoxLayout;
    more_details_label_ = new QLabel;
    more_details_label_->setText(tr("Pending"));
    cancel_button_ = new QPushButton(tr("Cancel"));
    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    hlayout_->addWidget(more_details_label_);
    hlayout_->addWidget(spacer);
    hlayout_->addWidget(cancel_button_);
    hlayout_->setContentsMargins(-1, 0, -1, 6);
    layout_->setContentsMargins(-1, 0, -1, 6);
    layout_->addLayout(hlayout_);

    setLayout(layout_);
    setLabel(description_label_);
    setBar(progress_bar_);
    setCancelButton(cancel_button_);
}

FileBrowserProgressDialog::~FileBrowserProgressDialog()
{
    if (progress_request_ != NULL)
        progress_request_->deleteLater();
}

void FileBrowserProgressDialog::initTaskInfo()
{
    task_finished_ = false;
    if (task_->canceled()) {
        return;
    }
    QString title, label;
    if (task_->type() == FileNetworkTask::Upload) {
        title = tr("Upload");
        label = tr("Uploading %1");
    } else {
        title = tr("Download");
        label = tr("Downloading %1");
    }
    setWindowTitle(title);
    setLabelText(label.arg(QFileInfo(task_->localFilePath()).fileName()));

    more_details_label_->setText("");

    setMaximum(0);
    setValue(0);
}

void FileBrowserProgressDialog::onCurrentNameUpdate(QString current_name)
{
    QString label = tr("Uploading %1");
    setLabelText(label.arg(current_name));
}

void FileBrowserProgressDialog::onProgressUpdate(qint64 processed_bytes, qint64 total_bytes)
{
    // Skip the updates if the task has been cancelled, because we may already
    // have already rejected this dialog.
    if (task_->canceled()) {
        return;
    }
    // if the value is less than the maxmium, this dialog will close itself
    // add this guard for safety
    if (processed_bytes >= total_bytes)
        total_bytes = processed_bytes + 1;

    if (total_bytes > INT_MAX) {
        if (maximum() != INT_MAX)
            setMaximum(INT_MAX);

        // Avoid overflow
        double progress = double(processed_bytes) * INT_MAX / total_bytes;
        setValue((int)progress);
    } else {
        if (maximum() != total_bytes)
            setMaximum(total_bytes);

        setValue(processed_bytes);
    }

    more_details_label_->setText(tr("%1 of %2")
                            .arg(::readableFileSizeV2(processed_bytes))
                            .arg(::readableFileSizeV2(total_bytes)));
}

void FileBrowserProgressDialog::onTaskFinished(bool success)
{
    task_finished_ = true;
    // printf ("FileBrowserProgressDialog: onTaskFinished\n");
    if (task_->canceled()) {
        return;
    }

    cancel_button_->setVisible(false);

    // When this "onTaskFinished" slot is called, the task may NOT
    // have really finished yet, i.e. if we configured "async save" on
    // server, we need to query the async save progress and only close
    // the dialog after the async save is done.
    //
    // TODO: Right now the async save progress query is implemented
    // here, but ideally it should be implemented inside the
    // ReliablePostFileTask class for better encapsulation.
    progerss_id_ = task_->oid();

    //https://dev.seafile.com/seafhttp/upload-api/b7443978-42cf-4cc6-87bf-add0fc7ad6e3
    //https://dev.seafile.com/seafhttp/idx_progress
    progress_url_ = ::urlJoin(QUrl(task_->url().toString(QUrl::PrettyDecoded).
                                   section("upload", 0, 0)), kQueryIndexUrl);
    if (success) {
        // printf ("progress dialog: task success\n");

        //Judge "-" as a task id or a file id
        //Compatible with new and old server versions
        if (progerss_id_.contains("-")) {
            onQueryUpdate();
            index_progress_timer_->start(3000);
        } else {
            accept();
        }
    } else {
        // printf ("progress dialog: task failed\n");
        reject();
    }
}

void FileBrowserProgressDialog::onQueryUpdate()
{
    if (progress_request_) {
        progress_request_->deleteLater();
        progress_request_ = NULL;
    }

    progress_request_ = new GetIndexProgressRequest(progress_url_, progerss_id_);
    connect(progress_request_, SIGNAL(success(const ServerIndexProgress&)),
            this, SLOT(onQuerySuccess(const ServerIndexProgress&)));
    connect(progress_request_, SIGNAL(failed(const ApiError& error)),
            this, SLOT(onQueryFailed(const ApiError& error)));

    progress_request_->send();
}

void FileBrowserProgressDialog::onQuerySuccess(const ServerIndexProgress &result)
{
    setLabelText(tr("Saving"));
    more_details_label_->setText(tr("%1 of %2")
                            .arg(::readableFileSizeV2(result.indexed))
                            .arg(::readableFileSizeV2(result.total)));
    if (result.status == 0) {
        index_progress_timer_->stop();
        accept();
    } else if (result.status == -1) {
        index_progress_timer_->stop();
        seafApplet->warningBox(tr("File save failed"), this);
        reject();
    }
}

void FileBrowserProgressDialog::onQueryFailed(const ApiError& error)
{
    qWarning("get index progress request error: %s", error.toString().toUtf8().data());
    // when occour http error stop index_progress_timer.
    if (error.type() == ApiError::HTTP_ERROR) {
        index_progress_timer_->stop();
        seafApplet->warningBox(tr("Index progress request error %1").arg(error.httpErrorCode()));
        reject();
    }
}

void FileBrowserProgressDialog::cancel()
{
    if (task_finished_ || task_->canceled()) {
        return;
    }
    if (task_->type() == FileNetworkTask::Upload) {
        task_->cancel();
    } else {
        // For download tasks we need to go through the transfer manager
        TransferManager::instance()->cancelDownload(task_->repoId(), task_->path());
    }
    reject();
}

void FileBrowserProgressDialog::onOneFileUploadFailed(const QString &filename,
                                                      bool single_file)
{
    if (task_->canceled()) {
        return;
    }

    FileUploadTask *upload_task = (FileUploadTask *)task_;

    QString msg =
        tr("Failed to upload file \"%1\", do you want to retry?").arg(filename);
    ActionOnFailure choice = retryOrSkipOrAbort(msg, single_file);

    switch (choice) {
        case ActionRetry:
            upload_task->continueWithFailedFile(true);
            break;
        case ActionSkip:
            upload_task->continueWithFailedFile(false);
            break;
        case ActionAbort:
            cancel();
            break;
    }
}

FileBrowserProgressDialog::ActionOnFailure
FileBrowserProgressDialog::retryOrSkipOrAbort(const QString& msg, bool single_file)
{
    QMessageBox box(this);
    box.setText(msg);
    box.setWindowTitle(getBrand());
    box.setIcon(QMessageBox::Question);

    QPushButton *yes_btn = box.addButton(tr("Retry"), QMessageBox::YesRole);
    QPushButton *no_btn = nullptr;
    if (!single_file) {
        // If this is single file upload/update, we only show "retry" and
        // "abort".
        no_btn = box.addButton(tr("Skip"), QMessageBox::NoRole);
    }
    box.addButton(tr("Abort"), QMessageBox::RejectRole);

    box.setDefaultButton(yes_btn);
    box.exec();
    QAbstractButton *btn = box.clickedButton();
    if (btn == yes_btn) {
        return ActionRetry;
    } else if (btn == no_btn) {
        return ActionSkip;
    }

    return ActionAbort;
}
<|endoftext|>


<commit_before>//===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//

#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/Demangle.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/CommandLine.h"

#include <unistd.h>

#include <algorithm>
#include <iostream>
#include <csignal>

using llvm::dyn_cast;
using llvm::StringRef;
using llvm::ArrayRef;
using namespace llvm::object;

using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;

enum class ActionType {
  None,
  DumpReflectionSections,
  DumpHeapInstance
};

namespace options {
static llvm::cl::opt<ActionType>
Action(llvm::cl::desc("Mode:"),
       llvm::cl::values(
         clEnumValN(ActionType::DumpReflectionSections,
                    "dump-reflection-sections",
                    "Dump the field reflection section"),
         clEnumValN(ActionType::DumpHeapInstance,
                    "dump-heap-instance",
                    "Dump the field layout for a heap instance by running "
                    "a Swift executable"),
         clEnumValEnd));

static llvm::cl::opt<std::string>
BinaryFilename("binary-filename", llvm::cl::desc("Filename of the binary file"),
               llvm::cl::Required);

static llvm::cl::opt<std::string>
Architecture("arch", llvm::cl::desc("Architecture to inspect in the binary"),
             llvm::cl::Required);
} // end namespace options

template<typename T>
static T unwrap(llvm::ErrorOr<T> value) {
  if (!value.getError())
    return std::move(value.get());
  std::cerr << "swift-reflection-test error: " << value.getError().message() << "\n";
  exit(EXIT_FAILURE);
}

static llvm::object::SectionRef
getSectionRef(const ObjectFile *objectFile,
              ArrayRef<StringRef> anySectionNames) {
  for (auto section : objectFile->sections()) {
    StringRef sectionName;
    section.getName(sectionName);
    for (auto desiredName : anySectionNames) {
      if (sectionName.equals(desiredName)) {
        return section;
      }
    }
  }
  return SectionRef();
}

static int doDumpReflectionSections(std::string binaryFilename,
                                    StringRef arch) {
  // Note: binaryOrError and objectOrError own the memory for our ObjectFile;
  // once they go out of scope, we can no longer do anything.
  OwningBinary<Binary> binaryOwner;
  std::unique_ptr<llvm::object::ObjectFile> objectOwner;

  auto Expected = std::move(llvm::object::createBinary(binaryFilename));
  if (!Expected) {
    std::cerr << "Could not create binary for " << binaryFilename;
    return EXIT_FAILURE;
  }

  binaryOwner = std::move(Expected.get());
  const llvm::object::Binary *binaryFile = binaryOwner.getBinary();

  // The object file we are doing lookups in -- either the binary itself, or
  // a particular slice of a universal binary.
  const ObjectFile *objectFile;

  if (auto o = dyn_cast<ObjectFile>(binaryFile)) {
    objectFile = o;
  } else {
    auto universal = cast<MachOUniversalBinary>(binaryFile);
    objectOwner = unwrap(universal->getObjectForArch(arch));
    objectFile = objectOwner.get();
  }

  // Field descriptor section
  auto fieldSectionRef = getSectionRef(objectFile, {
    "__swift3_fieldmd", ".swift3_fieldmd"
  });

  if (fieldSectionRef.getObject() == nullptr) {
    std::cerr << binaryFilename;
    std::cerr << " doesn't have a field reflection section!\n";
    return EXIT_FAILURE;
  }

  StringRef fieldSectionContents;
  fieldSectionRef.getContents(fieldSectionContents);

  const FieldSection fieldSection {
    reinterpret_cast<const void *>(fieldSectionContents.begin()),
    reinterpret_cast<const void *>(fieldSectionContents.end())
  };

  // Associated type section - optional
  AssociatedTypeSection associatedTypeSection {nullptr, nullptr};

  auto associatedTypeSectionRef = getSectionRef(objectFile, {
    "__swift3_assocty", ".swift3_assocty"
  });

  if (associatedTypeSectionRef.getObject() != nullptr) {
    StringRef associatedTypeSectionContents;
    associatedTypeSectionRef.getContents(associatedTypeSectionContents);
    associatedTypeSection = {
      reinterpret_cast<const void *>(associatedTypeSectionContents.begin()),
      reinterpret_cast<const void *>(associatedTypeSectionContents.end()),
    };
  }

  // Builtin types section
  BuiltinTypeSection builtinTypeSection {nullptr, nullptr};

  auto builtinTypeSectionRef = getSectionRef(objectFile, {
    "__swift3_builtin", ".swift3_builtin"
  });

  if (builtinTypeSectionRef.getObject() != nullptr) {
    StringRef builtinTypeSectionContents;
    builtinTypeSectionRef.getContents(builtinTypeSectionContents);

    builtinTypeSection = {
      reinterpret_cast<const void *>(builtinTypeSectionContents.begin()),
      reinterpret_cast<const void *>(builtinTypeSectionContents.end())
    };
  }

  // Typeref section
  auto typeRefSectionRef = getSectionRef(objectFile, {
    "__swift3_typeref", ".swift3_typeref"
  });

  if (typeRefSectionRef.getObject() == nullptr) {
    std::cerr << binaryFilename;
    std::cerr << " doesn't have an associated typeref section!\n";
    return EXIT_FAILURE;
  }

  StringRef typeRefSectionContents;
  typeRefSectionRef.getContents(typeRefSectionContents);

  const GenericSection typeRefSection {
    reinterpret_cast<const void *>(typeRefSectionContents.begin()),
    reinterpret_cast<const void *>(typeRefSectionContents.end())
  };

  // Reflection strings section
  auto reflectionStringsSectionRef = getSectionRef(objectFile, {
    "__swift3_reflstr", ".swift3_reflstr"
  });

  if (reflectionStringsSectionRef.getObject() == nullptr) {
    std::cerr << binaryFilename;
    std::cerr << " doesn't have an associated reflection strings section!\n";
    return EXIT_FAILURE;
  }

  StringRef reflectionStringsSectionContents;
  reflectionStringsSectionRef.getContents(reflectionStringsSectionContents);

  const GenericSection reflectionStringsSection {
    reinterpret_cast<const void *>(reflectionStringsSectionContents.begin()),
    reinterpret_cast<const void *>(reflectionStringsSectionContents.end())
  };

  // Construct the TypeRefBuilder
  TypeRefBuilder builder;
  builder.addReflectionInfo({
    binaryFilename,
    fieldSection,
    associatedTypeSection,
    builtinTypeSection,
    typeRefSection,
    reflectionStringsSection,
  });

  // Dump everything
  builder.dumpAllSections(std::cout);

  return EXIT_SUCCESS;
}

int main(int argc, char *argv[]) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
  return doDumpReflectionSections(options::BinaryFilename,
                                  options::Architecture);
}

<commit_msg>swift-reflection-dump: fix -Wpessimizing-move (#2240)<commit_after>//===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//

#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/Demangle.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/CommandLine.h"

#include <unistd.h>

#include <algorithm>
#include <iostream>
#include <csignal>

using llvm::dyn_cast;
using llvm::StringRef;
using llvm::ArrayRef;
using namespace llvm::object;

using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;

enum class ActionType {
  None,
  DumpReflectionSections,
  DumpHeapInstance
};

namespace options {
static llvm::cl::opt<ActionType>
Action(llvm::cl::desc("Mode:"),
       llvm::cl::values(
         clEnumValN(ActionType::DumpReflectionSections,
                    "dump-reflection-sections",
                    "Dump the field reflection section"),
         clEnumValN(ActionType::DumpHeapInstance,
                    "dump-heap-instance",
                    "Dump the field layout for a heap instance by running "
                    "a Swift executable"),
         clEnumValEnd));

static llvm::cl::opt<std::string>
BinaryFilename("binary-filename", llvm::cl::desc("Filename of the binary file"),
               llvm::cl::Required);

static llvm::cl::opt<std::string>
Architecture("arch", llvm::cl::desc("Architecture to inspect in the binary"),
             llvm::cl::Required);
} // end namespace options

template<typename T>
static T unwrap(llvm::ErrorOr<T> value) {
  if (!value.getError())
    return std::move(value.get());
  std::cerr << "swift-reflection-test error: " << value.getError().message() << "\n";
  exit(EXIT_FAILURE);
}

static llvm::object::SectionRef
getSectionRef(const ObjectFile *objectFile,
              ArrayRef<StringRef> anySectionNames) {
  for (auto section : objectFile->sections()) {
    StringRef sectionName;
    section.getName(sectionName);
    for (auto desiredName : anySectionNames) {
      if (sectionName.equals(desiredName)) {
        return section;
      }
    }
  }
  return SectionRef();
}

static int doDumpReflectionSections(std::string binaryFilename,
                                    StringRef arch) {
  // Note: binaryOrError and objectOrError own the memory for our ObjectFile;
  // once they go out of scope, we can no longer do anything.
  OwningBinary<Binary> binaryOwner;
  std::unique_ptr<llvm::object::ObjectFile> objectOwner;

  auto Expected = llvm::object::createBinary(binaryFilename);
  if (!Expected) {
    std::cerr << "Could not create binary for " << binaryFilename;
    return EXIT_FAILURE;
  }

  binaryOwner = std::move(Expected.get());
  const llvm::object::Binary *binaryFile = binaryOwner.getBinary();

  // The object file we are doing lookups in -- either the binary itself, or
  // a particular slice of a universal binary.
  const ObjectFile *objectFile;

  if (auto o = dyn_cast<ObjectFile>(binaryFile)) {
    objectFile = o;
  } else {
    auto universal = cast<MachOUniversalBinary>(binaryFile);
    objectOwner = unwrap(universal->getObjectForArch(arch));
    objectFile = objectOwner.get();
  }

  // Field descriptor section
  auto fieldSectionRef = getSectionRef(objectFile, {
    "__swift3_fieldmd", ".swift3_fieldmd"
  });

  if (fieldSectionRef.getObject() == nullptr) {
    std::cerr << binaryFilename;
    std::cerr << " doesn't have a field reflection section!\n";
    return EXIT_FAILURE;
  }

  StringRef fieldSectionContents;
  fieldSectionRef.getContents(fieldSectionContents);

  const FieldSection fieldSection {
    reinterpret_cast<const void *>(fieldSectionContents.begin()),
    reinterpret_cast<const void *>(fieldSectionContents.end())
  };

  // Associated type section - optional
  AssociatedTypeSection associatedTypeSection {nullptr, nullptr};

  auto associatedTypeSectionRef = getSectionRef(objectFile, {
    "__swift3_assocty", ".swift3_assocty"
  });

  if (associatedTypeSectionRef.getObject() != nullptr) {
    StringRef associatedTypeSectionContents;
    associatedTypeSectionRef.getContents(associatedTypeSectionContents);
    associatedTypeSection = {
      reinterpret_cast<const void *>(associatedTypeSectionContents.begin()),
      reinterpret_cast<const void *>(associatedTypeSectionContents.end()),
    };
  }

  // Builtin types section
  BuiltinTypeSection builtinTypeSection {nullptr, nullptr};

  auto builtinTypeSectionRef = getSectionRef(objectFile, {
    "__swift3_builtin", ".swift3_builtin"
  });

  if (builtinTypeSectionRef.getObject() != nullptr) {
    StringRef builtinTypeSectionContents;
    builtinTypeSectionRef.getContents(builtinTypeSectionContents);

    builtinTypeSection = {
      reinterpret_cast<const void *>(builtinTypeSectionContents.begin()),
      reinterpret_cast<const void *>(builtinTypeSectionContents.end())
    };
  }

  // Typeref section
  auto typeRefSectionRef = getSectionRef(objectFile, {
    "__swift3_typeref", ".swift3_typeref"
  });

  if (typeRefSectionRef.getObject() == nullptr) {
    std::cerr << binaryFilename;
    std::cerr << " doesn't have an associated typeref section!\n";
    return EXIT_FAILURE;
  }

  StringRef typeRefSectionContents;
  typeRefSectionRef.getContents(typeRefSectionContents);

  const GenericSection typeRefSection {
    reinterpret_cast<const void *>(typeRefSectionContents.begin()),
    reinterpret_cast<const void *>(typeRefSectionContents.end())
  };

  // Reflection strings section
  auto reflectionStringsSectionRef = getSectionRef(objectFile, {
    "__swift3_reflstr", ".swift3_reflstr"
  });

  if (reflectionStringsSectionRef.getObject() == nullptr) {
    std::cerr << binaryFilename;
    std::cerr << " doesn't have an associated reflection strings section!\n";
    return EXIT_FAILURE;
  }

  StringRef reflectionStringsSectionContents;
  reflectionStringsSectionRef.getContents(reflectionStringsSectionContents);

  const GenericSection reflectionStringsSection {
    reinterpret_cast<const void *>(reflectionStringsSectionContents.begin()),
    reinterpret_cast<const void *>(reflectionStringsSectionContents.end())
  };

  // Construct the TypeRefBuilder
  TypeRefBuilder builder;
  builder.addReflectionInfo({
    binaryFilename,
    fieldSection,
    associatedTypeSection,
    builtinTypeSection,
    typeRefSection,
    reflectionStringsSection,
  });

  // Dump everything
  builder.dumpAllSections(std::cout);

  return EXIT_SUCCESS;
}

int main(int argc, char *argv[]) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
  return doDumpReflectionSections(options::BinaryFilename,
                                  options::Architecture);
}

<|endoftext|>


<commit_before>/* Includes ------------------------------------------------------------------*/

/* Function prototypes -------------------------------------------------------*/

// Explicit Declaration of System Mode
SYSTEM_MODE(AUTOMATIC);

/* Preprocessor Defined ------------------------------------------------------*/
#define ALERT_INTERVAL   10000              // Alert every 10 seconds

/* Constants -----------------------------------------------------------------*/
const char webhookName[] = "sendSMS";
const char cellNumber[] = "+15555555555";   // Cell Phone Number (Ex: +15555555555)

/* Objects -------------------------------------------------------------------*/

/* Global Variables ----------------------------------------------------------*/
char message[200];
char coreID[30];
unsigned long lastAlert = 0;

/* Setup Function - Run One @ Startup ----------------------------------------*/
void setup()
{
    Serial.begin(9600);

    Spark.deviceID().toCharArray(coreID, Spark.deviceID().length());

    sprintf(message, "{\"n\":\"%s\", \"m\":\"%s is online\"}", cellNumber, coreID);
    Spark.publish(webhookName, message);
    lastAlert = millis();
}

/* Loop Function - Run Indefinitely ------------------------------------------*/
void loop()
{
    // Check if we need to start the next sample
    if((millis() - lastAlert) > ALERT_INTERVAL)
    {
        sprintf(message, "{\"n\":\"%s\", \"m\":\"%s says hello\"}", cellNumber, coreID);

        Serial.println("Sending out message");
        Serial.print("\tMessage: ");
        Serial.println(message);
        Serial.println();

        Spark.publish(webhookName, message);
        lastAlert = millis();
    }
}<commit_msg>Changed default sms interval to 60 seconds<commit_after>/* Includes ------------------------------------------------------------------*/

/* Function prototypes -------------------------------------------------------*/

// Explicit Declaration of System Mode
SYSTEM_MODE(AUTOMATIC);

/* Preprocessor Defined ------------------------------------------------------*/
#define ALERT_INTERVAL   60000              // Alert every 10 seconds

/* Constants -----------------------------------------------------------------*/
const char webhookName[] = "sendSMS";
const char cellNumber[] = "+15555555555";   // Cell Phone Number (Ex: +15555555555)

/* Objects -------------------------------------------------------------------*/

/* Global Variables ----------------------------------------------------------*/
char message[200];
char coreID[30];
unsigned long lastAlert = 0;

/* Setup Function - Run One @ Startup ----------------------------------------*/
void setup()
{
    Serial.begin(9600);

    Spark.deviceID().toCharArray(coreID, Spark.deviceID().length());

    sprintf(message, "{\"n\":\"%s\", \"m\":\"%s is online\"}", cellNumber, coreID);
    Spark.publish(webhookName, message);
    lastAlert = millis();
}

/* Loop Function - Run Indefinitely ------------------------------------------*/
void loop()
{
    // Check if we need to start the next sample
    if((millis() - lastAlert) > ALERT_INTERVAL)
    {
        sprintf(message, "{\"n\":\"%s\", \"m\":\"%s says hello\"}", cellNumber, coreID);

        Serial.println("Sending out message");
        Serial.print("\tMessage: ");
        Serial.println(message);
        Serial.println();

        Spark.publish(webhookName, message);
        lastAlert = millis();
    }
}<|endoftext|>


<commit_before>
////using the C++ API

#include "zorba/zorba_api.h"

//for debug
//#include "../src/compiler/parser/xquery_driver.h"
#include "../src/util/logging/loggermanager.hh"
#include "timer.h"
#include "error_display.h"
#include "zorba/util/properties.h"

#ifdef WIN32
	#include "../src/util/win32/compatib_defs.h"
#endif

#include <fstream>
#include <iostream>
#include <iomanip>

using namespace xqp;
using namespace std;

#ifdef UNICODE
#error apitest: UNICODE no longer supported
#endif

int apitest_alert_callback(ZorbaAlert *alert_mess,
                           XQuery*  current_xquery,
                           XQueryExecution* current_xqueryresult,
                           void *param)
{
#ifndef NDEBUG
  if((alert_mess->alert_type != ZorbaAlert::USER_ERROR_ALERT) &&
    (alert_mess->alert_type != ZorbaAlert::USER_TRACE_ALERT))
  {
    cerr << g_error_in_file << ": " << g_error_at_line << endl;
  }
#endif
  cerr << endl;

  DisplayOneAlert(alert_mess);

  cerr.flush();

  return -1;
}

void set_var (string name, string val,
              DynamicQueryContext_t dctx,
              XQueryExecution_t result)
{
  if (name [name.size () - 1] == ':' && dctx != NULL)
  {
    dctx->SetVariable(name.substr (0, name.size () - 1), xqp_string(val));
  }
  else if (name[name.size () - 1] != ':' && result != NULL)
  {
    ifstream is (val.c_str ());
    assert (is);
    result->SetVariable(name, val.c_str(), is);
  }
}

void slurp_file (const char *fname, string &result) {
  ifstream qfile(fname); assert (qfile);

  qfile.seekg (0, ios::end);
  size_t len = qfile.tellg ();
  qfile.seekg (0, ios::beg);
  char *str = new char [len];
  qfile.read (str, len);

  string sstr (str, len);
  result.swap (sstr);
  delete [] str;
}

class ZorbaEngineWrapper {
public:
  ZorbaEngine &factory;
  StaticQueryContext_t sctx;

  ZorbaEngineWrapper (alert_callback alert_cb = NULL, void *alert_param = NULL)
    : factory (ZorbaEngine::getInstance())
  {
    factory.initThread();
    /// register the alerts callback
    ZorbaAlertsManager& errmanager = factory.getAlertsManagerForCurrentThread();

    if (alert_cb != NULL)
      errmanager.RegisterAlertCallback(alert_cb, alert_param);

    sctx = factory.createStaticContext();
    sctx->AddCollation("http://www.flworfound.org/apitest/coll1", "en");
    sctx->AddCollation("http://www.flworfound.org/apitest/coll2", "de");
    sctx->AddCollation("http://www.flworfound.org/apitest/coll3", "fr");
    sctx->SetOrderingMode(StaticQueryContext::unordered);
  }
  ~ZorbaEngineWrapper () {
    DisplayErrorListForCurrentThread();

    factory.uninitThread();
    factory.shutdown();
  }

  XQueryExecution_t createExecution (XQuery_t query, const vector< pair <string, string> > &vars) {
    DynamicQueryContext_t dctx = factory.createDynamicContext ();
    for (vector<pair <string, string> >::const_iterator iter = vars.begin ();
         iter != vars.end (); iter++)
      set_var (iter->first, iter->second, dctx, NULL);

    XQueryExecution_t result = query->createExecution(dctx);

    if(! result.isNull()) {
      for (vector<pair <string, string> >::const_iterator iter = vars.begin ();
           iter != vars.end (); iter++)
        set_var (iter->first, iter->second, NULL, result);
    }

    return result;
  }
};

class TimePrinter {
  Timer timer;
public:
  TimePrinter () {}
  ~TimePrinter () {
    timer.end();
    timer.print(cout);
  }
};

// TODO: for now apitest users expect 0 even for error results; this should change
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
  if (! Properties::load(argc,argv))
    return 1;
  Properties* lProp = Properties::instance();

  // start timer as soon as possible, if enabled
  auto_ptr<TimePrinter> timer (lProp->printTime() ? new TimePrinter : NULL);

  g_abort_when_fatal_error = lProp->abortWhenFatalError();

  xqp::LoggerManager::logmanager()->setLoggerConfig("#1#logging.log");

  // output file
  auto_ptr<ostream> outputFile (lProp->useResultFile() ? new ofstream (lProp->getResultFile().c_str()) : NULL);
  ostream *resultFile = outputFile.get ();
  if (resultFile == NULL)
    resultFile = &cout;

  // query text
  const char* fname = lProp->getQuery().c_str();
  string query_text = "1+2";  // the default query if no file or query is specified
  if (lProp->inlineQuery())
    query_text = fname;
  else if (*fname != '\0')
    slurp_file (fname, query_text);
  if (lProp->printQuery())
    cout << query_text << endl;

  // start the zorba engine
  ZorbaEngineWrapper zengine (apitest_alert_callback, (void*) 101);

  // compile query
  XQuery_t query = zengine.factory.createQuery(query_text.c_str(), zengine.sctx);
  if (query.isNull ())
    return 0;

  // create dynamic context and execution
  vector<pair <string, string> > ext_vars = lProp->getExternalVars ();
  XQueryExecution_t result = zengine.createExecution (query, ext_vars);

  result->setAlertsParam(result.get_ptr());  // to be passed to alerts callback when error occurs

  if (lProp->useSerializer()) {
    result->serialize(*resultFile);
    // newline should not be sent when serializing!
  } else {
    Item_t it;
    while (NULL != (it = result->next ()).get_ptr ())
      *resultFile << it->show() << endl;
  }

  if (result->isError ())
    return 0;

  result->close ();

  return 0;
}
<commit_msg>close the query execution even in the case of errors<commit_after>
////using the C++ API

#include "zorba/zorba_api.h"

//for debug
//#include "../src/compiler/parser/xquery_driver.h"
#include "../src/util/logging/loggermanager.hh"
#include "timer.h"
#include "error_display.h"
#include "zorba/util/properties.h"

#ifdef WIN32
	#include "../src/util/win32/compatib_defs.h"
#endif

#include <fstream>
#include <iostream>
#include <iomanip>

using namespace xqp;
using namespace std;

#ifdef UNICODE
#error apitest: UNICODE no longer supported
#endif

int apitest_alert_callback(ZorbaAlert *alert_mess,
                           XQuery*  current_xquery,
                           XQueryExecution* current_xqueryresult,
                           void *param)
{
#ifndef NDEBUG
  if((alert_mess->alert_type != ZorbaAlert::USER_ERROR_ALERT) &&
    (alert_mess->alert_type != ZorbaAlert::USER_TRACE_ALERT))
  {
    cerr << g_error_in_file << ": " << g_error_at_line << endl;
  }
#endif
  cerr << endl;

  DisplayOneAlert(alert_mess);

  cerr.flush();

  return -1;
}

void set_var (string name, string val,
              DynamicQueryContext_t dctx,
              XQueryExecution_t result)
{
  if (name [name.size () - 1] == ':' && dctx != NULL)
  {
    dctx->SetVariable(name.substr (0, name.size () - 1), xqp_string(val));
  }
  else if (name[name.size () - 1] != ':' && result != NULL)
  {
    ifstream is (val.c_str ());
    assert (is);
    result->SetVariable(name, val.c_str(), is);
  }
}

void slurp_file (const char *fname, string &result) {
  ifstream qfile(fname); assert (qfile);

  qfile.seekg (0, ios::end);
  size_t len = qfile.tellg ();
  qfile.seekg (0, ios::beg);
  char *str = new char [len];
  qfile.read (str, len);

  string sstr (str, len);
  result.swap (sstr);
  delete [] str;
}

class ZorbaEngineWrapper {
public:
  ZorbaEngine &factory;
  StaticQueryContext_t sctx;

  ZorbaEngineWrapper (alert_callback alert_cb = NULL, void *alert_param = NULL)
    : factory (ZorbaEngine::getInstance())
  {
    factory.initThread();
    /// register the alerts callback
    ZorbaAlertsManager& errmanager = factory.getAlertsManagerForCurrentThread();

    if (alert_cb != NULL)
      errmanager.RegisterAlertCallback(alert_cb, alert_param);

    sctx = factory.createStaticContext();
    sctx->AddCollation("http://www.flworfound.org/apitest/coll1", "en");
    sctx->AddCollation("http://www.flworfound.org/apitest/coll2", "de");
    sctx->AddCollation("http://www.flworfound.org/apitest/coll3", "fr");
    sctx->SetOrderingMode(StaticQueryContext::unordered);
  }
  ~ZorbaEngineWrapper () {
    DisplayErrorListForCurrentThread();

    factory.uninitThread();
    factory.shutdown();
  }

  XQueryExecution_t createExecution (XQuery_t query, const vector< pair <string, string> > &vars) {
    DynamicQueryContext_t dctx = factory.createDynamicContext ();
    for (vector<pair <string, string> >::const_iterator iter = vars.begin ();
         iter != vars.end (); iter++)
      set_var (iter->first, iter->second, dctx, NULL);

    XQueryExecution_t result = query->createExecution(dctx);

    if(! result.isNull()) {
      for (vector<pair <string, string> >::const_iterator iter = vars.begin ();
           iter != vars.end (); iter++)
        set_var (iter->first, iter->second, NULL, result);
    }

    return result;
  }
};

class TimePrinter {
  Timer timer;
public:
  TimePrinter () {}
  ~TimePrinter () {
    timer.end();
    timer.print(cout);
  }
};

// TODO: for now apitest users expect 0 even for error results; this should change
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
  if (! Properties::load(argc,argv))
    return 1;
  Properties* lProp = Properties::instance();

  // start timer as soon as possible, if enabled
  auto_ptr<TimePrinter> timer (lProp->printTime() ? new TimePrinter : NULL);

  g_abort_when_fatal_error = lProp->abortWhenFatalError();

  xqp::LoggerManager::logmanager()->setLoggerConfig("#1#logging.log");

  // output file
  auto_ptr<ostream> outputFile (lProp->useResultFile() ?
                                new ofstream (lProp->getResultFile().c_str()) :
                                NULL);
  ostream *resultFile = outputFile.get ();
  if (resultFile == NULL)
    resultFile = &cout;

  // query text
  const char* fname = lProp->getQuery().c_str();
  string query_text = "1+2";  // the default query if no file or query is specified
  if (lProp->inlineQuery())
    query_text = fname;
  else if (*fname != '\0')
    slurp_file (fname, query_text);
  if (lProp->printQuery())
    cout << query_text << endl;

  // start the zorba engine
  ZorbaEngineWrapper zengine (apitest_alert_callback, (void*) 101);

  // compile query
  XQuery_t query = zengine.factory.createQuery(query_text.c_str(), zengine.sctx);
  if (query.isNull ())
    return 0;

  // create dynamic context and execution
  vector<pair <string, string> > ext_vars = lProp->getExternalVars ();
  XQueryExecution_t result = zengine.createExecution (query, ext_vars);

  result->setAlertsParam(result.get_ptr());  // to be passed to alerts callback when error occurs

  if (lProp->useSerializer()) {
    result->serialize(*resultFile);
    // newline should not be sent when serializing!
  } else {
    Item_t it;
    while (NULL != (it = result->next ()).get_ptr ())
      *resultFile << it->show() << endl;
  }

  result->close ();

  if (result->isError ())
    return 0;

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <zorba/zorba.h>

#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>

#include "store/api/item.h"
#include "store/api/item_handle.h"

// tests are allowed to use internals
#include "api/unmarshaller.h"
#include "system/properties.h"

#include <zorba/store_manager.h>
#include <zorba/iterator.h>
#include <zorba/util/fs_util.h>
#include <zorba/xquery_exception.h>

// Global variable g_abort_on_error is used to generate an abort() when an
// error is encountered, to aid debugging
#ifndef NDEBUG
#ifdef BUILDING_ZORBA_STATIC
extern bool g_abort_on_error;
#else
ZORBA_DLL_PUBLIC bool g_abort_on_error;
#endif
#endif

using namespace zorba;
using namespace std;

void set_var (string name, string val, DynamicContext* dctx)
{
  if (name [name.size () - 1] == ':')
  {
    name = name.substr (0, name.size () - 1);
    Item lItem = Zorba::getInstance(NULL)->getItemFactory()->createString(val);
    if(name != ".") {
      dctx->setVariable(name, lItem);
    } else
      dctx->setContextItem(lItem);
  }
  else if (name[name.size () - 1] != ':')
  {
    ifstream is(val.c_str());
    assert (is);
    try {
      XmlDataManager_t lXmlMgr = Zorba::getInstance(NULL)->createXmlDataManager();
      Item lDoc = lXmlMgr->parseXML(is);
      assert (lDoc.getNodeKind() == zorba::store::StoreConsts::documentNode);
      if(name != ".")
        dctx->setVariable(name, lDoc);
      else
        dctx->setContextItem(lDoc);
    } catch (zorba::ZorbaException& e) {
      std::cerr << "could not set external variable "  << e << std::endl;
      exit(1);
    }
  }
}

#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
  // read the command file properties
  if (! Properties::load(argc,argv))
    return 4;

  Properties* lProp = Properties::instance();
  if (! lProp->hasSingleQuery ()) {
    cout << "Error: either a single inline query or a single query file must be supplied" << endl;
    return 4;
  }
  Zorba_CompilerHints chints;
  switch (lProp->optimizer()) {
  case 0:
    chints.opt_level = ZORBA_OPT_LEVEL_O0;
    break;
  case 1:
    chints.opt_level = ZORBA_OPT_LEVEL_O1;
    break;
  case 2:
    chints.opt_level = ZORBA_OPT_LEVEL_O1;
    break;
  default:
    chints.opt_level = ZORBA_OPT_LEVEL_O1;
  }

  chints.for_serialization_only = false;

  if (Properties::instance()->serializeOnlyQuery() > 0)
  {
    chints.for_serialization_only = true;
  }

  // default is false
  if (lProp->libModule())
  {
    chints.lib_module = true;
  }

  // output file (either a file or the standard out if no file is specified)
  auto_ptr<ostream> outputFile (lProp->resultFile ().empty ()
                                ? NULL : new ofstream (lProp->resultFile().c_str()));
  ostream *resultFile = outputFile.get ();
  if (resultFile == NULL)
    resultFile = &cout;

  // input file (either from a file or given as parameter)
  auto_ptr<istream> qfile;
  std::string path;

  if (! lProp->inlineQuery())
  {
    path = lProp->queryFile ();
    fs::make_absolute( &path );
    qfile.reset (new ifstream (path.c_str ()));
    if (!qfile->good() || qfile->eof())
    {
      cerr << "no query given or not readable " << path << endl;
      return 3;
    }
  }
  else
  {
    qfile.reset (new istringstream(lProp->query ()));
  }

  // print the query if requested
  if (lProp->printQuery()) {
    lProp->debug_out ()<< "Query text:\n";
    copy (istreambuf_iterator<char> (*qfile), istreambuf_iterator<char> (), ostreambuf_iterator<char> (lProp->debug_out ()));
    lProp->debug_out () << "\n" << endl;
    qfile->seekg(0); // go back to the beginning
  }

  // Instantiate the simple store
  void* store = zorba::StoreManager::getStore();

  // Set the g_abort_on_exception flag in error_manager.cpp
#ifndef NDEBUG
  if (lProp->abort())
    g_abort_on_error = true;
#endif

  // start processing
  Zorba* zengine = Zorba::getInstance(store);

  zorba::StaticContext_t staticContext = zengine->createStaticContext();

  // start parsing the query
  XQuery_t query = zengine->createQuery ();

#ifdef ZORBA_WITH_DEBUGGER
  if (lProp->debug())
  {
    query->setDebugMode(lProp->debug());
    Zorba_CompilerHints lHints;
    lHints.opt_level = ZORBA_OPT_LEVEL_O0;
  }
#endif

  if (! lProp->inlineQuery())
  {
    query->setFileName(path);
  }

  if (lProp->jsoniqParser())
  {
    staticContext->setJSONiqVersion(zorba::jsoniq_version_1_0);
  }

  try
  {
    query->compile(*qfile, staticContext, chints);
  }
  catch (ZorbaException& e)
  {
    // no need to close because the object is not valid
    cerr << "Compilation error: " << e << endl;
    return 1;
  }

  if (lProp->testPlanSerialization())
  {
    try
    {
      std::string binary_path;
      if (lProp->inlineQuery())
        binary_path = path + ".plan";
      else
        binary_path = "./temp.plan";

      std::ofstream fbinary(binary_path.c_str(), std::ios_base::binary);
      if (!query->saveExecutionPlan(fbinary))
      {
        printf("save execution plan FAILED\n");
        return 0x0badc0de;
      }
      fbinary.close();
      printf("saved execution plan at: %s\n", binary_path.c_str());
    }
    catch(zorba::ZorbaException &err)
    {
      std::cout << err << std::endl;
      return -1;
    }

    // Now load back the plan
    try
    {
      std::string binary_path;
      if (lProp->inlineQuery())
        binary_path = path + ".plan";
      else
        binary_path = "./temp.plan";
      query = zengine->createQuery();
      std::ifstream ifbinary(binary_path.c_str(), std::ios_base::binary);
      if(!ifbinary.is_open())
      {
        std::cout << "cannot open plan " << binary_path << std::endl;
        return 15;
      }

      bool load_ret = query->loadExecutionPlan(ifbinary);

      if (!load_ret)
      {
        std::cout << "cannot load plan " << binary_path << std::endl;
        return 16;
      }

      printf("load execution plan: %s\n", binary_path.c_str());
    }
    catch(zorba::ZorbaException &err)
    {
      std::cout << err << std::endl;
      return -1;
    }
  }

  // set external variables
  vector<pair <string, string> > ext_vars = lProp->getExternalVars();
  DynamicContext* dctx = query->getDynamicContext ();
  dctx->setImplicitTimezone (lProp->tz ());
  for (vector<pair <string, string> >::const_iterator iter = ext_vars.begin ();
       iter != ext_vars.end (); iter++)
  {
    set_var (iter->first, iter->second, dctx);
  }

  //if you want to print the plan into a file
  if( ! lProp->dotPlanFile().empty () )
  {
    auto_ptr<ostream> planFile (new ofstream (lProp->dotPlanFile().c_str()));
    ostream *printPlanFile = planFile.get ();

    query->printPlan(*printPlanFile, true);
  }

  int return_code = 0;
  if (! lProp->compileOnly() && ! lProp->libModule())
  {
    // output the result (either using xml serialization or using show)

    try
    {
      if (lProp->useSerializer())
      {
        Zorba_SerializerOptions opts = Zorba_SerializerOptions::SerializerOptionsFromStringParams(lProp->getSerializerParameters());
        query->execute(*resultFile, &opts);
      }
      else if (lProp->iterPlanTest())
      {
        Iterator_t result = query->iterator();
        result->open();
        Item lItem;
        while (result->next(lItem))
        {
          ;
        }
        result->close();
      }
      else
      {
        Iterator_t result = query->iterator();
        result->open();
        Item lItem;
        while (result->next(lItem))
        {
          // unmarshall the store item from the api item
          store::Item_t lStoreItem = Unmarshaller::getInternalItem(lItem);
          *resultFile << lStoreItem->show() << endl;
        }
        result->close();
      }
    }
    catch (ZorbaException &e)
    {
      cerr << "Execution error: " << e << endl;
      return_code = 2;
    }
  }

  staticContext->removeReference();  // force destruction
  staticContext = NULL;
  query->close();
  zengine->shutdown();
  zorba::StoreManager::shutdownStore(store);
  return return_code;
}
<commit_msg>store::Item is not a DLL public class anymore<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <zorba/zorba.h>

#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>

// tests are allowed to use internals
#include "api/unmarshaller.h"
#include "system/properties.h"

#include <zorba/store_manager.h>
#include <zorba/iterator.h>
#include <zorba/util/fs_util.h>
#include <zorba/xquery_exception.h>

// Global variable g_abort_on_error is used to generate an abort() when an
// error is encountered, to aid debugging
#ifndef NDEBUG
#ifdef BUILDING_ZORBA_STATIC
extern bool g_abort_on_error;
#else
ZORBA_DLL_PUBLIC bool g_abort_on_error;
#endif
#endif

using namespace zorba;
using namespace std;

void set_var (string name, string val, DynamicContext* dctx)
{
  if (name [name.size () - 1] == ':')
  {
    name = name.substr (0, name.size () - 1);
    Item lItem = Zorba::getInstance(NULL)->getItemFactory()->createString(val);
    if(name != ".") {
      dctx->setVariable(name, lItem);
    } else
      dctx->setContextItem(lItem);
  }
  else if (name[name.size () - 1] != ':')
  {
    ifstream is(val.c_str());
    assert (is);
    try {
      XmlDataManager_t lXmlMgr = Zorba::getInstance(NULL)->createXmlDataManager();
      Item lDoc = lXmlMgr->parseXML(is);
      assert (lDoc.getNodeKind() == zorba::store::StoreConsts::documentNode);
      if(name != ".")
        dctx->setVariable(name, lDoc);
      else
        dctx->setContextItem(lDoc);
    } catch (zorba::ZorbaException& e) {
      std::cerr << "could not set external variable "  << e << std::endl;
      exit(1);
    }
  }
}

#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
  // read the command file properties
  if (! Properties::load(argc,argv))
    return 4;

  Properties* lProp = Properties::instance();
  if (! lProp->hasSingleQuery ()) {
    cout << "Error: either a single inline query or a single query file must be supplied" << endl;
    return 4;
  }
  Zorba_CompilerHints chints;
  switch (lProp->optimizer()) {
  case 0:
    chints.opt_level = ZORBA_OPT_LEVEL_O0;
    break;
  case 1:
    chints.opt_level = ZORBA_OPT_LEVEL_O1;
    break;
  case 2:
    chints.opt_level = ZORBA_OPT_LEVEL_O1;
    break;
  default:
    chints.opt_level = ZORBA_OPT_LEVEL_O1;
  }

  chints.for_serialization_only = false;

  if (Properties::instance()->serializeOnlyQuery() > 0)
  {
    chints.for_serialization_only = true;
  }

  // default is false
  if (lProp->libModule())
  {
    chints.lib_module = true;
  }

  // output file (either a file or the standard out if no file is specified)
  auto_ptr<ostream> outputFile (lProp->resultFile ().empty ()
                                ? NULL : new ofstream (lProp->resultFile().c_str()));
  ostream *resultFile = outputFile.get ();
  if (resultFile == NULL)
    resultFile = &cout;

  // input file (either from a file or given as parameter)
  auto_ptr<istream> qfile;
  std::string path;

  if (! lProp->inlineQuery())
  {
    path = lProp->queryFile ();
    fs::make_absolute( &path );
    qfile.reset (new ifstream (path.c_str ()));
    if (!qfile->good() || qfile->eof())
    {
      cerr << "no query given or not readable " << path << endl;
      return 3;
    }
  }
  else
  {
    qfile.reset (new istringstream(lProp->query ()));
  }

  // print the query if requested
  if (lProp->printQuery()) {
    lProp->debug_out ()<< "Query text:\n";
    copy (istreambuf_iterator<char> (*qfile), istreambuf_iterator<char> (), ostreambuf_iterator<char> (lProp->debug_out ()));
    lProp->debug_out () << "\n" << endl;
    qfile->seekg(0); // go back to the beginning
  }

  // Instantiate the simple store
  void* store = zorba::StoreManager::getStore();

  // Set the g_abort_on_exception flag in error_manager.cpp
#ifndef NDEBUG
  if (lProp->abort())
    g_abort_on_error = true;
#endif

  // start processing
  Zorba* zengine = Zorba::getInstance(store);

  zorba::StaticContext_t staticContext = zengine->createStaticContext();

  // start parsing the query
  XQuery_t query = zengine->createQuery ();

#ifdef ZORBA_WITH_DEBUGGER
  if (lProp->debug())
  {
    query->setDebugMode(lProp->debug());
    Zorba_CompilerHints lHints;
    lHints.opt_level = ZORBA_OPT_LEVEL_O0;
  }
#endif

  if (! lProp->inlineQuery())
  {
    query->setFileName(path);
  }

  if (lProp->jsoniqParser())
  {
    staticContext->setJSONiqVersion(zorba::jsoniq_version_1_0);
  }

  try
  {
    query->compile(*qfile, staticContext, chints);
  }
  catch (ZorbaException& e)
  {
    // no need to close because the object is not valid
    cerr << "Compilation error: " << e << endl;
    return 1;
  }

  if (lProp->testPlanSerialization())
  {
    try
    {
      std::string binary_path;
      if (lProp->inlineQuery())
        binary_path = path + ".plan";
      else
        binary_path = "./temp.plan";

      std::ofstream fbinary(binary_path.c_str(), std::ios_base::binary);
      if (!query->saveExecutionPlan(fbinary))
      {
        printf("save execution plan FAILED\n");
        return 0x0badc0de;
      }
      fbinary.close();
      printf("saved execution plan at: %s\n", binary_path.c_str());
    }
    catch(zorba::ZorbaException &err)
    {
      std::cout << err << std::endl;
      return -1;
    }

    // Now load back the plan
    try
    {
      std::string binary_path;
      if (lProp->inlineQuery())
        binary_path = path + ".plan";
      else
        binary_path = "./temp.plan";
      query = zengine->createQuery();
      std::ifstream ifbinary(binary_path.c_str(), std::ios_base::binary);
      if(!ifbinary.is_open())
      {
        std::cout << "cannot open plan " << binary_path << std::endl;
        return 15;
      }

      bool load_ret = query->loadExecutionPlan(ifbinary);

      if (!load_ret)
      {
        std::cout << "cannot load plan " << binary_path << std::endl;
        return 16;
      }

      printf("load execution plan: %s\n", binary_path.c_str());
    }
    catch(zorba::ZorbaException &err)
    {
      std::cout << err << std::endl;
      return -1;
    }
  }

  // set external variables
  vector<pair <string, string> > ext_vars = lProp->getExternalVars();
  DynamicContext* dctx = query->getDynamicContext ();
  dctx->setImplicitTimezone (lProp->tz ());
  for (vector<pair <string, string> >::const_iterator iter = ext_vars.begin ();
       iter != ext_vars.end (); iter++)
  {
    set_var (iter->first, iter->second, dctx);
  }

  //if you want to print the plan into a file
  if( ! lProp->dotPlanFile().empty () )
  {
    auto_ptr<ostream> planFile (new ofstream (lProp->dotPlanFile().c_str()));
    ostream *printPlanFile = planFile.get ();

    query->printPlan(*printPlanFile, true);
  }

  int return_code = 0;
  if (! lProp->compileOnly() && ! lProp->libModule())
  {
    // output the result (either using xml serialization or using show)

    try
    {
      if (lProp->useSerializer())
      {
        Zorba_SerializerOptions opts = Zorba_SerializerOptions::SerializerOptionsFromStringParams(lProp->getSerializerParameters());
        query->execute(*resultFile, &opts);
      }
      else if (lProp->iterPlanTest())
      {
        Iterator_t result = query->iterator();
        result->open();
        Item lItem;
        while (result->next(lItem))
        {
          ;
        }
        result->close();
      }
      else
      {
        Iterator_t result = query->iterator();
        result->open();
        Item lItem;
        while (result->next(lItem))
        {
          ;
        }
        result->close();
      }
    }
    catch (ZorbaException &e)
    {
      cerr << "Execution error: " << e << endl;
      return_code = 2;
    }
  }

  staticContext->removeReference();  // force destruction
  staticContext = NULL;
  query->close();
  zengine->shutdown();
  zorba::StoreManager::shutdownStore(store);
  return return_code;
}
<|endoftext|>


<commit_before>#include "xmlLoader.h"
#include "../../../utils/xmlUtils.h"

#include <QtCore/QDebug>

XmlLoader::XmlLoader(Scene *scene)
{
	mScene = scene;
}

void XmlLoader::readString(const QString &text)
{
	mDocument.setContent(text);
	QDomNodeList const graphics = mDocument.elementsByTagName("graphics");

	for (unsigned i = 0; i < graphics.length(); ++i) {
		QDomElement graphic = graphics.at(i).toElement();
		readGraphics(graphic);
	}
}

void XmlLoader::readFile(const QString &fileName)
{
	mDocument = utils::xmlUtils::loadDocument(fileName);
	QDomNodeList const graphics = mDocument.elementsByTagName("graphics");

	for (unsigned i = 0; i < graphics.length(); ++i) {
		QDomElement graphic = graphics.at(i).toElement();
		readGraphics(graphic);
	}
}

void XmlLoader::readGraphics(QDomElement const &graphic)
{
	QDomNodeList graphicAttributes = graphic.childNodes();

	for (unsigned i = 0; i < graphicAttributes.length(); ++i) {
		QDomElement type = graphicAttributes.at(i).toElement();
		if (type.tagName() == "picture")
			readPicture(type);
		else if (type.tagName() == "labels")
			readLabels(type);
		else if (type.tagName() == "ports")
			readPorts(type);
		else
			qDebug() << "ololo_graphics";
	}
}

void XmlLoader::readPicture(QDomElement const &picture)
{
	QDomNodeList pictureAttributes = picture.childNodes();

	qreal sizePictureX = (picture.attribute("sizex", "")).toInt();
	qreal sizePictureY = (picture.attribute("sizey", "")).toInt();
	mDrift = QPointF(mScene->centerEmpty().x() - sizePictureX / 2, mScene->centerEmpty().y() - sizePictureY / 2);

	for (unsigned i = 0; i < pictureAttributes.length(); ++i) {
		QDomElement type = pictureAttributes.at(i).toElement();
		if (type.tagName() == "line")
			readLine(type);
		else if (type.tagName() == "ellipse")
			readEllipse(type);
		else if (type.tagName() == "arc")
			readArch(type);
		else if (type.tagName() == "rectangle")
			readRectangle(type);
		else if (type.tagName() == "stylus")
			readStylus(type);
		else
			qDebug() << "ololo_picture";
	}
}

void XmlLoader::readLabels(QDomElement const &label)
{
	QDomNodeList labelAttributes = label.childNodes();

	for (unsigned i = 0; i < labelAttributes.length(); ++i) {
		QDomElement type = labelAttributes.at(i).toElement();
		if (type.tagName() == "label")
			readLabel(type);
		else
			qDebug() << "ololo_labelS";
	}
}

void XmlLoader::readPorts(QDomElement const &port)
{
	QDomNodeList portAttributes = port.childNodes();

	for (unsigned i = 0; i < portAttributes.length(); ++i) {
		QDomElement type = portAttributes.at(i).toElement();
		if (type.tagName() == "linePort")
			readLinePort(type);
		else if (type.tagName() == "pointPort")
			readPointPort(type);
		else
			qDebug() << "ololo_ports";
	}
}

QRectF XmlLoader::readRectOfXandY(QDomElement const &docItem)
{
	qreal x1 = (docItem.attribute("x1", "0")).toDouble() + mDrift.x();
	qreal x2 = (docItem.attribute("x2", "0")).toDouble() + mDrift.x();
	qreal y1 = (docItem.attribute("y1", "0")).toDouble() + mDrift.y();
	qreal y2 = (docItem.attribute("y2", "0")).toDouble() + mDrift.y();
	return QRectF(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
}

QPointF XmlLoader::readXandY(QDomElement const &docItem)
{
	qreal x = (docItem.attribute("x", "0")).toDouble() + mDrift.x();
	qreal y= (docItem.attribute("y", "0")).toDouble() + mDrift.y();
	return QPointF(x, y);
}

void XmlLoader::readLine(QDomElement const &line)
{
	QRectF rect = readRectOfXandY(line);
	Line* item = new Line(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	item->readPenBrush(line);
	mScene->addItem(item);
}

void XmlLoader::readEllipse(QDomElement const &ellipse)
{
	QRectF rect = readRectOfXandY(ellipse);
	Ellipse* item = new Ellipse(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	item->readPenBrush(ellipse);
	mScene->addItem(item);
}

void XmlLoader::readArch(QDomElement const &arch)
{
	QRectF rect = readRectOfXandY(arch);
	Arch* item = new Arch(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	int spanAngle = arch.attribute("spanAngle", "0").toInt();
	int startAngle = arch.attribute("startAngle", "0").toInt();
	item->setSpanAngle(spanAngle);
	item->setStartAngle(startAngle);
	mScene->addItem(item);
}

void XmlLoader::readRectangle(QDomElement const &rectangle)
{
	QRectF rect = readRectOfXandY(rectangle);
	Rectangle* item = new Rectangle(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	item->readPenBrush(rectangle);
	mScene->addItem(item);
}

void XmlLoader::readStylus(QDomElement const &stylus)
{
	QDomNodeList stylusAttributes = stylus.childNodes();

	Stylus* stylusItem = new Stylus(0, 0, NULL);
	for (unsigned i = 0; i < stylusAttributes.length(); ++i) {
		QDomElement type = stylusAttributes.at(i).toElement();
		if (type.tagName() == "line") {
			QRectF rect = readRectOfXandY(type);
			Line* item = new Line(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
			item->readPenBrush(type);
			stylusItem->mListLine.push_back(item);
		}
		else
			qDebug() << "ololo_stylus";
	}
	mScene->addItem(stylusItem);
}

void XmlLoader::readLabel(QDomElement const &label)
{
	QPointF point = readXandY(label);
	Text* item;
	if (label.hasAttribute("text")) {
		item = new Text(point.x(), point.y(), label.attribute("text", ""));
		item->setIsDynamicText(false);
	} else if (label.hasAttribute("textBinded")) {
		item = new Text(point.x(), point.y(), label.attribute("textBinded", ""));
		item->setIsDynamicText(true);
	}
	else
		qDebug() << "ololo_label";
	mScene->addItem(item);
}

void XmlLoader::readLinePort(QDomElement const &linePort)
{
	QDomNodeList linePortAttributes = linePort.childNodes();
	qreal x1 = 0;
	qreal y1 = 0;
	qreal x2 = 0;
	qreal y2 = 0;
	for (unsigned i = 0; i < linePortAttributes.length(); ++i) {
		QDomElement type = linePortAttributes.at(i).toElement();
		if (type.tagName() == "start") {
			x1 = (type.attribute("startx", "0")).toDouble() + mDrift.x();
			y1 = (type.attribute("starty", "0")).toDouble() + mDrift.y();
		}
		else if (type.tagName() == "end") {
			x2 = (type.attribute("endx", "0")).toDouble() + mDrift.x();
			y2 = (type.attribute("endy", "0")).toDouble() + mDrift.y();
		} else
			qDebug() << "ololo_linePort";

	}
	LinePort* item = new LinePort(x1, y1, x2, y2, NULL);
	mScene->addItem(item);
}

void XmlLoader::readPointPort(QDomElement const &pointPort)
{
	QPointF point = readXandY(pointPort);
	PointPort* item = new PointPort(point.x(), point.y(), NULL);
	mScene->addItem(item);
}
<commit_msg>removed compiler warning<commit_after>#include "xmlLoader.h"
#include "../../../utils/xmlUtils.h"

#include <QtCore/QDebug>

XmlLoader::XmlLoader(Scene *scene)
{
	mScene = scene;
}

void XmlLoader::readString(const QString &text)
{
	mDocument.setContent(text);
	QDomNodeList const graphics = mDocument.elementsByTagName("graphics");

	for (unsigned i = 0; i < graphics.length(); ++i) {
		QDomElement graphic = graphics.at(i).toElement();
		readGraphics(graphic);
	}
}

void XmlLoader::readFile(const QString &fileName)
{
	mDocument = utils::xmlUtils::loadDocument(fileName);
	QDomNodeList const graphics = mDocument.elementsByTagName("graphics");

	for (unsigned i = 0; i < graphics.length(); ++i) {
		QDomElement graphic = graphics.at(i).toElement();
		readGraphics(graphic);
	}
}

void XmlLoader::readGraphics(QDomElement const &graphic)
{
	QDomNodeList graphicAttributes = graphic.childNodes();

	for (unsigned i = 0; i < graphicAttributes.length(); ++i) {
		QDomElement type = graphicAttributes.at(i).toElement();
		if (type.tagName() == "picture")
			readPicture(type);
		else if (type.tagName() == "labels")
			readLabels(type);
		else if (type.tagName() == "ports")
			readPorts(type);
		else
			qDebug() << "ololo_graphics";
	}
}

void XmlLoader::readPicture(QDomElement const &picture)
{
	QDomNodeList pictureAttributes = picture.childNodes();

	qreal sizePictureX = (picture.attribute("sizex", "")).toInt();
	qreal sizePictureY = (picture.attribute("sizey", "")).toInt();
	mDrift = QPointF(mScene->centerEmpty().x() - sizePictureX / 2, mScene->centerEmpty().y() - sizePictureY / 2);

	for (unsigned i = 0; i < pictureAttributes.length(); ++i) {
		QDomElement type = pictureAttributes.at(i).toElement();
		if (type.tagName() == "line")
			readLine(type);
		else if (type.tagName() == "ellipse")
			readEllipse(type);
		else if (type.tagName() == "arc")
			readArch(type);
		else if (type.tagName() == "rectangle")
			readRectangle(type);
		else if (type.tagName() == "stylus")
			readStylus(type);
		else
			qDebug() << "ololo_picture";
	}
}

void XmlLoader::readLabels(QDomElement const &label)
{
	QDomNodeList labelAttributes = label.childNodes();

	for (unsigned i = 0; i < labelAttributes.length(); ++i) {
		QDomElement type = labelAttributes.at(i).toElement();
		if (type.tagName() == "label")
			readLabel(type);
		else
			qDebug() << "ololo_labelS";
	}
}

void XmlLoader::readPorts(QDomElement const &port)
{
	QDomNodeList portAttributes = port.childNodes();

	for (unsigned i = 0; i < portAttributes.length(); ++i) {
		QDomElement type = portAttributes.at(i).toElement();
		if (type.tagName() == "linePort")
			readLinePort(type);
		else if (type.tagName() == "pointPort")
			readPointPort(type);
		else
			qDebug() << "ololo_ports";
	}
}

QRectF XmlLoader::readRectOfXandY(QDomElement const &docItem)
{
	qreal x1 = (docItem.attribute("x1", "0")).toDouble() + mDrift.x();
	qreal x2 = (docItem.attribute("x2", "0")).toDouble() + mDrift.x();
	qreal y1 = (docItem.attribute("y1", "0")).toDouble() + mDrift.y();
	qreal y2 = (docItem.attribute("y2", "0")).toDouble() + mDrift.y();
	return QRectF(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
}

QPointF XmlLoader::readXandY(QDomElement const &docItem)
{
	qreal x = (docItem.attribute("x", "0")).toDouble() + mDrift.x();
	qreal y= (docItem.attribute("y", "0")).toDouble() + mDrift.y();
	return QPointF(x, y);
}

void XmlLoader::readLine(QDomElement const &line)
{
	QRectF rect = readRectOfXandY(line);
	Line* item = new Line(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	item->readPenBrush(line);
	mScene->addItem(item);
}

void XmlLoader::readEllipse(QDomElement const &ellipse)
{
	QRectF rect = readRectOfXandY(ellipse);
	Ellipse* item = new Ellipse(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	item->readPenBrush(ellipse);
	mScene->addItem(item);
}

void XmlLoader::readArch(QDomElement const &arch)
{
	QRectF rect = readRectOfXandY(arch);
	Arch* item = new Arch(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	int spanAngle = arch.attribute("spanAngle", "0").toInt();
	int startAngle = arch.attribute("startAngle", "0").toInt();
	item->setSpanAngle(spanAngle);
	item->setStartAngle(startAngle);
	mScene->addItem(item);
}

void XmlLoader::readRectangle(QDomElement const &rectangle)
{
	QRectF rect = readRectOfXandY(rectangle);
	Rectangle* item = new Rectangle(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
	item->readPenBrush(rectangle);
	mScene->addItem(item);
}

void XmlLoader::readStylus(QDomElement const &stylus)
{
	QDomNodeList stylusAttributes = stylus.childNodes();

	Stylus* stylusItem = new Stylus(0, 0, NULL);
	for (unsigned i = 0; i < stylusAttributes.length(); ++i) {
		QDomElement type = stylusAttributes.at(i).toElement();
		if (type.tagName() == "line") {
			QRectF rect = readRectOfXandY(type);
			Line* item = new Line(rect.left(), rect.top(), rect.right(), rect.bottom(), NULL);
			item->readPenBrush(type);
			stylusItem->mListLine.push_back(item);
		}
		else
			qDebug() << "ololo_stylus";
	}
	mScene->addItem(stylusItem);
}

void XmlLoader::readLabel(QDomElement const &label)
{
	QPointF point = readXandY(label);
	Text* item = NULL;
	if (label.hasAttribute("text")) {
		item = new Text(point.x(), point.y(), label.attribute("text", ""));
		item->setIsDynamicText(false);
	} else if (label.hasAttribute("textBinded")) {
		item = new Text(point.x(), point.y(), label.attribute("textBinded", ""));
		item->setIsDynamicText(true);
	}
	else
		qDebug() << "ololo_label";
	mScene->addItem(item);
}

void XmlLoader::readLinePort(QDomElement const &linePort)
{
	QDomNodeList linePortAttributes = linePort.childNodes();
	qreal x1 = 0;
	qreal y1 = 0;
	qreal x2 = 0;
	qreal y2 = 0;
	for (unsigned i = 0; i < linePortAttributes.length(); ++i) {
		QDomElement type = linePortAttributes.at(i).toElement();
		if (type.tagName() == "start") {
			x1 = (type.attribute("startx", "0")).toDouble() + mDrift.x();
			y1 = (type.attribute("starty", "0")).toDouble() + mDrift.y();
		}
		else if (type.tagName() == "end") {
			x2 = (type.attribute("endx", "0")).toDouble() + mDrift.x();
			y2 = (type.attribute("endy", "0")).toDouble() + mDrift.y();
		} else
			qDebug() << "ololo_linePort";

	}
	LinePort* item = new LinePort(x1, y1, x2, y2, NULL);
	mScene->addItem(item);
}

void XmlLoader::readPointPort(QDomElement const &pointPort)
{
	QPointF point = readXandY(pointPort);
	PointPort* item = new PointPort(point.x(), point.y(), NULL);
	mScene->addItem(item);
}
<|endoftext|>


<commit_before>#include <osgViewer/Viewer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osg/Node>

#include <osgGA/SphericalManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/GUIEventHandler>
#include <osgGA/GUIEventAdapter>
#include <osgGA/GUIActionAdapter>
#include <osgViewer/ViewerEventHandlers>

#include <osgUtil/LineSegmentIntersector>
#include <osgUtil/Optimizer>

#include <iostream>

class PickingHandler : public osgGA::GUIEventHandler {
public:

    PickingHandler() {
        m_xMouseCoordAtLastPress = -1;
        m_yMouseCoordAtLastPress = -1;
    }

    // EventHandler interface
    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*) {
        if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) {

            if (m_xMouseCoordAtLastPress != ea.getX() || m_yMouseCoordAtLastPress != ea.getY()) {
                return false;
            }

            return printDescriptionOfIntersectedDrawable(ea, aa);

        } else if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) {
            m_xMouseCoordAtLastPress = ea.getX();
            m_yMouseCoordAtLastPress = ea.getY();
        }

        return false;
    }

private:

    bool printDescriptionOfIntersectedDrawable(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) {

        osgUtil::LineSegmentIntersector::Intersections intersections;
#if OSG_VERSION_GREATER_OR_EQUAL( 3, 3, 2)

            if (!aa.computeIntersections(ea, intersections)) {
                return false;
            }
#else
           return false;
#endif

        osgUtil::LineSegmentIntersector::Intersection firstIntersection = *intersections.begin();

        if (firstIntersection.drawable == nullptr) {
            return false;
        }

#if OSG_VERSION_GREATER_OR_EQUAL( 3, 3, 2)

        if (firstIntersection.drawable->getNumDescriptions() == 0) {
            std::cout << "Intersected drawable has no description:" << std::endl;
            return true;
        }

        std::cout << "Description of intersected drawable:" << std::endl;
        for (const std::string& desc : firstIntersection.drawable->getDescriptions()) {
            std::cout << "  " << desc << std::endl;
        }
#else
        std::cout << firstIntersection.drawable->getName()<< std::endl;
#endif
        std::cout << std::endl;

        return true;
    }

    int m_xMouseCoordAtLastPress;
    int m_yMouseCoordAtLastPress;
};

int main(int argc, char *argv[])
{
    osg::setNotifyLevel(osg::WARN);

    std::cout << "Using plugin directory: " << PLUGIN_BIN_DIR << std::endl;
    osgDB::Registry::instance()->getLibraryFilePathList().push_front(PLUGIN_BIN_DIR);

    osgDB::Registry::instance()->addFileExtensionAlias("gml", "citygml");

    if (argc < 2) {
        std::cerr << "No citygml file specified..." << std::endl;
        return 1;
    }

    osg::ref_ptr<osgDB::Options> options = new osgDB::Options("usemaxlodonly storegeomids");

    std::cout << "Loading file: " << argv[1] << std::endl;
    osg::ref_ptr<osg::Node> node = osgDB::readNodeFile(argv[1], options);

    if (node == nullptr) {
        std::cerr << "Failed to load file " << argv[1] << std::endl;
        return 1;
    }

    std::cout << "Optimizing node..." << std::endl;
    osgUtil::Optimizer optimizer;
    optimizer.optimize(node, osgUtil::Optimizer::ALL_OPTIMIZATIONS);

    std::cout << "Setup viewer..." << std::endl;

    osg::ref_ptr<osgGA::SphericalManipulator> manip = new osgGA::SphericalManipulator();
    manip->setAutoComputeHomePosition(true);
    manip->setNode(node);

    osgViewer::Viewer viewer;
    viewer.setUpViewInWindow(0, 0, 800, 600);
    viewer.setSceneData(node);
    viewer.setCameraManipulator(manip);
    viewer.addEventHandler(new osgGA::StateSetManipulator(node->getOrCreateStateSet()));
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new PickingHandler());
    viewer.addEventHandler(new osgViewer::HelpHandler());
    viewer.run();

    return 0;
}

<commit_msg>Update CitygmlOsgViewer.cpp<commit_after>#include <osgViewer/Viewer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osg/Node>

#include <osgGA/SphericalManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/GUIEventHandler>
#include <osgGA/GUIEventAdapter>
#include <osgGA/GUIActionAdapter>
#include <osgViewer/ViewerEventHandlers>

#include <osgUtil/LineSegmentIntersector>
#include <osgUtil/Optimizer>

#include <iostream>

class PickingHandler : public osgGA::GUIEventHandler {
public:

    PickingHandler() {
        m_xMouseCoordAtLastPress = -1;
        m_yMouseCoordAtLastPress = -1;
    }

    // EventHandler interface
    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*) {
        if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) {

            if (m_xMouseCoordAtLastPress != ea.getX() || m_yMouseCoordAtLastPress != ea.getY()) {
                return false;
            }

            return printDescriptionOfIntersectedDrawable(ea, aa);

        } else if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) {
            m_xMouseCoordAtLastPress = ea.getX();
            m_yMouseCoordAtLastPress = ea.getY();
        }

        return false;
    }

private:

    bool printDescriptionOfIntersectedDrawable(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) {

        osgUtil::LineSegmentIntersector::Intersections intersections;
#if OSG_VERSION_GREATER_OR_EQUAL(3,3,2)

            if (!aa.computeIntersections(ea, intersections)) {
                return false;
            }
#else
           return false;
#endif

        osgUtil::LineSegmentIntersector::Intersection firstIntersection = *intersections.begin();

        if (firstIntersection.drawable == nullptr) {
            return false;
        }

#if OSG_VERSION_GREATER_OR_EQUAL(3,3,2)

        if (firstIntersection.drawable->getNumDescriptions() == 0) {
            std::cout << "Intersected drawable has no description:" << std::endl;
            return true;
        }

        std::cout << "Description of intersected drawable:" << std::endl;
        for (const std::string& desc : firstIntersection.drawable->getDescriptions()) {
            std::cout << "  " << desc << std::endl;
        }
#else
        std::cout << firstIntersection.drawable->getName()<< std::endl;
#endif
        std::cout << std::endl;

        return true;
    }

    int m_xMouseCoordAtLastPress;
    int m_yMouseCoordAtLastPress;
};

int main(int argc, char *argv[])
{
    osg::setNotifyLevel(osg::WARN);

    std::cout << "Using plugin directory: " << PLUGIN_BIN_DIR << std::endl;
    osgDB::Registry::instance()->getLibraryFilePathList().push_front(PLUGIN_BIN_DIR);

    osgDB::Registry::instance()->addFileExtensionAlias("gml", "citygml");

    if (argc < 2) {
        std::cerr << "No citygml file specified..." << std::endl;
        return 1;
    }

    osg::ref_ptr<osgDB::Options> options = new osgDB::Options("usemaxlodonly storegeomids");

    std::cout << "Loading file: " << argv[1] << std::endl;
    osg::ref_ptr<osg::Node> node = osgDB::readNodeFile(argv[1], options);

    if (node == nullptr) {
        std::cerr << "Failed to load file " << argv[1] << std::endl;
        return 1;
    }

    std::cout << "Optimizing node..." << std::endl;
    osgUtil::Optimizer optimizer;
    optimizer.optimize(node, osgUtil::Optimizer::ALL_OPTIMIZATIONS);

    std::cout << "Setup viewer..." << std::endl;

    osg::ref_ptr<osgGA::SphericalManipulator> manip = new osgGA::SphericalManipulator();
    manip->setAutoComputeHomePosition(true);
    manip->setNode(node);

    osgViewer::Viewer viewer;
    viewer.setUpViewInWindow(0, 0, 800, 600);
    viewer.setSceneData(node);
    viewer.setCameraManipulator(manip);
    viewer.addEventHandler(new osgGA::StateSetManipulator(node->getOrCreateStateSet()));
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new PickingHandler());
    viewer.addEventHandler(new osgViewer::HelpHandler());
    viewer.run();

    return 0;
}

<|endoftext|>