<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/dreamview/backend/simulation_world/simulation_world_updater.h"

#include "google/protobuf/util/json_util.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/map/hdmap/hdmap_util.h"

namespace apollo {
namespace dreamview {

using apollo::common::adapter::AdapterManager;
using apollo::common::monitor::MonitorMessageItem;
using apollo::common::util::GetProtoFromASCIIFile;
using apollo::hdmap::EndWayPointFile;
using apollo::routing::RoutingRequest;
using google::protobuf::util::MessageToJsonString;
using Json = nlohmann::json;

SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,
                                               const MapService *map_service,
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
      map_service_(map_service),
      websocket_(websocket) {
  // Initialize default end point
  if (!GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {
    AWARN << "Failed to load default end point from " << EndWayPointFile();
  }

  websocket_->RegisterMessageHandler(
      "RetrieveMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto iter = json.find("elements");
        if (iter != json.end()) {
          MapElementIds map_element_ids(*iter);
          auto retrieved = map_service_->RetrieveMapElements(map_element_ids);

          std::string retrieved_json_string;
          MessageToJsonString(retrieved, &retrieved_json_string);

          Json response;
          response["type"] = "MapData";
          response["data"] = Json::parse(retrieved_json_string);

          websocket_->SendData(conn, response.dump());
        }
      });

  websocket_->RegisterMessageHandler(
      "RetrieveMapElementsByRadius",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto radius = json.find("radius");
        if (radius == json.end()) {
          AERROR << "Cannot retrieve map elements with unknown radius.";
          return;
        }

        Json response = sim_world_service_.GetMapElements(*radius);
        response["type"] = "MapElements";
        websocket_->SendData(conn, response.dump());
      });

  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        RoutingRequest routing_request;

        bool succeed = ConstructRoutingRequest(json, &routing_request);
        if (succeed) {
          AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,
                                                   &routing_request);
          AdapterManager::PublishRoutingRequest(routing_request);
        }

        // Publish monitor message.
        if (succeed) {
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::INFO, "Routing Request Sent");
        } else {
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::ERROR, "Failed to send routing request");
        }
      });

  websocket_->RegisterMessageHandler(
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

        std::string to_send;
        {
          // Pay the price to copy the data instead of sending data over the
          // wire while holding the lock.
          boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);
          to_send = simulation_world_json_;
        }
        websocket_->SendData(conn, to_send, true);
      });
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
    const Json &json, RoutingRequest *routing_request) {
  // Input validations
  if (json.find("start") == json.end() ||
      json.find("sendDefaultRoute") == json.end()) {
    AERROR << "Cannot prepare a routing request: input validation failed.";
    return false;
  }

  // Try to reload end point if it hasn't be loaded yet.
  if (!default_end_point_.has_id() &&
      !GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {
    AERROR << "Failed to load default end point from " << EndWayPointFile();
    return false;
  }

  // set start point
  auto start = json["start"];
  if (start.find("x") == start.end() || start.find("y") == start.end()) {
    AERROR << "Failed to prepare a routing request: start point not found";
    return false;
  }
  map_service_->ConstructLaneWayPoint(start["x"], start["y"],
                                      routing_request->mutable_start());

  // set way point(s) if any
  auto iter = json.find("waypoint");
  if (iter != json.end()) {
    auto *waypoint = routing_request->mutable_waypoint();
    for (size_t i = 0; i < iter->size(); ++i) {
      auto &point = (*iter)[i];
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
  RoutingRequest::LaneWaypoint *endLane = routing_request->mutable_end();
  if (json["sendDefaultRoute"]) {
    endLane->set_id(default_end_point_.id());
    endLane->set_s(default_end_point_.s());
    auto *pose = endLane->mutable_pose();
    pose->set_x(default_end_point_.pose().x());
    pose->set_y(default_end_point_.pose().y());
  } else {
    if (json.find("end") == json.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }

    auto end = json["end"];
    if (end.find("x") == end.end() || end.find("y") == end.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }
    map_service_->ConstructLaneWayPoint(end["x"], end["y"], endLane);
  }

  return true;
}

void SimulationWorldUpdater::Start() {
  // start ROS timer, one-shot = false, auto-start = true
  timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval),
                                       &SimulationWorldUpdater::OnTimer, this);
}

void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {
  sim_world_service_.Update();

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);

    simulation_world_json_ =
        sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump();
  }
}

}  // namespace dreamview
}  // namespace apollo
<commit_msg>Dreamview: Load default end when needed (#449)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/dreamview/backend/simulation_world/simulation_world_updater.h"

#include "google/protobuf/util/json_util.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/map/hdmap/hdmap_util.h"

namespace apollo {
namespace dreamview {

using apollo::common::adapter::AdapterManager;
using apollo::common::monitor::MonitorMessageItem;
using apollo::common::util::GetProtoFromASCIIFile;
using apollo::hdmap::EndWayPointFile;
using apollo::routing::RoutingRequest;
using google::protobuf::util::MessageToJsonString;
using Json = nlohmann::json;

SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,
                                               const MapService *map_service,
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
      map_service_(map_service),
      websocket_(websocket) {
  // Initialize default end point
  if (!GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {
    AWARN << "Failed to load default end point from " << EndWayPointFile();
  }

  websocket_->RegisterMessageHandler(
      "RetrieveMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto iter = json.find("elements");
        if (iter != json.end()) {
          MapElementIds map_element_ids(*iter);
          auto retrieved = map_service_->RetrieveMapElements(map_element_ids);

          std::string retrieved_json_string;
          MessageToJsonString(retrieved, &retrieved_json_string);

          Json response;
          response["type"] = "MapData";
          response["data"] = Json::parse(retrieved_json_string);

          websocket_->SendData(conn, response.dump());
        }
      });

  websocket_->RegisterMessageHandler(
      "RetrieveMapElementsByRadius",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto radius = json.find("radius");
        if (radius == json.end()) {
          AERROR << "Cannot retrieve map elements with unknown radius.";
          return;
        }

        Json response = sim_world_service_.GetMapElements(*radius);
        response["type"] = "MapElements";
        websocket_->SendData(conn, response.dump());
      });

  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        RoutingRequest routing_request;

        bool succeed = ConstructRoutingRequest(json, &routing_request);
        if (succeed) {
          AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,
                                                   &routing_request);
          AdapterManager::PublishRoutingRequest(routing_request);
        }

        // Publish monitor message.
        if (succeed) {
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
                                                   "Routing Request Sent");
        } else {
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::ERROR, "Failed to send routing request");
        }
      });

  websocket_->RegisterMessageHandler(
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

        std::string to_send;
        {
          // Pay the price to copy the data instead of sending data over the
          // wire while holding the lock.
          boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);
          to_send = simulation_world_json_;
        }
        websocket_->SendData(conn, to_send, true);
      });
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
    const Json &json, RoutingRequest *routing_request) {
  // Input validations
  if (json.find("start") == json.end() ||
      json.find("sendDefaultRoute") == json.end()) {
    AERROR << "Cannot prepare a routing request: input validation failed.";
    return false;
  }

  // set start point
  auto start = json["start"];
  if (start.find("x") == start.end() || start.find("y") == start.end()) {
    AERROR << "Failed to prepare a routing request: start point not found";
    return false;
  }
  map_service_->ConstructLaneWayPoint(start["x"], start["y"],
                                      routing_request->mutable_start());

  // set way point(s) if any
  auto iter = json.find("waypoint");
  if (iter != json.end()) {
    auto *waypoint = routing_request->mutable_waypoint();
    for (size_t i = 0; i < iter->size(); ++i) {
      auto &point = (*iter)[i];
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
  RoutingRequest::LaneWaypoint *endLane = routing_request->mutable_end();
  if (json["sendDefaultRoute"]) {
    // Try to reload end point if it hasn't been loaded yet.
    if (!default_end_point_.has_id() &&
        !GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {
      AERROR << "Failed to load default end point from " << EndWayPointFile();
      return false;
    }

    endLane->set_id(default_end_point_.id());
    endLane->set_s(default_end_point_.s());
    auto *pose = endLane->mutable_pose();
    pose->set_x(default_end_point_.pose().x());
    pose->set_y(default_end_point_.pose().y());
  } else {
    if (json.find("end") == json.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }

    auto end = json["end"];
    if (end.find("x") == end.end() || end.find("y") == end.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }
    map_service_->ConstructLaneWayPoint(end["x"], end["y"], endLane);
  }

  return true;
}

void SimulationWorldUpdater::Start() {
  // start ROS timer, one-shot = false, auto-start = true
  timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval),
                                       &SimulationWorldUpdater::OnTimer, this);
}

void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {
  sim_world_service_.Update();

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);

    simulation_world_json_ =
        sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump();
  }
}

}  // namespace dreamview
}  // namespace apollo
<|endoftext|>


<commit_before>#include <node.h>
#include <windows.h>
#include <TlHelp32.h>
#include <vector>
#include "process.h"
#include "memoryjs.h"

process::process() {}

process::~process() {
	CloseHandle(hProcess);
}

using v8::Exception;
using v8::Isolate;
using v8::String;

PROCESSENTRY32 process::processEntry;
HANDLE process::hProcess;

PROCESSENTRY32 process::openProcess(const char* processName, char** errorMessage){
	PROCESSENTRY32 process;

	// A list of processes (PROCESSENTRY32)
	std::vector<PROCESSENTRY32> processes = getProcesses(errorMessage);

	for(std::vector<PROCESSENTRY32>::size_type i = 0; i != processes.size(); i++){
		// Check to see if this is the process we want.
		if (!strcmp(processes[i].szExeFile, processName)) {
			// Store the process handle and process ID internally
			// for reading/writing to memory
			process::hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processes[i].th32ProcessID);

			// Store the handle (just for reference to close the handle later)
			// process is returned and processEntry is used internally for reading/writing to memory
			handle = (int) process::hProcess;
			process = processEntry = processes[i];

			break;
		}
	}

	return process;
}

void process::closeProcess(){
	CloseHandle((HANDLE) handle);
}

std::vector<PROCESSENTRY32> process::getProcesses(char** errorMessage) {
	// Take a snapshot of all processes.
	HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
	PROCESSENTRY32 pEntry;

	if (hProcessSnapshot == INVALID_HANDLE_VALUE) {
		*errorMessage = "method failed to take snapshot of the process";
	}

	// Before use, set the structure size.
	pEntry.dwSize = sizeof(pEntry);

	// Exit if unable to find the first process.
	if (!Process32First(hProcessSnapshot, &pEntry)) {
		CloseHandle(hProcessSnapshot);
		*errorMessage = "method failed to retrieve the first process";
	}

	std::vector<PROCESSENTRY32> processes;

	// Loop through processes.
	do {
		// Add the process to the vector
		processes.push_back(pEntry);
	} while (Process32Next(hProcessSnapshot, &pEntry));

	CloseHandle(hProcessSnapshot);
	return processes;
}
<commit_msg>closed process handle correctly<commit_after>#include <node.h>
#include <windows.h>
#include <TlHelp32.h>
#include <vector>
#include "process.h"
#include "memoryjs.h"

process::process() {}

process::~process() {
	CloseHandle(hProcess);
}

using v8::Exception;
using v8::Isolate;
using v8::String;

PROCESSENTRY32 process::processEntry;
HANDLE process::hProcess;

PROCESSENTRY32 process::openProcess(const char* processName, char** errorMessage){
	PROCESSENTRY32 process;

	// A list of processes (PROCESSENTRY32)
	std::vector<PROCESSENTRY32> processes = getProcesses(errorMessage);

	for(std::vector<PROCESSENTRY32>::size_type i = 0; i != processes.size(); i++){
		// Check to see if this is the process we want.
		if (!strcmp(processes[i].szExeFile, processName)) {
			// Store the process handle and process ID internally
			// for reading/writing to memory
			process::hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processes[i].th32ProcessID);

			// Store the handle (just for reference to close the handle later)
			// process is returned and processEntry is used internally for reading/writing to memory
			handle = (int) process::hProcess;
			process = processEntry = processes[i];

			break;
		}
	}

	return process;
}

void process::closeProcess(){
	CloseHandle(process::hProcess);
}

std::vector<PROCESSENTRY32> process::getProcesses(char** errorMessage) {
	// Take a snapshot of all processes.
	HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
	PROCESSENTRY32 pEntry;

	if (hProcessSnapshot == INVALID_HANDLE_VALUE) {
		*errorMessage = "method failed to take snapshot of the process";
	}

	// Before use, set the structure size.
	pEntry.dwSize = sizeof(pEntry);

	// Exit if unable to find the first process.
	if (!Process32First(hProcessSnapshot, &pEntry)) {
		CloseHandle(hProcessSnapshot);
		*errorMessage = "method failed to retrieve the first process";
	}

	std::vector<PROCESSENTRY32> processes;

	// Loop through processes.
	do {
		// Add the process to the vector
		processes.push_back(pEntry);
	} while (Process32Next(hProcessSnapshot, &pEntry));

	CloseHandle(hProcessSnapshot);
	return processes;
}
<|endoftext|>


<commit_before>// Be careful to use a platform-specific conditional include to only make the
// code visible for the appropriate platform.  Arduino will try to compile and
// link all .cpp files regardless of platform.
#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__)

#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

#include "WatchdogAVR.h"

// Define watchdog timer interrupt.
ISR(WDT_vect)
{
    // Nothing needs to be done, however interrupt handler must be defined to
    // prevent a reset.
}

int WatchdogAVR::enable(int maxPeriodMS) {
    // Pick the closest appropriate watchdog timer value.
    int actualMS;
    _setPeriod(maxPeriodMS, _wdto, actualMS);
    // Enable the watchdog and return the actual countdown value.
    wdt_enable(_wdto);
    return actualMS;
}

void WatchdogAVR::reset() {
    // Reset the watchdog.
    wdt_reset();
}

void WatchdogAVR::disable() {
    // Disable the watchdog and clear any saved watchdog timer value.
    wdt_disable();
    _wdto = -1;
}

int WatchdogAVR::sleep(int maxPeriodMS) {
    // Pick the closest appropriate watchdog timer value.
    int sleepWDTO, actualMS;
    _setPeriod(maxPeriodMS, sleepWDTO, actualMS);

    // Build watchdog prescaler register value before timing critical code.
    uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) |
                   ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) |
                   ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) |
                   ((sleepWDTO & 0x01 ? 1 : 0) << WDP0);

    // The next section is timing critical so interrupts are disabled.
    cli();
    // First clear any previous watchdog reset.
    MCUSR &= ~(1<<WDRF);
    // Now change the watchdog prescaler and interrupt enable bit so the watchdog
    // reset only triggers the interrupt (and wakes from deep sleep) and not a
    // full device reset.  This is a timing critical section of code that must
    // happen in 4 cycles.
    WDTCSR |= (1<<WDCE) | (1<<WDE);  // Set WDCE and WDE to enable changes.
    WDTCSR = wdps;                   // Set the prescaler bit values.
    WDTCSR |= (1<<WDIE);             // Enable only watchdog interrupts.
    // Critical section finished, re-enable interrupts.
    sei();

    // Set full power-down sleep mode and go to sleep.
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();

    // Chip is now asleep!

    // Once awakened by the watchdog execution resumes here.  Start by disabling
    // sleep.
    sleep_disable();

    // Check if the user had the watchdog enabled before sleep and re-enable it.
    if (_wdto != -1) {
        wdt_enable(_wdto);
    }

    // Return how many actual milliseconds were spent sleeping.
    return actualMS;
}

void WatchdogAVR::_setPeriod(int maxMS, int &wdto, int &actualMS) {
    // Note the order of these if statements from highest to lowest  is
    // important so that control flow cascades down to the right value based
    // on its position in the range of discrete timeouts.
    if ((maxMS >= 8000) || (maxMS == 0)) {
        wdto     = WDTO_8S;
        actualMS = 8000;
    }
    else if (maxMS >= 4000) {
        wdto     = WDTO_4S;
        actualMS = 4000;
    }
    else if (maxMS >= 2000) {
        wdto     = WDTO_2S;
        actualMS = 2000;
    }
    else if (maxMS >= 1000) {
        wdto     = WDTO_1S;
        actualMS = 1000;
    }
    else if (maxMS >= 500) {
        wdto     = WDTO_500MS;
        actualMS = 500;
    }
    else if (maxMS >= 250) {
        wdto     = WDTO_250MS;
        actualMS = 250;
    }
    else if (maxMS >= 120) {
        wdto     = WDTO_120MS;
        actualMS = 120;
    }
    else if (maxMS >= 60) {
        wdto     = WDTO_60MS;
        actualMS = 60;
    }
    else if (maxMS >= 30) {
        wdto     = WDTO_30MS;
        actualMS = 30;
    }
    else {
        wdto     = WDTO_15MS;
        actualMS = 15;
    }
}

#endif<commit_msg>disable USB on '32u4 for ~200uA savings<commit_after>// Be careful to use a platform-specific conditional include to only make the
// code visible for the appropriate platform.  Arduino will try to compile and
// link all .cpp files regardless of platform.
#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__)

#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

#include "WatchdogAVR.h"

// Define watchdog timer interrupt.
ISR(WDT_vect)
{
    // Nothing needs to be done, however interrupt handler must be defined to
    // prevent a reset.
}

int WatchdogAVR::enable(int maxPeriodMS) {
    // Pick the closest appropriate watchdog timer value.
    int actualMS;
    _setPeriod(maxPeriodMS, _wdto, actualMS);
    // Enable the watchdog and return the actual countdown value.
    wdt_enable(_wdto);
    return actualMS;
}

void WatchdogAVR::reset() {
    // Reset the watchdog.
    wdt_reset();
}

void WatchdogAVR::disable() {
    // Disable the watchdog and clear any saved watchdog timer value.
    wdt_disable();
    _wdto = -1;
}

int WatchdogAVR::sleep(int maxPeriodMS) {
    // Pick the closest appropriate watchdog timer value.
    int sleepWDTO, actualMS;
    _setPeriod(maxPeriodMS, sleepWDTO, actualMS);

    // Build watchdog prescaler register value before timing critical code.
    uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) |
                   ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) |
                   ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) |
                   ((sleepWDTO & 0x01 ? 1 : 0) << WDP0);

    // The next section is timing critical so interrupts are disabled.
    cli();
    // First clear any previous watchdog reset.
    MCUSR &= ~(1<<WDRF);
    // Now change the watchdog prescaler and interrupt enable bit so the watchdog
    // reset only triggers the interrupt (and wakes from deep sleep) and not a
    // full device reset.  This is a timing critical section of code that must
    // happen in 4 cycles.
    WDTCSR |= (1<<WDCE) | (1<<WDE);  // Set WDCE and WDE to enable changes.
    WDTCSR = wdps;                   // Set the prescaler bit values.
    WDTCSR |= (1<<WDIE);             // Enable only watchdog interrupts.
    // Critical section finished, re-enable interrupts.
    sei();

    // Disable USB if it exists
    #ifdef USBCON
      USBCON |= _BV(FRZCLK);  //freeze USB clock
      PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
      USBCON &= ~_BV(USBE);   // disable USB
    #endif

    // Set full power-down sleep mode and go to sleep.
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();

    // Chip is now asleep!

    // Once awakened by the watchdog execution resumes here.  Start by disabling
    // sleep.
    sleep_disable();

    // Check if the user had the watchdog enabled before sleep and re-enable it.
    if (_wdto != -1) {
        wdt_enable(_wdto);
    }

    // Return how many actual milliseconds were spent sleeping.
    return actualMS;
}

void WatchdogAVR::_setPeriod(int maxMS, int &wdto, int &actualMS) {
    // Note the order of these if statements from highest to lowest  is
    // important so that control flow cascades down to the right value based
    // on its position in the range of discrete timeouts.
    if ((maxMS >= 8000) || (maxMS == 0)) {
        wdto     = WDTO_8S;
        actualMS = 8000;
    }
    else if (maxMS >= 4000) {
        wdto     = WDTO_4S;
        actualMS = 4000;
    }
    else if (maxMS >= 2000) {
        wdto     = WDTO_2S;
        actualMS = 2000;
    }
    else if (maxMS >= 1000) {
        wdto     = WDTO_1S;
        actualMS = 1000;
    }
    else if (maxMS >= 500) {
        wdto     = WDTO_500MS;
        actualMS = 500;
    }
    else if (maxMS >= 250) {
        wdto     = WDTO_250MS;
        actualMS = 250;
    }
    else if (maxMS >= 120) {
        wdto     = WDTO_120MS;
        actualMS = 120;
    }
    else if (maxMS >= 60) {
        wdto     = WDTO_60MS;
        actualMS = 60;
    }
    else if (maxMS >= 30) {
        wdto     = WDTO_30MS;
        actualMS = 30;
    }
    else {
        wdto     = WDTO_15MS;
        actualMS = 15;
    }
}

#endif
<|endoftext|>


<commit_before>/**
 * @file Cosa/Canvas/Font/FixedNums8x16.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2014, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/Canvas/Font/FixedNums8x16.hh"
#include "Cosa/Board.hh"

FixedNums8x16 fixednums8x16;

const uint8_t FixedNums8x16::width = 8;
const uint8_t FixedNums8x16::height = 16;
const uint8_t FixedNums8x16::first = '+';
const uint8_t FixedNums8x16::last = ':';

const uint8_t FixedNums8x16::bitmap[] __PROGMEM = {
  8,16,'+',':',
  0x80, 0x80, 0x80, 0xe0, 0xe0, 0x80, 0x80, 0x80,
  0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, // char '+'
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0xb0, 0x70, 0x00, 0x00, 0x00, // char ','
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // char '-'
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00, // char '.'
  0x00, 0x00, 0x00, 0xc0, 0xf0, 0x3c, 0x0f, 0x03,
  0x30, 0x3c, 0x0f, 0x03, 0x00, 0x00, 0x00, 0x00, // char '/'
  0xfc, 0xfe, 0x03, 0x81, 0x61, 0x1b, 0xfe, 0xfc,
  0x0f, 0x1f, 0x36, 0x21, 0x20, 0x30, 0x1f, 0x0f, // char '0'
  0x04, 0x04, 0x06, 0xff, 0xff, 0x00, 0x00, 0x00,
  0x20, 0x20, 0x20, 0x3f, 0x3f, 0x20, 0x20, 0x20, // char '1'
  0x0c, 0x0e, 0x03, 0x01, 0x81, 0xc3, 0x7e, 0x3c,
  0x38, 0x3c, 0x26, 0x23, 0x21, 0x20, 0x20, 0x20, // char '2'
  0x0c, 0x0e, 0x43, 0x41, 0x41, 0x43, 0xfe, 0xbc,
  0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '3'
  0x00, 0xe0, 0xfc, 0x1f, 0x83, 0x80, 0x00, 0x00,
  0x0f, 0x0f, 0x08, 0x08, 0x3f, 0x3f, 0x08, 0x08, // char '4'
#if defined(BOARD_ATMEGA2560)
  0x3f, 0x3f, 0x21, 0x21, 0x41, 0x61, 0xc1, 0x81,
#else
  0x3f, 0x3f, 0x21, 0x21, 0x21, 0x61, 0xc1, 0x81,
#endif
  0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '5'
  0xe0, 0xf8, 0x5c, 0x46, 0x43, 0xc1, 0x81, 0x01,
  0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '6'
  0x01, 0x01, 0x01, 0x01, 0x81, 0xf1, 0x7f, 0x0f,
  0x00, 0x00, 0x00, 0x3c, 0x3f, 0x03, 0x00, 0x00, // char '7'
  0x1c, 0xbe, 0xe3, 0x41, 0x41, 0xe3, 0xbe, 0x1c,
  0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '8'
  0x3c, 0x7e, 0xc3, 0x81, 0x81, 0x83, 0xfe, 0xfc,
  0x20, 0x20, 0x20, 0x30, 0x18, 0x0e, 0x07, 0x01, // char '9'
  0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00  // char ':
};
<commit_msg>Remove specs from FixedNums font bitmap<commit_after>/**
 * @file Cosa/Canvas/Font/FixedNums8x16.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2014, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/Canvas/Font/FixedNums8x16.hh"
#include "Cosa/Board.hh"

FixedNums8x16 fixednums8x16;

const uint8_t FixedNums8x16::width = 8;
const uint8_t FixedNums8x16::height = 16;
const uint8_t FixedNums8x16::first = '+';
const uint8_t FixedNums8x16::last = ':';

const uint8_t FixedNums8x16::bitmap[] __PROGMEM = {
  0x80, 0x80, 0x80, 0xe0, 0xe0, 0x80, 0x80, 0x80,
  0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, // char '+'
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0xb0, 0x70, 0x00, 0x00, 0x00, // char ','
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // char '-'
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00, // char '.'
  0x00, 0x00, 0x00, 0xc0, 0xf0, 0x3c, 0x0f, 0x03,
  0x30, 0x3c, 0x0f, 0x03, 0x00, 0x00, 0x00, 0x00, // char '/'
  0xfc, 0xfe, 0x03, 0x81, 0x61, 0x1b, 0xfe, 0xfc,
  0x0f, 0x1f, 0x36, 0x21, 0x20, 0x30, 0x1f, 0x0f, // char '0'
  0x04, 0x04, 0x06, 0xff, 0xff, 0x00, 0x00, 0x00,
  0x20, 0x20, 0x20, 0x3f, 0x3f, 0x20, 0x20, 0x20, // char '1'
  0x0c, 0x0e, 0x03, 0x01, 0x81, 0xc3, 0x7e, 0x3c,
  0x38, 0x3c, 0x26, 0x23, 0x21, 0x20, 0x20, 0x20, // char '2'
  0x0c, 0x0e, 0x43, 0x41, 0x41, 0x43, 0xfe, 0xbc,
  0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '3'
  0x00, 0xe0, 0xfc, 0x1f, 0x83, 0x80, 0x00, 0x00,
  0x0f, 0x0f, 0x08, 0x08, 0x3f, 0x3f, 0x08, 0x08, // char '4'
#if defined(BOARD_ATMEGA2560)
  0x3f, 0x3f, 0x21, 0x21, 0x41, 0x61, 0xc1, 0x81,
#else
  0x3f, 0x3f, 0x21, 0x21, 0x21, 0x61, 0xc1, 0x81,
#endif
  0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '5'
  0xe0, 0xf8, 0x5c, 0x46, 0x43, 0xc1, 0x81, 0x01,
  0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '6'
  0x01, 0x01, 0x01, 0x01, 0x81, 0xf1, 0x7f, 0x0f,
  0x00, 0x00, 0x00, 0x3c, 0x3f, 0x03, 0x00, 0x00, // char '7'
  0x1c, 0xbe, 0xe3, 0x41, 0x41, 0xe3, 0xbe, 0x1c,
  0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, // char '8'
  0x3c, 0x7e, 0xc3, 0x81, 0x81, 0x83, 0xfe, 0xfc,
  0x20, 0x20, 0x20, 0x30, 0x18, 0x0e, 0x07, 0x01, // char '9'
  0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00  // char ':
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: iodlgimp.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:33:13 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _IODLGIMP_HXX
#define _IODLGIMP_HXX

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_MENUBTN_HXX
#include <vcl/menubtn.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif

#include "svtools/svarray.hxx"

#include <vector>

//*****************************************************************************

class Accelerator;
class CheckBox;
class SvtFileDialog;
class SvStringsDtor;
class SvUShorts;

//*****************************************************************************

#define FILEDIALOG_DEF_EXTSEP       ';'
#define FILEDIALOG_DEF_WILDCARD     '*'
#define FILEDIALOG_DEF_IMAGEBORDER  10
#define FILEDIALOG_DEF_TIMEOUT      250

//*****************************************************************************

String GetRegularExpression_Impl( const String& rFilter );

//*****************************************************************************
// SvtFileDialogFilter_Impl
//*****************************************************************************

/*  [Beschreibung]

    Instanzen dieser Klasse repr"asentieren einen Filter
*/

class SvtFileDialogFilter_Impl
{
private:
    String  m_aName;    // name of the entry
    String  m_aType;    // filter wildcard - if empty, the entry marks a group

public:
    SvtFileDialogFilter_Impl( const String& rName, const String& rType );
    ~SvtFileDialogFilter_Impl();

    const String&       GetName() const     { return m_aName; }
    const String&       GetType() const     { return m_aType; }

    sal_Bool            isGroupSeparator() const    { return 0 == m_aType.Len(); }
};

//*****************************************************************************
// SvtFileDialogFilterList_Impl
//*****************************************************************************

SV_DECL_PTRARR_DEL( SvtFileDialogFilterList_Impl, SvtFileDialogFilter_Impl*, 3, 3 );

//*****************************************************************************
// SvtFileDlgMode
//*****************************************************************************

enum SvtFileDlgMode
{
    FILEDLG_MODE_OPEN = 0,
    FILEDLG_MODE_SAVE = 1
};

//*****************************************************************************
// SvtFileDlgType
//*****************************************************************************

enum SvtFileDlgType
{
    FILEDLG_TYPE_FILEDLG = 0,
    FILEDLG_TYPE_PATHDLG
};

//*****************************************************************************
// SvtFileDialogURLSelector
//*****************************************************************************
class SvtFileDialogURLSelector : public MenuButton
{
private:
    SvtFileDialog*      m_pParent;
    PopupMenu*          m_pMenu;

protected:
//    inline  const SvtFileDialog*  GetParent() const { return _pParent; }
    inline        SvtFileDialog*  GetParent()       { return m_pParent; }

protected:
            void    OpenURL( const String& rURL );

    virtual void    FillURLMenu( PopupMenu* _pMenu ) = 0;

protected:
    SvtFileDialogURLSelector( SvtFileDialog* _pParent, const ResId& _rResId, sal_uInt16 _nButtonId );
    ~SvtFileDialogURLSelector();

    virtual void        Activate();
};

//*****************************************************************************
// SvtUpButton_Impl
//*****************************************************************************

class SvtUpButton_Impl : public SvtFileDialogURLSelector
{
private:
    SvStringsDtor*      _pURLs;

public:
    SvtUpButton_Impl( SvtFileDialog* pParent, const ResId& rResId );
    ~SvtUpButton_Impl();

protected:
    virtual void        FillURLMenu( PopupMenu* _pMenu );
    virtual void        Select();
    virtual void        Click();
};

//*****************************************************************************
// SvtTravelButton_Impl
//*****************************************************************************

class SvtTravelButton_Impl : public SvtFileDialogURLSelector
{
private:
    ::std::vector< String > m_aFavourites;

public:
    SvtTravelButton_Impl( SvtFileDialog* pParent, const ResId& rResId );
    ~SvtTravelButton_Impl();

            void            SetFavouriteLocations( const ::std::vector< String >& _rLocations );

protected:
    virtual void        FillURLMenu( PopupMenu* _pMenu );
    virtual void        Select();
    virtual void        Click();
};

//*****************************************************************************
// SvtFileDlgState
//*****************************************************************************

typedef sal_uInt8 SvtFileDlgState;

#define FILEDLG_STATE_NONE        ((SvtFileDlgState)0x00)
#define FILEDLG_STATE_REMOTE      ((SvtFileDlgState)0x01)

//*****************************************************************************
// SvtExpFileDlg_Impl
//*****************************************************************************
class SvtURLBox;
class SvtExpFileDlg_Impl
{
private:
    DECL_STATIC_LINK( SvtExpFileDlg_Impl, UnClickHdl, Button* );

private:
    ListBox*                        _pLbFilter;

    const SvtFileDialogFilter_Impl* _pCurFilter;
    String                          m_sCurrentFilterDisplayName;    // may differ from _pCurFilter->GetName in case it is a cached entry

public:
    SvtFileDialogFilterList_Impl*   _pFilter;
    SvtFileDialogFilter_Impl*       _pUserFilter;

    FixedText*                      _pFtFileName;
    SvtURLBox*                      _pEdFileName;

    FixedText*                      _pFtFileVersion;
    ListBox*                        _pLbFileVersion;

    FixedText*                      _pFtTemplates;
    ListBox*                        _pLbTemplates;

    FixedText*                      _pFtImageTemplates;
    ListBox*                        _pLbImageTemplates;

    FixedText*                      _pFtFileType;
    PushButton*                     _pBtnFileOpen;
    PushButton*                     _pBtnCancel;
    HelpButton*                     _pBtnHelp;
    SvtUpButton_Impl*               _pBtnUp;
    ImageButton*                    _pBtnNewFolder;
    SvtTravelButton_Impl*           _pBtnStandard;
    CheckBox*                       _pCbPassword;
    FixedText*                      _pFtCurrentPath;
    CheckBox*                       _pCbAutoExtension;
    CheckBox*                       _pCbOptions;

    SvtFileDlgMode                  _eMode;
    SvtFileDlgType                  _eDlgType;
    SvtFileDlgState                 _nState;
    WinBits                         _nStyle;

    String                          _aStdDir;

    // beim traveln der Filterbox erst Zeitversetzt filtern
    Timer                           _aFilterTimer;

    // Zeigt der OpenHdl_Imp(), ob das Open durch einen Doppelclick ausgel"ost wurde
    sal_Bool                        _bDoubleClick;
    sal_Bool                        m_bNeedDelayedFilterExecute;

    // Liste mit den 5 zuletzt genutzten Filtern
    // Defaultfilter fuer <Alle> oder <Alle ...>
    const SvtFileDialogFilter_Impl* _pDefaultFilter;

    // Multiselektion?
    sal_Bool                        _bMultiSelection;

    // Fixgr"ossen f"ur Resize merken
    long                            _nFixDeltaHeight;
    Size                            _a6Size;
    Size                            _aDlgSize;
    String                          _aIniKey;

    sal_Bool                        _bFolderHasOpened;

                            SvtExpFileDlg_Impl( WinBits nBits );
                            ~SvtExpFileDlg_Impl();

    void                    SetStandardDir( const String& _rDir );
    inline const String&    GetStandardDir() const          { return _aStdDir; }
    inline void             DisableFilterBoxAutoWidth()     { _pLbFilter->EnableDDAutoWidth( FALSE ); }

    // ------------------------------------------
    // access to the filter listbox only as Control* - we want to maintain the entries/userdata ourself
            Control*        GetFilterListControl()          { return _pLbFilter; }
            const Control*  GetFilterListControl() const    { return _pLbFilter; }
            void            CreateFilterListControl( Window* _pParent, const ResId& _rId );
    inline  void            SetFilterListSelectHdl( const Link& _rHandler );

    // inits the listbox for the filters from the filter list (_pFilter)
            void            ClearFilterList( );
            void            InitFilterList( );
    inline  sal_Bool        HasFilterListEntry( const String& _rFilterName );
    inline  void            SelectFilterListEntry( const String& _rFilterName );
    inline  void            SetNoFilterListSelection( );
            void            InsertFilterListEntry( const SvtFileDialogFilter_Impl* _pFilterDesc );
                                // _pFilterDesc must already have been added to _pFilter
    inline  SvtFileDialogFilter_Impl*   GetSelectedFilterEntry( String& /* [out] */ _rDisplayName ) const;
    inline  sal_Bool        IsFilterListTravelSelect() const;

    SvtFileDialogFilter_Impl*   FindFilter( const String& _rFilterName );

    // ------------------------------------------
    // access to the current filter via methods only - need to care for consistency between _pCurFilter and m_sCurrentFilterDisplayName
    inline      const SvtFileDialogFilter_Impl*     GetCurFilter( ) const;
    inline      const String&                       GetCurFilterDisplayName() const;
                void                                SetCurFilter( SvtFileDialogFilter_Impl* _pFilter, const String& _rDisplayName );
    inline      void                                SetCurFilter( SvtFileDialogFilter_Impl* _pFilter );
};

inline void SvtExpFileDlg_Impl::SetFilterListSelectHdl( const Link& _rHandler )
{
    _pLbFilter->SetSelectHdl( _rHandler );
}

inline sal_Bool SvtExpFileDlg_Impl::HasFilterListEntry( const String& _rFilterName )
{
    return ( LISTBOX_ENTRY_NOTFOUND != _pLbFilter->GetEntryPos( _rFilterName ) );
}

inline void SvtExpFileDlg_Impl::SelectFilterListEntry( const String& _rFilterName )
{
    _pLbFilter->SelectEntry( _rFilterName );
}

inline  void SvtExpFileDlg_Impl::SetNoFilterListSelection( )
{
    _pLbFilter->SetNoSelection( );
}

inline SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetSelectedFilterEntry( String& _rDisplayName ) const
{
    _rDisplayName = _pLbFilter->GetSelectEntry();
    return static_cast< SvtFileDialogFilter_Impl* >( _pLbFilter->GetEntryData ( _pLbFilter->GetSelectEntryPos() ) );
}

inline sal_Bool SvtExpFileDlg_Impl::IsFilterListTravelSelect() const
{
    return _pLbFilter->IsTravelSelect();
}

inline const SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetCurFilter( ) const
{
    return _pCurFilter;
}

inline const String& SvtExpFileDlg_Impl::GetCurFilterDisplayName() const
{
    return m_sCurrentFilterDisplayName;
}

inline  void SvtExpFileDlg_Impl::SetCurFilter( SvtFileDialogFilter_Impl* pFilter )
{
    SetCurFilter( pFilter, pFilter->GetName() );
}

#endif // #ifndef _IODLGIMP_HXX

<commit_msg>INTEGRATION: CWS dba202a (1.3.12); FILE MERGED 2005/10/24 08:30:20 fs 1.3.12.1: #i35830# only strip extensions which really are extensions - thanks to rvojta@openoffice.org for the patch<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: iodlgimp.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-12-21 13:10:55 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _IODLGIMP_HXX
#define _IODLGIMP_HXX

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_MENUBTN_HXX
#include <vcl/menubtn.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif

#include "svtools/svarray.hxx"

#include <vector>

//*****************************************************************************

class Accelerator;
class CheckBox;
class SvtFileDialog;
class SvStringsDtor;
class SvUShorts;

//*****************************************************************************

#define FILEDIALOG_DEF_EXTSEP       ';'
#define FILEDIALOG_DEF_WILDCARD     '*'
#define FILEDIALOG_DEF_IMAGEBORDER  10
#define FILEDIALOG_DEF_TIMEOUT      250

//*****************************************************************************

String GetRegularExpression_Impl( const String& rFilter );

//*****************************************************************************
// SvtFileDialogFilter_Impl
//*****************************************************************************

/*  [Beschreibung]

    Instanzen dieser Klasse repr"asentieren einen Filter
*/

class SvtFileDialogFilter_Impl
{
private:
    String  m_aName;    // name of the entry
    String  m_aType;    // filter wildcard - if empty, the entry marks a group

public:
    SvtFileDialogFilter_Impl( const String& rName, const String& rType );
    ~SvtFileDialogFilter_Impl();

    const String&       GetName() const     { return m_aName; }
    const String&       GetType() const     { return m_aType; }
    const String        GetExtension() const    { return m_aType.Copy( 2 ); }

    sal_Bool            isGroupSeparator() const    { return 0 == m_aType.Len(); }
};

//*****************************************************************************
// SvtFileDialogFilterList_Impl
//*****************************************************************************

SV_DECL_PTRARR_DEL( SvtFileDialogFilterList_Impl, SvtFileDialogFilter_Impl*, 3, 3 );

//*****************************************************************************
// SvtFileDlgMode
//*****************************************************************************

enum SvtFileDlgMode
{
    FILEDLG_MODE_OPEN = 0,
    FILEDLG_MODE_SAVE = 1
};

//*****************************************************************************
// SvtFileDlgType
//*****************************************************************************

enum SvtFileDlgType
{
    FILEDLG_TYPE_FILEDLG = 0,
    FILEDLG_TYPE_PATHDLG
};

//*****************************************************************************
// SvtFileDialogURLSelector
//*****************************************************************************
class SvtFileDialogURLSelector : public MenuButton
{
private:
    SvtFileDialog*      m_pParent;
    PopupMenu*          m_pMenu;

protected:
//    inline  const SvtFileDialog*  GetParent() const { return _pParent; }
    inline        SvtFileDialog*  GetParent()       { return m_pParent; }

protected:
            void    OpenURL( const String& rURL );

    virtual void    FillURLMenu( PopupMenu* _pMenu ) = 0;

protected:
    SvtFileDialogURLSelector( SvtFileDialog* _pParent, const ResId& _rResId, sal_uInt16 _nButtonId );
    ~SvtFileDialogURLSelector();

    virtual void        Activate();
};

//*****************************************************************************
// SvtUpButton_Impl
//*****************************************************************************

class SvtUpButton_Impl : public SvtFileDialogURLSelector
{
private:
    SvStringsDtor*      _pURLs;

public:
    SvtUpButton_Impl( SvtFileDialog* pParent, const ResId& rResId );
    ~SvtUpButton_Impl();

protected:
    virtual void        FillURLMenu( PopupMenu* _pMenu );
    virtual void        Select();
    virtual void        Click();
};

//*****************************************************************************
// SvtTravelButton_Impl
//*****************************************************************************

class SvtTravelButton_Impl : public SvtFileDialogURLSelector
{
private:
    ::std::vector< String > m_aFavourites;

public:
    SvtTravelButton_Impl( SvtFileDialog* pParent, const ResId& rResId );
    ~SvtTravelButton_Impl();

            void            SetFavouriteLocations( const ::std::vector< String >& _rLocations );

protected:
    virtual void        FillURLMenu( PopupMenu* _pMenu );
    virtual void        Select();
    virtual void        Click();
};

//*****************************************************************************
// SvtFileDlgState
//*****************************************************************************

typedef sal_uInt8 SvtFileDlgState;

#define FILEDLG_STATE_NONE        ((SvtFileDlgState)0x00)
#define FILEDLG_STATE_REMOTE      ((SvtFileDlgState)0x01)

//*****************************************************************************
// SvtExpFileDlg_Impl
//*****************************************************************************
class SvtURLBox;
class SvtExpFileDlg_Impl
{
private:
    DECL_STATIC_LINK( SvtExpFileDlg_Impl, UnClickHdl, Button* );

private:
    ListBox*                        _pLbFilter;

    const SvtFileDialogFilter_Impl* _pCurFilter;
    String                          m_sCurrentFilterDisplayName;    // may differ from _pCurFilter->GetName in case it is a cached entry

public:
    SvtFileDialogFilterList_Impl*   _pFilter;
    SvtFileDialogFilter_Impl*       _pUserFilter;

    FixedText*                      _pFtFileName;
    SvtURLBox*                      _pEdFileName;

    FixedText*                      _pFtFileVersion;
    ListBox*                        _pLbFileVersion;

    FixedText*                      _pFtTemplates;
    ListBox*                        _pLbTemplates;

    FixedText*                      _pFtImageTemplates;
    ListBox*                        _pLbImageTemplates;

    FixedText*                      _pFtFileType;
    PushButton*                     _pBtnFileOpen;
    PushButton*                     _pBtnCancel;
    HelpButton*                     _pBtnHelp;
    SvtUpButton_Impl*               _pBtnUp;
    ImageButton*                    _pBtnNewFolder;
    SvtTravelButton_Impl*           _pBtnStandard;
    CheckBox*                       _pCbPassword;
    FixedText*                      _pFtCurrentPath;
    CheckBox*                       _pCbAutoExtension;
    CheckBox*                       _pCbOptions;

    SvtFileDlgMode                  _eMode;
    SvtFileDlgType                  _eDlgType;
    SvtFileDlgState                 _nState;
    WinBits                         _nStyle;

    String                          _aStdDir;

    // beim traveln der Filterbox erst Zeitversetzt filtern
    Timer                           _aFilterTimer;

    // Zeigt der OpenHdl_Imp(), ob das Open durch einen Doppelclick ausgel"ost wurde
    sal_Bool                        _bDoubleClick;
    sal_Bool                        m_bNeedDelayedFilterExecute;

    // Liste mit den 5 zuletzt genutzten Filtern
    // Defaultfilter fuer <Alle> oder <Alle ...>
    const SvtFileDialogFilter_Impl* _pDefaultFilter;

    // Multiselektion?
    sal_Bool                        _bMultiSelection;

    // Fixgr"ossen f"ur Resize merken
    long                            _nFixDeltaHeight;
    Size                            _a6Size;
    Size                            _aDlgSize;
    String                          _aIniKey;

    sal_Bool                        _bFolderHasOpened;

                            SvtExpFileDlg_Impl( WinBits nBits );
                            ~SvtExpFileDlg_Impl();

    void                    SetStandardDir( const String& _rDir );
    inline const String&    GetStandardDir() const          { return _aStdDir; }
    inline void             DisableFilterBoxAutoWidth()     { _pLbFilter->EnableDDAutoWidth( FALSE ); }

    // ------------------------------------------
    // access to the filter listbox only as Control* - we want to maintain the entries/userdata ourself
            Control*        GetFilterListControl()          { return _pLbFilter; }
            const Control*  GetFilterListControl() const    { return _pLbFilter; }
            void            CreateFilterListControl( Window* _pParent, const ResId& _rId );
    inline  void            SetFilterListSelectHdl( const Link& _rHandler );

    // inits the listbox for the filters from the filter list (_pFilter)
            void            ClearFilterList( );
            void            InitFilterList( );
    inline  sal_Bool        HasFilterListEntry( const String& _rFilterName );
    inline  void            SelectFilterListEntry( const String& _rFilterName );
    inline  void            SetNoFilterListSelection( );
            void            InsertFilterListEntry( const SvtFileDialogFilter_Impl* _pFilterDesc );
                                // _pFilterDesc must already have been added to _pFilter
    inline  SvtFileDialogFilter_Impl*   GetSelectedFilterEntry( String& /* [out] */ _rDisplayName ) const;
    inline  sal_Bool        IsFilterListTravelSelect() const;

    SvtFileDialogFilter_Impl*   FindFilter( const String& _rFilterName );

    // ------------------------------------------
    // access to the current filter via methods only - need to care for consistency between _pCurFilter and m_sCurrentFilterDisplayName
    inline      const SvtFileDialogFilter_Impl*     GetCurFilter( ) const;
    inline      const String&                       GetCurFilterDisplayName() const;
                void                                SetCurFilter( SvtFileDialogFilter_Impl* _pFilter, const String& _rDisplayName );
    inline      void                                SetCurFilter( SvtFileDialogFilter_Impl* _pFilter );
};

inline void SvtExpFileDlg_Impl::SetFilterListSelectHdl( const Link& _rHandler )
{
    _pLbFilter->SetSelectHdl( _rHandler );
}

inline sal_Bool SvtExpFileDlg_Impl::HasFilterListEntry( const String& _rFilterName )
{
    return ( LISTBOX_ENTRY_NOTFOUND != _pLbFilter->GetEntryPos( _rFilterName ) );
}

inline void SvtExpFileDlg_Impl::SelectFilterListEntry( const String& _rFilterName )
{
    _pLbFilter->SelectEntry( _rFilterName );
}

inline  void SvtExpFileDlg_Impl::SetNoFilterListSelection( )
{
    _pLbFilter->SetNoSelection( );
}

inline SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetSelectedFilterEntry( String& _rDisplayName ) const
{
    _rDisplayName = _pLbFilter->GetSelectEntry();
    return static_cast< SvtFileDialogFilter_Impl* >( _pLbFilter->GetEntryData ( _pLbFilter->GetSelectEntryPos() ) );
}

inline sal_Bool SvtExpFileDlg_Impl::IsFilterListTravelSelect() const
{
    return _pLbFilter->IsTravelSelect();
}

inline const SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetCurFilter( ) const
{
    return _pCurFilter;
}

inline const String& SvtExpFileDlg_Impl::GetCurFilterDisplayName() const
{
    return m_sCurrentFilterDisplayName;
}

inline  void SvtExpFileDlg_Impl::SetCurFilter( SvtFileDialogFilter_Impl* pFilter )
{
    SetCurFilter( pFilter, pFilter->GetName() );
}

#endif // #ifndef _IODLGIMP_HXX

<|endoftext|>


<commit_before>/*

Copyright (c) 2011, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include <iostream>

#include "test.hpp"
#include "setup_transfer.hpp"

void test_swarm()
{
	using namespace libtorrent;

	// these are declared before the session objects
	// so that they are destructed last. This enables
	// the sessions to destruct in parallel
	session_proxy p1;
	session_proxy p2;
	session_proxy p3;

	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48010, 49000), "0.0.0.0", 0);
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49010, 50000), "0.0.0.0", 0);
	session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50010, 51000), "0.0.0.0", 0);

	ses1.set_alert_mask(alert::all_categories);
	ses2.set_alert_mask(alert::all_categories);
	ses3.set_alert_mask(alert::all_categories);

	// this is to avoid everything finish from a single peer
	// immediately. To make the swarm actually connect all
	// three peers before finishing.
	float rate_limit = 100000;

	session_settings settings;
	settings.allow_multiple_connections_per_ip = true;
	settings.ignore_limits_on_local_network = false;
	settings.choking_algorithm = session_settings::auto_expand_choker;
	settings.upload_rate_limit = rate_limit;
	settings.unchoke_slots_limit = 1;
	ses1.set_settings(settings);

	settings.upload_rate_limit = rate_limit / 10;
	settings.download_rate_limit = rate_limit / 5;
	settings.unchoke_slots_limit = 0;
	ses2.set_settings(settings);
	ses3.set_settings(settings);

#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.out_enc_policy = pe_settings::forced;
	pes.in_enc_policy = pe_settings::forced;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
	ses3.set_pe_settings(pes);
#endif

	torrent_handle tor1;
	torrent_handle tor2;
	torrent_handle tor3;

	boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_unchoke");

	session_status st = ses1.status();
	TEST_CHECK(st.allowed_upload_slots == 1);
	for (int i = 0; i < 50; ++i)
	{
		print_alerts(ses1, "ses1");
		print_alerts(ses2, "ses2");
		print_alerts(ses3, "ses3");

		st = ses1.status();
		std::cerr << st.allowed_upload_slots << " ";
		if (st.allowed_upload_slots >= 2) break;

		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();
		torrent_status st3 = tor3.status();

		print_ses_rate(i, &st1, &st2, &st3);

		test_sleep(1000);
	}

	TEST_CHECK(st.allowed_upload_slots >= 2);

	// make sure the files are deleted
	ses1.remove_torrent(tor1, session::delete_files);
	ses2.remove_torrent(tor2, session::delete_files);
	ses3.remove_torrent(tor3, session::delete_files);

	// this allows shutting down the sessions in parallel
	p1 = ses1.abort();
	p2 = ses2.abort();
	p3 = ses3.abort();
}

int test_main()
{
	using namespace libtorrent;

	// in case the previous run was t r catch (std::exception&) {}erminated
	error_code ec;
	remove_all("./tmp1_unchoke", ec);
	remove_all("./tmp2_unchoke", ec);
	remove_all("./tmp3_unchoke", ec);

	test_swarm();

	test_sleep(2000);
	TEST_CHECK(!exists("./tmp1_unchoke/temporary"));
	TEST_CHECK(!exists("./tmp2_unchoke/temporary"));
	TEST_CHECK(!exists("./tmp3_unchoke/temporary"));

	remove_all("./tmp1_unchoke", ec);
	remove_all("./tmp2_unchoke", ec);
	remove_all("./tmp3_unchoke", ec);

	return 0;
}

<commit_msg>minor test_auto_unchoke cleanup<commit_after>/*

Copyright (c) 2011, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include <iostream>

#include "test.hpp"
#include "setup_transfer.hpp"

void test_swarm()
{
	using namespace libtorrent;

	// these are declared before the session objects
	// so that they are destructed last. This enables
	// the sessions to destruct in parallel
	session_proxy p1;
	session_proxy p2;
	session_proxy p3;

	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48010, 49000), "0.0.0.0", 0);
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49010, 50000), "0.0.0.0", 0);
	session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50010, 51000), "0.0.0.0", 0);

	ses1.set_alert_mask(alert::all_categories);
	ses2.set_alert_mask(alert::all_categories);
	ses3.set_alert_mask(alert::all_categories);

	// this is to avoid everything finish from a single peer
	// immediately. To make the swarm actually connect all
	// three peers before finishing.
	float rate_limit = 100000;

	session_settings settings;
	settings.allow_multiple_connections_per_ip = true;
	settings.ignore_limits_on_local_network = false;
	settings.choking_algorithm = session_settings::auto_expand_choker;
	settings.upload_rate_limit = rate_limit;
	settings.unchoke_slots_limit = 1;
	ses1.set_settings(settings);

	settings.upload_rate_limit = rate_limit / 10;
	settings.download_rate_limit = rate_limit / 5;
	settings.unchoke_slots_limit = 0;
	ses2.set_settings(settings);
	ses3.set_settings(settings);

#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.out_enc_policy = pe_settings::forced;
	pes.in_enc_policy = pe_settings::forced;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
	ses3.set_pe_settings(pes);
#endif

	torrent_handle tor1;
	torrent_handle tor2;
	torrent_handle tor3;

	boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_unchoke");

	session_status st = ses1.status();
	TEST_CHECK(st.allowed_upload_slots == 1);
	for (int i = 0; i < 100; ++i)
	{
		print_alerts(ses1, "ses1");
		print_alerts(ses2, "ses2");
		print_alerts(ses3, "ses3");

		st = ses1.status();
		fprintf(stderr, "allowed unchoked: %d\n", st.allowed_upload_slots);
		if (st.allowed_upload_slots >= 2) break;

		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();
		torrent_status st3 = tor3.status();

		print_ses_rate(i, &st1, &st2, &st3);

		test_sleep(100);
	}

	TEST_CHECK(st.allowed_upload_slots >= 2);

	// make sure the files are deleted
	ses1.remove_torrent(tor1, session::delete_files);
	ses2.remove_torrent(tor2, session::delete_files);
	ses3.remove_torrent(tor3, session::delete_files);

	// this allows shutting down the sessions in parallel
	p1 = ses1.abort();
	p2 = ses2.abort();
	p3 = ses3.abort();
}

int test_main()
{
	using namespace libtorrent;

	// in case the previous run was t r catch (std::exception&) {}erminated
	error_code ec;
	remove_all("./tmp1_unchoke", ec);
	remove_all("./tmp2_unchoke", ec);
	remove_all("./tmp3_unchoke", ec);

	test_swarm();

	test_sleep(2000);
	TEST_CHECK(!exists("./tmp1_unchoke/temporary"));
	TEST_CHECK(!exists("./tmp2_unchoke/temporary"));
	TEST_CHECK(!exists("./tmp3_unchoke/temporary"));

	remove_all("./tmp1_unchoke", ec);
	remove_all("./tmp2_unchoke", ec);
	remove_all("./tmp3_unchoke", ec);

	return 0;
}

<|endoftext|>


<commit_before>/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2011 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id: header 310447 2011-04-23 21:14:10Z bjori $ */
extern "C"
{
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
}

#include <vector>
#include <string>
#include "php_zeppelin.h"
#include "libzp/include/zp_client.h"
#include "slash/include/slash_status.h"
#include "zend.h"

/* If you declare any globals in php_zeppelin.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(zeppelin)
*/
static int le_zeppelin;

/* True global resources - no need for thread safety here */
zend_class_entry *zeppelin_client_ext;

/* {{{ zeppelin_functions[]
 *
 * Every user visible function must have an entry in zeppelin_functions[].
 */

//zend_function_entry zeppelin_functions[] = {
//    PHP_FE(confirm_zeppelin_compiled,    NULL)        /* For testing, remove later. */
//    PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)
//    {NULL, NULL, NULL}
//    //PHP_FE_END    /* Must be the last line in zeppelin_functions[] */
//};
zend_function_entry zeppelin_functions[] = {
	{NULL, NULL, NULL}
};

zend_function_entry phppan_functions[] = {
    PHP_FE(confirm_zeppelin_compiled,    NULL)        /* For testing, remove later. */
    PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, mget, NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};
/* }}} */

/* {{{ zeppelin_module_entry
 */
zend_module_entry zeppelin_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    "zeppelin",
    zeppelin_functions,
    PHP_MINIT(zeppelin),
    PHP_MSHUTDOWN(zeppelin),
    PHP_RINIT(zeppelin),        /* Replace with NULL if there's nothing to do at request start */
    PHP_RSHUTDOWN(zeppelin),    /* Replace with NULL if there's nothing to do at request end */
    PHP_MINFO(zeppelin),
#if ZEND_MODULE_API_NO >= 20010901
    "0.1", /* Replace with version number for your extension */
#endif
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

extern "C"
{
#ifdef COMPILE_DL_ZEPPELIN
ZEND_GET_MODULE(zeppelin)
#endif
}

static void zeppelin_destructor_zeppelin_client(zend_rsrc_list_entry * rsrc TSRMLS_DC)
{
	libzp::Client *zp = (libzp::Client *) rsrc->ptr;
    delete zp;
}

int zeppelin_client_get(zval *id, libzp::Client **zeppelin_sock TSRMLS_DC, int no_throw)
{
    zval **socket;
    int resource_type;

    if (Z_TYPE_P(id) != IS_OBJECT || zend_hash_find(Z_OBJPROP_P(id), "Zeppelin",
                sizeof("Zeppelin"), (void **) &socket) == FAILURE) {
        return -1;
    }

    *zeppelin_sock = (libzp::Client *) zend_list_find(Z_LVAL_PP(socket), &resource_type);

    if (!*zeppelin_sock || resource_type != le_zeppelin) {
        return -1;
    }

    return Z_LVAL_PP(socket);
}

PHP_MINIT_FUNCTION(zeppelin)
{
    /* If you have INI entries, uncomment these lines
    REGISTER_INI_ENTRIES();
    */
    zend_class_entry zeppelin_class_entry;
//    INIT_CLASS_ENTRY(zeppelin_class_entry, "Zeppelin", zeppelin_functions);
    INIT_CLASS_ENTRY(zeppelin_class_entry, "Zeppelin", phppan_functions);
    zeppelin_client_ext = zend_register_internal_class(&zeppelin_class_entry TSRMLS_CC);

    le_zeppelin = zend_register_list_destructors_ex(
        zeppelin_destructor_zeppelin_client,
        NULL,
        "zeppelin-client", module_number
    );

    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(zeppelin)
{
    /* uncomment this line if you have INI entries
    UNREGISTER_INI_ENTRIES();
    */
    return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(zeppelin)
{
    return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(zeppelin)
{
    return SUCCESS;
}
/* }}} */

/* {{{ PHP _MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(zeppelin)
{
    php_info_print_table_start();
    php_info_print_table_header(2, "zeppelin support", "enabled");
    php_info_print_table_end();

    /* Remove comments if you have entries in php.ini
    DISPLAY_INI_ENTRIES();
    */
}
/* }}} */

PHP_METHOD(Zeppelin, __construct)
{
  char *ip = NULL;
  int ip_len = 0;
  int port = 0;
  char *table = NULL;
  int table_len = 0;
  zval *self;
  zval *object;
  int id;
  int timeout = -1;
  libzp::Options options;
  libzp::Client *zp = NULL;
  char * addrs = NULL;
  int addrs_len = 0;

  if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss|l",
	&object, zeppelin_client_ext, &addrs, &addrs_len, &table, &table_len, &timeout) == SUCCESS) {
	std::vector<std::string> addr_v;
	char *addr = strtok(addrs, ";");
	while(addr != NULL) {
	  addr_v.push_back(std::string(addr));
	  addr = strtok(NULL,";");
	}

	std::string ip;
	int port = 0;
	// Split address into ip and port
	for (size_t i = 0; i < addr_v.size(); i++) {
	  if(!slash::ParseIpPortString(addr_v[i], ip, port)) {
		RETURN_FALSE;
	  }
	  libzp::Node node(ip, port);
	  options.meta_addr.push_back(node);
	}
	// Timeout
	if (timeout != -1) {
	  options.op_timeout = timeout;
	}
	// Connect
	zp = new libzp::Client(options, std::string(table, table_len));
  } else {
	RETURN_FALSE;
  }

#if PHP_VERSION_ID >= 50400
	id = zend_list_insert(zp, le_zeppelin TSRMLS_CC);
#else
	id = zend_list_insert(zp, le_zeppelin);
#endif
	add_property_resource(object, "Zeppelin", id);
}

PHP_METHOD(Zeppelin, __destruct)
{
    // todo
}

PHP_FUNCTION(confirm_zeppelin_compiled)
{
    char *arg = NULL;
    int arg_len, len;
    char *strg;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
        return;
    }

    len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "zeppelin", arg);
    RETURN_STRINGL(strg, len, 0);
}

PHP_METHOD(Zeppelin, set)
{
    char *key   = NULL;
    char *value = NULL;
    int argc = ZEND_NUM_ARGS();
    int key_len   = 0;
    int value_len = 0;
    zval *object;
    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss",
                &object, zeppelin_client_ext, &key, &key_len, &value, &value_len) == FAILURE) {
        return;
    }

	libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

	libzp::Status s = zp->Set(std::string(key, key_len), std::string(value, value_len));
    if (s.ok()) {
        RETVAL_TRUE;
    } else {
        RETVAL_FALSE;
    }
}

PHP_METHOD(Zeppelin, get)
{
    struct timeval tv;
    char *key   = NULL;
    int argc = ZEND_NUM_ARGS();
    int key_len   = 0;
    zval *object;
    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os",
                &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {
        return;
    }

	libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

    std::string val;
	libzp::Status s = zp->Get(std::string(key, key_len), &val);
	if (s.ok()) {
        RETVAL_STRINGL((char *)val.data(), val.size(), 1);
	} else {
        RETVAL_FALSE;
	}
}

PHP_METHOD(Zeppelin, mget)
{
    zval *keys = NULL;
    int argc = ZEND_NUM_ARGS();
    zval *object;

    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa",
                &object, zeppelin_client_ext, &keys) == FAILURE) {
        RETURN_FALSE;
    }

    libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

    std::vector<std::string> vkeys;
    if (Z_TYPE_P(keys) == IS_ARRAY) {
        zval **arrval;
        HashPosition pos;
        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos);
        while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&arrval, &pos) == SUCCESS) {
            if (Z_TYPE_PP(arrval) == IS_STRING) {
                vkeys.push_back(std::string(Z_STRVAL_PP(arrval), Z_STRLEN_PP(arrval)));
            }
            zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos);
        }
    }

    std::map<std::string, std::string> result;
    libzp::Status s = zp->Mget(vkeys, &result);
    if (s.ok()) {
        if (return_value_used) {
            array_init(return_value);
            std::map<std::string, std::string>::iterator r_it = result.begin();
            for (; r_it != result.end(); ++r_it) {
                add_assoc_string(return_value, (char *) r_it->first.data(),
                    (char *) r_it->second.data(), 1);
            }
        }
    } else {
        RETVAL_FALSE;
    }
}

PHP_METHOD(Zeppelin, delete)
{
    char *key   = NULL;
    int argc = ZEND_NUM_ARGS();
    int key_len   = 0;
    zval *object;
    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os",
                &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {
        return;
    }

	libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

	libzp::Status s = zp->Delete(std::string(key, key_len));
    if (s.ok()) {
        RETVAL_TRUE;
    } else {
        RETVAL_FALSE;
    }
}

/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/*
 * Local variables:

/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<commit_msg>bugfix phpzeppelin mget<commit_after>/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2011 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id: header 310447 2011-04-23 21:14:10Z bjori $ */
extern "C"
{
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
}

#include <vector>
#include <string>
#include "php_zeppelin.h"
#include "libzp/include/zp_client.h"
#include "slash/include/slash_status.h"
#include "zend.h"

/* If you declare any globals in php_zeppelin.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(zeppelin)
*/
static int le_zeppelin;

/* True global resources - no need for thread safety here */
zend_class_entry *zeppelin_client_ext;

/* {{{ zeppelin_functions[]
 *
 * Every user visible function must have an entry in zeppelin_functions[].
 */

//zend_function_entry zeppelin_functions[] = {
//    PHP_FE(confirm_zeppelin_compiled,    NULL)        /* For testing, remove later. */
//    PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)
//    PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)
//    {NULL, NULL, NULL}
//    //PHP_FE_END    /* Must be the last line in zeppelin_functions[] */
//};
zend_function_entry zeppelin_functions[] = {
	{NULL, NULL, NULL}
};

zend_function_entry phppan_functions[] = {
    PHP_FE(confirm_zeppelin_compiled,    NULL)        /* For testing, remove later. */
    PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Zeppelin, mget, NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};
/* }}} */

/* {{{ zeppelin_module_entry
 */
zend_module_entry zeppelin_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    "zeppelin",
    zeppelin_functions,
    PHP_MINIT(zeppelin),
    PHP_MSHUTDOWN(zeppelin),
    PHP_RINIT(zeppelin),        /* Replace with NULL if there's nothing to do at request start */
    PHP_RSHUTDOWN(zeppelin),    /* Replace with NULL if there's nothing to do at request end */
    PHP_MINFO(zeppelin),
#if ZEND_MODULE_API_NO >= 20010901
    "0.1", /* Replace with version number for your extension */
#endif
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

extern "C"
{
#ifdef COMPILE_DL_ZEPPELIN
ZEND_GET_MODULE(zeppelin)
#endif
}

static void zeppelin_destructor_zeppelin_client(zend_rsrc_list_entry * rsrc TSRMLS_DC)
{
	libzp::Client *zp = (libzp::Client *) rsrc->ptr;
    delete zp;
}

int zeppelin_client_get(zval *id, libzp::Client **zeppelin_sock TSRMLS_DC, int no_throw)
{
    zval **socket;
    int resource_type;

    if (Z_TYPE_P(id) != IS_OBJECT || zend_hash_find(Z_OBJPROP_P(id), "Zeppelin",
                sizeof("Zeppelin"), (void **) &socket) == FAILURE) {
        return -1;
    }

    *zeppelin_sock = (libzp::Client *) zend_list_find(Z_LVAL_PP(socket), &resource_type);

    if (!*zeppelin_sock || resource_type != le_zeppelin) {
        return -1;
    }

    return Z_LVAL_PP(socket);
}

PHP_MINIT_FUNCTION(zeppelin)
{
    /* If you have INI entries, uncomment these lines
    REGISTER_INI_ENTRIES();
    */
    zend_class_entry zeppelin_class_entry;
//    INIT_CLASS_ENTRY(zeppelin_class_entry, "Zeppelin", zeppelin_functions);
    INIT_CLASS_ENTRY(zeppelin_class_entry, "Zeppelin", phppan_functions);
    zeppelin_client_ext = zend_register_internal_class(&zeppelin_class_entry TSRMLS_CC);

    le_zeppelin = zend_register_list_destructors_ex(
        zeppelin_destructor_zeppelin_client,
        NULL,
        "zeppelin-client", module_number
    );

    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(zeppelin)
{
    /* uncomment this line if you have INI entries
    UNREGISTER_INI_ENTRIES();
    */
    return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(zeppelin)
{
    return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(zeppelin)
{
    return SUCCESS;
}
/* }}} */

/* {{{ PHP _MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(zeppelin)
{
    php_info_print_table_start();
    php_info_print_table_header(2, "zeppelin support", "enabled");
    php_info_print_table_end();

    /* Remove comments if you have entries in php.ini
    DISPLAY_INI_ENTRIES();
    */
}
/* }}} */

PHP_METHOD(Zeppelin, __construct)
{
  char *ip = NULL;
  int ip_len = 0;
  int port = 0;
  char *table = NULL;
  int table_len = 0;
  zval *self;
  zval *object;
  int id;
  int timeout = -1;
  libzp::Options options;
  libzp::Client *zp = NULL;
  char * addrs = NULL;
  int addrs_len = 0;

  if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss|l",
	&object, zeppelin_client_ext, &addrs, &addrs_len, &table, &table_len, &timeout) == SUCCESS) {
	std::vector<std::string> addr_v;
	char *addr = strtok(addrs, ";");
	while(addr != NULL) {
	  addr_v.push_back(std::string(addr));
	  addr = strtok(NULL,";");
	}

	std::string ip;
	int port = 0;
	// Split address into ip and port
	for (size_t i = 0; i < addr_v.size(); i++) {
	  if(!slash::ParseIpPortString(addr_v[i], ip, port)) {
		RETURN_FALSE;
	  }
	  libzp::Node node(ip, port);
	  options.meta_addr.push_back(node);
	}
	// Timeout
	if (timeout != -1) {
	  options.op_timeout = timeout;
	}
	// Connect
	zp = new libzp::Client(options, std::string(table, table_len));
  } else {
	RETURN_FALSE;
  }

#if PHP_VERSION_ID >= 50400
	id = zend_list_insert(zp, le_zeppelin TSRMLS_CC);
#else
	id = zend_list_insert(zp, le_zeppelin);
#endif
	add_property_resource(object, "Zeppelin", id);
}

PHP_METHOD(Zeppelin, __destruct)
{
    // todo
}

PHP_FUNCTION(confirm_zeppelin_compiled)
{
    char *arg = NULL;
    int arg_len, len;
    char *strg;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
        return;
    }

    len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "zeppelin", arg);
    RETURN_STRINGL(strg, len, 0);
}

PHP_METHOD(Zeppelin, set)
{
    char *key   = NULL;
    char *value = NULL;
    int argc = ZEND_NUM_ARGS();
    int key_len   = 0;
    int value_len = 0;
    zval *object;
    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss",
                &object, zeppelin_client_ext, &key, &key_len, &value, &value_len) == FAILURE) {
        return;
    }

	libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

	libzp::Status s = zp->Set(std::string(key, key_len), std::string(value, value_len));
    if (s.ok()) {
        RETVAL_TRUE;
    } else {
        RETVAL_FALSE;
    }
}

PHP_METHOD(Zeppelin, get)
{
    struct timeval tv;
    char *key   = NULL;
    int argc = ZEND_NUM_ARGS();
    int key_len   = 0;
    zval *object;
    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os",
                &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {
        return;
    }

	libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

    std::string val;
	libzp::Status s = zp->Get(std::string(key, key_len), &val);
	if (s.ok()) {
        RETVAL_STRINGL((char *)val.data(), val.size(), 1);
	} else {
        RETVAL_FALSE;
	}
}

PHP_METHOD(Zeppelin, mget)
{
    zval *keys = NULL;
    int argc = ZEND_NUM_ARGS();
    zval *object;

    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa",
                &object, zeppelin_client_ext, &keys) == FAILURE) {
        RETURN_FALSE;
    }

    libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

    std::vector<std::string> vkeys;
    if (Z_TYPE_P(keys) == IS_ARRAY) {
        zval **arrval;
        HashPosition pos;
        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos);
        while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&arrval, &pos) == SUCCESS) {
            if (Z_TYPE_PP(arrval) == IS_STRING) {
                vkeys.push_back(std::string(Z_STRVAL_PP(arrval), Z_STRLEN_PP(arrval)));
            }
            zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos);
        }
    }

    std::map<std::string, std::string> result;
    libzp::Status s = zp->Mget(vkeys, &result);
    if (s.ok()) {
        if (return_value_used) {
            array_init(return_value);
            std::map<std::string, std::string>::iterator r_it = result.begin();
            for (; r_it != result.end(); ++r_it) {
				add_assoc_stringl_ex(return_value, (char *) r_it->first.data(), r_it->first.size() + 1,
					(char *) r_it->second.data(), r_it->second.size(), 1);
            }
        }
    } else {
        RETVAL_FALSE;
    }
}

PHP_METHOD(Zeppelin, delete)
{
    char *key   = NULL;
    int argc = ZEND_NUM_ARGS();
    int key_len   = 0;
    zval *object;
    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os",
                &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {
        return;
    }

	libzp::Client *zp;
    if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {
        RETURN_FALSE;
    }

	libzp::Status s = zp->Delete(std::string(key, key_len));
    if (s.ok()) {
        RETVAL_TRUE;
    } else {
        RETVAL_FALSE;
    }
}

/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/*
 * Local variables:

/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<|endoftext|>


<commit_before>#include <unordered_map>
#include <mutex>
#include <thread>

#include <brynet/net/Platform.h>
#include <brynet/net/Noexcept.h>

#include <brynet/net/SSLHelper.h>

namespace brynet { namespace net {

    SSLHelper::Ptr SSLHelper::Create()
    {
        class make_shared_enabler : public SSLHelper {};
        return std::make_shared<make_shared_enabler>();
    }

    SSLHelper::SSLHelper() BRYNET_NOEXCEPT
    {
#ifdef USE_OPENSSL
        mOpenSSLCTX = nullptr;
#endif
    }

    SSLHelper::~SSLHelper() BRYNET_NOEXCEPT
    {
#ifdef USE_OPENSSL
        destroySSL();
#endif
    }

#ifdef USE_OPENSSL
    SSL_CTX* SSLHelper::getOpenSSLCTX()
    {
        return mOpenSSLCTX;
    }

    static void cryptoSetThreadIDCallback(CRYPTO_THREADID* id)
    {
#ifdef PLATFORM_WINDOWS
        CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(GetCurrentThreadId()));
#else
        CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(pthread_self()));
#endif
    }

    static std::unordered_map<int, std::shared_ptr<std::mutex>> cryptoLocks;
    static void cryptoLockingCallback(int mode,
        int type,
        const char *file, int line)
    {
        (void)file;
        (void)line;
        if (mode & CRYPTO_LOCK)
        {
            cryptoLocks[type]->lock();
        }
        else if (mode & CRYPTO_UNLOCK)
        {
            cryptoLocks[type]->unlock();
        }
    }

    static std::once_flag initCryptoThreadSafeSupportOnceFlag;
    static void InitCryptoThreadSafeSupport()
    {
        for (int i = 0; i < CRYPTO_num_locks(); i++)
        {
            cryptoLocks[i] = std::make_shared<std::mutex>();
        }

        CRYPTO_THREADID_set_callback(cryptoSetThreadIDCallback);
        CRYPTO_set_locking_callback(cryptoLockingCallback);
    }

    bool SSLHelper::initSSL(const std::string& certificate, const std::string& privatekey)
    {
        std::call_once(initCryptoThreadSafeSupportOnceFlag, InitCryptoThreadSafeSupport);

        if (mOpenSSLCTX != nullptr)
        {
            return false;
        }
        if (certificate.empty() || privatekey.empty())
        {
            return false;
        }

        mOpenSSLCTX = SSL_CTX_new(SSLv23_method());
        SSL_CTX_set_client_CA_list(mOpenSSLCTX, SSL_load_client_CA_file(certificate.c_str()));
        SSL_CTX_set_verify_depth(mOpenSSLCTX, 10);

        if (SSL_CTX_use_certificate_chain_file(mOpenSSLCTX, certificate.c_str()) <= 0)
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
            return false;
        }

        if (SSL_CTX_use_PrivateKey_file(mOpenSSLCTX, privatekey.c_str(), SSL_FILETYPE_PEM) <= 0)
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
            return false;
        }

        if (!SSL_CTX_check_private_key(mOpenSSLCTX))
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
            return false;
        }

        return true;
    }

    void SSLHelper::destroySSL()
    {
        if (mOpenSSLCTX != nullptr)
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
        }
    }
#endif

} }<commit_msg>fix warning of unused ssl crypto function<commit_after>#include <unordered_map>
#include <mutex>
#include <thread>

#include <brynet/net/Platform.h>
#include <brynet/net/Noexcept.h>

#include <brynet/net/SSLHelper.h>

namespace brynet { namespace net {

    SSLHelper::Ptr SSLHelper::Create()
    {
        class make_shared_enabler : public SSLHelper {};
        return std::make_shared<make_shared_enabler>();
    }

    SSLHelper::SSLHelper() BRYNET_NOEXCEPT
    {
        #ifdef USE_OPENSSL
        mOpenSSLCTX = nullptr;
        #endif
    }

    SSLHelper::~SSLHelper() BRYNET_NOEXCEPT
    {
        #ifdef USE_OPENSSL
        destroySSL();
        #endif
    }

    #ifdef USE_OPENSSL
    SSL_CTX* SSLHelper::getOpenSSLCTX()
    {
        return mOpenSSLCTX;
    }

    #ifndef CRYPTO_THREADID_set_callback
    static void cryptoSetThreadIDCallback(CRYPTO_THREADID* id)
    {
        #ifdef PLATFORM_WINDOWS
        CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(GetCurrentThreadId()));
        #else
        CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(pthread_self()));
        #endif
    }
    #endif

    #ifndef CRYPTO_set_locking_callback
    static std::unordered_map<int, std::shared_ptr<std::mutex>> cryptoLocks;
    static void cryptoLockingCallback(int mode,
        int type,
        const char *file, int line)
    {
        (void)file;
        (void)line;
        if (mode & CRYPTO_LOCK)
        {
            cryptoLocks[type]->lock();
        }
        else if (mode & CRYPTO_UNLOCK)
        {
            cryptoLocks[type]->unlock();
        }
    }
    #endif

    static std::once_flag initCryptoThreadSafeSupportOnceFlag;
    static void InitCryptoThreadSafeSupport()
    {
        #ifndef CRYPTO_THREADID_set_callback
        CRYPTO_THREADID_set_callback(cryptoSetThreadIDCallback);
        #endif

        #ifndef CRYPTO_set_locking_callback
        for (int i = 0; i < CRYPTO_num_locks(); i++)
        {
            cryptoLocks[i] = std::make_shared<std::mutex>();
        }
        CRYPTO_set_locking_callback(cryptoLockingCallback);
        #endif
    }

    bool SSLHelper::initSSL(const std::string& certificate, const std::string& privatekey)
    {
        std::call_once(initCryptoThreadSafeSupportOnceFlag, InitCryptoThreadSafeSupport);

        if (mOpenSSLCTX != nullptr)
        {
            return false;
        }
        if (certificate.empty() || privatekey.empty())
        {
            return false;
        }

        mOpenSSLCTX = SSL_CTX_new(SSLv23_method());
        SSL_CTX_set_client_CA_list(mOpenSSLCTX, SSL_load_client_CA_file(certificate.c_str()));
        SSL_CTX_set_verify_depth(mOpenSSLCTX, 10);

        if (SSL_CTX_use_certificate_chain_file(mOpenSSLCTX, certificate.c_str()) <= 0)
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
            return false;
        }

        if (SSL_CTX_use_PrivateKey_file(mOpenSSLCTX, privatekey.c_str(), SSL_FILETYPE_PEM) <= 0)
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
            return false;
        }

        if (!SSL_CTX_check_private_key(mOpenSSLCTX))
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
            return false;
        }

        return true;
    }

    void SSLHelper::destroySSL()
    {
        if (mOpenSSLCTX != nullptr)
        {
            SSL_CTX_free(mOpenSSLCTX);
            mOpenSSLCTX = nullptr;
        }
    }
    #endif

} }<|endoftext|>