text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include <gtest/gtest.h>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"
class Parallel2Test : testing::Test { };
TEST(Parallel2Test, Test1)
{
std::future<int> f1 = asyncply::_async([](int data){return data;}, 10);
ASSERT_EQ(f1.get(), 10);
}
TEST(Parallel2Test, Test2)
{
auto f1 = asyncply::async([](){return 15;});
auto f2 = f1->then([](int data) {
std::cout << "post, received: " << data << std::endl;
return data + 6;
});
ASSERT_EQ(f2->get(), 15 + 6);
}
TEST(Parallel2Test, Test3)
{
std::vector<int> a;
for(int i=0; i<100; ++i)
{
a.push_back(1);
a.push_back(4);
a.push_back(12);
a.push_back(-3);
a.push_back(22);
}
std::atomic<int> total;
total = 0;
asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
total += i;
});
ASSERT_EQ(total, 3600);
}
TEST(Parallel2Test, Test3_async)
{
std::vector<int> a;
for(int i=0; i<100; ++i)
{
a.push_back(1);
a.push_back(4);
a.push_back(12);
a.push_back(-3);
a.push_back(22);
}
std::atomic<int> total;
total = 0;
asyncply::for_each(a.begin(), a.end(), [&total](int i) {
total += i;
});
ASSERT_EQ(total, 3600);
}
TEST(Parallel2Test, Test4)
{
auto total_ps = asyncply::parallel_sync(
[]()
{
return asyncply::sequence(1.0,
[](double data)
{
return data + 1.0;
},
[](double data)
{
return data + 1.0;
});
},
[]()
{
return asyncply::sequence(1.0,
[](double data)
{
return data + 1.0;
},
[](double data)
{
return data + 1.0;
});
}
);
ASSERT_EQ(total_ps, 6);
}
TEST(Parallel2Test, Test5)
{
std::atomic<int> total;
total = 0;
auto process = asyncply::parallel(
[&total]()
{
std::cout << "hi" << std::endl;
total += 1;
},
[&total]()
{
std::cout << "bye" << std::endl;
total += 1;
}
);
auto process2 = process->then([&total]()
{
std::cout << "no accum" << std::endl;
total += 1;
});
process2->get();
ASSERT_EQ(total, 3);
}
TEST(Parallel2Test, Test6)
{
std::atomic<int> total;
total = 0;
{
auto process = asyncply::parallel(
[&total]()
{
std::cout << "hi" << std::endl;
total += 1;
},
[&total]()
{
std::cout << "bye" << std::endl;
total += 1;
}
);
auto process2 = process->then([&total]()
{
std::cout << "no accum" << std::endl;
total += 1;
});
// wait end
process2->get();
}
ASSERT_EQ(total, 3);
}
<commit_msg>Update test_parallel2.cpp<commit_after>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include <gtest/gtest.h>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"
class Parallel2Test : testing::Test { };
TEST(Parallel2Test, Test1)
{
std::future<int> f1 = asyncply::_async([](int data){return data;}, 10);
ASSERT_EQ(f1.get(), 10);
}
TEST(Parallel2Test, Test2)
{
auto f1 = asyncply::async([](){return 15;});
auto f2 = f1->then([](int data) {
std::cout << "post, received: " << data << std::endl;
return data + 6;
});
ASSERT_EQ(f2->get(), 15 + 6);
}
TEST(Parallel2Test, Test3)
{
std::vector<int> a;
for(int i=0; i<100; ++i)
{
a.push_back(1);
a.push_back(4);
a.push_back(12);
a.push_back(-3);
a.push_back(22);
}
std::atomic<int> total;
total = 0;
asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
total += i;
});
ASSERT_EQ(total, 3600);
}
TEST(Parallel2Test, Test3_async)
{
std::vector<int> a;
for(int i=0; i<100; ++i)
{
a.push_back(1);
a.push_back(4);
a.push_back(12);
a.push_back(-3);
a.push_back(22);
}
std::atomic<int> total;
total = 0;
asyncply::for_each(a.begin(), a.end(), [&total](int i) {
total += i;
});
ASSERT_EQ(total, 3600);
}
TEST(Parallel2Test, Test4)
{
double total_ps = asyncply::parallel_sync(
[]()
{
return asyncply::sequence(1.0,
[](double data)
{
return data + 1.0;
},
[](double data)
{
return data + 1.0;
});
},
[]()
{
return asyncply::sequence(1.0,
[](double data)
{
return data + 1.0;
},
[](double data)
{
return data + 1.0;
});
}
);
ASSERT_EQ(total_ps, 6);
}
TEST(Parallel2Test, Test5)
{
std::atomic<int> total;
total = 0;
auto process = asyncply::parallel(
[&total]()
{
std::cout << "hi" << std::endl;
total += 1;
},
[&total]()
{
std::cout << "bye" << std::endl;
total += 1;
}
);
auto process2 = process->then([&total]()
{
std::cout << "no accum" << std::endl;
total += 1;
});
process2->get();
ASSERT_EQ(total, 3);
}
TEST(Parallel2Test, Test6)
{
std::atomic<int> total;
total = 0;
{
auto process = asyncply::parallel(
[&total]()
{
std::cout << "hi" << std::endl;
total += 1;
},
[&total]()
{
std::cout << "bye" << std::endl;
total += 1;
}
);
auto process2 = process->then([&total]()
{
std::cout << "no accum" << std::endl;
total += 1;
});
// wait end
process2->get();
}
ASSERT_EQ(total, 3);
}
<|endoftext|>
|
<commit_before>// A C / C++ program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include "dk.h"
using namespace std;
int src, tgt;
int NV, NE;
map<int, Point> cities;
double** g;
double** c;
Graph gg;
void set_input()
{
src = 0; tgt = 5;
cout << "Input source city index: " << src << endl;
cout << "Input destination city index: " << tgt << endl;
cout << "Computing shortest path from: " << src << " to "
<< tgt << endl;
}
void get_input()
{
cout << "Input source city index: ";
cin >> src;
cout << "Input destination city index: ";
cin >> tgt;
cout << "Computing shortest path from: " << src << " to "
<< tgt << endl;
}
void make_graph2()
{
int u, v, d, i, j;
ifstream in("./doc/sample.txt", ios::in);
if(in.is_open())
{
for(i = 0; i < NE; ++i)
{
in >> u;
in >> v;
Vertex vu(u);
Vertex vv(v);
vu.p = cities[u];
vv.p = cities[v];
gg.add_edge(vu, vv, cities[u].distance(cities[v]));
}
cout << gg;
}
}
void make_graph()
{
int u, v, d, i, j;
ifstream in("./doc/sample.txt", ios::in);
stringstream ss;
if(in.is_open())
{
in >> NV >> NE;
for(i = 0; i < NV; ++i)
{
Point p;
in >> p.idx;
in >> p.x;
in >> p.y;
cities[p.idx] = p;
cout << "Add City: " << p << endl;
}
g = new double*[NV];
c = new double*[NV];
for(i = 0; i < NV; ++i)
{
g[i] = new double[NV];
}
for(i = 0; i < NV; ++i)
{
for(j = 0; j < NV; ++j)
{
g[i][j] = 0;
}
}
for(i = 0; i < NE; ++i)
{
in >> u;
in >> v;
ss << u;
Vertex vu(ss.str());
ss.str(""); ss.clear();
ss << v;
Vertex vv(ss.str());
ss.str(""); ss.clear();
vu.p = cities[u];
vv.p = cities[v];
g[u][v] = g[v][u] = cities[u].distance(cities[v]);
gg.add_edge(vu, vv, cities[u].distance(cities[v]));
}
for(i = 0; i < NV; ++i)
{
for(j = 0; j < NV; ++j)
{
cout << g[i][j] << "\t";
}
cout << endl;
}
cout << gg;
}
}
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int mindk(double dist[], bool sptSet[])
{
// Initialize min value
double min = DBL_MAX, min_index;
for (int v = 0; v < NV; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance array
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
int printdk(double dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < NV; i++)
printf("%d \t\t %f\n", i, dist[i]);
}
void printc()
{
for (int i = 0; i < NV; ++i)
{
for(int j = 0; j < NV; ++j)
{
cout << c[i][j]<< "\t";
}
cout << endl;
}
}
set<int> dk(double** & dk, int src, int tgt)
{
set<int> path;
double dist[NV]; // The output array. dist[i] will hold the shortest
// distance from src to i
bool sptSet[NV]; // sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < NV; i++)
dist[i] = DBL_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
//dist[src] = 0;
int cc = 0, nc = 0;
// Find shortest path for all vertices
for (int count = 0; count < NV-1; count++)
{
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in first iteration.
int u = mindk(dist, sptSet);
if (count == tgt)
cout << "u: " << u << endl;
// Mark the picked vertex as processed
sptSet[u] = true;
//cout << "p: " << u << endl;
// Update dist value of the adjacent vertices of the picked vertex.
for (int v = 0; v < NV; v++)
{
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && g[u][v] && dist[u] != DBL_MAX
&& dist[u] + g[u][v] < dist[v])
{
path.insert(count);
dist[v] = dist[u] + g[u][v];
}
}
}
// print the constructed distance array
printdk(dist, NV);
//printc();
return path;
}
int main()
{
make_graph();
set_input();
get<int> p = dk(g, src, tgt);
stringstream ss;
string srcstr, tgtstr;
ss << src; ss >> srcstr;
ss.str(""); ss.clear();
ss << tgt; ss >> tgtstr;
ss.str(""); ss.clear();
set<string> pp = gg.dk_spath(srcstr, tgtstr, tgt);
set<int>::iterator i = p.begin();
for( ; i != p.end(); ++i)
cout << *i << " -> ";
cout << tgt << endl;
set<string>::iterator ii = pp.begin();
for( ; ii != pp.end(); ++ii)
cout << *ii << " -> ";
cout << tgt << endl;
return 0;
}
<commit_msg>add input file command line option<commit_after>// A C / C++ program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph
#include <stdio.h>
#include <limits.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include "dk.h"
using namespace std;
string mapfile = "";
int src, tgt;
int NV, NE;
map<int, Point> cities;
double** g;
double** c;
Graph gg;
void set_input()
{
src = 0; tgt = 5;
cout << "Input source city index: " << src << endl;
cout << "Input destination city index: " << tgt << endl;
cout << "Computing shortest path from: " << src << " to "
<< tgt << endl;
}
void get_input()
{
cout << "Input source city index: ";
cin >> src;
cout << "Input destination city index: ";
cin >> tgt;
cout << "Computing shortest path from: " << src << " to "
<< tgt << endl;
}
void make_graph(string input = "./doc/sample.txt")
{
int u, v, d, i, j;
ifstream in(input.c_str(), ios::in);
stringstream ss;
if(in.is_open())
{
in >> NV >> NE;
for(i = 0; i < NV; ++i)
{
Point p;
in >> p.idx;
in >> p.x;
in >> p.y;
cities[p.idx] = p;
cout << "Add City: " << p << endl;
}
g = new double*[NV];
c = new double*[NV];
for(i = 0; i < NV; ++i)
{
g[i] = new double[NV];
}
for(i = 0; i < NV; ++i)
{
for(j = 0; j < NV; ++j)
{
g[i][j] = 0;
}
}
for(i = 0; i < NE; ++i)
{
in >> u;
in >> v;
ss << u;
Vertex vu(ss.str());
ss.str(""); ss.clear();
ss << v;
Vertex vv(ss.str());
ss.str(""); ss.clear();
vu.p = cities[u];
vv.p = cities[v];
g[u][v] = g[v][u] = cities[u].distance(cities[v]);
gg.add_edge(vu, vv, cities[u].distance(cities[v]));
}
for(i = 0; i < NV; ++i)
{
for(j = 0; j < NV; ++j)
{
cout << g[i][j] << "\t";
}
cout << endl;
}
cout << gg;
}
}
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int mindk(double dist[], bool sptSet[])
{
// Initialize min value
double min = DBL_MAX, min_index;
for (int v = 0; v < NV; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance array
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
int printdk(double dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < NV; i++)
printf("%d \t\t %f\n", i, dist[i]);
}
void printc()
{
for (int i = 0; i < NV; ++i)
{
for(int j = 0; j < NV; ++j)
{
cout << c[i][j]<< "\t";
}
cout << endl;
}
}
set<int> dk(double** & dk, int src, int tgt)
{
set<int> path;
double dist[NV]; // The output array. dist[i] will hold the shortest
// distance from src to i
bool sptSet[NV]; // sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < NV; i++)
dist[i] = DBL_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
//dist[src] = 0;
int cc = 0, nc = 0;
// Find shortest path for all vertices
for (int count = 0; count < NV-1; count++)
{
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in first iteration.
int u = mindk(dist, sptSet);
if (count == tgt)
cout << "u: " << u << endl;
// Mark the picked vertex as processed
sptSet[u] = true;
//cout << "p: " << u << endl;
// Update dist value of the adjacent vertices of the picked vertex.
for (int v = 0; v < NV; v++)
{
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && g[u][v] && dist[u] != DBL_MAX
&& dist[u] + g[u][v] < dist[v])
{
path.insert(count);
dist[v] = dist[u] + g[u][v];
}
}
}
// print the constructed distance array
printdk(dist, NV);
//printc();
return path;
}
int main(int argc, char* argv[])
{
if (argc == 2)
{
stringstream s;
s << argv[1];
s >> mapfile;
}
make_graph();
get_input();
set<int> p = dk(g, src, tgt);
stringstream ss;
string srcstr, tgtstr;
ss << src; ss >> srcstr;
ss.str(""); ss.clear();
ss << tgt; ss >> tgtstr;
ss.str(""); ss.clear();
set<string> pp = gg.dk_spath(srcstr, tgtstr, tgt);
set<int>::iterator i = p.begin();
for( ; i != p.end(); ++i)
cout << *i << " -> ";
cout << tgt << endl;
set<string>::iterator ii = pp.begin();
for( ; ii != pp.end(); ++ii)
cout << *ii << " -> ";
cout << tgt << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "BenchTimer.h"
#include "SkCommandLineFlags.h"
#include "SkForceLinking.h"
#include "SkGraphics.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkRecordDraw.h"
#include "SkRecordOpts.h"
#include "SkRecorder.h"
#include "SkStream.h"
#include "SkString.h"
__SK_FORCE_IMAGE_DECODER_LINKING;
DEFINE_string2(skps, r, "skps", "Directory containing SKPs to read and re-record.");
DEFINE_int32(loops, 10, "Number of times to play back each SKP.");
DEFINE_bool(skr, false, "Play via SkRecord instead of SkPicture.");
DEFINE_int32(tile, 1000000000, "Simulated tile size.");
DEFINE_string(match, "", "The usual filters on file names of SKPs to bench.");
DEFINE_string(timescale, "ms", "Print times in ms, us, or ns");
static double scale_time(double ms) {
if (FLAGS_timescale.contains("us")) ms *= 1000;
if (FLAGS_timescale.contains("ns")) ms *= 1000000;
return ms;
}
static void bench(SkPMColor* scratch, SkPicture& src, const char* name) {
// We don't use the public SkRecording interface here because we need kWriteOnly_Mode.
// (We don't want SkPicturePlayback to be able to optimize playing into our SkRecord.)
SkRecord record;
SkRecorder recorder(SkRecorder::kWriteOnly_Mode, &record, src.width(), src.height());
src.draw(&recorder);
SkRecordOptimize(&record);
SkAutoTDelete<SkCanvas> canvas(SkCanvas::NewRasterDirectN32(src.width(),
src.height(),
scratch,
src.width() * sizeof(SkPMColor)));
canvas->clipRect(SkRect::MakeWH(SkIntToScalar(FLAGS_tile), SkIntToScalar(FLAGS_tile)));
BenchTimer timer;
timer.start();
for (int i = 0; i < FLAGS_loops; i++) {
if (FLAGS_skr) {
SkRecordDraw(record, canvas.get());
} else {
src.draw(canvas.get());
}
}
timer.end();
const double msPerLoop = timer.fCpu / (double)FLAGS_loops;
printf("%f\t%s\n", scale_time(msPerLoop), name);
}
int tool_main(int argc, char** argv);
int tool_main(int argc, char** argv) {
SkCommandLineFlags::Parse(argc, argv);
SkAutoGraphics autoGraphics;
// We share a single scratch bitmap among benches to reduce the profile noise from allocation.
static const int kMaxArea = 209825221; // tabl_mozilla is this big.
SkAutoTMalloc<SkPMColor> scratch(kMaxArea);
SkOSFile::Iter it(FLAGS_skps[0], ".skp");
SkString filename;
bool failed = false;
while (it.next(&filename)) {
if (SkCommandLineFlags::ShouldSkip(FLAGS_match, filename.c_str())) {
continue;
}
const SkString path = SkOSPath::SkPathJoin(FLAGS_skps[0], filename.c_str());
SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path.c_str()));
if (!stream) {
SkDebugf("Could not read %s.\n", path.c_str());
failed = true;
continue;
}
SkAutoTUnref<SkPicture> src(SkPicture::CreateFromStream(stream));
if (!src) {
SkDebugf("Could not read %s as an SkPicture.\n", path.c_str());
failed = true;
continue;
}
if (src->width() * src->height() > kMaxArea) {
SkDebugf("%s (%dx%d) is larger than hardcoded scratch bitmap (%dpx).\n",
path.c_str(), src->width(), src->height(), kMaxArea);
failed = true;
continue;
}
bench(scratch.get(), *src, filename.c_str());
}
return failed ? 1 : 0;
}
#if !defined SK_BUILD_FOR_IOS
int main(int argc, char * const argv[]) {
return tool_main(argc, (char**) argv);
}
#endif
<commit_msg>Use a tilegrid for bench_playback.<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "BenchTimer.h"
#include "SkCommandLineFlags.h"
#include "SkForceLinking.h"
#include "SkGraphics.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkRecordDraw.h"
#include "SkRecordOpts.h"
#include "SkRecorder.h"
#include "SkStream.h"
#include "SkString.h"
__SK_FORCE_IMAGE_DECODER_LINKING;
DEFINE_string2(skps, r, "skps", "Directory containing SKPs to read and re-record.");
DEFINE_int32(loops, 10, "Number of times to play back each SKP.");
DEFINE_bool(skr, false, "Play via SkRecord instead of SkPicture.");
DEFINE_int32(tile, 1000000000, "Simulated tile size.");
DEFINE_string(match, "", "The usual filters on file names of SKPs to bench.");
DEFINE_string(timescale, "ms", "Print times in ms, us, or ns");
static double scale_time(double ms) {
if (FLAGS_timescale.contains("us")) ms *= 1000;
if (FLAGS_timescale.contains("ns")) ms *= 1000000;
return ms;
}
static void bench(SkPMColor* scratch, SkPicture& src, const char* name) {
// We don't use the public SkRecording interface here because we need kWriteOnly_Mode.
// (We don't want SkPicturePlayback to be able to optimize playing into our SkRecord.)
SkRecord record;
SkRecorder recorder(SkRecorder::kWriteOnly_Mode, &record, src.width(), src.height());
src.draw(&recorder);
SkRecordOptimize(&record);
SkAutoTDelete<SkCanvas> canvas(SkCanvas::NewRasterDirectN32(src.width(),
src.height(),
scratch,
src.width() * sizeof(SkPMColor)));
canvas->clipRect(SkRect::MakeWH(SkIntToScalar(FLAGS_tile), SkIntToScalar(FLAGS_tile)));
BenchTimer timer;
timer.start();
for (int i = 0; i < FLAGS_loops; i++) {
if (FLAGS_skr) {
SkRecordDraw(record, canvas.get());
} else {
src.draw(canvas.get());
}
}
timer.end();
const double msPerLoop = timer.fCpu / (double)FLAGS_loops;
printf("%f\t%s\n", scale_time(msPerLoop), name);
}
int tool_main(int argc, char** argv);
int tool_main(int argc, char** argv) {
SkCommandLineFlags::Parse(argc, argv);
SkAutoGraphics autoGraphics;
// We share a single scratch bitmap among benches to reduce the profile noise from allocation.
static const int kMaxArea = 209825221; // tabl_mozilla is this big.
SkAutoTMalloc<SkPMColor> scratch(kMaxArea);
SkOSFile::Iter it(FLAGS_skps[0], ".skp");
SkString filename;
bool failed = false;
while (it.next(&filename)) {
if (SkCommandLineFlags::ShouldSkip(FLAGS_match, filename.c_str())) {
continue;
}
const SkString path = SkOSPath::SkPathJoin(FLAGS_skps[0], filename.c_str());
SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path.c_str()));
if (!stream) {
SkDebugf("Could not read %s.\n", path.c_str());
failed = true;
continue;
}
SkAutoTUnref<SkPicture> src(SkPicture::CreateFromStream(stream));
if (!src) {
SkDebugf("Could not read %s as an SkPicture.\n", path.c_str());
failed = true;
continue;
}
if (src->width() * src->height() > kMaxArea) {
SkDebugf("%s (%dx%d) is larger than hardcoded scratch bitmap (%dpx).\n",
path.c_str(), src->width(), src->height(), kMaxArea);
failed = true;
continue;
}
// Rerecord into a picture using a tile grid.
SkTileGridFactory::TileGridInfo info;
info.fTileInterval.set(FLAGS_tile, FLAGS_tile);
info.fMargin.setEmpty();
info.fOffset.setZero();
SkTileGridFactory factory(info);
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(src->width(), src->height(),
&factory,
SkPicture::kUsePathBoundsForClip_RecordingFlag);
src->draw(canvas);
SkAutoTUnref<SkPicture> replay(recorder.endRecording());
bench(scratch.get(), *replay, filename.c_str());
}
return failed ? 1 : 0;
}
#if !defined SK_BUILD_FOR_IOS
int main(int argc, char * const argv[]) {
return tool_main(argc, (char**) argv);
}
#endif
<|endoftext|>
|
<commit_before>//===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief The ELF component of yaml2obj.
///
//===----------------------------------------------------------------------===//
#include "yaml2obj.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFYAML.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
// There is similar code in yaml2coff, but with some slight COFF-specific
// variations like different initial state. Might be able to deduplicate
// some day, but also want to make sure that the Mach-O use case is served.
//
// This class has a deliberately small interface, since a lot of
// implementation variation is possible.
//
// TODO: Use an ordered container with a suffix-based comparison in order
// to deduplicate suffixes. std::map<> with a custom comparator is likely
// to be the simplest implementation, but a suffix trie could be more
// suitable for the job.
namespace {
class StringTableBuilder {
/// \brief Indices of strings currently present in `Buf`.
StringMap<unsigned> StringIndices;
/// \brief The contents of the string table as we build it.
std::string Buf;
public:
StringTableBuilder() {
Buf.push_back('\0');
}
/// \returns Index of string in string table.
unsigned addString(StringRef S) {
StringMapEntry<unsigned> &Entry = StringIndices.GetOrCreateValue(S);
unsigned &I = Entry.getValue();
if (I != 0)
return I;
I = Buf.size();
Buf.append(S.begin(), S.end());
Buf.push_back('\0');
return I;
}
size_t size() const {
return Buf.size();
}
void writeToStream(raw_ostream &OS) {
OS.write(Buf.data(), Buf.size());
}
};
} // end anonymous namespace
// This class is used to build up a contiguous binary blob while keeping
// track of an offset in the output (which notionally begins at
// `InitialOffset`).
namespace {
class ContiguousBlobAccumulator {
const uint64_t InitialOffset;
raw_svector_ostream OS;
public:
ContiguousBlobAccumulator(uint64_t InitialOffset_, SmallVectorImpl<char> &Buf)
: InitialOffset(InitialOffset_), OS(Buf) {}
raw_ostream &getOS() { return OS; }
uint64_t currentOffset() const { return InitialOffset + OS.tell(); }
void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
};
} // end anonymous namespace
// Used to keep track of section names, so that in the YAML file sections
// can be referenced by name instead of by index.
namespace {
class SectionNameToIdxMap {
StringMap<int> Map;
public:
/// \returns true if name is already present in the map.
bool addName(StringRef SecName, unsigned i) {
StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
if (Entry.getValue() != -1)
return true;
Entry.setValue((int)i);
return false;
}
/// \returns true if name is not present in the map
bool lookupSection(StringRef SecName, unsigned &Idx) const {
StringMap<int>::const_iterator I = Map.find(SecName);
if (I == Map.end())
return true;
Idx = I->getValue();
return false;
}
};
} // end anonymous namespace
template <class T>
static size_t vectorDataSize(const std::vector<T> &Vec) {
return Vec.size() * sizeof(T);
}
template <class T>
static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
OS.write((const char *)Vec.data(), vectorDataSize(Vec));
}
template <class T>
static void zero(T &Obj) {
memset(&Obj, 0, sizeof(Obj));
}
/// \brief Create a string table in `SHeader`, which we assume is already
/// zero'd.
template <class Elf_Shdr>
static void createStringTableSectionHeader(Elf_Shdr &SHeader,
StringTableBuilder &STB,
ContiguousBlobAccumulator &CBA) {
SHeader.sh_type = ELF::SHT_STRTAB;
SHeader.sh_offset = CBA.currentOffset();
SHeader.sh_size = STB.size();
STB.writeToStream(CBA.getOS());
SHeader.sh_addralign = 1;
}
// FIXME: This function is hideous. Between the sheer number of parameters
// and the hideous ELF typenames, it's just a travesty. Factor the ELF
// output into a class (templated on ELFT) and share some typedefs.
template <class ELFT>
static void handleSymtabSectionHeader(
const ELFYAML::Section &Sec,
const typename object::ELFObjectFile<ELFT>::Elf_Ehdr &Header,
typename object::ELFObjectFile<ELFT>::Elf_Shdr &SHeader,
StringTableBuilder &StrTab, ContiguousBlobAccumulator &CBA,
unsigned DotStrtabSecNo) {
typedef typename object::ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
// TODO: Ensure that a manually specified `Link` field is diagnosed as an
// error for SHT_SYMTAB.
SHeader.sh_link = DotStrtabSecNo;
// TODO: Once we handle symbol binding, this should be one greater than
// symbol table index of the last local symbol.
SHeader.sh_info = 0;
SHeader.sh_entsize = sizeof(Elf_Sym);
std::vector<Elf_Sym> Syms;
{
// Ensure STN_UNDEF is present
Elf_Sym Sym;
zero(Sym);
Syms.push_back(Sym);
}
for (unsigned i = 0, e = Sec.Symbols.size(); i != e; ++i) {
const ELFYAML::Symbol &Sym = Sec.Symbols[i];
Elf_Sym Symbol;
zero(Symbol);
if (!Sym.Name.empty())
Symbol.st_name = StrTab.addString(Sym.Name);
Symbol.setBindingAndType(Sym.Binding, Sym.Type);
Syms.push_back(Symbol);
}
SHeader.sh_offset = CBA.currentOffset();
SHeader.sh_size = vectorDataSize(Syms);
writeVectorData(CBA.getOS(), Syms);
}
template <class ELFT>
static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
using namespace llvm::ELF;
using namespace llvm::object;
typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
const ELFYAML::FileHeader &Hdr = Doc.Header;
Elf_Ehdr Header;
zero(Header);
Header.e_ident[EI_MAG0] = 0x7f;
Header.e_ident[EI_MAG1] = 'E';
Header.e_ident[EI_MAG2] = 'L';
Header.e_ident[EI_MAG3] = 'F';
Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
bool IsLittleEndian = ELFT::TargetEndianness == support::little;
Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
Header.e_ident[EI_VERSION] = EV_CURRENT;
// TODO: Implement ELF_ELFOSABI enum.
Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
// TODO: Implement ELF_ABIVERSION enum.
Header.e_ident[EI_ABIVERSION] = 0;
Header.e_type = Hdr.Type;
Header.e_machine = Hdr.Machine;
Header.e_version = EV_CURRENT;
Header.e_entry = Hdr.Entry;
Header.e_ehsize = sizeof(Elf_Ehdr);
// TODO: Flesh out section header support.
// TODO: Program headers.
Header.e_shentsize = sizeof(Elf_Shdr);
// Immediately following the ELF header.
Header.e_shoff = sizeof(Header);
const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
// "+ 3" for
// - SHT_NULL entry (placed first, i.e. 0'th entry)
// - string table (.strtab) (placed second to last)
// - section header string table. (placed last)
Header.e_shnum = Sections.size() + 3;
// Place section header string table last.
Header.e_shstrndx = Header.e_shnum - 1;
const unsigned DotStrtabSecNo = Header.e_shnum - 2;
SectionNameToIdxMap SN2I;
for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
StringRef Name = Sections[i].Name;
if (Name.empty())
continue;
// "+ 1" to take into account the SHT_NULL entry.
if (SN2I.addName(Name, i + 1)) {
errs() << "error: Repeated section name: '" << Name
<< "' at YAML section number " << i << ".\n";
return 1;
}
}
StringTableBuilder SHStrTab;
SmallVector<char, 128> Buf;
// XXX: This offset is tightly coupled with the order that we write
// things to `OS`.
const size_t SectionContentBeginOffset =
Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
std::vector<Elf_Shdr> SHeaders;
{
// Ensure SHN_UNDEF entry is present. An all-zero section header is a
// valid SHN_UNDEF entry since SHT_NULL == 0.
Elf_Shdr SHdr;
zero(SHdr);
SHeaders.push_back(SHdr);
}
StringTableBuilder DotStrTab;
for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
const ELFYAML::Section &Sec = Sections[i];
Elf_Shdr SHeader;
zero(SHeader);
SHeader.sh_name = SHStrTab.addString(Sec.Name);
SHeader.sh_type = Sec.Type;
SHeader.sh_flags = Sec.Flags;
SHeader.sh_addr = Sec.Address;
SHeader.sh_offset = CBA.currentOffset();
SHeader.sh_size = Sec.Content.binary_size();
Sec.Content.writeAsBinary(CBA.getOS());
if (!Sec.Link.empty()) {
unsigned Index;
if (SN2I.lookupSection(Sec.Link, Index)) {
errs() << "error: Unknown section referenced: '" << Sec.Link
<< "' at YAML section number " << i << ".\n";
return 1;
}
SHeader.sh_link = Index;
}
SHeader.sh_info = 0;
SHeader.sh_addralign = Sec.AddressAlign;
SHeader.sh_entsize = 0;
// XXX: Really ugly right now. Need to put common state into a class.
if (Sec.Type == ELFYAML::ELF_SHT(SHT_SYMTAB))
handleSymtabSectionHeader<ELFT>(Sec, Header, SHeader, DotStrTab, CBA,
DotStrtabSecNo);
SHeaders.push_back(SHeader);
}
// .strtab string table header.
Elf_Shdr DotStrTabSHeader;
zero(DotStrTabSHeader);
DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
createStringTableSectionHeader(DotStrTabSHeader, DotStrTab, CBA);
// Section header string table header.
Elf_Shdr SHStrTabSHeader;
zero(SHStrTabSHeader);
createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
OS.write((const char *)&Header, sizeof(Header));
writeVectorData(OS, SHeaders);
OS.write((const char *)&DotStrTabSHeader, sizeof(DotStrTabSHeader));
OS.write((const char *)&SHStrTabSHeader, sizeof(SHStrTabSHeader));
CBA.writeBlobToStream(OS);
return 0;
}
int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
yaml::Input YIn(Buf->getBuffer());
ELFYAML::Object Doc;
YIn >> Doc;
if (YIn.error()) {
errs() << "yaml2obj: Failed to parse YAML file!\n";
return 1;
}
if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
return writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
else
return writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
} else {
if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
return writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
else
return writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
}
}
<commit_msg>There is no ELF ABI version enum.<commit_after>//===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief The ELF component of yaml2obj.
///
//===----------------------------------------------------------------------===//
#include "yaml2obj.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFYAML.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
// There is similar code in yaml2coff, but with some slight COFF-specific
// variations like different initial state. Might be able to deduplicate
// some day, but also want to make sure that the Mach-O use case is served.
//
// This class has a deliberately small interface, since a lot of
// implementation variation is possible.
//
// TODO: Use an ordered container with a suffix-based comparison in order
// to deduplicate suffixes. std::map<> with a custom comparator is likely
// to be the simplest implementation, but a suffix trie could be more
// suitable for the job.
namespace {
class StringTableBuilder {
/// \brief Indices of strings currently present in `Buf`.
StringMap<unsigned> StringIndices;
/// \brief The contents of the string table as we build it.
std::string Buf;
public:
StringTableBuilder() {
Buf.push_back('\0');
}
/// \returns Index of string in string table.
unsigned addString(StringRef S) {
StringMapEntry<unsigned> &Entry = StringIndices.GetOrCreateValue(S);
unsigned &I = Entry.getValue();
if (I != 0)
return I;
I = Buf.size();
Buf.append(S.begin(), S.end());
Buf.push_back('\0');
return I;
}
size_t size() const {
return Buf.size();
}
void writeToStream(raw_ostream &OS) {
OS.write(Buf.data(), Buf.size());
}
};
} // end anonymous namespace
// This class is used to build up a contiguous binary blob while keeping
// track of an offset in the output (which notionally begins at
// `InitialOffset`).
namespace {
class ContiguousBlobAccumulator {
const uint64_t InitialOffset;
raw_svector_ostream OS;
public:
ContiguousBlobAccumulator(uint64_t InitialOffset_, SmallVectorImpl<char> &Buf)
: InitialOffset(InitialOffset_), OS(Buf) {}
raw_ostream &getOS() { return OS; }
uint64_t currentOffset() const { return InitialOffset + OS.tell(); }
void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
};
} // end anonymous namespace
// Used to keep track of section names, so that in the YAML file sections
// can be referenced by name instead of by index.
namespace {
class SectionNameToIdxMap {
StringMap<int> Map;
public:
/// \returns true if name is already present in the map.
bool addName(StringRef SecName, unsigned i) {
StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
if (Entry.getValue() != -1)
return true;
Entry.setValue((int)i);
return false;
}
/// \returns true if name is not present in the map
bool lookupSection(StringRef SecName, unsigned &Idx) const {
StringMap<int>::const_iterator I = Map.find(SecName);
if (I == Map.end())
return true;
Idx = I->getValue();
return false;
}
};
} // end anonymous namespace
template <class T>
static size_t vectorDataSize(const std::vector<T> &Vec) {
return Vec.size() * sizeof(T);
}
template <class T>
static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
OS.write((const char *)Vec.data(), vectorDataSize(Vec));
}
template <class T>
static void zero(T &Obj) {
memset(&Obj, 0, sizeof(Obj));
}
/// \brief Create a string table in `SHeader`, which we assume is already
/// zero'd.
template <class Elf_Shdr>
static void createStringTableSectionHeader(Elf_Shdr &SHeader,
StringTableBuilder &STB,
ContiguousBlobAccumulator &CBA) {
SHeader.sh_type = ELF::SHT_STRTAB;
SHeader.sh_offset = CBA.currentOffset();
SHeader.sh_size = STB.size();
STB.writeToStream(CBA.getOS());
SHeader.sh_addralign = 1;
}
// FIXME: This function is hideous. Between the sheer number of parameters
// and the hideous ELF typenames, it's just a travesty. Factor the ELF
// output into a class (templated on ELFT) and share some typedefs.
template <class ELFT>
static void handleSymtabSectionHeader(
const ELFYAML::Section &Sec,
const typename object::ELFObjectFile<ELFT>::Elf_Ehdr &Header,
typename object::ELFObjectFile<ELFT>::Elf_Shdr &SHeader,
StringTableBuilder &StrTab, ContiguousBlobAccumulator &CBA,
unsigned DotStrtabSecNo) {
typedef typename object::ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
// TODO: Ensure that a manually specified `Link` field is diagnosed as an
// error for SHT_SYMTAB.
SHeader.sh_link = DotStrtabSecNo;
// TODO: Once we handle symbol binding, this should be one greater than
// symbol table index of the last local symbol.
SHeader.sh_info = 0;
SHeader.sh_entsize = sizeof(Elf_Sym);
std::vector<Elf_Sym> Syms;
{
// Ensure STN_UNDEF is present
Elf_Sym Sym;
zero(Sym);
Syms.push_back(Sym);
}
for (unsigned i = 0, e = Sec.Symbols.size(); i != e; ++i) {
const ELFYAML::Symbol &Sym = Sec.Symbols[i];
Elf_Sym Symbol;
zero(Symbol);
if (!Sym.Name.empty())
Symbol.st_name = StrTab.addString(Sym.Name);
Symbol.setBindingAndType(Sym.Binding, Sym.Type);
Syms.push_back(Symbol);
}
SHeader.sh_offset = CBA.currentOffset();
SHeader.sh_size = vectorDataSize(Syms);
writeVectorData(CBA.getOS(), Syms);
}
template <class ELFT>
static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
using namespace llvm::ELF;
using namespace llvm::object;
typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
const ELFYAML::FileHeader &Hdr = Doc.Header;
Elf_Ehdr Header;
zero(Header);
Header.e_ident[EI_MAG0] = 0x7f;
Header.e_ident[EI_MAG1] = 'E';
Header.e_ident[EI_MAG2] = 'L';
Header.e_ident[EI_MAG3] = 'F';
Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
bool IsLittleEndian = ELFT::TargetEndianness == support::little;
Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
Header.e_ident[EI_VERSION] = EV_CURRENT;
// TODO: Implement ELF_ELFOSABI enum.
Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
Header.e_ident[EI_ABIVERSION] = 0;
Header.e_type = Hdr.Type;
Header.e_machine = Hdr.Machine;
Header.e_version = EV_CURRENT;
Header.e_entry = Hdr.Entry;
Header.e_ehsize = sizeof(Elf_Ehdr);
// TODO: Flesh out section header support.
// TODO: Program headers.
Header.e_shentsize = sizeof(Elf_Shdr);
// Immediately following the ELF header.
Header.e_shoff = sizeof(Header);
const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
// "+ 3" for
// - SHT_NULL entry (placed first, i.e. 0'th entry)
// - string table (.strtab) (placed second to last)
// - section header string table. (placed last)
Header.e_shnum = Sections.size() + 3;
// Place section header string table last.
Header.e_shstrndx = Header.e_shnum - 1;
const unsigned DotStrtabSecNo = Header.e_shnum - 2;
SectionNameToIdxMap SN2I;
for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
StringRef Name = Sections[i].Name;
if (Name.empty())
continue;
// "+ 1" to take into account the SHT_NULL entry.
if (SN2I.addName(Name, i + 1)) {
errs() << "error: Repeated section name: '" << Name
<< "' at YAML section number " << i << ".\n";
return 1;
}
}
StringTableBuilder SHStrTab;
SmallVector<char, 128> Buf;
// XXX: This offset is tightly coupled with the order that we write
// things to `OS`.
const size_t SectionContentBeginOffset =
Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
std::vector<Elf_Shdr> SHeaders;
{
// Ensure SHN_UNDEF entry is present. An all-zero section header is a
// valid SHN_UNDEF entry since SHT_NULL == 0.
Elf_Shdr SHdr;
zero(SHdr);
SHeaders.push_back(SHdr);
}
StringTableBuilder DotStrTab;
for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
const ELFYAML::Section &Sec = Sections[i];
Elf_Shdr SHeader;
zero(SHeader);
SHeader.sh_name = SHStrTab.addString(Sec.Name);
SHeader.sh_type = Sec.Type;
SHeader.sh_flags = Sec.Flags;
SHeader.sh_addr = Sec.Address;
SHeader.sh_offset = CBA.currentOffset();
SHeader.sh_size = Sec.Content.binary_size();
Sec.Content.writeAsBinary(CBA.getOS());
if (!Sec.Link.empty()) {
unsigned Index;
if (SN2I.lookupSection(Sec.Link, Index)) {
errs() << "error: Unknown section referenced: '" << Sec.Link
<< "' at YAML section number " << i << ".\n";
return 1;
}
SHeader.sh_link = Index;
}
SHeader.sh_info = 0;
SHeader.sh_addralign = Sec.AddressAlign;
SHeader.sh_entsize = 0;
// XXX: Really ugly right now. Need to put common state into a class.
if (Sec.Type == ELFYAML::ELF_SHT(SHT_SYMTAB))
handleSymtabSectionHeader<ELFT>(Sec, Header, SHeader, DotStrTab, CBA,
DotStrtabSecNo);
SHeaders.push_back(SHeader);
}
// .strtab string table header.
Elf_Shdr DotStrTabSHeader;
zero(DotStrTabSHeader);
DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
createStringTableSectionHeader(DotStrTabSHeader, DotStrTab, CBA);
// Section header string table header.
Elf_Shdr SHStrTabSHeader;
zero(SHStrTabSHeader);
createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
OS.write((const char *)&Header, sizeof(Header));
writeVectorData(OS, SHeaders);
OS.write((const char *)&DotStrTabSHeader, sizeof(DotStrTabSHeader));
OS.write((const char *)&SHStrTabSHeader, sizeof(SHStrTabSHeader));
CBA.writeBlobToStream(OS);
return 0;
}
int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
yaml::Input YIn(Buf->getBuffer());
ELFYAML::Object Doc;
YIn >> Doc;
if (YIn.error()) {
errs() << "yaml2obj: Failed to parse YAML file!\n";
return 1;
}
if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
return writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
else
return writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
} else {
if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
return writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
else
return writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
}
}
<|endoftext|>
|
<commit_before><commit_msg>Remove the DCHECK in the UrlRequestautomationJob::ReadRawData function which asserts that this function is only invoked in the IO thread. While this is true for ChromeFrame in general for chrome frame net tests this DCHECK fires beause the test suite runs the url request tests in a worker thread created specifically to run these tests.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Fix flaky ExtensionBrowserTest.IncognitoYesScript.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Disabling flaky ExtensionBrowserTest.IncognitoYesScript test.<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium 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 "chrome/browser/ui/toolbar/wrench_menu_model.h"
#include "base/command_line.h"
#include "base/i18n/number_formatting.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/common/chrome_switches.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
void WrenchMenuModel::Build() {
AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
AddItemWithStringId(IDC_NEW_WINDOW, IDS_NEW_WINDOW);
if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession))
AddItemWithStringId(IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW);
AddSeparator();
CreateCutCopyPaste();
AddSeparator();
CreateZoomFullscreen();
AddSeparator();
AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
tools_menu_model_.reset(new ToolsMenuModel(this, browser_));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_TOOLS_MENU,
tools_menu_model_.get());
AddSeparator();
bookmark_sub_menu_model_.reset(new BookmarkSubMenuModel(this, browser_));
AddSubMenuWithStringId(IDC_BOOKMARKS_MENU, IDS_BOOKMARKS_MENU,
bookmark_sub_menu_model_.get());
AddItemWithStringId(IDC_SHOW_HISTORY, IDS_SHOW_HISTORY);
AddItemWithStringId(IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS);
AddSeparator();
AddItemWithStringId(IDC_OPTIONS, IDS_SETTINGS);
AddItem(IDC_ABOUT, l10n_util::GetStringUTF16(IDS_ABOUT));
string16 num_background_pages = base::FormatNumber(
TaskManager::GetBackgroundPageCount());
AddItem(IDC_VIEW_BACKGROUND_PAGES,
l10n_util::GetStringFUTF16(IDS_VIEW_BACKGROUND_PAGES,
num_background_pages));
AddItem(IDC_UPGRADE_DIALOG, l10n_util::GetStringUTF16(IDS_UPDATE_NOW));
AddItem(IDC_VIEW_INCOMPATIBILITIES,
l10n_util::GetStringUTF16(IDS_VIEW_INCOMPATIBILITIES));
// Use an icon for IDC_HELP_PAGE menu item.
AddItemWithStringId(IDC_HELP_PAGE, IDS_HELP_PAGE);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SetIcon(GetIndexOfCommandId(IDC_HELP_PAGE),
*rb.GetBitmapNamed(IDR_HELP_MENU));
// Show IDC_FEEDBACK in top-tier wrench menu for ChromeOS.
AddItemWithStringId(IDC_FEEDBACK, IDS_FEEDBACK);
AddGlobalErrorMenuItems();
AddSeparator();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession)) {
AddItemWithStringId(IDC_EXIT, IDS_EXIT_GUEST_MODE);
AddItemWithStringId(IDC_SHUTDOWN, IDS_SHUTDOWN_BUTTON);
} else if (chromeos::UserManager::Get()->IsLoggedInAsDemoUser()) {
AddItemWithStringId(IDC_EXIT, IDS_SIGN_OUT);
} else {
AddItemWithStringId(IDC_LOCK_SCREEN, IDS_LOCK_SCREEN);
AddItemWithStringId(IDC_EXIT, IDS_SIGN_OUT);
AddItemWithStringId(IDC_SHUTDOWN, IDS_SHUTDOWN_BUTTON);
}
}
<commit_msg>Remove several useless menu items from wrench menu for ash build.<commit_after>// Copyright (c) 2012 The Chromium 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 "chrome/browser/ui/toolbar/wrench_menu_model.h"
#include "base/command_line.h"
#include "base/i18n/number_formatting.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/common/chrome_switches.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
void WrenchMenuModel::Build() {
AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
AddItemWithStringId(IDC_NEW_WINDOW, IDS_NEW_WINDOW);
if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession))
AddItemWithStringId(IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW);
AddSeparator();
CreateCutCopyPaste();
AddSeparator();
CreateZoomFullscreen();
AddSeparator();
AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
tools_menu_model_.reset(new ToolsMenuModel(this, browser_));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_TOOLS_MENU,
tools_menu_model_.get());
AddSeparator();
bookmark_sub_menu_model_.reset(new BookmarkSubMenuModel(this, browser_));
AddSubMenuWithStringId(IDC_BOOKMARKS_MENU, IDS_BOOKMARKS_MENU,
bookmark_sub_menu_model_.get());
AddItemWithStringId(IDC_SHOW_HISTORY, IDS_SHOW_HISTORY);
AddItemWithStringId(IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS);
AddSeparator();
AddItemWithStringId(IDC_OPTIONS, IDS_SETTINGS);
AddItem(IDC_ABOUT, l10n_util::GetStringUTF16(IDS_ABOUT));
string16 num_background_pages = base::FormatNumber(
TaskManager::GetBackgroundPageCount());
AddItem(IDC_VIEW_BACKGROUND_PAGES,
l10n_util::GetStringFUTF16(IDS_VIEW_BACKGROUND_PAGES,
num_background_pages));
AddItem(IDC_UPGRADE_DIALOG, l10n_util::GetStringUTF16(IDS_UPDATE_NOW));
AddItem(IDC_VIEW_INCOMPATIBILITIES,
l10n_util::GetStringUTF16(IDS_VIEW_INCOMPATIBILITIES));
#if !defined(USE_ASH)
// Use an icon for IDC_HELP_PAGE menu item.
AddItemWithStringId(IDC_HELP_PAGE, IDS_HELP_PAGE);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SetIcon(GetIndexOfCommandId(IDC_HELP_PAGE),
*rb.GetBitmapNamed(IDR_HELP_MENU));
#endif
// Show IDC_FEEDBACK in top-tier wrench menu for ChromeOS.
AddItemWithStringId(IDC_FEEDBACK, IDS_FEEDBACK);
AddGlobalErrorMenuItems();
#if !defined(USE_ASH)
AddSeparator();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession)) {
AddItemWithStringId(IDC_EXIT, IDS_EXIT_GUEST_MODE);
AddItemWithStringId(IDC_SHUTDOWN, IDS_SHUTDOWN_BUTTON);
} else if (chromeos::UserManager::Get()->IsLoggedInAsDemoUser()) {
AddItemWithStringId(IDC_EXIT, IDS_SIGN_OUT);
} else {
AddItemWithStringId(IDC_LOCK_SCREEN, IDS_LOCK_SCREEN);
AddItemWithStringId(IDC_EXIT, IDS_SIGN_OUT);
AddItemWithStringId(IDC_SHUTDOWN, IDS_SHUTDOWN_BUTTON);
}
#endif
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium 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 "chrome/browser/ui/webui/shared_resources_data_source.h"
#include <string>
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/shared_resources.h"
#include "grit/shared_resources_map.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
int PathToIDR(const std::string& path) {
int idr = -1;
if (path == "app/resources/folder_closed.png") {
idr = IDR_FOLDER_CLOSED;
} else if (path == "app/resources/folder_closed_rtl.png") {
idr = IDR_FOLDER_CLOSED_RTL;
} else if (path == "app/resources/folder_open.png") {
idr = IDR_FOLDER_OPEN;
} else if (path == "app/resources/folder_open_rtl.png") {
idr = IDR_FOLDER_OPEN_RTL;
} else if (path == "app/resources/throbber.png") {
idr = IDR_THROBBER;
} else {
// The name of the files in the grd list are prefixed with the following
// directory:
std::string key("shared/");
key += path;
for (size_t i = 0; i < kSharedResourcesSize; ++i) {
if (kSharedResources[i].name == key) {
idr = kSharedResources[i].value;
break;
}
}
}
return idr;
}
} // namespace
SharedResourcesDataSource::SharedResourcesDataSource()
: DataSource(chrome::kChromeUIResourcesHost, NULL) {
}
SharedResourcesDataSource::~SharedResourcesDataSource() {
}
void SharedResourcesDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
int idr = PathToIDR(path);
DCHECK_NE(-1, idr);
const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr));
SendResponse(request_id, bytes);
}
std::string SharedResourcesDataSource::GetMimeType(
const std::string& path) const {
// Requests should not block on the disk! On Windows this goes to the
// registry.
// http://code.google.com/p/chromium/issues/detail?id=59849
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::string mime_type;
net::GetMimeTypeFromFile(FilePath().AppendASCII(path), &mime_type);
return mime_type;
}
<commit_msg>shared_resources_data_source.cc: add path name to dcheck<commit_after>// Copyright (c) 2011 The Chromium 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 "chrome/browser/ui/webui/shared_resources_data_source.h"
#include <string>
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/shared_resources.h"
#include "grit/shared_resources_map.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
int PathToIDR(const std::string& path) {
int idr = -1;
if (path == "app/resources/folder_closed.png") {
idr = IDR_FOLDER_CLOSED;
} else if (path == "app/resources/folder_closed_rtl.png") {
idr = IDR_FOLDER_CLOSED_RTL;
} else if (path == "app/resources/folder_open.png") {
idr = IDR_FOLDER_OPEN;
} else if (path == "app/resources/folder_open_rtl.png") {
idr = IDR_FOLDER_OPEN_RTL;
} else if (path == "app/resources/throbber.png") {
idr = IDR_THROBBER;
} else {
// The name of the files in the grd list are prefixed with the following
// directory:
std::string key("shared/");
key += path;
for (size_t i = 0; i < kSharedResourcesSize; ++i) {
if (kSharedResources[i].name == key) {
idr = kSharedResources[i].value;
break;
}
}
}
return idr;
}
} // namespace
SharedResourcesDataSource::SharedResourcesDataSource()
: DataSource(chrome::kChromeUIResourcesHost, NULL) {
}
SharedResourcesDataSource::~SharedResourcesDataSource() {
}
void SharedResourcesDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
int idr = PathToIDR(path);
DCHECK_NE(-1, idr) << " path: " << path;
const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr));
SendResponse(request_id, bytes);
}
std::string SharedResourcesDataSource::GetMimeType(
const std::string& path) const {
// Requests should not block on the disk! On Windows this goes to the
// registry.
// http://code.google.com/p/chromium/issues/detail?id=59849
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::string mime_type;
net::GetMimeTypeFromFile(FilePath().AppendASCII(path), &mime_type);
return mime_type;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium 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 "remoting/base/decoder_vp8.h"
#include "base/logging.h"
#include "media/base/media.h"
#include "media/base/yuv_convert.h"
#include "remoting/base/util.h"
extern "C" {
#define VPX_CODEC_DISABLE_COMPAT 1
#include "third_party/libvpx/libvpx.h"
}
namespace remoting {
DecoderVp8::DecoderVp8()
: state_(kUninitialized),
codec_(NULL),
last_image_(NULL),
horizontal_scale_ratio_(1.0),
vertical_scale_ratio_(1.0) {
}
DecoderVp8::~DecoderVp8() {
if (codec_) {
vpx_codec_err_t ret = vpx_codec_destroy(codec_);
CHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec";
}
delete codec_;
}
void DecoderVp8::Initialize(scoped_refptr<media::VideoFrame> frame) {
DCHECK_EQ(kUninitialized, state_);
if (frame->format() != media::VideoFrame::RGB32) {
LOG(INFO) << "DecoderVp8 only supports RGB32 as output";
state_ = kError;
return;
}
frame_ = frame;
state_ = kReady;
}
Decoder::DecodeResult DecoderVp8::DecodePacket(const VideoPacket* packet) {
DCHECK_EQ(kReady, state_);
// Initialize the codec as needed.
if (!codec_) {
codec_ = new vpx_codec_ctx_t();
// TODO(hclam): Scale the number of threads with number of cores of the
// machine.
vpx_codec_dec_cfg config;
config.w = 0;
config.h = 0;
config.threads = 2;
vpx_codec_err_t ret =
vpx_codec_dec_init(
codec_, vpx_codec_vp8_dx(), &config, 0);
if (ret != VPX_CODEC_OK) {
LOG(INFO) << "Cannot initialize codec.";
delete codec_;
codec_ = NULL;
state_ = kError;
return DECODE_ERROR;
}
}
// Do the actual decoding.
vpx_codec_err_t ret = vpx_codec_decode(
codec_, reinterpret_cast<const uint8*>(packet->data().data()),
packet->data().size(), NULL, 0);
if (ret != VPX_CODEC_OK) {
LOG(INFO) << "Decoding failed:" << vpx_codec_err_to_string(ret) << "\n"
<< "Details: " << vpx_codec_error(codec_) << "\n"
<< vpx_codec_error_detail(codec_);
return DECODE_ERROR;
}
// Gets the decoded data.
vpx_codec_iter_t iter = NULL;
vpx_image_t* image = vpx_codec_get_frame(codec_, &iter);
if (!image) {
LOG(INFO) << "No video frame decoded";
return DECODE_ERROR;
}
last_image_ = image;
RectVector rects;
rects.reserve(packet->dirty_rects_size());
for (int i = 0; i < packet->dirty_rects_size(); ++i) {
Rect remoting_rect = packet->dirty_rects(i);
rects.push_back(SkIRect::MakeXYWH(remoting_rect.x(),
remoting_rect.y(),
remoting_rect.width(),
remoting_rect.height()));
}
if (!DoScaling())
ConvertRects(rects, &updated_rects_);
else
ScaleAndConvertRects(rects, &updated_rects_);
return DECODE_DONE;
}
void DecoderVp8::GetUpdatedRects(RectVector* rects) {
rects->swap(updated_rects_);
}
void DecoderVp8::Reset() {
frame_ = NULL;
state_ = kUninitialized;
}
bool DecoderVp8::IsReadyForData() {
return state_ == kReady;
}
VideoPacketFormat::Encoding DecoderVp8::Encoding() {
return VideoPacketFormat::ENCODING_VP8;
}
void DecoderVp8::SetScaleRatios(double horizontal_ratio,
double vertical_ratio) {
// TODO(hclam): Ratio greater than 1.0 is not supported. This is
// because we need to reallocate the backing video frame and this
// is not implemented yet.
if (horizontal_ratio > 1.0 || horizontal_ratio <= 0.0 ||
vertical_ratio > 1.0 || vertical_ratio <= 0.0) {
return;
}
horizontal_scale_ratio_ = horizontal_ratio;
vertical_scale_ratio_ = vertical_ratio;
}
void DecoderVp8::SetClipRect(const SkIRect& clip_rect) {
clip_rect_ = clip_rect;
}
void DecoderVp8::RefreshRects(const RectVector& rects) {
if (!DoScaling())
ConvertRects(rects, &updated_rects_);
else
ScaleAndConvertRects(rects, &updated_rects_);
}
bool DecoderVp8::DoScaling() const {
return horizontal_scale_ratio_ != 1.0 || vertical_scale_ratio_ != 1.0;
}
void DecoderVp8::ConvertRects(const RectVector& rects,
RectVector* output_rects) {
if (!last_image_)
return;
uint8* data_start = frame_->data(media::VideoFrame::kRGBPlane);
const int stride = frame_->stride(media::VideoFrame::kRGBPlane);
output_rects->clear();
output_rects->reserve(rects.size());
for (size_t i = 0; i < rects.size(); ++i) {
// Clip by the clipping rectangle first.
SkIRect dest_rect = rects[i];
if (!dest_rect.intersect(clip_rect_))
continue;
// Round down the image width and height.
int image_width = RoundToTwosMultiple(last_image_->d_w);
int image_height = RoundToTwosMultiple(last_image_->d_h);
// Then clip by the rounded down dimension of the image for safety.
if (!dest_rect.intersect(SkIRect::MakeWH(image_width, image_height)))
continue;
// Align the rectangle to avoid artifacts in color space conversion.
dest_rect = AlignRect(dest_rect);
ConvertYUVToRGB32WithRect(last_image_->planes[0],
last_image_->planes[1],
last_image_->planes[2],
data_start,
dest_rect,
last_image_->stride[0],
last_image_->stride[1],
stride);
output_rects->push_back(dest_rect);
}
}
void DecoderVp8::ScaleAndConvertRects(const RectVector& rects,
RectVector* output_rects) {
if (!last_image_)
return;
uint8* data_start = frame_->data(media::VideoFrame::kRGBPlane);
const int stride = frame_->stride(media::VideoFrame::kRGBPlane);
output_rects->clear();
output_rects->reserve(rects.size());
for (size_t i = 0; i < rects.size(); ++i) {
// Round down the image width and height.
int image_width = RoundToTwosMultiple(last_image_->d_w);
int image_height = RoundToTwosMultiple(last_image_->d_h);
// Clip by the rounded down dimension of the image for safety.
SkIRect dest_rect = rects[i];
if (!dest_rect.intersect(SkIRect::MakeWH(image_width, image_height)))
continue;
// Align the rectangle to avoid artifacts in color space conversion.
dest_rect = AlignRect(dest_rect);
SkIRect scaled_rect = ScaleRect(dest_rect,
horizontal_scale_ratio_,
vertical_scale_ratio_);
ScaleYUVToRGB32WithRect(last_image_->planes[0],
last_image_->planes[1],
last_image_->planes[2],
data_start,
dest_rect,
scaled_rect,
last_image_->stride[0],
last_image_->stride[1],
stride);
output_rects->push_back(scaled_rect);
}
}
} // namespace remoting
<commit_msg>Initialize clip_rect_ member to be empty until explicitly set.<commit_after>// Copyright (c) 2011 The Chromium 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 "remoting/base/decoder_vp8.h"
#include "base/logging.h"
#include "media/base/media.h"
#include "media/base/yuv_convert.h"
#include "remoting/base/util.h"
extern "C" {
#define VPX_CODEC_DISABLE_COMPAT 1
#include "third_party/libvpx/libvpx.h"
}
namespace remoting {
DecoderVp8::DecoderVp8()
: state_(kUninitialized),
codec_(NULL),
last_image_(NULL),
clip_rect_(SkIRect::MakeEmpty()),
horizontal_scale_ratio_(1.0),
vertical_scale_ratio_(1.0) {
}
DecoderVp8::~DecoderVp8() {
if (codec_) {
vpx_codec_err_t ret = vpx_codec_destroy(codec_);
CHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec";
}
delete codec_;
}
void DecoderVp8::Initialize(scoped_refptr<media::VideoFrame> frame) {
DCHECK_EQ(kUninitialized, state_);
if (frame->format() != media::VideoFrame::RGB32) {
LOG(INFO) << "DecoderVp8 only supports RGB32 as output";
state_ = kError;
return;
}
frame_ = frame;
state_ = kReady;
}
Decoder::DecodeResult DecoderVp8::DecodePacket(const VideoPacket* packet) {
DCHECK_EQ(kReady, state_);
// Initialize the codec as needed.
if (!codec_) {
codec_ = new vpx_codec_ctx_t();
// TODO(hclam): Scale the number of threads with number of cores of the
// machine.
vpx_codec_dec_cfg config;
config.w = 0;
config.h = 0;
config.threads = 2;
vpx_codec_err_t ret =
vpx_codec_dec_init(
codec_, vpx_codec_vp8_dx(), &config, 0);
if (ret != VPX_CODEC_OK) {
LOG(INFO) << "Cannot initialize codec.";
delete codec_;
codec_ = NULL;
state_ = kError;
return DECODE_ERROR;
}
}
// Do the actual decoding.
vpx_codec_err_t ret = vpx_codec_decode(
codec_, reinterpret_cast<const uint8*>(packet->data().data()),
packet->data().size(), NULL, 0);
if (ret != VPX_CODEC_OK) {
LOG(INFO) << "Decoding failed:" << vpx_codec_err_to_string(ret) << "\n"
<< "Details: " << vpx_codec_error(codec_) << "\n"
<< vpx_codec_error_detail(codec_);
return DECODE_ERROR;
}
// Gets the decoded data.
vpx_codec_iter_t iter = NULL;
vpx_image_t* image = vpx_codec_get_frame(codec_, &iter);
if (!image) {
LOG(INFO) << "No video frame decoded";
return DECODE_ERROR;
}
last_image_ = image;
RectVector rects;
rects.reserve(packet->dirty_rects_size());
for (int i = 0; i < packet->dirty_rects_size(); ++i) {
Rect remoting_rect = packet->dirty_rects(i);
rects.push_back(SkIRect::MakeXYWH(remoting_rect.x(),
remoting_rect.y(),
remoting_rect.width(),
remoting_rect.height()));
}
if (!DoScaling())
ConvertRects(rects, &updated_rects_);
else
ScaleAndConvertRects(rects, &updated_rects_);
return DECODE_DONE;
}
void DecoderVp8::GetUpdatedRects(RectVector* rects) {
rects->swap(updated_rects_);
}
void DecoderVp8::Reset() {
frame_ = NULL;
state_ = kUninitialized;
}
bool DecoderVp8::IsReadyForData() {
return state_ == kReady;
}
VideoPacketFormat::Encoding DecoderVp8::Encoding() {
return VideoPacketFormat::ENCODING_VP8;
}
void DecoderVp8::SetScaleRatios(double horizontal_ratio,
double vertical_ratio) {
// TODO(hclam): Ratio greater than 1.0 is not supported. This is
// because we need to reallocate the backing video frame and this
// is not implemented yet.
if (horizontal_ratio > 1.0 || horizontal_ratio <= 0.0 ||
vertical_ratio > 1.0 || vertical_ratio <= 0.0) {
return;
}
horizontal_scale_ratio_ = horizontal_ratio;
vertical_scale_ratio_ = vertical_ratio;
}
void DecoderVp8::SetClipRect(const SkIRect& clip_rect) {
clip_rect_ = clip_rect;
}
void DecoderVp8::RefreshRects(const RectVector& rects) {
if (!DoScaling())
ConvertRects(rects, &updated_rects_);
else
ScaleAndConvertRects(rects, &updated_rects_);
}
bool DecoderVp8::DoScaling() const {
return horizontal_scale_ratio_ != 1.0 || vertical_scale_ratio_ != 1.0;
}
void DecoderVp8::ConvertRects(const RectVector& rects,
RectVector* output_rects) {
if (!last_image_)
return;
uint8* data_start = frame_->data(media::VideoFrame::kRGBPlane);
const int stride = frame_->stride(media::VideoFrame::kRGBPlane);
output_rects->clear();
output_rects->reserve(rects.size());
for (size_t i = 0; i < rects.size(); ++i) {
// Clip by the clipping rectangle first.
SkIRect dest_rect = rects[i];
if (!dest_rect.intersect(clip_rect_))
continue;
// Round down the image width and height.
int image_width = RoundToTwosMultiple(last_image_->d_w);
int image_height = RoundToTwosMultiple(last_image_->d_h);
// Then clip by the rounded down dimension of the image for safety.
if (!dest_rect.intersect(SkIRect::MakeWH(image_width, image_height)))
continue;
// Align the rectangle to avoid artifacts in color space conversion.
dest_rect = AlignRect(dest_rect);
ConvertYUVToRGB32WithRect(last_image_->planes[0],
last_image_->planes[1],
last_image_->planes[2],
data_start,
dest_rect,
last_image_->stride[0],
last_image_->stride[1],
stride);
output_rects->push_back(dest_rect);
}
}
void DecoderVp8::ScaleAndConvertRects(const RectVector& rects,
RectVector* output_rects) {
if (!last_image_)
return;
uint8* data_start = frame_->data(media::VideoFrame::kRGBPlane);
const int stride = frame_->stride(media::VideoFrame::kRGBPlane);
output_rects->clear();
output_rects->reserve(rects.size());
for (size_t i = 0; i < rects.size(); ++i) {
// Round down the image width and height.
int image_width = RoundToTwosMultiple(last_image_->d_w);
int image_height = RoundToTwosMultiple(last_image_->d_h);
// Clip by the rounded down dimension of the image for safety.
SkIRect dest_rect = rects[i];
if (!dest_rect.intersect(SkIRect::MakeWH(image_width, image_height)))
continue;
// Align the rectangle to avoid artifacts in color space conversion.
dest_rect = AlignRect(dest_rect);
SkIRect scaled_rect = ScaleRect(dest_rect,
horizontal_scale_ratio_,
vertical_scale_ratio_);
ScaleYUVToRGB32WithRect(last_image_->planes[0],
last_image_->planes[1],
last_image_->planes[2],
data_start,
dest_rect,
scaled_rect,
last_image_->stride[0],
last_image_->stride[1],
stride);
output_rects->push_back(scaled_rect);
}
}
} // namespace remoting
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow 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 "tensorflow/lite/kernels/internal/reference/quantize.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/reference/requantize.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/quantize.h"
#include "tensorflow/lite/micro/kernels/xtensa/xtensa.h"
#include "tensorflow/lite/micro/micro_utils.h"
namespace tflite {
namespace {
#if defined(HIFI4) || defined(HIFI4_INTERNAL) || defined(HIFI5)
TfLiteStatus EvalXtensa(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
auto* op_data = static_cast<OpDataQuantizeReference*>(node->user_data);
const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0);
TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, 0);
if (output->type == kTfLiteInt8 && input->type == kTfLiteInt16) {
#if defined(HIFI4) || defined(HIFI4_INTERNAL)
int size = ElementCount(*input->dims);
TF_LITE_ENSURE_EQ(
context,
xa_nn_elm_requantize_asym16s_asym8s(
tflite::micro::GetTensorData<int8_t>(output),
tflite::micro::GetTensorData<int16_t>(input),
op_data->input_zero_point, op_data->quantization_params.zero_point,
op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#elif defined(HIFI5)
int size = ElementCount(*input->dims);
TF_LITE_ENSURE_EQ(
context,
xa_nn_elm_requantize_asym16s_asym8s(
tflite::micro::GetTensorData<int8_t>(output),
tflite::micro::GetTensorData<int16_t>(input),
op_data->input_zero_point, op_data->quantization_params.zero_point,
op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#else
static_assert(false, "Unsupported xtensa architecture.");
#endif // defined(HIFI4) || defined (HIFI4_INTERNAL)
} else if (output->type == kTfLiteInt32 &&
(input->type == kTfLiteInt16 || input->type == kTfLiteInt8)) {
int size = ElementCount(*input->dims);
int32_t zero_point = op_data->quantization_params.zero_point;
if (input->type == kTfLiteInt16) {
#if defined(HIFI5)
int size = ElementCount(*input->dims);
TF_LITE_ENSURE_EQ(context,
xa_nn_elm_requantize_asym16s_asym32s(
tflite::micro::GetTensorData<int32_t>(output),
tflite::micro::GetTensorData<int16_t>(input),
op_data->input_zero_point,
op_data->quantization_params.zero_point,
op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#else
reference_ops::Requantize(tflite::micro::GetTensorData<int16_t>(input),
size, op_data->requantize_output_multiplier,
op_data->requantize_output_shift,
op_data->input_zero_point, zero_point,
tflite::micro::GetTensorData<int32_t>(output));
#endif // defined(HIFI5)
} else if (output->type == kTfLiteInt16 && input->type == kTfLiteInt32) {
reference_ops::Requantize(tflite::micro::GetTensorData<int32_t>(input),
size, op_data->requantize_output_multiplier,
op_data->requantize_output_shift,
op_data->input_zero_point, zero_point,
tflite::micro::GetTensorData<int16_t>(output));
} else {
#if defined(HIFI5)
const int8_t* input_data_ptr;
int32_t* output_data_ptr;
input_data_ptr = tflite::micro::GetTensorData<int8_t>(input);
output_data_ptr = tflite::micro::GetTensorData<int32_t>(output);
TF_LITE_ENSURE_EQ(
context,
xa_nn_elm_requantize_asym8s_asym32s(
output_data_ptr, input_data_ptr, op_data->input_zero_point,
zero_point, op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#else
reference_ops::Requantize(tflite::micro::GetTensorData<int8_t>(input),
size, op_data->requantize_output_multiplier,
op_data->requantize_output_shift,
op_data->input_zero_point, zero_point,
tflite::micro::GetTensorData<int32_t>(output));
#endif // defined(HIFI5)
}
} else {
TF_LITE_KERNEL_LOG(context, "Input %s, output %s not supported.",
TfLiteTypeGetName(input->type),
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
return kTfLiteOk;
}
#endif // defined(HIFI4) || defined (HIFI4_INTERNAL) || defined(HIFI5)
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
return context->AllocatePersistentBuffer(context,
sizeof(OpDataQuantizeReference));
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
TfLiteTensor* output = GetOutput(context, node, 0);
const TfLiteTensor* input = GetInput(context, node, 0);
auto* op_data = static_cast<OpDataQuantizeReference*>(node->user_data);
op_data->quantization_params.zero_point = output->params.zero_point;
op_data->quantization_params.scale =
static_cast<double>(output->params.scale);
op_data->input_zero_point = input->params.zero_point;
double effective_scale = static_cast<double>(input->params.scale) /
static_cast<double>(output->params.scale);
QuantizeMultiplier(effective_scale, &op_data->requantize_output_multiplier,
&op_data->requantize_output_shift);
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
#if defined(HIFI4) || defined(HIFI4_INTERNAL) || defined(HIFI5)
return EvalXtensa(context, node);
#else
return EvalQuantizeReference(context, node);
#endif // defined(HIFI4) || defined (HIFI4_INTERNAL) || defined(HIFI5)
}
} // namespace
TfLiteRegistration Register_QUANTIZE() {
return {/*init=*/Init,
/*free=*/nullptr,
/*prepare=*/Prepare,
/*invoke=*/Eval,
/*profiling_string=*/nullptr,
/*builtin_code=*/0,
/*custom_name=*/nullptr,
/*version=*/0};
}
} // namespace tflite
<commit_msg>Fix error in int32->int16 quantize on xtensa. (#816)<commit_after>/* Copyright 2021 The TensorFlow 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 "tensorflow/lite/kernels/internal/reference/quantize.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/reference/requantize.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/quantize.h"
#include "tensorflow/lite/micro/kernels/xtensa/xtensa.h"
#include "tensorflow/lite/micro/micro_utils.h"
namespace tflite {
namespace {
#if defined(HIFI4) || defined(HIFI4_INTERNAL) || defined(HIFI5)
TfLiteStatus EvalXtensa(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
auto* op_data = static_cast<OpDataQuantizeReference*>(node->user_data);
const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0);
TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, 0);
if (output->type == kTfLiteInt8 && input->type == kTfLiteInt16) {
#if defined(HIFI4) || defined(HIFI4_INTERNAL)
int size = ElementCount(*input->dims);
TF_LITE_ENSURE_EQ(
context,
xa_nn_elm_requantize_asym16s_asym8s(
tflite::micro::GetTensorData<int8_t>(output),
tflite::micro::GetTensorData<int16_t>(input),
op_data->input_zero_point, op_data->quantization_params.zero_point,
op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#elif defined(HIFI5)
int size = ElementCount(*input->dims);
TF_LITE_ENSURE_EQ(
context,
xa_nn_elm_requantize_asym16s_asym8s(
tflite::micro::GetTensorData<int8_t>(output),
tflite::micro::GetTensorData<int16_t>(input),
op_data->input_zero_point, op_data->quantization_params.zero_point,
op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#else
static_assert(false, "Unsupported xtensa architecture.");
#endif // defined(HIFI4) || defined (HIFI4_INTERNAL)
} else if (output->type == kTfLiteInt32 &&
(input->type == kTfLiteInt16 || input->type == kTfLiteInt8)) {
int size = ElementCount(*input->dims);
int32_t zero_point = op_data->quantization_params.zero_point;
if (input->type == kTfLiteInt16) {
#if defined(HIFI5)
int size = ElementCount(*input->dims);
TF_LITE_ENSURE_EQ(context,
xa_nn_elm_requantize_asym16s_asym32s(
tflite::micro::GetTensorData<int32_t>(output),
tflite::micro::GetTensorData<int16_t>(input),
op_data->input_zero_point,
op_data->quantization_params.zero_point,
op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#else
reference_ops::Requantize(tflite::micro::GetTensorData<int16_t>(input),
size, op_data->requantize_output_multiplier,
op_data->requantize_output_shift,
op_data->input_zero_point, zero_point,
tflite::micro::GetTensorData<int32_t>(output));
#endif // defined(HIFI5)
} else {
#if defined(HIFI5)
const int8_t* input_data_ptr;
int32_t* output_data_ptr;
input_data_ptr = tflite::micro::GetTensorData<int8_t>(input);
output_data_ptr = tflite::micro::GetTensorData<int32_t>(output);
TF_LITE_ENSURE_EQ(
context,
xa_nn_elm_requantize_asym8s_asym32s(
output_data_ptr, input_data_ptr, op_data->input_zero_point,
zero_point, op_data->requantize_output_shift,
op_data->requantize_output_multiplier, size),
0);
#else
reference_ops::Requantize(tflite::micro::GetTensorData<int8_t>(input),
size, op_data->requantize_output_multiplier,
op_data->requantize_output_shift,
op_data->input_zero_point, zero_point,
tflite::micro::GetTensorData<int32_t>(output));
#endif // defined(HIFI5)
}
} else if (output->type == kTfLiteInt16 && input->type == kTfLiteInt32) {
int size = ElementCount(*input->dims);
int32_t zero_point = op_data->quantization_params.zero_point;
reference_ops::Requantize(tflite::micro::GetTensorData<int32_t>(input),
size, op_data->requantize_output_multiplier,
op_data->requantize_output_shift,
op_data->input_zero_point, zero_point,
tflite::micro::GetTensorData<int16_t>(output));
} else {
TF_LITE_KERNEL_LOG(context, "Input %s, output %s not supported.",
TfLiteTypeGetName(input->type),
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
return kTfLiteOk;
}
#endif // defined(HIFI4) || defined (HIFI4_INTERNAL) || defined(HIFI5)
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
return context->AllocatePersistentBuffer(context,
sizeof(OpDataQuantizeReference));
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
TfLiteTensor* output = GetOutput(context, node, 0);
const TfLiteTensor* input = GetInput(context, node, 0);
auto* op_data = static_cast<OpDataQuantizeReference*>(node->user_data);
op_data->quantization_params.zero_point = output->params.zero_point;
op_data->quantization_params.scale =
static_cast<double>(output->params.scale);
op_data->input_zero_point = input->params.zero_point;
double effective_scale = static_cast<double>(input->params.scale) /
static_cast<double>(output->params.scale);
QuantizeMultiplier(effective_scale, &op_data->requantize_output_multiplier,
&op_data->requantize_output_shift);
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
#if defined(HIFI4) || defined(HIFI4_INTERNAL) || defined(HIFI5)
return EvalXtensa(context, node);
#else
return EvalQuantizeReference(context, node);
#endif // defined(HIFI4) || defined (HIFI4_INTERNAL) || defined(HIFI5)
}
} // namespace
TfLiteRegistration Register_QUANTIZE() {
return {/*init=*/Init,
/*free=*/nullptr,
/*prepare=*/Prepare,
/*invoke=*/Eval,
/*profiling_string=*/nullptr,
/*builtin_code=*/0,
/*custom_name=*/nullptr,
/*version=*/0};
}
} // namespace tflite
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCoordinate.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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 "vtkCoordinate.h"
#include "vtkViewport.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkCoordinate* vtkCoordinate::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCoordinate");
if(ret)
{
return (vtkCoordinate*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCoordinate;
}
#define VTK_RINT(x) ((x > 0.0) ? (int)(x + 0.5) : (int)(x - 0.5))
// Creates an Coordinate with the following defaults:
// value of 0, 0, 0 in world coordinates
vtkCoordinate::vtkCoordinate()
{
this->CoordinateSystem = VTK_WORLD;
this->Value[0] = 0.0;
this->Value[1] = 0.0;
this->Value[2] = 0.0;
this->Viewport = NULL;
this->ReferenceCoordinate = NULL;
this->Computing = 0;
}
// Destroy a Coordinate.
vtkCoordinate::~vtkCoordinate()
{
// To get rid of references (Refence counting).
this->SetReferenceCoordinate(NULL);
this->SetViewport(NULL);
}
const char *vtkCoordinate::GetCoordinateSystemAsString()
{
switch (this->CoordinateSystem)
{
case VTK_DISPLAY:
return "Display";
case VTK_NORMALIZED_DISPLAY:
return "Normalized Display";
case VTK_VIEWPORT:
return "Viewport";
case VTK_NORMALIZED_VIEWPORT:
return "Normalized Viewport";
case VTK_VIEW:
return "View";
case VTK_WORLD:
return "World";
default:
return "UNKNOWN!";
}
}
void vtkCoordinate::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkObject::PrintSelf(os,indent);
os << indent << "Coordinate System: " << this->GetCoordinateSystemAsString() << "\n";
os << indent << "Value: (" << this->Value[0] << ","
<< this->Value[1] << "," << this->Value[2] << ")\n";
os << indent << "ReferenceCoordinate: " << this->ReferenceCoordinate << "\n";
os << indent << "Viewport: " << this->Viewport << "\n";
}
void vtkCoordinate::SetViewport(vtkViewport *viewport)
{
if (this->Viewport != viewport)
{
if (this->Viewport != NULL)
{
this->Viewport->UnRegister(this);
}
this->Viewport = viewport;
if (this->Viewport != NULL)
{
this->Viewport->Register(this);
}
this->Modified();
}
}
float *vtkCoordinate::GetComputedWorldValue(vtkViewport* viewport)
{
float *val = this->ComputedWorldValue;
// prevent infinite loops
if (this->Computing)
{
return val;
}
this->Computing = 1;
val[0] = this->Value[0];
val[1] = this->Value[1];
val[2] = this->Value[2];
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
// if viewport is NULL then we can only do minimal calculations
if (!viewport)
{
if (this->CoordinateSystem == VTK_WORLD)
{
if (this->ReferenceCoordinate)
{
float *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedWorldValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
this->Computing = 0;
}
else
{
vtkErrorMacro("Attempt to compute world coordinates from another coordinate system without a viewport");
}
return val;
}
if (this->ReferenceCoordinate && this->CoordinateSystem != VTK_WORLD)
{
float RefValue[3];
int *ival;
ival = this->ReferenceCoordinate->GetComputedDisplayValue(viewport);
RefValue[0] = (float)(ival[0]);
RefValue[1] = (float)(ival[1]);
RefValue[2] = (float)(ival[2]);
// convert to current coordinate system
switch (this->CoordinateSystem)
{
case VTK_NORMALIZED_DISPLAY:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
break;
case VTK_VIEWPORT:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
viewport->NormalizedDisplayToViewport(RefValue[0],RefValue[1]);
break;
case VTK_NORMALIZED_VIEWPORT:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
viewport->NormalizedDisplayToViewport(RefValue[0],RefValue[1]);
viewport->ViewportToNormalizedViewport(RefValue[0],RefValue[1]);
break;
case VTK_VIEW:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
viewport->NormalizedDisplayToViewport(RefValue[0],RefValue[1]);
viewport->ViewportToNormalizedViewport(RefValue[0],RefValue[1]);
viewport->NormalizedViewportToView(RefValue[0],RefValue[1],RefValue[2]);
break;
}
// add to current value
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
// compute our WC
switch (this->CoordinateSystem)
{
case VTK_DISPLAY:
viewport->DisplayToNormalizedDisplay(val[0],val[1]);
case VTK_NORMALIZED_DISPLAY:
viewport->NormalizedDisplayToViewport(val[0],val[1]);
case VTK_VIEWPORT:
viewport->ViewportToNormalizedViewport(val[0],val[1]);
case VTK_NORMALIZED_VIEWPORT:
viewport->NormalizedViewportToView(val[0],val[1],val[2]);
case VTK_VIEW:
viewport->ViewToWorld(val[0],val[1],val[2]);
}
if (this->ReferenceCoordinate && this->CoordinateSystem == VTK_WORLD)
{
float *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedWorldValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
this->Computing = 0;
vtkDebugMacro("Returning WorldValue of : " <<
this->ComputedWorldValue[0] << " , " <<
this->ComputedWorldValue[1] << " , " <<
this->ComputedWorldValue[2]);
return val;
}
int *vtkCoordinate::GetComputedViewportValue(vtkViewport* viewport)
{
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
int *d = this->GetComputedDisplayValue(viewport);
if (!viewport)
{
vtkDebugMacro("Attempt to convert to compute viewport coordinates without a viewport, results may not be valid");
return this->ComputedDisplayValue;
}
float f[2];
f[0] = (float)d[0];
f[1] = (float)d[1];
viewport->DisplayToNormalizedDisplay(f[0],f[1]);
viewport->NormalizedDisplayToViewport(f[0],f[1]);
this->ComputedViewportValue[0] = (int)VTK_RINT(f[0]);
this->ComputedViewportValue[1] = (int)VTK_RINT(f[1]);
return this->ComputedViewportValue;
}
int *vtkCoordinate::GetComputedLocalDisplayValue(vtkViewport* viewport)
{
float a[2];
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
this->GetComputedDisplayValue(viewport);
if (!viewport)
{
vtkErrorMacro("Attempt to convert to local display coordinates without a viewport");
return this->ComputedDisplayValue;
}
a[0] = (float)this->ComputedDisplayValue[0];
a[1] = (float)this->ComputedDisplayValue[1];
viewport->DisplayToLocalDisplay(a[0],a[1]);
this->ComputedDisplayValue[0] = (int)VTK_RINT(a[0]);
this->ComputedDisplayValue[1] = (int)VTK_RINT(a[1]);
vtkDebugMacro("Returning LocalDisplayValue of : " <<
this->ComputedDisplayValue[0] << " , " <<
this->ComputedDisplayValue[1]);
return this->ComputedDisplayValue;
}
int *vtkCoordinate::GetComputedDisplayValue(vtkViewport* viewport)
{
float val[3];
// prevent infinite loops
if (this->Computing)
{
return this->ComputedDisplayValue;
}
this->Computing = 1;
val[0] = this->Value[0];
val[1] = this->Value[1];
val[2] = this->Value[2];
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
// if viewport is NULL, there is very little we can do
if (viewport == NULL)
{
// for DISPLAY and VIEWPORT just use the value
if (this->CoordinateSystem == VTK_DISPLAY)
{
this->ComputedDisplayValue[0] = (int)VTK_RINT(val[0]);
this->ComputedDisplayValue[1] = (int)VTK_RINT(val[1]);
if (this->ReferenceCoordinate)
{
int *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedDisplayValue(viewport);
this->ComputedDisplayValue[0] += RefValue[0];
this->ComputedDisplayValue[1] += RefValue[1];
}
}
else
{
vtkErrorMacro("Request for coordinate transformation without required viewport");
}
return this->ComputedDisplayValue;
}
// compute our DC
switch (this->CoordinateSystem)
{
case VTK_WORLD:
if (this->ReferenceCoordinate)
{
float *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedWorldValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
viewport->WorldToView(val[0],val[1],val[2]);
case VTK_VIEW:
viewport->ViewToNormalizedViewport(val[0],val[1],val[2]);
case VTK_NORMALIZED_VIEWPORT:
viewport->NormalizedViewportToViewport(val[0],val[1]);
case VTK_VIEWPORT:
if ((this->CoordinateSystem == VTK_NORMALIZED_VIEWPORT ||
this->CoordinateSystem == VTK_VIEWPORT) &&
this->ReferenceCoordinate)
{
int *RefValue;
RefValue =
this->ReferenceCoordinate->GetComputedViewportValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
}
viewport->ViewportToNormalizedDisplay(val[0],val[1]);
case VTK_NORMALIZED_DISPLAY:
viewport->NormalizedDisplayToDisplay(val[0],val[1]);
}
this->ComputedDisplayValue[0] = (int)VTK_RINT(val[0]);
this->ComputedDisplayValue[1] = (int)VTK_RINT(val[1]);
// if we have a reference coordinate and we haven't handled it yet
if (this->ReferenceCoordinate &&
(this->CoordinateSystem == VTK_DISPLAY ||
this->CoordinateSystem == VTK_NORMALIZED_DISPLAY))
{
int *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedDisplayValue(viewport);
this->ComputedDisplayValue[0] += RefValue[0];
this->ComputedDisplayValue[1] += RefValue[1];
}
this->Computing = 0;
vtkDebugMacro("Returning DisplayValue of : " <<
this->ComputedDisplayValue[0] << " , " <<
this->ComputedDisplayValue[1]);
return this->ComputedDisplayValue;
}
float *vtkCoordinate::GetComputedValue(vtkViewport* viewport)
{
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
switch (this->CoordinateSystem)
{
case VTK_WORLD:
return this->GetComputedWorldValue(viewport);
case VTK_VIEW:
case VTK_NORMALIZED_VIEWPORT:
case VTK_VIEWPORT:
{
// result stored in computed world value due to float
// but is really a viewport value
int *v = this->GetComputedViewportValue(viewport);
this->ComputedWorldValue[0] = v[0];
this->ComputedWorldValue[1] = v[1];
break;
}
case VTK_NORMALIZED_DISPLAY:
case VTK_DISPLAY:
{
// result stored in computed world value due to float
// but is really a display value
int *d = this->GetComputedDisplayValue(viewport);
this->ComputedWorldValue[0] = d[0];
this->ComputedWorldValue[1] = d[1];
break;
}
}
return this->ComputedWorldValue;
}
<commit_msg>ERR: uninitialied memory read.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCoordinate.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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 "vtkCoordinate.h"
#include "vtkViewport.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkCoordinate* vtkCoordinate::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCoordinate");
if(ret)
{
return (vtkCoordinate*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCoordinate;
}
#define VTK_RINT(x) ((x > 0.0) ? (int)(x + 0.5) : (int)(x - 0.5))
// Creates an Coordinate with the following defaults:
// value of 0, 0, 0 in world coordinates
vtkCoordinate::vtkCoordinate()
{
this->CoordinateSystem = VTK_WORLD;
this->Value[0] = 0.0;
this->Value[1] = 0.0;
this->Value[2] = 0.0;
this->Viewport = NULL;
this->ReferenceCoordinate = NULL;
this->Computing = 0;
}
// Destroy a Coordinate.
vtkCoordinate::~vtkCoordinate()
{
// To get rid of references (Refence counting).
this->SetReferenceCoordinate(NULL);
this->SetViewport(NULL);
}
const char *vtkCoordinate::GetCoordinateSystemAsString()
{
switch (this->CoordinateSystem)
{
case VTK_DISPLAY:
return "Display";
case VTK_NORMALIZED_DISPLAY:
return "Normalized Display";
case VTK_VIEWPORT:
return "Viewport";
case VTK_NORMALIZED_VIEWPORT:
return "Normalized Viewport";
case VTK_VIEW:
return "View";
case VTK_WORLD:
return "World";
default:
return "UNKNOWN!";
}
}
void vtkCoordinate::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkObject::PrintSelf(os,indent);
os << indent << "Coordinate System: " << this->GetCoordinateSystemAsString() << "\n";
os << indent << "Value: (" << this->Value[0] << ","
<< this->Value[1] << "," << this->Value[2] << ")\n";
os << indent << "ReferenceCoordinate: " << this->ReferenceCoordinate << "\n";
os << indent << "Viewport: " << this->Viewport << "\n";
}
void vtkCoordinate::SetViewport(vtkViewport *viewport)
{
if (this->Viewport != viewport)
{
if (this->Viewport != NULL)
{
this->Viewport->UnRegister(this);
}
this->Viewport = viewport;
if (this->Viewport != NULL)
{
this->Viewport->Register(this);
}
this->Modified();
}
}
float *vtkCoordinate::GetComputedWorldValue(vtkViewport* viewport)
{
float *val = this->ComputedWorldValue;
// prevent infinite loops
if (this->Computing)
{
return val;
}
this->Computing = 1;
val[0] = this->Value[0];
val[1] = this->Value[1];
val[2] = this->Value[2];
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
// if viewport is NULL then we can only do minimal calculations
if (!viewport)
{
if (this->CoordinateSystem == VTK_WORLD)
{
if (this->ReferenceCoordinate)
{
float *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedWorldValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
this->Computing = 0;
}
else
{
vtkErrorMacro("Attempt to compute world coordinates from another coordinate system without a viewport");
}
return val;
}
if (this->ReferenceCoordinate && this->CoordinateSystem != VTK_WORLD)
{
float RefValue[3];
int *ival;
ival = this->ReferenceCoordinate->GetComputedDisplayValue(viewport);
RefValue[0] = (float)(ival[0]);
RefValue[1] = (float)(ival[1]);
RefValue[2] = 0.0;
// convert to current coordinate system
switch (this->CoordinateSystem)
{
case VTK_NORMALIZED_DISPLAY:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
break;
case VTK_VIEWPORT:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
viewport->NormalizedDisplayToViewport(RefValue[0],RefValue[1]);
break;
case VTK_NORMALIZED_VIEWPORT:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
viewport->NormalizedDisplayToViewport(RefValue[0],RefValue[1]);
viewport->ViewportToNormalizedViewport(RefValue[0],RefValue[1]);
break;
case VTK_VIEW:
viewport->DisplayToNormalizedDisplay(RefValue[0],RefValue[1]);
viewport->NormalizedDisplayToViewport(RefValue[0],RefValue[1]);
viewport->ViewportToNormalizedViewport(RefValue[0],RefValue[1]);
viewport->NormalizedViewportToView(RefValue[0],RefValue[1],RefValue[2]);
break;
}
// add to current value
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
// compute our WC
switch (this->CoordinateSystem)
{
case VTK_DISPLAY:
viewport->DisplayToNormalizedDisplay(val[0],val[1]);
case VTK_NORMALIZED_DISPLAY:
viewport->NormalizedDisplayToViewport(val[0],val[1]);
case VTK_VIEWPORT:
viewport->ViewportToNormalizedViewport(val[0],val[1]);
case VTK_NORMALIZED_VIEWPORT:
viewport->NormalizedViewportToView(val[0],val[1],val[2]);
case VTK_VIEW:
viewport->ViewToWorld(val[0],val[1],val[2]);
}
if (this->ReferenceCoordinate && this->CoordinateSystem == VTK_WORLD)
{
float *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedWorldValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
this->Computing = 0;
vtkDebugMacro("Returning WorldValue of : " <<
this->ComputedWorldValue[0] << " , " <<
this->ComputedWorldValue[1] << " , " <<
this->ComputedWorldValue[2]);
return val;
}
int *vtkCoordinate::GetComputedViewportValue(vtkViewport* viewport)
{
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
int *d = this->GetComputedDisplayValue(viewport);
if (!viewport)
{
vtkDebugMacro("Attempt to convert to compute viewport coordinates without a viewport, results may not be valid");
return this->ComputedDisplayValue;
}
float f[2];
f[0] = (float)d[0];
f[1] = (float)d[1];
viewport->DisplayToNormalizedDisplay(f[0],f[1]);
viewport->NormalizedDisplayToViewport(f[0],f[1]);
this->ComputedViewportValue[0] = (int)VTK_RINT(f[0]);
this->ComputedViewportValue[1] = (int)VTK_RINT(f[1]);
return this->ComputedViewportValue;
}
int *vtkCoordinate::GetComputedLocalDisplayValue(vtkViewport* viewport)
{
float a[2];
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
this->GetComputedDisplayValue(viewport);
if (!viewport)
{
vtkErrorMacro("Attempt to convert to local display coordinates without a viewport");
return this->ComputedDisplayValue;
}
a[0] = (float)this->ComputedDisplayValue[0];
a[1] = (float)this->ComputedDisplayValue[1];
viewport->DisplayToLocalDisplay(a[0],a[1]);
this->ComputedDisplayValue[0] = (int)VTK_RINT(a[0]);
this->ComputedDisplayValue[1] = (int)VTK_RINT(a[1]);
vtkDebugMacro("Returning LocalDisplayValue of : " <<
this->ComputedDisplayValue[0] << " , " <<
this->ComputedDisplayValue[1]);
return this->ComputedDisplayValue;
}
int *vtkCoordinate::GetComputedDisplayValue(vtkViewport* viewport)
{
float val[3];
// prevent infinite loops
if (this->Computing)
{
return this->ComputedDisplayValue;
}
this->Computing = 1;
val[0] = this->Value[0];
val[1] = this->Value[1];
val[2] = this->Value[2];
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
// if viewport is NULL, there is very little we can do
if (viewport == NULL)
{
// for DISPLAY and VIEWPORT just use the value
if (this->CoordinateSystem == VTK_DISPLAY)
{
this->ComputedDisplayValue[0] = (int)VTK_RINT(val[0]);
this->ComputedDisplayValue[1] = (int)VTK_RINT(val[1]);
if (this->ReferenceCoordinate)
{
int *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedDisplayValue(viewport);
this->ComputedDisplayValue[0] += RefValue[0];
this->ComputedDisplayValue[1] += RefValue[1];
}
}
else
{
vtkErrorMacro("Request for coordinate transformation without required viewport");
}
return this->ComputedDisplayValue;
}
// compute our DC
switch (this->CoordinateSystem)
{
case VTK_WORLD:
if (this->ReferenceCoordinate)
{
float *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedWorldValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
val[2] += RefValue[2];
}
viewport->WorldToView(val[0],val[1],val[2]);
case VTK_VIEW:
viewport->ViewToNormalizedViewport(val[0],val[1],val[2]);
case VTK_NORMALIZED_VIEWPORT:
viewport->NormalizedViewportToViewport(val[0],val[1]);
case VTK_VIEWPORT:
if ((this->CoordinateSystem == VTK_NORMALIZED_VIEWPORT ||
this->CoordinateSystem == VTK_VIEWPORT) &&
this->ReferenceCoordinate)
{
int *RefValue;
RefValue =
this->ReferenceCoordinate->GetComputedViewportValue(viewport);
val[0] += RefValue[0];
val[1] += RefValue[1];
}
viewport->ViewportToNormalizedDisplay(val[0],val[1]);
case VTK_NORMALIZED_DISPLAY:
viewport->NormalizedDisplayToDisplay(val[0],val[1]);
}
this->ComputedDisplayValue[0] = (int)VTK_RINT(val[0]);
this->ComputedDisplayValue[1] = (int)VTK_RINT(val[1]);
// if we have a reference coordinate and we haven't handled it yet
if (this->ReferenceCoordinate &&
(this->CoordinateSystem == VTK_DISPLAY ||
this->CoordinateSystem == VTK_NORMALIZED_DISPLAY))
{
int *RefValue;
RefValue = this->ReferenceCoordinate->GetComputedDisplayValue(viewport);
this->ComputedDisplayValue[0] += RefValue[0];
this->ComputedDisplayValue[1] += RefValue[1];
}
this->Computing = 0;
vtkDebugMacro("Returning DisplayValue of : " <<
this->ComputedDisplayValue[0] << " , " <<
this->ComputedDisplayValue[1]);
return this->ComputedDisplayValue;
}
float *vtkCoordinate::GetComputedValue(vtkViewport* viewport)
{
// use our viewport if set
if (this->Viewport)
{
viewport = this->Viewport;
}
switch (this->CoordinateSystem)
{
case VTK_WORLD:
return this->GetComputedWorldValue(viewport);
case VTK_VIEW:
case VTK_NORMALIZED_VIEWPORT:
case VTK_VIEWPORT:
{
// result stored in computed world value due to float
// but is really a viewport value
int *v = this->GetComputedViewportValue(viewport);
this->ComputedWorldValue[0] = v[0];
this->ComputedWorldValue[1] = v[1];
break;
}
case VTK_NORMALIZED_DISPLAY:
case VTK_DISPLAY:
{
// result stored in computed world value due to float
// but is really a display value
int *d = this->GetComputedDisplayValue(viewport);
this->ComputedWorldValue[0] = d[0];
this->ComputedWorldValue[1] = d[1];
break;
}
}
return this->ComputedWorldValue;
}
<|endoftext|>
|
<commit_before><commit_msg>Reverted workaround that disables events in JIT compilation because it makes CompiledMethodLoad event disabled and makes some tests to pass. This bug should be fixed in a different way, possibly with an implementation of lazy resolution on x86_64.<commit_after><|endoftext|>
|
<commit_before>/*
* Handling of virtual-to-phisycal memory translation.
* Copyright, Svilen Kanev, 2014
*/
#include <stdio.h>
#include <cstdlib>
#include <unordered_map>
#include "host.h"
#include "misc.h"
#include "machine.h"
#include "options.h"
#include "stats.h"
#include "memory.h"
#include "synchronization.h"
/* VPN to PPN hash map. Note: these are page numbers, not addresses. */
typedef std::unordered_map<md_addr_t, md_paddr_t> page_table_t;
static int num_address_spaces;
static page_table_t * page_tables;
static md_addr_t * brk_point;
static counter_t * page_count;
static counter_t phys_page_count;
void mem_init(int num_processes)
{
num_address_spaces = num_processes;
page_tables = new page_table_t[num_processes];
page_count = new counter_t[num_processes];
brk_point = new md_addr_t[num_processes];
}
/* We allocate physical pages to virtual pages on a
* first-come-first-serve basis. Seems like linux frowns upon
* page coloring, so should be reasonably accurate. */
static md_paddr_t next_ppn_to_allocate = 0x00000100; /* arbitrary starting point; */
void mem_newmap(int asid, md_addr_t addr, size_t length)
{
ZPIN_TRACE(INVALID_CORE, "mem_newmap: %d, %x, length: %x\n", asid, addr, length);
assert(addr != 0); // Mapping 0-th page might cause hell to break loose, don't do it.
/* Check alignment */
if (MEM_OFFSET(addr)) {
fprintf(stderr, "mem_newmap: Address %x not aligned\n", addr);
abort();
}
/* Add every page in the range to page table */
md_addr_t last_addr = ROUND_UP(addr + length, PAGE_SIZE);
for (md_addr_t curr_addr = addr; (curr_addr <= last_addr) && curr_addr; curr_addr += PAGE_SIZE) {
if (mem_is_mapped(asid, curr_addr))
continue; /* Attempting to double-map is ok */
md_addr_t curr_vpn = curr_addr >> PAGE_SHIFT;
page_tables[asid][curr_vpn] = next_ppn_to_allocate;
next_ppn_to_allocate++;
page_count[asid]++;
phys_page_count++;
}
}
void mem_delmap(int asid, md_addr_t addr, size_t length)
{
ZPIN_TRACE(INVALID_CORE, "mem_delmap: %d, %x, length: %x\n", asid, addr, length);
/* Check alignment */
if (MEM_OFFSET(addr)) {
fprintf(stderr, "mem_delmap: Address %x not aligned\n", addr);
abort();
}
/* Remove every page in the range from page table */
md_addr_t last_addr = ROUND_UP(addr + length, PAGE_SIZE);
for (md_addr_t curr_addr = addr; (curr_addr <= last_addr) && curr_addr; curr_addr += PAGE_SIZE) {
if (!mem_is_mapped(asid, curr_addr))
continue; /* Attempting to remove something missing is ok */
md_addr_t curr_vpn = curr_addr >> PAGE_SHIFT;
page_tables[asid].erase(curr_vpn);
page_count[asid]--;
phys_page_count--;
}
}
/* Check if page has been touched in this address space */
bool mem_is_mapped(int asid, md_addr_t addr)
{
md_addr_t vpn = addr >> PAGE_SHIFT;
return (page_tables[asid].count(vpn) > 0);
}
md_paddr_t v2p_translate(int asid, md_addr_t addr)
{
/* Page is mapped, just look it up */
if (mem_is_mapped(asid, addr)) {
md_addr_t vpn = addr >> PAGE_SHIFT;
return (page_tables[asid][vpn] << PAGE_SHIFT) + MEM_OFFSET(addr);
}
/* Else, return zeroth page and someone in higher layers will
* complain if necessary */
return 0 + MEM_OFFSET(addr);
}
/* Wrapper around v2p_translate, to be called without holding the memory_lock */
md_paddr_t v2p_translate_safe(int asid, md_addr_t virt_addr)
{
md_paddr_t res;
lk_lock(&memory_lock, 1);
res = v2p_translate(asid, virt_addr);
lk_unlock(&memory_lock);
return res;
}
/* Get top of data segment */
md_addr_t mem_brk(int asid)
{
return brk_point[asid];
}
/* Update top of data segment */
void mem_update_brk(int asid, md_addr_t brk_)
{
brk_point[asid] = brk_;
}
/* register memory system-specific statistics */
void mem_reg_stats(struct stat_sdb_t *sdb)
{
char buf[512];
stat_reg_note(sdb,"\n#### SIMULATED MEMORY STATS ####");
stat_reg_counter(sdb, TRUE, "core_page_count", "total number of physical pages allocated",
&phys_page_count, 0, FALSE, NULL);
for (int i=0; i<num_address_spaces; i++) {
sprintf(buf, "prog_%d.page_count", i);
stat_reg_counter(sdb, TRUE, buf, "total number of pages allocated",
(page_count + i), 0, FALSE, NULL);
}
}
<commit_msg>Check for valid address space id in v2p.<commit_after>/*
* Handling of virtual-to-phisycal memory translation.
* Copyright, Svilen Kanev, 2014
*/
#include <stdio.h>
#include <cstdlib>
#include <unordered_map>
#include "host.h"
#include "misc.h"
#include "machine.h"
#include "options.h"
#include "stats.h"
#include "memory.h"
#include "synchronization.h"
/* VPN to PPN hash map. Note: these are page numbers, not addresses. */
typedef std::unordered_map<md_addr_t, md_paddr_t> page_table_t;
static int num_address_spaces;
static page_table_t * page_tables;
static md_addr_t * brk_point;
static counter_t * page_count;
static counter_t phys_page_count;
void mem_init(int num_processes)
{
num_address_spaces = num_processes;
page_tables = new page_table_t[num_processes];
page_count = new counter_t[num_processes];
brk_point = new md_addr_t[num_processes];
}
/* We allocate physical pages to virtual pages on a
* first-come-first-serve basis. Seems like linux frowns upon
* page coloring, so should be reasonably accurate. */
static md_paddr_t next_ppn_to_allocate = 0x00000100; /* arbitrary starting point; */
void mem_newmap(int asid, md_addr_t addr, size_t length)
{
ZPIN_TRACE(INVALID_CORE, "mem_newmap: %d, %x, length: %x\n", asid, addr, length);
assert(asid >= 0 && asid < num_address_spaces);
assert(addr != 0); // Mapping 0-th page might cause hell to break loose, don't do it.
/* Check alignment */
if (MEM_OFFSET(addr)) {
fprintf(stderr, "mem_newmap: Address %x not aligned\n", addr);
abort();
}
/* Add every page in the range to page table */
md_addr_t last_addr = ROUND_UP(addr + length, PAGE_SIZE);
for (md_addr_t curr_addr = addr; (curr_addr <= last_addr) && curr_addr; curr_addr += PAGE_SIZE) {
if (mem_is_mapped(asid, curr_addr))
continue; /* Attempting to double-map is ok */
md_addr_t curr_vpn = curr_addr >> PAGE_SHIFT;
page_tables[asid][curr_vpn] = next_ppn_to_allocate;
next_ppn_to_allocate++;
page_count[asid]++;
phys_page_count++;
}
}
void mem_delmap(int asid, md_addr_t addr, size_t length)
{
ZPIN_TRACE(INVALID_CORE, "mem_delmap: %d, %x, length: %x\n", asid, addr, length);
assert(asid >= 0 && asid < num_address_spaces);
/* Check alignment */
if (MEM_OFFSET(addr)) {
fprintf(stderr, "mem_delmap: Address %x not aligned\n", addr);
abort();
}
/* Remove every page in the range from page table */
md_addr_t last_addr = ROUND_UP(addr + length, PAGE_SIZE);
for (md_addr_t curr_addr = addr; (curr_addr <= last_addr) && curr_addr; curr_addr += PAGE_SIZE) {
if (!mem_is_mapped(asid, curr_addr))
continue; /* Attempting to remove something missing is ok */
md_addr_t curr_vpn = curr_addr >> PAGE_SHIFT;
page_tables[asid].erase(curr_vpn);
page_count[asid]--;
phys_page_count--;
}
}
/* Check if page has been touched in this address space */
bool mem_is_mapped(int asid, md_addr_t addr)
{
assert(asid >= 0 && asid < num_address_spaces);
md_addr_t vpn = addr >> PAGE_SHIFT;
return (page_tables[asid].count(vpn) > 0);
}
md_paddr_t v2p_translate(int asid, md_addr_t addr)
{
assert(asid >= 0 && asid < num_address_spaces);
/* Page is mapped, just look it up */
if (mem_is_mapped(asid, addr)) {
md_addr_t vpn = addr >> PAGE_SHIFT;
return (page_tables[asid][vpn] << PAGE_SHIFT) + MEM_OFFSET(addr);
}
/* Else, return zeroth page and someone in higher layers will
* complain if necessary */
return 0 + MEM_OFFSET(addr);
}
/* Wrapper around v2p_translate, to be called without holding the memory_lock */
md_paddr_t v2p_translate_safe(int asid, md_addr_t virt_addr)
{
md_paddr_t res;
lk_lock(&memory_lock, 1);
res = v2p_translate(asid, virt_addr);
lk_unlock(&memory_lock);
return res;
}
/* Get top of data segment */
md_addr_t mem_brk(int asid)
{
assert(asid >= 0 && asid < num_address_spaces);
return brk_point[asid];
}
/* Update top of data segment */
void mem_update_brk(int asid, md_addr_t brk_)
{
assert(asid >= 0 && asid < num_address_spaces);
brk_point[asid] = brk_;
}
/* register memory system-specific statistics */
void mem_reg_stats(struct stat_sdb_t *sdb)
{
char buf[512];
stat_reg_note(sdb,"\n#### SIMULATED MEMORY STATS ####");
stat_reg_counter(sdb, TRUE, "core_page_count", "total number of physical pages allocated",
&phys_page_count, 0, FALSE, NULL);
for (int i=0; i<num_address_spaces; i++) {
sprintf(buf, "prog_%d.page_count", i);
stat_reg_counter(sdb, TRUE, buf, "total number of pages allocated",
(page_count + i), 0, FALSE, NULL);
}
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/platform/device_context.h"
#include <set>
#include <string>
#include <unordered_set>
#include <vector>
#include "paddle/fluid/memory/memory.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/framework/rw_lock.h"
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif
namespace paddle {
namespace platform {
DeviceContextPool* DeviceContextPool::pool = nullptr;
platform::DeviceContext* DeviceContextPool::Get(const platform::Place& place) {
auto it = device_contexts_.find(place);
if (it == device_contexts_.end()) {
PADDLE_THROW(
"'Place' is not supported, Please re-compile with WITH_GPU "
"option");
}
return it->second.get().get();
}
template <typename DevCtx, typename PlaceType>
inline void EmplaceDeviceContext(
std::map<Place, std::shared_future<std::unique_ptr<DeviceContext>>>*
map_ptr,
platform::Place p) {
using PtrType = std::unique_ptr<DeviceContext>;
map_ptr->emplace(p, std::async(std::launch::deferred, [=] {
// lazy evaluation. i.e., only create device context at
// first `Get`
return PtrType(new DevCtx(boost::get<PlaceType>(p)));
}));
}
DeviceContextPool::DeviceContextPool(
const std::vector<platform::Place>& places) {
PADDLE_ENFORCE_GT(places.size(), 0);
std::set<Place> set;
for (auto& p : places) {
set.insert(p);
}
for (auto& p : set) {
if (platform::is_cpu_place(p)) {
#ifdef PADDLE_WITH_MKLDNN
EmplaceDeviceContext<MKLDNNDeviceContext, CPUPlace>(&device_contexts_, p);
#else
EmplaceDeviceContext<CPUDeviceContext, CPUPlace>(&device_contexts_, p);
#endif
} else if (platform::is_gpu_place(p)) {
#ifdef PADDLE_WITH_CUDA
EmplaceDeviceContext<CUDADeviceContext, CUDAPlace>(&device_contexts_, p);
#else
PADDLE_THROW(
"'CUDAPlace' is not supported, Please re-compile with WITH_GPU "
"option");
#endif
} else if (platform::is_cuda_pinned_place(p)) {
#ifdef PADDLE_WITH_CUDA
EmplaceDeviceContext<CUDAPinnedDeviceContext, CUDAPinnedPlace>(
&device_contexts_, p);
#else
PADDLE_THROW(
"'CUDAPlace' is not supported, Please re-compile with WITH_GPU "
"option");
#endif
}
}
}
CPUDeviceContext::CPUDeviceContext() {
eigen_device_.reset(new Eigen::DefaultDevice());
}
CPUDeviceContext::CPUDeviceContext(CPUPlace place) : place_(place) {
eigen_device_.reset(new Eigen::DefaultDevice());
}
Eigen::DefaultDevice* CPUDeviceContext::eigen_device() const {
return eigen_device_.get();
}
Place CPUDeviceContext::GetPlace() const { return place_; }
#ifdef PADDLE_WITH_CUDA
class EigenCudaStreamDevice : public Eigen::StreamInterface {
public:
EigenCudaStreamDevice() : scratch_(nullptr), semaphore_(nullptr) {
Eigen::initializeDeviceProp();
}
~EigenCudaStreamDevice() override {}
void Reinitialize(const cudaStream_t* cuda_stream, CUDAPlace place) {
stream_ = cuda_stream;
place_ = place;
device_prop_ = &Eigen::m_deviceProperties[place.device];
}
const cudaStream_t& stream() const override { return *stream_; }
const cudaDeviceProp& deviceProperties() const override {
return *device_prop_;
}
void* allocate(size_t num_bytes) const override {
auto buf = paddle::memory::Alloc(place_, num_bytes,
memory::Allocator::kScratchpad);
void* retv = buf->ptr();
allocations_[buf->ptr()] = std::move(buf);
return retv;
}
void deallocate(void* buffer) const override {
allocations_.erase(allocations_.find(buffer));
}
void* scratchpad() const override {
if (scratch_ == NULL) {
scratch_ = allocate(Eigen::kCudaScratchSize + sizeof(unsigned int));
}
return scratch_;
}
unsigned int* semaphore() const override {
if (semaphore_ == NULL) {
char* scratch =
static_cast<char*>(scratchpad()) + Eigen::kCudaScratchSize;
semaphore_ = reinterpret_cast<unsigned int*>(scratch);
PADDLE_ENFORCE(
cudaMemsetAsync(semaphore_, 0, sizeof(unsigned int), *stream_));
}
return semaphore_;
}
private:
CUDAPlace place_;
const cudaStream_t* stream_; // not owned;
const cudaDeviceProp* device_prop_; // not owned;
mutable void* scratch_;
mutable unsigned int* semaphore_;
mutable std::unordered_map<void*, memory::AllocationPtr> allocations_;
};
CudnnHolder::CudnnHolder(const cudaStream_t* stream, const CUDAPlace& place)
: workspace_(nullptr), stream_(stream), place_(place) {
PADDLE_ENFORCE(dynload::cudnnCreate(&cudnn_handle_));
PADDLE_ENFORCE(dynload::cudnnSetStream(cudnn_handle_, *stream_));
}
CudnnHolder::~CudnnHolder() {
PADDLE_ENFORCE(dynload::cudnnDestroy(cudnn_handle_));
}
void CudnnHolder::ReallocateWorkspace(size_t required_workspace_len) {
if (required_workspace_len <= WorkspaceSize()) {
return;
}
if (workspace_ != nullptr) {
// Maybe someone is using the current workspace
PADDLE_ENFORCE(cudaStreamSynchronize(*stream_));
workspace_.reset();
}
workspace_ = paddle::memory::Alloc(place_, required_workspace_len,
paddle::memory::Allocator::kScratchpad);
}
CUDADeviceContext::CUDADeviceContext(CUDAPlace place)
: place_(place), cudnn_holder_(nullptr) {
CUDADeviceGuard guard(place_.device);
compute_capability_ = GetCUDAComputeCapability(place_.device);
multi_process_ = GetCUDAMultiProcessors(place_.device);
max_threads_per_mp_ = GetCUDAMaxThreadsPerMultiProcessor(place_.device);
PADDLE_ENFORCE(cudaStreamCreate(&stream_));
eigen_stream_.reset(new EigenCudaStreamDevice());
eigen_stream_->Reinitialize(&stream_, place);
eigen_device_.reset(new Eigen::GpuDevice(eigen_stream_.get()));
PADDLE_ENFORCE(dynload::cublasCreate(&cublas_handle_));
PADDLE_ENFORCE(dynload::cublasSetStream(cublas_handle_, stream_));
if (dynload::HasCUDNN()) {
cudnn_holder_.reset(new CudnnHolder(&stream_, place));
}
driver_version_ = GetCUDADriverVersion(place_.device);
runtime_version_ = GetCUDARuntimeVersion(place_.device);
LOG_FIRST_N(WARNING, 1) << "Please NOTE: device: " << place_.device
<< ", CUDA Capability: " << compute_capability_
<< ", Driver Version: " << driver_version_ / 1000
<< "." << (driver_version_ % 100) / 10
<< ", Runtime Version: " << runtime_version_ / 1000
<< "." << (runtime_version_ % 100) / 10;
size_t cudnn_dso_ver = dynload::cudnnGetVersion();
LOG_FIRST_N(WARNING, 1) << "device: " << place_.device
<< ", cuDNN Version: " << cudnn_dso_ver / 1000 << "."
<< (cudnn_dso_ver % 100) / 10 << ".";
callback_manager_.reset(new StreamCallbackManager(stream_));
}
CUDADeviceContext::~CUDADeviceContext() {
SetDeviceId(place_.device);
Wait();
WaitStreamCallback();
PADDLE_ENFORCE(dynload::cublasDestroy(cublas_handle_));
eigen_stream_.reset();
eigen_device_.reset();
PADDLE_ENFORCE(cudaStreamDestroy(stream_));
}
Place CUDADeviceContext::GetPlace() const { return place_; }
void CUDADeviceContext::Wait() const {
PADDLE_ENFORCE(cudaStreamSynchronize(stream_));
PADDLE_ENFORCE(cudaGetLastError());
}
int CUDADeviceContext::GetComputeCapability() const {
return compute_capability_;
}
int CUDADeviceContext::GetMaxPhysicalThreadCount() const {
return multi_process_ * max_threads_per_mp_;
}
Eigen::GpuDevice* CUDADeviceContext::eigen_device() const {
return eigen_device_.get();
}
cublasHandle_t CUDADeviceContext::cublas_handle() const {
return cublas_handle_;
}
cudnnHandle_t CUDADeviceContext::cudnn_handle() const {
return cudnn_holder_->cudnn_handle();
}
CudnnWorkspaceHandle CUDADeviceContext::cudnn_workspace_handle() const {
return CudnnWorkspaceHandle(cudnn_holder_.get());
}
cudaStream_t CUDADeviceContext::stream() const { return stream_; }
CUDAPinnedDeviceContext::CUDAPinnedDeviceContext() {
eigen_device_.reset(new Eigen::DefaultDevice());
}
CUDAPinnedDeviceContext::CUDAPinnedDeviceContext(CUDAPinnedPlace place)
: place_(place) {
eigen_device_.reset(new Eigen::DefaultDevice());
}
Eigen::DefaultDevice* CUDAPinnedDeviceContext::eigen_device() const {
return eigen_device_.get();
}
Place CUDAPinnedDeviceContext::GetPlace() const { return place_; }
#endif
#ifdef PADDLE_WITH_MKLDNN
MKLDNNDeviceContext::MKLDNNDeviceContext(CPUPlace place)
: CPUDeviceContext(place), engine_(mkldnn::engine::cpu, 0), p_blobmap_() {
p_blobmap_.reset(new BlobMap());
p_mutex_.reset(new std::mutex());
}
namespace {
// Current thread's id.
thread_local int cur_thread_id = 0;
}
void set_cur_thread_id(int tid) { cur_thread_id = tid; }
int get_cur_thread_id(void) { return cur_thread_id; }
void MKLDNNDeviceContext::SetBlob(const std::string& name,
std::shared_ptr<void> data) const {
BlobMap* pMap = p_blobmap_.get();
std::shared_ptr<KeyBlob> pBlob = nullptr;
int tid = platform::get_cur_thread_id();
std::lock_guard<std::mutex> lock(*p_mutex_.get());
// Find KeyBlob for current thread
auto map_it = pMap->find(tid);
if (map_it == pMap->end()) {
// 1st time to set blob in current thread
pBlob = std::shared_ptr<KeyBlob>(new KeyBlob());
(*pMap)[tid] = pBlob;
} else {
pBlob = map_it->second;
}
// Find Key in found (or newly created) KeyBlob
auto key_it = pBlob->find(name);
if (key_it == pBlob->end()) {
(*pBlob)[name] = data; // create new blob
} else {
key_it->second = data; // set data to existing blob
}
// lock will be automatically released when out of scope
return;
}
std::shared_ptr<void> MKLDNNDeviceContext::GetBlob(
const std::string& name) const {
BlobMap* pMap = p_blobmap_.get();
std::shared_ptr<KeyBlob> pBlob = nullptr;
int tid = platform::get_cur_thread_id();
std::lock_guard<std::mutex> lock(*p_mutex_.get());
// Find KeyBlob for current thread firstly
auto map_it = pMap->find(tid);
if (map_it == pMap->end()) return nullptr;
pBlob = map_it->second;
// Find Blob via name
auto key_it = pBlob->find(name);
if (key_it == pBlob->end()) return nullptr;
// lock will be automatically released when out of scope
return key_it->second;
}
#endif
} // namespace platform
} // namespace paddle
<commit_msg>fix deallocate bug test=develop<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/platform/device_context.h"
#include <set>
#include <string>
#include <unordered_set>
#include <vector>
#include "paddle/fluid/memory/memory.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/framework/rw_lock.h"
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif
namespace paddle {
namespace platform {
DeviceContextPool* DeviceContextPool::pool = nullptr;
platform::DeviceContext* DeviceContextPool::Get(const platform::Place& place) {
auto it = device_contexts_.find(place);
if (it == device_contexts_.end()) {
PADDLE_THROW(
"'Place' is not supported, Please re-compile with WITH_GPU "
"option");
}
return it->second.get().get();
}
template <typename DevCtx, typename PlaceType>
inline void EmplaceDeviceContext(
std::map<Place, std::shared_future<std::unique_ptr<DeviceContext>>>*
map_ptr,
platform::Place p) {
using PtrType = std::unique_ptr<DeviceContext>;
map_ptr->emplace(p, std::async(std::launch::deferred, [=] {
// lazy evaluation. i.e., only create device context at
// first `Get`
return PtrType(new DevCtx(boost::get<PlaceType>(p)));
}));
}
DeviceContextPool::DeviceContextPool(
const std::vector<platform::Place>& places) {
PADDLE_ENFORCE_GT(places.size(), 0);
std::set<Place> set;
for (auto& p : places) {
set.insert(p);
}
for (auto& p : set) {
if (platform::is_cpu_place(p)) {
#ifdef PADDLE_WITH_MKLDNN
EmplaceDeviceContext<MKLDNNDeviceContext, CPUPlace>(&device_contexts_, p);
#else
EmplaceDeviceContext<CPUDeviceContext, CPUPlace>(&device_contexts_, p);
#endif
} else if (platform::is_gpu_place(p)) {
#ifdef PADDLE_WITH_CUDA
EmplaceDeviceContext<CUDADeviceContext, CUDAPlace>(&device_contexts_, p);
#else
PADDLE_THROW(
"'CUDAPlace' is not supported, Please re-compile with WITH_GPU "
"option");
#endif
} else if (platform::is_cuda_pinned_place(p)) {
#ifdef PADDLE_WITH_CUDA
EmplaceDeviceContext<CUDAPinnedDeviceContext, CUDAPinnedPlace>(
&device_contexts_, p);
#else
PADDLE_THROW(
"'CUDAPlace' is not supported, Please re-compile with WITH_GPU "
"option");
#endif
}
}
}
CPUDeviceContext::CPUDeviceContext() {
eigen_device_.reset(new Eigen::DefaultDevice());
}
CPUDeviceContext::CPUDeviceContext(CPUPlace place) : place_(place) {
eigen_device_.reset(new Eigen::DefaultDevice());
}
Eigen::DefaultDevice* CPUDeviceContext::eigen_device() const {
return eigen_device_.get();
}
Place CPUDeviceContext::GetPlace() const { return place_; }
#ifdef PADDLE_WITH_CUDA
class EigenCudaStreamDevice : public Eigen::StreamInterface {
public:
EigenCudaStreamDevice() : scratch_(nullptr), semaphore_(nullptr) {
Eigen::initializeDeviceProp();
}
~EigenCudaStreamDevice() override {}
void Reinitialize(const cudaStream_t* cuda_stream, CUDAPlace place) {
stream_ = cuda_stream;
place_ = place;
device_prop_ = &Eigen::m_deviceProperties[place.device];
}
const cudaStream_t& stream() const override { return *stream_; }
const cudaDeviceProp& deviceProperties() const override {
return *device_prop_;
}
void* allocate(size_t num_bytes) const override {
auto buf = paddle::memory::Alloc(place_, num_bytes,
memory::Allocator::kScratchpad);
void* retv = buf->ptr();
allocations_[buf->ptr()] = std::move(buf);
return retv;
}
void deallocate(void* buffer) const override { allocations_.erase(buffer); }
void* scratchpad() const override {
if (scratch_ == NULL) {
scratch_ = allocate(Eigen::kCudaScratchSize + sizeof(unsigned int));
}
return scratch_;
}
unsigned int* semaphore() const override {
if (semaphore_ == NULL) {
char* scratch =
static_cast<char*>(scratchpad()) + Eigen::kCudaScratchSize;
semaphore_ = reinterpret_cast<unsigned int*>(scratch);
PADDLE_ENFORCE(
cudaMemsetAsync(semaphore_, 0, sizeof(unsigned int), *stream_));
}
return semaphore_;
}
private:
CUDAPlace place_;
const cudaStream_t* stream_; // not owned;
const cudaDeviceProp* device_prop_; // not owned;
mutable void* scratch_;
mutable unsigned int* semaphore_;
mutable std::unordered_map<void*, memory::AllocationPtr> allocations_;
};
CudnnHolder::CudnnHolder(const cudaStream_t* stream, const CUDAPlace& place)
: workspace_(nullptr), stream_(stream), place_(place) {
PADDLE_ENFORCE(dynload::cudnnCreate(&cudnn_handle_));
PADDLE_ENFORCE(dynload::cudnnSetStream(cudnn_handle_, *stream_));
}
CudnnHolder::~CudnnHolder() {
PADDLE_ENFORCE(dynload::cudnnDestroy(cudnn_handle_));
}
void CudnnHolder::ReallocateWorkspace(size_t required_workspace_len) {
if (required_workspace_len <= WorkspaceSize()) {
return;
}
if (workspace_ != nullptr) {
// Maybe someone is using the current workspace
PADDLE_ENFORCE(cudaStreamSynchronize(*stream_));
workspace_.reset();
}
workspace_ = paddle::memory::Alloc(place_, required_workspace_len,
paddle::memory::Allocator::kScratchpad);
}
CUDADeviceContext::CUDADeviceContext(CUDAPlace place)
: place_(place), cudnn_holder_(nullptr) {
CUDADeviceGuard guard(place_.device);
compute_capability_ = GetCUDAComputeCapability(place_.device);
multi_process_ = GetCUDAMultiProcessors(place_.device);
max_threads_per_mp_ = GetCUDAMaxThreadsPerMultiProcessor(place_.device);
PADDLE_ENFORCE(cudaStreamCreate(&stream_));
eigen_stream_.reset(new EigenCudaStreamDevice());
eigen_stream_->Reinitialize(&stream_, place);
eigen_device_.reset(new Eigen::GpuDevice(eigen_stream_.get()));
PADDLE_ENFORCE(dynload::cublasCreate(&cublas_handle_));
PADDLE_ENFORCE(dynload::cublasSetStream(cublas_handle_, stream_));
if (dynload::HasCUDNN()) {
cudnn_holder_.reset(new CudnnHolder(&stream_, place));
}
driver_version_ = GetCUDADriverVersion(place_.device);
runtime_version_ = GetCUDARuntimeVersion(place_.device);
LOG_FIRST_N(WARNING, 1) << "Please NOTE: device: " << place_.device
<< ", CUDA Capability: " << compute_capability_
<< ", Driver Version: " << driver_version_ / 1000
<< "." << (driver_version_ % 100) / 10
<< ", Runtime Version: " << runtime_version_ / 1000
<< "." << (runtime_version_ % 100) / 10;
size_t cudnn_dso_ver = dynload::cudnnGetVersion();
LOG_FIRST_N(WARNING, 1) << "device: " << place_.device
<< ", cuDNN Version: " << cudnn_dso_ver / 1000 << "."
<< (cudnn_dso_ver % 100) / 10 << ".";
callback_manager_.reset(new StreamCallbackManager(stream_));
}
CUDADeviceContext::~CUDADeviceContext() {
SetDeviceId(place_.device);
Wait();
WaitStreamCallback();
PADDLE_ENFORCE(dynload::cublasDestroy(cublas_handle_));
eigen_stream_.reset();
eigen_device_.reset();
PADDLE_ENFORCE(cudaStreamDestroy(stream_));
}
Place CUDADeviceContext::GetPlace() const { return place_; }
void CUDADeviceContext::Wait() const {
PADDLE_ENFORCE(cudaStreamSynchronize(stream_));
PADDLE_ENFORCE(cudaGetLastError());
}
int CUDADeviceContext::GetComputeCapability() const {
return compute_capability_;
}
int CUDADeviceContext::GetMaxPhysicalThreadCount() const {
return multi_process_ * max_threads_per_mp_;
}
Eigen::GpuDevice* CUDADeviceContext::eigen_device() const {
return eigen_device_.get();
}
cublasHandle_t CUDADeviceContext::cublas_handle() const {
return cublas_handle_;
}
cudnnHandle_t CUDADeviceContext::cudnn_handle() const {
return cudnn_holder_->cudnn_handle();
}
CudnnWorkspaceHandle CUDADeviceContext::cudnn_workspace_handle() const {
return CudnnWorkspaceHandle(cudnn_holder_.get());
}
cudaStream_t CUDADeviceContext::stream() const { return stream_; }
CUDAPinnedDeviceContext::CUDAPinnedDeviceContext() {
eigen_device_.reset(new Eigen::DefaultDevice());
}
CUDAPinnedDeviceContext::CUDAPinnedDeviceContext(CUDAPinnedPlace place)
: place_(place) {
eigen_device_.reset(new Eigen::DefaultDevice());
}
Eigen::DefaultDevice* CUDAPinnedDeviceContext::eigen_device() const {
return eigen_device_.get();
}
Place CUDAPinnedDeviceContext::GetPlace() const { return place_; }
#endif
#ifdef PADDLE_WITH_MKLDNN
MKLDNNDeviceContext::MKLDNNDeviceContext(CPUPlace place)
: CPUDeviceContext(place), engine_(mkldnn::engine::cpu, 0), p_blobmap_() {
p_blobmap_.reset(new BlobMap());
p_mutex_.reset(new std::mutex());
}
namespace {
// Current thread's id.
thread_local int cur_thread_id = 0;
}
void set_cur_thread_id(int tid) { cur_thread_id = tid; }
int get_cur_thread_id(void) { return cur_thread_id; }
void MKLDNNDeviceContext::SetBlob(const std::string& name,
std::shared_ptr<void> data) const {
BlobMap* pMap = p_blobmap_.get();
std::shared_ptr<KeyBlob> pBlob = nullptr;
int tid = platform::get_cur_thread_id();
std::lock_guard<std::mutex> lock(*p_mutex_.get());
// Find KeyBlob for current thread
auto map_it = pMap->find(tid);
if (map_it == pMap->end()) {
// 1st time to set blob in current thread
pBlob = std::shared_ptr<KeyBlob>(new KeyBlob());
(*pMap)[tid] = pBlob;
} else {
pBlob = map_it->second;
}
// Find Key in found (or newly created) KeyBlob
auto key_it = pBlob->find(name);
if (key_it == pBlob->end()) {
(*pBlob)[name] = data; // create new blob
} else {
key_it->second = data; // set data to existing blob
}
// lock will be automatically released when out of scope
return;
}
std::shared_ptr<void> MKLDNNDeviceContext::GetBlob(
const std::string& name) const {
BlobMap* pMap = p_blobmap_.get();
std::shared_ptr<KeyBlob> pBlob = nullptr;
int tid = platform::get_cur_thread_id();
std::lock_guard<std::mutex> lock(*p_mutex_.get());
// Find KeyBlob for current thread firstly
auto map_it = pMap->find(tid);
if (map_it == pMap->end()) return nullptr;
pBlob = map_it->second;
// Find Blob via name
auto key_it = pBlob->find(name);
if (key_it == pBlob->end()) return nullptr;
// lock will be automatically released when out of scope
return key_it->second;
}
#endif
} // namespace platform
} // namespace paddle
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// NB: You must compile with -rdynamic for llvm to be able to find the appropriate symbols
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
int call_counter[4] = {0, 0, 0, 0};
extern "C" DLLEXPORT int my_func(int counter, int x) {
call_counter[counter]++;
return x;
}
HalidePureExtern_2(int, my_func, int, int);
// A parallel for loop runner that isn't actually parallel
int not_really_parallel_for(void *ctx, int (*f)(void *, int, uint8_t *), int min, int extent, uint8_t *closure) {
for (int i = min; i < min + extent; i++) {
f(ctx, i, closure);
}
return 0;
}
int main(int argc, char **argv) {
Var x, y;
Func f;
f(x, y) = my_func(0, Expr(0)) + my_func(1, y) + my_func(2, x*32 + y);
// llvm rightly refuses to lift loop invariants out of loops that
// might have an extent of zero. It's possible wasted work.
f.bound(x, 0, 32).bound(y, 0, 32);
Buffer<int> im = f.realize(32, 32);
// Check the result was what we expected
for (int y = 0; y < 32; y++) {
for (int x = 0; x < 32; x++) {
int correct = y + 32*x + y;
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
// Check the call counters
if (call_counter[0] != 1 || call_counter[1] != 32 || call_counter[2] != 32*32) {
printf("Call counters were %d %d %d instead of %d %d %d\n",
call_counter[0], call_counter[1], call_counter[2],
1, 32, 32*32);
return -1;
}
// Note that things don't get lifted out of parallel loops - Each
// thread will independently call your extern function.
Func g;
g(x, y) = my_func(3, Expr(0));
g.parallel(y);
// Avoid the race condition by not actually being parallel
g.set_custom_do_par_for(¬_really_parallel_for);
g.realize(32, 32);
if (call_counter[3] != 32) {
printf("Call counter for parallel call was %d instead of %d\n",
call_counter[3], 32);
return -1;
}
printf("Success!\n");
return 0;
}
<commit_msg>Fix test<commit_after>#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// NB: You must compile with -rdynamic for llvm to be able to find the appropriate symbols
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
int call_counter[4] = {0, 0, 0, 0};
extern "C" DLLEXPORT int my_func(int counter, int x) {
call_counter[counter]++;
return x;
}
HalidePureExtern_2(int, my_func, int, int);
// A parallel for loop runner that isn't actually parallel
int not_really_parallel_for(void *ctx, int (*f)(void *, int, uint8_t *), int min, int extent, uint8_t *closure) {
for (int i = min; i < min + extent; i++) {
f(ctx, i, closure);
}
return 0;
}
int main(int argc, char **argv) {
Var x, y;
Func f;
f(x, y) = my_func(0, Expr(0)) + my_func(1, y) + my_func(2, x*32 + y);
// llvm rightly refuses to lift loop invariants out of loops that
// might have an extent of zero. It's possible wasted work.
f.bound(x, 0, 32).bound(y, 0, 32);
Buffer<int> im = f.realize(32, 32);
// Check the result was what we expected
for (int y = 0; y < 32; y++) {
for (int x = 0; x < 32; x++) {
int correct = y + 32*x + y;
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
// Check the call counters
if (call_counter[0] != 1 || call_counter[1] != 32 || call_counter[2] != 32*32) {
printf("Call counters were %d %d %d instead of %d %d %d\n",
call_counter[0], call_counter[1], call_counter[2],
1, 32, 32*32);
return -1;
}
// Note that things also get lifted out of parallel loops.
Func g;
g(x, y) = my_func(3, Expr(0));
g.parallel(y);
// Avoid the race condition by not actually being parallel
g.set_custom_do_par_for(¬_really_parallel_for);
g.realize(32, 32);
if (call_counter[3] != 1) {
printf("Call counter for parallel call was %d instead of %d\n",
call_counter[3], 32);
return -1;
}
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-04-16
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
#include "distortos/StaticSignalsReceiver.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack.
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param QueuedSignals is the max number of queued signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable queuing of signals for this thread
* \param CaughtSignals is the max number of caught signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable catching of signals for this thread
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, bool CanReceiveSignals, size_t QueuedSignals, size_t CaughtSignals, typename Function,
typename... Args>
class StaticThread : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack and internal
* StaticSignalsReceiver object.
*
* Specialization for threads with enabled reception of signals (CanReceiveSignals == true)
*
* \param StackSize is the size of stack, bytes
* \param QueuedSignals is the max number of queued signals for this thread, 0 to disable queuing of signals for this
* thread
* \param CaughtSignals is the max number of caught signals for this thread, 0 to disable catching of signals for this
* thread
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, size_t QueuedSignals, size_t CaughtSignals, typename Function, typename... Args>
class StaticThread<StackSize, true, QueuedSignals, CaughtSignals, Function, Args...> : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, &staticSignalsReceiver_,
std::forward<Function>(function), std::forward<Args>(args)...},
staticSignalsReceiver_{}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
/// internal StaticSignalsReceiver object
StaticSignalsReceiver<QueuedSignals, CaughtSignals> staticSignalsReceiver_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param QueuedSignals is the max number of queued signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable queuing of signals for this thread
* \param CaughtSignals is the max number of caught signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable catching of signals for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, size_t QueuedSignals = {}, size_t CaughtSignals = {},
typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, QueuedSignals, CaughtSignals, Function, Args...>
makeStaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args)
{
return {priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...};
}
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param QueuedSignals is the max number of queued signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable queuing of signals for this thread
* \param CaughtSignals is the max number of caught signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable catching of signals for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, size_t QueuedSignals = {}, size_t CaughtSignals = {},
typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, QueuedSignals, CaughtSignals, Function, Args...>
makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<commit_msg>StaticThread: rename CaughtSignals template argument to SignalActions<commit_after>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-05-16
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
#include "distortos/StaticSignalsReceiver.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack.
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param QueuedSignals is the max number of queued signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable queuing of signals for this thread
* \param SignalActions is the max number of different SignalAction objects for this thread, relevant only if
* CanReceiveSignals == true, 0 to disable catching of signals for this thread
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, bool CanReceiveSignals, size_t QueuedSignals, size_t SignalActions, typename Function,
typename... Args>
class StaticThread : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack and internal
* StaticSignalsReceiver object.
*
* Specialization for threads with enabled reception of signals (CanReceiveSignals == true)
*
* \param StackSize is the size of stack, bytes
* \param QueuedSignals is the max number of queued signals for this thread, 0 to disable queuing of signals for this
* thread
* \param SignalActions is the max number of different SignalAction objects for this thread, relevant only if
* CanReceiveSignals == true, 0 to disable catching of signals for this thread
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, size_t QueuedSignals, size_t SignalActions, typename Function, typename... Args>
class StaticThread<StackSize, true, QueuedSignals, SignalActions, Function, Args...> : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, &staticSignalsReceiver_,
std::forward<Function>(function), std::forward<Args>(args)...},
staticSignalsReceiver_{}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
/// internal StaticSignalsReceiver object
StaticSignalsReceiver<QueuedSignals, SignalActions> staticSignalsReceiver_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param QueuedSignals is the max number of queued signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable queuing of signals for this thread
* \param SignalActions is the max number of different SignalAction objects for this thread, relevant only if
* CanReceiveSignals == true, 0 to disable catching of signals for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, size_t QueuedSignals = {}, size_t SignalActions = {},
typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, QueuedSignals, SignalActions, Function, Args...>
makeStaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args)
{
return {priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...};
}
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param QueuedSignals is the max number of queued signals for this thread, relevant only if CanReceiveSignals == true,
* 0 to disable queuing of signals for this thread
* \param SignalActions is the max number of different SignalAction objects for this thread, relevant only if
* CanReceiveSignals == true, 0 to disable catching of signals for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, size_t QueuedSignals = {}, size_t SignalActions = {},
typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, QueuedSignals, SignalActions, Function, Args...>
makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 nyorain
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
/// file Contains the Span template class for not-owned contigous ranges.
#pragma once
#ifndef NYTL_INCLUDE_SPAN
#define NYTL_INCLUDE_SPAN
#include <nytl/fwd/span.hpp> // nytl::Span default template parameter
#include <nytl/scalar.hpp> // nytl::constants::dynamicSize
#include <cstdlib> // std::size_t
#include <stdexcept> // std::out_of_range
#include <array> // std::array
namespace nytl {
namespace detail {
template<typename T, typename C, typename = void> struct ValidContainerT;
template<typename T, typename C> using ValidContainer = typename ValidContainerT<T, C>::type;
} // namespace nytl::detail
/// The underlaying storage type of spans that is specialized for dyanmic size.
template<typename T, std::size_t N> struct SpanStorage;
/// \brief Describes a contigous, non-owned range of elements of type 'T'.
/// \details Spans can be used to pass sequences of elements around in a lightweight manner.
/// Its main use are function parameters sine instead of a std::vector it will not allocate
/// any memory or copy any elements but instead just reference them.
/// \tparam T The type the range is defined over. Use const types for non-mutable ranges.
/// \tparam N The size of the range. If not known at compile
/// time, use nytl::constants::dynamicSize (also defaulted to dynamicSize).
///
/// Some examples below. Note that Spans must be used carefully outside of temporary
/// expressions since they are only valid as long the object they reference is valid.
/// ```cpp
/// void foo(nytl::Span<std::string> names); // takes dyanmic amount of strings, might modify it
/// void bar(nytl::Span<const std::string, 3> names); // takes exactly 3 const strings
/// void baz(nytl::Span<const std::string, 5> names); // takes exactly 5 const strings
///
/// int main()
/// {
/// std::array<std::string, 3> namesArray {"foo", "bar", "baz"};
/// foo(namesArray); // works
/// bar(namesArray); // works
/// baz(namesArray); // will throw std::logic_error since baz requires exactly 5 strings
///
/// std::vector<std::string> namesVector {"foo", "bar", "baz", "abz", "bla"};
/// foo(namesVector); // works
/// bar(namesVector); // will throw std::logic_error since bar requires exactly 3 strings
/// baz(namesVector); // works
///
/// // If we only want the first 3 elements from namesVector as range we can do it like this
/// bar({namesVector.data(), 3}); // works, takes the first 3 elements
/// foo({*namesVector.data(), 4}); // we can also use references
///
/// // careful when using span outside of temporary expressions
/// auto span = nytl::Span<int>(std::vector<int>{4, 1, 2, 0});
/// // std::cout << span[0] << "\n"; // undefined behaviour!
/// }
///
/// void foo(nytl::Span<std::string> names)
/// {
/// // Some usage possibilities for span.
//// // The main usage is iterating over it:
/// for(auto& name : names)
/// std::cout << name << "\n";
///
/// // We might alternatively do this with a traditional for loop
/// for(auto i = 0u; i < names.size(); ++i)
/// std::cout << name << "\n";
///
/// // In this case we have a span of std::string, not const std::string,
/// // therefore we might also change it. This will change the names in the actual
/// // sequence this span references. Usually nytl::Span<const T> is used when the
/// // span is only read
/// if(!names.empty()) {
/// names.front() = "first name";
/// names.back() = "last name";
/// }
///
/// // A span can additionally be sliced into a subspan. This can either be
/// // done with a size known at compile time (which will result in a fixed-size span)
/// // or dynamically for a dynamic-sized span.
/// if(names.size() <= 2) return;
/// for(auto& name : names.slice(2, names.size() - 2)) // output everything but the first two
/// std::cout << name << "\n";
///
/// for(auto& name : names.slice<2>(0)) // output only the first two names
/// std::cout << name << "\n";
/// }
/// ```
template<typename T, std::size_t N>
class Span : public SpanStorage<T, N> {
public:
using Value = T;
using Iterator = T*;
using ReverseIterator = std::reverse_iterator<T*>;
using Reference = T&;
using Pointer = T*;
using Difference = std::ptrdiff_t;
using Size = std::size_t;
public:
using SpanStorage<T, N>::SpanStorage;
constexpr Span() noexcept = default;
constexpr Span(std::nullptr_t) noexcept : Span(nullptr, 0) {}
template<typename C, typename = detail::ValidContainer<T, C>>
constexpr Span(C& c) : Span(c.data(), c.size()) {}
template<typename C, typename = detail::ValidContainer<T, C>, std::size_t S = C::size()>
constexpr Span(C& c) : Span(c.data()) {}
constexpr Pointer data() const noexcept { return this->data_; }
constexpr Size size() const noexcept { return this->size_; }
constexpr bool empty() const noexcept { return size() == 0; }
constexpr Iterator begin() const noexcept { return data(); }
constexpr Iterator end() const noexcept { return data() + size(); }
constexpr ReverseIterator rbegin() const noexcept { return {end()}; }
constexpr ReverseIterator rend() const noexcept { return {begin()}; }
constexpr Reference operator[](Size i) const noexcept { return *(data() + i); }
constexpr Reference at(Size i) const { checkThrow(i); return data()[i]; }
constexpr Reference front() const noexcept { return *data(); }
constexpr Reference back() const noexcept { return *(data() + size() - 1); }
constexpr Span<T> slice(Size pos, Size size) const { return {data() + pos, size}; }
template<Size S> constexpr Span<T, S> slice(Size pos) const { return {data() + pos}; }
protected:
void checkThrow(Size i) const { if(i >= size()) throw std::out_of_range("nytl::Span::at"); }
};
// Default SpanStorage implementation for compile-time size
template<typename T, std::size_t N>
struct SpanStorage {
constexpr SpanStorage() noexcept = default;
constexpr SpanStorage(T* pointer, std::size_t size = N) : data_(pointer)
{
if(size != N) throw std::logic_error("nytl::Span:: invalid size");
if(!pointer && size != 0) throw std::logic_error("nytl::Span:: invalid data");
}
constexpr SpanStorage(T& ref, std::size_t size = N) : SpanStorage(&ref, size) {}
constexpr SpanStorage(T (&arr)[N]) : SpanStorage(arr, N) {}
T* data_ {};
constexpr static auto size_ = N;
};
// SpanStorage specialization for runtime size. Stored an extra size value.
template<typename T>
struct SpanStorage<T, constants::dynamicSize> {
constexpr SpanStorage() noexcept = default;
constexpr SpanStorage(T* pointer, std::size_t size = 1) : data_(pointer), size_(size)
{
if(!pointer && size != 0) throw std::logic_error("nytl::Span:: invalid data");
}
constexpr SpanStorage(T& ref, std::size_t size = 1) : SpanStorage(&ref, size) {}
template<std::size_t S> constexpr SpanStorage(T (&arr)[S]) : SpanStorage(arr, S) {}
T* data_ {};
std::size_t size_ {};
};
// SpanStorage specialization for runtime size with const parameter.
// Allows constrsuction from initializer list.
template<typename T>
struct SpanStorage<const T, 0> {
constexpr SpanStorage() noexcept = default;
constexpr SpanStorage(const T* pointer, std::size_t size = 1) : data_(pointer), size_(size)
{
if(!pointer && size != 0) throw std::logic_error("nytl::Span:: invalid data");
}
constexpr SpanStorage(const T& ref, std::size_t size = 1) : SpanStorage(&ref, size) {}
template<std::size_t S> constexpr SpanStorage(T (&arr)[S]) : SpanStorage(arr, S) {}
constexpr SpanStorage(const std::initializer_list<T>& l)
: SpanStorage(l.begin(), l.size()) {}
const T* data_ {};
std::size_t size_ {};
};
namespace detail {
// Returns whether 'C' is a valid container to construct a Span<T> from
template<typename T, typename C>
struct ValidContainerT<T, C,
typename std::enable_if<
std::is_convertible<
decltype(std::declval<C>().data()),
T*
>::value &&
std::is_convertible<
decltype(std::declval<C>().size()),
std::size_t
>::value
>::type
> { using type = void; };
} // namespace detail
} // namespace nytl
#endif // header guard
<commit_msg>Update span.hpp<commit_after>// Copyright (c) 2017 nyorain
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
/// file Contains the Span template class for not-owned contigous ranges.
#pragma once
#ifndef NYTL_INCLUDE_SPAN
#define NYTL_INCLUDE_SPAN
#include <nytl/fwd/span.hpp> // nytl::Span default template parameter
#include <nytl/scalar.hpp> // nytl::constants::dynamicSize
#include <cstdlib> // std::size_t
#include <stdexcept> // std::out_of_range
#include <initializer_list> // std::initializer_list
#include <array> // std::array
namespace nytl {
namespace detail {
template<typename T, typename C, typename = void> struct ValidContainerT;
template<typename T, typename C> using ValidContainer = typename ValidContainerT<T, C>::type;
} // namespace nytl::detail
/// The underlaying storage type of spans that is specialized for dyanmic size.
template<typename T, std::size_t N> struct SpanStorage;
/// \brief Describes a contigous, non-owned range of elements of type 'T'.
/// \details Spans can be used to pass sequences of elements around in a lightweight manner.
/// Its main use are function parameters sine instead of a std::vector it will not allocate
/// any memory or copy any elements but instead just reference them.
/// \tparam T The type the range is defined over. Use const types for non-mutable ranges.
/// \tparam N The size of the range. If not known at compile
/// time, use nytl::constants::dynamicSize (also defaulted to dynamicSize).
///
/// Some examples below. Note that Spans must be used carefully outside of temporary
/// expressions since they are only valid as long the object they reference is valid.
/// ```cpp
/// void foo(nytl::Span<std::string> names); // takes dyanmic amount of strings, might modify it
/// void bar(nytl::Span<const std::string, 3> names); // takes exactly 3 const strings
/// void baz(nytl::Span<const std::string, 5> names); // takes exactly 5 const strings
///
/// int main()
/// {
/// std::array<std::string, 3> namesArray {"foo", "bar", "baz"};
/// foo(namesArray); // works
/// bar(namesArray); // works
/// baz(namesArray); // will throw std::logic_error since baz requires exactly 5 strings
///
/// std::vector<std::string> namesVector {"foo", "bar", "baz", "abz", "bla"};
/// foo(namesVector); // works
/// bar(namesVector); // will throw std::logic_error since bar requires exactly 3 strings
/// baz(namesVector); // works
///
/// // If we only want the first 3 elements from namesVector as range we can do it like this
/// bar({namesVector.data(), 3}); // works, takes the first 3 elements
/// foo({*namesVector.data(), 4}); // we can also use references
///
/// // careful when using span outside of temporary expressions
/// auto span = nytl::Span<int>(std::vector<int>{4, 1, 2, 0});
/// // std::cout << span[0] << "\n"; // undefined behaviour!
/// }
///
/// void foo(nytl::Span<std::string> names)
/// {
/// // Some usage possibilities for span.
//// // The main usage is iterating over it:
/// for(auto& name : names)
/// std::cout << name << "\n";
///
/// // We might alternatively do this with a traditional for loop
/// for(auto i = 0u; i < names.size(); ++i)
/// std::cout << name << "\n";
///
/// // In this case we have a span of std::string, not const std::string,
/// // therefore we might also change it. This will change the names in the actual
/// // sequence this span references. Usually nytl::Span<const T> is used when the
/// // span is only read
/// if(!names.empty()) {
/// names.front() = "first name";
/// names.back() = "last name";
/// }
///
/// // A span can additionally be sliced into a subspan. This can either be
/// // done with a size known at compile time (which will result in a fixed-size span)
/// // or dynamically for a dynamic-sized span.
/// if(names.size() <= 2) return;
/// for(auto& name : names.slice(2, names.size() - 2)) // output everything but the first two
/// std::cout << name << "\n";
///
/// for(auto& name : names.slice<2>(0)) // output only the first two names
/// std::cout << name << "\n";
/// }
/// ```
template<typename T, std::size_t N>
class Span : public SpanStorage<T, N> {
public:
using Value = T;
using Iterator = T*;
using ReverseIterator = std::reverse_iterator<T*>;
using Reference = T&;
using Pointer = T*;
using Difference = std::ptrdiff_t;
using Size = std::size_t;
public:
using SpanStorage<T, N>::SpanStorage;
constexpr Span() noexcept = default;
constexpr Span(std::nullptr_t) noexcept : Span(nullptr, 0) {}
template<typename C, typename = detail::ValidContainer<T, C>>
constexpr Span(C& c) : Span(c.data(), c.size()) {}
template<typename C, typename = detail::ValidContainer<T, C>, std::size_t S = C::size()>
constexpr Span(C& c) : Span(c.data()) {}
constexpr Pointer data() const noexcept { return this->data_; }
constexpr Size size() const noexcept { return this->size_; }
constexpr bool empty() const noexcept { return size() == 0; }
constexpr Iterator begin() const noexcept { return data(); }
constexpr Iterator end() const noexcept { return data() + size(); }
constexpr ReverseIterator rbegin() const noexcept { return {end()}; }
constexpr ReverseIterator rend() const noexcept { return {begin()}; }
constexpr Reference operator[](Size i) const noexcept { return *(data() + i); }
constexpr Reference at(Size i) const { checkThrow(i); return data()[i]; }
constexpr Reference front() const noexcept { return *data(); }
constexpr Reference back() const noexcept { return *(data() + size() - 1); }
constexpr Span<T> slice(Size pos, Size size) const { return {data() + pos, size}; }
template<Size S> constexpr Span<T, S> slice(Size pos) const { return {data() + pos}; }
protected:
void checkThrow(Size i) const { if(i >= size()) throw std::out_of_range("nytl::Span::at"); }
};
// Default SpanStorage implementation for compile-time size
template<typename T, std::size_t N>
struct SpanStorage {
constexpr SpanStorage() noexcept = default;
constexpr SpanStorage(T* pointer, std::size_t size = N) : data_(pointer)
{
if(size != N) throw std::logic_error("nytl::Span:: invalid size");
if(!pointer && size != 0) throw std::logic_error("nytl::Span:: invalid data");
}
constexpr SpanStorage(T& ref, std::size_t size = N) : SpanStorage(&ref, size) {}
constexpr SpanStorage(T (&arr)[N]) : SpanStorage(arr, N) {}
T* data_ {};
constexpr static auto size_ = N;
};
// SpanStorage specialization for runtime size. Stored an extra size value.
template<typename T>
struct SpanStorage<T, constants::dynamicSize> {
constexpr SpanStorage() noexcept = default;
constexpr SpanStorage(T* pointer, std::size_t size = 1) : data_(pointer), size_(size)
{
if(!pointer && size != 0) throw std::logic_error("nytl::Span:: invalid data");
}
constexpr SpanStorage(T& ref, std::size_t size = 1) : SpanStorage(&ref, size) {}
template<std::size_t S> constexpr SpanStorage(T (&arr)[S]) : SpanStorage(arr, S) {}
T* data_ {};
std::size_t size_ {};
};
// SpanStorage specialization for runtime size with const parameter.
// Allows constrsuction from initializer list.
template<typename T>
struct SpanStorage<const T, 0> {
constexpr SpanStorage() noexcept = default;
constexpr SpanStorage(const T* pointer, std::size_t size = 1) : data_(pointer), size_(size)
{
if(!pointer && size != 0) throw std::logic_error("nytl::Span:: invalid data");
}
constexpr SpanStorage(const T& ref, std::size_t size = 1) : SpanStorage(&ref, size) {}
template<std::size_t S> constexpr SpanStorage(T (&arr)[S]) : SpanStorage(arr, S) {}
constexpr SpanStorage(const std::initializer_list<T>& l)
: SpanStorage(l.begin(), l.size()) {}
const T* data_ {};
std::size_t size_ {};
};
namespace detail {
// Returns whether 'C' is a valid container to construct a Span<T> from
template<typename T, typename C>
struct ValidContainerT<T, C,
typename std::enable_if<
std::is_convertible<
decltype(std::declval<C>().data()),
T*
>::value &&
std::is_convertible<
decltype(std::declval<C>().size()),
std::size_t
>::value
>::type
> { using type = void; };
} // namespace detail
} // namespace nytl
#endif // header guard
<|endoftext|>
|
<commit_before>#pragma once
#include <gunrock/algorithms/algorithms.hxx>
using vertex_t = int;
using edge_t = int;
using weight_t = float;
namespace gunrock {
namespace mst {
template <typename vertex_t>
struct param_t {
// No parameters for this algorithm
};
template <typename vertex_t, typename weight_t>
struct result_t {
weight_t* mst_weight;
result_t(weight_t* _mst_weight) : mst_weight(_mst_weight) {}
};
// <boilerplate>
template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
param_type param;
result_type result;
problem_t(graph_t& G,
param_type& _param,
result_type& _result,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::problem_t<graph_t>(G, _context),
param(_param),
result(_result) {}
using vertex_t = typename graph_t::vertex_type;
using edge_t = typename graph_t::edge_type;
using weight_t = typename graph_t::weight_type;
// </boilerplate>
graph_t g = this->get_graph();
int n_vertices = g.get_number_of_vertices();
thrust::device_vector<vertex_t> roots;
thrust::device_vector<vertex_t> new_roots;
thrust::device_vector<weight_t> min_weights;
thrust::device_vector<int> mst_edges;
thrust::device_vector<int> super_vertices;
thrust::device_vector<int> min_neighbors;
void init() {
auto policy = this->context->get_context(0)->execution_policy();
roots.resize(n_vertices);
new_roots.resize(n_vertices);
min_weights.resize(n_vertices);
min_neighbors.resize(n_vertices);
mst_edges.resize(1);
super_vertices.resize(1);
auto d_mst_weight = thrust::device_pointer_cast(this->result.mst_weight);
thrust::fill(policy, min_weights.begin(), min_weights.end(),
std::numeric_limits<weight_t>::max());
thrust::fill(policy, d_mst_weight, d_mst_weight + 1, 0);
thrust::fill(policy, min_neighbors.begin(), min_neighbors.end(), -1);
thrust::sequence(policy, roots.begin(), roots.end(), 0);
thrust::sequence(policy, new_roots.begin(), new_roots.end(), 0);
thrust::sequence(policy, super_vertices.begin(), super_vertices.end(),
n_vertices);
}
void reset() {
// TODO: reset
return;
}
};
// <boilerplate>
template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
enactor_t(problem_t* _problem,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::enactor_t<problem_t>(_problem, _context) {}
using vertex_t = typename problem_t::vertex_t;
using edge_t = typename problem_t::edge_t;
using weight_t = typename problem_t::weight_t;
using frontier_t = typename enactor_t<problem_t>::frontier_t;
// </boilerplate>
// How to initialize the frontier at the beginning of the application.
void prepare_frontier(frontier_t* f,
cuda::multi_context_t& context) override {
// get pointer to the problem
auto P = this->get_problem();
auto n_vertices = P->get_graph().get_number_of_vertices();
auto n_edges = P->get_graph().get_number_of_edges();
// Fill the frontier with a sequence of vertices from 0 -> n_vertices.
f->sequence((edge_t)0, n_edges, context.get_context(0)->stream());
}
// One iteration of the application
void loop(cuda::multi_context_t& context) override {
auto E = this->get_enactor();
auto P = this->get_problem();
auto G = P->get_graph();
auto mst_weight = P->result.mst_weight;
auto mst_edges = P->mst_edges.data().get();
auto super_vertices = P->super_vertices.data().get();
auto min_neighbors = P->min_neighbors.data().get();
auto roots = P->roots.data().get();
auto new_roots = P->new_roots.data().get();
auto min_weights = P->min_weights.data().get();
auto policy = this->context->get_context(0)->execution_policy();
thrust::fill_n(policy, min_weights, P->n_vertices,
std::numeric_limits<weight_t>::max());
thrust::fill_n(policy, min_neighbors, P->n_vertices, -1);
// Find minimum weight for each vertex
// TODO: update for multi-directional edges?
auto get_min_weights = [min_weights, roots, G] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto neighbor = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// If they are already part of same super vertex, do not check
if (roots[source] != roots[neighbor]) {
// Store minimum weight
auto old_weight =
math::atomic::min(&(min_weights[roots[source]]), weight);
// printf(
// "1: source %i roots[source] %i weight %f min weight %f weight < "
// "old weight %i\n",
// source, roots[source], weight, min_weights[roots[source]],
// weight < old_weight);
return weight < old_weight;
}
return false;
};
auto get_min_neighbors =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto weight = G.get_edge_weight(e);
if (weight == min_weights[roots[source]]) {
auto old_val = math::atomic::max(&min_neighbors[roots[source]], e);
if (old_val < e) {
return true;
}
}
return false;
};
// just used for graph
auto remove_ties =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto dest = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
//printf("source %i dest %i weight %f\n", source, dest, weight);
if (e == min_neighbors[roots[source]]) {
return true;
}
return false;
};
// just used for graph
auto remove_dups =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto dest = G.get_destination_vertex(e);
if (source < dest ||
G.get_destination_vertex(min_neighbors[roots[dest]]) != source ||
G.get_source_vertex(min_neighbors[roots[dest]]) != dest) {
return true;
}
return false;
};
// Add weights to MST
auto add_to_mst = [G, roots, mst_weight, mst_edges, super_vertices,
min_neighbors, min_weights, new_roots] __host__
__device__(vertex_t const& v) -> void {
if (min_weights[v] != std::numeric_limits<weight_t>::max()) {
auto source = G.get_source_vertex(min_neighbors[v]);
auto dest = G.get_destination_vertex(min_neighbors[v]);
auto weight = min_weights[v];
// TODO: technically there is a race between reads/writes to
// new_roots[dest];
if (source < dest ||
G.get_destination_vertex(min_neighbors[roots[dest]]) != source ||
G.get_source_vertex(min_neighbors[roots[dest]]) != dest) {
// printf("v %i\n", source);
// printf("u %i\n", dest);
// printf("add mst v %i\n", v);
// printf("add mst u %i\n", u);
// printf("add mst v root %i\n", roots[v]);
// printf("add mst u root %i\n", roots[u]);
// Not sure cycle comparison for inc/dec vs add; using atomic::add for
// now because it is in our math.hxx
math::atomic::add(&mst_weight[0], weight);
//printf("%i,%i,%f\n", source, dest, weight);
//printf("GPU mst weight %f\n", mst_weight[0]);
math::atomic::add(&mst_edges[0], 1);
//printf("GPU mst edges %i\n", mst_edges[0]);
math::atomic::add(&super_vertices[0], -1);
// printf("super vertices %i\n", super_vertices[0]);
atomicExch((&new_roots[v]), new_roots[dest]);
return;
}
}
};
// Jump pointers in parallel for
// read and write from different copies of roots to resolve races
auto jump_pointers_parallel =
[roots, new_roots] __host__ __device__(vertex_t const& v) -> void {
vertex_t u = roots[v];
while (roots[u] != u) {
u = roots[u];
}
new_roots[v] = u;
return;
};
// Execute advance operator to get min weights
auto in_frontier = &(this->frontiers[0]);
auto out_frontier = &(this->frontiers[1]);
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, get_min_weights, in_frontier, out_frontier, context);
// Execute filter operator to get min neighbors
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, get_min_neighbors, out_frontier, out_frontier, context);
// Execute filter operator to remove ties from frontier
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, remove_ties, out_frontier, out_frontier, context);
// Execute filter operator to remove ties from frontier
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, remove_dups, out_frontier, out_frontier, context);
// Execute parallel for to add weights to MST
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
add_to_mst, // lambda function
context // context
);
(&(this->frontiers[1]))->print();
// TODO: remove cycles (because we can't check that roots aren't equal when
// adding due to races)
// TODO: exit on error if super_vertices not decremented
// Execute parallel for to jump pointers
thrust::copy_n(policy, new_roots, P->n_vertices, roots);
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
jump_pointers_parallel, // lambda function
context // context
);
thrust::copy_n(policy, new_roots, P->n_vertices, roots);
}
virtual bool is_converged(cuda::multi_context_t& context) {
//if (this->iteration > 0) {
// return true;
//}
//return false;
auto P = this->get_problem();
return (P->super_vertices[0] == 1);
}
};
template <typename graph_t>
float run(
graph_t& G,
typename graph_t::weight_type* mst_weight, // Output
// Context for application (eg, GPU + CUDA stream it will be
// executed on)
std::shared_ptr<cuda::multi_context_t> context =
std::shared_ptr<cuda::multi_context_t>(new cuda::multi_context_t(0))) {
using vertex_t = typename graph_t::vertex_type;
using weight_t = typename graph_t::weight_type;
// instantiate `param` and `result` templates
using param_type = param_t<vertex_t>;
using result_type = result_t<vertex_t, weight_t>;
// initialize `param` and `result` w/ the appropriate parameters / data
// structures
param_type param;
result_type result(mst_weight);
// <boilerplate> This code probably should be the same across all
// applications, unless maybe you're doing something like multi-gpu /
// concurrent function calls
// instantiate `problem` and `enactor` templates.
using problem_type = problem_t<graph_t, param_type, result_type>;
using enactor_type = enactor_t<problem_type>;
// initialize problem; call `init` and `reset` to prepare data structures
problem_type problem(G, param, result, context);
problem.init();
// problem.reset();
// initialize enactor; call enactor, returning GPU elapsed time
enactor_type enactor(&problem, context);
return enactor.enact();
// </boilerplate>
}
} // namespace mst
} // namespace gunrock<commit_msg>printing etc<commit_after>#pragma once
#include <gunrock/algorithms/algorithms.hxx>
using vertex_t = int;
using edge_t = int;
using weight_t = float;
namespace gunrock {
namespace mst {
template <typename vertex_t>
struct param_t {
// No parameters for this algorithm
};
template <typename vertex_t, typename weight_t>
struct result_t {
weight_t* mst_weight;
result_t(weight_t* _mst_weight) : mst_weight(_mst_weight) {}
};
// <boilerplate>
template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
param_type param;
result_type result;
problem_t(graph_t& G,
param_type& _param,
result_type& _result,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::problem_t<graph_t>(G, _context),
param(_param),
result(_result) {}
using vertex_t = typename graph_t::vertex_type;
using edge_t = typename graph_t::edge_type;
using weight_t = typename graph_t::weight_type;
// </boilerplate>
graph_t g = this->get_graph();
int n_vertices = g.get_number_of_vertices();
thrust::device_vector<vertex_t> roots;
thrust::device_vector<vertex_t> new_roots;
thrust::device_vector<weight_t> min_weights;
thrust::device_vector<int> mst_edges;
thrust::device_vector<int> super_vertices;
thrust::device_vector<int> min_neighbors;
void init() {
cudaDeviceSetLimit(cudaLimitPrintfFifoSize, 1073741824);
auto policy = this->context->get_context(0)->execution_policy();
roots.resize(n_vertices);
new_roots.resize(n_vertices);
min_weights.resize(n_vertices);
min_neighbors.resize(n_vertices);
mst_edges.resize(1);
super_vertices.resize(1);
auto d_mst_weight = thrust::device_pointer_cast(this->result.mst_weight);
thrust::fill(policy, min_weights.begin(), min_weights.end(),
std::numeric_limits<weight_t>::max());
thrust::fill(policy, d_mst_weight, d_mst_weight + 1, 0);
thrust::fill(policy, min_neighbors.begin(), min_neighbors.end(), -1);
thrust::sequence(policy, roots.begin(), roots.end(), 0);
thrust::sequence(policy, new_roots.begin(), new_roots.end(), 0);
thrust::sequence(policy, super_vertices.begin(), super_vertices.end(),
n_vertices);
}
void reset() {
// TODO: reset
return;
}
};
// <boilerplate>
template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
enactor_t(problem_t* _problem,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::enactor_t<problem_t>(_problem, _context) {}
using vertex_t = typename problem_t::vertex_t;
using edge_t = typename problem_t::edge_t;
using weight_t = typename problem_t::weight_t;
using frontier_t = typename enactor_t<problem_t>::frontier_t;
// </boilerplate>
// How to initialize the frontier at the beginning of the application.
void prepare_frontier(frontier_t* f,
cuda::multi_context_t& context) override {
// get pointer to the problem
auto P = this->get_problem();
auto n_vertices = P->get_graph().get_number_of_vertices();
auto n_edges = P->get_graph().get_number_of_edges();
// Fill the frontier with a sequence of vertices from 0 -> n_vertices.
f->sequence((edge_t)0, n_edges, context.get_context(0)->stream());
}
// One iteration of the application
void loop(cuda::multi_context_t& context) override {
auto E = this->get_enactor();
auto P = this->get_problem();
auto G = P->get_graph();
auto mst_weight = P->result.mst_weight;
auto mst_edges = P->mst_edges.data().get();
auto super_vertices = P->super_vertices.data().get();
auto min_neighbors = P->min_neighbors.data().get();
auto roots = P->roots.data().get();
auto new_roots = P->new_roots.data().get();
auto min_weights = P->min_weights.data().get();
auto policy = this->context->get_context(0)->execution_policy();
thrust::fill_n(policy, min_weights, P->n_vertices,
std::numeric_limits<weight_t>::max());
thrust::fill_n(policy, min_neighbors, P->n_vertices, -1);
// Find minimum weight for each vertex
// TODO: update for multi-directional edges?
auto get_min_weights = [min_weights, roots, G] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto neighbor = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// If they are already part of same super vertex, do not check
if (roots[source] != roots[neighbor]) {
// Store minimum weight
auto old_weight =
math::atomic::min(&(min_weights[roots[source]]), weight);
// printf(
// "1: source %i roots[source] %i weight %f min weight %f weight < "
// "old weight %i\n",
// source, roots[source], weight, min_weights[roots[source]],
// weight < old_weight);
return weight < old_weight;
}
return false;
};
auto get_min_neighbors =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto weight = G.get_edge_weight(e);
if (weight == min_weights[roots[source]]) {
auto old_val = math::atomic::max(&min_neighbors[roots[source]], e);
if (old_val < e) {
return true;
}
}
return false;
};
// just used for graph
auto remove_ties =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto dest = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// printf("source %i dest %i weight %f\n", source, dest, weight);
if (e == min_neighbors[roots[source]]) {
return true;
}
return false;
};
// just used for graph
auto remove_dups =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto dest = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
if (source < dest ||
G.get_destination_vertex(min_neighbors[roots[dest]]) != source ||
G.get_source_vertex(min_neighbors[roots[dest]]) != dest) {
return true;
}
return false;
};
auto print_weights =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> bool {
auto source = G.get_source_vertex(e);
auto dest = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
printf("%i,%i,%f\n", int(source), int(dest), float(weight));
return true;
};
// Add weights to MST
auto add_to_mst = [G, roots, mst_weight, mst_edges, super_vertices,
min_neighbors, min_weights, new_roots] __host__
__device__(vertex_t const& v) -> void {
if (min_weights[v] != std::numeric_limits<weight_t>::max()) {
auto source = G.get_source_vertex(min_neighbors[v]);
auto dest = G.get_destination_vertex(min_neighbors[v]);
auto weight = min_weights[v];
// TODO: technically there is a race between reads/writes to
// new_roots[dest];
if (source < dest ||
G.get_destination_vertex(min_neighbors[roots[dest]]) != source ||
G.get_source_vertex(min_neighbors[roots[dest]]) != dest) {
// printf("v %i\n", source);
// printf("u %i\n", dest);
// printf("add mst v %i\n", v);
// printf("add mst u %i\n", u);
// printf("add mst v root %i\n", roots[v]);
// printf("add mst u root %i\n", roots[u]);
// Not sure cycle comparison for inc/dec vs add; using atomic::add for
// now because it is in our math.hxx
math::atomic::add(&mst_weight[0], weight);
// printf("%i,%i,%f\n", source, dest, weight);
// printf("GPU mst weight %f\n", mst_weight[0]);
math::atomic::add(&mst_edges[0], 1);
// printf("GPU mst edges %i\n", mst_edges[0]);
math::atomic::add(&super_vertices[0], -1);
// printf("super vertices %i\n", super_vertices[0]);
atomicExch((&new_roots[v]), new_roots[dest]);
return;
}
}
};
// Jump pointers in parallel for
// read and write from different copies of roots to resolve races
auto jump_pointers_parallel =
[roots, new_roots] __host__ __device__(vertex_t const& v) -> void {
vertex_t u = roots[v];
while (roots[u] != u) {
u = roots[u];
}
new_roots[v] = u;
return;
};
// Execute advance operator to get min weights
auto in_frontier = &(this->frontiers[0]);
auto out_frontier = &(this->frontiers[1]);
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, get_min_weights, in_frontier, out_frontier, context);
// Execute filter operator to get min neighbors
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, get_min_neighbors, out_frontier, out_frontier, context);
// Execute filter operator to remove ties from frontier
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, remove_ties, out_frontier, out_frontier, context);
// Execute filter operator to remove duplicates from frontier
operators::filter::execute<operators::filter_algorithm_t::remove>(
G, remove_dups, out_frontier, out_frontier, context);
// Execute parallel for operator to print weights
operators::parallel_for::execute<operators::parallel_for_each_t::element>(
*out_frontier, print_weights, context);
// Execute parallel for to add weights to MST
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
add_to_mst, // lambda function
context // context
);
// Print frontier
//(&(this->frontiers[1]))->print();
// TODO: exit on error if super_vertices not decremented
// Execute parallel for to jump pointers
thrust::copy_n(policy, new_roots, P->n_vertices, roots);
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
jump_pointers_parallel, // lambda function
context // context
);
thrust::copy_n(policy, new_roots, P->n_vertices, roots);
}
virtual bool is_converged(cuda::multi_context_t& context) {
// if (this->iteration > 0) {
// return true;
//}
// return false;
auto P = this->get_problem();
return (P->super_vertices[0] == 1);
}
};
template <typename graph_t>
float run(
graph_t& G,
typename graph_t::weight_type* mst_weight, // Output
// Context for application (eg, GPU + CUDA stream it will be
// executed on)
std::shared_ptr<cuda::multi_context_t> context =
std::shared_ptr<cuda::multi_context_t>(new cuda::multi_context_t(0))) {
using vertex_t = typename graph_t::vertex_type;
using weight_t = typename graph_t::weight_type;
// instantiate `param` and `result` templates
using param_type = param_t<vertex_t>;
using result_type = result_t<vertex_t, weight_t>;
// initialize `param` and `result` w/ the appropriate parameters / data
// structures
param_type param;
result_type result(mst_weight);
// <boilerplate> This code probably should be the same across all
// applications, unless maybe you're doing something like multi-gpu /
// concurrent function calls
// instantiate `problem` and `enactor` templates.
using problem_type = problem_t<graph_t, param_type, result_type>;
using enactor_type = enactor_t<problem_type>;
// initialize problem; call `init` and `reset` to prepare data structures
problem_type problem(G, param, result, context);
problem.init();
// problem.reset();
// initialize enactor; call enactor, returning GPU elapsed time
enactor_type enactor(&problem, context);
return enactor.enact();
// </boilerplate>
}
} // namespace mst
} // namespace gunrock<|endoftext|>
|
<commit_before>#ifndef H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_EXCEPTION_HPP
#define H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_EXCEPTION_HPP
#include "internal/common.hpp"
#include <QCoreApplication>
#include <QException>
namespace cutehmi {
/**
* %Exception.
*/
class CUTEHMI_API Exception:
public QException
{
Q_DECLARE_TR_FUNCTIONS(cutehmi::Exception) // This macro ends with "private:" specifier :o !!!
public:
Exception(const QString & what);
void raise() const noexcept(false) override;
Exception * clone() const override;
const char * what() const noexcept override;
private:
QByteArray m_whatArr;
};
}
#endif
//(c)MP: Copyright © 2018, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<commit_msg>Make constructor explicit.<commit_after>#ifndef H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_EXCEPTION_HPP
#define H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_EXCEPTION_HPP
#include "internal/common.hpp"
#include <QCoreApplication>
#include <QException>
namespace cutehmi {
/**
* %Exception.
*/
class CUTEHMI_API Exception:
public QException
{
Q_DECLARE_TR_FUNCTIONS(cutehmi::Exception) // This macro ends with "private:" specifier :o !!!
public:
explicit Exception(const QString & what);
void raise() const noexcept(false) override;
Exception * clone() const override;
const char * what() const noexcept override;
private:
QByteArray m_whatArr;
};
}
#endif
//(c)MP: Copyright © 2018, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_CVS_GRAMMAR_HPP
#define MAPNIK_CVS_GRAMMAR_HPP
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace mapnik {
namespace qi = boost::spirit::qi;
using csv_value = std::string;
using csv_line = std::vector<csv_value>;
using csv_data = std::vector<csv_line>;
template <typename Iterator>
struct csv_line_grammar : qi::grammar<Iterator, csv_line(std::string const&), qi::blank_type>
{
csv_line_grammar() : csv_line_grammar::base_type(line)
{
using namespace qi;
qi::_a_type _a;
qi::_r1_type _r1;
qi::lit_type lit;
//qi::eol_type eol;
qi::_1_type _1;
qi::char_type char_;
qi::omit_type omit;
unesc_char.add
("\\a", '\a')
("\\b", '\b')
("\\f", '\f')
("\\n", '\n')
("\\r", '\r')
("\\t", '\t')
("\\v", '\v')
("\\\\",'\\')
("\\\'", '\'')
("\\\"", '\"')
("\"\"", '\"') // double quote
;
line = column(_r1) % char_(_r1)
;
column = quoted | *(char_ - (lit(_r1) /*| eol*/))
;
quoted = omit[char_("\"'")[_a = _1]] > text(_a) > -lit(_a)
;
text = *(unesc_char | (char_ - char_(_r1)))
;
BOOST_SPIRIT_DEBUG_NODES((line)(column)(quoted));
}
private:
qi::rule<Iterator, csv_line(std::string const&), qi::blank_type> line;
qi::rule<Iterator, csv_value(std::string const&)> column; // no-skip
qi::rule<Iterator, csv_value(char)> text;
qi::rule<Iterator, qi::locals<char>, csv_value()> quoted;
qi::symbols<char const, char const> unesc_char;
};
template <typename Iterator>
struct csv_file_grammar : qi::grammar<Iterator, csv_data(std::string const&), qi::blank_type>
{
csv_file_grammar() : csv_file_grammar::base_type(start)
{
using namespace qi;
qi::eol_type eol;
qi::_r1_type _r1;
start = -line(_r1) % eol
;
BOOST_SPIRIT_DEBUG_NODES((start));
}
private:
qi::rule<Iterator, csv_data(std::string const&), qi::blank_type> start;
csv_line_grammar<Iterator> line;
};
}
#endif // MAPNIK_CVS_GRAMMAR_HPP
<commit_msg>CSV grammar : skip leading `\n` and/or `\r` which result from std::getline used with non-native line endings The goal is to support LF, CR and CRLF on all platforms.<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_CVS_GRAMMAR_HPP
#define MAPNIK_CVS_GRAMMAR_HPP
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace mapnik {
namespace qi = boost::spirit::qi;
using csv_value = std::string;
using csv_line = std::vector<csv_value>;
using csv_data = std::vector<csv_line>;
template <typename Iterator>
struct csv_line_grammar : qi::grammar<Iterator, csv_line(std::string const&), qi::blank_type>
{
csv_line_grammar() : csv_line_grammar::base_type(line)
{
using namespace qi;
qi::_a_type _a;
qi::_r1_type _r1;
qi::lit_type lit;
//qi::eol_type eol;
qi::_1_type _1;
qi::char_type char_;
qi::omit_type omit;
unesc_char.add
("\\a", '\a')
("\\b", '\b')
("\\f", '\f')
("\\n", '\n')
("\\r", '\r')
("\\t", '\t')
("\\v", '\v')
("\\\\",'\\')
("\\\'", '\'')
("\\\"", '\"')
("\"\"", '\"') // double quote
;
line = column(_r1) % char_(_r1)
;
column = -omit[char_("\n\r")] >> quoted | *(char_ - (lit(_r1) /*| eol*/))
;
quoted = omit[char_("\"'")[_a = _1]] > text(_a) > -lit(_a)
;
text = *(unesc_char | (char_ - char_(_r1)))
;
BOOST_SPIRIT_DEBUG_NODES((line)(column)(quoted));
}
private:
qi::rule<Iterator, csv_line(std::string const&), qi::blank_type> line;
qi::rule<Iterator, csv_value(std::string const&)> column; // no-skip
qi::rule<Iterator, csv_value(char)> text;
qi::rule<Iterator, qi::locals<char>, csv_value()> quoted;
qi::symbols<char const, char const> unesc_char;
};
template <typename Iterator>
struct csv_file_grammar : qi::grammar<Iterator, csv_data(std::string const&), qi::blank_type>
{
csv_file_grammar() : csv_file_grammar::base_type(start)
{
using namespace qi;
qi::eol_type eol;
qi::_r1_type _r1;
start = -line(_r1) % eol
;
BOOST_SPIRIT_DEBUG_NODES((start));
}
private:
qi::rule<Iterator, csv_data(std::string const&), qi::blank_type> start;
csv_line_grammar<Iterator> line;
};
}
#endif // MAPNIK_CVS_GRAMMAR_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3dcommn.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:24:44 $
*
* 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 _B3D_B3DCOMMN_HXX
#define _B3D_B3DCOMMN_HXX
#ifndef _B3D_BASE3D_HXX
#include "base3d.hxx"
#endif
#ifndef _B3D_B3DGEOM_HXX
#include "b3dgeom.hxx"
#endif
// Defines fuer clipping flags (nFlag0,1)
#define CLIPFLAG_LEFT 0x0001
#define CLIPFLAG_RIGHT 0x0002
#define CLIPFLAG_BOTTOM 0x0004
#define CLIPFLAG_TOP 0x0008
#define CLIPFLAG_FRONT 0x0010
#define CLIPFLAG_BACK 0x0020
#define CLIPFLAG_ALL (CLIPFLAG_LEFT|CLIPFLAG_RIGHT| \
CLIPFLAG_BOTTOM|CLIPFLAG_TOP| \
CLIPFLAG_FRONT|CLIPFLAG_BACK)
/*************************************************************************
|*
|* Bucket fuer Indices
|*
\************************************************************************/
BASE3D_DECL_BUCKET(UINT32, Bucket)
/*************************************************************************
|*
|* Die Basisklasse fuer Standard 3D Ausgaben auf StarView Basis
|*
\************************************************************************/
#define BUFFER_OVERHEAD (20)
class Base3DCommon : public Base3D
{
protected:
// Buffers fuer temporaere geometrische Daten
B3dEntityBucket aBuffers;
// Remember if last primitive was rejected
BOOL bLastPrimitiveRejected : 1;
// #93184# flag for polygon normal direction
BOOL bNormalPointsAway : 1;
public:
Base3DCommon(OutputDevice* pOutDev);
virtual ~Base3DCommon();
// Beleuchtung setzen/lesen
virtual void SetLightGroup(B3dLightGroup* pSet, BOOL bSetGlobal=TRUE);
// Info if last primitive was rejected
BOOL WasLastPrimitiveRejected()
{ return bLastPrimitiveRejected; }
// Szenenverwaltung
virtual void StartScene();
virtual void EndScene();
protected:
// Geometrische Daten uebergeben
virtual B3dEntity& ImplGetFreeEntity();
virtual void ImplStartPrimitive();
virtual void ImplEndPrimitive();
virtual void ImplPostAddVertex(B3dEntity& rEnt);
void Create3DPoint(UINT32 nInd);
void Create3DPointClipped(UINT32 nInd);
void Create3DLine(UINT32 nInd1, UINT32 nInd2);
void Create3DLineClipped(UINT32 nInd1, UINT32 nInd2);
void Create3DTriangle(UINT32 nInd1, UINT32 nInd2, UINT32 nInd3);
virtual void Clipped3DPoint(UINT32 nInd) = 0;
virtual void Clipped3DLine(UINT32 nInd1,UINT32 nInd2) = 0;
virtual void Clipped3DTriangle(UINT32 nInd1,UINT32 nInd2, UINT32 nInd3) = 0;
// clipping functions
BOOL AreEqual(UINT32 nInd1, UINT32 nInd2);
BOOL Clip3DPoint(UINT32 nInd);
BOOL Clip3DLine(UINT32& nInd1,UINT32& nInd2);
BOOL Clip3DPolygon(UINT32Bucket& rEdgeIndex);
UINT16 GetClipFlags(UINT32 nInd);
BOOL IsInside(UINT32 nInd, UINT32 nDim, BOOL bLow);
void ClipPoly(UINT32Bucket& rEdgeIndex, UINT16 nDim,BOOL bLow);
void CalcNewPoint(UINT32 nNew,UINT32 nHigh,UINT32 nLow,
UINT16 nDim, double fBound);
// Beleuchtungsmodell (ColorModel) in einem Punkt loesen
// Punkt MUSS in ClipCoordinates vorliegen !
void SolveColorModel(B3dColor&, Vector3D&, const Vector3D&);
B3dColor SolveColorModel(B3dMaterial& rMat, Vector3D& rVec,
const Vector3D& rPnt);
// Beleuchtungsmodell (ColorModel) fuer eine Lichtquelle loesen
B3dColor SolveColorModel(B3dLight& rLight, B3dMaterial& rMat,
Vector3D& rVec, const Vector3D& rPnt);
};
#endif // _B3D_B3DCOMMN_HXX
<commit_msg>INTEGRATION: CWS aw024 (1.2.236); FILE MERGED 2006/10/27 12:15:40 aw 1.2.236.3: #i39528# ::basegfx -> basegfx adaption 2005/09/20 04:17:21 aw 1.2.236.2: RESYNC: (1.2-1.3); FILE MERGED 2005/04/26 14:51:21 aw 1.2.236.1: #i39528#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3dcommn.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 16:06:20 $
*
* 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 _B3D_B3DCOMMN_HXX
#define _B3D_B3DCOMMN_HXX
#ifndef _B3D_BASE3D_HXX
#include "base3d.hxx"
#endif
#ifndef _B3D_B3DGEOM_HXX
#include "b3dgeom.hxx"
#endif
// Defines fuer clipping flags (nFlag0,1)
#define CLIPFLAG_LEFT 0x0001
#define CLIPFLAG_RIGHT 0x0002
#define CLIPFLAG_BOTTOM 0x0004
#define CLIPFLAG_TOP 0x0008
#define CLIPFLAG_FRONT 0x0010
#define CLIPFLAG_BACK 0x0020
#define CLIPFLAG_ALL (CLIPFLAG_LEFT|CLIPFLAG_RIGHT| \
CLIPFLAG_BOTTOM|CLIPFLAG_TOP| \
CLIPFLAG_FRONT|CLIPFLAG_BACK)
/*************************************************************************
|*
|* Bucket fuer Indices
|*
\************************************************************************/
BASE3D_DECL_BUCKET(sal_uInt32, Bucket)
/*************************************************************************
|*
|* Die Basisklasse fuer Standard 3D Ausgaben auf StarView Basis
|*
\************************************************************************/
#define BUFFER_OVERHEAD (20)
class Base3DCommon : public Base3D
{
protected:
// Buffers fuer temporaere geometrische Daten
B3dEntityBucket aBuffers;
// Remember if last primitive was rejected
unsigned bLastPrimitiveRejected : 1;
// #93184# flag for polygon normal direction
unsigned bNormalPointsAway : 1;
public:
Base3DCommon(OutputDevice* pOutDev);
virtual ~Base3DCommon();
// Beleuchtung setzen/lesen
virtual void SetLightGroup(B3dLightGroup* pSet, sal_Bool bSetGlobal=sal_True);
// Info if last primitive was rejected
sal_Bool WasLastPrimitiveRejected()
{ return bLastPrimitiveRejected; }
// Szenenverwaltung
virtual void StartScene();
virtual void EndScene();
protected:
// Geometrische Daten uebergeben
virtual B3dEntity& ImplGetFreeEntity();
virtual void ImplStartPrimitive();
virtual void ImplEndPrimitive();
virtual void ImplPostAddVertex(B3dEntity& rEnt);
void Create3DPoint(sal_uInt32 nInd);
void Create3DPointClipped(sal_uInt32 nInd);
void Create3DLine(sal_uInt32 nInd1, sal_uInt32 nInd2);
void Create3DLineClipped(sal_uInt32 nInd1, sal_uInt32 nInd2);
void Create3DTriangle(sal_uInt32 nInd1, sal_uInt32 nInd2, sal_uInt32 nInd3);
virtual void Clipped3DPoint(sal_uInt32 nInd) = 0;
virtual void Clipped3DLine(sal_uInt32 nInd1,sal_uInt32 nInd2) = 0;
virtual void Clipped3DTriangle(sal_uInt32 nInd1,sal_uInt32 nInd2, sal_uInt32 nInd3) = 0;
// clipping functions
sal_Bool AreEqual(sal_uInt32 nInd1, sal_uInt32 nInd2);
sal_Bool Clip3DPoint(sal_uInt32 nInd);
sal_Bool Clip3DLine(sal_uInt32& nInd1,sal_uInt32& nInd2);
sal_Bool Clip3DPolygon(sal_uInt32Bucket& rEdgeIndex);
sal_uInt16 GetClipFlags(sal_uInt32 nInd);
sal_Bool IsInside(sal_uInt32 nInd, sal_uInt32 nDim, sal_Bool bLow);
void ClipPoly(sal_uInt32Bucket& rEdgeIndex, sal_uInt16 nDim,sal_Bool bLow);
void CalcNewPoint(sal_uInt32 nNew,sal_uInt32 nHigh,sal_uInt32 nLow,
sal_uInt16 nDim, double fBound);
// Beleuchtungsmodell (ColorModel) in einem Punkt loesen
// Punkt MUSS in ClipCoordinates vorliegen !
void SolveColorModel(B3dColor& rCol, basegfx::B3DVector& rVec, const basegfx::B3DPoint& rPnt);
B3dColor SolveColorModel(B3dMaterial& rMat, basegfx::B3DVector& rVec, const basegfx::B3DPoint& rPnt);
// Beleuchtungsmodell (ColorModel) fuer eine Lichtquelle loesen
B3dColor SolveColorModel(B3dLight& rLight, B3dMaterial& rMat, basegfx::B3DVector& rVec, const basegfx::B3DPoint& rPnt);
};
#endif // _B3D_B3DCOMMN_HXX
<|endoftext|>
|
<commit_before>/*
* linker32.cpp
*
* Created on: Jul 23, 2014
* Author: Pimenta
*/
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <set>
#include <map>
#include <string>
using namespace std;
typedef uint32_t uword_t;
#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif
#ifndef WORD_WIDTH
#define WORD_WIDTH 32
#endif
struct ObjectFile32 {
uword_t offset;
map<string, uword_t> exported;
map<string, set<uword_t>> imported;
set<uword_t> relative;
uword_t mem_size;
uword_t* mem;
~ObjectFile32() {
delete[] mem;
}
void setStarter() {
offset = 0;
imported["start"].emplace(2);
relative.emplace(0);
relative.emplace(1);
relative.emplace(2);
mem_size = 4;
mem = new uword_t[4];
mem[0] = 3;
mem[1] = 3;
mem[2] = 0;
mem[3] = 0;
}
void read(const char* fn, uword_t offs) {
offset = offs;
fstream f(fn, fstream::in | fstream::binary);
uword_t tmp;
// read number of exported symbols
f.read((char*)&tmp, sizeof(uword_t));
// read exported symbols
for (uword_t i = 0; i < tmp; ++i) {
string sym;
uword_t addr;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
// address
f.read((char*)&addr, sizeof(uword_t));
exported[sym] = addr;
}
// read number of symbols of pending references
f.read((char*)&tmp, sizeof(uword_t));
// read symbols of pending references
for (uword_t i = 0; i < tmp; ++i) {
string sym;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
uword_t tmp2;
// read number of references to current symbol
f.read((char*)&tmp2, sizeof(uword_t));
// read references to current symbol
for (uword_t j = 0; j < tmp2; ++j) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
imported[sym].emplace(addr);
}
}
// read number of relative addresses
f.read((char*)&tmp, sizeof(uword_t));
// read relative addresses
for (uword_t i = 0; i < tmp; ++i) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
relative.emplace(addr);
}
// read assembled code size
f.read((char*)&mem_size, sizeof(uword_t));
// read assembled code
mem = new uword_t[mem_size];
f.read((char*)mem, sizeof(uword_t)*mem_size);
f.close();
}
};
int linker32(int argc, char* argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage mode: subleq-ld <object_files...> <meminit_file>\n");
return 0;
}
bool executable = string(argv[1]) == "-exec";
// read object files
ObjectFile32 files[argc - 2];
if (executable) {
files[0].setStarter();
}
else {
files[0].read(argv[1], 0);
}
for (int i = 1; i < argc - 2; ++i) {
files[i].read(argv[i + 1], files[i - 1].offset + files[i - 1].mem_size);
}
uword_t mem_size = 0;
uword_t* mem = new uword_t[MEM_WORDS];
map<string, uword_t> symbols;
map<string, set<uword_t>> references;
set<uword_t> relatives;
for (auto& file : files) {
// assemble global symbol table
for (auto& sym : file.exported) {
symbols[sym.first] = sym.second + file.offset;
}
// assemble global reference table
for (auto& sym : file.imported) {
set<uword_t>& refs = references[sym.first];
for (auto addr : sym.second) {
refs.emplace(addr + file.offset);
}
}
// assemble global relative address table
for (auto addr : file.relative) {
relatives.emplace(addr + file.offset);
file.mem[addr] += file.offset; // relocating
}
// copy object code
memcpy(&mem[mem_size], file.mem, file.mem_size*sizeof(uword_t));
mem_size += file.mem_size;
}
// solve references
for (auto ref = references.begin(); ref != references.end();) {
auto sym = symbols.find(ref->first);
if (sym == symbols.end()) {
ref++;
}
else {
for (auto addr : ref->second) {
mem[addr] = sym->second;
}
references.erase(ref++);
}
}
// output
fstream f(argv[argc - 1], fstream::out | fstream::binary);
uword_t tmp;
// write number of exported symbols
tmp = symbols.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write exported symbols
for (auto& sym : symbols) {
// string
f.write(sym.first.c_str(), sym.first.size() + 1);
// address
tmp = sym.second;
f.write((const char*)&tmp, sizeof(uword_t));
}
// write number of symbols of pending references
tmp = references.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write symbols of pending references
for (auto& sym : references) {
// string
f.write(sym.first.c_str(), sym.first.size() + 1);
// write number of references to current symbol
tmp = sym.second.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write references to current symbol
for (auto ref : sym.second) {
tmp = ref;
f.write((const char*)&tmp, sizeof(uword_t));
}
}
// write number of relative addresses
tmp = relatives.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write relative addresses
for (auto addr : relatives) {
tmp = addr;
f.write((const char*)&tmp, sizeof(uword_t));
}
// write assembled code size
f.write((const char*)&mem_size, sizeof(uword_t));
// write assembled code
f.write((const char*)mem, sizeof(uword_t)*mem_size);
f.close();
// output mif
f.open((string(argv[argc - 1]) + ".mif").c_str(), fstream::out);
char buf[20];
f << "DEPTH = " << MEM_WORDS << ";\n";
f << "WIDTH = " << WORD_WIDTH << ";\n";
f << "ADDRESS_RADIX = HEX;\n";
f << "DATA_RADIX = HEX;\n";
f << "CONTENT\n";
f << "BEGIN\n";
f << "\n";
for (uword_t i = 0; i < mem_size; ++i) {
sprintf(buf, "%08x", i);
f << buf;
sprintf(buf, "%08x", mem[i]);
f << " : " << buf << ";\n";
}
f << "\n";
f << "END;\n";
f.close();
delete[] mem;
return 0;
}
<commit_msg>Now the linker relocates only resolved addresses<commit_after>/*
* linker32.cpp
*
* Created on: Jul 23, 2014
* Author: Pimenta
*/
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <set>
#include <map>
#include <string>
using namespace std;
typedef uint32_t uword_t;
#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif
#ifndef WORD_WIDTH
#define WORD_WIDTH 32
#endif
struct ObjectFile32 {
uword_t offset;
map<string, uword_t> exported;
map<string, set<uword_t>> imported;
set<uword_t> relative;
uword_t mem_size;
uword_t* mem;
~ObjectFile32() {
delete[] mem;
}
void setStarter() {
offset = 0;
imported["start"].emplace(2);
relative.emplace(0);
relative.emplace(1);
relative.emplace(2);
mem_size = 4;
mem = new uword_t[4];
mem[0] = 3;
mem[1] = 3;
mem[2] = 0;
mem[3] = 0;
}
void read(const char* fn, uword_t offs) {
offset = offs;
fstream f(fn, fstream::in | fstream::binary);
uword_t tmp;
// read number of exported symbols
f.read((char*)&tmp, sizeof(uword_t));
// read exported symbols
for (uword_t i = 0; i < tmp; ++i) {
string sym;
uword_t addr;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
// address
f.read((char*)&addr, sizeof(uword_t));
exported[sym] = addr;
}
// read number of symbols of pending references
f.read((char*)&tmp, sizeof(uword_t));
// read symbols of pending references
for (uword_t i = 0; i < tmp; ++i) {
string sym;
// string
{
char c;
f.read(&c, sizeof(char));
while (c != '\0') {
sym += c;
f.read(&c, sizeof(char));
}
}
uword_t tmp2;
// read number of references to current symbol
f.read((char*)&tmp2, sizeof(uword_t));
// read references to current symbol
for (uword_t j = 0; j < tmp2; ++j) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
imported[sym].emplace(addr);
}
}
// read number of relative addresses
f.read((char*)&tmp, sizeof(uword_t));
// read relative addresses
for (uword_t i = 0; i < tmp; ++i) {
uword_t addr;
f.read((char*)&addr, sizeof(uword_t));
relative.emplace(addr);
}
// read assembled code size
f.read((char*)&mem_size, sizeof(uword_t));
// read assembled code
mem = new uword_t[mem_size];
f.read((char*)mem, sizeof(uword_t)*mem_size);
f.close();
}
};
int linker32(int argc, char* argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage mode: subleq-ld <object_files...> <meminit_file>\n");
return 0;
}
bool executable = string(argv[1]) == "-exec";
// read object files
ObjectFile32 files[argc - 2];
if (executable) {
files[0].setStarter();
}
else {
files[0].read(argv[1], 0);
}
for (int i = 1; i < argc - 2; ++i) {
files[i].read(argv[i + 1], files[i - 1].offset + files[i - 1].mem_size);
}
uword_t mem_size = 0;
uword_t* mem = new uword_t[MEM_WORDS];
map<string, uword_t> symbols;
map<string, set<uword_t>> references;
set<uword_t> relatives;
for (auto& file : files) {
// assemble global symbol table
for (auto& sym : file.exported) {
symbols[sym.first] = sym.second + file.offset;
}
// assemble global reference table
set<uword_t> pendingReferences;
for (auto& sym : file.imported) {
set<uword_t>& refs = references[sym.first];
for (auto addr : sym.second) {
refs.emplace(addr + file.offset);
pendingReferences.emplace(addr);
}
}
// assemble global relative address table
for (auto addr : file.relative) {
relatives.emplace(addr + file.offset);
// relocate only resolved addresses
if (pendingReferences.find(addr) == pendingReferences.end()) {
file.mem[addr] += file.offset;
}
}
// copy object code
memcpy(&mem[mem_size], file.mem, file.mem_size*sizeof(uword_t));
mem_size += file.mem_size;
}
// resolve references
for (auto ref = references.begin(); ref != references.end();) {
auto sym = symbols.find(ref->first);
if (sym == symbols.end()) {
ref++;
}
else {
for (auto addr : ref->second) {
mem[addr] += sym->second;
}
references.erase(ref++);
}
}
// output
fstream f(argv[argc - 1], fstream::out | fstream::binary);
uword_t tmp;
// write number of exported symbols
tmp = symbols.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write exported symbols
for (auto& sym : symbols) {
// string
f.write(sym.first.c_str(), sym.first.size() + 1);
// address
tmp = sym.second;
f.write((const char*)&tmp, sizeof(uword_t));
}
// write number of symbols of pending references
tmp = references.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write symbols of pending references
for (auto& sym : references) {
// string
f.write(sym.first.c_str(), sym.first.size() + 1);
// write number of references to current symbol
tmp = sym.second.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write references to current symbol
for (auto ref : sym.second) {
tmp = ref;
f.write((const char*)&tmp, sizeof(uword_t));
}
}
// write number of relative addresses
tmp = relatives.size();
f.write((const char*)&tmp, sizeof(uword_t));
// write relative addresses
for (auto addr : relatives) {
tmp = addr;
f.write((const char*)&tmp, sizeof(uword_t));
}
// write assembled code size
f.write((const char*)&mem_size, sizeof(uword_t));
// write assembled code
f.write((const char*)mem, sizeof(uword_t)*mem_size);
f.close();
// output mif
f.open((string(argv[argc - 1]) + ".mif").c_str(), fstream::out);
char buf[20];
f << "DEPTH = " << MEM_WORDS << ";\n";
f << "WIDTH = " << WORD_WIDTH << ";\n";
f << "ADDRESS_RADIX = HEX;\n";
f << "DATA_RADIX = HEX;\n";
f << "CONTENT\n";
f << "BEGIN\n";
f << "\n";
for (uword_t i = 0; i < mem_size; ++i) {
sprintf(buf, "%08x", i);
f << buf;
sprintf(buf, "%08x", mem[i]);
f << " : " << buf << ";\n";
}
f << "\n";
f << "END;\n";
f.close();
delete[] mem;
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/gpad:$Id$
// Author: Rene Brun 08/01/2000
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TGuiFactory.h"
#include "TInspectCanvas.h"
#include "TButton.h"
#include "TClass.h"
#include "TLine.h"
#include "TLink.h"
#include "TDataMember.h"
#include "TDataType.h"
#include "TRealData.h"
#include "TLatex.h"
#include "snprintf.h"
ClassImp(TInspectCanvas)
//////////////////////////////////////////////////////////////////////////
// //
// TInspectorObject //
// //
//////////////////////////////////////////////////////////////////////////
class TInspectorObject : public TObject
{
// This class is designed to wrap a Foreign object in order to
// inject it into the Browse sub-system.
public:
TInspectorObject(void *obj, TClass *cl) : fObj(obj),fClass(cl) {};
~TInspectorObject(){;}
void *GetObject() const { return fObj; };
void Inspect() const {
gGuiFactory->CreateInspectorImp(this, 400, 200);
};
TClass *IsA() const { return fClass; }
private:
void *fObj; //! pointer to the foreign object
TClass *fClass; //! pointer to class of the foreign object
};
//______________________________________________________________________________//*-*
//*-* A InspectCanvas is a canvas specialized to inspect Root objects.
//
//Begin_Html
/*
<img src="gif/InspectCanvas.gif">
*/
//End_Html
//
//______________________________________________________________________________
TInspectCanvas::TInspectCanvas() : TCanvas()
{
// InspectCanvas default constructor.
fBackward = 0;
fForward = 0;
fCurObject = 0;
fObjects = 0;
fLogx = kFALSE;
fLogy = kFALSE;
}
//_____________________________________________________________________________
TInspectCanvas::TInspectCanvas(UInt_t ww, UInt_t wh)
: TCanvas("inspect","ROOT Object Inspector",ww,wh)
{
// InspectCanvas constructor.
fBackward = 0;
fForward = 0;
fCurObject = 0;
fObjects = new TList;
fLogx = kFALSE;
fLogy = kFALSE;
}
//______________________________________________________________________________
TInspectCanvas::~TInspectCanvas()
{
// InspectCanvas default destructor.
if (fObjects) {
fObjects->Clear("nodelete");
delete fObjects;
}
}
//______________________________________________________________________________
void TInspectCanvas::InspectObject(TObject *obj)
{
// Dump contents of obj in a graphics canvas.
// Same action as TObject::Dump but in a graphical form.
// In addition pointers to other objects can be followed.
//
// The following picture is the Inspect of a histogram object:
//Begin_Html
/*
<img src="gif/hpxinspect.gif">
*/
//End_Html
Int_t cdate = 0;
Int_t ctime = 0;
UInt_t *cdatime = 0;
Bool_t isdate = kFALSE;
Bool_t isbits = kFALSE;
const Int_t kname = 1;
const Int_t kvalue = 25;
const Int_t ktitle = 37;
const Int_t kline = 1024;
char line[kline];
char *pname;
TClass *cl = obj->IsA();
if (cl == 0) return;
TInspectorObject *proxy=0;
if (!cl->InheritsFrom(TObject::Class())) {
// This is possible only if obj is actually a TInspectorObject
// wrapping a non-TObject.
proxy = (TInspectorObject*)obj;
obj = (TObject*)proxy->GetObject();
}
if (!cl->GetListOfRealData()) cl->BuildRealData(obj);
// Count number of data members in order to resize the canvas
TRealData *rd;
TIter next(cl->GetListOfRealData());
Int_t nreal = cl->GetListOfRealData()->GetSize();
if (nreal == 0) return;
Int_t nrows = 33;
if (nreal+7 > nrows) nrows = nreal+7;
Int_t nh = nrows*15;
Int_t nw = 700;
TVirtualPad *canvas = GetVirtCanvas();
canvas->Clear(); // remove primitives from canvas
canvas->SetCanvasSize(nw, nh); // set new size of drawing area
canvas->Range(0,-3,20,nreal+4);
Float_t xvalue = 5;
Float_t xtitle = 8;
Float_t dy = 1;
Float_t ytext = Float_t(nreal) - 1.5;
Float_t tsize = 0.99/ytext;
if (tsize < 0.02) tsize = 0.02;
if (tsize > 0.03) tsize = 0.03;
// Create text objects
TText tname, tvalue, ttitle;
TText *tval;
tname.SetTextFont(61);
tname.SetTextAngle(0);
tname.SetTextAlign(12);
tname.SetTextColor(1);
tname.SetTextSize(tsize);
tvalue.SetTextFont(61);
tvalue.SetTextAngle(0);
tvalue.SetTextAlign(12);
tvalue.SetTextColor(1);
tvalue.SetTextSize(tsize);
ttitle.SetTextFont(62);
ttitle.SetTextAngle(0);
ttitle.SetTextAlign(12);
ttitle.SetTextColor(1);
ttitle.SetTextSize(tsize);
Float_t x1 = 0.2;
Float_t x2 = 19.8;
Float_t y1 = -0.5;
Float_t y2 = Float_t(nreal) - 0.5;
Float_t y3 = y2 + 1;
Float_t y4 = y3 + 1.5;
Float_t db = 25./GetWh();
Float_t btop = 0.999;
// Draw buttons
fBackward = new TButton("backward","TInspectCanvas::GoBackward();",.01,btop-db,.15,btop);
fBackward->Draw();
fBackward->SetToolTipText("Inspect previous object");
fForward = new TButton("forward", "TInspectCanvas::GoForward();", .21,btop-db,.35,btop);
fForward->Draw();
fForward->SetToolTipText("Inspect next object");
// Draw surrounding box and title areas
TLine frame;
frame.SetLineColor(1);
frame.SetLineStyle(1);
frame.SetLineWidth(1);
frame.DrawLine(x1, y1, x2, y1);
frame.DrawLine(x2, y1, x2, y4);
frame.DrawLine(x2, y4, x1, y4);
frame.DrawLine(x1, y4, x1, y1);
frame.DrawLine(x1, y2, x2, y2);
frame.DrawLine(x1, y3, x2, y3);
frame.DrawLine(xvalue, y1, xvalue, y3);
frame.DrawLine(xtitle, y1, xtitle, y3);
ttitle.SetTextSize(0.8*tsize);
ttitle.SetTextAlign(21);
ttitle.DrawText(0.5*(x1+xvalue), y2+0.1, "Member Name");
ttitle.DrawText(0.5*(xvalue+xtitle), y2+0.1, "Value");
ttitle.DrawText(0.5*(xtitle+x2), y2+0.1, "Title");
ttitle.SetTextSize(1.2*tsize);
ttitle.SetTextColor(2);
ttitle.SetTextAlign(11);
ttitle.DrawText(x1+0.2, y3+0.1, cl->GetName());
if (proxy==0) {
ttitle.SetTextColor(4);
strncpy(line,obj->GetName(),kline); line[kline-1]=0;
ttitle.DrawText(xvalue+0.2, y3+0.1, line);
ttitle.SetTextColor(6);
ttitle.DrawText(xtitle+2, y3+0.1, obj->GetTitle());
} else {
ttitle.SetTextColor(4);
snprintf(line,1023,"%s:%d","Foreign object",0);
ttitle.DrawText(xvalue+0.2, y3+0.1, line);
ttitle.SetTextColor(6);
ttitle.DrawText(xtitle+2, y3+0.1, "no title given");
}
ttitle.SetTextSize(tsize);
ttitle.SetTextColor(1);
ttitle.SetTextFont(11);
ttitle.SetTextAlign(12);
//---Now loop on data members-----------------------
// We make 3 passes. Faster than one single pass because changing
// font parameters is time consuming
for (Int_t pass = 0; pass < 3; pass++) {
ytext = y2 - 0.5;
next.Reset();
while ((rd = (TRealData*) next())) {
TDataMember *member = rd->GetDataMember();
if (!member) continue;
TDataType *membertype = member->GetDataType();
isdate = kFALSE;
if (strcmp(member->GetName(),"fDatime") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) {
isdate = kTRUE;
}
isbits = kFALSE;
if (strcmp(member->GetName(),"fBits") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) {
isbits = kTRUE;
}
// Encode data member name
pname = &line[kname];
for (Int_t i=0;i<kline;i++) line[i] = ' ';
line[kline-1] = 0;
strncpy(pname,rd->GetName(),128); pname[127]=0;
if (strstr(member->GetFullTypeName(),"**")) strcat(pname,"**");
// Encode data value or pointer value
tval = &tvalue;
Int_t offset = rd->GetThisOffset();
char *pointer = (char*)obj + offset;
char **ppointer = (char**)(pointer);
TLink *tlink = 0;
TClass *clm=0;
if (!membertype) {
clm = member->GetClass();
}
if (member->IsaPointer()) {
char **p3pointer = (char**)(*ppointer);
if (clm && !clm->IsStartingWithTObject() ) {
//NOTE: memory leak!
p3pointer = (char**)new TInspectorObject(p3pointer,clm);
}
if (!p3pointer) {
sprintf(&line[kvalue],"->0");
} else if (!member->IsBasic()) {
if (pass == 1) {
tlink = new TLink(xvalue+0.1, ytext, p3pointer);
}
} else if (membertype) {
if (!strcmp(membertype->GetTypeName(), "char"))
{strncpy(&line[kvalue], *ppointer,128); line[kline-1]=0;}
else
{strncpy(&line[kvalue], membertype->AsString(p3pointer),128); line[kline-1] =0;}
} else if (!strcmp(member->GetFullTypeName(), "char*") ||
!strcmp(member->GetFullTypeName(), "const char*")) {
{strncpy(&line[kvalue], *ppointer,128); line[kline-1]=0;}
} else {
if (pass == 1) tlink = new TLink(xvalue+0.1, ytext, p3pointer);
}
} else if (membertype)
if (isdate) {
cdatime = (UInt_t*)pointer;
TDatime::GetDateTime(cdatime[0],cdate,ctime);
snprintf(&line[kvalue],1023,"%d/%d",cdate,ctime);
} else if (isbits) {
snprintf(&line[kvalue],1023,"0x%08x", *(UInt_t*)pointer);
} else {
strncpy(&line[kvalue], membertype->AsString(pointer),128); line[kline-1]=0;
}
else
sprintf(&line[kvalue],"->%lx ", (Long_t)pointer);
// Encode data member title
Int_t ltit = 0;
if (isdate == kFALSE && strcmp(member->GetFullTypeName(), "char*") &&
strcmp(member->GetFullTypeName(), "const char*")) {
Int_t lentit = strlen(member->GetTitle());
if (lentit >= kline-ktitle) lentit = kline-ktitle-1;
strncpy(&line[ktitle],member->GetTitle(),128); line[kline-1]=0;
line[ktitle+lentit] = 0;
ltit = ktitle;
}
// Ready to draw the name, value and title columns
if (pass == 0)tname.DrawText( x1+0.1, ytext, &line[kname]);
if (pass == 1) {
if (tlink) {
tlink->SetTextFont(61);
tlink->SetTextAngle(0);
tlink->SetTextAlign(12);
tlink->SetTextColor(2);
tlink->SetTextSize(tsize);
tlink->SetBit(kCanDelete);
tlink->Draw();
if (strstr(member->GetFullTypeName(),"**")) tlink->SetBit(TLink::kIsStarStar);
tlink->SetName(member->GetTypeName());
} else {
tval->DrawText(xvalue+0.1, ytext, &line[kvalue]);
}
}
if (pass == 2 && ltit) ttitle.DrawText(xtitle+0.3, ytext, &line[ltit]);
ytext -= dy;
}
}
Update();
fCurObject = obj;
}
//______________________________________________________________________________
void TInspectCanvas::GoBackward()
{
// static function , inspect previous object
TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect");
TObject *cur = inspect->GetCurObject();
TObject *obj = inspect->GetObjects()->Before(cur);
if (obj) inspect->InspectObject(obj);
}
//______________________________________________________________________________
void TInspectCanvas::GoForward()
{
// static function , inspect next object
TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect");
TObject *cur = inspect->GetCurObject();
TObject *obj = inspect->GetObjects()->After(cur);
if (obj) inspect->InspectObject(obj);
}
//______________________________________________________________________________
void TInspectCanvas::Inspector(TObject *obj)
{
// static function , interface to InspectObject.
// Create the InspectCanvas if it does not exist yet.
TVirtualPad *padsav = gPad;
TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect");
if (!inspect) inspect = new TInspectCanvas(700,600);
else inspect->cd();
inspect->InspectObject(obj);
inspect->GetObjects()->Add(obj);
//obj->SetBit(kMustCleanup);
if (padsav) padsav->cd();
}
//______________________________________________________________________________
void TInspectCanvas::RecursiveRemove(TObject *obj)
{
// Recursively remove object from the list of objects.
fObjects->Remove(obj);
TPad::RecursiveRemove(obj);
}
<commit_msg>Fix a compilation warning<commit_after>// @(#)root/gpad:$Id$
// Author: Rene Brun 08/01/2000
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TGuiFactory.h"
#include "TInspectCanvas.h"
#include "TButton.h"
#include "TClass.h"
#include "TLine.h"
#include "TLink.h"
#include "TDataMember.h"
#include "TDataType.h"
#include "TRealData.h"
#include "TLatex.h"
#include "snprintf.h"
ClassImp(TInspectCanvas)
//////////////////////////////////////////////////////////////////////////
// //
// TInspectorObject //
// //
//////////////////////////////////////////////////////////////////////////
class TInspectorObject : public TObject
{
// This class is designed to wrap a Foreign object in order to
// inject it into the Browse sub-system.
public:
TInspectorObject(void *obj, TClass *cl) : fObj(obj),fClass(cl) {};
~TInspectorObject(){;}
void *GetObject() const { return fObj; };
void Inspect() const {
gGuiFactory->CreateInspectorImp(this, 400, 200);
};
TClass *IsA() const { return fClass; }
private:
void *fObj; //! pointer to the foreign object
TClass *fClass; //! pointer to class of the foreign object
};
//______________________________________________________________________________//*-*
//*-* A InspectCanvas is a canvas specialized to inspect Root objects.
//
//Begin_Html
/*
<img src="gif/InspectCanvas.gif">
*/
//End_Html
//
//______________________________________________________________________________
TInspectCanvas::TInspectCanvas() : TCanvas()
{
// InspectCanvas default constructor.
fBackward = 0;
fForward = 0;
fCurObject = 0;
fObjects = 0;
fLogx = kFALSE;
fLogy = kFALSE;
}
//_____________________________________________________________________________
TInspectCanvas::TInspectCanvas(UInt_t ww, UInt_t wh)
: TCanvas("inspect","ROOT Object Inspector",ww,wh)
{
// InspectCanvas constructor.
fBackward = 0;
fForward = 0;
fCurObject = 0;
fObjects = new TList;
fLogx = kFALSE;
fLogy = kFALSE;
}
//______________________________________________________________________________
TInspectCanvas::~TInspectCanvas()
{
// InspectCanvas default destructor.
if (fObjects) {
fObjects->Clear("nodelete");
delete fObjects;
}
}
//______________________________________________________________________________
void TInspectCanvas::InspectObject(TObject *obj)
{
// Dump contents of obj in a graphics canvas.
// Same action as TObject::Dump but in a graphical form.
// In addition pointers to other objects can be followed.
//
// The following picture is the Inspect of a histogram object:
//Begin_Html
/*
<img src="gif/hpxinspect.gif">
*/
//End_Html
Int_t cdate = 0;
Int_t ctime = 0;
UInt_t *cdatime = 0;
Bool_t isdate = kFALSE;
Bool_t isbits = kFALSE;
const Int_t kname = 1;
const Int_t kvalue = 25;
const Int_t ktitle = 37;
const Int_t kline = 1024;
char line[kline];
char *pname;
TClass *cl = obj->IsA();
if (cl == 0) return;
TInspectorObject *proxy=0;
if (!cl->InheritsFrom(TObject::Class())) {
// This is possible only if obj is actually a TInspectorObject
// wrapping a non-TObject.
proxy = (TInspectorObject*)obj;
obj = (TObject*)proxy->GetObject();
}
if (!cl->GetListOfRealData()) cl->BuildRealData(obj);
// Count number of data members in order to resize the canvas
TRealData *rd;
TIter next(cl->GetListOfRealData());
Int_t nreal = cl->GetListOfRealData()->GetSize();
if (nreal == 0) return;
Int_t nrows = 33;
if (nreal+7 > nrows) nrows = nreal+7;
Int_t nh = nrows*15;
Int_t nw = 700;
TVirtualPad *canvas = GetVirtCanvas();
canvas->Clear(); // remove primitives from canvas
canvas->SetCanvasSize(nw, nh); // set new size of drawing area
canvas->Range(0,-3,20,nreal+4);
Float_t xvalue = 5;
Float_t xtitle = 8;
Float_t dy = 1;
Float_t ytext = Float_t(nreal) - 1.5;
Float_t tsize = 0.99/ytext;
if (tsize < 0.02) tsize = 0.02;
if (tsize > 0.03) tsize = 0.03;
// Create text objects
TText tname, tvalue, ttitle;
TText *tval;
tname.SetTextFont(61);
tname.SetTextAngle(0);
tname.SetTextAlign(12);
tname.SetTextColor(1);
tname.SetTextSize(tsize);
tvalue.SetTextFont(61);
tvalue.SetTextAngle(0);
tvalue.SetTextAlign(12);
tvalue.SetTextColor(1);
tvalue.SetTextSize(tsize);
ttitle.SetTextFont(62);
ttitle.SetTextAngle(0);
ttitle.SetTextAlign(12);
ttitle.SetTextColor(1);
ttitle.SetTextSize(tsize);
Float_t x1 = 0.2;
Float_t x2 = 19.8;
Float_t y1 = -0.5;
Float_t y2 = Float_t(nreal) - 0.5;
Float_t y3 = y2 + 1;
Float_t y4 = y3 + 1.5;
Float_t db = 25./GetWh();
Float_t btop = 0.999;
// Draw buttons
fBackward = new TButton("backward","TInspectCanvas::GoBackward();",.01,btop-db,.15,btop);
fBackward->Draw();
fBackward->SetToolTipText("Inspect previous object");
fForward = new TButton("forward", "TInspectCanvas::GoForward();", .21,btop-db,.35,btop);
fForward->Draw();
fForward->SetToolTipText("Inspect next object");
// Draw surrounding box and title areas
TLine frame;
frame.SetLineColor(1);
frame.SetLineStyle(1);
frame.SetLineWidth(1);
frame.DrawLine(x1, y1, x2, y1);
frame.DrawLine(x2, y1, x2, y4);
frame.DrawLine(x2, y4, x1, y4);
frame.DrawLine(x1, y4, x1, y1);
frame.DrawLine(x1, y2, x2, y2);
frame.DrawLine(x1, y3, x2, y3);
frame.DrawLine(xvalue, y1, xvalue, y3);
frame.DrawLine(xtitle, y1, xtitle, y3);
ttitle.SetTextSize(0.8*tsize);
ttitle.SetTextAlign(21);
ttitle.DrawText(0.5*(x1+xvalue), y2+0.1, "Member Name");
ttitle.DrawText(0.5*(xvalue+xtitle), y2+0.1, "Value");
ttitle.DrawText(0.5*(xtitle+x2), y2+0.1, "Title");
ttitle.SetTextSize(1.2*tsize);
ttitle.SetTextColor(2);
ttitle.SetTextAlign(11);
ttitle.DrawText(x1+0.2, y3+0.1, cl->GetName());
if (proxy==0) {
ttitle.SetTextColor(4);
strncpy(line,obj->GetName(),kline); line[kline-1]=0;
ttitle.DrawText(xvalue+0.2, y3+0.1, line);
ttitle.SetTextColor(6);
ttitle.DrawText(xtitle+2, y3+0.1, obj->GetTitle());
} else {
ttitle.SetTextColor(4);
snprintf(line,1023,"%s:%d","Foreign object",0);
ttitle.DrawText(xvalue+0.2, y3+0.1, line);
ttitle.SetTextColor(6);
ttitle.DrawText(xtitle+2, y3+0.1, "no title given");
}
ttitle.SetTextSize(tsize);
ttitle.SetTextColor(1);
ttitle.SetTextFont(11);
ttitle.SetTextAlign(12);
//---Now loop on data members-----------------------
// We make 3 passes. Faster than one single pass because changing
// font parameters is time consuming
for (Int_t pass = 0; pass < 3; pass++) {
ytext = y2 - 0.5;
next.Reset();
while ((rd = (TRealData*) next())) {
TDataMember *member = rd->GetDataMember();
if (!member) continue;
TDataType *membertype = member->GetDataType();
isdate = kFALSE;
if (strcmp(member->GetName(),"fDatime") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) {
isdate = kTRUE;
}
isbits = kFALSE;
if (strcmp(member->GetName(),"fBits") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) {
isbits = kTRUE;
}
// Encode data member name
pname = &line[kname];
for (Int_t i=0;i<kline;i++) line[i] = ' ';
line[kline-1] = 0;
strncpy(pname,rd->GetName(),128); pname[127]=0;
if (strstr(member->GetFullTypeName(),"**")) strcat(pname,"**");
// Encode data value or pointer value
tval = &tvalue;
Int_t offset = rd->GetThisOffset();
char *pointer = (char*)obj + offset;
char **ppointer = (char**)(pointer);
TLink *tlink = 0;
TClass *clm=0;
if (!membertype) {
clm = member->GetClass();
}
if (member->IsaPointer()) {
char **p3pointer = (char**)(*ppointer);
if (clm && !clm->IsStartingWithTObject() ) {
//NOTE: memory leak!
p3pointer = (char**)new TInspectorObject(p3pointer,clm);
}
if (!p3pointer) {
sprintf(&line[kvalue],"->0");
} else if (!member->IsBasic()) {
if (pass == 1) {
tlink = new TLink(xvalue+0.1, ytext, p3pointer);
}
} else if (membertype) {
if (!strcmp(membertype->GetTypeName(), "char"))
{strncpy(&line[kvalue], *ppointer,128); line[kline-1]=0;}
else
{strncpy(&line[kvalue], membertype->AsString(p3pointer),128); line[kline-1] =0;}
} else if (!strcmp(member->GetFullTypeName(), "char*") ||
!strcmp(member->GetFullTypeName(), "const char*")) {
{strncpy(&line[kvalue], *ppointer,128); line[kline-1]=0;}
} else {
if (pass == 1) tlink = new TLink(xvalue+0.1, ytext, p3pointer);
}
} else if (membertype)
if (isdate) {
cdatime = (UInt_t*)pointer;
TDatime::GetDateTime(cdatime[0],cdate,ctime);
snprintf(&line[kvalue],1023-kvalue,"%d/%d",cdate,ctime);
} else if (isbits) {
snprintf(&line[kvalue],1023-kvalue,"0x%08x", *(UInt_t*)pointer);
} else {
strncpy(&line[kvalue], membertype->AsString(pointer),128); line[kline-1]=0;
}
else
sprintf(&line[kvalue],"->%lx ", (Long_t)pointer);
// Encode data member title
Int_t ltit = 0;
if (isdate == kFALSE && strcmp(member->GetFullTypeName(), "char*") &&
strcmp(member->GetFullTypeName(), "const char*")) {
Int_t lentit = strlen(member->GetTitle());
if (lentit >= kline-ktitle) lentit = kline-ktitle-1;
strncpy(&line[ktitle],member->GetTitle(),128); line[kline-1]=0;
line[ktitle+lentit] = 0;
ltit = ktitle;
}
// Ready to draw the name, value and title columns
if (pass == 0)tname.DrawText( x1+0.1, ytext, &line[kname]);
if (pass == 1) {
if (tlink) {
tlink->SetTextFont(61);
tlink->SetTextAngle(0);
tlink->SetTextAlign(12);
tlink->SetTextColor(2);
tlink->SetTextSize(tsize);
tlink->SetBit(kCanDelete);
tlink->Draw();
if (strstr(member->GetFullTypeName(),"**")) tlink->SetBit(TLink::kIsStarStar);
tlink->SetName(member->GetTypeName());
} else {
tval->DrawText(xvalue+0.1, ytext, &line[kvalue]);
}
}
if (pass == 2 && ltit) ttitle.DrawText(xtitle+0.3, ytext, &line[ltit]);
ytext -= dy;
}
}
Update();
fCurObject = obj;
}
//______________________________________________________________________________
void TInspectCanvas::GoBackward()
{
// static function , inspect previous object
TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect");
TObject *cur = inspect->GetCurObject();
TObject *obj = inspect->GetObjects()->Before(cur);
if (obj) inspect->InspectObject(obj);
}
//______________________________________________________________________________
void TInspectCanvas::GoForward()
{
// static function , inspect next object
TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect");
TObject *cur = inspect->GetCurObject();
TObject *obj = inspect->GetObjects()->After(cur);
if (obj) inspect->InspectObject(obj);
}
//______________________________________________________________________________
void TInspectCanvas::Inspector(TObject *obj)
{
// static function , interface to InspectObject.
// Create the InspectCanvas if it does not exist yet.
TVirtualPad *padsav = gPad;
TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect");
if (!inspect) inspect = new TInspectCanvas(700,600);
else inspect->cd();
inspect->InspectObject(obj);
inspect->GetObjects()->Add(obj);
//obj->SetBit(kMustCleanup);
if (padsav) padsav->cd();
}
//______________________________________________________________________________
void TInspectCanvas::RecursiveRemove(TObject *obj)
{
// Recursively remove object from the list of objects.
fObjects->Remove(obj);
TPad::RecursiveRemove(obj);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "topojson_datasource.hpp"
#include "topojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/variant.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/extensions/index/rtree/rtree.hpp>
// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/json/topojson_grammar.hpp>
#include <mapnik/json/topojson_utils.hpp>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(topojson_datasource)
struct attr_value_converter : public boost::static_visitor<mapnik::eAttributeType>
{
mapnik::eAttributeType operator() (mapnik::value_integer /*val*/) const
{
return mapnik::Integer;
}
mapnik::eAttributeType operator() (double /*val*/) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (float /*val*/) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (bool /*val*/) const
{
return mapnik::Boolean;
}
mapnik::eAttributeType operator() (std::string const& /*val*/) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_unicode_string const& /*val*/) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_null const& /*val*/) const
{
return mapnik::String;
}
};
struct geometry_type_visitor : public boost::static_visitor<int>
{
int operator() (mapnik::topojson::point const&) const
{
return static_cast<int>(mapnik::datasource::Point);
}
int operator() (mapnik::topojson::multi_point const&) const
{
return static_cast<int>(mapnik::datasource::Point);
}
int operator() (mapnik::topojson::linestring const&) const
{
return static_cast<int>(mapnik::datasource::LineString);
}
int operator() (mapnik::topojson::multi_linestring const&) const
{
return static_cast<int>(mapnik::datasource::LineString);
}
int operator() (mapnik::topojson::polygon const&) const
{
return static_cast<int>(mapnik::datasource::Polygon);
}
int operator() (mapnik::topojson::multi_polygon const&) const
{
return static_cast<int>(mapnik::datasource::Polygon);
}
int operator() (mapnik::topojson::invalid const&) const
{
return -1;
}
};
struct collect_attributes_visitor : public boost::static_visitor<void>
{
mapnik::layer_descriptor & desc_;
collect_attributes_visitor(mapnik::layer_descriptor & desc):
desc_(desc) {}
void operator() (mapnik::topojson::invalid const& g) {}
template <typename GeomType>
void operator() (GeomType const& g)
{
if (g.props)
{
for (auto const& p : *g.props)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(p),
boost::apply_visitor(attr_value_converter(),std::get<1>(p))));
}
}
}
};
topojson_datasource::topojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(*params.get<std::string>("type"),
*params.get<std::string>("encoding","utf-8")),
file_(*params.get<std::string>("file","")),
extent_(),
tr_(new mapnik::transcoder(*params.get<std::string>("encoding","utf-8"))),
tree_(16,1)
{
if (file_.empty()) throw mapnik::datasource_exception("TopoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
{
file_ = *base + "/" + file_;
}
typedef std::istreambuf_iterator<char> base_iterator_type;
#if defined (_WINDOWS)
std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary);
#else
std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary);
#endif
if (!is.is_open())
{
throw mapnik::datasource_exception("TopoJSON Plugin: could not open: '" + file_ + "'");
}
boost::spirit::multi_pass<base_iterator_type> begin =
boost::spirit::make_default_multi_pass(base_iterator_type(is));
boost::spirit::multi_pass<base_iterator_type> end =
boost::spirit::make_default_multi_pass(base_iterator_type());
mapnik::topojson::topojson_grammar<boost::spirit::multi_pass<base_iterator_type> > g;
bool result = boost::spirit::qi::phrase_parse(begin, end, g, boost::spirit::standard_wide::space, topo_);
if (!result)
{
throw mapnik::datasource_exception("topojson_datasource: Failed parse TopoJSON file '" + file_ + "'");
}
std::size_t count = 0;
for (auto const& geom : topo_.geometries)
{
mapnik::box2d<double> bbox = boost::apply_visitor(mapnik::topojson::bounding_box_visitor(topo_), geom);
if (bbox.valid())
{
if (count == 0)
{
extent_ = bbox;
collect_attributes_visitor assessor(desc_);
boost::apply_visitor(assessor,geom);
}
else
{
extent_.expand_to_include(bbox);
}
tree_.insert(box_type(point_type(bbox.minx(),bbox.miny()),point_type(bbox.maxx(),bbox.maxy())), count);
}
++count;
}
}
topojson_datasource::~topojson_datasource() { }
const char * topojson_datasource::name()
{
return "topojson";
}
boost::optional<mapnik::datasource::geometry_t> topojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
int multi_type = 0;
std::size_t num_features = topo_.geometries.size();
for (std::size_t i = 0; i < num_features && i < 5; ++i)
{
mapnik::topojson::geometry const& geom = topo_.geometries[i];
int type = boost::apply_visitor(geometry_type_visitor(),geom);
if (type > 0)
{
if (multi_type > 0 && multi_type != type)
{
result.reset(mapnik::datasource::Collection);
return result;
}
else
{
result.reset(static_cast<mapnik::datasource::geometry_t>(type));
}
multi_type = type;
}
}
return result;
}
mapnik::datasource::datasource_t topojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> topojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor topojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr topojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& b = q.get_bbox();
if (extent_.intersects(b))
{
box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy()));
return std::make_shared<topojson_featureset>(topo_, *tr_, tree_.find(box));
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr topojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
for (auto const& attr_info : desc_.get_descriptors())
{
q.add_property_name(attr_info.get_name());
}
return features(q);
}
<commit_msg>fix compile with BOOST_SPIRIT_NO_PREDEFINED_TERMINALS<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "topojson_datasource.hpp"
#include "topojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/variant.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/extensions/index/rtree/rtree.hpp>
// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/json/topojson_grammar.hpp>
#include <mapnik/json/topojson_utils.hpp>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(topojson_datasource)
struct attr_value_converter : public boost::static_visitor<mapnik::eAttributeType>
{
mapnik::eAttributeType operator() (mapnik::value_integer /*val*/) const
{
return mapnik::Integer;
}
mapnik::eAttributeType operator() (double /*val*/) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (float /*val*/) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (bool /*val*/) const
{
return mapnik::Boolean;
}
mapnik::eAttributeType operator() (std::string const& /*val*/) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_unicode_string const& /*val*/) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_null const& /*val*/) const
{
return mapnik::String;
}
};
struct geometry_type_visitor : public boost::static_visitor<int>
{
int operator() (mapnik::topojson::point const&) const
{
return static_cast<int>(mapnik::datasource::Point);
}
int operator() (mapnik::topojson::multi_point const&) const
{
return static_cast<int>(mapnik::datasource::Point);
}
int operator() (mapnik::topojson::linestring const&) const
{
return static_cast<int>(mapnik::datasource::LineString);
}
int operator() (mapnik::topojson::multi_linestring const&) const
{
return static_cast<int>(mapnik::datasource::LineString);
}
int operator() (mapnik::topojson::polygon const&) const
{
return static_cast<int>(mapnik::datasource::Polygon);
}
int operator() (mapnik::topojson::multi_polygon const&) const
{
return static_cast<int>(mapnik::datasource::Polygon);
}
int operator() (mapnik::topojson::invalid const&) const
{
return -1;
}
};
struct collect_attributes_visitor : public boost::static_visitor<void>
{
mapnik::layer_descriptor & desc_;
collect_attributes_visitor(mapnik::layer_descriptor & desc):
desc_(desc) {}
void operator() (mapnik::topojson::invalid const& g) {}
template <typename GeomType>
void operator() (GeomType const& g)
{
if (g.props)
{
for (auto const& p : *g.props)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(p),
boost::apply_visitor(attr_value_converter(),std::get<1>(p))));
}
}
}
};
topojson_datasource::topojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(*params.get<std::string>("type"),
*params.get<std::string>("encoding","utf-8")),
file_(*params.get<std::string>("file","")),
extent_(),
tr_(new mapnik::transcoder(*params.get<std::string>("encoding","utf-8"))),
tree_(16,1)
{
if (file_.empty()) throw mapnik::datasource_exception("TopoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
{
file_ = *base + "/" + file_;
}
typedef std::istreambuf_iterator<char> base_iterator_type;
#if defined (_WINDOWS)
std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary);
#else
std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary);
#endif
if (!is.is_open())
{
throw mapnik::datasource_exception("TopoJSON Plugin: could not open: '" + file_ + "'");
}
boost::spirit::multi_pass<base_iterator_type> begin =
boost::spirit::make_default_multi_pass(base_iterator_type(is));
boost::spirit::multi_pass<base_iterator_type> end =
boost::spirit::make_default_multi_pass(base_iterator_type());
mapnik::topojson::topojson_grammar<boost::spirit::multi_pass<base_iterator_type> > g;
boost::spirit::standard_wide::space_type space;
bool result = boost::spirit::qi::phrase_parse(begin, end, g, space, topo_);
if (!result)
{
throw mapnik::datasource_exception("topojson_datasource: Failed parse TopoJSON file '" + file_ + "'");
}
std::size_t count = 0;
for (auto const& geom : topo_.geometries)
{
mapnik::box2d<double> bbox = boost::apply_visitor(mapnik::topojson::bounding_box_visitor(topo_), geom);
if (bbox.valid())
{
if (count == 0)
{
extent_ = bbox;
collect_attributes_visitor assessor(desc_);
boost::apply_visitor(assessor,geom);
}
else
{
extent_.expand_to_include(bbox);
}
tree_.insert(box_type(point_type(bbox.minx(),bbox.miny()),point_type(bbox.maxx(),bbox.maxy())), count);
}
++count;
}
}
topojson_datasource::~topojson_datasource() { }
const char * topojson_datasource::name()
{
return "topojson";
}
boost::optional<mapnik::datasource::geometry_t> topojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
int multi_type = 0;
std::size_t num_features = topo_.geometries.size();
for (std::size_t i = 0; i < num_features && i < 5; ++i)
{
mapnik::topojson::geometry const& geom = topo_.geometries[i];
int type = boost::apply_visitor(geometry_type_visitor(),geom);
if (type > 0)
{
if (multi_type > 0 && multi_type != type)
{
result.reset(mapnik::datasource::Collection);
return result;
}
else
{
result.reset(static_cast<mapnik::datasource::geometry_t>(type));
}
multi_type = type;
}
}
return result;
}
mapnik::datasource::datasource_t topojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> topojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor topojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr topojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& b = q.get_bbox();
if (extent_.intersects(b))
{
box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy()));
return std::make_shared<topojson_featureset>(topo_, *tr_, tree_.find(box));
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr topojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
for (auto const& attr_info : desc_.get_descriptors())
{
q.add_property_name(attr_info.get_name());
}
return features(q);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_MEMORY_INPUT_HPP
#define TAO_PEGTL_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "normal.hpp"
#include "nothing.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/at.hpp"
#include "internal/bump.hpp"
#include "internal/eolf.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
#include "internal/until.hpp"
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< tracking_mode, typename Eol, typename Source >
class memory_input_base;
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::eager, Eol, Source >
{
public:
using iterator_t = internal::iterator;
template< typename T >
memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin.data ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
[[nodiscard]] const char* current() const noexcept
{
return m_current.data;
}
[[nodiscard]] const char* begin() const noexcept
{
return m_begin;
}
[[nodiscard]] const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
[[nodiscard]] std::size_t byte() const noexcept
{
return m_current.byte;
}
[[nodiscard]] std::size_t line() const noexcept
{
return m_current.line;
}
[[nodiscard]] std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
void restart( const std::size_t in_byte = 0, const std::size_t in_line = 1, const std::size_t in_byte_in_line = 0 )
{
m_current.data = m_begin;
m_current.byte = in_byte;
m_current.line = in_line;
m_current.byte_in_line = in_byte_in_line;
}
template< rewind_mode M >
void restart( const internal::marker< iterator_t, M >& m )
{
m_current = m.iterator();
}
protected:
const char* const m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::lazy, Eol, Source >
{
public:
using iterator_t = const char*;
template< typename T >
memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin ),
m_current( in_begin.data ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
[[nodiscard]] const char* current() const noexcept
{
return m_current;
}
[[nodiscard]] const char* begin() const noexcept
{
return m_begin.data;
}
[[nodiscard]] const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
[[nodiscard]] std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAO_PEGTL_NAMESPACE::position( c, m_source );
}
void restart()
{
m_current = m_begin.data;
}
template< rewind_mode M >
void restart( const internal::marker< iterator_t, M >& m )
{
m_current = m.iterator();
}
protected:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
} // namespace internal
template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf, typename Source = std::string >
class memory_input
: public internal::memory_input_base< P, Eol, Source >
{
public:
static constexpr tracking_mode tracking_mode_v = P;
using eol_t = Eol;
using source_t = Source;
using typename internal::memory_input_base< P, Eol, Source >::iterator_t;
using action_t = internal::action_input< memory_input >;
using internal::memory_input_base< P, Eol, Source >::memory_input_base;
template< typename T >
memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( const std::string_view in_string, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( std::string&&, T&& ) = delete;
template< typename T >
memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) )
{}
memory_input( const memory_input& ) = delete;
memory_input( memory_input&& ) = delete;
~memory_input() = default;
memory_input operator=( const memory_input& ) = delete;
memory_input operator=( memory_input&& ) = delete;
[[nodiscard]] const Source& source() const noexcept
{
return this->m_source;
}
[[nodiscard]] bool empty() const noexcept
{
return this->current() == this->end();
}
[[nodiscard]] std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
[[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
[[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept
{
return static_cast< std::uint8_t >( peek_char( offset ) );
}
[[nodiscard]] iterator_t& iterator() noexcept
{
return this->m_current;
}
[[nodiscard]] const iterator_t& iterator() const noexcept
{
return this->m_current;
}
using internal::memory_input_base< P, Eol, Source >::position;
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const
{
return position( iterator() );
}
void discard() const noexcept {}
void require( const std::size_t /*unused*/ ) const noexcept {}
template< rewind_mode M >
[[nodiscard]] internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( iterator() );
}
[[nodiscard]] const char* at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return this->begin() + p.byte;
}
[[nodiscard]] const char* begin_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return at( p ) - p.byte_in_line;
}
[[nodiscard]] const char* end_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
using input_t = memory_input< tracking_mode::lazy, Eol, const char* >;
input_t in( at( p ), this->end(), "" );
using grammar = internal::until< internal::at< internal::eolf > >;
(void)normal< grammar >::match< apply_mode::nothing, rewind_mode::dontcare, nothing, normal >( in );
return in.current();
}
[[nodiscard]] std::string_view line_at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
const char* b = begin_of_line( p );
return std::string_view( b, static_cast< std::size_t >( end_of_line( p ) - b ) );
}
};
template< typename... Ts >
memory_input( Ts&&... )->memory_input<>;
} // namespace TAO_PEGTL_NAMESPACE
#endif
<commit_msg>Simplify<commit_after>// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_MEMORY_INPUT_HPP
#define TAO_PEGTL_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "normal.hpp"
#include "nothing.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/at.hpp"
#include "internal/bump.hpp"
#include "internal/eolf.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
#include "internal/until.hpp"
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< tracking_mode, typename Eol, typename Source >
class memory_input_base;
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::eager, Eol, Source >
{
public:
using iterator_t = internal::iterator;
template< typename T >
memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin.data ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
[[nodiscard]] const char* current() const noexcept
{
return m_current.data;
}
[[nodiscard]] const char* begin() const noexcept
{
return m_begin;
}
[[nodiscard]] const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
[[nodiscard]] std::size_t byte() const noexcept
{
return m_current.byte;
}
[[nodiscard]] std::size_t line() const noexcept
{
return m_current.line;
}
[[nodiscard]] std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
void restart( const std::size_t in_byte = 0, const std::size_t in_line = 1, const std::size_t in_byte_in_line = 0 )
{
m_current.data = m_begin;
m_current.byte = in_byte;
m_current.line = in_line;
m_current.byte_in_line = in_byte_in_line;
}
protected:
const char* const m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::lazy, Eol, Source >
{
public:
using iterator_t = const char*;
template< typename T >
memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin ),
m_current( in_begin.data ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
[[nodiscard]] const char* current() const noexcept
{
return m_current;
}
[[nodiscard]] const char* begin() const noexcept
{
return m_begin.data;
}
[[nodiscard]] const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
[[nodiscard]] std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAO_PEGTL_NAMESPACE::position( c, m_source );
}
void restart()
{
m_current = m_begin.data;
}
protected:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
} // namespace internal
template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf, typename Source = std::string >
class memory_input
: public internal::memory_input_base< P, Eol, Source >
{
public:
static constexpr tracking_mode tracking_mode_v = P;
using eol_t = Eol;
using source_t = Source;
using typename internal::memory_input_base< P, Eol, Source >::iterator_t;
using action_t = internal::action_input< memory_input >;
using internal::memory_input_base< P, Eol, Source >::memory_input_base;
template< typename T >
memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( const std::string_view in_string, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( std::string&&, T&& ) = delete;
template< typename T >
memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) )
{}
template< typename T >
memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible_v< Source, T&& > )
: memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) )
{}
memory_input( const memory_input& ) = delete;
memory_input( memory_input&& ) = delete;
~memory_input() = default;
memory_input operator=( const memory_input& ) = delete;
memory_input operator=( memory_input&& ) = delete;
[[nodiscard]] const Source& source() const noexcept
{
return this->m_source;
}
[[nodiscard]] bool empty() const noexcept
{
return this->current() == this->end();
}
[[nodiscard]] std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
[[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
[[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept
{
return static_cast< std::uint8_t >( peek_char( offset ) );
}
[[nodiscard]] iterator_t& iterator() noexcept
{
return this->m_current;
}
[[nodiscard]] const iterator_t& iterator() const noexcept
{
return this->m_current;
}
using internal::memory_input_base< P, Eol, Source >::restart;
template< rewind_mode M >
void restart( const internal::marker< iterator_t, M >& m ) noexcept
{
iterator() = m.iterator();
}
using internal::memory_input_base< P, Eol, Source >::position;
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const
{
return position( iterator() );
}
void discard() const noexcept {}
void require( const std::size_t /*unused*/ ) const noexcept {}
template< rewind_mode M >
[[nodiscard]] internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( iterator() );
}
[[nodiscard]] const char* at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return this->begin() + p.byte;
}
[[nodiscard]] const char* begin_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
return at( p ) - p.byte_in_line;
}
[[nodiscard]] const char* end_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
using input_t = memory_input< tracking_mode::lazy, Eol, const char* >;
input_t in( at( p ), this->end(), "" );
using grammar = internal::until< internal::at< internal::eolf > >;
(void)normal< grammar >::match< apply_mode::nothing, rewind_mode::dontcare, nothing, normal >( in );
return in.current();
}
[[nodiscard]] std::string_view line_at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept
{
const char* b = begin_of_line( p );
return std::string_view( b, static_cast< std::size_t >( end_of_line( p ) - b ) );
}
};
template< typename... Ts >
memory_input( Ts&&... )->memory_input<>;
} // namespace TAO_PEGTL_NAMESPACE
#endif
<|endoftext|>
|
<commit_before>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef TYPE_SAFE_OPTIONAL_REF_HPP_INCLUDED
#define TYPE_SAFE_OPTIONAL_REF_HPP_INCLUDED
#include <type_safe/optional.hpp>
namespace type_safe
{
/// A `StoragePolicy` for [ts::basic_optional]() that allows optional references.
///
/// The actual `value_type` passed to the optional is [std::reference_wrapper<T>](),
/// but the reference types are normal references, so `value()` will return a `T&`
/// and `value_or()` takes a fallback reference of the same type and returns one of them.
/// Assigning an optional will always change the target of the reference.
/// You cannot pass rvalues.
///
/// If `XValue` is `true`, you still cannot pass rvalues,
/// but the result of `value()`/`value_or()` will return an rvalue reference,
/// to allow moving of the stored value into something else.
///
/// Depending on the const-ness of `T` is the reference to `const` or non-const as well,
/// unless `XValue` is true`, in which case `T` must not be `const`.
template <typename T, bool XValue = false>
class reference_optional_storage
{
static_assert(!std::is_reference<T>::value, "pass the type without reference");
static_assert(!XValue || !std::is_const<T>::value, "must not be const if xvalue reference");
using result_type = typename std::conditional<XValue, T&&, T&>::type;
struct prevent_rvalues
{
};
public:
using value_type = std::reference_wrapper<T>;
using lvalue_reference = T&;
using const_lvalue_reference = lvalue_reference;
using rvalue_reference = prevent_rvalues;
using const_rvalue_reference = rvalue_reference;
template <typename U>
using rebind = reference_optional_storage<U, XValue>;
/// \effects Creates it without a bound reference.
reference_optional_storage() noexcept : pointer_(nullptr)
{
}
/// \effects Binds the reference to `obj`.
void create_value(lvalue_reference obj) noexcept
{
pointer_ = &obj;
}
/// \effects Binds the reference to the same reference in `other`.
void create_value(const reference_optional_storage& other) noexcept
{
pointer_ = other.pointer_;
}
/// \effects Binds the same target as `const_ref`.
/// \param 1
/// \exclude
template <typename U,
typename = typename std::
enable_if<std::is_same<U, typename std::remove_const<T>::type>::value>::type>
void create_value(const basic_optional<reference_optional_storage<U, XValue>>& const_ref)
{
pointer_ = const_ref.has_value() ? &const_ref.value() : nullptr;
}
/// \effects Same as `destroy_value()`.
void create_value(std::nullptr_t) noexcept
{
destroy_value();
}
void create_value(T&&) = delete;
/// \effects Binds the reference to the same reference in `other`.
void copy_value(const reference_optional_storage& other) noexcept
{
pointer_ = other.pointer_;
}
/// \effects Swaps the reference with the reference in `other`,
/// i.e. rebinds them, no value change.
void swap_value(reference_optional_storage& other) noexcept
{
std::swap(pointer_, other.pointer_);
}
/// \effects Unbinds the reference.
void destroy_value() noexcept
{
pointer_ = nullptr;
}
/// \returns `true` if the reference is bound, `false` otherwise.
bool has_value() const noexcept
{
return pointer_ != nullptr;
}
/// \returns The target of the reference.
/// Depending on `XValue`, this will either be `T&` or `T&&`.
result_type get_value() const noexcept
{
return static_cast<result_type>(*pointer_);
}
/// \returns Either `get_value()` or `other`.
/// Depending on `XValue`, this will either be `T&` or `T&&`.
result_type get_value_or(lvalue_reference other) const
{
return has_value() ? get_value() : static_cast<result_type>(other);
}
private:
T* pointer_;
};
/// A [ts::basic_optional]() that uses [ts::reference_optional_storage]().
/// It is an optional reference.
/// \notes `T` is the type without the reference, i.e. `optional_ref<int>`.
template <typename T>
using optional_ref = basic_optional<reference_optional_storage<T>>;
/// \returns A [ts::optional_ref<T>]() to the pointee of `ptr` or `nullopt`.
template <typename T>
optional_ref<T> ref(T* ptr) noexcept
{
return ptr ? optional_ref<T>(*ptr) : nullopt;
}
/// \returns A [ts::optional_ref<T>]() to `const` to the pointee of `ptr` or `nullopt`.
template <typename T>
optional_ref<const T> cref(const T* ptr) noexcept
{
return ptr ? optional_ref<const T>(*ptr) : nullopt;
}
/// A [ts::basic_optional]() that uses [ts::reference_optional_storage]() with `XValue` being `true`.
/// It is an optional reference to an xvalue,
/// i.e. an lvalue that can be moved from, like returned by `std::move()`.
/// \notes `T` is the type without the reference, i.e. `optional_xvalue_ref<int>`.
template <typename T>
using optional_xvalue_ref = basic_optional<reference_optional_storage<T, true>>;
/// \returns A [ts::optional_xvalue_ref<T>]() to the pointee of `ptr` or `nullopt`.
/// \notes The pointee will be moved from when you call `value()`.
template <typename T>
optional_xvalue_ref<T> xref(T* ptr) noexcept
{
return ptr ? optional_xvalue_ref<T>(*ptr) : nullopt;
}
/// \returns A [ts::optional<T>]() containing a copy of the value of `ref`
/// if there is any value.
/// \requires `T` must be copyable.
template <typename T>
optional<typename std::remove_const<T>::type> copy(const optional_ref<T>& ref)
{
return ref.has_value() ? make_optional(ref.value()) : nullopt;
}
/// \returns A [ts::optional<T>]() containing a copy of the value of `ref` created by move constructing
/// if there is any value.
/// \requires `T` must be moveable.
template <typename T>
optional<T> move(const optional_xvalue_ref<T>& ref) noexcept(
std::is_nothrow_move_constructible<T>::value)
{
return ref.has_value() ? make_optional(ref.value()) : nullopt;
}
} // namespace type_safe
#endif // TYPE_SAFE_OPTIONAL_REF_HPP_INCLUDED
<commit_msg>Add optional_ref to module again<commit_after>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef TYPE_SAFE_OPTIONAL_REF_HPP_INCLUDED
#define TYPE_SAFE_OPTIONAL_REF_HPP_INCLUDED
#include <type_safe/optional.hpp>
namespace type_safe
{
/// A `StoragePolicy` for [ts::basic_optional]() that allows optional references.
///
/// The actual `value_type` passed to the optional is [std::reference_wrapper<T>](),
/// but the reference types are normal references, so `value()` will return a `T&`
/// and `value_or()` takes a fallback reference of the same type and returns one of them.
/// Assigning an optional will always change the target of the reference.
/// You cannot pass rvalues.
///
/// If `XValue` is `true`, you still cannot pass rvalues,
/// but the result of `value()`/`value_or()` will return an rvalue reference,
/// to allow moving of the stored value into something else.
///
/// Depending on the const-ness of `T` is the reference to `const` or non-const as well,
/// unless `XValue` is true`, in which case `T` must not be `const`.
/// \module optional
template <typename T, bool XValue = false>
class reference_optional_storage
{
static_assert(!std::is_reference<T>::value, "pass the type without reference");
static_assert(!XValue || !std::is_const<T>::value, "must not be const if xvalue reference");
using result_type = typename std::conditional<XValue, T&&, T&>::type;
struct prevent_rvalues
{
};
public:
using value_type = std::reference_wrapper<T>;
using lvalue_reference = T&;
using const_lvalue_reference = lvalue_reference;
using rvalue_reference = prevent_rvalues;
using const_rvalue_reference = rvalue_reference;
template <typename U>
using rebind = reference_optional_storage<U, XValue>;
/// \effects Creates it without a bound reference.
reference_optional_storage() noexcept : pointer_(nullptr)
{
}
/// \effects Binds the reference to `obj`.
void create_value(lvalue_reference obj) noexcept
{
pointer_ = &obj;
}
/// \effects Binds the reference to the same reference in `other`.
void create_value(const reference_optional_storage& other) noexcept
{
pointer_ = other.pointer_;
}
/// \effects Binds the same target as `const_ref`.
/// \param 1
/// \exclude
template <typename U,
typename = typename std::
enable_if<std::is_same<U, typename std::remove_const<T>::type>::value>::type>
void create_value(const basic_optional<reference_optional_storage<U, XValue>>& const_ref)
{
pointer_ = const_ref.has_value() ? &const_ref.value() : nullptr;
}
/// \effects Same as `destroy_value()`.
void create_value(std::nullptr_t) noexcept
{
destroy_value();
}
void create_value(T&&) = delete;
/// \effects Binds the reference to the same reference in `other`.
void copy_value(const reference_optional_storage& other) noexcept
{
pointer_ = other.pointer_;
}
/// \effects Swaps the reference with the reference in `other`,
/// i.e. rebinds them, no value change.
void swap_value(reference_optional_storage& other) noexcept
{
std::swap(pointer_, other.pointer_);
}
/// \effects Unbinds the reference.
void destroy_value() noexcept
{
pointer_ = nullptr;
}
/// \returns `true` if the reference is bound, `false` otherwise.
bool has_value() const noexcept
{
return pointer_ != nullptr;
}
/// \returns The target of the reference.
/// Depending on `XValue`, this will either be `T&` or `T&&`.
result_type get_value() const noexcept
{
return static_cast<result_type>(*pointer_);
}
/// \returns Either `get_value()` or `other`.
/// Depending on `XValue`, this will either be `T&` or `T&&`.
result_type get_value_or(lvalue_reference other) const
{
return has_value() ? get_value() : static_cast<result_type>(other);
}
private:
T* pointer_;
};
/// A [ts::basic_optional]() that uses [ts::reference_optional_storage]().
/// It is an optional reference.
/// \notes `T` is the type without the reference, i.e. `optional_ref<int>`.
/// \module optional
template <typename T>
using optional_ref = basic_optional<reference_optional_storage<T>>;
/// \returns A [ts::optional_ref<T>]() to the pointee of `ptr` or `nullopt`.
/// \module optional
template <typename T>
optional_ref<T> ref(T* ptr) noexcept
{
return ptr ? optional_ref<T>(*ptr) : nullopt;
}
/// \returns A [ts::optional_ref<T>]() to `const` to the pointee of `ptr` or `nullopt`.
/// \module optional
template <typename T>
optional_ref<const T> cref(const T* ptr) noexcept
{
return ptr ? optional_ref<const T>(*ptr) : nullopt;
}
/// A [ts::basic_optional]() that uses [ts::reference_optional_storage]() with `XValue` being `true`.
/// It is an optional reference to an xvalue,
/// i.e. an lvalue that can be moved from, like returned by `std::move()`.
/// \notes `T` is the type without the reference, i.e. `optional_xvalue_ref<int>`.
/// \module optional
template <typename T>
using optional_xvalue_ref = basic_optional<reference_optional_storage<T, true>>;
/// \returns A [ts::optional_xvalue_ref<T>]() to the pointee of `ptr` or `nullopt`.
/// \notes The pointee will be moved from when you call `value()`.
/// \module optional
template <typename T>
optional_xvalue_ref<T> xref(T* ptr) noexcept
{
return ptr ? optional_xvalue_ref<T>(*ptr) : nullopt;
}
/// \returns A [ts::optional<T>]() containing a copy of the value of `ref`
/// if there is any value.
/// \requires `T` must be copyable.
/// \module optional
template <typename T>
optional<typename std::remove_const<T>::type> copy(const optional_ref<T>& ref)
{
return ref.has_value() ? make_optional(ref.value()) : nullopt;
}
/// \returns A [ts::optional<T>]() containing a copy of the value of `ref` created by move constructing
/// if there is any value.
/// \requires `T` must be moveable.
/// \module optional
template <typename T>
optional<T> move(const optional_xvalue_ref<T>& ref) noexcept(
std::is_nothrow_move_constructible<T>::value)
{
return ref.has_value() ? make_optional(ref.value()) : nullopt;
}
} // namespace type_safe
#endif // TYPE_SAFE_OPTIONAL_REF_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: rtl_old_testint64.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-05-03 09:10:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// LLA:
// this file is converted to use with testshl2
// original was placed in sal/test/textenc.cxx
// fndef _OSL_DIAGNOSE_H_
// nclude <osl/diagnose.h>
// #endif
#include <sal/types.h>
#define TEST_ENSURE(c, m) CPPUNIT_ASSERT_MESSAGE((m), (c))
// #if OSL_DEBUG_LEVEL > 0
// #define TEST_ENSURE(c, m) OSL_ENSURE(c, m)
// #else
// #define TEST_ENSURE(c, m) OSL_VERIFY(c)
// #endif
#include <cppunit/simpleheader.hxx>
// -----------------------------------------------------------------------------
namespace rtl_math
{
class int64 : public CppUnit::TestFixture
{
public:
void test_int64();
CPPUNIT_TEST_SUITE( int64 );
CPPUNIT_TEST( test_int64 );
CPPUNIT_TEST_SUITE_END( );
};
void int64::test_int64()
{
#ifndef SAL_INT64_IS_STRUCT
#ifdef UNX
sal_Int64 i1 = -3223372036854775807LL;
sal_uInt64 u1 = 5223372036854775807ULL;
#else
sal_Int64 i1 = -3223372036854775807;
sal_uInt64 u1 = 5223372036854775807;
#endif
sal_Int64 i2 = 0;
sal_uInt64 u2 = 0;
#else
sal_Int64 i1;
sal_setInt64(&i1, 3965190145L, -750499787L);
sal_Int64 i2 = { 0, 0 };
sal_uInt64 u1;
sal_setUInt64(&u1, 1651507199UL, 1216161073UL);
sal_uInt64 u2 = {0, 0 };
#endif
sal_uInt32 low = 0;
sal_Int32 high = 0;
sal_getInt64(i1, &low, &high);
sal_setInt64(&i2, low, high);
sal_uInt32 ulow = 0;
sal_uInt32 uhigh = 0;
sal_getUInt64(u1, &ulow, &uhigh);
sal_setUInt64(&u2, ulow, uhigh);
#ifndef SAL_INT64_IS_STRUCT
TEST_ENSURE( i1 == i2, "test_int64 error 1");
TEST_ENSURE( u1 == u2, "test_int64 error 2");
#else
TEST_ENSURE( (i1.Part1 == i2.Part1) && (i1.Part2 == i2.Part2),
"test_int64 error 1");
TEST_ENSURE( (u1.Part1 == u2.Part1) && (u1.Part2 == u2.Part2),
"test_int64 error 2");
#endif
return;
}
} // namespace rtl_math
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_math::int64, "rtl_math" );
// -----------------------------------------------------------------------------
NOADDITIONAL;
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.162); FILE MERGED 2005/09/05 17:45:06 rt 1.2.162.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rtl_old_testint64.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:46: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
*
************************************************************************/
// LLA:
// this file is converted to use with testshl2
// original was placed in sal/test/textenc.cxx
// fndef _OSL_DIAGNOSE_H_
// nclude <osl/diagnose.h>
// #endif
#include <sal/types.h>
#define TEST_ENSURE(c, m) CPPUNIT_ASSERT_MESSAGE((m), (c))
// #if OSL_DEBUG_LEVEL > 0
// #define TEST_ENSURE(c, m) OSL_ENSURE(c, m)
// #else
// #define TEST_ENSURE(c, m) OSL_VERIFY(c)
// #endif
#include <cppunit/simpleheader.hxx>
// -----------------------------------------------------------------------------
namespace rtl_math
{
class int64 : public CppUnit::TestFixture
{
public:
void test_int64();
CPPUNIT_TEST_SUITE( int64 );
CPPUNIT_TEST( test_int64 );
CPPUNIT_TEST_SUITE_END( );
};
void int64::test_int64()
{
#ifndef SAL_INT64_IS_STRUCT
#ifdef UNX
sal_Int64 i1 = -3223372036854775807LL;
sal_uInt64 u1 = 5223372036854775807ULL;
#else
sal_Int64 i1 = -3223372036854775807;
sal_uInt64 u1 = 5223372036854775807;
#endif
sal_Int64 i2 = 0;
sal_uInt64 u2 = 0;
#else
sal_Int64 i1;
sal_setInt64(&i1, 3965190145L, -750499787L);
sal_Int64 i2 = { 0, 0 };
sal_uInt64 u1;
sal_setUInt64(&u1, 1651507199UL, 1216161073UL);
sal_uInt64 u2 = {0, 0 };
#endif
sal_uInt32 low = 0;
sal_Int32 high = 0;
sal_getInt64(i1, &low, &high);
sal_setInt64(&i2, low, high);
sal_uInt32 ulow = 0;
sal_uInt32 uhigh = 0;
sal_getUInt64(u1, &ulow, &uhigh);
sal_setUInt64(&u2, ulow, uhigh);
#ifndef SAL_INT64_IS_STRUCT
TEST_ENSURE( i1 == i2, "test_int64 error 1");
TEST_ENSURE( u1 == u2, "test_int64 error 2");
#else
TEST_ENSURE( (i1.Part1 == i2.Part1) && (i1.Part2 == i2.Part2),
"test_int64 error 1");
TEST_ENSURE( (u1.Part1 == u2.Part1) && (u1.Part2 == u2.Part2),
"test_int64 error 2");
#endif
return;
}
} // namespace rtl_math
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_math::int64, "rtl_math" );
// -----------------------------------------------------------------------------
NOADDITIONAL;
<|endoftext|>
|
<commit_before>#define __STDC_FORMAT_MACROS
#include "parser.h"
#include "pageTags.h"
#include "util/exception.h"
#include "util/minmax.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <limits.h>
#define STREQ(src, literal) (strncmp(src, literal, strlen(literal)) == 0)
#define WH ".wowhead.com/"
#define WW ".wowwiki.com/"
#define FLUSH flush(ptr)
void Parser::flush(const char* end) {
int len = end - mNodeStart;
EASSERT(len >= 0);
if(len > 0) {
addTextNode(mNodeStart, len);
mNodeStart = end;
}
}
void Parser::parse(const char* src) {
const char* ptr = src;
mNodeStart = ptr;
mbtowc(NULL, NULL, 0); // reset shift state.
while(*ptr) {
// skip invalid utf-8 sequences.
wchar_t w;
int res = mbtowc(&w, ptr, MB_LEN_MAX);
if(res <= 0) {
if(res < 0) {
printf("Invalid UTF-8 0x%x @ pos %" PRIuPTR "\n", (unsigned char)*ptr, ptr - src);
}
FLUSH;
ptr++;
mNodeStart = ptr;
continue;
} else if(res > 1) { // valid utf-8 beyond ascii
ptr += res;
continue;
}
if(STREQ(ptr, "http://")) { // unescaped link
FLUSH;
ptr = parseUnescapedUrl(ptr);
mNodeStart = ptr;
continue;
}
char c = *ptr;
ptr++;
if(c == '[') { // start tag
while(*ptr == '[') {
ptr++;
}
const char* endPtr = strchr(ptr, ']');
if(!endPtr) {
break;
}
flush(ptr-1);
mNodeStart = ptr;
parseTag(ptr, endPtr - ptr);
ptr = endPtr + 1;
mNodeStart = ptr;
} else if(c == '\\' && *ptr == 'n') {
flush(ptr-1);
ptr++;
mNodeStart = ptr;
addLinebreakNode();
}
}
FLUSH;
}
template<class Map>
bool Parser::pageTag(const char* type, size_t typeLen, const char* tag, size_t tagLen,
Map& map)
{
if(strncmp(type, tag, typeLen) != 0)
return false;
//printf("%*s tag: %.*s\n", (int)(typeLen-1), type, (int)tagLen, tag);
const char* idString = tag + typeLen;
size_t idLen = tagLen - typeLen;
const char* space = (char*)memchr(idString, ' ', idLen);
if(space)
idLen = space - idString;
map.load();
addPageNode(map, type, idString, idLen);
return true;
}
enum CompRes {
crMatch,
crMismatch,
crIgnore,
};
static CompRes compareTag(const char* t, size_t tLen, const char* tag, size_t tagLen,
bool& hasAttributes)
{
bool match = strncmp(t, tag, tLen) == 0 &&
(tagLen == tLen || (hasAttributes = isspace(tag[tLen])));
if(!match)
return crMismatch;
return crMatch;
}
// intentional fallthrough
#define COMPARE_TAG(t, matchAction) { CompRes cr = compareTag(t, strlen(t), tag, len, hasAttributes);\
switch(cr) {\
case crIgnore: printf("Ignored tag: %s\n", t); return;\
case crMatch: matchAction\
case crMismatch: break;\
} }
#define COMPLEX_TAG(t, type, dst, end) COMPARE_TAG(t, addTagNode(type, tag, len, strlen(t), dst, end); return;)
#define END_TAG(t) COMPARE_TAG(t, addEndTag(t); return;)
#define SIMPLE_TAG(t, type) COMPLEX_TAG(t, type, t, "/" t); END_TAG("/" t)
#define C_TAG(t, type, dst, end) COMPLEX_TAG(t, type, dst, end); END_TAG("/" t)
#define FORMATTING_TAG(t, type) COMPARE_TAG(t, addFormattingTag(tag, len, strlen(t), type); return;); END_TAG("/" t)
#define SPECIAL_TAG(t, addFunc) COMPARE_TAG(t, addFunc; return;); END_TAG("/" t)
void Parser::parseTag(const char* tag, size_t len) {
bool hasAttributes;
//printf("tag: %i %.*s\n", tagState, (int)len, tag);
FORMATTING_TAG("b", BOLD);
FORMATTING_TAG("i", ITALIC);
FORMATTING_TAG("small", SMALL);
FORMATTING_TAG("s", SMALL);
FORMATTING_TAG("u", UNDERLINED);
SIMPLE_TAG("table", TABLE);
SIMPLE_TAG("tr", TR);
SIMPLE_TAG("td", TD);
//SIMPLE_TAG("li", LIST_ITEM);
SPECIAL_TAG("li", addListItem());
SPECIAL_TAG("code", addCodeTag());
SPECIAL_TAG("quote", addQuoteTag());
SIMPLE_TAG("ul", LIST);
SIMPLE_TAG("ol", LIST);
if(!strncmp("url=", tag, 4) || !strncmp("url:", tag, 4) || !strncmp("url ", tag, 4)) {
//printf("url tag: %i %.*s\n", tagState, (int)len, tag);
const char* url = tag + 4;
size_t urlLen = len - 4;
parseUrl(url, urlLen);
return;
}
//C_TAG("url", ANCHOR, "a", "/a");
COMPARE_TAG("url", return;); // get rid of empty [url] tags.
END_TAG("/url");
if(strncmp("color=", tag, 6) == 0) {
const char* idString = tag + 6;
size_t idLen = len - 6;
addColorTag(idString, idLen);
return;
}
END_TAG("/color");
#define PAGE_TAG(name, map) if(pageTag(name "=", sizeof(name), tag, len, map)) return;
PAGE_TAGS(PAGE_TAG);
// Unknown tag.
// Assume it is intended to be printed as plain text, with its brackets[].
printf("unknown tag: %.*s\n", (int)len, tag);
mNodeStart = tag-1;
flush(tag+len+1);
}
#ifdef WIN32
#include <algorithm>
static const char* memmem(const char* a, size_t alen, const char* b, size_t blen) {
const char* res = std::search(a, a+alen, b, b+blen);
if(res >= a+alen)
return NULL;
return res;
}
#endif
static bool isUrlChar(char c) {
//gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
//sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
return isalnum(c) || c == '_' || c == '#' || c == '?' || c == '/' || c == '-' ||
c == '=' || c == '.' || c == ':' || c == '&' || c == '(' || c == ')' ||
c == '%';
}
static bool isWowheadNonUrlChar(char c) {
return c == '/' || c == '?' || c == '.' || c == '-' || c == '&' || ((unsigned int)c) > 127;
}
void Parser::parseUrl(const char* url, size_t len) {
// skip starting whitespace
while(isspace(*url)) {
len--;
url++;
}
// skip broken '['
if(*url == '[') {
url++;
len--;
}
// check for start-quote mark.
if(*url == '"') {
url++;
len--;
}
// check for whitespace.
// skip whitespace and any data afterwards.
const char* ptr = url;
const char* end = url + len;
while(ptr < end) {
// also check for end-quote mark and the invalid start-tag marker.
if(isspace(*ptr) || *ptr == '"' || *ptr == '[')
break;
ptr++;
}
len = ptr - url;
// s/http://*.wowhead.com/
const char* whf = (char*)memmem(url, len, WH, strlen(WH));
if(whf) {
const char* path = whf + strlen(WH);
if(*path == '?')
path += 1;
size_t pathLen = len - (path - url);
// cut off broken parts
const char* c = path;
while(c < (path + pathLen)) {
if(isWowheadNonUrlChar(*c))
break;
c++;
}
pathLen = c - path;
if(pathLen > 0) {
addWowfootUrlNode(path, pathLen);
return;
}
}
// s/http://*.wowwiki.com/
//printf("URL test: %*s\n", (int)len, url);
const char* wwf = (char*)memmem(url, len, WW, strlen(WW));
if(wwf) {
const char* path = wwf + strlen(WW);
size_t pathLen = len - (path - url);
addWowpediaUrlNode(path, pathLen);
return;
}
// old-style wowhead paths.
if(strncmp(url, "/?", 2) == 0) {
url += 2;
len -= 2;
}
if(len > 0)
addUrlNode(url, len);
}
// returns new ptr.
const char* Parser::parseUnescapedUrl(const char* ptr) {
// find the end of the URL
const char* end = ptr;
while(isUrlChar(*end)) {
end++;
}
size_t len = end - ptr;
// check for path
const char* domain = ptr + 7;
const char* slash = (char*)memchr(domain, '/', end - domain);
if(!slash) {
addUrlNode(ptr, len);
addTextNode(ptr, len);
addUrlEndNode();
return end;
}
const char* path = slash + 1;
// we can assume wowhead urls never have slashes '/',
// or '?', except as the first character in the path.
// todo: if(len < strlen(WH))...
const char* subdomain = slash - (strlen(WH) - 1);
//printf("sd: %s\n", subdomain);
bool isWowhead = STREQ(subdomain, WH);
if(isWowhead && *path == '?')
path++;
end = path;
while(isUrlChar(*end)) {
if(isWowhead && isWowheadNonUrlChar(*end))
break;
end++;
}
size_t pathLen = end - path;
size_t urlLen = end - ptr;
//printf("uu: %i %.*s\n", isWowhead, urlLen, ptr);
if(isWowhead) {
// write name of linked entity (item, object, spell, quest, et. al)
// use PAGE_TAG code
#define UE_TAG(name, map) if(pageTag(name "=", sizeof(name), path, pathLen, map)) return end;
PAGE_TAGS(UE_TAG);
len = pathLen;
} else {
len = urlLen;
}
// wowwiki->wowpedia
const char* wwf = (char*)memmem(ptr, urlLen, WW, strlen(WW));
if(wwf) {
addWowpediaUrlNode(path, pathLen);
addStaticTextNode("http://www.wowpedia.org/");
addTextNode(path, pathLen);
addUrlEndNode();
return end;
}
if(!isWowhead)
path = ptr;
addUrlNode(path, len);
addTextNode(path, len);
addUrlEndNode();
return end;
}
<commit_msg>comments: stop URLs on linebreak.<commit_after>#define __STDC_FORMAT_MACROS
#include "parser.h"
#include "pageTags.h"
#include "util/exception.h"
#include "util/minmax.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <limits.h>
#define STREQ(src, literal) (strncmp(src, literal, strlen(literal)) == 0)
#define WH ".wowhead.com/"
#define WW ".wowwiki.com/"
#define FLUSH flush(ptr)
void Parser::flush(const char* end) {
int len = end - mNodeStart;
EASSERT(len >= 0);
if(len > 0) {
addTextNode(mNodeStart, len);
mNodeStart = end;
}
}
void Parser::parse(const char* src) {
const char* ptr = src;
mNodeStart = ptr;
mbtowc(NULL, NULL, 0); // reset shift state.
while(*ptr) {
// skip invalid utf-8 sequences.
wchar_t w;
int res = mbtowc(&w, ptr, MB_LEN_MAX);
if(res <= 0) {
if(res < 0) {
printf("Invalid UTF-8 0x%x @ pos %" PRIuPTR "\n", (unsigned char)*ptr, ptr - src);
}
FLUSH;
ptr++;
mNodeStart = ptr;
continue;
} else if(res > 1) { // valid utf-8 beyond ascii
ptr += res;
continue;
}
if(STREQ(ptr, "http://")) { // unescaped link
FLUSH;
ptr = parseUnescapedUrl(ptr);
mNodeStart = ptr;
continue;
}
char c = *ptr;
ptr++;
if(c == '[') { // start tag
while(*ptr == '[') {
ptr++;
}
const char* endPtr = strchr(ptr, ']');
if(!endPtr) {
break;
}
flush(ptr-1);
mNodeStart = ptr;
parseTag(ptr, endPtr - ptr);
ptr = endPtr + 1;
mNodeStart = ptr;
} else if(c == '\\' && *ptr == 'n') {
flush(ptr-1);
ptr++;
mNodeStart = ptr;
addLinebreakNode();
}
}
FLUSH;
}
template<class Map>
bool Parser::pageTag(const char* type, size_t typeLen, const char* tag, size_t tagLen,
Map& map)
{
if(strncmp(type, tag, typeLen) != 0)
return false;
//printf("%*s tag: %.*s\n", (int)(typeLen-1), type, (int)tagLen, tag);
const char* idString = tag + typeLen;
size_t idLen = tagLen - typeLen;
const char* space = (char*)memchr(idString, ' ', idLen);
if(space)
idLen = space - idString;
map.load();
addPageNode(map, type, idString, idLen);
return true;
}
enum CompRes {
crMatch,
crMismatch,
crIgnore,
};
static CompRes compareTag(const char* t, size_t tLen, const char* tag, size_t tagLen,
bool& hasAttributes)
{
bool match = strncmp(t, tag, tLen) == 0 &&
(tagLen == tLen || (hasAttributes = isspace(tag[tLen])));
if(!match)
return crMismatch;
return crMatch;
}
// intentional fallthrough
#define COMPARE_TAG(t, matchAction) { CompRes cr = compareTag(t, strlen(t), tag, len, hasAttributes);\
switch(cr) {\
case crIgnore: printf("Ignored tag: %s\n", t); return;\
case crMatch: matchAction\
case crMismatch: break;\
} }
#define COMPLEX_TAG(t, type, dst, end) COMPARE_TAG(t, addTagNode(type, tag, len, strlen(t), dst, end); return;)
#define END_TAG(t) COMPARE_TAG(t, addEndTag(t); return;)
#define SIMPLE_TAG(t, type) COMPLEX_TAG(t, type, t, "/" t); END_TAG("/" t)
#define C_TAG(t, type, dst, end) COMPLEX_TAG(t, type, dst, end); END_TAG("/" t)
#define FORMATTING_TAG(t, type) COMPARE_TAG(t, addFormattingTag(tag, len, strlen(t), type); return;); END_TAG("/" t)
#define SPECIAL_TAG(t, addFunc) COMPARE_TAG(t, addFunc; return;); END_TAG("/" t)
void Parser::parseTag(const char* tag, size_t len) {
bool hasAttributes;
//printf("tag: %i %.*s\n", tagState, (int)len, tag);
FORMATTING_TAG("b", BOLD);
FORMATTING_TAG("i", ITALIC);
FORMATTING_TAG("small", SMALL);
FORMATTING_TAG("s", SMALL);
FORMATTING_TAG("u", UNDERLINED);
SIMPLE_TAG("table", TABLE);
SIMPLE_TAG("tr", TR);
SIMPLE_TAG("td", TD);
//SIMPLE_TAG("li", LIST_ITEM);
SPECIAL_TAG("li", addListItem());
SPECIAL_TAG("code", addCodeTag());
SPECIAL_TAG("quote", addQuoteTag());
SIMPLE_TAG("ul", LIST);
SIMPLE_TAG("ol", LIST);
if(!strncmp("url=", tag, 4) || !strncmp("url:", tag, 4) || !strncmp("url ", tag, 4)) {
//printf("url tag: %i %.*s\n", tagState, (int)len, tag);
const char* url = tag + 4;
size_t urlLen = len - 4;
parseUrl(url, urlLen);
return;
}
//C_TAG("url", ANCHOR, "a", "/a");
COMPARE_TAG("url", return;); // get rid of empty [url] tags.
END_TAG("/url");
if(strncmp("color=", tag, 6) == 0) {
const char* idString = tag + 6;
size_t idLen = len - 6;
addColorTag(idString, idLen);
return;
}
END_TAG("/color");
#define PAGE_TAG(name, map) if(pageTag(name "=", sizeof(name), tag, len, map)) return;
PAGE_TAGS(PAGE_TAG);
// Unknown tag.
// Assume it is intended to be printed as plain text, with its brackets[].
printf("unknown tag: %.*s\n", (int)len, tag);
mNodeStart = tag-1;
flush(tag+len+1);
}
#ifdef WIN32
#include <algorithm>
static const char* memmem(const char* a, size_t alen, const char* b, size_t blen) {
const char* res = std::search(a, a+alen, b, b+blen);
if(res >= a+alen)
return NULL;
return res;
}
#endif
static bool isUrlChar(char c) {
//gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
//sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
return isalnum(c) || c == '_' || c == '#' || c == '?' || c == '/' || c == '-' ||
c == '=' || c == '.' || c == ':' || c == '&' || c == '(' || c == ')' ||
c == '%';
}
static bool isWowheadNonUrlChar(char c) {
return c == '/' || c == '?' || c == '.' || c == '-' || c == '&' || ((unsigned int)c) > 127;
}
void Parser::parseUrl(const char* url, size_t len) {
// skip starting whitespace
while(isspace(*url)) {
len--;
url++;
}
// skip broken '['
if(*url == '[') {
url++;
len--;
}
// check for start-quote mark.
if(*url == '"') {
url++;
len--;
}
// check for whitespace.
// skip whitespace and any data afterwards.
const char* ptr = url;
const char* end = url + len;
while(ptr < end) {
// also check for end-quote mark and the invalid start-tag marker.
// and linebreak.
if(isspace(*ptr) || *ptr == '"' || *ptr == '[' ||
(ptr[0] == '\\' && ptr[1] == 'n'))
break;
ptr++;
}
len = ptr - url;
// s/http://*.wowhead.com/
const char* whf = (char*)memmem(url, len, WH, strlen(WH));
if(whf) {
const char* path = whf + strlen(WH);
if(*path == '?')
path += 1;
size_t pathLen = len - (path - url);
// cut off broken parts
const char* c = path;
while(c < (path + pathLen)) {
if(isWowheadNonUrlChar(*c))
break;
c++;
}
pathLen = c - path;
if(pathLen > 0) {
addWowfootUrlNode(path, pathLen);
return;
}
}
// s/http://*.wowwiki.com/
//printf("URL test: %*s\n", (int)len, url);
const char* wwf = (char*)memmem(url, len, WW, strlen(WW));
if(wwf) {
const char* path = wwf + strlen(WW);
size_t pathLen = len - (path - url);
addWowpediaUrlNode(path, pathLen);
return;
}
// old-style wowhead paths.
if(strncmp(url, "/?", 2) == 0) {
url += 2;
len -= 2;
}
if(len > 0)
addUrlNode(url, len);
}
// returns new ptr.
const char* Parser::parseUnescapedUrl(const char* ptr) {
// find the end of the URL
const char* end = ptr;
while(isUrlChar(*end)) {
end++;
}
size_t len = end - ptr;
// check for path
const char* domain = ptr + 7;
const char* slash = (char*)memchr(domain, '/', end - domain);
if(!slash) {
addUrlNode(ptr, len);
addTextNode(ptr, len);
addUrlEndNode();
return end;
}
const char* path = slash + 1;
// we can assume wowhead urls never have slashes '/',
// or '?', except as the first character in the path.
// todo: if(len < strlen(WH))...
const char* subdomain = slash - (strlen(WH) - 1);
//printf("sd: %s\n", subdomain);
bool isWowhead = STREQ(subdomain, WH);
if(isWowhead && *path == '?')
path++;
end = path;
while(isUrlChar(*end)) {
if(isWowhead && isWowheadNonUrlChar(*end))
break;
end++;
}
size_t pathLen = end - path;
size_t urlLen = end - ptr;
//printf("uu: %i %.*s\n", isWowhead, urlLen, ptr);
if(isWowhead) {
// write name of linked entity (item, object, spell, quest, et. al)
// use PAGE_TAG code
#define UE_TAG(name, map) if(pageTag(name "=", sizeof(name), path, pathLen, map)) return end;
PAGE_TAGS(UE_TAG);
len = pathLen;
} else {
len = urlLen;
}
// wowwiki->wowpedia
const char* wwf = (char*)memmem(ptr, urlLen, WW, strlen(WW));
if(wwf) {
addWowpediaUrlNode(path, pathLen);
addStaticTextNode("http://www.wowpedia.org/");
addTextNode(path, pathLen);
addUrlEndNode();
return end;
}
if(!isWowhead)
path = ptr;
addUrlNode(path, len);
addTextNode(path, len);
addUrlEndNode();
return end;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "topojson_datasource.hpp"
#include "topojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/variant.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/extensions/index/rtree/rtree.hpp>
// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/json/topojson_grammar.hpp>
#include <mapnik/json/topojson_utils.hpp>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(topojson_datasource)
topojson_datasource::topojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(*params.get<std::string>("type"),
*params.get<std::string>("encoding","utf-8")),
file_(*params.get<std::string>("file","")),
extent_(),
tr_(new mapnik::transcoder(*params.get<std::string>("encoding","utf-8"))),
tree_(16,1)
{
if (file_.empty()) throw mapnik::datasource_exception("TopoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
{
file_ = *base + "/" + file_;
}
typedef std::istreambuf_iterator<char> base_iterator_type;
#if defined (_WINDOWS)
std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary);
#else
std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary);
#endif
if (!is.is_open())
{
throw mapnik::datasource_exception("TopoJSON Plugin: could not open: '" + file_ + "'");
}
boost::spirit::multi_pass<base_iterator_type> begin =
boost::spirit::make_default_multi_pass(base_iterator_type(is));
boost::spirit::multi_pass<base_iterator_type> end =
boost::spirit::make_default_multi_pass(base_iterator_type());
mapnik::topojson::topojson_grammar<boost::spirit::multi_pass<base_iterator_type> > g;
bool result = boost::spirit::qi::phrase_parse(begin, end, g, boost::spirit::standard_wide::space, topo_);
if (!result)
{
throw mapnik::datasource_exception("topojson_datasource: Failed parse TopoJSON file '" + file_ + "'");
}
std::size_t count = 0;
for (auto const& geom : topo_.geometries)
{
mapnik::box2d<double> bbox = boost::apply_visitor(mapnik::topojson::bounding_box_visitor(topo_), geom);
if (bbox.valid())
{
if (count == 0) extent_ = bbox;
else extent_.expand_to_include(bbox);
tree_.insert(box_type(point_type(bbox.minx(),bbox.miny()),point_type(bbox.maxx(),bbox.maxy())), count++);
}
}
}
topojson_datasource::~topojson_datasource() { }
const char * topojson_datasource::name()
{
return "topojson";
}
boost::optional<mapnik::datasource::geometry_t> topojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
return result;
}
mapnik::datasource::datasource_t topojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> topojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor topojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr topojson_datasource::features(mapnik::query const& q) const
{
std::cerr << "Resolution=" << std::get<0>(q.resolution())
<< "," << std::get<1>(q.resolution())
<< " scale_denominator=" << q.scale_denominator() << std::endl;
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& b = q.get_bbox();
if (extent_.intersects(b))
{
box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy()));
index_array_ = tree_.find(box);
return std::make_shared<topojson_featureset>(topo_, *tr_, index_array_.begin(), index_array_.end());
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr topojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
for (auto const& attr_info : desc_.get_descriptors())
{
q.add_property_name(attr_info.get_name());
}
return features(q);
}
<commit_msg>fix index<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "topojson_datasource.hpp"
#include "topojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/variant.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/extensions/index/rtree/rtree.hpp>
// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/json/topojson_grammar.hpp>
#include <mapnik/json/topojson_utils.hpp>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(topojson_datasource)
topojson_datasource::topojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(*params.get<std::string>("type"),
*params.get<std::string>("encoding","utf-8")),
file_(*params.get<std::string>("file","")),
extent_(),
tr_(new mapnik::transcoder(*params.get<std::string>("encoding","utf-8"))),
tree_(16,1)
{
if (file_.empty()) throw mapnik::datasource_exception("TopoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
{
file_ = *base + "/" + file_;
}
typedef std::istreambuf_iterator<char> base_iterator_type;
#if defined (_WINDOWS)
std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary);
#else
std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary);
#endif
if (!is.is_open())
{
throw mapnik::datasource_exception("TopoJSON Plugin: could not open: '" + file_ + "'");
}
boost::spirit::multi_pass<base_iterator_type> begin =
boost::spirit::make_default_multi_pass(base_iterator_type(is));
boost::spirit::multi_pass<base_iterator_type> end =
boost::spirit::make_default_multi_pass(base_iterator_type());
mapnik::topojson::topojson_grammar<boost::spirit::multi_pass<base_iterator_type> > g;
bool result = boost::spirit::qi::phrase_parse(begin, end, g, boost::spirit::standard_wide::space, topo_);
if (!result)
{
throw mapnik::datasource_exception("topojson_datasource: Failed parse TopoJSON file '" + file_ + "'");
}
std::size_t count = 0;
for (auto const& geom : topo_.geometries)
{
mapnik::box2d<double> bbox = boost::apply_visitor(mapnik::topojson::bounding_box_visitor(topo_), geom);
if (bbox.valid())
{
if (count == 0) extent_ = bbox;
else extent_.expand_to_include(bbox);
tree_.insert(box_type(point_type(bbox.minx(),bbox.miny()),point_type(bbox.maxx(),bbox.maxy())), count);
}
++count;
}
}
topojson_datasource::~topojson_datasource() { }
const char * topojson_datasource::name()
{
return "topojson";
}
boost::optional<mapnik::datasource::geometry_t> topojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
return result;
}
mapnik::datasource::datasource_t topojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> topojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor topojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr topojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& b = q.get_bbox();
if (extent_.intersects(b))
{
box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy()));
index_array_ = tree_.find(box);
return std::make_shared<topojson_featureset>(topo_, *tr_, index_array_.begin(), index_array_.end());
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr topojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
for (auto const& attr_info : desc_.get_descriptors())
{
q.add_property_name(attr_info.get_name());
}
return features(q);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_CONFIG_HPP
#define XTENSOR_CONFIG_HPP
#define XTENSOR_VERSION_MAJOR 0
#define XTENSOR_VERSION_MINOR 9
#define XTENSOR_VERSION_PATCH 0
// DETECT 3.6 <= clang < 3.8 for compiler bug workaround.
#ifdef __clang__
#if __clang_major__ == 3 && __clang_minor__ < 8
#define X_OLD_CLANG
#include <initializer_list>
#include <vector>
#endif
#endif
#ifndef DEFAULT_DATA_CONTAINER
#define DEFAULT_DATA_CONTAINER(T, A) uvector<T, A>
#endif
#ifndef DEFAULT_SHAPE_CONTAINER
#define DEFAULT_SHAPE_CONTAINER(T, EA, SA) \
std::vector<typename DEFAULT_DATA_CONTAINER(T, EA)::size_type, SA>
#endif
#ifndef DEFAULT_LAYOUT
#define DEFAULT_LAYOUT layout_type::row_major
#endif
#endif
<commit_msg>Release 0.10.0<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_CONFIG_HPP
#define XTENSOR_CONFIG_HPP
#define XTENSOR_VERSION_MAJOR 0
#define XTENSOR_VERSION_MINOR 10
#define XTENSOR_VERSION_PATCH 0
// DETECT 3.6 <= clang < 3.8 for compiler bug workaround.
#ifdef __clang__
#if __clang_major__ == 3 && __clang_minor__ < 8
#define X_OLD_CLANG
#include <initializer_list>
#include <vector>
#endif
#endif
#ifndef DEFAULT_DATA_CONTAINER
#define DEFAULT_DATA_CONTAINER(T, A) uvector<T, A>
#endif
#ifndef DEFAULT_SHAPE_CONTAINER
#define DEFAULT_SHAPE_CONTAINER(T, EA, SA) \
std::vector<typename DEFAULT_DATA_CONTAINER(T, EA)::size_type, SA>
#endif
#ifndef DEFAULT_LAYOUT
#define DEFAULT_LAYOUT layout_type::row_major
#endif
#endif
<|endoftext|>
|
<commit_before>#ifndef ORG_EEROS_HALFEATURES_HAL_HPP_
#define ORG_EEROS_HALFEATURES_HAL_HPP_
#include <map>
#include <string>
namespace eeros{
namespace hal{
enum Direction {
In,
Out
};
enum Type {
Logic,
Real
};
const std::map<std::string, Direction> directionOfChannel = {
{ "DigIn", In },
{ "DigOut", Out },
{ "AnalogOut", Out },
{ "AnalogIn", In },
{ "Pwm", Out },
{ "Fqd", In }
};
const std::map<std::string, Type> typeOfChannel = {
{ "DigIn", Logic },
{ "DigOut", Logic },
{ "AnalogOut", Real },
{ "AnalogIn", Real },
{ "Pwm", Real },
{ "Fqd", Real }
};
};
};
#endif /* ORG_EEROS_HALFEATURES_HAL_HPP_ */<commit_msg>repair wdt<commit_after>#ifndef ORG_EEROS_HALFEATURES_HAL_HPP_
#define ORG_EEROS_HALFEATURES_HAL_HPP_
#include <map>
#include <string>
namespace eeros{
namespace hal{
enum Direction {
In,
Out
};
enum Type {
Logic,
Real
};
const std::map<std::string, Direction> directionOfChannel = {
{ "DigIn", In },
{ "DigOut", Out },
{ "AnalogOut", Out },
{ "AnalogIn", In },
{ "Pwm", Out },
{ "Watchdog", Out },
{ "Fqd", In }
};
const std::map<std::string, Type> typeOfChannel = {
{ "DigIn", Logic },
{ "DigOut", Logic },
{ "AnalogOut", Real },
{ "AnalogIn", Real },
{ "Pwm", Real },
{ "Watchdog", Logic },
{ "Fqd", Real }
};
};
};
#endif /* ORG_EEROS_HALFEATURES_HAL_HPP_ */<|endoftext|>
|
<commit_before>/*
This file is part of KAddressBook.
Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "templateselectiondialog.h"
#include <QtCore/QAbstractTableModel>
#include <QtCore/QFile>
#include <QtGui/QLabel>
#include <QtGui/QListView>
#include <QtGui/QMouseEvent>
#include <QtGui/QStyledItemDelegate>
#include <kconfig.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kvbox.h>
class TemplatesModel : public QAbstractTableModel
{
public:
TemplatesModel( QObject *parent = 0 )
: QAbstractTableModel( parent )
{
update();
}
virtual int rowCount( const QModelIndex &parent = QModelIndex() ) const
{
if ( !parent.isValid() )
return mTemplates.count();
else
return 0;
}
virtual int columnCount( const QModelIndex &parent = QModelIndex() ) const
{
if ( !parent.isValid() )
return 2;
else
return 0;
}
virtual QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const
{
if ( !index.isValid() || index.row() >= mTemplates.count() || index.column() >= 2 )
return QVariant();
if ( role == Qt::DisplayRole ) {
if ( index.column() == 0 )
return mTemplates[ index.row() ].first;
else
return mTemplates[ index.row() ].second;
}
return QVariant();
}
virtual bool removeRows( int row, int count, const QModelIndex &parent = QModelIndex() )
{
if ( parent.isValid() || row < 0 || row >= mTemplates.count() )
return false;
beginRemoveRows( parent, row, row + count - 1 );
for ( int i = 0; i < count; ++i ) {
QFile::remove( mTemplates[ row ].second );
mTemplates.removeAt( row );
}
endRemoveRows();
return true;
}
void update()
{
beginResetModel();
mTemplates.clear();
const QStringList files = KGlobal::dirs()->findAllResources( "data" , "kaddressbook/csv-templates/*.desktop",
KStandardDirs::Recursive | KStandardDirs::NoDuplicates );
for ( int i = 0; i < files.count(); ++i ) {
KConfig config( files.at( i ), KConfig::SimpleConfig );
if ( !config.hasGroup( "csv column map" ) )
continue;
KConfigGroup group( &config, "Misc" );
mTemplates.append( qMakePair( group.readEntry( "Name" ), files.at( i ) ) );
}
endResetModel();
}
bool templatesAvailable() const
{
return !mTemplates.isEmpty();
}
private:
QList<QPair<QString, QString> > mTemplates;
};
class TemplateSelectionDelegate : public QStyledItemDelegate
{
public:
explicit TemplateSelectionDelegate( QObject *parent = 0 )
: QStyledItemDelegate( parent ), mIcon( "list-remove" )
{
}
virtual void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
QStyledItemDelegate::paint( painter, option, index );
mIcon.paint( painter, option.rect, Qt::AlignRight );
}
QSize sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
QSize hint = QStyledItemDelegate::sizeHint( option, index );
hint.setWidth( hint.width() + 16 );
return hint;
}
virtual bool editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index )
{
if ( event->type() == QEvent::MouseButtonRelease ) {
const QMouseEvent *mouseEvent = static_cast<QMouseEvent*>( event );
QRect buttonRect = option.rect;
buttonRect.setLeft( buttonRect.right() - 16 );
if ( buttonRect.contains( mouseEvent->pos() ) ) {
const QString templateName = index.data( Qt::DisplayRole ).toString();
if ( KMessageBox::questionYesNo( 0, i18n( "Do you really want to delete template '%1'?", templateName ) ) == KMessageBox::Yes ) {
model->removeRows( index.row(), 1 );
return true;
}
}
}
return QStyledItemDelegate::editorEvent( event, model, option, index );
}
private:
KIcon mIcon;
};
TemplateSelectionDialog::TemplateSelectionDialog( QWidget *parent )
: KDialog( parent )
{
setCaption( i18nc( "@title:window", "Template Selection" ) );
setButtons( Ok | Cancel );
KVBox *wdg = new KVBox( this );
setMainWidget( wdg );
new QLabel( i18nc( "@info", "Please select a template, that matches the CSV file:" ), wdg );
mView = new QListView( wdg );
mView->setModel( new TemplatesModel( this ) );
mView->setItemDelegate( new TemplateSelectionDelegate( this ) );
button( Ok )->setEnabled( false );
connect( mView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ),
this, SLOT( updateButtons() ) );
}
bool TemplateSelectionDialog::templatesAvailable() const
{
return static_cast<TemplatesModel*>( mView->model() )->templatesAvailable();
}
QString TemplateSelectionDialog::selectedTemplate() const
{
const QModelIndex rowIndex = mView->currentIndex();
const QModelIndex index = mView->model()->index( rowIndex.row(), 1 );
return index.data( Qt::DisplayRole ).toString();
}
void TemplateSelectionDialog::updateButtons()
{
button( Ok )->setEnabled( mView->currentIndex().isValid() );
}
#include "templateselectiondialog.moc"
<commit_msg>Do not allow to remove templates from system wide directories<commit_after>/*
This file is part of KAddressBook.
Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "templateselectiondialog.h"
#include <QtCore/QAbstractTableModel>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtGui/QLabel>
#include <QtGui/QListView>
#include <QtGui/QMouseEvent>
#include <QtGui/QStyledItemDelegate>
#include <kconfig.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kvbox.h>
typedef struct {
QString displayName;
QString fileName;
bool isDeletable;
} TemplateInfo;
class TemplatesModel : public QAbstractTableModel
{
public:
TemplatesModel( QObject *parent = 0 )
: QAbstractTableModel( parent )
{
update();
}
virtual int rowCount( const QModelIndex &parent = QModelIndex() ) const
{
if ( !parent.isValid() )
return mTemplates.count();
else
return 0;
}
virtual int columnCount( const QModelIndex &parent = QModelIndex() ) const
{
if ( !parent.isValid() )
return 2;
else
return 0;
}
virtual QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const
{
if ( !index.isValid() || index.row() >= mTemplates.count() || index.column() >= 2 )
return QVariant();
if ( role == Qt::DisplayRole ) {
if ( index.column() == 0 )
return mTemplates[ index.row() ].displayName;
else
return mTemplates[ index.row() ].fileName;
}
if ( role == Qt::UserRole )
return mTemplates[ index.row() ].isDeletable;
return QVariant();
}
virtual bool removeRows( int row, int count, const QModelIndex &parent = QModelIndex() )
{
if ( parent.isValid() || row < 0 || row >= mTemplates.count() )
return false;
beginRemoveRows( parent, row, row + count - 1 );
for ( int i = 0; i < count; ++i ) {
if ( !QFile::remove( mTemplates[ row ].fileName ) )
return false;
mTemplates.removeAt( row );
}
endRemoveRows();
return true;
}
void update()
{
beginResetModel();
mTemplates.clear();
const QStringList files = KGlobal::dirs()->findAllResources( "data" , "kaddressbook/csv-templates/*.desktop",
KStandardDirs::Recursive | KStandardDirs::NoDuplicates );
for ( int i = 0; i < files.count(); ++i ) {
KConfig config( files.at( i ), KConfig::SimpleConfig );
if ( !config.hasGroup( "csv column map" ) )
continue;
KConfigGroup group( &config, "Misc" );
TemplateInfo info;
info.displayName = group.readEntry( "Name" );
info.fileName = files.at( i );
const QFileInfo fileInfo( info.fileName );
info.isDeletable = QFileInfo( fileInfo.absolutePath() ).isWritable();
mTemplates.append( info );
}
endResetModel();
}
bool templatesAvailable() const
{
return !mTemplates.isEmpty();
}
private:
QList<TemplateInfo> mTemplates;
};
class TemplateSelectionDelegate : public QStyledItemDelegate
{
public:
explicit TemplateSelectionDelegate( QObject *parent = 0 )
: QStyledItemDelegate( parent ), mIcon( "list-remove" )
{
}
virtual void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
QStyledItemDelegate::paint( painter, option, index );
if ( index.data( Qt::UserRole ).toBool() )
mIcon.paint( painter, option.rect, Qt::AlignRight );
}
QSize sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
QSize hint = QStyledItemDelegate::sizeHint( option, index );
if ( index.data( Qt::UserRole ).toBool() )
hint.setWidth( hint.width() + 16 );
return hint;
}
virtual bool editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index )
{
if ( event->type() == QEvent::MouseButtonRelease && index.data( Qt::UserRole ).toBool() ) {
const QMouseEvent *mouseEvent = static_cast<QMouseEvent*>( event );
QRect buttonRect = option.rect;
buttonRect.setLeft( buttonRect.right() - 16 );
if ( buttonRect.contains( mouseEvent->pos() ) ) {
const QString templateName = index.data( Qt::DisplayRole ).toString();
if ( KMessageBox::questionYesNo( 0, i18n( "Do you really want to delete template '%1'?", templateName ) ) == KMessageBox::Yes ) {
model->removeRows( index.row(), 1 );
return true;
}
}
}
return QStyledItemDelegate::editorEvent( event, model, option, index );
}
private:
KIcon mIcon;
};
TemplateSelectionDialog::TemplateSelectionDialog( QWidget *parent )
: KDialog( parent )
{
setCaption( i18nc( "@title:window", "Template Selection" ) );
setButtons( Ok | Cancel );
KVBox *wdg = new KVBox( this );
setMainWidget( wdg );
new QLabel( i18nc( "@info", "Please select a template, that matches the CSV file:" ), wdg );
mView = new QListView( wdg );
mView->setModel( new TemplatesModel( this ) );
mView->setItemDelegate( new TemplateSelectionDelegate( this ) );
button( Ok )->setEnabled( false );
connect( mView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ),
this, SLOT( updateButtons() ) );
}
bool TemplateSelectionDialog::templatesAvailable() const
{
return static_cast<TemplatesModel*>( mView->model() )->templatesAvailable();
}
QString TemplateSelectionDialog::selectedTemplate() const
{
const QModelIndex rowIndex = mView->currentIndex();
const QModelIndex index = mView->model()->index( rowIndex.row(), 1 );
return index.data( Qt::DisplayRole ).toString();
}
void TemplateSelectionDialog::updateButtons()
{
button( Ok )->setEnabled( mView->currentIndex().isValid() );
}
#include "templateselectiondialog.moc"
<|endoftext|>
|
<commit_before>// Material.cpp
#include "Material.h"
#include "CycException.h"
#include "CycLimits.h"
#include "Timer.h"
#include "Logger.h"
#include <cmath>
#include <vector>
#include <list>
using namespace std;
using namespace boost;
list<Material*> Material::materials_;
bool Material::decay_wanted_ = false;
int Material::decay_interval_ = 1;
bool Material::type_is_recorded_ = false;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material() {
setQuantity(0);
last_update_time_ = TI->time();
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
materials_.push_back(this);
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::~Material() {
materials_.remove(this);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material(CompMapPtr comp) {
setQuantity(0);
IsoVector vec = IsoVector(comp);
last_update_time_ = TI->time();
iso_vector_ = vec;
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material(IsoVector vec) {
last_update_time_ = TI->time();
iso_vector_ = vec;
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material(const Material& other) {
iso_vector_ = other.iso_vector_;
last_update_time_ = other.last_update_time_;
quantity_ = other.quantity_;
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::absorb(mat_rsrc_ptr matToAdd) {
// @gidden figure out how to handle this with the database - mjg
// Get the given Material's composition.
double amt = matToAdd->quantity();
double ratio = ((quantity_ < cyclus::eps_rsrc()) ? 1 : quantity_/amt);
iso_vector_.mix(matToAdd->isoVector(),ratio); // @MJG_FLAG this looks like it copies isoVector()... should this return a pointer?
quantity_ += amt;
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " absorbed material ID="
<< matToAdd->ID() << ".";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr Material::extract(double mass) {
if(quantity_ < mass){
string err = "The mass ";
err += mass;
err += " cannot be extracted from Material with ID ";
err += ID_;
throw CycNegativeValueException(err);
}
// remove our mass
quantity_ -= mass;
// make a new material, set its mass
mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(iso_vector_));
new_mat->setQuantity(mass);
// we just split a resource, so keep track of the original for book keeping
new_mat->setOriginalID( this->originalID() );
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had " << mass
<< " kg extracted from it. New mass=" << quantity() << " kg.";
return new_mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr Material::extract(const CompMapPtr remove_comp, double remove_amt, MassUnit unit) {
CompMapPtr final_comp = CompMapPtr(this->unnormalizeComp(MASS));
remove_comp->massify();
assert(!final_comp->normalized());
assert(remove_comp->normalized());
double original_amt = this->mass(unit);
double final_amt = original_amt - remove_amt;
if (final_amt < -cyclus::eps_rsrc()) {
stringstream ss;
ss << "Trying to extract " << remove_amt
<< " of a something from a material that has "
<< original_amt << " of something." << endl;
throw CycNegativeValueException(ss.str());
}
int iso;
double remove_amt_i, final_amt_i;
for (CompMap::iterator it = remove_comp->begin();
it != remove_comp->end(); it++) {
// get quantity of isotope to remove
remove_amt_i = it->second * remove_amt;
if ( remove_amt_i/remove_amt <= cyclus::eps_rsrc() ) { remove_amt_i = 0; };
// get quantity of isotope to stay
iso = it->first;
final_amt_i = this->mass(iso, unit) - remove_amt_i;
// check information
if ( final_amt_i/final_amt < -cyclus::eps_rsrc() ) {
stringstream ss;
ss << "The Material " << this->ID()
<< " has insufficient material to extract the isotope : " << iso ;
throw CycNegativeValueException(ss.str());
} else if (final_amt_i/final_amt <= cyclus::eps_rsrc()) {
final_amt_i = 0;
}
// add isotope to the final comp
(*final_comp)[iso] = final_amt_i;
}
// make new material
mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(remove_comp));
new_mat->setQuantity(remove_amt, unit);
new_mat->setOriginalID( this->originalID() ); // book keeping
// adjust old material
this->iso_vector_ = IsoVector(final_comp);
this->setQuantity(final_amt, unit);
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had composition extracted.";
return new_mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::print() {
CLOG(LEV_INFO4) << "Material ID=" << ID_
<< ", quantity=" << quantity() << ", units=" << units();
CLOG(LEV_INFO5) << "Composition {";
CLOG(LEV_INFO5) << detail();
CLOG(LEV_INFO5) << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string Material::detail() {
vector<string>::iterator entry;
vector<string> entries = iso_vector_.comp()->compStrings();
for (entry = entries.begin(); entry != entries.end(); entry++) {
CLOG(LEV_INFO5) << " " << *entry;
}
return "";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::setQuantity(double quantity) {
quantity_ = quantity;
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had mass set to"
<< quantity << " kg";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::setQuantity(double quantity, MassUnit unit) {
setQuantity( convertToKg(quantity,unit) );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::quantity() {
return quantity_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::mass(MassUnit unit) {
return convertFromKg(quantity(),unit);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::mass(Iso tope, MassUnit unit) {
return convertFromKg(mass(tope),unit);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::mass(Iso tope){
double to_ret;
CompMapPtr the_comp = isoVector().comp();
the_comp->massify();
if(the_comp->count(tope) != 0) {
to_ret = the_comp->massFraction(tope)*mass(KG);
} else {
to_ret = 0;
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::convertFromKg(double mass, MassUnit to_unit) {
double converted;
switch( to_unit ) {
case G :
converted = mass*1000.0;
break;
case KG :
converted = mass;
break;
default:
throw CycException("The unit provided is not a supported mass unit.");
}
return converted;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::convertToKg(double mass, MassUnit from_unit) {
double in_kg;
switch( from_unit ) {
case G :
in_kg = mass/1000.0;
break;
case KG :
in_kg = mass;
break;
default:
throw CycException("The unit provided is not a supported mass unit.");
}
return in_kg;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::moles(){
double m_a_ratio = isoVector().comp()->mass_to_atom_ratio();
return mass(G)/m_a_ratio;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::moles(Iso tope){
double to_ret;
CompMapPtr the_comp = isoVector().comp();
the_comp->atomify();
if(the_comp->count(tope) != 0) {
to_ret = moles()*isoVector().comp()->atomFraction(tope);
} else {
to_ret = 0;
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr Material::unnormalizeComp(Basis basis){
CompMapPtr norm_comp = isoVector().comp();
double scaling;
switch(basis) {
case MASS :
norm_comp->massify();
scaling = this->mass(KG);
break;
case ATOM :
norm_comp->atomify();
scaling = this->moles();
break;
default :
throw CycException("The basis provided is not a supported CompMap basis");
}
CompMapPtr full_comp = CompMapPtr(new CompMap(*norm_comp));
CompMap::iterator it;
for( it=norm_comp->begin(); it!= norm_comp->end(); ++it ){
(*full_comp)[it->first] = scaling*(it->second);
}
return full_comp;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rsrc_ptr Material::clone() {
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " was cloned.";
rsrc_ptr mat(new Material(*this));
mat->setQuantity(this->quantity());
return mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Material::checkQuality(rsrc_ptr other){
// This will be false until proven true
bool toRet = false;
IsoVector lhs_vec = iso_vector_;
try {
// Make sure the other is a material
mat_rsrc_ptr mat = dynamic_pointer_cast<Material>(other);
if (mat) {
toRet = true;
}
} catch (...) { }
CLOG(LEV_DEBUG1) << "Material is checking quality, i.e. both are "
<< "Materials, and the answer is " << toRet << " with true = " << true << ".";
return toRet;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::decay() {
int curr_time = TI->time();
int delta_time = curr_time - last_update_time_;
isoVector().decay(delta_time);
last_update_time_ = curr_time;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::decayMaterials() {
for (list<Material*>::iterator mat = materials_.begin();
mat != materials_.end();
mat++){
(*mat)->decay();
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Material::isMaterial(rsrc_ptr rsrc)
{
mat_rsrc_ptr cast = dynamic_pointer_cast<Material>(rsrc);
return !(cast.get() == 0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::addToTable() {
Resource::addToTable();
iso_vector_.record();
}
<commit_msg>this fixes the extract_complete_inexact_comp test<commit_after>// Material.cpp
#include "Material.h"
#include "CycException.h"
#include "CycLimits.h"
#include "Timer.h"
#include "Logger.h"
#include <cmath>
#include <vector>
#include <list>
using namespace std;
using namespace boost;
list<Material*> Material::materials_;
bool Material::decay_wanted_ = false;
int Material::decay_interval_ = 1;
bool Material::type_is_recorded_ = false;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material() {
setQuantity(0);
last_update_time_ = TI->time();
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
materials_.push_back(this);
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::~Material() {
materials_.remove(this);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material(CompMapPtr comp) {
setQuantity(0);
IsoVector vec = IsoVector(comp);
last_update_time_ = TI->time();
iso_vector_ = vec;
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material(IsoVector vec) {
last_update_time_ = TI->time();
iso_vector_ = vec;
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Material::Material(const Material& other) {
iso_vector_ = other.iso_vector_;
last_update_time_ = other.last_update_time_;
quantity_ = other.quantity_;
CLOG(LEV_INFO4) << "Material ID=" << ID_ << " was created.";
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::absorb(mat_rsrc_ptr matToAdd) {
// @gidden figure out how to handle this with the database - mjg
// Get the given Material's composition.
double amt = matToAdd->quantity();
double ratio = ((quantity_ < cyclus::eps_rsrc()) ? 1 : quantity_/amt);
iso_vector_.mix(matToAdd->isoVector(),ratio); // @MJG_FLAG this looks like it copies isoVector()... should this return a pointer?
quantity_ += amt;
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " absorbed material ID="
<< matToAdd->ID() << ".";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr Material::extract(double mass) {
if(quantity_ < mass){
string err = "The mass ";
err += mass;
err += " cannot be extracted from Material with ID ";
err += ID_;
throw CycNegativeValueException(err);
}
// remove our mass
quantity_ -= mass;
// make a new material, set its mass
mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(iso_vector_));
new_mat->setQuantity(mass);
// we just split a resource, so keep track of the original for book keeping
new_mat->setOriginalID( this->originalID() );
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had " << mass
<< " kg extracted from it. New mass=" << quantity() << " kg.";
return new_mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr Material::extract(const CompMapPtr remove_comp, double remove_amt, MassUnit unit) {
CompMapPtr final_comp = CompMapPtr(this->unnormalizeComp(MASS));
remove_comp->massify();
assert(!final_comp->normalized());
assert(remove_comp->normalized());
double original_amt = this->mass(unit);
double final_amt = original_amt - remove_amt;
if (final_amt < -cyclus::eps_rsrc()) {
stringstream ss;
ss << "Trying to extract " << remove_amt
<< " of a something from a material that has "
<< original_amt << " of something." << endl;
throw CycNegativeValueException(ss.str());
}
int iso;
double remove_amt_i, final_amt_i;
for (CompMap::iterator it = remove_comp->begin();
it != remove_comp->end(); it++) {
// get quantity of isotope to remove
remove_amt_i = it->second * remove_amt;
if ( remove_amt_i/remove_amt <= cyclus::eps_rsrc() ) { remove_amt_i = 0; };
// get quantity of isotope to stay
iso = it->first;
final_amt_i = this->mass(iso, unit) - remove_amt_i;
// check information
if ( final_amt_i/final_amt < -cyclus::eps_rsrc() && abs(final_amt/final_amt_i) > cyclus::eps_rsrc()) {
stringstream ss;
ss << "The Material " << this->ID()
<< " has insufficient material to extract the isotope : " << iso ;
throw CycNegativeValueException(ss.str());
} else if (final_amt_i/final_amt <= cyclus::eps_rsrc() || abs(final_amt/final_amt_i) < cyclus::eps_rsrc()) {
final_amt_i = 0;
}
// add isotope to the final comp
(*final_comp)[iso] = final_amt_i;
}
// make new material
mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(remove_comp));
new_mat->setQuantity(remove_amt, unit);
new_mat->setOriginalID( this->originalID() ); // book keeping
// adjust old material
this->iso_vector_ = IsoVector(final_comp);
this->setQuantity(final_amt, unit);
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had composition extracted.";
return new_mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::print() {
CLOG(LEV_INFO4) << "Material ID=" << ID_
<< ", quantity=" << quantity() << ", units=" << units();
CLOG(LEV_INFO5) << "Composition {";
CLOG(LEV_INFO5) << detail();
CLOG(LEV_INFO5) << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string Material::detail() {
vector<string>::iterator entry;
vector<string> entries = iso_vector_.comp()->compStrings();
for (entry = entries.begin(); entry != entries.end(); entry++) {
CLOG(LEV_INFO5) << " " << *entry;
}
return "";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::setQuantity(double quantity) {
quantity_ = quantity;
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had mass set to"
<< quantity << " kg";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::setQuantity(double quantity, MassUnit unit) {
setQuantity( convertToKg(quantity,unit) );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::quantity() {
return quantity_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::mass(MassUnit unit) {
return convertFromKg(quantity(),unit);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::mass(Iso tope, MassUnit unit) {
return convertFromKg(mass(tope),unit);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::mass(Iso tope){
double to_ret;
CompMapPtr the_comp = isoVector().comp();
the_comp->massify();
if(the_comp->count(tope) != 0) {
to_ret = the_comp->massFraction(tope)*mass(KG);
} else {
to_ret = 0;
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::convertFromKg(double mass, MassUnit to_unit) {
double converted;
switch( to_unit ) {
case G :
converted = mass*1000.0;
break;
case KG :
converted = mass;
break;
default:
throw CycException("The unit provided is not a supported mass unit.");
}
return converted;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::convertToKg(double mass, MassUnit from_unit) {
double in_kg;
switch( from_unit ) {
case G :
in_kg = mass/1000.0;
break;
case KG :
in_kg = mass;
break;
default:
throw CycException("The unit provided is not a supported mass unit.");
}
return in_kg;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::moles(){
double m_a_ratio = isoVector().comp()->mass_to_atom_ratio();
return mass(G)/m_a_ratio;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Material::moles(Iso tope){
double to_ret;
CompMapPtr the_comp = isoVector().comp();
the_comp->atomify();
if(the_comp->count(tope) != 0) {
to_ret = moles()*isoVector().comp()->atomFraction(tope);
} else {
to_ret = 0;
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr Material::unnormalizeComp(Basis basis){
CompMapPtr norm_comp = isoVector().comp();
double scaling;
switch(basis) {
case MASS :
norm_comp->massify();
scaling = this->mass(KG);
break;
case ATOM :
norm_comp->atomify();
scaling = this->moles();
break;
default :
throw CycException("The basis provided is not a supported CompMap basis");
}
CompMapPtr full_comp = CompMapPtr(new CompMap(*norm_comp));
CompMap::iterator it;
for( it=norm_comp->begin(); it!= norm_comp->end(); ++it ){
(*full_comp)[it->first] = scaling*(it->second);
}
return full_comp;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rsrc_ptr Material::clone() {
CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " was cloned.";
rsrc_ptr mat(new Material(*this));
mat->setQuantity(this->quantity());
return mat;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Material::checkQuality(rsrc_ptr other){
// This will be false until proven true
bool toRet = false;
IsoVector lhs_vec = iso_vector_;
try {
// Make sure the other is a material
mat_rsrc_ptr mat = dynamic_pointer_cast<Material>(other);
if (mat) {
toRet = true;
}
} catch (...) { }
CLOG(LEV_DEBUG1) << "Material is checking quality, i.e. both are "
<< "Materials, and the answer is " << toRet << " with true = " << true << ".";
return toRet;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::decay() {
int curr_time = TI->time();
int delta_time = curr_time - last_update_time_;
isoVector().decay(delta_time);
last_update_time_ = curr_time;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::decayMaterials() {
for (list<Material*>::iterator mat = materials_.begin();
mat != materials_.end();
mat++){
(*mat)->decay();
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Material::isMaterial(rsrc_ptr rsrc)
{
mat_rsrc_ptr cast = dynamic_pointer_cast<Material>(rsrc);
return !(cast.get() == 0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Material::addToTable() {
Resource::addToTable();
iso_vector_.record();
}
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <fstream>
#include <cassert>
#include <set>
#include <getopt.h>
#include <osmium/index/map/all.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/visitor.hpp>
#include <osmium/geom/geojson.hpp>
#include <osmium/geom/tile.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/handler.hpp>
#include "rapid_geojson.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#pragma GCC diagnostic pop
typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_pos_type;
typedef osmium::handler::NodeLocationsForWays<index_pos_type> location_handler_type;
typedef rapidjson::Writer<rapidjson::StringBuffer> writer_type;
typedef std::set<osmium::geom::Tile> tileset_type;
class JSONFeature {
rapidjson::StringBuffer m_stream;
writer_type m_writer;
osmium::geom::RapidGeoJSONFactory<writer_type> m_factory;
public:
JSONFeature() :
m_stream(),
m_writer(m_stream),
m_factory(m_writer) {
m_writer.StartObject();
m_writer.String("type");
m_writer.String("Feature");
}
void add_point(const osmium::Node& node) {
m_factory.create_point(node);
}
void add_linestring(const osmium::Way& way) {
m_factory.create_linestring(way);
}
void add_polygon(const osmium::Way& way) {
m_factory.create_polygon(way);
}
void add_tags(const osmium::TagList& tags, const char* id_name, osmium::object_id_type id) {
m_writer.String("properties");
m_writer.StartObject();
m_writer.String(id_name);
m_writer.Double(id);
for (const auto& tag : tags) {
m_writer.String(tag.key());
m_writer.String(tag.value());
}
m_writer.EndObject();
}
void append_to(std::string& buffer) {
m_writer.EndObject();
buffer.append(m_stream.GetString(), m_stream.GetSize());
buffer.append(1, '\n');
}
}; // class JSONFeature
class JSONHandler : public osmium::handler::Handler {
std::string m_buffer;
int m_geometry_error_count;
bool m_create_polygons;
tileset_type m_tiles;
unsigned int m_zoom;
void flush_to_output() {
auto written = write(1, m_buffer.data(), m_buffer.size());
assert(written == long(m_buffer.size()));
m_buffer.clear();
}
void maybe_flush() {
if (m_buffer.size() > 1024*1024) {
flush_to_output();
}
}
public:
JSONHandler(bool create_polygons, const tileset_type& tiles, unsigned int zoom) :
m_buffer(),
m_geometry_error_count(0),
m_create_polygons(create_polygons),
m_tiles(tiles),
m_zoom(zoom) {
}
~JSONHandler() {
flush_to_output();
}
void node(const osmium::Node& node) {
if (node.tags().empty()) {
return;
}
osmium::geom::Tile tile(m_zoom, node.location());
if (!m_tiles.empty() && !m_tiles.count(tile)) {
return;
}
JSONFeature feature;
feature.add_point(node);
feature.add_tags(node.tags(), "_osm_node_id", node.id());
feature.append_to(m_buffer);
maybe_flush();
}
void way(const osmium::Way& way) {
try {
if (!m_tiles.empty()) {
bool keep = false;
for (auto ref : way.nodes()) {
osmium::geom::Tile tile(m_zoom, ref.location());
if (m_tiles.count(tile)) {
keep = true;
break;
}
}
if (!keep) {
return;
}
}
{
JSONFeature feature;
feature.add_linestring(way);
feature.add_tags(way.tags(), "_osm_way_id", way.id());
feature.append_to(m_buffer);
}
if (m_create_polygons && way.is_closed()) {
JSONFeature feature;
feature.add_polygon(way);
feature.add_tags(way.tags(), "_osm_way_id", way.id());
feature.append_to(m_buffer);
}
} catch (osmium::geometry_error&) {
++m_geometry_error_count;
} catch (osmium::invalid_location&) {
++m_geometry_error_count;
}
maybe_flush();
}
int geometry_error_count() const {
return m_geometry_error_count;
}
}; // class JSONHandler
/* ================================================== */
void print_help() {
std::cout << "minjur [OPTIONS] [INFILE]\n\n" \
<< "If INFILE is not given stdin is assumed.\n" \
<< "Output is always to stdout.\n" \
<< "\nOptions:\n" \
<< " -d, --dump=FILE Dump location cache to file after run\n" \
<< " -h, --help This help message\n" \
<< " -l, --location-store=TYPE Set location store\n" \
<< " -L, --list-location-stores Show available location stores\n" \
<< " -n, --nodes=sparse|dense Are node IDs sparse or dense?\n" \
<< " -p, --polygons Create polygons from closed ways\n" \
<< " -t, --tilefile=FILE File with tiles to filter\n" \
<< " -z, --zoom=ZOOM Zoom level for tiles (default: 15)\n";
}
tileset_type read_tiles_list(const std::string& filename, int zoom) {
tileset_type tiles;
if (!filename.empty()) {
std::ifstream file(filename);
if (! file.is_open()) {
std::cerr << "can't open file file\n";
exit(1);
}
uint32_t z;
uint32_t x;
uint32_t y;
while (file) {
file >> z;
file >> x;
file >> y;
tiles.emplace(z, x, y);
}
}
return tiles;
}
int main(int argc, char* argv[]) {
const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
static struct option long_options[] = {
{"dump", required_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"location-store", required_argument, 0, 'l'},
{"list-location-stores", no_argument, 0, 'L'},
{"nodes", required_argument, 0, 'n'},
{"polygons", no_argument, 0, 'p'},
{"tilefile", required_argument, 0, 't'},
{"zoom", required_argument, 0, 'z'},
{0, 0, 0, 0}
};
std::string location_store;
std::string locations_dump_file;
std::string tile_file_name;
bool create_polygons = false;
int zoom = 15;
bool nodes_dense = false;
while (true) {
int c = getopt_long(argc, argv, "d:hl:Ln:pt:z:", long_options, 0);
if (c == -1) {
break;
}
switch (c) {
case 'd':
locations_dump_file = optarg;
break;
case 'h':
print_help();
exit(0);
case 'l':
location_store = optarg;
break;
case 'L':
std::cout << "Available map types:\n";
for (const auto& map_type : map_factory.map_types()) {
std::cout << " " << map_type << "\n";
}
exit(0);
case 'n':
if (!strcmp(optarg, "sparse")) {
nodes_dense = false;
} else if (!strcmp(optarg, "dense")) {
nodes_dense = true;
} else {
std::cerr << "Set --nodes, -n to 'sparse' or 'dense'\n";
exit(1);
}
break;
case 'p':
create_polygons = true;
break;
case 't':
tile_file_name = optarg;
break;
case 'z':
zoom = atoi(optarg);
break;
default:
exit(1);
}
}
if (location_store.empty()) {
location_store = nodes_dense ? "dense" : "sparse";
if (map_factory.has_map_type(location_store + "_mmap_array")) {
location_store.append("_mmap_array");
} else {
location_store.append("_mem_array");
}
}
std::cerr << "Using the '" << location_store << "' location store. Use -l or -n to change this.\n";
std::string input_filename;
int remaining_args = argc - optind;
if (remaining_args > 1) {
std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE]" << std::endl;
exit(1);
} else if (remaining_args == 1) {
input_filename = argv[optind];
std::cerr << "Reading from '" << input_filename << "'...\n";
} else {
input_filename = "-";
std::cerr << "Reading from STDIN...\n";
}
tileset_type tiles { read_tiles_list(tile_file_name, zoom) };
osmium::io::Reader reader(input_filename);
std::unique_ptr<index_pos_type> index_pos = map_factory.create_map(location_store);
location_handler_type location_handler(*index_pos);
location_handler.ignore_errors();
JSONHandler json_handler(create_polygons, tiles, zoom);
osmium::apply(reader, location_handler, json_handler);
reader.close();
if (json_handler.geometry_error_count()) {
std::cerr << "Number of geometry errors (not written to output): " << json_handler.geometry_error_count() << "\n";
}
google::protobuf::ShutdownProtobufLibrary();
if (!locations_dump_file.empty()) {
std::cerr << "Writing locations store to '" << locations_dump_file << "'...\n";
int locations_fd = open(locations_dump_file.c_str(), O_WRONLY | O_CREAT, 0644);
if (locations_fd < 0) {
std::cerr << "Can not open file: " << strerror(errno) << "\n";
exit(1);
}
if (location_store.substr(0, 5) == "dense") {
index_pos->dump_as_array(locations_fd);
} else {
index_pos->dump_as_list(locations_fd);
}
close(locations_fd);
}
std::cerr << "Done.\n";
}
<commit_msg>Add more metadata to geojson properties.<commit_after>
#include <iostream>
#include <fstream>
#include <cassert>
#include <set>
#include <getopt.h>
#include <osmium/index/map/all.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/visitor.hpp>
#include <osmium/geom/geojson.hpp>
#include <osmium/geom/tile.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/handler.hpp>
#include "rapid_geojson.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#pragma GCC diagnostic pop
typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_pos_type;
typedef osmium::handler::NodeLocationsForWays<index_pos_type> location_handler_type;
typedef rapidjson::Writer<rapidjson::StringBuffer> writer_type;
typedef std::set<osmium::geom::Tile> tileset_type;
class JSONFeature {
rapidjson::StringBuffer m_stream;
writer_type m_writer;
osmium::geom::RapidGeoJSONFactory<writer_type> m_factory;
public:
JSONFeature() :
m_stream(),
m_writer(m_stream),
m_factory(m_writer) {
m_writer.StartObject();
m_writer.String("type");
m_writer.String("Feature");
}
void add_point(const osmium::Node& node) {
m_factory.create_point(node);
}
void add_linestring(const osmium::Way& way) {
m_factory.create_linestring(way);
}
void add_polygon(const osmium::Way& way) {
m_factory.create_polygon(way);
}
void add_properties(const osmium::OSMObject& object, const char* id_name) {
m_writer.String("properties");
m_writer.StartObject();
m_writer.String(id_name);
m_writer.Double(object.id());
m_writer.String("_version");
m_writer.Int(object.version());
m_writer.String("_changeset");
m_writer.Int(object.changeset());
m_writer.String("_uid");
m_writer.Int(object.uid());
m_writer.String("_user");
m_writer.String(object.user());
m_writer.String("_timestamp");
m_writer.Int(object.timestamp().seconds_since_epoch());
for (const auto& tag : object.tags()) {
m_writer.String(tag.key());
m_writer.String(tag.value());
}
m_writer.EndObject();
}
void append_to(std::string& buffer) {
m_writer.EndObject();
buffer.append(m_stream.GetString(), m_stream.GetSize());
buffer.append(1, '\n');
}
}; // class JSONFeature
class JSONHandler : public osmium::handler::Handler {
std::string m_buffer;
int m_geometry_error_count;
bool m_create_polygons;
tileset_type m_tiles;
unsigned int m_zoom;
void flush_to_output() {
auto written = write(1, m_buffer.data(), m_buffer.size());
assert(written == long(m_buffer.size()));
m_buffer.clear();
}
void maybe_flush() {
if (m_buffer.size() > 1024*1024) {
flush_to_output();
}
}
public:
JSONHandler(bool create_polygons, const tileset_type& tiles, unsigned int zoom) :
m_buffer(),
m_geometry_error_count(0),
m_create_polygons(create_polygons),
m_tiles(tiles),
m_zoom(zoom) {
}
~JSONHandler() {
flush_to_output();
}
void node(const osmium::Node& node) {
if (node.tags().empty()) {
return;
}
osmium::geom::Tile tile(m_zoom, node.location());
if (!m_tiles.empty() && !m_tiles.count(tile)) {
return;
}
JSONFeature feature;
feature.add_point(node);
feature.add_properties(node, "_osm_node_id");
feature.append_to(m_buffer);
maybe_flush();
}
void way(const osmium::Way& way) {
try {
if (!m_tiles.empty()) {
bool keep = false;
for (auto ref : way.nodes()) {
osmium::geom::Tile tile(m_zoom, ref.location());
if (m_tiles.count(tile)) {
keep = true;
break;
}
}
if (!keep) {
return;
}
}
{
JSONFeature feature;
feature.add_linestring(way);
feature.add_properties(way, "_osm_way_id");
feature.append_to(m_buffer);
}
if (m_create_polygons && way.is_closed()) {
JSONFeature feature;
feature.add_polygon(way);
feature.add_properties(way, "_osm_way_id");
feature.append_to(m_buffer);
}
} catch (osmium::geometry_error&) {
++m_geometry_error_count;
} catch (osmium::invalid_location&) {
++m_geometry_error_count;
}
maybe_flush();
}
int geometry_error_count() const {
return m_geometry_error_count;
}
}; // class JSONHandler
/* ================================================== */
void print_help() {
std::cout << "minjur [OPTIONS] [INFILE]\n\n" \
<< "If INFILE is not given stdin is assumed.\n" \
<< "Output is always to stdout.\n" \
<< "\nOptions:\n" \
<< " -d, --dump=FILE Dump location cache to file after run\n" \
<< " -h, --help This help message\n" \
<< " -l, --location-store=TYPE Set location store\n" \
<< " -L, --list-location-stores Show available location stores\n" \
<< " -n, --nodes=sparse|dense Are node IDs sparse or dense?\n" \
<< " -p, --polygons Create polygons from closed ways\n" \
<< " -t, --tilefile=FILE File with tiles to filter\n" \
<< " -z, --zoom=ZOOM Zoom level for tiles (default: 15)\n";
}
tileset_type read_tiles_list(const std::string& filename, int zoom) {
tileset_type tiles;
if (!filename.empty()) {
std::ifstream file(filename);
if (! file.is_open()) {
std::cerr << "can't open file file\n";
exit(1);
}
uint32_t z;
uint32_t x;
uint32_t y;
while (file) {
file >> z;
file >> x;
file >> y;
tiles.emplace(z, x, y);
}
}
return tiles;
}
int main(int argc, char* argv[]) {
const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
static struct option long_options[] = {
{"dump", required_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"location-store", required_argument, 0, 'l'},
{"list-location-stores", no_argument, 0, 'L'},
{"nodes", required_argument, 0, 'n'},
{"polygons", no_argument, 0, 'p'},
{"tilefile", required_argument, 0, 't'},
{"zoom", required_argument, 0, 'z'},
{0, 0, 0, 0}
};
std::string location_store;
std::string locations_dump_file;
std::string tile_file_name;
bool create_polygons = false;
int zoom = 15;
bool nodes_dense = false;
while (true) {
int c = getopt_long(argc, argv, "d:hl:Ln:pt:z:", long_options, 0);
if (c == -1) {
break;
}
switch (c) {
case 'd':
locations_dump_file = optarg;
break;
case 'h':
print_help();
exit(0);
case 'l':
location_store = optarg;
break;
case 'L':
std::cout << "Available map types:\n";
for (const auto& map_type : map_factory.map_types()) {
std::cout << " " << map_type << "\n";
}
exit(0);
case 'n':
if (!strcmp(optarg, "sparse")) {
nodes_dense = false;
} else if (!strcmp(optarg, "dense")) {
nodes_dense = true;
} else {
std::cerr << "Set --nodes, -n to 'sparse' or 'dense'\n";
exit(1);
}
break;
case 'p':
create_polygons = true;
break;
case 't':
tile_file_name = optarg;
break;
case 'z':
zoom = atoi(optarg);
break;
default:
exit(1);
}
}
if (location_store.empty()) {
location_store = nodes_dense ? "dense" : "sparse";
if (map_factory.has_map_type(location_store + "_mmap_array")) {
location_store.append("_mmap_array");
} else {
location_store.append("_mem_array");
}
}
std::cerr << "Using the '" << location_store << "' location store. Use -l or -n to change this.\n";
std::string input_filename;
int remaining_args = argc - optind;
if (remaining_args > 1) {
std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE]" << std::endl;
exit(1);
} else if (remaining_args == 1) {
input_filename = argv[optind];
std::cerr << "Reading from '" << input_filename << "'...\n";
} else {
input_filename = "-";
std::cerr << "Reading from STDIN...\n";
}
tileset_type tiles { read_tiles_list(tile_file_name, zoom) };
osmium::io::Reader reader(input_filename);
std::unique_ptr<index_pos_type> index_pos = map_factory.create_map(location_store);
location_handler_type location_handler(*index_pos);
location_handler.ignore_errors();
JSONHandler json_handler(create_polygons, tiles, zoom);
osmium::apply(reader, location_handler, json_handler);
reader.close();
if (json_handler.geometry_error_count()) {
std::cerr << "Number of geometry errors (not written to output): " << json_handler.geometry_error_count() << "\n";
}
google::protobuf::ShutdownProtobufLibrary();
if (!locations_dump_file.empty()) {
std::cerr << "Writing locations store to '" << locations_dump_file << "'...\n";
int locations_fd = open(locations_dump_file.c_str(), O_WRONLY | O_CREAT, 0644);
if (locations_fd < 0) {
std::cerr << "Can not open file: " << strerror(errno) << "\n";
exit(1);
}
if (location_store.substr(0, 5) == "dense") {
index_pos->dump_as_array(locations_fd);
} else {
index_pos->dump_as_list(locations_fd);
}
close(locations_fd);
}
std::cerr << "Done.\n";
}
<|endoftext|>
|
<commit_before>// bdlt_timetable.cpp -*-C++-*-
#include <bdlt_timetable.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_timetable_cpp,"$Id$ $CSID$")
#include <bdlt_dateutil.h>
#include <bslim_printer.h>
#include <bsl_ostream.h>
namespace BloombergLP {
namespace bdlt {
// ============================
// class Timetable_ResetProctor
// ============================
class Timetable_ResetProctor {
// This class implements a proctor that, unless its 'release' method has
// previously been invoked, automatically invokes 'reset' on a 'Timetable'
// upon destruction.
// DATA
Timetable *d_timetable_p; // managed timetable
private:
// NOT IMPLEMENTED
Timetable_ResetProctor(const Timetable_ResetProctor&);
Timetable_ResetProctor& operator=(const Timetable_ResetProctor&);
public:
// CREATORS
Timetable_ResetProctor(Timetable *timetable)
// Create a 'reset' proctor that conditionally manages the specified
// 'timetable'.
: d_timetable_p(timetable)
{
BSLS_ASSERT_SAFE(timetable);
}
~Timetable_ResetProctor()
// Destroy this object and, if 'release' has not been invoked, invoke
// the managed timetable's 'reset' method.
{
if (d_timetable_p) {
d_timetable_p->reset();
}
}
// MANIPULATORS
void release()
// Release from management the timetable currently managed by this
// proctor. If there is no managed timetable, this method has no
// effect.
{
d_timetable_p = 0;
}
};
// -------------------------
// class TimetableTransition
// -------------------------
// ACCESSORS
// Aspects
bsl::ostream& TimetableTransition::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
if (stream.bad()) {
return stream; // RETURN
}
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start(true); // 'true' -> suppress '['
stream << d_code << '@' << d_datetime;
printer.end(true); // 'true' -> suppress ']'
return stream;
}
// -------------------
// class Timetable_Day
// -------------------
// MANIPULATORS
bool Timetable_Day::addTransition(const Time& time, int code)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(0 <= code || Timetable::k_UNSET_TRANSITION_CODE == code);
int previousFinalCode = finalTransitionCode();
bsl::vector<Timetable_CompactableTransition>::iterator iter =
bsl::lower_bound(d_transitions.begin(),
d_transitions.end(),
time);
if (iter == d_transitions.end()) {
d_transitions.emplace_back(time, code);
}
else if (iter->d_time != time) {
d_transitions.insert(iter,
Timetable_CompactableTransition(time, code));
}
else {
iter->d_code = code;
}
return previousFinalCode != finalTransitionCode();
}
bool Timetable_Day::removeTransition(const Time& time)
{
bsl::vector<Timetable_CompactableTransition>::iterator iter =
bsl::lower_bound(d_transitions.begin(),
d_transitions.end(),
time);
if (iter == d_transitions.end() || iter->d_time != time) {
return false; // RETURN
}
int previousFinalCode = finalTransitionCode();
d_transitions.erase(iter);
return previousFinalCode != finalTransitionCode();
}
// ACCESSORS
int Timetable_Day::transitionCodeInEffect(const Time& time) const
{
BSLS_ASSERT(24 > time.hour());
bsl::vector<Timetable_CompactableTransition>::const_iterator iter =
bsl::upper_bound(d_transitions.begin(),
d_transitions.end(),
time);
if (iter == d_transitions.end()) {
return finalTransitionCode(); // RETURN
}
else if (iter == d_transitions.begin()) {
return d_initialTransitionCode; // RETURN
}
--iter;
return iter->d_code;
}
// ---------------
// class Timetable
// ---------------
// CREATORS
Timetable::Timetable(bslma::Allocator *basicAllocator)
: d_firstDate(9999, 12, 31)
, d_lastDate(1, 1, 1)
, d_initialTransitionCode(k_UNSET_TRANSITION_CODE)
, d_timetable(basicAllocator)
{
}
Timetable::Timetable(const Date& firstDate,
const Date& lastDate,
int initialTransitionCode,
bslma::Allocator *basicAllocator)
: d_initialTransitionCode(initialTransitionCode)
, d_timetable(basicAllocator)
{
BSLS_ASSERT(firstDate <= lastDate);
BSLS_ASSERT( 0 <= initialTransitionCode
|| k_UNSET_TRANSITION_CODE == initialTransitionCode);
setValidRange(firstDate, lastDate);
}
Timetable::Timetable(const Timetable& original,
bslma::Allocator *basicAllocator)
: d_firstDate(original.d_firstDate)
, d_lastDate(original.d_lastDate)
, d_initialTransitionCode(original.d_initialTransitionCode)
, d_timetable(original.d_timetable, basicAllocator)
{
}
// MANIPULATORS
void Timetable::addTransition(const Date& date, const Time& time, int code)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(isInRange(date));
BSLS_ASSERT(0 <= code || k_UNSET_TRANSITION_CODE == code);
Timetable_ResetProctor proctor(this);
bsl::size_t index = date - d_firstDate;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.addTransition(time, code);
d_timetable.replace(index, daily);
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
void Timetable::addTransitions(const DayOfWeek::Enum& dayOfWeek,
const Time& time,
int code,
const Date& firstDate,
const Date& lastDate)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(firstDate <= lastDate);
BSLS_ASSERT(isInRange(firstDate));
BSLS_ASSERT(isInRange(lastDate));
BSLS_ASSERT(0 <= code || k_UNSET_TRANSITION_CODE == code);
Date correctedFirstDate = DateUtil::nextDayOfWeekInclusive(dayOfWeek,
firstDate);
Date correctedLastDate = DateUtil::previousDayOfWeekInclusive(dayOfWeek,
lastDate);
for (Date date = correctedFirstDate;
date <= correctedLastDate;
date += 7) {
addTransition(date, time, code);
}
}
void Timetable::removeTransition(const Date& date, const Time& time)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(isInRange(date));
Timetable_ResetProctor proctor(this);
bsl::size_t index = date - d_firstDate;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.removeTransition(time);
d_timetable.replace(index, daily);
int code = daily.finalTransitionCode();
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
void Timetable::removeTransitions(const Date& date)
{
BSLS_ASSERT(isInRange(date));
Timetable_ResetProctor proctor(this);
bsl::size_t index = date - d_firstDate;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.removeAllTransitions();
d_timetable.replace(index, daily);
int code = daily.finalTransitionCode();
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
void Timetable::removeTransitions(const DayOfWeek::Enum& dayOfWeek,
const Time& time,
const Date& firstDate,
const Date& lastDate)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(firstDate <= lastDate);
BSLS_ASSERT(isInRange(firstDate));
BSLS_ASSERT(isInRange(lastDate));
Date correctedFirstDate = DateUtil::nextDayOfWeekInclusive(dayOfWeek,
firstDate);
Date correctedLastDate = DateUtil::previousDayOfWeekInclusive(dayOfWeek,
lastDate);
for (Date date = correctedFirstDate;
date <= correctedLastDate;
date += 7) {
removeTransition(date, time);
}
}
void Timetable::setInitialTransitionCode(int code)
{
BSLS_ASSERT(0 <= code || k_UNSET_TRANSITION_CODE == code);
d_initialTransitionCode = code;
if ( 0 < d_timetable.length()
&& d_timetable.front().initialTransitionCode()
!= d_initialTransitionCode) {
Timetable_ResetProctor proctor(this);
bsl::size_t index = 0;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
}
void Timetable::setValidRange(const Date& firstDate, const Date& lastDate)
{
BSLS_ASSERT(firstDate <= lastDate);
Timetable_ResetProctor proctor(this);
if (d_firstDate > d_lastDate) {
// The 'Timetable' has the default constructed value.
bsl::size_t n = static_cast<bsl::size_t>(lastDate - firstDate + 1);
Timetable_Day daily;
daily.setInitialTransitionCode(d_initialTransitionCode);
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.push_back(daily);
}
}
else if (firstDate > d_lastDate || lastDate < d_firstDate) {
// The 'Timetable' does not have the default constructed value and the
// current valid range does not overlap the new range.
int initialTransitionCode = d_initialTransitionCode;
reset();
d_initialTransitionCode = initialTransitionCode;
bsl::size_t n = static_cast<bsl::size_t>(lastDate - firstDate + 1);
Timetable_Day daily;
daily.setInitialTransitionCode(initialTransitionCode);
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.push_back(daily);
}
}
else {
// The 'Timetable' does not have the default constructed value and the
// current valid range overlaps the new range.
if (firstDate < d_firstDate) {
bsl::size_t n = static_cast<bsl::size_t>(d_firstDate - firstDate);
Timetable_Day daily;
daily.setInitialTransitionCode(d_initialTransitionCode);
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.insert(0, daily);
}
}
else if (firstDate > d_firstDate) {
d_timetable.remove(0, firstDate - d_firstDate);
setInitialTransitionCode(d_initialTransitionCode);
}
if (lastDate > d_lastDate) {
bsl::size_t n = static_cast<bsl::size_t>(lastDate - d_lastDate);
Timetable_Day daily;
daily.setInitialTransitionCode(
d_timetable.back().finalTransitionCode());
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.push_back(daily);
}
}
else if (lastDate < d_lastDate) {
bsl::size_t n = static_cast<bsl::size_t>(d_lastDate - lastDate);
d_timetable.remove(d_timetable.length() - n, n);
}
}
d_firstDate = firstDate;
d_lastDate = lastDate;
proctor.release();
}
// ACCESSORS
Timetable::const_iterator Timetable::begin() const
{
bsl::size_t dayIndex = 0;
while (dayIndex < d_timetable.length()
&& 0 == d_timetable[dayIndex].size()) {
++dayIndex;
}
return Timetable_ConstIterator(*this, dayIndex, 0);
}
// Aspects
bsl::ostream& Timetable::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
if (stream.bad()) {
return stream; // RETURN
}
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start();
printer.printAttribute("firstDate", d_firstDate);
printer.printAttribute("lastDate", d_lastDate);
printer.printAttribute("initialTransitionCode", d_initialTransitionCode);
if (length()) {
printer.printValue(begin(), end());
}
printer.end();
return stream;
}
// -----------------------------
// class Timetable_ConstIterator
// -----------------------------
// MANIPULATORS
Timetable_ConstIterator& Timetable_ConstIterator::operator++()
{
BSLS_ASSERT(d_dayIndex < d_timetable_p->d_timetable.length());
++d_transitionIndex;
while (d_dayIndex < d_timetable_p->d_timetable.length()
&& d_transitionIndex ==
d_timetable_p->d_timetable[d_dayIndex].size()) {
d_transitionIndex = 0;
++d_dayIndex;
}
return *this;
}
Timetable_ConstIterator& Timetable_ConstIterator::operator--()
{
BSLS_ASSERT(0 < d_dayIndex || 0 < d_transitionIndex);
if (d_transitionIndex) {
--d_transitionIndex;
}
else {
--d_dayIndex;
while (d_dayIndex
&& 0 == d_timetable_p->d_timetable[d_dayIndex].size()) {
--d_dayIndex;
}
BSLS_ASSERT_SAFE(0 < d_timetable_p->d_timetable[d_dayIndex].size());
d_transitionIndex = d_timetable_p->d_timetable[d_dayIndex].size() - 1;
}
return *this;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2018 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>correcting ASSERT<commit_after>// bdlt_timetable.cpp -*-C++-*-
#include <bdlt_timetable.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_timetable_cpp,"$Id$ $CSID$")
#include <bdlt_dateutil.h>
#include <bslim_printer.h>
#include <bsl_ostream.h>
namespace BloombergLP {
namespace bdlt {
// ============================
// class Timetable_ResetProctor
// ============================
class Timetable_ResetProctor {
// This class implements a proctor that, unless its 'release' method has
// previously been invoked, automatically invokes 'reset' on a 'Timetable'
// upon destruction.
// DATA
Timetable *d_timetable_p; // managed timetable
private:
// NOT IMPLEMENTED
Timetable_ResetProctor(const Timetable_ResetProctor&);
Timetable_ResetProctor& operator=(const Timetable_ResetProctor&);
public:
// CREATORS
Timetable_ResetProctor(Timetable *timetable)
// Create a 'reset' proctor that conditionally manages the specified
// 'timetable'.
: d_timetable_p(timetable)
{
BSLS_ASSERT_SAFE(timetable);
}
~Timetable_ResetProctor()
// Destroy this object and, if 'release' has not been invoked, invoke
// the managed timetable's 'reset' method.
{
if (d_timetable_p) {
d_timetable_p->reset();
}
}
// MANIPULATORS
void release()
// Release from management the timetable currently managed by this
// proctor. If there is no managed timetable, this method has no
// effect.
{
d_timetable_p = 0;
}
};
// -------------------------
// class TimetableTransition
// -------------------------
// ACCESSORS
// Aspects
bsl::ostream& TimetableTransition::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
if (stream.bad()) {
return stream; // RETURN
}
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start(true); // 'true' -> suppress '['
stream << d_code << '@' << d_datetime;
printer.end(true); // 'true' -> suppress ']'
return stream;
}
// -------------------
// class Timetable_Day
// -------------------
// MANIPULATORS
bool Timetable_Day::addTransition(const Time& time, int code)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(0 <= code || Timetable::k_UNSET_TRANSITION_CODE == code);
int previousFinalCode = finalTransitionCode();
bsl::vector<Timetable_CompactableTransition>::iterator iter =
bsl::lower_bound(d_transitions.begin(),
d_transitions.end(),
time);
if (iter == d_transitions.end()) {
d_transitions.emplace_back(time, code);
}
else if (iter->d_time != time) {
d_transitions.insert(iter,
Timetable_CompactableTransition(time, code));
}
else {
iter->d_code = code;
}
return previousFinalCode != finalTransitionCode();
}
bool Timetable_Day::removeTransition(const Time& time)
{
bsl::vector<Timetable_CompactableTransition>::iterator iter =
bsl::lower_bound(d_transitions.begin(),
d_transitions.end(),
time);
if (iter == d_transitions.end() || iter->d_time != time) {
return false; // RETURN
}
int previousFinalCode = finalTransitionCode();
d_transitions.erase(iter);
return previousFinalCode != finalTransitionCode();
}
// ACCESSORS
int Timetable_Day::transitionCodeInEffect(const Time& time) const
{
BSLS_ASSERT(24 > time.hour());
bsl::vector<Timetable_CompactableTransition>::const_iterator iter =
bsl::upper_bound(d_transitions.begin(),
d_transitions.end(),
time);
if (iter == d_transitions.end()) {
return finalTransitionCode(); // RETURN
}
else if (iter == d_transitions.begin()) {
return d_initialTransitionCode; // RETURN
}
--iter;
return iter->d_code;
}
// ---------------
// class Timetable
// ---------------
// CREATORS
Timetable::Timetable(bslma::Allocator *basicAllocator)
: d_firstDate(9999, 12, 31)
, d_lastDate(1, 1, 1)
, d_initialTransitionCode(k_UNSET_TRANSITION_CODE)
, d_timetable(basicAllocator)
{
}
Timetable::Timetable(const Date& firstDate,
const Date& lastDate,
int initialTransitionCode,
bslma::Allocator *basicAllocator)
: d_initialTransitionCode(initialTransitionCode)
, d_timetable(basicAllocator)
{
BSLS_ASSERT(firstDate <= lastDate);
BSLS_ASSERT( 0 <= initialTransitionCode
|| k_UNSET_TRANSITION_CODE == initialTransitionCode);
setValidRange(firstDate, lastDate);
}
Timetable::Timetable(const Timetable& original,
bslma::Allocator *basicAllocator)
: d_firstDate(original.d_firstDate)
, d_lastDate(original.d_lastDate)
, d_initialTransitionCode(original.d_initialTransitionCode)
, d_timetable(original.d_timetable, basicAllocator)
{
}
// MANIPULATORS
void Timetable::addTransition(const Date& date, const Time& time, int code)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(isInRange(date));
BSLS_ASSERT(0 <= code || k_UNSET_TRANSITION_CODE == code);
Timetable_ResetProctor proctor(this);
bsl::size_t index = date - d_firstDate;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.addTransition(time, code);
d_timetable.replace(index, daily);
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
void Timetable::addTransitions(const DayOfWeek::Enum& dayOfWeek,
const Time& time,
int code,
const Date& firstDate,
const Date& lastDate)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(firstDate <= lastDate);
BSLS_ASSERT(isInRange(firstDate));
BSLS_ASSERT(isInRange(lastDate));
BSLS_ASSERT(0 <= code || k_UNSET_TRANSITION_CODE == code);
Date correctedFirstDate = DateUtil::nextDayOfWeekInclusive(dayOfWeek,
firstDate);
Date correctedLastDate = DateUtil::previousDayOfWeekInclusive(dayOfWeek,
lastDate);
for (Date date = correctedFirstDate;
date <= correctedLastDate;
date += 7) {
addTransition(date, time, code);
}
}
void Timetable::removeTransition(const Date& date, const Time& time)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(isInRange(date));
Timetable_ResetProctor proctor(this);
bsl::size_t index = date - d_firstDate;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.removeTransition(time);
d_timetable.replace(index, daily);
int code = daily.finalTransitionCode();
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
void Timetable::removeTransitions(const Date& date)
{
BSLS_ASSERT(isInRange(date));
Timetable_ResetProctor proctor(this);
bsl::size_t index = date - d_firstDate;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.removeAllTransitions();
d_timetable.replace(index, daily);
int code = daily.finalTransitionCode();
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
void Timetable::removeTransitions(const DayOfWeek::Enum& dayOfWeek,
const Time& time,
const Date& firstDate,
const Date& lastDate)
{
BSLS_ASSERT(24 > time.hour());
BSLS_ASSERT(firstDate <= lastDate);
BSLS_ASSERT(isInRange(firstDate));
BSLS_ASSERT(isInRange(lastDate));
Date correctedFirstDate = DateUtil::nextDayOfWeekInclusive(dayOfWeek,
firstDate);
Date correctedLastDate = DateUtil::previousDayOfWeekInclusive(dayOfWeek,
lastDate);
for (Date date = correctedFirstDate;
date <= correctedLastDate;
date += 7) {
removeTransition(date, time);
}
}
void Timetable::setInitialTransitionCode(int code)
{
BSLS_ASSERT(0 <= code || k_UNSET_TRANSITION_CODE == code);
d_initialTransitionCode = code;
if ( 0 < d_timetable.length()
&& d_timetable.front().initialTransitionCode()
!= d_initialTransitionCode) {
Timetable_ResetProctor proctor(this);
bsl::size_t index = 0;
Timetable_Day daily(d_timetable[index]);
bool roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
while (roll && index < d_timetable.length()) {
daily = d_timetable[index];
roll = daily.setInitialTransitionCode(code);
d_timetable.replace(index, daily);
++index;
}
proctor.release();
}
}
void Timetable::setValidRange(const Date& firstDate, const Date& lastDate)
{
BSLS_ASSERT(firstDate <= lastDate);
Timetable_ResetProctor proctor(this);
if (d_firstDate > d_lastDate) {
// The 'Timetable' has the default constructed value.
bsl::size_t n = static_cast<bsl::size_t>(lastDate - firstDate + 1);
Timetable_Day daily;
daily.setInitialTransitionCode(d_initialTransitionCode);
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.push_back(daily);
}
}
else if (firstDate > d_lastDate || lastDate < d_firstDate) {
// The 'Timetable' does not have the default constructed value and the
// current valid range does not overlap the new range.
int initialTransitionCode = d_initialTransitionCode;
reset();
d_initialTransitionCode = initialTransitionCode;
bsl::size_t n = static_cast<bsl::size_t>(lastDate - firstDate + 1);
Timetable_Day daily;
daily.setInitialTransitionCode(initialTransitionCode);
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.push_back(daily);
}
}
else {
// The 'Timetable' does not have the default constructed value and the
// current valid range overlaps the new range.
if (firstDate < d_firstDate) {
bsl::size_t n = static_cast<bsl::size_t>(d_firstDate - firstDate);
Timetable_Day daily;
daily.setInitialTransitionCode(d_initialTransitionCode);
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.insert(0, daily);
}
}
else if (firstDate > d_firstDate) {
d_timetable.remove(0, firstDate - d_firstDate);
setInitialTransitionCode(d_initialTransitionCode);
}
if (lastDate > d_lastDate) {
bsl::size_t n = static_cast<bsl::size_t>(lastDate - d_lastDate);
Timetable_Day daily;
daily.setInitialTransitionCode(
d_timetable.back().finalTransitionCode());
for (bsl::size_t i = 0; i < n; ++i) {
d_timetable.push_back(daily);
}
}
else if (lastDate < d_lastDate) {
bsl::size_t n = static_cast<bsl::size_t>(d_lastDate - lastDate);
d_timetable.remove(d_timetable.length() - n, n);
}
}
d_firstDate = firstDate;
d_lastDate = lastDate;
proctor.release();
}
// ACCESSORS
Timetable::const_iterator Timetable::begin() const
{
bsl::size_t dayIndex = 0;
while (dayIndex < d_timetable.length()
&& 0 == d_timetable[dayIndex].size()) {
++dayIndex;
}
return Timetable_ConstIterator(*this, dayIndex, 0);
}
// Aspects
bsl::ostream& Timetable::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
if (stream.bad()) {
return stream; // RETURN
}
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start();
printer.printAttribute("firstDate", d_firstDate);
printer.printAttribute("lastDate", d_lastDate);
printer.printAttribute("initialTransitionCode", d_initialTransitionCode);
if (length()) {
printer.printValue(begin(), end());
}
printer.end();
return stream;
}
// -----------------------------
// class Timetable_ConstIterator
// -----------------------------
// MANIPULATORS
Timetable_ConstIterator& Timetable_ConstIterator::operator++()
{
BSLS_ASSERT(d_dayIndex < d_timetable_p->d_timetable.length());
++d_transitionIndex;
while (d_dayIndex < d_timetable_p->d_timetable.length()
&& d_transitionIndex ==
d_timetable_p->d_timetable[d_dayIndex].size()) {
d_transitionIndex = 0;
++d_dayIndex;
}
return *this;
}
Timetable_ConstIterator& Timetable_ConstIterator::operator--()
{
BSLS_ASSERT(0 < d_dayIndex || 0 < d_transitionIndex);
if (d_transitionIndex) {
--d_transitionIndex;
}
else {
--d_dayIndex;
while (d_dayIndex
&& 0 == d_timetable_p->d_timetable[d_dayIndex].size()) {
--d_dayIndex;
}
BSLS_ASSERT(0 < d_timetable_p->d_timetable[d_dayIndex].size());
d_transitionIndex = d_timetable_p->d_timetable[d_dayIndex].size() - 1;
}
return *this;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2018 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* lxqt-connman-applet - a gui frontend for connman
*
* Copyright: 2014-2015 Christian Surlykke
*
* This program or 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.
* 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QDebug>
#include <QMenu>
#include <QString>
#include <QStringList>
#include <QActionGroup>
#include <QLabel>
#include <QVariant>
#include <LXQt/Settings>
#include <QDBusArgument>
#include "manager.h"
#include "technology.h"
#include "iconproducer.h"
#include "ui_strings.h"
#include "systemtray.h"
SystemTray::SystemTray(QObject *parent) :
QSystemTrayIcon(parent),
technologyEntries(this),
serviceEntries(this),
technologyHeading(this),
servicesHeading(this),
quitAction(tr("Quit"), this),
trayIcon(":/icons/network-wired.png")
{
technologyEntries.setExclusive(false);
QLabel* technologyHeadingLabel = new QLabel("<b>" + tr("Technologies:") + "</b>");
technologyHeadingLabel->setMargin(5);
technologyHeading.setDefaultWidget(technologyHeadingLabel);
QLabel* servicesHeadingLabel = new QLabel("<b>" + tr("Services:") + "</b>");
servicesHeadingLabel->setMargin(5);
servicesHeading.setDefaultWidget(servicesHeadingLabel);
quitAction.setIcon(QIcon::fromTheme("application-exit"));
setContextMenu(new QMenu());
connect(contextMenu(), SIGNAL(aboutToShow()), this, SLOT(buildMenu()));
connect(&quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(&technologyEntries, SIGNAL(triggered(QAction*)), this, SLOT(onTechnologyClicked(QAction*)));
connect(&serviceEntries, SIGNAL(triggered(QAction*)), this, SLOT(onServiceClicked(QAction*)));
connect(Manager::instance(), SIGNAL(connectionStateChanged()), this, SLOT(updateIcon()));
connect(IconProducer::instance(), SIGNAL(iconsChanged()), this, SLOT(updateIcon()));
updateIcon();
}
void SystemTray::updateIcon()
{
switch (Manager::instance()->connectionState())
{
case Manager::Disconnected:
setIcon(IconProducer::instance()->disconnected());
break;
case Manager::Connected_Wired:
setIcon(IconProducer::instance()->wired_connected());
break;
default:
setIcon(IconProducer::instance()->wireless(Manager::instance()->signalStrength()));
}
}
void SystemTray::buildMenu()
{
qDebug() << "Building menu..." ;
contextMenu()->clear();
contextMenu()->addAction(&technologyHeading);
foreach (Technology* technology, Manager::instance()->technologies())
{
QAction *action = contextMenu()->addAction(uiString(technology->name()));
action->setCheckable(true);
action->setChecked(technology->powered());
technologyEntries.addAction(action);
action->setData(QVariant::fromValue<QDBusObjectPath>(technology->path()));
}
contextMenu()->addSeparator();
contextMenu()->addAction(&servicesHeading);
foreach (Service* service, Manager::instance()->services())
{
QAction* action = contextMenu()->addAction("");
serviceEntries.addAction(action);
update(action, service);
}
contextMenu()->addSeparator();
contextMenu()->addAction(&quitAction);
}
void SystemTray::update(QAction *action, Service *service)
{
QString actionText;
QIcon actionIcon;
if (service->type() == "wifi")
{
actionIcon = IconProducer::instance()->wireless(service->signalStrength());
actionText = service->name();
}
else if (service->type() == "ethernet")
{
actionText = QString("%1 (%2)").arg(uiString(service->name())).arg(uiString(service->interfaceName()));
}
else
{
actionText = uiString(service->name());
}
if (service->state() == "association")
{
actionText.append(" (a)");
}
else if (service->state() == "configuration")
{
actionText.append(" (c)");
}
else if (service->state() == "ready")
{
actionText.append(" (R)");
}
action->setIcon(actionIcon);
action->setText(actionText);
action->setData(QVariant::fromValue<QDBusObjectPath>(service->path()));
action->setCheckable(true);
action->setChecked(service->state() == "online");
}
void SystemTray::onTechnologyClicked(QAction *action)
{
QDBusObjectPath path = action->data().value<QDBusObjectPath>();
qDebug() << path.path() << "clicked";
Technology *technology = Manager::instance()->technology(path) ;
if (! technology)
{
qWarning() << "Invalid technology clicked:" << path.path();
return;
}
technology->togglePowered();
}
void SystemTray::onServiceClicked(QAction *action)
{
QDBusObjectPath path = action->data().value<QDBusObjectPath>();
Service* service = Manager::instance()->service(path);
if (! service)
{
qWarning() << "Invalid service clicked:" << path.path();
return;
}
qDebug() << "Service" << service->name() << "clicked";
qDebug() << "State:" << service->state();
if (service->state() == "idle" || service->state() == "failure")
{
qDebug() << "Connect...";
service->Connect();
}
else if (service->state() == "online")
{
qDebug() << "disconnect...";
service->disconnect();
}
}
<commit_msg>Allow disconnect when service semiconnected<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* lxqt-connman-applet - a gui frontend for connman
*
* Copyright: 2014-2015 Christian Surlykke
*
* This program or 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.
* 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QDebug>
#include <QMenu>
#include <QString>
#include <QStringList>
#include <QActionGroup>
#include <QLabel>
#include <QVariant>
#include <LXQt/Settings>
#include <QDBusArgument>
#include "manager.h"
#include "technology.h"
#include "iconproducer.h"
#include "ui_strings.h"
#include "systemtray.h"
SystemTray::SystemTray(QObject *parent) :
QSystemTrayIcon(parent),
technologyEntries(this),
serviceEntries(this),
technologyHeading(this),
servicesHeading(this),
quitAction(tr("Quit"), this),
trayIcon(":/icons/network-wired.png")
{
technologyEntries.setExclusive(false);
QLabel* technologyHeadingLabel = new QLabel("<b>" + tr("Technologies:") + "</b>");
technologyHeadingLabel->setMargin(5);
technologyHeading.setDefaultWidget(technologyHeadingLabel);
QLabel* servicesHeadingLabel = new QLabel("<b>" + tr("Services:") + "</b>");
servicesHeadingLabel->setMargin(5);
servicesHeading.setDefaultWidget(servicesHeadingLabel);
quitAction.setIcon(QIcon::fromTheme("application-exit"));
setContextMenu(new QMenu());
connect(contextMenu(), SIGNAL(aboutToShow()), this, SLOT(buildMenu()));
connect(&quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(&technologyEntries, SIGNAL(triggered(QAction*)), this, SLOT(onTechnologyClicked(QAction*)));
connect(&serviceEntries, SIGNAL(triggered(QAction*)), this, SLOT(onServiceClicked(QAction*)));
connect(Manager::instance(), SIGNAL(connectionStateChanged()), this, SLOT(updateIcon()));
connect(IconProducer::instance(), SIGNAL(iconsChanged()), this, SLOT(updateIcon()));
updateIcon();
}
void SystemTray::updateIcon()
{
switch (Manager::instance()->connectionState())
{
case Manager::Disconnected:
setIcon(IconProducer::instance()->disconnected());
break;
case Manager::Connected_Wired:
setIcon(IconProducer::instance()->wired_connected());
break;
default:
setIcon(IconProducer::instance()->wireless(Manager::instance()->signalStrength()));
}
}
void SystemTray::buildMenu()
{
qDebug() << "Building menu..." ;
contextMenu()->clear();
contextMenu()->addAction(&technologyHeading);
foreach (Technology* technology, Manager::instance()->technologies())
{
QAction *action = contextMenu()->addAction(uiString(technology->name()));
action->setCheckable(true);
action->setChecked(technology->powered());
technologyEntries.addAction(action);
action->setData(QVariant::fromValue<QDBusObjectPath>(technology->path()));
}
contextMenu()->addSeparator();
contextMenu()->addAction(&servicesHeading);
foreach (Service* service, Manager::instance()->services())
{
QAction* action = contextMenu()->addAction("");
serviceEntries.addAction(action);
update(action, service);
}
contextMenu()->addSeparator();
contextMenu()->addAction(&quitAction);
}
void SystemTray::update(QAction *action, Service *service)
{
QString actionText;
QIcon actionIcon;
if (service->type() == "wifi")
{
actionIcon = IconProducer::instance()->wireless(service->signalStrength());
actionText = service->name();
}
else if (service->type() == "ethernet")
{
actionText = QString("%1 (%2)").arg(uiString(service->name())).arg(uiString(service->interfaceName()));
}
else
{
actionText = uiString(service->name());
}
if (service->state() == "association")
{
actionText.append(" (a)");
}
else if (service->state() == "configuration")
{
actionText.append(" (c)");
}
else if (service->state() == "ready")
{
actionText.append(" (R)");
}
action->setIcon(actionIcon);
action->setText(actionText);
action->setData(QVariant::fromValue<QDBusObjectPath>(service->path()));
action->setCheckable(true);
action->setChecked(service->state() == "online");
}
void SystemTray::onTechnologyClicked(QAction *action)
{
QDBusObjectPath path = action->data().value<QDBusObjectPath>();
qDebug() << path.path() << "clicked";
Technology *technology = Manager::instance()->technology(path) ;
if (! technology)
{
qWarning() << "Invalid technology clicked:" << path.path();
return;
}
technology->togglePowered();
}
void SystemTray::onServiceClicked(QAction *action)
{
QDBusObjectPath path = action->data().value<QDBusObjectPath>();
Service* service = Manager::instance()->service(path);
if (! service)
{
qWarning() << "Invalid service clicked:" << path.path();
return;
}
qDebug() << "Service" << service->name() << "clicked";
qDebug() << "State:" << service->state();
if (service->state() == "idle" || service->state() == "failure")
{
qDebug() << "Connect...";
service->Connect();
}
else
{
qDebug() << "disconnect...";
service->disconnect();
}
}
<|endoftext|>
|
<commit_before>
#ifdef __OBJC__
#define OBJC_CLASS(name) @class name
#else
#define OBJC_CLASS(name) typedef struct objc_object name
#endif
<commit_msg>Fix for compiling.<commit_after>
#ifndef AT_LANG_H
#define AT_LANG_H
#ifdef __OBJC__
#define OBJC_CLASS(name) @class name
#else
#define OBJC_CLASS(name) typedef struct objc_object name
#endif
#endif
<|endoftext|>
|
<commit_before>void surfaces() {
//Draw 2-Dim functions
// To see the output of this macro, click begin_html <a href="gif/surfaces.gif">here</a> end_html
//Author: Rene Brun
TCanvas *c1 = new TCanvas("c1","Surfaces Drawing Options",200,10,700,900);
c1->SetFillColor(42);
gStyle->SetFrameFillColor(42);
auto title = new TPaveText(.2,0.96,.8,.995);
title->SetFillColor(33);
title->AddText("Examples of Surface options");
title->Draw();
auto pad1 = new TPad("pad1","Gouraud shading",0.03,0.50,0.98,0.95,21);
auto pad2 = new TPad("pad2","Color mesh",0.03,0.02,0.98,0.48,21);
pad1->Draw();
pad2->Draw();
//
// We generate a 2-D function
TF2 *f2 = new TF2("f2","x**2 + y**2 - x**3 -8*x*y**4",-1,1.2,-1.5,1.5);
f2->SetContour(48);
f2->SetFillColor(45);
// Draw this function in pad1 with Gouraud shading option
pad1->cd();
pad1->SetPhi(-80);
pad1->SetLogz();
f2->Draw("surf4");
// Draw this function in pad2 with color mesh option
pad2->cd();
pad2->SetTheta(25);
pad2->SetPhi(-110);
pad2->SetLogz();
f2->Draw("surf1");
//add axis titles. The titles are set on the intermediate
//histogram used for visualisation. We must force this histogram
//to be created, then force the redrawing of the two pads
pad2->Update();
f2->GetHistogram()->GetXaxis()->SetTitle("x title");
f2->GetHistogram()->GetYaxis()->SetTitle("y title");
f2->GetHistogram()->GetXaxis()->SetTitleOffset(1.4);
f2->GetHistogram()->GetYaxis()->SetTitleOffset(1.4);
pad1->Modified();
pad2->Modified();
}
<commit_msg>Either auto only, or good old correct declarations.<commit_after>void surfaces() {
//Draw 2-Dim functions
// To see the output of this macro, click begin_html <a href="gif/surfaces.gif">here</a> end_html
//Author: Rene Brun
TCanvas *c1 = new TCanvas("c1","Surfaces Drawing Options",200,10,700,900);
c1->SetFillColor(42);
gStyle->SetFrameFillColor(42);
TPaveText *title = new TPaveText(.2,0.96,.8,.995);
title->SetFillColor(33);
title->AddText("Examples of Surface options");
title->Draw();
TPad *pad1 = new TPad("pad1","Gouraud shading",0.03,0.50,0.98,0.95,21);
TPad *pad2 = new TPad("pad2","Color mesh",0.03,0.02,0.98,0.48,21);
pad1->Draw();
pad2->Draw();
//
// We generate a 2-D function
TF2 *f2 = new TF2("f2","x**2 + y**2 - x**3 -8*x*y**4",-1,1.2,-1.5,1.5);
f2->SetContour(48);
f2->SetFillColor(45);
// Draw this function in pad1 with Gouraud shading option
pad1->cd();
pad1->SetPhi(-80);
pad1->SetLogz();
f2->Draw("surf4");
// Draw this function in pad2 with color mesh option
pad2->cd();
pad2->SetTheta(25);
pad2->SetPhi(-110);
pad2->SetLogz();
f2->Draw("surf1");
//add axis titles. The titles are set on the intermediate
//histogram used for visualisation. We must force this histogram
//to be created, then force the redrawing of the two pads
pad2->Update();
f2->GetHistogram()->GetXaxis()->SetTitle("x title");
f2->GetHistogram()->GetYaxis()->SetTitle("y title");
f2->GetHistogram()->GetXaxis()->SetTitleOffset(1.4);
f2->GetHistogram()->GetYaxis()->SetTitleOffset(1.4);
pad1->Modified();
pad2->Modified();
}
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct CondorcetVoting {
int winner(vector <string> votes) {
const int cc = sz(votes[0]);
fr(i, cc) {
bool f = true;
fr(j, cc) {
int c = 0;
ei(k, votes) {
if (k[i] < k[j]) --c;
if (k[i] > k[j]) ++c;
}
if (c <= 0) {
f = false;
break;
} else {
cout << i << " preferred to " << j << endl;
}
}
if (f) return i;
}
return -1;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
CondorcetVoting *obj;
int answer;
obj = new CondorcetVoting();
clock_t startTime = clock();
answer = obj->winner(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
int p1;
// ----- test 0 -----
disabled = false;
p0 = {"acbd","bacd","bdca"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"abc","bca","cab"};
p1 = -1;
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"cezdqcw"};
p1 = -1;
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"abcd","abcd","abcd","abcd","abcd","abcd","cbad","cbad","cbad","cbad","cbad","dbca","cbda","cbda"};
p1 = 1;
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 4 -----
disabled = false;
p0 = {"abbcbbbaaccaaccbbacbbbaacbccbccacaaacaacaaacbccaac","accbabcaacacbcccbbccbbcaccccccbbcbbcbaccbcbcacbcbc","acacaaabccaaaccabbaaaacabaaabacacbaacbcccbccbcbacb","acbcbabaabbcaababaacbabcacbaccabbaaacccbcabbbcacba","cbbbacbbacccbbabbbcbaabaaaacaacbcbccbaaccbcaaccbcb","cbacbbcbbcbcaaabccabcabbcbacaaabccabbcbacbbacbbaca","cacaabccbbbaaacccacbbcacababbcaaabccbbacbbbccacbaa","bccbbabaaaababcbabbbbcbcacbcbcbacccacacacacacacaab","bccabcaabcabbccaaccbcabaaabbbcaabaaabbbbabbbaabaac","accccbabaaaabcbacabbcbbacaacaaaacccbbbcacaccccaaac","cccbcaababbaacaaabbbaabbccccacaacbacaacbbbaacccbbb","bccccaccbcbbaaaaaaaaccbababcabaaccacbbabbbcabbaaca","cbacacaabbccacaabbbbbbccabcbbaccacbcacacacbccbcbcc","baabcabccaaaaccbaacaaccacccbcbbaaacacaccbcaacbbbba","bccaaaabcbbcbbbbbcaabaacccbccbbcbabacaaccbccaababb","cacbbbbcabbcbaabbccbaccbaacbbcbbbbcabababccabbbcab","bccbcacbccaacacccccaacabacbacbbbcaabacacccbbbccaac","aaaccbbbacacbaaaacacaabbaacccbcccbcabbccbcacabbacb","bcabcbbacbacacbbaaccabcabcbbaabacacccbbbcabbbc"
"aacb","bacbbbbaccbaabbbbbcaccbbcbcabbbccbcacccbabbbcaaacc","bababcacbacacacccccbbcacccbbcbccaccaacbbcacabcabba","aaabaccbbcacaacbabccccabbbcbcccccccbaacbccbaacbbbc","abacbaaaaaccacbbbaccbbbabaacbcbccacccabaaaacbaabbb","cbbcacbaccabbbcaacbcbabbcabcbaccabcbbbcabcbcbaacca","babbacaaacbbcbbbabbaabcbabcbbaacaacbbbaaaabbcabcca","cbabaacabcccaabbbacccaccbacabbaacaaabcbcccbcbcccaa","aabbbcbacabbcabcbcccbccaccbcacbaacabbbccaabaabcbba","caccabcccabbaacbabbaaaccccccccaaccbcaccacaabacccba","bbbcabcababaabacaccacabcbccacccbbbbcbbbaccabcabaab","bbbcaababbbbababababcbbbbaaabbacaabcacbbccbcaaaaaa","bcbacccaaaabbcbcabbbcababbcacaabbbbcbbacbaabcbaccb","bbcaccaaccacbbaaccaaaabccbbacbcbacaacbacbccaaccbba","abaaacbccbbabbcaccbaccccbaaacaccccababcbccccbabcca","acccaccababababacbbaccbcabcaccbabaabacbaacaaacabca","aaabababccabccbcbabcabcacbbcacbcbbbabcabacbcaacacb","ccacbaabbcbaccaccbbabbabbabaacccabcaaccacacccbbcab","bbaabcbabbbaacacabaabcbaaabacbccccaccaaaacbacabbbc","abaaaccaacbbcacacbcbccbaaacbbcbacabbbcca"
"bbbccaaaac","bbacbabbcacbbacccaccbcbcabbcbaacabbbbabbaaabaacacb","cacbacbccbcbabacccacabcacacabbcabbccaacacbaaacaacb","bacbbacbccccabcbabcbbcbacacaaabcbaccccaabaabbacbcb","abcaaccccabccaaaaccbabccacbcaaaacaccaccccccaaaabaa","bacabcbccbacccbaaaabcbbaabbabaabcabacccbcabacccbcc","babaccbbcbcbacccabccbcccbaaaaacccabcbccbbbbcbabcbc","cccbbaccbabbbbcbcbcbaaacbbcacbcaacacacccbcabccbcaa","caacbcacbccaaaaacaaababbcccacbabaaabcaacaaababacba","cccccaccabcaacababbacbcbabbcaacbacbabbbccbabcbabbb","ccbcababcabcbcccaccccacabcbaaacaabccbbaabaccbaccab","abbbcacaccabcbccbacabbbccaccaaaacccabbcbacbbccabcb","bacabccabcbbcaacbcacabcbccacbcccbcbcaaaabbaabccabb"};
p1 = 12;
all_right = (disabled || KawigiEdit_RunTest(4, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 5 -----
disabled = false;
p0 = {"h","e","l","l","o"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(5, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>CondorcetVoting<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct CondorcetVoting {
int winner(vector <string> votes) {
const int cc = sz(votes[0]);
fr(i, cc) {
bool f = true;
fr(j, cc) {
int c = 0;
ei(k, votes) {
if (k[i] < k[j]) ++c;
if (k[i] > k[j]) --c;
}
if (c <= 0) {
f = false;
break;
} else {
cout << i << " preferred to " << j << endl;
}
}
if (f) return i;
}
return -1;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
CondorcetVoting *obj;
int answer;
obj = new CondorcetVoting();
clock_t startTime = clock();
answer = obj->winner(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
int p1;
// ----- test 0 -----
disabled = false;
p0 = {"acbd","bacd","bdca"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"abc","bca","cab"};
p1 = -1;
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"cezdqcw"};
p1 = -1;
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"abcd","abcd","abcd","abcd","abcd","abcd","cbad","cbad","cbad","cbad","cbad","dbca","cbda","cbda"};
p1 = 1;
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 4 -----
disabled = false;
p0 = {"abbcbbbaaccaaccbbacbbbaacbccbccacaaacaacaaacbccaac","accbabcaacacbcccbbccbbcaccccccbbcbbcbaccbcbcacbcbc","acacaaabccaaaccabbaaaacabaaabacacbaacbcccbccbcbacb","acbcbabaabbcaababaacbabcacbaccabbaaacccbcabbbcacba","cbbbacbbacccbbabbbcbaabaaaacaacbcbccbaaccbcaaccbcb","cbacbbcbbcbcaaabccabcabbcbacaaabccabbcbacbbacbbaca","cacaabccbbbaaacccacbbcacababbcaaabccbbacbbbccacbaa","bccbbabaaaababcbabbbbcbcacbcbcbacccacacacacacacaab","bccabcaabcabbccaaccbcabaaabbbcaabaaabbbbabbbaabaac","accccbabaaaabcbacabbcbbacaacaaaacccbbbcacaccccaaac","cccbcaababbaacaaabbbaabbccccacaacbacaacbbbaacccbbb","bccccaccbcbbaaaaaaaaccbababcabaaccacbbabbbcabbaaca","cbacacaabbccacaabbbbbbccabcbbaccacbcacacacbccbcbcc","baabcabccaaaaccbaacaaccacccbcbbaaacacaccbcaacbbbba","bccaaaabcbbcbbbbbcaabaacccbccbbcbabacaaccbccaababb","cacbbbbcabbcbaabbccbaccbaacbbcbbbbcabababccabbbcab","bccbcacbccaacacccccaacabacbacbbbcaabacacccbbbccaac","aaaccbbbacacbaaaacacaabbaacccbcccbcabbccbcacabbacb","bcabcbbacbacacbbaaccabcabcbbaabacacccbbbcabbbc"
"aacb","bacbbbbaccbaabbbbbcaccbbcbcabbbccbcacccbabbbcaaacc","bababcacbacacacccccbbcacccbbcbccaccaacbbcacabcabba","aaabaccbbcacaacbabccccabbbcbcccccccbaacbccbaacbbbc","abacbaaaaaccacbbbaccbbbabaacbcbccacccabaaaacbaabbb","cbbcacbaccabbbcaacbcbabbcabcbaccabcbbbcabcbcbaacca","babbacaaacbbcbbbabbaabcbabcbbaacaacbbbaaaabbcabcca","cbabaacabcccaabbbacccaccbacabbaacaaabcbcccbcbcccaa","aabbbcbacabbcabcbcccbccaccbcacbaacabbbccaabaabcbba","caccabcccabbaacbabbaaaccccccccaaccbcaccacaabacccba","bbbcabcababaabacaccacabcbccacccbbbbcbbbaccabcabaab","bbbcaababbbbababababcbbbbaaabbacaabcacbbccbcaaaaaa","bcbacccaaaabbcbcabbbcababbcacaabbbbcbbacbaabcbaccb","bbcaccaaccacbbaaccaaaabccbbacbcbacaacbacbccaaccbba","abaaacbccbbabbcaccbaccccbaaacaccccababcbccccbabcca","acccaccababababacbbaccbcabcaccbabaabacbaacaaacabca","aaabababccabccbcbabcabcacbbcacbcbbbabcabacbcaacacb","ccacbaabbcbaccaccbbabbabbabaacccabcaaccacacccbbcab","bbaabcbabbbaacacabaabcbaaabacbccccaccaaaacbacabbbc","abaaaccaacbbcacacbcbccbaaacbbcbacabbbcca"
"bbbccaaaac","bbacbabbcacbbacccaccbcbcabbcbaacabbbbabbaaabaacacb","cacbacbccbcbabacccacabcacacabbcabbccaacacbaaacaacb","bacbbacbccccabcbabcbbcbacacaaabcbaccccaabaabbacbcb","abcaaccccabccaaaaccbabccacbcaaaacaccaccccccaaaabaa","bacabcbccbacccbaaaabcbbaabbabaabcabacccbcabacccbcc","babaccbbcbcbacccabccbcccbaaaaacccabcbccbbbbcbabcbc","cccbbaccbabbbbcbcbcbaaacbbcacbcaacacacccbcabccbcaa","caacbcacbccaaaaacaaababbcccacbabaaabcaacaaababacba","cccccaccabcaacababbacbcbabbcaacbacbabbbccbabcbabbb","ccbcababcabcbcccaccccacabcbaaacaabccbbaabaccbaccab","abbbcacaccabcbccbacabbbccaccaaaacccabbcbacbbccabcb","bacabccabcbbcaacbcacabcbccacbcccbcbcaaaabbaabccabb"};
p1 = 12;
all_right = (disabled || KawigiEdit_RunTest(4, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 5 -----
disabled = false;
p0 = {"h","e","l","l","o"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(5, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|>
|
<commit_before>#ifndef SIMDIFY_VEC3_FLT
#define SIMDIFY_VEC3_FLT
#include "../vec3.hpp"
#include "../util/inline.hpp"
#ifdef SIMDIFY_SSE
#define INL SIMDIFY_FORCE_INLINE
namespace simd {
template <>
struct basic_vec3<flt> {
using mm_t = flt::mm_t;
using fp_t = flt::fp_t;
using bitmask_t = flt::bitmask_t;
union {
struct { fp_t x, y, z, extra; };
sse mm;
};
INL basic_vec3() = default;
INL basic_vec3(const basic_vec3& other) : mm(other.mm) {}
INL basic_vec3& operator=(const basic_vec3& other) { mm = other.mm; return *this; }
INL explicit basic_vec3(const flt& t) : x(t.mm), y(t.mm), z(t.mm) {}
INL explicit basic_vec3(fp_t t) : x(t), y(t), z(t) {}
INL explicit basic_vec3(const sse& w) : mm(w) {}
INL basic_vec3(const flt& tx, const flt& ty, const flt& tz) :
x(tx.mm), y(ty.mm), z(tz.mm) {}
INL basic_vec3(fp_t tx, fp_t ty, fp_t tz) :
x(tx), y(ty), z(tz) {}
template <typename S>
INL explicit basic_vec3(const S& other) : x(other.x), y(other.y), z(other.z) {}
template <typename S>
INL basic_vec3& operator=(const S& other) {
x = other.x; y = other.y; z = other.z;
return *this;
}
INL basic_vec3& operator[](std::size_t) { return *this; }
INL const basic_vec3& operator[](std::size_t) const { return *this; }
};
using vec3f = basic_vec3<flt>;
template <>
struct bitwise_not<vec3f> {
vec3f neg;
INL explicit bitwise_not(const vec3f& r) : neg(r) {}
INL explicit operator const vec3f() const { return vec3f(sse(~neg.mm)); }
};
INL const vec3f operator&(const vec3f& l, const vec3f& r) { return vec3f(l.mm & r.mm); }
INL const vec3f operator|(const vec3f& l, const vec3f& r) { return vec3f(l.mm | r.mm); }
INL const vec3f operator^(const vec3f& l, const vec3f& r) { return vec3f(l.mm ^ r.mm); }
INL const bitwise_not<vec3f> operator~(const vec3f& l) { return bitwise_not<vec3f>(l); }
INL const vec3f operator<(const vec3f& l, const vec3f& r) { return vec3f(l.mm < r.mm); }
INL const vec3f operator>(const vec3f& l, const vec3f& r) { return vec3f(l.mm > r.mm); }
INL const vec3f operator<=(const vec3f& l, const vec3f& r) { return vec3f(l.mm <= r.mm); }
INL const vec3f operator>=(const vec3f& l, const vec3f& r) { return vec3f(l.mm >= r.mm); }
INL const vec3f operator==(const vec3f& l, const vec3f& r) { return vec3f(l.mm == r.mm); }
INL const vec3f operator!=(const vec3f& l, const vec3f& r) { return vec3f(l.mm != r.mm); }
INL const vec3f operator+(const vec3f& l, const vec3f& r) { return vec3f(l.mm + r.mm); }
INL const vec3f operator-(const vec3f& l, const vec3f& r) { return vec3f(l.mm - r.mm); }
INL const vec3f operator*(const vec3f& l, const vec3f& r) { return vec3f(l.mm * r.mm); }
INL const vec3f operator/(const vec3f& l, const vec3f& r) { return vec3f(l.mm / r.mm); }
INL const vec3f andnot(const vec3f& l, const vec3f& r) { return vec3f(andnot(l.mm, r.mm)); }
INL const vec3f min(const vec3f& l, const vec3f& r) { return vec3f(min(l.mm, r.mm)); }
INL const vec3f max(const vec3f& l, const vec3f& r) { return vec3f(max(l.mm, r.mm)); }
INL const vec3f cond(const vec3f& p, const vec3f& t, const vec3f& f) { return vec3f(cond(p.mm, t.mm, f.mm)); }
}
#undef INL
#endif // SIMDIFY_SSE
#endif // SIMDIFY_VEC3_FLT
<commit_msg>MSVC compiler errors/warnings removal sweep<commit_after>#ifndef SIMDIFY_VEC3_FLT
#define SIMDIFY_VEC3_FLT
#include "../vec3.hpp"
#include "../util/inline.hpp"
#ifdef SIMDIFY_SSE
#define INL SIMDIFY_FORCE_INLINE
namespace simd {
template <>
struct basic_vec3<flt> {
using mm_t = flt::mm_t;
using fp_t = flt::fp_t;
using bitmask_t = flt::bitmask_t;
union {
struct { fp_t x, y, z, extra; };
sse::mm_t mm;
};
INL basic_vec3() = default;
INL basic_vec3(const basic_vec3& other) : mm(other.mm) {}
INL basic_vec3& operator=(const basic_vec3& other) { mm = other.mm; return *this; }
INL explicit basic_vec3(const flt& t) : x(t.mm), y(t.mm), z(t.mm) {}
INL explicit basic_vec3(fp_t t) : x(t), y(t), z(t) {}
INL explicit basic_vec3(const sse& w) : mm(w.mm) {}
INL basic_vec3(const flt& tx, const flt& ty, const flt& tz) :
x(tx.mm), y(ty.mm), z(tz.mm) {}
INL basic_vec3(fp_t tx, fp_t ty, fp_t tz) :
x(tx), y(ty), z(tz) {}
template <typename S>
INL explicit basic_vec3(const S& other) : x(other.x), y(other.y), z(other.z) {}
template <typename S>
INL basic_vec3& operator=(const S& other) {
x = other.x; y = other.y; z = other.z;
return *this;
}
INL basic_vec3& operator[](std::size_t) { return *this; }
INL const basic_vec3& operator[](std::size_t) const { return *this; }
};
using vec3f = basic_vec3<flt>;
template <>
struct bitwise_not<vec3f> {
vec3f neg;
INL explicit bitwise_not(const vec3f& r) : neg(r) {}
INL explicit operator const vec3f() const { return vec3f(sse(~neg.mm)); }
};
INL const vec3f operator&(const vec3f& l, const vec3f& r) { return vec3f(l.mm & r.mm); }
INL const vec3f operator|(const vec3f& l, const vec3f& r) { return vec3f(l.mm | r.mm); }
INL const vec3f operator^(const vec3f& l, const vec3f& r) { return vec3f(l.mm ^ r.mm); }
INL const bitwise_not<vec3f> operator~(const vec3f& l) { return bitwise_not<vec3f>(l); }
INL const vec3f operator<(const vec3f& l, const vec3f& r) { return vec3f(l.mm < r.mm); }
INL const vec3f operator>(const vec3f& l, const vec3f& r) { return vec3f(l.mm > r.mm); }
INL const vec3f operator<=(const vec3f& l, const vec3f& r) { return vec3f(l.mm <= r.mm); }
INL const vec3f operator>=(const vec3f& l, const vec3f& r) { return vec3f(l.mm >= r.mm); }
INL const vec3f operator==(const vec3f& l, const vec3f& r) { return vec3f(l.mm == r.mm); }
INL const vec3f operator!=(const vec3f& l, const vec3f& r) { return vec3f(l.mm != r.mm); }
INL const vec3f operator+(const vec3f& l, const vec3f& r) { return vec3f(l.mm + r.mm); }
INL const vec3f operator-(const vec3f& l, const vec3f& r) { return vec3f(l.mm - r.mm); }
INL const vec3f operator*(const vec3f& l, const vec3f& r) { return vec3f(l.mm * r.mm); }
INL const vec3f operator/(const vec3f& l, const vec3f& r) { return vec3f(l.mm / r.mm); }
INL const vec3f andnot(const vec3f& l, const vec3f& r) { return vec3f(andnot(l.mm, r.mm)); }
INL const vec3f min(const vec3f& l, const vec3f& r) { return vec3f(min(l.mm, r.mm)); }
INL const vec3f max(const vec3f& l, const vec3f& r) { return vec3f(max(l.mm, r.mm)); }
INL const vec3f cond(const vec3f& p, const vec3f& t, const vec3f& f) { return vec3f(cond(p.mm, t.mm, f.mm)); }
}
#undef INL
#endif // SIMDIFY_SSE
#endif // SIMDIFY_VEC3_FLT
<|endoftext|>
|
<commit_before>#include "merlin.h"
namespace merlin {
Merlin::Merlin() {
// MagickWandGenesis();
}
Merlin::~Merlin() {
MagickWandTerminus();
}
void
Merlin::Initialize(Handle<Object> target) {
HandleScope scope;
Handle<Object> merlin = Object::New();
merlin->Set(String::NewSymbol("version"),
String::New(MERLIN_VERSION));
MerlinImage::Initialize(merlin);
MagickWandGenesis();
target->Set(String::NewSymbol("merlin"), merlin);
}
} // namespace
extern "C" void
init(Handle<Object> target)
{
HandleScope scope;
merlin::Merlin::Initialize(target);
}
<commit_msg>made the initialization less stupid<commit_after>#include "merlin.h"
namespace merlin {
Merlin::Merlin() {
// MagickWandGenesis();
}
Merlin::~Merlin() {
MagickWandTerminus();
}
void
Merlin::Initialize(Handle<Object> target) {
HandleScope scope;
target->Set(String::NewSymbol("version"),
String::New(MERLIN_VERSION));
MerlinImage::Initialize(target);
MagickWandGenesis();
Handle<ObjectTemplate> global = ObjectTemplate::New();
Handle<Context> context = Context::New(NULL, global);
Context::Scope context_scope(context);
context->Global()->Set(String::NewSymbol("merlin"), target);
}
} // namespace
extern "C" void
init(Handle<Object> target)
{
HandleScope scope;
merlin::Merlin::Initialize(target);
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Bobby Powers. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
#pragma once
#ifndef _ENCIRCLING_ARRAY_HPP_
#define _ENCIRCLING_ARRAY_HPP_
#include "_common.hpp"
#include <memory>
#include <cstring>
namespace encircling {
// Without passing an instance of this to std::shared_ptr, Valgrind
// reports a mismatched free error.
template <typename T>
class _ArrayFree
{
public:
void operator() (T* d) const
{
delete[] d;
}
};
template <typename T>
class Array {
public:
typedef T value_type;
explicit Array(const size_t n) : _n(n), _data(new T[n], _ArrayFree<T>())
{
memset(_data.get(), 0, n*sizeof(T));
}
virtual ~Array() {}
T& operator[](size_t i)
{
if (unlikely(i >= _n))
throw RuntimePanic("Array::operator[] out-of-bounds");
return _data.get()[i];
}
T const& operator[](size_t i) const
{
if (unlikely(i >= _n))
throw RuntimePanic("Array::operator[] out-of-bounds");
return _data.get()+i;
}
private:
size_t const _n;
std::shared_ptr<T> const _data;
};
} // namespace encircling
#endif // _ENCIRCLING_ARRAY_HPP_
<commit_msg>array: add len() method<commit_after>// Copyright 2013 Bobby Powers. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
#pragma once
#ifndef _ENCIRCLING_ARRAY_HPP_
#define _ENCIRCLING_ARRAY_HPP_
#include "_common.hpp"
#include <memory>
#include <cstring>
namespace encircling {
// Without passing an instance of this to std::shared_ptr, Valgrind
// reports a mismatched free error.
template <typename T>
class _ArrayFree
{
public:
void operator() (T* d) const
{
delete[] d;
}
};
template <typename T>
class Array {
public:
typedef T value_type;
explicit Array(const size_t n) : _n(n), _data(new T[n], _ArrayFree<T>())
{
memset(_data.get(), 0, n*sizeof(T));
}
virtual ~Array() {}
T& operator[](size_t i)
{
if (unlikely(i >= _n))
throw RuntimePanic("Array::operator[] out-of-bounds");
return _data.get()[i];
}
T const& operator[](size_t i) const
{
if (unlikely(i >= _n))
throw RuntimePanic("Array::operator[] out-of-bounds");
return _data.get()+i;
}
size_t len() { return _n; }
private:
size_t const _n;
std::shared_ptr<T> const _data;
};
} // namespace encircling
#endif // _ENCIRCLING_ARRAY_HPP_
<|endoftext|>
|
<commit_before>#ifndef RENDERER_COLOR_HPP
#define RENDERER_COLOR_HPP
#include "base.hpp"
namespace renderer {
class Color {
float rgb[3] = { 0 };
public:
Color();
Color(float r, float g, float b);
Color(const Color &);
Color(Color &&);
Color& operator = (const Color&);
Color& operator = (Color&&);
~Color();
Color operator + (const Color&) const;
Color operator - (const Color&) const;
Color operator * (float f) const;
Color operator / (float f) const;
bool operator == (const Color&);
Color Modulate (const Color&) const;
Color clamp() const;
inline float r() const { return rgb[0]; };
inline float g() const { return rgb[1]; };
inline float b() const { return rgb[2]; };
inline int rInt() const {
return r() * 255;
}
inline int gInt() const {
return g() * 255;
}
inline int bInt() const {
return b() * 255;
}
public:
static const Color Black;
static const Color White;
static const Color Red;
static const Color Green;
static const Color Blue;
};
}
#endif // RENDERER_COLOR_HPP
<commit_msg>no message<commit_after>#ifndef RENDERER_COLOR_HPP
#define RENDERER_COLOR_HPP
#include "base.hpp"
namespace renderer {
class Color {
float rgb[3] = { 0 };
public:
Color();
Color(float r, float g, float b);
Color(const Color &);
Color(Color &&);
Color& operator = (const Color&);
Color& operator = (Color&&);
~Color();
Color operator + (const Color&) const;
Color operator - (const Color&) const;
Color operator * (float f) const;
Color operator / (float f) const;
bool operator == (const Color&);
Color Modulate (const Color&) const;
Color clamp() const;
inline float r() const { return rgb[0]; };
inline float g() const { return rgb[1]; };
inline float b() const { return rgb[2]; };
inline int rInt() const {
return min(int(r() * 255), 255);
}
inline int gInt() const {
return min(int(g() * 255), 255);
}
inline int bInt() const {
return min(int(b() * 255), 255);
}
public:
static const Color Black;
static const Color White;
static const Color Red;
static const Color Green;
static const Color Blue;
};
}
#endif // RENDERER_COLOR_HPP
<|endoftext|>
|
<commit_before>#include "stack.hpp"
#ifndef STACK_CPP
#define STACK_CPP
template <typename T>
stack<T>::stack() : count_(0), array_size_(1), array_(new T[array_size_])
{}
template <typename T>
size_t stack<T> :: count() const
{
return count_;
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template <typename T>
void stack <T> :: push(const T& b)
{
if(count_==array_size_)
{
array_size_*=2;
T*l=copy_new(array_,count_,array_size_);
delete[] array_;
array_=l;
l=nullptr;
}
array_[count_]=b;
count_++;
}
template <typename T>
stack<T>::stack(const stack&c) : array_size_(c.array_size_),count_(c.count_), array_(copy_new(c.array_, c.count_, c.array_size_ ))
{};
/*template<typename T>
T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size)
{T*l=new T[array_size];
std::copy(arr,arr+count,l);
return;}*/
template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
if (this != &b)
{
delete[] array_;
array_size_ = b.array_size_;
count_ = b.count_;
array_ = copy_new(b.array_, count_, array_size_);
}
return *this;
}
template <typename T>
T stack<T>::pop()
{
if (!count_)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) {
return false;
}
else {
for (size_t i = 0; i < count_; i++) {
if (_s.array_[i] != array_[i]) {
return false;
}
}
}
return true;
}
#endif
<commit_msg>Update stack.cpp<commit_after>#include "stack.hpp"
#ifndef STACK_CPP
#define STACK_CPP
template <typename T>
stack<T>::stack() : count_(0), array_size_(1), array_(new T[array_size_])
{}
template <typename T>
size_t stack<T> :: count() const
{
return count_;
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template <typename T>
void stack <T> :: push(const T& b)
{
if(count_==array_size_)
{
array_size_*=2;
T*l=copy_new(array_,count_,array_size_);
delete[] array_;
array_=l;
l=nullptr;
}
array_[count_]=b;
count_++;
}
template <typename T>
stack<T>::stack(const stack&c) : array_size_(c.array_size_),count_(c.count_), array_(copy_new(c.array_, c.count_, c.array_size_ ))
{};
/*template<typename T>
T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size)
{T*l=new T[array_size];
std::copy(arr,arr+count,l);
return;}*/
template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
if (this != &b)
{
delete[] array_;
array_size_ = b.array_size_;
count_ = b.count_;
array_ = copy_new(b.array_, count_, array_size_);
}
return *this;
}
template <typename T>
T stack<T>::pop()
{
if (!count_)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
const T& stack<T>::top()
{
return array_[count_];
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) {
return false;
}
else {
for (size_t i = 0; i < count_; i++) {
if (_s.array_[i] != array_[i]) {
return false;
}
}
}
return true;
}
#endif
<|endoftext|>
|
<commit_before>#include "stack.hpp"
#include <stdexcept>
#ifndef STACK_CPP
#define STACK_CPP
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)),size_(size),counter_(0)
{}
auto bitset::set(size_t index)->void //инициализация всех битов единицами или изменение значения тдельного бита
{
if (index >= 0 && index < size_)
{
ptr_[index] = true; ++counter_;
}
else throw("problem with index");
}
auto bitset::reset(size_t index) throw(std::out_of_range) -> void //обнуление указанных битов
{
if (index >= size_)
{
throw (std::out_of_range("problem with index"));
}
ptr_[index] = false;
--counter_;
}
auto bitset::test(size_t index) const throw(std::out_of_range) -> bool //возвращает значение указанного бита
{
if (index >= size_)
{
throw (std::out_of_range("problem with index"));
}
return ptr_[index];
}
auto bitset::size() const -> size_t
{
return size_;
}
auto bitset::counter() const -> size_t
{
return counter_;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size))//конструктор с параметром
{}
template<typename T>
allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) //конструктор копирования
{
for (size_t i=0; i < size_; i++)
{
if (map_->test(i))
{
destroy(prt_ +i);
}
construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator()
{
if (this->count() > 0)
{
destroy(ptr_, ptr_ + size_());
}
operator delete(ptr_);
}
template<typename T> //увеличение памяти
auto allocator<T>::resize()->void
{
allocator<T> alloc(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; ++i) if(map_->test(i)) alloc.construct(alloc.get() + i, ptr_[i]);
this->swap(alloc);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void
{
if (ptr >= ptr_&&ptr < ptr_ + size_)
{
new(ptr)T(value);
map_->set(ptr - ptr_);
}
else { throw("error"); }
}
template<typename T>
auto allocator<T>::destroy(T * ptr)->void
{
if (ptr < ptr_ || ptr >= ptr_ + size_)
{
throw std::out_of_range("Error");
} else
{
if (map_->test(ptr-ptr_) == false)
{
ptr->~T();
map_->reset(ptr - ptr_);
}}
template<typename T> //получаем ptr_
auto allocator<T>::get()-> T* { return ptr_; }
template<typename T>
auto allocator<T>::get() const -> T const * { return ptr_; }
template<typename T>
auto allocator<T>::count() const -> size_t{ return map_->counter(); }
template<typename T> //заполненность
auto allocator<T>::full() const -> bool { return (map_->counter() == size_); }
template<typename T>
auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); }
template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void
{
if(first>=ptr_&&last<=ptr_+this->count())
for (; first != last; ++first)
{
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::swap(allocator & other)->void{
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(map_, other.map_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename T>
stack<T>::stack(size_t size) : allocator_(size)
{}
template<typename T>
auto stack<T>::operator =(stack const & other)-> stack &
{
if (this != &other)
{
(allocator<T>(other.allocator_)).swap(allocator_);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const ->bool
{
return allocator_.empty();
}
template<typename T>
auto stack<T>::count()const->size_t
{
return allocator_.count();
}
template<typename T>
auto stack<T>::push(T const & value)->void
{
if (allocator_.full()) allocator_.resize();
allocator_.construct(allocator_.get() + this->count(), value);
}
template<typename T>
auto stack<T>::pop()->void
{
if (allocator_.count() == 0) throw std::logic_error("Empty");
allocator_.destroy(allocator_.get() + (this->count() - 1));
}
template<typename T>
auto stack<T>::top()->T&
{
if (this->count() > 0) return(*(allocator_.get() + this->count() - 1));
else this->throw_is_empty();
}
template<typename T>
auto stack<T>::top()const->T const &
{
if (this->count() > 0) return(*(allocator_.get() + this->count() - 1));
else this->throw_is_empty();
}
template<typename T>
auto stack<T>::throw_is_empty()const->void
{
throw("Stack is empty");
}
#endif
<commit_msg>Update stack.cpp<commit_after>#include "stack.hpp"
#include <stdexcept>
#ifndef STACK_CPP
#define STACK_CPP
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)),size_(size),counter_(0)
{}
auto bitset::set(size_t index)->void //инициализация всех битов единицами или изменение значения тдельного бита
{
if (index >= 0 && index < size_)
{
ptr_[index] = true; ++counter_;
}
else throw("problem with index");
}
auto bitset::reset(size_t index) throw(std::out_of_range) -> void //обнуление указанных битов
{
if (index >= size_)
{
throw (std::out_of_range("problem with index"));
}
ptr_[index] = false;
--counter_;
}
auto bitset::test(size_t index) const throw(std::out_of_range) -> bool //возвращает значение указанного бита
{
if (index >= size_)
{
throw (std::out_of_range("problem with index"));
}
return ptr_[index];
}
auto bitset::size() const -> size_t
{
return size_;
}
auto bitset::counter() const -> size_t
{
return counter_;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size))//конструктор с параметром
{}
template<typename T>
allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) //конструктор копирования
{
for (size_t i=0; i < size_; i++)
{
if (map_->test(i))
{
destroy(prt_ +i);
}
construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator()
{
if (this->count() > 0)
{
destroy(ptr_, ptr_ + size_());
}
operator delete(ptr_);
}
template<typename T> //увеличение памяти
auto allocator<T>::resize()->void
{
allocator<T> alloc(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; ++i) if(map_->test(i)) alloc.construct(alloc.get() + i, ptr_[i]);
this->swap(alloc);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void
{
if (ptr >= ptr_&&ptr < ptr_ + size_)
{
new(ptr)T(value);
map_->set(ptr - ptr_);
}
else { throw("error"); }
}
template <typename T>
auto allocator<T>::destroy(T * ptr)->void
{
if (ptr < ptr_ || ptr >= ptr_ + size_ || map_->test(ptr-ptr_) == false)
{
throw std::out_of_range("Error");
}
ptr->~T();
map_->reset(ptr - ptr_);
}
template<typename T> //получаем ptr_
auto allocator<T>::get()-> T* { return ptr_; }
template<typename T>
auto allocator<T>::get() const -> T const * { return ptr_; }
template<typename T>
auto allocator<T>::count() const -> size_t{ return map_->counter(); }
template<typename T> //заполненность
auto allocator<T>::full() const -> bool { return (map_->counter() == size_); }
template<typename T>
auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); }
template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void
{
if(first>=ptr_&&last<=ptr_+this->count())
for (; first != last; ++first)
{
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::swap(allocator & other)->void{
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(map_, other.map_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename T>
stack<T>::stack(size_t size) : allocator_(size)
{}
template<typename T>
auto stack<T>::operator =(stack const & other)-> stack &
{
if (this != &other)
{
(allocator<T>(other.allocator_)).swap(allocator_);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const ->bool
{
return allocator_.empty();
}
template<typename T>
auto stack<T>::count()const->size_t
{
return allocator_.count();
}
template<typename T>
auto stack<T>::push(T const & value)->void
{
if (allocator_.full()) allocator_.resize();
allocator_.construct(allocator_.get() + this->count(), value);
}
template<typename T>
auto stack<T>::pop()->void
{
if (allocator_.count() == 0) throw std::logic_error("Empty");
allocator_.destroy(allocator_.get() + (this->count() - 1));
}
template<typename T>
auto stack<T>::top()->T&
{
if (this->count() > 0) return(*(allocator_.get() + this->count() - 1));
else this->throw_is_empty();
}
template<typename T>
auto stack<T>::top()const->T const &
{
if (this->count() > 0) return(*(allocator_.get() + this->count() - 1));
else this->throw_is_empty();
}
template<typename T>
auto stack<T>::throw_is_empty()const->void
{
throw("Stack is empty");
}
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
stack();
stack(const stack<T> &);
size_t count() const;
void print()const;
void push(T const &);
void swap(const stack<T>&);
T pop();
stack<T>& operator=(const stack<T> &);
~stack();
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}
template<class T>
stack<T>::~stack()
{
count_ = 0;
array_size_ = 0;
delete[] array_;
}
template <typename T>
stack<T>::stack(const stack<T>& copy)
{
array_size_ = copy.array_size_;
count_ = copy.count_;
array_ = new T*[array_size_];
for (int i = 0; i < array_size_; i++)
array_[array_size_] = copy.array_[array_size_];
}
template<class T>
size_t stack<T>::count() const
{
return count_;
}
template<typename T>
void stack<T>::swap(const stack& x)
{
std::swap(x.array_size_, array_size_);
std::swap(count_, x.count_);
std::swap(x.array_, array_);
}
template <typename T>
void stack<T>::push(T const &value)
{
if (array_size_ == 0)
{
array_size_ = 1;
array_ = new T[array_size_];
}
else if (array_size_ == count_)
{
array_size_ = array_size_ * 2;
swap();
//T *s1 = new T[array_size_];
//for (int i = 0; i < count_; i++)
//std::copy(int i = 0; i < count; i++)
// s1[i] = array_[i];
//delete[] array_;
//array_ = s1;
}
array_[count_] = value;
count_++;
}
template <typename T>
T stack<T>::pop()
{
if (count_ == 0)
throw "Stack is empty" ;
count_--;
T x = array_[count_];
swap();
return x;
}
template <typename T>
void stack<T>::print() const
{
for (int i = 0; i < array_size_; i++)
cout << array_[i];
}
template<typename T>
stack<T>& stack<T>::operator=(const stack<T> & tmp)
{
if (this != &tmp)
{
delete[] array_;
}
if (array_size_ != 0)
{
array_size_ = tmp.array_size_;
count_ = tmp.count_;
array_=new T[count_];
std::copy(tmp.array_, tmp.array_ + tmp.count_, array_);
}
return *this;
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
stack();
stack(const stack<T> &);
size_t count() const;
void print()const;
void push(T const &);
void swap(const stack<T>&);
T pop();
stack<T>& operator=(const stack<T> &);
~stack();
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}
template<class T>
stack<T>::~stack()
{
count_ = 0;
array_size_ = 0;
delete[] array_;
}
template <typename T>
stack<T>::stack(const stack<T>& copy)
{
array_size_ = copy.array_size_;
count_ = copy.count_;
array_ = new T*[array_size_];
for (int i = 0; i < array_size_; i++)
array_[array_size_] = copy.array_[array_size_];
}
template<class T>
size_t stack<T>::count() const
{
return count_;
}
template<typename T>
void stack<T>::swap(const stack& x)
{
std::swap(x.array_size_, array_size_);
std::swap(count_, x.count_);
std::swap(x.array_, array_);
}
template <typename T>
void stack<T>::push(T const &value)
{
if (array_size_ == 0)
{
array_size_ = 1;
array_ = new T[array_size_];
}
else if (array_size_ == count_)
{
array_size_ = array_size_ * 2;
T *s1 = new T[array_size_];
std::copy(array_, array_ + count_, ptr;
//for (int i = 0; i < count_; i++)
//std::copy(int i = 0; i < count; i++)
// s1[i] = array_[i];
delete[] array_;
array_ = s1;
}
array_[count_] = value;
count_++;
}
template <typename T>
T stack<T>::pop()
{
if (count_ == 0)
throw "Stack is empty" ;
count_--;
T x = array_[count_];
swap();
return x;
}
template <typename T>
void stack<T>::print() const
{
for (int i = 0; i < array_size_; i++)
cout << array_[i];
}
template<typename T>
stack<T>& stack<T>::operator=(const stack<T> & tmp)
{
if (this != &tmp)
{
delete[] array_;
}
if (array_size_ != 0)
{
array_size_ = tmp.array_size_;
count_ = tmp.count_;
array_=new T[count_];
std::copy(tmp.array_, tmp.array_ + tmp.count_, array_);
}
return *this;
}
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
stack();/*strong*/
stack(const stack<T> &);
size_t count() const; /*noexcept*/
void print()const;
void push(T const &); /*basic*/
void swap(stack<T>&); /*noexcept*/
void pop(); /*no safety*/
T top(); /*strong*/
bool empty() const; /*noexcept*/
stack<T>& operator=(stack<T> &); /*basic*/
~stack();/*noexcept*/
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}
template<class T>
stack<T>::~stack()
{
count_ = 0;
array_size_ = 0;
delete[] array_;
}
template <typename T>
stack<T>::stack(const stack<T>& copy)
{
array_size_ = copy.array_size_;
count_ = copy.count_;
array_ = new T[count_];
std::copy(copy.array_, copy.array_ + copy.count_, array_);
}
template<class T>
size_t stack<T>::count() const
{
return count_;
}
template <typename T>
bool stack<T>::empty() const
{
return (count_ == 0);
}
template<typename T>
void stack<T>::swap(stack& x)
{
std::swap(x.array_size_, array_size_);
std::swap(count_, x.count_);
std::swap(x.array_, array_);
}
template <typename T>
T stack<T>::top()
{
if (empty())
{
std::cout << "Stack is empty!";
}
return array_[count_ - 1];
}
template <typename T>
void stack<T>::push(T const &value)
{
if (array_size_ == 0)
{
array_size_ = 1;
array_ = new T[array_size_];
}
else if (array_size_ == count_)
{
array_size_ = array_size_ * 2;
T *s1 = new T[array_size_];
std::copy(array_, array_ + count_, s1);
//for (int i = 0; i < count_; i++)
//std::copy(int i = 0; i < count; i++)
// s1[i] = array_[i];
delete[] array_;
array_ = s1;
}
array_[count_] = value;
count_++;
}
template <typename T>
void stack<T>::pop()
{
if (count_ == 0)
throw "Stack is empty" ;
count_--;
return array_[count_];
}
template <typename T>
void stack<T>::print() const
{
for (int i = 0; i < array_size_; i++)
cout << array_[i];
}
template<typename T>
stack<T>& stack<T>::operator=(stack<T> & tmp)
{
if (this != &tmp)
{
stack(tmp).swap(*this);
}
return *this;
}
<commit_msg>Update stack.hpp<commit_after>#include <iostream>
using namespace std;
template <typename T>
class stack
{
public:
stack();/*strong*/
stack(const stack<T> &);
size_t count() const; /*noexcept*/
void print()const;
void push(T const &); /*basic*/
void swap(stack<T>&); /*noexcept*/
void pop(); /*no safety*/
T top(); /*strong*/
bool empty() const; /*noexcept*/
stack<T>& operator=(stack<T> &); /*basic*/
~stack();/*noexcept*/
private:
T * array_;
size_t array_size_;
size_t count_;
};
template <typename T>
stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr }
{}
template<class T>
stack<T>::~stack()
{
count_ = 0;
array_size_ = 0;
delete[] array_;
}
template <typename T>
stack<T>::stack(const stack<T>& copy)
{
array_size_ = copy.array_size_;
count_ = copy.count_;
array_ = new T[count_];
std::copy(copy.array_, copy.array_ + copy.count_, array_);
}
template<class T>
size_t stack<T>::count() const
{
return count_;
}
template <typename T>
bool stack<T>::empty() const
{
return (count_ == 0);
}
template<typename T>
void stack<T>::swap(stack& x)
{
std::swap(x.array_size_, array_size_);
std::swap(count_, x.count_);
std::swap(x.array_, array_);
}
template <typename T>
T stack<T>::top()
{
if (empty())
{
std::cout << "Stack is empty!";
}
return array_[count_ - 1];
}
template <typename T>
void stack<T>::push(T const &value)
{
if (array_size_ == 0)
{
array_size_ = 1;
array_ = new T[array_size_];
}
else if (array_size_ == count_)
{
array_size_ = array_size_ * 2;
T *s1 = new T[array_size_];
std::copy(array_, array_ + count_, s1);
//for (int i = 0; i < count_; i++)
//std::copy(int i = 0; i < count; i++)
// s1[i] = array_[i];
delete[] array_;
array_ = s1;
}
array_[count_] = value;
count_++;
}
template <typename T>
void stack<T>::pop()
{
if (count_ == 0)
throw "Stack is empty" ;
count_--;
}
template <typename T>
void stack<T>::print() const
{
for (int i = 0; i < array_size_; i++)
cout << array_[i];
}
template<typename T>
stack<T>& stack<T>::operator=(stack<T> & tmp)
{
if (this != &tmp)
{
stack(tmp).swap(*this);
}
return *this;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scuiautofmt.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2006-07-21 14:09:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
//------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/algitem.hxx>
#include <svx/boxitem.hxx>
#include <svx/brshitem.hxx>
#include <svx/cntritem.hxx>
#include <svx/colritem.hxx>
#include <svx/crsditem.hxx>
#include <svx/fontitem.hxx>
#include <svx/postitem.hxx>
#include <svx/shdditem.hxx>
#include <svx/udlnitem.hxx>
#include <svx/wghtitem.hxx>
#include <svtools/zforlist.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>
#include "sc.hrc"
#include "scmod.hxx"
#include "attrib.hxx"
#include "zforauto.hxx"
#include "scitems.hxx"
#include "global.hxx"
#include "globstr.hrc"
#include "autoform.hxx"
#include "strindlg.hxx"
#include "miscdlgs.hrc"
#include "scuiautofmt.hxx"
#include "scresid.hxx"
#include "document.hxx"
//========================================================================
// AutoFormat-Dialog:
ScAutoFormatDlg::ScAutoFormatDlg( Window* pParent,
ScAutoFormat* pAutoFormat,
const ScAutoFormatData* pSelFormatData,
ScDocument* pDoc ) :
ModalDialog ( pParent, ScResId( RID_SCDLG_AUTOFORMAT ) ),
//
aLbFormat ( this, ScResId( LB_FORMAT ) ),
aFlFormat ( this, ScResId( FL_FORMAT ) ),
pWndPreview ( new AutoFmtPreview( this, ScResId( WND_PREVIEW ), pDoc ) ),
aBtnNumFormat ( this, ScResId( BTN_NUMFORMAT ) ),
aBtnBorder ( this, ScResId( BTN_BORDER ) ),
aBtnFont ( this, ScResId( BTN_FONT ) ),
aBtnPattern ( this, ScResId( BTN_PATTERN ) ),
aBtnAlignment ( this, ScResId( BTN_ALIGNMENT ) ),
aBtnAdjust ( this, ScResId( BTN_ADJUST ) ),
aFlFormatting ( this, ScResId( FL_FORMATTING ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aBtnAdd ( this, ScResId( BTN_ADD ) ),
aBtnRemove ( this, ScResId( BTN_REMOVE ) ),
aBtnMore ( this, ScResId( BTN_MORE ) ),
aBtnRename ( this, ScResId( BTN_RENAME ) ),
aStrTitle ( ScResId( STR_ADD_TITLE ) ),
aStrLabel ( ScResId( STR_ADD_LABEL ) ),
aStrRename ( ScResId( STR_RENAME_TITLE ) ),
aStrClose ( ScResId( STR_BTN_CLOSE ) ),
aStrDelTitle ( ScResId( STR_DEL_TITLE ) ),
aStrDelMsg ( ScResId( STR_DEL_MSG ) ) ,
//
nIndex ( 0 ),
bFmtInserted ( FALSE ),
bCoreDataChanged( FALSE ),
pFormat ( pAutoFormat ),
pSelFmtData ( pSelFormatData )
{
Init();
pWndPreview->NotifyChange( (*pFormat)[0] );
FreeResource();
}
//------------------------------------------------------------------------
__EXPORT ScAutoFormatDlg::~ScAutoFormatDlg()
{
delete pWndPreview;
}
//------------------------------------------------------------------------
void ScAutoFormatDlg::Init()
{
USHORT nCount;
String aEntry;
aLbFormat .SetSelectHdl( LINK( this, ScAutoFormatDlg, SelFmtHdl ) );
aBtnNumFormat.SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnBorder .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnFont .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnPattern .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnAlignment.SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnAdjust .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnAdd .SetClickHdl ( LINK( this, ScAutoFormatDlg, AddHdl ) );
aBtnRemove .SetClickHdl ( LINK( this, ScAutoFormatDlg, RemoveHdl ) );
aBtnOk .SetClickHdl ( LINK( this, ScAutoFormatDlg, CloseHdl ) );
aBtnCancel .SetClickHdl ( LINK( this, ScAutoFormatDlg, CloseHdl ) );
aBtnRename .SetClickHdl ( LINK( this, ScAutoFormatDlg, RenameHdl ) );
aLbFormat .SetDoubleClickHdl( LINK( this, ScAutoFormatDlg, DblClkHdl ) );
aBtnMore.AddWindow( &aBtnRename );
aBtnMore.AddWindow( &aBtnNumFormat );
aBtnMore.AddWindow( &aBtnBorder );
aBtnMore.AddWindow( &aBtnFont );
aBtnMore.AddWindow( &aBtnPattern );
aBtnMore.AddWindow( &aBtnAlignment );
aBtnMore.AddWindow( &aBtnAdjust );
aBtnMore.AddWindow( &aFlFormatting );
nCount = pFormat->GetCount();
for ( USHORT i = 0; i < nCount; i++ )
{
((*pFormat)[i])->GetName( aEntry );
aLbFormat.InsertEntry( aEntry );
}
if ( nCount == 1 )
aBtnRemove.Disable();
aLbFormat.SelectEntryPos( 0 );
aBtnRename.Disable();
aBtnRemove.Disable();
nIndex = 0;
UpdateChecks();
if ( !pSelFmtData )
{
aBtnAdd.Disable();
aBtnRemove.Disable();
bFmtInserted = TRUE;
}
}
//------------------------------------------------------------------------
void ScAutoFormatDlg::UpdateChecks()
{
ScAutoFormatData* pData = (*pFormat)[nIndex];
aBtnNumFormat.Check( pData->GetIncludeValueFormat() );
aBtnBorder .Check( pData->GetIncludeFrame() );
aBtnFont .Check( pData->GetIncludeFont() );
aBtnPattern .Check( pData->GetIncludeBackground() );
aBtnAlignment.Check( pData->GetIncludeJustify() );
aBtnAdjust .Check( pData->GetIncludeWidthHeight() );
}
//------------------------------------------------------------------------
// Handler:
//---------
IMPL_LINK( ScAutoFormatDlg, CloseHdl, PushButton *, pBtn )
{
if ( pBtn == &aBtnOk || pBtn == &aBtnCancel )
{
if ( bCoreDataChanged )
ScGlobal::GetAutoFormat()->Save();
EndDialog( (pBtn == &aBtnOk) ? RET_OK : RET_CANCEL );
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( ScAutoFormatDlg, DblClkHdl, void *, EMPTYARG )
{
if ( bCoreDataChanged )
ScGlobal::GetAutoFormat()->Save();
EndDialog( RET_OK );
return 0;
}
IMPL_LINK_INLINE_END( ScAutoFormatDlg, DblClkHdl, void *, EMPTYARG )
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, CheckHdl, Button *, pBtn )
{
ScAutoFormatData* pData = (*pFormat)[nIndex];
BOOL bCheck = ((CheckBox*)pBtn)->IsChecked();
if ( pBtn == &aBtnNumFormat )
pData->SetIncludeValueFormat( bCheck );
else if ( pBtn == &aBtnBorder )
pData->SetIncludeFrame( bCheck );
else if ( pBtn == &aBtnFont )
pData->SetIncludeFont( bCheck );
else if ( pBtn == &aBtnPattern )
pData->SetIncludeBackground( bCheck );
else if ( pBtn == &aBtnAlignment )
pData->SetIncludeJustify( bCheck );
else if ( pBtn == &aBtnAdjust )
pData->SetIncludeWidthHeight( bCheck );
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
pWndPreview->NotifyChange( pData );
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, AddHdl, void *, EMPTYARG )
{
if ( !bFmtInserted && pSelFmtData )
{
String aStrStandard( ScResId(STR_STANDARD) );
String aFormatName;
ScStringInputDlg* pDlg;
BOOL bOk = FALSE;
while ( !bOk )
{
pDlg = new ScStringInputDlg( this,
aStrTitle,
aStrLabel,
aFormatName,
HID_SC_ADD_AUTOFMT );
if ( pDlg->Execute() == RET_OK )
{
pDlg->GetInputString( aFormatName );
if ( (aFormatName.Len() > 0) && (aFormatName != aStrStandard) )
{
ScAutoFormatData* pNewData
= new ScAutoFormatData( *pSelFmtData );
pNewData->SetName( aFormatName );
bFmtInserted = pFormat->Insert( pNewData );
if ( bFmtInserted )
{
USHORT nAt = pFormat->IndexOf( pNewData );
aLbFormat.InsertEntry( aFormatName, nAt );
aLbFormat.SelectEntry( aFormatName );
aBtnAdd.Disable();
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
SelFmtHdl( 0 );
bOk = TRUE;
}
else
delete pNewData;
}
if ( !bFmtInserted )
{
USHORT nRet = ErrorBox( this,
WinBits( WB_OK_CANCEL | WB_DEF_OK),
ScGlobal::GetRscString(STR_INVALID_AFNAME)
).Execute();
bOk = ( nRet == RET_CANCEL );
}
}
else
bOk = TRUE;
delete pDlg;
}
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, RemoveHdl, void *, EMPTYARG )
{
if ( (nIndex > 0) && (aLbFormat.GetEntryCount() > 0) )
{
String aMsg( aStrDelMsg.GetToken( 0, '#' ) );
aMsg += aLbFormat.GetSelectEntry();
aMsg += aStrDelMsg.GetToken( 1, '#' );
if ( RET_YES ==
QueryBox( this, WinBits( WB_YES_NO | WB_DEF_YES ), aMsg ).Execute() )
{
aLbFormat.RemoveEntry( nIndex );
aLbFormat.SelectEntryPos( nIndex-1 );
if ( nIndex-1 == 0 )
aBtnRemove.Disable();
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
pFormat->AtFree( nIndex ); // in der Core loeschen
nIndex--;
SelFmtHdl( 0 );
}
}
SelFmtHdl( 0 );
return 0;
}
IMPL_LINK( ScAutoFormatDlg, RenameHdl, void *, pBtn)
{
BOOL bOk = FALSE;
while( !bOk )
{
String aFormatName=aLbFormat.GetSelectEntry();
String aEntry;
ScStringInputDlg* pDlg = new ScStringInputDlg( this,
aStrRename,
aStrLabel,
aFormatName,
HID_SC_RENAME_AUTOFMT );
if( pDlg->Execute() == RET_OK )
{
BOOL bFmtRenamed = FALSE;
pDlg->GetInputString( aFormatName );
USHORT n;
if ( aFormatName.Len() > 0 )
{
for( n = 0; n < pFormat->GetCount(); ++n )
{
(*pFormat)[n]->GetName(aEntry);
if ( aEntry== aFormatName)
break;
}
if( n >= pFormat->GetCount() )
{
// Format mit dem Namen noch nicht vorhanden, also
// umbenennen
aLbFormat.RemoveEntry(nIndex );
ScAutoFormatData* p=(*pFormat)[ nIndex ];
ScAutoFormatData* pNewData
= new ScAutoFormatData(*p);
pFormat->AtFree( nIndex );
pNewData->SetName( aFormatName );
pFormat->Insert( pNewData);
USHORT nCount = pFormat->GetCount();
aLbFormat.SetUpdateMode(FALSE);
aLbFormat.Clear();
for ( USHORT i = 0; i < nCount; i++ )
{
((*pFormat)[i])->GetName( aEntry );
aLbFormat.InsertEntry( aEntry );
}
aLbFormat.SetUpdateMode( TRUE);
aLbFormat.SelectEntry( aFormatName);
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
SelFmtHdl( 0 );
bOk = TRUE;
bFmtRenamed = TRUE;
}
}
if( !bFmtRenamed )
{
bOk = RET_CANCEL == ErrorBox( this,
WinBits( WB_OK_CANCEL | WB_DEF_OK),
ScGlobal::GetRscString(STR_INVALID_AFNAME)
).Execute();
}
}
else
bOk = TRUE;
delete pDlg;
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, SelFmtHdl, void *, EMPTYARG )
{
nIndex = aLbFormat.GetSelectEntryPos();
UpdateChecks();
if ( nIndex == 0 )
{
aBtnRename.Disable();
aBtnRemove.Disable();
}
else
{
aBtnRename.Enable();
aBtnRemove.Enable();
}
pWndPreview->NotifyChange( (*pFormat)[nIndex] );
return 0;
}
//------------------------------------------------------------------------
String __EXPORT ScAutoFormatDlg::GetCurrFormatName()
{
String aResult;
((*pFormat)[nIndex])->GetName( aResult );
return aResult;
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.6.110); FILE MERGED 2006/12/12 17:03:18 nn 1.6.110.2: #i69284# warning-free: ui, unxlngi6 2006/12/01 08:53:35 nn 1.6.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scuiautofmt.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-02-27 13:33:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
//------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/algitem.hxx>
#include <svx/boxitem.hxx>
#include <svx/brshitem.hxx>
#include <svx/cntritem.hxx>
#include <svx/colritem.hxx>
#include <svx/crsditem.hxx>
#include <svx/fontitem.hxx>
#include <svx/postitem.hxx>
#include <svx/shdditem.hxx>
#include <svx/udlnitem.hxx>
#include <svx/wghtitem.hxx>
#include <svtools/zforlist.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>
#include "sc.hrc"
#include "scmod.hxx"
#include "attrib.hxx"
#include "zforauto.hxx"
#include "scitems.hxx"
#include "global.hxx"
#include "globstr.hrc"
#include "autoform.hxx"
#include "strindlg.hxx"
#include "miscdlgs.hrc"
#include "scuiautofmt.hxx"
#include "scresid.hxx"
#include "document.hxx"
//========================================================================
// AutoFormat-Dialog:
ScAutoFormatDlg::ScAutoFormatDlg( Window* pParent,
ScAutoFormat* pAutoFormat,
const ScAutoFormatData* pSelFormatData,
ScDocument* pDoc ) :
ModalDialog ( pParent, ScResId( RID_SCDLG_AUTOFORMAT ) ),
//
aFlFormat ( this, ScResId( FL_FORMAT ) ),
aLbFormat ( this, ScResId( LB_FORMAT ) ),
pWndPreview ( new AutoFmtPreview( this, ScResId( WND_PREVIEW ), pDoc ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aBtnAdd ( this, ScResId( BTN_ADD ) ),
aBtnRemove ( this, ScResId( BTN_REMOVE ) ),
aBtnMore ( this, ScResId( BTN_MORE ) ),
aFlFormatting ( this, ScResId( FL_FORMATTING ) ),
aBtnNumFormat ( this, ScResId( BTN_NUMFORMAT ) ),
aBtnBorder ( this, ScResId( BTN_BORDER ) ),
aBtnFont ( this, ScResId( BTN_FONT ) ),
aBtnPattern ( this, ScResId( BTN_PATTERN ) ),
aBtnAlignment ( this, ScResId( BTN_ALIGNMENT ) ),
aBtnAdjust ( this, ScResId( BTN_ADJUST ) ),
aBtnRename ( this, ScResId( BTN_RENAME ) ),
aStrTitle ( ScResId( STR_ADD_TITLE ) ),
aStrLabel ( ScResId( STR_ADD_LABEL ) ),
aStrClose ( ScResId( STR_BTN_CLOSE ) ),
aStrDelTitle ( ScResId( STR_DEL_TITLE ) ),
aStrDelMsg ( ScResId( STR_DEL_MSG ) ) ,
aStrRename ( ScResId( STR_RENAME_TITLE ) ),
//
pFormat ( pAutoFormat ),
pSelFmtData ( pSelFormatData ),
nIndex ( 0 ),
bCoreDataChanged( FALSE ),
bFmtInserted ( FALSE )
{
Init();
pWndPreview->NotifyChange( (*pFormat)[0] );
FreeResource();
}
//------------------------------------------------------------------------
__EXPORT ScAutoFormatDlg::~ScAutoFormatDlg()
{
delete pWndPreview;
}
//------------------------------------------------------------------------
void ScAutoFormatDlg::Init()
{
USHORT nCount;
String aEntry;
aLbFormat .SetSelectHdl( LINK( this, ScAutoFormatDlg, SelFmtHdl ) );
aBtnNumFormat.SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnBorder .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnFont .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnPattern .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnAlignment.SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnAdjust .SetClickHdl ( LINK( this, ScAutoFormatDlg, CheckHdl ) );
aBtnAdd .SetClickHdl ( LINK( this, ScAutoFormatDlg, AddHdl ) );
aBtnRemove .SetClickHdl ( LINK( this, ScAutoFormatDlg, RemoveHdl ) );
aBtnOk .SetClickHdl ( LINK( this, ScAutoFormatDlg, CloseHdl ) );
aBtnCancel .SetClickHdl ( LINK( this, ScAutoFormatDlg, CloseHdl ) );
aBtnRename .SetClickHdl ( LINK( this, ScAutoFormatDlg, RenameHdl ) );
aLbFormat .SetDoubleClickHdl( LINK( this, ScAutoFormatDlg, DblClkHdl ) );
aBtnMore.AddWindow( &aBtnRename );
aBtnMore.AddWindow( &aBtnNumFormat );
aBtnMore.AddWindow( &aBtnBorder );
aBtnMore.AddWindow( &aBtnFont );
aBtnMore.AddWindow( &aBtnPattern );
aBtnMore.AddWindow( &aBtnAlignment );
aBtnMore.AddWindow( &aBtnAdjust );
aBtnMore.AddWindow( &aFlFormatting );
nCount = pFormat->GetCount();
for ( USHORT i = 0; i < nCount; i++ )
{
((*pFormat)[i])->GetName( aEntry );
aLbFormat.InsertEntry( aEntry );
}
if ( nCount == 1 )
aBtnRemove.Disable();
aLbFormat.SelectEntryPos( 0 );
aBtnRename.Disable();
aBtnRemove.Disable();
nIndex = 0;
UpdateChecks();
if ( !pSelFmtData )
{
aBtnAdd.Disable();
aBtnRemove.Disable();
bFmtInserted = TRUE;
}
}
//------------------------------------------------------------------------
void ScAutoFormatDlg::UpdateChecks()
{
ScAutoFormatData* pData = (*pFormat)[nIndex];
aBtnNumFormat.Check( pData->GetIncludeValueFormat() );
aBtnBorder .Check( pData->GetIncludeFrame() );
aBtnFont .Check( pData->GetIncludeFont() );
aBtnPattern .Check( pData->GetIncludeBackground() );
aBtnAlignment.Check( pData->GetIncludeJustify() );
aBtnAdjust .Check( pData->GetIncludeWidthHeight() );
}
//------------------------------------------------------------------------
// Handler:
//---------
IMPL_LINK( ScAutoFormatDlg, CloseHdl, PushButton *, pBtn )
{
if ( pBtn == &aBtnOk || pBtn == &aBtnCancel )
{
if ( bCoreDataChanged )
ScGlobal::GetAutoFormat()->Save();
EndDialog( (pBtn == &aBtnOk) ? RET_OK : RET_CANCEL );
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( ScAutoFormatDlg, DblClkHdl, void *, EMPTYARG )
{
if ( bCoreDataChanged )
ScGlobal::GetAutoFormat()->Save();
EndDialog( RET_OK );
return 0;
}
IMPL_LINK_INLINE_END( ScAutoFormatDlg, DblClkHdl, void *, EMPTYARG )
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, CheckHdl, Button *, pBtn )
{
ScAutoFormatData* pData = (*pFormat)[nIndex];
BOOL bCheck = ((CheckBox*)pBtn)->IsChecked();
if ( pBtn == &aBtnNumFormat )
pData->SetIncludeValueFormat( bCheck );
else if ( pBtn == &aBtnBorder )
pData->SetIncludeFrame( bCheck );
else if ( pBtn == &aBtnFont )
pData->SetIncludeFont( bCheck );
else if ( pBtn == &aBtnPattern )
pData->SetIncludeBackground( bCheck );
else if ( pBtn == &aBtnAlignment )
pData->SetIncludeJustify( bCheck );
else if ( pBtn == &aBtnAdjust )
pData->SetIncludeWidthHeight( bCheck );
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
pWndPreview->NotifyChange( pData );
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, AddHdl, void *, EMPTYARG )
{
if ( !bFmtInserted && pSelFmtData )
{
String aStrStandard( ScResId(STR_STANDARD) );
String aFormatName;
ScStringInputDlg* pDlg;
BOOL bOk = FALSE;
while ( !bOk )
{
pDlg = new ScStringInputDlg( this,
aStrTitle,
aStrLabel,
aFormatName,
HID_SC_ADD_AUTOFMT );
if ( pDlg->Execute() == RET_OK )
{
pDlg->GetInputString( aFormatName );
if ( (aFormatName.Len() > 0) && (aFormatName != aStrStandard) )
{
ScAutoFormatData* pNewData
= new ScAutoFormatData( *pSelFmtData );
pNewData->SetName( aFormatName );
bFmtInserted = pFormat->Insert( pNewData );
if ( bFmtInserted )
{
USHORT nAt = pFormat->IndexOf( pNewData );
aLbFormat.InsertEntry( aFormatName, nAt );
aLbFormat.SelectEntry( aFormatName );
aBtnAdd.Disable();
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
SelFmtHdl( 0 );
bOk = TRUE;
}
else
delete pNewData;
}
if ( !bFmtInserted )
{
USHORT nRet = ErrorBox( this,
WinBits( WB_OK_CANCEL | WB_DEF_OK),
ScGlobal::GetRscString(STR_INVALID_AFNAME)
).Execute();
bOk = ( nRet == RET_CANCEL );
}
}
else
bOk = TRUE;
delete pDlg;
}
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, RemoveHdl, void *, EMPTYARG )
{
if ( (nIndex > 0) && (aLbFormat.GetEntryCount() > 0) )
{
String aMsg( aStrDelMsg.GetToken( 0, '#' ) );
aMsg += aLbFormat.GetSelectEntry();
aMsg += aStrDelMsg.GetToken( 1, '#' );
if ( RET_YES ==
QueryBox( this, WinBits( WB_YES_NO | WB_DEF_YES ), aMsg ).Execute() )
{
aLbFormat.RemoveEntry( nIndex );
aLbFormat.SelectEntryPos( nIndex-1 );
if ( nIndex-1 == 0 )
aBtnRemove.Disable();
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
pFormat->AtFree( nIndex ); // in der Core loeschen
nIndex--;
SelFmtHdl( 0 );
}
}
SelFmtHdl( 0 );
return 0;
}
IMPL_LINK( ScAutoFormatDlg, RenameHdl, void *, EMPTYARG )
{
BOOL bOk = FALSE;
while( !bOk )
{
String aFormatName=aLbFormat.GetSelectEntry();
String aEntry;
ScStringInputDlg* pDlg = new ScStringInputDlg( this,
aStrRename,
aStrLabel,
aFormatName,
HID_SC_RENAME_AUTOFMT );
if( pDlg->Execute() == RET_OK )
{
BOOL bFmtRenamed = FALSE;
pDlg->GetInputString( aFormatName );
USHORT n;
if ( aFormatName.Len() > 0 )
{
for( n = 0; n < pFormat->GetCount(); ++n )
{
(*pFormat)[n]->GetName(aEntry);
if ( aEntry== aFormatName)
break;
}
if( n >= pFormat->GetCount() )
{
// Format mit dem Namen noch nicht vorhanden, also
// umbenennen
aLbFormat.RemoveEntry(nIndex );
ScAutoFormatData* p=(*pFormat)[ nIndex ];
ScAutoFormatData* pNewData
= new ScAutoFormatData(*p);
pFormat->AtFree( nIndex );
pNewData->SetName( aFormatName );
pFormat->Insert( pNewData);
USHORT nCount = pFormat->GetCount();
aLbFormat.SetUpdateMode(FALSE);
aLbFormat.Clear();
for ( USHORT i = 0; i < nCount; i++ )
{
((*pFormat)[i])->GetName( aEntry );
aLbFormat.InsertEntry( aEntry );
}
aLbFormat.SetUpdateMode( TRUE);
aLbFormat.SelectEntry( aFormatName);
if ( !bCoreDataChanged )
{
aBtnCancel.SetText( aStrClose );
bCoreDataChanged = TRUE;
}
SelFmtHdl( 0 );
bOk = TRUE;
bFmtRenamed = TRUE;
}
}
if( !bFmtRenamed )
{
bOk = RET_CANCEL == ErrorBox( this,
WinBits( WB_OK_CANCEL | WB_DEF_OK),
ScGlobal::GetRscString(STR_INVALID_AFNAME)
).Execute();
}
}
else
bOk = TRUE;
delete pDlg;
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK( ScAutoFormatDlg, SelFmtHdl, void *, EMPTYARG )
{
nIndex = aLbFormat.GetSelectEntryPos();
UpdateChecks();
if ( nIndex == 0 )
{
aBtnRename.Disable();
aBtnRemove.Disable();
}
else
{
aBtnRename.Enable();
aBtnRemove.Enable();
}
pWndPreview->NotifyChange( (*pFormat)[nIndex] );
return 0;
}
//------------------------------------------------------------------------
String __EXPORT ScAutoFormatDlg::GetCurrFormatName()
{
String aResult;
((*pFormat)[nIndex])->GetName( aResult );
return aResult;
}
<|endoftext|>
|
<commit_before>/* FILTERBANK - multi-band reson instrument
This is like INPUTSIG from IIR, except that the parameters for each filter
band are time-varying.
p0 = output start time
p1 = input start time
p2 = input duration
p3 = amplitude multiplier *
p4 = ring-down duration
p5 = input channel
p6 = pan (in percent-to-left form: 0-1) *
Followed by one or more (up to 60) filter band descriptions, given by
triplets of
a. center frequency (Hz or oct.pc) *
b. bandwidth (percent of center frequency, from 0 to 1) *
c. relative amplitude (0-1) *
So the settings for the first band would occupy pfields 7-9, the second,
pfields 10-12, and so on.
* p3 (amplitude), p6 (pan) as well as the center frequency, bandwidth, and
relative amplitude pfields for individual bands can receive dynamic updates
from a table or real-time control source. If you want to change the center
frequency over time, use either Hz or linear octaves. The latter requires
converting to Hz with: cf = makeconverter(cf, "cpsoct")
The point of the ring-down duration parameter is to let you control
how long the filter will sound after the input has stopped. Too short
a time, and the sound may be cut off prematurely.
John Gibson <johgibso at gmail dot com>, 25 Feb 2007.
Based on IIR and MULTEQ.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ugens.h>
#include <Ougens.h>
#include <Instrument.h>
#include <PField.h>
#include "FILTERBANK.h"
#include <rt.h>
#include <rtdefs.h>
#include <float.h> // for FLT_MIN
#define FIRST_BAND_ARG 7
#define BAND_ARGS 3
FilterBand::FilterBand(float srate, float cf, float bw, float amp)
: _cf(cf), _bw(bw), _amp(amp)
{
_filt = new Oreson(srate, cf, bw, Oreson::kRMSResponse);
}
FilterBand::~FilterBand()
{
delete _filt;
}
FILTERBANK::FILTERBANK()
: branch(0), numbands(0), in(NULL), filt(NULL)
{
}
FILTERBANK::~FILTERBANK()
{
delete [] in;
for (int i = 0; i < numbands; i++)
delete filt[i];
delete [] filt;
}
int FILTERBANK::init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float inskip = p[1];
float dur = p[2];
float ringdur = p[4];
inchan = int(p[5]);
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
insamps = int(dur * SR + 0.5);
if (rtsetoutput(outskip, dur + ringdur, this) == -1)
return DONT_SCHEDULE;
if (inchan >= inputChannels())
return die("FILTERBANK", "Input channel pfield the exceeds number of configured input channels (%d).", inputChannels());
if ((nargs - FIRST_BAND_ARG) % BAND_ARGS)
return die("FILTERBANK", "For each band, need cf, bw, and amp.");
numbands = (nargs - FIRST_BAND_ARG) / BAND_ARGS;
filt = new FilterBand * [numbands];
int band = 0;
for (int i = FIRST_BAND_ARG; i < nargs; i += BAND_ARGS) {
float cf = p[i] < 15.0 ? cpspch(p[i]) : p[i];
float bw = p[i + 1];
float amp = p[i + 2];
filt[band] = new FilterBand(SR, cf, bw, amp);
band++;
}
return nSamps();
}
void FILTERBANK::doupdate()
{
double p[nargs];
update(p, nargs);
amp = p[3];
pan = p[6];
int band = 0;
for (int i = FIRST_BAND_ARG; i < nargs; i += BAND_ARGS) {
float cf = p[i] < 15.0 ? cpspch(p[i]) : p[i];
if (cf > SR * 0.5)
cf = SR * 0.5;
float bw = p[i + 1] * cf;
if (bw <= 0.0)
bw = FLT_MIN;
float famp = p[i + 2];
filt[band]->setparams(cf, bw, famp);
band++;
}
}
int FILTERBANK::configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
int FILTERBANK::run()
{
const int inchans = inputChannels();
const int outchans = outputChannels();
const int samps = framesToRun() * inchans;
if (currentFrame() < insamps)
rtgetin(in, this, samps);
for (int i = 0; i < samps; i += inchans) {
if (--branch <= 0) {
doupdate();
branch = getSkip();
}
float insig;
if (currentFrame() < insamps)
insig = in[i + inchan];
else
insig = 0.0f;
float outsig = 0.0f;
for (int n = 0; n < numbands; n++)
outsig += filt[n]->next(insig);
float out[2];
out[0] = outsig * amp;
if (outchans == 2) {
out[1] = out[0] * (1.0 - pan);
out[0] *= pan;
}
rtaddout(out);
increment();
}
return framesToRun();
}
Instrument *makeFILTERBANK()
{
FILTERBANK *inst;
inst = new FILTERBANK();
inst->set_bus_config("FILTERBANK");
return inst;
}
#ifndef EMBEDDED
void rtprofile()
{
RT_INTRO("FILTERBANK", makeFILTERBANK);
}
#endif
<commit_msg>Make error message about out-of-range inchan consistent with other instruments.<commit_after>/* FILTERBANK - multi-band reson instrument
This is like INPUTSIG from IIR, except that the parameters for each filter
band are time-varying.
p0 = output start time
p1 = input start time
p2 = input duration
p3 = amplitude multiplier *
p4 = ring-down duration
p5 = input channel
p6 = pan (in percent-to-left form: 0-1) *
Followed by one or more (up to 60) filter band descriptions, given by
triplets of
a. center frequency (Hz or oct.pc) *
b. bandwidth (percent of center frequency, from 0 to 1) *
c. relative amplitude (0-1) *
So the settings for the first band would occupy pfields 7-9, the second,
pfields 10-12, and so on.
* p3 (amplitude), p6 (pan) as well as the center frequency, bandwidth, and
relative amplitude pfields for individual bands can receive dynamic updates
from a table or real-time control source. If you want to change the center
frequency over time, use either Hz or linear octaves. The latter requires
converting to Hz with: cf = makeconverter(cf, "cpsoct")
The point of the ring-down duration parameter is to let you control
how long the filter will sound after the input has stopped. Too short
a time, and the sound may be cut off prematurely.
John Gibson <johgibso at gmail dot com>, 25 Feb 2007.
Based on IIR and MULTEQ.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ugens.h>
#include <Ougens.h>
#include <Instrument.h>
#include <PField.h>
#include "FILTERBANK.h"
#include <rt.h>
#include <rtdefs.h>
#include <float.h> // for FLT_MIN
#define FIRST_BAND_ARG 7
#define BAND_ARGS 3
FilterBand::FilterBand(float srate, float cf, float bw, float amp)
: _cf(cf), _bw(bw), _amp(amp)
{
_filt = new Oreson(srate, cf, bw, Oreson::kRMSResponse);
}
FilterBand::~FilterBand()
{
delete _filt;
}
FILTERBANK::FILTERBANK()
: branch(0), numbands(0), in(NULL), filt(NULL)
{
}
FILTERBANK::~FILTERBANK()
{
delete [] in;
for (int i = 0; i < numbands; i++)
delete filt[i];
delete [] filt;
}
int FILTERBANK::init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float inskip = p[1];
float dur = p[2];
float ringdur = p[4];
inchan = int(p[5]);
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
insamps = int(dur * SR + 0.5);
if (inchan >= inputChannels())
return die("FILTERBANK", "You asked for channel %d of a %d-channel file.",
inchan, inputChannels());
if (rtsetoutput(outskip, dur + ringdur, this) == -1)
return DONT_SCHEDULE;
if ((nargs - FIRST_BAND_ARG) % BAND_ARGS)
return die("FILTERBANK", "For each band, need cf, bw, and amp.");
numbands = (nargs - FIRST_BAND_ARG) / BAND_ARGS;
filt = new FilterBand * [numbands];
int band = 0;
for (int i = FIRST_BAND_ARG; i < nargs; i += BAND_ARGS) {
float cf = p[i] < 15.0 ? cpspch(p[i]) : p[i];
float bw = p[i + 1];
float amp = p[i + 2];
filt[band] = new FilterBand(SR, cf, bw, amp);
band++;
}
return nSamps();
}
void FILTERBANK::doupdate()
{
double p[nargs];
update(p, nargs);
amp = p[3];
pan = p[6];
int band = 0;
for (int i = FIRST_BAND_ARG; i < nargs; i += BAND_ARGS) {
float cf = p[i] < 15.0 ? cpspch(p[i]) : p[i];
if (cf > SR * 0.5)
cf = SR * 0.5;
float bw = p[i + 1] * cf;
if (bw <= 0.0)
bw = FLT_MIN;
float famp = p[i + 2];
filt[band]->setparams(cf, bw, famp);
band++;
}
}
int FILTERBANK::configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
int FILTERBANK::run()
{
const int inchans = inputChannels();
const int outchans = outputChannels();
const int samps = framesToRun() * inchans;
if (currentFrame() < insamps)
rtgetin(in, this, samps);
for (int i = 0; i < samps; i += inchans) {
if (--branch <= 0) {
doupdate();
branch = getSkip();
}
float insig;
if (currentFrame() < insamps)
insig = in[i + inchan];
else
insig = 0.0f;
float outsig = 0.0f;
for (int n = 0; n < numbands; n++)
outsig += filt[n]->next(insig);
float out[2];
out[0] = outsig * amp;
if (outchans == 2) {
out[1] = out[0] * (1.0 - pan);
out[0] *= pan;
}
rtaddout(out);
increment();
}
return framesToRun();
}
Instrument *makeFILTERBANK()
{
FILTERBANK *inst;
inst = new FILTERBANK();
inst->set_bus_config("FILTERBANK");
return inst;
}
#ifndef EMBEDDED
void rtprofile()
{
RT_INTRO("FILTERBANK", makeFILTERBANK);
}
#endif
<|endoftext|>
|
<commit_before>
#undef BUILDING_QT4_GUI
#include "qt4_gui.hpp"
#include "../testdialogs/dlg_test.h"
#include <gwenhywfar/gwenhywfar.h>
#include <gwenhywfar/gui.h>
#include <gwenhywfar/dialog.h>
#include <gwenhywfar/debug.h>
#include <qapplication.h>
int test1(int argc, char **argv) {
QApplication a(argc, argv);
QT4_Gui *gui;
int rv;
GWEN_DIALOG *dlg;
rv=GWEN_Init();
if (rv) {
DBG_ERROR_ERR(0, rv);
return 2;
}
GWEN_Logger_SetLevel(0, GWEN_LoggerLevel_Info);
/* create GUI */
gui=new QT4_Gui();
GWEN_Gui_SetGui(gui->getCInterface());
dlg=Dlg_Test1_new();
if (dlg==NULL) {
fprintf(stderr, "Could not create dialog.\n");
return 2;
}
rv=GWEN_Gui_ExecDialog(dlg, 0);
fprintf(stderr, "Result: %d\n", rv);
return 0;
}
int test2(int argc, char **argv) {
QApplication a(argc, argv);
QT4_Gui *gui;
QString lf;
int rv;
uint32_t pid;
rv=GWEN_Init();
if (rv) {
DBG_ERROR_ERR(0, rv);
return 2;
}
GWEN_Logger_SetLevel(0, GWEN_LoggerLevel_Info);
/* create GUI */
gui=new QT4_Gui();
GWEN_Gui_SetGui(gui->getCInterface());
#if 0
pid=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_PROGRESS | GWEN_GUI_PROGRESS_KEEP_OPEN,
"Progress-Title",
"This is an example progress with 2 steps"
"<html>This is an <strong>example</strong> progress with 2 steps</html>",
2,
0);
#else
pid=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_PROGRESS | GWEN_GUI_PROGRESS_KEEP_OPEN,
"Progress-Title",
"This is an <b>example</b> progress with 2 steps",
2,
0);
#endif
GWEN_Gui_ProgressAdvance(pid, 1);
rv=GWEN_Gui_MessageBox(GWEN_GUI_MSG_FLAGS_TYPE_INFO,
"MessageBox-Title",
"This message box should appear in the context of the open progress dialog",
"Button1",
"Button2",
"Button3",
pid);
GWEN_Gui_ProgressAdvance(pid, 2);
GWEN_Gui_ProgressEnd(pid);
return 0;
}
int test3(int argc, char **argv) {
int rv;
uint32_t id1;
uint32_t id2;
uint64_t i1;
uint64_t i2;
QApplication a(argc, argv);
QT4_Gui *gui;
gui=new QT4_Gui();
GWEN_Gui_SetGui(gui->getCInterface());
id1=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_LOG |
GWEN_GUI_PROGRESS_SHOW_ABORT |
GWEN_GUI_PROGRESS_KEEP_OPEN,
"Progress-Title",
"<html>"
"<p><b>This</b> is an example <i>text</i>..</p>"
"<p>As you can see <font color=red>colors</font> can "
"be used.</p>"
"</html>",
10,
0);
for (i1=1; i1<=10; i1++) {
char numbuf[128];
snprintf(numbuf, sizeof(numbuf)-1, "Step %d\n", (int)i1);
GWEN_Gui_ProgressLog(id1, GWEN_LoggerLevel_Notice, numbuf);
id2=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_LOG |
GWEN_GUI_PROGRESS_DELAY |
GWEN_GUI_PROGRESS_SHOW_ABORT,
"2nd progress",
"Starting 2nd progress...",
10,
id1);
for (i2=1; i2<=10; i2++) {
sleep(1);
fprintf(stderr, "Advancing %d/%d\n", (int)i1, (int)i2);
rv=GWEN_Gui_ProgressAdvance(id2, i2);
if (rv==GWEN_ERROR_USER_ABORTED) {
fprintf(stderr, "Aborted by user (2)\n");
break;
}
}
GWEN_Gui_ProgressEnd(id2);
rv=GWEN_Gui_ProgressAdvance(id1, i1);
if (rv==GWEN_ERROR_USER_ABORTED) {
fprintf(stderr, "Aborted by user (1)\n");
break;
}
}
GWEN_Gui_ProgressEnd(id1);
return 0;
}
int main(int argc, char **argv) {
return test1(argc, argv);
//return test2(argc, argv);
//return test3(argc, argv);
}
<commit_msg>Adapted to latest gcc.<commit_after>
#undef BUILDING_QT4_GUI
#include "qt4_gui.hpp"
#include "../testdialogs/dlg_test.h"
#include <gwenhywfar/gwenhywfar.h>
#include <gwenhywfar/gui.h>
#include <gwenhywfar/dialog.h>
#include <gwenhywfar/debug.h>
#include <qapplication.h>
#include <unistd.h>
int test1(int argc, char **argv) {
QApplication a(argc, argv);
QT4_Gui *gui;
int rv;
GWEN_DIALOG *dlg;
rv=GWEN_Init();
if (rv) {
DBG_ERROR_ERR(0, rv);
return 2;
}
GWEN_Logger_SetLevel(0, GWEN_LoggerLevel_Info);
/* create GUI */
gui=new QT4_Gui();
GWEN_Gui_SetGui(gui->getCInterface());
dlg=Dlg_Test1_new();
if (dlg==NULL) {
fprintf(stderr, "Could not create dialog.\n");
return 2;
}
rv=GWEN_Gui_ExecDialog(dlg, 0);
fprintf(stderr, "Result: %d\n", rv);
return 0;
}
int test2(int argc, char **argv) {
QApplication a(argc, argv);
QT4_Gui *gui;
QString lf;
int rv;
uint32_t pid;
rv=GWEN_Init();
if (rv) {
DBG_ERROR_ERR(0, rv);
return 2;
}
GWEN_Logger_SetLevel(0, GWEN_LoggerLevel_Info);
/* create GUI */
gui=new QT4_Gui();
GWEN_Gui_SetGui(gui->getCInterface());
#if 0
pid=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_PROGRESS | GWEN_GUI_PROGRESS_KEEP_OPEN,
"Progress-Title",
"This is an example progress with 2 steps"
"<html>This is an <strong>example</strong> progress with 2 steps</html>",
2,
0);
#else
pid=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_PROGRESS | GWEN_GUI_PROGRESS_KEEP_OPEN,
"Progress-Title",
"This is an <b>example</b> progress with 2 steps",
2,
0);
#endif
GWEN_Gui_ProgressAdvance(pid, 1);
rv=GWEN_Gui_MessageBox(GWEN_GUI_MSG_FLAGS_TYPE_INFO,
"MessageBox-Title",
"This message box should appear in the context of the open progress dialog",
"Button1",
"Button2",
"Button3",
pid);
GWEN_Gui_ProgressAdvance(pid, 2);
GWEN_Gui_ProgressEnd(pid);
return 0;
}
int test3(int argc, char **argv) {
int rv;
uint32_t id1;
uint32_t id2;
uint64_t i1;
uint64_t i2;
QApplication a(argc, argv);
QT4_Gui *gui;
gui=new QT4_Gui();
GWEN_Gui_SetGui(gui->getCInterface());
id1=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_LOG |
GWEN_GUI_PROGRESS_SHOW_ABORT |
GWEN_GUI_PROGRESS_KEEP_OPEN,
"Progress-Title",
"<html>"
"<p><b>This</b> is an example <i>text</i>..</p>"
"<p>As you can see <font color=red>colors</font> can "
"be used.</p>"
"</html>",
10,
0);
for (i1=1; i1<=10; i1++) {
char numbuf[128];
snprintf(numbuf, sizeof(numbuf)-1, "Step %d\n", (int)i1);
GWEN_Gui_ProgressLog(id1, GWEN_LoggerLevel_Notice, numbuf);
id2=GWEN_Gui_ProgressStart(GWEN_GUI_PROGRESS_SHOW_LOG |
GWEN_GUI_PROGRESS_DELAY |
GWEN_GUI_PROGRESS_SHOW_ABORT,
"2nd progress",
"Starting 2nd progress...",
10,
id1);
for (i2=1; i2<=10; i2++) {
sleep(1);
fprintf(stderr, "Advancing %d/%d\n", (int)i1, (int)i2);
rv=GWEN_Gui_ProgressAdvance(id2, i2);
if (rv==GWEN_ERROR_USER_ABORTED) {
fprintf(stderr, "Aborted by user (2)\n");
break;
}
}
GWEN_Gui_ProgressEnd(id2);
rv=GWEN_Gui_ProgressAdvance(id1, i1);
if (rv==GWEN_ERROR_USER_ABORTED) {
fprintf(stderr, "Aborted by user (1)\n");
break;
}
}
GWEN_Gui_ProgressEnd(id1);
return 0;
}
int main(int argc, char **argv) {
return test1(argc, argv);
//return test2(argc, argv);
//return test3(argc, argv);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <ctime> //for seeding srand
#define WORDLIST_LENGTH 40
#define MAX_INCORRECT_GUESSES 6
using namespace std;
enum EGameState : int
{
WaitingToStart,
InProgress,
Over
};
//draws the current state of the hangman
void DrawHangman(int IncorrectGuesses)
{
//draw hangman
char Face = (IncorrectGuesses > 0) ? 'O' : ' ';
char Torso = (IncorrectGuesses > 1) ? '|' : ' ';
char ArmR = (IncorrectGuesses > 2) ? '/' : ' ';
char ArmL = (IncorrectGuesses > 3) ? '\\' : ' ';
char LegR = (IncorrectGuesses > 4) ? '/' : ' ';
char LegL = (IncorrectGuesses > 5) ? '\\' : ' ';
cout << endl
<< "\t +----+" << endl
<< "\t | |" << endl
<< "\t " << Face << " |" << endl
<< "\t " << ArmR << Torso << ArmL << " |" << endl
<< "\t " << LegR << " " << LegL << " |" << endl
<< "\t |" << endl
<< "\t==========" << endl
<< endl;
}
//print guesses
void PrintGuesses(string &ChosenWord, string &CorrectGuesses, string &IncorrectGuesses)
{
cout << "Word: ";
for (int i = 0; i < ChosenWord.length(); i++)
{
if (CorrectGuesses.find(ChosenWord[i]) != string::npos)
{
cout << ChosenWord[i] << " ";
}
else
{
cout << "_ ";
}
}
cout << endl << endl;
cout << "Incorrect Guesses: " << endl;
for (int i = 0; i < IncorrectGuesses.length(); i++)
{
cout << IncorrectGuesses[i] << " ";
}
cout << endl;
}
//determines if the player's guess was correct or not
void HandlePlayerGuess(char PlayerGuess, string ChosenWord, string *CorrectGuesses, string *IncorrectGuesses)
{
//see if we've guessed this letter already
if (CorrectGuesses->find(PlayerGuess) != string::npos || IncorrectGuesses->find(PlayerGuess) != string::npos)
{
cout << "You've already guessed " << PlayerGuess << "!" << endl;
cout << "Try again." << endl;
}
else if (ChosenWord.find(PlayerGuess) != string::npos)
{
//letter is in word
cout << "Correct! There is a " << PlayerGuess << " in the word." << endl;
*CorrectGuesses += PlayerGuess;
}
else
{
//letter is not in word
cout << "WROOONG" << endl;
*IncorrectGuesses += PlayerGuess;
}
}
int main()
{
cout << endl
<< " ==========" << endl
<< " Hangman!" << endl
<< " ==========" << endl << endl;
EGameState GameState = EGameState::WaitingToStart;
//40 most common english nouns over 3 letters long
string Worldlist[WORDLIST_LENGTH] = { "time", "year", "people", "thing", "woman", "life", "child", "world", "school", "state", "family", "student", "group", "country", "problem", "hand", "part", "place", "case", "week", "company", "system", "issue", "side", "kind", "head", "house", "service", "friend", "father", "power", "hour", "game", "line", "member", "city", "community", "name", "president", "team" };
//load notification with title
cout << "Loaded default wordlist: " << endl
<< "\"Top 40 Most Common English Nouns Over 3 Letters Long\"." << endl;
//choose a random word within that list
cout << endl << "I'm thinking of a word..." << endl;
srand(time(0));
string ChosenWord = Worldlist[rand() % int(WORDLIST_LENGTH)];
string CorrectGuesses;
string IncorrectGuesses;
cout << "Okay, I've got it!" << endl;
cout << endl << endl;
system("pause");
//start game
GameState = EGameState::InProgress;
bool bWonLastGame = false;
//game loop
while (GameState == InProgress)
{
system("cls"); //windows-only, sorry;
//update the player on how they're doing
DrawHangman(IncorrectGuesses.length());
PrintGuesses(ChosenWord, CorrectGuesses, IncorrectGuesses);
//cout << " ((DEBUG)) word is: " << ChosenWord << endl;
cout << "Make a guess: ";
string PlayerGuess;
getline(cin, PlayerGuess);
HandlePlayerGuess(PlayerGuess[0], ChosenWord, &CorrectGuesses, &IncorrectGuesses);
if (IncorrectGuesses.length() >= MAX_INCORRECT_GUESSES)
{
GameState = EGameState::Over;
bWonLastGame = false;
}
else if (CorrectGuesses.length() == ChosenWord.length())
{
GameState = EGameState::Over;
bWonLastGame = true;
}
}
//draw end screen
system("cls");
DrawHangman(IncorrectGuesses.length());
cout << endl << "Game over: " << (bWonLastGame ? "You won!" : "You lost.") << endl;
if (!bWonLastGame)
{
cout << "The word was \"" << ChosenWord << "\"." << endl;
}
cout << "Want to try again? ";
cout << endl << endl;
}
<commit_msg>add replayability and make status messages easier (possible) to read<commit_after>#include <iostream>
#include <string>
#include <ctime> //for seeding srand
#define WORDLIST_LENGTH 40
#define MAX_INCORRECT_GUESSES 6
using namespace std;
enum EGameState : int
{
WaitingToStart,
InProgress,
Over
};
//draws the current state of the hangman
void DrawHangman(int IncorrectGuesses)
{
//draw hangman
char Face = (IncorrectGuesses > 0) ? 'O' : ' ';
char Torso = (IncorrectGuesses > 1) ? '|' : ' ';
char ArmR = (IncorrectGuesses > 2) ? '/' : ' ';
char ArmL = (IncorrectGuesses > 3) ? '\\' : ' ';
char LegR = (IncorrectGuesses > 4) ? '/' : ' ';
char LegL = (IncorrectGuesses > 5) ? '\\' : ' ';
cout << endl
<< "\t +----+" << endl
<< "\t | |" << endl
<< "\t " << Face << " |" << endl
<< "\t " << ArmR << Torso << ArmL << " |" << endl
<< "\t " << LegR << " " << LegL << " |" << endl
<< "\t |" << endl
<< "\t==========" << endl
<< endl;
}
//print guesses
void PrintGuesses(string &ChosenWord, string &CorrectGuesses, string &IncorrectGuesses)
{
cout << "Word: ";
for (int i = 0; i < ChosenWord.length(); i++)
{
if (CorrectGuesses.find(ChosenWord[i]) != string::npos)
{
cout << ChosenWord[i] << " ";
}
else
{
cout << "_ ";
}
}
cout << endl << endl;
cout << "Incorrect Guesses: " << endl;
for (int i = 0; i < IncorrectGuesses.length(); i++)
{
cout << IncorrectGuesses[i] << " ";
}
cout << endl;
}
//determines if the player's guess was correct or not
void HandlePlayerGuess(char PlayerGuess, string ChosenWord, string *CorrectGuesses, string *IncorrectGuesses, string *StatusMessage)
{
//see if we've guessed this letter already
if (CorrectGuesses->find(PlayerGuess) != string::npos || IncorrectGuesses->find(PlayerGuess) != string::npos)
{
cout << "You've already guessed " << PlayerGuess << "!" << endl;
cout << "Try again." << endl;
}
else if (ChosenWord.find(PlayerGuess) != string::npos)
{
//letter is in word
*StatusMessage = "Correct! There is a ";
*CorrectGuesses += PlayerGuess;
}
else
{
//letter is not in word
*StatusMessage = "Nope! There are no ";
*IncorrectGuesses += PlayerGuess;
}
*StatusMessage += PlayerGuess;
*StatusMessage += " in the word.";
}
int main()
{
cout << endl
<< " ==========" << endl
<< " Hangman!" << endl
<< " ==========" << endl << endl;
EGameState GameState = EGameState::WaitingToStart;
//40 most common english nouns over 3 letters long
string Worldlist[WORDLIST_LENGTH] = { "time", "year", "people", "thing", "woman", "life", "child", "world", "school", "state", "family", "student", "group", "country", "problem", "hand", "part", "place", "case", "week", "company", "system", "issue", "side", "kind", "head", "house", "service", "friend", "father", "power", "hour", "game", "line", "member", "city", "community", "name", "president", "team" };
//load notification with title
cout << "Loaded default wordlist: " << endl
<< "\"Top 40 Most Common English Nouns Over 3 Letters Long\"." << endl;
//choose a random word within that list
cout << endl << "I'm thinking of a word..." << endl;
srand(time(0));
string ChosenWord = Worldlist[rand() % int(WORDLIST_LENGTH)];
string CorrectGuesses;
string IncorrectGuesses;
cout << "Okay, I've got it!" << endl;
cout << endl << endl;
system("pause");
bool bPlayAgain = true;
while (bPlayAgain)
{
//start game
GameState = EGameState::InProgress;
bool bWonLastGame = false;
string StatusMessage = "";
//game loop
while (GameState == InProgress)
{
system("cls"); //windows-only, sorry;
//update the player on how they're doing
DrawHangman(IncorrectGuesses.length());
PrintGuesses(ChosenWord, CorrectGuesses, IncorrectGuesses);
cout << endl << StatusMessage << endl << endl;
//cout << " ((DEBUG)) word is: " << ChosenWord << endl;
cout << "Make a guess: ";
string PlayerGuess;
getline(cin, PlayerGuess);
HandlePlayerGuess(PlayerGuess[0], ChosenWord, &CorrectGuesses, &IncorrectGuesses, &StatusMessage);
if (IncorrectGuesses.length() >= MAX_INCORRECT_GUESSES)
{
GameState = EGameState::Over;
bWonLastGame = false;
}
else if (CorrectGuesses.length() == ChosenWord.length())
{
GameState = EGameState::Over;
bWonLastGame = true;
}
}
//draw end screen
system("cls");
DrawHangman(IncorrectGuesses.length());
cout << endl << "Game over: " << (bWonLastGame ? "You won!" : "You lost.") << endl;
if (!bWonLastGame)
{
cout << "The word was \"" << ChosenWord << "\"." << endl;
}
cout << endl << endl;
cout << "Want to try again? ";
string PlayAgainInput = "";
getline(cin, PlayAgainInput);
bPlayAgain = (PlayAgainInput[0] == 'y');
}
system("cls");
cout << "Thanks for playing!" << endl << endl;
system("pause");
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: SlsViewOverlay.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-03-30 09:26:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "view/SlsViewOverlay.hxx"
#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "view/SlideSorterView.hxx"
#include "SlideSorterViewShell.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsPageObject.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
#include "ViewShellBase.hxx"
#include "UpdateLockManager.hxx"
#include "Window.hxx"
#include "sdpage.hxx"
namespace {
class ShowingModeGuard
{
public:
explicit ShowingModeGuard (::sd::slidesorter::view::OverlayBase& rOverlay,
bool bHideAndSave = false)
: mrOverlay (rOverlay),
mbIsShowing (mrOverlay.IsShowing()),
mbRestorePending(false)
{
if (mbIsShowing)
if (bHideAndSave)
{
mrOverlay.GetViewOverlay().HideAndSave (
::sd::slidesorter::view::ViewOverlay::OPT_XOR);
mbRestorePending = true;
}
mrOverlay.Hide();
}
~ShowingModeGuard (void)
{
if (mbIsShowing)
{
mrOverlay.Show();
if (mbRestorePending)
mrOverlay.GetViewOverlay().Restore ();
}
}
private:
::sd::slidesorter::view::OverlayBase& mrOverlay;
bool mbIsShowing;
bool mbRestorePending;
};
}
namespace sd { namespace slidesorter { namespace view {
//===== ViewOverlay =========================================================
ViewOverlay::ViewOverlay (SlideSorterViewShell& rViewShell)
: mrViewShell (rViewShell),
maSelectionRectangleOverlay(*this),
maMouseOverIndicatorOverlay(*this),
maInsertionIndicatorOverlay(*this),
maSubstitutionOverlay(*this),
mbSelectionRectangleWasVisible(false),
mbMouseOverIndicatorWasVisible(false),
mbInsertionIndicatorWasVisible(false),
mbSubstitutionDisplayWasVisible(false),
mnHideAndSaveLevel(0)
{
}
ViewOverlay::~ViewOverlay (void)
{
}
SelectionRectangleOverlay& ViewOverlay::GetSelectionRectangleOverlay (void)
{
return maSelectionRectangleOverlay;
}
MouseOverIndicatorOverlay& ViewOverlay::GetMouseOverIndicatorOverlay (void)
{
return maMouseOverIndicatorOverlay;
}
InsertionIndicatorOverlay& ViewOverlay::GetInsertionIndicatorOverlay (void)
{
return maInsertionIndicatorOverlay;
}
SubstitutionOverlay& ViewOverlay::GetSubstitutionOverlay (void)
{
return maSubstitutionOverlay;
}
void ViewOverlay::Paint (void)
{
maSelectionRectangleOverlay.Paint();
maMouseOverIndicatorOverlay.Paint();
maInsertionIndicatorOverlay.Paint();
maSubstitutionOverlay.Paint();
}
controller::SlideSorterController& ViewOverlay::GetController (void)
{
return mrViewShell.GetSlideSorterController();
}
SlideSorterViewShell& ViewOverlay::GetViewShell (void)
{
return mrViewShell;
}
void ViewOverlay::HideAndSave (OverlayPaintType eType)
{
if (mnHideAndSaveLevel++ == 0)
{
// Remember the current state of the visiblities of the overlays.
mbSelectionRectangleWasVisible = maSelectionRectangleOverlay.IsShowing();
mbMouseOverIndicatorWasVisible = maMouseOverIndicatorOverlay.IsShowing();
mbInsertionIndicatorWasVisible = maInsertionIndicatorOverlay.IsShowing();
mbSubstitutionDisplayWasVisible = maSubstitutionOverlay.IsShowing();
// Remember that we have saved the current state.
meSavedStateType = eType;
// Hide the overlays.
if (eType==OPT_ALL || eType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Hide();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Hide();
if (eType==OPT_ALL || eType==OPT_PAINT)
{
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Hide();
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Hide();
}
}
}
void ViewOverlay::Restore (void)
{
if (--mnHideAndSaveLevel == 0)
{
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_PAINT)
{
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Show();
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Show();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Show();
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Show();
}
}
}
//===== OverlayBase =========================================================
OverlayBase::OverlayBase (ViewOverlay& rViewOverlay)
: mrViewOverlay(rViewOverlay),
mbIsShowing (false)
{
}
OverlayBase::~OverlayBase (void)
{
}
void OverlayBase::Paint (void)
{
}
bool OverlayBase::IsShowing (void)
{
return mbIsShowing;
}
void OverlayBase::Toggle (void)
{
if (IsShowing())
Hide();
else
Show();
}
void OverlayBase::Show (void)
{
if ( ! IsShowing())
{
mbIsShowing = true;
Paint ();
}
}
void OverlayBase::Hide (void)
{
if (IsShowing())
{
mbIsShowing = false;
Paint ();
}
}
ViewOverlay& OverlayBase::GetViewOverlay (void)
{
return mrViewOverlay;
}
//===== SubstitutionOverlay =================================================
SubstitutionOverlay::SubstitutionOverlay (ViewOverlay& rViewOverlay)
: OverlayBase(rViewOverlay)
{
}
SubstitutionOverlay::~SubstitutionOverlay (void)
{
}
void SubstitutionOverlay::Paint (void)
{
::osl::MutexGuard aGuard (maMutex);
SubstitutionShapeList::const_iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
while (aShape!=aShapeEnd)
{
mrViewOverlay.GetViewShell().DrawMarkRect (*aShape);
aShape++;
}
OverlayBase::Paint();
}
void SubstitutionOverlay::Create (
model::PageEnumeration& rSelection,
const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
maPosition = rPosition;
maShapes.clear();
while (rSelection.HasMoreElements())
{
maShapes.push_back (
rSelection.GetNextElement().GetPageObject()
->GetCurrentBoundRect());
}
}
void SubstitutionOverlay::Clear (void)
{
ShowingModeGuard aGuard (*this);
maShapes.clear();
}
void SubstitutionOverlay::Move (const Point& rOffset)
{
SetPosition (maPosition + rOffset);
}
void SubstitutionOverlay::SetPosition (const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
Point rOffset = rPosition - maPosition;
SubstitutionShapeList::iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
for (;aShape!=aShapeEnd; aShape++)
aShape->SetPos (aShape->TopLeft() + rOffset);
maPosition = rPosition;
}
const Point& SubstitutionOverlay::GetPosition (void) const
{
return maPosition;
}
//===== SelectionRectangleOverlay ===========================================
SelectionRectangleOverlay::SelectionRectangleOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
maAnchor(0,0),
maSecondCorner(0,0)
{
}
void SelectionRectangleOverlay::Paint (void)
{
// mrViewOverlay.GetViewShell().DrawMarkRect (maSelectionRectangle);
}
void SelectionRectangleOverlay::Show (void)
{
if ( ! mbIsShowing)
{
Start (maAnchor);
Update (maSecondCorner);
OverlayBase::Show();
}
}
void SelectionRectangleOverlay::Hide (void)
{
if (mbIsShowing)
{
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().EndEncirclement();
OverlayBase::Hide();
}
}
Rectangle SelectionRectangleOverlay::GetSelectionRectangle (void)
{
return Rectangle(maAnchor, maSecondCorner);
}
void SelectionRectangleOverlay::Start (const Point& rAnchor)
{
maAnchor = rAnchor;
maSecondCorner = rAnchor;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().BegEncirclement(maAnchor);
OverlayBase::Show();
}
void SelectionRectangleOverlay::Update (const Point& rSecondCorner)
{
maSecondCorner = rSecondCorner;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().MovEncirclement(maSecondCorner);
}
//===== InsertionIndicatorOverlay ===========================================
InsertionIndicatorOverlay::InsertionIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay)
{
}
void InsertionIndicatorOverlay::SetPositionAndSize (
const Rectangle& aNewBoundingBox)
{
if (maBoundingBox != aNewBoundingBox)
{
ShowingModeGuard aGuard (*this, true);
maBoundingBox = aNewBoundingBox;
}
}
void InsertionIndicatorOverlay::Paint (void)
{
Color aColor;
if (mbIsShowing)
aColor = Application::GetSettings().GetStyleSettings().GetFontColor();
else
aColor = Application::GetSettings().GetStyleSettings().GetWindowColor();
mrViewOverlay.GetViewShell().DrawFilledRect (
maBoundingBox,
aColor,
aColor);
}
void InsertionIndicatorOverlay::SetPosition (const Point& rPoint)
{
static const bool bAllowHorizontalInsertMarker = true;
Layouter& rLayouter (
mrViewOverlay.GetController().GetView().GetLayouter());
USHORT nPageCount
= mrViewOverlay.GetController().GetModel().GetPageCount();
sal_Int32 nInsertionIndex = rLayouter.GetInsertionIndex (rPoint,
bAllowHorizontalInsertMarker);
if (nInsertionIndex >= nPageCount)
nInsertionIndex = nPageCount-1;
sal_Int32 nDrawIndex = nInsertionIndex;
bool bVertical = false;
bool bLeftOrTop = false;
if (nInsertionIndex >= 0)
{
// Now that we know where to insert, we still have to determine
// where to draw the marker. There are two decisions to make:
// 1. Draw a vertical or a horizontal insert marker.
// The horizontal one may only be chosen when there is only one
// column.
// 2. The vertical (standard) insert marker may be painted left to
// the insert page or right of the previous one. When both pages
// are in the same row this makes no difference. Otherwise the
// posiotions are at the left and right ends of two rows.
Point aPageCenter (rLayouter.GetPageObjectBox (
nInsertionIndex).Center());
if (bAllowHorizontalInsertMarker
&& rLayouter.GetColumnCount() == 1)
{
bVertical = false;
bLeftOrTop = (rPoint.Y() <= aPageCenter.Y());
}
else
{
bVertical = true;
bLeftOrTop = (rPoint.X() <= aPageCenter.X());
}
// Add one when the mark was painted below or to the right of the
// page object.
if ( ! bLeftOrTop)
nInsertionIndex += 1;
}
mnInsertionIndex = nInsertionIndex;
Rectangle aBox;
if (mnInsertionIndex >= 0)
aBox = rLayouter.GetInsertionMarkerBox (
nDrawIndex,
bVertical,
bLeftOrTop);
SetPositionAndSize (aBox);
}
sal_Int32 InsertionIndicatorOverlay::GetInsertionPageIndex (void) const
{
return mnInsertionIndex;
}
//===== MouseOverIndicatorOverlay ===========================================
MouseOverIndicatorOverlay::MouseOverIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
mpPageUnderMouse(NULL)
{
}
void MouseOverIndicatorOverlay::SetSlideUnderMouse (
const model::PageDescriptor* pDescriptor)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
if (mpPageUnderMouse != pDescriptor)
{
ShowingModeGuard aGuard (*this, true);
mpPageUnderMouse = pDescriptor;
}
}
void MouseOverIndicatorOverlay::Paint (void)
{
if (mpPageUnderMouse != NULL)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
{
SlideSorterView& rView (rViewShell.GetSlideSorterController().GetView());
OutputDevice* pDevice = rView.GetWindow();
PageObjectViewObjectContact* pContact = mpPageUnderMouse->GetViewObjectContact();
if (pDevice != NULL
&& pContact != NULL)
{
pContact->PaintFrame(*pDevice, mbIsShowing);
}
}
}
}
} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS impress44 (1.6.8); FILE MERGED 2005/04/05 11:55:00 af 1.6.8.1: #i46671# Fixed repaint problems of selection rectangle.<commit_after>/*************************************************************************
*
* $RCSfile: SlsViewOverlay.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2005-04-12 16:59:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "view/SlsViewOverlay.hxx"
#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "view/SlideSorterView.hxx"
#include "SlideSorterViewShell.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsPageObject.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
#include "ViewShellBase.hxx"
#include "UpdateLockManager.hxx"
#include "Window.hxx"
#include "sdpage.hxx"
namespace {
class ShowingModeGuard
{
public:
explicit ShowingModeGuard (::sd::slidesorter::view::OverlayBase& rOverlay,
bool bHideAndSave = false)
: mrOverlay (rOverlay),
mbIsShowing (mrOverlay.IsShowing()),
mbRestorePending(false)
{
if (mbIsShowing)
if (bHideAndSave)
{
mrOverlay.GetViewOverlay().HideAndSave (
::sd::slidesorter::view::ViewOverlay::OPT_XOR);
mbRestorePending = true;
}
mrOverlay.Hide();
}
~ShowingModeGuard (void)
{
if (mbIsShowing)
{
mrOverlay.Show();
if (mbRestorePending)
mrOverlay.GetViewOverlay().Restore ();
}
}
private:
::sd::slidesorter::view::OverlayBase& mrOverlay;
bool mbIsShowing;
bool mbRestorePending;
};
}
namespace sd { namespace slidesorter { namespace view {
//===== ViewOverlay =========================================================
ViewOverlay::ViewOverlay (SlideSorterViewShell& rViewShell)
: mrViewShell (rViewShell),
maSelectionRectangleOverlay(*this),
maMouseOverIndicatorOverlay(*this),
maInsertionIndicatorOverlay(*this),
maSubstitutionOverlay(*this),
mbSelectionRectangleWasVisible(false),
mbMouseOverIndicatorWasVisible(false),
mbInsertionIndicatorWasVisible(false),
mbSubstitutionDisplayWasVisible(false),
mnHideAndSaveLevel(0)
{
}
ViewOverlay::~ViewOverlay (void)
{
}
SelectionRectangleOverlay& ViewOverlay::GetSelectionRectangleOverlay (void)
{
return maSelectionRectangleOverlay;
}
MouseOverIndicatorOverlay& ViewOverlay::GetMouseOverIndicatorOverlay (void)
{
return maMouseOverIndicatorOverlay;
}
InsertionIndicatorOverlay& ViewOverlay::GetInsertionIndicatorOverlay (void)
{
return maInsertionIndicatorOverlay;
}
SubstitutionOverlay& ViewOverlay::GetSubstitutionOverlay (void)
{
return maSubstitutionOverlay;
}
void ViewOverlay::Paint (void)
{
maSelectionRectangleOverlay.Paint();
maMouseOverIndicatorOverlay.Paint();
maInsertionIndicatorOverlay.Paint();
maSubstitutionOverlay.Paint();
}
controller::SlideSorterController& ViewOverlay::GetController (void)
{
return mrViewShell.GetSlideSorterController();
}
SlideSorterViewShell& ViewOverlay::GetViewShell (void)
{
return mrViewShell;
}
void ViewOverlay::HideAndSave (OverlayPaintType eType)
{
if (mnHideAndSaveLevel++ == 0)
{
// Remember the current state of the visiblities of the overlays.
mbSelectionRectangleWasVisible = maSelectionRectangleOverlay.IsShowing();
mbMouseOverIndicatorWasVisible = maMouseOverIndicatorOverlay.IsShowing();
mbInsertionIndicatorWasVisible = maInsertionIndicatorOverlay.IsShowing();
mbSubstitutionDisplayWasVisible = maSubstitutionOverlay.IsShowing();
// Remember that we have saved the current state.
meSavedStateType = eType;
// Hide the overlays.
if (eType==OPT_ALL || eType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Hide();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Hide();
if (eType==OPT_ALL || eType==OPT_PAINT)
{
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Hide();
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Hide();
}
}
}
void ViewOverlay::Restore (void)
{
if (--mnHideAndSaveLevel == 0)
{
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_PAINT)
{
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Show();
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Show();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Show();
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Show();
}
}
}
//===== OverlayBase =========================================================
OverlayBase::OverlayBase (ViewOverlay& rViewOverlay)
: mrViewOverlay(rViewOverlay),
mbIsShowing (false)
{
}
OverlayBase::~OverlayBase (void)
{
}
void OverlayBase::Paint (void)
{
}
bool OverlayBase::IsShowing (void)
{
return mbIsShowing;
}
void OverlayBase::Toggle (void)
{
if (IsShowing())
Hide();
else
Show();
}
void OverlayBase::Show (void)
{
if ( ! IsShowing())
{
mbIsShowing = true;
Paint ();
}
}
void OverlayBase::Hide (void)
{
if (IsShowing())
{
mbIsShowing = false;
Paint ();
}
}
ViewOverlay& OverlayBase::GetViewOverlay (void)
{
return mrViewOverlay;
}
//===== SubstitutionOverlay =================================================
SubstitutionOverlay::SubstitutionOverlay (ViewOverlay& rViewOverlay)
: OverlayBase(rViewOverlay)
{
}
SubstitutionOverlay::~SubstitutionOverlay (void)
{
}
void SubstitutionOverlay::Paint (void)
{
::osl::MutexGuard aGuard (maMutex);
SubstitutionShapeList::const_iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
while (aShape!=aShapeEnd)
{
mrViewOverlay.GetViewShell().DrawMarkRect (*aShape);
aShape++;
}
OverlayBase::Paint();
}
void SubstitutionOverlay::Create (
model::PageEnumeration& rSelection,
const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
maPosition = rPosition;
maShapes.clear();
while (rSelection.HasMoreElements())
{
maShapes.push_back (
rSelection.GetNextElement().GetPageObject()
->GetCurrentBoundRect());
}
}
void SubstitutionOverlay::Clear (void)
{
ShowingModeGuard aGuard (*this);
maShapes.clear();
}
void SubstitutionOverlay::Move (const Point& rOffset)
{
SetPosition (maPosition + rOffset);
}
void SubstitutionOverlay::SetPosition (const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
Point rOffset = rPosition - maPosition;
SubstitutionShapeList::iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
for (;aShape!=aShapeEnd; aShape++)
aShape->SetPos (aShape->TopLeft() + rOffset);
maPosition = rPosition;
}
const Point& SubstitutionOverlay::GetPosition (void) const
{
return maPosition;
}
//===== SelectionRectangleOverlay ===========================================
SelectionRectangleOverlay::SelectionRectangleOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
maAnchor(0,0),
maSecondCorner(0,0)
{
}
void SelectionRectangleOverlay::Paint (void)
{
// mrViewOverlay.GetViewShell().DrawMarkRect (maSelectionRectangle);
}
void SelectionRectangleOverlay::Show (void)
{
if ( ! mbIsShowing)
{
SlideSorterView& rView (mrViewOverlay.GetViewShell().GetSlideSorterController().GetView());
rView.BegEncirclement(maAnchor);
rView.MovEncirclement(maSecondCorner);
OverlayBase::Show();
}
}
void SelectionRectangleOverlay::Hide (void)
{
if (mbIsShowing)
{
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().EndEncirclement();
OverlayBase::Hide();
}
}
Rectangle SelectionRectangleOverlay::GetSelectionRectangle (void)
{
return Rectangle(maAnchor, maSecondCorner);
}
void SelectionRectangleOverlay::Start (const Point& rAnchor)
{
maAnchor = rAnchor;
maSecondCorner = rAnchor;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().BegEncirclement(maAnchor);
OverlayBase::Show();
}
void SelectionRectangleOverlay::Update (const Point& rSecondCorner)
{
maSecondCorner = rSecondCorner;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().MovEncirclement(maSecondCorner);
}
//===== InsertionIndicatorOverlay ===========================================
InsertionIndicatorOverlay::InsertionIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay)
{
}
void InsertionIndicatorOverlay::SetPositionAndSize (
const Rectangle& aNewBoundingBox)
{
if (maBoundingBox != aNewBoundingBox)
{
ShowingModeGuard aGuard (*this, true);
maBoundingBox = aNewBoundingBox;
}
}
void InsertionIndicatorOverlay::Paint (void)
{
Color aColor;
if (mbIsShowing)
aColor = Application::GetSettings().GetStyleSettings().GetFontColor();
else
aColor = Application::GetSettings().GetStyleSettings().GetWindowColor();
mrViewOverlay.GetViewShell().DrawFilledRect (
maBoundingBox,
aColor,
aColor);
}
void InsertionIndicatorOverlay::SetPosition (const Point& rPoint)
{
static const bool bAllowHorizontalInsertMarker = true;
Layouter& rLayouter (
mrViewOverlay.GetController().GetView().GetLayouter());
USHORT nPageCount
= mrViewOverlay.GetController().GetModel().GetPageCount();
sal_Int32 nInsertionIndex = rLayouter.GetInsertionIndex (rPoint,
bAllowHorizontalInsertMarker);
if (nInsertionIndex >= nPageCount)
nInsertionIndex = nPageCount-1;
sal_Int32 nDrawIndex = nInsertionIndex;
bool bVertical = false;
bool bLeftOrTop = false;
if (nInsertionIndex >= 0)
{
// Now that we know where to insert, we still have to determine
// where to draw the marker. There are two decisions to make:
// 1. Draw a vertical or a horizontal insert marker.
// The horizontal one may only be chosen when there is only one
// column.
// 2. The vertical (standard) insert marker may be painted left to
// the insert page or right of the previous one. When both pages
// are in the same row this makes no difference. Otherwise the
// posiotions are at the left and right ends of two rows.
Point aPageCenter (rLayouter.GetPageObjectBox (
nInsertionIndex).Center());
if (bAllowHorizontalInsertMarker
&& rLayouter.GetColumnCount() == 1)
{
bVertical = false;
bLeftOrTop = (rPoint.Y() <= aPageCenter.Y());
}
else
{
bVertical = true;
bLeftOrTop = (rPoint.X() <= aPageCenter.X());
}
// Add one when the mark was painted below or to the right of the
// page object.
if ( ! bLeftOrTop)
nInsertionIndex += 1;
}
mnInsertionIndex = nInsertionIndex;
Rectangle aBox;
if (mnInsertionIndex >= 0)
aBox = rLayouter.GetInsertionMarkerBox (
nDrawIndex,
bVertical,
bLeftOrTop);
SetPositionAndSize (aBox);
}
sal_Int32 InsertionIndicatorOverlay::GetInsertionPageIndex (void) const
{
return mnInsertionIndex;
}
//===== MouseOverIndicatorOverlay ===========================================
MouseOverIndicatorOverlay::MouseOverIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
mpPageUnderMouse(NULL)
{
}
void MouseOverIndicatorOverlay::SetSlideUnderMouse (
const model::PageDescriptor* pDescriptor)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
if (mpPageUnderMouse != pDescriptor)
{
ShowingModeGuard aGuard (*this, true);
mpPageUnderMouse = pDescriptor;
}
}
void MouseOverIndicatorOverlay::Paint (void)
{
if (mpPageUnderMouse != NULL)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
{
SlideSorterView& rView (rViewShell.GetSlideSorterController().GetView());
OutputDevice* pDevice = rView.GetWindow();
PageObjectViewObjectContact* pContact = mpPageUnderMouse->GetViewObjectContact();
if (pDevice != NULL
&& pContact != NULL)
{
pContact->PaintFrame(*pDevice, mbIsShowing);
}
}
}
}
} } } // end of namespace ::sd::slidesorter::view
<|endoftext|>
|
<commit_before>/*
This file is part of the KDE project
Copyright (C) 2002-2003 Daniel Molkentin <molkentin@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qpopupmenu.h>
#include <qsplitter.h>
#include <qtextedit.h>
#include <dcopclient.h>
#include <dcopref.h>
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klistview.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kstdaction.h>
#include <kxmlguifactory.h>
#include <libkdepim/infoextension.h>
#include <libkdepim/sidebarextension.h>
#include "knotes_part.h"
class NotesItem : public KListViewItem
{
public:
NotesItem( KListView *parent, const QString &id, const QString &text );
QString id() { return noteID; };
private:
QString noteID;
};
NotesItem::NotesItem( KListView *parent, const QString &id, const QString &text )
: KListViewItem( parent, text )
{
noteID = id;
setRenameEnabled( 0, true );
setPixmap( 0, KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Small ) );
}
KNotesPart::KNotesPart( QObject *parent, const char *name )
: KParts::ReadOnlyPart( parent, name ),
mPopupMenu( 0 ),
mNoteChanged( false )
{
setInstance( new KInstance( "knotes" ) );
mICal = new KCal::CalendarLocal;
connect(mICal, SIGNAL(calendarChanged()), SLOT(slotCalendarChanged()));
mICal->load(::locate("data", "knotes/notes.ics"));
mNotes = mICal->journals();
QSplitter *splitter = new QSplitter( Qt::Horizontal );
mNotesView = new KListView( splitter );
mNotesView->setSelectionMode( QListView::Extended );
mNotesView->addColumn( i18n( "Title" ) );
(void) new KParts::SideBarExtension( mNotesView, this, "NotesSideBarExtension" );
mNotesEdit = new QTextEdit( splitter );
KStdAction::openNew( this, SLOT( newNote() ), actionCollection() );
mActionEdit = new KAction( i18n( "Rename" ), "editrename", this,
SLOT( renameNote() ), actionCollection(),
"edit_rename" );
mActionDelete = new KAction( i18n( "Delete" ), "editdelete", 0, this,
SLOT( removeSelectedNotes() ), actionCollection(),
"edit_delete" );
(void) new KAction( i18n( "Reload" ), "reload", 0, this,
SLOT( reloadNotes() ), actionCollection(), "view_refresh" );
connect( mNotesView, SIGNAL( selectionChanged() ),
this, SLOT( showNote() ) );
connect( mNotesView, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int ) ),
this, SLOT( popupRMB( QListViewItem*, const QPoint&, int ) ) );
connect( mNotesView, SIGNAL( itemRenamed( QListViewItem*, int, const QString& ) ),
this, SLOT( noteRenamed( QListViewItem*, int, const QString& ) ) );
connect( mNotesEdit, SIGNAL( textChanged() ),
this, SLOT( noteChanged() ) );
reloadNotes();
setWidget( splitter );
mAppIcon = KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Small );
KParts::InfoExtension *info = new KParts::InfoExtension( this, "KNoteInfoExtension" );
connect( this, SIGNAL( noteSelected( const QString& ) ),
info, SIGNAL( textChanged( const QString& ) ) );
connect( this, SIGNAL( noteSelected( const QPixmap& ) ),
info, SIGNAL( iconChanged( const QPixmap& ) ) );
setXMLFile( "knotes_part.rc" );
}
KNotesPart::~KNotesPart()
{
saveNote();
}
void KNotesPart::reloadNotes()
{
if ( !kapp->dcopClient()->isApplicationRegistered( "knotes" ) ) {
QString *error = 0;
int started = KApplication::startServiceByDesktopName( "knotes",
QString(), error );
if ( started > 0 ) {
if ( error )
KMessageBox::error( 0L, *error, i18n( "Error" ) );
return;
}
delete error;
}
mNotesView->clear();
NotesMap map;
QCString replyType;
QByteArray data, replyData;
QDataStream arg( data, IO_WriteOnly );
if ( kapp->dcopClient()->call( "knotes", "KNotesIface", "notes()", data, replyType, replyData ) ) {
kdDebug(5602) << "Reply Type: " << replyType << endl;
QDataStream answer( replyData, IO_ReadOnly );
answer >> map;
}
NotesMap::ConstIterator it;
for ( it = map.begin(); it != map.end(); ++it )
(void) new NotesItem( mNotesView, it.key(), it.data() );
mNotesView->setCurrentItem( mNotesView->firstChild() );
showNote( mNotesView->firstChild() );
}
bool KNotesPart::openFile()
{
return false;
}
void KNotesPart::popupRMB( QListViewItem *item, const QPoint& pos, int )
{
mPopupMenu = static_cast<QPopupMenu*>( factory()->container( "notePopup", this ) );
if ( !mPopupMenu )
return;
bool state = ( item != 0 );
mActionEdit->setEnabled( state );
mActionDelete->setEnabled( state );
mPopupMenu->popup( pos );
}
void KNotesPart::removeNote()
{
NotesItem *item = static_cast<NotesItem*>( mNotesView->currentItem() );
if ( !item )
return;
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "killNote(QString, bool)", item->id(), true );
reloadNotes();
}
void KNotesPart::removeSelectedNotes()
{
QStringList ids;
QStringList names;
QListViewItemIterator it( mNotesView );
while ( it.current() ) {
if ( it.current()->isSelected() ) {
ids += static_cast<NotesItem*>( it.current() )->id();
names += it.current()->text( 0 );
}
++it;
}
if ( ids.isEmpty() )
return;
if ( ids.count() == 1 ) {
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "killNote(QString)", ids.first() );
} else {
int ret = KMessageBox::warningContinueCancelList( 0,
i18n( "Do you really want to delete that note?", "Do you really want to delete these %n notes?", ids.count() ),
names,
i18n( "Confirm Delete" ),
i18n( "Delete" ) );
int doIt = ( ret == KMessageBox::Continue );
if ( doIt )
for ( QStringList::ConstIterator it = ids.begin(); it != ids.end(); ++it ) {
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "killNote(QString, bool)", *it, true );
}
}
reloadNotes();
}
void KNotesPart::renameNote()
{
if ( mNotesView->currentItem() )
mNotesView->currentItem()->startRename( 0 );
}
void KNotesPart::noteRenamed( QListViewItem *i, int, const QString& text )
{
NotesItem *item = static_cast<NotesItem*>( i );
if ( !item )
return;
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.send( "setName(QString,QString)", item->id(), text );
}
void KNotesPart::showNote()
{
showNote( mNotesView->currentItem() );
}
void KNotesPart::showNote( QListViewItem *i )
{
if ( !mCurrentNote.isEmpty() ) {
if ( mNoteChanged )
saveNote();
}
mNotesEdit->clear();
NotesItem *item = static_cast<NotesItem*>( i );
if ( !item ) {
mCurrentNote = "";
return;
}
mCurrentNote = item->id();
DCOPRef dcopCall( "knotes", "KNotesIface" );
mNotesEdit->blockSignals( true );
mNotesEdit->setText( dcopCall.call( "text(QString)", item->id() ) );
mNotesEdit->blockSignals( false );
emit noteSelected( item->text( 0 ) );
emit noteSelected( mAppIcon );
}
void KNotesPart::noteChanged()
{
mNoteChanged = true;
}
void KNotesPart::saveNote()
{
if ( mCurrentNote.isEmpty() )
return;
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.send( "setText(QString,QString)", mCurrentNote, mNotesEdit->text() );
mNoteChanged = false;
}
void KNotesPart::newNote()
{
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "newNote(QString, QString)", QString::null, QString::null );
reloadNotes();
}
#include "knotes_part.moc"
<commit_msg>This slot doesn't exist<commit_after>/*
This file is part of the KDE project
Copyright (C) 2002-2003 Daniel Molkentin <molkentin@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qpopupmenu.h>
#include <qsplitter.h>
#include <qtextedit.h>
#include <dcopclient.h>
#include <dcopref.h>
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klistview.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kstdaction.h>
#include <kxmlguifactory.h>
#include <libkdepim/infoextension.h>
#include <libkdepim/sidebarextension.h>
#include "knotes_part.h"
class NotesItem : public KListViewItem
{
public:
NotesItem( KListView *parent, const QString &id, const QString &text );
QString id() { return noteID; };
private:
QString noteID;
};
NotesItem::NotesItem( KListView *parent, const QString &id, const QString &text )
: KListViewItem( parent, text )
{
noteID = id;
setRenameEnabled( 0, true );
setPixmap( 0, KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Small ) );
}
KNotesPart::KNotesPart( QObject *parent, const char *name )
: KParts::ReadOnlyPart( parent, name ),
mPopupMenu( 0 ),
mNoteChanged( false )
{
setInstance( new KInstance( "knotes" ) );
mICal = new KCal::CalendarLocal;
//connect(mICal, SIGNAL(calendarChanged()), SLOT(slotCalendarChanged()));
mICal->load(::locate("data", "knotes/notes.ics"));
mNotes = mICal->journals();
QSplitter *splitter = new QSplitter( Qt::Horizontal );
mNotesView = new KListView( splitter );
mNotesView->setSelectionMode( QListView::Extended );
mNotesView->addColumn( i18n( "Title" ) );
(void) new KParts::SideBarExtension( mNotesView, this, "NotesSideBarExtension" );
mNotesEdit = new QTextEdit( splitter );
KStdAction::openNew( this, SLOT( newNote() ), actionCollection() );
mActionEdit = new KAction( i18n( "Rename" ), "editrename", this,
SLOT( renameNote() ), actionCollection(),
"edit_rename" );
mActionDelete = new KAction( i18n( "Delete" ), "editdelete", 0, this,
SLOT( removeSelectedNotes() ), actionCollection(),
"edit_delete" );
(void) new KAction( i18n( "Reload" ), "reload", 0, this,
SLOT( reloadNotes() ), actionCollection(), "view_refresh" );
connect( mNotesView, SIGNAL( selectionChanged() ),
this, SLOT( showNote() ) );
connect( mNotesView, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int ) ),
this, SLOT( popupRMB( QListViewItem*, const QPoint&, int ) ) );
connect( mNotesView, SIGNAL( itemRenamed( QListViewItem*, int, const QString& ) ),
this, SLOT( noteRenamed( QListViewItem*, int, const QString& ) ) );
connect( mNotesEdit, SIGNAL( textChanged() ),
this, SLOT( noteChanged() ) );
reloadNotes();
setWidget( splitter );
mAppIcon = KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Small );
KParts::InfoExtension *info = new KParts::InfoExtension( this, "KNoteInfoExtension" );
connect( this, SIGNAL( noteSelected( const QString& ) ),
info, SIGNAL( textChanged( const QString& ) ) );
connect( this, SIGNAL( noteSelected( const QPixmap& ) ),
info, SIGNAL( iconChanged( const QPixmap& ) ) );
setXMLFile( "knotes_part.rc" );
}
KNotesPart::~KNotesPart()
{
saveNote();
}
void KNotesPart::reloadNotes()
{
if ( !kapp->dcopClient()->isApplicationRegistered( "knotes" ) ) {
QString *error = 0;
int started = KApplication::startServiceByDesktopName( "knotes",
QString(), error );
if ( started > 0 ) {
if ( error )
KMessageBox::error( 0L, *error, i18n( "Error" ) );
return;
}
delete error;
}
mNotesView->clear();
NotesMap map;
QCString replyType;
QByteArray data, replyData;
QDataStream arg( data, IO_WriteOnly );
if ( kapp->dcopClient()->call( "knotes", "KNotesIface", "notes()", data, replyType, replyData ) ) {
kdDebug(5602) << "Reply Type: " << replyType << endl;
QDataStream answer( replyData, IO_ReadOnly );
answer >> map;
}
NotesMap::ConstIterator it;
for ( it = map.begin(); it != map.end(); ++it )
(void) new NotesItem( mNotesView, it.key(), it.data() );
mNotesView->setCurrentItem( mNotesView->firstChild() );
showNote( mNotesView->firstChild() );
}
bool KNotesPart::openFile()
{
return false;
}
void KNotesPart::popupRMB( QListViewItem *item, const QPoint& pos, int )
{
mPopupMenu = static_cast<QPopupMenu*>( factory()->container( "notePopup", this ) );
if ( !mPopupMenu )
return;
bool state = ( item != 0 );
mActionEdit->setEnabled( state );
mActionDelete->setEnabled( state );
mPopupMenu->popup( pos );
}
void KNotesPart::removeNote()
{
NotesItem *item = static_cast<NotesItem*>( mNotesView->currentItem() );
if ( !item )
return;
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "killNote(QString, bool)", item->id(), true );
reloadNotes();
}
void KNotesPart::removeSelectedNotes()
{
QStringList ids;
QStringList names;
QListViewItemIterator it( mNotesView );
while ( it.current() ) {
if ( it.current()->isSelected() ) {
ids += static_cast<NotesItem*>( it.current() )->id();
names += it.current()->text( 0 );
}
++it;
}
if ( ids.isEmpty() )
return;
if ( ids.count() == 1 ) {
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "killNote(QString)", ids.first() );
} else {
int ret = KMessageBox::warningContinueCancelList( 0,
i18n( "Do you really want to delete that note?", "Do you really want to delete these %n notes?", ids.count() ),
names,
i18n( "Confirm Delete" ),
i18n( "Delete" ) );
int doIt = ( ret == KMessageBox::Continue );
if ( doIt )
for ( QStringList::ConstIterator it = ids.begin(); it != ids.end(); ++it ) {
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "killNote(QString, bool)", *it, true );
}
}
reloadNotes();
}
void KNotesPart::renameNote()
{
if ( mNotesView->currentItem() )
mNotesView->currentItem()->startRename( 0 );
}
void KNotesPart::noteRenamed( QListViewItem *i, int, const QString& text )
{
NotesItem *item = static_cast<NotesItem*>( i );
if ( !item )
return;
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.send( "setName(QString,QString)", item->id(), text );
}
void KNotesPart::showNote()
{
showNote( mNotesView->currentItem() );
}
void KNotesPart::showNote( QListViewItem *i )
{
if ( !mCurrentNote.isEmpty() ) {
if ( mNoteChanged )
saveNote();
}
mNotesEdit->clear();
NotesItem *item = static_cast<NotesItem*>( i );
if ( !item ) {
mCurrentNote = "";
return;
}
mCurrentNote = item->id();
DCOPRef dcopCall( "knotes", "KNotesIface" );
mNotesEdit->blockSignals( true );
mNotesEdit->setText( dcopCall.call( "text(QString)", item->id() ) );
mNotesEdit->blockSignals( false );
emit noteSelected( item->text( 0 ) );
emit noteSelected( mAppIcon );
}
void KNotesPart::noteChanged()
{
mNoteChanged = true;
}
void KNotesPart::saveNote()
{
if ( mCurrentNote.isEmpty() )
return;
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.send( "setText(QString,QString)", mCurrentNote, mNotesEdit->text() );
mNoteChanged = false;
}
void KNotesPart::newNote()
{
DCOPRef dcopCall( "knotes", "KNotesIface" );
dcopCall.call( "newNote(QString, QString)", QString::null, QString::null );
reloadNotes();
}
#include "knotes_part.moc"
<|endoftext|>
|
<commit_before>// $CXX -std=c++11 webmdump.cc -pthread -o webmdump -Wall -Wextra -Werror
#include "io-main.h"
#include "../broadcast.cc"
static const char * ebml_tag_name(const struct ebml_tag t)
{
switch (t.id) {
case EBML_TAG_EBML: return "EBML";
case EBML_TAG_Void: return "Void";
case EBML_TAG_CRC32: return "CRC32";
case EBML_TAG_Segment: return "Segment";
case EBML_TAG_SeekHead: return "SeekHead";
case EBML_TAG_Info: return "Info";
case EBML_TAG_Cluster: return "Cluster";
case EBML_TAG_PrevSize: return "PrevSize";
case EBML_TAG_SimpleBlock: return "SimpleBlock";
case EBML_TAG_BlockGroup: return "BlockGroup";
case EBML_TAG_Block: return "Block";
case EBML_TAG_ReferenceBlock: return "ReferenceBlock";
case EBML_TAG_Tracks: return "Tracks";
case EBML_TAG_Cues: return "Cues";
case EBML_TAG_Chapters: return "Chapters";
}
static char unknown[16];
snprintf(unknown, sizeof(unknown), "0x%X", (unsigned) t.id);
return unknown;
}
struct protocol : aio::protocol
{
const int id;
static int _id;
std::string buffer;
protocol(aio::transport *t) : aio::protocol(t), id(_id++)
{
printf("<%d> +++\n", id);
}
virtual ~protocol()
{
printf("<%d> ---\n", id);
}
int data_received(const struct aio::stringview data)
{
buffer.append(data.base, data.size);
struct ebml_buffer buf = { (const uint8_t *) buffer.data(), buffer.size() };
while (1) {
struct ebml_tag tag = ebml_parse_tag(buf);
if (!tag.consumed)
break;
if (!ebml_tag_is_endless(tag) && tag.id != EBML_TAG_Segment) {
if (tag.consumed + tag.length > buf.size)
break;
buf = ebml_buffer_advance(buf, tag.length);
}
buf = ebml_buffer_advance(buf, tag.consumed);
printf("<%d> %s [%zu]\n", id, ebml_tag_name(tag), tag.length);
}
buffer.erase(0, (const char *) buf.base - buffer.data());
return 0;
}
};
int protocol::_id = 0;
int main(void)
{
return aio_main::run_server([](aio::transport *t) { return new protocol(t); });
}
<commit_msg>http-webm: fix an invalid cast.<commit_after>// $CXX -std=c++11 webmdump.cc -pthread -o webmdump -Wall -Wextra -Werror
#include "io-main.h"
#include "../broadcast.cc"
static const char * ebml_tag_name(const struct ebml_tag t)
{
switch (t.id) {
case EBML_TAG_EBML: return "EBML";
case EBML_TAG_Void: return "Void";
case EBML_TAG_CRC32: return "CRC32";
case EBML_TAG_Segment: return "Segment";
case EBML_TAG_SeekHead: return "SeekHead";
case EBML_TAG_Info: return "Info";
case EBML_TAG_Cluster: return "Cluster";
case EBML_TAG_PrevSize: return "PrevSize";
case EBML_TAG_SimpleBlock: return "SimpleBlock";
case EBML_TAG_BlockGroup: return "BlockGroup";
case EBML_TAG_Block: return "Block";
case EBML_TAG_ReferenceBlock: return "ReferenceBlock";
case EBML_TAG_Tracks: return "Tracks";
case EBML_TAG_Cues: return "Cues";
case EBML_TAG_Chapters: return "Chapters";
}
static char unknown[16];
snprintf(unknown, sizeof(unknown), "0x%X", (unsigned) t.id);
return unknown;
}
struct protocol : aio::protocol
{
const int id;
static int _id;
std::string buffer;
protocol(aio::transport *t) : aio::protocol(t), id(_id++)
{
printf("<%d> +++\n", id);
}
virtual ~protocol()
{
printf("<%d> ---\n", id);
}
int data_received(const struct aio::stringview data)
{
buffer.append(data.base, data.size);
struct ebml_buffer buf = { (uint8_t *) buffer.data(), buffer.size() };
while (1) {
struct ebml_tag tag = ebml_parse_tag(buf);
if (!tag.consumed)
break;
if (!ebml_tag_is_endless(tag) && tag.id != EBML_TAG_Segment) {
if (tag.consumed + tag.length > buf.size)
break;
buf = ebml_buffer_advance(buf, tag.length);
}
buf = ebml_buffer_advance(buf, tag.consumed);
printf("<%d> %s [%zu]\n", id, ebml_tag_name(tag), tag.length);
}
buffer.erase(0, (const char *) buf.base - buffer.data());
return 0;
}
};
int protocol::_id = 0;
int main(void)
{
return aio_main::run_server([](aio::transport *t) { return new protocol(t); });
}
<|endoftext|>
|
<commit_before>#ifndef INC_AL_CONTROL_GLV_HPP
#define INC_AL_CONTROL_GLV_HPP
#include "allocore/io/al_Window.hpp"
#include "GLV/glv_core.h"
namespace al {
struct GLVControl {
GLVControl(glv::GLV * v): mGLV(v){}
void glv(glv::GLV * v){ mGLV=v; }
glv::GLV& glv(){ return *mGLV; }
protected:
glv::GLV * mGLV;
};
/// Mapping from keyboard and mouse controls to a GLV object
struct GLVInputControl : public GLVControl, public InputEventHandler {
GLVInputControl(glv::GLV * v): GLVControl(v){}
virtual ~GLVInputControl(){}
virtual bool onMouseDown(const Mouse& m){
glv::space_t xrel=m.x(), yrel=m.y();
glv().setMouseDown(xrel,yrel, m.button(), 0);
glv().setMousePos(m.x(), m.y(), xrel, yrel);
return !glv().propagateEvent();
}
virtual bool onMouseDrag(const Mouse& m){
return !motionToGLV(m, glv::Event::MouseDrag);
}
virtual bool onMouseMove(const al::Mouse& m){
return !motionToGLV(m, glv::Event::MouseMove);
}
virtual bool onMouseUp(const al::Mouse& m){
glv::space_t xrel, yrel;
glv().setMouseUp(xrel,yrel, m.button(), 0);
glv().setMousePos(m.x(), m.y(), xrel, yrel);
return !glv().propagateEvent();
}
virtual bool onKeyDown(const Keyboard& k){
return !keyToGLV(k, true);
}
virtual bool onKeyUp(const al::Keyboard& k){
return !keyToGLV(k, false);
}
protected:
bool keyToGLV(const al::Keyboard& k, bool down){
down ? glv().setKeyDown(k.key()) : glv().setKeyUp(k.key());
const_cast<glv::Keyboard*>(&glv().keyboard())->alt(k.alt());
const_cast<glv::Keyboard*>(&glv().keyboard())->caps(k.caps());
const_cast<glv::Keyboard*>(&glv().keyboard())->ctrl(k.ctrl());
const_cast<glv::Keyboard*>(&glv().keyboard())->meta(k.meta());
const_cast<glv::Keyboard*>(&glv().keyboard())->shift(k.shift());
return glv().propagateEvent();
}
bool motionToGLV(const al::Mouse& m, glv::Event::t e){
glv::space_t x = m.x(), y = m.y(), relx = x, rely = y;
glv().setMouseMotion(relx, rely, e);
glv().setMousePos((int)x, (int)y, relx, rely);
return glv().propagateEvent();
}
};
/// Mapping from window events to a GLV object
struct GLVWindowControl : public GLVControl, public WindowEventHandler {
GLVWindowControl(glv::GLV * v): GLVControl(v){}
virtual ~GLVWindowControl(){}
virtual bool onCreate(){
glv().broadcastEvent(glv::Event::WindowCreate);
return true;
}
virtual bool onDestroy(){
glv().broadcastEvent(glv::Event::WindowDestroy);
return true;
}
virtual bool onFrame(){
glv().drawGLV(glv().w, glv().h, window().spf());
//glv().preamble(glv().w, glv().h);
//glv().drawWidgets(glv().w, glv().h, window().spf());
return true;
}
virtual bool onResize(int dw, int dh){
glv().extent(glv().width() + dw, glv().height() + dh);
//printf("%d %d %f %f\n", dw, dh, glv().width(), glv().height());
glv().broadcastEvent(glv::Event::WindowResize);
return true;
}
//virtual bool onVisibility(bool v){ return true; }
};
/// Pose GLV model
struct PoseModel : public glv::Model{
PoseModel(Pose& p): pose(p){}
virtual ~PoseModel(){}
virtual const glv::Data& getData(glv::Data& d) const {
d.resize(glv::Data::FLOAT, 7);
d.assignFromArray(pose.pos().elems, 3);
d.assignFromArray(&pose.quat()[0], 4, 1, 3);
// double a[4];
// pose.quat().toAxisAngle(a[0], a[1],a[2],a[3]);
// d.assignFromArray(a, 4, 1, 3);
return d;
}
virtual void setData(const glv::Data& d){
pose.pos(d.at<float>(0), d.at<float>(1), d.at<float>(2));
pose.quat().set(d.at<float>(3), d.at<float>(4), d.at<float>(5), d.at<float>(6));
// pose.quat().fromAxisAngle(d.at<float>(3), d.at<float>(4), d.at<float>(5), d.at<float>(6));
}
Pose& pose;
};
} // al::
#endif
<commit_msg>no need for GLV path specifier<commit_after>#ifndef INC_AL_CONTROL_GLV_HPP
#define INC_AL_CONTROL_GLV_HPP
#include "allocore/io/al_Window.hpp"
#include "glv_core.h"
namespace al {
struct GLVControl {
GLVControl(glv::GLV * v): mGLV(v){}
void glv(glv::GLV * v){ mGLV=v; }
glv::GLV& glv(){ return *mGLV; }
protected:
glv::GLV * mGLV;
};
/// Mapping from keyboard and mouse controls to a GLV object
struct GLVInputControl : public GLVControl, public InputEventHandler {
GLVInputControl(glv::GLV * v): GLVControl(v){}
virtual ~GLVInputControl(){}
virtual bool onMouseDown(const Mouse& m){
glv::space_t xrel=m.x(), yrel=m.y();
glv().setMouseDown(xrel,yrel, m.button(), 0);
glv().setMousePos(m.x(), m.y(), xrel, yrel);
return !glv().propagateEvent();
}
virtual bool onMouseDrag(const Mouse& m){
return !motionToGLV(m, glv::Event::MouseDrag);
}
virtual bool onMouseMove(const al::Mouse& m){
return !motionToGLV(m, glv::Event::MouseMove);
}
virtual bool onMouseUp(const al::Mouse& m){
glv::space_t xrel, yrel;
glv().setMouseUp(xrel,yrel, m.button(), 0);
glv().setMousePos(m.x(), m.y(), xrel, yrel);
return !glv().propagateEvent();
}
virtual bool onKeyDown(const Keyboard& k){
return !keyToGLV(k, true);
}
virtual bool onKeyUp(const al::Keyboard& k){
return !keyToGLV(k, false);
}
protected:
bool keyToGLV(const al::Keyboard& k, bool down){
down ? glv().setKeyDown(k.key()) : glv().setKeyUp(k.key());
const_cast<glv::Keyboard*>(&glv().keyboard())->alt(k.alt());
const_cast<glv::Keyboard*>(&glv().keyboard())->caps(k.caps());
const_cast<glv::Keyboard*>(&glv().keyboard())->ctrl(k.ctrl());
const_cast<glv::Keyboard*>(&glv().keyboard())->meta(k.meta());
const_cast<glv::Keyboard*>(&glv().keyboard())->shift(k.shift());
return glv().propagateEvent();
}
bool motionToGLV(const al::Mouse& m, glv::Event::t e){
glv::space_t x = m.x(), y = m.y(), relx = x, rely = y;
glv().setMouseMotion(relx, rely, e);
glv().setMousePos((int)x, (int)y, relx, rely);
return glv().propagateEvent();
}
};
/// Mapping from window events to a GLV object
struct GLVWindowControl : public GLVControl, public WindowEventHandler {
GLVWindowControl(glv::GLV * v): GLVControl(v){}
virtual ~GLVWindowControl(){}
virtual bool onCreate(){
glv().broadcastEvent(glv::Event::WindowCreate);
return true;
}
virtual bool onDestroy(){
glv().broadcastEvent(glv::Event::WindowDestroy);
return true;
}
virtual bool onFrame(){
glv().drawGLV(glv().w, glv().h, window().spf());
//glv().preamble(glv().w, glv().h);
//glv().drawWidgets(glv().w, glv().h, window().spf());
return true;
}
virtual bool onResize(int dw, int dh){
glv().extent(glv().width() + dw, glv().height() + dh);
//printf("%d %d %f %f\n", dw, dh, glv().width(), glv().height());
glv().broadcastEvent(glv::Event::WindowResize);
return true;
}
//virtual bool onVisibility(bool v){ return true; }
};
/// Pose GLV model
struct PoseModel : public glv::Model{
PoseModel(Pose& p): pose(p){}
virtual ~PoseModel(){}
virtual const glv::Data& getData(glv::Data& d) const {
d.resize(glv::Data::FLOAT, 7);
d.assignFromArray(pose.pos().elems, 3);
d.assignFromArray(&pose.quat()[0], 4, 1, 3);
// double a[4];
// pose.quat().toAxisAngle(a[0], a[1],a[2],a[3]);
// d.assignFromArray(a, 4, 1, 3);
return d;
}
virtual void setData(const glv::Data& d){
pose.pos(d.at<float>(0), d.at<float>(1), d.at<float>(2));
pose.quat().set(d.at<float>(3), d.at<float>(4), d.at<float>(5), d.at<float>(6));
// pose.quat().fromAxisAngle(d.at<float>(3), d.at<float>(4), d.at<float>(5), d.at<float>(6));
}
Pose& pose;
};
} // al::
#endif
<|endoftext|>
|
<commit_before>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Covariant Innovation General Public License,
* Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://covariant.cn/licenses/LICENSE-1.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2019 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,2,1,6
#define COVSCRIPT_VERSION_STR "3.2.1 Ailuropoda melanoleuca(Unstable) Build 6"
#define COVSCRIPT_STD_VERSION 190501
#define COVSCRIPT_API_VERSION 190622
#define COVSCRIPT_ABI_VERSION 190510
<commit_msg>version: 3.2.1 build 7<commit_after>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Covariant Innovation General Public License,
* Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://covariant.cn/licenses/LICENSE-1.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2019 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,2,1,7
#define COVSCRIPT_VERSION_STR "3.2.1 Ailuropoda melanoleuca(Unstable) Build 7"
#define COVSCRIPT_STD_VERSION 190601
#define COVSCRIPT_API_VERSION 190623
#define COVSCRIPT_ABI_VERSION 190510
<|endoftext|>
|
<commit_before>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Covariant Innovation General Public License,
* Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://covariant.cn/licenses/LICENSE-1.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2019 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,2,0,8
#define COVSCRIPT_VERSION_STR "3.2.0 Psephurus gladius(Stable) Build 8"
#define COVSCRIPT_STD_VERSION 190501
#define COVSCRIPT_API_VERSION 190510
#define COVSCRIPT_ABI_VERSION 190510
<commit_msg>Update version.hpp<commit_after>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Covariant Innovation General Public License,
* Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://covariant.cn/licenses/LICENSE-1.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2019 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,2,1,1
#define COVSCRIPT_VERSION_STR "3.2.1 Psephurus gladius(Unstable) Build 1"
#define COVSCRIPT_STD_VERSION 190501
#define COVSCRIPT_API_VERSION 190525
#define COVSCRIPT_ABI_VERSION 190510
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Utility functions for curand
*/
#pragma once
#include "curand.h"
namespace etl {
namespace impl {
namespace curand {
#define curand_call(call) \
{ \
auto status = call; \
if (status != CURAND_STATUS_SUCCESS) { \
std::cerr << "CURAND error: " << status << " from " << #call << std::endl \
<< "from " << __FILE__ << ":" << __LINE__ << std::endl; \
} \
}
void generate_normal(curandGenerator_t generator, float* gpu_memory, size_t n, float mean, float stddev){
curand_call(curandGenerateNormal(generator, gpu_memory, n, mean, stddev));
}
void generate_normal(curandGenerator_t generator, double* gpu_memory, size_t n, double mean, double stddev){
curand_call(curandGenerateNormalDouble(generator, gpu_memory, n, mean, stddev));
}
void generate_uniform(curandGenerator_t generator, float* gpu_memory, size_t n){
curand_call(curandGenerateUniform(generator, gpu_memory, n));
}
void generate_uniform(curandGenerator_t generator, double* gpu_memory, size_t n){
curand_call(curandGenerateUniformDouble(generator, gpu_memory, n));
}
} //end of namespace curand
} //end of namespace impl
} //end of namespace etl
<commit_msg>Fix CURAND handling of odd sequences<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Utility functions for curand
*/
#pragma once
#include "curand.h"
namespace etl {
namespace impl {
namespace curand {
#define curand_call(call) \
{ \
auto status = call; \
if (status != CURAND_STATUS_SUCCESS) { \
std::cerr << "CURAND error: " << status << " from " << #call << std::endl \
<< "from " << __FILE__ << ":" << __LINE__ << std::endl; \
} \
}
void generate_normal(curandGenerator_t generator, float* gpu_memory, size_t n, float mean, float stddev){
// Note: CURAND is dumb, cannot generate odd sequences...
if(n % 2 == 0){
curand_call(curandGenerateNormal(generator, gpu_memory, n, mean, stddev));
} else {
// Generate the first n - 1 numbers
curand_call(curandGenerateNormal(generator, gpu_memory, n - 1, mean, stddev));
// Generate the last two numbers
curand_call(curandGenerateNormal(generator, gpu_memory + (n - 3), 2, mean, stddev));
}
}
void generate_normal(curandGenerator_t generator, double* gpu_memory, size_t n, double mean, double stddev){
// Note: CURAND is dumb, cannot generate odd sequences...
if(n % 2 == 0){
curand_call(curandGenerateNormalDouble(generator, gpu_memory, n, mean, stddev));
} else {
// Generate the first n - 1 numbers
curand_call(curandGenerateNormalDouble(generator, gpu_memory, n - 1, mean, stddev));
// Generate the last two numbers
curand_call(curandGenerateNormalDouble(generator, gpu_memory + (n - 3), 2, mean, stddev));
}
}
void generate_uniform(curandGenerator_t generator, float* gpu_memory, size_t n){
curand_call(curandGenerateUniform(generator, gpu_memory, n));
}
void generate_uniform(curandGenerator_t generator, double* gpu_memory, size_t n){
curand_call(curandGenerateUniformDouble(generator, gpu_memory, n));
}
} //end of namespace curand
} //end of namespace impl
} //end of namespace etl
<|endoftext|>
|
<commit_before>#ifndef GCN_ACTIONLISTENER_HPP
#define GCN_ACTIONLISTENER_HPP
#include <string>
namespace gcn
{
/**
* A ActionListener listens for action events from a widget.
*
* @see Widget::addActionListener
*/
class ActionListener
{
public:
/**
* Destructor.
*/
virtual ~ActionListener() { }
/**
* This function is called upon an action recieved from a widget.
*
* @param eventId the identifier of the widget.
*/
virtual void action(const std::string& eventId) = 0;
}; // end ActionListener
} // end gcn
#endif // end GCN_ACTIONLISTENER_HPP
<commit_msg>Fixed a typo<commit_after>#ifndef GCN_ACTIONLISTENER_HPP
#define GCN_ACTIONLISTENER_HPP
#include <string>
namespace gcn
{
/**
* An ActionListener listens for action events from a widget.
*
* @see Widget::addActionListener
*/
class ActionListener
{
public:
/**
* Destructor.
*/
virtual ~ActionListener() { }
/**
* This function is called upon an action recieved from a widget.
*
* @param eventId the identifier of the widget.
*/
virtual void action(const std::string& eventId) = 0;
}; // end ActionListener
} // end gcn
#endif // end GCN_ACTIONLISTENER_HPP
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/core/state_matrix.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2017, Yan Zhou
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_CORE_STATE_MATRIX_HPP
#define MCKL_CORE_STATE_MATRIX_HPP
#include <mckl/internal/common.hpp>
#include <mckl/core/matrix.hpp>
#include <mckl/core/particle.hpp>
namespace mckl
{
/// \brief Particle::state_type subtype
/// \ingroup Core
template <MatrixLayout Layout, std::size_t Dim, typename T>
class StateMatrix : public Matrix<Layout, T>
{
using layout_dispatch = std::integral_constant<MatrixLayout, Layout>;
using row_major = std::integral_constant<MatrixLayout, RowMajor>;
using col_major = std::integral_constant<MatrixLayout, ColMajor>;
public:
using size_type = typename Matrix<Layout, T>::size_type;
using value_type = typename Matrix<Layout, T>::value_type;
template <typename S>
class particle_index_type : public ParticleIndexBase<S>
{
public:
particle_index_type() = default;
particle_index_type(
typename Particle<S>::size_type i, Particle<S> *pptr)
: ParticleIndexBase<S>(i, pptr)
{
}
/// \brief `this->particle().state().dim()`
std::size_t dim() const { return this->particle().state().dim(); }
/// \brief `this->particle().state().row_stride()`
size_type stride() const
{
return this->particle().state().row_stride();
}
/// \brief `this->particle().state().row_data(this->i())`
value_type *data() const
{
return this->particle().state().row_data(this->i());
}
/// \brief `this->particle().state()(this->i(), j)`
value_type &operator[](size_type j) const
{
return this->particle().state()(
static_cast<size_type>(this->i()), j);
}
/// \brief `this->particle().state()(this->i(), j)`
value_type &operator()(size_type j) const { return operator[](j); }
/// \brief `this->particle().state().at(this->i(), j)`
value_type &at(size_type j) const
{
runtime_assert(
j < dim(), "**StateMatrix::at** index out of range");
return operator[](j);
}
}; // class particle_index_type
explicit StateMatrix(size_type N) : Matrix<Layout, T>(N, Dim) {}
StateMatrix(size_type N, size_type dim) : Matrix<Layout, T>(N, dim)
{
static_assert(Dim == 0,
"**StateMatrix::StateMatrix** used with an object with fixed "
"dimension");
}
/// \brief The numbrer of samples
size_type size() const { return this->nrow(); }
/// \brief The dimension
size_type dim() const { return this->ncol(); }
using Matrix<Layout, T>::reserve;
/// \brief Reserve space for specified sample size
void reserve(size_type N) { this->reserve_nrow(N); }
using Matrix<Layout, T>::resize;
/// \brief Change the sample size
void resize(size_type N) { this->resize(N, dim()); }
/// \brief Select samples
///
/// \param N The new sample size
/// \param index N-vector of parent index
///
/// \details
/// Let \f$a_i\f$ denote the value of `index[i]`, and
/// \f$r_i = \sum_{j=1}^N \mathbb{I}_{\{i\}}(a_j)\f$. Then it is required
/// that \f$a_i = i\f$ for all \f$r_i > 0\f$.
template <typename IntType, typename InputIter>
void select(IntType N, InputIter index)
{
select_dispatch(N, index, layout_dispatch());
}
/// \brief Duplicate a sample
///
/// \param src The index of sample to be duplicated
/// \param dst The index of sample to be eliminated
void duplicate(size_type src, size_type dst)
{
if (src == dst)
return;
duplicate_dispatch(src, dst, layout_dispatch(),
std::integral_constant<bool, (Dim == 0 || 8 < Dim)>());
}
private:
template <typename IntType, typename InputIter>
void select_dispatch(IntType N, InputIter index, row_major)
{
size_type n = static_cast<size_type>(N);
if (size() == 0 || internal::is_nullptr(index)) {
resize(n);
return;
}
if (n > size())
resize(n);
for (size_type dst = 0; dst != n; ++dst, ++index)
duplicate(static_cast<size_type>(*index), dst);
if (n < size())
resize(n);
return;
}
template <typename IntType, typename InputIter>
void select_dispatch(IntType N, InputIter index, col_major)
{
size_type n = static_cast<size_type>(N);
if (size() == 0 || internal::is_nullptr(index)) {
resize(n);
return;
}
InputIter idx = index;
if (n == size()) {
for (size_type j = 0; j != dim(); ++j) {
idx = index;
const value_type *src = this->col_data(j);
value_type *dst = this->col_data(j);
for (size_type i = 0; i != n; ++i, ++idx)
dst[i] = src[*idx];
}
} else {
Matrix<ColMajor, T> tmp(N, dim());
for (size_type j = 0; j != dim(); ++j) {
idx = index;
const value_type *src = this->col_data(j);
value_type *dst = tmp.col_data(j);
for (size_type i = 0; i != n; ++i, ++idx)
dst[i] = src[*idx];
}
Matrix<ColMajor, T>::operator=(std::move(tmp));
}
return;
}
void duplicate_dispatch(
size_type src, size_type dst, row_major, std::true_type)
{
std::copy_n(this->row_data(src), dim(), this->row_data(dst));
}
void duplicate_dispatch(
size_type src, size_type dst, row_major, std::false_type)
{
duplicate_j<0>(this->row_data(src), this->row_data(dst), row_major(),
std::integral_constant<bool, 0 < Dim>());
}
template <std::size_t>
void duplicate_j(
const value_type *, value_type *, row_major, std::false_type)
{
}
template <std::size_t D>
void duplicate_j(
const value_type *src, value_type *dst, row_major, std::true_type)
{
dst[D] = src[D];
duplicate_j<D + 1>(src, dst, row_major(),
std::integral_constant<bool, D + 1 < Dim>());
}
void duplicate_dispatch(
size_type src, size_type dst, col_major, std::true_type)
{
for (size_type d = 0; d != dim(); ++d)
this->operator()(dst, d) = this->operator()(src, d);
}
void duplicate_dispatch(
size_type src, size_type dst, col_major, std::false_type)
{
duplicate_j<0>(this->row_data(src), this->col_data(dst), col_major(),
std::integral_constant<bool, 0 < Dim>());
}
template <std::size_t>
void duplicate_j(
const value_type *, value_type *, col_major, std::false_type)
{
}
template <std::size_t D>
void duplicate_j(
const value_type *src, value_type *dst, col_major, std::true_type)
{
dst[D * size()] = src[D * size()];
duplicate_j<D + 1>(
src, dst, std::integral_constant<bool, D + 1 < Dim>());
}
}; // class StateMatrix
} // namespace mckl
#endif // MCKL_CORE_STATE_MATRIX_HPP
<commit_msg>remove conflicting operator[]<commit_after>//============================================================================
// MCKL/include/mckl/core/state_matrix.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2017, Yan Zhou
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_CORE_STATE_MATRIX_HPP
#define MCKL_CORE_STATE_MATRIX_HPP
#include <mckl/internal/common.hpp>
#include <mckl/core/matrix.hpp>
#include <mckl/core/particle.hpp>
namespace mckl
{
/// \brief Particle::state_type subtype
/// \ingroup Core
template <MatrixLayout Layout, std::size_t Dim, typename T>
class StateMatrix : public Matrix<Layout, T>
{
using layout_dispatch = std::integral_constant<MatrixLayout, Layout>;
using row_major = std::integral_constant<MatrixLayout, RowMajor>;
using col_major = std::integral_constant<MatrixLayout, ColMajor>;
public:
using size_type = typename Matrix<Layout, T>::size_type;
using value_type = typename Matrix<Layout, T>::value_type;
template <typename S>
class particle_index_type : public ParticleIndexBase<S>
{
public:
particle_index_type() = default;
particle_index_type(
typename Particle<S>::size_type i, Particle<S> *pptr)
: ParticleIndexBase<S>(i, pptr)
{
}
/// \brief `this->particle().state().dim()`
std::size_t dim() const { return this->particle().state().dim(); }
/// \brief `this->particle().state().row_stride()`
size_type stride() const
{
return this->particle().state().row_stride();
}
/// \brief `this->particle().state().row_data(this->i())`
value_type *data() const
{
return this->particle().state().row_data(this->i());
}
/// \brief `this->particle().state()(this->i(), j)`
value_type &operator()(size_type j) const
{
return this->particle().state()(this->i(), j);
}
/// \brief `this->particle().state().at(this->i(), j)`
value_type &at(size_type j) const
{
runtime_assert(
j < dim(), "**StateMatrix::at** index out of range");
return operator()(j);
}
}; // class particle_index_type
explicit StateMatrix(size_type N) : Matrix<Layout, T>(N, Dim) {}
StateMatrix(size_type N, size_type dim) : Matrix<Layout, T>(N, dim)
{
static_assert(Dim == 0,
"**StateMatrix::StateMatrix** used with an object with fixed "
"dimension");
}
/// \brief The numbrer of samples
size_type size() const { return this->nrow(); }
/// \brief The dimension
size_type dim() const { return this->ncol(); }
using Matrix<Layout, T>::reserve;
/// \brief Reserve space for specified sample size
void reserve(size_type N) { this->reserve_nrow(N); }
using Matrix<Layout, T>::resize;
/// \brief Change the sample size
void resize(size_type N) { this->resize(N, dim()); }
/// \brief Select samples
///
/// \param N The new sample size
/// \param index N-vector of parent index
///
/// \details
/// Let \f$a_i\f$ denote the value of `index[i]`, and
/// \f$r_i = \sum_{j=1}^N \mathbb{I}_{\{i\}}(a_j)\f$. Then it is required
/// that \f$a_i = i\f$ for all \f$r_i > 0\f$.
template <typename IntType, typename InputIter>
void select(IntType N, InputIter index)
{
select_dispatch(N, index, layout_dispatch());
}
/// \brief Duplicate a sample
///
/// \param src The index of sample to be duplicated
/// \param dst The index of sample to be eliminated
void duplicate(size_type src, size_type dst)
{
if (src == dst)
return;
duplicate_dispatch(src, dst, layout_dispatch(),
std::integral_constant<bool, (Dim == 0 || 8 < Dim)>());
}
private:
template <typename IntType, typename InputIter>
void select_dispatch(IntType N, InputIter index, row_major)
{
size_type n = static_cast<size_type>(N);
if (size() == 0 || internal::is_nullptr(index)) {
resize(n);
return;
}
if (n > size())
resize(n);
for (size_type dst = 0; dst != n; ++dst, ++index)
duplicate(static_cast<size_type>(*index), dst);
if (n < size())
resize(n);
return;
}
template <typename IntType, typename InputIter>
void select_dispatch(IntType N, InputIter index, col_major)
{
size_type n = static_cast<size_type>(N);
if (size() == 0 || internal::is_nullptr(index)) {
resize(n);
return;
}
InputIter idx = index;
if (n == size()) {
for (size_type j = 0; j != dim(); ++j) {
idx = index;
const value_type *src = this->col_data(j);
value_type *dst = this->col_data(j);
for (size_type i = 0; i != n; ++i, ++idx)
dst[i] = src[*idx];
}
} else {
Matrix<ColMajor, T> tmp(N, dim());
for (size_type j = 0; j != dim(); ++j) {
idx = index;
const value_type *src = this->col_data(j);
value_type *dst = tmp.col_data(j);
for (size_type i = 0; i != n; ++i, ++idx)
dst[i] = src[*idx];
}
Matrix<ColMajor, T>::operator=(std::move(tmp));
}
return;
}
void duplicate_dispatch(
size_type src, size_type dst, row_major, std::true_type)
{
std::copy_n(this->row_data(src), dim(), this->row_data(dst));
}
void duplicate_dispatch(
size_type src, size_type dst, row_major, std::false_type)
{
duplicate_j<0>(this->row_data(src), this->row_data(dst), row_major(),
std::integral_constant<bool, 0 < Dim>());
}
template <std::size_t>
void duplicate_j(
const value_type *, value_type *, row_major, std::false_type)
{
}
template <std::size_t D>
void duplicate_j(
const value_type *src, value_type *dst, row_major, std::true_type)
{
dst[D] = src[D];
duplicate_j<D + 1>(src, dst, row_major(),
std::integral_constant<bool, D + 1 < Dim>());
}
void duplicate_dispatch(
size_type src, size_type dst, col_major, std::true_type)
{
for (size_type d = 0; d != dim(); ++d)
this->operator()(dst, d) = this->operator()(src, d);
}
void duplicate_dispatch(
size_type src, size_type dst, col_major, std::false_type)
{
duplicate_j<0>(this->row_data(src), this->col_data(dst), col_major(),
std::integral_constant<bool, 0 < Dim>());
}
template <std::size_t>
void duplicate_j(
const value_type *, value_type *, col_major, std::false_type)
{
}
template <std::size_t D>
void duplicate_j(
const value_type *src, value_type *dst, col_major, std::true_type)
{
dst[D * size()] = src[D * size()];
duplicate_j<D + 1>(
src, dst, std::integral_constant<bool, D + 1 < Dim>());
}
}; // class StateMatrix
} // namespace mckl
#endif // MCKL_CORE_STATE_MATRIX_HPP
<|endoftext|>
|
<commit_before>#ifndef INC_METTLE_DRIVER_CMD_LINE_HPP
#define INC_METTLE_DRIVER_CMD_LINE_HPP
#include <chrono>
#include <cstdint>
#include <memory>
#include <vector>
#include <string>
#include <boost/any.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include "filters.hpp"
#include "object_factory.hpp"
#include "detail/export.hpp"
#include "detail/optional.hpp"
#include "log/core.hpp"
#include "log/indent.hpp"
#ifdef _WIN32
# include <wtypes.h>
#endif
namespace mettle {
struct generic_options {
bool show_help = false;
};
METTLE_PUBLIC boost::program_options::options_description
make_generic_options(generic_options &opts);
struct driver_options {
METTLE_OPTIONAL_NS::optional<std::chrono::milliseconds> timeout;
filter_set filters;
};
METTLE_PUBLIC boost::program_options::options_description
make_driver_options(driver_options &opts);
enum class color_option {
never,
automatic,
always
};
bool color_enabled(color_option opt, int fd = 1 /* STDOUT_FILENO */);
struct output_options {
std::string output;
color_option color = color_option::never;
std::size_t runs = 1;
bool show_terminal = false;
bool show_time = false;
};
using logger_factory = object_factory<
std::unique_ptr<log::file_logger>(indenting_ostream &, const output_options &)
>;
METTLE_PUBLIC logger_factory make_logger_factory();
METTLE_PUBLIC boost::program_options::options_description
make_output_options(output_options &opts, const logger_factory &factory);
METTLE_PUBLIC boost::program_options::option_description *
has_option(const boost::program_options::options_description &options,
const boost::program_options::variables_map &args);
template<typename Char>
std::vector<std::basic_string<Char>> filter_options(
const boost::program_options::basic_parsed_options<Char> &parsed,
const boost::program_options::options_description &desc
) {
std::vector<std::basic_string<Char>> filtered;
for(auto &&option : parsed.options) {
if(desc.find_nothrow(option.string_key, false)) {
auto &&tokens = option.original_tokens;
filtered.insert(filtered.end(), tokens.begin(), tokens.end());
}
}
return filtered;
}
METTLE_PUBLIC attr_filter parse_attr(const std::string &value);
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
color_option*, int);
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
attr_filter_set*, int);
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
name_filter_set*, int);
} // namespace mettle
// Put these in the boost namespace so that ADL picks them up (via the
// boost::any parameter).
namespace boost {
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
std::chrono::milliseconds*, int);
#ifdef _WIN32
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values, HANDLE*, int);
#endif
template<typename T>
void validate(boost::any &v, const std::vector<std::string> &values,
METTLE_OPTIONAL_NS::optional<T>*, int) {
using namespace boost::program_options;
using optional_t = METTLE_OPTIONAL_NS::optional<T>;
if(v.empty())
v = optional_t();
auto *val = boost::any_cast<optional_t>(&v);
assert(val);
boost::any a;
validate(a, values, static_cast<T*>(nullptr), 0);
*val = boost::any_cast<T>(a);
}
} // namespace boost
#endif
<commit_msg>Fix cmd line exports for Windows<commit_after>#ifndef INC_METTLE_DRIVER_CMD_LINE_HPP
#define INC_METTLE_DRIVER_CMD_LINE_HPP
#include <chrono>
#include <cstdint>
#include <memory>
#include <vector>
#include <string>
#include <boost/any.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include "filters.hpp"
#include "object_factory.hpp"
#include "detail/export.hpp"
#include "detail/optional.hpp"
#include "log/core.hpp"
#include "log/indent.hpp"
#ifdef _WIN32
# include <wtypes.h>
#endif
namespace mettle {
struct generic_options {
bool show_help = false;
};
METTLE_PUBLIC boost::program_options::options_description
make_generic_options(generic_options &opts);
struct driver_options {
METTLE_OPTIONAL_NS::optional<std::chrono::milliseconds> timeout;
filter_set filters;
};
METTLE_PUBLIC boost::program_options::options_description
make_driver_options(driver_options &opts);
enum class color_option {
never,
automatic,
always
};
METTLE_PUBLIC bool
color_enabled(color_option opt, int fd = 1 /* STDOUT_FILENO */);
struct output_options {
std::string output;
color_option color = color_option::never;
std::size_t runs = 1;
bool show_terminal = false;
bool show_time = false;
};
using logger_factory = object_factory<
std::unique_ptr<log::file_logger>(indenting_ostream &, const output_options &)
>;
METTLE_PUBLIC logger_factory make_logger_factory();
METTLE_PUBLIC boost::program_options::options_description
make_output_options(output_options &opts, const logger_factory &factory);
METTLE_PUBLIC boost::program_options::option_description *
has_option(const boost::program_options::options_description &options,
const boost::program_options::variables_map &args);
template<typename Char>
std::vector<std::basic_string<Char>> filter_options(
const boost::program_options::basic_parsed_options<Char> &parsed,
const boost::program_options::options_description &desc
) {
std::vector<std::basic_string<Char>> filtered;
for(auto &&option : parsed.options) {
if(desc.find_nothrow(option.string_key, false)) {
auto &&tokens = option.original_tokens;
filtered.insert(filtered.end(), tokens.begin(), tokens.end());
}
}
return filtered;
}
METTLE_PUBLIC attr_filter parse_attr(const std::string &value);
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
color_option*, int);
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
attr_filter_set*, int);
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
name_filter_set*, int);
} // namespace mettle
// Put these in the boost namespace so that ADL picks them up (via the
// boost::any parameter).
namespace boost {
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values,
std::chrono::milliseconds*, int);
#ifdef _WIN32
METTLE_PUBLIC void
validate(boost::any &v, const std::vector<std::string> &values, HANDLE*, int);
#endif
template<typename T>
void validate(boost::any &v, const std::vector<std::string> &values,
METTLE_OPTIONAL_NS::optional<T>*, int) {
using namespace boost::program_options;
using optional_t = METTLE_OPTIONAL_NS::optional<T>;
if(v.empty())
v = optional_t();
auto *val = boost::any_cast<optional_t>(&v);
assert(val);
boost::any a;
validate(a, values, static_cast<T*>(nullptr), 0);
*val = boost::any_cast<T>(a);
}
} // namespace boost
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include "string_util.hpp"
class InvalidCdImageException : public Oddlib::Exception
{
public:
explicit InvalidCdImageException(const char* msg)
: Exception(msg)
{
}
};
const Uint32 kRawSectorSize = 2352;
const Uint32 kFileSystemStartSector = 16;
class RawCdImage
{
public:
RawCdImage(const RawCdImage&) = delete;
RawCdImage& operator = (const RawCdImage&) = delete;
RawCdImage(Oddlib::Stream& stream)
: mStream(stream)
{
ReadFileSystem();
}
void LogTree()
{
mRoot.Log(1);
}
bool FileExists(std::string fileName)
{
return DoFind(fileName) != nullptr;
}
std::unique_ptr<Oddlib::IStream> ReadFile(std::string fileName)
{
DrWrapper* record = DoFind(fileName);
if (!record)
{
throw Oddlib::Exception("File not found on CD-ROM");
}
return std::make_unique<Stream>(record->mDr, record->mName, mStream);
}
public:
struct DrWrapper;
DrWrapper* DoFind(std::string fileName)
{
if (fileName.empty())
{
return false;
}
if (fileName[0] != '\\')
{
fileName = "\\" + fileName;
}
auto parts = string_util::split(fileName, '\\');
return mRoot.Find(parts);
}
// Each sector is 2352 bytes
#pragma pack(push)
#pragma pack(1)
struct RawSectorHeader
{
Uint8 mSync[12]; // Sync bytes of 0xFF
Uint8 mMin;
Uint8 mSecond;
Uint8 mFrame; // aka sector number
Uint8 mMode;
Uint8 mData[2336];
};
struct both_endian_32
{
Uint32 little;
Uint32 big;
};
struct both_endian_16
{
Uint16 little;
Uint16 big;
};
struct date_time
{
Uint8 year[4];
Uint8 month[2];
Uint8 day[2];
Uint8 hour[2];
Uint8 minute[2];
Uint8 second[2];
Uint8 mil[2];
Uint8 gmt;
};
struct volume_descriptor
{
Uint8 mType;
Uint8 mMagic[5];
Uint8 mVersion;
Uint8 mUnused;
Uint8 mSys_id[32];
Uint8 mVol_id[32];
Uint8 mUnused2[8];
both_endian_32 vol_size;
Uint8 mUnused3[32];
both_endian_16 vol_count;
both_endian_16 vol_index;
both_endian_16 logical_block_size;
both_endian_32 path_table_size;
Uint32 path_table_location_LSB;
Uint32 path_table_optional_location_LSB;
Uint32 path_table_location_MSB;
Uint32 path_table_optional_location_MSB;
Uint8 root_entry[34];
Uint8 vol_set_id[128];
Uint8 publisher_id[128];
Uint8 data_preparer_id[128];
Uint8 app_id[128];
Uint8 copyright_file[38];
Uint8 abstract_file[36];
Uint8 biblio_file[37];
date_time vol_creation;
date_time vol_modif;
date_time vol_expiration;
date_time vol_effective;
Uint8 file_structure_version;
Uint8 unused4;
Uint8 extra_data[512];
Uint8 reserved[653];
};
struct path_entry
{
Uint8 name_length;
Uint8 extended_length;
Uint32 location;
Uint16 parent;
};
struct directory_record
{
Uint8 length;
Uint8 extended_length;
both_endian_32 location;
both_endian_32 data_length;
Uint8 date[7]; //irregular
Uint8 flags;
Uint8 unit_size;
Uint8 gap_size;
both_endian_16 sequence_number;
Uint8 length_file_id; //files end with ;1
//file id
//padding
//system use
};
public:
struct CDXASector
{
//uint8_t sync[12];
// uint8_t header[4];
struct CDXASubHeader
{
uint8_t file_number;
uint8_t channel;
uint8_t submode;
uint8_t coding_info;
uint8_t file_number_copy;
uint8_t channel_number_copy;
uint8_t submode_copy;
uint8_t coding_info_copy;
} subheader;
uint8_t data[2328];
};
#pragma pack(pop)
private:
class Sector
{
public:
Sector(unsigned int sectorNumber, Oddlib::IStream& stream)
{
const auto pos = kRawSectorSize*sectorNumber;
stream.Seek(pos);
stream.ReadBytes(reinterpret_cast<Uint8*>(&mData), kRawSectorSize);
RawSectorHeader* rawHeader = reinterpret_cast<RawSectorHeader*>(&mData);
if (rawHeader->mMode != 2)
{
throw InvalidCdImageException(("Only mode 2 sectors supported got (" + std::to_string(rawHeader->mMode) + ")").c_str());
}
// To tell the different Mode 2s apart you have to examine bytes 16 - 23 of the sector
// (the first 8 bytes of Mode Data).If bytes 16 - 19 are not the same as 20 - 23,
// then it is Mode 2. If they are equal and bit 5 is on(0x20), then it is Mode 2 Form 2.
// Otherwise it is Mode 2 Form 1.
CDXASector* xaHeader = reinterpret_cast<CDXASector*>(&mData);
if (xaHeader->subheader.file_number == xaHeader->subheader.file_number_copy &&
xaHeader->subheader.channel == xaHeader->subheader.channel_number_copy &&
xaHeader->subheader.submode == xaHeader->subheader.submode_copy &&
xaHeader->subheader.coding_info == xaHeader->subheader.coding_info_copy &&
xaHeader->subheader.submode & 0x20
)
{
// Mode 2 Form 2
mMode2Form1 = false;
}
else
{
// Mode 2 Form 1
mMode2Form1 = true;
}
}
Uint8* DataPtr()
{
if (mMode2Form1)
{
return &mData.mData[8];
}
else
{
return &mData.mData[0];
}
}
Uint8* RawPtr()
{
return reinterpret_cast<Uint8*>(&mData);
}
Uint32 DataLength()
{
return mMode2Form1 ? 2048 : 2336;
}
private:
RawSectorHeader mData;
bool mMode2Form1 = false;
};
const char* NamePointer(directory_record* dr)
{
return ((const char*)&dr->length_file_id) + 1;
}
bool IsDots(directory_record* dr)
{
return (dr->length_file_id == 1 && (NamePointer(dr)[0] == 0x0 || NamePointer(dr)[0] == 0x1));
}
std::vector<Uint8> ReadFile(directory_record* dr)
{
int dataSize = dr->data_length.little;
auto dataSector = dr->location.little;
std::vector<Uint8> data;
data.reserve(dataSize);
do
{
auto sizeToRead = dataSize;
Sector sector(dataSector++, mStream);
//if (sizeToRead > sector.DataLength())
{
sizeToRead = sector.DataLength();
dataSize -= sector.DataLength();
}
const Uint8* ptr = sector.RawPtr();
for (size_t i = 0; i < kRawSectorSize; i++)
{
data.emplace_back(*ptr);
ptr++;
}
} while (dataSize > 0);
return data;
}
class Stream : public Oddlib::IStream
{
public:
Stream(const Stream&) = delete;
Stream& operator = (const Stream&) = delete;
Stream(directory_record& dr, std::string name, Oddlib::IStream& stream)
: mDr(dr), mName(name), mStream(stream)
{
mSector = mDr.location.little;
}
virtual void ReadUInt8(Uint8& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Uint8));
}
virtual void ReadUInt32(Uint32& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Uint32));
}
virtual void ReadUInt16(Uint16& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Uint16));
}
virtual void ReadSInt16(Sint16& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Sint16));
}
virtual void ReadBytes(Sint8* pDest, size_t destSize) override
{
ReadBytes(reinterpret_cast<Uint8*>(pDest), destSize);
}
virtual void ReadBytes(Uint8* pDest, size_t destSize) override
{
mStream.Seek(mSector * kRawSectorSize);
mSector++;
mStream.Seek(mStream.Pos() + 14+2);
mStream.ReadBytes(pDest, destSize);
Sector s(mDr.location.little, mStream);
}
virtual void Seek(size_t pos) override
{
throw std::runtime_error("Seek() not implemented");
}
virtual size_t Pos() const override
{
throw std::runtime_error("Pos() not implemented");
}
virtual size_t Size() const override
{
return mDr.data_length.little;
}
virtual bool AtEnd() const override
{
return false;
}
virtual const std::string& Name() const override
{
return mName;
}
private:
unsigned int mSector = 0;
directory_record mDr;
std::string mName;
Oddlib::IStream& mStream;
};
struct Directory;
void ReadDirectory(directory_record* rec, Directory* d)
{
const auto dataSize = rec->data_length.little;
auto sector = rec->location.little;
size_t totalDataRead = 0;
while (totalDataRead != dataSize)
{
Sector sector(sector++, mStream);
totalDataRead += sector.DataLength();
directory_record* dr = (directory_record*)sector.DataPtr();
while (dr->length)
{
if (!IsDots(dr))
{
std::string name(NamePointer(dr), dr->length_file_id);
//std::cout << name.c_str() << std::endl;
if ((dr->flags & 2) && dr->location.little != rec->location.little)
{
auto dir = std::make_unique<Directory>();
dir->mDir.mDr = *dr;
dir->mDir.mName = name;
d->mChildren.push_back(std::move(dir));
ReadDirectory(dr, d->mChildren.back().get());
}
else
{
if (string_util::ends_with(name, ";1"))
{
name = name.substr(0, name.length() - 2);
}
d->mFiles.emplace_back(DrWrapper{ *dr, name });
// ReadFile(dr);
}
}
char* ptr = reinterpret_cast<char*>(dr);
dr = reinterpret_cast<directory_record*>(ptr + dr->length);
}
}
}
void ReadFileSystem()
{
volume_descriptor* volDesc = nullptr;
auto secNum = kFileSystemStartSector - 1;
do
{
secNum++;
Sector sector(secNum, mStream);
volDesc = (volume_descriptor*)sector.DataPtr();
if (volDesc->mType == 1)
{
directory_record* dr = (directory_record*)&volDesc->root_entry[0];
mRoot.mDir = DrWrapper{ *dr, "" };
ReadDirectory(dr, &mRoot);
break;
}
} while (volDesc->mType != 1);
}
Oddlib::Stream& mStream;
public:
struct DrWrapper
{
directory_record mDr;
std::string mName;
};
private:
struct Directory
{
DrWrapper mDir;
std::vector<DrWrapper> mFiles;
std::vector<std::unique_ptr<Directory>> mChildren;
void Log(int level)
{
{
std::string indent(level, '-');
std::cout << indent.c_str() << "[dir] " << mDir.mName.c_str() << std::endl;
}
{
std::string indent(level + 1, '-');
for (auto& file : mFiles)
{
std::cout << indent.c_str() << "[file] " << file.mName.c_str() << std::endl;
}
}
for (auto& child : mChildren)
{
child->Log(level + 1);
}
}
DrWrapper* Find(std::deque<std::string>& parts)
{
if (parts.empty())
{
return nullptr;
}
auto find = parts.front();
if (mDir.mName == find)
{
parts.pop_front();
if (parts.size() > 1)
{
for (auto& child : mChildren)
{
auto ret = child->Find(parts);
if (ret)
{
return ret;
}
}
return nullptr;
}
else
{
find = parts.front();
for (auto& file : mFiles)
{
if (file.mName == find)
{
return &file;
}
}
return nullptr;
}
}
else
{
// Dir name not matching
return nullptr;
}
}
};
Directory mRoot;
};
<commit_msg>fix gcc/clang compile error<commit_after>#pragma once
#include <string>
#include "string_util.hpp"
class InvalidCdImageException : public Oddlib::Exception
{
public:
explicit InvalidCdImageException(const char* msg)
: Exception(msg)
{
}
};
const Uint32 kRawSectorSize = 2352;
const Uint32 kFileSystemStartSector = 16;
class RawCdImage
{
public:
RawCdImage(const RawCdImage&) = delete;
RawCdImage& operator = (const RawCdImage&) = delete;
RawCdImage(Oddlib::Stream& stream)
: mStream(stream)
{
ReadFileSystem();
}
void LogTree()
{
mRoot.Log(1);
}
bool FileExists(std::string fileName)
{
return DoFind(fileName) != nullptr;
}
std::unique_ptr<Oddlib::IStream> ReadFile(std::string fileName)
{
DrWrapper* record = DoFind(fileName);
if (!record)
{
throw Oddlib::Exception("File not found on CD-ROM");
}
return std::make_unique<Stream>(record->mDr, record->mName, mStream);
}
public:
struct DrWrapper;
DrWrapper* DoFind(std::string fileName)
{
if (fileName.empty())
{
return false;
}
if (fileName[0] != '\\')
{
fileName = "\\" + fileName;
}
auto parts = string_util::split(fileName, '\\');
return mRoot.Find(parts);
}
// Each sector is 2352 bytes
#pragma pack(push)
#pragma pack(1)
struct RawSectorHeader
{
Uint8 mSync[12]; // Sync bytes of 0xFF
Uint8 mMin;
Uint8 mSecond;
Uint8 mFrame; // aka sector number
Uint8 mMode;
Uint8 mData[2336];
};
struct both_endian_32
{
Uint32 little;
Uint32 big;
};
struct both_endian_16
{
Uint16 little;
Uint16 big;
};
struct date_time
{
Uint8 year[4];
Uint8 month[2];
Uint8 day[2];
Uint8 hour[2];
Uint8 minute[2];
Uint8 second[2];
Uint8 mil[2];
Uint8 gmt;
};
struct volume_descriptor
{
Uint8 mType;
Uint8 mMagic[5];
Uint8 mVersion;
Uint8 mUnused;
Uint8 mSys_id[32];
Uint8 mVol_id[32];
Uint8 mUnused2[8];
both_endian_32 vol_size;
Uint8 mUnused3[32];
both_endian_16 vol_count;
both_endian_16 vol_index;
both_endian_16 logical_block_size;
both_endian_32 path_table_size;
Uint32 path_table_location_LSB;
Uint32 path_table_optional_location_LSB;
Uint32 path_table_location_MSB;
Uint32 path_table_optional_location_MSB;
Uint8 root_entry[34];
Uint8 vol_set_id[128];
Uint8 publisher_id[128];
Uint8 data_preparer_id[128];
Uint8 app_id[128];
Uint8 copyright_file[38];
Uint8 abstract_file[36];
Uint8 biblio_file[37];
date_time vol_creation;
date_time vol_modif;
date_time vol_expiration;
date_time vol_effective;
Uint8 file_structure_version;
Uint8 unused4;
Uint8 extra_data[512];
Uint8 reserved[653];
};
struct path_entry
{
Uint8 name_length;
Uint8 extended_length;
Uint32 location;
Uint16 parent;
};
struct directory_record
{
Uint8 length;
Uint8 extended_length;
both_endian_32 location;
both_endian_32 data_length;
Uint8 date[7]; //irregular
Uint8 flags;
Uint8 unit_size;
Uint8 gap_size;
both_endian_16 sequence_number;
Uint8 length_file_id; //files end with ;1
//file id
//padding
//system use
};
public:
struct CDXASector
{
//uint8_t sync[12];
// uint8_t header[4];
struct CDXASubHeader
{
uint8_t file_number;
uint8_t channel;
uint8_t submode;
uint8_t coding_info;
uint8_t file_number_copy;
uint8_t channel_number_copy;
uint8_t submode_copy;
uint8_t coding_info_copy;
} subheader;
uint8_t data[2328];
};
#pragma pack(pop)
private:
class Sector
{
public:
Sector(unsigned int sectorNumber, Oddlib::IStream& stream)
{
const auto pos = kRawSectorSize*sectorNumber;
stream.Seek(pos);
stream.ReadBytes(reinterpret_cast<Uint8*>(&mData), kRawSectorSize);
RawSectorHeader* rawHeader = reinterpret_cast<RawSectorHeader*>(&mData);
if (rawHeader->mMode != 2)
{
throw InvalidCdImageException(("Only mode 2 sectors supported got (" + std::to_string(rawHeader->mMode) + ")").c_str());
}
// To tell the different Mode 2s apart you have to examine bytes 16 - 23 of the sector
// (the first 8 bytes of Mode Data).If bytes 16 - 19 are not the same as 20 - 23,
// then it is Mode 2. If they are equal and bit 5 is on(0x20), then it is Mode 2 Form 2.
// Otherwise it is Mode 2 Form 1.
CDXASector* xaHeader = reinterpret_cast<CDXASector*>(&mData);
if (xaHeader->subheader.file_number == xaHeader->subheader.file_number_copy &&
xaHeader->subheader.channel == xaHeader->subheader.channel_number_copy &&
xaHeader->subheader.submode == xaHeader->subheader.submode_copy &&
xaHeader->subheader.coding_info == xaHeader->subheader.coding_info_copy &&
xaHeader->subheader.submode & 0x20
)
{
// Mode 2 Form 2
mMode2Form1 = false;
}
else
{
// Mode 2 Form 1
mMode2Form1 = true;
}
}
Uint8* DataPtr()
{
if (mMode2Form1)
{
return &mData.mData[8];
}
else
{
return &mData.mData[0];
}
}
Uint8* RawPtr()
{
return reinterpret_cast<Uint8*>(&mData);
}
Uint32 DataLength()
{
return mMode2Form1 ? 2048 : 2336;
}
private:
RawSectorHeader mData;
bool mMode2Form1 = false;
};
const char* NamePointer(directory_record* dr)
{
return ((const char*)&dr->length_file_id) + 1;
}
bool IsDots(directory_record* dr)
{
return (dr->length_file_id == 1 && (NamePointer(dr)[0] == 0x0 || NamePointer(dr)[0] == 0x1));
}
std::vector<Uint8> ReadFile(directory_record* dr)
{
int dataSize = dr->data_length.little;
auto dataSector = dr->location.little;
std::vector<Uint8> data;
data.reserve(dataSize);
do
{
auto sizeToRead = dataSize;
Sector sector(dataSector++, mStream);
//if (sizeToRead > sector.DataLength())
{
sizeToRead = sector.DataLength();
dataSize -= sector.DataLength();
}
const Uint8* ptr = sector.RawPtr();
for (size_t i = 0; i < kRawSectorSize; i++)
{
data.emplace_back(*ptr);
ptr++;
}
} while (dataSize > 0);
return data;
}
class Stream : public Oddlib::IStream
{
public:
Stream(const Stream&) = delete;
Stream& operator = (const Stream&) = delete;
Stream(directory_record& dr, std::string name, Oddlib::IStream& stream)
: mDr(dr), mName(name), mStream(stream)
{
mSector = mDr.location.little;
}
virtual void ReadUInt8(Uint8& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Uint8));
}
virtual void ReadUInt32(Uint32& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Uint32));
}
virtual void ReadUInt16(Uint16& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Uint16));
}
virtual void ReadSInt16(Sint16& output) override
{
ReadBytes(reinterpret_cast<Uint8*>(&output), sizeof(Sint16));
}
virtual void ReadBytes(Sint8* pDest, size_t destSize) override
{
ReadBytes(reinterpret_cast<Uint8*>(pDest), destSize);
}
virtual void ReadBytes(Uint8* pDest, size_t destSize) override
{
mStream.Seek(mSector * kRawSectorSize);
mSector++;
mStream.Seek(mStream.Pos() + 14+2);
mStream.ReadBytes(pDest, destSize);
Sector s(mDr.location.little, mStream);
}
virtual void Seek(size_t pos) override
{
throw std::runtime_error("Seek() not implemented");
}
virtual size_t Pos() const override
{
throw std::runtime_error("Pos() not implemented");
}
virtual size_t Size() const override
{
return mDr.data_length.little;
}
virtual bool AtEnd() const override
{
return false;
}
virtual const std::string& Name() const override
{
return mName;
}
private:
unsigned int mSector = 0;
directory_record mDr;
std::string mName;
Oddlib::IStream& mStream;
};
struct Directory;
void ReadDirectory(directory_record* rec, Directory* d)
{
const auto dataSize = rec->data_length.little;
auto sectorNum = rec->location.little;
size_t totalDataRead = 0;
while (totalDataRead != dataSize)
{
Sector sector(sectorNum++, mStream);
totalDataRead += sector.DataLength();
directory_record* dr = (directory_record*)sector.DataPtr();
while (dr->length)
{
if (!IsDots(dr))
{
std::string name(NamePointer(dr), dr->length_file_id);
//std::cout << name.c_str() << std::endl;
if ((dr->flags & 2) && dr->location.little != rec->location.little)
{
auto dir = std::make_unique<Directory>();
dir->mDir.mDr = *dr;
dir->mDir.mName = name;
d->mChildren.push_back(std::move(dir));
ReadDirectory(dr, d->mChildren.back().get());
}
else
{
if (string_util::ends_with(name, ";1"))
{
name = name.substr(0, name.length() - 2);
}
d->mFiles.emplace_back(DrWrapper{ *dr, name });
// ReadFile(dr);
}
}
char* ptr = reinterpret_cast<char*>(dr);
dr = reinterpret_cast<directory_record*>(ptr + dr->length);
}
}
}
void ReadFileSystem()
{
volume_descriptor* volDesc = nullptr;
auto secNum = kFileSystemStartSector - 1;
do
{
secNum++;
Sector sector(secNum, mStream);
volDesc = (volume_descriptor*)sector.DataPtr();
if (volDesc->mType == 1)
{
directory_record* dr = (directory_record*)&volDesc->root_entry[0];
mRoot.mDir = DrWrapper{ *dr, "" };
ReadDirectory(dr, &mRoot);
break;
}
} while (volDesc->mType != 1);
}
Oddlib::Stream& mStream;
public:
struct DrWrapper
{
directory_record mDr;
std::string mName;
};
private:
struct Directory
{
DrWrapper mDir;
std::vector<DrWrapper> mFiles;
std::vector<std::unique_ptr<Directory>> mChildren;
void Log(int level)
{
{
std::string indent(level, '-');
std::cout << indent.c_str() << "[dir] " << mDir.mName.c_str() << std::endl;
}
{
std::string indent(level + 1, '-');
for (auto& file : mFiles)
{
std::cout << indent.c_str() << "[file] " << file.mName.c_str() << std::endl;
}
}
for (auto& child : mChildren)
{
child->Log(level + 1);
}
}
DrWrapper* Find(std::deque<std::string>& parts)
{
if (parts.empty())
{
return nullptr;
}
auto find = parts.front();
if (mDir.mName == find)
{
parts.pop_front();
if (parts.size() > 1)
{
for (auto& child : mChildren)
{
auto ret = child->Find(parts);
if (ret)
{
return ret;
}
}
return nullptr;
}
else
{
find = parts.front();
for (auto& file : mFiles)
{
if (file.mName == find)
{
return &file;
}
}
return nullptr;
}
}
else
{
// Dir name not matching
return nullptr;
}
}
};
Directory mRoot;
};
<|endoftext|>
|
<commit_before>/*
* algorithm.hpp
*
* Created on: 28 мая 2016 г.
* Author: sergey.fedorov
*/
/**
* @page Metaprogramming algorithms
*
*/
#ifndef PUSHKIN_META_ALGORITHM_HPP_
#define PUSHKIN_META_ALGORITHM_HPP_
#include <type_traits>
#include <limits>
#include <pushkin/meta/type_tuple.hpp>
namespace psst {
namespace meta {
/**
* Metafunction to determine if typename T is contained in type
* variadic pack Y ...
*/
template < typename T, typename ... Y >
struct contains;
template < typename T, typename V, typename ... Y >
struct contains< T, V, Y ... > : contains < T, Y ...> {};
template < typename T, typename ... Y >
struct contains< T, T, Y ... > : ::std::true_type {};
template < typename T >
struct contains< T, T > : ::std::true_type {};
template < typename T, typename Y >
struct contains< T, Y > : ::std::false_type {};
template < typename T >
struct contains<T> : ::std::false_type {};
template < typename T, typename ... Y >
struct contains< T, type_tuple<Y...> > : contains<T, Y...> {};
template < typename ... T >
struct is_empty : ::std::false_type {};
template <>
struct is_empty<> : ::std::true_type {};
template <>
struct is_empty<void> : ::std::true_type {};
template < typename ... T >
struct is_empty< type_tuple<T...> >
: ::std::conditional<
(sizeof ... (T) > 0),
::std::false_type,
::std::true_type
>::type {};
namespace detail {
template < typename T, ::std::size_t N, typename ... Y >
struct index_of_impl;
template < typename T, ::std::size_t N, typename V, typename ... Y >
struct index_of_impl< T, N, V, Y ... > : index_of_impl<T, N + 1, Y...> {};
template < typename T, ::std::size_t N, typename ... Y >
struct index_of_impl< T, N, T, Y ... > {
static constexpr ::std::size_t value = N;
static constexpr bool found = true;
};
template < typename T, ::std::size_t N >
struct index_of_impl< T, N, T > {
static constexpr ::std::size_t value = N;
static constexpr bool found = true;
};
template < typename T, ::std::size_t N, typename Y>
struct index_of_impl<T, N, Y> {
static constexpr ::std::size_t value = ::std::numeric_limits<::std::size_t>::max();
static constexpr bool found = false;
};
template < typename T, ::std::size_t N>
struct index_of_impl<T, N> {
static constexpr ::std::size_t value = ::std::numeric_limits<::std::size_t>::max();
static constexpr bool found = false;
};
} /* namespace detail */
template < typename T, typename ... Y >
struct index_of : detail::index_of_impl<T, 0, Y...> {};
template < typename T, typename ... Y >
struct index_of< T, type_tuple<Y...> > : detail::index_of_impl<T, 0, Y...> {};
template < typename ... T >
struct combine;
template <>
struct combine<> {
using type = type_tuple<>;
};
template < typename T >
struct combine < T > {
using type = type_tuple<T>;
};
template < typename ... T >
struct combine < type_tuple<T...> > {
using type = type_tuple<T...>;
};
template < typename ... T, typename U, typename ... Y >
struct combine< type_tuple<T...>, U, Y...>
: combine< type_tuple<T..., U>, Y...> {};
template < typename T, typename ... U, typename ... Y >
struct combine< T, type_tuple<U...>, Y... > :
combine<type_tuple<T, U...>, Y...>{};
template < typename ... T, typename ... U, typename ... Y >
struct combine< type_tuple<T...>, type_tuple<U...>, Y... > {
using type = typename combine< type_tuple<T..., U... >, Y...>::type;
};
template < typename T, typename ... Y >
struct push_back {
using type = type_tuple<Y..., T>;
};
template < typename T, typename ... Y >
struct push_back<type_tuple<Y...>, T > {
using type = type_tuple<Y..., T>;
};
template < typename T, typename ... Y >
struct push_front {
using type = type_tuple<T, Y...>;
};
template < typename T, typename ... Y >
struct push_front<type_tuple<Y...>, T > {
using type = type_tuple<T, Y...>;
};
template < typename T, typename ... Y>
struct remove_type;
template < typename T, typename V, typename ... Y >
struct remove_type<T, V, Y ...> {
using type = typename push_front<
typename remove_type<T, Y...>::type, V >::type;
};
template < typename T, typename ... Y >
struct remove_type<T, T, Y...> {
using type = typename remove_type<T, Y...>::type;
};
template < typename T >
struct remove_type <T> {
using type = type_tuple<>;
};
template < typename T, typename ... Y >
struct remove_type< type_tuple<Y...>, T > {
using type = typename remove_type<T, Y...>::type;
};
template < typename T, typename ... Y >
struct noop {
using type = type_tuple<Y...>;
};
template < typename T, typename ... Y >
struct insert_type : ::std::conditional<
contains<T, Y...>::value,
noop<T, Y...>,
typename ::std::conditional<
::std::is_same< T, void >::value,
noop<T, Y...>,
push_front<T, Y...>
>::type
>::type {};
template < typename T, typename ... Y >
struct insert_type< type_tuple<Y...>, T > {
using type = typename insert_type<T, Y...>::type;
};
template < typename ... T >
struct unique;
template < typename T, typename ... Y >
struct unique<T, Y...> {
using type = typename insert_type<
typename unique<Y...>::type, T>::type;
};
template <>
struct unique<> {
using type = type_tuple<>;
};
template < typename ... T >
struct unique< type_tuple<T...> > : unique<T...> {};
template < typename ... T, typename ... Y >
struct unique< type_tuple<T...>, type_tuple<Y...> >
: unique<T..., Y...> {};
template < typename ... T, typename ... Y >
struct unique< unique<T...>, unique<Y...> >
: unique<T..., Y...> {};
template < typename T, typename ... Y >
struct contains< T, unique<Y...> > : contains<T, Y...> {};
template < template <typename> class Predicate, typename ... T >
struct all_match;
template < template <typename> class Predicate, typename T, typename ... Y >
struct all_match< Predicate, T, Y... >
: ::std::conditional<
Predicate<T>::value,
all_match<Predicate, Y...>,
::std::false_type
>::type {};
template < template <typename> class Predicate, typename T >
struct all_match< Predicate, T >
: ::std::conditional<
Predicate<T>::value,
::std::true_type,
::std::false_type
>::type {};
template < template <typename> class Predicate >
struct all_match< Predicate >
: ::std::false_type {};
template < template <typename> class Predicate, typename ... T >
struct all_match< Predicate, type_tuple<T...> >
: all_match<Predicate, T...> {};
template < template <typename> class Predicate, typename ... T>
struct any_match;
template < template <typename> class Predicate, typename T, typename ... Y >
struct any_match< Predicate, T, Y... >
: ::std::conditional<
Predicate<T>::value,
::std::true_type,
any_match<Predicate, Y ...>
>::type {};
template < template <typename> class Predicate, typename T >
struct any_match< Predicate, T >
: std::conditional<
Predicate<T>::value,
::std::true_type,
::std::false_type
>::type {};
template < template <typename> class Predicate >
struct any_match< Predicate > : ::std::false_type {};
template < template <typename> class Predicate, typename ... T >
struct any_match< Predicate, type_tuple<T...> >
: any_match< Predicate, T... >{};
namespace detail {
} /* namespace detail */
template < template <typename> class Predicate, typename ... T >
struct find_if;
template <template <typename> class Predicate>
struct find_if<Predicate> {
using type = type_tuple<>;
};
template < template <typename> class Predicate, typename T, typename ... Y>
struct find_if< Predicate, T, Y... >
: ::std::conditional<
Predicate<T>::value,
combine< T, typename find_if<Predicate, Y...>::type>,
find_if<Predicate, Y...>
>::type {};
template < template <typename> class Predicate, typename T >
struct find_if< Predicate, T >
: ::std::conditional<
Predicate<T>::value,
combine<T>,
combine<>
>::type {};
template < template <typename> class Predicate, typename ... T>
struct find_if< Predicate, type_tuple<T...> > : find_if< Predicate, T... > {};
template < template<typename> class Predicate, typename ... T >
struct transform {
using type = type_tuple< typename Predicate<T>::type ... >;
};
template < template<typename> class Predicate, typename ... T >
struct transform < Predicate, type_tuple<T...> >
: transform< Predicate, T... > {};
template < template<typename> class Predicate >
struct transform<Predicate> {
using type = type_tuple<>;
};
template < template<typename> class Predicate, typename T >
struct invert {
static constexpr bool value = !Predicate<T>::value;
};
} /* namespace meta */
} /* namespace pus */
#endif /* PUSHKIN_META_ALGORITHM_HPP_ */
<commit_msg>Add `front` and `pop_front` metafunctions<commit_after>/*
* algorithm.hpp
*
* Created on: 28 мая 2016 г.
* Author: sergey.fedorov
*/
/**
* @page Metaprogramming algorithms
*
*/
#ifndef PUSHKIN_META_ALGORITHM_HPP_
#define PUSHKIN_META_ALGORITHM_HPP_
#include <type_traits>
#include <limits>
#include <pushkin/meta/type_tuple.hpp>
namespace psst {
namespace meta {
/**
* Metafunction to determine if typename T is contained in type
* variadic pack Y ...
*/
template < typename T, typename ... Y >
struct contains;
template < typename T, typename V, typename ... Y >
struct contains< T, V, Y ... > : contains < T, Y ...> {};
template < typename T, typename ... Y >
struct contains< T, T, Y ... > : ::std::true_type {};
template < typename T >
struct contains< T, T > : ::std::true_type {};
template < typename T, typename Y >
struct contains< T, Y > : ::std::false_type {};
template < typename T >
struct contains<T> : ::std::false_type {};
template < typename T, typename ... Y >
struct contains< T, type_tuple<Y...> > : contains<T, Y...> {};
/**
* Metafunction to determine if a variadic pack is empty
*/
template < typename ... T >
struct is_empty : ::std::false_type {};
template <>
struct is_empty<> : ::std::true_type {};
template <>
struct is_empty<void> : ::std::true_type {};
template < typename ... T >
struct is_empty< type_tuple<T...> >
: ::std::conditional<
(sizeof ... (T) > 0),
::std::false_type,
::std::true_type
>::type {};
template < typename ... T >
struct front;
template < typename T, typename ... Y >
struct front<T, Y...> {
using type = T;
};
template < typename ... T >
struct front< type_tuple<T...> > : front<T...> {};
namespace detail {
template < typename T, ::std::size_t N, typename ... Y >
struct index_of_impl;
template < typename T, ::std::size_t N, typename V, typename ... Y >
struct index_of_impl< T, N, V, Y ... > : index_of_impl<T, N + 1, Y...> {};
template < typename T, ::std::size_t N, typename ... Y >
struct index_of_impl< T, N, T, Y ... > {
static constexpr ::std::size_t value = N;
static constexpr bool found = true;
};
template < typename T, ::std::size_t N >
struct index_of_impl< T, N, T > {
static constexpr ::std::size_t value = N;
static constexpr bool found = true;
};
template < typename T, ::std::size_t N, typename Y>
struct index_of_impl<T, N, Y> {
static constexpr ::std::size_t value = ::std::numeric_limits<::std::size_t>::max();
static constexpr bool found = false;
};
template < typename T, ::std::size_t N>
struct index_of_impl<T, N> {
static constexpr ::std::size_t value = ::std::numeric_limits<::std::size_t>::max();
static constexpr bool found = false;
};
} /* namespace detail */
template < typename T, typename ... Y >
struct index_of : detail::index_of_impl<T, 0, Y...> {};
template < typename T, typename ... Y >
struct index_of< T, type_tuple<Y...> > : detail::index_of_impl<T, 0, Y...> {};
template < typename ... T >
struct combine;
template <>
struct combine<> {
using type = type_tuple<>;
};
template < typename T >
struct combine < T > {
using type = type_tuple<T>;
};
template < typename ... T >
struct combine < type_tuple<T...> > {
using type = type_tuple<T...>;
};
template < typename ... T, typename U, typename ... Y >
struct combine< type_tuple<T...>, U, Y...>
: combine< type_tuple<T..., U>, Y...> {};
template < typename T, typename ... U, typename ... Y >
struct combine< T, type_tuple<U...>, Y... > :
combine<type_tuple<T, U...>, Y...>{};
template < typename ... T, typename ... U, typename ... Y >
struct combine< type_tuple<T...>, type_tuple<U...>, Y... > {
using type = typename combine< type_tuple<T..., U... >, Y...>::type;
};
template < typename T, typename ... Y >
struct push_back {
using type = type_tuple<Y..., T>;
};
template < typename T, typename ... Y >
struct push_back<type_tuple<Y...>, T > {
using type = type_tuple<Y..., T>;
};
template < typename T, typename ... Y >
struct push_front {
using type = type_tuple<T, Y...>;
};
template < typename T, typename ... Y >
struct push_front<type_tuple<Y...>, T > {
using type = type_tuple<T, Y...>;
};
template < typename ... T >
struct pop_front;
template < typename T, typename ... Y >
struct pop_front<T, Y...> {
using type = type_tuple<Y...>;
};
template <>
struct pop_front<> {
using type = type_tuple<>;
};
template < typename ... T >
struct pop_front< type_tuple<T...> > : pop_front<T...> {};
template < typename T, typename ... Y>
struct remove_type;
template < typename T, typename V, typename ... Y >
struct remove_type<T, V, Y ...> {
using type = typename push_front<
typename remove_type<T, Y...>::type, V >::type;
};
template < typename T, typename ... Y >
struct remove_type<T, T, Y...> {
using type = typename remove_type<T, Y...>::type;
};
template < typename T >
struct remove_type <T> {
using type = type_tuple<>;
};
template < typename T, typename ... Y >
struct remove_type< type_tuple<Y...>, T > {
using type = typename remove_type<T, Y...>::type;
};
template < typename T, typename ... Y >
struct noop {
using type = type_tuple<Y...>;
};
template < typename T, typename ... Y >
struct insert_type : ::std::conditional<
contains<T, Y...>::value,
noop<T, Y...>,
typename ::std::conditional<
::std::is_same< T, void >::value,
noop<T, Y...>,
push_front<T, Y...>
>::type
>::type {};
template < typename T, typename ... Y >
struct insert_type< type_tuple<Y...>, T > {
using type = typename insert_type<T, Y...>::type;
};
template < typename ... T >
struct unique;
template < typename T, typename ... Y >
struct unique<T, Y...> {
using type = typename insert_type<
typename unique<Y...>::type, T>::type;
};
template <>
struct unique<> {
using type = type_tuple<>;
};
template < typename ... T >
struct unique< type_tuple<T...> > : unique<T...> {};
template < typename ... T, typename ... Y >
struct unique< type_tuple<T...>, type_tuple<Y...> >
: unique<T..., Y...> {};
template < typename ... T, typename ... Y >
struct unique< unique<T...>, unique<Y...> >
: unique<T..., Y...> {};
template < typename T, typename ... Y >
struct contains< T, unique<Y...> > : contains<T, Y...> {};
template < template <typename> class Predicate, typename ... T >
struct all_match;
template < template <typename> class Predicate, typename T, typename ... Y >
struct all_match< Predicate, T, Y... >
: ::std::conditional<
Predicate<T>::value,
all_match<Predicate, Y...>,
::std::false_type
>::type {};
template < template <typename> class Predicate, typename T >
struct all_match< Predicate, T >
: ::std::conditional<
Predicate<T>::value,
::std::true_type,
::std::false_type
>::type {};
template < template <typename> class Predicate >
struct all_match< Predicate >
: ::std::false_type {};
template < template <typename> class Predicate, typename ... T >
struct all_match< Predicate, type_tuple<T...> >
: all_match<Predicate, T...> {};
template < template <typename> class Predicate, typename ... T>
struct any_match;
template < template <typename> class Predicate, typename T, typename ... Y >
struct any_match< Predicate, T, Y... >
: ::std::conditional<
Predicate<T>::value,
::std::true_type,
any_match<Predicate, Y ...>
>::type {};
template < template <typename> class Predicate, typename T >
struct any_match< Predicate, T >
: std::conditional<
Predicate<T>::value,
::std::true_type,
::std::false_type
>::type {};
template < template <typename> class Predicate >
struct any_match< Predicate > : ::std::false_type {};
template < template <typename> class Predicate, typename ... T >
struct any_match< Predicate, type_tuple<T...> >
: any_match< Predicate, T... >{};
namespace detail {
} /* namespace detail */
template < template <typename> class Predicate, typename ... T >
struct find_if;
template <template <typename> class Predicate>
struct find_if<Predicate> {
using type = type_tuple<>;
};
template < template <typename> class Predicate, typename T, typename ... Y>
struct find_if< Predicate, T, Y... >
: ::std::conditional<
Predicate<T>::value,
combine< T, typename find_if<Predicate, Y...>::type>,
find_if<Predicate, Y...>
>::type {};
template < template <typename> class Predicate, typename T >
struct find_if< Predicate, T >
: ::std::conditional<
Predicate<T>::value,
combine<T>,
combine<>
>::type {};
template < template <typename> class Predicate, typename ... T>
struct find_if< Predicate, type_tuple<T...> > : find_if< Predicate, T... > {};
template < template<typename> class Predicate, typename ... T >
struct transform {
using type = type_tuple< typename Predicate<T>::type ... >;
};
template < template<typename> class Predicate, typename ... T >
struct transform < Predicate, type_tuple<T...> >
: transform< Predicate, T... > {};
template < template<typename> class Predicate >
struct transform<Predicate> {
using type = type_tuple<>;
};
template < template<typename> class Predicate, typename T >
struct invert {
static constexpr bool value = !Predicate<T>::value;
};
} /* namespace meta */
} /* namespace pus */
#endif /* PUSHKIN_META_ALGORITHM_HPP_ */
<|endoftext|>
|
<commit_before>// Copyright 2021 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://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.
#define PW_LOG_LEVEL PW_THREAD_CONFIG_LOG_LEVEL
#include "pw_thread/snapshot.h"
#include <cinttypes>
#include <string_view>
#include "pw_bytes/span.h"
#include "pw_function/function.h"
#include "pw_log/log.h"
#include "pw_protobuf/encoder.h"
#include "pw_status/status.h"
#include "pw_thread/config.h"
#include "pw_thread_protos/thread.pwpb.h"
namespace pw::thread {
Status SnapshotStack(const StackContext& stack,
proto::Thread::StreamEncoder& encoder,
const ProcessThreadStackCallback& thread_stack_callback) {
// TODO(b/234890430): Add support for ascending stacks.
encoder.WriteStackStartPointer(stack.stack_high_addr).IgnoreError();
encoder.WriteStackEndPointer(stack.stack_low_addr).IgnoreError();
encoder.WriteStackPointer(stack.stack_pointer).IgnoreError();
// The PRIuPTR is an appropriate format specifier for uintptr_t values
// https://stackoverflow.com/a/5796039/1224002
PW_LOG_DEBUG("Active stack: 0x%08" PRIuPTR "x-0x%08" PRIuPTR "x (%ld bytes)",
stack.stack_high_addr,
stack.stack_pointer,
static_cast<long>(stack.stack_high_addr) -
static_cast<long>(stack.stack_pointer));
if (stack.stack_pointer_est_peak.has_value()) {
const uintptr_t stack_pointer_est_peak =
stack.stack_pointer_est_peak.value();
encoder.WriteStackPointerEstPeak(stack_pointer_est_peak).IgnoreError();
PW_LOG_DEBUG("Est peak stack: 0x%08" PRIuPTR "x-0x%08" PRIuPTR
"x (%ld bytes)",
stack.stack_high_addr,
stack_pointer_est_peak,
static_cast<long>(stack.stack_high_addr) -
static_cast<long>(stack_pointer_est_peak));
}
PW_LOG_DEBUG("Stack Limits: 0x%08" PRIuPTR "x-0x%08" PRIuPTR "x (%ld bytes)",
stack.stack_low_addr,
stack.stack_high_addr,
static_cast<long>(stack.stack_high_addr) -
static_cast<long>(stack.stack_low_addr));
if (stack.stack_pointer > stack.stack_high_addr) {
PW_LOG_ERROR("%s's stack underflowed by %lu bytes",
stack.thread_name.data(),
static_cast<long unsigned>(stack.stack_pointer -
stack.stack_high_addr));
return Status::OutOfRange();
}
// Log an error, but don't prevent the capture.
if (stack.stack_pointer < stack.stack_low_addr) {
PW_LOG_ERROR(
"%s's stack overflowed by %lu bytes",
stack.thread_name.data(),
static_cast<long unsigned>(stack.stack_low_addr - stack.stack_pointer));
}
return thread_stack_callback(
encoder,
ConstByteSpan(reinterpret_cast<const std::byte*>(stack.stack_pointer),
stack.stack_high_addr - stack.stack_pointer));
}
} // namespace pw::thread
<commit_msg>pw_thread: Fix uintptr_t hex formatting<commit_after>// Copyright 2021 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://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.
#define PW_LOG_LEVEL PW_THREAD_CONFIG_LOG_LEVEL
#include "pw_thread/snapshot.h"
#include <cinttypes>
#include <string_view>
#include "pw_bytes/span.h"
#include "pw_function/function.h"
#include "pw_log/log.h"
#include "pw_protobuf/encoder.h"
#include "pw_status/status.h"
#include "pw_thread/config.h"
#include "pw_thread_protos/thread.pwpb.h"
namespace pw::thread {
Status SnapshotStack(const StackContext& stack,
proto::Thread::StreamEncoder& encoder,
const ProcessThreadStackCallback& thread_stack_callback) {
// TODO(b/234890430): Add support for ascending stacks.
encoder.WriteStackStartPointer(stack.stack_high_addr).IgnoreError();
encoder.WriteStackEndPointer(stack.stack_low_addr).IgnoreError();
encoder.WriteStackPointer(stack.stack_pointer).IgnoreError();
// The PRIxPTR is an appropriate format specifier for hex uintptr_t values
// https://stackoverflow.com/a/5796039/1224002
PW_LOG_DEBUG("Active stack: 0x%08" PRIxPTR "-0x%08" PRIxPTR " (%ld bytes)",
stack.stack_high_addr,
stack.stack_pointer,
static_cast<long>(stack.stack_high_addr) -
static_cast<long>(stack.stack_pointer));
if (stack.stack_pointer_est_peak.has_value()) {
const uintptr_t stack_pointer_est_peak =
stack.stack_pointer_est_peak.value();
encoder.WriteStackPointerEstPeak(stack_pointer_est_peak).IgnoreError();
PW_LOG_DEBUG("Est peak stack: 0x%08" PRIxPTR "-0x%08" PRIxPTR
" (%ld bytes)",
stack.stack_high_addr,
stack_pointer_est_peak,
static_cast<long>(stack.stack_high_addr) -
static_cast<long>(stack_pointer_est_peak));
}
PW_LOG_DEBUG("Stack Limits: 0x%08" PRIxPTR "-0x%08" PRIxPTR " (%ld bytes)",
stack.stack_low_addr,
stack.stack_high_addr,
static_cast<long>(stack.stack_high_addr) -
static_cast<long>(stack.stack_low_addr));
if (stack.stack_pointer > stack.stack_high_addr) {
PW_LOG_ERROR("%s's stack underflowed by %lu bytes",
stack.thread_name.data(),
static_cast<long unsigned>(stack.stack_pointer -
stack.stack_high_addr));
return Status::OutOfRange();
}
// Log an error, but don't prevent the capture.
if (stack.stack_pointer < stack.stack_low_addr) {
PW_LOG_ERROR(
"%s's stack overflowed by %lu bytes",
stack.thread_name.data(),
static_cast<long unsigned>(stack.stack_low_addr - stack.stack_pointer));
}
return thread_stack_callback(
encoder,
ConstByteSpan(reinterpret_cast<const std::byte*>(stack.stack_pointer),
stack.stack_high_addr - stack.stack_pointer));
}
} // namespace pw::thread
<|endoftext|>
|
<commit_before>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef TYPE_SAFE_BOUNDED_TYPE_HPP_INCLUDED
#define TYPE_SAFE_BOUNDED_TYPE_HPP_INCLUDED
#include <type_traits>
#include <type_safe/constrained_type.hpp>
namespace type_safe
{
namespace constraints
{
struct dynamic_bound { };
namespace detail
{
// Base to enable empty base optimization when BoundConstant is not dynamic_bound.
// Neccessary when T is not a class.
template <class T>
struct Wrapper
{
T value;
};
template <class BoundConstant>
struct is_dynamic : std::is_same<BoundConstant,dynamic_bound>
{
};
template <class T, class BoundConstant>
using Base = typename std::conditional<is_dynamic<BoundConstant>::value,
Wrapper<T>,
BoundConstant>::type;
} // detail namespace
#define TYPE_SAFE_DETAIL_MAKE(Name, Op) \
template <typename T, typename BoundConstant = dynamic_bound> \
class Name : detail::Base<T, BoundConstant> \
{ \
using Base = detail::Base<T, BoundConstant>; \
\
static constexpr bool is_dynamic = detail::is_dynamic<BoundConstant>::value; \
public: \
explicit Name() \
{ \
static_assert(!is_dynamic,"constructor requires static bound"); \
} \
\
explicit Name(const T& bound) : Base{bound} \
{ \
static_assert(is_dynamic,"constructor requires dynamic bound"); \
} \
\
explicit Name(T&& bound) noexcept(std::is_nothrow_move_constructible<T>::value) \
: Base{std::move(bound)} \
{ \
static_assert(is_dynamic,"constructor requires dynamic bound"); \
} \
\
template <typename U> \
bool operator()(const U& u) const \
{ \
return u Op get_bound(); \
} \
\
const T& get_bound() const noexcept \
{ \
return Base::value; \
} \
};
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is less than some given value.
TYPE_SAFE_DETAIL_MAKE(less, <)
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is less than or equal to some given value.
TYPE_SAFE_DETAIL_MAKE(less_equal, <=)
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is greater than some given value.
TYPE_SAFE_DETAIL_MAKE(greater, >)
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is greater than or equal to some given value.
TYPE_SAFE_DETAIL_MAKE(greater_equal, >=)
#undef TYPE_SAFE_DETAIL_MAKE
namespace detail
{
// checks that that the value is less than the upper bound
template <bool Inclusive, typename T, typename BoundConstant>
using upper_bound_t =
typename std::conditional<Inclusive, less_equal<T, BoundConstant>,
less<T, BoundConstant>>::type;
// checks that the value is greater than the lower bound
template <bool Inclusive, typename T, typename BoundConstant>
using lower_bound_t =
typename std::conditional<Inclusive, greater_equal<T, BoundConstant>,
greater<T, BoundConstant>>::type;
} // namespace detail
constexpr bool open = false;
constexpr bool closed = true;
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is between two given bounds,
/// `LowerInclusive`/`UpperInclusive` control whether the lower/upper bound itself is valid too.
/// `LowerConstant`/`UpperConstant` control whether the lower/upper bound is specified statically or dinamically.
/// When one is `dynamic_bound`, its bound is specified at run-time. Otherwise, it must match
/// the interface and semantics of `std::integral_constant<T>`, in which case its `value` is the bound.
template <typename T, bool LowerInclusive, bool UpperInclusive,
typename LowerConstant = dynamic_bound,
typename UpperConstant = dynamic_bound>
class bounded : detail::lower_bound_t<LowerInclusive, T, LowerConstant>,
detail::upper_bound_t<UpperInclusive, T, UpperConstant>
{
static constexpr bool lower_is_dynamic = detail::is_dynamic<LowerConstant>::value;
static constexpr bool upper_is_dynamic = detail::is_dynamic<UpperConstant>::value;
using Lower = detail::lower_bound_t<LowerInclusive, T, LowerConstant>;
using Upper = detail::upper_bound_t<UpperInclusive, T, UpperConstant>;
const Lower& lower() const noexcept { return *this; }
const Upper& upper() const noexcept { return *this; }
template <typename U>
using decay_same = std::is_same<typename std::decay<U>::type, T>;
public:
template <typename LC = LowerConstant, typename UC = UpperConstant,
typename = typename std::enable_if<
decay_same<typename LC::value_type>::value>::type,
typename = typename std::enable_if<
decay_same<typename UC::value_type>::value>::type>
bounded()
{
static_assert(!lower_is_dynamic && !upper_is_dynamic,
"constructor requires static bounds");
}
template <typename U, bool req = upper_is_dynamic, typename LC = LowerConstant,
typename = typename std::enable_if<req &&
decay_same<typename LC::value_type>::value>::type>
bounded(U&& upper)
: Upper(std::forward<U>(upper))
{
static_assert(!lower_is_dynamic && upper_is_dynamic,
"constructor requires dynamic upper bound");
}
template <typename U, typename UC = UpperConstant, bool req = lower_is_dynamic,
typename = typename std::enable_if<req &&
decay_same<typename UC::value_type>::value>::type>
bounded(U&& lower)
: Lower(std::forward<U>(lower))
{
static_assert(lower_is_dynamic && !upper_is_dynamic,
"constructor requires dynamic lower bound");
}
template <typename U1, typename U2,
typename = typename std::enable_if<decay_same<U1>::value>::type,
typename = typename std::enable_if<decay_same<U2>::value>::type>
bounded(U1&& lower, U2&& upper)
: Lower(std::forward<U1>(lower)), Upper(std::forward<U2>(upper))
{
static_assert(upper_is_dynamic && lower_is_dynamic,
"constructor requires dynamic bounds");
}
template <typename U>
bool operator()(const U& u) const
{
return lower()(u) && upper()(u);
}
const T& get_lower_bound() const noexcept
{
return lower().get_bound();
}
const T& get_upper_bound() const noexcept
{
return upper().get_bound();
}
};
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is between two given bounds but not the bounds themselves.
template <typename T>
using open_interval = bounded<T, open, open>;
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is between two given bounds or the bounds themselves.
template <typename T>
using closed_interval = bounded<T, closed, closed>;
} // namespace constraints
/// \exclude
namespace detail
{
template <typename T, typename U1, typename U2>
struct bounded_value_type_impl
{
static_assert(!std::is_same<T, U1>::value && !std::is_same<U1, U2>::value,
"make_bounded() called with mismatching types");
};
template <typename T>
struct bounded_value_type_impl<T, T, T>
{
using type = T;
};
template <typename T, typename U1, typename U2>
using bounded_value_type =
typename bounded_value_type_impl<typename std::decay<T>::type,
typename std::decay<U1>::type,
typename std::decay<U2>::type>::type;
} // namespace detail
/// An alias for [type_safe::constrained_type<T, Constraint, Verifier>]() that uses [type_safe::constraints::bounded<T, LowerInclusive, UpperInclusive>]() as its `Constraint`.
/// \notes This is some type where the values must be in a certain interval.
template <typename T, bool LowerInclusive, bool UpperInclusive,
typename LowerConstant = constraints::dynamic_bound,
typename UpperConstant = constraints::dynamic_bound>
using bounded_type =
constrained_type<T, constraints::bounded<T, LowerInclusive, UpperInclusive,
LowerConstant, UpperConstant>>;
/// \returns A [type_safe::bounded_type<T, LowerInclusive, UpperInclusive>]() with the given `value` and lower and upper bounds,
/// where those bounds are valid values as well.
template <typename T, typename U1, typename U2>
auto make_bounded(T&& value, U1&& lower, U2&& upper)
-> bounded_type<detail::bounded_value_type<T, U1, U2>, true, true>
{
using value_type = detail::bounded_value_type<T, U1, U2>;
return bounded_type<value_type, true,
true>(std::forward<T>(value),
constraints::closed_interval<value_type>(std::forward<U1>(lower),
std::forward<U2>(
upper)));
}
/// \returns A [type_safe::bounded_type<T, LowerInclusive, UpperInclusive>]() with the given `value` and lower and upper bounds,
/// where those bounds are not valid values.
template <typename T, typename U1, typename U2>
auto make_bounded_exclusive(T&& value, U1&& lower, U2&& upper)
-> bounded_type<detail::bounded_value_type<T, U1, U2>, false, false>
{
using value_type = detail::bounded_value_type<T, U1, U2>;
return bounded_type<value_type, false,
false>(std::forward<T>(value),
constraints::open_interval<value_type>(std::forward<U1>(lower),
std::forward<U2>(upper)));
}
/// \effects Changes `val` so that it is in the interval.
/// If it is not in the interval, assigns the bound that is closer to the value.
template <typename T, typename U>
void clamp(const constraints::closed_interval<T>& interval, U& val)
{
if (val < interval.get_lower_bound())
val = static_cast<U>(interval.get_lower_bound());
else if (val > interval.get_upper_bound())
val = static_cast<U>(interval.get_upper_bound());
}
/// A `Verifier` for [type_safe::constrained_type<T, Constraint, Verifier]() that clamps the value to make it valid.
/// It must be used together with [type_safe::constraints::less_equal<T>](), [type_safe::constraints::greater_equal<T>]() or [type_safe::constraints::closed_interval<T>]().
struct clamping_verifier
{
/// \effects If `val` is greater than the bound of `p`,
/// assigns the bound to `val`.
/// Otherwise does nothing.
template <typename Value, typename T>
static void verify(Value& val, const constraints::less_equal<T>& p)
{
if (!p(val))
val = static_cast<Value>(p.get_bound());
}
/// \effects If `val` is less than the bound of `p`,
/// assigns the bound to `val`.
/// Otherwise does nothing.
template <typename Value, typename T>
static void verify(Value& val, const constraints::greater_equal<T>& p)
{
if (!p(val))
val = static_cast<Value>(p.get_bound());
}
/// \effects Same as `clamp(interval, val)`.
template <typename Value, typename T>
static void verify(Value& val, const constraints::closed_interval<T>& interval)
{
clamp(interval, val);
}
};
/// An alias for [type_safe::constrained_type<T, Constraint, Verifier>]() that uses [type_safe::constraints::closed_interval<T>]() as its `Constraint`
/// and [type_safe::clamping_verifier]() as its `Verifier`.
/// \notes This is some type where the values are always clamped so that they are in a certain interval.
template <typename T>
using clamped_type = constrained_type<T, constraints::closed_interval<T>, clamping_verifier>;
/// \returns A [type_safe::clamped_type<T>]() with the given `value` and lower and upper bounds.
template <typename T, typename U1, typename U2>
auto make_clamped(T&& value, U1&& lower, U2&& upper)
-> clamped_type<detail::bounded_value_type<T, U1, U2>>
{
using value_type = detail::bounded_value_type<T, U1, U2>;
return clamped_type<value_type>(std::forward<T>(value),
constraints::closed_interval<value_type>(std::forward<U1>(
lower),
std::forward<U2>(
upper)));
}
} // namespace type_safe
#endif // TYPE_SAFE_BOUNDED_TYPE_HPP_INCLUDED
<commit_msg>[fixup] Add overload so that `static_assert` can trigger<commit_after>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef TYPE_SAFE_BOUNDED_TYPE_HPP_INCLUDED
#define TYPE_SAFE_BOUNDED_TYPE_HPP_INCLUDED
#include <type_traits>
#include <type_safe/constrained_type.hpp>
namespace type_safe
{
namespace constraints
{
struct dynamic_bound { };
namespace detail
{
// Base to enable empty base optimization when BoundConstant is not dynamic_bound.
// Neccessary when T is not a class.
template <class T>
struct Wrapper
{
T value;
};
template <class BoundConstant>
struct is_dynamic : std::is_same<BoundConstant,dynamic_bound>
{
};
template <class T, class BoundConstant>
using Base = typename std::conditional<is_dynamic<BoundConstant>::value,
Wrapper<T>,
BoundConstant>::type;
} // detail namespace
#define TYPE_SAFE_DETAIL_MAKE(Name, Op) \
template <typename T, typename BoundConstant = dynamic_bound> \
class Name : detail::Base<T, BoundConstant> \
{ \
using Base = detail::Base<T, BoundConstant>; \
\
static constexpr bool is_dynamic = detail::is_dynamic<BoundConstant>::value; \
public: \
explicit Name() \
{ \
static_assert(!is_dynamic,"constructor requires static bound"); \
} \
\
explicit Name(const T& bound) : Base{bound} \
{ \
static_assert(is_dynamic,"constructor requires dynamic bound"); \
} \
\
explicit Name(T&& bound) noexcept(std::is_nothrow_move_constructible<T>::value) \
: Base{std::move(bound)} \
{ \
static_assert(is_dynamic,"constructor requires dynamic bound"); \
} \
\
template <typename U> \
bool operator()(const U& u) const \
{ \
return u Op get_bound(); \
} \
\
const T& get_bound() const noexcept \
{ \
return Base::value; \
} \
};
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is less than some given value.
TYPE_SAFE_DETAIL_MAKE(less, <)
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is less than or equal to some given value.
TYPE_SAFE_DETAIL_MAKE(less_equal, <=)
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is greater than some given value.
TYPE_SAFE_DETAIL_MAKE(greater, >)
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is greater than or equal to some given value.
TYPE_SAFE_DETAIL_MAKE(greater_equal, >=)
#undef TYPE_SAFE_DETAIL_MAKE
namespace detail
{
// checks that that the value is less than the upper bound
template <bool Inclusive, typename T, typename BoundConstant>
using upper_bound_t =
typename std::conditional<Inclusive, less_equal<T, BoundConstant>,
less<T, BoundConstant>>::type;
// checks that the value is greater than the lower bound
template <bool Inclusive, typename T, typename BoundConstant>
using lower_bound_t =
typename std::conditional<Inclusive, greater_equal<T, BoundConstant>,
greater<T, BoundConstant>>::type;
} // namespace detail
constexpr bool open = false;
constexpr bool closed = true;
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is between two given bounds,
/// `LowerInclusive`/`UpperInclusive` control whether the lower/upper bound itself is valid too.
/// `LowerConstant`/`UpperConstant` control whether the lower/upper bound is specified statically or dinamically.
/// When one is `dynamic_bound`, its bound is specified at run-time. Otherwise, it must match
/// the interface and semantics of `std::integral_constant<T>`, in which case its `value` is the bound.
template <typename T, bool LowerInclusive, bool UpperInclusive,
typename LowerConstant = dynamic_bound,
typename UpperConstant = dynamic_bound>
class bounded : detail::lower_bound_t<LowerInclusive, T, LowerConstant>,
detail::upper_bound_t<UpperInclusive, T, UpperConstant>
{
static constexpr bool lower_is_dynamic = detail::is_dynamic<LowerConstant>::value;
static constexpr bool upper_is_dynamic = detail::is_dynamic<UpperConstant>::value;
using Lower = detail::lower_bound_t<LowerInclusive, T, LowerConstant>;
using Upper = detail::upper_bound_t<UpperInclusive, T, UpperConstant>;
const Lower& lower() const noexcept { return *this; }
const Upper& upper() const noexcept { return *this; }
template <typename U>
using decay_same = std::is_same<typename std::decay<U>::type, T>;
public:
template <typename LC = LowerConstant, typename UC = UpperConstant,
typename = typename std::enable_if<
decay_same<typename LC::value_type>::value>::type,
typename = typename std::enable_if<
decay_same<typename UC::value_type>::value>::type>
bounded()
{
static_assert(!lower_is_dynamic && !upper_is_dynamic,
"constructor requires static bounds");
}
template <typename U, bool req = upper_is_dynamic, typename LC = LowerConstant,
typename = typename std::enable_if<req &&
decay_same<typename LC::value_type>::value>::type>
bounded(U&& upper)
: Upper(std::forward<U>(upper))
{
}
template <typename U, typename UC = UpperConstant, bool req = lower_is_dynamic,
typename = typename std::enable_if<req &&
decay_same<typename UC::value_type>::value>::type>
bounded(U&& lower)
: Lower(std::forward<U>(lower))
{
}
/// \exclude
template <typename U, bool req = lower_is_dynamic!=upper_is_dynamic,
typename = typename std::enable_if<!req>::type>
bounded(U&&)
{
static_assert(req,"one-argument constructors require a dynamic and static bound");
}
template <typename U1, typename U2,
typename = typename std::enable_if<decay_same<U1>::value>::type,
typename = typename std::enable_if<decay_same<U2>::value>::type>
bounded(U1&& lower, U2&& upper)
: Lower(std::forward<U1>(lower)), Upper(std::forward<U2>(upper))
{
static_assert(upper_is_dynamic && lower_is_dynamic,
"constructor requires dynamic bounds");
}
template <typename U>
bool operator()(const U& u) const
{
return lower()(u) && upper()(u);
}
const T& get_lower_bound() const noexcept
{
return lower().get_bound();
}
const T& get_upper_bound() const noexcept
{
return upper().get_bound();
}
};
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is between two given bounds but not the bounds themselves.
template <typename T>
using open_interval = bounded<T, open, open>;
/// A `Constraint` for the [type_safe::constrained_type<T, Constraint, Verifier>]().
/// A value is valid if it is between two given bounds or the bounds themselves.
template <typename T>
using closed_interval = bounded<T, closed, closed>;
} // namespace constraints
/// \exclude
namespace detail
{
template <typename T, typename U1, typename U2>
struct bounded_value_type_impl
{
static_assert(!std::is_same<T, U1>::value && !std::is_same<U1, U2>::value,
"make_bounded() called with mismatching types");
};
template <typename T>
struct bounded_value_type_impl<T, T, T>
{
using type = T;
};
template <typename T, typename U1, typename U2>
using bounded_value_type =
typename bounded_value_type_impl<typename std::decay<T>::type,
typename std::decay<U1>::type,
typename std::decay<U2>::type>::type;
} // namespace detail
/// An alias for [type_safe::constrained_type<T, Constraint, Verifier>]() that uses [type_safe::constraints::bounded<T, LowerInclusive, UpperInclusive>]() as its `Constraint`.
/// \notes This is some type where the values must be in a certain interval.
template <typename T, bool LowerInclusive, bool UpperInclusive,
typename LowerConstant = constraints::dynamic_bound,
typename UpperConstant = constraints::dynamic_bound>
using bounded_type =
constrained_type<T, constraints::bounded<T, LowerInclusive, UpperInclusive,
LowerConstant, UpperConstant>>;
/// \returns A [type_safe::bounded_type<T, LowerInclusive, UpperInclusive>]() with the given `value` and lower and upper bounds,
/// where those bounds are valid values as well.
template <typename T, typename U1, typename U2>
auto make_bounded(T&& value, U1&& lower, U2&& upper)
-> bounded_type<detail::bounded_value_type<T, U1, U2>, true, true>
{
using value_type = detail::bounded_value_type<T, U1, U2>;
return bounded_type<value_type, true,
true>(std::forward<T>(value),
constraints::closed_interval<value_type>(std::forward<U1>(lower),
std::forward<U2>(
upper)));
}
/// \returns A [type_safe::bounded_type<T, LowerInclusive, UpperInclusive>]() with the given `value` and lower and upper bounds,
/// where those bounds are not valid values.
template <typename T, typename U1, typename U2>
auto make_bounded_exclusive(T&& value, U1&& lower, U2&& upper)
-> bounded_type<detail::bounded_value_type<T, U1, U2>, false, false>
{
using value_type = detail::bounded_value_type<T, U1, U2>;
return bounded_type<value_type, false,
false>(std::forward<T>(value),
constraints::open_interval<value_type>(std::forward<U1>(lower),
std::forward<U2>(upper)));
}
/// \effects Changes `val` so that it is in the interval.
/// If it is not in the interval, assigns the bound that is closer to the value.
template <typename T, typename U>
void clamp(const constraints::closed_interval<T>& interval, U& val)
{
if (val < interval.get_lower_bound())
val = static_cast<U>(interval.get_lower_bound());
else if (val > interval.get_upper_bound())
val = static_cast<U>(interval.get_upper_bound());
}
/// A `Verifier` for [type_safe::constrained_type<T, Constraint, Verifier]() that clamps the value to make it valid.
/// It must be used together with [type_safe::constraints::less_equal<T>](), [type_safe::constraints::greater_equal<T>]() or [type_safe::constraints::closed_interval<T>]().
struct clamping_verifier
{
/// \effects If `val` is greater than the bound of `p`,
/// assigns the bound to `val`.
/// Otherwise does nothing.
template <typename Value, typename T>
static void verify(Value& val, const constraints::less_equal<T>& p)
{
if (!p(val))
val = static_cast<Value>(p.get_bound());
}
/// \effects If `val` is less than the bound of `p`,
/// assigns the bound to `val`.
/// Otherwise does nothing.
template <typename Value, typename T>
static void verify(Value& val, const constraints::greater_equal<T>& p)
{
if (!p(val))
val = static_cast<Value>(p.get_bound());
}
/// \effects Same as `clamp(interval, val)`.
template <typename Value, typename T>
static void verify(Value& val, const constraints::closed_interval<T>& interval)
{
clamp(interval, val);
}
};
/// An alias for [type_safe::constrained_type<T, Constraint, Verifier>]() that uses [type_safe::constraints::closed_interval<T>]() as its `Constraint`
/// and [type_safe::clamping_verifier]() as its `Verifier`.
/// \notes This is some type where the values are always clamped so that they are in a certain interval.
template <typename T>
using clamped_type = constrained_type<T, constraints::closed_interval<T>, clamping_verifier>;
/// \returns A [type_safe::clamped_type<T>]() with the given `value` and lower and upper bounds.
template <typename T, typename U1, typename U2>
auto make_clamped(T&& value, U1&& lower, U2&& upper)
-> clamped_type<detail::bounded_value_type<T, U1, U2>>
{
using value_type = detail::bounded_value_type<T, U1, U2>;
return clamped_type<value_type>(std::forward<T>(value),
constraints::closed_interval<value_type>(std::forward<U1>(
lower),
std::forward<U2>(
upper)));
}
} // namespace type_safe
#endif // TYPE_SAFE_BOUNDED_TYPE_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_CONFIG_HPP
#define XTENSOR_CONFIG_HPP
#define XTENSOR_VERSION_MAJOR 0
#define XTENSOR_VERSION_MINOR 8
#define XTENSOR_VERSION_PATCH 1
// DETECT 3.6 <= clang < 3.8 for compiler bug workaround.
#ifdef __clang__
#if __clang_major__ == 3 && __clang_minor__ < 8
#define X_OLD_CLANG
#include <initializer_list>
#include <vector>
#endif
#endif
#ifndef DEFAULT_DATA_CONTAINER
#define DEFAULT_DATA_CONTAINER(T, A) uvector<T, A>
#endif
#ifndef DEFAULT_SHAPE_CONTAINER
#define DEFAULT_SHAPE_CONTAINER(T, EA, SA) \
std::vector<typename DEFAULT_DATA_CONTAINER(T, EA)::size_type, SA>
#endif
#endif
<commit_msg>Release 0.8.2<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_CONFIG_HPP
#define XTENSOR_CONFIG_HPP
#define XTENSOR_VERSION_MAJOR 0
#define XTENSOR_VERSION_MINOR 8
#define XTENSOR_VERSION_PATCH 2
// DETECT 3.6 <= clang < 3.8 for compiler bug workaround.
#ifdef __clang__
#if __clang_major__ == 3 && __clang_minor__ < 8
#define X_OLD_CLANG
#include <initializer_list>
#include <vector>
#endif
#endif
#ifndef DEFAULT_DATA_CONTAINER
#define DEFAULT_DATA_CONTAINER(T, A) uvector<T, A>
#endif
#ifndef DEFAULT_SHAPE_CONTAINER
#define DEFAULT_SHAPE_CONTAINER(T, EA, SA) \
std::vector<typename DEFAULT_DATA_CONTAINER(T, EA)::size_type, SA>
#endif
#endif
<|endoftext|>
|
<commit_before>/**
* @file llavatariconctrl.cpp
* @brief LLAvatarIconCtrl class implementation
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llavatariconctrl.h"
// viewer includes
#include "llagent.h"
#include "llavatarconstants.h"
#include "llcallingcard.h" // for LLAvatarTracker
#include "llavataractions.h"
#include "llmenugl.h"
#include "lluictrlfactory.h"
#include "llagentdata.h"
#include "llimfloater.h"
// library includes
#include "llavatarnamecache.h"
#define MENU_ITEM_VIEW_PROFILE 0
#define MENU_ITEM_SEND_IM 1
static LLDefaultChildRegistry::Register<LLAvatarIconCtrl> r("avatar_icon");
bool LLAvatarIconIDCache::LLAvatarIconIDCacheItem::expired()
{
const F64 SEC_PER_DAY_PLUS_HOUR = (24.0 + 1.0) * 60.0 * 60.0;
F64 delta = LLDate::now().secondsSinceEpoch() - cached_time.secondsSinceEpoch();
if (delta > SEC_PER_DAY_PLUS_HOUR)
return true;
return false;
}
void LLAvatarIconIDCache::load ()
{
llinfos << "Loading avatar icon id cache." << llendl;
// build filename for each user
std::string resolved_filename = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, mFilename);
llifstream file(resolved_filename);
if (!file.is_open())
return;
// add each line in the file to the list
int uuid_len = UUID_STR_LENGTH-1;
std::string line;
while (std::getline(file, line))
{
LLUUID avatar_id;
LLUUID icon_id;
LLDate date;
std::string avatar_id_str = line.substr(0,uuid_len);
std::string icon_id_str = line.substr(uuid_len,uuid_len);
std::string date_str = line.substr(uuid_len*2, line.length()-uuid_len*2);
if(!avatar_id.set(avatar_id_str) || !icon_id.set(icon_id_str) || !date.fromString(date_str))
continue;
LLAvatarIconIDCacheItem item = {icon_id,date};
mCache[avatar_id] = item;
}
file.close();
}
void LLAvatarIconIDCache::save ()
{
std::string resolved_filename = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, mFilename);
// open a file for writing
llofstream file (resolved_filename);
if (!file.is_open())
{
llwarns << "can't open avatar icons cache file\"" << mFilename << "\" for writing" << llendl;
return;
}
for(std::map<LLUUID,LLAvatarIconIDCacheItem>::iterator it = mCache.begin();it!=mCache.end();++it)
{
if(!it->second.expired())
{
file << it->first << it->second.icon_id << it->second.cached_time << std::endl;
}
}
file.close();
}
LLUUID* LLAvatarIconIDCache::get (const LLUUID& avatar_id)
{
std::map<LLUUID,LLAvatarIconIDCacheItem>::iterator it = mCache.find(avatar_id);
if(it==mCache.end())
return 0;
if(it->second.expired())
return 0;
return &it->second.icon_id;
}
void LLAvatarIconIDCache::add (const LLUUID& avatar_id,const LLUUID& icon_id)
{
LLAvatarIconIDCacheItem item = {icon_id,LLDate::now()};
mCache[avatar_id] = item;
}
void LLAvatarIconIDCache::remove (const LLUUID& avatar_id)
{
mCache.erase(avatar_id);
}
LLAvatarIconCtrl::Params::Params()
: avatar_id("avatar_id"),
draw_tooltip("draw_tooltip", true),
default_icon_name("default_icon_name")
{
}
LLAvatarIconCtrl::LLAvatarIconCtrl(const LLAvatarIconCtrl::Params& p)
: LLIconCtrl(p),
mDrawTooltip(p.draw_tooltip),
mDefaultIconName(p.default_icon_name)
{
mPriority = LLViewerFetchedTexture::BOOST_ICON;
LLRect rect = p.rect;
mDrawWidth = llmax(32, rect.getWidth()) ;
mDrawHeight = llmax(32, rect.getHeight()) ;
static LLUICachedControl<S32> llavatariconctrl_symbol_hpad("UIAvatariconctrlSymbolHPad", 2);
static LLUICachedControl<S32> llavatariconctrl_symbol_vpad("UIAvatariconctrlSymbolVPad", 2);
static LLUICachedControl<S32> llavatariconctrl_symbol_size("UIAvatariconctrlSymbolSize", 5);
static LLUICachedControl<std::string> llavatariconctrl_symbol_pos("UIAvatariconctrlSymbolPosition", "BottomRight");
// BottomRight is the default position
S32 left = rect.getWidth() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_hpad;
S32 bottom = llavatariconctrl_symbol_vpad;
if ("BottomLeft" == (std::string)llavatariconctrl_symbol_pos)
{
left = llavatariconctrl_symbol_hpad;
bottom = llavatariconctrl_symbol_vpad;
}
else if ("TopLeft" == (std::string)llavatariconctrl_symbol_pos)
{
left = llavatariconctrl_symbol_hpad;
bottom = rect.getHeight() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_vpad;
}
else if ("TopRight" == (std::string)llavatariconctrl_symbol_pos)
{
left = rect.getWidth() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_hpad;
bottom = rect.getHeight() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_vpad;
}
rect.setOriginAndSize(left, bottom, llavatariconctrl_symbol_size, llavatariconctrl_symbol_size);
if (p.avatar_id.isProvided())
{
LLSD value(p.avatar_id);
setValue(value);
}
else
{
LLIconCtrl::setValue(mDefaultIconName);
}
}
LLAvatarIconCtrl::~LLAvatarIconCtrl()
{
if (mAvatarId.notNull())
{
LLAvatarPropertiesProcessor::getInstance()->removeObserver(mAvatarId, this);
// Name callbacks will be automatically disconnected since LLUICtrl is trackable
}
}
//virtual
void LLAvatarIconCtrl::setValue(const LLSD& value)
{
if (value.isUUID())
{
LLAvatarPropertiesProcessor* app =
LLAvatarPropertiesProcessor::getInstance();
if (mAvatarId.notNull())
{
app->removeObserver(mAvatarId, this);
}
if (mAvatarId != value.asUUID())
{
mAvatarId = value.asUUID();
// *BUG: This will return stale icons if a user changes their
// profile picture. However, otherwise we send too many upstream
// AvatarPropertiesRequest messages.
// to get fresh avatar icon use
// LLAvatarIconIDCache::getInstance()->remove(avatar_id);
// Check if cache already contains image_id for that avatar
if (!updateFromCache())
{
// *TODO: Consider getting avatar icon/badge directly from
// People API, rather than sending AvatarPropertyRequest
// messages. People API already hits the user table.
LLIconCtrl::setValue(mDefaultIconName);
app->addObserver(mAvatarId, this);
app->sendAvatarPropertiesRequest(mAvatarId);
}
}
}
else
{
LLIconCtrl::setValue(value);
}
LLAvatarNameCache::get(mAvatarId,
boost::bind(&LLAvatarIconCtrl::onAvatarNameCache,
this, _1, _2));
}
bool LLAvatarIconCtrl::updateFromCache()
{
LLUUID* icon_id_ptr = LLAvatarIconIDCache::getInstance()->get(mAvatarId);
if(!icon_id_ptr)
return false;
const LLUUID& icon_id = *icon_id_ptr;
// Update the avatar
if (icon_id.notNull())
{
LLIconCtrl::setValue(icon_id);
}
else
{
LLIconCtrl::setValue(mDefaultIconName);
}
return true;
}
//virtual
void LLAvatarIconCtrl::processProperties(void* data, EAvatarProcessorType type)
{
if (APT_PROPERTIES == type)
{
LLAvatarData* avatar_data = static_cast<LLAvatarData*>(data);
if (avatar_data)
{
if (avatar_data->avatar_id != mAvatarId)
{
return;
}
LLAvatarIconIDCache::getInstance()->add(mAvatarId,avatar_data->image_id);
updateFromCache();
}
}
}
void LLAvatarIconCtrl::onAvatarNameCache(const LLUUID& agent_id, const LLAvatarName& av_name)
{
if (agent_id == mAvatarId)
{
// Most avatar icon controls are next to a UI element that shows
// a display name, so only show username.
mFullName = av_name.mUsername;
if (mDrawTooltip)
{
setToolTip(mFullName);
}
else
{
setToolTip(std::string());
}
}
}
<commit_msg>SH-2747 FIX<commit_after>/**
* @file llavatariconctrl.cpp
* @brief LLAvatarIconCtrl class implementation
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llavatariconctrl.h"
// viewer includes
#include "llagent.h"
#include "llavatarconstants.h"
#include "llcallingcard.h" // for LLAvatarTracker
#include "llavataractions.h"
#include "llmenugl.h"
#include "lluictrlfactory.h"
#include "llagentdata.h"
#include "llimfloater.h"
// library includes
#include "llavatarnamecache.h"
#define MENU_ITEM_VIEW_PROFILE 0
#define MENU_ITEM_SEND_IM 1
static LLDefaultChildRegistry::Register<LLAvatarIconCtrl> r("avatar_icon");
bool LLAvatarIconIDCache::LLAvatarIconIDCacheItem::expired()
{
const F64 SEC_PER_DAY_PLUS_HOUR = (24.0 + 1.0) * 60.0 * 60.0;
F64 delta = LLDate::now().secondsSinceEpoch() - cached_time.secondsSinceEpoch();
if (delta > SEC_PER_DAY_PLUS_HOUR)
return true;
return false;
}
void LLAvatarIconIDCache::load ()
{
llinfos << "Loading avatar icon id cache." << llendl;
// build filename for each user
std::string resolved_filename = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, mFilename);
llifstream file(resolved_filename);
if (!file.is_open())
return;
// add each line in the file to the list
int uuid_len = UUID_STR_LENGTH-1;
std::string line;
while (std::getline(file, line))
{
LLUUID avatar_id;
LLUUID icon_id;
LLDate date;
if (line.length()<=uuid_len*2)
continue; // short line, bail out to prevent substr calls throwing exception.
std::string avatar_id_str = line.substr(0,uuid_len);
std::string icon_id_str = line.substr(uuid_len,uuid_len);
std::string date_str = line.substr(uuid_len*2, line.length()-uuid_len*2);
if(!avatar_id.set(avatar_id_str) || !icon_id.set(icon_id_str) || !date.fromString(date_str))
continue;
LLAvatarIconIDCacheItem item = {icon_id,date};
mCache[avatar_id] = item;
}
file.close();
}
void LLAvatarIconIDCache::save ()
{
std::string resolved_filename = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, mFilename);
// open a file for writing
llofstream file (resolved_filename);
if (!file.is_open())
{
llwarns << "can't open avatar icons cache file\"" << mFilename << "\" for writing" << llendl;
return;
}
for(std::map<LLUUID,LLAvatarIconIDCacheItem>::iterator it = mCache.begin();it!=mCache.end();++it)
{
if(!it->second.expired())
{
file << it->first << it->second.icon_id << it->second.cached_time << std::endl;
}
}
file.close();
}
LLUUID* LLAvatarIconIDCache::get (const LLUUID& avatar_id)
{
std::map<LLUUID,LLAvatarIconIDCacheItem>::iterator it = mCache.find(avatar_id);
if(it==mCache.end())
return 0;
if(it->second.expired())
return 0;
return &it->second.icon_id;
}
void LLAvatarIconIDCache::add (const LLUUID& avatar_id,const LLUUID& icon_id)
{
LLAvatarIconIDCacheItem item = {icon_id,LLDate::now()};
mCache[avatar_id] = item;
}
void LLAvatarIconIDCache::remove (const LLUUID& avatar_id)
{
mCache.erase(avatar_id);
}
LLAvatarIconCtrl::Params::Params()
: avatar_id("avatar_id"),
draw_tooltip("draw_tooltip", true),
default_icon_name("default_icon_name")
{
}
LLAvatarIconCtrl::LLAvatarIconCtrl(const LLAvatarIconCtrl::Params& p)
: LLIconCtrl(p),
mDrawTooltip(p.draw_tooltip),
mDefaultIconName(p.default_icon_name)
{
mPriority = LLViewerFetchedTexture::BOOST_ICON;
LLRect rect = p.rect;
mDrawWidth = llmax(32, rect.getWidth()) ;
mDrawHeight = llmax(32, rect.getHeight()) ;
static LLUICachedControl<S32> llavatariconctrl_symbol_hpad("UIAvatariconctrlSymbolHPad", 2);
static LLUICachedControl<S32> llavatariconctrl_symbol_vpad("UIAvatariconctrlSymbolVPad", 2);
static LLUICachedControl<S32> llavatariconctrl_symbol_size("UIAvatariconctrlSymbolSize", 5);
static LLUICachedControl<std::string> llavatariconctrl_symbol_pos("UIAvatariconctrlSymbolPosition", "BottomRight");
// BottomRight is the default position
S32 left = rect.getWidth() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_hpad;
S32 bottom = llavatariconctrl_symbol_vpad;
if ("BottomLeft" == (std::string)llavatariconctrl_symbol_pos)
{
left = llavatariconctrl_symbol_hpad;
bottom = llavatariconctrl_symbol_vpad;
}
else if ("TopLeft" == (std::string)llavatariconctrl_symbol_pos)
{
left = llavatariconctrl_symbol_hpad;
bottom = rect.getHeight() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_vpad;
}
else if ("TopRight" == (std::string)llavatariconctrl_symbol_pos)
{
left = rect.getWidth() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_hpad;
bottom = rect.getHeight() - llavatariconctrl_symbol_size - llavatariconctrl_symbol_vpad;
}
rect.setOriginAndSize(left, bottom, llavatariconctrl_symbol_size, llavatariconctrl_symbol_size);
if (p.avatar_id.isProvided())
{
LLSD value(p.avatar_id);
setValue(value);
}
else
{
LLIconCtrl::setValue(mDefaultIconName);
}
}
LLAvatarIconCtrl::~LLAvatarIconCtrl()
{
if (mAvatarId.notNull())
{
LLAvatarPropertiesProcessor::getInstance()->removeObserver(mAvatarId, this);
// Name callbacks will be automatically disconnected since LLUICtrl is trackable
}
}
//virtual
void LLAvatarIconCtrl::setValue(const LLSD& value)
{
if (value.isUUID())
{
LLAvatarPropertiesProcessor* app =
LLAvatarPropertiesProcessor::getInstance();
if (mAvatarId.notNull())
{
app->removeObserver(mAvatarId, this);
}
if (mAvatarId != value.asUUID())
{
mAvatarId = value.asUUID();
// *BUG: This will return stale icons if a user changes their
// profile picture. However, otherwise we send too many upstream
// AvatarPropertiesRequest messages.
// to get fresh avatar icon use
// LLAvatarIconIDCache::getInstance()->remove(avatar_id);
// Check if cache already contains image_id for that avatar
if (!updateFromCache())
{
// *TODO: Consider getting avatar icon/badge directly from
// People API, rather than sending AvatarPropertyRequest
// messages. People API already hits the user table.
LLIconCtrl::setValue(mDefaultIconName);
app->addObserver(mAvatarId, this);
app->sendAvatarPropertiesRequest(mAvatarId);
}
}
}
else
{
LLIconCtrl::setValue(value);
}
LLAvatarNameCache::get(mAvatarId,
boost::bind(&LLAvatarIconCtrl::onAvatarNameCache,
this, _1, _2));
}
bool LLAvatarIconCtrl::updateFromCache()
{
LLUUID* icon_id_ptr = LLAvatarIconIDCache::getInstance()->get(mAvatarId);
if(!icon_id_ptr)
return false;
const LLUUID& icon_id = *icon_id_ptr;
// Update the avatar
if (icon_id.notNull())
{
LLIconCtrl::setValue(icon_id);
}
else
{
LLIconCtrl::setValue(mDefaultIconName);
}
return true;
}
//virtual
void LLAvatarIconCtrl::processProperties(void* data, EAvatarProcessorType type)
{
if (APT_PROPERTIES == type)
{
LLAvatarData* avatar_data = static_cast<LLAvatarData*>(data);
if (avatar_data)
{
if (avatar_data->avatar_id != mAvatarId)
{
return;
}
LLAvatarIconIDCache::getInstance()->add(mAvatarId,avatar_data->image_id);
updateFromCache();
}
}
}
void LLAvatarIconCtrl::onAvatarNameCache(const LLUUID& agent_id, const LLAvatarName& av_name)
{
if (agent_id == mAvatarId)
{
// Most avatar icon controls are next to a UI element that shows
// a display name, so only show username.
mFullName = av_name.mUsername;
if (mDrawTooltip)
{
setToolTip(mFullName);
}
else
{
setToolTip(std::string());
}
}
}
<|endoftext|>
|
<commit_before>/**
* @file llimconversation.cpp
* @brief LLIMConversation class implements the common behavior of LNearbyChatBar
* @brief and LLIMFloater for hosting both in LLIMContainer
*
* $LicenseInfo:firstyear=2012&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llimconversation.h"
#include "lldraghandle.h"
#include "llfloaterreg.h"
#include "llimfloater.h"
#include "llimfloatercontainer.h" // to replace separate IM Floaters with multifloater container
#include "lllayoutstack.h"
#include "llnearbychat.h"
const F32 REFRESH_INTERVAL = 0.2f;
LLIMConversation::LLIMConversation(const LLUUID& session_id)
: LLTransientDockableFloater(NULL, true, session_id)
, LLEventTimer(REFRESH_INTERVAL)
, mIsP2PChat(false)
, mExpandCollapseBtn(NULL)
, mTearOffBtn(NULL)
, mCloseBtn(NULL)
, mSessionID(session_id)
, mParticipantList(NULL)
{
mCommitCallbackRegistrar.add("IMSession.Menu.Action",
boost::bind(&LLIMConversation::onIMSessionMenuItemClicked, this, _2));
// mCommitCallbackRegistrar.add("IMSession.ExpCollapseBtn.Click",
// boost::bind(&LLIMConversation::onSlide, this));
// mCommitCallbackRegistrar.add("IMSession.CloseBtn.Click",
// boost::bind(&LLFloater::onClickClose, this));
mCommitCallbackRegistrar.add("IMSession.TearOffBtn.Click",
boost::bind(&LLIMConversation::onTearOffClicked, this));
mEnableCallbackRegistrar.add("IMSession.Menu.CompactExpandedModes.CheckItem",
boost::bind(&LLIMConversation::onIMCompactExpandedMenuItemCheck, this, _2));
mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.CheckItem",
boost::bind(&LLIMConversation::onIMShowModesMenuItemCheck, this, _2));
mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.Enable",
boost::bind(&LLIMConversation::onIMShowModesMenuItemEnable, this, _2));
}
LLIMConversation::~LLIMConversation()
{
if (mParticipantList)
{
delete mParticipantList;
mParticipantList = NULL;
}
}
BOOL LLIMConversation::postBuild()
{
mCloseBtn = getChild<LLButton>("close_btn");
mCloseBtn->setCommitCallback(boost::bind(&LLFloater::onClickClose, this));
mExpandCollapseBtn = getChild<LLButton>("expand_collapse_btn");
mExpandCollapseBtn->setClickedCallback(boost::bind(&LLIMConversation::onSlide, this));
mParticipantListPanel = getChild<LLLayoutPanel>("speakers_list_panel");
mTearOffBtn = getChild<LLButton>("tear_off_btn");
mTearOffBtn->setCommitCallback(boost::bind(&LLIMConversation::onTearOffClicked, this));
if (!getTornOff())
{
setOpenPositioning(LLFloaterEnums::POSITIONING_RELATIVE);
}
buildParticipantList();
if (isChatMultiTab())
{
return LLFloater::postBuild();
}
else
{
return LLDockableFloater::postBuild();
}
}
BOOL LLIMConversation::tick()
{
// This check is needed until LLFloaterReg::removeInstance() is synchronized with deleting the floater
// via LLMortician::updateClass(), to avoid calling dead instances. See LLFloater::destroy().
if (isDead()) return false;
// Need to resort the participant list if it's in sort by recent speaker order.
if (mParticipantList)
{
mParticipantList->update();
}
return false;
}
void LLIMConversation::buildParticipantList()
{ if (mIsNearbyChat)
{
}
else
{
// for group and ad-hoc chat we need to include agent into list
if(!mIsP2PChat && !mParticipantList && mSessionID.notNull())
{
LLSpeakerMgr* speaker_manager = LLIMModel::getInstance()->getSpeakerManager(mSessionID);
mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
}
}
}
void LLIMConversation::onSortMenuItemClicked(const LLSD& userdata)
{
// TODO: Check this code when sort order menu will be added. (EM)
if (!mParticipantList)
{
return;
}
std::string chosen_item = userdata.asString();
if (chosen_item == "sort_name")
{
mParticipantList->setSortOrder(LLParticipantList::E_SORT_BY_NAME);
}
}
void LLIMConversation::onIMSessionMenuItemClicked(const LLSD& userdata)
{
std::string item = userdata.asString();
if (item == "compact_view" || item == "expanded_view")
{
gSavedSettings.setBOOL("PlainTextChatHistory", item == "compact_view");
}
else
{
bool prev_value = gSavedSettings.getBOOL(item);
gSavedSettings.setBOOL(item, !prev_value);
}
LLIMConversation::processChatHistoryStyleUpdate();
}
bool LLIMConversation::onIMCompactExpandedMenuItemCheck(const LLSD& userdata)
{
std::string item = userdata.asString();
bool is_plain_text_mode = gSavedSettings.getBOOL("PlainTextChatHistory");
return is_plain_text_mode? item == "compact_view" : item == "expanded_view";
}
bool LLIMConversation::onIMShowModesMenuItemCheck(const LLSD& userdata)
{
return gSavedSettings.getBOOL(userdata.asString());
}
// enable/disable states for the "show time" and "show names" items of the show-modes menu
bool LLIMConversation::onIMShowModesMenuItemEnable(const LLSD& userdata)
{
std::string item = userdata.asString();
bool plain_text = gSavedSettings.getBOOL("PlainTextChatHistory");
bool is_not_names = (item != "IMShowNamesForP2PConv");
return (plain_text && (is_not_names || mIsP2PChat));
}
void LLIMConversation::updateHeaderAndToolbar()
{
bool is_hosted = getHost() != NULL;
if (is_hosted)
{
for (S32 i = 0; i < BUTTON_COUNT; i++)
{
if (mButtons[i])
{
// Hide the standard header buttons in a docked IM floater.
mButtons[i]->setVisible(false);
}
}
}
// Participant list should be visible only in torn off floaters.
bool is_participant_list_visible =
!is_hosted
&& gSavedSettings.getBOOL("IMShowControlPanel")
&& !mIsP2PChat
&& !mIsNearbyChat; // *TODO: temporarily disabled for Nearby chat
mParticipantListPanel->setVisible(is_participant_list_visible);
// Display collapse image (<<) if the floater is hosted
// or if it is torn off but has an open control panel.
bool is_expanded = is_hosted || is_participant_list_visible;
mExpandCollapseBtn->setImageOverlay(getString(is_expanded ? "collapse_icon" : "expand_icon"));
// The button (>>) should be disabled for torn off P2P conversations.
mExpandCollapseBtn->setEnabled(is_hosted || !mIsP2PChat && !mIsNearbyChat);
if (mDragHandle)
{
// toggle floater's drag handle and title visibility
mDragHandle->setVisible(!is_hosted);
}
mTearOffBtn->setImageOverlay(getString(is_hosted ? "tear_off_icon" : "return_icon"));
mCloseBtn->setVisible(is_hosted);
enableDisableCallBtn();
showTranslationCheckbox();
}
void LLIMConversation::showTranslationCheckbox(BOOL show)
{
getChild<LLUICtrl>("translate_chat_checkbox_lp")->setVisible(mIsNearbyChat? show : FALSE);
}
// static
void LLIMConversation::processChatHistoryStyleUpdate()
{
LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("impanel");
for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin();
iter != inst_list.end(); ++iter)
{
LLIMFloater* floater = dynamic_cast<LLIMFloater*>(*iter);
if (floater)
{
floater->reloadMessages();
}
}
LLNearbyChat* nearby_chat = LLNearbyChat::getInstance();
if (nearby_chat)
{
nearby_chat->reloadMessages();
}
}
void LLIMConversation::updateCallBtnState(bool callIsActive)
{
getChild<LLButton>("voice_call_btn")->setImageOverlay(
callIsActive? getString("call_btn_stop") : getString("call_btn_start"));
enableDisableCallBtn();
}
void LLIMConversation::onSlide(LLIMConversation* self)
{
LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(self->getHost());
if (host_floater)
{
// Hide the messages pane if a floater is hosted in the Conversations
host_floater->collapseMessagesPane(true);
}
else ///< floater is torn off
{
if (!self->mIsP2PChat)
{
bool expand = !self->mParticipantListPanel->getVisible();
// Expand/collapse the IM control panel
self->mParticipantListPanel->setVisible(expand);
gSavedSettings.setBOOL("IMShowControlPanel", expand);
self->mExpandCollapseBtn->setImageOverlay(self->getString(expand ? "collapse_icon" : "expand_icon"));
}
}
}
/*virtual*/
void LLIMConversation::onOpen(const LLSD& key)
{
LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(getHost());
if (host_floater)
{
// Show the messages pane when opening a floater hosted in the Conversations
host_floater->collapseMessagesPane(false);
}
updateHeaderAndToolbar();
}
void LLIMConversation::onTearOffClicked()
{
onClickTearOff(this);
updateHeaderAndToolbar();
}
// static
bool LLIMConversation::isChatMultiTab()
{
// Restart is required in order to change chat window type.
return true;
}
<commit_msg>CHUI-149 [WIP] Add the participant list to the nearby chat as IM-conversation<commit_after>/**
* @file llimconversation.cpp
* @brief LLIMConversation class implements the common behavior of LNearbyChatBar
* @brief and LLIMFloater for hosting both in LLIMContainer
*
* $LicenseInfo:firstyear=2012&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llimconversation.h"
#include "lldraghandle.h"
#include "llfloaterreg.h"
#include "llimfloater.h"
#include "llimfloatercontainer.h" // to replace separate IM Floaters with multifloater container
#include "lllayoutstack.h"
#include "llnearbychat.h"
const F32 REFRESH_INTERVAL = 0.2f;
LLIMConversation::LLIMConversation(const LLUUID& session_id)
: LLTransientDockableFloater(NULL, true, session_id)
, LLEventTimer(REFRESH_INTERVAL)
, mIsP2PChat(false)
, mExpandCollapseBtn(NULL)
, mTearOffBtn(NULL)
, mCloseBtn(NULL)
, mSessionID(session_id)
, mParticipantList(NULL)
{
mCommitCallbackRegistrar.add("IMSession.Menu.Action",
boost::bind(&LLIMConversation::onIMSessionMenuItemClicked, this, _2));
// mCommitCallbackRegistrar.add("IMSession.ExpCollapseBtn.Click",
// boost::bind(&LLIMConversation::onSlide, this));
// mCommitCallbackRegistrar.add("IMSession.CloseBtn.Click",
// boost::bind(&LLFloater::onClickClose, this));
mCommitCallbackRegistrar.add("IMSession.TearOffBtn.Click",
boost::bind(&LLIMConversation::onTearOffClicked, this));
mEnableCallbackRegistrar.add("IMSession.Menu.CompactExpandedModes.CheckItem",
boost::bind(&LLIMConversation::onIMCompactExpandedMenuItemCheck, this, _2));
mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.CheckItem",
boost::bind(&LLIMConversation::onIMShowModesMenuItemCheck, this, _2));
mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.Enable",
boost::bind(&LLIMConversation::onIMShowModesMenuItemEnable, this, _2));
}
LLIMConversation::~LLIMConversation()
{
if (mParticipantList)
{
delete mParticipantList;
mParticipantList = NULL;
}
}
BOOL LLIMConversation::postBuild()
{
mCloseBtn = getChild<LLButton>("close_btn");
mCloseBtn->setCommitCallback(boost::bind(&LLFloater::onClickClose, this));
mExpandCollapseBtn = getChild<LLButton>("expand_collapse_btn");
mExpandCollapseBtn->setClickedCallback(boost::bind(&LLIMConversation::onSlide, this));
mParticipantListPanel = getChild<LLLayoutPanel>("speakers_list_panel");
mTearOffBtn = getChild<LLButton>("tear_off_btn");
mTearOffBtn->setCommitCallback(boost::bind(&LLIMConversation::onTearOffClicked, this));
if (!getTornOff())
{
setOpenPositioning(LLFloaterEnums::POSITIONING_RELATIVE);
}
buildParticipantList();
if (isChatMultiTab())
{
return LLFloater::postBuild();
}
else
{
return LLDockableFloater::postBuild();
}
}
BOOL LLIMConversation::tick()
{
// This check is needed until LLFloaterReg::removeInstance() is synchronized with deleting the floater
// via LLMortician::updateClass(), to avoid calling dead instances. See LLFloater::destroy().
if (isDead()) return false;
// Need to resort the participant list if it's in sort by recent speaker order.
if (mParticipantList)
{
mParticipantList->update();
}
return false;
}
void LLIMConversation::buildParticipantList()
{
if (mIsNearbyChat)
{
LLLocalSpeakerMgr* speaker_manager = LLLocalSpeakerMgr::getInstance();
mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
}
else
{
// for group and ad-hoc chat we need to include agent into list
if(!mIsP2PChat && !mParticipantList && mSessionID.notNull())
{
LLSpeakerMgr* speaker_manager = LLIMModel::getInstance()->getSpeakerManager(mSessionID);
mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false);
}
}
}
void LLIMConversation::onSortMenuItemClicked(const LLSD& userdata)
{
// TODO: Check this code when sort order menu will be added. (EM)
if (!mParticipantList)
{
return;
}
std::string chosen_item = userdata.asString();
if (chosen_item == "sort_name")
{
mParticipantList->setSortOrder(LLParticipantList::E_SORT_BY_NAME);
}
}
void LLIMConversation::onIMSessionMenuItemClicked(const LLSD& userdata)
{
std::string item = userdata.asString();
if (item == "compact_view" || item == "expanded_view")
{
gSavedSettings.setBOOL("PlainTextChatHistory", item == "compact_view");
}
else
{
bool prev_value = gSavedSettings.getBOOL(item);
gSavedSettings.setBOOL(item, !prev_value);
}
LLIMConversation::processChatHistoryStyleUpdate();
}
bool LLIMConversation::onIMCompactExpandedMenuItemCheck(const LLSD& userdata)
{
std::string item = userdata.asString();
bool is_plain_text_mode = gSavedSettings.getBOOL("PlainTextChatHistory");
return is_plain_text_mode? item == "compact_view" : item == "expanded_view";
}
bool LLIMConversation::onIMShowModesMenuItemCheck(const LLSD& userdata)
{
return gSavedSettings.getBOOL(userdata.asString());
}
// enable/disable states for the "show time" and "show names" items of the show-modes menu
bool LLIMConversation::onIMShowModesMenuItemEnable(const LLSD& userdata)
{
std::string item = userdata.asString();
bool plain_text = gSavedSettings.getBOOL("PlainTextChatHistory");
bool is_not_names = (item != "IMShowNamesForP2PConv");
return (plain_text && (is_not_names || mIsP2PChat));
}
void LLIMConversation::updateHeaderAndToolbar()
{
bool is_hosted = getHost() != NULL;
if (is_hosted)
{
for (S32 i = 0; i < BUTTON_COUNT; i++)
{
if (mButtons[i])
{
// Hide the standard header buttons in a docked IM floater.
mButtons[i]->setVisible(false);
}
}
}
// Participant list should be visible only in torn off floaters.
bool is_participant_list_visible =
!is_hosted
&& gSavedSettings.getBOOL("IMShowControlPanel")
&& !mIsP2PChat;
mParticipantListPanel->setVisible(is_participant_list_visible);
// Display collapse image (<<) if the floater is hosted
// or if it is torn off but has an open control panel.
bool is_expanded = is_hosted || is_participant_list_visible;
mExpandCollapseBtn->setImageOverlay(getString(is_expanded ? "collapse_icon" : "expand_icon"));
// The button (>>) should be disabled for torn off P2P conversations.
mExpandCollapseBtn->setEnabled(is_hosted || !mIsP2PChat);
if (mDragHandle)
{
// toggle floater's drag handle and title visibility
mDragHandle->setVisible(!is_hosted);
}
mTearOffBtn->setImageOverlay(getString(is_hosted ? "tear_off_icon" : "return_icon"));
mCloseBtn->setVisible(is_hosted);
enableDisableCallBtn();
showTranslationCheckbox();
}
void LLIMConversation::showTranslationCheckbox(BOOL show)
{
getChild<LLUICtrl>("translate_chat_checkbox_lp")->setVisible(mIsNearbyChat? show : FALSE);
}
// static
void LLIMConversation::processChatHistoryStyleUpdate()
{
LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("impanel");
for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin();
iter != inst_list.end(); ++iter)
{
LLIMFloater* floater = dynamic_cast<LLIMFloater*>(*iter);
if (floater)
{
floater->reloadMessages();
}
}
LLNearbyChat* nearby_chat = LLNearbyChat::getInstance();
if (nearby_chat)
{
nearby_chat->reloadMessages();
}
}
void LLIMConversation::updateCallBtnState(bool callIsActive)
{
getChild<LLButton>("voice_call_btn")->setImageOverlay(
callIsActive? getString("call_btn_stop") : getString("call_btn_start"));
enableDisableCallBtn();
}
void LLIMConversation::onSlide(LLIMConversation* self)
{
LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(self->getHost());
if (host_floater)
{
// Hide the messages pane if a floater is hosted in the Conversations
host_floater->collapseMessagesPane(true);
}
else ///< floater is torn off
{
if (!self->mIsP2PChat)
{
bool expand = !self->mParticipantListPanel->getVisible();
// Expand/collapse the IM control panel
self->mParticipantListPanel->setVisible(expand);
gSavedSettings.setBOOL("IMShowControlPanel", expand);
self->mExpandCollapseBtn->setImageOverlay(self->getString(expand ? "collapse_icon" : "expand_icon"));
}
}
}
/*virtual*/
void LLIMConversation::onOpen(const LLSD& key)
{
LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(getHost());
if (host_floater)
{
// Show the messages pane when opening a floater hosted in the Conversations
host_floater->collapseMessagesPane(false);
}
updateHeaderAndToolbar();
}
void LLIMConversation::onTearOffClicked()
{
onClickTearOff(this);
updateHeaderAndToolbar();
}
// static
bool LLIMConversation::isChatMultiTab()
{
// Restart is required in order to change chat window type.
return true;
}
<|endoftext|>
|
<commit_before>// #define PY_SSIZE_T_CLEAN 1
#include <Python.h>
#include <bytesobject.h>
#include "tlsh.h"
#define TLSH_VERSION "0.2.0"
#define AUTHOR "Chun Cheng"
/* We want to update the hash using bytes object in Python 3 */
#if PY_MAJOR_VERSION >= 3
# define BYTES_VALUE_CHAR "y"
#else
# define BYTES_VALUE_CHAR "s"
#endif
#define MIN_TLSH_LEN 512
static char tlsh_doc[] =
"TLSH C version - similarity matching and searching";
static char tlsh_hash_doc[] =
"tlsh.hash(data)\n\n\
returns tlsh hexadecimal representation (string)";
static char tlsh_diff_doc[] =
"tlsh.diff(hash1, hash2)\n\n\
returns tlsh score (integer)";
static char tlsh_diffxlen_doc[] =
"tlsh.diffxlen(hash1, hash2) - ignore object lengths\n\n\
returns tlsh score (integer)";
// hash(data) returns byte buffer
static PyObject* hash_py(PyObject* self, PyObject* args) {
unsigned char* pBuffer;
int len;
if (!PyArg_ParseTuple(args, BYTES_VALUE_CHAR "#", &pBuffer, &len)) {
return NULL;
}
Tlsh tlsh;
tlsh.update(pBuffer, len);
tlsh.final();
const char *s = tlsh.getHash();
return Py_BuildValue("s", s);
}
// diff(hash1, hash2) returns integer
static PyObject* diff_py(PyObject* self, PyObject* args) {
char *hash1, *hash2;
if (!PyArg_ParseTuple(args, "ss", &hash1, &hash2)) {
return NULL;
}
Tlsh tlsh1, tlsh2;
tlsh1.fromTlshStr(hash1);
tlsh2.fromTlshStr(hash2);
int score = tlsh1.totalDiff(&tlsh2);
return Py_BuildValue("i", score);
}
//diffxlen(hash1, hash2) returns integer
static PyObject* diffxlen_py(PyObject* self, PyObject* args) {
char *hash1, *hash2;
if (!PyArg_ParseTuple(args, "ss", &hash1, &hash2)) {
return NULL;
}
Tlsh tlsh1, tlsh2;
tlsh1.fromTlshStr(hash1);
tlsh2.fromTlshStr(hash2);
int score = tlsh1.totalDiff(&tlsh2, false);
return Py_BuildValue("i", score);
}
// The module's methods
static PyMethodDef tlsh_methods[] =
{
{ "hash", hash_py, METH_VARARGS, tlsh_hash_doc },
{ "diff", diff_py, METH_VARARGS, tlsh_diff_doc },
{ "diffxlen", diffxlen_py, METH_VARARGS, tlsh_diffxlen_doc },
{ NULL, NULL } /* sentinel */
};
typedef struct {
PyObject_HEAD
unsigned short required_data;
bool finalized;
Tlsh tlsh;
} tlsh_TlshObject;
static PyObject * Tlsh_update(tlsh_TlshObject *, PyObject *);
static PyObject * Tlsh_final(tlsh_TlshObject *);
static PyObject * Tlsh_hexdigest(tlsh_TlshObject *);
static PyObject * Tlsh_diff(tlsh_TlshObject *, PyObject *);
static PyMethodDef Tlsh_methods[] = {
{"update", (PyCFunction) Tlsh_update, METH_VARARGS,
"Update the TLSH with the given string."
},
{"final", (PyCFunction) Tlsh_final, METH_NOARGS,
"Signal that no more data will be added. This is required before reading the hash."
},
{"hexdigest", (PyCFunction) Tlsh_hexdigest, METH_NOARGS,
"Get the computed TLSH as a string object containing only hexadecimal digits."
},
{"diff", (PyCFunction) Tlsh_diff, METH_VARARGS,
"Returns the TLSH score compared to the given Tlsh object or hexadecimal string."
},
{NULL} /* Sentinel */
};
static PyTypeObject tlsh_TlshType = {
PyObject_HEAD_INIT(NULL)
#if PY_MAJOR_VERSION < 3
0, /* ob_size */
#endif
"tlsh.Tlsh", /* tp_name */
sizeof(tlsh_TlshObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"TLSH objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Tlsh_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static PyObject *
Tlsh_update(tlsh_TlshObject *self, PyObject *args)
{
const char *str;
Py_ssize_t len;
if (!PyArg_ParseTuple(args, BYTES_VALUE_CHAR "#", &str, &len))
return NULL;
if (self->finalized) {
PyErr_SetString(PyExc_ValueError, "final() has already been called");
return NULL;
}
if (self->required_data < MIN_TLSH_LEN) {
self->required_data += len > MIN_TLSH_LEN ? MIN_TLSH_LEN : len;
}
self->tlsh.update((unsigned char *) str, (unsigned int) len);
Py_RETURN_NONE;
}
static PyObject *
Tlsh_final(tlsh_TlshObject *self)
{
if (self->finalized) {
PyErr_SetString(PyExc_ValueError, "final() has already been called");
return NULL;
}
if (self->required_data < MIN_TLSH_LEN) {
return PyErr_Format(PyExc_ValueError, "less than %u of input", MIN_TLSH_LEN);
}
self->finalized = true;
self->tlsh.final();
Py_RETURN_NONE;
}
static PyObject *
Tlsh_hexdigest(tlsh_TlshObject *self)
{
char hash[TLSH_STRING_LEN + 1];
if (!self->finalized) {
PyErr_SetString(PyExc_ValueError, "final() has not been called");
return NULL;
}
self->tlsh.getHash(hash, TLSH_STRING_LEN + 1);
if (hash[0] == '\0') {
PyErr_SetString(PyExc_ValueError, "error while getting hash (not enough entropy?)");
return NULL;
}
return Py_BuildValue("s", hash);
}
static PyObject *
Tlsh_diff(tlsh_TlshObject *self, PyObject *args)
{
PyObject *arg;
int score;
if (PyTuple_Size(args) != 1)
return PyErr_Format(PyExc_TypeError, "function takes exactly 1 argument (%lu given)", PyTuple_Size(args));
arg = PyTuple_GetItem(args, 0);
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(arg)) {
if ((arg = PyUnicode_AsASCIIString(arg)) == NULL) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
#else
if (PyString_Check(arg)) {
#endif
char *str;
Py_ssize_t len;
Tlsh other;
if (PyBytes_AsStringAndSize(arg, &str, &len) == -1) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
if (len != TLSH_STRING_LEN) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
if (other.fromTlshStr(str) != 0) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
score = self->tlsh.totalDiff(&other);
} else if (PyObject_TypeCheck(arg, &tlsh_TlshType)) {
tlsh_TlshObject * other_tlsh = (tlsh_TlshObject *) arg;
score = self->tlsh.totalDiff(&other_tlsh->tlsh);
} else {
PyErr_SetString(PyExc_ValueError, "argument is neither a Tlsh object nor a TLSH hex string");
return NULL;
}
return Py_BuildValue("i", score);
}
// Initializes the module
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"tlsh", /* m_name */
tlsh_doc, /* m_doc */
-1, /* m_size */
tlsh_methods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_tlsh(void)
{
PyObject *module;
tlsh_TlshType.tp_new = PyType_GenericNew;
if (PyType_Ready(&tlsh_TlshType) < 0)
return NULL;
module = PyModule_Create(&moduledef);
PyModule_AddStringConstant(module,
"__version__",
TLSH_VERSION);
PyModule_AddStringConstant(module,
"__author__",
AUTHOR);
Py_INCREF(&tlsh_TlshType);
PyModule_AddObject(module, "Tlsh", (PyObject *) &tlsh_TlshType);
return module;
}
#else
PyMODINIT_FUNC inittlsh(void)
{
PyObject *module;
tlsh_TlshType.tp_new = PyType_GenericNew;
if (PyType_Ready(&tlsh_TlshType) < 0)
return;
module = Py_InitModule3("tlsh",
tlsh_methods,
tlsh_doc);
PyModule_AddStringConstant(module,
"__version__",
TLSH_VERSION);
PyModule_AddStringConstant(module,
"__author__",
AUTHOR);
Py_INCREF(&tlsh_TlshType);
PyModule_AddObject(module, "Tlsh", (PyObject *) &tlsh_TlshType);
}
#endif
<commit_msg>Pick up fix from lunar@debian.org<commit_after>#define PY_SSIZE_T_CLEAN 1
#include <Python.h>
#include <bytesobject.h>
#include "tlsh.h"
#define TLSH_VERSION "0.2.0"
#define AUTHOR "Chun Cheng"
/* We want to update the hash using bytes object in Python 3 */
#if PY_MAJOR_VERSION >= 3
# define BYTES_VALUE_CHAR "y"
#else
# define BYTES_VALUE_CHAR "s"
#endif
#define MIN_TLSH_LEN 512
static char tlsh_doc[] =
"TLSH C version - similarity matching and searching";
static char tlsh_hash_doc[] =
"tlsh.hash(data)\n\n\
returns tlsh hexadecimal representation (string)";
static char tlsh_diff_doc[] =
"tlsh.diff(hash1, hash2)\n\n\
returns tlsh score (integer)";
static char tlsh_diffxlen_doc[] =
"tlsh.diffxlen(hash1, hash2) - ignore object lengths\n\n\
returns tlsh score (integer)";
// hash(data) returns byte buffer
static PyObject* hash_py(PyObject* self, PyObject* args) {
unsigned char* pBuffer;
Py_ssize_t len;
if (!PyArg_ParseTuple(args, BYTES_VALUE_CHAR "#", &pBuffer, &len)) {
return NULL;
}
Tlsh tlsh;
tlsh.update(pBuffer, len);
tlsh.final();
const char *s = tlsh.getHash();
return Py_BuildValue("s", s);
}
// diff(hash1, hash2) returns integer
static PyObject* diff_py(PyObject* self, PyObject* args) {
char *hash1, *hash2;
if (!PyArg_ParseTuple(args, "ss", &hash1, &hash2)) {
return NULL;
}
Tlsh tlsh1, tlsh2;
tlsh1.fromTlshStr(hash1);
tlsh2.fromTlshStr(hash2);
int score = tlsh1.totalDiff(&tlsh2);
return Py_BuildValue("i", score);
}
//diffxlen(hash1, hash2) returns integer
static PyObject* diffxlen_py(PyObject* self, PyObject* args) {
char *hash1, *hash2;
if (!PyArg_ParseTuple(args, "ss", &hash1, &hash2)) {
return NULL;
}
Tlsh tlsh1, tlsh2;
tlsh1.fromTlshStr(hash1);
tlsh2.fromTlshStr(hash2);
int score = tlsh1.totalDiff(&tlsh2, false);
return Py_BuildValue("i", score);
}
// The module's methods
static PyMethodDef tlsh_methods[] =
{
{ "hash", hash_py, METH_VARARGS, tlsh_hash_doc },
{ "diff", diff_py, METH_VARARGS, tlsh_diff_doc },
{ "diffxlen", diffxlen_py, METH_VARARGS, tlsh_diffxlen_doc },
{ NULL, NULL } /* sentinel */
};
typedef struct {
PyObject_HEAD
unsigned short required_data;
bool finalized;
Tlsh tlsh;
} tlsh_TlshObject;
static PyObject * Tlsh_update(tlsh_TlshObject *, PyObject *);
static PyObject * Tlsh_final(tlsh_TlshObject *);
static PyObject * Tlsh_hexdigest(tlsh_TlshObject *);
static PyObject * Tlsh_diff(tlsh_TlshObject *, PyObject *);
static PyMethodDef Tlsh_methods[] = {
{"update", (PyCFunction) Tlsh_update, METH_VARARGS,
"Update the TLSH with the given string."
},
{"final", (PyCFunction) Tlsh_final, METH_NOARGS,
"Signal that no more data will be added. This is required before reading the hash."
},
{"hexdigest", (PyCFunction) Tlsh_hexdigest, METH_NOARGS,
"Get the computed TLSH as a string object containing only hexadecimal digits."
},
{"diff", (PyCFunction) Tlsh_diff, METH_VARARGS,
"Returns the TLSH score compared to the given Tlsh object or hexadecimal string."
},
{NULL} /* Sentinel */
};
static PyTypeObject tlsh_TlshType = {
PyObject_HEAD_INIT(NULL)
#if PY_MAJOR_VERSION < 3
0, /* ob_size */
#endif
"tlsh.Tlsh", /* tp_name */
sizeof(tlsh_TlshObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"TLSH objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Tlsh_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static PyObject *
Tlsh_update(tlsh_TlshObject *self, PyObject *args)
{
const char *str;
Py_ssize_t len;
if (!PyArg_ParseTuple(args, BYTES_VALUE_CHAR "#", &str, &len))
return NULL;
if (self->finalized) {
PyErr_SetString(PyExc_ValueError, "final() has already been called");
return NULL;
}
if (self->required_data < MIN_TLSH_LEN) {
self->required_data += len > MIN_TLSH_LEN ? MIN_TLSH_LEN : len;
}
self->tlsh.update((unsigned char *) str, (unsigned int) len);
Py_RETURN_NONE;
}
static PyObject *
Tlsh_final(tlsh_TlshObject *self)
{
if (self->finalized) {
PyErr_SetString(PyExc_ValueError, "final() has already been called");
return NULL;
}
if (self->required_data < MIN_TLSH_LEN) {
return PyErr_Format(PyExc_ValueError, "less than %u of input", MIN_TLSH_LEN);
}
self->finalized = true;
self->tlsh.final();
Py_RETURN_NONE;
}
static PyObject *
Tlsh_hexdigest(tlsh_TlshObject *self)
{
char hash[TLSH_STRING_LEN + 1];
if (!self->finalized) {
PyErr_SetString(PyExc_ValueError, "final() has not been called");
return NULL;
}
self->tlsh.getHash(hash, TLSH_STRING_LEN + 1);
if (hash[0] == '\0') {
PyErr_SetString(PyExc_ValueError, "error while getting hash (not enough entropy?)");
return NULL;
}
return Py_BuildValue("s", hash);
}
static PyObject *
Tlsh_diff(tlsh_TlshObject *self, PyObject *args)
{
PyObject *arg;
int score;
if (PyTuple_Size(args) != 1)
return PyErr_Format(PyExc_TypeError, "function takes exactly 1 argument (%lu given)", PyTuple_Size(args));
arg = PyTuple_GetItem(args, 0);
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(arg)) {
if ((arg = PyUnicode_AsASCIIString(arg)) == NULL) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
#else
if (PyString_Check(arg)) {
#endif
char *str;
Py_ssize_t len;
Tlsh other;
if (PyBytes_AsStringAndSize(arg, &str, &len) == -1) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
if (len != TLSH_STRING_LEN) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
if (other.fromTlshStr(str) != 0) {
PyErr_SetString(PyExc_ValueError, "argument is not a TLSH hex string");
return NULL;
}
score = self->tlsh.totalDiff(&other);
} else if (PyObject_TypeCheck(arg, &tlsh_TlshType)) {
tlsh_TlshObject * other_tlsh = (tlsh_TlshObject *) arg;
score = self->tlsh.totalDiff(&other_tlsh->tlsh);
} else {
PyErr_SetString(PyExc_ValueError, "argument is neither a Tlsh object nor a TLSH hex string");
return NULL;
}
return Py_BuildValue("i", score);
}
// Initializes the module
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"tlsh", /* m_name */
tlsh_doc, /* m_doc */
-1, /* m_size */
tlsh_methods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_tlsh(void)
{
PyObject *module;
tlsh_TlshType.tp_new = PyType_GenericNew;
if (PyType_Ready(&tlsh_TlshType) < 0)
return NULL;
module = PyModule_Create(&moduledef);
PyModule_AddStringConstant(module,
"__version__",
TLSH_VERSION);
PyModule_AddStringConstant(module,
"__author__",
AUTHOR);
Py_INCREF(&tlsh_TlshType);
PyModule_AddObject(module, "Tlsh", (PyObject *) &tlsh_TlshType);
return module;
}
#else
PyMODINIT_FUNC inittlsh(void)
{
PyObject *module;
tlsh_TlshType.tp_new = PyType_GenericNew;
if (PyType_Ready(&tlsh_TlshType) < 0)
return;
module = Py_InitModule3("tlsh",
tlsh_methods,
tlsh_doc);
PyModule_AddStringConstant(module,
"__version__",
TLSH_VERSION);
PyModule_AddStringConstant(module,
"__author__",
AUTHOR);
Py_INCREF(&tlsh_TlshType);
PyModule_AddObject(module, "Tlsh", (PyObject *) &tlsh_TlshType);
}
#endif
<|endoftext|>
|
<commit_before>//mbind header
//Copyright (c) 2014 mmYYmmdd
#if !defined MMYYMMDD_MBIND_INCLUDED
#define MMYYMMDD_MBIND_INCLUDED
#include <type_traits>
#include <utility>
// Metaなbind mbind
namespace mymd {
namespace detail_mbind {
//-----------------------------------------------
// default converter
template <typename T>
struct no_cnv { using type = T; };
//-----------------------------------------------
// placeholder
template <template <typename> class...convert>
struct _X_ {
template <template <typename> class...a>
using append = _X_<convert..., a...>;
};
//-----------------------------------------------
template <typename>
struct voiD_t { using type = void; };
//-----------------------------------------------
template <typename T, typename = void>
struct has_type { using type = T; };
template <typename T>
struct has_type<T, typename voiD_t<typename T::type>::type>
{ using type = typename T::type; };
//-----------------------------------------------
template <template <typename> class...> struct type_convert;
template <>
struct type_convert<> { // workaround for VC
template <typename V>
using apply = V;
};
template <template <typename> class C>
struct type_convert<C> {
template <typename V>
using apply = typename has_type<C<V>>::type;
};
template <template <typename> class first, template <typename> class...tail>
struct type_convert<first, tail...> {
template <typename V>
using apply = typename has_type<first<typename type_convert<tail...>::template apply<V>>>::type;
};
//-----------------------------------------------
template <typename T>
struct if_placeholder { static const std::size_t value = 0; };
template <template <typename> class...C>
struct if_placeholder<_X_<C...>> { static const std::size_t value = 1; };
//-----------------------------------------------
template <typename...> struct count_placeholders;
template <typename first, typename...tail>
struct count_placeholders<first, tail...>
{ static const std::size_t value = if_placeholder<first>::value + count_placeholders<tail...>::value; };
template <>
struct count_placeholders<>
{ static const std::size_t value = 0; };
//-----------------------------------------------
template <typename T>
struct trap_placeholder {
static const bool value = false;
template <typename>
using convert = T; //not convert
};
template <template <typename> class...C>
struct trap_placeholder<_X_<C...>> {
static const bool value = true;
template <typename V>
using convert = typename type_convert<C...>::template apply<V>; //convert
};
//-----------------------------------------------
template <typename...> struct packeR { };
//-----------------------------------------------
template <typename, typename, typename = packeR<>> struct employ_placeholder;
template <typename T1, typename...T2, typename V1, typename... V2, typename...R>
struct employ_placeholder<packeR<T1, T2...>, packeR<V1, V2...>, packeR<R...>> {
using result = packeR<R...>;
using alt_t = typename trap_placeholder<T1>::template convert<V1>;
using base_v = typename std::conditional<trap_placeholder<T1>::value, packeR<V2...>, packeR<V1, V2...>>::type;
using base_t = employ_placeholder<packeR<T2...>, base_v, packeR<R..., alt_t>>;
using type = typename base_t::type;
};
template <typename V1, typename...V2, typename...R>
struct employ_placeholder<packeR<>, packeR<V1, V2...>, packeR<R...>>
{ using type = packeR<R...>; };
template <typename...T, typename...R>
struct employ_placeholder<packeR<T...>, packeR<>, packeR<R...>>
{ using type = packeR<R..., T...>; };
//-----------------------------------------------
template <template <typename...> class, typename> struct m_pack;
template <template <typename...> class M, typename...V>
struct m_pack<M, packeR<V...>>
{ using type = M<V...>; };
//-----------------------------------------------
template <typename left, typename right>
struct mbind_or {
static_assert(left::n_placeholders == right::n_placeholders, "mbind_or");
static const std::size_t n_placeholders = left::n_placeholders;
template <typename... V>
struct apply {
static constexpr bool value = left::template apply<V...>::value || right::template apply<V...>::value;
};
};
//------------
template <typename left, typename right>
struct mbind_and {
static_assert(left::n_placeholders == right::n_placeholders, "mbind_and");
static const std::size_t n_placeholders = left::n_placeholders;
template <typename... V>
struct apply {
static constexpr bool value = left::template apply<V...>::value && right::template apply<V...>::value;
};
};
//------------
template <typename T>
struct mbind_not {
static const std::size_t n_placeholders = T::n_placeholders;
template <typename... V>
struct apply {
static constexpr bool value = !T::template apply<V...>::value;
};
};
} //detail_mbind
using detail_mbind::_X_;
using _x_ = detail_mbind::_X_<detail_mbind::no_cnv>;
using _xrr_ = detail_mbind::_X_<std::remove_reference>;
using _xrcv_ = detail_mbind::_X_<std::remove_cv>;
using _xrcvr_ = detail_mbind::_X_<std::remove_cv, std::remove_reference>;
using _xdecay_ = detail_mbind::_X_<std::decay>;
template <template <typename...> class M, typename... binder>
class mbind {
template <typename... V>
using S = typename detail_mbind::employ_placeholder<detail_mbind::packeR<binder...>, detail_mbind::packeR<V...>>::type;
public:
static const std::size_t n_placeholders = detail_mbind::count_placeholders<binder...>::value;
template <typename... V>
using apply = typename detail_mbind::m_pack<M, S<V...>>::type;
template <typename... B>
using bind = mbind<M, binder..., B...>;
template <typename... B>
using rebind = mbind<M, B...>;
template <template <typename...> class M2>
using change = mbind<M2, binder...>;
};
//-------------------------------------------------
namespace detail_mbind {
template <typename T, typename = packeR<>, std::size_t C = T::n_placeholders> struct _x_supply;
template <typename T, typename... R, std::size_t C>
struct _x_supply<T, packeR<R...>, C> {
using type = typename _x_supply<T, packeR<_x_, R...>, C-1>::type;
};
template <typename T, typename... R>
struct _x_supply<T, packeR<R...>, 0> {
using type = mbind<T::template apply, R...>;
};
} //detail_mbind
template <template <typename...> class M1, typename... B1, template <typename...> class M2, typename... B2>
auto operator || (const mbind<M1, B1...>& , const mbind<M2, B2...>& )
-> typename detail_mbind::_x_supply<typename detail_mbind::mbind_or<mbind<M1, B1...>, mbind<M2, B2...>>>::type
{
return typename detail_mbind::_x_supply<typename detail_mbind::mbind_or<mbind<M1, B1...>, mbind<M2, B2...>>>::type{};
}
template <template <typename...> class M1, typename... B1, template <typename...> class M2, typename... B2>
auto operator && (const mbind<M1, B1...>& , const mbind<M2, B2...>& )
-> typename detail_mbind::_x_supply<typename detail_mbind::mbind_and<mbind<M1, B1...>, mbind<M2, B2...>>>::type
{
return typename detail_mbind::_x_supply<typename detail_mbind::mbind_and<mbind<M1, B1...>, mbind<M2, B2...>>>::type{};
}
template <template <typename...> class M, typename... B>
auto operator ! (const mbind<M, B...>&)
-> typename detail_mbind::_x_supply<typename detail_mbind::mbind_not<mbind<M, B...>>>::type
{
return typename detail_mbind::_x_supply<typename detail_mbind::mbind_not<mbind<M, B...>>>::type{};
}
}
#endif
<commit_msg>部分適用可能とした<commit_after>//mbind header
//Copyright (c) 2014 mmYYmmdd
#if !defined MMYYMMDD_MBIND_INCLUDED
#define MMYYMMDD_MBIND_INCLUDED
#include <type_traits>
#include <utility>
// Metaなbind mbind
namespace mymd {
namespace detail_mbind {
//-----------------------------------------------
template <typename...> struct packeR { };
//-----------------------------------------------
// default converter
template <typename T>
struct no_cnv { using type = T; };
//-----------------------------------------------
// placeholder
template <template <typename> class...convert>
struct _X_ {
template <template <typename> class...a>
using append = _X_<convert..., a...>;
};
//-----------------------------------------------
template <typename>
struct voiD_t { using type = void; };
//-----------------------------------------------
template <typename T, typename = void>
struct has_type { using type = T; };
template <typename T>
struct has_type<T, typename voiD_t<typename T::type>::type>
{ using type = typename T::type; };
//-----------------------------------------------
template <template <typename> class...> struct type_convert;
template <>
struct type_convert<> { // workaround for VC
template <typename V>
using apply = V;
};
template <template <typename> class C>
struct type_convert<C> {
template <typename V>
using apply = typename has_type<C<V>>::type;
};
template <template <typename> class first, template <typename> class...tail>
struct type_convert<first, tail...> {
template <typename V>
using apply = typename has_type<first<typename type_convert<tail...>::template apply<V>>>::type;
};
//-----------------------------------------------
template <typename T>
struct if_placeholder { static const std::size_t value = 0; };
template <template <typename> class...C>
struct if_placeholder<_X_<C...>> { static const std::size_t value = 1; };
//-----------------------------------------------
template <typename...> struct count_placeholders;
template <typename first, typename...tail>
struct count_placeholders<first, tail...>
{ static const std::size_t value = if_placeholder<first>::value + count_placeholders<tail...>::value; };
template <>
struct count_placeholders<>
{ static const std::size_t value = 0; };
template <typename...T>
struct count_placeholders<packeR<T...>>
{ static const std::size_t value = count_placeholders<T...>::value; };
//-----------------------------------------------
template <typename T>
struct trap_placeholder {
static const bool value = false;
template <typename>
using convert = T; //not convert
};
template <template <typename> class...C>
struct trap_placeholder<_X_<C...>> {
static const bool value = true;
template <typename V>
using convert = typename type_convert<C...>::template apply<V>; //convert
};
//-----------------------------------------------
template <typename, typename, typename = packeR<>> struct employ_placeholder;
template <typename T1, typename...T2, typename V1, typename... V2, typename...R>
struct employ_placeholder<packeR<T1, T2...>, packeR<V1, V2...>, packeR<R...>> {
using result = packeR<R...>;
using alt_t = typename trap_placeholder<T1>::template convert<V1>;
using base_v = typename std::conditional<trap_placeholder<T1>::value, packeR<V2...>, packeR<V1, V2...>>::type;
using base_t = employ_placeholder<packeR<T2...>, base_v, packeR<R..., alt_t>>;
using type = typename base_t::type;
};
template <typename V1, typename...V2, typename...R>
struct employ_placeholder<packeR<>, packeR<V1, V2...>, packeR<R...>>
{ using type = packeR<R...>; };
template <typename...T, typename...R>
struct employ_placeholder<packeR<T...>, packeR<>, packeR<R...>>
{ using type = packeR<R..., T...>; };
//-----------------------------------------------
template <typename left, typename right>
struct mbind_or {
static_assert(left::n_placeholders == right::n_placeholders, "mbind_or");
static const std::size_t n_placeholders = left::n_placeholders;
template <typename... V>
struct apply {
static constexpr bool value = left::template apply<V...>::value || right::template apply<V...>::value;
};
};
//------------
template <typename left, typename right>
struct mbind_and {
static_assert(left::n_placeholders == right::n_placeholders, "mbind_and");
static const std::size_t n_placeholders = left::n_placeholders;
template <typename... V>
struct apply {
static constexpr bool value = left::template apply<V...>::value && right::template apply<V...>::value;
};
};
//------------
template <typename T>
struct mbind_not {
static const std::size_t n_placeholders = T::n_placeholders;
template <typename... V>
struct apply {
static constexpr bool value = !T::template apply<V...>::value;
};
};
//-----------------------------------------------
template <template <typename...> class, typename> struct unPack;
template <template <typename...> class M, typename...V>
struct unPack<M, packeR<V...>>
{ using type = M<V...>; };
} //detail_mbind
using detail_mbind::_X_;
using _x_ = detail_mbind::_X_<detail_mbind::no_cnv>;
using _xrr_ = detail_mbind::_X_<std::remove_reference>;
using _xrcv_ = detail_mbind::_X_<std::remove_cv>;
using _xrcvr_ = detail_mbind::_X_<std::remove_cv, std::remove_reference>;
using _xdecay_ = detail_mbind::_X_<std::decay>;
template <template <typename...> class M, typename... binder>
class mbind {
template <typename... V>
using S = typename detail_mbind::employ_placeholder<detail_mbind::packeR<binder...>, detail_mbind::packeR<V...>>::type;
template <typename> struct rebind2;
template <typename... B> struct rebind2<detail_mbind::packeR<B...>>
{ using type = mbind<M, B...>; };
public:
static const std::size_t n_placeholders = detail_mbind::count_placeholders<binder...>::value;
template <typename... V>
using apply = typename std::conditional<
detail_mbind::count_placeholders<S<V...>>::value==0,
typename detail_mbind::unPack<M, S<V...>>::type,
typename rebind2<S<V...>>::type
>::type;
template <typename... B>
using bind = mbind<M, binder..., B...>;
template <typename... B>
using rebind = mbind<M, B...>;
template <template <typename...> class M2>
using change = mbind<M2, binder...>;
};
//-------------------------------------------------
namespace detail_mbind {
template <typename T, typename = packeR<>, std::size_t C = T::n_placeholders> struct _x_supply;
template <typename T, typename... R, std::size_t C>
struct _x_supply<T, packeR<R...>, C> {
using type = typename _x_supply<T, packeR<_x_, R...>, C-1>::type;
};
template <typename T, typename... R>
struct _x_supply<T, packeR<R...>, 0> {
using type = mbind<T::template apply, R...>;
};
} //detail_mbind
template <template <typename...> class M1, typename... B1, template <typename...> class M2, typename... B2>
auto operator || (const mbind<M1, B1...>& , const mbind<M2, B2...>& )
-> typename detail_mbind::_x_supply<typename detail_mbind::mbind_or<mbind<M1, B1...>, mbind<M2, B2...>>>::type
{
return typename detail_mbind::_x_supply<typename detail_mbind::mbind_or<mbind<M1, B1...>, mbind<M2, B2...>>>::type{};
}
template <template <typename...> class M1, typename... B1, template <typename...> class M2, typename... B2>
auto operator && (const mbind<M1, B1...>& , const mbind<M2, B2...>& )
-> typename detail_mbind::_x_supply<typename detail_mbind::mbind_and<mbind<M1, B1...>, mbind<M2, B2...>>>::type
{
return typename detail_mbind::_x_supply<typename detail_mbind::mbind_and<mbind<M1, B1...>, mbind<M2, B2...>>>::type{};
}
template <template <typename...> class M, typename... B>
auto operator ! (const mbind<M, B...>&)
-> typename detail_mbind::_x_supply<typename detail_mbind::mbind_not<mbind<M, B...>>>::type
{
return typename detail_mbind::_x_supply<typename detail_mbind::mbind_not<mbind<M, B...>>>::type{};
}
}
#endif
<|endoftext|>
|
<commit_before>#include "thread_manager.h"
#include "core_manager.h"
#include "performance_model.h"
#include "hooks_manager.h"
#include "config.h"
#include "log.h"
#include "transport.h"
#include "simulator.h"
#include "clock_skew_minimization_object.h"
#include "core.h"
#include "thread.h"
#include "scheduler.h"
#include "syscall_server.h"
#include <sys/syscall.h>
#include "os_compat.h"
const char* ThreadManager::stall_type_names[] = {
"unscheduled", "broken", "join", "mutex", "cond", "barrier", "futex", "pause", "sleep"
};
static_assert(ThreadManager::STALL_TYPES_MAX == sizeof(ThreadManager::stall_type_names) / sizeof(char*),
"Not enough values in ThreadManager::stall_type_names");
ThreadManager::ThreadManager()
: m_thread_tls(TLS::create())
, m_scheduler(Scheduler::create(this))
{
}
ThreadManager::~ThreadManager()
{
for (UInt32 i = 0; i < m_thread_state.size(); i++)
{
if (m_thread_state[i].status != Core::IDLE)
fprintf(stderr, "Thread %d still active when ThreadManager destructs\n", i);
delete m_threads[i];
}
delete m_thread_tls;
delete m_scheduler;
}
Thread* ThreadManager::getThreadFromID(thread_id_t thread_id)
{
LOG_ASSERT_ERROR((size_t)thread_id < m_threads.size(), "Invalid thread_id %d", thread_id);
return m_threads.at(thread_id);
}
Thread* ThreadManager::getCurrentThread(int threadIndex)
{
return m_thread_tls->getPtr<Thread>(threadIndex);
}
Thread* ThreadManager::findThreadByTid(pid_t tid)
{
for (UInt32 thread_id = 0; thread_id < m_threads.size(); ++thread_id)
{
if (m_threads.at(thread_id)->m_os_info.tid == tid)
return m_threads.at(thread_id);
}
return NULL;
}
Thread* ThreadManager::createThread(app_id_t app_id)
{
ScopedLock sl(m_thread_lock);
return createThread_unlocked(app_id);
}
Thread* ThreadManager::createThread_unlocked(app_id_t app_id)
{
thread_id_t thread_id = m_threads.size();
Thread *thread = new Thread(thread_id, app_id);
m_threads.push_back(thread);
m_thread_state.push_back(ThreadState());
m_thread_state[thread->getId()].status = Core::INITIALIZING;
core_id_t core_id = m_scheduler->threadCreate(thread_id);
if (core_id != INVALID_CORE_ID)
{
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
thread->setCore(core);
core->setState(Core::INITIALIZING);
}
return thread;
}
void ThreadManager::onThreadStart(thread_id_t thread_id, SubsecondTime time)
{
ScopedLock sl(m_thread_lock);
LOG_PRINT("onThreadStart(%i)", thread_id);
Thread *thread = getThreadFromID(thread_id);
m_thread_tls->set(thread);
thread->updateCoreTLS();
HooksManager::ThreadTime args = { thread_id: thread_id, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_START, (UInt64)&args);
Core *core = thread->getCore();
if (core)
{
// Set the CoreState to 'RUNNING'
core->setState(Core::RUNNING);
PerformanceModel *pm = core->getPerformanceModel();
// If the core already has a later time, we have to wait
time = std::max(time, pm->getElapsedTime());
pm->queueDynamicInstruction(new SpawnInstruction(time));
LOG_PRINT("Setting status[%i] -> RUNNING", thread_id);
m_thread_state[thread_id].status = Core::RUNNING;
HooksManager::ThreadMigrate args = { thread_id: thread_id, core_id: core->getId(), time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_MIGRATE, (UInt64)&args);
}
else
m_thread_state[thread_id].status = Core::STALLED;
if (m_thread_state[thread_id].waiter != INVALID_THREAD_ID)
{
getThreadFromID(m_thread_state[thread_id].waiter)->signal(time);
m_thread_state[thread_id].waiter = INVALID_THREAD_ID;
}
}
void ThreadManager::onThreadExit(thread_id_t thread_id)
{
ScopedLock sl(m_thread_lock);
Thread *thread = getThreadFromID(thread_id);
CoreManager *core_manager = Sim()->getCoreManager();
SubsecondTime time = core_manager->getCurrentCore()->getPerformanceModel()->getElapsedTime();
LOG_ASSERT_ERROR((UInt32)thread_id < m_thread_state.size(), "Thread id out of range: %d", thread_id);
assert(m_thread_state[thread_id].status == Core::RUNNING);
m_thread_state[thread_id].status = Core::IDLE;
// Implement pthread_join
wakeUpWaiter(thread_id, time);
// Implement CLONE_CHILD_CLEARTID
if (thread->m_os_info.clear_tid)
{
uint32_t zero = 0;
thread->getCore()->accessMemory(Core::NONE, Core::WRITE, thread->m_os_info.tid_ptr, (char*)&zero, sizeof(zero));
SubsecondTime end_time; // ignored
Sim()->getSyscallServer()->futexWake(thread_id, (int*)thread->m_os_info.tid_ptr, 1, FUTEX_BITSET_MATCH_ANY, time, end_time);
}
HooksManager::ThreadTime args = { thread_id: thread_id, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_EXIT, (UInt64)&args);
if (Sim()->getClockSkewMinimizationServer())
Sim()->getClockSkewMinimizationServer()->signal();
// Set the CoreState to 'IDLE'
core_manager->getCurrentCore()->setState(Core::IDLE);
m_thread_tls->set(NULL);
thread->setCore(NULL);
thread->updateCoreTLS();
}
thread_id_t ThreadManager::spawnThread(thread_id_t thread_id, app_id_t app_id, thread_func_t func, void *arg)
{
ScopedLock sl(getLock());
SubsecondTime time_start = SubsecondTime::Zero();
if (thread_id != INVALID_THREAD_ID)
{
Thread *thread = getThreadFromID(thread_id);
Core *core = thread->getCore();
time_start = core->getPerformanceModel()->getElapsedTime();
}
LOG_PRINT("(1) spawnThread with func: %p and arg: %p", func, arg);
Thread *new_thread = createThread_unlocked(app_id);
// Insert the request in the thread request queue
ThreadSpawnRequest req = { thread_id, new_thread->getId(), time_start };
m_thread_spawn_list.push(req);
LOG_PRINT("Done with (2)");
return new_thread->getId();
}
thread_id_t ThreadManager::getThreadToSpawn(SubsecondTime &time)
{
ScopedLock sl(getLock());
ThreadSpawnRequest req = m_thread_spawn_list.front();
m_thread_spawn_list.pop();
time = req.time;
return req.thread_id;
}
void ThreadManager::waitForThreadStart(thread_id_t thread_id, thread_id_t wait_thread_id)
{
ScopedLock sl(getLock());
Thread *self = getThreadFromID(thread_id);
if (m_thread_state[wait_thread_id].status == Core::INITIALIZING)
{
LOG_ASSERT_ERROR(m_thread_state[wait_thread_id].waiter == INVALID_THREAD_ID,
"Multiple threads waiting for thread: %d", wait_thread_id);
m_thread_state[wait_thread_id].waiter = thread_id;
self->wait(getLock());
}
}
void ThreadManager::moveThread(thread_id_t thread_id, core_id_t core_id, SubsecondTime time)
{
LOG_ASSERT_ERROR(getThreadState(thread_id) != Core::INITIALIZING, "Thread is initializing, it cannot be moved right now.");
Thread *thread = getThreadFromID(thread_id);
if (Core *core = thread->getCore())
core->setState(Core::IDLE);
if (core_id == INVALID_CORE_ID)
{
thread->setCore(NULL);
}
else
{
if (thread->getCore() == NULL)
{
// Unless core was stalled for sync/futex/..., wake it up
if (
m_thread_state[thread_id].status == Core::STALLED
&& m_thread_state[thread_id].stalled_reason == STALL_UNSCHEDULED
)
resumeThread(thread_id, INVALID_THREAD_ID, time);
}
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
thread->setCore(core);
core->setState(Core::RUNNING);
}
HooksManager::ThreadMigrate args = { thread_id: thread_id, core_id: core_id, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_MIGRATE, (UInt64)&args);
}
bool ThreadManager::areAllCoresRunning()
{
// Check if all the cores are running
bool is_all_running = true;
for (SInt32 i = 0; i < (SInt32) m_thread_state.size(); i++)
{
if (m_thread_state[i].status == Core::IDLE)
{
is_all_running = false;
break;
}
}
return is_all_running;
}
void ThreadManager::joinThread(thread_id_t thread_id, thread_id_t join_thread_id)
{
Thread *thread = getThreadFromID(thread_id);
Core *core = thread->getCore();
SubsecondTime end_time;
LOG_PRINT("Joining on thread: %d", join_thread_id);
{
ScopedLock sl(getLock());
if (m_thread_state[join_thread_id].status == Core::IDLE)
{
LOG_PRINT("Not running.");
return;
}
SubsecondTime start_time = core->getPerformanceModel()->getElapsedTime();
LOG_ASSERT_ERROR(m_thread_state[join_thread_id].waiter == INVALID_THREAD_ID,
"Multiple threads joining on thread: %d", join_thread_id);
m_thread_state[join_thread_id].waiter = thread_id;
end_time = stallThread(thread_id, ThreadManager::STALL_JOIN, start_time);
}
if (thread->reschedule(end_time, core))
core = thread->getCore();
core->getPerformanceModel()->queueDynamicInstruction(new SyncInstruction(end_time, SyncInstruction::JOIN));
LOG_PRINT("Exiting join thread.");
}
void ThreadManager::wakeUpWaiter(thread_id_t thread_id, SubsecondTime time)
{
if (m_thread_state[thread_id].waiter != INVALID_THREAD_ID)
{
LOG_PRINT("Waking up core: %d at time: %s", m_thread_state[thread_id].waiter, itostr(time).c_str());
// Resume the 'pthread_join' caller
resumeThread(m_thread_state[thread_id].waiter, thread_id, time);
m_thread_state[thread_id].waiter = INVALID_THREAD_ID;
}
LOG_PRINT("Exiting wakeUpWaiter");
}
void ThreadManager::stallThread_async(thread_id_t thread_id, stall_type_t reason, SubsecondTime time)
{
LOG_PRINT("Core(%i) -> STALLED", thread_id);
m_thread_state[thread_id].status = Core::STALLED;
m_thread_state[thread_id].stalled_reason = reason;
HooksManager::ThreadStall args = { thread_id: thread_id, reason: reason, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_STALL, (UInt64)&args);
if (Sim()->getClockSkewMinimizationServer())
Sim()->getClockSkewMinimizationServer()->signal();
}
SubsecondTime ThreadManager::stallThread(thread_id_t thread_id, stall_type_t reason, SubsecondTime time)
{
stallThread_async(thread_id, reason, time);
// It's possible that a HOOK_PERIODIC, called by SkewMinServer::signal(), called by stallThread_async(), woke us up again.
// We will then have been signal()d, but this signal was lost since we weren't in wait()
// If this is the case, don't go to sleep but return our wakeup time immediately
if (m_thread_state[thread_id].status == Core::RUNNING)
return getThreadFromID(thread_id)->getWakeupTime();
else
return getThreadFromID(thread_id)->wait(m_thread_lock);
}
void ThreadManager::resumeThread_async(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time, void *msg)
{
LOG_PRINT("Core(%i) -> RUNNING", thread_id);
m_thread_state[thread_id].status = Core::RUNNING;
HooksManager::ThreadResume args = { thread_id: thread_id, thread_by: thread_by, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_RESUME, (UInt64)&args);
}
void ThreadManager::resumeThread(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time, void *msg)
{
// We still have the m_thread_lock, so thread doesn't actually start running again until caller releases this lock
getThreadFromID(thread_id)->signal(time, msg);
resumeThread_async(thread_id, thread_by, time, msg);
}
bool ThreadManager::isThreadRunning(thread_id_t thread_id)
{
return (m_thread_state[thread_id].status == Core::RUNNING);
}
bool ThreadManager::isThreadInitializing(thread_id_t thread_id)
{
return (m_thread_state[thread_id].status == Core::INITIALIZING);
}
<commit_msg>[thread_manager] When starting a thread that doesn't immediately get a core, set its stalled_reason to STALL_UNSCHEDULED so moveThread knows to wake it up once it does get a core<commit_after>#include "thread_manager.h"
#include "core_manager.h"
#include "performance_model.h"
#include "hooks_manager.h"
#include "config.h"
#include "log.h"
#include "transport.h"
#include "simulator.h"
#include "clock_skew_minimization_object.h"
#include "core.h"
#include "thread.h"
#include "scheduler.h"
#include "syscall_server.h"
#include <sys/syscall.h>
#include "os_compat.h"
const char* ThreadManager::stall_type_names[] = {
"unscheduled", "broken", "join", "mutex", "cond", "barrier", "futex", "pause", "sleep"
};
static_assert(ThreadManager::STALL_TYPES_MAX == sizeof(ThreadManager::stall_type_names) / sizeof(char*),
"Not enough values in ThreadManager::stall_type_names");
ThreadManager::ThreadManager()
: m_thread_tls(TLS::create())
, m_scheduler(Scheduler::create(this))
{
}
ThreadManager::~ThreadManager()
{
for (UInt32 i = 0; i < m_thread_state.size(); i++)
{
if (m_thread_state[i].status != Core::IDLE)
fprintf(stderr, "Thread %d still active when ThreadManager destructs\n", i);
delete m_threads[i];
}
delete m_thread_tls;
delete m_scheduler;
}
Thread* ThreadManager::getThreadFromID(thread_id_t thread_id)
{
LOG_ASSERT_ERROR((size_t)thread_id < m_threads.size(), "Invalid thread_id %d", thread_id);
return m_threads.at(thread_id);
}
Thread* ThreadManager::getCurrentThread(int threadIndex)
{
return m_thread_tls->getPtr<Thread>(threadIndex);
}
Thread* ThreadManager::findThreadByTid(pid_t tid)
{
for (UInt32 thread_id = 0; thread_id < m_threads.size(); ++thread_id)
{
if (m_threads.at(thread_id)->m_os_info.tid == tid)
return m_threads.at(thread_id);
}
return NULL;
}
Thread* ThreadManager::createThread(app_id_t app_id)
{
ScopedLock sl(m_thread_lock);
return createThread_unlocked(app_id);
}
Thread* ThreadManager::createThread_unlocked(app_id_t app_id)
{
thread_id_t thread_id = m_threads.size();
Thread *thread = new Thread(thread_id, app_id);
m_threads.push_back(thread);
m_thread_state.push_back(ThreadState());
m_thread_state[thread->getId()].status = Core::INITIALIZING;
core_id_t core_id = m_scheduler->threadCreate(thread_id);
if (core_id != INVALID_CORE_ID)
{
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
thread->setCore(core);
core->setState(Core::INITIALIZING);
}
return thread;
}
void ThreadManager::onThreadStart(thread_id_t thread_id, SubsecondTime time)
{
ScopedLock sl(m_thread_lock);
LOG_PRINT("onThreadStart(%i)", thread_id);
Thread *thread = getThreadFromID(thread_id);
m_thread_tls->set(thread);
thread->updateCoreTLS();
HooksManager::ThreadTime args = { thread_id: thread_id, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_START, (UInt64)&args);
Core *core = thread->getCore();
if (core)
{
// Set the CoreState to 'RUNNING'
core->setState(Core::RUNNING);
PerformanceModel *pm = core->getPerformanceModel();
// If the core already has a later time, we have to wait
time = std::max(time, pm->getElapsedTime());
pm->queueDynamicInstruction(new SpawnInstruction(time));
LOG_PRINT("Setting status[%i] -> RUNNING", thread_id);
m_thread_state[thread_id].status = Core::RUNNING;
HooksManager::ThreadMigrate args = { thread_id: thread_id, core_id: core->getId(), time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_MIGRATE, (UInt64)&args);
}
else
{
m_thread_state[thread_id].status = Core::STALLED;
m_thread_state[thread_id].stalled_reason = STALL_UNSCHEDULED;
}
if (m_thread_state[thread_id].waiter != INVALID_THREAD_ID)
{
getThreadFromID(m_thread_state[thread_id].waiter)->signal(time);
m_thread_state[thread_id].waiter = INVALID_THREAD_ID;
}
}
void ThreadManager::onThreadExit(thread_id_t thread_id)
{
ScopedLock sl(m_thread_lock);
Thread *thread = getThreadFromID(thread_id);
CoreManager *core_manager = Sim()->getCoreManager();
SubsecondTime time = core_manager->getCurrentCore()->getPerformanceModel()->getElapsedTime();
LOG_ASSERT_ERROR((UInt32)thread_id < m_thread_state.size(), "Thread id out of range: %d", thread_id);
assert(m_thread_state[thread_id].status == Core::RUNNING);
m_thread_state[thread_id].status = Core::IDLE;
// Implement pthread_join
wakeUpWaiter(thread_id, time);
// Implement CLONE_CHILD_CLEARTID
if (thread->m_os_info.clear_tid)
{
uint32_t zero = 0;
thread->getCore()->accessMemory(Core::NONE, Core::WRITE, thread->m_os_info.tid_ptr, (char*)&zero, sizeof(zero));
SubsecondTime end_time; // ignored
Sim()->getSyscallServer()->futexWake(thread_id, (int*)thread->m_os_info.tid_ptr, 1, FUTEX_BITSET_MATCH_ANY, time, end_time);
}
HooksManager::ThreadTime args = { thread_id: thread_id, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_EXIT, (UInt64)&args);
if (Sim()->getClockSkewMinimizationServer())
Sim()->getClockSkewMinimizationServer()->signal();
// Set the CoreState to 'IDLE'
core_manager->getCurrentCore()->setState(Core::IDLE);
m_thread_tls->set(NULL);
thread->setCore(NULL);
thread->updateCoreTLS();
}
thread_id_t ThreadManager::spawnThread(thread_id_t thread_id, app_id_t app_id, thread_func_t func, void *arg)
{
ScopedLock sl(getLock());
SubsecondTime time_start = SubsecondTime::Zero();
if (thread_id != INVALID_THREAD_ID)
{
Thread *thread = getThreadFromID(thread_id);
Core *core = thread->getCore();
time_start = core->getPerformanceModel()->getElapsedTime();
}
LOG_PRINT("(1) spawnThread with func: %p and arg: %p", func, arg);
Thread *new_thread = createThread_unlocked(app_id);
// Insert the request in the thread request queue
ThreadSpawnRequest req = { thread_id, new_thread->getId(), time_start };
m_thread_spawn_list.push(req);
LOG_PRINT("Done with (2)");
return new_thread->getId();
}
thread_id_t ThreadManager::getThreadToSpawn(SubsecondTime &time)
{
ScopedLock sl(getLock());
ThreadSpawnRequest req = m_thread_spawn_list.front();
m_thread_spawn_list.pop();
time = req.time;
return req.thread_id;
}
void ThreadManager::waitForThreadStart(thread_id_t thread_id, thread_id_t wait_thread_id)
{
ScopedLock sl(getLock());
Thread *self = getThreadFromID(thread_id);
if (m_thread_state[wait_thread_id].status == Core::INITIALIZING)
{
LOG_ASSERT_ERROR(m_thread_state[wait_thread_id].waiter == INVALID_THREAD_ID,
"Multiple threads waiting for thread: %d", wait_thread_id);
m_thread_state[wait_thread_id].waiter = thread_id;
self->wait(getLock());
}
}
void ThreadManager::moveThread(thread_id_t thread_id, core_id_t core_id, SubsecondTime time)
{
LOG_ASSERT_ERROR(getThreadState(thread_id) != Core::INITIALIZING, "Thread is initializing, it cannot be moved right now.");
Thread *thread = getThreadFromID(thread_id);
if (Core *core = thread->getCore())
core->setState(Core::IDLE);
if (core_id == INVALID_CORE_ID)
{
thread->setCore(NULL);
}
else
{
if (thread->getCore() == NULL)
{
// Unless core was stalled for sync/futex/..., wake it up
if (
m_thread_state[thread_id].status == Core::STALLED
&& m_thread_state[thread_id].stalled_reason == STALL_UNSCHEDULED
)
resumeThread(thread_id, INVALID_THREAD_ID, time);
}
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
thread->setCore(core);
core->setState(Core::RUNNING);
}
HooksManager::ThreadMigrate args = { thread_id: thread_id, core_id: core_id, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_MIGRATE, (UInt64)&args);
}
bool ThreadManager::areAllCoresRunning()
{
// Check if all the cores are running
bool is_all_running = true;
for (SInt32 i = 0; i < (SInt32) m_thread_state.size(); i++)
{
if (m_thread_state[i].status == Core::IDLE)
{
is_all_running = false;
break;
}
}
return is_all_running;
}
void ThreadManager::joinThread(thread_id_t thread_id, thread_id_t join_thread_id)
{
Thread *thread = getThreadFromID(thread_id);
Core *core = thread->getCore();
SubsecondTime end_time;
LOG_PRINT("Joining on thread: %d", join_thread_id);
{
ScopedLock sl(getLock());
if (m_thread_state[join_thread_id].status == Core::IDLE)
{
LOG_PRINT("Not running.");
return;
}
SubsecondTime start_time = core->getPerformanceModel()->getElapsedTime();
LOG_ASSERT_ERROR(m_thread_state[join_thread_id].waiter == INVALID_THREAD_ID,
"Multiple threads joining on thread: %d", join_thread_id);
m_thread_state[join_thread_id].waiter = thread_id;
end_time = stallThread(thread_id, ThreadManager::STALL_JOIN, start_time);
}
if (thread->reschedule(end_time, core))
core = thread->getCore();
core->getPerformanceModel()->queueDynamicInstruction(new SyncInstruction(end_time, SyncInstruction::JOIN));
LOG_PRINT("Exiting join thread.");
}
void ThreadManager::wakeUpWaiter(thread_id_t thread_id, SubsecondTime time)
{
if (m_thread_state[thread_id].waiter != INVALID_THREAD_ID)
{
LOG_PRINT("Waking up core: %d at time: %s", m_thread_state[thread_id].waiter, itostr(time).c_str());
// Resume the 'pthread_join' caller
resumeThread(m_thread_state[thread_id].waiter, thread_id, time);
m_thread_state[thread_id].waiter = INVALID_THREAD_ID;
}
LOG_PRINT("Exiting wakeUpWaiter");
}
void ThreadManager::stallThread_async(thread_id_t thread_id, stall_type_t reason, SubsecondTime time)
{
LOG_PRINT("Core(%i) -> STALLED", thread_id);
m_thread_state[thread_id].status = Core::STALLED;
m_thread_state[thread_id].stalled_reason = reason;
HooksManager::ThreadStall args = { thread_id: thread_id, reason: reason, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_STALL, (UInt64)&args);
if (Sim()->getClockSkewMinimizationServer())
Sim()->getClockSkewMinimizationServer()->signal();
}
SubsecondTime ThreadManager::stallThread(thread_id_t thread_id, stall_type_t reason, SubsecondTime time)
{
stallThread_async(thread_id, reason, time);
// It's possible that a HOOK_PERIODIC, called by SkewMinServer::signal(), called by stallThread_async(), woke us up again.
// We will then have been signal()d, but this signal was lost since we weren't in wait()
// If this is the case, don't go to sleep but return our wakeup time immediately
if (m_thread_state[thread_id].status == Core::RUNNING)
return getThreadFromID(thread_id)->getWakeupTime();
else
return getThreadFromID(thread_id)->wait(m_thread_lock);
}
void ThreadManager::resumeThread_async(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time, void *msg)
{
LOG_PRINT("Core(%i) -> RUNNING", thread_id);
m_thread_state[thread_id].status = Core::RUNNING;
HooksManager::ThreadResume args = { thread_id: thread_id, thread_by: thread_by, time: time };
Sim()->getHooksManager()->callHooks(HookType::HOOK_THREAD_RESUME, (UInt64)&args);
}
void ThreadManager::resumeThread(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time, void *msg)
{
// We still have the m_thread_lock, so thread doesn't actually start running again until caller releases this lock
getThreadFromID(thread_id)->signal(time, msg);
resumeThread_async(thread_id, thread_by, time, msg);
}
bool ThreadManager::isThreadRunning(thread_id_t thread_id)
{
return (m_thread_state[thread_id].status == Core::RUNNING);
}
bool ThreadManager::isThreadInitializing(thread_id_t thread_id)
{
return (m_thread_state[thread_id].status == Core::INITIALIZING);
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Renderer/RenderDevice.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Renderer/Debug.hpp>
namespace Nz
{
Texture::~Texture() = default;
bool TextureParams::IsValid() const
{
if (!ImageParams::IsValid())
return false;
if (!renderDevice)
{
NazaraError("no render device set");
return false;
}
if (!usageFlags)
{
NazaraError("a texture should have at least one usage flag");
return false;
}
return true;
}
std::shared_ptr<Texture> Texture::CreateFromImage(const Image& image, const TextureParams& params)
{
NazaraAssert(params.IsValid(), "Invalid TextureParams");
Nz::TextureInfo texParams;
texParams.depth = image.GetDepth();
texParams.height = image.GetHeight();
texParams.pixelFormat = image.GetFormat();
texParams.type = image.GetType();
texParams.width = image.GetWidth();
texParams.usageFlags = params.usageFlags;
std::shared_ptr<Nz::Texture> texture = params.renderDevice->InstantiateTexture(texParams);
if (!texture->Update(image.GetConstPixels()))
{
NazaraError("failed to update texture");
return {};
}
return texture;
}
std::shared_ptr<Texture> Texture::LoadFromFile(const std::filesystem::path& filePath, const TextureParams& params)
{
std::shared_ptr<Image> image = Image::LoadFromFile(filePath, params);
return CreateFromImage(*image, params);
}
std::shared_ptr<Texture> Texture::LoadFromMemory(const void* data, std::size_t size, const TextureParams& params)
{
std::shared_ptr<Image> image = Image::LoadFromMemory(data, size, params);
return CreateFromImage(*image, params);
}
std::shared_ptr<Texture> Texture::LoadFromStream(Stream& stream, const TextureParams& params)
{
std::shared_ptr<Image> image = Image::LoadFromStream(stream, params);
return CreateFromImage(*image, params);
}
std::shared_ptr<Texture> Texture::LoadArrayFromFile(const std::filesystem::path& filePath, const TextureParams& textureParams, const Vector2ui& atlasSize)
{
std::shared_ptr<Image> image = Image::LoadArrayFromFile(filePath, textureParams, atlasSize);
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadArrayFromMemory(const void* data, std::size_t size, const TextureParams& textureParams, const Vector2ui& atlasSize)
{
std::shared_ptr<Image> image = Image::LoadArrayFromMemory(data, size, textureParams, atlasSize);
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadArrayFromStream(Stream& stream, const TextureParams& textureParams, const Vector2ui& atlasSize)
{
std::shared_ptr<Image> image = Image::LoadArrayFromStream(stream, textureParams, atlasSize);
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadCubemapFromFile(const std::filesystem::path& filePath, const TextureParams& textureParams, const CubemapParams& cubemapParams)
{
std::shared_ptr<Image> image = Image::LoadCubemapFromFile(filePath, textureParams, cubemapParams);
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadCubemapFromMemory(const void* data, std::size_t size, const TextureParams& textureParams, const CubemapParams& cubemapParams)
{
std::shared_ptr<Image> image = Image::LoadCubemapFromMemory(data, size, textureParams, cubemapParams);
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadCubemapFromStream(Stream& stream, const TextureParams& textureParams, const CubemapParams& cubemapParams)
{
std::shared_ptr<Image> image = Image::LoadCubemapFromStream(stream, textureParams, cubemapParams);
return CreateFromImage(*image, textureParams);
}
}
<commit_msg>Renderer/Texture: Handle image loading error<commit_after>// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Renderer/RenderDevice.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Renderer/Debug.hpp>
namespace Nz
{
Texture::~Texture() = default;
bool TextureParams::IsValid() const
{
if (!ImageParams::IsValid())
return false;
if (!renderDevice)
{
NazaraError("no render device set");
return false;
}
if (!usageFlags)
{
NazaraError("a texture should have at least one usage flag");
return false;
}
return true;
}
std::shared_ptr<Texture> Texture::CreateFromImage(const Image& image, const TextureParams& params)
{
NazaraAssert(params.IsValid(), "Invalid TextureParams");
Nz::TextureInfo texParams;
texParams.depth = image.GetDepth();
texParams.height = image.GetHeight();
texParams.pixelFormat = image.GetFormat();
texParams.type = image.GetType();
texParams.width = image.GetWidth();
texParams.usageFlags = params.usageFlags;
std::shared_ptr<Nz::Texture> texture = params.renderDevice->InstantiateTexture(texParams);
if (!texture->Update(image.GetConstPixels()))
{
NazaraError("failed to update texture");
return {};
}
return texture;
}
std::shared_ptr<Texture> Texture::LoadFromFile(const std::filesystem::path& filePath, const TextureParams& params)
{
std::shared_ptr<Image> image = Image::LoadFromFile(filePath, params);
if (!image)
return {};
return CreateFromImage(*image, params);
}
std::shared_ptr<Texture> Texture::LoadFromMemory(const void* data, std::size_t size, const TextureParams& params)
{
std::shared_ptr<Image> image = Image::LoadFromMemory(data, size, params);
if (!image)
return {};
return CreateFromImage(*image, params);
}
std::shared_ptr<Texture> Texture::LoadFromStream(Stream& stream, const TextureParams& params)
{
std::shared_ptr<Image> image = Image::LoadFromStream(stream, params);
if (!image)
return {};
return CreateFromImage(*image, params);
}
std::shared_ptr<Texture> Texture::LoadArrayFromFile(const std::filesystem::path& filePath, const TextureParams& textureParams, const Vector2ui& atlasSize)
{
std::shared_ptr<Image> image = Image::LoadArrayFromFile(filePath, textureParams, atlasSize);
if (!image)
return {};
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadArrayFromMemory(const void* data, std::size_t size, const TextureParams& textureParams, const Vector2ui& atlasSize)
{
std::shared_ptr<Image> image = Image::LoadArrayFromMemory(data, size, textureParams, atlasSize);
if (!image)
return {};
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadArrayFromStream(Stream& stream, const TextureParams& textureParams, const Vector2ui& atlasSize)
{
std::shared_ptr<Image> image = Image::LoadArrayFromStream(stream, textureParams, atlasSize);
if (!image)
return {};
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadCubemapFromFile(const std::filesystem::path& filePath, const TextureParams& textureParams, const CubemapParams& cubemapParams)
{
std::shared_ptr<Image> image = Image::LoadCubemapFromFile(filePath, textureParams, cubemapParams);
if (!image)
return {};
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadCubemapFromMemory(const void* data, std::size_t size, const TextureParams& textureParams, const CubemapParams& cubemapParams)
{
std::shared_ptr<Image> image = Image::LoadCubemapFromMemory(data, size, textureParams, cubemapParams);
if (!image)
return {};
return CreateFromImage(*image, textureParams);
}
std::shared_ptr<Texture> Texture::LoadCubemapFromStream(Stream& stream, const TextureParams& textureParams, const CubemapParams& cubemapParams)
{
std::shared_ptr<Image> image = Image::LoadCubemapFromStream(stream, textureParams, cubemapParams);
if (!image)
return {};
return CreateFromImage(*image, textureParams);
}
}
<|endoftext|>
|
<commit_before>
/*
* Rosetta web server, copyright(c) 2016, Thomas Hansen, phosphorusfive@gmail.com.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include "common/include/date.hpp"
#include "server/include/connection/request.hpp"
#include "server/include/connection/connection.hpp"
#include "server/include/connection/handlers/trace_handler.hpp"
namespace rosetta {
namespace server {
using std::string;
using namespace boost::asio;
using namespace boost::system;
using namespace rosetta::common;
string uri_encode (const string & entity);
trace_handler::trace_handler (class connection * connection, class request * request)
: request_handler (connection, request)
{ }
void trace_handler::handle (exceptional_executor x, functor callback)
{
// Writing status code.
write_status (200, x, [this, x, callback] (exceptional_executor x) {
// Figuring out what we're sending, before we send the headers, to see the size of our request.
auto buffer_ptr = build_content ();
// Building our request headers.
header_list headers {
{"Content-Type", "text/plain; charset=utf-8" },
{"Date", date::now ().to_string ()},
{"Content-Length", boost::lexical_cast<string> (buffer_ptr->size ())}};
// Writing HTTP headers to connection.
write_headers (headers, x, [this, callback, buffer_ptr] (exceptional_executor x) {
// Writing entire request, HTTP-Request line, and HTTP headers, back to client, as content.
async_write (connection()->socket(), buffer (*buffer_ptr), [buffer_ptr, callback, x] (const error_code & error, size_t bytes_written) {
// Invoking callback, signaling we're done.
callback (x);
});
}, true);
});
}
std::shared_ptr<std::vector<unsigned char> > trace_handler::build_content ()
{
std::shared_ptr<std::vector<unsigned char> > buffer_ptr = std::make_shared<std::vector<unsigned char> >();
// Return the HTTP-Request line.
buffer_ptr->insert (buffer_ptr->end(), request()->envelope().type ().begin(), request()->envelope().type().end());
buffer_ptr->push_back (' ');
buffer_ptr->insert (buffer_ptr->end(), request()->envelope().uri ().begin(), request()->envelope().uri().end());
// Pushing back arguments.
bool first = true;
for (auto idx : request()->envelope().parameters()) {
if (first) {
first = false;
buffer_ptr->push_back ('?');
} else {
buffer_ptr->push_back ('&');
}
// Making sure we URI encode parameter name and value.
auto name = uri_encode (std::get<0> (idx));
buffer_ptr->insert (buffer_ptr->end(), name.begin(), name.end());
auto value = uri_encode (std::get<1> (idx));
if (value.size() > 0) {
buffer_ptr->push_back ('=');
buffer_ptr->insert (buffer_ptr->end(), value.begin(), value.end());
}
}
buffer_ptr->push_back (' ');
buffer_ptr->insert (buffer_ptr->end(), request()->envelope().version().begin(), request()->envelope().version().end());
buffer_ptr->push_back ('\r');
buffer_ptr->push_back ('\n');
// Returning all HTTP headers.
for (auto idx : request()->envelope().headers ()) {
buffer_ptr->insert (buffer_ptr->end(), std::get<0> (idx).begin(), std::get<0> (idx).end());
buffer_ptr->push_back (':');
buffer_ptr->push_back (' ');
buffer_ptr->insert (buffer_ptr->end(), std::get<1> (idx).begin(), std::get<1> (idx).end());
buffer_ptr->push_back ('\r');
buffer_ptr->push_back ('\n');
}
// Appending the last CR/LF sequence.
buffer_ptr->push_back ('\r');
buffer_ptr->push_back ('\n');
return buffer_ptr;
}
/// Transforms the given unsigned char, which should be between [0-16), to a hex character.
unsigned char to_hex (unsigned char ch)
{
if (ch >= 0 && ch < 10)
ch += '0';
else if (ch >= 10 && ch < 16)
ch += ('a' -10);
return ch;
}
string uri_encode (const string & entity)
{
std::vector<unsigned char> return_value;
for (unsigned char idx : entity) {
if (idx == ' ') {
return_value.push_back ('+');
} else if ((idx >= 'a' && idx <= 'z') ||
(idx >= 'A' && idx <= 'Z') ||
(idx >= '0' && idx <= '9') ||
idx == '-' || idx == '_' || idx == '.' || idx == '~') {
return_value.push_back (idx);
} else {
// Encoding with % syntax.
return_value.push_back ('%');
return_value.push_back (to_hex (idx >> 4));
return_value.push_back (to_hex (idx & 0x0f));
}
}
return string (return_value.begin (), return_value.end ());
}
} // namespace server
} // namespace rosetta
<commit_msg>Added some comments in TRACE handler<commit_after>
/*
* Rosetta web server, copyright(c) 2016, Thomas Hansen, phosphorusfive@gmail.com.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include "common/include/date.hpp"
#include "server/include/connection/request.hpp"
#include "server/include/connection/connection.hpp"
#include "server/include/connection/handlers/trace_handler.hpp"
namespace rosetta {
namespace server {
using std::string;
using namespace boost::asio;
using namespace boost::system;
using namespace rosetta::common;
string uri_encode (const string & entity);
trace_handler::trace_handler (class connection * connection, class request * request)
: request_handler (connection, request)
{ }
void trace_handler::handle (exceptional_executor x, functor callback)
{
// Writing status code.
write_status (200, x, [this, x, callback] (exceptional_executor x) {
// Figuring out what we're sending, before we send the headers, to see the size of our request.
auto buffer_ptr = build_content ();
// Building our request headers.
header_list headers {
{"Content-Type", "text/plain; charset=utf-8" },
{"Date", date::now ().to_string ()},
{"Content-Length", boost::lexical_cast<string> (buffer_ptr->size ())}};
// Writing HTTP headers to connection.
write_headers (headers, x, [this, callback, buffer_ptr] (exceptional_executor x) {
// Writing entire request, HTTP-Request line, and HTTP headers, back to client, as content.
async_write (connection()->socket(), buffer (*buffer_ptr), [buffer_ptr, callback, x] (const error_code & error, size_t bytes_written) {
// Invoking callback, signaling we're done.
callback (x);
});
}, true);
});
}
std::shared_ptr<std::vector<unsigned char> > trace_handler::build_content ()
{
std::shared_ptr<std::vector<unsigned char> > buffer_ptr = std::make_shared<std::vector<unsigned char> >();
// Return the HTTP-Request line.
// Starting with HTTP method.
buffer_ptr->insert (buffer_ptr->end(), request()->envelope().type ().begin(), request()->envelope().type().end());
buffer_ptr->push_back (' ');
// Then the URI, without the parameters.
buffer_ptr->insert (buffer_ptr->end(), request()->envelope().uri ().begin(), request()->envelope().uri().end());
// Pushing parameters into the HTTP-Request line URI.
bool first = true;
for (auto idx : request()->envelope().parameters()) {
// Checking if this is the first parameter, or consecutive ones, to append either '?' or '&' accordingly.
if (first) {
first = false;
buffer_ptr->push_back ('?');
} else {
buffer_ptr->push_back ('&');
}
// Adding name of parameter, making sure we URI encode it.
const auto name = uri_encode (std::get<0> (idx));
buffer_ptr->insert (buffer_ptr->end(), name.begin(), name.end());
// Adding value of parameter, making sure we URI encode it.
const auto value = uri_encode (std::get<1> (idx));
if (value.size() > 0) {
// We only add '=' and value, if there actually is any value.
buffer_ptr->push_back ('=');
buffer_ptr->insert (buffer_ptr->end(), value.begin(), value.end());
}
}
// Adding HTTP version into content buffer.
buffer_ptr->push_back (' ');
buffer_ptr->insert (buffer_ptr->end(), request()->envelope().version().begin(), request()->envelope().version().end());
// CR/LF sequence, to prepare for HTTP headers.
buffer_ptr->push_back ('\r');
buffer_ptr->push_back ('\n');
// Returning all HTTP headers.
for (auto idx : request()->envelope().headers ()) {
// Header name and colon.
buffer_ptr->insert (buffer_ptr->end(), std::get<0> (idx).begin(), std::get<0> (idx).end());
buffer_ptr->push_back (':');
// Header value, prepended by a SP, for then to finish header with CR/LF sequence.
buffer_ptr->push_back (' ');
buffer_ptr->insert (buffer_ptr->end(), std::get<1> (idx).begin(), std::get<1> (idx).end());
buffer_ptr->push_back ('\r');
buffer_ptr->push_back ('\n');
}
// Returning result to caller.
return buffer_ptr;
}
/// Transforms the given unsigned char, which should be between [0-16), to a hex character.
unsigned char to_hex (unsigned char ch)
{
if (ch >= 0 && ch < 10)
ch += '0';
else if (ch >= 10 && ch < 16)
ch += ('a' -10);
return ch;
}
string uri_encode (const string & entity)
{
std::vector<unsigned char> return_value;
for (unsigned char idx : entity) {
if (idx == ' ') {
return_value.push_back ('+');
} else if ((idx >= 'a' && idx <= 'z') ||
(idx >= 'A' && idx <= 'Z') ||
(idx >= '0' && idx <= '9') ||
idx == '-' || idx == '_' || idx == '.' || idx == '~') {
return_value.push_back (idx);
} else {
// Encoding with % syntax.
return_value.push_back ('%');
return_value.push_back (to_hex (idx >> 4));
return_value.push_back (to_hex (idx & 0x0f));
}
}
return string (return_value.begin (), return_value.end ());
}
} // namespace server
} // namespace rosetta
<|endoftext|>
|
<commit_before>#include "Quatf.h"
#include <cmath>
#include "vmath\vmath.h"
///////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////
Quatf::Quatf()
: w{ 0 }
, v{}
{ }
Quatf::Quatf(float w, float x, float y, float z)
: Quatf(w, Vector3f{ x, y, z })
{ }
Quatf::Quatf(float w, const Vector3f& v)
: w{ w }
, v{ v }
{ }
Quatf::Quatf(const Quatf& other)
: w{ other.w }
, v{ other.v }
{ }
///////////////////////////////////////
// PUBLIC METHODS
///////////////////////////////////////
auto Quatf::length() const -> float
{
return std::sqrtf(w * w + v.lengthSq());
}
auto Quatf::normalize() -> void
{
auto len = length();
w /= len;
v /= len;
}
auto Quatf::normalized() const -> Quatf
{
Quatf copy{ w, v };
copy.normalize();
return copy;
}
auto Quatf::mat4() const -> Matrix4f
{
Matrix4f ret;
auto xx = v.x * v.x;
auto xy = v.x * v.y;
auto xz = v.x * v.z;
auto xw = v.x * w;
auto yy = v.y * v.y;
auto yz = v.y * v.z;
auto yw = v.y * w;
auto zz = v.z * v.z;
auto zw = v.z * w;
ret.at(0, 0) = 1 - 2 * (yy + zz);
ret.at(1, 0) = 2 * (xy - zw);
ret.at(2, 0) = 2 * (xz + yw);
ret.at(3, 0) = 0;
ret.at(0, 1) = 2 * (xy + zw);
ret.at(1, 1) = 1 - 2 * (xx + zz);
ret.at(2, 1) = 2 * (yz - xw);
ret.at(3, 1) = 0;
ret.at(0, 2) = 2 * (xz - yw);
ret.at(1, 2) = 2 * (yz + xw);
ret.at(2, 2) = 1 - 2 * (xx + yy);
ret.at(3, 2) = 0;
ret.at(0, 3) = 0;
ret.at(1, 3) = 0;
ret.at(2, 3) = 0;
ret.at(3, 3) = 1;
return ret;
}
auto Quatf::toEulerAngles() const -> Vector3f
{
Vector3f ret;
ret.x = std::atan2f(2 * (w * v.x + v.y * v.z), 1 - 2 * (v.x * v.x + v.y * v.y));
ret.y = std::asin(2 * (w * v.y - v.z * v.x));
ret.z = std::atan2f(2 * (w * v.z + v.x * v.y), 1 - 2 * (v.y * v.y + v.z * v.z));
return ret;
}
auto Quatf::rotatePoint(const Vector3f& p) const -> Vector3f
{
return rotatePoint(Quatf{ 0, p });
}
auto Quatf::rotatePoint(const Quatf& q) const -> Vector3f
{
auto& rot = *this;
auto result = rot * q * ~rot;
return result.v;
}
auto Quatf::operator=(const Quatf& rhs) -> Quatf&
{
w = rhs.w;
v = rhs.v;
return *this;
}
auto Quatf::operator*(const Quatf& rhs) const -> Quatf
{
const auto& lhs = *this;
float w = lhs.w * rhs.w - lhs.v.x * rhs.v.x - lhs.v.y * rhs.v.y - lhs.v.z * rhs.v.z;
float x = lhs.w * rhs.v.x + lhs.v.x * rhs.w + lhs.v.y * rhs.v.z - lhs.v.z * rhs.v.y;
float y = lhs.w * rhs.v.y - lhs.v.x * rhs.v.z + lhs.v.y * rhs.w + lhs.v.z * rhs.v.x;
float z = lhs.w * rhs.v.z + lhs.v.x * rhs.v.y - lhs.v.y * rhs.v.x + lhs.v.z * rhs.w;
return Quatf{ w, x, y, z };
}
auto Quatf::operator~() const -> Quatf
{
return Quatf{ w, -v };
}
auto Quatf::operator/(float f) const -> Quatf
{
return Quatf{ w / f, v / f };
}
auto Quatf::angleAxis(float angleDeg, float x, float y, float z) -> Quatf
{
return Quatf::angleAxis(angleDeg, Vector3f{ x, y, z });
}
auto Quatf::angleAxis(float angleDeg, Vector3f axis) -> Quatf
{
axis.normalize();
auto angleRad = static_cast<float>(DEG2RAD(angleDeg));
auto sa2 = std::sinf(angleRad / 2);
auto ca2 = std::cosf(angleRad / 2);
return Quatf{ ca2, axis * sa2 };
}
auto Quatf::fromMat4(const Matrix4f& mat) -> Quatf
{
#define m(x, y) mat.at(x, y)
Quatf ret;
ret.w = std::sqrtf(1.0f + m(0, 0) + m(1, 1) + m(2, 2)) / 2.0f;
float w4 =ret.w * 4.0f;
ret.v.x = (m(2, 1) - m(1, 2)) / w4;
ret.v.y = (m(0, 2) - m(2, 0)) / w4;
ret.v.z = (m(1, 0) - m(0, 1)) / w4;
return ret;
#undef m
}
auto Quatf::fromEulerAngles(const Vector3f& e) -> Quatf
{
throw "Not yet implemented";
}
auto Quatf::lerp(const Quatf& from, const Quatf& to, float t) -> Quatf
{
t = std::max(0.0f, std::min(t, 1.0f));
float t2 = 1 - t;
return Quatf{ from.w * t2 + to.w * t, from.v * t2 + to.v * t };
}
auto Quatf::slerp(const Quatf& from, const Quatf& to, float t) -> Quatf
{
t = std::max(0.0f, std::min(t, 1.0f));
float t2 = 1 - t;
float cosOmega = from.w * to.w
+ from.v.x * to.v.x
+ from.v.y * to.v.y
+ from.v.z * to.v.z;
float omega = std::acosf(cosOmega);
float sinOmega = std::sinf(omega);
if (std::abs(sinOmega) < epsilon)
return from;
float fromCoef = std::sin(t2 * omega) / sinOmega;
float toCoef = std::sin(t * omega) / sinOmega;
Quatf res;
res.w = fromCoef * from.w + toCoef * to.w;
res.v.x = fromCoef * from.v.x + toCoef * to.v.x;
res.v.y = fromCoef * from.v.y + toCoef * to.v.y;
res.v.z = fromCoef * from.v.z + toCoef * to.v.z;
return res;
}
///////////////////////////////////////
// NON-MEMBER FUNCTIONS
///////////////////////////////////////
auto operator*(float f, const Quatf& q) -> Quatf
{
return q * f;
}
auto operator*(const Quatf& q, float f) -> Quatf
{
return Quatf{ q.w * f, q.v * f };
}<commit_msg>Added euler angle interp<commit_after>#include "Quatf.h"
#include <cmath>
#include "vmath\vmath.h"
///////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////
Quatf::Quatf()
: w{ 0 }
, v{}
{ }
Quatf::Quatf(float w, float x, float y, float z)
: Quatf(w, Vector3f{ x, y, z })
{ }
Quatf::Quatf(float w, const Vector3f& v)
: w{ w }
, v{ v }
{ }
Quatf::Quatf(const Quatf& other)
: w{ other.w }
, v{ other.v }
{ }
///////////////////////////////////////
// PUBLIC METHODS
///////////////////////////////////////
auto Quatf::length() const -> float
{
return std::sqrtf(w * w + v.lengthSq());
}
auto Quatf::normalize() -> void
{
auto len = length();
w /= len;
v /= len;
}
auto Quatf::normalized() const -> Quatf
{
Quatf copy{ w, v };
copy.normalize();
return copy;
}
auto Quatf::mat4() const -> Matrix4f
{
Matrix4f ret;
auto xx = v.x * v.x;
auto xy = v.x * v.y;
auto xz = v.x * v.z;
auto xw = v.x * w;
auto yy = v.y * v.y;
auto yz = v.y * v.z;
auto yw = v.y * w;
auto zz = v.z * v.z;
auto zw = v.z * w;
ret.at(0, 0) = 1 - 2 * (yy + zz);
ret.at(1, 0) = 2 * (xy - zw);
ret.at(2, 0) = 2 * (xz + yw);
ret.at(3, 0) = 0;
ret.at(0, 1) = 2 * (xy + zw);
ret.at(1, 1) = 1 - 2 * (xx + zz);
ret.at(2, 1) = 2 * (yz - xw);
ret.at(3, 1) = 0;
ret.at(0, 2) = 2 * (xz - yw);
ret.at(1, 2) = 2 * (yz + xw);
ret.at(2, 2) = 1 - 2 * (xx + yy);
ret.at(3, 2) = 0;
ret.at(0, 3) = 0;
ret.at(1, 3) = 0;
ret.at(2, 3) = 0;
ret.at(3, 3) = 1;
return ret;
}
auto Quatf::toEulerAngles() const -> Vector3f
{
Vector3f ret;
ret.x = std::atan2f(2 * (w * v.x + v.y * v.z), 1 - 2 * (v.x * v.x + v.y * v.y));
ret.y = std::asin(2 * (w * v.y - v.z * v.x));
ret.z = std::atan2f(2 * (w * v.z + v.x * v.y), 1 - 2 * (v.y * v.y + v.z * v.z));
const float toDeg = 180.0f / static_cast<float>(M_PI);
ret.x *= toDeg;
ret.y *= toDeg;
ret.z *= toDeg;
return ret;
}
auto Quatf::rotatePoint(const Vector3f& p) const -> Vector3f
{
return rotatePoint(Quatf{ 0, p });
}
auto Quatf::rotatePoint(const Quatf& q) const -> Vector3f
{
auto& rot = *this;
auto result = rot * q * ~rot;
return result.v;
}
auto Quatf::operator=(const Quatf& rhs) -> Quatf&
{
w = rhs.w;
v = rhs.v;
return *this;
}
auto Quatf::operator*(const Quatf& rhs) const -> Quatf
{
const auto& lhs = *this;
float w = lhs.w * rhs.w - lhs.v.x * rhs.v.x - lhs.v.y * rhs.v.y - lhs.v.z * rhs.v.z;
float x = lhs.w * rhs.v.x + lhs.v.x * rhs.w + lhs.v.y * rhs.v.z - lhs.v.z * rhs.v.y;
float y = lhs.w * rhs.v.y - lhs.v.x * rhs.v.z + lhs.v.y * rhs.w + lhs.v.z * rhs.v.x;
float z = lhs.w * rhs.v.z + lhs.v.x * rhs.v.y - lhs.v.y * rhs.v.x + lhs.v.z * rhs.w;
return Quatf{ w, x, y, z };
}
auto Quatf::operator~() const -> Quatf
{
return Quatf{ w, -v };
}
auto Quatf::operator/(float f) const -> Quatf
{
return Quatf{ w / f, v / f };
}
auto Quatf::angleAxis(float angleDeg, float x, float y, float z) -> Quatf
{
return Quatf::angleAxis(angleDeg, Vector3f{ x, y, z });
}
auto Quatf::angleAxis(float angleDeg, Vector3f axis) -> Quatf
{
axis.normalize();
auto angleRad = static_cast<float>(DEG2RAD(angleDeg));
auto sa2 = std::sinf(angleRad / 2);
auto ca2 = std::cosf(angleRad / 2);
return Quatf{ ca2, axis * sa2 };
}
auto Quatf::fromMat4(const Matrix4f& mat) -> Quatf
{
#define m(x, y) mat.at(x, y)
Quatf ret;
ret.w = std::sqrtf(1.0f + m(0, 0) + m(1, 1) + m(2, 2)) / 2.0f;
float w4 =ret.w * 4.0f;
ret.v.x = (m(2, 1) - m(1, 2)) / w4;
ret.v.y = (m(0, 2) - m(2, 0)) / w4;
ret.v.z = (m(1, 0) - m(0, 1)) / w4;
return ret;
#undef m
}
auto Quatf::fromEulerAngles(const Vector3f& e) -> Quatf
{
return angleAxis(e.x, { 1, 0, 0 })
* angleAxis(e.y, { 0, 1, 0 })
* angleAxis(e.z, { 0, 0, 1 });
}
auto Quatf::lerp(const Quatf& from, const Quatf& to, float t) -> Quatf
{
t = std::max(0.0f, std::min(t, 1.0f));
float t2 = 1 - t;
return Quatf{ from.w * t2 + to.w * t, from.v * t2 + to.v * t };
}
auto Quatf::slerp(const Quatf& from, const Quatf& to, float t) -> Quatf
{
t = std::max(0.0f, std::min(t, 1.0f));
float t2 = 1 - t;
float cosOmega = from.w * to.w
+ from.v.x * to.v.x
+ from.v.y * to.v.y
+ from.v.z * to.v.z;
float omega = std::acosf(cosOmega);
float sinOmega = std::sinf(omega);
if (std::abs(sinOmega) < epsilon)
return from;
float fromCoef = std::sin(t2 * omega) / sinOmega;
float toCoef = std::sin(t * omega) / sinOmega;
Quatf res;
res.w = fromCoef * from.w + toCoef * to.w;
res.v.x = fromCoef * from.v.x + toCoef * to.v.x;
res.v.y = fromCoef * from.v.y + toCoef * to.v.y;
res.v.z = fromCoef * from.v.z + toCoef * to.v.z;
return res;
}
///////////////////////////////////////
// NON-MEMBER FUNCTIONS
///////////////////////////////////////
auto operator*(float f, const Quatf& q) -> Quatf
{
return q * f;
}
auto operator*(const Quatf& q, float f) -> Quatf
{
return Quatf{ q.w * f, q.v * f };
}<|endoftext|>
|
<commit_before>#define BOOST_TEST_STATIC_LINK
#define BOOST_TEST_MODULE FIXED_POINT_LIB_COMMON_USE_CASES
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/range/irange.hpp>
#include <limits>
#include <string>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include "./../../fixed_point_lib/src/number.hpp"
namespace utils { namespace unit_tests {
#define iterations 100000
namespace {
using utils::SOU_number;
using utils::UOU_number;
}
#define fmin(type) double(std::numeric_limits<type>::min())
#define fmax(type) double(std::numeric_limits<type>::max())
double r(double low, double high)
{
return low + std::rand() / (double(RAND_MAX) / (high - low));
}
BOOST_AUTO_TEST_SUITE(Summation)
// FIXED-POINT SUMMATION PRECISION TESTS
//////////////////////////////////////////////////////////////////////////
/// idea of tests 'commonCheck1' and 'commonCheck2':
/// 1. common checks for fixed-point accuracy
/// 2. number of accurate decimal numbers in fractional part is determined
/// as floor(log(10, 2^(f + 1) - 1)) - 1. Last number is errored by left
/// non-captured digits.
BOOST_AUTO_TEST_CASE(commonCheck1)
{
typedef UOU_number<28, 13>::type type1;
typedef UOU_number<37, 15>::type type2;
std::srand(static_cast<unsigned int>(std::time(0)));
BOOST_FOREACH(size_t it, boost::irange<size_t>(0, iterations, 1)) {
// shortening range not to take care about rounding errors at the
// bounds
double u1 = r(fmin(type1) + 1u, fmax(type1) - 1u);
double u2 = r(std::max(fmin(type1) + 1u - u1, fmin(type2) + 1u),
std::min(fmax(type1) - 1u - u1, fmax(type2) - 1u));
type1 const a(u1);
type2 const b(u2);
type1::sum_type const result = a + b;
std::stringstream message_stream;
message_stream
<< std::setprecision(5)
<< u1
<< " + "
<< u2
<< ": summation was made with unexpected rounding error";
BOOST_CHECK_MESSAGE(std::fabs(double(result) - (u1 + u2)) < 1E-3,
message_stream.str());
}
}
BOOST_AUTO_TEST_CASE(commonCheck2)
{
typedef SOU_number<56, 34>::type type1;
typedef SOU_number<56, 47>::type type2;
std::srand(static_cast<unsigned int>(std::time(0)));
BOOST_FOREACH(size_t it, boost::irange<size_t>(0, iterations, 1)) {
// shortening range not to take care about rounding errors at the
// bounds
double u1 = r(fmin(type1) + 1, fmax(type1) - 1);
double u2 = r(std::max(fmin(type1) + 1 - u1, fmin(type2) + 1u),
std::min(fmax(type1) - 1 - u1, fmax(type2) - 1u));
type1 const a(u1);
type2 const b(u2);
type1::sum_type const result = a + b;
std::stringstream message_stream;
message_stream
<< std::setprecision(11)
<< u1
<< " + "
<< u2
<< ": summation was made with unexpected rounding error";
BOOST_CHECK_MESSAGE(std::fabs(double(result) - (u1 + u2)) < 1E-9,
message_stream.str());
}
}
// POSITIVE/NEGATIVE OVERFLOW EVENTS HANDLING
//////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(positiveOverflow)
{
typedef SOU_number<8, 3>::type type;
type const a(31.9);
type const b(0.2);
try {
type const c(a + b);
BOOST_FAIL("Positive overflow event was not captured");
}
catch (std::overflow_error e){};
}
BOOST_AUTO_TEST_CASE(negativeOverflow)
{
typedef SOU_number<8, 3>::type type;
type const a(-31.9);
type const b(-0.2);
try {
type const c(a + b);
BOOST_FAIL("Negative overflow event was not captured");
}
catch (std::overflow_error e){};
}
BOOST_AUTO_TEST_SUITE_END()
}}
<commit_msg>sum_cases.cpp: do not link r function code in object file<commit_after>#define BOOST_TEST_STATIC_LINK
#define BOOST_TEST_MODULE FIXED_POINT_LIB_COMMON_USE_CASES
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/range/irange.hpp>
#include <limits>
#include <string>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include "./../../fixed_point_lib/src/number.hpp"
namespace utils { namespace unit_tests {
#define iterations 100000
namespace {
using utils::SOU_number;
using utils::UOU_number;
double r(double low, double high)
{
return low + std::rand() / (double(RAND_MAX) / (high - low));
}
}
#define fmin(type) double(std::numeric_limits<type>::min())
#define fmax(type) double(std::numeric_limits<type>::max())
BOOST_AUTO_TEST_SUITE(Summation)
// FIXED-POINT SUMMATION PRECISION TESTS
//////////////////////////////////////////////////////////////////////////
/// idea of tests 'commonCheck1' and 'commonCheck2':
/// 1. common checks for fixed-point accuracy
/// 2. number of accurate decimal numbers in fractional part is determined
/// as floor(log(10, 2^(f + 1) - 1)) - 1. Last number is errored by left
/// non-captured digits.
BOOST_AUTO_TEST_CASE(commonCheck1)
{
typedef UOU_number<28, 13>::type type1;
typedef UOU_number<37, 15>::type type2;
std::srand(static_cast<unsigned int>(std::time(0)));
BOOST_FOREACH(size_t it, boost::irange<size_t>(0, iterations, 1)) {
// shortening range not to take care about rounding errors at the
// bounds
double u1 = r(fmin(type1) + 1u, fmax(type1) - 1u);
double u2 = r(std::max(fmin(type1) + 1u - u1, fmin(type2) + 1u),
std::min(fmax(type1) - 1u - u1, fmax(type2) - 1u));
type1 const a(u1);
type2 const b(u2);
type1::sum_type const result = a + b;
std::stringstream message_stream;
message_stream
<< std::setprecision(5)
<< u1
<< " + "
<< u2
<< ": summation was made with unexpected rounding error";
BOOST_CHECK_MESSAGE(std::fabs(double(result) - (u1 + u2)) < 1E-3,
message_stream.str());
}
}
BOOST_AUTO_TEST_CASE(commonCheck2)
{
typedef SOU_number<56, 34>::type type1;
typedef SOU_number<56, 47>::type type2;
std::srand(static_cast<unsigned int>(std::time(0)));
BOOST_FOREACH(size_t it, boost::irange<size_t>(0, iterations, 1)) {
// shortening range not to take care about rounding errors at the
// bounds
double u1 = r(fmin(type1) + 1, fmax(type1) - 1);
double u2 = r(std::max(fmin(type1) + 1 - u1, fmin(type2) + 1u),
std::min(fmax(type1) - 1 - u1, fmax(type2) - 1u));
type1 const a(u1);
type2 const b(u2);
type1::sum_type const result = a + b;
std::stringstream message_stream;
message_stream
<< std::setprecision(11)
<< u1
<< " + "
<< u2
<< ": summation was made with unexpected rounding error";
BOOST_CHECK_MESSAGE(std::fabs(double(result) - (u1 + u2)) < 1E-9,
message_stream.str());
}
}
// POSITIVE/NEGATIVE OVERFLOW EVENTS HANDLING
//////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(positiveOverflow)
{
typedef SOU_number<8, 3>::type type;
type const a(31.9);
type const b(0.2);
try {
type const c(a + b);
BOOST_FAIL("Positive overflow event was not captured");
}
catch (std::overflow_error e){};
}
BOOST_AUTO_TEST_CASE(negativeOverflow)
{
typedef SOU_number<8, 3>::type type;
type const a(-31.9);
type const b(-0.2);
try {
type const c(a + b);
BOOST_FAIL("Negative overflow event was not captured");
}
catch (std::overflow_error e){};
}
BOOST_AUTO_TEST_SUITE_END()
#undef iterations
#undef fmin
#undef fmax
}}
<|endoftext|>
|
<commit_before>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <cerrno>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include "AstPrintDocs.h"
#include "AstToText.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "docs.h"
static int compareNames(const void* v1, const void* v2) {
Symbol* s1 = *(Symbol* const *)v1;
Symbol* s2 = *(Symbol* const *)v2;
return strcmp(s1->name, s2->name);
}
static int compareClasses(const void *v1, const void* v2) {
Type *t1 = *(Type* const *)v1;
Type *t2 = *(Type* const *)v2;
return strcmp(t1->symbol->name, t2->symbol->name);
}
void docs(void) {
if (fDocs) {
// Open the directory to store the docs
// This is the final location for the output format (e.g. the html files.).
std::string docsOutputDir;
if (strlen(fDocsFolder) > 0) {
docsOutputDir = fDocsFolder;
} else {
docsOutputDir = astr(getCwd(), "/docs");
}
// Root of the sphinx project and generated rst files. If
// --docs-save-sphinx is not specified, it will be a temp dir.
std::string docsTempDir = "";
std::string docsSphinxDir;
if (strlen(fDocsSphinxDir) > 0) {
docsSphinxDir = fDocsSphinxDir;
} else {
docsTempDir = makeTempDir("chpldoc-");
docsSphinxDir = docsTempDir;
}
// Make the intermediate dir and output dir.
makeDir(docsSphinxDir.c_str());
makeDir(docsOutputDir.c_str());
// The location of intermediate rst files.
std::string docsRstDir;
if (fDocsTextOnly) {
// For text-only mode, the output and working location is the same.
docsRstDir = docsOutputDir;
} else {
// For rst mode, the working location is somewhere inside the temp dir.
docsRstDir = generateSphinxProject(docsSphinxDir);
}
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!mod->hasFlag(FLAG_NO_DOC) && !devOnlyModule(mod)) {
if (isNotSubmodule(mod)) {
std::ofstream *file = openFileFromMod(mod, docsRstDir);
AstPrintDocs *docsVisitor = new AstPrintDocs(file);
mod->accept(docsVisitor);
delete docsVisitor;
// Comment the above three lines and uncomment the following line to
// get the old category based output (or alphabetical). Note that
// this will be restored (hopefully soon)... (thomasvandoren, 2015-02-22)
//
// printModule(file, mod, 0);
file->close();
}
}
}
if (!fDocsTextOnly) {
generateSphinxOutput(docsSphinxDir, docsOutputDir);
}
if (docsTempDir.length() > 0) {
deleteDir(docsTempDir.c_str());
}
}
}
bool isNotSubmodule(ModuleSymbol *mod) {
return (mod->defPoint == NULL ||
mod->defPoint->parentSymbol == NULL ||
mod->defPoint->parentSymbol->name == NULL ||
strcmp("chpl__Program", mod->defPoint->parentSymbol->name) == 0 ||
strcmp("_root", mod->defPoint->parentSymbol->name) == 0);
}
void printFields(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
for (int i = 1; i <= cl->fields.length; i++) {
if (VarSymbol *var = toVarSymbol(((DefExpr *)cl->fields.get(i))->sym)) {
var->printDocs(file, tabs);
}
}
}
void printClass(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
if (!cl->symbol->hasFlag(FLAG_NO_DOC) && ! cl->isUnion()) {
cl->printDocs(file, tabs);
printFields(file, cl, tabs + 1);
// In rst mode, add an additional line break after the attributes and
// before the next directive.
if (!fDocsTextOnly) {
*file << std::endl;
}
// If alphabetical option passed, alphabetizes the output
if (fDocsAlphabetize)
qsort(cl->methods.v, cl->methods.n, sizeof(cl->methods.v[0]),
compareNames);
forv_Vec(FnSymbol, fn, cl->methods){
// We only want to print methods defined within the class under the
// class header
if (fn->isPrimaryMethod())
fn->printDocs(file, tabs + 1);
}
}
}
// Returns true if the provided fn is a module initializer, class constructor,
// type constructor, or module copy of a class method. These functions are
// only printed in developer mode. Is not applicable to printing class
// functions.
bool devOnlyFunction(FnSymbol *fn) {
return (fn->hasFlag(FLAG_MODULE_INIT) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)
|| fn->hasFlag(FLAG_CONSTRUCTOR) || fn->isPrimaryMethod());
}
// Returns true if the provide module is one of the internal or standard
// modules. It is our opinion that these should only automatically be printed
// out if the user is in developer mode.
bool devOnlyModule(ModuleSymbol *mod) {
return mod->modTag == MOD_INTERNAL || mod->modTag == MOD_STANDARD;
}
void printModule(std::ofstream *file, ModuleSymbol *mod, unsigned int tabs) {
if (!mod->hasFlag(FLAG_NO_DOC)) {
mod->printDocs(file, tabs);
Vec<VarSymbol*> configs = mod->getTopLevelConfigVars();
if (fDocsAlphabetize)
qsort(configs.v, configs.n, sizeof(configs.v[0]), compareNames);
forv_Vec(VarSymbol, var, configs) {
var->printDocs(file, tabs + 1);
}
Vec<VarSymbol*> variables = mod->getTopLevelVariables();
if (fDocsAlphabetize)
qsort(variables.v, variables.n, sizeof(variables.v[0]), compareNames);
forv_Vec(VarSymbol, var, variables) {
var->printDocs(file, tabs + 1);
}
Vec<FnSymbol*> fns = mod->getTopLevelFunctions(fDocsIncludeExterns);
// If alphabetical option passed, fDocsAlphabetizes the output
if (fDocsAlphabetize)
qsort(fns.v, fns.n, sizeof(fns.v[0]), compareNames);
forv_Vec(FnSymbol, fn, fns) {
// TODO: Add flag to compiler to turn on doc dev only output
// We want methods on classes that are defined at the module level to be
// printed at the module level
if (!devOnlyFunction(fn) || fn->isSecondaryMethod()) {
fn->printDocs(file, tabs + 1);
}
}
Vec<AggregateType*> classes = mod->getTopLevelClasses();
if (fDocsAlphabetize)
qsort(classes.v, classes.n, sizeof(classes.v[0]), compareClasses);
forv_Vec(AggregateType, cl, classes) {
printClass(file, cl, tabs + 1);
}
Vec<ModuleSymbol*> mods = mod->getTopLevelModules();
if (fDocsAlphabetize)
qsort(mods.v, mods.n, sizeof(mods.v[0]), compareNames);
forv_Vec(ModuleSymbol, subMod, mods) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!devOnlyModule(subMod)) {
subMod->addPrefixToName(mod->docsName() + ".");
printModule(file, subMod, tabs + 1);
}
}
}
}
void createDocsFileFolders(std::string filename) {
size_t dirCutoff = filename.find("/");
size_t total = 0;
while (dirCutoff != std::string::npos) {
// Creates each subdirectory within the new documentation directory
dirCutoff += total;
std::string shorter = filename.substr(dirCutoff+1);
std::string otherHalf = filename.substr(0, dirCutoff);
makeDir(otherHalf.c_str());
total = dirCutoff + 1;
dirCutoff = shorter.find("/");
}
}
/* Create the directory (non-recursively). If an error occurs, exit and report
* error.
*/
static void makeDir(const char* dirpath) {
static const int dirPerms = S_IRWXU | S_IRWXG | S_IRWXO;
int result = mkdir(dirpath, dirPerms);
if (result != 0 && errno != 0 && errno != EEXIST) {
USR_FATAL(astr("Failed to create directory: ", dirpath,
" due to: ", strerror(errno)));
}
}
/*
* Create new sphinx project at given location and return path where .rst files
* should be placed.
*/
std::string generateSphinxProject(std::string dirpath) {
// Create the output dir under the docs output dir.
const char * sphinxDir = dirpath.c_str();
// Copy the sphinx template into the output dir.
const char * sphinxTemplate = astr(CHPL_HOME, "/third-party/chpldoc-venv/chpldoc-sphinx-project/*");
const char * cmd = astr("cp -r ", sphinxTemplate, " ", sphinxDir, "/");
mysystem(cmd, "copying chpldoc sphinx template");
const char * moddir = astr(sphinxDir, "/source/modules");
return std::string(moddir);
}
/*
* Invoke sphinx-build using sphinxDir to find conf.py and rst sources, and
* outputDir for generated html files.
*/
void generateSphinxOutput(std::string sphinxDir, std::string outputDir) {
// Set the PATH and VIRTUAL_ENV variables in the environment. The values are
// based on the install path in the third-party/chpldoc-venv/ dir.
const char * venvDir = astr(
CHPL_HOME, "/third-party/chpldoc-venv/install/",
CHPL_TARGET_PLATFORM, "/chpldoc-virtualenv");
const char * venvBinDir = astr(venvDir, "/bin");
const char * sphinxBuild = astr(venvBinDir, "/sphinx-build");
const char * envVars = astr("export PATH=", venvBinDir, ":$PATH && ",
"export VIRTUAL_ENV=", venvDir);
// Run:
// $envVars &&
// sphinx-build -b html
// -d $sphinxDir/build/doctrees -W
// $sphinxDir/source $outputDir
const char * cmdPrefix = astr(envVars, " && ");
const char * cmd = astr(
cmdPrefix,
sphinxBuild, " -b html -d ",
sphinxDir.c_str(), "/build/doctrees -W ",
sphinxDir.c_str(), "/source ", outputDir.c_str());
mysystem(cmd, "building html output from chpldoc sphinx project");
printf("HTML files are at: %s\n", outputDir.c_str());
}
std::string filenameFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = mod->filename;
if (mod->modTag == MOD_INTERNAL) {
filename = "internal-modules/";
} else if (mod ->modTag == MOD_STANDARD) {
filename = "standard-modules/";
} else {
size_t location = filename.rfind("/");
if (location != std::string::npos) {
filename = filename.substr(0, location + 1);
} else {
filename = "";
}
}
filename = docsWorkDir + "/" + filename;
createDocsFileFolders(filename);
// Creates files for each top level module.
if (fDocsTextOnly) {
filename = filename + mod->name + ".txt";
} else {
filename = filename + mod->name + ".rst";
}
return filename;
}
std::ofstream* openFileFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = filenameFromMod(mod, docsWorkDir);
return new std::ofstream(filename.c_str(), std::ios::out);
}
<commit_msg>Do not try to create directories with name "".<commit_after>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <cerrno>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include "AstPrintDocs.h"
#include "AstToText.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "docs.h"
static int compareNames(const void* v1, const void* v2) {
Symbol* s1 = *(Symbol* const *)v1;
Symbol* s2 = *(Symbol* const *)v2;
return strcmp(s1->name, s2->name);
}
static int compareClasses(const void *v1, const void* v2) {
Type *t1 = *(Type* const *)v1;
Type *t2 = *(Type* const *)v2;
return strcmp(t1->symbol->name, t2->symbol->name);
}
void docs(void) {
if (fDocs) {
// Open the directory to store the docs
// This is the final location for the output format (e.g. the html files.).
std::string docsOutputDir;
if (strlen(fDocsFolder) > 0) {
docsOutputDir = fDocsFolder;
} else {
docsOutputDir = astr(getCwd(), "/docs");
}
// Root of the sphinx project and generated rst files. If
// --docs-save-sphinx is not specified, it will be a temp dir.
std::string docsTempDir = "";
std::string docsSphinxDir;
if (strlen(fDocsSphinxDir) > 0) {
docsSphinxDir = fDocsSphinxDir;
} else {
docsTempDir = makeTempDir("chpldoc-");
docsSphinxDir = docsTempDir;
}
// Make the intermediate dir and output dir.
makeDir(docsSphinxDir.c_str());
makeDir(docsOutputDir.c_str());
// The location of intermediate rst files.
std::string docsRstDir;
if (fDocsTextOnly) {
// For text-only mode, the output and working location is the same.
docsRstDir = docsOutputDir;
} else {
// For rst mode, the working location is somewhere inside the temp dir.
docsRstDir = generateSphinxProject(docsSphinxDir);
}
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!mod->hasFlag(FLAG_NO_DOC) && !devOnlyModule(mod)) {
if (isNotSubmodule(mod)) {
std::ofstream *file = openFileFromMod(mod, docsRstDir);
AstPrintDocs *docsVisitor = new AstPrintDocs(file);
mod->accept(docsVisitor);
delete docsVisitor;
// Comment the above three lines and uncomment the following line to
// get the old category based output (or alphabetical). Note that
// this will be restored (hopefully soon)... (thomasvandoren, 2015-02-22)
//
// printModule(file, mod, 0);
file->close();
}
}
}
if (!fDocsTextOnly) {
generateSphinxOutput(docsSphinxDir, docsOutputDir);
}
if (docsTempDir.length() > 0) {
deleteDir(docsTempDir.c_str());
}
}
}
bool isNotSubmodule(ModuleSymbol *mod) {
return (mod->defPoint == NULL ||
mod->defPoint->parentSymbol == NULL ||
mod->defPoint->parentSymbol->name == NULL ||
strcmp("chpl__Program", mod->defPoint->parentSymbol->name) == 0 ||
strcmp("_root", mod->defPoint->parentSymbol->name) == 0);
}
void printFields(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
for (int i = 1; i <= cl->fields.length; i++) {
if (VarSymbol *var = toVarSymbol(((DefExpr *)cl->fields.get(i))->sym)) {
var->printDocs(file, tabs);
}
}
}
void printClass(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
if (!cl->symbol->hasFlag(FLAG_NO_DOC) && ! cl->isUnion()) {
cl->printDocs(file, tabs);
printFields(file, cl, tabs + 1);
// In rst mode, add an additional line break after the attributes and
// before the next directive.
if (!fDocsTextOnly) {
*file << std::endl;
}
// If alphabetical option passed, alphabetizes the output
if (fDocsAlphabetize)
qsort(cl->methods.v, cl->methods.n, sizeof(cl->methods.v[0]),
compareNames);
forv_Vec(FnSymbol, fn, cl->methods){
// We only want to print methods defined within the class under the
// class header
if (fn->isPrimaryMethod())
fn->printDocs(file, tabs + 1);
}
}
}
// Returns true if the provided fn is a module initializer, class constructor,
// type constructor, or module copy of a class method. These functions are
// only printed in developer mode. Is not applicable to printing class
// functions.
bool devOnlyFunction(FnSymbol *fn) {
return (fn->hasFlag(FLAG_MODULE_INIT) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)
|| fn->hasFlag(FLAG_CONSTRUCTOR) || fn->isPrimaryMethod());
}
// Returns true if the provide module is one of the internal or standard
// modules. It is our opinion that these should only automatically be printed
// out if the user is in developer mode.
bool devOnlyModule(ModuleSymbol *mod) {
return mod->modTag == MOD_INTERNAL || mod->modTag == MOD_STANDARD;
}
void printModule(std::ofstream *file, ModuleSymbol *mod, unsigned int tabs) {
if (!mod->hasFlag(FLAG_NO_DOC)) {
mod->printDocs(file, tabs);
Vec<VarSymbol*> configs = mod->getTopLevelConfigVars();
if (fDocsAlphabetize)
qsort(configs.v, configs.n, sizeof(configs.v[0]), compareNames);
forv_Vec(VarSymbol, var, configs) {
var->printDocs(file, tabs + 1);
}
Vec<VarSymbol*> variables = mod->getTopLevelVariables();
if (fDocsAlphabetize)
qsort(variables.v, variables.n, sizeof(variables.v[0]), compareNames);
forv_Vec(VarSymbol, var, variables) {
var->printDocs(file, tabs + 1);
}
Vec<FnSymbol*> fns = mod->getTopLevelFunctions(fDocsIncludeExterns);
// If alphabetical option passed, fDocsAlphabetizes the output
if (fDocsAlphabetize)
qsort(fns.v, fns.n, sizeof(fns.v[0]), compareNames);
forv_Vec(FnSymbol, fn, fns) {
// TODO: Add flag to compiler to turn on doc dev only output
// We want methods on classes that are defined at the module level to be
// printed at the module level
if (!devOnlyFunction(fn) || fn->isSecondaryMethod()) {
fn->printDocs(file, tabs + 1);
}
}
Vec<AggregateType*> classes = mod->getTopLevelClasses();
if (fDocsAlphabetize)
qsort(classes.v, classes.n, sizeof(classes.v[0]), compareClasses);
forv_Vec(AggregateType, cl, classes) {
printClass(file, cl, tabs + 1);
}
Vec<ModuleSymbol*> mods = mod->getTopLevelModules();
if (fDocsAlphabetize)
qsort(mods.v, mods.n, sizeof(mods.v[0]), compareNames);
forv_Vec(ModuleSymbol, subMod, mods) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!devOnlyModule(subMod)) {
subMod->addPrefixToName(mod->docsName() + ".");
printModule(file, subMod, tabs + 1);
}
}
}
}
void createDocsFileFolders(std::string filename) {
size_t dirCutoff = filename.find("/");
size_t total = 0;
while (dirCutoff != std::string::npos) {
// Creates each subdirectory within the new documentation directory
dirCutoff += total;
std::string shorter = filename.substr(dirCutoff+1);
std::string otherHalf = filename.substr(0, dirCutoff);
if (otherHalf.length() > 0) {
makeDir(otherHalf.c_str());
}
total = dirCutoff + 1;
dirCutoff = shorter.find("/");
}
}
/* Create the directory (non-recursively). If an error occurs, exit and report
* error.
*/
static void makeDir(const char* dirpath) {
static const int dirPerms = S_IRWXU | S_IRWXG | S_IRWXO;
int result = mkdir(dirpath, dirPerms);
if (result != 0 && errno != 0 && errno != EEXIST) {
USR_FATAL(astr("Failed to create directory: ", dirpath,
" due to: ", strerror(errno)));
}
}
/*
* Create new sphinx project at given location and return path where .rst files
* should be placed.
*/
std::string generateSphinxProject(std::string dirpath) {
// Create the output dir under the docs output dir.
const char * sphinxDir = dirpath.c_str();
// Copy the sphinx template into the output dir.
const char * sphinxTemplate = astr(CHPL_HOME, "/third-party/chpldoc-venv/chpldoc-sphinx-project/*");
const char * cmd = astr("cp -r ", sphinxTemplate, " ", sphinxDir, "/");
mysystem(cmd, "copying chpldoc sphinx template");
const char * moddir = astr(sphinxDir, "/source/modules");
return std::string(moddir);
}
/*
* Invoke sphinx-build using sphinxDir to find conf.py and rst sources, and
* outputDir for generated html files.
*/
void generateSphinxOutput(std::string sphinxDir, std::string outputDir) {
// Set the PATH and VIRTUAL_ENV variables in the environment. The values are
// based on the install path in the third-party/chpldoc-venv/ dir.
const char * venvDir = astr(
CHPL_HOME, "/third-party/chpldoc-venv/install/",
CHPL_TARGET_PLATFORM, "/chpldoc-virtualenv");
const char * venvBinDir = astr(venvDir, "/bin");
const char * sphinxBuild = astr(venvBinDir, "/sphinx-build");
const char * envVars = astr("export PATH=", venvBinDir, ":$PATH && ",
"export VIRTUAL_ENV=", venvDir);
// Run:
// $envVars &&
// sphinx-build -b html
// -d $sphinxDir/build/doctrees -W
// $sphinxDir/source $outputDir
const char * cmdPrefix = astr(envVars, " && ");
const char * cmd = astr(
cmdPrefix,
sphinxBuild, " -b html -d ",
sphinxDir.c_str(), "/build/doctrees -W ",
sphinxDir.c_str(), "/source ", outputDir.c_str());
mysystem(cmd, "building html output from chpldoc sphinx project");
printf("HTML files are at: %s\n", outputDir.c_str());
}
std::string filenameFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = mod->filename;
if (mod->modTag == MOD_INTERNAL) {
filename = "internal-modules/";
} else if (mod ->modTag == MOD_STANDARD) {
filename = "standard-modules/";
} else {
size_t location = filename.rfind("/");
if (location != std::string::npos) {
filename = filename.substr(0, location + 1);
} else {
filename = "";
}
}
filename = docsWorkDir + "/" + filename;
createDocsFileFolders(filename);
// Creates files for each top level module.
if (fDocsTextOnly) {
filename = filename + mod->name + ".txt";
} else {
filename = filename + mod->name + ".rst";
}
return filename;
}
std::ofstream* openFileFromMod(ModuleSymbol *mod, std::string docsWorkDir) {
std::string filename = filenameFromMod(mod, docsWorkDir);
return new std::ofstream(filename.c_str(), std::ios::out);
}
<|endoftext|>
|
<commit_before>// SAMPLE_PLUGIN.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include "plugin_utils.h"
class SAMPLE_PLUGIN : public bz_Plugin
{
virtual const char* Name (){return "SAMPLE PLUGIN";}
virtual void Init ( const char* config);
virtual void Event ( bz_EventData *eventData ){return;}
};
BZ_PLUGIN(SAMPLE_PLUGIN)
void SAMPLE_PLUGIN::Init ( const char* /*commandLine*/ )
{
bz_debugMessage(4,"SAMPLE_PLUGIN plugin loaded");
// init events here with Register();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Unused parameter breaks the --enable-debug build on linux<commit_after>// SAMPLE_PLUGIN.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include "plugin_utils.h"
class SAMPLE_PLUGIN : public bz_Plugin
{
virtual const char* Name (){return "SAMPLE PLUGIN";}
virtual void Init ( const char* config);
virtual void Event ( bz_EventData * /* eventData */ ){return;}
};
BZ_PLUGIN(SAMPLE_PLUGIN)
void SAMPLE_PLUGIN::Init ( const char* /*commandLine*/ )
{
bz_debugMessage(4,"SAMPLE_PLUGIN plugin loaded");
// init events here with Register();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>#include "selfdrive/ui/qt/offroad/networking.h"
#include <algorithm>
#include <QDebug>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QScrollBar>
#include "selfdrive/ui/qt/util.h"
#include "selfdrive/ui/qt/qt_window.h"
#include "selfdrive/ui/qt/widgets/controls.h"
#include "selfdrive/ui/qt/widgets/scrollview.h"
// Networking functions
Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) {
main_layout = new QStackedLayout(this);
wifi = new WifiManager(this);
connect(wifi, &WifiManager::refreshSignal, this, &Networking::refresh);
connect(wifi, &WifiManager::wrongPassword, this, &Networking::wrongPassword);
wifiScreen = new QWidget(this);
QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen);
vlayout->setContentsMargins(20, 20, 20, 20);
if (show_advanced) {
QPushButton* advancedSettings = new QPushButton("Advanced");
advancedSettings->setObjectName("advancedBtn");
advancedSettings->setStyleSheet("margin-right: 30px;");
advancedSettings->setFixedSize(350, 100);
connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); });
vlayout->addSpacing(10);
vlayout->addWidget(advancedSettings, 0, Qt::AlignRight);
vlayout->addSpacing(10);
}
wifiWidget = new WifiUI(this, wifi);
wifiWidget->setObjectName("wifiWidget");
connect(wifiWidget, &WifiUI::connectToNetwork, this, &Networking::connectToNetwork);
ScrollView *wifiScroller = new ScrollView(wifiWidget, this);
wifiScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
vlayout->addWidget(wifiScroller, 1);
main_layout->addWidget(wifiScreen);
an = new AdvancedNetworking(this, wifi);
connect(an, &AdvancedNetworking::backPress, [=]() { main_layout->setCurrentWidget(wifiScreen); });
main_layout->addWidget(an);
QPalette pal = palette();
pal.setColor(QPalette::Window, QColor(0x29, 0x29, 0x29));
setAutoFillBackground(true);
setPalette(pal);
// TODO: revisit pressed colors
setStyleSheet(R"(
#wifiWidget > QPushButton, #back_btn, #advancedBtn {
font-size: 50px;
margin: 0px;
padding: 15px;
border-width: 0;
border-radius: 30px;
color: #dddddd;
background-color: #444444;
}
)");
main_layout->setCurrentWidget(wifiScreen);
}
void Networking::refresh() {
wifiWidget->refresh();
an->refresh();
}
void Networking::connectToNetwork(const Network &n) {
if (wifi->isKnownConnection(n.ssid)) {
wifi->activateWifiConnection(n.ssid);
wifiWidget->refresh();
} else if (n.security_type == SecurityType::OPEN) {
wifi->connect(n);
} else if (n.security_type == SecurityType::WPA) {
QString pass = InputDialog::getText("Enter password", this, "for \"" + n.ssid + "\"", true, 8);
if (!pass.isEmpty()) {
wifi->connect(n, pass);
}
}
}
void Networking::wrongPassword(const QString &ssid) {
if (wifi->seenNetworks.contains(ssid)) {
const Network &n = wifi->seenNetworks.value(ssid);
QString pass = InputDialog::getText("Wrong password", this, "for \"" + n.ssid +"\"", true, 8);
if (!pass.isEmpty()) {
wifi->connect(n, pass);
}
}
}
void Networking::showEvent(QShowEvent *event) {
wifi->start();
}
void Networking::hideEvent(QHideEvent *event) {
wifi->stop();
}
// AdvancedNetworking functions
AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWidget(parent), wifi(wifi) {
QVBoxLayout* main_layout = new QVBoxLayout(this);
main_layout->setMargin(40);
main_layout->setSpacing(20);
// Back button
QPushButton* back = new QPushButton("Back");
back->setObjectName("back_btn");
back->setFixedSize(500, 100);
connect(back, &QPushButton::clicked, [=]() { emit backPress(); });
main_layout->addWidget(back, 0, Qt::AlignLeft);
ListWidget *list = new ListWidget(this);
// Enable tethering layout
tetheringToggle = new ToggleControl("Enable Tethering", "", "", wifi->isTetheringEnabled());
list->addItem(tetheringToggle);
QObject::connect(tetheringToggle, &ToggleControl::toggleFlipped, this, &AdvancedNetworking::toggleTethering);
// Change tethering password
ButtonControl *editPasswordButton = new ButtonControl("Tethering Password", "EDIT");
connect(editPasswordButton, &ButtonControl::clicked, [=]() {
QString pass = InputDialog::getText("Enter new tethering password", this, "", true, 8, wifi->getTetheringPassword());
if (!pass.isEmpty()) {
wifi->changeTetheringPassword(pass);
}
});
list->addItem(editPasswordButton);
// IP address
ipLabel = new LabelControl("IP Address", wifi->ipv4_address);
list->addItem(ipLabel);
// SSH keys
list->addItem(new SshToggle());
list->addItem(new SshControl());
// Roaming toggle
const bool roamingEnabled = params.getBool("GsmRoaming");
ToggleControl *roamingToggle = new ToggleControl("Enable Roaming", "", "", roamingEnabled);
QObject::connect(roamingToggle, &SshToggle::toggleFlipped, [=](bool state) {
params.putBool("GsmRoaming", state);
wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")));
});
list->addItem(roamingToggle);
// APN settings
ButtonControl *editApnButton = new ButtonControl("APN Setting", "EDIT");
connect(editApnButton, &ButtonControl::clicked, [=]() {
const bool roamingEnabled = params.getBool("GsmRoaming");
const QString cur_apn = QString::fromStdString(params.get("GsmApn"));
QString apn = InputDialog::getText("Enter APN", this, "leave blank for automatic configuration", false, -1, cur_apn).trimmed();
if (apn.isEmpty()) {
params.remove("GsmApn");
} else {
params.put("GsmApn", apn.toStdString());
}
wifi->updateGsmSettings(roamingEnabled, apn);
});
list->addItem(editApnButton);
// Set initial config
wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")));
main_layout->addWidget(new ScrollView(list, this));
main_layout->addStretch(1);
}
void AdvancedNetworking::refresh() {
ipLabel->setText(wifi->ipv4_address);
tetheringToggle->setEnabled(true);
update();
}
void AdvancedNetworking::toggleTethering(bool enabled) {
wifi->setTetheringEnabled(enabled);
tetheringToggle->setEnabled(false);
}
// WifiUI functions
WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) {
main_layout = new QVBoxLayout(this);
main_layout->setContentsMargins(0, 0, 0, 0);
main_layout->setSpacing(0);
// load imgs
for (const auto &s : {"low", "medium", "high", "full"}) {
QPixmap pix(ASSET_PATH + "/offroad/icon_wifi_strength_" + s + ".svg");
strengths.push_back(pix.scaledToHeight(68, Qt::SmoothTransformation));
}
lock = QPixmap(ASSET_PATH + "offroad/icon_lock_closed.svg").scaledToWidth(49, Qt::SmoothTransformation);
checkmark = QPixmap(ASSET_PATH + "offroad/icon_checkmark.svg").scaledToWidth(49, Qt::SmoothTransformation);
circled_slash = QPixmap(ASSET_PATH + "img_circled_slash.svg").scaledToWidth(49, Qt::SmoothTransformation);
QLabel *scanning = new QLabel("Scanning for networks...");
scanning->setStyleSheet("font-size: 65px;");
main_layout->addWidget(scanning, 0, Qt::AlignCenter);
setStyleSheet(R"(
QScrollBar::handle:vertical {
min-height: 0px;
border-radius: 4px;
background-color: #8A8A8A;
}
#forgetBtn {
font-size: 32px;
font-weight: 600;
color: #292929;
background-color: #BDBDBD;
border-width: 1px solid #828282;
border-radius: 5px;
padding: 40px;
padding-bottom: 16px;
padding-top: 16px;
}
#connecting {
font-size: 32px;
font-weight: 600;
color: white;
border-radius: 0;
padding: 27px;
padding-left: 43px;
padding-right: 43px;
background-color: black;
}
#ssidLabel {
font-size: 55px;
font-weight: 300;
text-align: left;
border: none;
padding-top: 50px;
padding-bottom: 50px;
}
#ssidLabel[disconnected=false] {
font-weight: 500;
}
#ssidLabel:disabled {
color: #696969;
}
)");
}
void WifiUI::refresh() {
// TODO: don't rebuild this every time
clearLayout(main_layout);
if (wifi->seenNetworks.size() == 0) {
QLabel *scanning = new QLabel("Scanning for networks...");
scanning->setStyleSheet("font-size: 65px;");
main_layout->addWidget(scanning, 0, Qt::AlignCenter);
return;
}
QList<Network> sortedNetworks = wifi->seenNetworks.values();
std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength);
// add networks
ListWidget *list = new ListWidget(this);
for (Network &network : sortedNetworks) {
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->setContentsMargins(44, 0, 73, 0);
hlayout->setSpacing(50);
// Clickable SSID label
ElidedLabel *ssidLabel = new ElidedLabel(network.ssid);
ssidLabel->setObjectName("ssidLabel");
ssidLabel->setEnabled(network.security_type != SecurityType::UNSUPPORTED);
ssidLabel->setProperty("disconnected", network.connected == ConnectedType::DISCONNECTED);
if (network.connected == ConnectedType::DISCONNECTED) {
QObject::connect(ssidLabel, &ElidedLabel::clicked, this, [=]() { emit connectToNetwork(network); });
}
hlayout->addWidget(ssidLabel, network.connected == ConnectedType::CONNECTING ? 0 : 1);
if (network.connected == ConnectedType::CONNECTING) {
QPushButton *connecting = new QPushButton("CONNECTING...");
connecting->setObjectName("connecting");
hlayout->addWidget(connecting, 2, Qt::AlignLeft);
}
// Forget button
if (wifi->isKnownConnection(network.ssid) && !wifi->isTetheringEnabled()) {
QPushButton *forgetBtn = new QPushButton("FORGET");
forgetBtn->setObjectName("forgetBtn");
QObject::connect(forgetBtn, &QPushButton::clicked, [=]() {
if (ConfirmationDialog::confirm("Forget Wi-Fi Network \"" + QString::fromUtf8(network.ssid) + "\"?", this)) {
wifi->forgetConnection(network.ssid);
}
});
hlayout->addWidget(forgetBtn, 0, Qt::AlignRight);
}
// Status icon
if (network.connected == ConnectedType::CONNECTED) {
QLabel *connectIcon = new QLabel();
connectIcon->setPixmap(checkmark);
hlayout->addWidget(connectIcon, 0, Qt::AlignRight);
} else if (network.security_type == SecurityType::UNSUPPORTED) {
QLabel *unsupportedIcon = new QLabel();
unsupportedIcon->setPixmap(circled_slash);
hlayout->addWidget(unsupportedIcon, 0, Qt::AlignRight);
} else if (network.security_type == SecurityType::WPA) {
QLabel *lockIcon = new QLabel();
lockIcon->setPixmap(lock);
hlayout->addWidget(lockIcon, 0, Qt::AlignRight);
} else {
hlayout->addSpacing(lock.width() + hlayout->spacing());
}
// Strength indicator
QLabel *strength = new QLabel();
strength->setPixmap(strengths[std::clamp((int)round(network.strength / 33.), 0, 3)]);
hlayout->addWidget(strength, 0, Qt::AlignRight);
list->addItem(hlayout);
}
main_layout->addWidget(list);
main_layout->addStretch(1);
}
<commit_msg>ui: advanced network settings fix button colors and sizes (#24846)<commit_after>#include "selfdrive/ui/qt/offroad/networking.h"
#include <algorithm>
#include <QDebug>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QScrollBar>
#include "selfdrive/ui/qt/util.h"
#include "selfdrive/ui/qt/qt_window.h"
#include "selfdrive/ui/qt/widgets/controls.h"
#include "selfdrive/ui/qt/widgets/scrollview.h"
// Networking functions
Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) {
main_layout = new QStackedLayout(this);
wifi = new WifiManager(this);
connect(wifi, &WifiManager::refreshSignal, this, &Networking::refresh);
connect(wifi, &WifiManager::wrongPassword, this, &Networking::wrongPassword);
wifiScreen = new QWidget(this);
QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen);
vlayout->setContentsMargins(20, 20, 20, 20);
if (show_advanced) {
QPushButton* advancedSettings = new QPushButton("Advanced");
advancedSettings->setObjectName("advanced_btn");
advancedSettings->setStyleSheet("margin-right: 30px;");
advancedSettings->setFixedSize(400, 100);
connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); });
vlayout->addSpacing(10);
vlayout->addWidget(advancedSettings, 0, Qt::AlignRight);
vlayout->addSpacing(10);
}
wifiWidget = new WifiUI(this, wifi);
wifiWidget->setObjectName("wifiWidget");
connect(wifiWidget, &WifiUI::connectToNetwork, this, &Networking::connectToNetwork);
ScrollView *wifiScroller = new ScrollView(wifiWidget, this);
wifiScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
vlayout->addWidget(wifiScroller, 1);
main_layout->addWidget(wifiScreen);
an = new AdvancedNetworking(this, wifi);
connect(an, &AdvancedNetworking::backPress, [=]() { main_layout->setCurrentWidget(wifiScreen); });
main_layout->addWidget(an);
QPalette pal = palette();
pal.setColor(QPalette::Window, QColor(0x29, 0x29, 0x29));
setAutoFillBackground(true);
setPalette(pal);
// TODO: revisit pressed colors
setStyleSheet(R"(
#wifiWidget > QPushButton, #back_btn, #advanced_btn {
font-size: 50px;
margin: 0px;
padding: 15px;
border-width: 0;
border-radius: 30px;
color: #dddddd;
background-color: #393939;
}
#back_btn:pressed, #advanced_btn:pressed {
background-color: #4a4a4a;
}
)");
main_layout->setCurrentWidget(wifiScreen);
}
void Networking::refresh() {
wifiWidget->refresh();
an->refresh();
}
void Networking::connectToNetwork(const Network &n) {
if (wifi->isKnownConnection(n.ssid)) {
wifi->activateWifiConnection(n.ssid);
wifiWidget->refresh();
} else if (n.security_type == SecurityType::OPEN) {
wifi->connect(n);
} else if (n.security_type == SecurityType::WPA) {
QString pass = InputDialog::getText("Enter password", this, "for \"" + n.ssid + "\"", true, 8);
if (!pass.isEmpty()) {
wifi->connect(n, pass);
}
}
}
void Networking::wrongPassword(const QString &ssid) {
if (wifi->seenNetworks.contains(ssid)) {
const Network &n = wifi->seenNetworks.value(ssid);
QString pass = InputDialog::getText("Wrong password", this, "for \"" + n.ssid +"\"", true, 8);
if (!pass.isEmpty()) {
wifi->connect(n, pass);
}
}
}
void Networking::showEvent(QShowEvent *event) {
wifi->start();
}
void Networking::hideEvent(QHideEvent *event) {
wifi->stop();
}
// AdvancedNetworking functions
AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWidget(parent), wifi(wifi) {
QVBoxLayout* main_layout = new QVBoxLayout(this);
main_layout->setMargin(40);
main_layout->setSpacing(20);
// Back button
QPushButton* back = new QPushButton("Back");
back->setObjectName("back_btn");
back->setFixedSize(400, 100);
connect(back, &QPushButton::clicked, [=]() { emit backPress(); });
main_layout->addWidget(back, 0, Qt::AlignLeft);
ListWidget *list = new ListWidget(this);
// Enable tethering layout
tetheringToggle = new ToggleControl("Enable Tethering", "", "", wifi->isTetheringEnabled());
list->addItem(tetheringToggle);
QObject::connect(tetheringToggle, &ToggleControl::toggleFlipped, this, &AdvancedNetworking::toggleTethering);
// Change tethering password
ButtonControl *editPasswordButton = new ButtonControl("Tethering Password", "EDIT");
connect(editPasswordButton, &ButtonControl::clicked, [=]() {
QString pass = InputDialog::getText("Enter new tethering password", this, "", true, 8, wifi->getTetheringPassword());
if (!pass.isEmpty()) {
wifi->changeTetheringPassword(pass);
}
});
list->addItem(editPasswordButton);
// IP address
ipLabel = new LabelControl("IP Address", wifi->ipv4_address);
list->addItem(ipLabel);
// SSH keys
list->addItem(new SshToggle());
list->addItem(new SshControl());
// Roaming toggle
const bool roamingEnabled = params.getBool("GsmRoaming");
ToggleControl *roamingToggle = new ToggleControl("Enable Roaming", "", "", roamingEnabled);
QObject::connect(roamingToggle, &SshToggle::toggleFlipped, [=](bool state) {
params.putBool("GsmRoaming", state);
wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")));
});
list->addItem(roamingToggle);
// APN settings
ButtonControl *editApnButton = new ButtonControl("APN Setting", "EDIT");
connect(editApnButton, &ButtonControl::clicked, [=]() {
const bool roamingEnabled = params.getBool("GsmRoaming");
const QString cur_apn = QString::fromStdString(params.get("GsmApn"));
QString apn = InputDialog::getText("Enter APN", this, "leave blank for automatic configuration", false, -1, cur_apn).trimmed();
if (apn.isEmpty()) {
params.remove("GsmApn");
} else {
params.put("GsmApn", apn.toStdString());
}
wifi->updateGsmSettings(roamingEnabled, apn);
});
list->addItem(editApnButton);
// Set initial config
wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")));
main_layout->addWidget(new ScrollView(list, this));
main_layout->addStretch(1);
}
void AdvancedNetworking::refresh() {
ipLabel->setText(wifi->ipv4_address);
tetheringToggle->setEnabled(true);
update();
}
void AdvancedNetworking::toggleTethering(bool enabled) {
wifi->setTetheringEnabled(enabled);
tetheringToggle->setEnabled(false);
}
// WifiUI functions
WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) {
main_layout = new QVBoxLayout(this);
main_layout->setContentsMargins(0, 0, 0, 0);
main_layout->setSpacing(0);
// load imgs
for (const auto &s : {"low", "medium", "high", "full"}) {
QPixmap pix(ASSET_PATH + "/offroad/icon_wifi_strength_" + s + ".svg");
strengths.push_back(pix.scaledToHeight(68, Qt::SmoothTransformation));
}
lock = QPixmap(ASSET_PATH + "offroad/icon_lock_closed.svg").scaledToWidth(49, Qt::SmoothTransformation);
checkmark = QPixmap(ASSET_PATH + "offroad/icon_checkmark.svg").scaledToWidth(49, Qt::SmoothTransformation);
circled_slash = QPixmap(ASSET_PATH + "img_circled_slash.svg").scaledToWidth(49, Qt::SmoothTransformation);
QLabel *scanning = new QLabel("Scanning for networks...");
scanning->setStyleSheet("font-size: 65px;");
main_layout->addWidget(scanning, 0, Qt::AlignCenter);
setStyleSheet(R"(
QScrollBar::handle:vertical {
min-height: 0px;
border-radius: 4px;
background-color: #8A8A8A;
}
#forgetBtn {
font-size: 32px;
font-weight: 600;
color: #292929;
background-color: #BDBDBD;
border-width: 1px solid #828282;
border-radius: 5px;
padding: 40px;
padding-bottom: 16px;
padding-top: 16px;
}
#connecting {
font-size: 32px;
font-weight: 600;
color: white;
border-radius: 0;
padding: 27px;
padding-left: 43px;
padding-right: 43px;
background-color: black;
}
#ssidLabel {
font-size: 55px;
font-weight: 300;
text-align: left;
border: none;
padding-top: 50px;
padding-bottom: 50px;
}
#ssidLabel[disconnected=false] {
font-weight: 500;
}
#ssidLabel:disabled {
color: #696969;
}
)");
}
void WifiUI::refresh() {
// TODO: don't rebuild this every time
clearLayout(main_layout);
if (wifi->seenNetworks.size() == 0) {
QLabel *scanning = new QLabel("Scanning for networks...");
scanning->setStyleSheet("font-size: 65px;");
main_layout->addWidget(scanning, 0, Qt::AlignCenter);
return;
}
QList<Network> sortedNetworks = wifi->seenNetworks.values();
std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength);
// add networks
ListWidget *list = new ListWidget(this);
for (Network &network : sortedNetworks) {
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->setContentsMargins(44, 0, 73, 0);
hlayout->setSpacing(50);
// Clickable SSID label
ElidedLabel *ssidLabel = new ElidedLabel(network.ssid);
ssidLabel->setObjectName("ssidLabel");
ssidLabel->setEnabled(network.security_type != SecurityType::UNSUPPORTED);
ssidLabel->setProperty("disconnected", network.connected == ConnectedType::DISCONNECTED);
if (network.connected == ConnectedType::DISCONNECTED) {
QObject::connect(ssidLabel, &ElidedLabel::clicked, this, [=]() { emit connectToNetwork(network); });
}
hlayout->addWidget(ssidLabel, network.connected == ConnectedType::CONNECTING ? 0 : 1);
if (network.connected == ConnectedType::CONNECTING) {
QPushButton *connecting = new QPushButton("CONNECTING...");
connecting->setObjectName("connecting");
hlayout->addWidget(connecting, 2, Qt::AlignLeft);
}
// Forget button
if (wifi->isKnownConnection(network.ssid) && !wifi->isTetheringEnabled()) {
QPushButton *forgetBtn = new QPushButton("FORGET");
forgetBtn->setObjectName("forgetBtn");
QObject::connect(forgetBtn, &QPushButton::clicked, [=]() {
if (ConfirmationDialog::confirm("Forget Wi-Fi Network \"" + QString::fromUtf8(network.ssid) + "\"?", this)) {
wifi->forgetConnection(network.ssid);
}
});
hlayout->addWidget(forgetBtn, 0, Qt::AlignRight);
}
// Status icon
if (network.connected == ConnectedType::CONNECTED) {
QLabel *connectIcon = new QLabel();
connectIcon->setPixmap(checkmark);
hlayout->addWidget(connectIcon, 0, Qt::AlignRight);
} else if (network.security_type == SecurityType::UNSUPPORTED) {
QLabel *unsupportedIcon = new QLabel();
unsupportedIcon->setPixmap(circled_slash);
hlayout->addWidget(unsupportedIcon, 0, Qt::AlignRight);
} else if (network.security_type == SecurityType::WPA) {
QLabel *lockIcon = new QLabel();
lockIcon->setPixmap(lock);
hlayout->addWidget(lockIcon, 0, Qt::AlignRight);
} else {
hlayout->addSpacing(lock.width() + hlayout->spacing());
}
// Strength indicator
QLabel *strength = new QLabel();
strength->setPixmap(strengths[std::clamp((int)round(network.strength / 33.), 0, 3)]);
hlayout->addWidget(strength, 0, Qt::AlignRight);
list->addItem(hlayout);
}
main_layout->addWidget(list);
main_layout->addStretch(1);
}
<|endoftext|>
|
<commit_before>#include "CaffeBatchPrediction.hpp"
#include "classifierio.hpp"
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
::google::InitGoogleLogging(argv[0]);
if (argc < 2)
{
cout << "Usage : " << argv[0] << " filelist_of_imgs.txt" << endl;
return 1;
}
ClassifierIO clio("d24", 5, -1);
vector<string> files = clio.getClassifierFiles();
for (auto it = files.cbegin(); it != files.cend(); ++it)
cout << *it << endl;
ifstream infile(argv[1]);
CaffeClassifier<Mat> c(files[0], files[1], files[2], files[3], 256);
Mat img;
Mat rsz;
Mat f32;
vector<Mat> imgs;
string filename;
while(getline(infile, filename))
{
cout << "Read " << filename << endl;
img = imread(filename);
resize(img, rsz, c.getInputGeometry());
rsz.convertTo(f32, CV_32FC3, 1/255.);
imgs.push_back(f32.clone());
}
while (clio.findNextClassifierStage(false))
{
vector<string> files = clio.getClassifierFiles();
CaffeClassifier<Mat> c(files[0], files[1], files[2], files[3], 256);
vector<vector<Prediction>> p = c.ClassifyBatch(imgs,2);
for (auto v = p.cbegin(); v != p.cend(); ++v)
{
for (auto it = v->cbegin(); it != v->cend(); ++it)
cout << it->first << " " << it->second << " ";
cout << endl;
}
cout <<"---------------------"<< endl;
}
return 0;
}
<commit_msg>Updates to print all epochs<commit_after>#include "CaffeBatchPrediction.hpp"
#include "classifierio.hpp"
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
::google::InitGoogleLogging(argv[0]);
if (argc < 2)
{
cout << "Usage : " << argv[0] << " filelist_of_imgs.txt" << endl;
return 1;
}
ClassifierIO clio("d24", 5, -1);
vector<string> files = clio.getClassifierFiles();
for (auto it = files.cbegin(); it != files.cend(); ++it)
cout << *it << endl;
ifstream infile(argv[1]);
CaffeClassifier<Mat> c(files[0], files[1], files[2], files[3], 256);
Mat img;
Mat rsz;
Mat f32;
vector<Mat> imgs;
string filename;
while(getline(infile, filename))
{
cout << "Read " << filename << endl;
img = imread(filename);
resize(img, rsz, c.getInputGeometry());
rsz.convertTo(f32, CV_32FC3, 1/255.);
imgs.push_back(f32.clone());
}
while (clio.findNextClassifierStage(false))
{
vector<string> files = clio.getClassifierFiles();
CaffeClassifier<Mat> c(files[0], files[1], files[2], files[3], 256);
vector<vector<Prediction>> p = c.ClassifyBatch(imgs,2);
for (auto v = p.cbegin(); v != p.cend(); ++v)
{
for (auto it = v->cbegin(); it != v->cend(); ++it)
cout << it->first << " " << it->second << " ";
cout << endl;
}
cout <<"---------------------"<< endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <vector>
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
namespace acmacs
{
template <typename Key, typename Value> class flat_map_t
{
public:
using key_type = Key;
using value_type = Value;
using entry_type = std::pair<Key, Value>;
flat_map_t() = default;
template <typename Iter> flat_map_t(Iter first, Iter last) : data_(first, last) {}
flat_map_t(std::initializer_list<entry_type> init) : data_{init} {}
auto begin() const { return data_.begin(); }
auto end() const { return data_.end(); }
auto empty() const { return data_.empty(); }
auto size() const { return data_.size(); }
const auto& operator[](size_t index) const { return data_[index]; }
void sort_by_key() { std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.first < e2.first; }); }
void sort_by_value() { std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second < e2.second; }); }
void sort_by_value_reverse() { std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second > e2.second; }); }
template <typename K> auto find(const K& key) const { return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; }); }
template <typename K> auto find(const K& key) { return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; }); }
template <typename K> bool exists(const K& key) const { return find(key) != std::end(data_); }
Value& at(const Key& key)
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
}
const Value& at(const Key& key) const
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
}
const Value* at_ptr(const Key& key) const
{
if (const auto found = find(key); found != std::end(data_))
return &found->second;
else
return nullptr;
}
auto& emplace(const Key& key, const Value& value) { return data_.emplace_back(key, value); }
auto& emplace(Key&& key, Value&& value) { return data_.emplace_back(std::move(key), std::move(value)); }
auto& emplace_or_replace(const Key& key, const Value& value)
{
if (auto found = find(key); found != std::end(data_)) {
found->second = value;
return *found;
}
else
return emplace(key, value);
}
auto& emplace_not_replace(const Key& key, const Value& value)
{
if (auto found = find(key); found != std::end(data_))
return *found;
else
return emplace(key, value);
}
auto& emplace_not_replace(const Key& key)
{
if (auto found = find(key); found != std::end(data_))
return *found;
else
return emplace(key, Value{});
}
void reserve(size_t sz) { data_.reserve(sz); }
private:
std::vector<entry_type> data_;
};
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>map_with_duplicating_keys_t<commit_after>#pragma once
#include <vector>
#include "acmacs-base/fmt.hh"
#include "acmacs-base/range-v3.hh"
// ----------------------------------------------------------------------
namespace acmacs
{
// see seqdb.cc Seqdb::hash_index() for sample usage
template <typename Key, typename Value> class map_with_duplicating_keys_t
{
public:
using entry_type = std::pair<Key, Value>;
using const_iterator = typename std::vector<entry_type>::const_iterator;
map_with_duplicating_keys_t() = default;
template <typename Range> void collect(Range&& rng)
{
data_ = rng | ranges::to<std::vector>;
ranges::sort(data_, [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
}
bool empty() const noexcept { return data_.empty(); }
template <typename FindKey> std::pair<const_iterator, const_iterator> find(const FindKey& key) const noexcept
{
const auto first = std::lower_bound(std::begin(data_), std::end(data_), key, [](const auto& e1, const auto& k2) { return e1.first < k2; });
// first may point to the wrong key, if key is not in the map
return {first, std::find_if(first, std::end(data_), [&key](const auto& en) { return en.first != key; })};
}
constexpr const auto& data() const { return data_; }
private:
std::vector<entry_type> data_;
};
// ----------------------------------------------------------------------
// see seqdb.cc Seqdb::seq_id_index() for sample usage
template <typename Key, typename Value> class map_with_unique_keys_t
{
public:
using entry_type = std::pair<Key, Value>;
map_with_unique_keys_t() = default;
template <typename Range> void collect(Range&& rng, bool check = true)
{
data_ = rng | ranges::to<std::vector>;
ranges::sort(data_, [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
if (check && data_.size() > 1) {
for (auto cur = std::next(std::begin(data_)); cur != std::end(data_); ++cur) {
if (cur->first == std::prev(cur)->first)
throw std::runtime_error{"duplicating keys within map_with_unique_keys_t"};
}
}
}
bool empty() const noexcept { return data_.empty(); }
const Value* find(const Key& key) const noexcept
{
if (const auto first = std::lower_bound(std::begin(data_), std::end(data_), key, [](const auto& e1, const auto& k2) { return e1.first < k2; }); first->first == key)
return &first->second;
else
return nullptr;
}
constexpr const auto& data() const { return data_; }
private:
std::vector<entry_type> data_;
};
// ----------------------------------------------------------------------
template <typename Key, typename Value> class flat_map_t
{
public:
using key_type = Key;
using value_type = Value;
using entry_type = std::pair<Key, Value>;
flat_map_t() = default;
template <typename Iter> flat_map_t(Iter first, Iter last) : data_(first, last) {}
flat_map_t(std::initializer_list<entry_type> init) : data_{init} {}
auto begin() const { return data_.begin(); }
auto end() const { return data_.end(); }
auto empty() const { return data_.empty(); }
auto size() const { return data_.size(); }
const auto& operator[](size_t index) const { return data_[index]; }
const auto& back() const { return data_.back(); }
auto& back() { return data_.back(); }
void sort_by_key()
{
std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
}
void sort_by_value()
{
std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second < e2.second; });
}
void sort_by_value_reverse()
{
std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second > e2.second; });
}
template <typename K> auto find(const K& key) const
{
return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
}
template <typename K> auto find(const K& key)
{
return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
}
template <typename K> bool exists(const K& key) const { return find(key) != std::end(data_); }
Value& at(const Key& key)
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
}
const Value& at(const Key& key) const
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
}
const Value* at_ptr(const Key& key) const
{
if (const auto found = find(key); found != std::end(data_))
return &found->second;
else
return nullptr;
}
auto& emplace(const Key& key, const Value& value) { return data_.emplace_back(key, value); }
auto& emplace(Key&& key, Value&& value) { return data_.emplace_back(std::move(key), std::move(value)); }
auto& emplace_or_replace(const Key& key, const Value& value)
{
if (auto found = find(key); found != std::end(data_)) {
found->second = value;
return *found;
}
else
return emplace(key, value);
}
auto& emplace_not_replace(const Key& key, const Value& value)
{
if (auto found = find(key); found != std::end(data_))
return *found;
else
return emplace(key, value);
}
auto& emplace_not_replace(const Key& key)
{
if (auto found = find(key); found != std::end(data_))
return *found;
else
return emplace(key, Value{});
}
void reserve(size_t sz) { data_.reserve(sz); }
private:
std::vector<entry_type> data_;
};
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>#pragma once
#include <string_view>
#include <string>
#include <vector>
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
namespace acmacs::messages::inline v1
{
using key_t = std::string_view;
using value_t = std::string;
// ----------------------------------------------------------------------
namespace key
{
constexpr static inline key_t unrecognized{"unrecognized"};
}
// ----------------------------------------------------------------------
namespace detail
{
struct position_t
{
std::string filename{};
size_t line_no{0};
position_t() = default;
position_t(std::string_view a_filename, size_t a_line_no) : filename{a_filename}, line_no{a_line_no} {}
};
} // namespace detail
struct position_t : public detail::position_t
{
using detail::position_t::position_t;
};
struct code_position_t : public detail::position_t
{
using detail::position_t::position_t;
};
struct message_t
{
key_t key;
std::string value;
position_t source;
code_position_t code;
// message_t& operator=(message_t&&) = default;
// parsing_message_t(const parsing_message_t&) = default;
message_t(key_t a_key, std::string_view a_value = {}) : key{a_key}, value{a_value} {}
message_t(key_t a_key, std::string_view a_value, const position_t& a_pos) : key{a_key}, value{a_value}, source{a_pos} {}
message_t(key_t a_key, std::string_view a_value, const code_position_t& a_code) : key{a_key}, value{a_value}, code{a_code} {}
message_t(key_t a_key, std::string_view a_value, const position_t& a_pos, const code_position_t& a_code) : key{a_key}, value{a_value}, source{a_pos}, code{a_code} {}
// // parsing_message_t(std::string_view a_key, std::string_view a_value, std::string_view a_suppliment) : key{a_key}, value{a_value}, suppliment{a_suppliment} {}
// parsing_message_t(std::string_view a_key = unrecognized) : key(a_key) {}
// bool operator==(std::string_view a_key) const { return key == a_key; }
// bool operator==(const parsing_message_t& rhs) const { return key == rhs.key && value == rhs.value; }
};
using messages_t = std::vector<message_t>;
void move(messages_t& target, messages_t&& from);
void move_and_add_source(messages_t& target, messages_t&& from, const position_t& source);
void report_by_type(messages_t& messages);
// ----------------------------------------------------------------------
using iter_t = typename messages_t::const_iterator;
using index_entry_t = std::pair<iter_t, iter_t>;
using index_t = std::vector<index_entry_t>;
index_t make_index(messages_t& messages);
void report(const index_t& index);
void report(iter_t first, iter_t last);
void report_by_count(iter_t first, iter_t last);
void report(key_t key, const index_t& index);
index_entry_t find(key_t key, const index_t& index);
} // namespace acmacs::messages::inline v1
// ----------------------------------------------------------------------
// template <> struct fmt::formatter<acmacs::messages::v1::detail::position_t> : public fmt::formatter<acmacs::fmt_helper::default_formatter>
// {
// template <typename FormatContext> auto format(const acmacs::messages::v1::detail::position_t& pos, FormatContext& ctx)
// {
// if (!pos.filename.empty())
// format_to(ctx.out(), " @@ {}:{}", pos.filename, pos.line_no);
// return ctx.out();
// }
// };
// ----------------------------------------------------------------------
#define MESSAGE_CODE_POSITION acmacs::messages::v1::code_position_t{__FILE__, __LINE__}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>formatting messages<commit_after>#pragma once
#include <string_view>
#include <string>
#include <vector>
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
namespace acmacs::messages::inline v1
{
using key_t = std::string_view;
using value_t = std::string;
// ----------------------------------------------------------------------
namespace key
{
constexpr static inline key_t unrecognized{"unrecognized"};
}
// ----------------------------------------------------------------------
namespace detail
{
struct position_t
{
std::string filename{};
size_t line_no{0};
position_t() = default;
position_t(std::string_view a_filename, size_t a_line_no) : filename{a_filename}, line_no{a_line_no} {}
};
} // namespace detail
struct position_t : public detail::position_t
{
using detail::position_t::position_t;
};
struct code_position_t : public detail::position_t
{
using detail::position_t::position_t;
};
struct message_t
{
key_t key;
std::string value;
position_t source;
code_position_t code;
// message_t& operator=(message_t&&) = default;
// parsing_message_t(const parsing_message_t&) = default;
message_t(key_t a_key, std::string_view a_value = {}) : key{a_key}, value{a_value} {}
message_t(key_t a_key, std::string_view a_value, const position_t& a_pos) : key{a_key}, value{a_value}, source{a_pos} {}
message_t(key_t a_key, std::string_view a_value, const code_position_t& a_code) : key{a_key}, value{a_value}, code{a_code} {}
message_t(key_t a_key, std::string_view a_value, const position_t& a_pos, const code_position_t& a_code) : key{a_key}, value{a_value}, source{a_pos}, code{a_code} {}
// // parsing_message_t(std::string_view a_key, std::string_view a_value, std::string_view a_suppliment) : key{a_key}, value{a_value}, suppliment{a_suppliment} {}
// parsing_message_t(std::string_view a_key = unrecognized) : key(a_key) {}
// bool operator==(std::string_view a_key) const { return key == a_key; }
// bool operator==(const parsing_message_t& rhs) const { return key == rhs.key && value == rhs.value; }
};
using messages_t = std::vector<message_t>;
void move(messages_t& target, messages_t&& from);
void move_and_add_source(messages_t& target, messages_t&& from, const position_t& source);
void report_by_type(messages_t& messages);
// ----------------------------------------------------------------------
using iter_t = typename messages_t::const_iterator;
using index_entry_t = std::pair<iter_t, iter_t>;
using index_t = std::vector<index_entry_t>;
index_t make_index(messages_t& messages);
void report(const index_t& index);
void report(iter_t first, iter_t last);
void report_by_count(iter_t first, iter_t last);
void report(key_t key, const index_t& index);
index_entry_t find(key_t key, const index_t& index);
} // namespace acmacs::messages::inline v1
// ----------------------------------------------------------------------
template <> struct fmt::formatter<acmacs::messages::v1::detail::position_t> : public fmt::formatter<acmacs::fmt_helper::default_formatter>
{
template <typename FormatContext> auto format(const acmacs::messages::v1::detail::position_t& pos, FormatContext& ctx)
{
if (!pos.filename.empty())
format_to(ctx.out(), " @@ {}:{}", pos.filename, pos.line_no);
return ctx.out();
}
};
template <> struct fmt::formatter<acmacs::messages::v1::position_t> : public fmt::formatter<acmacs::messages::v1::detail::position_t>
{
};
template <> struct fmt::formatter<acmacs::messages::v1::code_position_t> : public fmt::formatter<acmacs::messages::v1::detail::position_t>
{
};
template <> struct fmt::formatter<acmacs::messages::v1::message_t> : public fmt::formatter<acmacs::fmt_helper::default_formatter>
{
template <typename FormatContext> auto format(const acmacs::messages::v1::message_t& msg, FormatContext& ctx)
{
return format_to(ctx.out(), "{}: \"{}\"{}{}", msg.key, msg.value, msg.source, msg.code);
}
};
// ----------------------------------------------------------------------
#define MESSAGE_CODE_POSITION acmacs::messages::v1::code_position_t{__FILE__, __LINE__}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>#pragma once
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wreserved-id-macro" // in Python.h
#pragma GCC diagnostic ignored "-Wextra-semi"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wrange-loop-analysis"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#pragma GCC diagnostic ignored "-Wundef"
#pragma GCC diagnostic ignored "-Wdocumentation"
#pragma GCC diagnostic ignored "-Wcovered-switch-default"
#endif
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#pragma GCC diagnostic pop
namespace py = pybind11;
// ----------------------------------------------------------------------
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wmissing-prototypes"
// // #pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>pybind11 warning disabled<commit_after>#pragma once
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wreserved-id-macro" // in Python.h
#pragma GCC diagnostic ignored "-Wextra-semi"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wrange-loop-analysis"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#pragma GCC diagnostic ignored "-Wundef"
#pragma GCC diagnostic ignored "-Wdocumentation"
#pragma GCC diagnostic ignored "-Wcovered-switch-default"
#pragma GCC diagnostic ignored "-Wclass-varargs"
#endif
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#pragma GCC diagnostic pop
namespace py = pybind11;
// ----------------------------------------------------------------------
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wmissing-prototypes"
// // #pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QString>
#include "debugging.h"
#include <qmljs_environment.h>
#include <qmljs_objects.h>
#include <qv4ecmaobjects_p.h>
namespace QQmlJS {
namespace VM {
DiagnosticMessage::DiagnosticMessage()
: offset(0)
, length(0)
, startLine(0)
, startColumn(0)
, type(0)
, next(0)
{}
DiagnosticMessage::~DiagnosticMessage()
{
delete next;
}
String *DiagnosticMessage::buildFullMessage(ExecutionContext *ctx) const
{
QString msg;
if (!fileName.isEmpty())
msg = fileName + QLatin1Char(':');
msg += QString::number(startLine) + QLatin1Char(':') + QString::number(startColumn) + QLatin1String(": ");
if (type == QQmlJS::VM::DiagnosticMessage::Error)
msg += QLatin1String("error");
else
msg += QLatin1String("warning");
msg += ": " + message;
return ctx->engine->newString(msg);
}
bool ExecutionContext::hasBinding(String *name) const
{
if (!function)
return false;
for (unsigned int i = 0; i < function->varCount; ++i) {
if (__qmljs_string_equal(function->varList[i], name))
return true;
}
for (unsigned int i = 0; i < function->formalParameterCount; ++i) {
if (__qmljs_string_equal(function->formalParameterList[i], name))
return true;
}
if (activation)
return activation->__hasProperty__(this, name);
return false;
}
void ExecutionContext::createMutableBinding(String *name, bool deletable)
{
if (!activation)
activation = engine->newActivationObject();
if (activation->__hasProperty__(this, name))
return;
PropertyDescriptor desc;
desc.value = Value::undefinedValue();
desc.type = PropertyDescriptor::Data;
desc.configurable = deletable ? PropertyDescriptor::Set : PropertyDescriptor::Unset;
desc.writable = PropertyDescriptor::Set;
desc.enumberable = PropertyDescriptor::Set;
activation->__defineOwnProperty__(this, name, &desc);
}
bool ExecutionContext::setMutableBinding(ExecutionContext *scope, String *name, Value value)
{
// ### throw if scope->strict is true, and it would change an immutable binding
for (unsigned int i = 0; i < variableCount(); ++i) {
if (__qmljs_string_equal(variables()[i], name)) {
locals[i] = value;
return true;
}
}
for (unsigned int i = 0; i < formalCount(); ++i) {
if (__qmljs_string_equal(formals()[i], name)) {
arguments[i] = value;
return true;
}
}
if (activation && activation->__hasProperty__(scope, name)) {
activation->__put__(scope, name, value);
return true;
}
return false;
}
Value ExecutionContext::getBindingValue(ExecutionContext *scope, String *name, bool strict) const
{
Q_UNUSED(strict);
assert(function);
for (unsigned int i = 0; i < variableCount(); ++i) {
if (__qmljs_string_equal(variables()[i], name))
return locals[i];
}
for (unsigned int i = 0; i < formalCount(); ++i) {
if (__qmljs_string_equal(formals()[i], name))
return arguments[i];
}
if (activation && activation->__hasProperty__(this, name))
return activation->__get__(scope, name);
assert(false);
}
bool ExecutionContext::deleteBinding(ExecutionContext *scope, String *name)
{
if (activation)
activation->__delete__(scope, name);
if (scope->strictMode)
__qmljs_throw_type_error(scope);
return false;
}
void ExecutionContext::pushWithObject(Object *with)
{
With *w = new With;
w->next = withObject;
w->object = with;
withObject = w;
}
void ExecutionContext::popWithObject()
{
assert(withObject);
With *w = withObject;
withObject = w->next;
delete w;
}
ExecutionContext *ExecutionContext::outer() const
{
return function ? function->scope : 0;
}
String **ExecutionContext::formals() const
{
return function ? function->formalParameterList : 0;
}
unsigned int ExecutionContext::formalCount() const
{
return function ? function->formalParameterCount : 0;
}
String **ExecutionContext::variables() const
{
return function ? function->varList : 0;
}
unsigned int ExecutionContext::variableCount() const
{
return function ? function->varCount : 0;
}
void ExecutionContext::init(ExecutionEngine *eng)
{
engine = eng;
parent = 0;
thisObject = Value::nullValue();
function = 0;
arguments = 0;
argumentCount = 0;
locals = 0;
strictMode = false;
activation = 0;
withObject = 0;
eng->exception = Value::undefinedValue();
}
bool ExecutionContext::deleteProperty(String *name)
{
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->withObject) {
ExecutionContext::With *w = ctx->withObject;
while (w) {
if (w->object->__hasProperty__(this, name))
w->object->__delete__(this, name);
w = w->next;
}
}
if (ctx->activation) {
if (ctx->activation->__hasProperty__(this, name))
ctx->activation->__delete__(this, name);
}
}
if (strictMode)
throwSyntaxError(0);
return true;
}
void ExecutionContext::setProperty(String *name, Value value)
{
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->withObject) {
With *w = ctx->withObject;
while (w) {
if (w->object->__hasProperty__(ctx, name)) {
w->object->__put__(ctx, name, value);
return;
}
w = w->next;
}
}
if (ctx->setMutableBinding(this, name, value))
return;
}
if (strictMode)
throwReferenceError(Value::fromString(name));
engine->globalObject.objectValue()->__put__(this, name, value);
}
Value ExecutionContext::getProperty(String *name)
{
PropertyDescriptor tmp;
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->withObject) {
With *w = ctx->withObject;
while (w) {
if (PropertyDescriptor *pd = w->object->__getPropertyDescriptor__(this, name, &tmp))
return pd->value;
w = w->next;
}
}
for (unsigned int i = 0; i < ctx->variableCount(); ++i)
if (__qmljs_string_equal(ctx->variables()[i], name))
return ctx->locals[i];
for (unsigned int i = 0; i < ctx->formalCount(); ++i)
if (__qmljs_string_equal(ctx->formals()[i], name))
return ctx->arguments[i];
if (ctx->activation && ctx->activation->__hasProperty__(ctx, name))
return ctx->activation->__get__(ctx, name);
if (name->isEqualTo(ctx->engine->id_arguments)) {
Value arguments = Value::fromObject(new ArgumentsObject(this));
createMutableBinding(ctx->engine->id_arguments, false);
setMutableBinding(this, ctx->engine->id_arguments, arguments);
return arguments;
}
}
throwReferenceError(Value::fromString(name));
return Value::undefinedValue();
}
void ExecutionContext::inplaceBitOp(Value value, String *name, BinOp op)
{
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->activation) {
if (ctx->activation->inplaceBinOp(value, name, op, this))
return;
}
}
throwReferenceError(Value::fromString(name));
}
void ExecutionContext::throwError(Value value)
{
__qmljs_builtin_throw(value, this);
}
void ExecutionContext::throwError(const QString &message)
{
Value v = Value::fromString(this, message);
throwError(Value::fromObject(engine->newErrorObject(v)));
}
void ExecutionContext::throwSyntaxError(DiagnosticMessage *message)
{
throwError(Value::fromObject(engine->newSyntaxErrorObject(this, message)));
}
void ExecutionContext::throwTypeError()
{
throwError(Value::fromObject(engine->newTypeErrorObject(this, QStringLiteral("Type error"))));
}
void ExecutionContext::throwUnimplemented(const QString &message)
{
Value v = Value::fromString(this, QStringLiteral("Unimplemented ") + message);
throwError(Value::fromObject(engine->newErrorObject(v)));
}
void ExecutionContext::throwReferenceError(Value value)
{
String *s = value.toString(this);
QString msg = s->toQString() + QStringLiteral(" is not defined");
throwError(Value::fromObject(engine->newReferenceErrorObject(this, msg)));
}
void ExecutionContext::initCallContext(ExecutionContext *parent, const Value that, FunctionObject *f, Value *args, unsigned argc)
{
engine = parent->engine;
this->parent = parent;
thisObject = that;
function = f;
strictMode = f->strictMode;
arguments = args;
argumentCount = argc;
if (function->needsActivation || argc < function->formalParameterCount){
arguments = new Value[qMax(argc, function->formalParameterCount)];
if (argc)
std::copy(args, args + argc, arguments);
if (argc < function->formalParameterCount)
std::fill(arguments + argc, arguments + function->formalParameterCount, Value::undefinedValue());
}
locals = function->varCount ? new Value[function->varCount] : 0;
if (function->varCount)
std::fill(locals, locals + function->varCount, Value::undefinedValue());
if (function->needsActivation)
activation = engine->newActivationObject();
else
activation = 0;
withObject = 0;
if (engine->debugger)
engine->debugger->aboutToCall(f, this);
}
void ExecutionContext::leaveCallContext()
{
// ## Should rather be handled by a the activation object having a ref to the environment
if (activation) {
delete[] locals;
locals = 0;
}
parent = 0;
if (engine->debugger)
engine->debugger->justLeft(this);
}
void ExecutionContext::wireUpPrototype()
{
assert(thisObject.isObject());
Value proto = function->__get__(this, engine->id_prototype);
if (proto.isObject())
thisObject.objectValue()->prototype = proto.objectValue();
else
thisObject.objectValue()->prototype = engine->objectPrototype;
}
} // namespace VM
} // namespace QQmlJS
<commit_msg>Use __get__, so that accessor properties work correctly<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QString>
#include "debugging.h"
#include <qmljs_environment.h>
#include <qmljs_objects.h>
#include <qv4ecmaobjects_p.h>
namespace QQmlJS {
namespace VM {
DiagnosticMessage::DiagnosticMessage()
: offset(0)
, length(0)
, startLine(0)
, startColumn(0)
, type(0)
, next(0)
{}
DiagnosticMessage::~DiagnosticMessage()
{
delete next;
}
String *DiagnosticMessage::buildFullMessage(ExecutionContext *ctx) const
{
QString msg;
if (!fileName.isEmpty())
msg = fileName + QLatin1Char(':');
msg += QString::number(startLine) + QLatin1Char(':') + QString::number(startColumn) + QLatin1String(": ");
if (type == QQmlJS::VM::DiagnosticMessage::Error)
msg += QLatin1String("error");
else
msg += QLatin1String("warning");
msg += ": " + message;
return ctx->engine->newString(msg);
}
bool ExecutionContext::hasBinding(String *name) const
{
if (!function)
return false;
for (unsigned int i = 0; i < function->varCount; ++i) {
if (__qmljs_string_equal(function->varList[i], name))
return true;
}
for (unsigned int i = 0; i < function->formalParameterCount; ++i) {
if (__qmljs_string_equal(function->formalParameterList[i], name))
return true;
}
if (activation)
return activation->__hasProperty__(this, name);
return false;
}
void ExecutionContext::createMutableBinding(String *name, bool deletable)
{
if (!activation)
activation = engine->newActivationObject();
if (activation->__hasProperty__(this, name))
return;
PropertyDescriptor desc;
desc.value = Value::undefinedValue();
desc.type = PropertyDescriptor::Data;
desc.configurable = deletable ? PropertyDescriptor::Set : PropertyDescriptor::Unset;
desc.writable = PropertyDescriptor::Set;
desc.enumberable = PropertyDescriptor::Set;
activation->__defineOwnProperty__(this, name, &desc);
}
bool ExecutionContext::setMutableBinding(ExecutionContext *scope, String *name, Value value)
{
// ### throw if scope->strict is true, and it would change an immutable binding
for (unsigned int i = 0; i < variableCount(); ++i) {
if (__qmljs_string_equal(variables()[i], name)) {
locals[i] = value;
return true;
}
}
for (unsigned int i = 0; i < formalCount(); ++i) {
if (__qmljs_string_equal(formals()[i], name)) {
arguments[i] = value;
return true;
}
}
if (activation && activation->__hasProperty__(scope, name)) {
activation->__put__(scope, name, value);
return true;
}
return false;
}
Value ExecutionContext::getBindingValue(ExecutionContext *scope, String *name, bool strict) const
{
Q_UNUSED(strict);
assert(function);
for (unsigned int i = 0; i < variableCount(); ++i) {
if (__qmljs_string_equal(variables()[i], name))
return locals[i];
}
for (unsigned int i = 0; i < formalCount(); ++i) {
if (__qmljs_string_equal(formals()[i], name))
return arguments[i];
}
if (activation && activation->__hasProperty__(this, name))
return activation->__get__(scope, name);
assert(false);
}
bool ExecutionContext::deleteBinding(ExecutionContext *scope, String *name)
{
if (activation)
activation->__delete__(scope, name);
if (scope->strictMode)
__qmljs_throw_type_error(scope);
return false;
}
void ExecutionContext::pushWithObject(Object *with)
{
With *w = new With;
w->next = withObject;
w->object = with;
withObject = w;
}
void ExecutionContext::popWithObject()
{
assert(withObject);
With *w = withObject;
withObject = w->next;
delete w;
}
ExecutionContext *ExecutionContext::outer() const
{
return function ? function->scope : 0;
}
String **ExecutionContext::formals() const
{
return function ? function->formalParameterList : 0;
}
unsigned int ExecutionContext::formalCount() const
{
return function ? function->formalParameterCount : 0;
}
String **ExecutionContext::variables() const
{
return function ? function->varList : 0;
}
unsigned int ExecutionContext::variableCount() const
{
return function ? function->varCount : 0;
}
void ExecutionContext::init(ExecutionEngine *eng)
{
engine = eng;
parent = 0;
thisObject = Value::nullValue();
function = 0;
arguments = 0;
argumentCount = 0;
locals = 0;
strictMode = false;
activation = 0;
withObject = 0;
eng->exception = Value::undefinedValue();
}
bool ExecutionContext::deleteProperty(String *name)
{
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->withObject) {
ExecutionContext::With *w = ctx->withObject;
while (w) {
if (w->object->__hasProperty__(this, name))
w->object->__delete__(this, name);
w = w->next;
}
}
if (ctx->activation) {
if (ctx->activation->__hasProperty__(this, name))
ctx->activation->__delete__(this, name);
}
}
if (strictMode)
throwSyntaxError(0);
return true;
}
void ExecutionContext::setProperty(String *name, Value value)
{
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->withObject) {
With *w = ctx->withObject;
while (w) {
if (w->object->__hasProperty__(ctx, name)) {
w->object->__put__(ctx, name, value);
return;
}
w = w->next;
}
}
if (ctx->setMutableBinding(this, name, value))
return;
}
if (strictMode)
throwReferenceError(Value::fromString(name));
engine->globalObject.objectValue()->__put__(this, name, value);
}
Value ExecutionContext::getProperty(String *name)
{
PropertyDescriptor tmp;
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->withObject) {
With *w = ctx->withObject;
while (w) {
if (w->object->__hasProperty__(ctx, name))
return w->object->__get__(ctx, name);
w = w->next;
}
}
for (unsigned int i = 0; i < ctx->variableCount(); ++i)
if (__qmljs_string_equal(ctx->variables()[i], name))
return ctx->locals[i];
for (unsigned int i = 0; i < ctx->formalCount(); ++i)
if (__qmljs_string_equal(ctx->formals()[i], name))
return ctx->arguments[i];
if (ctx->activation && ctx->activation->__hasProperty__(ctx, name))
return ctx->activation->__get__(ctx, name);
if (name->isEqualTo(ctx->engine->id_arguments)) {
Value arguments = Value::fromObject(new ArgumentsObject(this));
createMutableBinding(ctx->engine->id_arguments, false);
setMutableBinding(this, ctx->engine->id_arguments, arguments);
return arguments;
}
}
throwReferenceError(Value::fromString(name));
return Value::undefinedValue();
}
void ExecutionContext::inplaceBitOp(Value value, String *name, BinOp op)
{
for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {
if (ctx->activation) {
if (ctx->activation->inplaceBinOp(value, name, op, this))
return;
}
}
throwReferenceError(Value::fromString(name));
}
void ExecutionContext::throwError(Value value)
{
__qmljs_builtin_throw(value, this);
}
void ExecutionContext::throwError(const QString &message)
{
Value v = Value::fromString(this, message);
throwError(Value::fromObject(engine->newErrorObject(v)));
}
void ExecutionContext::throwSyntaxError(DiagnosticMessage *message)
{
throwError(Value::fromObject(engine->newSyntaxErrorObject(this, message)));
}
void ExecutionContext::throwTypeError()
{
throwError(Value::fromObject(engine->newTypeErrorObject(this, QStringLiteral("Type error"))));
}
void ExecutionContext::throwUnimplemented(const QString &message)
{
Value v = Value::fromString(this, QStringLiteral("Unimplemented ") + message);
throwError(Value::fromObject(engine->newErrorObject(v)));
}
void ExecutionContext::throwReferenceError(Value value)
{
String *s = value.toString(this);
QString msg = s->toQString() + QStringLiteral(" is not defined");
throwError(Value::fromObject(engine->newReferenceErrorObject(this, msg)));
}
void ExecutionContext::initCallContext(ExecutionContext *parent, const Value that, FunctionObject *f, Value *args, unsigned argc)
{
engine = parent->engine;
this->parent = parent;
thisObject = that;
function = f;
strictMode = f->strictMode;
arguments = args;
argumentCount = argc;
if (function->needsActivation || argc < function->formalParameterCount){
arguments = new Value[qMax(argc, function->formalParameterCount)];
if (argc)
std::copy(args, args + argc, arguments);
if (argc < function->formalParameterCount)
std::fill(arguments + argc, arguments + function->formalParameterCount, Value::undefinedValue());
}
locals = function->varCount ? new Value[function->varCount] : 0;
if (function->varCount)
std::fill(locals, locals + function->varCount, Value::undefinedValue());
if (function->needsActivation)
activation = engine->newActivationObject();
else
activation = 0;
withObject = 0;
if (engine->debugger)
engine->debugger->aboutToCall(f, this);
}
void ExecutionContext::leaveCallContext()
{
// ## Should rather be handled by a the activation object having a ref to the environment
if (activation) {
delete[] locals;
locals = 0;
}
parent = 0;
if (engine->debugger)
engine->debugger->justLeft(this);
}
void ExecutionContext::wireUpPrototype()
{
assert(thisObject.isObject());
Value proto = function->__get__(this, engine->id_prototype);
if (proto.isObject())
thisObject.objectValue()->prototype = proto.objectValue();
else
thisObject.objectValue()->prototype = engine->objectPrototype;
}
} // namespace VM
} // namespace QQmlJS
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>
*
* 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.
*
* 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
*/
#include "abstractdictionary.h"
#include "wordentry.h"
#include "dictionaryzip.h"
#include <QtCore/QFile>
#include <QtCore/QVector>
using namespace MulaPluginStarDict;
class AbstractDictionary::Private
{
public:
Private()
: dictionaryFile(new QFile)
, compressedDictionaryFile(0)
, currentCacheItemIndex(0)
{
}
~Private()
{
}
QString sameTypeSequence;
QFile *dictionaryFile;
DictionaryZip *compressedDictionaryFile;
QList<WordEntry> cacheItemList;
int currentCacheItemIndex;
static const int wordDataCacheSize = 10;
};
AbstractDictionary::AbstractDictionary()
: d(new Private)
{
d->cacheItemList.reserve(d->wordDataCacheSize);
}
AbstractDictionary::~AbstractDictionary()
{
delete d->compressedDictionaryFile;
delete d->dictionaryFile;
delete d;
}
const QByteArray
AbstractDictionary::wordData(quint32 indexItemOffset, qint32 indexItemSize)
{
// Check first whether or not the data is already available in the cache
foreach(const WordEntry& cacheItem, d->cacheItemList)
{
if (!cacheItem.data().isEmpty() && cacheItem.dataOffset() == indexItemOffset)
return cacheItem.data();
}
if (d->dictionaryFile->isOpen())
d->dictionaryFile->seek(indexItemOffset);
QByteArray resultData;
QByteArray originalData;
if (!d->sameTypeSequence.isEmpty())
{
if (d->dictionaryFile->isOpen())
originalData = d->dictionaryFile->read(indexItemSize);
else
originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
int sameTypeSequenceLength = d->sameTypeSequence.length();
int sectionSize = 0;
int sectionPosition = 0;
//copy the head items.
foreach (const QChar& ch, d->sameTypeSequence.left(sameTypeSequenceLength - 1))
{
if (ch.isUpper())
{
sectionSize = *reinterpret_cast<quint32 *>(originalData.mid(sectionPosition).data());
sectionSize += sizeof(quint32);
}
else
{
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
}
resultData.append(ch);
resultData.append(originalData.mid(sectionPosition, sectionSize));
sectionPosition += sectionSize;
}
// Calculate the last item's size.
sectionSize = indexItemSize - sectionPosition;
if (d->sameTypeSequence.at(sameTypeSequenceLength - 1).isUpper())
{
originalData.fromRawData(reinterpret_cast<char*>(§ionSize), 4);
sectionSize += sizeof(quint32);
resultData.append(originalData.mid(sectionPosition, sectionSize));
}
else
{
resultData.append(originalData.mid(sectionPosition, sectionSize));
sectionPosition += sectionSize;
resultData.append('\0');
}
}
else
{
if (d->dictionaryFile->isOpen())
originalData = d->dictionaryFile->read(indexItemSize);
else
originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
resultData = originalData;
}
d->cacheItemList[d->currentCacheItemIndex].setData(resultData);
d->cacheItemList[d->currentCacheItemIndex].setDataOffset(indexItemOffset);
++d->currentCacheItemIndex;
if (d->currentCacheItemIndex == d->wordDataCacheSize)
d->currentCacheItemIndex = 0;
return resultData;
}
bool
AbstractDictionary::containFindData()
{
if (d->sameTypeSequence.isEmpty())
return true;
foreach (const QChar& ch, QString("mlgxty"))
{
if (d->sameTypeSequence.contains(ch))
return true;
}
return false;
}
bool AbstractDictionary::findData(const QStringList &searchWords, qint32 indexItemOffset, qint32 indexItemSize, QByteArray& originalData)
{
int wordCount = searchWords.size();
QVector<bool> wordFind(wordCount, false);
if (d->dictionaryFile->isOpen())
d->dictionaryFile->seek(indexItemOffset);
if (d->dictionaryFile->isOpen())
originalData = d->dictionaryFile->read(indexItemSize);
else
originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
int sectionSize = 0;
int sectionPosition = 0;
int foundCount = 0;
if (!d->sameTypeSequence.isEmpty())
{
int sameTypeSequenceLength = d->sameTypeSequence.length();
foreach (const QChar& ch, d->sameTypeSequence.left(sameTypeSequenceLength - 1))
{
switch (ch.toAscii())
{
case 'm':
case 'l':
case 'g':
case 't':
case 'x':
case 'y':
for (int j = 0; j < wordCount; ++j)
{
if (!wordFind.at(j) && originalData.indexOf(searchWords.at(j), sectionPosition) > -1)
{
wordFind[j] = true;
++foundCount;
}
}
// If everything has been found
if (foundCount == wordCount)
return true;
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
sectionPosition += sectionSize;
break;
default:
if (ch.isUpper())
{
sectionSize = *reinterpret_cast<quint32 *>(originalData.mid(sectionPosition).data());
sectionSize += sizeof(quint32);
}
else
{
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
}
sectionPosition += sectionSize;
}
}
switch (d->sameTypeSequence.at(sameTypeSequenceLength - 1).toAscii())
{
case 'm':
case 'l':
case 'g':
case 't':
case 'x':
case 'y':
sectionSize = indexItemSize - sectionSize;
for (int j = 0; j < wordCount; ++j)
{
if (!wordFind[j] && originalData.contains(searchWords.at(j).mid(sectionSize).toUtf8()))
{
wordFind[j] = true;
++foundCount;
}
}
if (foundCount == wordCount)
return true;
break;
}
}
else
{
for (; sectionPosition < indexItemSize; sectionPosition += sectionSize)
{
switch (originalData.at(sectionPosition))
{
case 'm':
case 'l':
case 'g':
case 't':
case 'x':
case 'y':
for (int j = 0; j < wordCount; ++j)
{
if (!wordFind.at(j) && originalData.indexOf(searchWords.at(j), sectionSize) > -1)
{
wordFind[j] = true;
++foundCount;
}
}
// Everything has been found
if (foundCount == wordCount)
return true;
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
break;
default:
if (QChar(originalData.at(sectionSize)).isUpper())
{
originalData.fromRawData(reinterpret_cast<char*>(§ionSize), 4);
sectionSize += sizeof(quint32);
}
else
{
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
}
}
}
}
return false;
}
DictionaryZip*
AbstractDictionary::compressedDictionaryFile() const
{
return d->compressedDictionaryFile;
}
QFile*
AbstractDictionary::dictionaryFile() const
{
return d->dictionaryFile;
}
QString&
AbstractDictionary::sameTypeSequence() const
{
return d->sameTypeSequence;
}
void
AbstractDictionary::setSameTypeSequence(const QString& sameTypeSequence)
{
d->sameTypeSequence = sameTypeSequence;
}
<commit_msg>Use sizeof(quint32) instead of hard coded values, like in this special case: 4<commit_after>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>
*
* 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.
*
* 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
*/
#include "abstractdictionary.h"
#include "wordentry.h"
#include "dictionaryzip.h"
#include <QtCore/QFile>
#include <QtCore/QVector>
using namespace MulaPluginStarDict;
class AbstractDictionary::Private
{
public:
Private()
: dictionaryFile(new QFile)
, compressedDictionaryFile(0)
, currentCacheItemIndex(0)
{
}
~Private()
{
}
QString sameTypeSequence;
QFile *dictionaryFile;
DictionaryZip *compressedDictionaryFile;
QList<WordEntry> cacheItemList;
int currentCacheItemIndex;
static const int wordDataCacheSize = 10;
};
AbstractDictionary::AbstractDictionary()
: d(new Private)
{
d->cacheItemList.reserve(d->wordDataCacheSize);
}
AbstractDictionary::~AbstractDictionary()
{
delete d->compressedDictionaryFile;
delete d->dictionaryFile;
delete d;
}
const QByteArray
AbstractDictionary::wordData(quint32 indexItemOffset, qint32 indexItemSize)
{
// Check first whether or not the data is already available in the cache
foreach(const WordEntry& cacheItem, d->cacheItemList)
{
if (!cacheItem.data().isEmpty() && cacheItem.dataOffset() == indexItemOffset)
return cacheItem.data();
}
if (d->dictionaryFile->isOpen())
d->dictionaryFile->seek(indexItemOffset);
QByteArray resultData;
QByteArray originalData;
if (!d->sameTypeSequence.isEmpty())
{
if (d->dictionaryFile->isOpen())
originalData = d->dictionaryFile->read(indexItemSize);
else
originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
int sameTypeSequenceLength = d->sameTypeSequence.length();
int sectionSize = 0;
int sectionPosition = 0;
//copy the head items.
foreach (const QChar& ch, d->sameTypeSequence.left(sameTypeSequenceLength - 1))
{
if (ch.isUpper())
{
sectionSize = *reinterpret_cast<quint32 *>(originalData.mid(sectionPosition).data());
sectionSize += sizeof(quint32);
}
else
{
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
}
resultData.append(ch);
resultData.append(originalData.mid(sectionPosition, sectionSize));
sectionPosition += sectionSize;
}
// Calculate the last item's size.
sectionSize = indexItemSize - sectionPosition;
if (d->sameTypeSequence.at(sameTypeSequenceLength - 1).isUpper())
{
originalData.fromRawData(reinterpret_cast<char*>(§ionSize), sizeof(quint32));
sectionSize += sizeof(quint32);
resultData.append(originalData.mid(sectionPosition, sectionSize));
}
else
{
resultData.append(originalData.mid(sectionPosition, sectionSize));
sectionPosition += sectionSize;
resultData.append('\0');
}
}
else
{
if (d->dictionaryFile->isOpen())
originalData = d->dictionaryFile->read(indexItemSize);
else
originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
resultData = originalData;
}
d->cacheItemList[d->currentCacheItemIndex].setData(resultData);
d->cacheItemList[d->currentCacheItemIndex].setDataOffset(indexItemOffset);
++d->currentCacheItemIndex;
if (d->currentCacheItemIndex == d->wordDataCacheSize)
d->currentCacheItemIndex = 0;
return resultData;
}
bool
AbstractDictionary::containFindData()
{
if (d->sameTypeSequence.isEmpty())
return true;
foreach (const QChar& ch, QString("mlgxty"))
{
if (d->sameTypeSequence.contains(ch))
return true;
}
return false;
}
bool AbstractDictionary::findData(const QStringList &searchWords, qint32 indexItemOffset, qint32 indexItemSize, QByteArray& originalData)
{
int wordCount = searchWords.size();
QVector<bool> wordFind(wordCount, false);
if (d->dictionaryFile->isOpen())
d->dictionaryFile->seek(indexItemOffset);
if (d->dictionaryFile->isOpen())
originalData = d->dictionaryFile->read(indexItemSize);
else
originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
int sectionSize = 0;
int sectionPosition = 0;
int foundCount = 0;
if (!d->sameTypeSequence.isEmpty())
{
int sameTypeSequenceLength = d->sameTypeSequence.length();
foreach (const QChar& ch, d->sameTypeSequence.left(sameTypeSequenceLength - 1))
{
switch (ch.toAscii())
{
case 'm':
case 'l':
case 'g':
case 't':
case 'x':
case 'y':
for (int j = 0; j < wordCount; ++j)
{
if (!wordFind.at(j) && originalData.indexOf(searchWords.at(j), sectionPosition) > -1)
{
wordFind[j] = true;
++foundCount;
}
}
// If everything has been found
if (foundCount == wordCount)
return true;
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
sectionPosition += sectionSize;
break;
default:
if (ch.isUpper())
{
sectionSize = *reinterpret_cast<quint32 *>(originalData.mid(sectionPosition).data());
sectionSize += sizeof(quint32);
}
else
{
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
}
sectionPosition += sectionSize;
}
}
switch (d->sameTypeSequence.at(sameTypeSequenceLength - 1).toAscii())
{
case 'm':
case 'l':
case 'g':
case 't':
case 'x':
case 'y':
sectionSize = indexItemSize - sectionSize;
for (int j = 0; j < wordCount; ++j)
{
if (!wordFind[j] && originalData.contains(searchWords.at(j).mid(sectionSize).toUtf8()))
{
wordFind[j] = true;
++foundCount;
}
}
if (foundCount == wordCount)
return true;
break;
}
}
else
{
for (; sectionPosition < indexItemSize; sectionPosition += sectionSize)
{
switch (originalData.at(sectionPosition))
{
case 'm':
case 'l':
case 'g':
case 't':
case 'x':
case 'y':
for (int j = 0; j < wordCount; ++j)
{
if (!wordFind.at(j) && originalData.indexOf(searchWords.at(j), sectionSize) > -1)
{
wordFind[j] = true;
++foundCount;
}
}
// Everything has been found
if (foundCount == wordCount)
return true;
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
break;
default:
if (QChar(originalData.at(sectionSize)).isUpper())
{
originalData.fromRawData(reinterpret_cast<char*>(§ionSize), 4);
sectionSize += sizeof(quint32);
}
else
{
sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
}
}
}
}
return false;
}
DictionaryZip*
AbstractDictionary::compressedDictionaryFile() const
{
return d->compressedDictionaryFile;
}
QFile*
AbstractDictionary::dictionaryFile() const
{
return d->dictionaryFile;
}
QString&
AbstractDictionary::sameTypeSequence() const
{
return d->sameTypeSequence;
}
void
AbstractDictionary::setSameTypeSequence(const QString& sameTypeSequence)
{
d->sameTypeSequence = sameTypeSequence;
}
<|endoftext|>
|
<commit_before>// --------------------------------------------------------
// Code generated by Papyrus C++
// --------------------------------------------------------
#define Annotator_AnnotatorLib_Loader_JSONLoader_BODY
/************************************************************
JSONLoader class body
************************************************************/
// include associated header file
#include <QDebug>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <AnnotatorLib/Object.h>
#include <AnnotatorLib/Session.h>
#include <AnnotatorLib/Loader/JSONLoader.h>
// Derived includes directives
namespace AnnotatorLib {
namespace Loader {
void JSONLoader::setPath(std::string path)
{
this->path = path;
}
StorageType JSONLoader::getType()
{
return AnnotatorLib::StorageType::JSON;
}
void JSONLoader::loadSession(Session *session)
{
QFile file(QString::fromStdString(this->path));
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QJsonDocument document = QJsonDocument::fromJson(file.readAll());
QJsonObject json = document.object();
loadAttributes(json, session);
loadClasses(json, session);
loadObjects(json, session);
loadFrames(json, session);
loadAnnotations(json, session);
loadAnnotationsNextPrevious(json, session);
}
file.close();
}
void JSONLoader::loadAttributes(QJsonObject &json, Session *session)
{
QJsonArray attributes = json.value("attributes").toArray();
for(QJsonValue value: attributes){
QJsonObject attribute = value.toObject();
unsigned long id = attribute["id"].toString().toLong();
QString name = attribute["name"].toString();
QString type = attribute["type"].toString();
// TODO: default value
AnnotatorLib::AttributeType t = AnnotatorLib::AttributeTypeFromString(type.toStdString());
AnnotatorLib::Attribute * a = new AnnotatorLib::Attribute(id, t, name.toStdString());
AnnotatorLib::AttributeValue *av;
switch(t){
case AnnotatorLib::AttributeType::STRING:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toStdString());
break;
case AnnotatorLib::AttributeType::INTEGER:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toLong());
break;
case AnnotatorLib::AttributeType::FLOAT:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toDouble());
break;
case AnnotatorLib::AttributeType::BOOLEAN:
av = new AnnotatorLib::AttributeValue(attribute["default"].toBool());
break;
default:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toStdString());
};
a->setDefaultValue(av);
session->addAttribute(a);
}
}
void JSONLoader::loadAnnotations(QJsonObject &json, Session *session)
{
QJsonArray annotations = json.value("annotations").toArray();
for(QJsonValue value: annotations){
QJsonObject annotation = value.toObject();
unsigned long id = annotation["id"].toString().toLong();
unsigned long object = annotation["object"].toString().toLong();
unsigned long frame = annotation["frame"].toString().toLong();
float x = annotation["x"].toString().toFloat();
float y = annotation["y"].toString().toFloat();
float width = annotation["width"].toString().toFloat();
float height = annotation["height"].toString().toFloat();
AnnotatorLib::AnnotationType type =
AnnotatorLib::AnnotationTypeFromString(annotation["type"].toString().toStdString());
AnnotatorLib::Object * o = session->getObject(object);
AnnotatorLib::Frame * f = session->getFrame(frame);
if(o != nullptr && f != nullptr) {
AnnotatorLib::Annotation * a = new AnnotatorLib::Annotation(id, f, o, type);
a->setPosition(x, y, width, height);
//add attributes
QJsonArray attributes = annotation.value("attributes").toArray();
for(QJsonValue attribute: attributes){
unsigned long atid = attribute.toString().toLong();
AnnotatorLib::Attribute * at = session->getAttribute(atid);
if(at != nullptr)
a->addAttribute(at);
}
session->addAnnotation(a);
}
}
}
void JSONLoader::loadClasses(QJsonObject &json, Session *session)
{
QJsonArray classes = json.value("classes").toArray();
for(QJsonValue value: classes){
QJsonObject object = value.toObject();
unsigned long id = object["id"].toString().toLong();
QString name = object["name"].toString();
AnnotatorLib::Class * c = new AnnotatorLib::Class(id, name.toStdString());
session->addClass(c);
}
}
void JSONLoader::loadObjects(QJsonObject &json, Session *session)
{
QJsonArray objects = json.value("objects").toArray();
for(QJsonValue value: objects){
QJsonObject object = value.toObject();
unsigned long id = object["id"].toString().toLong();
QString name = object["name"].toString();
AnnotatorLib::Object * o = new AnnotatorLib::Object(id);
o->setName(name.toStdString());
if(object.contains("class"))
o->setClass(session->getClass(object["class"].toString().toLong()));
QJsonArray frames = object.value("frames").toArray();
for(QJsonValue frame: frames){
unsigned long frid = frame.toString().toLong();
AnnotatorLib::Frame * fr = session->getFrame(frid);
// if(fr != nullptr)
// o->addFrame(fr);
}
QJsonArray attributes = object.value("attributes").toArray();
for(QJsonValue attribute: attributes){
unsigned long atid = attribute.toString().toLong();
AnnotatorLib::Attribute * at = session->getAttribute(atid);
if(at != nullptr)
o->addAttribute(at);
}
QJsonArray annotations = object.value("annotations").toArray();
for(QJsonValue annotation: annotations){
unsigned long anid = annotation.toString().toLong();
AnnotatorLib::Annotation * an = session->getAnnotation(anid);
if(an != nullptr)
o->addAnnotation(an);
}
session->addObject(o);
}
}
void JSONLoader::loadFrames(QJsonObject &json, Session *session)
{
QJsonArray frames = json.value("frames").toArray();
for(QJsonValue value: frames){
QJsonObject frame = value.toObject();
unsigned long id = frame["number"].toString().toLong();
AnnotatorLib::Frame * f = new AnnotatorLib::Frame(id);
QJsonArray annotations = frame.value("annotations").toArray();
for(QJsonValue annotation: annotations){
unsigned long anid = annotation.toString().toLong();
AnnotatorLib::Annotation * an = session->getAnnotation(anid);
if(an != nullptr)
f->addAnnotation(an);
}
session->addFrame(f);
}
}
void JSONLoader::loadAnnotationsNextPrevious(QJsonObject &json, Session *session)
{
QJsonArray annotations = json.value("annotations").toArray();
for(QJsonValue value: annotations){
QJsonObject annotation = value.toObject();
unsigned long id = annotation["id"].toString().toLong();
AnnotatorLib::Annotation * a = session->getAnnotation(id);
if(annotation.contains("previous")){
unsigned long previousId = annotation["previous"].toString().toLong();
a->setPrevious(session->getAnnotation(previousId));
}
if(annotation.contains("next")){
unsigned long nextId = annotation["next"].toString().toLong();
a->setNext(session->getAnnotation(nextId));
}
}
}
// static attributes (if any)
}// of namespace Loader
} // of namespace AnnotatorLib
/************************************************************
End of JSONLoader class body
************************************************************/
<commit_msg>Removed function for loading next and previous. The ordering is now based on the frame number.<commit_after>// --------------------------------------------------------
// Code generated by Papyrus C++
// --------------------------------------------------------
#define Annotator_AnnotatorLib_Loader_JSONLoader_BODY
/************************************************************
JSONLoader class body
************************************************************/
// include associated header file
#include <QDebug>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <AnnotatorLib/Object.h>
#include <AnnotatorLib/Session.h>
#include <AnnotatorLib/Loader/JSONLoader.h>
// Derived includes directives
namespace AnnotatorLib {
namespace Loader {
void JSONLoader::setPath(std::string path)
{
this->path = path;
}
StorageType JSONLoader::getType()
{
return AnnotatorLib::StorageType::JSON;
}
void JSONLoader::loadSession(Session *session)
{
QFile file(QString::fromStdString(this->path));
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QJsonDocument document = QJsonDocument::fromJson(file.readAll());
QJsonObject json = document.object();
loadAttributes(json, session);
loadClasses(json, session);
loadObjects(json, session);
loadFrames(json, session);
loadAnnotations(json, session);
//loadAnnotationsNextPrevious(json, session);
}
file.close();
}
void JSONLoader::loadAttributes(QJsonObject &json, Session *session)
{
QJsonArray attributes = json.value("attributes").toArray();
for(QJsonValue value: attributes){
QJsonObject attribute = value.toObject();
unsigned long id = attribute["id"].toString().toLong();
QString name = attribute["name"].toString();
QString type = attribute["type"].toString();
// TODO: default value
AnnotatorLib::AttributeType t = AnnotatorLib::AttributeTypeFromString(type.toStdString());
AnnotatorLib::Attribute * a = new AnnotatorLib::Attribute(id, t, name.toStdString());
AnnotatorLib::AttributeValue *av;
switch(t){
case AnnotatorLib::AttributeType::STRING:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toStdString());
break;
case AnnotatorLib::AttributeType::INTEGER:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toLong());
break;
case AnnotatorLib::AttributeType::FLOAT:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toDouble());
break;
case AnnotatorLib::AttributeType::BOOLEAN:
av = new AnnotatorLib::AttributeValue(attribute["default"].toBool());
break;
default:
av = new AnnotatorLib::AttributeValue(attribute["default"].toString().toStdString());
};
a->setDefaultValue(av);
session->addAttribute(a);
}
}
void JSONLoader::loadClasses(QJsonObject &json, Session *session)
{
QJsonArray classes = json.value("classes").toArray();
for(QJsonValue value: classes){
QJsonObject object = value.toObject();
unsigned long id = object["id"].toString().toLong();
QString name = object["name"].toString();
AnnotatorLib::Class * c = new AnnotatorLib::Class(id, name.toStdString());
session->addClass(c);
}
}
void JSONLoader::loadObjects(QJsonObject &json, Session *session)
{
QJsonArray objects = json.value("objects").toArray();
for(QJsonValue value: objects){
QJsonObject object = value.toObject();
unsigned long id = object["id"].toString().toLong();
QString name = object["name"].toString();
AnnotatorLib::Object * o = new AnnotatorLib::Object(id);
o->setName(name.toStdString());
if(object.contains("class"))
o->setClass(session->getClass(object["class"].toString().toLong()));
QJsonArray attributes = object.value("attributes").toArray();
for(QJsonValue attribute: attributes){
unsigned long atid = attribute.toString().toLong();
AnnotatorLib::Attribute * at = session->getAttribute(atid);
if(at != nullptr)
o->addAttribute(at);
}
session->addObject(o);
}
}
void JSONLoader::loadFrames(QJsonObject &json, Session *session)
{
QJsonArray frames = json.value("frames").toArray();
for(QJsonValue value: frames){
QJsonObject frame = value.toObject();
unsigned long nmb = frame["number"].toString().toLong();
AnnotatorLib::Frame * f = new AnnotatorLib::Frame(nmb);
session->addFrame(f);
}
}
void JSONLoader::loadAnnotations(QJsonObject &json, Session *session)
{
QJsonArray annotations = json.value("annotations").toArray();
for(QJsonValue value: annotations){
QJsonObject annotation = value.toObject();
unsigned long id = annotation["id"].toString().toLong();
unsigned long object = annotation["object"].toString().toLong();
unsigned long frame = annotation["frame"].toString().toLong();
float x = annotation["x"].toString().toFloat();
float y = annotation["y"].toString().toFloat();
float width = annotation["width"].toString().toFloat();
float height = annotation["height"].toString().toFloat();
AnnotatorLib::AnnotationType type =
AnnotatorLib::AnnotationTypeFromString(annotation["type"].toString().toStdString());
AnnotatorLib::Object * o = session->getObject(object);
AnnotatorLib::Frame * f = session->getFrame(frame);
if(o != nullptr && f != nullptr) {
AnnotatorLib::Annotation * a = new AnnotatorLib::Annotation(id, f, o, type);
a->setPosition(x, y, width, height);
//add attributes
QJsonArray attributes = annotation.value("attributes").toArray();
for(QJsonValue attribute: attributes){
unsigned long atid = attribute.toString().toLong();
AnnotatorLib::Attribute * at = session->getAttribute(atid);
if(at != nullptr)
a->addAttribute(at);
}
session->addAnnotation(a);
}
}
}
//NOTE: Not needed anymore. Since objects take care for the correct order (based on frame-number)!
//void JSONLoader::loadAnnotationsNextPrevious(QJsonObject &json, Session *session)
//{
// QJsonArray annotations = json.value("annotations").toArray();
// for(QJsonValue value: annotations){
// QJsonObject annotation = value.toObject();
// unsigned long id = annotation["id"].toString().toLong();
// AnnotatorLib::Annotation * a = session->getAnnotation(id);
// if(annotation.contains("previous")){
// unsigned long previousId = annotation["previous"].toString().toLong();
// a->setPrevious(session->getAnnotation(previousId));
// }
// if(annotation.contains("next")){
// unsigned long nextId = annotation["next"].toString().toLong();
// a->setNext(session->getAnnotation(nextId));
// }
// }
//}
// static attributes (if any)
}// of namespace Loader
} // of namespace AnnotatorLib
/************************************************************
End of JSONLoader class body
************************************************************/
<|endoftext|>
|
<commit_before>//===-- sanitizer_posix_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Tests for POSIX-specific code.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_POSIX
#include "sanitizer_common/sanitizer_common.h"
#include "gtest/gtest.h"
#include <pthread.h>
#include <sys/mman.h>
namespace __sanitizer {
static pthread_key_t key;
static bool destructor_executed;
extern "C"
void destructor(void *arg) {
uptr iter = reinterpret_cast<uptr>(arg);
if (iter > 1) {
ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void *>(iter - 1)));
return;
}
destructor_executed = true;
}
extern "C"
void *thread_func(void *arg) {
return reinterpret_cast<void*>(pthread_setspecific(key, arg));
}
static void SpawnThread(uptr iteration) {
destructor_executed = false;
pthread_t tid;
ASSERT_EQ(0, pthread_create(&tid, 0, &thread_func,
reinterpret_cast<void *>(iteration)));
void *retval;
ASSERT_EQ(0, pthread_join(tid, &retval));
ASSERT_EQ(0, retval);
}
TEST(SanitizerCommon, PthreadDestructorIterations) {
ASSERT_EQ(0, pthread_key_create(&key, &destructor));
SpawnThread(GetPthreadDestructorIterations());
EXPECT_TRUE(destructor_executed);
SpawnThread(GetPthreadDestructorIterations() + 1);
EXPECT_FALSE(destructor_executed);
ASSERT_EQ(0, pthread_key_delete(key));
}
TEST(SanitizerCommon, IsAccessibleMemoryRange) {
const int page_size = GetPageSize();
uptr mem = (uptr)mmap(0, 3 * page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
// Protect the middle page.
mprotect((void *)(mem + page_size), page_size, PROT_NONE);
EXPECT_TRUE(IsAccessibleMemoryRange(mem, page_size - 1));
EXPECT_TRUE(IsAccessibleMemoryRange(mem, page_size));
EXPECT_FALSE(IsAccessibleMemoryRange(mem, page_size + 1));
EXPECT_TRUE(IsAccessibleMemoryRange(mem + page_size - 1, 1));
EXPECT_FALSE(IsAccessibleMemoryRange(mem + page_size - 1, 2));
EXPECT_FALSE(IsAccessibleMemoryRange(mem + 2 * page_size - 1, 1));
EXPECT_TRUE(IsAccessibleMemoryRange(mem + 2 * page_size, page_size));
EXPECT_FALSE(IsAccessibleMemoryRange(mem, 3 * page_size));
EXPECT_FALSE(IsAccessibleMemoryRange(0x0, 2));
}
} // namespace __sanitizer
#endif // SANITIZER_POSIX
<commit_msg>[sanitizer_common][tests] Fix SanitizerCommon-Unit :: ./Sanitizer-*-Test/SanitizerCommon.PthreadDestructorIterations on Solaris<commit_after>//===-- sanitizer_posix_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Tests for POSIX-specific code.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_POSIX
#include "sanitizer_common/sanitizer_common.h"
#include "gtest/gtest.h"
#include <pthread.h>
#include <sys/mman.h>
namespace __sanitizer {
static pthread_key_t key;
static bool destructor_executed;
extern "C"
void destructor(void *arg) {
uptr iter = reinterpret_cast<uptr>(arg);
if (iter > 1) {
ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void *>(iter - 1)));
return;
}
destructor_executed = true;
}
extern "C"
void *thread_func(void *arg) {
return reinterpret_cast<void*>(pthread_setspecific(key, arg));
}
static void SpawnThread(uptr iteration) {
destructor_executed = false;
pthread_t tid;
ASSERT_EQ(0, pthread_create(&tid, 0, &thread_func,
reinterpret_cast<void *>(iteration)));
void *retval;
ASSERT_EQ(0, pthread_join(tid, &retval));
ASSERT_EQ(0, retval);
}
TEST(SanitizerCommon, PthreadDestructorIterations) {
ASSERT_EQ(0, pthread_key_create(&key, &destructor));
SpawnThread(GetPthreadDestructorIterations());
EXPECT_TRUE(destructor_executed);
SpawnThread(GetPthreadDestructorIterations() + 1);
#if SANITIZER_SOLARIS
// Solaris continues calling destructors beyond PTHREAD_DESTRUCTOR_ITERATIONS.
EXPECT_TRUE(destructor_executed);
#else
EXPECT_FALSE(destructor_executed);
#endif
ASSERT_EQ(0, pthread_key_delete(key));
}
TEST(SanitizerCommon, IsAccessibleMemoryRange) {
const int page_size = GetPageSize();
uptr mem = (uptr)mmap(0, 3 * page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
// Protect the middle page.
mprotect((void *)(mem + page_size), page_size, PROT_NONE);
EXPECT_TRUE(IsAccessibleMemoryRange(mem, page_size - 1));
EXPECT_TRUE(IsAccessibleMemoryRange(mem, page_size));
EXPECT_FALSE(IsAccessibleMemoryRange(mem, page_size + 1));
EXPECT_TRUE(IsAccessibleMemoryRange(mem + page_size - 1, 1));
EXPECT_FALSE(IsAccessibleMemoryRange(mem + page_size - 1, 2));
EXPECT_FALSE(IsAccessibleMemoryRange(mem + 2 * page_size - 1, 1));
EXPECT_TRUE(IsAccessibleMemoryRange(mem + 2 * page_size, page_size));
EXPECT_FALSE(IsAccessibleMemoryRange(mem, 3 * page_size));
EXPECT_FALSE(IsAccessibleMemoryRange(0x0, 2));
}
} // namespace __sanitizer
#endif // SANITIZER_POSIX
<|endoftext|>
|
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetLogLevel(OF_LOG_VERBOSE);
ofEnableDepthTest();
kinect.setRegistration(true);
kinect.init();
kinect.open();
ofSetFrameRate(30);
}
//--------------------------------------------------------------
void ofApp::update(){
kinect.update();
}
inline ofxPCL::PointXYZRGBCloud getPointCloudFromKinect(ofxKinect &kinect, int step = 2) {
ofxPCL::PointXYZRGBCloud cloud(new ofxPCL::PointXYZRGBCloud::element_type);
int count = 0;
int w = kinect.getWidth();
int h = kinect.getHeight();
cloud->width = ceil((float)w / (float)step) * ceil((float)h / (float)step);
cloud->height = 1;
cloud->is_dense = false;
cloud->points.resize(cloud->width * cloud->height);
for(int y = 0; y < h; y += step) {
for(int x = 0; x < w; x += step) {
if(kinect.getDistanceAt(x, y) > 0) {
ofVec3f v = kinect.getWorldCoordinateAt(x, y);
cloud->points[count].x = v.x;
cloud->points[count].y = v.y;
cloud->points[count].z = v.z;
ofColor col = kinect.getColorAt(x, y);
uint32_t rgb = ((uint32_t)col.r << 16 | (uint32_t)col.g << 8 | (uint32_t)col.b);
cloud->points[count].rgb = *reinterpret_cast<float*>(&rgb);
count++;
}
}
}
cloud->points.resize(count);
cloud->width = count;
return cloud;
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(10);
easyCam.begin();
ofxPCL::PointXYZRGBCloud cloud = getPointCloudFromKinect(kinect, 8);
ofxPCL::PointXYZRGBNormalCloud cloud_with_normals(new ofxPCL::PointXYZRGBNormalCloud::element_type);
ofxPCL::normalEstimation(cloud, cloud_with_normals);
ofMesh mesh = ofxPCL::triangulate(cloud_with_normals, 500);
ofPushMatrix();
// the projected points are 'upside down' and 'backwards'
ofScale(1, -1, -1);
ofTranslate(0, 0, -1000); // center the points a bit
if( toggleWireframe ) {
mesh.drawWireframe();
} else {
mesh.drawFaces();
}
// another solution
//ofxPCL::organizedFastMesh(kinect.getPixelsRef(), kinect.getRawDepthPixelsRef(), 8, 1).drawWireframe();
ofPopMatrix();
easyCam.end();
}
//--------------------------------------------------------------
void ofApp::exit(){
kinect.setCameraTiltAngle(0); // zero the tilt on exit
kinect.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if( key == ' ' ) {
toggleWireframe = !toggleWireframe;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Display framerate<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetLogLevel(OF_LOG_VERBOSE);
ofSetVerticalSync(true);
ofEnableDepthTest();
kinect.setRegistration(true);
kinect.init();
kinect.open();
ofSetFrameRate(15);
}
//--------------------------------------------------------------
void ofApp::update(){
kinect.update();
}
inline ofxPCL::PointXYZRGBCloud getPointCloudFromKinect(ofxKinect &kinect, int step = 2) {
ofxPCL::PointXYZRGBCloud cloud(new ofxPCL::PointXYZRGBCloud::element_type);
int count = 0;
int w = kinect.getWidth();
int h = kinect.getHeight();
cloud->width = ceil((float)w / (float)step) * ceil((float)h / (float)step);
cloud->height = 1;
cloud->is_dense = false;
cloud->points.resize(cloud->width * cloud->height);
for(int y = 0; y < h; y += step) {
for(int x = 0; x < w; x += step) {
if(kinect.getDistanceAt(x, y) > 0) {
ofVec3f v = kinect.getWorldCoordinateAt(x, y);
cloud->points[count].x = v.x;
cloud->points[count].y = v.y;
cloud->points[count].z = v.z;
ofColor col = kinect.getColorAt(x, y);
uint32_t rgb = ((uint32_t)col.r << 16 | (uint32_t)col.g << 8 | (uint32_t)col.b);
cloud->points[count].rgb = *reinterpret_cast<float*>(&rgb);
count++;
}
}
}
cloud->points.resize(count);
cloud->width = count;
return cloud;
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(10);
easyCam.begin();
ofxPCL::PointXYZRGBCloud cloud = getPointCloudFromKinect(kinect, 4);
ofxPCL::PointXYZRGBNormalCloud cloud_with_normals(new ofxPCL::PointXYZRGBNormalCloud::element_type);
ofxPCL::normalEstimation(cloud, cloud_with_normals);
ofMesh mesh = ofxPCL::triangulate(cloud_with_normals, 500);
ofPushMatrix();
// the projected points are 'upside down' and 'backwards'
ofScale(1, -1, -1);
ofTranslate(0, 0, -1000); // center the points a bit
if( toggleWireframe ) {
mesh.drawWireframe();
} else {
mesh.drawFaces();
}
// another solution
//ofxPCL::organizedFastMesh(kinect.getPixelsRef(), kinect.getRawDepthPixelsRef(), 8, 1).drawWireframe();
ofPopMatrix();
easyCam.end();
ofSetColor(255);
ofDrawBitmapString("FPS: " + ofToString(ofGetFrameRate()), 20, 50);
}
//--------------------------------------------------------------
void ofApp::exit(){
kinect.setCameraTiltAngle(0); // zero the tilt on exit
kinect.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if( key == ' ' ) {
toggleWireframe = !toggleWireframe;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2016-2017 Pelagicore AB
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
* BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*
* For further information see LICENSE
*/
#include <string>
#include <unistd.h>
#include "waylandgateway.h"
namespace softwarecontainer {
// These lines are needed in order to define the fields, which otherwise would
// yield linker errors.
constexpr const char *WaylandGateway::ENABLED_FIELD;
constexpr const char *WaylandGateway::WAYLAND_RUNTIME_DIR_VARIABLE_NAME;
constexpr const char *WAYLAND_SOCKET_FILE_VARIABLE_NAME;
WaylandGateway::WaylandGateway(std::shared_ptr<ContainerAbstractInterface> container) :
Gateway(ID, container, true /*this GW is dynamic*/),
m_enabled(false),
m_activatedOnce(false)
{
}
WaylandGateway::~WaylandGateway()
{
}
bool WaylandGateway::readConfigElement(const json_t *element)
{
bool configValue = false;
if (!JSONParser::read(element, ENABLED_FIELD, configValue)) {
log_error() << "Key " << ENABLED_FIELD << " missing or not bool in json configuration";
return false;
}
if (!m_enabled) {
m_enabled = configValue;
}
return true;
}
bool WaylandGateway::activateGateway()
{
if (!m_enabled) {
log_info() << "Wayland gateway disabled";
return true;
}
/* If we are enabled and have been activated once already, we shouldn't do anything more
since bind-mounting again would fail and the whitelisting principle means
that we never need to do more than what is already done in this state, e.g.
'enabled' is the most permissive state. */
if (m_enabled && m_activatedOnce) {
log_info() << "Ignoring redundant activation";
return true;
}
std::string SOCKET_FILE_NAME = Glib::getenv(WAYLAND_SOCKET_FILE_VARIABLE_NAME);
if (SOCKET_FILE_NAME.empty()) {
log_error() << "Missing Wayland socket file name. " << WAYLAND_SOCKET_FILE_VARIABLE_NAME << " environment variable not set";
return false;
}
bool hasWayland = false;
std::string dir = Glib::getenv(WAYLAND_RUNTIME_DIR_VARIABLE_NAME, hasWayland);
if (!hasWayland) {
log_error() << "Should enable wayland gateway, but " << WAYLAND_RUNTIME_DIR_VARIABLE_NAME << " is not defined";
return false;
}
std::shared_ptr<ContainerAbstractInterface> container = getContainer();
log_info() << "enabling Wayland gateway. Socket dir:" << dir;
std::string pathInHost = buildPath(dir, SOCKET_FILE_NAME);
std::string pathInContainer = buildPath("/gateways", SOCKET_FILE_NAME);
if (!container->bindMountInContainer(pathInHost, pathInContainer, false)) {
log_error() << "Could not bind mount the wayland socket into the container";
return false;
}
std::string socketDir = parentPath(pathInContainer);
container->setEnvironmentVariable(WAYLAND_RUNTIME_DIR_VARIABLE_NAME, socketDir);
m_activatedOnce = true;
return true;
}
bool WaylandGateway::teardownGateway()
{
return true;
}
} // namespace softwarecontainer
<commit_msg>waylandgateway: Fix uninitialized const variable<commit_after>/*
* Copyright (C) 2016-2017 Pelagicore AB
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
* BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*
* For further information see LICENSE
*/
#include <string>
#include <unistd.h>
#include "waylandgateway.h"
namespace softwarecontainer {
// These lines are needed in order to define the fields, which otherwise would
// yield linker errors.
constexpr const char *WaylandGateway::ENABLED_FIELD;
constexpr const char *WaylandGateway::WAYLAND_RUNTIME_DIR_VARIABLE_NAME;
constexpr const char *WaylandGateway::WAYLAND_SOCKET_FILE_VARIABLE_NAME;
WaylandGateway::WaylandGateway(std::shared_ptr<ContainerAbstractInterface> container) :
Gateway(ID, container, true /*this GW is dynamic*/),
m_enabled(false),
m_activatedOnce(false)
{
}
WaylandGateway::~WaylandGateway()
{
}
bool WaylandGateway::readConfigElement(const json_t *element)
{
bool configValue = false;
if (!JSONParser::read(element, ENABLED_FIELD, configValue)) {
log_error() << "Key " << ENABLED_FIELD << " missing or not bool in json configuration";
return false;
}
if (!m_enabled) {
m_enabled = configValue;
}
return true;
}
bool WaylandGateway::activateGateway()
{
if (!m_enabled) {
log_info() << "Wayland gateway disabled";
return true;
}
/* If we are enabled and have been activated once already, we shouldn't do anything more
since bind-mounting again would fail and the whitelisting principle means
that we never need to do more than what is already done in this state, e.g.
'enabled' is the most permissive state. */
if (m_enabled && m_activatedOnce) {
log_info() << "Ignoring redundant activation";
return true;
}
std::string SOCKET_FILE_NAME = Glib::getenv(WAYLAND_SOCKET_FILE_VARIABLE_NAME);
if (SOCKET_FILE_NAME.empty()) {
log_error() << "Missing Wayland socket file name. " << WAYLAND_SOCKET_FILE_VARIABLE_NAME << " environment variable not set";
return false;
}
bool hasWayland = false;
std::string dir = Glib::getenv(WAYLAND_RUNTIME_DIR_VARIABLE_NAME, hasWayland);
if (!hasWayland) {
log_error() << "Should enable wayland gateway, but " << WAYLAND_RUNTIME_DIR_VARIABLE_NAME << " is not defined";
return false;
}
std::shared_ptr<ContainerAbstractInterface> container = getContainer();
log_info() << "enabling Wayland gateway. Socket dir:" << dir;
std::string pathInHost = buildPath(dir, SOCKET_FILE_NAME);
std::string pathInContainer = buildPath("/gateways", SOCKET_FILE_NAME);
if (!container->bindMountInContainer(pathInHost, pathInContainer, false)) {
log_error() << "Could not bind mount the wayland socket into the container";
return false;
}
std::string socketDir = parentPath(pathInContainer);
container->setEnvironmentVariable(WAYLAND_RUNTIME_DIR_VARIABLE_NAME, socketDir);
m_activatedOnce = true;
return true;
}
bool WaylandGateway::teardownGateway()
{
return true;
}
} // namespace softwarecontainer
<|endoftext|>
|
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef __learning_hh__
#define __learning_hh__
#include "writable.hh"
#include "factory.hh"
#include <math.h>
#include "alphabet.hh" // To have clue about time, names...
class Log;
class Learning: public Writable {
public:
Learning(Log&l);
virtual ~Learning() { }
virtual void setAlphabet(Alphabet* a) {
alphabet=a;
}
virtual void suggest(int action) { }
virtual void execute(int action) { }
virtual float getF(int action) { return FP_NAN; }
virtual float getC(int sug,int exe) { return FP_NAN; }
virtual float getE(int action) { return FP_NAN; }
protected:
bool suggested;
int suggested_action;
Alphabet* alphabet;
Log& log;
};
FACTORY_DECLARATION(Learning)
Learning* new_learning(Log&, std::string&);
#endif
<commit_msg>default values<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef __learning_hh__
#define __learning_hh__
#include "writable.hh"
#include "factory.hh"
#include <math.h>
#include "alphabet.hh" // To have clue about time, names...
class Log;
class Learning: public Writable {
public:
Learning(Log&l);
virtual ~Learning() { }
virtual void setAlphabet(Alphabet* a) {
alphabet=a;
}
virtual void suggest(int action) { }
virtual void execute(int action) { }
virtual float getF(int action) { return 0.0; }
virtual float getC(int sug,int exe) { return 0.0; }
virtual float getE(int action) { return 0.0; }
protected:
bool suggested;
int suggested_action;
Alphabet* alphabet;
Log& log;
};
FACTORY_DECLARATION(Learning)
Learning* new_learning(Log&, std::string&);
#endif
<|endoftext|>
|
<commit_before>#include <string.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <time.h>
#include "SuMo.h"
#include "Timer.h"
/* specific to file */
const int NUM_ARGS = 4;
const char* filename = "logData";
const char* description = "log data from DAQ";
using namespace std;
/********************/
/* subtract pedestal values on-line */
static bool PED_SUBTRCT = false;
static int LIMIT_READOUT_RATE = 6000; //usecs limit between event polling
static int NUM_SEQ_TIMEOUTS = 100; // number of sequential timeouts before ending run
const float MAX_INT_TIMER = 800.; // max cpu timer before ending run (secs)
/* note: usb timeout defined in include/stdUSB.h */
bool overwriteExistingFile = false;
int main(int argc, char* argv[]){
if(argc == 2 && std::string(argv[1]) == "-h"){
cout << endl;
cout << filename << " :: " << description << endl;
cout << filename << " :: takes " << NUM_ARGS-1 << " arguments" << endl;
return 1;
}
else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){
cout << "error: too many number of arguments" << endl;
return -1;
}
else{
int num_checks = 5;
int num_events = 100;
SuMo command;
char log_data_filename[100];
strcpy(log_data_filename, argv[1]);
num_events = atoi(argv[2]);
int trig_mode = atoi(argv[3]);
if(command.check_active_boards(num_checks))
return 1;
vector<packet_t**> events = command.get_data(num_events, trig_mode, 0);
command.log_data(log_data_filename, events, trig_mode);
return 0;
}
}
vector<packet_t**> SuMo::get_data(unsigned int NUM_READS, int trig_mode, int acq_rate){
int check_event;
int asic_baseline[psecSampleCells];
int count = 0;
int psec_cnt = 0;
int last_k;
float _now_, t = 0.;
char logDataFilename[300];
Timer timer = Timer();
time_t now;
unsigned short sample;
int* Meta;
vector<packet_t**> event_data;
// read all front end cards
bool all[numFrontBoards];
for(int i = 0; i < numFrontBoards; i++) all[i] = true;
load_ped();
int number_of_frontend_cards = 0;
for( int board = 0; board < numFrontBoards; board++){
if(DC_ACTIVE[board]) number_of_frontend_cards++;
}
cout << "--------------------------------------------------------------" << endl;
cout << "number of front-end boards detected = " << number_of_frontend_cards
<< " of " << numFrontBoards << " address slots in system" << endl;
cout << "Trying for " << NUM_READS << " events logged to disk, in a timeout window of "
<< MAX_INT_TIMER << " seconds" << endl;
cout << "--------------------------------------------------------------" << endl << endl;
usleep(100000);
/* cpu time zero */
timer.start();
bool reset_event = true;
// set read mode to NULL
set_usb_read_mode(0);
if(mode==USB2x) set_usb_read_mode_slaveDevice(0);
system_card_trig_valid(false);
if(mode==USB2x) system_slave_card_trig_valid(false);
//check system trigger number
read_CC(false, false, 100);
int board_trigger= CC_EVENT_COUNT_FROMCC0;
int last_board_trigger = board_trigger;
for(int k=0; k<NUM_READS; k++){
set_usb_read_mode(0);
if(mode==USB2x) set_usb_read_mode_slaveDevice(0);
time(&now);
t = timer.stop();
// interrupt if past specified logging time
if(t > MAX_INT_TIMER) {
cout << endl << "readout timed out at " << t << "on event " << k << endl;
break;
}
// trig_mode = 1 is external source or PSEC4 self trigger
// trig_mode = 0 is over software (USB), i.e. calibration logging
if(trig_mode == 0){
manage_cc_fifo(1);
if(mode==USB2x) manage_cc_fifo_slaveDevice(1);
// 'rate-only' mode, only pull data every second
if(trig_mode == 2) usleep(3e6);
prep_sync();
if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);
software_trigger((unsigned int) 15);
make_sync();
//acq rate limit
usleep(LIMIT_READOUT_RATE); // somewhat arbitrary hard-coded rate limitation
//system_card_trig_valid(false);
//if(mode == USB2x) system_slave_card_trig_valid(false);
}
else{
manage_cc_fifo(1);
if(mode==USB2x) manage_cc_fifo_slaveDevice(1);
usleep(100);
for(int iii=0; iii<2; iii++){
system_card_trig_valid(false);
if(mode==USB2x) system_slave_card_trig_valid(false);
}
//send in trig 'valid' signal
sys_wait(100);
prep_sync();
if(mode==USB2x) system_slave_card_trig_valid(true);
system_card_trig_valid(true);
make_sync();
//}
//acq rate limit
usleep(acq_rate+LIMIT_READOUT_RATE);
}
int num_pulls = 0;
int evts = 0;
int digs = 0;
while(board_trigger==last_board_trigger && t < MAX_INT_TIMER){
read_CC(false, false, 100);
board_trigger = CC_EVENT_COUNT_FROMCC0;
cout << "waiting for trigger... on system event: "
<< board_trigger << " & readout attempt " << k
<< " @time " << t << " \r";
cout.flush();
usleep(1000);
t = timer.stop();
num_pulls++;
if(num_pulls > 100) break;
//if(num_pulls > 10) break; //use this is board trigger does not iterate
}
last_board_trigger = board_trigger;
if(mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
//set_usb_read_mode_slaveDevice(0), set_usb_read_mode(0);
evts = read_CC(false, false, 0);
for(int chkdig=0; chkdig<numFrontBoards; chkdig++)
digs+=DIGITIZING_START_FLAG[chkdig];
//if(evts == 0){
//reset_event = true;
//k = k-1;
//continue;
//}
//condition for dumping event and trying again.
//else if( DIGITIZING_START_FLAG[2] == 0 || evts < 6 || evts != digs){
if( evts == 0 || evts != digs){
print_to_terminal(k, NUM_READS,CC_EVENT_COUNT_FROMCC0, board_trigger, t);
cout << " --NULL-- " << endl;
//cout.flush();
reset_event = true;
k = k-1; //repeat event
continue;
}
// show event number at terminal
else{
if((k+1) % 1 == 0 || k==0){
print_to_terminal(k, NUM_READS, CC_EVENT_COUNT_FROMCC0, board_trigger, t);
cout << " \r";
cout.flush();
}
}
/**************************************/
//Do bulk read on all front-end cards
int numBoards = read_AC(1, all, false);
/**************************************/
sys_wait(10000);
for(int jj=0; jj<2; jj++){
//prep_sync();
//turn off 'trig valid flag' until checking if data in buffer
if(mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
if(mode == USB2x) set_usb_read_mode_slaveDevice(0);
set_usb_read_mode(0);
}
reset_event = true; //have event, go ahead and reset for next event
// form data for filesave
for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){
if(BOARDS_READOUT[targetAC] && numBoards > 0){
psec_cnt = 0;
// assign meta data
Meta=get_AC_info(false, targetAC, false,k, t, t, evts);
check_event = 0;
for(int i = 0; i < AC_CHANNELS; i++){
if(i>0 && i % 6 == 0) psec_cnt ++;
for(int j = 0; j < psecSampleCells; j++){
sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];
if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j];
adcDat[targetAC]->Data[i][j] = (unsigned int) sample;
}
}
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++){
asic_baseline[j] = baseline[j];
adcDat[targetAC]->Data[AC_CHANNELS][j] = Meta[j];
}
}
//if timeout on only some, but not all boards
else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] && DC_ACTIVE[targetAC]){
for(int i = 0; i < AC_CHANNELS; i++){
if(i>0 && i % 6 == 0) psec_cnt ++;
for(int j = 0; j < psecSampleCells; j++){
sample = 0xFF;
adcDat[targetAC]->Data[i][j] = sample;
}
}
for(int j = 0; j < psecSampleCells; j++){
adcDat[targetAC]->Data[AC_CHANNELS][j] =0;
}
}
}
event_data.push_back(adcDat);
last_k = k;
}
cout << endl;
cout << "Done on readout: " << last_k+1 << " :: @time " << t << " sec" << endl;
cleanup();
dump_data();
return event_data;
}
int SuMo::log_data(const char* log_filename, vector<packet_t**> event_data, int trig_mode){
int asic_baseline[psecSampleCells];
float _now_, t = 0.;
Timer timer = Timer();
time_t now;
int last_k;
char logDataFilename[300];
// 'scalar' mode
ofstream rate_fs;
if(trig_mode == 2){
char logRateFilename[300];
sprintf(logRateFilename, "%s.rate", log_filename);
rate_fs.open(logRateFilename, ios::trunc);
}
// full waveform, standard mode
time(&now);
char timestring[100];
strftime(timestring, 80, "%Y-%m-%d-%H-%M", localtime(&now));
// sprintf(logDataFilename, "%s-%s.acdc.dat", timestring, log_filename);
sprintf(logDataFilename, "%s.acdc", log_filename);
// check if file exists, inquire whether to overwrite
// shouldn't be an issue now since file timestamped in filename ^^
string temp;
while(fileExists(logDataFilename)){
cout << "file already exists, try new filename: (or enter to overwrite / ctrl-C to quit): ";
getline(cin, temp);
if(temp.empty()) break;
sprintf(logDataFilename, "%s.acdc", temp.c_str());
}
ofstream ofs;
ofs.open(logDataFilename, ios::trunc);
// save pedestal data to file header for reference, easy access
// zero pad to match data format
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++){
asic_baseline[j] = baseline[j];
}
/* Create header */
char delim = ' ';
ofs << "Event" << delim << "Board" << delim << "Channel" << delim << "Samples" << endl;
/* Record events */
// For each event
for(int event = 0; event < event_data.size(); event++){
packet_t** events = event_data[event];
// For each board
for (int board = 0; board < numFrontBoards; board++){
if (!DC_ACTIVE[board]) continue;
// For each channels
for (int ch = 0; ch < AC_CHANNELS; ch++){
ofs << event << delim << board << delim << ch + 1;
// For each sample
for (int i = 0; i < psecSampleCells; i++) {
int ped_subtracted = events[board]->Data[ch][i] - PED_DATA[board][ch][i];
ofs << delim << dec << ped_subtracted; // std::dec
}
ofs << endl;
}
}
if(trig_mode == 2){
for(int board=0; board<numFrontBoards; board++){
// Get the event vector for the given board
if (DC_ACTIVE[board]){
if(BOARDS_READOUT[board]){
rate_fs << event << "\t" << board << "\t" << t << "\t";
for(int channel=0; channel < AC_CHANNELS; channel++) rate_fs << events[board]->self_trig_scalar[channel] << "\t";
rate_fs << endl;
}
}
}
}
last_k = event;
}
cout << endl;
cout << "Done on readout: " << last_k+1 << " :: @time " <<t<< " sec" << endl;
cleanup();
ofs.close();
if(trig_mode == 2) rate_fs.close();
cout << "Data saved in file: " << logDataFilename << endl << "*****" << endl;
return 0;
}
void SuMo::print_to_terminal(int k, int NUM_READS, int cc_event, int board_trig, double t){
cout << "Readout: " << k+1 << " of " << NUM_READS;
cout <<" :: system|sw evt-" << cc_event << "|" << board_trig;
cout <<" :: evtflags-";
for(int evt_flag =0; evt_flag< numFrontBoards; evt_flag++) cout << EVENT_FLAG[evt_flag];
cout << " :: digflags-";
for(int dig_flag =0; dig_flag< numFrontBoards; dig_flag++) cout << DIGITIZING_START_FLAG[dig_flag];
cout <<" :: @time "<< t << " sec ";
//cout.flush();
}
<commit_msg>decided to pivot other way<commit_after>#include <string.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <time.h>
#include "SuMo.h"
#include "Timer.h"
/* specific to file */
const int NUM_ARGS = 4;
const char* filename = "logData";
const char* description = "log data from DAQ";
using namespace std;
/********************/
/* subtract pedestal values on-line */
static bool PED_SUBTRCT = false;
static int LIMIT_READOUT_RATE = 6000; //usecs limit between event polling
static int NUM_SEQ_TIMEOUTS = 100; // number of sequential timeouts before ending run
const float MAX_INT_TIMER = 800.; // max cpu timer before ending run (secs)
/* note: usb timeout defined in include/stdUSB.h */
bool overwriteExistingFile = false;
int main(int argc, char* argv[]){
if(argc == 2 && std::string(argv[1]) == "-h"){
cout << endl;
cout << filename << " :: " << description << endl;
cout << filename << " :: takes " << NUM_ARGS-1 << " arguments" << endl;
return 1;
}
else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){
cout << "error: too many number of arguments" << endl;
return -1;
}
else{
int num_checks = 5;
int num_events = 100;
SuMo command;
char log_data_filename[100];
strcpy(log_data_filename, argv[1]);
num_events = atoi(argv[2]);
int trig_mode = atoi(argv[3]);
if(command.check_active_boards(num_checks))
return 1;
vector<packet_t**> events = command.get_data(num_events, trig_mode, 0);
command.log_data(log_data_filename, events, trig_mode);
return 0;
}
}
vector<packet_t**> SuMo::get_data(unsigned int NUM_READS, int trig_mode, int acq_rate){
int check_event;
int asic_baseline[psecSampleCells];
int count = 0;
int psec_cnt = 0;
int last_k;
float _now_, t = 0.;
char logDataFilename[300];
Timer timer = Timer();
time_t now;
unsigned short sample;
int* Meta;
vector<packet_t**> event_data;
// read all front end cards
bool all[numFrontBoards];
for(int i = 0; i < numFrontBoards; i++) all[i] = true;
load_ped();
int number_of_frontend_cards = 0;
for( int board = 0; board < numFrontBoards; board++){
if(DC_ACTIVE[board]) number_of_frontend_cards++;
}
cout << "--------------------------------------------------------------" << endl;
cout << "number of front-end boards detected = " << number_of_frontend_cards
<< " of " << numFrontBoards << " address slots in system" << endl;
cout << "Trying for " << NUM_READS << " events logged to disk, in a timeout window of "
<< MAX_INT_TIMER << " seconds" << endl;
cout << "--------------------------------------------------------------" << endl << endl;
usleep(100000);
/* cpu time zero */
timer.start();
bool reset_event = true;
// set read mode to NULL
set_usb_read_mode(0);
if(mode==USB2x) set_usb_read_mode_slaveDevice(0);
system_card_trig_valid(false);
if(mode==USB2x) system_slave_card_trig_valid(false);
//check system trigger number
read_CC(false, false, 100);
int board_trigger= CC_EVENT_COUNT_FROMCC0;
int last_board_trigger = board_trigger;
for(int k=0; k<NUM_READS; k++){
set_usb_read_mode(0);
if(mode==USB2x) set_usb_read_mode_slaveDevice(0);
time(&now);
t = timer.stop();
// interrupt if past specified logging time
if(t > MAX_INT_TIMER) {
cout << endl << "readout timed out at " << t << "on event " << k << endl;
break;
}
// trig_mode = 1 is external source or PSEC4 self trigger
// trig_mode = 0 is over software (USB), i.e. calibration logging
if(trig_mode == 0){
manage_cc_fifo(1);
if(mode==USB2x) manage_cc_fifo_slaveDevice(1);
// 'rate-only' mode, only pull data every second
if(trig_mode == 2) usleep(3e6);
prep_sync();
if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);
software_trigger((unsigned int) 15);
make_sync();
//acq rate limit
usleep(LIMIT_READOUT_RATE); // somewhat arbitrary hard-coded rate limitation
//system_card_trig_valid(false);
//if(mode == USB2x) system_slave_card_trig_valid(false);
}
else{
manage_cc_fifo(1);
if(mode==USB2x) manage_cc_fifo_slaveDevice(1);
usleep(100);
for(int iii=0; iii<2; iii++){
system_card_trig_valid(false);
if(mode==USB2x) system_slave_card_trig_valid(false);
}
//send in trig 'valid' signal
sys_wait(100);
prep_sync();
if(mode==USB2x) system_slave_card_trig_valid(true);
system_card_trig_valid(true);
make_sync();
//}
//acq rate limit
usleep(acq_rate+LIMIT_READOUT_RATE);
}
int num_pulls = 0;
int evts = 0;
int digs = 0;
while(board_trigger==last_board_trigger && t < MAX_INT_TIMER){
read_CC(false, false, 100);
board_trigger = CC_EVENT_COUNT_FROMCC0;
cout << "waiting for trigger... on system event: "
<< board_trigger << " & readout attempt " << k
<< " @time " << t << " \r";
cout.flush();
usleep(1000);
t = timer.stop();
num_pulls++;
if(num_pulls > 100) break;
//if(num_pulls > 10) break; //use this is board trigger does not iterate
}
last_board_trigger = board_trigger;
if(mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
//set_usb_read_mode_slaveDevice(0), set_usb_read_mode(0);
evts = read_CC(false, false, 0);
for(int chkdig=0; chkdig<numFrontBoards; chkdig++)
digs+=DIGITIZING_START_FLAG[chkdig];
//if(evts == 0){
//reset_event = true;
//k = k-1;
//continue;
//}
//condition for dumping event and trying again.
//else if( DIGITIZING_START_FLAG[2] == 0 || evts < 6 || evts != digs){
if( evts == 0 || evts != digs){
print_to_terminal(k, NUM_READS,CC_EVENT_COUNT_FROMCC0, board_trigger, t);
cout << " --NULL-- " << endl;
//cout.flush();
reset_event = true;
k = k-1; //repeat event
continue;
}
// show event number at terminal
else{
if((k+1) % 1 == 0 || k==0){
print_to_terminal(k, NUM_READS, CC_EVENT_COUNT_FROMCC0, board_trigger, t);
cout << " \r";
cout.flush();
}
}
/**************************************/
//Do bulk read on all front-end cards
int numBoards = read_AC(1, all, false);
/**************************************/
sys_wait(10000);
for(int jj=0; jj<2; jj++){
//prep_sync();
//turn off 'trig valid flag' until checking if data in buffer
if(mode == USB2x) system_slave_card_trig_valid(false);
system_card_trig_valid(false);
if(mode == USB2x) set_usb_read_mode_slaveDevice(0);
set_usb_read_mode(0);
}
reset_event = true; //have event, go ahead and reset for next event
// form data for filesave
for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){
if(BOARDS_READOUT[targetAC] && numBoards > 0){
psec_cnt = 0;
// assign meta data
Meta=get_AC_info(false, targetAC, false,k, t, t, evts);
check_event = 0;
for(int i = 0; i < AC_CHANNELS; i++){
if(i>0 && i % 6 == 0) psec_cnt ++;
for(int j = 0; j < psecSampleCells; j++){
sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];
if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j];
adcDat[targetAC]->Data[i][j] = (unsigned int) sample;
}
}
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++){
asic_baseline[j] = baseline[j];
adcDat[targetAC]->Data[AC_CHANNELS][j] = Meta[j];
}
}
//if timeout on only some, but not all boards
else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] && DC_ACTIVE[targetAC]){
for(int i = 0; i < AC_CHANNELS; i++){
if(i>0 && i % 6 == 0) psec_cnt ++;
for(int j = 0; j < psecSampleCells; j++){
sample = 0xFF;
adcDat[targetAC]->Data[i][j] = sample;
}
}
for(int j = 0; j < psecSampleCells; j++){
adcDat[targetAC]->Data[AC_CHANNELS][j] =0;
}
}
}
event_data.push_back(adcDat);
last_k = k;
}
cout << endl;
cout << "Done on readout: " << last_k+1 << " :: @time " << t << " sec" << endl;
cleanup();
dump_data();
return event_data;
}
int SuMo::log_data(const char* log_filename, vector<packet_t**> event_data, int trig_mode){
int asic_baseline[psecSampleCells];
float _now_, t = 0.;
Timer timer = Timer();
time_t now;
int last_k;
char logDataFilename[300];
// 'scalar' mode
ofstream rate_fs;
if(trig_mode == 2){
char logRateFilename[300];
sprintf(logRateFilename, "%s.rate", log_filename);
rate_fs.open(logRateFilename, ios::trunc);
}
// full waveform, standard mode
time(&now);
char timestring[100];
strftime(timestring, 80, "%Y-%m-%d-%H-%M", localtime(&now));
// sprintf(logDataFilename, "%s-%s.acdc.dat", timestring, log_filename);
sprintf(logDataFilename, "%s.acdc", log_filename);
// check if file exists, inquire whether to overwrite
// shouldn't be an issue now since file timestamped in filename ^^
string temp;
while(fileExists(logDataFilename)){
cout << "file already exists, try new filename: (or enter to overwrite / ctrl-C to quit): ";
getline(cin, temp);
if(temp.empty()) break;
sprintf(logDataFilename, "%s.acdc", temp.c_str());
}
ofstream ofs;
ofs.open(logDataFilename, ios::trunc);
// save pedestal data to file header for reference, easy access
// zero pad to match data format
/* wraparound_correction, if desired: */
int baseline[psecSampleCells];
unwrap_baseline(baseline, 2);
for (int j = 0; j < psecSampleCells; j++){
asic_baseline[j] = baseline[j];
}
/* Create header */
char delim = ' ';
ofs << "Event" << delim << "Board" << delim << "Cell";
for(int ch = 1; ch <= AC_CHANNELS; ch++){
ofs << delim << "Ch" << ch;
}
ofs << endl;
/* Record events */
// For each event
for(int event = 0; event < event_data.size(); event++){
packet_t** events = event_data[event];
// For each board
for (int board = 0; board < numFrontBoards; board++){
if (!DC_ACTIVE[board]) continue;
// For each sample
for (int i = 0; i < psecSampleCells; i++){
ofs << event << delim << board << delim << i;
// For each channel
for (int ch = 0; ch < AC_CHANNELS; ch++) {
int ped_subtracted = events[board]->Data[ch][i] - PED_DATA[board][ch][i];
ofs << delim << dec << ped_subtracted; // std::dec
}
ofs << endl;
}
}
if(trig_mode == 2){
for(int board=0; board<numFrontBoards; board++){
// Get the event vector for the given board
if (DC_ACTIVE[board]){
if(BOARDS_READOUT[board]){
rate_fs << event << "\t" << board << "\t" << t << "\t";
for(int channel=0; channel < AC_CHANNELS; channel++) rate_fs << events[board]->self_trig_scalar[channel] << "\t";
rate_fs << endl;
}
}
}
}
last_k = event;
}
cout << endl;
cout << "Done on readout: " << last_k+1 << " :: @time " <<t<< " sec" << endl;
cleanup();
ofs.close();
if(trig_mode == 2) rate_fs.close();
cout << "Data saved in file: " << logDataFilename << endl << "*****" << endl;
return 0;
}
void SuMo::print_to_terminal(int k, int NUM_READS, int cc_event, int board_trig, double t){
cout << "Readout: " << k+1 << " of " << NUM_READS;
cout <<" :: system|sw evt-" << cc_event << "|" << board_trig;
cout <<" :: evtflags-";
for(int evt_flag =0; evt_flag< numFrontBoards; evt_flag++) cout << EVENT_FLAG[evt_flag];
cout << " :: digflags-";
for(int dig_flag =0; dig_flag< numFrontBoards; dig_flag++) cout << DIGITIZING_START_FLAG[dig_flag];
cout <<" :: @time "<< t << " sec ";
//cout.flush();
}
<|endoftext|>
|
<commit_before>/* gobby - A GTKmm driven libobby client
* Copyright (C) 2005, 2006 0x539 dev group
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <ctime>
#include <obby/format_string.hpp>
#include "features.hpp"
#include "logview.hpp"
#ifdef WITH_GNOME
# include <libgnomevfs/gnome-vfs-utils.h>
#endif
#if defined(WITH_GNOME)
void show_url(const char* url)
{
gnome_vfs_url_show(url);
}
#elif defined(WIN32)
void show_url(const char* url)
{
ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNA);
}
#elif defined(OSX)
void show_url(const char* url)
{
Glib::spawn_command_line_async("open " + std::string(url) );
}
#endif
Gobby::LogView::LogView():
#ifdef HAVE_SHOW_URL
Gtk::TextView(), m_default(Gdk::XTERM), m_hand(Gdk::HAND2),
m_hovering(false)
#else
Gtk::TextView()
#endif
{
m_end_mark = get_buffer()->create_mark(
"end_mark", get_buffer()->end(), false
);
set_editable(false);
set_cursor_visible(false);
set_wrap_mode(Gtk::WRAP_WORD_CHAR);
#ifdef HAVE_SHOW_URL
signal_motion_notify_event().connect(
sigc::mem_fun(*this, &LogView::on_motion_notify)
);
signal_event_after().connect(
sigc::mem_fun(*this, &LogView::on_event_after)
);
Gdk::Color blue;
blue.set_red(0x0000);
blue.set_green(0x0000);
blue.set_blue(0xffff);
m_tag_link = Gtk::TextTag::create();
m_tag_link->property_foreground_gdk() = blue;
m_tag_link->property_underline() = Pango::UNDERLINE_SINGLE;
get_buffer()->get_tag_table()->add(m_tag_link);
#endif
}
void Gobby::LogView::clear()
{
get_buffer()->set_text("");
}
void Gobby::LogView::log(const Glib::ustring& text,
const Glib::ustring& color)
{
log(text, color, std::time(NULL) );
}
void Gobby::LogView::log(const Glib::ustring& text,
const Glib::ustring& color,
std::time_t timestamp)
{
Glib::RefPtr<Gtk::TextBuffer> buffer = get_buffer();
Glib::RefPtr<Gtk::TextTag> tag = buffer->get_tag_table()->lookup(color);
Glib::ustring ins_text = text;
if(ins_text[ins_text.length() - 1] != '\n') ins_text += "\n";
const char* formatter = "%X";
std::time_t cur_time_t = std::time(NULL);
std::tm cur_time_tm = *std::localtime(&cur_time_t);
std::tm given_time_tm = *std::localtime(×tamp);
// Show date if the text was not logged today
if(cur_time_tm.tm_yday != given_time_tm.tm_yday ||
cur_time_tm.tm_year != given_time_tm.tm_year)
{
formatter = "%x %X";
}
char buf[0x7f];
std::strftime(buf, 0x7f, formatter, &given_time_tm);
obby::format_string str("[%0%] %1%");
str << buf << ins_text.raw();
if(!tag)
{
tag = Gtk::TextTag::create();
tag->property_foreground() = color;
buffer->get_tag_table()->add(tag);
tag->set_priority(0);
}
Gtk::TextIter end = buffer->insert_with_tag(
buffer->end(),
str.str(),
tag
);
scroll_to_mark(m_end_mark, 0.0f);
#ifdef HAVE_SHOW_URL
Gtk::TextIter begin = end;
begin.backward_chars(text.length() );
set_url_tag(begin, end);
#endif
}
#ifdef HAVE_SHOW_URL
void Gobby::LogView::set_url_tag(const Gtk::TextIter& begin,
const Gtk::TextIter& end)
{
Gtk::TextIter pos = begin;
Gtk::TextIter match_begin, match_end;
Gtk::TextSearchFlags flags = Gtk::TextSearchFlags(0);
while(pos.forward_search("http://", flags, match_begin, match_end, end))
{
// Advance to next space
pos = match_end;
while(pos != end && !Glib::Unicode::isspace(*pos))
++ pos;
get_buffer()->apply_tag(m_tag_link, match_begin, pos);
}
}
bool Gobby::LogView::on_motion_notify(GdkEventMotion* event)
{
int buffer_x, buffer_y;
window_to_buffer_coords(
Gtk::TEXT_WINDOW_WIDGET,
static_cast<int>(event->x),
static_cast<int>(event->y),
buffer_x,
buffer_y
);
Gtk::TextIter iter;
get_iter_at_location(iter, buffer_x, buffer_y);
if(iter.has_tag(m_tag_link) && !m_hovering)
{
get_window(Gtk::TEXT_WINDOW_TEXT)->set_cursor(m_hand);
m_hovering = true;
}
else if(!iter.has_tag(m_tag_link) && m_hovering)
{
get_window(Gtk::TEXT_WINDOW_TEXT)->set_cursor(m_default);
m_hovering = false;
}
gdk_window_get_pointer(
Gtk::Widget::get_window()->gobj(),
NULL, NULL, NULL
);
return false;
}
void Gobby::LogView::on_event_after(GdkEvent* event)
{
if(event->type != GDK_BUTTON_RELEASE) return;
GdkEventButton* button_event = &event->button;
if(button_event->button != 1) return;
Glib::RefPtr<Gtk::TextBuffer> buffer = get_buffer();
Gtk::TextIter begin, end;
buffer->get_selection_bounds(begin, end);
if(begin != end) return;
int buffer_x, buffer_y;
window_to_buffer_coords(
Gtk::TEXT_WINDOW_WIDGET,
static_cast<int>(button_event->x),
static_cast<int>(button_event->y),
buffer_x,
buffer_y
);
Gtk::TextIter iter;
get_iter_at_location(iter, buffer_x, buffer_y);
if(!iter.has_tag(m_tag_link) ) return;
begin = end = iter;
begin.backward_to_tag_toggle(m_tag_link);
end.forward_to_tag_toggle(m_tag_link);
Glib::ustring link = begin.get_slice(end);
show_url(link.c_str() );
}
#endif
<commit_msg>[project @ MingW compilation fix]<commit_after>/* gobby - A GTKmm driven libobby client
* Copyright (C) 2005, 2006 0x539 dev group
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <ctime>
#include <obby/format_string.hpp>
#include "features.hpp"
#include "logview.hpp"
#ifdef WITH_GNOME
# include <libgnomevfs/gnome-vfs-utils.h>
#endif
#ifdef WIN32
# include <windows.h>
#endif
#if defined(WITH_GNOME)
void show_url(const char* url)
{
gnome_vfs_url_show(url);
}
#elif defined(WIN32)
void show_url(const char* url)
{
ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNA);
}
#elif defined(OSX)
void show_url(const char* url)
{
Glib::spawn_command_line_async("open " + std::string(url) );
}
#endif
Gobby::LogView::LogView():
#ifdef HAVE_SHOW_URL
Gtk::TextView(), m_default(Gdk::XTERM), m_hand(Gdk::HAND2),
m_hovering(false)
#else
Gtk::TextView()
#endif
{
m_end_mark = get_buffer()->create_mark(
"end_mark", get_buffer()->end(), false
);
set_editable(false);
set_cursor_visible(false);
set_wrap_mode(Gtk::WRAP_WORD_CHAR);
#ifdef HAVE_SHOW_URL
signal_motion_notify_event().connect(
sigc::mem_fun(*this, &LogView::on_motion_notify)
);
signal_event_after().connect(
sigc::mem_fun(*this, &LogView::on_event_after)
);
Gdk::Color blue;
blue.set_red(0x0000);
blue.set_green(0x0000);
blue.set_blue(0xffff);
m_tag_link = Gtk::TextTag::create();
m_tag_link->property_foreground_gdk() = blue;
m_tag_link->property_underline() = Pango::UNDERLINE_SINGLE;
get_buffer()->get_tag_table()->add(m_tag_link);
#endif
}
void Gobby::LogView::clear()
{
get_buffer()->set_text("");
}
void Gobby::LogView::log(const Glib::ustring& text,
const Glib::ustring& color)
{
log(text, color, std::time(NULL) );
}
void Gobby::LogView::log(const Glib::ustring& text,
const Glib::ustring& color,
std::time_t timestamp)
{
Glib::RefPtr<Gtk::TextBuffer> buffer = get_buffer();
Glib::RefPtr<Gtk::TextTag> tag = buffer->get_tag_table()->lookup(color);
Glib::ustring ins_text = text;
if(ins_text[ins_text.length() - 1] != '\n') ins_text += "\n";
const char* formatter = "%X";
std::time_t cur_time_t = std::time(NULL);
std::tm cur_time_tm = *std::localtime(&cur_time_t);
std::tm given_time_tm = *std::localtime(×tamp);
// Show date if the text was not logged today
if(cur_time_tm.tm_yday != given_time_tm.tm_yday ||
cur_time_tm.tm_year != given_time_tm.tm_year)
{
formatter = "%x %X";
}
char buf[0x7f];
std::strftime(buf, 0x7f, formatter, &given_time_tm);
obby::format_string str("[%0%] %1%");
str << buf << ins_text.raw();
if(!tag)
{
tag = Gtk::TextTag::create();
tag->property_foreground() = color;
buffer->get_tag_table()->add(tag);
tag->set_priority(0);
}
Gtk::TextIter end = buffer->insert_with_tag(
buffer->end(),
str.str(),
tag
);
scroll_to_mark(m_end_mark, 0.0f);
#ifdef HAVE_SHOW_URL
Gtk::TextIter begin = end;
begin.backward_chars(text.length() );
set_url_tag(begin, end);
#endif
}
#ifdef HAVE_SHOW_URL
void Gobby::LogView::set_url_tag(const Gtk::TextIter& begin,
const Gtk::TextIter& end)
{
Gtk::TextIter pos = begin;
Gtk::TextIter match_begin, match_end;
Gtk::TextSearchFlags flags = Gtk::TextSearchFlags(0);
while(pos.forward_search("http://", flags, match_begin, match_end, end))
{
// Advance to next space
pos = match_end;
while(pos != end && !Glib::Unicode::isspace(*pos))
++ pos;
get_buffer()->apply_tag(m_tag_link, match_begin, pos);
}
}
bool Gobby::LogView::on_motion_notify(GdkEventMotion* event)
{
int buffer_x, buffer_y;
window_to_buffer_coords(
Gtk::TEXT_WINDOW_WIDGET,
static_cast<int>(event->x),
static_cast<int>(event->y),
buffer_x,
buffer_y
);
Gtk::TextIter iter;
get_iter_at_location(iter, buffer_x, buffer_y);
if(iter.has_tag(m_tag_link) && !m_hovering)
{
get_window(Gtk::TEXT_WINDOW_TEXT)->set_cursor(m_hand);
m_hovering = true;
}
else if(!iter.has_tag(m_tag_link) && m_hovering)
{
get_window(Gtk::TEXT_WINDOW_TEXT)->set_cursor(m_default);
m_hovering = false;
}
gdk_window_get_pointer(
Gtk::Widget::get_window()->gobj(),
NULL, NULL, NULL
);
return false;
}
void Gobby::LogView::on_event_after(GdkEvent* event)
{
if(event->type != GDK_BUTTON_RELEASE) return;
GdkEventButton* button_event = &event->button;
if(button_event->button != 1) return;
Glib::RefPtr<Gtk::TextBuffer> buffer = get_buffer();
Gtk::TextIter begin, end;
buffer->get_selection_bounds(begin, end);
if(begin != end) return;
int buffer_x, buffer_y;
window_to_buffer_coords(
Gtk::TEXT_WINDOW_WIDGET,
static_cast<int>(button_event->x),
static_cast<int>(button_event->y),
buffer_x,
buffer_y
);
Gtk::TextIter iter;
get_iter_at_location(iter, buffer_x, buffer_y);
if(!iter.has_tag(m_tag_link) ) return;
begin = end = iter;
begin.backward_to_tag_toggle(m_tag_link);
end.forward_to_tag_toggle(m_tag_link);
Glib::ustring link = begin.get_slice(end);
show_url(link.c_str() );
}
#endif
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include "demoloop.h"
#include "graphics/2d_primitives.h"
#include "hsl.h"
using namespace std;
using namespace demoloop;
#define NUM_VERTS 12
float t = 0;
const float CYCLE_LENGTH = 6;
class Loop015 : public Demoloop {
public:
Loop015() : Demoloop(150, 150, 150), RADIUS(height / 6) {
glDisable(GL_DEPTH_TEST);
float phi = 0.0f;
const float interval = DEMOLOOP_M_PI * 2 / NUM_VERTS * 2;
for (int i = 0; i < NUM_VERTS - 1; i+=2, phi += interval) {
vertices[i].x = RADIUS * cosf(phi);
vertices[i].y = RADIUS * sinf(phi);
vertices[i].z = 1;
vertices[i + 1].x = RADIUS * cosf(phi + interval);
vertices[i + 1].y = RADIUS * sinf(phi + interval);
vertices[i + 1].z = 1;
}
gl.getTransform() = glm::translate(gl.getTransform(), {width / 2, height / 2, 0});
}
void Update(float dt) {
t += dt;
float cycle = fmod(t, CYCLE_LENGTH);
float cycle_ratio = cycle / CYCLE_LENGTH;
setColor(255, 255, 255);
gl.lines(vertices, NUM_VERTS);
const float interval = DEMOLOOP_M_PI * 2 / 6;
float apothem = cos(DEMOLOOP_M_PI / 6) * RADIUS;
float side = 2 * apothem * tan(DEMOLOOP_M_PI / 6);
for (int i = 0; i < 6; ++i) {
gl.pushTransform();
glm::mat4 &m = gl.getTransform();
int current_vertex = fmod(floor(i + cycle_ratio * 6), 6);
float phi = current_vertex * interval + DEMOLOOP_M_PI / 3 * 2;
float x = side * cosf(phi) * pow(sinf(cycle_ratio * DEMOLOOP_M_PI), 2);
float y = side * sinf(phi) * pow(sinf(cycle_ratio * DEMOLOOP_M_PI), 2);
m = glm::translate(m, {x, y, 0});
gl.lines(vertices, NUM_VERTS);
gl.popTransform();
}
}
private:
const float RADIUS;
Vertex vertices[NUM_VERTS];
};
int main(int, char**){
Loop015 loop;
loop.Run();
return 0;
}
<commit_msg>update loop017<commit_after>#include <algorithm>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include "demoloop.h"
#include "graphics/2d_primitives.h"
#include "hsl.h"
using namespace std;
using namespace demoloop;
const uint32_t NUM_VERTS = 6;
float t = 0;
const float CYCLE_LENGTH = 6;
class Loop015 : public Demoloop {
public:
Loop015() : Demoloop(150, 150, 150), RADIUS(height / 6) {
glDisable(GL_DEPTH_TEST);
const float interval = DEMOLOOP_M_PI * 2 / NUM_VERTS;
for (uint32_t i = 0; i < NUM_VERTS; ++i) {
const float phi = interval * i;
vertices[i].x = RADIUS * cosf(phi);
vertices[i].y = RADIUS * sinf(phi);
vertices[i].z = 1;
}
gl.getTransform() = glm::translate(gl.getTransform(), {width / 2, height / 2, 0});
}
void Update(float dt) {
t += dt;
float cycle = fmod(t, CYCLE_LENGTH);
float cycle_ratio = cycle / CYCLE_LENGTH;
setColor(255, 255, 255);
gl.lineLoop(vertices, NUM_VERTS, glm::mat4());
const float interval = DEMOLOOP_M_PI * 2 / 6;
float apothem = cos(DEMOLOOP_M_PI / 6) * RADIUS;
float side = 2 * apothem * tan(DEMOLOOP_M_PI / 6);
for (int i = 0; i < 6; ++i) {
int current_vertex = fmod(floor(i + cycle_ratio * 6), 6);
float phi = current_vertex * interval + DEMOLOOP_M_PI / 3 * 2;
float x = side * cosf(phi) * pow(sinf(cycle_ratio * DEMOLOOP_M_PI), 2);
float y = side * sinf(phi) * pow(sinf(cycle_ratio * DEMOLOOP_M_PI), 2);
glm::mat4 m;
m = glm::translate(m, {x, y, 0});
gl.lineLoop(vertices, NUM_VERTS, m);
}
}
private:
const float RADIUS;
Vertex vertices[NUM_VERTS];
};
int main(int, char**){
Loop015 loop;
loop.Run();
return 0;
}
<|endoftext|>
|
<commit_before>//===- ReadConst.cpp - Code to constants and constant pools ---------------===//
//
// This file implements functionality to deserialize constants and entire
// constant pools.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include <algorithm>
const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
const uchar *EndBuf) {
unsigned PrimType;
if (read_vbr(Buf, EndBuf, PrimType)) return 0;
const Type *Val = 0;
if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
return Val;
switch (PrimType) {
case Type::FunctionTyID: {
unsigned Typ;
if (read_vbr(Buf, EndBuf, Typ)) return Val;
const Type *RetType = getType(Typ);
if (RetType == 0) return Val;
unsigned NumParams;
if (read_vbr(Buf, EndBuf, NumParams)) return Val;
std::vector<const Type*> Params;
while (NumParams--) {
if (read_vbr(Buf, EndBuf, Typ)) return Val;
const Type *Ty = getType(Typ);
if (Ty == 0) return Val;
Params.push_back(Ty);
}
bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
if (isVarArg) Params.pop_back();
return FunctionType::get(RetType, Params, isVarArg);
}
case Type::ArrayTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return Val;
unsigned NumElements;
if (read_vbr(Buf, EndBuf, NumElements)) return Val;
BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
<< NumElements << "\n");
return ArrayType::get(ElementType, NumElements);
}
case Type::StructTyID: {
unsigned Typ;
std::vector<const Type*> Elements;
if (read_vbr(Buf, EndBuf, Typ)) return Val;
while (Typ) { // List is terminated by void/0 typeid
const Type *Ty = getType(Typ);
if (Ty == 0) return Val;
Elements.push_back(Ty);
if (read_vbr(Buf, EndBuf, Typ)) return Val;
}
return StructType::get(Elements);
}
case Type::PointerTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return Val;
return PointerType::get(ElementType);
}
case Type::OpaqueTyID: {
return OpaqueType::get();
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize"
<< " primitive Type " << PrimType << "\n";
return Val;
}
}
// refineAbstractType - The callback method is invoked when one of the
// elements of TypeValues becomes more concrete...
//
void BytecodeParser::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
if (OldType == NewType &&
OldType->isAbstract()) return; // Type is modified, but same
TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
FunctionTypeValues.end(), OldType);
if (I == FunctionTypeValues.end()) {
I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
assert(I != ModuleTypeValues.end() &&
"Can't refine a type I don't know about!");
}
if (OldType == NewType) {
assert(!OldType->isAbstract());
I->removeUserFromConcrete();
} else {
*I = NewType; // Update to point to new, more refined type.
}
}
// parseTypeConstants - We have to use this wierd code to handle recursive
// types. We know that recursive types will only reference the current slab of
// values in the type plane, but they can forward reference types before they
// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
// this ugly problem, we pesimistically insert an opaque type for each type we
// are about to read. This means that forward references will resolve to
// something and when we reread the type later, we can replace the opaque type
// with a new resolved concrete type.
//
void debug_type_tables();
bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
TypeValuesListTy &Tab,
unsigned NumEntries) {
assert(Tab.size() == 0 && "should not have read type constants in before!");
// Insert a bunch of opaque types to be resolved later...
for (unsigned i = 0; i < NumEntries; ++i)
Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
// Loop through reading all of the types. Forward types will make use of the
// opaque types just inserted.
//
for (unsigned i = 0; i < NumEntries; ++i) {
const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
if (NewTy == 0) return true;
BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
"' Replacing: " << OldTy << "\n");
// Don't insertValue the new type... instead we want to replace the opaque
// type with the new concrete value...
//
// Refine the abstract type to the new type. This causes all uses of the
// abstract type to use the newty. This also will cause the opaque type
// to be deleted...
//
((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
// This should have replace the old opaque type with the new type in the
// value table... or with a preexisting type that was already in the system
assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
}
BCR_TRACE(5, "Resulting types:\n");
for (unsigned i = 0; i < NumEntries; ++i) {
BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
}
debug_type_tables();
return false;
}
bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
const Type *Ty, Constant *&V) {
// We must check for a ConstantExpr before switching by type because
// a ConstantExpr can be of any type, and has no explicit value.
//
unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
if (read_vbr(Buf, EndBuf, isExprNumArgs)) return true;
if (isExprNumArgs) {
// FIXME: Encoding of constant exprs could be much more compact!
unsigned Opcode;
std::vector<Constant*> ArgVec;
ArgVec.reserve(isExprNumArgs);
if (read_vbr(Buf, EndBuf, Opcode)) return true;
// Read the slot number and types of each of the arguments
for (unsigned i = 0; i != isExprNumArgs; ++i) {
unsigned ArgValSlot, ArgTypeSlot;
if (read_vbr(Buf, EndBuf, ArgValSlot)) return true;
if (read_vbr(Buf, EndBuf, ArgTypeSlot)) return true;
const Type *ArgTy = getType(ArgTypeSlot);
if (ArgTy == 0) return true;
BCR_TRACE(4, "CE Arg " << i << ": Type: '" << ArgTy << "' slot: "
<< ArgValSlot << "\n");
// Get the arg value from its slot if it exists, otherwise a placeholder
Constant *C = getConstantValue(ArgTy, ArgValSlot);
if (C == 0) return true;
ArgVec.push_back(C);
}
// Construct a ConstantExpr of the appropriate kind
if (isExprNumArgs == 1) { // All one-operand expressions
assert(Opcode == Instruction::Cast);
V = ConstantExpr::getCast(ArgVec[0], Ty);
} else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
V = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
} else { // All other 2-operand expressions
V = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
}
return false;
}
// Ok, not an ConstantExpr. We now know how to read the given type...
switch (Ty->getPrimitiveID()) {
case Type::BoolTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
if (Val != 0 && Val != 1) return true;
V = ConstantBool::get(Val == 1);
break;
}
case Type::UByteTyID: // Unsigned integer types...
case Type::UShortTyID:
case Type::UIntTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
if (!ConstantUInt::isValueValidForType(Ty, Val)) return true;
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::ULongTyID: {
uint64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::SByteTyID: // Unsigned integer types...
case Type::ShortTyID:
case Type::IntTyID: {
int Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
if (!ConstantSInt::isValueValidForType(Ty, Val)) return true;
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::LongTyID: {
int64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::FloatTyID: {
float F;
if (input_data(Buf, EndBuf, &F, &F+1)) return true;
V = ConstantFP::get(Ty, F);
break;
}
case Type::DoubleTyID: {
double Val;
if (input_data(Buf, EndBuf, &Val, &Val+1)) return true;
V = ConstantFP::get(Ty, Val);
break;
}
case Type::TypeTyID:
assert(0 && "Type constants should be handled seperately!!!");
abort();
case Type::ArrayTyID: {
const ArrayType *AT = cast<const ArrayType>(Ty);
unsigned NumElements = AT->getNumElements();
std::vector<Constant*> Elements;
while (NumElements--) { // Read all of the elements of the constant.
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return true;
Constant *C = getConstantValue(AT->getElementType(), Slot);
if (!C) return true;
Elements.push_back(C);
}
V = ConstantArray::get(AT, Elements);
break;
}
case Type::StructTyID: {
const StructType *ST = cast<StructType>(Ty);
const StructType::ElementTypes &ET = ST->getElementTypes();
std::vector<Constant *> Elements;
for (unsigned i = 0; i < ET.size(); ++i) {
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return true;
Constant *C = getConstantValue(ET[i], Slot);
if (!C) return true;
Elements.push_back(C);
}
V = ConstantStruct::get(ST, Elements);
break;
}
case Type::PointerTyID: {
const PointerType *PT = cast<const PointerType>(Ty);
unsigned SubClass;
if (HasImplicitZeroInitializer)
SubClass = 1;
else
if (read_vbr(Buf, EndBuf, SubClass)) return true;
switch (SubClass) {
case 0: // ConstantPointerNull value...
V = ConstantPointerNull::get(PT);
break;
case 1: { // ConstantPointerRef value...
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return true;
BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
// Check to see if we have already read this global variable...
Value *Val = getValue(PT, Slot, false);
GlobalValue *GV;
if (Val) {
if (!(GV = dyn_cast<GlobalValue>(Val))) return true;
BCR_TRACE(5, "Value Found in ValueTable!\n");
} else if (RevisionNum > 0) {
// Revision #0 could have forward references to globals that were wierd.
// We got rid of this in subsequent revs.
return true;
} else { // Nope... find or create a forward ref. for it
GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
if (I != GlobalRefs.end()) {
BCR_TRACE(5, "Previous forward ref found!\n");
GV = cast<GlobalValue>(I->second);
} else {
BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
// Create a placeholder for the global variable reference...
GlobalVariable *GVar =
new GlobalVariable(PT->getElementType(), false,
GlobalValue::InternalLinkage);
// Keep track of the fact that we have a forward ref to recycle it
GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
// Must temporarily push this value into the module table...
TheModule->getGlobalList().push_back(GVar);
GV = GVar;
}
}
V = ConstantPointerRef::get(GV);
break;
}
default:
BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
return true;
}
break;
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize constant value of type '"
<< Ty->getName() << "'\n";
return true;
}
return false;
}
bool BytecodeParser::ParseGlobalTypes(const uchar *&Buf, const uchar *EndBuf) {
ValueTable T;
return ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
}
bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
ValueTable &Tab,
TypeValuesListTy &TypeTab) {
while (Buf < EndBuf) {
unsigned NumEntries, Typ;
if (read_vbr(Buf, EndBuf, NumEntries) ||
read_vbr(Buf, EndBuf, Typ)) return true;
const Type *Ty = getType(Typ);
if (Ty == 0) return true;
BCR_TRACE(3, "Type: '" << Ty << "' NumEntries: " << NumEntries << "\n");
if (Typ == Type::TypeTyID) {
if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
} else {
for (unsigned i = 0; i < NumEntries; ++i) {
Constant *C;
int Slot;
if (parseConstantValue(Buf, EndBuf, Ty, C)) return true;
assert(C && "parseConstantValue returned NULL!");
BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
if ((Slot = insertValue(C, Tab)) == -1) return true;
// If we are reading a function constant table, make sure that we adjust
// the slot number to be the real global constant number.
//
if (&Tab != &ModuleValues && Typ < ModuleValues.size())
Slot += ModuleValues[Typ]->size();
ResolveReferencesToValue(C, (unsigned)Slot);
}
}
}
if (Buf > EndBuf) return true;
return false;
}
<commit_msg>Fix Bug: Assembler/2003-05-12-MinIntProblem.llx<commit_after>//===- ReadConst.cpp - Code to constants and constant pools ---------------===//
//
// This file implements functionality to deserialize constants and entire
// constant pools.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include <algorithm>
const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
const uchar *EndBuf) {
unsigned PrimType;
if (read_vbr(Buf, EndBuf, PrimType)) return 0;
const Type *Val = 0;
if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
return Val;
switch (PrimType) {
case Type::FunctionTyID: {
unsigned Typ;
if (read_vbr(Buf, EndBuf, Typ)) return Val;
const Type *RetType = getType(Typ);
if (RetType == 0) return Val;
unsigned NumParams;
if (read_vbr(Buf, EndBuf, NumParams)) return Val;
std::vector<const Type*> Params;
while (NumParams--) {
if (read_vbr(Buf, EndBuf, Typ)) return Val;
const Type *Ty = getType(Typ);
if (Ty == 0) return Val;
Params.push_back(Ty);
}
bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
if (isVarArg) Params.pop_back();
return FunctionType::get(RetType, Params, isVarArg);
}
case Type::ArrayTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return Val;
unsigned NumElements;
if (read_vbr(Buf, EndBuf, NumElements)) return Val;
BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
<< NumElements << "\n");
return ArrayType::get(ElementType, NumElements);
}
case Type::StructTyID: {
unsigned Typ;
std::vector<const Type*> Elements;
if (read_vbr(Buf, EndBuf, Typ)) return Val;
while (Typ) { // List is terminated by void/0 typeid
const Type *Ty = getType(Typ);
if (Ty == 0) return Val;
Elements.push_back(Ty);
if (read_vbr(Buf, EndBuf, Typ)) return Val;
}
return StructType::get(Elements);
}
case Type::PointerTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return Val;
return PointerType::get(ElementType);
}
case Type::OpaqueTyID: {
return OpaqueType::get();
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize"
<< " primitive Type " << PrimType << "\n";
return Val;
}
}
// refineAbstractType - The callback method is invoked when one of the
// elements of TypeValues becomes more concrete...
//
void BytecodeParser::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
if (OldType == NewType &&
OldType->isAbstract()) return; // Type is modified, but same
TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
FunctionTypeValues.end(), OldType);
if (I == FunctionTypeValues.end()) {
I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
assert(I != ModuleTypeValues.end() &&
"Can't refine a type I don't know about!");
}
if (OldType == NewType) {
assert(!OldType->isAbstract());
I->removeUserFromConcrete();
} else {
*I = NewType; // Update to point to new, more refined type.
}
}
// parseTypeConstants - We have to use this wierd code to handle recursive
// types. We know that recursive types will only reference the current slab of
// values in the type plane, but they can forward reference types before they
// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
// this ugly problem, we pesimistically insert an opaque type for each type we
// are about to read. This means that forward references will resolve to
// something and when we reread the type later, we can replace the opaque type
// with a new resolved concrete type.
//
void debug_type_tables();
bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
TypeValuesListTy &Tab,
unsigned NumEntries) {
assert(Tab.size() == 0 && "should not have read type constants in before!");
// Insert a bunch of opaque types to be resolved later...
for (unsigned i = 0; i < NumEntries; ++i)
Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
// Loop through reading all of the types. Forward types will make use of the
// opaque types just inserted.
//
for (unsigned i = 0; i < NumEntries; ++i) {
const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
if (NewTy == 0) return true;
BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
"' Replacing: " << OldTy << "\n");
// Don't insertValue the new type... instead we want to replace the opaque
// type with the new concrete value...
//
// Refine the abstract type to the new type. This causes all uses of the
// abstract type to use the newty. This also will cause the opaque type
// to be deleted...
//
((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
// This should have replace the old opaque type with the new type in the
// value table... or with a preexisting type that was already in the system
assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
}
BCR_TRACE(5, "Resulting types:\n");
for (unsigned i = 0; i < NumEntries; ++i) {
BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
}
debug_type_tables();
return false;
}
bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
const Type *Ty, Constant *&V) {
// We must check for a ConstantExpr before switching by type because
// a ConstantExpr can be of any type, and has no explicit value.
//
unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
if (read_vbr(Buf, EndBuf, isExprNumArgs)) return true;
if (isExprNumArgs) {
// FIXME: Encoding of constant exprs could be much more compact!
unsigned Opcode;
std::vector<Constant*> ArgVec;
ArgVec.reserve(isExprNumArgs);
if (read_vbr(Buf, EndBuf, Opcode)) return true;
// Read the slot number and types of each of the arguments
for (unsigned i = 0; i != isExprNumArgs; ++i) {
unsigned ArgValSlot, ArgTypeSlot;
if (read_vbr(Buf, EndBuf, ArgValSlot)) return true;
if (read_vbr(Buf, EndBuf, ArgTypeSlot)) return true;
const Type *ArgTy = getType(ArgTypeSlot);
if (ArgTy == 0) return true;
BCR_TRACE(4, "CE Arg " << i << ": Type: '" << ArgTy << "' slot: "
<< ArgValSlot << "\n");
// Get the arg value from its slot if it exists, otherwise a placeholder
Constant *C = getConstantValue(ArgTy, ArgValSlot);
if (C == 0) return true;
ArgVec.push_back(C);
}
// Construct a ConstantExpr of the appropriate kind
if (isExprNumArgs == 1) { // All one-operand expressions
assert(Opcode == Instruction::Cast);
V = ConstantExpr::getCast(ArgVec[0], Ty);
} else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
V = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
} else { // All other 2-operand expressions
V = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
}
return false;
}
// Ok, not an ConstantExpr. We now know how to read the given type...
switch (Ty->getPrimitiveID()) {
case Type::BoolTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
if (Val != 0 && Val != 1) return true;
V = ConstantBool::get(Val == 1);
break;
}
case Type::UByteTyID: // Unsigned integer types...
case Type::UShortTyID:
case Type::UIntTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
if (!ConstantUInt::isValueValidForType(Ty, Val)) return true;
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::ULongTyID: {
uint64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::SByteTyID: // Signed integer types...
case Type::ShortTyID:
case Type::IntTyID: {
case Type::LongTyID:
int64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return true;
if (!ConstantSInt::isValueValidForType(Ty, Val)) return true;
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::FloatTyID: {
float F;
if (input_data(Buf, EndBuf, &F, &F+1)) return true;
V = ConstantFP::get(Ty, F);
break;
}
case Type::DoubleTyID: {
double Val;
if (input_data(Buf, EndBuf, &Val, &Val+1)) return true;
V = ConstantFP::get(Ty, Val);
break;
}
case Type::TypeTyID:
assert(0 && "Type constants should be handled seperately!!!");
abort();
case Type::ArrayTyID: {
const ArrayType *AT = cast<const ArrayType>(Ty);
unsigned NumElements = AT->getNumElements();
std::vector<Constant*> Elements;
while (NumElements--) { // Read all of the elements of the constant.
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return true;
Constant *C = getConstantValue(AT->getElementType(), Slot);
if (!C) return true;
Elements.push_back(C);
}
V = ConstantArray::get(AT, Elements);
break;
}
case Type::StructTyID: {
const StructType *ST = cast<StructType>(Ty);
const StructType::ElementTypes &ET = ST->getElementTypes();
std::vector<Constant *> Elements;
for (unsigned i = 0; i < ET.size(); ++i) {
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return true;
Constant *C = getConstantValue(ET[i], Slot);
if (!C) return true;
Elements.push_back(C);
}
V = ConstantStruct::get(ST, Elements);
break;
}
case Type::PointerTyID: {
const PointerType *PT = cast<const PointerType>(Ty);
unsigned SubClass;
if (HasImplicitZeroInitializer)
SubClass = 1;
else
if (read_vbr(Buf, EndBuf, SubClass)) return true;
switch (SubClass) {
case 0: // ConstantPointerNull value...
V = ConstantPointerNull::get(PT);
break;
case 1: { // ConstantPointerRef value...
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return true;
BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
// Check to see if we have already read this global variable...
Value *Val = getValue(PT, Slot, false);
GlobalValue *GV;
if (Val) {
if (!(GV = dyn_cast<GlobalValue>(Val))) return true;
BCR_TRACE(5, "Value Found in ValueTable!\n");
} else if (RevisionNum > 0) {
// Revision #0 could have forward references to globals that were wierd.
// We got rid of this in subsequent revs.
return true;
} else { // Nope... find or create a forward ref. for it
GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
if (I != GlobalRefs.end()) {
BCR_TRACE(5, "Previous forward ref found!\n");
GV = cast<GlobalValue>(I->second);
} else {
BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
// Create a placeholder for the global variable reference...
GlobalVariable *GVar =
new GlobalVariable(PT->getElementType(), false,
GlobalValue::InternalLinkage);
// Keep track of the fact that we have a forward ref to recycle it
GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
// Must temporarily push this value into the module table...
TheModule->getGlobalList().push_back(GVar);
GV = GVar;
}
}
V = ConstantPointerRef::get(GV);
break;
}
default:
BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
return true;
}
break;
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize constant value of type '"
<< Ty->getName() << "'\n";
return true;
}
return false;
}
bool BytecodeParser::ParseGlobalTypes(const uchar *&Buf, const uchar *EndBuf) {
ValueTable T;
return ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
}
bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
ValueTable &Tab,
TypeValuesListTy &TypeTab) {
while (Buf < EndBuf) {
unsigned NumEntries, Typ;
if (read_vbr(Buf, EndBuf, NumEntries) ||
read_vbr(Buf, EndBuf, Typ)) return true;
const Type *Ty = getType(Typ);
if (Ty == 0) return true;
BCR_TRACE(3, "Type: '" << Ty << "' NumEntries: " << NumEntries << "\n");
if (Typ == Type::TypeTyID) {
if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
} else {
for (unsigned i = 0; i < NumEntries; ++i) {
Constant *C;
int Slot;
if (parseConstantValue(Buf, EndBuf, Ty, C)) return true;
assert(C && "parseConstantValue returned NULL!");
BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
if ((Slot = insertValue(C, Tab)) == -1) return true;
// If we are reading a function constant table, make sure that we adjust
// the slot number to be the real global constant number.
//
if (&Tab != &ModuleValues && Typ < ModuleValues.size())
Slot += ModuleValues[Typ]->size();
ResolveReferencesToValue(C, (unsigned)Slot);
}
}
}
if (Buf > EndBuf) return true;
return false;
}
<|endoftext|>
|
<commit_before>//===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level copy propagation pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "codegen-cp"
STATISTIC(NumDeletes, "Number of dead copies deleted");
namespace {
class MachineCopyPropagation : public MachineFunctionPass {
const TargetRegisterInfo *TRI;
const TargetInstrInfo *TII;
MachineRegisterInfo *MRI;
public:
static char ID; // Pass identification, replacement for typeid
MachineCopyPropagation() : MachineFunctionPass(ID) {
initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
typedef SmallVector<unsigned, 4> DestList;
typedef DenseMap<unsigned, DestList> SourceMap;
void SourceNoLongerAvailable(unsigned Reg,
SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap);
bool CopyPropagateBlock(MachineBasicBlock &MBB);
};
}
char MachineCopyPropagation::ID = 0;
char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
"Machine Copy Propagation Pass", false, false)
void
MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg,
SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap) {
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
SourceMap::iterator SI = SrcMap.find(*AI);
if (SI != SrcMap.end()) {
const DestList& Defs = SI->second;
for (DestList::const_iterator I = Defs.begin(), E = Defs.end();
I != E; ++I) {
unsigned MappedDef = *I;
// Source of copy is no longer available for propagation.
AvailCopyMap.erase(MappedDef);
for (MCSubRegIterator SR(MappedDef, TRI); SR.isValid(); ++SR)
AvailCopyMap.erase(*SR);
}
}
}
}
static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
const MachineInstr *MI) {
const MachineBasicBlock *MBB = CopyMI->getParent();
if (MI->getParent() != MBB)
return false;
MachineBasicBlock::const_iterator I = CopyMI;
MachineBasicBlock::const_iterator E = MBB->end();
MachineBasicBlock::const_iterator E2 = MI;
++I;
while (I != E && I != E2) {
if (I->hasUnmodeledSideEffects() || I->isCall() ||
I->isTerminator())
return false;
++I;
}
return true;
}
/// isNopCopy - Return true if the specified copy is really a nop. That is
/// if the source of the copy is the same of the definition of the copy that
/// supplied the source. If the source of the copy is a sub-register than it
/// must check the sub-indices match. e.g.
/// ecx = mov eax
/// al = mov cl
/// But not
/// ecx = mov eax
/// al = mov ch
static bool isNopCopy(MachineInstr *CopyMI, unsigned Def, unsigned Src,
const TargetRegisterInfo *TRI) {
unsigned SrcSrc = CopyMI->getOperand(1).getReg();
if (Def == SrcSrc)
return true;
if (TRI->isSubRegister(SrcSrc, Def)) {
unsigned SrcDef = CopyMI->getOperand(0).getReg();
unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
if (!SubIdx)
return false;
return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
}
return false;
}
bool MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
SmallSetVector<MachineInstr*, 8> MaybeDeadCopies; // Candidates for deletion
DenseMap<unsigned, MachineInstr*> AvailCopyMap; // Def -> available copies map
DenseMap<unsigned, MachineInstr*> CopyMap; // Def -> copies map
SourceMap SrcMap; // Src -> Def map
DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
bool Changed = false;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
MachineInstr *MI = &*I;
++I;
if (MI->isCopy()) {
unsigned Def = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
!TargetRegisterInfo::isVirtualRegister(Src) &&
"MachineCopyPropagation should be run after register allocation!");
DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
if (CI != AvailCopyMap.end()) {
MachineInstr *CopyMI = CI->second;
if (!MRI->isReserved(Def) &&
(!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
isNopCopy(CopyMI, Def, Src, TRI)) {
// The two copies cancel out and the source of the first copy
// hasn't been overridden, eliminate the second one. e.g.
// %ECX<def> = COPY %EAX<kill>
// ... nothing clobbered EAX.
// %EAX<def> = COPY %ECX
// =>
// %ECX<def> = COPY %EAX
//
// Also avoid eliminating a copy from reserved registers unless the
// definition is proven not clobbered. e.g.
// %RSP<def> = COPY %RAX
// CALL
// %RAX<def> = COPY %RSP
DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
// Clear any kills of Def between CopyMI and MI. This extends the
// live range.
for (MachineBasicBlock::iterator I = CopyMI, E = MI; I != E; ++I)
I->clearRegisterKills(Def, TRI);
MI->eraseFromParent();
Changed = true;
++NumDeletes;
continue;
}
}
// If Src is defined by a previous copy, the previous copy cannot be
// eliminated.
for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
// Copy is now a candidate for deletion.
MaybeDeadCopies.insert(MI);
// If 'Def' is previously source of another copy, then this earlier copy's
// source is no longer available. e.g.
// %xmm9<def> = copy %xmm2
// ...
// %xmm2<def> = copy %xmm0
// ...
// %xmm2<def> = copy %xmm9
SourceNoLongerAvailable(Def, SrcMap, AvailCopyMap);
// Remember Def is defined by the copy.
// ... Make sure to clear the def maps of aliases first.
for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
++SR) {
CopyMap[*SR] = MI;
AvailCopyMap[*SR] = MI;
}
// Remember source that's copied to Def. Once it's clobbered, then
// it's no longer available for copy propagation.
if (std::find(SrcMap[Src].begin(), SrcMap[Src].end(), Def) ==
SrcMap[Src].end()) {
SrcMap[Src].push_back(Def);
}
continue;
}
// Not a copy.
SmallVector<unsigned, 2> Defs;
int RegMaskOpNum = -1;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MachineOperand &MO = MI->getOperand(i);
if (MO.isRegMask())
RegMaskOpNum = i;
if (!MO.isReg())
continue;
unsigned Reg = MO.getReg();
if (!Reg)
continue;
assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
"MachineCopyPropagation should be run after register allocation!");
if (MO.isDef()) {
Defs.push_back(Reg);
continue;
}
// If 'Reg' is defined by a copy, the copy is no longer a candidate
// for elimination.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
DenseMap<unsigned, MachineInstr*>::iterator CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
// Treat undef use like defs for copy propagation but not for
// dead copy. We would need to do a liveness check to be sure the copy
// is dead for undef uses.
// The backends are allowed to do whatever they want with undef value
// and we cannot be sure this register will not be rewritten to break
// some false dependencies for the hardware for instance.
if (MO.isUndef())
Defs.push_back(Reg);
}
// The instruction has a register mask operand which means that it clobbers
// a large set of registers. It is possible to use the register mask to
// prune the available copies, but treat it like a basic block boundary for
// now.
if (RegMaskOpNum >= 0) {
// Erase any MaybeDeadCopies whose destination register is clobbered.
const MachineOperand &MaskMO = MI->getOperand(RegMaskOpNum);
for (SmallSetVector<MachineInstr*, 8>::iterator
DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
DI != DE; ++DI) {
unsigned Reg = (*DI)->getOperand(0).getReg();
if (MRI->isReserved(Reg) || !MaskMO.clobbersPhysReg(Reg))
continue;
DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
(*DI)->dump());
(*DI)->eraseFromParent();
Changed = true;
++NumDeletes;
}
// Clear all data structures as if we were beginning a new basic block.
MaybeDeadCopies.clear();
AvailCopyMap.clear();
CopyMap.clear();
SrcMap.clear();
continue;
}
for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
unsigned Reg = Defs[i];
// No longer defined by a copy.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
// If 'Reg' is previously source of a copy, it is no longer available for
// copy propagation.
SourceNoLongerAvailable(Reg, SrcMap, AvailCopyMap);
}
}
// If MBB doesn't have successors, delete the copies whose defs are not used.
// If MBB does have successors, then conservative assume the defs are live-out
// since we don't want to trust live-in lists.
if (MBB.succ_empty()) {
for (SmallSetVector<MachineInstr*, 8>::iterator
DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
DI != DE; ++DI) {
if (!MRI->isReserved((*DI)->getOperand(0).getReg())) {
(*DI)->eraseFromParent();
Changed = true;
++NumDeletes;
}
}
}
return Changed;
}
bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
if (skipOptnoneFunction(*MF.getFunction()))
return false;
bool Changed = false;
TRI = MF.getSubtarget().getRegisterInfo();
TII = MF.getSubtarget().getInstrInfo();
MRI = &MF.getRegInfo();
for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Changed |= CopyPropagateBlock(*I);
return Changed;
}
<commit_msg>MachineCopyPropagation: Use ranged for, cleanup; NFC<commit_after>//===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level copy propagation pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "codegen-cp"
STATISTIC(NumDeletes, "Number of dead copies deleted");
namespace {
class MachineCopyPropagation : public MachineFunctionPass {
const TargetRegisterInfo *TRI;
const TargetInstrInfo *TII;
const MachineRegisterInfo *MRI;
public:
static char ID; // Pass identification, replacement for typeid
MachineCopyPropagation() : MachineFunctionPass(ID) {
initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
typedef SmallVector<unsigned, 4> DestList;
typedef DenseMap<unsigned, DestList> SourceMap;
void SourceNoLongerAvailable(unsigned Reg, SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap);
bool CopyPropagateBlock(MachineBasicBlock &MBB);
};
}
char MachineCopyPropagation::ID = 0;
char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
"Machine Copy Propagation Pass", false, false)
void
MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg, SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap) {
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
SourceMap::iterator SI = SrcMap.find(*AI);
if (SI != SrcMap.end()) {
const DestList& Defs = SI->second;
for (unsigned MappedDef : Defs) {
// Source of copy is no longer available for propagation.
for (MCSubRegIterator SR(MappedDef, TRI, true); SR.isValid(); ++SR)
AvailCopyMap.erase(*SR);
}
}
}
}
static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
const MachineInstr *MI) {
const MachineBasicBlock *MBB = CopyMI->getParent();
if (MI->getParent() != MBB)
return false;
for (MachineBasicBlock::const_iterator I = std::next(CopyMI->getIterator()),
E = MBB->end(), E2 = MI->getIterator(); I != E && I != E2; ++I) {
if (I->hasUnmodeledSideEffects() || I->isCall() ||
I->isTerminator())
return false;
}
return true;
}
/// isNopCopy - Return true if the specified copy is really a nop. That is
/// if the source of the copy is the same of the definition of the copy that
/// supplied the source. If the source of the copy is a sub-register than it
/// must check the sub-indices match. e.g.
/// ecx = mov eax
/// al = mov cl
/// But not
/// ecx = mov eax
/// al = mov ch
static bool isNopCopy(const MachineInstr *CopyMI, unsigned Def, unsigned Src,
const TargetRegisterInfo *TRI) {
unsigned SrcSrc = CopyMI->getOperand(1).getReg();
if (Def == SrcSrc)
return true;
if (TRI->isSubRegister(SrcSrc, Def)) {
unsigned SrcDef = CopyMI->getOperand(0).getReg();
unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
if (!SubIdx)
return false;
return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
}
return false;
}
bool MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
SmallSetVector<MachineInstr*, 8> MaybeDeadCopies; // Candidates for deletion
DenseMap<unsigned, MachineInstr*> AvailCopyMap; // Def -> available copies map
DenseMap<unsigned, MachineInstr*> CopyMap; // Def -> copies map
SourceMap SrcMap; // Src -> Def map
DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
bool Changed = false;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
MachineInstr *MI = &*I;
++I;
if (MI->isCopy()) {
unsigned Def = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
!TargetRegisterInfo::isVirtualRegister(Src) &&
"MachineCopyPropagation should be run after register allocation!");
DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
if (CI != AvailCopyMap.end()) {
MachineInstr *CopyMI = CI->second;
if (!MRI->isReserved(Def) &&
(!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
isNopCopy(CopyMI, Def, Src, TRI)) {
// The two copies cancel out and the source of the first copy
// hasn't been overridden, eliminate the second one. e.g.
// %ECX<def> = COPY %EAX<kill>
// ... nothing clobbered EAX.
// %EAX<def> = COPY %ECX
// =>
// %ECX<def> = COPY %EAX
//
// Also avoid eliminating a copy from reserved registers unless the
// definition is proven not clobbered. e.g.
// %RSP<def> = COPY %RAX
// CALL
// %RAX<def> = COPY %RSP
DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
// Clear any kills of Def between CopyMI and MI. This extends the
// live range.
for (MachineInstr &MMI
: make_range(CopyMI->getIterator(), MI->getIterator()))
MMI.clearRegisterKills(Def, TRI);
MI->eraseFromParent();
Changed = true;
++NumDeletes;
continue;
}
}
// If Src is defined by a previous copy, the previous copy cannot be
// eliminated.
for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
// Copy is now a candidate for deletion.
if (!MRI->isReserved(Def))
MaybeDeadCopies.insert(MI);
// If 'Def' is previously source of another copy, then this earlier copy's
// source is no longer available. e.g.
// %xmm9<def> = copy %xmm2
// ...
// %xmm2<def> = copy %xmm0
// ...
// %xmm2<def> = copy %xmm9
SourceNoLongerAvailable(Def, SrcMap, AvailCopyMap);
// Remember Def is defined by the copy.
// ... Make sure to clear the def maps of aliases first.
for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
++SR) {
CopyMap[*SR] = MI;
AvailCopyMap[*SR] = MI;
}
// Remember source that's copied to Def. Once it's clobbered, then
// it's no longer available for copy propagation.
SmallVectorImpl<unsigned> &DestList = SrcMap[Src];
if (std::find(DestList.begin(), DestList.end(), Def) == DestList.end())
DestList.push_back(Def);
continue;
}
// Not a copy.
SmallVector<unsigned, 2> Defs;
const MachineOperand *RegMask = nullptr;
for (const MachineOperand &MO : MI->operands()) {
if (MO.isRegMask())
RegMask = &MO;
if (!MO.isReg())
continue;
unsigned Reg = MO.getReg();
if (!Reg)
continue;
assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
"MachineCopyPropagation should be run after register allocation!");
if (MO.isDef()) {
Defs.push_back(Reg);
continue;
}
// If 'Reg' is defined by a copy, the copy is no longer a candidate
// for elimination.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
DenseMap<unsigned, MachineInstr*>::iterator CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
// Treat undef use like defs for copy propagation but not for
// dead copy. We would need to do a liveness check to be sure the copy
// is dead for undef uses.
// The backends are allowed to do whatever they want with undef value
// and we cannot be sure this register will not be rewritten to break
// some false dependencies for the hardware for instance.
if (MO.isUndef())
Defs.push_back(Reg);
}
// The instruction has a register mask operand which means that it clobbers
// a large set of registers. It is possible to use the register mask to
// prune the available copies, but treat it like a basic block boundary for
// now.
if (RegMask) {
// Erase any MaybeDeadCopies whose destination register is clobbered.
for (MachineInstr *MaybeDead : MaybeDeadCopies) {
unsigned Reg = MaybeDead->getOperand(0).getReg();
assert(!MRI->isReserved(Reg));
if (!RegMask->clobbersPhysReg(Reg))
continue;
DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
MaybeDead->dump());
MaybeDead->eraseFromParent();
Changed = true;
++NumDeletes;
}
// Clear all data structures as if we were beginning a new basic block.
MaybeDeadCopies.clear();
AvailCopyMap.clear();
CopyMap.clear();
SrcMap.clear();
continue;
}
for (unsigned Reg : Defs) {
// No longer defined by a copy.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
// If 'Reg' is previously source of a copy, it is no longer available for
// copy propagation.
SourceNoLongerAvailable(Reg, SrcMap, AvailCopyMap);
}
}
// If MBB doesn't have successors, delete the copies whose defs are not used.
// If MBB does have successors, then conservative assume the defs are live-out
// since we don't want to trust live-in lists.
if (MBB.succ_empty()) {
for (MachineInstr *MaybeDead : MaybeDeadCopies) {
assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
MaybeDead->eraseFromParent();
Changed = true;
++NumDeletes;
}
}
return Changed;
}
bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
if (skipOptnoneFunction(*MF.getFunction()))
return false;
bool Changed = false;
TRI = MF.getSubtarget().getRegisterInfo();
TII = MF.getSubtarget().getInstrInfo();
MRI = &MF.getRegInfo();
for (MachineBasicBlock &MBB : MF)
Changed |= CopyPropagateBlock(MBB);
return Changed;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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.
*
*/
#ifndef WEBSOCKETPP_MD5_WRAPPER_HPP
#define WEBSOCKETPP_MD5_WRAPPER_HPP
#include "md5.h"
namespace websocketpp {
// could be compiled separately
inline void md5_hash_string(const std::string& s);
char digest[17];
md5_state_t state;
md5_init(&state);
md5_append(&state, (const md5_byte_t *)s.c_str(), 16);
md5_finish(&state, (md5_byte_t *)digest);
digest[16] = '\0';
return std::string(digest);
}
#endif // WEBSOCKETPP_MD5_WRAPPER_HPP<commit_msg>fixes md5 bug<commit_after>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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.
*
*/
#ifndef WEBSOCKETPP_MD5_WRAPPER_HPP
#define WEBSOCKETPP_MD5_WRAPPER_HPP
#include "md5.h"
namespace websocketpp {
// could be compiled separately
inline std::string md5_hash_string(const std::string& s) {
char digest[17];
md5_state_t state;
md5_init(&state);
md5_append(&state, (const md5_byte_t *)s.c_str(), 16);
md5_finish(&state, (md5_byte_t *)digest);
digest[16] = '\0';
return std::string(digest);
}
} // websocketpp
#endif // WEBSOCKETPP_MD5_WRAPPER_HPP<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_SPARC_SYSCALLRETURN_HH__
#define __ARCH_SPARC_SYSCALLRETURN_HH__
#include <inttypes.h>
#include "arch/sparc/regfile.hh"
class SyscallReturn
{
public:
template <class T>
SyscallReturn(T v, bool s)
{
retval = (uint64_t)v;
success = s;
}
template <class T>
SyscallReturn(T v)
{
success = (v >= 0);
retval = (uint64_t)v;
}
~SyscallReturn() {}
SyscallReturn& operator=(const SyscallReturn& s)
{
retval = s.retval;
success = s.success;
return *this;
}
bool successful() { return success; }
uint64_t value() { return retval; }
private:
uint64_t retval;
bool success;
};
namespace SparcISA
{
static inline void setSyscallReturn(SyscallReturn return_value,
RegFile *regs)
{
// check for error condition. SPARC syscall convention is to
// indicate success/failure in reg the carry bit of the ccr
// and put the return value itself in the standard return value reg ().
if (return_value.successful()) {
// no error, clear XCC.C
regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) & 0xEF);
regs->setIntReg(ReturnValueReg, return_value.value());
} else {
// got an error, set XCC.C
regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) | 0x10);
regs->setIntReg(ReturnValueReg, return_value.value());
}
}
};
#endif
<commit_msg>Set both xcc.c and icc.c on return from a syscall.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_SPARC_SYSCALLRETURN_HH__
#define __ARCH_SPARC_SYSCALLRETURN_HH__
#include <inttypes.h>
#include "arch/sparc/regfile.hh"
class SyscallReturn
{
public:
template <class T>
SyscallReturn(T v, bool s)
{
retval = (uint64_t)v;
success = s;
}
template <class T>
SyscallReturn(T v)
{
success = (v >= 0);
retval = (uint64_t)v;
}
~SyscallReturn() {}
SyscallReturn& operator=(const SyscallReturn& s)
{
retval = s.retval;
success = s.success;
return *this;
}
bool successful() { return success; }
uint64_t value() { return retval; }
private:
uint64_t retval;
bool success;
};
namespace SparcISA
{
static inline void setSyscallReturn(SyscallReturn return_value,
RegFile *regs)
{
// check for error condition. SPARC syscall convention is to
// indicate success/failure in reg the carry bit of the ccr
// and put the return value itself in the standard return value reg ().
if (return_value.successful()) {
// no error, clear XCC.C
regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) & 0xEE);
regs->setIntReg(ReturnValueReg, return_value.value());
} else {
// got an error, set XCC.C
regs->setMiscReg(MISCREG_CCR, regs->readMiscReg(MISCREG_CCR) | 0x11);
regs->setIntReg(ReturnValueReg, return_value.value());
}
}
};
#endif
<|endoftext|>
|
<commit_before>#include "lib/universal_include.h"
#include "missile.h"
#include "lib/gfx/debug_render.h"
#include "lib/gfx/simple_primitives.h"
#include "lib/gfx/shape.h"
#include "lib/sound/sound_system.h"
#include "lib/hi_res_time.h"
#include "lib/resource.h"
#include "arena.h"
#include "big_explosions.h"
#include "camera.h"
#include "ship.h"
#include "level.h"
#define MISSILE_HOVER_HEIGHT 8.0f
#define MISSILE_SPEED 160.0f
#define MISSILE_TURN_SPEED 0.0043f
Missile::Missile(GameObj *owner, GameObj *target, Vector3 const &pos, Vector3 const &front)
: GameObj(ObjTypeMissile, pos)
{
m_owner = owner;
m_target = target;
m_shields = 1.9f;
m_front = front;
m_shape = g_resourceManager.GetShape("missile.shp");
}
void Missile::Advance()
{
// Missiles move so fast that they can jump from one side of an object to
// the other in a single frame advance. When that happens, no collision
// with the object will be detected. To prevent this we divide the frame
// advance time and advance the missile in many small steps.
int numSlices = 10;
float advanceTime = g_advanceTime / (float)numSlices;
for (int slice = 0; slice < numSlices; slice++)
{
// Steer towards target in the horizontal plane
Vector3 toTarg = m_target->m_pos - m_pos;
toTarg.y = 0.0f;
m_front.y = 0.0f;
Vector3 crossProd = m_front.CrossProduct(toTarg);
if (crossProd.Len() > MISSILE_TURN_SPEED)
crossProd.SetLen(MISSILE_TURN_SPEED);
m_front.RotateAround(crossProd);
// Steer towards the target in the vertical plane
float offsetFromIdealHeight = MISSILE_HOVER_HEIGHT - m_pos.y;
m_front.y = signf(offsetFromIdealHeight) * sqrtf(fabs(offsetFromIdealHeight)) * 0.08f;
m_front.Normalize();
// Move
m_pos += m_front * MISSILE_SPEED * advanceTime;
// Hit check this missile against other game objects in the location
int numObjs = g_level->m_objects.Size();
for (int i = 0; i < numObjs; i++)
{
GameObj *o = g_level->m_objects[i];
if (o == this || o == m_owner)
continue;
if (!o->m_shape)
continue;
if (o->m_type == ObjTypeJumpPad)
continue;
SpherePackage sp(m_pos, 2.2f);
Matrix34 osMat(o->m_front, g_upVector, o->m_pos);
if (o->m_shape->SphereHit(&sp, osMat, true))
{
// Missile has hit something, destroy the missile
if (o->m_type == ObjTypePlayerShip)
g_level->DeleteObj(this);
else
TakeHit(m_shields + 1.0f);
// Give damage to whatever we hit
o->TakeHit(4.0f);
return; // This missile is dead now. No need to do the rest of the time slices.
}
}
}
}
void Missile::Render()
{
Matrix34 mat(m_front, Vector3(0,1,0), m_pos);
m_shape->Render(0.0f, mat);
}
void Missile::TakeHit(float force)
{
m_shields -= force;
if (m_shields <= 0)
{
g_soundSystem->PlayWave("missile_destroyed.wav", &m_pos);
g_level->AddObj(new MissileDeath(m_pos));
g_level->DeleteObj(this);
}
}
<commit_msg>Oops. Missile physics was highly frame rate dependant, that's why I kept on having to tweak it.<commit_after>#include "lib/universal_include.h"
#include "missile.h"
#include "lib/gfx/debug_render.h"
#include "lib/gfx/simple_primitives.h"
#include "lib/gfx/shape.h"
#include "lib/sound/sound_system.h"
#include "lib/hi_res_time.h"
#include "lib/resource.h"
#include "arena.h"
#include "big_explosions.h"
#include "camera.h"
#include "ship.h"
#include "level.h"
#define MISSILE_HOVER_HEIGHT 8.0f
#define MISSILE_SPEED 160.0f
#define MISSILE_TURN_SPEED 2.15f
Missile::Missile(GameObj *owner, GameObj *target, Vector3 const &pos, Vector3 const &front)
: GameObj(ObjTypeMissile, pos)
{
m_owner = owner;
m_target = target;
m_shields = 1.9f;
m_front = front;
m_shape = g_resourceManager.GetShape("missile.shp");
}
void Missile::Advance()
{
// Missiles move so fast that they can jump from one side of an object to
// the other in a single frame advance. When that happens, no collision
// with the object will be detected. To prevent this we divide the frame
// advance time and advance the missile in many small steps.
int numSlices = 10;
float advanceTime = g_advanceTime / (float)numSlices;
for (int slice = 0; slice < numSlices; slice++)
{
// Steer towards target in the horizontal plane
Vector3 toTarg = m_target->m_pos - m_pos;
toTarg.y = 0.0f;
m_front.y = 0.0f;
Vector3 crossProd = m_front.CrossProduct(toTarg);
if (crossProd.Len() > MISSILE_TURN_SPEED)
crossProd.SetLen(MISSILE_TURN_SPEED * advanceTime);
m_front.RotateAround(crossProd);
// Steer towards the target in the vertical plane
float offsetFromIdealHeight = MISSILE_HOVER_HEIGHT - m_pos.y;
m_front.y = signf(offsetFromIdealHeight) * sqrtf(fabs(offsetFromIdealHeight)) * 0.08f;
m_front.Normalize();
// Move
m_pos += m_front * MISSILE_SPEED * advanceTime;
// Hit check this missile against other game objects in the location
int numObjs = g_level->m_objects.Size();
for (int i = 0; i < numObjs; i++)
{
GameObj *o = g_level->m_objects[i];
if (o == this || o == m_owner)
continue;
if (!o->m_shape)
continue;
if (o->m_type == ObjTypeJumpPad)
continue;
SpherePackage sp(m_pos, 2.2f);
Matrix34 osMat(o->m_front, g_upVector, o->m_pos);
if (o->m_shape->SphereHit(&sp, osMat, true))
{
// Missile has hit something, destroy the missile
if (o->m_type == ObjTypePlayerShip)
g_level->DeleteObj(this);
else
TakeHit(m_shields + 1.0f);
// Give damage to whatever we hit
o->TakeHit(4.0f);
return; // This missile is dead now. No need to do the rest of the time slices.
}
}
}
}
void Missile::Render()
{
Matrix34 mat(m_front, Vector3(0,1,0), m_pos);
m_shape->Render(0.0f, mat);
}
void Missile::TakeHit(float force)
{
m_shields -= force;
if (m_shields <= 0)
{
g_soundSystem->PlayWave("missile_destroyed.wav", &m_pos);
g_level->AddObj(new MissileDeath(m_pos));
g_level->DeleteObj(this);
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 Peter Kmmel
// Copyright (c) 2005 Richard Sposato
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
// The authors make no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
// $Header$
//#define LOKI_CLASS_LEVEL_THREADING
#define LOKI_OBJECT_LEVEL_THREADING
// Uncomment this to test new [] and delete [].
#define LOKI_SMALL_OBJECT_USE_NEW_ARRAY
#include "SmallObj.h"
#include "timer.h"
#include <iostream>
#include <string>
#define COMPARE_BOOST_POOL
#ifdef COMPARE_BOOST_POOL
#include <boost\pool\object_pool.hpp>
#endif
using namespace std;
template<unsigned int N>
class ThisIsASmallObject
{
char data[N];
};
template<unsigned int N, class T>
struct Base : public ThisIsASmallObject<N>, public T {};
template<unsigned int N>
struct Base<N, void> : public ThisIsASmallObject<N> {};
#ifdef COMPARE_BOOST_POOL
template<unsigned int N>
class BoostPoolNew : public Base<N,void>
{
private:
static boost::object_pool< BoostPoolNew<N> > BoostPool;
public:
/// Throwing single-object new throws bad_alloc when allocation fails.
#ifdef _MSC_VER
/// @note MSVC complains about non-empty exception specification lists.
static void * operator new ( std::size_t )
#else
static void * operator new ( std::size_t ) throw ( std::bad_alloc )
#endif
{
return BoostPool.malloc();
}
/// Non-throwing single-object new returns NULL if allocation fails.
static void * operator new ( std::size_t, const std::nothrow_t & ) throw ()
{
return BoostPool.malloc();
}
/// Placement single-object new merely calls global placement new.
inline static void * operator new ( std::size_t size, void * place )
{
return ::operator new( size, place );
}
/// Single-object delete.
static void operator delete ( void * p ) throw ()
{
BoostPool.free( reinterpret_cast< BoostPoolNew * >( p ) );
}
/** Non-throwing single-object delete is only called when nothrow
new operator is used, and the constructor throws an exception.
*/
static void operator delete ( void * p, const std::nothrow_t & ) throw()
{
BoostPool.free( reinterpret_cast< BoostPoolNew * >( p ) );
}
/// Placement single-object delete merely calls global placement delete.
inline static void operator delete ( void * p, void * place )
{
::operator delete ( p, place );
}
};
template<unsigned int N>
boost::object_pool< BoostPoolNew<N> > BoostPoolNew<N>::BoostPool;
#endif
template<class T>
int run_oneline_new_delete(int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
{
delete new T;
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_delete(int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
{
T* p = new T;
delete p;
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_delete(T** array, int N, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
for (int n=0; n<N; n++)
{
array[n] = new T;
delete array[n];
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new(T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
array[i] = new T;
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_delete(T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
delete array[i];
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_delete_array(int N, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
{
T* p = new T[N];
delete [] p;
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_array( int N, T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
array[i] = new T[N];
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_delete_array( T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
delete [] array[i];
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<unsigned int N, int loop>
void testSize()
{
typedef Base<N, void>
A;
typedef Base<N, Loki::SmallObject< Loki::SingleThreaded > >
B;
typedef Base<N, Loki::SmallValueObject< Loki::SingleThreaded > >
C;
#ifdef COMPARE_BOOST_POOL
typedef BoostPoolNew<N>
D;
#endif
cout << "Small-Object Benchmark Tests \n" << endl;
cout << "A = global new and delete \tsizeof(A) =" << sizeof(A) << endl;
cout << "B = Loki::SmallObject \tsizeof(B) =" << sizeof(B) << endl;
cout << "C = Loki::SmallValueObject\tsizeof(C) =" << sizeof(C) << endl;
#ifdef COMPARE_BOOST_POOL
cout << "D = boost::object_pool \tsizeof(D) =" << sizeof(D) << endl;
#endif
cout << endl << endl;
Timer t;
t.t100 = 0;
t.t100 = run_oneline_new_delete<A>(loop,t,"'delete new A' : ");
run_new_delete<B>(loop,t,"'delete new B' : ");
run_new_delete<C>(loop,t,"'delete new C' : ");
#ifdef COMPARE_BOOST_POOL
run_new_delete<D>(loop,t,"'delete new D' : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_new_delete<A>(loop,t,"new & delete A : ");
run_new_delete<B>(loop,t,"new & delete B : ");
run_new_delete<C>(loop,t,"new & delete C : ");
#ifdef COMPARE_BOOST_POOL
run_new_delete<D>(loop,t,"new & delete D : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
int N = 10000;
int loop2 = loop/N*10;
A** a = new A*[N];
B** b = new B*[N];
C** c = new C*[N];
#ifdef COMPARE_BOOST_POOL
D** d = new D*[N];
#endif
for(int i=0; i<N; i++)
{
a[i]=0;
b[i]=0;
c[i]=0;
#ifdef COMPARE_BOOST_POOL
d[i]=0;
#endif
}
t.t100 = 0;
t.t100 = run_new_delete(a,N,loop2,t,"new & del. A on array: ");
run_new_delete(b,N,loop2,t,"new & del. B on array: ");
run_new_delete(c,N,loop2,t,"new & del. C on array: ");
#ifdef COMPARE_BOOST_POOL
run_new_delete(d,N,loop2,t,"new & del. D on array: ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_new(a,N,t,"new A on array : ");
run_new(b,N,t,"new B on array : ");
run_new(c,N,t,"new C on array : ");
#ifdef COMPARE_BOOST_POOL
run_new(d,N,t,"new D on array : ");
#endif
cout << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_delete(a,N,t,"delete A on array : ");
run_delete(b,N,t,"delete B on array : ");
run_delete(c,N,t,"delete C on array : ");
#ifdef COMPARE_BOOST_POOL
run_delete(d,N,t,"delete D on array : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
N = 5;
t.t100 = 0;
t.t100 = run_new_delete_array<A>(N,loop,t,"new & delete [] A : ");
run_new_delete_array<B>(N,loop,t,"new & delete [] B : ");
run_new_delete_array<C>(N,loop,t,"new & delete [] C : ");
#ifdef COMPARE_BOOST_POOL
run_new_delete_array<D>(N,loop,t,"new & delete [] D : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
int count = 100;
t.t100 = 0;
t.t100 = run_new_array(N,a,count,t,"new [] A on array : ");
run_new_array(N,b,count,t,"new [] B on array : ");
run_new_array(N,c,count,t,"new [] C on array : ");
#ifdef COMPARE_BOOST_POOL
run_new_array(N,d,count,t,"new [] D on array : ");
#endif
cout << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_delete_array(a,count,t,"delete [] A on array : ");
run_delete_array(b,count,t,"delete [] B on array : ");
run_delete_array(c,count,t,"delete [] C on array : ");
#ifdef COMPARE_BOOST_POOL
run_delete_array(d,count,t,"delete [] D on array : ");
#endif
delete [] a;
delete [] b;
delete [] c;
#ifdef COMPARE_BOOST_POOL
delete [] d;
#endif
cout << endl << endl;
Loki::AllocatorSingleton<>::ClearExtraMemory();
////////////////////////////////////////////////////////////////////////////////
}
int main()
{
cout << endl;
const int loop = 700000;
testSize<8,loop>();
testSize<64,loop>();
//testSize<256,loop>();
//testSize<1024,loop>();
system("PAUSE");
return 0;
}
// ----------------------------------------------------------------------------
// $Log$
// Revision 1.9 2005/10/26 23:30:06 syntheticpp
// make object size more flexible
//
// Revision 1.8 2005/10/26 00:41:00 rich_sposato
// Added comparison to boost::pool memory allocator.
//
// Revision 1.7 2005/10/14 18:35:06 rich_sposato
// Added cvs keywords.
//
<commit_msg>gcc fix<commit_after>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 Peter Kmmel
// Copyright (c) 2005 Richard Sposato
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
// The authors make no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
// $Header$
//#define LOKI_CLASS_LEVEL_THREADING
//#define LOKI_OBJECT_LEVEL_THREADING
// Uncomment this to test new [] and delete [].
#define LOKI_SMALL_OBJECT_USE_NEW_ARRAY
#include "SmallObj.h"
#include "timer.h"
#include <iostream>
#include <string>
//#define COMPARE_BOOST_POOL
#ifdef COMPARE_BOOST_POOL
#include <boost\pool\object_pool.hpp>
#endif
using namespace std;
template<unsigned int N>
class ThisIsASmallObject
{
char data[N];
};
template<unsigned int N, class T>
struct Base : public ThisIsASmallObject<N>, public T {};
template<unsigned int N>
struct Base<N, void> : public ThisIsASmallObject<N> {};
#ifdef COMPARE_BOOST_POOL
template<unsigned int N>
class BoostPoolNew : public Base<N,void>
{
private:
static boost::object_pool< BoostPoolNew<N> > BoostPool;
public:
/// Throwing single-object new throws bad_alloc when allocation fails.
#ifdef _MSC_VER
/// @note MSVC complains about non-empty exception specification lists.
static void * operator new ( std::size_t )
#else
static void * operator new ( std::size_t ) throw ( std::bad_alloc )
#endif
{
return BoostPool.malloc();
}
/// Non-throwing single-object new returns NULL if allocation fails.
static void * operator new ( std::size_t, const std::nothrow_t & ) throw ()
{
return BoostPool.malloc();
}
/// Placement single-object new merely calls global placement new.
inline static void * operator new ( std::size_t size, void * place )
{
return ::operator new( size, place );
}
/// Single-object delete.
static void operator delete ( void * p ) throw ()
{
BoostPool.free( reinterpret_cast< BoostPoolNew * >( p ) );
}
/** Non-throwing single-object delete is only called when nothrow
new operator is used, and the constructor throws an exception.
*/
static void operator delete ( void * p, const std::nothrow_t & ) throw()
{
BoostPool.free( reinterpret_cast< BoostPoolNew * >( p ) );
}
/// Placement single-object delete merely calls global placement delete.
inline static void operator delete ( void * p, void * place )
{
::operator delete ( p, place );
}
};
template<unsigned int N>
boost::object_pool< BoostPoolNew<N> > BoostPoolNew<N>::BoostPool;
#endif
template<class T>
int run_oneline_new_delete(int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
{
delete new T;
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_delete(int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
{
T* p = new T;
delete p;
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_delete(T** array, int N, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
for (int n=0; n<N; n++)
{
array[n] = new T;
delete array[n];
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new(T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
array[i] = new T;
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_delete(T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
delete array[i];
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_delete_array(int N, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
{
T* p = new T[N];
delete [] p;
}
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_new_array( int N, T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
array[i] = new T[N];
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<class T>
int run_delete_array( T** array, int loop, Timer& t, const char* s)
{
t.start();
/****************************************************************/
for (int i=0; i<loop; ++i)
delete [] array[i];
/****************************************************************/
t.stop();
t.print(t.t(),s);
return t.t();
}
template<unsigned int Size, int loop>
void testSize()
{
typedef Base<Size, void>
A;
typedef Base<Size, Loki::SmallObject< Loki::SingleThreaded > >
B;
typedef Base<Size, Loki::SmallValueObject< Loki::SingleThreaded > >
C;
#ifdef COMPARE_BOOST_POOL
typedef BoostPoolNew<Size>
D;
#endif
cout << "Small-Object Benchmark Tests \n" << endl;
cout << "A = global new and delete \tsizeof(A) =" << sizeof(A) << endl;
cout << "B = Loki::SmallObject \tsizeof(B) =" << sizeof(B) << endl;
cout << "C = Loki::SmallValueObject\tsizeof(C) =" << sizeof(C) << endl;
#ifdef COMPARE_BOOST_POOL
cout << "D = boost::object_pool \tsizeof(D) =" << sizeof(D) << endl;
#endif
cout << endl << endl;
Timer t;
t.t100 = 0;
t.t100 = run_oneline_new_delete<A>(loop,t,"'delete new A' : ");
run_new_delete<B>(loop,t,"'delete new B' : ");
run_new_delete<C>(loop,t,"'delete new C' : ");
#ifdef COMPARE_BOOST_POOL
run_new_delete<D>(loop,t,"'delete new D' : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_new_delete<A>(loop,t,"new & delete A : ");
run_new_delete<B>(loop,t,"new & delete B : ");
run_new_delete<C>(loop,t,"new & delete C : ");
#ifdef COMPARE_BOOST_POOL
run_new_delete<D>(loop,t,"new & delete D : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
int N = 10000;
int loop2 = loop/N*10;
A** a = new A*[N];
B** b = new B*[N];
C** c = new C*[N];
#ifdef COMPARE_BOOST_POOL
D** d = new D*[N];
#endif
for(int i=0; i<N; i++)
{
a[i]=0;
b[i]=0;
c[i]=0;
#ifdef COMPARE_BOOST_POOL
d[i]=0;
#endif
}
t.t100 = 0;
t.t100 = run_new_delete(a,N,loop2,t,"new & del. A on array: ");
run_new_delete(b,N,loop2,t,"new & del. B on array: ");
run_new_delete(c,N,loop2,t,"new & del. C on array: ");
#ifdef COMPARE_BOOST_POOL
run_new_delete(d,N,loop2,t,"new & del. D on array: ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_new(a,N,t,"new A on array : ");
run_new(b,N,t,"new B on array : ");
run_new(c,N,t,"new C on array : ");
#ifdef COMPARE_BOOST_POOL
run_new(d,N,t,"new D on array : ");
#endif
cout << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_delete(a,N,t,"delete A on array : ");
run_delete(b,N,t,"delete B on array : ");
run_delete(c,N,t,"delete C on array : ");
#ifdef COMPARE_BOOST_POOL
run_delete(d,N,t,"delete D on array : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
N = 5;
t.t100 = 0;
t.t100 = run_new_delete_array<A>(N,loop,t,"new & delete [] A : ");
run_new_delete_array<B>(N,loop,t,"new & delete [] B : ");
run_new_delete_array<C>(N,loop,t,"new & delete [] C : ");
#ifdef COMPARE_BOOST_POOL
run_new_delete_array<D>(N,loop,t,"new & delete [] D : ");
#endif
cout << endl << endl;
////////////////////////////////////////////////////////////////////////////////
int count = 100;
t.t100 = 0;
t.t100 = run_new_array(N,a,count,t,"new [] A on array : ");
run_new_array(N,b,count,t,"new [] B on array : ");
run_new_array(N,c,count,t,"new [] C on array : ");
#ifdef COMPARE_BOOST_POOL
run_new_array(N,d,count,t,"new [] D on array : ");
#endif
cout << endl;
////////////////////////////////////////////////////////////////////////////////
t.t100 = 0;
t.t100 = run_delete_array(a,count,t,"delete [] A on array : ");
run_delete_array(b,count,t,"delete [] B on array : ");
run_delete_array(c,count,t,"delete [] C on array : ");
#ifdef COMPARE_BOOST_POOL
run_delete_array(d,count,t,"delete [] D on array : ");
#endif
delete [] a;
delete [] b;
delete [] c;
#ifdef COMPARE_BOOST_POOL
delete [] d;
#endif
cout << endl << endl;
Loki::AllocatorSingleton<>::ClearExtraMemory();
////////////////////////////////////////////////////////////////////////////////
}
int main()
{
cout << endl;
const int loop = 700000;
testSize<8,loop>();
testSize<64,loop>();
//testSize<256,loop>();
//testSize<1024,loop>();
system("PAUSE");
return 0;
}
// ----------------------------------------------------------------------------
// $Log$
// Revision 1.10 2005/10/27 19:10:32 syntheticpp
// gcc fix
//
// Revision 1.9 2005/10/26 23:30:06 syntheticpp
// make object size more flexible
//
// Revision 1.8 2005/10/26 00:41:00 rich_sposato
// Added comparison to boost::pool memory allocator.
//
// Revision 1.7 2005/10/14 18:35:06 rich_sposato
// Added cvs keywords.
//
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014, The Cinder Project, All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/cocoa/AppMac.h"
#include "cinder/app/cocoa/AppImplMac.h"
#include "cinder/Log.h"
using namespace std;
namespace cinder { namespace app {
AppMac::AppMac()
: AppBase()
{
const Settings *settings = dynamic_cast<Settings *>( sSettingsFromMain );
CI_ASSERT( settings );
Platform::get()->setExecutablePath( getAppPath() );
mImpl = [[AppImplMac alloc] init:this settings:*settings];
enablePowerManagement( settings->isPowerManagementEnabled() ); // TODO: consider moving to common method
}
AppMac::~AppMac()
{
[mImpl release];
}
void AppMac::launch()
{
[[NSApplication sharedApplication] run];
}
WindowRef AppMac::createWindow( const Window::Format &format )
{
return [mImpl createWindow:format];
}
void AppMac::quit()
{
[mImpl quit];
}
float AppMac::getFrameRate() const
{
return [mImpl getFrameRate];
}
void AppMac::setFrameRate( float frameRate )
{
[mImpl setFrameRate:frameRate];
}
void AppMac::disableFrameRate()
{
[mImpl disableFrameRate];
}
bool AppMac::isFrameRateEnabled() const
{
return [mImpl isFrameRateEnabled];
}
fs::path AppMac::getAppPath() const
{
return fs::path( [[[NSBundle mainBundle] bundlePath] UTF8String] );
}
WindowRef AppMac::getWindow() const
{
return [mImpl getWindow];
}
WindowRef AppMac::getWindowIndex( size_t index ) const
{
return [mImpl getWindowIndex:index];
}
size_t AppMac::getNumWindows() const
{
return [mImpl getNumWindows];
}
WindowRef AppMac::getForegroundWindow() const
{
return [mImpl getForegroundWindow];
}
void AppMac::hideCursor()
{
[NSCursor hide];
}
void AppMac::showCursor()
{
[NSCursor unhide];
}
ivec2 AppMac::getMousePos() const
{
NSPoint loc = [NSEvent mouseLocation];
return ivec2( loc.x, cinder::Display::getMainDisplay()->getHeight() - loc.y );
}
} } // namespace cinder::app
<commit_msg>Addressing #788, making getAppPath() on Mac match MSW<commit_after>/*
Copyright (c) 2014, The Cinder Project, All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/cocoa/AppMac.h"
#include "cinder/app/cocoa/AppImplMac.h"
#include "cinder/Log.h"
using namespace std;
namespace cinder { namespace app {
AppMac::AppMac()
: AppBase()
{
const Settings *settings = dynamic_cast<Settings *>( sSettingsFromMain );
CI_ASSERT( settings );
Platform::get()->setExecutablePath( getAppPath() );
mImpl = [[AppImplMac alloc] init:this settings:*settings];
enablePowerManagement( settings->isPowerManagementEnabled() ); // TODO: consider moving to common method
}
AppMac::~AppMac()
{
[mImpl release];
}
void AppMac::launch()
{
[[NSApplication sharedApplication] run];
}
WindowRef AppMac::createWindow( const Window::Format &format )
{
return [mImpl createWindow:format];
}
void AppMac::quit()
{
[mImpl quit];
}
float AppMac::getFrameRate() const
{
return [mImpl getFrameRate];
}
void AppMac::setFrameRate( float frameRate )
{
[mImpl setFrameRate:frameRate];
}
void AppMac::disableFrameRate()
{
[mImpl disableFrameRate];
}
bool AppMac::isFrameRateEnabled() const
{
return [mImpl isFrameRateEnabled];
}
fs::path AppMac::getAppPath() const
{
return fs::path( [[[NSBundle mainBundle] bundlePath] UTF8String] ).parent_path();
}
WindowRef AppMac::getWindow() const
{
return [mImpl getWindow];
}
WindowRef AppMac::getWindowIndex( size_t index ) const
{
return [mImpl getWindowIndex:index];
}
size_t AppMac::getNumWindows() const
{
return [mImpl getNumWindows];
}
WindowRef AppMac::getForegroundWindow() const
{
return [mImpl getForegroundWindow];
}
void AppMac::hideCursor()
{
[NSCursor hide];
}
void AppMac::showCursor()
{
[NSCursor unhide];
}
ivec2 AppMac::getMousePos() const
{
NSPoint loc = [NSEvent mouseLocation];
return ivec2( loc.x, cinder::Display::getMainDisplay()->getHeight() - loc.y );
}
} } // namespace cinder::app
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.