<commit_before>/*

Copyright (c) 2013, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include <vector>
#include <string>
#include <stdio.h>
#include "application_manager/commands/mobile/system_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "config_profile/profile.h"
#include "utils/file_system.h"
#include "formatters/CFormatterJsonBase.hpp"
#include "json/json.h"

namespace application_manager {

namespace commands {

uint32_t SystemRequest::index = 0;

SystemRequest::SystemRequest(const MessageSharedPtr& message)
    : CommandRequestImpl(message) {
}

SystemRequest::~SystemRequest() {
}

void SystemRequest::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  ApplicationSharedPtr application =
      ApplicationManagerImpl::instance()->application(connection_key());

  if (!(application.valid())) {
    LOG4CXX_ERROR(logger_, "NULL pointer");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  const mobile_apis::RequestType::eType request_type =
      static_cast<mobile_apis::RequestType::eType>(
          (*message_)[strings::msg_params][strings::request_type].asInt());

  if (!(*message_)[strings::params].keyExists(strings::binary_data) &&
      (mobile_apis::RequestType::PROPRIETARY == request_type ||
       mobile_apis::RequestType::QUERY_APPS == request_type)) {

      LOG4CXX_ERROR(logger_, "Binary data empty");

      SendResponse(false, mobile_apis::Result::INVALID_DATA);
      return;
  }

  std::vector<uint8_t> binary_data;
  if ((*message_)[strings::params].keyExists(strings::binary_data)) {
    binary_data = (*message_)[strings::params][strings::binary_data].asBinary();
  }

  if (mobile_apis::RequestType::QUERY_APPS == request_type) {
    using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;

    const std::string json(binary_data.begin(), binary_data.end());
    Json::Value value;
    Json::Reader reader;
    if (!reader.parse(json.c_str(), value)) {
      LOG4CXX_ERROR(logger_, "Can't parse json received from QueryApps.");
      return;
    }

    smart_objects::SmartObject sm_object;
    CFormatterJsonBase::jsonValueToObj(value, sm_object);

    if (!ValidateQueryAppData(sm_object)) {
      SendResponse(false, mobile_apis::Result::INVALID_DATA);
      return;
    }

    ApplicationManagerImpl::instance()->ProcessQueryApp(sm_object,
                                                        connection_key());
    SendResponse(true, mobile_apis::Result::SUCCESS);
    return;
  }

  std::string file_path = profile::Profile::instance()->system_files_path();
  if (!file_system::CreateDirectoryRecursively(file_path)) {
    LOG4CXX_ERROR(logger_, "Cann't create folder.");
    SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
    return;
  }

  std::string file_name = "SYNC";
  if ((*message_)[strings::msg_params].keyExists(strings::file_name)) {
    file_name = (*message_)[strings::msg_params][strings::file_name].asString();
  }

  // to avoid override existing file
  const uint8_t max_size = 255;
  char buf[max_size] = {'\0'};
  snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%d%s", index++, file_name.c_str());
  file_name = buf;

  std::string full_file_path = file_path + "/" + file_name;
  if (binary_data.size()) {
    if (mobile_apis::Result::SUCCESS  !=
        (ApplicationManagerImpl::instance()->SaveBinary(
            binary_data, file_path, file_name, 0))) {
      SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
      return;
    }
  } else {
    if (!(file_system::CreateFile(full_file_path))) {
      SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
      return;
    }
  }

  smart_objects::SmartObject msg_params = smart_objects::SmartObject(
      smart_objects::SmartType_Map);
  if (std::string::npos != file_name.find("IVSU")) {
    msg_params[strings::file_name] = file_name.c_str();
  } else {
    msg_params[strings::file_name] = full_file_path;
  }

  if (mobile_apis::RequestType::PROPRIETARY != request_type) {
    msg_params[strings::app_id] = (application->mobile_app_id());
  }
  msg_params[strings::request_type] =
      (*message_)[strings::msg_params][strings::request_type];
  SendHMIRequest(hmi_apis::FunctionID::BasicCommunication_SystemRequest,
                 &msg_params, true);

}

void SystemRequest::on_event(const event_engine::Event& event) {
  LOG4CXX_INFO(logger_, "AddSubMenuRequest::on_event");
  const smart_objects::SmartObject& message = event.smart_object();

  switch (event.id()) {
    case hmi_apis::FunctionID::BasicCommunication_SystemRequest: {
      mobile_apis::Result::eType result_code =
          GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
              message[strings::params][hmi_response::code].asUInt()));
      bool result = mobile_apis::Result::SUCCESS == result_code;

      ApplicationSharedPtr application =
             ApplicationManagerImpl::instance()->application(connection_key());

      if (!(application.valid())) {
        LOG4CXX_ERROR(logger_, "NULL pointer");
        return;
      }

      SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
      break;
    }
    default: {
      LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
      return;
    }
  }
}

bool SystemRequest::ValidateQueryAppData(
    const smart_objects::SmartObject& data) const  {
  if (!data.isValid()) {
    LOG4CXX_ERROR(logger_, "QueryApps response is not valid.");
    return false;
  }
  if (!data.keyExists(json::response)) {
    LOG4CXX_ERROR(logger_,
                  "QueryApps response does not contain '"
                  << json::response << "' parameter.");
    return false;
  }
  smart_objects::SmartArray* obj_array = data[json::response].asArray();
  if (NULL == obj_array) {
    return false;
  }

  const std::size_t arr_size(obj_array->size());
  for (std::size_t idx = 0; idx < arr_size; ++idx) {
    const smart_objects::SmartObject& app_data = (*obj_array)[idx];
    if (!app_data.isValid()) {
      LOG4CXX_ERROR(logger_, "Wrong application data in json file.");
      continue;
    }
    std::string os_type;
    if (app_data.keyExists(json::ios)) {
      os_type = json::ios;
      if (!app_data[os_type].keyExists(json::urlScheme)) {
        LOG4CXX_ERROR(logger_, "Can't find URL scheme in json file.");
        continue;
      }
    } else if (app_data.keyExists(json::android)) {
      os_type = json::android;
      if (!app_data[os_type].keyExists(json::packageName)) {
        LOG4CXX_ERROR(logger_, "Can't find package name in json file.");
        continue;
      }
    }

    if (os_type.empty()) {
      LOG4CXX_ERROR(logger_, "Can't find mobile OS type in json file.");
      continue;
    }

    if (!app_data.keyExists(json::appId)) {
      LOG4CXX_ERROR(logger_, "Can't find app ID in json file.");
      continue;
    }

    if (!app_data.keyExists(json::name)) {
      LOG4CXX_ERROR(logger_, "Can't find app name in json file.");
      continue;
    }

    return true;
  }

  return true;
}

}  // namespace commands

}  // namespace application_manager
<commit_msg>APPLINK-11451 Fix validation of query_app json<commit_after>/*

Copyright (c) 2013, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include <vector>
#include <string>
#include <stdio.h>
#include "application_manager/commands/mobile/system_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "config_profile/profile.h"
#include "utils/file_system.h"
#include "formatters/CFormatterJsonBase.hpp"
#include "json/json.h"

namespace application_manager {

namespace commands {

uint32_t SystemRequest::index = 0;

SystemRequest::SystemRequest(const MessageSharedPtr& message)
    : CommandRequestImpl(message) {
}

SystemRequest::~SystemRequest() {
}

void SystemRequest::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  ApplicationSharedPtr application =
      ApplicationManagerImpl::instance()->application(connection_key());

  if (!(application.valid())) {
    LOG4CXX_ERROR(logger_, "NULL pointer");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  const mobile_apis::RequestType::eType request_type =
      static_cast<mobile_apis::RequestType::eType>(
          (*message_)[strings::msg_params][strings::request_type].asInt());

  if (!(*message_)[strings::params].keyExists(strings::binary_data) &&
      (mobile_apis::RequestType::PROPRIETARY == request_type ||
       mobile_apis::RequestType::QUERY_APPS == request_type)) {

      LOG4CXX_ERROR(logger_, "Binary data empty");

      SendResponse(false, mobile_apis::Result::INVALID_DATA);
      return;
  }

  std::vector<uint8_t> binary_data;
  if ((*message_)[strings::params].keyExists(strings::binary_data)) {
    binary_data = (*message_)[strings::params][strings::binary_data].asBinary();
  }

  if (mobile_apis::RequestType::QUERY_APPS == request_type) {
    using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;

    const std::string json(binary_data.begin(), binary_data.end());
    Json::Value value;
    Json::Reader reader;
    if (!reader.parse(json.c_str(), value)) {
      LOG4CXX_ERROR(logger_, "Can't parse json received from QueryApps.");
      return;
    }

    smart_objects::SmartObject sm_object;
    CFormatterJsonBase::jsonValueToObj(value, sm_object);

    if (!ValidateQueryAppData(sm_object)) {
      SendResponse(false, mobile_apis::Result::INVALID_DATA);
      return;
    }

    ApplicationManagerImpl::instance()->ProcessQueryApp(sm_object,
                                                        connection_key());
    SendResponse(true, mobile_apis::Result::SUCCESS);
    return;
  }

  std::string file_path = profile::Profile::instance()->system_files_path();
  if (!file_system::CreateDirectoryRecursively(file_path)) {
    LOG4CXX_ERROR(logger_, "Cann't create folder.");
    SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
    return;
  }

  std::string file_name = "SYNC";
  if ((*message_)[strings::msg_params].keyExists(strings::file_name)) {
    file_name = (*message_)[strings::msg_params][strings::file_name].asString();
  }

  // to avoid override existing file
  const uint8_t max_size = 255;
  char buf[max_size] = {'\0'};
  snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%d%s", index++, file_name.c_str());
  file_name = buf;

  std::string full_file_path = file_path + "/" + file_name;
  if (binary_data.size()) {
    if (mobile_apis::Result::SUCCESS  !=
        (ApplicationManagerImpl::instance()->SaveBinary(
            binary_data, file_path, file_name, 0))) {
      SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
      return;
    }
  } else {
    if (!(file_system::CreateFile(full_file_path))) {
      SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
      return;
    }
  }

  smart_objects::SmartObject msg_params = smart_objects::SmartObject(
      smart_objects::SmartType_Map);
  if (std::string::npos != file_name.find("IVSU")) {
    msg_params[strings::file_name] = file_name.c_str();
  } else {
    msg_params[strings::file_name] = full_file_path;
  }

  if (mobile_apis::RequestType::PROPRIETARY != request_type) {
    msg_params[strings::app_id] = (application->mobile_app_id());
  }
  msg_params[strings::request_type] =
      (*message_)[strings::msg_params][strings::request_type];
  SendHMIRequest(hmi_apis::FunctionID::BasicCommunication_SystemRequest,
                 &msg_params, true);

}

void SystemRequest::on_event(const event_engine::Event& event) {
  LOG4CXX_INFO(logger_, "AddSubMenuRequest::on_event");
  const smart_objects::SmartObject& message = event.smart_object();

  switch (event.id()) {
    case hmi_apis::FunctionID::BasicCommunication_SystemRequest: {
      mobile_apis::Result::eType result_code =
          GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
              message[strings::params][hmi_response::code].asUInt()));
      bool result = mobile_apis::Result::SUCCESS == result_code;

      ApplicationSharedPtr application =
             ApplicationManagerImpl::instance()->application(connection_key());

      if (!(application.valid())) {
        LOG4CXX_ERROR(logger_, "NULL pointer");
        return;
      }

      SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
      break;
    }
    default: {
      LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
      return;
    }
  }
}

bool SystemRequest::ValidateQueryAppData(
    const smart_objects::SmartObject& data) const  {
  if (!data.isValid()) {
    LOG4CXX_ERROR(logger_, "QueryApps response is not valid.");
    return false;
  }
  if (!data.keyExists(json::response)) {
    LOG4CXX_ERROR(logger_,
                  "QueryApps response does not contain '"
                  << json::response << "' parameter.");
    return false;
  }
  smart_objects::SmartArray* obj_array = data[json::response].asArray();
  if (NULL == obj_array) {
    return false;
  }

  const std::size_t arr_size(obj_array->size());
  for (std::size_t idx = 0; idx < arr_size; ++idx) {
    const smart_objects::SmartObject& app_data = (*obj_array)[idx];
    if (!app_data.isValid()) {
      LOG4CXX_ERROR(logger_, "Wrong application data in json file.");
      continue;
    }
    std::string os_type;
    if (app_data.keyExists(json::ios)) {
      os_type = json::ios;
      if (!app_data[os_type].keyExists(json::urlScheme)) {
        LOG4CXX_ERROR(logger_, "Can't find URL scheme in json file.");
        continue;
      }
    } else if (app_data.keyExists(json::android)) {
      os_type = json::android;
      if (!app_data[os_type].keyExists(json::packageName)) {
        LOG4CXX_ERROR(logger_, "Can't find package name in json file.");
        continue;
      }
    }

    if (os_type.empty()) {
      LOG4CXX_ERROR(logger_, "Can't find mobile OS type in json file.");
      continue;
    }

    if (!app_data.keyExists(json::appId)) {
      LOG4CXX_ERROR(logger_, "Can't find app ID in json file.");
      continue;
    }

    if (!app_data.keyExists(json::name)) {
      LOG4CXX_ERROR(logger_, "Can't find app name in json file.");
      continue;
    }

    return true;
  }

  return false;
}

}  // namespace commands

}  // namespace application_manager
<|endoftext|>


<commit_before>/*
    kopeteballoon.cpp  -  Nice Balloon

    Copyright (c) 2002      by Duncan Mac-Vicar Prett <duncan@kde.org>

    Kopete    (c) 2002      by the Kopete developers  <kopete-devel@kde.org>

    Portions of this code based on Kim Applet code
    Copyright (c) 2000-2002 by Malte Starostik        <malte@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qpointarray.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qlayout.h>

#include <kdeversion.h>
#if KDE_VERSION > 0x030100
#include <kglobalsettings.h>
#endif

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>

#include "kopeteballoon.h"
#include "systemtray.h"

KopeteBalloon::KopeteBalloon( const QString &text, const QString &pix )
: QWidget( 0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize |
	WStyle_NoBorder | WStyle_Tool | WX11BypassWM )
{
	resize( 139, 104 );

	setCaption( trUtf8( "" ) );
	QVBoxLayout *BalloonLayout = new QVBoxLayout( this, 24, 6, "BalloonLayout");

	QHBoxLayout *Layout1 = new QHBoxLayout( 0, 0, 6, "Layout1");

	m_image = new QLabel( this, "m_image" );
	m_image->setScaledContents( FALSE );
	Layout1->addWidget( m_image );

	m_caption = new QLabel( this, "m_caption" );
	m_caption->setText( trUtf8( "" ) );
	Layout1->addWidget( m_caption );
	BalloonLayout->addLayout( Layout1 );

	QHBoxLayout *Layout2 = new QHBoxLayout( 0, 0, 6, "Layout2");
	QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	Layout2->addItem( spacer );

	QPushButton *viewButton = new QPushButton( this, "m_reject" );
	viewButton->setText( i18n( "View" ) );

	QPushButton *ignoreButton = new QPushButton( this );
	ignoreButton->setText( i18n( "Ignore" ) );

	Layout2->addWidget( viewButton );
	Layout2->addWidget( ignoreButton );

	QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	Layout2->addItem( spacer_2 );
	BalloonLayout->addLayout( Layout2 );

	setPalette(QToolTip::palette());
	setAutoMask(true);

	m_image->setPixmap(locate("data", pix));
	m_caption->setText(text);

	connect( viewButton, SIGNAL( clicked() ), SIGNAL( signalButtonClicked() ) );
	connect( ignoreButton, SIGNAL( clicked() ), SIGNAL( signalIgnoreButtonClicked() ) );
	connect( viewButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
	connect( ignoreButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
}

void KopeteBalloon::setAnchor( const QPoint &anchor)
{
	m_anchor = anchor;
	updateMask();
}

KopeteBalloon::~KopeteBalloon()
{
}

void KopeteBalloon::updateMask()
{
	QRegion mask(10, 10, width() - 20, height() - 20);

	QPoint corners[8] = {
		QPoint(width() - 50, 10),
		QPoint(10, 10),
		QPoint(10, height() - 50),
		QPoint(width() - 50, height() - 50),
		QPoint(width() - 10, 10),
		QPoint(10, 10),
		QPoint(10, height() - 10),
		QPoint(width() - 10, height() - 10)
	};

	for (int i = 0; i < 4; ++i)
	{
		QPointArray corner;
		corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90);
		corner.resize(corner.size() + 1);
		corner.setPoint(corner.size() - 1, corners[i + 4]);
		mask -= corner;
	}

	// get screen-geometry for screen our anchor is on
	// (geometry can differ from screen to screen!
	#if KDE_VERSION > 0x030100
		QRect deskRect = KGlobalSettings::desktopGeometry(m_anchor);
	#else
		QDesktopWidget* tmp = QApplication::desktop();
		QRect deskRect = tmp->screenGeometry(tmp->screenNumber(m_anchor));
	#endif

	bool bottom = (m_anchor.y() + height()) > (deskRect.height() - 48);
	bool right = (m_anchor.x() + width()) > (deskRect.width() - 48);

	QPointArray arrow(4);
	arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0));
	arrow.setPoint(1, QPoint(right ? width() - 10 : 10, bottom ? height() - 30 : 30));
	arrow.setPoint(2, QPoint(right ? width() - 30 : 30, bottom ? height() - 10 : 10));
	arrow.setPoint(3, arrow[0]);
	mask += arrow;
	setMask(mask);

	move(right ? m_anchor.x() - width() : m_anchor.x(),
	     bottom ? m_anchor.y() - height() : m_anchor.y());
}

#include "kopeteballoon.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>that #if was wrong :)<commit_after>/*
    kopeteballoon.cpp  -  Nice Balloon

    Copyright (c) 2002      by Duncan Mac-Vicar Prett <duncan@kde.org>

    Kopete    (c) 2002      by the Kopete developers  <kopete-devel@kde.org>

    Portions of this code based on Kim Applet code
    Copyright (c) 2000-2002 by Malte Starostik        <malte@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qpointarray.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qlayout.h>

#include <kdeversion.h>
#if KDE_VERSION > 0x030190
#include <kglobalsettings.h>
#endif

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>

#include "kopeteballoon.h"
#include "systemtray.h"

KopeteBalloon::KopeteBalloon( const QString &text, const QString &pix )
: QWidget( 0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize |
	WStyle_NoBorder | WStyle_Tool | WX11BypassWM )
{
	resize( 139, 104 );

	setCaption( trUtf8( "" ) );
	QVBoxLayout *BalloonLayout = new QVBoxLayout( this, 24, 6, "BalloonLayout");

	QHBoxLayout *Layout1 = new QHBoxLayout( 0, 0, 6, "Layout1");

	m_image = new QLabel( this, "m_image" );
	m_image->setScaledContents( FALSE );
	Layout1->addWidget( m_image );

	m_caption = new QLabel( this, "m_caption" );
	m_caption->setText( trUtf8( "" ) );
	Layout1->addWidget( m_caption );
	BalloonLayout->addLayout( Layout1 );

	QHBoxLayout *Layout2 = new QHBoxLayout( 0, 0, 6, "Layout2");
	QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	Layout2->addItem( spacer );

	QPushButton *viewButton = new QPushButton( this, "m_reject" );
	viewButton->setText( i18n( "View" ) );

	QPushButton *ignoreButton = new QPushButton( this );
	ignoreButton->setText( i18n( "Ignore" ) );

	Layout2->addWidget( viewButton );
	Layout2->addWidget( ignoreButton );

	QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	Layout2->addItem( spacer_2 );
	BalloonLayout->addLayout( Layout2 );

	setPalette(QToolTip::palette());
	setAutoMask(true);

	m_image->setPixmap(locate("data", pix));
	m_caption->setText(text);

	connect( viewButton, SIGNAL( clicked() ), SIGNAL( signalButtonClicked() ) );
	connect( ignoreButton, SIGNAL( clicked() ), SIGNAL( signalIgnoreButtonClicked() ) );
	connect( viewButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
	connect( ignoreButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
}

void KopeteBalloon::setAnchor( const QPoint &anchor)
{
	m_anchor = anchor;
	updateMask();
}

KopeteBalloon::~KopeteBalloon()
{
}

void KopeteBalloon::updateMask()
{
	QRegion mask(10, 10, width() - 20, height() - 20);

	QPoint corners[8] = {
		QPoint(width() - 50, 10),
		QPoint(10, 10),
		QPoint(10, height() - 50),
		QPoint(width() - 50, height() - 50),
		QPoint(width() - 10, 10),
		QPoint(10, 10),
		QPoint(10, height() - 10),
		QPoint(width() - 10, height() - 10)
	};

	for (int i = 0; i < 4; ++i)
	{
		QPointArray corner;
		corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90);
		corner.resize(corner.size() + 1);
		corner.setPoint(corner.size() - 1, corners[i + 4]);
		mask -= corner;
	}

	// get screen-geometry for screen our anchor is on
	// (geometry can differ from screen to screen!
	#if KDE_VERSION > 0x030190
		QRect deskRect = KGlobalSettings::desktopGeometry(m_anchor);
	#else
		QDesktopWidget* tmp = QApplication::desktop();
		QRect deskRect = tmp->screenGeometry(tmp->screenNumber(m_anchor));
	#endif

	bool bottom = (m_anchor.y() + height()) > (deskRect.height() - 48);
	bool right = (m_anchor.x() + width()) > (deskRect.width() - 48);

	QPointArray arrow(4);
	arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0));
	arrow.setPoint(1, QPoint(right ? width() - 10 : 10, bottom ? height() - 30 : 30));
	arrow.setPoint(2, QPoint(right ? width() - 30 : 30, bottom ? height() - 10 : 10));
	arrow.setPoint(3, arrow[0]);
	mask += arrow;
	setMask(mask);

	move(right ? m_anchor.x() - width() : m_anchor.x(),
	     bottom ? m_anchor.y() - height() : m_anchor.y());
}

#include "kopeteballoon.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>//===- StandardTypes.cpp - MLIR Standard Type Classes ---------------------===//
//
// Copyright 2019 The MLIR 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 "mlir/IR/StandardTypes.h"
#include "TypeDetail.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Support/STLExtras.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"

using namespace mlir;
using namespace mlir::detail;

//===----------------------------------------------------------------------===//
// Integer Type
//===----------------------------------------------------------------------===//

/// Verify the construction of an integer type.
LogicalResult IntegerType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, unsigned width) {
  if (width > IntegerType::kMaxWidth) {
    if (loc)
      context->emitError(*loc) << "integer bitwidth is limited to "
                               << IntegerType::kMaxWidth << " bits";
    return failure();
  }
  return success();
}

IntegerType IntegerType::get(unsigned width, MLIRContext *context) {
  return Base::get(context, StandardTypes::Integer, width);
}

IntegerType IntegerType::getChecked(unsigned width, MLIRContext *context,
                                    Location location) {
  return Base::getChecked(location, context, StandardTypes::Integer, width);
}

unsigned IntegerType::getWidth() const { return getImpl()->width; }

//===----------------------------------------------------------------------===//
// Float Type
//===----------------------------------------------------------------------===//

unsigned FloatType::getWidth() const {
  switch (getKind()) {
  case StandardTypes::BF16:
  case StandardTypes::F16:
    return 16;
  case StandardTypes::F32:
    return 32;
  case StandardTypes::F64:
    return 64;
  default:
    llvm_unreachable("unexpected type");
  }
}

/// Returns the floating semantics for the given type.
const llvm::fltSemantics &FloatType::getFloatSemantics() const {
  if (isBF16())
    // Treat BF16 like a double. This is unfortunate but BF16 fltSemantics is
    // not defined in LLVM.
    // TODO(jpienaar): add BF16 to LLVM? fltSemantics are internal to APFloat.cc
    // else one could add it.
    //  static const fltSemantics semBF16 = {127, -126, 8, 16};
    return APFloat::IEEEdouble();
  if (isF16())
    return APFloat::IEEEhalf();
  if (isF32())
    return APFloat::IEEEsingle();
  if (isF64())
    return APFloat::IEEEdouble();
  llvm_unreachable("non-floating point type used");
}

unsigned Type::getIntOrFloatBitWidth() const {
  assert(isIntOrFloat() && "only ints and floats have a bitwidth");
  if (auto intType = dyn_cast<IntegerType>()) {
    return intType.getWidth();
  }

  auto floatType = cast<FloatType>();
  return floatType.getWidth();
}

//===----------------------------------------------------------------------===//
// VectorOrTensorType
//===----------------------------------------------------------------------===//

Type VectorOrTensorType::getElementType() const {
  return static_cast<ImplType *>(type)->elementType;
}

unsigned VectorOrTensorType::getElementTypeBitWidth() const {
  return getElementType().getIntOrFloatBitWidth();
}

unsigned VectorOrTensorType::getNumElements() const {
  switch (getKind()) {
  case StandardTypes::Vector:
  case StandardTypes::RankedTensor: {
    assert(hasStaticShape() && "expected type to have static shape");
    auto shape = getShape();
    unsigned num = 1;
    for (auto dim : shape)
      num *= dim;
    return num;
  }
  default:
    llvm_unreachable("not a VectorOrTensorType or not ranked");
  }
}

/// If this is ranked tensor or vector type, return the rank. If it is an
/// unranked tensor, return -1.
int64_t VectorOrTensorType::getRank() const {
  switch (getKind()) {
  case StandardTypes::Vector:
  case StandardTypes::RankedTensor:
    return getShape().size();
  case StandardTypes::UnrankedTensor:
    return -1;
  default:
    llvm_unreachable("not a VectorOrTensorType");
  }
}

int64_t VectorOrTensorType::getDimSize(unsigned i) const {
  switch (getKind()) {
  case StandardTypes::Vector:
  case StandardTypes::RankedTensor:
    return getShape()[i];
  default:
    llvm_unreachable("not a VectorOrTensorType or not ranked");
  }
}

// Get the number of number of bits require to store a value of the given vector
// or tensor types.  Compute the value recursively since tensors are allowed to
// have vectors as elements.
int64_t VectorOrTensorType::getSizeInBits() const {
  assert(hasStaticShape() &&
         "cannot get the bit size of an aggregate with a dynamic shape");

  auto elementType = getElementType();
  if (elementType.isIntOrFloat())
    return elementType.getIntOrFloatBitWidth() * getNumElements();

  // Tensors can have vectors and other tensors as elements, vectors cannot.
  assert(!isa<VectorType>() && "unsupported vector element type");
  auto elementVectorOrTensorType = elementType.dyn_cast<VectorOrTensorType>();
  assert(elementVectorOrTensorType && "unsupported tensor element type");
  return getNumElements() * elementVectorOrTensorType.getSizeInBits();
}

ArrayRef<int64_t> VectorOrTensorType::getShape() const {
  switch (getKind()) {
  case StandardTypes::Vector:
    return cast<VectorType>().getShape();
  case StandardTypes::RankedTensor:
    return cast<RankedTensorType>().getShape();
  default:
    llvm_unreachable("not a VectorOrTensorType or not ranked");
  }
}

bool VectorOrTensorType::hasStaticShape() const {
  if (isa<UnrankedTensorType>())
    return false;
  return llvm::none_of(getShape(), [](int64_t i) { return i < 0; });
}

//===----------------------------------------------------------------------===//
// VectorType
//===----------------------------------------------------------------------===//

VectorType VectorType::get(ArrayRef<int64_t> shape, Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::Vector, shape,
                   elementType);
}

VectorType VectorType::getChecked(ArrayRef<int64_t> shape, Type elementType,
                                  Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::Vector, shape, elementType);
}

LogicalResult VectorType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
    Type elementType) {
  if (shape.empty()) {
    if (loc)
      context->emitError(*loc, "vector types must have at least one dimension");
    return failure();
  }

  if (!isValidElementType(elementType)) {
    if (loc)
      context->emitError(*loc, "vector elements must be int or float type");
    return failure();
  }

  if (any_of(shape, [](int64_t i) { return i <= 0; })) {
    if (loc)
      context->emitError(*loc,
                         "vector types must have positive constant sizes");
    return failure();
  }
  return success();
}

ArrayRef<int64_t> VectorType::getShape() const { return getImpl()->getShape(); }

//===----------------------------------------------------------------------===//
// TensorType
//===----------------------------------------------------------------------===//

// Check if "elementType" can be an element type of a tensor. Emit errors if
// location is not nullptr.  Returns failure if check failed.
static inline LogicalResult checkTensorElementType(Optional<Location> location,
                                                   MLIRContext *context,
                                                   Type elementType) {
  if (!TensorType::isValidElementType(elementType)) {
    if (location)
      context->emitError(*location, "invalid tensor element type");
    return failure();
  }
  return success();
}

//===----------------------------------------------------------------------===//
// RankedTensorType
//===----------------------------------------------------------------------===//

RankedTensorType RankedTensorType::get(ArrayRef<int64_t> shape,
                                       Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::RankedTensor, shape,
                   elementType);
}

RankedTensorType RankedTensorType::getChecked(ArrayRef<int64_t> shape,
                                              Type elementType,
                                              Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::RankedTensor, shape, elementType);
}

LogicalResult RankedTensorType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
    Type elementType) {
  for (int64_t s : shape) {
    if (s < -1) {
      if (loc)
        context->emitError(*loc, "invalid tensor dimension size");
      return failure();
    }
  }
  return checkTensorElementType(loc, context, elementType);
}

ArrayRef<int64_t> RankedTensorType::getShape() const {
  return getImpl()->getShape();
}

//===----------------------------------------------------------------------===//
// UnrankedTensorType
//===----------------------------------------------------------------------===//

UnrankedTensorType UnrankedTensorType::get(Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::UnrankedTensor,
                   elementType);
}

UnrankedTensorType UnrankedTensorType::getChecked(Type elementType,
                                                  Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::UnrankedTensor, elementType);
}

LogicalResult UnrankedTensorType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
  return checkTensorElementType(loc, context, elementType);
}

//===----------------------------------------------------------------------===//
// MemRefType
//===----------------------------------------------------------------------===//

/// Get or create a new MemRefType defined by the arguments.  If the resulting
/// type would be ill-formed, return nullptr.  If the location is provided,
/// emit detailed error messages.  To emit errors when the location is unknown,
/// pass in an instance of UnknownLoc.
MemRefType MemRefType::getImpl(ArrayRef<int64_t> shape, Type elementType,
                               ArrayRef<AffineMap> affineMapComposition,
                               unsigned memorySpace,
                               Optional<Location> location) {
  auto *context = elementType.getContext();

  for (int64_t s : shape) {
    // Negative sizes are not allowed except for `-1` that means dynamic size.
    if (s < -1) {
      if (location)
        context->emitError(*location, "invalid memref size");
      return {};
    }
  }

  // Check that the structure of the composition is valid, i.e. that each
  // subsequent affine map has as many inputs as the previous map has results.
  // Take the dimensionality of the MemRef for the first map.
  auto dim = shape.size();
  unsigned i = 0;
  for (const auto &affineMap : affineMapComposition) {
    if (affineMap.getNumDims() != dim) {
      if (location)
        context->emitError(
            *location,
            "memref affine map dimension mismatch between " +
                (i == 0 ? Twine("memref rank") : "affine map " + Twine(i)) +
                " and affine map" + Twine(i + 1) + ": " + Twine(dim) +
                " != " + Twine(affineMap.getNumDims()));
      return nullptr;
    }

    dim = affineMap.getNumResults();
    ++i;
  }

  // Drop the unbounded identity maps from the composition.
  // This may lead to the composition becoming empty, which is interpreted as an
  // implicit identity.
  llvm::SmallVector<AffineMap, 2> cleanedAffineMapComposition;
  for (const auto &map : affineMapComposition) {
    if (map.isIdentity() && !map.isBounded())
      continue;
    cleanedAffineMapComposition.push_back(map);
  }

  return Base::get(context, StandardTypes::MemRef, shape, elementType,
                   cleanedAffineMapComposition, memorySpace);
}

ArrayRef<int64_t> MemRefType::getShape() const {
  return static_cast<ImplType *>(type)->getShape();
}

Type MemRefType::getElementType() const {
  return static_cast<ImplType *>(type)->elementType;
}

ArrayRef<AffineMap> MemRefType::getAffineMaps() const {
  return static_cast<ImplType *>(type)->getAffineMaps();
}

unsigned MemRefType::getMemorySpace() const {
  return static_cast<ImplType *>(type)->memorySpace;
}

unsigned MemRefType::getNumDynamicDims() const {
  return llvm::count_if(getShape(), [](int64_t i) { return i < 0; });
}

//===----------------------------------------------------------------------===//
/// ComplexType
//===----------------------------------------------------------------------===//

ComplexType ComplexType::get(Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::Complex,
                   elementType);
}

ComplexType ComplexType::getChecked(Type elementType, Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::Complex, elementType);
}

/// Verify the construction of an integer type.
LogicalResult ComplexType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
  if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) {
    if (loc)
      context->emitError(*loc, "invalid element type for complex");
    return failure();
  }
  return success();
}

Type ComplexType::getElementType() { return getImpl()->elementType; }

//===----------------------------------------------------------------------===//
/// TupleType
//===----------------------------------------------------------------------===//

/// Get or create a new TupleType with the provided element types. Assumes the
/// arguments define a well-formed type.
TupleType TupleType::get(ArrayRef<Type> elementTypes, MLIRContext *context) {
  return Base::get(context, StandardTypes::Tuple, elementTypes);
}

/// Return the elements types for this tuple.
ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }

/// Return the number of element types.
unsigned TupleType::size() const { return getImpl()->size(); }
<commit_msg>    Fix MacOS build: static constexpr must be defined<commit_after>//===- StandardTypes.cpp - MLIR Standard Type Classes ---------------------===//
//
// Copyright 2019 The MLIR 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 "mlir/IR/StandardTypes.h"
#include "TypeDetail.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Support/STLExtras.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"

using namespace mlir;
using namespace mlir::detail;

//===----------------------------------------------------------------------===//
// Integer Type
//===----------------------------------------------------------------------===//

// static constexpr must have a definition (until in C++17 and inline variable).
constexpr unsigned IntegerType::kMaxWidth;

/// Verify the construction of an integer type.
LogicalResult IntegerType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, unsigned width) {
  if (width > IntegerType::kMaxWidth) {
    if (loc)
      context->emitError(*loc) << "integer bitwidth is limited to "
                               << IntegerType::kMaxWidth << " bits";
    return failure();
  }
  return success();
}

IntegerType IntegerType::get(unsigned width, MLIRContext *context) {
  return Base::get(context, StandardTypes::Integer, width);
}

IntegerType IntegerType::getChecked(unsigned width, MLIRContext *context,
                                    Location location) {
  return Base::getChecked(location, context, StandardTypes::Integer, width);
}

unsigned IntegerType::getWidth() const { return getImpl()->width; }

//===----------------------------------------------------------------------===//
// Float Type
//===----------------------------------------------------------------------===//

unsigned FloatType::getWidth() const {
  switch (getKind()) {
  case StandardTypes::BF16:
  case StandardTypes::F16:
    return 16;
  case StandardTypes::F32:
    return 32;
  case StandardTypes::F64:
    return 64;
  default:
    llvm_unreachable("unexpected type");
  }
}

/// Returns the floating semantics for the given type.
const llvm::fltSemantics &FloatType::getFloatSemantics() const {
  if (isBF16())
    // Treat BF16 like a double. This is unfortunate but BF16 fltSemantics is
    // not defined in LLVM.
    // TODO(jpienaar): add BF16 to LLVM? fltSemantics are internal to APFloat.cc
    // else one could add it.
    //  static const fltSemantics semBF16 = {127, -126, 8, 16};
    return APFloat::IEEEdouble();
  if (isF16())
    return APFloat::IEEEhalf();
  if (isF32())
    return APFloat::IEEEsingle();
  if (isF64())
    return APFloat::IEEEdouble();
  llvm_unreachable("non-floating point type used");
}

unsigned Type::getIntOrFloatBitWidth() const {
  assert(isIntOrFloat() && "only ints and floats have a bitwidth");
  if (auto intType = dyn_cast<IntegerType>()) {
    return intType.getWidth();
  }

  auto floatType = cast<FloatType>();
  return floatType.getWidth();
}

//===----------------------------------------------------------------------===//
// VectorOrTensorType
//===----------------------------------------------------------------------===//

Type VectorOrTensorType::getElementType() const {
  return static_cast<ImplType *>(type)->elementType;
}

unsigned VectorOrTensorType::getElementTypeBitWidth() const {
  return getElementType().getIntOrFloatBitWidth();
}

unsigned VectorOrTensorType::getNumElements() const {
  switch (getKind()) {
  case StandardTypes::Vector:
  case StandardTypes::RankedTensor: {
    assert(hasStaticShape() && "expected type to have static shape");
    auto shape = getShape();
    unsigned num = 1;
    for (auto dim : shape)
      num *= dim;
    return num;
  }
  default:
    llvm_unreachable("not a VectorOrTensorType or not ranked");
  }
}

/// If this is ranked tensor or vector type, return the rank. If it is an
/// unranked tensor, return -1.
int64_t VectorOrTensorType::getRank() const {
  switch (getKind()) {
  case StandardTypes::Vector:
  case StandardTypes::RankedTensor:
    return getShape().size();
  case StandardTypes::UnrankedTensor:
    return -1;
  default:
    llvm_unreachable("not a VectorOrTensorType");
  }
}

int64_t VectorOrTensorType::getDimSize(unsigned i) const {
  switch (getKind()) {
  case StandardTypes::Vector:
  case StandardTypes::RankedTensor:
    return getShape()[i];
  default:
    llvm_unreachable("not a VectorOrTensorType or not ranked");
  }
}

// Get the number of number of bits require to store a value of the given vector
// or tensor types.  Compute the value recursively since tensors are allowed to
// have vectors as elements.
int64_t VectorOrTensorType::getSizeInBits() const {
  assert(hasStaticShape() &&
         "cannot get the bit size of an aggregate with a dynamic shape");

  auto elementType = getElementType();
  if (elementType.isIntOrFloat())
    return elementType.getIntOrFloatBitWidth() * getNumElements();

  // Tensors can have vectors and other tensors as elements, vectors cannot.
  assert(!isa<VectorType>() && "unsupported vector element type");
  auto elementVectorOrTensorType = elementType.dyn_cast<VectorOrTensorType>();
  assert(elementVectorOrTensorType && "unsupported tensor element type");
  return getNumElements() * elementVectorOrTensorType.getSizeInBits();
}

ArrayRef<int64_t> VectorOrTensorType::getShape() const {
  switch (getKind()) {
  case StandardTypes::Vector:
    return cast<VectorType>().getShape();
  case StandardTypes::RankedTensor:
    return cast<RankedTensorType>().getShape();
  default:
    llvm_unreachable("not a VectorOrTensorType or not ranked");
  }
}

bool VectorOrTensorType::hasStaticShape() const {
  if (isa<UnrankedTensorType>())
    return false;
  return llvm::none_of(getShape(), [](int64_t i) { return i < 0; });
}

//===----------------------------------------------------------------------===//
// VectorType
//===----------------------------------------------------------------------===//

VectorType VectorType::get(ArrayRef<int64_t> shape, Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::Vector, shape,
                   elementType);
}

VectorType VectorType::getChecked(ArrayRef<int64_t> shape, Type elementType,
                                  Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::Vector, shape, elementType);
}

LogicalResult VectorType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
    Type elementType) {
  if (shape.empty()) {
    if (loc)
      context->emitError(*loc, "vector types must have at least one dimension");
    return failure();
  }

  if (!isValidElementType(elementType)) {
    if (loc)
      context->emitError(*loc, "vector elements must be int or float type");
    return failure();
  }

  if (any_of(shape, [](int64_t i) { return i <= 0; })) {
    if (loc)
      context->emitError(*loc,
                         "vector types must have positive constant sizes");
    return failure();
  }
  return success();
}

ArrayRef<int64_t> VectorType::getShape() const { return getImpl()->getShape(); }

//===----------------------------------------------------------------------===//
// TensorType
//===----------------------------------------------------------------------===//

// Check if "elementType" can be an element type of a tensor. Emit errors if
// location is not nullptr.  Returns failure if check failed.
static inline LogicalResult checkTensorElementType(Optional<Location> location,
                                                   MLIRContext *context,
                                                   Type elementType) {
  if (!TensorType::isValidElementType(elementType)) {
    if (location)
      context->emitError(*location, "invalid tensor element type");
    return failure();
  }
  return success();
}

//===----------------------------------------------------------------------===//
// RankedTensorType
//===----------------------------------------------------------------------===//

RankedTensorType RankedTensorType::get(ArrayRef<int64_t> shape,
                                       Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::RankedTensor, shape,
                   elementType);
}

RankedTensorType RankedTensorType::getChecked(ArrayRef<int64_t> shape,
                                              Type elementType,
                                              Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::RankedTensor, shape, elementType);
}

LogicalResult RankedTensorType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
    Type elementType) {
  for (int64_t s : shape) {
    if (s < -1) {
      if (loc)
        context->emitError(*loc, "invalid tensor dimension size");
      return failure();
    }
  }
  return checkTensorElementType(loc, context, elementType);
}

ArrayRef<int64_t> RankedTensorType::getShape() const {
  return getImpl()->getShape();
}

//===----------------------------------------------------------------------===//
// UnrankedTensorType
//===----------------------------------------------------------------------===//

UnrankedTensorType UnrankedTensorType::get(Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::UnrankedTensor,
                   elementType);
}

UnrankedTensorType UnrankedTensorType::getChecked(Type elementType,
                                                  Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::UnrankedTensor, elementType);
}

LogicalResult UnrankedTensorType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
  return checkTensorElementType(loc, context, elementType);
}

//===----------------------------------------------------------------------===//
// MemRefType
//===----------------------------------------------------------------------===//

/// Get or create a new MemRefType defined by the arguments.  If the resulting
/// type would be ill-formed, return nullptr.  If the location is provided,
/// emit detailed error messages.  To emit errors when the location is unknown,
/// pass in an instance of UnknownLoc.
MemRefType MemRefType::getImpl(ArrayRef<int64_t> shape, Type elementType,
                               ArrayRef<AffineMap> affineMapComposition,
                               unsigned memorySpace,
                               Optional<Location> location) {
  auto *context = elementType.getContext();

  for (int64_t s : shape) {
    // Negative sizes are not allowed except for `-1` that means dynamic size.
    if (s < -1) {
      if (location)
        context->emitError(*location, "invalid memref size");
      return {};
    }
  }

  // Check that the structure of the composition is valid, i.e. that each
  // subsequent affine map has as many inputs as the previous map has results.
  // Take the dimensionality of the MemRef for the first map.
  auto dim = shape.size();
  unsigned i = 0;
  for (const auto &affineMap : affineMapComposition) {
    if (affineMap.getNumDims() != dim) {
      if (location)
        context->emitError(
            *location,
            "memref affine map dimension mismatch between " +
                (i == 0 ? Twine("memref rank") : "affine map " + Twine(i)) +
                " and affine map" + Twine(i + 1) + ": " + Twine(dim) +
                " != " + Twine(affineMap.getNumDims()));
      return nullptr;
    }

    dim = affineMap.getNumResults();
    ++i;
  }

  // Drop the unbounded identity maps from the composition.
  // This may lead to the composition becoming empty, which is interpreted as an
  // implicit identity.
  llvm::SmallVector<AffineMap, 2> cleanedAffineMapComposition;
  for (const auto &map : affineMapComposition) {
    if (map.isIdentity() && !map.isBounded())
      continue;
    cleanedAffineMapComposition.push_back(map);
  }

  return Base::get(context, StandardTypes::MemRef, shape, elementType,
                   cleanedAffineMapComposition, memorySpace);
}

ArrayRef<int64_t> MemRefType::getShape() const {
  return static_cast<ImplType *>(type)->getShape();
}

Type MemRefType::getElementType() const {
  return static_cast<ImplType *>(type)->elementType;
}

ArrayRef<AffineMap> MemRefType::getAffineMaps() const {
  return static_cast<ImplType *>(type)->getAffineMaps();
}

unsigned MemRefType::getMemorySpace() const {
  return static_cast<ImplType *>(type)->memorySpace;
}

unsigned MemRefType::getNumDynamicDims() const {
  return llvm::count_if(getShape(), [](int64_t i) { return i < 0; });
}

//===----------------------------------------------------------------------===//
/// ComplexType
//===----------------------------------------------------------------------===//

ComplexType ComplexType::get(Type elementType) {
  return Base::get(elementType.getContext(), StandardTypes::Complex,
                   elementType);
}

ComplexType ComplexType::getChecked(Type elementType, Location location) {
  return Base::getChecked(location, elementType.getContext(),
                          StandardTypes::Complex, elementType);
}

/// Verify the construction of an integer type.
LogicalResult ComplexType::verifyConstructionInvariants(
    llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
  if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) {
    if (loc)
      context->emitError(*loc, "invalid element type for complex");
    return failure();
  }
  return success();
}

Type ComplexType::getElementType() { return getImpl()->elementType; }

//===----------------------------------------------------------------------===//
/// TupleType
//===----------------------------------------------------------------------===//

/// Get or create a new TupleType with the provided element types. Assumes the
/// arguments define a well-formed type.
TupleType TupleType::get(ArrayRef<Type> elementTypes, MLIRContext *context) {
  return Base::get(context, StandardTypes::Tuple, elementTypes);
}

/// Return the elements types for this tuple.
ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }

/// Return the number of element types.
unsigned TupleType::size() const { return getImpl()->size(); }
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////

#include "VppResponse.h"

#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>

#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackDumper.h"
#include "Basics/tri-strings.h"
#include "Rest/VppRequest.h"

using namespace arangodb;
using namespace arangodb::basics;

bool VppResponse::HIDE_PRODUCT_HEADER = false;

VppResponse::VppResponse(ResponseCode code, uint64_t id)
    : GeneralResponse(code),
      _connectionType(CONNECTION_KEEP_ALIVE),
      _contentType(ContentType::VPACK),
      _header(nullptr),
      _payload(),
      _messageID(id) {}

void VppResponse::reset(ResponseCode code) {
  _responseCode = code;
  _headers.clear();
  _connectionType = CONNECTION_KEEP_ALIVE;
  _contentType = ContentType::TEXT;
}

void VppResponse::setPayload(ContentType contentType,
                             arangodb::velocypack::Slice const& slice,
                             bool generateBody, VPackOptions const& options) {
  if (generateBody) {
    // addPayload(slice);
    if (slice.isEmptyObject()) {
      throw std::logic_error("payload should be empty!!");
    }
    _payload.append(slice.startAs<char>(),
                    std::distance(slice.begin(), slice.end()));
  }
};

VPackMessageNoOwnBuffer VppResponse::prepareForNetwork() {
  VPackBuilder builder;
  builder.openObject();
  for (auto const& item : _headers) {
    builder.add(item.first, VPackValue(item.second));
  }
  builder.close();
  _header = builder.steal();
  return VPackMessageNoOwnBuffer(VPackSlice(_header->data()),
                                 VPackSlice(_payload.data()), _messageID);
}
// void VppResponse::writeHeader(basics::StringBuffer*) {}
<commit_msg>fix header<commit_after>///////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////

#include "VppResponse.h"

#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>

#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackDumper.h"
#include "Basics/tri-strings.h"
#include "Meta/conversion.h"
#include "Rest/VppRequest.h"

using namespace arangodb;
using namespace arangodb::basics;

bool VppResponse::HIDE_PRODUCT_HEADER = false;

VppResponse::VppResponse(ResponseCode code, uint64_t id)
    : GeneralResponse(code),
      _connectionType(CONNECTION_KEEP_ALIVE),
      _contentType(ContentType::VPACK),
      _header(nullptr),
      _payload(),
      _messageID(id) {}

void VppResponse::reset(ResponseCode code) {
  _responseCode = code;
  _headers.clear();
  _connectionType = CONNECTION_KEEP_ALIVE;
  _contentType = ContentType::TEXT;
}

void VppResponse::setPayload(ContentType contentType,
                             arangodb::velocypack::Slice const& slice,
                             bool generateBody, VPackOptions const& options) {
  if (generateBody) {
    // addPayload(slice);
    if (slice.isEmptyObject()) {
      throw std::logic_error("payload should be empty!!");
    }
    _payload.append(slice.startAs<char>(),
                    std::distance(slice.begin(), slice.end()));
  }
};

VPackMessageNoOwnBuffer VppResponse::prepareForNetwork() {
  VPackBuilder builder;
  builder.openObject();
  builder.add("version", VPackValue(int(1)));
  builder.add("type", VPackValue(int(1)));  // 2 == response
  builder.add(
      "responseCode",
      VPackValue(static_cast<int>(meta::underlyingValue(_responseCode))));
  // for (auto const& item : _headers) {
  //  builder.add(item.first, VPackValue(item.second));
  //}
  builder.close();
  _header = builder.steal();
  return VPackMessageNoOwnBuffer(VPackSlice(_header->data()),
                                 VPackSlice(_payload.data()), _messageID);
}
// void VppResponse::writeHeader(basics::StringBuffer*) {}
<|endoftext|>


<commit_before>#include "THClKernels.h"
#include "EasyCL.h"
#include "THClTensor.h"
#include <stdexcept>
#include "THClReduceApplyUtils.h"
#include "CLKernel_structs.h"

using namespace std;

// Constructor
THClKernels::THClKernels(THClState *state, CLKernel *kernel) :
  state(state),
  kernel(kernel) {
}
THClKernels::~THClKernels() {
  for( int i = 0; i < (int)tensorInfoCls.size(); i++ ) {
    delete tensorInfoCls[i];
  }
}
// CLTensors =====================
THClKernels *THClKernels::in(THClTensor *tensor) {
  try {
    kernel->in(THClTensor_wrapper(state, tensor));
    kernel->in((int)THClTensor_storageOffset(state, tensor));
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::inout(THClTensor *tensor) {
  try {
    kernel->inout(THClTensor_wrapper(state, tensor));
    kernel->in((int)THClTensor_storageOffset(state, tensor));
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::out(THClTensor *tensor) {
  try {
    kernel->out(THClTensor_wrapper(state, tensor));
    kernel->in((int)THClTensor_storageOffset(state, tensor));
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
// scalars ==================
THClKernels *THClKernels::in(int value) {
  try {
    kernel->in(value);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::in(float value) {
  try {
    kernel->in(value);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
// CLTensorInfos ================
template< typename IndexType >
THClKernels *THClKernels::in(TensorInfo<IndexType>tensorInfo) {
  TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
  kernel->in(1, tensorInfoCl);
  kernel->in(tensorInfo.wrapper);
  tensorInfoCls.push_back(tensorInfoCl);
  return this;
}
template< typename IndexType >
THClKernels *THClKernels::inout(TensorInfo<IndexType>tensorInfo) {
  TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
  kernel->in(1, tensorInfoCl);
  kernel->inout(tensorInfo.wrapper);
  tensorInfoCls.push_back(tensorInfoCl);
  return this;
}
template< typename IndexType >
THClKernels *THClKernels::out(TensorInfo<IndexType>tensorInfo) {
  TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
  if( !tensorInfo.wrapper->isOnDevice() ) {
    tensorInfo.wrapper->createOnDevice();
  }
  kernel->in(1, tensorInfoCl);
  kernel->out(tensorInfo.wrapper);
  tensorInfoCls.push_back(tensorInfoCl);
  return this;
}
// CLWrapper ===============
THClKernels *THClKernels::in(CLWrapper *wrapper) {
  try {
    kernel->in(wrapper);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::inout(CLWrapper *wrapper) {
  try {
    kernel->inout(wrapper);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::out(CLWrapper *wrapper) {
  try {
    if( !wrapper->isOnDevice() ) {
      wrapper->createOnDevice();
    }
    kernel->out(wrapper);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
void THClKernels::run(dim3 grid, dim3 block) {
  dim3 global_ws;
  for( int i = 0; i < 3; i++ ) {
      global_ws.vec[i] = grid.vec[i] * block.vec[i];
  }
  try {
    kernel->run(3, global_ws.as_size_t(), block.as_size_t());
  } catch( runtime_error &e ) {
    THError(e.what());
  }
}
// locals ==================
THClKernels *THClKernels::localFloats(int count) {
  try {
    kernel->localFloats(count);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
}

// template instantiations ====================
#define DECLARE_THCLKERNELS(IndexType) \
template \
THClKernels *THClKernels::in<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::inout<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::out<IndexType>(TensorInfo<IndexType>tensorInfo);

DECLARE_THCLKERNELS(unsigned int);
DECLARE_THCLKERNELS(unsigned long);

template CLKernel *CLKernel::in<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::inout<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::out<>(int N, const TensorInfoCl *data);

<commit_msg>more diag output if kernel crash<commit_after>#include "THClKernels.h"
#include "EasyCL.h"
#include "THClTensor.h"
#include <stdexcept>
#include "THClReduceApplyUtils.h"
#include "CLKernel_structs.h"

#include <iostream>
using namespace std;

// Constructor
THClKernels::THClKernels(THClState *state, CLKernel *kernel) :
  state(state),
  kernel(kernel) {
}
THClKernels::~THClKernels() {
  for( int i = 0; i < (int)tensorInfoCls.size(); i++ ) {
    delete tensorInfoCls[i];
  }
}
// CLTensors =====================
THClKernels *THClKernels::in(THClTensor *tensor) {
  try {
    kernel->in(THClTensor_wrapper(state, tensor));
    kernel->in((int)THClTensor_storageOffset(state, tensor));
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::inout(THClTensor *tensor) {
  try {
    kernel->inout(THClTensor_wrapper(state, tensor));
    kernel->in((int)THClTensor_storageOffset(state, tensor));
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::out(THClTensor *tensor) {
  try {
    kernel->out(THClTensor_wrapper(state, tensor));
    kernel->in((int)THClTensor_storageOffset(state, tensor));
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
// scalars ==================
THClKernels *THClKernels::in(int value) {
  try {
    kernel->in(value);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::in(float value) {
  try {
    kernel->in(value);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
// CLTensorInfos ================
template< typename IndexType >
THClKernels *THClKernels::in(TensorInfo<IndexType>tensorInfo) {
  TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
  kernel->in(1, tensorInfoCl);
  kernel->in(tensorInfo.wrapper);
  tensorInfoCls.push_back(tensorInfoCl);
  return this;
}
template< typename IndexType >
THClKernels *THClKernels::inout(TensorInfo<IndexType>tensorInfo) {
  TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
  kernel->in(1, tensorInfoCl);
  kernel->inout(tensorInfo.wrapper);
  tensorInfoCls.push_back(tensorInfoCl);
  return this;
}
template< typename IndexType >
THClKernels *THClKernels::out(TensorInfo<IndexType>tensorInfo) {
  TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
  if( !tensorInfo.wrapper->isOnDevice() ) {
    tensorInfo.wrapper->createOnDevice();
  }
  kernel->in(1, tensorInfoCl);
  kernel->out(tensorInfo.wrapper);
  tensorInfoCls.push_back(tensorInfoCl);
  return this;
}
// CLWrapper ===============
THClKernels *THClKernels::in(CLWrapper *wrapper) {
  try {
    kernel->in(wrapper);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::inout(CLWrapper *wrapper) {
  try {
    kernel->inout(wrapper);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
THClKernels *THClKernels::out(CLWrapper *wrapper) {
  try {
    if( !wrapper->isOnDevice() ) {
      wrapper->createOnDevice();
    }
    kernel->out(wrapper);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
  return this;
}
void THClKernels::run(dim3 grid, dim3 block) {
  dim3 global_ws;
  for( int i = 0; i < 3; i++ ) {
      global_ws.vec[i] = grid.vec[i] * block.vec[i];
  }
  try {
    kernel->run(3, global_ws.as_size_t(), block.as_size_t());
  } catch( runtime_error &e ) {
    cout << e.what() << endl;
    THError(e.what());
  }
}
// locals ==================
THClKernels *THClKernels::localFloats(int count) {
  try {
    kernel->localFloats(count);
  } catch( runtime_error &e ) {
    THError(e.what());
  }
}

// template instantiations ====================
#define DECLARE_THCLKERNELS(IndexType) \
template \
THClKernels *THClKernels::in<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::inout<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::out<IndexType>(TensorInfo<IndexType>tensorInfo);

DECLARE_THCLKERNELS(unsigned int);
DECLARE_THCLKERNELS(unsigned long);

template CLKernel *CLKernel::in<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::inout<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::out<>(int N, const TensorInfoCl *data);

<|endoftext|>