<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include <net/CURLNetRequest.h>
#include <common/PosixThreadImpl.h>

#include "rhodes/JNINetRequest.h"
#include "rhodes/RhoClassFactory.h"
#include "rhodes/sslimpl.h"
#include "rhodes/rhocryptimpl.h"
#include "rhodes/SecurityTokenGenerator.h"

static rho::common::CRhoClassFactory g_rhoClassFactory;
rho::common::IRhoClassFactory* rho_get_RhoClassFactory()
{
    return &g_rhoClassFactory;
}

namespace rho
{
namespace common
{

net::INetRequestImpl* CRhoClassFactory::createNetRequestImpl()
{
    //return new net::CURLNetRequest();
    return new net::JNINetRequest();
}

IRhoThreadImpl *CRhoClassFactory::createThreadImpl()
{
    return new CPosixThreadImpl();
}

IRhoCrypt *CRhoClassFactory::createRhoCrypt()
{
    return new CRhoCryptImpl;
}

const ISecurityTokenGenerator* CRhoClassFactory::createSecurityTokenGenerator()
{
    static SecurityTokenGenerator global_generator;
    return &global_generator;
}

} // namespace common
} // namespace rho

<commit_msg>new property android_net_curl, by deafault 1<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include <net/CURLNetRequest.h>
#include <common/PosixThreadImpl.h>

#include "rhodes/JNINetRequest.h"
#include "rhodes/RhoClassFactory.h"
#include "rhodes/sslimpl.h"
#include "rhodes/rhocryptimpl.h"
#include "rhodes/SecurityTokenGenerator.h"

static rho::common::CRhoClassFactory g_rhoClassFactory;
rho::common::IRhoClassFactory* rho_get_RhoClassFactory()
{
    return &g_rhoClassFactory;
}

namespace rho
{
namespace common
{

net::INetRequestImpl* CRhoClassFactory::createNetRequestImpl()
{
    bool prop_exists = rho_conf_is_property_exists("android_net_curl");
    if(!prop_exists)
        rho_conf_setInt("android_net_curl", 1);

    if (rho_conf_getInt("android_net_curl"))
        return new net::CURLNetRequest();
    else
        return new net::JNINetRequest();
}

IRhoThreadImpl *CRhoClassFactory::createThreadImpl()
{
    return new CPosixThreadImpl();
}

IRhoCrypt *CRhoClassFactory::createRhoCrypt()
{
    return new CRhoCryptImpl;
}

const ISecurityTokenGenerator* CRhoClassFactory::createSecurityTokenGenerator()
{
    static SecurityTokenGenerator global_generator;
    return &global_generator;
}

} // namespace common
} // namespace rho

<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// ospcommon
#include "ospcommon/tasking/parallel_for.h"
#include "common/Data.h"
// ospray
#include "DistributedRaycast.h"
#include "../../common/DistributedModel.h"
#include "../MPILoadBalancer.h"
#include "../../fb/DistributedFrameBuffer.h"
// ispc exports
#include "DistributedRaycast_ispc.h"

namespace ospray {
  namespace mpi {

    struct RegionInfo
    {
      int currentRegion;
      bool *regionVisible;

      RegionInfo() : currentRegion(0), regionVisible(nullptr) {}
    };

    // DistributedRaycastRenderer definitions /////////////////////////////////

    DistributedRaycastRenderer::DistributedRaycastRenderer()
    {
      ispcEquivalent = ispc::DistributedRaycastRenderer_create(this);
    }

    void DistributedRaycastRenderer::commit()
    {
      Renderer::commit();
      if (!dynamic_cast<DistributedModel*>(model)) {
        throw std::runtime_error("DistributedRaycastRender must use a DistributedModel from "
                                 "the MPIDistributedDevice");
      }
    }

    float DistributedRaycastRenderer::renderFrame(FrameBuffer *fb,
                                                  const uint32 channelFlags)
    {
      using namespace mpicommon;

      auto *dfb = dynamic_cast<DistributedFrameBuffer *>(fb);
      dfb->setFrameMode(DistributedFrameBuffer::ALPHA_BLEND);
      dfb->startNewFrame(errorThreshold);
      dfb->beginFrame();

      DistributedModel *distribModel = dynamic_cast<DistributedModel*>(model);
      ispc::DistributedRaycastRenderer_setRegions(ispcEquivalent,
          (ispc::box3f*)distribModel->myRegions.data(),
          distribModel->myRegions.size(),
          (ispc::box3f*)distribModel->othersRegions.data(),
          distribModel->othersRegions.size());

      const size_t numRegions = distribModel->myRegions.size()
        + distribModel->othersRegions.size();

      beginFrame(dfb);

      tasking::parallel_for(dfb->getTotalTiles(), [&](int taskIndex) {
        const size_t numTiles_x = fb->getNumTiles().x;
        const size_t tile_y = taskIndex / numTiles_x;
        const size_t tile_x = taskIndex - tile_y*numTiles_x;
        const vec2i tileID(tile_x, tile_y);
        const int32 accumID = fb->accumID(tileID);
        const bool tileOwner = (taskIndex % numGlobalRanks()) == globalRank();

        if (dfb->tileError(tileID) <= errorThreshold) {
          return;
        }

        // The first 0..myRegions.size() - 1 entries are for my regions,
        // the following entries are for other nodes regions
        RegionInfo regionInfo;
        regionInfo.regionVisible = STACK_BUFFER(bool, numRegions);
        std::fill(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, false);

        Tile __aligned(64) tile(tileID, dfb->size, accumID);

        // We use the task of rendering the first region to also fill out the block visiblility list
        const int NUM_JOBS = (TILE_SIZE * TILE_SIZE) / RENDERTILE_PIXELS_PER_JOB;
        tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
          renderTile(&regionInfo, tile, tIdx);
        });

        if (regionInfo.regionVisible[0]) {
          tile.generation = 1;
          tile.children = 0;
          fb->setTile(tile);
        }

        // If we own the tile send the background color and the count of children for the
        // number of regions projecting to it that will be sent.
        if (tileOwner) {
          tile.generation = 0;
          tile.children = std::count(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, true);
          std::fill(tile.r, tile.r + TILE_SIZE * TILE_SIZE, bgColor.x);
          std::fill(tile.g, tile.g + TILE_SIZE * TILE_SIZE, bgColor.y);
          std::fill(tile.b, tile.b + TILE_SIZE * TILE_SIZE, bgColor.z);
          std::fill(tile.a, tile.a + TILE_SIZE * TILE_SIZE, 1.0);
          std::fill(tile.z, tile.z + TILE_SIZE * TILE_SIZE, std::numeric_limits<float>::infinity());
          fb->setTile(tile);
        }

        // Render the rest of our regions that project to this tile and ship them off
        tile.generation = 1;
        tile.children = 0;
        for (size_t bid = 1; bid < distribModel->myRegions.size(); ++bid) {
          if (!regionInfo.regionVisible[bid]) {
            continue;
          }
          regionInfo.currentRegion = bid;
          tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
            renderTile(&regionInfo, tile, tIdx);
          });
          fb->setTile(tile);
        }
      });

      dfb->waitUntilFinished();
      endFrame(nullptr, channelFlags);

      return dfb->endFrame(errorThreshold);
    }

    std::string DistributedRaycastRenderer::toString() const
    {
      return "ospray::mpi::DistributedRaycastRenderer";
    }

    OSP_REGISTER_RENDERER(DistributedRaycastRenderer, mpi_raycast);

  } // ::ospray::mpi
} // ::ospray

<commit_msg>Use the bg color opacity as well for the background tile the owner sends<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// ospcommon
#include "ospcommon/tasking/parallel_for.h"
#include "common/Data.h"
// ospray
#include "DistributedRaycast.h"
#include "../../common/DistributedModel.h"
#include "../MPILoadBalancer.h"
#include "../../fb/DistributedFrameBuffer.h"
// ispc exports
#include "DistributedRaycast_ispc.h"

namespace ospray {
  namespace mpi {

    struct RegionInfo
    {
      int currentRegion;
      bool *regionVisible;

      RegionInfo() : currentRegion(0), regionVisible(nullptr) {}
    };

    // DistributedRaycastRenderer definitions /////////////////////////////////

    DistributedRaycastRenderer::DistributedRaycastRenderer()
    {
      ispcEquivalent = ispc::DistributedRaycastRenderer_create(this);
    }

    void DistributedRaycastRenderer::commit()
    {
      Renderer::commit();
      if (!dynamic_cast<DistributedModel*>(model)) {
        throw std::runtime_error("DistributedRaycastRender must use a DistributedModel from "
                                 "the MPIDistributedDevice");
      }
    }

    float DistributedRaycastRenderer::renderFrame(FrameBuffer *fb,
                                                  const uint32 channelFlags)
    {
      using namespace mpicommon;

      auto *dfb = dynamic_cast<DistributedFrameBuffer *>(fb);
      dfb->setFrameMode(DistributedFrameBuffer::ALPHA_BLEND);
      dfb->startNewFrame(errorThreshold);
      dfb->beginFrame();

      DistributedModel *distribModel = dynamic_cast<DistributedModel*>(model);
      ispc::DistributedRaycastRenderer_setRegions(ispcEquivalent,
          (ispc::box3f*)distribModel->myRegions.data(),
          distribModel->myRegions.size(),
          (ispc::box3f*)distribModel->othersRegions.data(),
          distribModel->othersRegions.size());

      const size_t numRegions = distribModel->myRegions.size()
        + distribModel->othersRegions.size();

      beginFrame(dfb);

      tasking::parallel_for(dfb->getTotalTiles(), [&](int taskIndex) {
        const size_t numTiles_x = fb->getNumTiles().x;
        const size_t tile_y = taskIndex / numTiles_x;
        const size_t tile_x = taskIndex - tile_y*numTiles_x;
        const vec2i tileID(tile_x, tile_y);
        const int32 accumID = fb->accumID(tileID);
        const bool tileOwner = (taskIndex % numGlobalRanks()) == globalRank();

        if (dfb->tileError(tileID) <= errorThreshold) {
          return;
        }

        // The first 0..myRegions.size() - 1 entries are for my regions,
        // the following entries are for other nodes regions
        RegionInfo regionInfo;
        regionInfo.regionVisible = STACK_BUFFER(bool, numRegions);
        std::fill(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, false);

        Tile __aligned(64) tile(tileID, dfb->size, accumID);

        // We use the task of rendering the first region to also fill out the block visiblility list
        const int NUM_JOBS = (TILE_SIZE * TILE_SIZE) / RENDERTILE_PIXELS_PER_JOB;
        tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
          renderTile(&regionInfo, tile, tIdx);
        });

        if (regionInfo.regionVisible[0]) {
          tile.generation = 1;
          tile.children = 0;
          fb->setTile(tile);
        }

        // If we own the tile send the background color and the count of children for the
        // number of regions projecting to it that will be sent.
        if (tileOwner) {
          tile.generation = 0;
          tile.children = std::count(regionInfo.regionVisible, regionInfo.regionVisible + numRegions, true);
          std::fill(tile.r, tile.r + TILE_SIZE * TILE_SIZE, bgColor.x);
          std::fill(tile.g, tile.g + TILE_SIZE * TILE_SIZE, bgColor.y);
          std::fill(tile.b, tile.b + TILE_SIZE * TILE_SIZE, bgColor.z);
          std::fill(tile.a, tile.a + TILE_SIZE * TILE_SIZE, bgColor.w);
          std::fill(tile.z, tile.z + TILE_SIZE * TILE_SIZE, std::numeric_limits<float>::infinity());
          fb->setTile(tile);
        }

        // Render the rest of our regions that project to this tile and ship them off
        tile.generation = 1;
        tile.children = 0;
        for (size_t bid = 1; bid < distribModel->myRegions.size(); ++bid) {
          if (!regionInfo.regionVisible[bid]) {
            continue;
          }
          regionInfo.currentRegion = bid;
          tasking::parallel_for(NUM_JOBS, [&](int tIdx) {
            renderTile(&regionInfo, tile, tIdx);
          });
          fb->setTile(tile);
        }
      });

      dfb->waitUntilFinished();
      endFrame(nullptr, channelFlags);

      return dfb->endFrame(errorThreshold);
    }

    std::string DistributedRaycastRenderer::toString() const
    {
      return "ospray::mpi::DistributedRaycastRenderer";
    }

    OSP_REGISTER_RENDERER(DistributedRaycastRenderer, mpi_raycast);

  } // ::ospray::mpi
} // ::ospray

<|endoftext|>


<commit_before>#include "client.h"
#include "util.h"
#include <thread>
#include <sys/time.h>
#include "unistd.h"

Client::Client(const std::string id, const User* user, uint16_t keepAlive, const Will* will) : pingDulation(0), Terminal(id, user, keepAlive, will) {}

Client::~Client() {}

MQTT_ERROR Client::ping() {
    this->ct->sendMessage(new PingreqMessage());
    gettimeofday(&(this->timeOfPing), NULL);
    return NO_ERROR;
}

void pingLoop(Client* c) {
    while (c->isConnecting) {
        usleep(c->pingDulation);
        c->ct->sendMessage(new PingrespMessage());
        gettimeofday(&(c->timeOfPing), NULL);
    }
}

MQTT_ERROR Client::connect(const std::string addr, int port, bool cs) {
    if (this->ID.size() == 0 && !cs) {
        return CLEANSESSION_MUST_BE_TRUE;
        cs = true;
    }

    this->ct = new Transport(addr, port);
    this->ct->connectTarget();
    this->cleanSession = cs;
    int64_t len = this->ct->sendMessage(new ConnectMessage(this->keepAlive, this->ID, this->cleanSession, this->will, this->user));
    if (len == -1) {
        //return ; // TODO: transport error?
    }
    std::thread t(readLoop, this);
    t.join();
    this->readThread = &t;
    return NO_ERROR;
}

MQTT_ERROR Client::disconnectProcessing() {
    MQTT_ERROR err = NO_ERROR;
    if (this->isConnecting) {
        this->isConnecting = false; // this makes readLoop stop
    }
    err = this->disconnectBase();
    return err;
}

MQTT_ERROR Client::publish(const std::string topic, const std::string data, uint8_t qos, bool retain) {
    if (qos >= 3) {
        return INVALID_QOS_3;
    }
    //if ()

    uint16_t id = 0;
    if (qos > 0) {
        MQTT_ERROR err = getUsablePacketID(&id);
        if (err != NO_ERROR) {
            return err;
        }
    }
    return this->sendMessage(new PublishMessage(false, qos, retain, id, topic, data));
}

MQTT_ERROR Client::subscribe(std::vector<SubscribeTopic*> topics) {
    uint16_t id = 0;
    MQTT_ERROR err = getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i]->topic, "/", &parts);
        for (int j = 0; i < parts.size(); i++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (false) {
            } // has suffix of '#' and '+'
        }
    }
    return this->sendMessage(new SubscribeMessage(id, topics));
}

MQTT_ERROR Client::unsubscribe(std::vector<std::string> topics) {
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i], "/", &parts);
        for (int j = 0; j < parts.size(); j++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (false) {
            } // has suffix of '#' and '+'
        }
    }
    uint16_t id = 0;
    MQTT_ERROR err = this->getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    return this->sendMessage(new UnsubscribeMessage(id, topics));
}

MQTT_ERROR Client::disconnect() {
    MQTT_ERROR err = this->sendMessage(new DisconnectMessage());
    // TODO : find out how to use thread
    //std::thread t = std::thread([]{
    usleep(this->pingDulation*2);
    this->disconnectProcessing();
    //});
    return err;
}

MQTT_ERROR Client::recvConnectMessage(ConnectMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvConnackMessage(ConnackMessage* m) {
    if (m->returnCode != CONNECT_ACCEPTED) {
        //return m->ReturnCode;
    }

    this->isConnecting = true;
    if (this->keepAlive != 0) {
        std::thread t(pingLoop, this);
        t.join();
    }

    return this->redelivery();
}

MQTT_ERROR Client::recvPublishMessage(PublishMessage* m) {
    if (m->fh->dup) {
        // re-delivered;
    } else {
        // first time delivery
    }

    if (m->fh->retain) {
        // retained Message
    }

    switch (m->fh->qos) {
    case 0:
        if (m->fh->packetID != 0) {
            return PACKET_ID_SHOULD_BE_ZERO; // packet id should be zero
        }
    case 1:
        return this->sendMessage(new PubackMessage(m->fh->packetID));
    case 2:
        return this->sendMessage(new PubrecMessage(m->fh->packetID));
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubackMessage(PubackMessage* m) {
    if (m->fh->packetID > 0) {
        return this->ackMessage(m->fh->packetID);
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubrecMessage(PubrecMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubrelMessage(m->fh->packetID));
    return err;
}
MQTT_ERROR Client::recvPubrelMessage(PubrelMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubcompMessage(m->fh->packetID));
    return err;
}

MQTT_ERROR Client::recvPubcompMessage(PubcompMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvSubscribeMessage(SubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvSubackMessage(SubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvUnsubscribeMessage(UnsubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvUnsubackMessage(UnsubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvPingreqMessage(PingreqMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvPingrespMessage(PingrespMessage* m) {
    // TODO: implement duration base connection management
    struct timeval tmp;
    gettimeofday(&tmp, NULL);
    this->pingDulation = (tmp.tv_sec - this->timeOfPing.tv_sec)*1000000 + (tmp.tv_usec - this->timeOfPing.tv_usec);
    if (this->pingDulation >= this->keepAlive) {
        this->sendMessage(new DisconnectMessage());
        return SERVER_TIMED_OUT;
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvDisconnectMessage(DisconnectMessage* m) {return INVALID_MESSAGE_CAME;}

<commit_msg>add condition<commit_after>#include "client.h"
#include "util.h"
#include <thread>
#include <sys/time.h>
#include "unistd.h"

Client::Client(const std::string id, const User* user, uint16_t keepAlive, const Will* will) : pingDulation(0), Terminal(id, user, keepAlive, will) {}

Client::~Client() {}

MQTT_ERROR Client::ping() {
    this->ct->sendMessage(new PingreqMessage());
    gettimeofday(&(this->timeOfPing), NULL);
    return NO_ERROR;
}

void pingLoop(Client* c) {
    while (c->isConnecting) {
        usleep(c->pingDulation);
        c->ct->sendMessage(new PingrespMessage());
        gettimeofday(&(c->timeOfPing), NULL);
    }
}

MQTT_ERROR Client::connect(const std::string addr, int port, bool cs) {
    if (this->ID.size() == 0 && !cs) {
        return CLEANSESSION_MUST_BE_TRUE;
        cs = true;
    }

    this->ct = new Transport(addr, port);
    this->ct->connectTarget();
    this->cleanSession = cs;
    int64_t len = this->ct->sendMessage(new ConnectMessage(this->keepAlive, this->ID, this->cleanSession, this->will, this->user));
    if (len == -1) {
        //return ; // TODO: transport error?
    }
    std::thread t(readLoop, this);
    t.join();
    this->readThread = &t;
    return NO_ERROR;
}

MQTT_ERROR Client::disconnectProcessing() {
    MQTT_ERROR err = NO_ERROR;
    if (this->isConnecting) {
        this->isConnecting = false; // this makes readLoop stop
    }
    err = this->disconnectBase();
    return err;
}

MQTT_ERROR Client::publish(const std::string topic, const std::string data, uint8_t qos, bool retain) {
    if (qos >= 3) {
        return INVALID_QOS_3;
    }
    //if ()

    uint16_t id = 0;
    if (qos > 0) {
        MQTT_ERROR err = getUsablePacketID(&id);
        if (err != NO_ERROR) {
            return err;
        }
    }
    return this->sendMessage(new PublishMessage(false, qos, retain, id, topic, data));
}

MQTT_ERROR Client::subscribe(std::vector<SubscribeTopic*> topics) {
    uint16_t id = 0;
    MQTT_ERROR err = getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i]->topic, "/", &parts);
        for (int j = 0; i < parts.size(); i++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (false) {
            } // has suffix of '#' and '+'
        }
    }
    return this->sendMessage(new SubscribeMessage(id, topics));
}

MQTT_ERROR Client::unsubscribe(std::vector<std::string> topics) {
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i], "/", &parts);
        for (int j = 0; j < parts.size(); j++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (parts[j][parts[j].size()-1] == '#' || parts[j][parts[j].size()-1] == '+') {
                return WILDCARD_MUST_NOT_BE_ADJACENT_TO_NAME;
            }
        }
    }
    uint16_t id = 0;
    MQTT_ERROR err = this->getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    return this->sendMessage(new UnsubscribeMessage(id, topics));
}

MQTT_ERROR Client::disconnect() {
    MQTT_ERROR err = this->sendMessage(new DisconnectMessage());
    // TODO : find out how to use thread
    //std::thread t = std::thread([]{
    usleep(this->pingDulation*2);
    this->disconnectProcessing();
    //});
    return err;
}

MQTT_ERROR Client::recvConnectMessage(ConnectMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvConnackMessage(ConnackMessage* m) {
    if (m->returnCode != CONNECT_ACCEPTED) {
        //return m->ReturnCode;
    }

    this->isConnecting = true;
    if (this->keepAlive != 0) {
        std::thread t(pingLoop, this);
        t.join();
    }

    return this->redelivery();
}

MQTT_ERROR Client::recvPublishMessage(PublishMessage* m) {
    if (m->fh->dup) {
        // re-delivered;
    } else {
        // first time delivery
    }

    if (m->fh->retain) {
        // retained Message
    }

    switch (m->fh->qos) {
    case 0:
        if (m->fh->packetID != 0) {
            return PACKET_ID_SHOULD_BE_ZERO; // packet id should be zero
        }
    case 1:
        return this->sendMessage(new PubackMessage(m->fh->packetID));
    case 2:
        return this->sendMessage(new PubrecMessage(m->fh->packetID));
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubackMessage(PubackMessage* m) {
    if (m->fh->packetID > 0) {
        return this->ackMessage(m->fh->packetID);
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubrecMessage(PubrecMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubrelMessage(m->fh->packetID));
    return err;
}
MQTT_ERROR Client::recvPubrelMessage(PubrelMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubcompMessage(m->fh->packetID));
    return err;
}

MQTT_ERROR Client::recvPubcompMessage(PubcompMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvSubscribeMessage(SubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvSubackMessage(SubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvUnsubscribeMessage(UnsubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvUnsubackMessage(UnsubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvPingreqMessage(PingreqMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvPingrespMessage(PingrespMessage* m) {
    // TODO: implement duration base connection management
    struct timeval tmp;
    gettimeofday(&tmp, NULL);
    this->pingDulation = (tmp.tv_sec - this->timeOfPing.tv_sec)*1000000 + (tmp.tv_usec - this->timeOfPing.tv_usec);
    if (this->pingDulation >= this->keepAlive) {
        this->sendMessage(new DisconnectMessage());
        return SERVER_TIMED_OUT;
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvDisconnectMessage(DisconnectMessage* m) {return INVALID_MESSAGE_CAME;}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Staikos Computing Services Inc. <info@staikos.net>
 * Copyright (C) 2007 Trolltech ASA
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "PlatformScrollBar.h"

#include "EventHandler.h"
#include "FrameView.h"
#include "Frame.h"
#include "GraphicsContext.h"
#include "IntRect.h"
#include "PlatformMouseEvent.h"
#include "ScrollbarTheme.h"

#include <QApplication>
#include <QDebug>
#include <QPainter>
#include <QStyle>
#include <QMenu>

using namespace std;

static QString tr(const char* text)
{
    return QCoreApplication::translate("QWebPage", text);
}

namespace WebCore {

PlatformScrollbar::PlatformScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize size
    : Scrollbar(client, orientation, size)
{
}

bool PlatformScrollbar::handleContextMenuEvent(const PlatformMouseEvent& event)
{
#ifndef QT_NO_CONTEXTMENU
    bool horizontal = (m_orientation == HorizontalScrollbar);

    QMenu menu;
    QAction* actScrollHere = menu.addAction(tr("Scroll here"));
    menu.addSeparator();

    QAction* actScrollTop = menu.addAction(horizontal ? tr("Left edge") : tr("Top"));
    QAction* actScrollBottom = menu.addAction(horizontal ? tr("Right edge") : tr("Bottom"));
    menu.addSeparator();

    QAction* actPageUp = menu.addAction(horizontal ? tr("Page left") : tr("Page up"));
    QAction* actPageDown = menu.addAction(horizontal ? tr("Page right") : tr("Page down"));
    menu.addSeparator();

    QAction* actScrollUp = menu.addAction(horizontal ? tr("Scroll left") : tr("Scroll up"));
    QAction* actScrollDown = menu.addAction(horizontal ? tr("Scroll right") : tr("Scroll down"));

    const QPoint globalPos = QPoint(event.globalX(), event.globalY());
    QAction* actionSelected = menu.exec(globalPos);

    if (actionSelected == 0)
        /* Do nothing */ ;
    else if (actionSelected == actScrollHere) {
        const QPoint pos = convertFromContainingWindow(event.pos());
        setValue(pixelPosToRangeValue(horizontal ? pos.x() : pos.y()));
    } else if (actionSelected == actScrollTop)
        setValue(0);
    else if (actionSelected == actScrollBottom)
        setValue(m_totalSize - m_visibleSize);
    else if (actionSelected == actPageUp)
        scroll(horizontal ? ScrollLeft: ScrollUp, ScrollByPage, 1);
    else if (actionSelected == actPageDown)
        scroll(horizontal ? ScrollRight : ScrollDown, ScrollByPage, 1);
    else if (actionSelected == actScrollUp)
        scroll(horizontal ? ScrollLeft : ScrollUp, ScrollByLine, 1);
    else if (actionSelected == actScrollDown)
        scroll(horizontal ? ScrollRight : ScrollDown, ScrollByLine, 1);
#endif // QT_NO_CONTEXTMENU
    return true;
}

void PlatformScrollbar::invalidate()
{
    // Get the root widget.
    ScrollView* outermostView = topLevel();
    if (!outermostView)
        return;
    IntRect windowRect = convertToContainingWindow(IntRect(0, 0, width(), height()));
    outermostView->addToDirtyRegion(windowRect);
}

}

// vim: ts=4 sw=4 et
<commit_msg>Fix Qt build bustage in PlatformScrollbarQt.cpp<commit_after>/*
 * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Staikos Computing Services Inc. <info@staikos.net>
 * Copyright (C) 2007 Trolltech ASA
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "PlatformScrollBar.h"

#include "EventHandler.h"
#include "FrameView.h"
#include "Frame.h"
#include "GraphicsContext.h"
#include "IntRect.h"
#include "PlatformMouseEvent.h"
#include "ScrollbarTheme.h"

#include <QApplication>
#include <QDebug>
#include <QPainter>
#include <QStyle>
#include <QMenu>

using namespace std;

static QString tr(const char* text)
{
    return QCoreApplication::translate("QWebPage", text);
}

namespace WebCore {

PlatformScrollbar::PlatformScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize size)
    : Scrollbar(client, orientation, size)
{
}

bool PlatformScrollbar::handleContextMenuEvent(const PlatformMouseEvent& event)
{
#ifndef QT_NO_CONTEXTMENU
    bool horizontal = (m_orientation == HorizontalScrollbar);

    QMenu menu;
    QAction* actScrollHere = menu.addAction(tr("Scroll here"));
    menu.addSeparator();

    QAction* actScrollTop = menu.addAction(horizontal ? tr("Left edge") : tr("Top"));
    QAction* actScrollBottom = menu.addAction(horizontal ? tr("Right edge") : tr("Bottom"));
    menu.addSeparator();

    QAction* actPageUp = menu.addAction(horizontal ? tr("Page left") : tr("Page up"));
    QAction* actPageDown = menu.addAction(horizontal ? tr("Page right") : tr("Page down"));
    menu.addSeparator();

    QAction* actScrollUp = menu.addAction(horizontal ? tr("Scroll left") : tr("Scroll up"));
    QAction* actScrollDown = menu.addAction(horizontal ? tr("Scroll right") : tr("Scroll down"));

    const QPoint globalPos = QPoint(event.globalX(), event.globalY());
    QAction* actionSelected = menu.exec(globalPos);

    if (actionSelected == 0)
        /* Do nothing */ ;
    else if (actionSelected == actScrollHere) {
        const QPoint pos = convertFromContainingWindow(event.pos());
        setValue(pixelPosToRangeValue(horizontal ? pos.x() : pos.y()));
    } else if (actionSelected == actScrollTop)
        setValue(0);
    else if (actionSelected == actScrollBottom)
        setValue(m_totalSize - m_visibleSize);
    else if (actionSelected == actPageUp)
        scroll(horizontal ? ScrollLeft: ScrollUp, ScrollByPage, 1);
    else if (actionSelected == actPageDown)
        scroll(horizontal ? ScrollRight : ScrollDown, ScrollByPage, 1);
    else if (actionSelected == actScrollUp)
        scroll(horizontal ? ScrollLeft : ScrollUp, ScrollByLine, 1);
    else if (actionSelected == actScrollDown)
        scroll(horizontal ? ScrollRight : ScrollDown, ScrollByLine, 1);
#endif // QT_NO_CONTEXTMENU
    return true;
}

void PlatformScrollbar::invalidate()
{
    // Get the root widget.
    ScrollView* outermostView = topLevel();
    if (!outermostView)
        return;
    IntRect windowRect = convertToContainingWindow(IntRect(0, 0, width(), height()));
    outermostView->addToDirtyRegion(windowRect);
}

}

// vim: ts=4 sw=4 et
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formattributes.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:14:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_FORMATTRIBUTES_HXX_
#include "formattributes.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;

    //=====================================================================
    //= OAttributeMetaData
    //=====================================================================
    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getCommonControlAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case CCA_NAME:              return "name";
            case CCA_SERVICE_NAME:      return "control-implementation";
            case CCA_BUTTON_TYPE:       return "button-type";
            case CCA_CONTROL_ID:        return "id";
            case CCA_CURRENT_SELECTED:  return "current-selected";
            case CCA_CURRENT_VALUE:     return "current-value";
            case CCA_DISABLED:          return "disabled";
            case CCA_DROPDOWN:          return "dropdown";
            case CCA_FOR:               return "for";
            case CCA_IMAGE_DATA:        return "image-data";
            case CCA_LABEL:             return "label";
            case CCA_MAX_LENGTH:        return "max-length";
            case CCA_PRINTABLE:         return "printable";
            case CCA_READONLY:          return "readonly";
            case CCA_SELECTED:          return "selected";
            case CCA_SIZE:              return "size";
            case CCA_TAB_INDEX:         return "tab-index";
            case CCA_TARGET_FRAME:      return "target-frame";
            case CCA_TARGET_LOCATION:   return "href";      // the only special thing here: TargetLocation is represented by an xlink:href attribute
            case CCA_TAB_STOP:          return "tab-stop";
            case CCA_TITLE:             return "title";
            case CCA_VALUE:             return "value";
            case CCA_ORIENTATION:       return "orientation";
            case CCA_VISUAL_EFFECT:     return "visual-effect";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getCommonControlAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getCommonControlAttributeNamespace(sal_Int32 _nId)
    {
        if (CCA_TARGET_LOCATION == _nId)
            return XML_NAMESPACE_XLINK;

        if (CCA_TARGET_FRAME == _nId)
            return XML_NAMESPACE_OFFICE;

        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getFormAttributeName(FormAttributes _eAttrib)
    {
        switch (_eAttrib)
        {
            case faName:                return "name";
            case faServiceName:         return "service-name";
            case faAction:              return "href";      // the only special thing here: Action is represented by an xlink:href attribute
            case faEnctype:             return "enctype";
            case faMethod:              return "method";
            case faTargetFrame:         return "target-frame";
            case faAllowDeletes:        return "allow-deletes";
            case faAllowInserts:        return "allow-inserts";
            case faAllowUpdates:        return "allow-updates";
            case faApplyFilter:         return "apply-filter";
            case faCommand:             return "command";
            case faCommandType:         return "command-type";
            case faEscapeProcessing:    return "escape-processing";
            case faDatasource:          return "datasource";
            case faConnectionResource:  return "connection-resource";
            case faDetailFiels:         return "detail-fields";
            case faFilter:              return "filter";
            case faIgnoreResult:        return "ignore-result";
            case faMasterFields:        return "master-fields";
            case faNavigationMode:      return "navigation-mode";
            case faOrder:               return "order";
            case faTabbingCycle:        return "tab-cycle";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getFormAttributeName: invalid id!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getFormAttributeNamespace(FormAttributes _eAttrib)
    {
        if (faAction == _eAttrib)
            return XML_NAMESPACE_XLINK;

        if (faTargetFrame == _eAttrib)
            return XML_NAMESPACE_OFFICE;

        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getDatabaseAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case DA_BOUND_COLUMN:       return "bound-column";
            case DA_CONVERT_EMPTY:      return "convert-empty-to-null";
            case DA_DATA_FIELD:         return "data-field";
            case DA_LIST_SOURCE:        return "list-source";
            case DA_LIST_SOURCE_TYPE:   return "list-source-type";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getDatabaseAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getDatabaseAttributeNamespace(sal_Int32 /*_nId*/)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getBindingAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case BA_LINKED_CELL:       return "linked-cell";
            case BA_LIST_LINKING_TYPE: return "list-linkage-type";
            case BA_LIST_CELL_RANGE:   return "source-cell-range";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getBindingAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getBindingAttributeNamespace(sal_Int32)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getSpecialAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case SCA_ECHO_CHAR:             return "echo-char";
            case SCA_MAX_VALUE:             return "max-value";
            case SCA_MIN_VALUE:             return "min-value";
            case SCA_VALIDATION:            return "validation";
            case SCA_MULTI_LINE:            return "multi-line";
            case SCA_AUTOMATIC_COMPLETION:  return "auto-complete";
            case SCA_MULTIPLE:              return "multiple";
            case SCA_DEFAULT_BUTTON:        return "default-button";
            case SCA_CURRENT_STATE:         return "current-state";
            case SCA_IS_TRISTATE:           return "is-tristate";
            case SCA_STATE:                 return "state";
            case SCA_COLUMN_STYLE_NAME:     return "text-style-name";
            case SCA_STEP_SIZE:             return "step-size";
            case SCA_PAGE_STEP_SIZE:        return "page-step-size";
            case SCA_REPEAT_DELAY:          return "delay-for-repeat";
            case SCA_TOGGLE:                return "toggle";
            case SCA_FOCUS_ON_CLICK:        return "focus-on-click";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getSpecialAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getSpecialAttributeNamespace(sal_Int32 /*_nId*/)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getOfficeFormsAttributeName(OfficeFormsAttributes _eAttrib)
    {
        switch (_eAttrib)
        {
            case ofaAutomaticFocus:     return "automatic-focus";
            case ofaApplyDesignMode:    return "apply-design-mode";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getOfficeFormsAttributeName: invalid id!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getOfficeFormsAttributeNamespace(OfficeFormsAttributes /* _eAttrib */)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //=====================================================================
    //= OAttribute2Property
    //=====================================================================
    //---------------------------------------------------------------------
    OAttribute2Property::OAttribute2Property()
    {
    }

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

    //---------------------------------------------------------------------
    const OAttribute2Property::AttributeAssignment* OAttribute2Property::getAttributeTranslation(
            const ::rtl::OUString& _rAttribName)
    {
        ConstAttributeAssignmentsIterator aPos = m_aKnownProperties.find(_rAttribName);
        if (m_aKnownProperties.end() != aPos)
            return &aPos->second;
        return NULL;
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addStringProperty(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Char* _pAttributeDefault)
    {
        implAdd(_pAttributeName, _rPropertyName, ::getCppuType( static_cast< ::rtl::OUString* >(NULL) ),
            _pAttributeDefault ? ::rtl::OUString::createFromAscii(_pAttributeDefault) : ::rtl::OUString());
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addBooleanProperty(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Bool _bAttributeDefault, const sal_Bool _bInverseSemantics)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertBool(aDefault, _bAttributeDefault);
        AttributeAssignment& aAssignment = implAdd(_pAttributeName, _rPropertyName, ::getBooleanCppuType(), aDefault.makeStringAndClear());
        aAssignment.bInverseSemantics = _bInverseSemantics;
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addInt16Property(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Int16 _nAttributeDefault)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertNumber(aDefault, (sal_Int32)_nAttributeDefault);
        implAdd(_pAttributeName, _rPropertyName, ::getCppuType( static_cast< sal_Int16* >(NULL) ), aDefault.makeStringAndClear());
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addInt32Property(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Int32 _nAttributeDefault)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertNumber( aDefault, _nAttributeDefault );
        implAdd( _pAttributeName, _rPropertyName, ::getCppuType( static_cast< sal_Int32* >(NULL) ), aDefault.makeStringAndClear() );
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addEnumProperty(
            const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
            const sal_uInt16 _nAttributeDefault, const SvXMLEnumMapEntry* _pValueMap,
            const ::com::sun::star::uno::Type* _pType)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertEnum(aDefault, _nAttributeDefault, _pValueMap);
        AttributeAssignment& aAssignment = implAdd(_pAttributeName, _rPropertyName,
            _pType ? *_pType : ::getCppuType( static_cast< sal_Int32* >(NULL) ),
                // this assumes that the setPropertyValue for enums can handle int32's ....
            aDefault.makeStringAndClear());
        aAssignment.pEnumMap = _pValueMap;
    }

    //---------------------------------------------------------------------
    OAttribute2Property::AttributeAssignment& OAttribute2Property::implAdd(
            const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
            const ::com::sun::star::uno::Type& _rType, const ::rtl::OUString& /*_rDefaultString*/)
    {
        OSL_ENSURE(m_aKnownProperties.end() == m_aKnownProperties.find(::rtl::OUString::createFromAscii(_pAttributeName)),
            "OAttribute2Property::implAdd: already have this attribute!");

        ::rtl::OUString sAttributeName = ::rtl::OUString::createFromAscii(_pAttributeName);

        AttributeAssignment aAssignment;
        aAssignment.sAttributeName = sAttributeName;
        aAssignment.sPropertyName = _rPropertyName;
        aAssignment.aPropertyType = _rType;

        // redundance, the accessor is stored in aAssignment.sAttributeName, too
        return m_aKnownProperties[sAttributeName] = aAssignment;
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.20.162); FILE MERGED 2008/04/01 16:09:46 thb 1.20.162.3: #i85898# Stripping all external header guards 2008/04/01 13:04:50 thb 1.20.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:12 rt 1.20.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: formattributes.cxx,v $
 * $Revision: 1.21 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "formattributes.hxx"
#include "xmlnmspe.hxx"
#include <xmloff/xmluconv.hxx>
#include <rtl/ustrbuf.hxx>

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;

    //=====================================================================
    //= OAttributeMetaData
    //=====================================================================
    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getCommonControlAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case CCA_NAME:              return "name";
            case CCA_SERVICE_NAME:      return "control-implementation";
            case CCA_BUTTON_TYPE:       return "button-type";
            case CCA_CONTROL_ID:        return "id";
            case CCA_CURRENT_SELECTED:  return "current-selected";
            case CCA_CURRENT_VALUE:     return "current-value";
            case CCA_DISABLED:          return "disabled";
            case CCA_DROPDOWN:          return "dropdown";
            case CCA_FOR:               return "for";
            case CCA_IMAGE_DATA:        return "image-data";
            case CCA_LABEL:             return "label";
            case CCA_MAX_LENGTH:        return "max-length";
            case CCA_PRINTABLE:         return "printable";
            case CCA_READONLY:          return "readonly";
            case CCA_SELECTED:          return "selected";
            case CCA_SIZE:              return "size";
            case CCA_TAB_INDEX:         return "tab-index";
            case CCA_TARGET_FRAME:      return "target-frame";
            case CCA_TARGET_LOCATION:   return "href";      // the only special thing here: TargetLocation is represented by an xlink:href attribute
            case CCA_TAB_STOP:          return "tab-stop";
            case CCA_TITLE:             return "title";
            case CCA_VALUE:             return "value";
            case CCA_ORIENTATION:       return "orientation";
            case CCA_VISUAL_EFFECT:     return "visual-effect";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getCommonControlAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getCommonControlAttributeNamespace(sal_Int32 _nId)
    {
        if (CCA_TARGET_LOCATION == _nId)
            return XML_NAMESPACE_XLINK;

        if (CCA_TARGET_FRAME == _nId)
            return XML_NAMESPACE_OFFICE;

        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getFormAttributeName(FormAttributes _eAttrib)
    {
        switch (_eAttrib)
        {
            case faName:                return "name";
            case faServiceName:         return "service-name";
            case faAction:              return "href";      // the only special thing here: Action is represented by an xlink:href attribute
            case faEnctype:             return "enctype";
            case faMethod:              return "method";
            case faTargetFrame:         return "target-frame";
            case faAllowDeletes:        return "allow-deletes";
            case faAllowInserts:        return "allow-inserts";
            case faAllowUpdates:        return "allow-updates";
            case faApplyFilter:         return "apply-filter";
            case faCommand:             return "command";
            case faCommandType:         return "command-type";
            case faEscapeProcessing:    return "escape-processing";
            case faDatasource:          return "datasource";
            case faConnectionResource:  return "connection-resource";
            case faDetailFiels:         return "detail-fields";
            case faFilter:              return "filter";
            case faIgnoreResult:        return "ignore-result";
            case faMasterFields:        return "master-fields";
            case faNavigationMode:      return "navigation-mode";
            case faOrder:               return "order";
            case faTabbingCycle:        return "tab-cycle";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getFormAttributeName: invalid id!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getFormAttributeNamespace(FormAttributes _eAttrib)
    {
        if (faAction == _eAttrib)
            return XML_NAMESPACE_XLINK;

        if (faTargetFrame == _eAttrib)
            return XML_NAMESPACE_OFFICE;

        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getDatabaseAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case DA_BOUND_COLUMN:       return "bound-column";
            case DA_CONVERT_EMPTY:      return "convert-empty-to-null";
            case DA_DATA_FIELD:         return "data-field";
            case DA_LIST_SOURCE:        return "list-source";
            case DA_LIST_SOURCE_TYPE:   return "list-source-type";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getDatabaseAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getDatabaseAttributeNamespace(sal_Int32 /*_nId*/)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getBindingAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case BA_LINKED_CELL:       return "linked-cell";
            case BA_LIST_LINKING_TYPE: return "list-linkage-type";
            case BA_LIST_CELL_RANGE:   return "source-cell-range";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getBindingAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getBindingAttributeNamespace(sal_Int32)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getSpecialAttributeName(sal_Int32 _nId)
    {
        switch (_nId)
        {
            case SCA_ECHO_CHAR:             return "echo-char";
            case SCA_MAX_VALUE:             return "max-value";
            case SCA_MIN_VALUE:             return "min-value";
            case SCA_VALIDATION:            return "validation";
            case SCA_MULTI_LINE:            return "multi-line";
            case SCA_AUTOMATIC_COMPLETION:  return "auto-complete";
            case SCA_MULTIPLE:              return "multiple";
            case SCA_DEFAULT_BUTTON:        return "default-button";
            case SCA_CURRENT_STATE:         return "current-state";
            case SCA_IS_TRISTATE:           return "is-tristate";
            case SCA_STATE:                 return "state";
            case SCA_COLUMN_STYLE_NAME:     return "text-style-name";
            case SCA_STEP_SIZE:             return "step-size";
            case SCA_PAGE_STEP_SIZE:        return "page-step-size";
            case SCA_REPEAT_DELAY:          return "delay-for-repeat";
            case SCA_TOGGLE:                return "toggle";
            case SCA_FOCUS_ON_CLICK:        return "focus-on-click";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getSpecialAttributeName: invalid id (maybe you or-ed two flags?)!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getSpecialAttributeNamespace(sal_Int32 /*_nId*/)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //---------------------------------------------------------------------
    const sal_Char* OAttributeMetaData::getOfficeFormsAttributeName(OfficeFormsAttributes _eAttrib)
    {
        switch (_eAttrib)
        {
            case ofaAutomaticFocus:     return "automatic-focus";
            case ofaApplyDesignMode:    return "apply-design-mode";
            default:
                OSL_ENSURE(sal_False, "OAttributeMetaData::getOfficeFormsAttributeName: invalid id!");
        }
        return "";
    }

    //---------------------------------------------------------------------
    sal_uInt16 OAttributeMetaData::getOfficeFormsAttributeNamespace(OfficeFormsAttributes /* _eAttrib */)
    {
        // nothing special here
        return XML_NAMESPACE_FORM;
    }

    //=====================================================================
    //= OAttribute2Property
    //=====================================================================
    //---------------------------------------------------------------------
    OAttribute2Property::OAttribute2Property()
    {
    }

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

    //---------------------------------------------------------------------
    const OAttribute2Property::AttributeAssignment* OAttribute2Property::getAttributeTranslation(
            const ::rtl::OUString& _rAttribName)
    {
        ConstAttributeAssignmentsIterator aPos = m_aKnownProperties.find(_rAttribName);
        if (m_aKnownProperties.end() != aPos)
            return &aPos->second;
        return NULL;
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addStringProperty(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Char* _pAttributeDefault)
    {
        implAdd(_pAttributeName, _rPropertyName, ::getCppuType( static_cast< ::rtl::OUString* >(NULL) ),
            _pAttributeDefault ? ::rtl::OUString::createFromAscii(_pAttributeDefault) : ::rtl::OUString());
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addBooleanProperty(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Bool _bAttributeDefault, const sal_Bool _bInverseSemantics)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertBool(aDefault, _bAttributeDefault);
        AttributeAssignment& aAssignment = implAdd(_pAttributeName, _rPropertyName, ::getBooleanCppuType(), aDefault.makeStringAndClear());
        aAssignment.bInverseSemantics = _bInverseSemantics;
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addInt16Property(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Int16 _nAttributeDefault)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertNumber(aDefault, (sal_Int32)_nAttributeDefault);
        implAdd(_pAttributeName, _rPropertyName, ::getCppuType( static_cast< sal_Int16* >(NULL) ), aDefault.makeStringAndClear());
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addInt32Property(
        const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
        const sal_Int32 _nAttributeDefault)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertNumber( aDefault, _nAttributeDefault );
        implAdd( _pAttributeName, _rPropertyName, ::getCppuType( static_cast< sal_Int32* >(NULL) ), aDefault.makeStringAndClear() );
    }

    //---------------------------------------------------------------------
    void OAttribute2Property::addEnumProperty(
            const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
            const sal_uInt16 _nAttributeDefault, const SvXMLEnumMapEntry* _pValueMap,
            const ::com::sun::star::uno::Type* _pType)
    {
        ::rtl::OUStringBuffer aDefault;
        SvXMLUnitConverter::convertEnum(aDefault, _nAttributeDefault, _pValueMap);
        AttributeAssignment& aAssignment = implAdd(_pAttributeName, _rPropertyName,
            _pType ? *_pType : ::getCppuType( static_cast< sal_Int32* >(NULL) ),
                // this assumes that the setPropertyValue for enums can handle int32's ....
            aDefault.makeStringAndClear());
        aAssignment.pEnumMap = _pValueMap;
    }

    //---------------------------------------------------------------------
    OAttribute2Property::AttributeAssignment& OAttribute2Property::implAdd(
            const sal_Char* _pAttributeName, const ::rtl::OUString& _rPropertyName,
            const ::com::sun::star::uno::Type& _rType, const ::rtl::OUString& /*_rDefaultString*/)
    {
        OSL_ENSURE(m_aKnownProperties.end() == m_aKnownProperties.find(::rtl::OUString::createFromAscii(_pAttributeName)),
            "OAttribute2Property::implAdd: already have this attribute!");

        ::rtl::OUString sAttributeName = ::rtl::OUString::createFromAscii(_pAttributeName);

        AttributeAssignment aAssignment;
        aAssignment.sAttributeName = sAttributeName;
        aAssignment.sPropertyName = _rPropertyName;
        aAssignment.aPropertyType = _rType;

        // redundance, the accessor is stored in aAssignment.sAttributeName, too
        return m_aKnownProperties[sAttributeName] = aAssignment;
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

<|endoftext|>


<commit_before>/*
* MPI Add, Subtract, Word Multiply
* (C) 1999-2010,2016 Jack Lloyd
*     2006 Luca Piccarreta
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/mp_core.h>
#include <botan/internal/mp_asmi.h>
#include <botan/internal/ct_utils.h>
#include <botan/exceptn.h>
#include <botan/mem_ops.h>

namespace Botan {

/*
* If cond == 0, does nothing.
* If cond > 0, swaps x[0:size] with y[0:size]
* Runs in constant time
*/
void bigint_cnd_swap(word cnd, word x[], word y[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   for(size_t i = 0; i != size; ++i)
      {
      word a = x[i];
      word b = y[i];
      x[i] = CT::select(mask, b, a);
      y[i] = CT::select(mask, a, b);
      }
   }

/*
* If cond > 0 adds x[0:size] to y[0:size] and returns carry
* Runs in constant time
*/
word bigint_cnd_add(word cnd, word x[], const word y[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   word carry = 0;
   for(size_t i = 0; i != size; ++i)
      {
      /*
      Here we are relying on asm version of word_add being
      a single addcl or equivalent. Fix this.
      */
      const word z = word_add(x[i], y[i], &carry);
      x[i] = CT::select(mask, z, x[i]);
      }

   return carry & mask;
   }

/*
* If cond > 0 subs x[0:size] to y[0:size] and returns borrow
* Runs in constant time
*/
word bigint_cnd_sub(word cnd, word x[], const word y[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   word carry = 0;
   for(size_t i = 0; i != size; ++i)
      {
      const word z = word_sub(x[i], y[i], &carry);
      x[i] = CT::select(mask, z, x[i]);
      }

   return carry & mask;
   }

void bigint_cnd_abs(word cnd, word x[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   word carry = mask & 1;
   for(size_t i = 0; i != size; ++i)
      {
      const word z = word_add(~x[i], 0, &carry);
      x[i] = CT::select(mask, z, x[i]);
      }
   }

/*
* Two Operand Addition, No Carry
*/
word bigint_add2_nc(word x[], size_t x_size, const word y[], size_t y_size)
   {
   word carry = 0;

   BOTAN_ASSERT(x_size >= y_size, "Expected sizes");

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_add2(x + i, y + i, carry);

   for(size_t i = blocks; i != y_size; ++i)
      x[i] = word_add(x[i], y[i], &carry);

   for(size_t i = y_size; i != x_size; ++i)
      x[i] = word_add(x[i], 0, &carry);

   return carry;
   }

/*
* Three Operand Addition, No Carry
*/
word bigint_add3_nc(word z[], const word x[], size_t x_size,
                              const word y[], size_t y_size)
   {
   if(x_size < y_size)
      { return bigint_add3_nc(z, y, y_size, x, x_size); }

   word carry = 0;

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_add3(z + i, x + i, y + i, carry);

   for(size_t i = blocks; i != y_size; ++i)
      z[i] = word_add(x[i], y[i], &carry);

   for(size_t i = y_size; i != x_size; ++i)
      z[i] = word_add(x[i], 0, &carry);

   return carry;
   }

/*
* Two Operand Addition
*/
void bigint_add2(word x[], size_t x_size, const word y[], size_t y_size)
   {
   if(bigint_add2_nc(x, x_size, y, y_size))
      x[x_size] += 1;
   }

/*
* Three Operand Addition
*/
void bigint_add3(word z[], const word x[], size_t x_size,
                           const word y[], size_t y_size)
   {
   z[(x_size > y_size ? x_size : y_size)] +=
      bigint_add3_nc(z, x, x_size, y, y_size);
   }

/*
* Two Operand Subtraction
*/
word bigint_sub2(word x[], size_t x_size, const word y[], size_t y_size)
   {
   word borrow = 0;

   BOTAN_ASSERT(x_size >= y_size, "Expected sizes");

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      borrow = word8_sub2(x + i, y + i, borrow);

   for(size_t i = blocks; i != y_size; ++i)
      x[i] = word_sub(x[i], y[i], &borrow);

   for(size_t i = y_size; i != x_size; ++i)
      x[i] = word_sub(x[i], 0, &borrow);

   return borrow;
   }

/*
* Two Operand Subtraction x = y - x
*/
void bigint_sub2_rev(word x[],  const word y[], size_t y_size)
   {
   word borrow = 0;

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      borrow = word8_sub2_rev(x + i, y + i, borrow);

   for(size_t i = blocks; i != y_size; ++i)
      x[i] = word_sub(y[i], x[i], &borrow);

   BOTAN_ASSERT(!borrow, "y must be greater than x");
   }

/*
* Three Operand Subtraction
*/
word bigint_sub3(word z[], const word x[], size_t x_size,
                           const word y[], size_t y_size)
   {
   word borrow = 0;

   BOTAN_ASSERT(x_size >= y_size, "Expected sizes");

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      borrow = word8_sub3(z + i, x + i, y + i, borrow);

   for(size_t i = blocks; i != y_size; ++i)
      z[i] = word_sub(x[i], y[i], &borrow);

   for(size_t i = y_size; i != x_size; ++i)
      z[i] = word_sub(x[i], 0, &borrow);

   return borrow;
   }

/*
* Two Operand Linear Multiply
*/
void bigint_linmul2(word x[], size_t x_size, word y)
   {
   const size_t blocks = x_size - (x_size % 8);

   word carry = 0;

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_linmul2(x + i, y, carry);

   for(size_t i = blocks; i != x_size; ++i)
      x[i] = word_madd2(x[i], y, &carry);

   x[x_size] = carry;
   }

/*
* Three Operand Linear Multiply
*/
void bigint_linmul3(word z[], const word x[], size_t x_size, word y)
   {
   const size_t blocks = x_size - (x_size % 8);

   word carry = 0;

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_linmul3(z + i, x + i, y, carry);

   for(size_t i = blocks; i != x_size; ++i)
      z[i] = word_madd2(x[i], y, &carry);

   z[x_size] = carry;
   }

/*
* Single Operand Left Shift
*/
void bigint_shl1(word x[], size_t x_size, size_t word_shift, size_t bit_shift)
   {
   if(word_shift)
      {
      copy_mem(x + word_shift, x, x_size);
      clear_mem(x, word_shift);
      }

   if(bit_shift)
      {
      word carry = 0;
      for(size_t j = word_shift; j != x_size + word_shift + 1; ++j)
         {
         word temp = x[j];
         x[j] = (temp << bit_shift) | carry;
         carry = (temp >> (MP_WORD_BITS - bit_shift));
         }
      }
   }

/*
* Single Operand Right Shift
*/
void bigint_shr1(word x[], size_t x_size, size_t word_shift, size_t bit_shift)
   {
   if(x_size < word_shift)
      {
      clear_mem(x, x_size);
      return;
      }

   if(word_shift)
      {
      copy_mem(x, x + word_shift, x_size - word_shift);
      clear_mem(x + x_size - word_shift, word_shift);
      }

   if(bit_shift)
      {
      word carry = 0;

      size_t top = x_size - word_shift;

      while(top >= 4)
         {
         word w = x[top-1];
         x[top-1] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         w = x[top-2];
         x[top-2] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         w = x[top-3];
         x[top-3] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         w = x[top-4];
         x[top-4] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         top -= 4;
         }

      while(top)
         {
         word w = x[top-1];
         x[top-1] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         top--;
         }
      }
   }

/*
* Two Operand Left Shift
*/
void bigint_shl2(word y[], const word x[], size_t x_size,
                 size_t word_shift, size_t bit_shift)
   {
   for(size_t j = 0; j != x_size; ++j)
      y[j + word_shift] = x[j];
   if(bit_shift)
      {
      word carry = 0;
      for(size_t j = word_shift; j != x_size + word_shift + 1; ++j)
         {
         word w = y[j];
         y[j] = (w << bit_shift) | carry;
         carry = (w >> (MP_WORD_BITS - bit_shift));
         }
      }
   }

/*
* Two Operand Right Shift
*/
void bigint_shr2(word y[], const word x[], size_t x_size,
                 size_t word_shift, size_t bit_shift)
   {
   if(x_size < word_shift) return;

   for(size_t j = 0; j != x_size - word_shift; ++j)
      y[j] = x[j + word_shift];
   if(bit_shift)
      {
      word carry = 0;
      for(size_t j = x_size - word_shift; j > 0; --j)
         {
         word w = y[j-1];
         y[j-1] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));
         }
      }
   }

/*
* Compare two MP integers
*/
int32_t bigint_cmp(const word x[], size_t x_size,
                  const word y[], size_t y_size)
   {
   if(x_size < y_size) { return (-bigint_cmp(y, y_size, x, x_size)); }

   while(x_size > y_size)
      {
      if(x[x_size-1])
         return 1;
      x_size--;
      }

   for(size_t i = x_size; i > 0; --i)
      {
      if(x[i-1] > y[i-1])
         return 1;
      if(x[i-1] < y[i-1])
         return -1;
      }

   return 0;
   }

/*
* Do a 2-word/1-word Division
*/
word bigint_divop(word n1, word n0, word d)
   {
   if(d == 0)
      throw Invalid_Argument("bigint_divop divide by zero");

   word high = n1 % d, quotient = 0;

   for(size_t i = 0; i != MP_WORD_BITS; ++i)
      {
      word high_top_bit = (high & MP_WORD_TOP_BIT);

      high <<= 1;
      high |= (n0 >> (MP_WORD_BITS-1-i)) & 1;
      quotient <<= 1;

      if(high_top_bit || high >= d)
         {
         high -= d;
         quotient |= 1;
         }
      }

   return quotient;
   }

/*
* Do a 2-word/1-word Modulo
*/
word bigint_modop(word n1, word n0, word d)
   {
   word z = bigint_divop(n1, n0, d);
   word dummy = 0;
   z = word_madd2(z, d, &dummy);
   return (n0-z);
   }

}
<commit_msg>Use dword for bigint_divop if available<commit_after>/*
* MPI Add, Subtract, Word Multiply
* (C) 1999-2010,2016 Jack Lloyd
*     2006 Luca Piccarreta
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/mp_core.h>
#include <botan/internal/mp_asmi.h>
#include <botan/internal/ct_utils.h>
#include <botan/exceptn.h>
#include <botan/mem_ops.h>

namespace Botan {

/*
* If cond == 0, does nothing.
* If cond > 0, swaps x[0:size] with y[0:size]
* Runs in constant time
*/
void bigint_cnd_swap(word cnd, word x[], word y[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   for(size_t i = 0; i != size; ++i)
      {
      word a = x[i];
      word b = y[i];
      x[i] = CT::select(mask, b, a);
      y[i] = CT::select(mask, a, b);
      }
   }

/*
* If cond > 0 adds x[0:size] to y[0:size] and returns carry
* Runs in constant time
*/
word bigint_cnd_add(word cnd, word x[], const word y[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   word carry = 0;
   for(size_t i = 0; i != size; ++i)
      {
      /*
      Here we are relying on asm version of word_add being
      a single addcl or equivalent. Fix this.
      */
      const word z = word_add(x[i], y[i], &carry);
      x[i] = CT::select(mask, z, x[i]);
      }

   return carry & mask;
   }

/*
* If cond > 0 subs x[0:size] to y[0:size] and returns borrow
* Runs in constant time
*/
word bigint_cnd_sub(word cnd, word x[], const word y[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   word carry = 0;
   for(size_t i = 0; i != size; ++i)
      {
      const word z = word_sub(x[i], y[i], &carry);
      x[i] = CT::select(mask, z, x[i]);
      }

   return carry & mask;
   }

void bigint_cnd_abs(word cnd, word x[], size_t size)
   {
   const word mask = CT::expand_mask(cnd);

   word carry = mask & 1;
   for(size_t i = 0; i != size; ++i)
      {
      const word z = word_add(~x[i], 0, &carry);
      x[i] = CT::select(mask, z, x[i]);
      }
   }

/*
* Two Operand Addition, No Carry
*/
word bigint_add2_nc(word x[], size_t x_size, const word y[], size_t y_size)
   {
   word carry = 0;

   BOTAN_ASSERT(x_size >= y_size, "Expected sizes");

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_add2(x + i, y + i, carry);

   for(size_t i = blocks; i != y_size; ++i)
      x[i] = word_add(x[i], y[i], &carry);

   for(size_t i = y_size; i != x_size; ++i)
      x[i] = word_add(x[i], 0, &carry);

   return carry;
   }

/*
* Three Operand Addition, No Carry
*/
word bigint_add3_nc(word z[], const word x[], size_t x_size,
                              const word y[], size_t y_size)
   {
   if(x_size < y_size)
      { return bigint_add3_nc(z, y, y_size, x, x_size); }

   word carry = 0;

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_add3(z + i, x + i, y + i, carry);

   for(size_t i = blocks; i != y_size; ++i)
      z[i] = word_add(x[i], y[i], &carry);

   for(size_t i = y_size; i != x_size; ++i)
      z[i] = word_add(x[i], 0, &carry);

   return carry;
   }

/*
* Two Operand Addition
*/
void bigint_add2(word x[], size_t x_size, const word y[], size_t y_size)
   {
   if(bigint_add2_nc(x, x_size, y, y_size))
      x[x_size] += 1;
   }

/*
* Three Operand Addition
*/
void bigint_add3(word z[], const word x[], size_t x_size,
                           const word y[], size_t y_size)
   {
   z[(x_size > y_size ? x_size : y_size)] +=
      bigint_add3_nc(z, x, x_size, y, y_size);
   }

/*
* Two Operand Subtraction
*/
word bigint_sub2(word x[], size_t x_size, const word y[], size_t y_size)
   {
   word borrow = 0;

   BOTAN_ASSERT(x_size >= y_size, "Expected sizes");

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      borrow = word8_sub2(x + i, y + i, borrow);

   for(size_t i = blocks; i != y_size; ++i)
      x[i] = word_sub(x[i], y[i], &borrow);

   for(size_t i = y_size; i != x_size; ++i)
      x[i] = word_sub(x[i], 0, &borrow);

   return borrow;
   }

/*
* Two Operand Subtraction x = y - x
*/
void bigint_sub2_rev(word x[],  const word y[], size_t y_size)
   {
   word borrow = 0;

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      borrow = word8_sub2_rev(x + i, y + i, borrow);

   for(size_t i = blocks; i != y_size; ++i)
      x[i] = word_sub(y[i], x[i], &borrow);

   BOTAN_ASSERT(!borrow, "y must be greater than x");
   }

/*
* Three Operand Subtraction
*/
word bigint_sub3(word z[], const word x[], size_t x_size,
                           const word y[], size_t y_size)
   {
   word borrow = 0;

   BOTAN_ASSERT(x_size >= y_size, "Expected sizes");

   const size_t blocks = y_size - (y_size % 8);

   for(size_t i = 0; i != blocks; i += 8)
      borrow = word8_sub3(z + i, x + i, y + i, borrow);

   for(size_t i = blocks; i != y_size; ++i)
      z[i] = word_sub(x[i], y[i], &borrow);

   for(size_t i = y_size; i != x_size; ++i)
      z[i] = word_sub(x[i], 0, &borrow);

   return borrow;
   }

/*
* Two Operand Linear Multiply
*/
void bigint_linmul2(word x[], size_t x_size, word y)
   {
   const size_t blocks = x_size - (x_size % 8);

   word carry = 0;

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_linmul2(x + i, y, carry);

   for(size_t i = blocks; i != x_size; ++i)
      x[i] = word_madd2(x[i], y, &carry);

   x[x_size] = carry;
   }

/*
* Three Operand Linear Multiply
*/
void bigint_linmul3(word z[], const word x[], size_t x_size, word y)
   {
   const size_t blocks = x_size - (x_size % 8);

   word carry = 0;

   for(size_t i = 0; i != blocks; i += 8)
      carry = word8_linmul3(z + i, x + i, y, carry);

   for(size_t i = blocks; i != x_size; ++i)
      z[i] = word_madd2(x[i], y, &carry);

   z[x_size] = carry;
   }

/*
* Single Operand Left Shift
*/
void bigint_shl1(word x[], size_t x_size, size_t word_shift, size_t bit_shift)
   {
   if(word_shift)
      {
      copy_mem(x + word_shift, x, x_size);
      clear_mem(x, word_shift);
      }

   if(bit_shift)
      {
      word carry = 0;
      for(size_t j = word_shift; j != x_size + word_shift + 1; ++j)
         {
         word temp = x[j];
         x[j] = (temp << bit_shift) | carry;
         carry = (temp >> (MP_WORD_BITS - bit_shift));
         }
      }
   }

/*
* Single Operand Right Shift
*/
void bigint_shr1(word x[], size_t x_size, size_t word_shift, size_t bit_shift)
   {
   if(x_size < word_shift)
      {
      clear_mem(x, x_size);
      return;
      }

   if(word_shift)
      {
      copy_mem(x, x + word_shift, x_size - word_shift);
      clear_mem(x + x_size - word_shift, word_shift);
      }

   if(bit_shift)
      {
      word carry = 0;

      size_t top = x_size - word_shift;

      while(top >= 4)
         {
         word w = x[top-1];
         x[top-1] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         w = x[top-2];
         x[top-2] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         w = x[top-3];
         x[top-3] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         w = x[top-4];
         x[top-4] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         top -= 4;
         }

      while(top)
         {
         word w = x[top-1];
         x[top-1] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));

         top--;
         }
      }
   }

/*
* Two Operand Left Shift
*/
void bigint_shl2(word y[], const word x[], size_t x_size,
                 size_t word_shift, size_t bit_shift)
   {
   for(size_t j = 0; j != x_size; ++j)
      y[j + word_shift] = x[j];
   if(bit_shift)
      {
      word carry = 0;
      for(size_t j = word_shift; j != x_size + word_shift + 1; ++j)
         {
         word w = y[j];
         y[j] = (w << bit_shift) | carry;
         carry = (w >> (MP_WORD_BITS - bit_shift));
         }
      }
   }

/*
* Two Operand Right Shift
*/
void bigint_shr2(word y[], const word x[], size_t x_size,
                 size_t word_shift, size_t bit_shift)
   {
   if(x_size < word_shift) return;

   for(size_t j = 0; j != x_size - word_shift; ++j)
      y[j] = x[j + word_shift];
   if(bit_shift)
      {
      word carry = 0;
      for(size_t j = x_size - word_shift; j > 0; --j)
         {
         word w = y[j-1];
         y[j-1] = (w >> bit_shift) | carry;
         carry = (w << (MP_WORD_BITS - bit_shift));
         }
      }
   }

/*
* Compare two MP integers
*/
int32_t bigint_cmp(const word x[], size_t x_size,
                  const word y[], size_t y_size)
   {
   if(x_size < y_size) { return (-bigint_cmp(y, y_size, x, x_size)); }

   while(x_size > y_size)
      {
      if(x[x_size-1])
         return 1;
      x_size--;
      }

   for(size_t i = x_size; i > 0; --i)
      {
      if(x[i-1] > y[i-1])
         return 1;
      if(x[i-1] < y[i-1])
         return -1;
      }

   return 0;
   }

/*
* Do a 2-word/1-word Division
*/
word bigint_divop(word n1, word n0, word d)
   {
   if(d == 0)
      throw Invalid_Argument("bigint_divop divide by zero");

#if defined(BOTAN_HAS_MP_DWORD)
   return ((static_cast<dword>(n1) << MP_WORD_BITS) | n0) / d;
#else

   word high = n1 % d, quotient = 0;

   for(size_t i = 0; i != MP_WORD_BITS; ++i)
      {
      word high_top_bit = (high & MP_WORD_TOP_BIT);

      high <<= 1;
      high |= (n0 >> (MP_WORD_BITS-1-i)) & 1;
      quotient <<= 1;

      if(high_top_bit || high >= d)
         {
         high -= d;
         quotient |= 1;
         }
      }

   return quotient;
#endif
   }

/*
* Do a 2-word/1-word Modulo
*/
word bigint_modop(word n1, word n0, word d)
   {
   word z = bigint_divop(n1, n0, d);
   word dummy = 0;
   z = word_madd2(z, d, &dummy);
   return (n0-z);
   }

}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "medialibrary/IMediaLibrary.h"
#include "mocks/NoopCallback.h"

#include <iostream>
#include <condition_variable>
#include <mutex>

int main( int argc, char** argv )
{
    if ( argc < 2 )
    {
        std::cerr << "usage: " << argv[0] << " <entrypoint>" << std::endl;
        return 1;
    }

    for ( auto i = 0; i < 1000; ++i )
    {
        auto testCb = std::make_unique<mock::NoopCallback>();
        std::unique_ptr<medialibrary::IMediaLibrary> ml( NewMediaLibrary() );
        ml->initialize( "/tmp/test.db", "/tmp/ml_folder", testCb.get() );
        ml->start();
        ml->discover( argv[1] );
        ml->reload();
    }
    return 0;
}
<commit_msg>tests: fast_teardown: Ensure the discoverer thread is started<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "medialibrary/IMediaLibrary.h"
#include "mocks/NoopCallback.h"
#include "utils/Filename.h"
#include "compat/Mutex.h"
#include "compat/ConditionVariable.h"

#include <iostream>
#include <unistd.h>

class FastTearDownCb : public mock::NoopCallback
{
public:
    FastTearDownCb()
        : m_started( false )
    {
    }

    void prepareWait()
    {
        m_mutex.lock();
        m_started = false;
    }

    virtual void onDiscoveryProgress( const std::string& ) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_started = true;
        }
        m_cond.notify_all();
    }

    void waitForDiscoveryStarted()
    {
        std::unique_lock<compat::Mutex> lock( m_mutex, std::adopt_lock );
        m_cond.wait_for( lock, std::chrono::seconds{ 5 }, [this](){
            return m_started == true;
        });
    }

private:
    compat::Mutex m_mutex;
    compat::ConditionVariable m_cond;
    bool m_started;
};

int main( int argc, char** argv )
{
    if ( argc < 2 )
    {
        std::cerr << "usage: " << argv[0] << " <entrypoint>" << std::endl;
        return 1;
    }
    auto entryPoint = utils::file::toMrl( argv[1] );

    for ( auto i = 0; i < 1000; ++i )
    {
        auto testCb = std::make_unique<FastTearDownCb>();
        std::unique_ptr<medialibrary::IMediaLibrary> ml( NewMediaLibrary() );
        ml->initialize( "/tmp/test.db", "/tmp/ml_folder", testCb.get() );
        testCb->prepareWait();
        ml->start();
        ml->discover( entryPoint );
        ml->reload();
        testCb->waitForDiscoveryStarted();
    }
    return 0;
}
<|endoftext|>