<commit_before>///////////////////////////////////////////////////////////////
//Generates forwarding headers using the information
//in the header.lst & vendor.lst files
//
//To create a header list from an existing directory of headers
//dir *.h /b > headers.lst

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <ctime>
using namespace std;

struct Compiler
	{
	Compiler() {}
	Compiler(const string& VersionTest, const string& SubDir) :
	 version_test(VersionTest), subdir(SubDir)
		{}
	string version_test;
	string subdir;
	};

typedef vector<Compiler> cv_t;

int main(int argc, char* argv[])
	{
	if(argc < 2)
		{
		cout <<"Usage: <Header List> [Version/Vender List]"<<endl;
		return -1;
		}

	cv_t vendors;
	char buf[1024];
	string check;
	string subdir;
	fstream vendor_file;
	if(argc >= 3)
		{
		vendor_file.open(argv[2], ios::in);
		if(!vendor_file.is_open())
			{
			cout << "Unable to open vendor file: " << argv[2] << endl;
			return -2;
			}
		else
			{
			vendors.reserve(10);
			while(!vendor_file.eof())
				{
				check  = "";
				subdir = "";
				vendor_file.getline(buf, 1024, '\n');
				check = buf;
				vendor_file.getline(buf, 1024, '\n');
				subdir = buf;
				vendor_file.getline(buf, 1024, '\n');
				if(!(check.empty() || subdir.empty()))
					vendors.push_back(Compiler(check, subdir));
				else
					{
					cout << "Error parsing vendors, check:" << check << "\tsubdir:" << subdir << endl;
					}
				}
			}
		}
	else //if(vendors.empty())
		{
		cout << "No vendor file provided, using defaults\n";
		vendors.reserve(10);
		vendors.push_back(Compiler("(_MSC_VER >= 1300)", "MSVC\\1300"));
		vendors.push_back(Compiler("(__BORLANDC__)", "Borland"));
		vendors.push_back(Compiler("( (__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ > 95)) )", "Reference"));
		}

	fstream header_list(argv[1]);
	string header;
	stringstream ss;

	if(!header_list.is_open())
		{
		cout << "Invalid header list file, " << argv[1] << endl;
		return -3;
		}
	while(!header_list.eof())
		{
		header_list >> header;
		cout << header << endl;
		fstream header_file(header.c_str(), ios::out);
		if(!header_file.is_open())
			{
			cout << "Unable to open header file for output: " << header << endl;
			}
		else
			{
			ss.str("");
			ss << "//Generated header: " << header << endl;
			size_t n = ss.str().size();
			for(size_t i=0; i<n; ++i)
				header_file << "/";
			header_file << endl;
			header_file << ss.str();
			header_file << "//Forwards to the appropriate code\n";
			header_file << "// that works on the detected compiler\n";
			time_t rawtime; time(&rawtime);
			header_file << "//Generated on " << ctime(&rawtime);
			header_file << endl << endl;

			cv_t::iterator it=vendors.begin(), itEnd = vendors.end();

			header_file << "#ifdef LOKI_USE_REFERENCE\n";
			header_file << "#\tinclude \"./Reference/" << header << "\"\n";
			//header_file << "#\tinclude \".\\Reference\\" << header << "\"\n";
			header_file << "#else\n";

			header_file << "#\tif " << it->version_test << endl;
			//header_file << "#\t\tinclude \".\\" << it->subdir;
			header_file << "#\t\tinclude \"./" << it->subdir;
			//header_file << "\\" << header << "\"\n";
			header_file << "/" << header << "\"\n";
			++it;
			for(; it!=itEnd; ++it)
				{
				header_file << "#\telif " << it->version_test << endl;
				//header_file << "#\t\tinclude \".\\" << it->subdir;
				header_file << "#\t\tinclude \"." << it->subdir;
				//header_file << "\\" << header << "\"\n";
				header_file << "/" << header << "\"\n";
				}
			header_file << "#\telse\n";
			header_file << "\t\t//Define LOKI_USE_REFERENCE and get back to us on the results\n";
			header_file << "#\t\terror Compiler not tested with Loki, #define LOKI_USE_REFERENCE\n";
			header_file << "#\tendif\n";
			header_file << "#endif\n";
			}
		}
#ifdef _MSC_VER
	system("PAUSE");
#endif
	return 0;
	}<commit_msg>Fixed missing / bug<commit_after>///////////////////////////////////////////////////////////////
//Generates forwarding headers using the information
//in the header.lst & vendor.lst files
//
//To create a header list from an existing directory of headers
//dir *.h /b > headers.lst

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <ctime>
using namespace std;

struct Compiler
	{
	Compiler() {}
	Compiler(const string& VersionTest, const string& SubDir) :
	 version_test(VersionTest), subdir(SubDir)
		{}
	string version_test;
	string subdir;
	};

typedef vector<Compiler> cv_t;

int main(int argc, char* argv[])
	{
	if(argc < 2)
		{
		cout <<"Usage: <Header List> [Version/Vendor List]"<<endl;
		return -1;
		}

	cv_t vendors;
	char buf[1024];
	string check;
	string subdir;
	fstream vendor_file;
	if(argc >= 3)
		{
		vendor_file.open(argv[2], ios::in);
		if(!vendor_file.is_open())
			{
			cout << "Unable to open vendor file: " << argv[2] << endl;
			return -2;
			}
		else
			{
			vendors.reserve(10);
			while(!vendor_file.eof())
				{
				check  = "";
				subdir = "";
				vendor_file.getline(buf, 1024, '\n');
				check = buf;
				vendor_file.getline(buf, 1024, '\n');
				subdir = buf;
				vendor_file.getline(buf, 1024, '\n');
				if(!(check.empty() || subdir.empty()))
					vendors.push_back(Compiler(check, subdir));
				else
					{
					cout << "Error parsing vendors, check:" << check << "\tsubdir:" << subdir << endl;
					}
				}
			}
		}
	else //if(vendors.empty())
		{
		cout << "No vendor file provided, using defaults\n";
		vendors.reserve(10);
		vendors.push_back(Compiler("(_MSC_VER >= 1300)", "MSVC\\1300"));
		vendors.push_back(Compiler("(__BORLANDC__)", "Borland"));
		vendors.push_back(Compiler("( (__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ > 95)) )", "Reference"));
		}

	fstream header_list(argv[1]);
	string header;
	stringstream ss;

	if(!header_list.is_open())
		{
		cout << "Invalid header list file, " << argv[1] << endl;
		return -3;
		}
	while(!header_list.eof())
		{
		header_list >> header;
		cout << header << endl;
		fstream header_file(header.c_str(), ios::out);
		if(!header_file.is_open())
			{
			cout << "Unable to open header file for output: " << header << endl;
			}
		else
			{
			ss.str("");
			ss << "//Generated header: " << header << endl;
			size_t n = ss.str().size();
			for(size_t i=0; i<n; ++i)
				header_file << "/";
			header_file << endl;
			header_file << ss.str();
			header_file << "//Forwards to the appropriate code\n";
			header_file << "// that works on the detected compiler\n";
			time_t rawtime; time(&rawtime);
			header_file << "//Generated on " << ctime(&rawtime);
			header_file << endl << endl;

			cv_t::iterator it=vendors.begin(), itEnd = vendors.end();

			header_file << "#ifdef LOKI_USE_REFERENCE\n";
			header_file << "#\tinclude \"./Reference/" << header << "\"\n";
			//header_file << "#\tinclude \".\\Reference\\" << header << "\"\n";
			header_file << "#else\n";

			header_file << "#\tif " << it->version_test << endl;
			//header_file << "#\t\tinclude \".\\" << it->subdir;
			header_file << "#\t\tinclude \"./" << it->subdir;
			//header_file << "\\" << header << "\"\n";
			header_file << "/" << header << "\"\n";
			++it;
			for(; it!=itEnd; ++it)
				{
				header_file << "#\telif " << it->version_test << endl;
				//header_file << "#\t\tinclude \".\\" << it->subdir;
				header_file << "#\t\tinclude \"./" << it->subdir;
				//header_file << "\\" << header << "\"\n";
				header_file << "/" << header << "\"\n";
				}
			header_file << "#\telse\n";
			header_file << "\t\t//Define LOKI_USE_REFERENCE and get back to us on the results\n";
			header_file << "#\t\terror Compiler not tested with Loki, #define LOKI_USE_REFERENCE\n";
			header_file << "#\tendif\n";
			header_file << "#endif\n";
			}
		}
#ifdef _MSC_VER
	system("PAUSE");
#endif
	return 0;
	}<|endoftext|>


<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 <cstdlib>

#include <fstream>
#include <iostream>
#include <string>

#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/signal/debug_handler.h"
#include "src/ext/cpputil/include/system/terminal.h"

#include "src/cfg/dot_writer.h"
#include "tools/gadgets/target.h"
#include "tools/ui/console.h"

using namespace cpputil;
using namespace std;
using namespace stoke;

auto& content = Heading::create("Content Options:");
auto& dib = FlagArg::create("dib")
            .alternate("def_in_block")
            .description("Display def in values for basic blocks");
auto& dii = FlagArg::create("dii")
            .alternate("def_in_instr")
            .description("Display def in values for instructions");
auto& lob = FlagArg::create("lob")
            .alternate("live_out_block")
            .description("Display live out values for basic blocks");
auto& dom = FlagArg::create("dom")
            .alternate("dominators")
            .description("Display dominators");

auto& io = Heading::create("I/O Options:");
auto& out = ValueArg<string>::create("o")
            .alternate("out")
            .usage("<path/to/file.pdf>")
            .description("Path to write cfg to")
            .default_val("./cfg.pdf");
auto& view = FlagArg::create("view")
             .alternate("v")
             .description("View cfg immediately");

void to_dot() {
  ofstream ofs(string("/tmp/stoke.") + getenv("USER") + ".dot");

  TargetGadget target;

  DotWriter dw;
  dw.set_def_in(dib, dii)
  .set_live_out(lob)
  .set_dom(dom);

  dw(ofs, target);
}

bool to_pdf() {
  Terminal term;
  term << "cat /tmp/stoke.$USER.dot | dot -Tpdf > " << out.value() << endl;
  return term.result() == 0;
}

bool view_pdf() {
  Terminal term;
  term << "evince " << out.value() << endl;
  return term.result() == 0;
}

bool rm_pdf() {
  Terminal term;
  term << "rm -f " << out.value() << endl;
  return term.result() == 0;
}

int main(int argc, char** argv) {
  CommandLineConfig::strict_with_convenience(argc, argv);
  DebugHandler::install_sigsegv();
  DebugHandler::install_sigill();

  to_dot();
  if (!to_pdf()) {
    Console::error(1) << "Unable to save file!" << endl;
  } else if (view && !view_pdf()) {
    Console::error(1) << "Unable to open file for viewing!" << endl;
  } else if (view && !rm_pdf()) {
    Console::error(1) << "Unable to remove file!" << endl;
  }

  return 0;
}

<commit_msg>mkstmp in stoke debug cfg.<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 <cstdlib>

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/signal/debug_handler.h"
#include "src/ext/cpputil/include/system/terminal.h"

#include "src/cfg/dot_writer.h"
#include "tools/gadgets/target.h"
#include "tools/ui/console.h"

using namespace cpputil;
using namespace std;
using namespace stoke;

auto& content = Heading::create("Content Options:");
auto& dib = FlagArg::create("dib")
            .alternate("def_in_block")
            .description("Display def in values for basic blocks");
auto& dii = FlagArg::create("dii")
            .alternate("def_in_instr")
            .description("Display def in values for instructions");
auto& lob = FlagArg::create("lob")
            .alternate("live_out_block")
            .description("Display live out values for basic blocks");
auto& dom = FlagArg::create("dom")
            .alternate("dominators")
            .description("Display dominators");

auto& io = Heading::create("I/O Options:");
auto& out = ValueArg<string>::create("o")
            .alternate("out")
            .usage("<path/to/file.pdf>")
            .description("Path to write cfg to")
            .default_val("./cfg.pdf");
auto& view = FlagArg::create("view")
             .alternate("v")
             .description("View cfg immediately");

string tempfile(const string& temp) {
	vector<char> v(temp.begin(), temp.end());
	v.push_back('\0');

	const auto fd = mkstemp(v.data());
	return string(v.begin(), v.end()-1);
}

void to_dot(const string& dot_file) {
  ofstream ofs(dot_file);

  TargetGadget target;

  DotWriter dw;
  dw.set_def_in(dib, dii)
  .set_live_out(lob)
  .set_dom(dom);

  dw(ofs, target);
}

bool to_pdf(const string& dot_file, const string& pdf_file) {
  Terminal term;
  term << "cat " << dot_file << " | dot -Tpdf > " << pdf_file << " 2> /dev/null" << endl;
  return term.result() == 0;
}

bool view_pdf(const string& pdf_file) {
  Terminal term;
  term << "evince " << pdf_file << endl;
  return term.result() == 0;
}

int main(int argc, char** argv) {
  CommandLineConfig::strict_with_convenience(argc, argv);
  DebugHandler::install_sigsegv();
  DebugHandler::install_sigill();

	const auto dot_file = tempfile("/tmp/stoke_debug_cfg.dot.XXXXXX");

  to_dot(dot_file);
  if (!to_pdf(dot_file, out.value())) {
    Console::error(1) << "Unable to save file!" << endl;
  } else if (view && !view_pdf(out.value())) {
    Console::error(1) << "Unable to open file for viewing!" << endl;
  }

  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "OrbitClientServices/ProcessClient.h"

#include "OrbitBase/Logging.h"
#include "grpcpp/grpcpp.h"
#include "outcome.hpp"
#include "services.grpc.pb.h"
#include "symbol.pb.h"
#include "tracepoint.pb.h"

namespace {

using orbit_grpc_protos::GetDebugInfoFileRequest;
using orbit_grpc_protos::GetDebugInfoFileResponse;
using orbit_grpc_protos::GetModuleListRequest;
using orbit_grpc_protos::GetModuleListResponse;
using orbit_grpc_protos::GetProcessListRequest;
using orbit_grpc_protos::GetProcessListResponse;
using orbit_grpc_protos::GetProcessMemoryRequest;
using orbit_grpc_protos::GetProcessMemoryResponse;
using orbit_grpc_protos::GetTracepointListRequest;
using orbit_grpc_protos::GetTracepointListResponse;
using orbit_grpc_protos::ModuleInfo;
using orbit_grpc_protos::ProcessInfo;
using orbit_grpc_protos::ProcessService;
using orbit_grpc_protos::TracepointInfo;

constexpr uint64_t kGrpcDefaultTimeoutMilliseconds = 1000;

std::unique_ptr<grpc::ClientContext> CreateContext(uint64_t timeout_milliseconds) {
  auto context = std::make_unique<grpc::ClientContext>();

  std::chrono::time_point deadline =
      std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_milliseconds);
  context->set_deadline(deadline);

  return context;
}

}  // namespace

ErrorMessageOr<std::vector<orbit_grpc_protos::ProcessInfo>> ProcessClient::GetProcessList() {
  GetProcessListRequest request;
  GetProcessListResponse response;
  std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);

  grpc::Status status = process_service_->GetProcessList(context.get(), request, &response);
  if (!status.ok()) {
    ERROR("gRPC call to GetProcessList failed: %s (error_code=%d)", status.error_message(),
          status.error_code());
    return ErrorMessage(status.error_message());
  }

  const auto& processes = response.processes();

  return std::vector<ProcessInfo>(processes.begin(), processes.end());
}

ErrorMessageOr<std::vector<ModuleInfo>> ProcessClient::LoadModuleList(int32_t pid) {
  GetModuleListRequest request;
  GetModuleListResponse response;
  request.set_process_id(pid);

  std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
  grpc::Status status = process_service_->GetModuleList(context.get(), request, &response);

  if (!status.ok()) {
    ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
    return ErrorMessage(status.error_message());
  }

  const auto& modules = response.modules();

  return std::vector<ModuleInfo>(modules.begin(), modules.end());
}

ErrorMessageOr<std::vector<TracepointInfo>> ProcessClient::LoadTracepointList() {
  GetTracepointListRequest request;
  GetTracepointListResponse response;

  std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
  grpc::Status status = process_service_->GetTracepointList(context.get(), request, &response);

  if (!status.ok()) {
    ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
    return ErrorMessage(status.error_message());
  }

  const auto& tracepoints = response.tracepoints();

  return std::vector<TracepointInfo>(tracepoints.begin(), tracepoints.end());
}

ErrorMessageOr<std::string> ProcessClient::FindDebugInfoFile(const std::string& module_path) {
  GetDebugInfoFileRequest request;
  GetDebugInfoFileResponse response;

  request.set_module_path(module_path);

  std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);

  grpc::Status status = process_service_->GetDebugInfoFile(context.get(), request, &response);
  if (!status.ok()) {
    ERROR("gRPC call to GetDebugInfoFile failed: %s", status.error_message());
    return ErrorMessage(status.error_message());
  }

  return response.debug_info_file_path();
}

ErrorMessageOr<std::string> ProcessClient::LoadProcessMemory(int32_t pid, uint64_t address,
                                                             uint64_t size) {
  GetProcessMemoryRequest request;
  request.set_pid(pid);
  request.set_address(address);
  request.set_size(size);

  GetProcessMemoryResponse response;

  std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);

  grpc::Status status = process_service_->GetProcessMemory(context.get(), request, &response);
  if (!status.ok()) {
    ERROR("gRPC call to GetProcessMemory failed: %s", status.error_message());
    return ErrorMessage(status.error_message());
  }

  return std::move(*response.mutable_memory());
}<commit_msg>Add default value for timeout_milliseconds to ProcessClient::CreateContext<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "OrbitClientServices/ProcessClient.h"

#include "OrbitBase/Logging.h"
#include "grpcpp/grpcpp.h"
#include "outcome.hpp"
#include "services.grpc.pb.h"
#include "symbol.pb.h"
#include "tracepoint.pb.h"

namespace {

using orbit_grpc_protos::GetDebugInfoFileRequest;
using orbit_grpc_protos::GetDebugInfoFileResponse;
using orbit_grpc_protos::GetModuleListRequest;
using orbit_grpc_protos::GetModuleListResponse;
using orbit_grpc_protos::GetProcessListRequest;
using orbit_grpc_protos::GetProcessListResponse;
using orbit_grpc_protos::GetProcessMemoryRequest;
using orbit_grpc_protos::GetProcessMemoryResponse;
using orbit_grpc_protos::GetTracepointListRequest;
using orbit_grpc_protos::GetTracepointListResponse;
using orbit_grpc_protos::ModuleInfo;
using orbit_grpc_protos::ProcessInfo;
using orbit_grpc_protos::ProcessService;
using orbit_grpc_protos::TracepointInfo;

constexpr uint64_t kGrpcDefaultTimeoutMilliseconds = 1000;

std::unique_ptr<grpc::ClientContext> CreateContext(
    uint64_t timeout_milliseconds = kGrpcDefaultTimeoutMilliseconds) {
  auto context = std::make_unique<grpc::ClientContext>();
  std::chrono::time_point deadline =
      std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_milliseconds);
  context->set_deadline(deadline);

  return context;
}

}  // namespace

ErrorMessageOr<std::vector<orbit_grpc_protos::ProcessInfo>> ProcessClient::GetProcessList() {
  GetProcessListRequest request;
  GetProcessListResponse response;
  std::unique_ptr<grpc::ClientContext> context = CreateContext();

  grpc::Status status = process_service_->GetProcessList(context.get(), request, &response);
  if (!status.ok()) {
    ERROR("gRPC call to GetProcessList failed: %s (error_code=%d)", status.error_message(),
          status.error_code());
    return ErrorMessage(status.error_message());
  }

  const auto& processes = response.processes();

  return std::vector<ProcessInfo>(processes.begin(), processes.end());
}

ErrorMessageOr<std::vector<ModuleInfo>> ProcessClient::LoadModuleList(int32_t pid) {
  GetModuleListRequest request;
  GetModuleListResponse response;
  request.set_process_id(pid);

  std::unique_ptr<grpc::ClientContext> context = CreateContext();
  grpc::Status status = process_service_->GetModuleList(context.get(), request, &response);

  if (!status.ok()) {
    ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
    return ErrorMessage(status.error_message());
  }

  const auto& modules = response.modules();

  return std::vector<ModuleInfo>(modules.begin(), modules.end());
}

ErrorMessageOr<std::vector<TracepointInfo>> ProcessClient::LoadTracepointList() {
  GetTracepointListRequest request;
  GetTracepointListResponse response;

  std::unique_ptr<grpc::ClientContext> context = CreateContext();
  grpc::Status status = process_service_->GetTracepointList(context.get(), request, &response);

  if (!status.ok()) {
    ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
    return ErrorMessage(status.error_message());
  }

  const auto& tracepoints = response.tracepoints();

  return std::vector<TracepointInfo>(tracepoints.begin(), tracepoints.end());
}

ErrorMessageOr<std::string> ProcessClient::FindDebugInfoFile(const std::string& module_path) {
  GetDebugInfoFileRequest request;
  GetDebugInfoFileResponse response;

  request.set_module_path(module_path);

  std::unique_ptr<grpc::ClientContext> context = CreateContext();

  grpc::Status status = process_service_->GetDebugInfoFile(context.get(), request, &response);
  if (!status.ok()) {
    ERROR("gRPC call to GetDebugInfoFile failed: %s", status.error_message());
    return ErrorMessage(status.error_message());
  }

  return response.debug_info_file_path();
}

ErrorMessageOr<std::string> ProcessClient::LoadProcessMemory(int32_t pid, uint64_t address,
                                                             uint64_t size) {
  GetProcessMemoryRequest request;
  request.set_pid(pid);
  request.set_address(address);
  request.set_size(size);

  GetProcessMemoryResponse response;

  std::unique_ptr<grpc::ClientContext> context = CreateContext();

  grpc::Status status = process_service_->GetProcessMemory(context.get(), request, &response);
  if (!status.ok()) {
    ERROR("gRPC call to GetProcessMemory failed: %s", status.error_message());
    return ErrorMessage(status.error_message());
  }

  return std::move(*response.mutable_memory());
}<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

#include <iostream>

// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"
#include "grins/parabolic_profile.h"

//libMesh
#include "libmesh/dirichlet_boundaries.h"
#include "libmesh/dof_map.h"
//#include "libmesh/exact_solution.h"

// GRVY
#ifdef GRINS_HAVE_GRVY
#include "grvy.h"
#endif

// libMesh::Number
// exact_solution( const libMesh::Point& p,
// 		const libMesh::Parameters&,   // parameters, not needed
// 		const std::string&,  // sys_name, not needed
// 		const std::string&); // unk_name, not needed);

// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// 		  const libMesh::Parameters&,   // parameters, not needed
// 		  const std::string&,  // sys_name, not needed
// 		  const std::string&); // unk_name, not needed);

// class ParabolicBCFactory : public GRINS::BoundaryConditionsFactory
// {
// public:

//   ParabolicBCFactory()
//     : GRINS::BoundaryConditionsFactory()
//   { return; };

//   ~ParabolicBCFactory(){return;};

//   std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > build_dirichlet( );
// };

// Function to set the Dirichlet boundary function for the inlet u velocity and nu profiles
class BdyFunction : public FunctionBase<Number>
{
public:
  BdyFunction (MeshFunction)
    : MeshFunction.initialize)
  { this->_initialized = true; }

  virtual Number operator() (const Point&, const Real = 0)
  { libmesh_not_implemented(); }

  virtual void operator() (const Point& p,
                           const Real,
                           DenseVector<Number>& output)
  {
    output.resize(2);
    output.zero();
    const Real y=p(1);
    // Set the parabolic inflow boundary conditions at stations 0 & 1
    output(_u_var) = (_sign)*((y-2) * (y-3));
    output(_v_var) = 0;
  }

  virtual AutoPtr<FunctionBase<Number> > clone() const
  { return AutoPtr<FunctionBase<Number> > (new BdyFunction(_u_var, _v_var, _sign)); }

private:
  const unsigned int _u_var, _v_var;
};

int main(int argc, char* argv[])
{

#ifdef GRINS_USE_GRVY_TIMERS
  GRVY::GRVY_Timer_Class grvy_timer;
  grvy_timer.Init("GRINS Timer");
#endif

  // Check command line count.
  if( argc < 2 )
    {
      // TODO: Need more consistent error handling.
      std::cerr << "Error: Must specify libMesh input file." << std::endl;
      exit(1); // TODO: something more sophisticated for parallel runs?
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = argv[1];

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

#ifdef GRINS_USE_GRVY_TIMERS
  grvy_timer.BeginTimer("Initialize Solver");
#endif

  // Initialize libMesh library.
  libMesh::LibMeshInit libmesh_init(argc, argv);

  // Build a 1-d turbulent_bc_system to get the bc data from files
  libMesh::SerialMesh mesh(libmesh_init.comm);

  libMesh::AutoPtr<MeshRefinement> mesh_refinement =
    build_mesh_refinement(mesh, param);

  mesh.read("file.xda");

  //mesh.all_second_order();

  // And an EquationSystems to run on it
  libMesh::EquationSystems equation_systems (mesh);

  libMesh::LinearImplicitSystem & turbulent_bc_system = equation_systems.add_system<libMesh::LinearImplicitSystem>("Turbulent-BC");

  equation_systems.read("sol.xda", READ,
			libMesh::EquationSystems::READ_HEADER |
  			     libMesh::EquationSystems::READ_DATA |
  			     libMesh::EquationSystems::READ_ADDITIONAL_DATA);

  // Prepare a global solution and a MeshFunction of the Turbulent system
  libMesh::AutoPtr<MeshFunction> coarse_values;
  libMesh::AutoPtr<libMesh::NumericVector<Number> > turbulent_bc_soln = libMesh::NumericVector<Number>::build(equation_systems.comm());

  std::vector<unsigned int>turbulent_bc_system_variables;
  turbulent_bc_system_variables.push_back(0);
  turbulent_bc_system_variables.push_back(1);

  turbulent_bc_values = libMesh::AutoPtr<libMesh::MeshFunction>
    (new libMesh::MeshFunction(equation_systems,
			       *turbulent_bc_soln,
			       turbulent_bc_system.get_dof_map(),
			       turbulent_bc_system_variables ));

  turbulent_bc_values->init();

  GRINS::SimulationBuilder sim_builder;

  std::tr1::shared_ptr<ParabolicBCFactory> bc_factory( new ParabolicBCFactory );

  sim_builder.attach_bc_factory(bc_factory);

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder,
                           libmesh_init.comm() );

#ifdef GRINS_USE_GRVY_TIMERS
  grvy_timer.EndTimer("Initialize Solver");

  // Attach GRVY timer to solver
  grins.attach_grvy_timer( &grvy_timer );
#endif

  // Solve
  grins.run();

  // Get equation systems to create ExactSolution object
  //std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();

  // Create Exact solution object and attach exact solution quantities
  //libMesh::ExactSolution exact_sol(*es);

  //exact_sol.attach_exact_value(&exact_solution);
  //exact_sol.attach_exact_deriv(&exact_derivative);

  // Compute error and get it in various norms
  //exact_sol.compute_error("GRINS", "u");

  //double l2error = exact_sol.l2_error("GRINS", "u");
  //double h1error = exact_sol.h1_error("GRINS", "u");

  // Needs to change to 1 based on comparison
  int return_flag = 0;

  // if( l2error > 1.0e-9 || h1error > 1.0e-9 )
  //   {
  //     return_flag = 1;

  //     std::cout << "Tolerance exceeded for velocity in Poiseuille test." << std::endl
  // 		<< "l2 error = " << l2error << std::endl
  // 		<< "h1 error = " << h1error << std::endl;
  //   }

  // // Compute error and get it in various norms
  // exact_sol.compute_error("GRINS", "p");

  // l2error = exact_sol.l2_error("GRINS", "p");
  // h1error = exact_sol.h1_error("GRINS", "p");

  // if( l2error > 2.0e-9 || h1error > 2.0e-9 )
  //   {
  //     return_flag = 1;

  //     std::cout << "Tolerance exceeded for pressure in Poiseuille test." << std::endl
  // 		<< "l2 error = " << l2error << std::endl
  // 		<< "h1 error = " << h1error << std::endl;
  //   }

  return return_flag;
}

// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > ParabolicBCFactory::build_dirichlet( )
// {
//   GRINS::DBCContainer cont;
//   cont.add_var_name( "u" );
//   cont.add_bc_id( 1 );
//   cont.add_bc_id( 3 );

//   std::tr1::shared_ptr<libMesh::FunctionBase<libMesh::Number> > u_func( new GRINS::ParabolicProfile );

//   cont.set_func( u_func );

//   std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > mymap;

//   mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::incompressible_navier_stokes,  cont) );

//   return mymap;
// }

// libMesh::Number
// exact_solution( const libMesh::Point& p,
// 		const libMesh::Parameters& /*params*/,   // parameters, not needed
// 		const std::string& /*sys_name*/,  // sys_name, not needed
// 		const std::string& var )  // unk_name, not needed);
// {
//   const double x = p(0);
//   const double y = p(1);

//   libMesh::Number f = 0;
//   // Hardcoded to velocity in input file.
//   if( var == "u" ) f = 4*y*(1-y);
//   else if( var == "p" ) f = 120.0 + (80.0-120.0)/5.0*x;
//   else libmesh_assert(false);

//   return f;
// }

// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// 		  const libMesh::Parameters& /*params*/,   // parameters, not needed
// 		  const std::string& /*sys_name*/,  // sys_name, not needed
// 		  const std::string& var)  // unk_name, not needed);
// {
//   const double y = p(1);

//   libMesh::Gradient g;

//   // Hardcoded to velocity in input file.
//   if( var == "u" )
//     {
//       g(0) = 0.0;
//       g(1) = 4*(1-y) - 4*y;

// #if LIBMESH_DIM > 2
//       g(2) = 0.0;
// #endif
//     }

//   if( var == "p" )
//     {
//       g(0) = (80.0-120.0)/5.0;
//       g(1) = 0.0;

// #if LIBMESH_DIM > 2
//       g(2) = 0.0;
// #endif
//     }
//   return g;
// }
<commit_msg>Turbulent channel example can now read in Todd's 1d solution<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

#include <iostream>

// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"
#include "grins/parabolic_profile.h"

//libMesh
#include "libmesh/dirichlet_boundaries.h"
#include "libmesh/dof_map.h"
#include "libmesh/fe_base.h"
#include "libmesh/fe_interface.h"
#include "libmesh/mesh_function.h"
#include "libmesh/linear_implicit_system.h"
//#include "libmesh/exact_solution.h"

// GRVY
#ifdef GRINS_HAVE_GRVY
#include "grvy.h"
#endif

// Function to set the Dirichlet boundary function for the inlet u velocity and nu profiles
class TurbulentBdyFunction : public libMesh::FunctionBase<libMesh::Number>
{
public:
  TurbulentBdyFunction (libMesh::MeshFunction* _turbulent_bc_values) :
    turbulent_bc_values(_turbulent_bc_values)
  { this->_initialized = true; }

  virtual libMesh::Number operator() (const libMesh::Point&, const libMesh::Real = 0)
  { libmesh_not_implemented(); }

  virtual void operator() (const libMesh::Point& p,
                           const libMesh::Real t,
                           libMesh::DenseVector<libMesh::Number>& output)
  {
    output.resize(4);
    output.zero();
    turbulent_bc_values->operator()(p, t, output);
  }

  virtual libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > clone() const
  { return libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > (new TurbulentBdyFunction(turbulent_bc_values)); }

private:
  libMesh::MeshFunction* turbulent_bc_values;
};

int main(int argc, char* argv[])
{

#ifdef GRINS_USE_GRVY_TIMERS
  GRVY::GRVY_Timer_Class grvy_timer;
  grvy_timer.Init("GRINS Timer");
#endif

  // Check command line count.
  if( argc < 2 )
    {
      // TODO: Need more consistent error handling.
      std::cerr << "Error: Must specify libMesh input file." << std::endl;
      exit(1); // TODO: something more sophisticated for parallel runs?
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = argv[1];

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

#ifdef GRINS_USE_GRVY_TIMERS
  grvy_timer.BeginTimer("Initialize Solver");
#endif

  // Initialize libMesh library.
  libMesh::LibMeshInit libmesh_init(argc, argv);

  // Build a 1-d turbulent_bc_system to get the bc data from files
  libMesh::SerialMesh mesh(libmesh_init.comm());

  mesh.read("/home/vikram/grins/test/test_data/turbulent_channel_Re944_grid.xda");

  //mesh.all_second_order();

  // And an EquationSystems to run on it
  libMesh::EquationSystems equation_systems (mesh);

  libMesh::LinearImplicitSystem & turbulent_bc_system = equation_systems.add_system<libMesh::LinearImplicitSystem>("Turbulent-BC");

  equation_systems.read("/home/vikram/grins/test/test_data/turbulent_channel_soln.xda", libMesh::XdrMODE::READ,
			libMesh::EquationSystems::READ_HEADER |
  			     libMesh::EquationSystems::READ_DATA |
  			     libMesh::EquationSystems::READ_ADDITIONAL_DATA);

  // Prepare a global solution and a MeshFunction of the Turbulent system
  libMesh::AutoPtr<libMesh::MeshFunction> turbulent_bc_values;

libMesh::AutoPtr<libMesh::NumericVector<libMesh::Number> > turbulent_bc_soln = libMesh::NumericVector<libMesh::Number>::build(turbulent_bc_system.comm());

  std::vector<unsigned int>turbulent_bc_system_variables;
  turbulent_bc_system_variables.push_back(0);
  turbulent_bc_system_variables.push_back(3);

  turbulent_bc_values = libMesh::AutoPtr<libMesh::MeshFunction>
    (new libMesh::MeshFunction(equation_systems,
			       *turbulent_bc_soln,
			       turbulent_bc_system.get_dof_map(),
			       turbulent_bc_system_variables ));

  turbulent_bc_values->init();

  TurbulentBdyFunction turbulent_inlet(turbulent_bc_values.get());

  const libMesh::boundary_id_type left_inlet_id = 0;
  std::set<libMesh::boundary_id_type> left_inlet_bdy;
  left_inlet_bdy.insert(left_inlet_id);

  // The uv identifier for the setting the inlet and wall velocity boundary conditions
  std::vector<unsigned int> unu(1, 0);
  unu.push_back(3);

turbulent_bc_system.get_dof_map().add_dirichlet_boundary
(libMesh::DirichletBoundary (left_inlet_bdy, unu, &turbulent_inlet));

  GRINS::SimulationBuilder sim_builder;

//std::tr1::shared_ptr<ParabolicBCFactory> bc_factory( new ParabolicBCFactory );

//sim_builder.attach_bc_factory(bc_factory);

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder,
                           libmesh_init.comm() );

#ifdef GRINS_USE_GRVY_TIMERS
  grvy_timer.EndTimer("Initialize Solver");

  // Attach GRVY timer to solver
  grins.attach_grvy_timer( &grvy_timer );
#endif

  // Solve
  grins.run();

  // Get equation systems to create ExactSolution object
  //std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();

  // Create Exact solution object and attach exact solution quantities
  //libMesh::ExactSolution exact_sol(*es);

  //exact_sol.attach_exact_value(&exact_solution);
  //exact_sol.attach_exact_deriv(&exact_derivative);

  // Compute error and get it in various norms
  //exact_sol.compute_error("GRINS", "u");

  //double l2error = exact_sol.l2_error("GRINS", "u");
  //double h1error = exact_sol.h1_error("GRINS", "u");

  // Needs to change to 1 based on comparison
  int return_flag = 0;

  // if( l2error > 1.0e-9 || h1error > 1.0e-9 )
  //   {
  //     return_flag = 1;

  //     std::cout << "Tolerance exceeded for velocity in Poiseuille test." << std::endl
  // 		<< "l2 error = " << l2error << std::endl
  // 		<< "h1 error = " << h1error << std::endl;
  //   }

  // // Compute error and get it in various norms
  // exact_sol.compute_error("GRINS", "p");

  // l2error = exact_sol.l2_error("GRINS", "p");
  // h1error = exact_sol.h1_error("GRINS", "p");

  // if( l2error > 2.0e-9 || h1error > 2.0e-9 )
  //   {
  //     return_flag = 1;

  //     std::cout << "Tolerance exceeded for pressure in Poiseuille test." << std::endl
  // 		<< "l2 error = " << l2error << std::endl
  // 		<< "h1 error = " << h1error << std::endl;
  //   }

  return return_flag;
}

// libMesh::Number
// exact_solution( const libMesh::Point& p,
// 		const libMesh::Parameters&,   // parameters, not needed
// 		const std::string&,  // sys_name, not needed
// 		const std::string&); // unk_name, not needed);

// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// 		  const libMesh::Parameters&,   // parameters, not needed
// 		  const std::string&,  // sys_name, not needed
// 		  const std::string&); // unk_name, not needed);

// class ParabolicBCFactory : public GRINS::BoundaryConditionsFactory
// {
// public:

//   ParabolicBCFactory()
//     : GRINS::BoundaryConditionsFactory()
//   { return; };

//   ~ParabolicBCFactory(){return;};

//   std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > build_dirichlet( );
// };

// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > ParabolicBCFactory::build_dirichlet( )
// {
//   GRINS::DBCContainer cont;
//   cont.add_var_name( "u" );
//   cont.add_bc_id( 1 );
//   cont.add_bc_id( 3 );

//   std::tr1::shared_ptr<libMesh::FunctionBase<libMesh::Number> > u_func( new GRINS::ParabolicProfile );

//   cont.set_func( u_func );

//   std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > mymap;

//   mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::incompressible_navier_stokes,  cont) );

//   return mymap;
// }

// libMesh::Number
// exact_solution( const libMesh::Point& p,
// 		const libMesh::Parameters& /*params*/,   // parameters, not needed
// 		const std::string& /*sys_name*/,  // sys_name, not needed
// 		const std::string& var )  // unk_name, not needed);
// {
//   const double x = p(0);
//   const double y = p(1);

//   libMesh::Number f = 0;
//   // Hardcoded to velocity in input file.
//   if( var == "u" ) f = 4*y*(1-y);
//   else if( var == "p" ) f = 120.0 + (80.0-120.0)/5.0*x;
//   else libmesh_assert(false);

//   return f;
// }

// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// 		  const libMesh::Parameters& /*params*/,   // parameters, not needed
// 		  const std::string& /*sys_name*/,  // sys_name, not needed
// 		  const std::string& var)  // unk_name, not needed);
// {
//   const double y = p(1);

//   libMesh::Gradient g;

//   // Hardcoded to velocity in input file.
//   if( var == "u" )
//     {
//       g(0) = 0.0;
//       g(1) = 4*(1-y) - 4*y;

// #if LIBMESH_DIM > 2
//       g(2) = 0.0;
// #endif
//     }

//   if( var == "p" )
//     {
//       g(0) = (80.0-120.0)/5.0;
//       g(1) = 0.0;

// #if LIBMESH_DIM > 2
//       g(2) = 0.0;
// #endif
//     }
//   return g;
// }
<|endoftext|>


<commit_before>#include "qextserialport.h"
#include "qextserialenumerator.h"
#include "dialog.h"
#include "ui_dialog.h"
#include <QtCore>
#include <QDebug>
#include <QFileDialog>
#include <QThread>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStandardPaths>
#include <QFileInfo>
#include <QApplication>
#include <QDesktopWidget>
#include <QTimer>
#include <QWebHistory>
#include <QMessageBox>
#include <QSettings>

#include "qgc.h"
#include "qgcfirmwareupgradeworker.h"

Dialog::Dialog(QWidget *parent) :
    QWidget(parent),
    loading(false),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
        if (!info.portName.isEmpty())
            ui->portBox->addItem(info.portName);
    //make sure user can input their own port name!
    ui->portBox->setEditable(true);

//    ui->led->turnOff();

    PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10};
    port = new QextSerialPort(ui->portBox->currentText(), settings, QextSerialPort::Polling);

    enumerator = new QextSerialEnumerator(this);
    enumerator->setUpNotifications();

    ui->boardComboBox->addItem("PX4FMU v1.6+", 5);
    ui->boardComboBox->addItem("PX4FLOW v1.1+", 6);
    ui->boardComboBox->addItem("PX4IO v1.3+", 7);
    ui->boardComboBox->addItem("PX4 board #8", 8);
    ui->boardComboBox->addItem("PX4 board #9", 9);
    ui->boardComboBox->addItem("PX4 board #10", 10);
    ui->boardComboBox->addItem("PX4 board #11", 11);

    connect(ui->portBox, SIGNAL(editTextChanged(QString)), SLOT(onPortNameChanged(QString)));
    connect(ui->flashButton, SIGNAL(clicked()), SLOT(onUploadButtonClicked()));
    connect(ui->selectFileButton, SIGNAL(clicked()), SLOT(onFileSelectRequested()));
    connect(ui->cancelButton, SIGNAL(clicked()), SLOT(onCancelButtonClicked()));

    connect(ui->webView->page(), SIGNAL(downloadRequested(const QNetworkRequest&)), this, SLOT(onDownloadRequested(const QNetworkRequest&)));
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(ui->webView->page(), SIGNAL(linkClicked(const QUrl&)), this, SLOT(onLinkClicked(const QUrl&)));

    connect(ui->prevButton, SIGNAL(clicked()), ui->webView, SLOT(back()));
    connect(ui->homeButton, SIGNAL(clicked()), this, SLOT(onHomeRequested()));

    connect(ui->advancedCheckBox, SIGNAL(clicked(bool)), this, SLOT(onToggleAdvancedMode(bool)));

    connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
    connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));

    setWindowTitle(tr("QUpgrade Firmware Upload / Configuration Tool"));

    // Adjust the size
    const int screenHeight = qMin(1000, QApplication::desktop()->height() - 100);

    resize(700, qMax(screenHeight, 550));

    // about:blank shouldn't be part of the history
    ui->webView->history()->clear();
    onHomeRequested();

    // load settings
    loadSettings();

    // Set up initial state
    if (!lastFilename.isEmpty()) {
        ui->flashButton->setEnabled(true);
    } else {
        ui->flashButton->setEnabled(false);
    }
}

Dialog::~Dialog()
{
    storeSettings();
    delete ui;
    delete port;
}

void Dialog::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Dialog::onToggleAdvancedMode(bool enabled)
{
    ui->selectFileButton->setVisible(enabled);
    ui->flashButton->setVisible(enabled);
    ui->portBox->setVisible(enabled);
    ui->portLabel->setVisible(enabled);
    ui->boardIdLabel->setVisible(enabled);
    ui->boardComboBox->setVisible(enabled);
    // Hide web view if advanced
    ui->webView->setVisible(!enabled);
    ui->homeButton->setVisible(!enabled);
    ui->prevButton->setVisible(!enabled);
}

void Dialog::loadSettings()
{
    QSettings set;
    lastFilename = set.value("LAST_FILENAME", lastFilename).toString();
    ui->advancedCheckBox->setChecked(set.value("ADVANCED_MODE", false).toBool());

    int boardIndex = ui->boardComboBox->findData(set.value("BOARD_ID", 5));
    if (boardIndex >= 0)
        ui->boardComboBox->setCurrentIndex(boardIndex);

    int portIndex = ui->portBox->findText(set.value("PORT_NAME", "").toString());
    if (portIndex >= 0) {
        ui->portBox->setCurrentIndex(portIndex);
    } else {
        qDebug() << "could not find port" << set.value("PORT_NAME", "");
    }

    onToggleAdvancedMode(ui->advancedCheckBox->isChecked());

    // Check if in advanced mode
    if (!lastFilename.isEmpty() && ui->advancedCheckBox->isChecked()) {
        ui->upgradeLog->appendPlainText(tr("Pre-selected file %1\nfor flashing (click 'Flash' to upgrade)").arg(lastFilename));

        updateBoardId(lastFilename);
    }
}

void Dialog::storeSettings()
{
    QSettings set;
    if (lastFilename != "")
        set.setValue("LAST_FILENAME", lastFilename);
    set.setValue("ADVANCED_MODE", ui->advancedCheckBox->isChecked());
    set.setValue("BOARD_ID", ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()));
    set.setValue("PORT_NAME", ui->portBox->currentText());
}

void Dialog::updateBoardId(const QString &fileName) {
    // XXX this should be moved in separe classes
    if (fileName.endsWith(".px4")) {
        // Attempt to decode JSON
        QFile json(lastFilename);
        json.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray jbytes = json.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(jbytes);

        if (doc.isNull()) {
            // Error, bail out
            ui->upgradeLog->appendPlainText(tr("supplied file is not a valid JSON document"));
        }

        QJsonObject px4 = doc.object();

        int checkBoardId = (int) (px4.value(QString("board_id")).toDouble());
        ui->upgradeLog->appendPlainText(tr("loaded file for board ID %1").arg(checkBoardId));

        // Set correct board ID
        int index = ui->boardComboBox->findData(checkBoardId);

        if (index >= 0) {
            ui->boardComboBox->setCurrentIndex(index);
        } else {
            qDebug() << "Combo box: board not found:" << index;
        }
    }
}

void Dialog::onHomeRequested()
{
    // Load start file into web view
    ui->webView->setUrl(QUrl::fromUserInput(QCoreApplication::applicationDirPath()+"/files/html/index.html"));
    ui->homeButton->setEnabled(false);
    ui->prevButton->setEnabled(false);
}

void Dialog::onLinkClicked(const QUrl &url)
{
    QString firmwareFile = QFileInfo(url.toString()).fileName();

    // If not a firmware file, ignore
    if (!(firmwareFile.endsWith(".px4") || firmwareFile.endsWith(".bin"))) {
        ui->webView->load(url);
        ui->homeButton->setEnabled(true);
        ui->prevButton->setEnabled(true);
        return;
    }

    QString filename;

    // If a IO firmware file, open save as Dialog
    if (firmwareFile.endsWith(".bin") && firmwareFile.contains("px4io")) {
        QString path = QString(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
        qDebug() << path;
        filename = QFileDialog::getExistingDirectory(this, tr("Select folder (microSD Card)"),
                                                path);
        filename.append("/" + firmwareFile);
    } else {

        // Make sure the user doesn't screw up flashing
        QMessageBox msgBox;
        msgBox.setText("Please unplug your PX4 board now");
        msgBox.exec();

        filename = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);

        if (filename.isEmpty()) {
            qDebug() << "Falling back to temp dir";
            QString filename = QStandardPaths::writableLocation(QStandardPaths::TempLocation);

            // If still empty, bail out
            if (filename.isEmpty())
                ui->upgradeLog->appendHtml(tr("FAILED storing firmware to downloads or temp directory. Harddisk not writable."));
                return;
        }

        filename += "/" + firmwareFile;
    }

    if (filename == "") {
        return;
    }

    // Else, flash the firmware
    lastFilename = filename;

    // Pattern matched, abort current QWebView load
    ui->webView->stop();

    ui->upgradeLog->appendHtml(tr("Downloading firmware file %1").arg(url.toString()));

    QNetworkRequest newRequest(url);
    newRequest.setUrl(url);
    newRequest.setAttribute(QNetworkRequest::User, filename);

    QNetworkAccessManager *networkManager = ui->webView->page()->networkAccessManager();
    QNetworkReply *reply = networkManager->get(newRequest);
    connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
    connect(reply, SIGNAL(finished()), this, SLOT(onDownloadFinished()));
}

void Dialog::onDownloadRequested(const QNetworkRequest &request)
{
    onLinkClicked(request.url());
}

void Dialog::onPortNameChanged(const QString & /*name*/)
{
    if (port->isOpen()) {
        port->close();
//        ui->led->turnOff();
    }
}

void Dialog::onDownloadFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());

    if (!reply) {
        // bail out, nothing to do
        return;
    }

    if (loading) {
        onCancelButtonClicked();
        ui->upgradeLog->appendPlainText(tr("Waiting for firmware flashing to complete.."));
    } else {

        // Reset progress
        ui->upgradeProgressBar->setValue(0);

        // Pick file
        QString fileName = lastFilename;

        qDebug() << "Handling filename:" << fileName;

        // Store file in download location
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            fprintf(stderr, "Could not open %s for writing: %s\n",
                    qPrintable(fileName),
                    qPrintable(file.errorString()));
            return;
        }

        file.write(reply->readAll());

        if (lastFilename.contains("px4io")) {
            // Done, bail out
            return;
        }

        if (fileName.length() > 0) {
            // Got a filename, upload
            onLoadStart();
            lastFilename = fileName;

            worker = QGCFirmwareUpgradeWorker::putWorkerInThread(fileName);
            // Hook up status from worker to progress bar
            connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
            // Hook up text from worker to label
            connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up error handling
            //connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up status from worker to this class
            connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));

            // Make sure user gets the board going now
            QMessageBox msgBox;
            msgBox.setText("Please connect your PX4 board now");
            msgBox.exec();
        }
    }
}

void Dialog::onFileSelectRequested()
{
    if (loading) {
        worker->abortUpload();
        loading = false;
        ui->flashButton->setEnabled(true);
    }

    // Pick file
    QString fileName = QFileDialog::getOpenFileName(this,
                            tr("Open Firmware File"), lastFilename, tr("Firmware Files (*.px4 *.bin)"));

    if (fileName != "") {
        lastFilename = fileName;

        updateBoardId(lastFilename);
    }
}

void Dialog::onCancelButtonClicked()
{
    if (loading) {
        worker->abortUpload();
        ui->cancelButton->setEnabled(false);
        ui->upgradeLog->appendPlainText(tr("Waiting for last upgrade operaton to abort.."));
    }
}

void Dialog::onUploadButtonClicked()
{
    if (loading) {
        onCancelButtonClicked();
    } else {

        if (lastFilename.length() > 0) {
            // Got a filename, upload
            loading = true;
            ui->flashButton->setEnabled(false);
            ui->cancelButton->setEnabled(true);

            int id = -1;

            // Set board ID for worker
            if (ui->boardComboBox->isVisible()) {
                bool ok;
                int tmp = ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()).toInt(&ok);
                if (ok)
                    id = tmp;
            }

            worker = QGCFirmwareUpgradeWorker::putWorkerInThread(lastFilename, ui->portBox->currentText(), id);

            connect(ui->portBox, SIGNAL(currentTextChanged(QString)), worker, SLOT(setPort(QString)));

            // Hook up status from worker to progress bar
            connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
            // Hook up text from worker to label
            connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up error handling
            connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up status from worker to this class
            connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
        }
    }
}

void Dialog::onPortAddedOrRemoved()
{
    QString current = ui->portBox->currentText();

    ui->portBox->blockSignals(true);

    // Delete old ports
    for (int i = 0; i < ui->portBox->count(); i++)
    {
        bool found = false;
        foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
            if (info.portName == ui->portBox->itemText(i))
                found = true;

        if (!found && !ui->portBox->itemText(i).contains("Automatic"))
            ui->portBox->removeItem(i);
    }

    // Add new ports
    foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
        if (ui->portBox->findText(info.portName) < 0) {
            if (!info.portName.isEmpty())
                ui->portBox->addItem(info.portName);
        }

    ui->portBox->blockSignals(false);
}

void Dialog::onLoadStart()
{
    loading = true;
    ui->flashButton->setEnabled(false);
    ui->cancelButton->setEnabled(true);
}

void Dialog::onLoadFinished(bool success)
{
    loading = false;
    ui->flashButton->setEnabled(true);
    ui->cancelButton->setEnabled(false);

    if (success) {
        ui->upgradeLog->appendPlainText(tr("Upload succeeded."));
    } else {
        ui->upgradeLog->appendPlainText(tr("Upload aborted and failed."));
        ui->upgradeProgressBar->setValue(0);
    }
}

void Dialog::onDownloadProgress(qint64 curr, qint64 total)
{
    // Take care of cases where 0 / 0 is emitted as error return value
    if (total > 0)
        ui->upgradeProgressBar->setValue((curr*100) / total);
}
<commit_msg>Attempt to fix windows symptoms<commit_after>#include "qextserialport.h"
#include "qextserialenumerator.h"
#include "dialog.h"
#include "ui_dialog.h"
#include <QtCore>
#include <QDebug>
#include <QFileDialog>
#include <QThread>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStandardPaths>
#include <QFileInfo>
#include <QApplication>
#include <QDesktopWidget>
#include <QTimer>
#include <QWebHistory>
#include <QMessageBox>
#include <QSettings>

#include "qgc.h"
#include "qgcfirmwareupgradeworker.h"

Dialog::Dialog(QWidget *parent) :
    QWidget(parent),
    loading(false),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
        if (!info.portName.isEmpty())
            ui->portBox->addItem(info.portName);
    //make sure user can input their own port name!
    ui->portBox->setEditable(true);

//    ui->led->turnOff();

    PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10};
    port = new QextSerialPort(ui->portBox->currentText(), settings, QextSerialPort::Polling);

    enumerator = new QextSerialEnumerator(this);
    enumerator->setUpNotifications();

    ui->boardComboBox->addItem("PX4FMU v1.6+", 5);
    ui->boardComboBox->addItem("PX4FLOW v1.1+", 6);
    ui->boardComboBox->addItem("PX4IO v1.3+", 7);
    ui->boardComboBox->addItem("PX4 board #8", 8);
    ui->boardComboBox->addItem("PX4 board #9", 9);
    ui->boardComboBox->addItem("PX4 board #10", 10);
    ui->boardComboBox->addItem("PX4 board #11", 11);

    connect(ui->portBox, SIGNAL(editTextChanged(QString)), SLOT(onPortNameChanged(QString)));
    connect(ui->flashButton, SIGNAL(clicked()), SLOT(onUploadButtonClicked()));
    connect(ui->selectFileButton, SIGNAL(clicked()), SLOT(onFileSelectRequested()));
    connect(ui->cancelButton, SIGNAL(clicked()), SLOT(onCancelButtonClicked()));

    connect(ui->webView->page(), SIGNAL(downloadRequested(const QNetworkRequest&)), this, SLOT(onDownloadRequested(const QNetworkRequest&)));
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(ui->webView->page(), SIGNAL(linkClicked(const QUrl&)), this, SLOT(onLinkClicked(const QUrl&)));

    connect(ui->prevButton, SIGNAL(clicked()), ui->webView, SLOT(back()));
    connect(ui->homeButton, SIGNAL(clicked()), this, SLOT(onHomeRequested()));

    connect(ui->advancedCheckBox, SIGNAL(clicked(bool)), this, SLOT(onToggleAdvancedMode(bool)));

    connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
    connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));

    setWindowTitle(tr("QUpgrade Firmware Upload / Configuration Tool"));

    // Adjust the size
    const int screenHeight = qMin(1000, QApplication::desktop()->height() - 100);

    resize(700, qMax(screenHeight, 550));

    // about:blank shouldn't be part of the history
    ui->webView->history()->clear();
    onHomeRequested();

    // load settings
    loadSettings();

    // Set up initial state
    if (!lastFilename.isEmpty()) {
        ui->flashButton->setEnabled(true);
    } else {
        ui->flashButton->setEnabled(false);
    }
}

Dialog::~Dialog()
{
    storeSettings();
    delete ui;
    delete port;
}

void Dialog::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Dialog::onToggleAdvancedMode(bool enabled)
{
    ui->selectFileButton->setVisible(enabled);
    ui->flashButton->setVisible(enabled);
    ui->portBox->setVisible(enabled);
    ui->portLabel->setVisible(enabled);
    ui->boardIdLabel->setVisible(enabled);
    ui->boardComboBox->setVisible(enabled);
    // Hide web view if advanced
    ui->webView->setVisible(!enabled);
    ui->homeButton->setVisible(!enabled);
    ui->prevButton->setVisible(!enabled);
}

void Dialog::loadSettings()
{
    QSettings set;
    lastFilename = set.value("LAST_FILENAME", lastFilename).toString();
    ui->advancedCheckBox->setChecked(set.value("ADVANCED_MODE", false).toBool());

    int boardIndex = ui->boardComboBox->findData(set.value("BOARD_ID", 5));
    if (boardIndex >= 0)
        ui->boardComboBox->setCurrentIndex(boardIndex);

    int portIndex = ui->portBox->findText(set.value("PORT_NAME", "").toString());
    if (portIndex >= 0) {
        ui->portBox->setCurrentIndex(portIndex);
    } else {
        qDebug() << "could not find port" << set.value("PORT_NAME", "");
    }

    onToggleAdvancedMode(ui->advancedCheckBox->isChecked());

    // Check if in advanced mode
    if (!lastFilename.isEmpty() && ui->advancedCheckBox->isChecked()) {
        ui->upgradeLog->appendPlainText(tr("Pre-selected file %1\nfor flashing (click 'Flash' to upgrade)").arg(lastFilename));

        updateBoardId(lastFilename);
    }
}

void Dialog::storeSettings()
{
    QSettings set;
    if (lastFilename != "")
        set.setValue("LAST_FILENAME", lastFilename);
    set.setValue("ADVANCED_MODE", ui->advancedCheckBox->isChecked());
    set.setValue("BOARD_ID", ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()));
    set.setValue("PORT_NAME", ui->portBox->currentText());
}

void Dialog::updateBoardId(const QString &fileName) {
    // XXX this should be moved in separe classes
    if (fileName.endsWith(".px4")) {
        // Attempt to decode JSON
        QFile json(lastFilename);
        json.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray jbytes = json.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(jbytes);

        if (doc.isNull()) {
            // Error, bail out
            ui->upgradeLog->appendPlainText(tr("supplied file is not a valid JSON document"));
        }

        QJsonObject px4 = doc.object();

        int checkBoardId = (int) (px4.value(QString("board_id")).toDouble());
        ui->upgradeLog->appendPlainText(tr("loaded file for board ID %1").arg(checkBoardId));

        // Set correct board ID
        int index = ui->boardComboBox->findData(checkBoardId);

        if (index >= 0) {
            ui->boardComboBox->setCurrentIndex(index);
        } else {
            qDebug() << "Combo box: board not found:" << index;
        }
    }
}

void Dialog::onHomeRequested()
{
    // Load start file into web view
    ui->webView->setUrl(QUrl::fromUserInput(QCoreApplication::applicationDirPath()+"/files/html/index.html"));
    ui->homeButton->setEnabled(false);
    ui->prevButton->setEnabled(false);
}

void Dialog::onLinkClicked(const QUrl &url)
{
    QString firmwareFile = QFileInfo(url.toString()).fileName();

    // If not a firmware file, ignore
    if (!(firmwareFile.endsWith(".px4") || firmwareFile.endsWith(".bin"))) {
        ui->webView->load(url);
        ui->homeButton->setEnabled(true);
        ui->prevButton->setEnabled(true);
        return;
    }

    QString filename;

    // If a IO firmware file, open save as Dialog
    if (firmwareFile.endsWith(".bin") && firmwareFile.contains("px4io")) {
        QString path = QString(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
        qDebug() << path;
        filename = QFileDialog::getExistingDirectory(this, tr("Select folder (microSD Card)"),
                                                path);
        filename.append("/" + firmwareFile);
    } else {

        // Make sure the user doesn't screw up flashing
        QMessageBox msgBox;
        msgBox.setText("Please unplug your PX4 board now");
        msgBox.exec();

        filename = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);

        if (filename.isEmpty()) {
            qDebug() << "Falling back to temp dir";
            QString filename = QStandardPaths::writableLocation(QStandardPaths::TempLocation);

            // If still empty, bail out
            if (filename.isEmpty())
                ui->upgradeLog->appendHtml(tr("FAILED storing firmware to downloads or temp directory. Harddisk not writable."));
                return;
        }

        filename += "/" + firmwareFile;
    }

    if (filename == "") {
        return;
    }

    // Else, flash the firmware
    lastFilename = filename;

    ui->upgradeLog->appendHtml(tr("Downloading firmware file %1").arg(url.toString()));

    QNetworkRequest newRequest(url);
    newRequest.setUrl(url);
    newRequest.setAttribute(QNetworkRequest::User, filename);

    QNetworkAccessManager *networkManager = ui->webView->page()->networkAccessManager();
    QNetworkReply *reply = networkManager->get(newRequest);
    connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
    connect(reply, SIGNAL(finished()), this, SLOT(onDownloadFinished()));
}

void Dialog::onDownloadRequested(const QNetworkRequest &request)
{
    onLinkClicked(request.url());
}

void Dialog::onPortNameChanged(const QString & /*name*/)
{
    if (port->isOpen()) {
        port->close();
//        ui->led->turnOff();
    }
}

void Dialog::onDownloadFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());

    if (!reply) {
        // bail out, nothing to do
        ui->upgradeLog->appendPlainText("Download failed, invalid context");
        return;
    }

    if (loading) {
        onCancelButtonClicked();
        ui->upgradeLog->appendPlainText(tr("Still flashing. Waiting for firmware flashing to complete.."));
    } else {

        // Reset progress
        ui->upgradeProgressBar->setValue(0);

        // Pick file
        QString fileName = lastFilename;

        qDebug() << "Handling filename:" << fileName;

        // Store file in download location
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            ui->upgradeLog->appendPlainText(tr("Could not open %s for writing: %s\n").arg(fileName).arg(file.errorString()));
            return;
        }

        file.write(reply->readAll());
        file.close();

        if (lastFilename.contains("px4io")) {
            // Done, bail out
            return;
        }

        if (fileName.length() > 0) {
            // Got a filename, upload
            onLoadStart();
            lastFilename = fileName;

            worker = QGCFirmwareUpgradeWorker::putWorkerInThread(fileName);
            // Hook up status from worker to progress bar
            connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
            // Hook up text from worker to label
            connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up error handling
            //connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up status from worker to this class
            connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));

            // Make sure user gets the board going now
            QMessageBox msgBox;
            msgBox.setText("Please connect your PX4 board now");
            msgBox.exec();
        }
    }
}

void Dialog::onFileSelectRequested()
{
    if (loading) {
        worker->abortUpload();
        loading = false;
        ui->flashButton->setEnabled(true);
    }

    // Pick file
    QString fileName = QFileDialog::getOpenFileName(this,
                            tr("Open Firmware File"), lastFilename, tr("Firmware Files (*.px4 *.bin)"));

    if (fileName != "") {
        lastFilename = fileName;

        updateBoardId(lastFilename);
    }
}

void Dialog::onCancelButtonClicked()
{
    if (loading) {
        worker->abortUpload();
        ui->cancelButton->setEnabled(false);
        ui->upgradeLog->appendPlainText(tr("Waiting for last upgrade operaton to abort.."));
    }
}

void Dialog::onUploadButtonClicked()
{
    if (loading) {
        onCancelButtonClicked();
    } else {

        if (lastFilename.length() > 0) {
            // Got a filename, upload
            loading = true;
            ui->flashButton->setEnabled(false);
            ui->cancelButton->setEnabled(true);

            int id = -1;

            // Set board ID for worker
            if (ui->boardComboBox->isVisible()) {
                bool ok;
                int tmp = ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()).toInt(&ok);
                if (ok)
                    id = tmp;
            }

            worker = QGCFirmwareUpgradeWorker::putWorkerInThread(lastFilename, ui->portBox->currentText(), id);

            connect(ui->portBox, SIGNAL(currentTextChanged(QString)), worker, SLOT(setPort(QString)));

            // Hook up status from worker to progress bar
            connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
            // Hook up text from worker to label
            connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up error handling
            connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
            // Hook up status from worker to this class
            connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
        }
    }
}

void Dialog::onPortAddedOrRemoved()
{
    QString current = ui->portBox->currentText();

    ui->portBox->blockSignals(true);

    // Delete old ports
    for (int i = 0; i < ui->portBox->count(); i++)
    {
        bool found = false;
        foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
            if (info.portName == ui->portBox->itemText(i))
                found = true;

        if (!found && !ui->portBox->itemText(i).contains("Automatic"))
            ui->portBox->removeItem(i);
    }

    // Add new ports
    foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
        if (ui->portBox->findText(info.portName) < 0) {
            if (!info.portName.isEmpty())
                ui->portBox->addItem(info.portName);
        }

    ui->portBox->blockSignals(false);
}

void Dialog::onLoadStart()
{
    loading = true;
    ui->flashButton->setEnabled(false);
    ui->cancelButton->setEnabled(true);
}

void Dialog::onLoadFinished(bool success)
{
    loading = false;
    ui->flashButton->setEnabled(true);
    ui->cancelButton->setEnabled(false);

    if (success) {
        ui->upgradeLog->appendPlainText(tr("Upload succeeded."));
    } else {
        ui->upgradeLog->appendPlainText(tr("Upload aborted and failed."));
        ui->upgradeProgressBar->setValue(0);
    }
}

void Dialog::onDownloadProgress(qint64 curr, qint64 total)
{
    // Take care of cases where 0 / 0 is emitted as error return value
    if (total > 0)
        ui->upgradeProgressBar->setValue((curr*100) / total);
}
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "condor_random_num.h"
#include "io_proxy.h"
#include "io_proxy_handler.h"
#include "ipv6_hostname.h"

#define IO_PROXY_COOKIE_SIZE 32

static char * cookie_create( int length );

IOProxy::IOProxy()
	:
	server(NULL),
	m_shadow(NULL),
	cookie(0),
	socket_registered(false),
	m_want_io(false),
	m_want_updates(false),
	m_want_delayed(false)
{
}

IOProxy::~IOProxy()
{
	if ( daemonCore && socket_registered && server ) {
		daemonCore->Cancel_Socket(server);
	}
	if ( server ) {
		server->close();
		delete server;
	}
	if(cookie) free(cookie);
}

/*
This callback is invoked for each new incoming connection.
In response, fork a new IOProxyHandler child to deal with the stream.
Returns KEEP_STREAM if the stream is still valid, ~KEEP_STREAM otherwise.
*/

int IOProxy::connect_callback( Stream * /*stream*/ )
{
	ReliSock *client = new ReliSock;
	bool accept_client = false;
	int success;

	success = server->accept(*client);
	if(success) {
		// TODO: This is arbitrarily picking IPv4.  Should we match protocol of *client?
		if(get_local_ipaddr(CP_IPV4).compare_address(client->peer_addr())) {
			dprintf(D_FULLDEBUG,"IOProxy: accepting connection from %s\n",client->peer_ip_str());
			accept_client = true;
		} else {
			dprintf(D_ALWAYS,"IOProxy: rejecting connection from %s: invalid ip addr\n",client->peer_ip_str());
		}
	} else {
		dprintf(D_ALWAYS,"IOProxy: Couldn't accept connection: %s\n",strerror(errno));
	}

	if(accept_client) {
		IOProxyHandler *handler = new IOProxyHandler(m_shadow, m_want_io, m_want_updates, m_want_delayed);
		if(!handler->init(client,cookie)) {
			dprintf(D_ALWAYS,"IOProxy: couldn't register request callback!\n");
			client->close();
			delete client;
		}

	} else {
		client->close();
		delete client;
	}

	return KEEP_STREAM;
}

/*
Initialize this proxy and dump the contact information into the given file.
Returns true on success, false otherwise.
*/

bool IOProxy::init( JICShadow *shadow, const char *config_file, bool want_io, bool want_updates, bool want_delayed )
{
	m_shadow = shadow;
	m_want_io = want_io;
	m_want_updates = want_updates;
	m_want_delayed = want_delayed;

	FILE *file=0;
	int fd=-1;

	server = new ReliSock;
	if ( !server ) {
		dprintf(D_ALWAYS,"IOProxy: couldn't create socket\n");
		return false;
	}

	if(!server->bind(false)) {
		dprintf(D_ALWAYS,"IOProxy: couldn't bind: %s\n",strerror(errno));
		return false;
	}

	if(!server->listen()) {
		dprintf(D_ALWAYS,"IOProxy: couldn't listen: %s\n",strerror(errno));
		return false;
	}

	cookie = cookie_create(IO_PROXY_COOKIE_SIZE);
	if(!cookie) {
		dprintf(D_ALWAYS,"IOProxy: couldn't create cookie: %s\n",strerror(errno));
		goto failure;
	}
	fd = safe_open_wrapper_follow(config_file,
	                       O_CREAT|O_TRUNC|O_WRONLY,
	                       0700);
	if(fd<0) {
		dprintf(D_ALWAYS,
		        "IOProxy: couldn't write to %s: %s\n",
		        config_file,
		        strerror(errno));
		goto failure;
	}

	file = fdopen(fd,"w");
	if(!file) {
		dprintf(D_ALWAYS,"IOProxy: couldn't create I/O stream: %s\n",strerror(errno));
		goto failure;
	}

	fprintf(file,"%s %d %s\n",my_ip_string(),server->get_port(),cookie);
	fclose(file);

	daemonCore->Register_Socket( server, "IOProxy listen socket",
		(SocketHandlercpp) &IOProxy::connect_callback,
		"IOProxy connect callback", this );
	socket_registered = true;
	return true;

	failure:
	if(cookie) free(cookie);
	if(file) fclose(file);
	IGNORE_RETURN unlink(config_file);
	server->close();
	return false;
}

/*
On success, returns a newly-allocated random cookie string.
On failure, returns null.
*/

static char * cookie_create( int length )
{
	char *c = (char*) malloc(length);
	if(!c) return 0;

	for( int i=0; i<length; i++ ) {
		c[i] = 'a'+get_random_int()%26;
	}

	c[length-1] = 0;

	return c;
}

<commit_msg>The IO proxy (chirp server) in the starter now behaves more sanely in a multiprotocol world.<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "condor_random_num.h"
#include "io_proxy.h"
#include "io_proxy_handler.h"
#include "ipv6_hostname.h"
#include "condor_config.h"

#define IO_PROXY_COOKIE_SIZE 32

static char * cookie_create( int length );

IOProxy::IOProxy()
	:
	server(NULL),
	m_shadow(NULL),
	cookie(0),
	socket_registered(false),
	m_want_io(false),
	m_want_updates(false),
	m_want_delayed(false)
{
}

IOProxy::~IOProxy()
{
	if ( daemonCore && socket_registered && server ) {
		daemonCore->Cancel_Socket(server);
	}
	if ( server ) {
		server->close();
		delete server;
	}
	if(cookie) free(cookie);
}

/*
This callback is invoked for each new incoming connection.
In response, fork a new IOProxyHandler child to deal with the stream.
Returns KEEP_STREAM if the stream is still valid, ~KEEP_STREAM otherwise.
*/

int IOProxy::connect_callback( Stream * /*stream*/ )
{
	ReliSock *client = new ReliSock;
	bool accept_client = false;
	int success;

	success = server->accept(*client);
	if(success) {
		// I'm not sure why we believe the socket could be bound to anything
		// other than the address we want to hear from, but...
		condor_sockaddr remote = client->peer_addr();
		if( remote.is_loopback() ) {
			dprintf(D_FULLDEBUG,"IOProxy: accepting connection from %s\n",client->peer_ip_str());
			accept_client = true;
		} else {
			dprintf(D_ALWAYS,"IOProxy: rejecting connection from %s: invalid ip addr\n",client->peer_ip_str());
		}
	} else {
		dprintf(D_ALWAYS,"IOProxy: Couldn't accept connection: %s\n",strerror(errno));
	}

	if(accept_client) {
		IOProxyHandler *handler = new IOProxyHandler(m_shadow, m_want_io, m_want_updates, m_want_delayed);
		if(!handler->init(client,cookie)) {
			dprintf(D_ALWAYS,"IOProxy: couldn't register request callback!\n");
			client->close();
			delete client;
		}

	} else {
		client->close();
		delete client;
	}

	return KEEP_STREAM;
}

/*
Initialize this proxy and dump the contact information into the given file.
Returns true on success, false otherwise.
*/

bool IOProxy::init( JICShadow *shadow, const char *config_file, bool want_io, bool want_updates, bool want_delayed )
{
	m_shadow = shadow;
	m_want_io = want_io;
	m_want_updates = want_updates;
	m_want_delayed = want_delayed;

	FILE *file=0;
	int fd=-1;

	server = new ReliSock;
	if ( !server ) {
		dprintf(D_ALWAYS,"IOProxy: couldn't create socket\n");
		return false;
	}

	//
	// Without other arguments, Sock::bind() now generates an IPv6 loopback
	// address if we're in mixed-mode on machines without a real IPv6 address.
	// That's fine (we'll rewrite the address on the way out if we have to),
	// but my_ip_string() no longer matches, which causes chirp grief (because
	// we pass our address to it here, via the chirp.config file).
	//
	// Instead, just go ahead and bind to IPv4 (unless it's disabled, in
	// which case, use IPv6); and use the loopback address, which is more
	// secure.  Regardless, use the actual address on which we're listening
	// to fill in the .chirp.config file.
	//

	condor_protocol proto = CP_IPV4;
	if( ! param_boolean( "ENABLE_IPV4", true ) ) { proto = CP_IPV6; }
	if(!server->bind( proto, false, 0, true )) {
		dprintf(D_ALWAYS,"IOProxy: couldn't bind: %s\n",strerror(errno));
		return false;
	}

	if(!server->listen()) {
		dprintf(D_ALWAYS,"IOProxy: couldn't listen: %s\n",strerror(errno));
		return false;
	}

	cookie = cookie_create(IO_PROXY_COOKIE_SIZE);
	if(!cookie) {
		dprintf(D_ALWAYS,"IOProxy: couldn't create cookie: %s\n",strerror(errno));
		goto failure;
	}
	fd = safe_open_wrapper_follow(config_file,
	                       O_CREAT|O_TRUNC|O_WRONLY,
	                       0700);
	if(fd<0) {
		dprintf(D_ALWAYS,
		        "IOProxy: couldn't write to %s: %s\n",
		        config_file,
		        strerror(errno));
		goto failure;
	}

	file = fdopen(fd,"w");
	if(!file) {
		dprintf(D_ALWAYS,"IOProxy: couldn't create I/O stream: %s\n",strerror(errno));
		goto failure;
	}

	fprintf( file, "%s %d %s\n", server->my_ip_str(), server->get_port(), cookie );
	fclose(file);

	daemonCore->Register_Socket( server, "IOProxy listen socket",
		(SocketHandlercpp) &IOProxy::connect_callback,
		"IOProxy connect callback", this );
	socket_registered = true;
	return true;

	failure:
	if(cookie) free(cookie);
	if(file) fclose(file);
	IGNORE_RETURN unlink(config_file);
	server->close();
	return false;
}

/*
On success, returns a newly-allocated random cookie string.
On failure, returns null.
*/

static char * cookie_create( int length )
{
	char *c = (char*) malloc(length);
	if(!c) return 0;

	for( int i=0; i<length; i++ ) {
		c[i] = 'a'+get_random_int()%26;
	}

	c[length-1] = 0;

	return c;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <folly/ScopeGuard.h>
#include <quic/dsr/frontend/WriteFunctions.h>

namespace quic {
uint64_t writePacketizationRequest(
    QuicServerConnectionState& connection,
    const ConnectionId& dstCid,
    size_t packetLimit,
    const Aead& aead,
    TimePoint writeLoopBeginTime) {
  DSRStreamFrameScheduler scheduler(connection);
  uint64_t packetCounter = 0;
  folly::F14FastSet<DSRPacketizationRequestSender*> senders;
  SCOPE_EXIT {
    std::for_each(
        senders.begin(), senders.end(), [](auto* sender) { sender->flush(); });
  };
  if (!writeLoopTimeLimit(writeLoopBeginTime, connection)) {
    return packetCounter;
  }
  while (scheduler.hasPendingData() && packetCounter < packetLimit &&
         (packetCounter < connection.transportSettings.maxBatchSize ||
          writeLoopTimeLimit(writeLoopBeginTime, connection))) {
    auto packetNum = getNextPacketNum(connection, PacketNumberSpace::AppData);
    ShortHeader header(ProtectionType::KeyPhaseZero, dstCid, packetNum);
    auto writableBytes = std::min(
        connection.udpSendPacketLen,
        congestionControlWritableBytes(connection));
    uint64_t cipherOverhead = aead.getCipherOverhead();
    if (writableBytes < cipherOverhead) {
      writableBytes = 0;
    } else {
      writableBytes -= cipherOverhead;
    }

    DSRPacketBuilder packetBuilder(
        writableBytes,
        std::move(header),
        getAckState(connection, PacketNumberSpace::AppData)
            .largestAckedByPeer.value_or(0));
    auto schedulerResult = scheduler.writeStream(packetBuilder);
    if (!schedulerResult.writeSuccess) {
      /**
       * Scheduling can fail when we:
       * (1) run out of flow control
       * (2) there is actually no DSR stream to write - we shouldn't come here
       *     in the first place though.
       * (3) Packet is no space left - e.g., due to CC
       * (4) Error in write codec - Can that happen?
       *
       * At least for (1) and (3), we should flush the sender.
       */
      if (schedulerResult.sender) {
        senders.insert(schedulerResult.sender);
      }
      return packetCounter;
    }
    CHECK(schedulerResult.sender);
    auto packet = std::move(packetBuilder).buildPacket();
    // The contract is that if scheduler can schedule, builder has to be able to
    // build.
    CHECK_GT(packet.encodedSize, 0);
    bool instructionAddError = false;
    for (const auto& instruction : packet.sendInstructions) {
      if (!schedulerResult.sender->addSendInstruction(instruction)) {
        instructionAddError = true;
        break;
      }
    }

    // Similar to the regular write case, if we build, we update connection
    // states. The connection states are changed already no matter the result
    // of addSendInstruction() call.
    updateConnection(
        connection,
        folly::none /* Packet Event */,
        packet.packet,
        Clock::now(),
        packet.encodedSize,
        // TODO: (yangchi) Figure out how to calculate the
        // packet.encodedBodySize for the DSR case. For now, it's not being
        // used, so setting it to 0
        0,
        true /* isDSRPacket */);
    connection.dsrPacketCount++;

    if (instructionAddError) {
      // TODO: Support empty write loop detection
      senders.insert(schedulerResult.sender);
      return packetCounter;
    }
    ++packetCounter;
    senders.insert(schedulerResult.sender);
  }
  return packetCounter;
}
} // namespace quic
<commit_msg>Add DSR flushing qlog events.<commit_after>/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <folly/ScopeGuard.h>
#include <quic/dsr/frontend/WriteFunctions.h>

namespace quic {
uint64_t writePacketizationRequest(
    QuicServerConnectionState& connection,
    const ConnectionId& dstCid,
    size_t packetLimit,
    const Aead& aead,
    TimePoint writeLoopBeginTime) {
  DSRStreamFrameScheduler scheduler(connection);
  uint64_t packetCounter = 0;
  folly::F14FastSet<DSRPacketizationRequestSender*> senders;
  SCOPE_EXIT {
    for (auto sender : senders) {
      if (connection.qLogger) {
        connection.qLogger->addTransportStateUpdate("DSR flushing sender");
      }
      sender->flush();
    }
  };
  if (!writeLoopTimeLimit(writeLoopBeginTime, connection)) {
    return packetCounter;
  }
  while (scheduler.hasPendingData() && packetCounter < packetLimit &&
         (packetCounter < connection.transportSettings.maxBatchSize ||
          writeLoopTimeLimit(writeLoopBeginTime, connection))) {
    auto packetNum = getNextPacketNum(connection, PacketNumberSpace::AppData);
    ShortHeader header(ProtectionType::KeyPhaseZero, dstCid, packetNum);
    auto writableBytes = std::min(
        connection.udpSendPacketLen,
        congestionControlWritableBytes(connection));
    uint64_t cipherOverhead = aead.getCipherOverhead();
    if (writableBytes < cipherOverhead) {
      writableBytes = 0;
    } else {
      writableBytes -= cipherOverhead;
    }

    DSRPacketBuilder packetBuilder(
        writableBytes,
        std::move(header),
        getAckState(connection, PacketNumberSpace::AppData)
            .largestAckedByPeer.value_or(0));
    auto schedulerResult = scheduler.writeStream(packetBuilder);
    if (!schedulerResult.writeSuccess) {
      /**
       * Scheduling can fail when we:
       * (1) run out of flow control
       * (2) there is actually no DSR stream to write - we shouldn't come here
       *     in the first place though.
       * (3) Packet is no space left - e.g., due to CC
       * (4) Error in write codec - Can that happen?
       *
       * At least for (1) and (3), we should flush the sender.
       */
      if (schedulerResult.sender) {
        senders.insert(schedulerResult.sender);
      }
      return packetCounter;
    }
    CHECK(schedulerResult.sender);
    auto packet = std::move(packetBuilder).buildPacket();
    // The contract is that if scheduler can schedule, builder has to be able to
    // build.
    CHECK_GT(packet.encodedSize, 0);
    bool instructionAddError = false;
    for (const auto& instruction : packet.sendInstructions) {
      if (!schedulerResult.sender->addSendInstruction(instruction)) {
        instructionAddError = true;
        break;
      }
    }

    // Similar to the regular write case, if we build, we update connection
    // states. The connection states are changed already no matter the result
    // of addSendInstruction() call.
    updateConnection(
        connection,
        folly::none /* Packet Event */,
        packet.packet,
        Clock::now(),
        packet.encodedSize,
        // TODO: (yangchi) Figure out how to calculate the
        // packet.encodedBodySize for the DSR case. For now, it's not being
        // used, so setting it to 0
        0,
        true /* isDSRPacket */);
    connection.dsrPacketCount++;

    if (instructionAddError) {
      // TODO: Support empty write loop detection
      senders.insert(schedulerResult.sender);
      return packetCounter;
    }
    ++packetCounter;
    senders.insert(schedulerResult.sender);
  }
  return packetCounter;
}
} // namespace quic
<|endoftext|>


<commit_before>//   Copyright 2015 Patrick Putnam
//
//   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.
#ifndef CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
#define CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_

#include "clotho/data_spaces/phenotype_evaluator/weight_accumulator_def.hpp"
#include "clotho/data_spaces/phenotype_evaluator/column_aligned_weight_accumulator.hpp"
#include "clotho/data_spaces/phenotype_evaluator/row_grouped_weight_accumulator.hpp"

#endif  // CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
<commit_msg>Adding row vector based accumulator<commit_after>//   Copyright 2015 Patrick Putnam
//
//   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.
#ifndef CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
#define CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_

#include "clotho/data_spaces/phenotype_evaluator/weight_accumulator_def.hpp"
#include "clotho/data_spaces/phenotype_evaluator/column_aligned_weight_accumulator.hpp"
#include "clotho/data_spaces/phenotype_evaluator/row_grouped_weight_accumulator.hpp"
#include "clotho/data_spaces/phenotype_evaluator/row_vector_weight_accumulator.hpp"

#endif  // CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
<|endoftext|>