format dir demo

This commit is contained in:
Mathis Logemann 2022-01-26 23:34:08 +01:00
parent 65035706fb
commit 4fbaa032f0
20 changed files with 888 additions and 996 deletions

View file

@ -45,19 +45,21 @@
#include <iostream> #include <iostream>
int main(int, char**)
int main ( int, char** )
{ {
using namespace mapnik; using namespace mapnik;
const std::string srs_lcc="+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs"; const std::string srs_lcc =
const std::string srs_merc="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over"; "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs";
const std::string srs_merc = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 "
"+units=m +nadgrids=@null +wktext +no_defs +over";
try { try
{
std::cout << " running demo ... \n"; std::cout << " running demo ... \n";
datasource_cache::instance().register_datasources("plugins/input/"); datasource_cache::instance().register_datasources("plugins/input/");
freetype_engine::register_font("fonts/dejavu-fonts-ttf-2.37/ttf/DejaVuSans.ttf"); freetype_engine::register_font("fonts/dejavu-fonts-ttf-2.37/ttf/DejaVuSans.ttf");
Map m(800,600); Map m(800, 600);
m.set_background(parse_color("white")); m.set_background(parse_color("white"));
m.set_srs(srs_merc); m.set_srs(srs_merc);
// create styles // create styles
@ -93,13 +95,13 @@ int main ( int, char** )
rule r; rule r;
{ {
line_symbolizer line_sym; line_symbolizer line_sym;
put(line_sym,keys::stroke,color(0,0,0)); put(line_sym, keys::stroke, color(0, 0, 0));
put(line_sym,keys::stroke_width,1.0); put(line_sym, keys::stroke_width, 1.0);
dash_array dash; dash_array dash;
dash.emplace_back(8,4); dash.emplace_back(8, 4);
dash.emplace_back(2,2); dash.emplace_back(2, 2);
dash.emplace_back(2,2); dash.emplace_back(2, 2);
put(line_sym,keys::stroke_dasharray,dash); put(line_sym, keys::stroke_dasharray, dash);
r.append(std::move(line_sym)); r.append(std::move(line_sym));
} }
provlines_style.add_rule(std::move(r)); provlines_style.add_rule(std::move(r));
@ -127,10 +129,10 @@ int main ( int, char** )
r.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4")); r.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
{ {
line_symbolizer line_sym; line_symbolizer line_sym;
put(line_sym,keys::stroke,color(171,158,137)); put(line_sym, keys::stroke, color(171, 158, 137));
put(line_sym,keys::stroke_width,2.0); put(line_sym, keys::stroke_width, 2.0);
put(line_sym,keys::stroke_linecap,ROUND_CAP); put(line_sym, keys::stroke_linecap, ROUND_CAP);
put(line_sym,keys::stroke_linejoin,ROUND_JOIN); put(line_sym, keys::stroke_linejoin, ROUND_JOIN);
r.append(std::move(line_sym)); r.append(std::move(line_sym));
} }
roads34_style.add_rule(std::move(r)); roads34_style.add_rule(std::move(r));
@ -144,10 +146,10 @@ int main ( int, char** )
r.set_filter(parse_expression("[CLASS] = 2")); r.set_filter(parse_expression("[CLASS] = 2"));
{ {
line_symbolizer line_sym; line_symbolizer line_sym;
put(line_sym,keys::stroke,color(171,158,137)); put(line_sym, keys::stroke, color(171, 158, 137));
put(line_sym,keys::stroke_width,4.0); put(line_sym, keys::stroke_width, 4.0);
put(line_sym,keys::stroke_linecap,ROUND_CAP); put(line_sym, keys::stroke_linecap, ROUND_CAP);
put(line_sym,keys::stroke_linejoin,ROUND_JOIN); put(line_sym, keys::stroke_linejoin, ROUND_JOIN);
r.append(std::move(line_sym)); r.append(std::move(line_sym));
} }
roads2_style_1.add_rule(std::move(r)); roads2_style_1.add_rule(std::move(r));
@ -160,10 +162,10 @@ int main ( int, char** )
r.set_filter(parse_expression("[CLASS] = 2")); r.set_filter(parse_expression("[CLASS] = 2"));
{ {
line_symbolizer line_sym; line_symbolizer line_sym;
put(line_sym,keys::stroke,color(255,250,115)); put(line_sym, keys::stroke, color(255, 250, 115));
put(line_sym,keys::stroke_width,2.0); put(line_sym, keys::stroke_width, 2.0);
put(line_sym,keys::stroke_linecap,ROUND_CAP); put(line_sym, keys::stroke_linecap, ROUND_CAP);
put(line_sym,keys::stroke_linejoin,ROUND_JOIN); put(line_sym, keys::stroke_linejoin, ROUND_JOIN);
r.append(std::move(line_sym)); r.append(std::move(line_sym));
} }
roads2_style_2.add_rule(std::move(r)); roads2_style_2.add_rule(std::move(r));
@ -177,10 +179,10 @@ int main ( int, char** )
r.set_filter(parse_expression("[CLASS] = 1")); r.set_filter(parse_expression("[CLASS] = 1"));
{ {
line_symbolizer line_sym; line_symbolizer line_sym;
put(line_sym,keys::stroke,color(188,149,28)); put(line_sym, keys::stroke, color(188, 149, 28));
put(line_sym,keys::stroke_width,7.0); put(line_sym, keys::stroke_width, 7.0);
put(line_sym,keys::stroke_linecap,ROUND_CAP); put(line_sym, keys::stroke_linecap, ROUND_CAP);
put(line_sym,keys::stroke_linejoin,ROUND_JOIN); put(line_sym, keys::stroke_linejoin, ROUND_JOIN);
r.append(std::move(line_sym)); r.append(std::move(line_sym));
} }
roads1_style_1.add_rule(std::move(r)); roads1_style_1.add_rule(std::move(r));
@ -193,10 +195,10 @@ int main ( int, char** )
r.set_filter(parse_expression("[CLASS] = 1")); r.set_filter(parse_expression("[CLASS] = 1"));
{ {
line_symbolizer line_sym; line_symbolizer line_sym;
put(line_sym,keys::stroke,color(242,191,36)); put(line_sym, keys::stroke, color(242, 191, 36));
put(line_sym,keys::stroke_width,5.0); put(line_sym, keys::stroke_width, 5.0);
put(line_sym,keys::stroke_linecap,ROUND_CAP); put(line_sym, keys::stroke_linecap, ROUND_CAP);
put(line_sym,keys::stroke_linejoin,ROUND_JOIN); put(line_sym, keys::stroke_linejoin, ROUND_JOIN);
r.append(std::move(line_sym)); r.append(std::move(line_sym));
} }
roads1_style_2.add_rule(std::move(r)); roads1_style_2.add_rule(std::move(r));
@ -212,10 +214,11 @@ int main ( int, char** )
text_placements_ptr placement_finder = std::make_shared<text_placements_dummy>(); text_placements_ptr placement_finder = std::make_shared<text_placements_dummy>();
placement_finder->defaults.format_defaults.face_name = "DejaVu Sans Book"; placement_finder->defaults.format_defaults.face_name = "DejaVu Sans Book";
placement_finder->defaults.format_defaults.text_size = 10.0; placement_finder->defaults.format_defaults.text_size = 10.0;
placement_finder->defaults.format_defaults.fill = color(0,0,0); placement_finder->defaults.format_defaults.fill = color(0, 0, 0);
placement_finder->defaults.format_defaults.halo_fill = color(255,255,200); placement_finder->defaults.format_defaults.halo_fill = color(255, 255, 200);
placement_finder->defaults.format_defaults.halo_radius = 1.0; placement_finder->defaults.format_defaults.halo_radius = 1.0;
placement_finder->defaults.set_format_tree(std::make_shared<mapnik::formatting::text_node>(parse_expression("[GEONAME]"))); placement_finder->defaults.set_format_tree(
std::make_shared<mapnik::formatting::text_node>(parse_expression("[GEONAME]")));
put<text_placements_ptr>(text_sym, keys::text_placements_, placement_finder); put<text_placements_ptr>(text_sym, keys::text_placements_, placement_finder);
r.append(std::move(text_sym)); r.append(std::move(text_sym));
} }
@ -228,9 +231,9 @@ int main ( int, char** )
// Provincial polygons // Provincial polygons
{ {
parameters p; parameters p;
p["type"]="shape"; p["type"] = "shape";
p["file"]="demo/data/boundaries"; p["file"] = "demo/data/boundaries";
p["encoding"]="utf8"; p["encoding"] = "utf8";
layer lyr("Provinces"); layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_datasource(datasource_cache::instance().create(p));
@ -242,8 +245,8 @@ int main ( int, char** )
// Drainage // Drainage
{ {
parameters p; parameters p;
p["type"]="shape"; p["type"] = "shape";
p["file"]="demo/data/qcdrainage"; p["file"] = "demo/data/qcdrainage";
layer lyr("Quebec Hydrography"); layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_datasource(datasource_cache::instance().create(p));
lyr.set_srs(srs_lcc); lyr.set_srs(srs_lcc);
@ -253,8 +256,8 @@ int main ( int, char** )
{ {
parameters p; parameters p;
p["type"]="shape"; p["type"] = "shape";
p["file"]="demo/data/ontdrainage"; p["file"] = "demo/data/ontdrainage";
layer lyr("Ontario Hydrography"); layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_datasource(datasource_cache::instance().create(p));
lyr.set_srs(srs_lcc); lyr.set_srs(srs_lcc);
@ -265,8 +268,8 @@ int main ( int, char** )
// Provincial boundaries // Provincial boundaries
{ {
parameters p; parameters p;
p["type"]="shape"; p["type"] = "shape";
p["file"]="demo/data/boundaries_l"; p["file"] = "demo/data/boundaries_l";
layer lyr("Provincial borders"); layer lyr("Provincial borders");
lyr.set_srs(srs_lcc); lyr.set_srs(srs_lcc);
lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_datasource(datasource_cache::instance().create(p));
@ -277,8 +280,8 @@ int main ( int, char** )
// Roads // Roads
{ {
parameters p; parameters p;
p["type"]="shape"; p["type"] = "shape";
p["file"]="demo/data/roads"; p["file"] = "demo/data/roads";
layer lyr("Roads"); layer lyr("Roads");
lyr.set_srs(srs_lcc); lyr.set_srs(srs_lcc);
lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_datasource(datasource_cache::instance().create(p));
@ -293,8 +296,8 @@ int main ( int, char** )
// popplaces // popplaces
{ {
parameters p; parameters p;
p["type"]="shape"; p["type"] = "shape";
p["file"]="demo/data/popplaces"; p["file"] = "demo/data/popplaces";
p["encoding"] = "utf8"; p["encoding"] = "utf8";
layer lyr("Populated Places"); layer lyr("Populated Places");
lyr.set_srs(srs_lcc); lyr.set_srs(srs_lcc);
@ -303,28 +306,28 @@ int main ( int, char** )
m.add_layer(lyr); m.add_layer(lyr);
} }
m.zoom_to_box(box2d<double>(-8024477.28459,5445190.38849,-7381388.20071,5662941.44855)); m.zoom_to_box(box2d<double>(-8024477.28459, 5445190.38849, -7381388.20071, 5662941.44855));
image_rgba8 buf(m.width(),m.height()); image_rgba8 buf(m.width(), m.height());
agg_renderer<image_rgba8> ren(m,buf); agg_renderer<image_rgba8> ren(m, buf);
ren.apply(); ren.apply();
std::string msg("These maps have been rendered using AGG in the current directory:\n"); std::string msg("These maps have been rendered using AGG in the current directory:\n");
#ifdef HAVE_JPEG #ifdef HAVE_JPEG
save_to_file(buf,"demo.jpg","jpeg"); save_to_file(buf, "demo.jpg", "jpeg");
msg += "- demo.jpg\n"; msg += "- demo.jpg\n";
#endif #endif
#ifdef HAVE_PNG #ifdef HAVE_PNG
save_to_file(buf,"demo.png","png"); save_to_file(buf, "demo.png", "png");
save_to_file(buf,"demo256.png","png8"); save_to_file(buf, "demo256.png", "png8");
msg += "- demo.png\n"; msg += "- demo.png\n";
msg += "- demo256.png\n"; msg += "- demo256.png\n";
#endif #endif
#ifdef HAVE_TIFF #ifdef HAVE_TIFF
save_to_file(buf,"demo.tif","tiff"); save_to_file(buf, "demo.tif", "tiff");
msg += "- demo.tif\n"; msg += "- demo.tif\n";
#endif #endif
#ifdef HAVE_WEBP #ifdef HAVE_WEBP
save_to_file(buf,"demo.webp","webp"); save_to_file(buf, "demo.webp", "webp");
msg += "- demo.webp\n"; msg += "- demo.webp\n";
#endif #endif
msg += "Have a look!\n"; msg += "Have a look!\n";
@ -332,8 +335,8 @@ int main ( int, char** )
#if defined(HAVE_CAIRO) #if defined(HAVE_CAIRO)
// save to pdf/svg files // save to pdf/svg files
save_to_cairo_file(m,"cairo-demo.pdf"); save_to_cairo_file(m, "cairo-demo.pdf");
save_to_cairo_file(m,"cairo-demo.svg"); save_to_cairo_file(m, "cairo-demo.svg");
/* we could also do: /* we could also do:
@ -342,38 +345,36 @@ int main ( int, char** )
but instead let's build up a surface for more flexibility but instead let's build up a surface for more flexibility
*/ */
cairo_surface_ptr image_surface( cairo_surface_ptr image_surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, m.width(), m.height()),
cairo_image_surface_create(CAIRO_FORMAT_ARGB32,m.width(),m.height()), cairo_surface_closer());
cairo_surface_closer());
double scale_factor = 1.0; double scale_factor = 1.0;
cairo_ptr image_context(create_context(image_surface)); cairo_ptr image_context(create_context(image_surface));
mapnik::cairo_renderer<cairo_ptr> png_render(m,image_context,scale_factor); mapnik::cairo_renderer<cairo_ptr> png_render(m, image_context, scale_factor);
png_render.apply(); png_render.apply();
// we can now write to png with cairo functionality // we can now write to png with cairo functionality
cairo_surface_write_to_png(&*image_surface, "cairo-demo.png"); cairo_surface_write_to_png(&*image_surface, "cairo-demo.png");
// but we can also benefit from quantization by converting // but we can also benefit from quantization by converting
// to a mapnik image object and then saving that // to a mapnik image object and then saving that
mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface)); mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface),
cairo_image_surface_get_height(&*image_surface));
cairo_image_to_rgba8(im_data, image_surface); cairo_image_to_rgba8(im_data, image_surface);
save_to_file(im_data, "cairo-demo256.png","png8"); save_to_file(im_data, "cairo-demo256.png", "png8");
cairo_surface_finish(&*image_surface); cairo_surface_finish(&*image_surface);
std::cout << "Three maps have been rendered using Cairo in the current directory:\n" std::cout << "Three maps have been rendered using Cairo in the current directory:\n"
"- cairo-demo.png\n" "- cairo-demo.png\n"
"- cairo-demo256.png\n" "- cairo-demo256.png\n"
"- cairo-demo.pdf\n" "- cairo-demo.pdf\n"
"- cairo-demo.svg\n" "- cairo-demo.svg\n"
"Have a look!\n"; "Have a look!\n";
#endif #endif
// save map definition (data + style) // save map definition (data + style)
save_map(m, "map.xml"); save_map(m, "map.xml");
} } catch (std::exception const& ex)
catch ( std::exception const& ex )
{ {
std::cerr << "### std::exception: " << ex.what() << std::endl; std::cerr << "### std::exception: " << ex.what() << std::endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} } catch (...)
catch ( ... )
{ {
std::cerr << "### Unknown exception." << std::endl; std::cerr << "### Unknown exception." << std::endl;
return EXIT_FAILURE; return EXIT_FAILURE;

View file

@ -17,12 +17,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include "about_dialog.hpp" #include "about_dialog.hpp"
about_dialog::about_dialog(QWidget* parent)
about_dialog::about_dialog(QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
ui.setupUi(this); ui.setupUi(this);
} }

View file

@ -17,8 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#if !defined ABOUT_DIALOG_HPP #if !defined ABOUT_DIALOG_HPP
#define ABOUT_DIALOG_HPP #define ABOUT_DIALOG_HPP
@ -27,12 +25,12 @@
class about_dialog : public QDialog class about_dialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
about_dialog(QWidget * parent = 0); about_dialog(QWidget* parent = 0);
private:
Ui::Dialog ui; private:
Ui::Dialog ui;
}; };
#endif // ABOUT_DIALOG_HPP
#endif //ABOUT_DIALOG_HPP

View file

@ -17,24 +17,22 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include "info_dialog.hpp" #include "info_dialog.hpp"
info_dialog::info_dialog(QVector<QPair<QString, QString>> const& info, QWidget* parent)
info_dialog::info_dialog(QVector<QPair<QString,QString> > const& info, QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
ui.setupUi(this); ui.setupUi(this);
ui.tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("Name")); ui.tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Name"));
ui.tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("Value")); ui.tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Value"));
ui.tableWidget->setRowCount(info.size()); ui.tableWidget->setRowCount(info.size());
ui.tableWidget->setColumnCount(2); ui.tableWidget->setColumnCount(2);
for (int i=0;i<info.size();++i) for (int i = 0; i < info.size(); ++i)
{ {
QTableWidgetItem *keyItem = new QTableWidgetItem(info[i].first); QTableWidgetItem* keyItem = new QTableWidgetItem(info[i].first);
QTableWidgetItem *valueItem = new QTableWidgetItem(info[i].second); QTableWidgetItem* valueItem = new QTableWidgetItem(info[i].second);
ui.tableWidget->setItem(i,0,keyItem); ui.tableWidget->setItem(i, 0, keyItem);
ui.tableWidget->setItem(i,1,valueItem); ui.tableWidget->setItem(i, 1, valueItem);
} }
} }

View file

@ -17,8 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef INFO_DIALOG_HPP #ifndef INFO_DIALOG_HPP
#define INFO_DIALOG_HPP #define INFO_DIALOG_HPP
@ -27,12 +25,12 @@
class info_dialog : public QDialog class info_dialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
info_dialog(QVector<QPair<QString,QString> > const& info,QWidget * parent = 0); info_dialog(QVector<QPair<QString, QString>> const& info, QWidget* parent = 0);
private:
Ui::InfoDialog ui; private:
Ui::InfoDialog ui;
}; };
#endif // INFO_DIALOG_HPP
#endif //INFO_DIALOG_HPP

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include "layer_info_dialog.hpp" #include "layer_info_dialog.hpp"
// mapnik // mapnik
@ -26,14 +25,13 @@
#include <mapnik/params_impl.hpp> #include <mapnik/params_impl.hpp>
#include <mapnik/layer.hpp> #include <mapnik/layer.hpp>
layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget* parent)
layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget *parent) : QDialog(parent)
: QDialog(parent)
{ {
ui.setupUi(this); ui.setupUi(this);
ui.tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("Name")); ui.tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Name"));
ui.tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("Value")); ui.tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Value"));
// Layer name // Layer name
ui.layerNameEdit->setText(QString(lay.name().c_str())); ui.layerNameEdit->setText(QString(lay.name().c_str()));
@ -50,17 +48,17 @@ layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget *parent)
ui.tableWidget->setColumnCount(2); ui.tableWidget->setColumnCount(2);
mapnik::parameters::const_iterator pos; mapnik::parameters::const_iterator pos;
int index=0; int index = 0;
for (pos = ps.begin();pos != ps.end();++pos) for (pos = ps.begin(); pos != ps.end(); ++pos)
{ {
boost::optional<std::string> result; boost::optional<std::string> result;
mapnik::util::apply_visitor(mapnik::value_extractor_visitor<std::string>(result),pos->second); mapnik::util::apply_visitor(mapnik::value_extractor_visitor<std::string>(result), pos->second);
if (result) if (result)
{ {
QTableWidgetItem *keyItem = new QTableWidgetItem(QString(pos->first.c_str())); QTableWidgetItem* keyItem = new QTableWidgetItem(QString(pos->first.c_str()));
QTableWidgetItem *valueItem = new QTableWidgetItem(QString((*result).c_str())); QTableWidgetItem* valueItem = new QTableWidgetItem(QString((*result).c_str()));
ui.tableWidget->setItem(index,0,keyItem); ui.tableWidget->setItem(index, 0, keyItem);
ui.tableWidget->setItem(index,1,valueItem); ui.tableWidget->setItem(index, 1, valueItem);
++index; ++index;
} }
} }
@ -69,5 +67,5 @@ layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget *parent)
Ui::LayerInfoDialog& layer_info_dialog::getUI() Ui::LayerInfoDialog& layer_info_dialog::getUI()
{ {
return ui; return ui;
} }

View file

@ -17,28 +17,25 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef LAYER_INFO_DIALOG_HPP #ifndef LAYER_INFO_DIALOG_HPP
#define LAYER_INFO_DIALOG_HPP #define LAYER_INFO_DIALOG_HPP
#include "ui_layer_info.h" #include "ui_layer_info.h"
#include <QDialog> #include <QDialog>
namespace mapnik namespace mapnik {
{
class layer; class layer;
} }
class layer_info_dialog : public QDialog class layer_info_dialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
layer_info_dialog(mapnik::layer& l, QWidget * parent = 0); layer_info_dialog(mapnik::layer& l, QWidget* parent = 0);
Ui::LayerInfoDialog& getUI(); Ui::LayerInfoDialog& getUI();
private:
Ui::LayerInfoDialog ui; private:
Ui::LayerInfoDialog ui;
}; };
#endif // LAYER_INFO_DIALOG_HPP
#endif //LAYER_INFO_DIALOG_HPP

View file

@ -17,38 +17,32 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include <QtGui> #include <QtGui>
#include "layerdelegate.hpp" #include "layerdelegate.hpp"
LayerDelegate::LayerDelegate(QObject *parent) LayerDelegate::LayerDelegate(QObject* parent)
: QAbstractItemDelegate(parent) : QAbstractItemDelegate(parent)
{ {}
}
void LayerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, void LayerDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
const QModelIndex &index) const
{ {
painter->setRenderHint(QPainter::Antialiasing); painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(QPen(QColor(255,0,0),1)); painter->setPen(QPen(QColor(255, 0, 0), 1));
if (option.state & QStyle::State_Selected) if (option.state & QStyle::State_Selected)
painter->setBrush(QBrush(QColor(0, 0, 255, 64))); painter->setBrush(QBrush(QColor(0, 0, 255, 64)));
else else
painter->setBrush(QBrush(QColor(255, 0, 0, 64))); painter->setBrush(QBrush(QColor(255, 0, 0, 64)));
painter->drawRoundedRect(option.rect, 4, 4);
painter->drawRoundedRect(option.rect,4,4);
if (option.state & QStyle::State_Selected) if (option.state & QStyle::State_Selected)
painter->setBrush(option.palette.highlightedText()); painter->setBrush(option.palette.highlightedText());
else else
painter->setBrush(QBrush(QColor(255, 120, 0, 127))); painter->setBrush(QBrush(QColor(255, 120, 0, 127)));
} }
QSize LayerDelegate::sizeHint(const QStyleOptionViewItem & /* option */, QSize LayerDelegate::sizeHint(const QStyleOptionViewItem& /* option */, const QModelIndex& /* index */) const
const QModelIndex & /* index */) const
{ {
return QSize(120,24); return QSize(120, 24);
} }

View file

@ -33,12 +33,10 @@ class LayerDelegate : public QAbstractItemDelegate
{ {
Q_OBJECT Q_OBJECT
public: public:
LayerDelegate(QObject *parent = 0); LayerDelegate(QObject* parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
}; };
#endif //LAYER_DELEGATE_HPP #endif // LAYER_DELEGATE_HPP

View file

@ -17,8 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include "layerlistmodel.hpp" #include "layerlistmodel.hpp"
#include <QIcon> #include <QIcon>
#include <QBrush> #include <QBrush>
@ -26,14 +24,16 @@
using mapnik::Map; using mapnik::Map;
LayerListModel::LayerListModel(std::shared_ptr<Map> map, QObject *parent) LayerListModel::LayerListModel(std::shared_ptr<Map> map, QObject* parent)
: QAbstractListModel(parent), : QAbstractListModel(parent)
map_(map) {} , map_(map)
{}
int LayerListModel::rowCount(QModelIndex const&) const int LayerListModel::rowCount(QModelIndex const&) const
{ {
if (map_) return map_->layers().size(); if (map_)
return 0; return map_->layers().size();
return 0;
} }
QVariant LayerListModel::data(QModelIndex const& index, int role) const QVariant LayerListModel::data(QModelIndex const& index, int role) const
@ -59,9 +59,9 @@ QVariant LayerListModel::data(QModelIndex const& index, int role) const
else if (role == Qt::CheckStateRole) else if (role == Qt::CheckStateRole)
{ {
if (map_->layers().at(index.row()).active()) if (map_->layers().at(index.row()).active())
return QVariant(Qt::Checked); return QVariant(Qt::Checked);
else else
return QVariant(Qt::Unchecked); return QVariant(Qt::Unchecked);
} }
else if (role == Qt::ForegroundRole) else if (role == Qt::ForegroundRole)
{ {
@ -76,8 +76,7 @@ QVariant LayerListModel::data(QModelIndex const& index, int role) const
} }
} }
QVariant LayerListModel::headerData(int section, Qt::Orientation orientation, QVariant LayerListModel::headerData(int section, Qt::Orientation orientation, int role) const
int role) const
{ {
if (role != Qt::DisplayRole) if (role != Qt::DisplayRole)
return QVariant(); return QVariant();
@ -88,37 +87,37 @@ QVariant LayerListModel::headerData(int section, Qt::Orientation orientation,
return QString("TODO Row %1").arg(section); return QString("TODO Row %1").arg(section);
} }
bool LayerListModel::setData(const QModelIndex &index, bool LayerListModel::setData(const QModelIndex& index, const QVariant& value, int role)
const QVariant &value, int role)
{ {
if (!map_) return false; if (!map_)
return false;
if (index.isValid() && role == Qt::CheckStateRole) if (index.isValid() && role == Qt::CheckStateRole)
{ {
int status = value.toInt(); int status = value.toInt();
std::vector<mapnik::layer> & layers = const_cast<std::vector<mapnik::layer>& >(map_->layers()); std::vector<mapnik::layer>& layers = const_cast<std::vector<mapnik::layer>&>(map_->layers());
layers.at(index.row()).set_active(status); layers.at(index.row()).set_active(status);
emit dataChanged(index, index); emit dataChanged(index, index);
return true; return true;
} }
return false; return false;
} }
Qt::ItemFlags LayerListModel::flags(QModelIndex const& index) const Qt::ItemFlags LayerListModel::flags(QModelIndex const& index) const
{ {
Qt::ItemFlags flags = QAbstractItemModel::flags(index); Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.isValid()) if (index.isValid())
flags |= Qt::ItemIsUserCheckable; flags |= Qt::ItemIsUserCheckable;
return flags; return flags;
} }
boost::optional<mapnik::layer&> LayerListModel::map_layer(int i) boost::optional<mapnik::layer&> LayerListModel::map_layer(int i)
{ {
if (map_) if (map_)
{ {
std::vector<mapnik::layer> & layers = const_cast<std::vector<mapnik::layer>& >(map_->layers()); std::vector<mapnik::layer>& layers = const_cast<std::vector<mapnik::layer>&>(map_->layers());
if (i < int(layers.size())) if (i < int(layers.size()))
return boost::optional<mapnik::layer&>(layers[i]); return boost::optional<mapnik::layer&>(layers[i]);
} }
return boost::optional<mapnik::layer&>(); return boost::optional<mapnik::layer&>();
} }

View file

@ -17,8 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef LAYER_LIST_MODEL_HPP #ifndef LAYER_LIST_MODEL_HPP
#define LAYER_LIST_MODEL_HPP #define LAYER_LIST_MODEL_HPP
@ -32,20 +30,18 @@
class LayerListModel : public QAbstractListModel class LayerListModel : public QAbstractListModel
{ {
Q_OBJECT Q_OBJECT
public: public:
LayerListModel(std::shared_ptr<mapnik::Map> map, QObject * parent = 0); LayerListModel(std::shared_ptr<mapnik::Map> map, QObject* parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex& parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex& index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
int role = Qt::DisplayRole) const; bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
bool setData(const QModelIndex &index, const QVariant &value, Qt::ItemFlags flags(QModelIndex const& index) const;
int role = Qt::EditRole); boost::optional<mapnik::layer&> map_layer(int i);
Qt::ItemFlags flags(QModelIndex const& index) const;
boost::optional<mapnik::layer&> map_layer(int i);
private: private:
std::shared_ptr<mapnik::Map> map_; std::shared_ptr<mapnik::Map> map_;
}; };
#endif //LAYER_LIST_MODEL_HPP #endif // LAYER_LIST_MODEL_HPP

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include "layerwidget.hpp" #include "layerwidget.hpp"
#include <qabstractitemdelegate.h> #include <qabstractitemdelegate.h>
#include <qapplication.h> #include <qapplication.h>
@ -33,65 +32,59 @@
#include "layer_info_dialog.hpp" #include "layer_info_dialog.hpp"
LayerTab::LayerTab(QWidget* parent) LayerTab::LayerTab(QWidget* parent)
: QListView(parent) {} : QListView(parent)
{}
void LayerTab::paintEvent(QPaintEvent* e)
void LayerTab::paintEvent(QPaintEvent *e)
{ {
QListView::paintEvent(e); QListView::paintEvent(e);
} }
void LayerTab::dataChanged(const QModelIndex &topLeft, void LayerTab::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles)
const QModelIndex &bottomRight,
const QVector<int> &roles)
{ {
emit update_mapwidget(); emit update_mapwidget();
QListView::dataChanged(topLeft, bottomRight, roles); QListView::dataChanged(topLeft, bottomRight, roles);
} }
void LayerTab::selectionChanged(const QItemSelection & selected, const QItemSelection &) void LayerTab::selectionChanged(const QItemSelection& selected, const QItemSelection&)
{ {
QModelIndexList list = selected.indexes(); QModelIndexList list = selected.indexes();
if (list.size() != 0) if (list.size() != 0)
{ {
qDebug("SELECTED LAYER -> %d",list[0].row()); qDebug("SELECTED LAYER -> %d", list[0].row());
emit layerSelected(list[0].row()); emit layerSelected(list[0].row());
} }
} }
void LayerTab::layerInfo() void LayerTab::layerInfo()
{ {
qDebug("Layer info"); qDebug("Layer info");
QModelIndexList indexes = selectedIndexes(); QModelIndexList indexes = selectedIndexes();
if (indexes.size() > 0) if (indexes.size() > 0)
{ {
qDebug("id = %d",indexes[0].row()); qDebug("id = %d", indexes[0].row());
}
}
} }
void LayerTab::layerInfo2(QModelIndex const& index) void LayerTab::layerInfo2(QModelIndex const& index)
{ {
qDebug("LayerInfo id = %d",index.row()); qDebug("LayerInfo id = %d", index.row());
QVector<QPair<QString,QString> > params; QVector<QPair<QString, QString>> params;
QVector<QString> style_names; QVector<QString> style_names;
unsigned i = index.row(); unsigned i = index.row();
LayerListModel * model = static_cast<LayerListModel*>(this->model()); LayerListModel* model = static_cast<LayerListModel*>(this->model());
boost::optional<mapnik::layer&> layer = model->map_layer(i); boost::optional<mapnik::layer&> layer = model->map_layer(i);
if (layer) if (layer)
{ {
layer_info_dialog dlg(*layer,this); layer_info_dialog dlg(*layer, this);
dlg.exec(); dlg.exec();
} }
} }
StyleTab::StyleTab(QWidget*) StyleTab::StyleTab(QWidget*) {}
void StyleTab::contextMenuEvent(QContextMenuEvent* event)
{ {
qDebug("test");
}
void StyleTab::contextMenuEvent(QContextMenuEvent * event )
{
qDebug("test");
} }

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef LAYERWIDGET_HPP #ifndef LAYERWIDGET_HPP
#define LAYERWIDGET_HPP #define LAYERWIDGET_HPP
@ -28,27 +27,28 @@
class LayerTab : public QListView class LayerTab : public QListView
{ {
Q_OBJECT Q_OBJECT
public: public:
LayerTab(QWidget* parent=0); LayerTab(QWidget* parent = 0);
void paintEvent(QPaintEvent *e); void paintEvent(QPaintEvent* e);
signals: signals:
void update_mapwidget(); void update_mapwidget();
void layerSelected(int) const; void layerSelected(int) const;
public slots: public slots:
void layerInfo(); void layerInfo();
void layerInfo2(QModelIndex const&); void layerInfo2(QModelIndex const&);
protected slots: protected slots:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles); void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles);
void selectionChanged(const QItemSelection & selected, const QItemSelection &); void selectionChanged(const QItemSelection& selected, const QItemSelection&);
}; };
class StyleTab : public QTreeView class StyleTab : public QTreeView
{ {
Q_OBJECT Q_OBJECT
public: public:
StyleTab(QWidget* parent=0); StyleTab(QWidget* parent = 0);
protected:
void contextMenuEvent(QContextMenuEvent * event ); protected:
void contextMenuEvent(QContextMenuEvent* event);
}; };
#endif #endif

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
// qt // qt
#include <QApplication> #include <QApplication>
#include <QStringList> #include <QStringList>
@ -26,27 +25,26 @@
#include <mapnik/font_engine_freetype.hpp> #include <mapnik/font_engine_freetype.hpp>
#include "mainwindow.hpp" #include "mainwindow.hpp"
int main( int argc, char **argv ) int main(int argc, char** argv)
{ {
using mapnik::datasource_cache; using mapnik::datasource_cache;
using mapnik::freetype_engine; using mapnik::freetype_engine;
try try
{ {
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif #endif
QCoreApplication::setOrganizationName("Mapnik"); QCoreApplication::setOrganizationName("Mapnik");
QCoreApplication::setOrganizationDomain("mapnik.org"); QCoreApplication::setOrganizationDomain("mapnik.org");
QCoreApplication::setApplicationName("Viewer"); QCoreApplication::setApplicationName("Viewer");
QSettings settings("viewer.ini",QSettings::IniFormat); QSettings settings("viewer.ini", QSettings::IniFormat);
// register input plug-ins // register input plug-ins
QString plugins_dir = settings.value("mapnik/plugins_dir", QString plugins_dir = settings.value("mapnik/plugins_dir", QVariant("/usr/local/lib/mapnik/input/")).toString();
QVariant("/usr/local/lib/mapnik/input/")).toString();
datasource_cache::instance().register_datasources(plugins_dir.toStdString()); datasource_cache::instance().register_datasources(plugins_dir.toStdString());
// register fonts // register fonts
int count = settings.beginReadArray("mapnik/fonts"); int count = settings.beginReadArray("mapnik/fonts");
for (int index=0; index < count; ++index) for (int index = 0; index < count; ++index)
{ {
settings.setArrayIndex(index); settings.setArrayIndex(index);
QString font_dir = settings.value("dir").toString(); QString font_dir = settings.value("dir").toString();
@ -54,37 +52,40 @@ int main( int argc, char **argv )
} }
settings.endArray(); settings.endArray();
QApplication app( argc, argv ); QApplication app(argc, argv);
MainWindow window; MainWindow window;
window.show(); window.show();
if (argc > 1) window.open(argv[1]); if (argc > 1)
window.open(argv[1]);
if (argc >= 3) if (argc >= 3)
{ {
QStringList list = QString(argv[2]).split(","); QStringList list = QString(argv[2]).split(",");
if (list.size()==4) if (list.size() == 4)
{ {
bool ok; bool ok;
double x0 = list[0].toDouble(&ok); double x0 = list[0].toDouble(&ok);
double y0 = list[1].toDouble(&ok); double y0 = list[1].toDouble(&ok);
double x1 = list[2].toDouble(&ok); double x1 = list[2].toDouble(&ok);
double y1 = list[3].toDouble(&ok); double y1 = list[3].toDouble(&ok);
if (ok) window.set_default_extent(x0,y0,x1,y1); if (ok)
window.set_default_extent(x0, y0, x1, y1);
} }
} }
else else
{ {
std::shared_ptr<mapnik::Map> map = window.get_map(); std::shared_ptr<mapnik::Map> map = window.get_map();
if (map) map->zoom_all(); if (map)
map->zoom_all();
} }
if (argc == 4) if (argc == 4)
{ {
bool ok; bool ok;
double scaling_factor = QString(argv[3]).toDouble(&ok); double scaling_factor = QString(argv[3]).toDouble(&ok);
if (ok) window.set_scaling_factor(scaling_factor); if (ok)
window.set_scaling_factor(scaling_factor);
} }
return app.exec(); return app.exec();
} } catch (std::exception const& ex)
catch (std::exception const& ex)
{ {
std::cerr << "Could not start viewer: '" << ex.what() << "'\n"; std::cerr << "Could not start viewer: '" << ex.what() << "'\n";
return 1; return 1;

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
// stl // stl
#include <iostream> #include <iostream>
@ -58,27 +57,27 @@
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
MainWindow::MainWindow() MainWindow::MainWindow()
: filename_(), : filename_()
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428) , default_extent_(-20037508.3428, -20037508.3428, 20037508.3428, 20037508.3428)
{ {
mapWidget_ = new MapWidget(this); mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this); QSplitter* splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget; QTabWidget* tabWidget = new QTabWidget;
layerTab_ = new LayerTab; layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus); layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16)); layerTab_->setIconSize(QSize(16, 16));
//LayerDelegate *delegate = new LayerDelegate(this); // LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate); // layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this)); // layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode); // layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom); layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers")); tabWidget->addTab(layerTab_, tr("Layers"));
// Styles tab // Styles tab
styleTab_ = new StyleTab; styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles")); tabWidget->addTab(styleTab_, tr("Styles"));
splitter->addWidget(tabWidget); splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_); splitter->addWidget(mapWidget_);
QList<int> list; QList<int> list;
@ -89,7 +88,7 @@ MainWindow::MainWindow()
mapWidget_->setFocusPolicy(Qt::StrongFocus); mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus(); mapWidget_->setFocus();
//setCentralWidget(mapWidget_); // setCentralWidget(mapWidget_);
setCentralWidget(splitter); setCentralWidget(splitter);
createActions(); createActions();
createMenus(); createMenus();
@ -97,29 +96,28 @@ MainWindow::MainWindow()
createContextMenu(); createContextMenu();
setWindowTitle(tr("Mapnik Viewer")); setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this); status = new QStatusBar(this);
status->showMessage(tr("")); status->showMessage(tr(""));
setStatusBar(status); setStatusBar(status);
resize(800,600); resize(800, 600);
//connect mapview to layerlist // connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update())); connect(mapWidget_, SIGNAL(mapViewChanged()), layerTab_, SLOT(update()));
// slider // slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int))); connect(slider_, SIGNAL(valueChanged(int)), mapWidget_, SLOT(zoomToLevel(int)));
// renderer selector // renderer selector
connect(renderer_selector_,SIGNAL(currentIndexChanged(QString const&)), connect(renderer_selector_,
mapWidget_, SLOT(updateRenderer(QString const&))); SIGNAL(currentIndexChanged(QString const&)),
mapWidget_,
SLOT(updateRenderer(QString const&)));
// scale factor // scale factor
connect(scale_factor_,SIGNAL(valueChanged(double)), connect(scale_factor_, SIGNAL(valueChanged(double)), mapWidget_, SLOT(updateScaleFactor(double)));
mapWidget_, SLOT(updateScaleFactor(double)));
// //
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap())); connect(layerTab_, SIGNAL(update_mapwidget()), mapWidget_, SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)), connect(layerTab_, SIGNAL(layerSelected(int)), mapWidget_, SLOT(layerSelected(int)));
mapWidget_,SLOT(layerSelected(int)));
} }
MainWindow::~MainWindow() MainWindow::~MainWindow()
{ {
delete mapWidget_; delete mapWidget_;
@ -141,8 +139,7 @@ void MainWindow::open(QString const& path)
{ {
if (path.isNull()) if (path.isNull())
{ {
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"), filename_ = QFileDialog::getOpenFileName(this, tr("Open Mapnik file"), currentPath, "*.xml");
currentPath,"*.xml");
} }
else else
{ {
@ -151,18 +148,15 @@ void MainWindow::open(QString const& path)
if (!filename_.isEmpty()) if (!filename_.isEmpty())
{ {
load_map_file(filename_); load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_)); setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
} }
} }
void MainWindow::reload() void MainWindow::reload()
{ {
if (!filename_.isEmpty()) if (!filename_.isEmpty())
{ {
mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent(); mapnik::box2d<double> bbox = mapWidget_->getMap()->get_current_extent();
load_map_file(filename_); load_map_file(filename_);
mapWidget_->zoomToBox(bbox); mapWidget_->zoomToBox(bbox);
@ -173,39 +167,37 @@ void MainWindow::reload()
void MainWindow::save() void MainWindow::save()
{ {
QString initialPath = QDir::currentPath() + "/untitled.xml"; QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"), QString filename = QFileDialog::getSaveFileName(this,
tr("Save"),
initialPath, initialPath,
tr("%1 Files (*.xml)") tr("%1 Files (*.xml)").arg(QString("Mapnik definition")));
.arg(QString("Mapnik definition")));
if (!filename.isEmpty()) if (!filename.isEmpty())
{ {
std::cout<<"saving "<< filename.toStdString() << std::endl; std::cout << "saving " << filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString()); mapnik::save_map(*mapWidget_->getMap(), filename.toStdString());
} }
} }
void MainWindow::load_map_file(QString const& filename) void MainWindow::load_map_file(QString const& filename)
{ {
std::cout << "loading "<< filename.toStdString() << std::endl; std::cout << "loading " << filename.toStdString() << std::endl;
unsigned width = mapWidget_->width(); unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height(); unsigned height = mapWidget_->height();
std::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); std::shared_ptr<mapnik::Map> map(new mapnik::Map(width, height));
mapWidget_->setMap(map); mapWidget_->setMap(map);
try try
{ {
mapnik::auto_cpu_timer t(std::clog, "loading map took: "); mapnik::auto_cpu_timer t(std::clog, "loading map took: ");
mapnik::load_map(*map,filename.toStdString()); mapnik::load_map(*map, filename.toStdString());
} } catch (std::exception const& ex)
catch (std::exception const& ex)
{ {
std::cout << ex.what() << "\n"; std::cout << ex.what() << "\n";
} } catch (...)
catch (...)
{ {
std::cerr << "Exception caught in load_map\n"; std::cerr << "Exception caught in load_map\n";
} }
layerTab_->setModel(new LayerListModel(map,this)); layerTab_->setModel(new LayerListModel(map, this));
styleTab_->setModel(new StyleModel(map,this)); styleTab_->setModel(new StyleModel(map, this));
zoom_all(); zoom_all();
} }
@ -252,15 +244,15 @@ void MainWindow::about()
void MainWindow::export_as() void MainWindow::export_as()
{ {
QAction *action = qobject_cast<QAction *>(sender()); QAction* action = qobject_cast<QAction*>(sender());
QByteArray fileFormat = action->data().toByteArray(); QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat; QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"), QString fileName = QFileDialog::getSaveFileName(
initialPath, this,
tr("%1 Files (*.%2);;All Files (*)") tr("Export As"),
.arg(QString(fileFormat.toUpper())) initialPath,
.arg(QString(fileFormat))); tr("%1 Files (*.%2);;All Files (*)").arg(QString(fileFormat.toUpper())).arg(QString(fileFormat)));
if (!fileName.isEmpty()) if (!fileName.isEmpty())
{ {
QPixmap const& pix = mapWidget_->pixmap(); QPixmap const& pix = mapWidget_->pixmap();
@ -270,77 +262,76 @@ void MainWindow::export_as()
void MainWindow::print() void MainWindow::print()
{ {
// Q_ASSERT(mapWidget_->pixmap());
//Q_ASSERT(mapWidget_->pixmap()); // QPrintDialog dialog(&printer, this);
//QPrintDialog dialog(&printer, this); // if (dialog.exec()) {
//if (dialog.exec()) { // QPainter painter(&printer);
// QPainter painter(&printer); // QRect rect = painter.viewport();
// QRect rect = painter.viewport(); // QSize size = mapWidget_->pixmap()->size();
// QSize size = mapWidget_->pixmap()->size(); // size.scale(rect.size(), Qt::KeepAspectRatio);
// size.scale(rect.size(), Qt::KeepAspectRatio); // painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); // painter.setWindow(mapWidget_->pixmap()->rect());
// painter.setWindow(mapWidget_->pixmap()->rect()); // painter.drawPixmap(0, 0, *mapWidget_->pixmap());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap()); // }
//}
} }
void MainWindow::createActions() void MainWindow::createActions()
{ {
//exportAct = new QAction(tr("&Export as ..."),this); // exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E")); // exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); // connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this); zoomAllAct = new QAction(QIcon(":/images/home.png"), tr("Zoom All"), this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all())); connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this); zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"), tr("Zoom To Box"), this);
zoomBoxAct->setCheckable(true); zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box())); connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this); panAct = new QAction(QIcon(":/images/pan.png"), tr("Pan"), this);
panAct->setCheckable(true); panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan())); connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this); infoAct = new QAction(QIcon(":/images/info.png"), tr("Info"), this);
infoAct->setCheckable(true); infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info())); connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this); toolsGroup = new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct); toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct); toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct); toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true); zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this); openAct = new QAction(tr("Open Map definition"), this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open())); connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this); saveAct = new QAction(tr("Save Map definition"), this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save())); connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this); panLeftAct = new QAction(QIcon(":/images/left.png"), tr("&Pan Left"), this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left())); connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this); panRightAct = new QAction(QIcon(":/images/right.png"), tr("&Pan Right"), this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right())); connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this); panUpAct = new QAction(QIcon(":/images/up.png"), tr("&Pan Up"), this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up())); connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this); panDownAct = new QAction(QIcon(":/images/down.png"), tr("&Pan Down"), this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down())); connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this); reloadAct = new QAction(QIcon(":/images/reload.png"), tr("Reload"), this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_); layerInfo = new QAction(QIcon(":/images/info.png"), tr("&Layer info"), layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo())); connect(layerInfo, SIGNAL(triggered()), layerTab_, SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&))); connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_, SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats()) foreach (QByteArray format, QImageWriter::supportedImageFormats())
{ {
QString text = tr("%1...").arg(QString(format).toUpper()); QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this); QAction* action = new QAction(text, this);
action->setData(format); action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as())); connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action); exportAsActs.append(action);
} }
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this); printAct = new QAction(QIcon(":/images/print.png"), tr("&Print ..."), this);
printAct->setShortcut(tr("Ctrl+E")); printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print())); connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
@ -348,17 +339,17 @@ void MainWindow::createActions()
exitAct->setShortcut(tr("Ctrl+Q")); exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this); aboutAct = new QAction(QIcon(":/images/about.png"), tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
} }
void MainWindow::createMenus() void MainWindow::createMenus()
{ {
exportMenu = new QMenu(tr("&Export As"), this); exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs) foreach (QAction* action, exportAsActs)
exportMenu->addAction(action); exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this); fileMenu = new QMenu(tr("&File"), this);
fileMenu->addAction(openAct); fileMenu->addAction(openAct);
fileMenu->addAction(saveAct); fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu); fileMenu->addMenu(exportMenu);
@ -402,8 +393,8 @@ void MainWindow::createToolBars()
scale_factor_->setValue(1.0); scale_factor_->setValue(1.0);
fileToolBar->addWidget(scale_factor_); fileToolBar->addWidget(scale_factor_);
slider_ = new QSlider(Qt::Horizontal,fileToolBar); slider_ = new QSlider(Qt::Horizontal, fileToolBar);
slider_->setRange(1,18); slider_->setRange(1, 18);
slider_->setTickPosition(QSlider::TicksBelow); slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1); slider_->setTickInterval(1);
slider_->setTracking(false); slider_->setTracking(false);
@ -411,9 +402,7 @@ void MainWindow::createToolBars()
fileToolBar->addAction(aboutAct); fileToolBar->addAction(aboutAct);
} }
void MainWindow::set_default_extent(double x0, double y0, double x1, double y1)
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{ {
try try
{ {
@ -423,12 +412,12 @@ void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
mapnik::projection prj(map_ptr->srs()); mapnik::projection prj(map_ptr->srs());
prj.forward(x0, y0); prj.forward(x0, y0);
prj.forward(x1, y1); prj.forward(x1, y1);
default_extent_=mapnik::box2d<double>(x0, y0, x1, y1); default_extent_ = mapnik::box2d<double>(x0, y0, x1, y1);
mapWidget_->zoomToBox(default_extent_); mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT:" << default_extent_ << std::endl; std::cout << "SET DEFAULT EXT:" << default_extent_ << std::endl;
} }
} } catch (...)
catch (...) {} {}
} }
void MainWindow::set_scaling_factor(double scaling_factor) void MainWindow::set_scaling_factor(double scaling_factor)

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef MAINWINDOW_HPP #ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP #define MAINWINDOW_HPP
@ -30,7 +29,7 @@
#include "mapwidget.hpp" #include "mapwidget.hpp"
//using namespace mapnik; // using namespace mapnik;
class LayerTab; class LayerTab;
class StyleTab; class StyleTab;
@ -41,22 +40,24 @@ class QDoubleSpinBox;
class MainWindow : public QMainWindow class MainWindow : public QMainWindow
{ {
Q_OBJECT Q_OBJECT
public: public:
MainWindow(); MainWindow();
virtual ~MainWindow(); virtual ~MainWindow();
void set_default_extent(double x0,double y0,double x1, double y1); void set_default_extent(double x0, double y0, double x1, double y1);
void set_scaling_factor(double scaling_factor); void set_scaling_factor(double scaling_factor);
public :
public:
std::shared_ptr<mapnik::Map> get_map(); std::shared_ptr<mapnik::Map> get_map();
protected:
protected:
void closeEvent(QCloseEvent* event); void closeEvent(QCloseEvent* event);
public slots: public slots:
void zoom_all(); void zoom_all();
void zoom_to_box(); void zoom_to_box();
void pan(); void pan();
void info(); void info();
void export_as(); void export_as();
void open(QString const& path = QString()); void open(QString const& path = QString());
void reload(); void reload();
void save(); void save();
void print(); void print();
@ -65,7 +66,8 @@ public slots:
void pan_right(); void pan_right();
void pan_up(); void pan_up();
void pan_down(); void pan_down();
private:
private:
void createActions(); void createActions();
void createMenus(); void createMenus();
void createToolBars(); void createToolBars();
@ -74,43 +76,42 @@ private:
QString currentPath; QString currentPath;
QString filename_; QString filename_;
QAbstractItemModel *model; QAbstractItemModel* model;
LayerTab *layerTab_; LayerTab* layerTab_;
StyleTab * styleTab_; StyleTab* styleTab_;
MapWidget * mapWidget_; MapWidget* mapWidget_;
//actions // actions
QList<QAction *> exportAsActs; QList<QAction*> exportAsActs;
QActionGroup *toolsGroup; QActionGroup* toolsGroup;
QAction *zoomAllAct; QAction* zoomAllAct;
QAction *zoomBoxAct; QAction* zoomBoxAct;
QAction *panAct; QAction* panAct;
QAction *infoAct; QAction* infoAct;
QAction *openAct; QAction* openAct;
QAction *saveAct; QAction* saveAct;
QAction *printAct; QAction* printAct;
QAction *exitAct; QAction* exitAct;
QAction *aboutAct; QAction* aboutAct;
QAction *panLeftAct; QAction* panLeftAct;
QAction *panRightAct; QAction* panRightAct;
QAction *panUpAct; QAction* panUpAct;
QAction *panDownAct; QAction* panDownAct;
QAction *reloadAct; QAction* reloadAct;
QAction *layerInfo; QAction* layerInfo;
//toolbars // toolbars
QToolBar *fileToolBar; QToolBar* fileToolBar;
QToolBar *editToolBar; QToolBar* editToolBar;
//menus // menus
QMenu *exportMenu; QMenu* exportMenu;
QMenu *fileMenu; QMenu* fileMenu;
QMenu *helpMenu; QMenu* helpMenu;
//status bar // status bar
QStatusBar *status; QStatusBar* status;
QSlider * slider_; QSlider* slider_;
QComboBox * renderer_selector_; QComboBox* renderer_selector_;
QDoubleSpinBox * scale_factor_; QDoubleSpinBox* scale_factor_;
mapnik::box2d<double> default_extent_; mapnik::box2d<double> default_extent_;
}; };
#endif // MAINWINDOW_HPP
#endif //MAINWINDOW_HPP

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include <QtGui> #include <QtGui>
#include <boost/bind.hpp> #include <boost/bind.hpp>
@ -41,153 +40,139 @@
#include "mapwidget.hpp" #include "mapwidget.hpp"
#include "info_dialog.hpp" #include "info_dialog.hpp"
using mapnik::image_rgba8;
using mapnik::Map;
using mapnik::layer;
using mapnik::box2d; using mapnik::box2d;
using mapnik::coord2d; using mapnik::coord2d;
using mapnik::feature_kv_iterator;
using mapnik::feature_ptr; using mapnik::feature_ptr;
using mapnik::view_transform; using mapnik::image_rgba8;
using mapnik::layer;
using mapnik::Map;
using mapnik::projection; using mapnik::projection;
using mapnik::scale_denominator; using mapnik::scale_denominator;
using mapnik::feature_kv_iterator; using mapnik::view_transform;
double scales [] = {279541132.014, double scales[] = {279541132.014, 139770566.007, 69885283.0036, 34942641.5018, 17471320.7509,
139770566.007, 8735660.37545, 4367830.18772, 2183915.09386, 1091957.54693, 545978.773466,
69885283.0036, 272989.386733, 136494.693366, 68247.3466832, 34123.6733416, 17061.8366708,
34942641.5018, 8530.9183354, 4265.4591677, 2132.72958385, 1066.36479192, 533.182395962};
17471320.7509,
8735660.37545,
4367830.18772,
2183915.09386,
1091957.54693,
545978.773466,
272989.386733,
136494.693366,
68247.3466832,
34123.6733416,
17061.8366708,
8530.9183354,
4265.4591677,
2132.72958385,
1066.36479192,
533.182395962};
MapWidget::MapWidget(QWidget *parent) MapWidget::MapWidget(QWidget* parent)
: QWidget(parent), : QWidget(parent)
map_(), , map_()
selected_(1), , selected_(1)
extent_(), , extent_()
cur_tool_(ZoomToBox), , cur_tool_(ZoomToBox)
start_x_(0), , start_x_(0)
start_y_(0), , start_y_(0)
end_x_(0), , end_x_(0)
end_y_(0), , end_y_(0)
drag_(false), , drag_(false)
first_(true), , first_(true)
pen_(QColor(0,0,255,96)), , pen_(QColor(0, 0, 255, 96))
selectedLayer_(-1), , selectedLayer_(-1)
scaling_factor_(1.0), , scaling_factor_(1.0)
cur_renderer_(AGG) , cur_renderer_(AGG)
{ {
pen_.setWidth(3); pen_.setWidth(3);
pen_.setCapStyle(Qt::RoundCap); pen_.setCapStyle(Qt::RoundCap);
pen_.setJoinStyle(Qt::RoundJoin); pen_.setJoinStyle(Qt::RoundJoin);
} }
void MapWidget::setTool(eTool tool) void MapWidget::setTool(eTool tool)
{ {
cur_tool_=tool; cur_tool_ = tool;
} }
void MapWidget::paintEvent(QPaintEvent*) void MapWidget::paintEvent(QPaintEvent*)
{ {
QPainter painter(this); QPainter painter(this);
if (drag_) if (drag_)
{ {
if (cur_tool_ == ZoomToBox) if (cur_tool_ == ZoomToBox)
{ {
unsigned width = end_x_-start_x_; unsigned width = end_x_ - start_x_;
unsigned height = end_y_-start_y_; unsigned height = end_y_ - start_y_;
painter.drawPixmap(QPoint(0, 0),pix_); painter.drawPixmap(QPoint(0, 0), pix_);
painter.setPen(pen_); painter.setPen(pen_);
painter.setBrush(QColor(200,200,255,128)); painter.setBrush(QColor(200, 200, 255, 128));
painter.drawRect(start_x_,start_y_,width,height); painter.drawRect(start_x_, start_y_, width, height);
} }
else if (cur_tool_ == Pan) else if (cur_tool_ == Pan)
{ {
int dx = end_x_-start_x_; int dx = end_x_ - start_x_;
int dy = end_y_-start_y_; int dy = end_y_ - start_y_;
painter.setBrush(QColor(200,200,200,128)); painter.setBrush(QColor(200, 200, 200, 128));
painter.drawRect(0,0,width(),height()); painter.drawRect(0, 0, width(), height());
painter.drawPixmap(QPoint(dx,dy),pix_); painter.drawPixmap(QPoint(dx, dy), pix_);
} }
} }
else else
{ {
painter.drawPixmap(QPoint(0, 0),pix_); painter.drawPixmap(QPoint(0, 0), pix_);
} }
painter.end(); painter.end();
} }
void MapWidget::resizeEvent(QResizeEvent * ev) void MapWidget::resizeEvent(QResizeEvent* ev)
{ {
if (map_) if (map_)
{ {
map_->resize(ev->size().width(),ev->size().height()); map_->resize(ev->size().width(), ev->size().height());
updateMap(); updateMap();
} }
} }
void MapWidget::mousePressEvent(QMouseEvent* e) void MapWidget::mousePressEvent(QMouseEvent* e)
{ {
if (e->button()==Qt::LeftButton) if (e->button() == Qt::LeftButton)
{ {
if (cur_tool_ == ZoomToBox || cur_tool_==Pan) if (cur_tool_ == ZoomToBox || cur_tool_ == Pan)
{ {
start_x_ = e->x(); start_x_ = e->x();
start_y_ = e->y(); start_y_ = e->y();
drag_=true; drag_ = true;
} }
else if (cur_tool_==Info) else if (cur_tool_ == Info)
{ {
if (map_) if (map_)
{
QVector<QPair<QString,QString> > info;
projection map_proj(map_->srs(), true); // map projection
double scale_denom = scale_denominator(map_->scale(),map_proj.is_geographic());
view_transform t(map_->width(),map_->height(),map_->get_current_extent());
for (unsigned index = 0; index < map_->layer_count();++index)
{ {
if (int(index) != selectedLayer_) continue; QVector<QPair<QString, QString>> info;
layer & layer = map_->layers()[index]; projection map_proj(map_->srs(), true); // map projection
if (!layer.visible(scale_denom)) continue; double scale_denom = scale_denominator(map_->scale(), map_proj.is_geographic());
std::string name = layer.name(); view_transform t(map_->width(), map_->height(), map_->get_current_extent());
double x = e->x();
double y = e->y();
std::cout << "query at " << x << "," << y << "\n";
projection layer_proj(layer.srs(), true);
mapnik::proj_transform prj_trans(map_proj,layer_proj);
//std::auto_ptr<mapnik::memory_datasource> data(new mapnik::memory_datasource);
mapnik::featureset_ptr fs = map_->query_map_point(index,x,y);
if (fs) for (unsigned index = 0; index < map_->layer_count(); ++index)
{ {
feature_ptr feat = fs->next(); if (int(index) != selectedLayer_)
if (feat) continue;
{
feature_kv_iterator itr(*feat,true);
feature_kv_iterator end(*feat);
for ( ;itr!=end; ++itr) layer& layer = map_->layers()[index];
{ if (!layer.visible(scale_denom))
info.push_back(QPair<QString,QString>(QString(std::get<0>(*itr).c_str()), continue;
std::get<1>(*itr).to_string().c_str())); std::string name = layer.name();
} double x = e->x();
double y = e->y();
std::cout << "query at " << x << "," << y << "\n";
projection layer_proj(layer.srs(), true);
mapnik::proj_transform prj_trans(map_proj, layer_proj);
// std::auto_ptr<mapnik::memory_datasource> data(new mapnik::memory_datasource);
mapnik::featureset_ptr fs = map_->query_map_point(index, x, y);
if (fs)
{
feature_ptr feat = fs->next();
if (feat)
{
feature_kv_iterator itr(*feat, true);
feature_kv_iterator end(*feat);
for (; itr != end; ++itr)
{
info.push_back(QPair<QString, QString>(QString(std::get<0>(*itr).c_str()),
std::get<1>(*itr).to_string().c_str()));
}
#if 0 // #if 0 //
using path_type = mapnik::transform_path_adapter<mapnik::view_transform,mapnik::vertex_adapter>; using path_type = mapnik::transform_path_adapter<mapnik::view_transform,mapnik::vertex_adapter>;
@ -219,288 +204,285 @@ void MapWidget::mousePressEvent(QMouseEvent* e)
} }
} }
#endif #endif
} }
} }
if (info.size() > 0) if (info.size() > 0)
{ {
info_dialog info_dlg(info,this); info_dialog info_dlg(info, this);
info_dlg.exec(); info_dlg.exec();
break; break;
} }
}
// remove annotation layer
map_->layers().erase(
remove_if(map_->layers().begin(), map_->layers().end(), bind(&layer::name, _1) == "*annotations*"),
map_->layers().end());
} }
}
// remove annotation layer }
map_->layers().erase(remove_if(map_->layers().begin(), else if (e->button() == Qt::RightButton)
map_->layers().end(), {
bind(&layer::name,_1) == "*annotations*") // updateMap();
, map_->layers().end()); }
}
}
}
else if (e->button()==Qt::RightButton)
{
//updateMap();
}
} }
void MapWidget::mouseMoveEvent(QMouseEvent* e) void MapWidget::mouseMoveEvent(QMouseEvent* e)
{ {
if (cur_tool_ == ZoomToBox || cur_tool_==Pan) if (cur_tool_ == ZoomToBox || cur_tool_ == Pan)
{ {
end_x_ = e->x(); end_x_ = e->x();
end_y_ = e->y(); end_y_ = e->y();
update(); update();
} }
} }
void MapWidget::mouseReleaseEvent(QMouseEvent* e) void MapWidget::mouseReleaseEvent(QMouseEvent* e)
{ {
if (e->button()==Qt::LeftButton) if (e->button() == Qt::LeftButton)
{ {
end_x_ = e->x(); end_x_ = e->x();
end_y_ = e->y(); end_y_ = e->y();
if (cur_tool_ == ZoomToBox) if (cur_tool_ == ZoomToBox)
{ {
drag_=false; drag_ = false;
if (map_) if (map_)
{ {
view_transform t(map_->width(),map_->height(),map_->get_current_extent()); view_transform t(map_->width(), map_->height(), map_->get_current_extent());
box2d<double> box = t.backward(box2d<double>(start_x_,start_y_,end_x_,end_y_)); box2d<double> box = t.backward(box2d<double>(start_x_, start_y_, end_x_, end_y_));
map_->zoom_to_box(box); map_->zoom_to_box(box);
updateMap(); updateMap();
} }
} }
else if (cur_tool_==Pan) else if (cur_tool_ == Pan)
{ {
drag_=false; drag_ = false;
if (map_) if (map_)
{ {
int cx = int(0.5 * map_->width()); int cx = int(0.5 * map_->width());
int cy = int(0.5 * map_->height()); int cy = int(0.5 * map_->height());
int dx = end_x_ - start_x_; int dx = end_x_ - start_x_;
int dy = end_y_ - start_y_; int dy = end_y_ - start_y_;
map_->pan(cx - dx ,cy - dy); map_->pan(cx - dx, cy - dy);
updateMap(); updateMap();
} }
} }
} }
} }
void MapWidget::wheelEvent(QWheelEvent* e) void MapWidget::wheelEvent(QWheelEvent* e)
{ {
if (!map_) if (!map_)
{ {
return; return;
} }
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QPointF corner(map_->width(), map_->height()); QPointF corner(map_->width(), map_->height());
QPointF zoomCoords; QPointF zoomCoords;
double zoom; double zoom;
if (e->angleDelta().y() > 0) if (e->angleDelta().y() > 0)
{ {
zoom = 0.5; zoom = 0.5;
QPointF center = corner / 2; QPointF center = corner / 2;
QPointF delta = e->position() - center; QPointF delta = e->position() - center;
zoomCoords = zoom * delta + center; zoomCoords = zoom * delta + center;
} }
else else
{ {
zoom = 2.0; zoom = 2.0;
zoomCoords = corner - e->position(); zoomCoords = corner - e->position();
} }
#else #else
QPoint corner(map_->width(), map_->height()); QPoint corner(map_->width(), map_->height());
QPoint zoomCoords; QPoint zoomCoords;
double zoom; double zoom;
if (e->delta() > 0) if (e->delta() > 0)
{ {
zoom = 0.5; zoom = 0.5;
QPoint center = corner / 2; QPoint center = corner / 2;
QPoint delta = e->pos() - center; QPoint delta = e->pos() - center;
zoomCoords = zoom * delta + center; zoomCoords = zoom * delta + center;
} }
else else
{ {
zoom = 2.0; zoom = 2.0;
zoomCoords = corner - e->pos(); zoomCoords = corner - e->pos();
} }
#endif #endif
map_->pan_and_zoom(zoomCoords.x(), zoomCoords.y(), zoom); map_->pan_and_zoom(zoomCoords.x(), zoomCoords.y(), zoom);
updateMap(); updateMap();
} }
void MapWidget::keyPressEvent(QKeyEvent *e) void MapWidget::keyPressEvent(QKeyEvent* e)
{ {
std::cout << "key pressed:"<< e->key()<<"\n"; std::cout << "key pressed:" << e->key() << "\n";
switch (e->key()) { switch (e->key())
case Qt::Key_Minus: {
zoomOut(); case Qt::Key_Minus:
break; zoomOut();
case Qt::Key_Plus: break;
case 61: case Qt::Key_Plus:
zoomIn(); case 61:
break; zoomIn();
case 65: break;
defaultView(); case 65:
break; defaultView();
case Qt::Key_Up: break;
panUp(); case Qt::Key_Up:
break; panUp();
case Qt::Key_Down: break;
panDown(); case Qt::Key_Down:
break; panDown();
case Qt::Key_Left: break;
panLeft(); case Qt::Key_Left:
break; panLeft();
case Qt::Key_Right: break;
panRight(); case Qt::Key_Right:
break; panRight();
case 49: break;
zoomToLevel(10); case 49:
break; zoomToLevel(10);
case 50: break;
zoomToLevel(11); case 50:
break; zoomToLevel(11);
case 51: break;
zoomToLevel(12); case 51:
break; zoomToLevel(12);
case 52: break;
zoomToLevel(13); case 52:
break; zoomToLevel(13);
case 53: break;
zoomToLevel(14); case 53:
break; zoomToLevel(14);
case 54: break;
zoomToLevel(15); case 54:
break; zoomToLevel(15);
case 55: break;
zoomToLevel(16); case 55:
break; zoomToLevel(16);
case 56: break;
zoomToLevel(17); case 56:
break; zoomToLevel(17);
case 57: break;
zoomToLevel(18); case 57:
break; zoomToLevel(18);
default: break;
QWidget::keyPressEvent(e); default:
} QWidget::keyPressEvent(e);
}
} }
void MapWidget::zoomToBox(mapnik::box2d<double> const& bbox) void MapWidget::zoomToBox(mapnik::box2d<double> const& bbox)
{ {
if (map_) if (map_)
{ {
map_->zoom_to_box(bbox); map_->zoom_to_box(bbox);
updateMap(); updateMap();
} }
} }
void MapWidget::defaultView() void MapWidget::defaultView()
{ {
if (map_) if (map_)
{ {
map_->resize(width(),height()); map_->resize(width(), height());
map_->zoom_all(); map_->zoom_all();
updateMap(); updateMap();
} }
} }
void MapWidget::zoomIn() void MapWidget::zoomIn()
{ {
if (map_) if (map_)
{ {
map_->zoom(0.5); map_->zoom(0.5);
updateMap(); updateMap();
} }
} }
void MapWidget::zoomOut() void MapWidget::zoomOut()
{ {
if (map_) if (map_)
{ {
map_->zoom(2.0); map_->zoom(2.0);
updateMap(); updateMap();
} }
} }
void MapWidget::panUp() void MapWidget::panUp()
{ {
if (map_) if (map_)
{ {
double cx = 0.5*map_->width(); double cx = 0.5 * map_->width();
double cy = 0.5*map_->height(); double cy = 0.5 * map_->height();
map_->pan(int(cx),int(cy - cy*0.25)); map_->pan(int(cx), int(cy - cy * 0.25));
updateMap(); updateMap();
} }
} }
void MapWidget::panDown() void MapWidget::panDown()
{ {
if (map_) if (map_)
{ {
double cx = 0.5*map_->width(); double cx = 0.5 * map_->width();
double cy = 0.5*map_->height(); double cy = 0.5 * map_->height();
map_->pan(int(cx),int(cy + cy*0.25)); map_->pan(int(cx), int(cy + cy * 0.25));
updateMap(); updateMap();
} }
} }
void MapWidget::panLeft() void MapWidget::panLeft()
{ {
if (map_) if (map_)
{ {
double cx = 0.5*map_->width(); double cx = 0.5 * map_->width();
double cy = 0.5*map_->height(); double cy = 0.5 * map_->height();
map_->pan(int(cx - cx * 0.25),int(cy)); map_->pan(int(cx - cx * 0.25), int(cy));
updateMap(); updateMap();
} }
} }
void MapWidget::panRight() void MapWidget::panRight()
{ {
if (map_) if (map_)
{ {
double cx = 0.5*map_->width(); double cx = 0.5 * map_->width();
double cy = 0.5*map_->height(); double cy = 0.5 * map_->height();
map_->pan(int(cx + cx * 0.25),int(cy)); map_->pan(int(cx + cx * 0.25), int(cy));
updateMap(); updateMap();
} }
} }
void MapWidget::zoomToLevel(int level) void MapWidget::zoomToLevel(int level)
{ {
if ( map_ && level >= 0 && level < 19 ) if (map_ && level >= 0 && level < 19)
{ {
double scale_denom = scales[level]; double scale_denom = scales[level];
std::cerr << "scale denominator = " << scale_denom << "\n"; std::cerr << "scale denominator = " << scale_denom << "\n";
mapnik::box2d<double> ext = map_->get_current_extent(); mapnik::box2d<double> ext = map_->get_current_extent();
double width = static_cast<double>(map_->width()); double width = static_cast<double>(map_->width());
double height= static_cast<double>(map_->height()); double height = static_cast<double>(map_->height());
mapnik::coord2d pt = ext.center(); mapnik::coord2d pt = ext.center();
double res = scale_denom * 0.00028; double res = scale_denom * 0.00028;
mapnik::box2d<double> box(pt.x - 0.5 * width * res, mapnik::box2d<double> box(pt.x - 0.5 * width * res,
pt.y - 0.5 * height*res, pt.y - 0.5 * height * res,
pt.x + 0.5 * width * res, pt.x + 0.5 * width * res,
pt.y + 0.5 * height*res); pt.y + 0.5 * height * res);
map_->zoom_to_box(box); map_->zoom_to_box(box);
updateMap(); updateMap();
} }
} }
void MapWidget::export_to_file(unsigned ,unsigned ,std::string const&,std::string const&) void MapWidget::export_to_file(unsigned, unsigned, std::string const&, std::string const&)
{ {
//image_rgba8 image(width,height); // image_rgba8 image(width,height);
//agg_renderer renderer(map,image); // agg_renderer renderer(map,image);
//renderer.apply(); // renderer.apply();
//image.saveToFile(filename,type); // image.saveToFile(filename,type);
std::cout << "Export to file .." << std::endl; std::cout << "Export to file .." << std::endl;
} }
@ -509,47 +491,44 @@ void MapWidget::set_scaling_factor(double scaling_factor)
scaling_factor_ = scaling_factor; scaling_factor_ = scaling_factor;
} }
void render_agg(mapnik::Map const& map, double scaling_factor, QPixmap & pix) void render_agg(mapnik::Map const& map, double scaling_factor, QPixmap& pix)
{ {
unsigned width=map.width(); unsigned width = map.width();
unsigned height=map.height(); unsigned height = map.height();
image_rgba8 buf(width,height); image_rgba8 buf(width, height);
mapnik::agg_renderer<image_rgba8> ren(map,buf,scaling_factor); mapnik::agg_renderer<image_rgba8> ren(map, buf, scaling_factor);
try try
{ {
mapnik::auto_cpu_timer t(std::clog, "rendering took: "); mapnik::auto_cpu_timer t(std::clog, "rendering took: ");
ren.apply(); ren.apply();
QImage image((uchar*)buf.data(),width,height,QImage::Format_ARGB32); QImage image((uchar*)buf.data(), width, height, QImage::Format_ARGB32);
pix = QPixmap::fromImage(image.rgbSwapped()); pix = QPixmap::fromImage(image.rgbSwapped());
} }
//catch (mapnik::config_error & ex) // catch (mapnik::config_error & ex)
//{ //{
// std::cerr << ex.what() << std::endl; // std::cerr << ex.what() << std::endl;
//} // }
catch (std::exception const& ex) catch (std::exception const& ex)
{ {
std::cerr << "exception: " << ex.what() << std::endl; std::cerr << "exception: " << ex.what() << std::endl;
} } catch (...)
catch (...)
{ {
std::cerr << "Unknown exception caught!\n"; std::cerr << "Unknown exception caught!\n";
} }
} }
void render_grid(mapnik::Map const& map, double scaling_factor, QPixmap& pix)
void render_grid(mapnik::Map const& map, double scaling_factor, QPixmap & pix)
{ {
std::cerr << "Not supported" << std::endl; std::cerr << "Not supported" << std::endl;
} }
void render_cairo(mapnik::Map const& map, double scaling_factor, QPixmap& pix)
void render_cairo(mapnik::Map const& map, double scaling_factor, QPixmap & pix)
{ {
// FIXME // FIXME
#ifdef HAVE_CAIRO #ifdef HAVE_CAIRO
mapnik::cairo_surface_ptr image_surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32,map.width(),map.height()), mapnik::cairo_surface_ptr image_surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, map.width(), map.height()),
mapnik::cairo_surface_closer()); mapnik::cairo_surface_closer());
mapnik::cairo_ptr cairo = mapnik::create_context(image_surface); mapnik::cairo_ptr cairo = mapnik::create_context(image_surface);
if (cairo) if (cairo)
@ -560,16 +539,19 @@ void render_cairo(mapnik::Map const& map, double scaling_factor, QPixmap & pix)
} }
mapnik::image_rgba8 data(map.width(), map.height()); mapnik::image_rgba8 data(map.width(), map.height());
mapnik::cairo_image_to_rgba8(data, image_surface); mapnik::cairo_image_to_rgba8(data, image_surface);
QImage image((uchar*)data.bytes(),data.width(),data.height(),QImage::Format_ARGB32); QImage image((uchar*)data.bytes(), data.width(), data.height(), QImage::Format_ARGB32);
pix = QPixmap::fromImage(image.rgbSwapped()); pix = QPixmap::fromImage(image.rgbSwapped());
#endif #endif
} }
void MapWidget::updateRenderer(QString const& txt) void MapWidget::updateRenderer(QString const& txt)
{ {
if (txt == "AGG") cur_renderer_ = AGG; if (txt == "AGG")
else if (txt == "Cairo") cur_renderer_ = Cairo; cur_renderer_ = AGG;
else if (txt == "Grid") cur_renderer_ = Grid; else if (txt == "Cairo")
cur_renderer_ = Cairo;
else if (txt == "Grid")
cur_renderer_ = Grid;
std::cerr << "Update renderer called" << std::endl; std::cerr << "Update renderer called" << std::endl;
updateMap(); updateMap();
} }
@ -582,50 +564,49 @@ void MapWidget::updateScaleFactor(double scale_factor)
void MapWidget::updateMap() void MapWidget::updateMap()
{ {
if (map_) if (map_)
{ {
if (cur_renderer_== AGG) if (cur_renderer_ == AGG)
{ {
render_agg(*map_, scaling_factor_, pix_); render_agg(*map_, scaling_factor_, pix_);
} }
else if (cur_renderer_ == Cairo) else if (cur_renderer_ == Cairo)
{ {
render_cairo(*map_, scaling_factor_, pix_); render_cairo(*map_, scaling_factor_, pix_);
} }
else if (cur_renderer_ == Grid) else if (cur_renderer_ == Grid)
{ {
render_grid(*map_, scaling_factor_, pix_); render_grid(*map_, scaling_factor_, pix_);
} }
else else
{ {
std::cerr << "Unknown renderer..." << std::endl; std::cerr << "Unknown renderer..." << std::endl;
} }
try try
{ {
projection prj(map_->srs(), true); // map projection projection prj(map_->srs(), true); // map projection
box2d<double> ext = map_->get_current_extent(); box2d<double> ext = map_->get_current_extent();
double x0 = ext.minx(); double x0 = ext.minx();
double y0 = ext.miny(); double y0 = ext.miny();
double x1 = ext.maxx(); double x1 = ext.maxx();
double y1 = ext.maxy(); double y1 = ext.maxy();
double z = 0; double z = 0;
std::string dest_srs = {"epsg:4326"}; std::string dest_srs = {"epsg:4326"};
mapnik::proj_transform proj_tr(map_->srs(), dest_srs); mapnik::proj_transform proj_tr(map_->srs(), dest_srs);
proj_tr.forward(x0, y0, z); proj_tr.forward(x0, y0, z);
proj_tr.forward(x1, y1, z); proj_tr.forward(x1, y1, z);
std::cout << "MAP SIZE:" << map_->width() << "," << map_->height() << std::endl; std::cout << "MAP SIZE:" << map_->width() << "," << map_->height() << std::endl;
std::cout << "BBOX (WGS84): " << x0 << "," << y0 << "," << x1 << "," << y1 << "\n"; std::cout << "BBOX (WGS84): " << x0 << "," << y0 << "," << x1 << "," << y1 << "\n";
update(); update();
// emit signal to interested widgets // emit signal to interested widgets
emit mapViewChanged(); emit mapViewChanged();
} } catch (...)
catch (...) {
{ std::cerr << "Unknown exception caught!\n";
std::cerr << "Unknown exception caught!\n"; }
} }
}
} }
std::shared_ptr<Map> MapWidget::getMap() std::shared_ptr<Map> MapWidget::getMap()
@ -638,7 +619,6 @@ void MapWidget::setMap(std::shared_ptr<Map> map)
map_ = map; map_ = map;
} }
void MapWidget::layerSelected(int index) void MapWidget::layerSelected(int index)
{ {
selectedLayer_ = index; selectedLayer_ = index;

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef MAP_WIDGET_HPP #ifndef MAP_WIDGET_HPP
#define MAP_WIDGET_HPP #define MAP_WIDGET_HPP
@ -30,7 +29,6 @@
#include <string> #include <string>
#include <memory> #include <memory>
#ifndef Q_MOC_RUN #ifndef Q_MOC_RUN
#include <mapnik/map.hpp> #include <mapnik/map.hpp>
#endif #endif
@ -39,22 +37,16 @@ class MapWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
enum eTool enum eTool {
{
ZoomToBox = 1, ZoomToBox = 1,
Pan, Pan,
Info, Info,
}; };
enum eRenderer enum eRenderer { AGG, Cairo, Grid };
{
AGG,
Cairo,
Grid
};
private: private:
std::shared_ptr<mapnik::Map> map_; std::shared_ptr<mapnik::Map> map_;
int selected_; int selected_;
QPixmap pix_; QPixmap pix_;
@ -70,11 +62,12 @@ private:
int selectedLayer_; int selectedLayer_;
double scaling_factor_; double scaling_factor_;
eRenderer cur_renderer_; eRenderer cur_renderer_;
public:
MapWidget(QWidget *parent=0); public:
MapWidget(QWidget* parent = 0);
void setTool(eTool tool); void setTool(eTool tool);
std::shared_ptr<mapnik::Map> getMap(); std::shared_ptr<mapnik::Map> getMap();
inline QPixmap const& pixmap() const { return pix_;} inline QPixmap const& pixmap() const { return pix_; }
void setMap(std::shared_ptr<mapnik::Map> map); void setMap(std::shared_ptr<mapnik::Map> map);
void defaultView(); void defaultView();
void zoomToBox(mapnik::box2d<double> const& box); void zoomToBox(mapnik::box2d<double> const& box);
@ -85,26 +78,24 @@ public:
void panUp(); void panUp();
void panDown(); void panDown();
void set_scaling_factor(double); void set_scaling_factor(double);
public slots: public slots:
void zoomToLevel(int level); void zoomToLevel(int level);
void updateMap(); void updateMap();
void layerSelected(int); void layerSelected(int);
void updateRenderer(QString const& txt); void updateRenderer(QString const& txt);
void updateScaleFactor(double scale_factor); void updateScaleFactor(double scale_factor);
signals: signals:
void mapViewChanged(); void mapViewChanged();
protected:
protected:
void paintEvent(QPaintEvent* ev); void paintEvent(QPaintEvent* ev);
void resizeEvent(QResizeEvent* ev); void resizeEvent(QResizeEvent* ev);
void mousePressEvent(QMouseEvent* e); void mousePressEvent(QMouseEvent* e);
void mouseMoveEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e);
void mouseReleaseEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent* e);
void wheelEvent(QWheelEvent* e); void wheelEvent(QWheelEvent* e);
void keyPressEvent(QKeyEvent *e); void keyPressEvent(QKeyEvent* e);
void export_to_file(unsigned width, void export_to_file(unsigned width, unsigned height, std::string const& filename, std::string const& type);
unsigned height,
std::string const& filename,
std::string const& type);
}; };
#endif // MAP_WIDGET_HPP #endif // MAP_WIDGET_HPP

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#include "styles_model.hpp" #include "styles_model.hpp"
#include <mapnik/config.hpp> #include <mapnik/config.hpp>
#include <mapnik/util/variant.hpp> #include <mapnik/util/variant.hpp>
@ -39,70 +38,50 @@ class node : private mapnik::util::noncopyable
{ {
struct node_base struct node_base
{ {
virtual QString name() const=0; virtual QString name() const = 0;
virtual QIcon icon() const=0; virtual QIcon icon() const = 0;
virtual ~node_base() {} virtual ~node_base() {}
}; };
template <typename T> template<typename T>
struct wrap : public node_base struct wrap : public node_base
{ {
wrap(T const& obj) wrap(T const& obj)
: obj_(obj) {} : obj_(obj)
{}
~wrap() {} ~wrap() {}
QString name () const QString name() const { return obj_.name(); }
{
return obj_.name();
}
QIcon icon() const QIcon icon() const { return obj_.icon(); }
{
return obj_.icon();
}
T obj_; T obj_;
}; };
public: public:
template <typename T> template<typename T>
node ( T const& obj, node * parent=0) node(T const& obj, node* parent = 0)
: impl_(new wrap<T>(obj)), : impl_(new wrap<T>(obj))
parent_(parent) , parent_(parent)
{} {}
QString name() const QString name() const { return impl_->name(); }
{
return impl_->name();
}
QIcon icon() const QIcon icon() const { return impl_->icon(); }
{
return impl_->icon();
}
unsigned num_children() const unsigned num_children() const { return children_.count(); }
{
return children_.count();
}
node * child(unsigned row) const node* child(unsigned row) const { return children_.value(row); }
{
return children_.value(row);
}
node * parent() const node* parent() const { return parent_; }
{
return parent_;
}
node * add_child(node * child) node* add_child(node* child)
{ {
children_.push_back(child); children_.push_back(child);
return child; return child;
} }
int row () const int row() const
{ {
if (parent_) if (parent_)
return parent_->children_.indexOf(const_cast<node*>(this)); return parent_->children_.indexOf(const_cast<node*>(this));
@ -110,94 +89,90 @@ public:
return 0; return 0;
} }
~node() ~node() { qDeleteAll(children_); }
{
qDeleteAll(children_);
}
private: private:
const std::unique_ptr<node_base> impl_; const std::unique_ptr<node_base> impl_;
QList<node*> children_; QList<node*> children_;
node * parent_; node* parent_;
}; };
struct symbolizer_info struct symbolizer_info
{ {
QString operator() (mapnik::point_symbolizer const& sym) const QString operator()(mapnik::point_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("PointSymbolizer"); return QString("PointSymbolizer");
} }
QString operator() (mapnik::line_symbolizer const& sym) const QString operator()(mapnik::line_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("LineSymbolizer"); return QString("LineSymbolizer");
} }
QString operator() (mapnik::line_pattern_symbolizer const& sym) const QString operator()(mapnik::line_pattern_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("LinePatternSymbolizer"); return QString("LinePatternSymbolizer");
} }
QString operator() (mapnik::polygon_symbolizer const& sym) const QString operator()(mapnik::polygon_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("PolygonSymbolizer"); return QString("PolygonSymbolizer");
} }
QString operator() (mapnik::polygon_pattern_symbolizer const& sym) const QString operator()(mapnik::polygon_pattern_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("PolygonSymbolizer"); return QString("PolygonSymbolizer");
} }
QString operator() (mapnik::text_symbolizer const& sym) const QString operator()(mapnik::text_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("TextSymbolizer"); return QString("TextSymbolizer");
} }
QString operator() (mapnik::shield_symbolizer const& sym) const QString operator()(mapnik::shield_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("ShieldSymbolizer"); return QString("ShieldSymbolizer");
} }
QString operator() (mapnik::markers_symbolizer const& sym) const QString operator()(mapnik::markers_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("MarkersSymbolizer"); return QString("MarkersSymbolizer");
} }
QString operator() (mapnik::building_symbolizer const& sym) const QString operator()(mapnik::building_symbolizer const& sym) const
{ {
boost::ignore_unused_variable_warning(sym); boost::ignore_unused_variable_warning(sym);
return QString("BuildingSymbolizer"); return QString("BuildingSymbolizer");
} }
template <typename T> template<typename T>
QString operator() (T const& ) const QString operator()(T const&) const
{ {
return QString ("FIXME"); return QString("FIXME");
} }
}; };
struct symbolizer_icon struct symbolizer_icon
{ {
QIcon operator() (mapnik::polygon_symbolizer const& sym) const QIcon operator()(mapnik::polygon_symbolizer const& sym) const
{ {
QPixmap pix(16,16); QPixmap pix(16, 16);
QPainter painter(&pix); QPainter painter(&pix);
mapnik::color const& fill = mapnik::get<mapnik::color>(sym, mapnik::keys::fill); mapnik::color const& fill = mapnik::get<mapnik::color>(sym, mapnik::keys::fill);
QBrush brush(QColor(fill.red(),fill.green(),fill.blue(),fill.alpha())); QBrush brush(QColor(fill.red(), fill.green(), fill.blue(), fill.alpha()));
painter.fillRect(0, 0, 16, 16, brush); painter.fillRect(0, 0, 16, 16, brush);
return QIcon(pix); return QIcon(pix);
} }
QIcon operator() (mapnik::point_symbolizer const& sym) const QIcon operator()(mapnik::point_symbolizer const& sym) const
{ {
// FIXME! // FIXME!
/* /*
@ -212,55 +187,57 @@ struct symbolizer_icon
*/ */
return QIcon(); return QIcon();
} }
QIcon operator() (mapnik::line_symbolizer const& sym) const QIcon operator()(mapnik::line_symbolizer const& sym) const
{ {
QPixmap pix(48,16); QPixmap pix(48, 16);
pix.fill(); pix.fill();
QPainter painter(&pix); QPainter painter(&pix);
//mapnik::stroke const& strk = sym.get_stroke(); // mapnik::stroke const& strk = sym.get_stroke();
mapnik::color const& col = mapnik::get<mapnik::color>(sym, mapnik::keys::stroke); mapnik::color const& col = mapnik::get<mapnik::color>(sym, mapnik::keys::stroke);
QPen pen(QColor(col.red(),col.green(),col.blue(),col.alpha())); QPen pen(QColor(col.red(), col.green(), col.blue(), col.alpha()));
pen.setWidth(mapnik::get<double>(sym, mapnik::keys::width)); pen.setWidth(mapnik::get<double>(sym, mapnik::keys::width));
painter.setPen(pen); painter.setPen(pen);
painter.drawLine(0,7,47,7); painter.drawLine(0, 7, 47, 7);
//painter.drawLine(7,15,12,0); // painter.drawLine(7,15,12,0);
//painter.drawLine(12,0,8,15); // painter.drawLine(12,0,8,15);
return QIcon(pix); return QIcon(pix);
} }
template <typename T> template<typename T>
QIcon operator() (T const& ) const QIcon operator()(T const&) const
{ {
return QIcon (":/images/filter.png"); return QIcon(":/images/filter.png");
} }
}; };
class symbolizer_node class symbolizer_node
{ {
public: public:
symbolizer_node(mapnik::symbolizer const & sym) symbolizer_node(mapnik::symbolizer const& sym)
: sym_(sym) {} : sym_(sym)
~symbolizer_node(){} {}
~symbolizer_node() {}
QString name() const QString name() const
{ {
//return QString("Symbolizer:fixme"); // return QString("Symbolizer:fixme");
return mapnik::util::apply_visitor(symbolizer_info(),sym_); return mapnik::util::apply_visitor(symbolizer_info(), sym_);
} }
QIcon icon() const QIcon icon() const
{ {
return mapnik::util::apply_visitor(symbolizer_icon(),sym_);//QIcon(":/images/filter.png"); return mapnik::util::apply_visitor(symbolizer_icon(), sym_); // QIcon(":/images/filter.png");
} }
mapnik::symbolizer const& sym_; mapnik::symbolizer const& sym_;
}; };
class rule_node class rule_node
{ {
public: public:
rule_node(QString name,mapnik::rule const & r) rule_node(QString name, mapnik::rule const& r)
: name_(name), : name_(name)
rule_(r) {} , rule_(r)
{}
~rule_node() {} ~rule_node() {}
QString name() const QString name() const
{ {
@ -268,81 +245,68 @@ public:
return QString(mapnik::to_expression_string(*filter).c_str()); return QString(mapnik::to_expression_string(*filter).c_str());
} }
QIcon icon() const QIcon icon() const { return QIcon(":/images/filter.png"); }
{
return QIcon(":/images/filter.png");
}
private: private:
QString name_; QString name_;
mapnik::rule const& rule_; mapnik::rule const& rule_;
}; };
class style_node class style_node
{ {
public: public:
style_node(QString name, mapnik::feature_type_style const& style) style_node(QString name, mapnik::feature_type_style const& style)
: name_(name), : name_(name)
style_(style) {} , style_(style)
{}
~style_node() {} ~style_node() {}
QString name() const QString name() const { return name_; }
{
return name_;
}
QIcon icon() const QIcon icon() const { return QIcon(":/images/style.png"); }
{
return QIcon(":/images/style.png");
}
private: private:
QString name_; QString name_;
mapnik::feature_type_style const& style_; mapnik::feature_type_style const& style_;
}; };
class map_node class map_node
{ {
public: public:
explicit map_node(std::shared_ptr<mapnik::Map> map) explicit map_node(std::shared_ptr<mapnik::Map> map)
: map_(map) {} : map_(map)
{}
~map_node() {} ~map_node() {}
QString name() const QString name() const { return QString("Map"); }
{
return QString("Map");
}
QIcon icon() const QIcon icon() const { return QIcon(":/images/map.png"); }
{
return QIcon(":/images/map.png");
}
private: private:
std::shared_ptr<mapnik::Map> map_; std::shared_ptr<mapnik::Map> map_;
}; };
StyleModel::StyleModel(std::shared_ptr<mapnik::Map> map, QObject * parent) StyleModel::StyleModel(std::shared_ptr<mapnik::Map> map, QObject* parent)
: QAbstractItemModel(parent), : QAbstractItemModel(parent)
root_(new node(map_node(map))) , root_(new node(map_node(map)))
{ {
using style_type = std::map<std::string,mapnik::feature_type_style>; using style_type = std::map<std::string, mapnik::feature_type_style>;
style_type const & styles = map->styles(); style_type const& styles = map->styles();
style_type::const_iterator itr = styles.begin(); style_type::const_iterator itr = styles.begin();
style_type::const_iterator end = styles.end(); style_type::const_iterator end = styles.end();
for (; itr != end; ++itr) for (; itr != end; ++itr)
{ {
node * style_n = root_->add_child(new node(style_node(QString(itr->first.c_str()),itr->second),root_.get())); node* style_n = root_->add_child(new node(style_node(QString(itr->first.c_str()), itr->second), root_.get()));
mapnik::rules const& rules = itr->second.get_rules(); mapnik::rules const& rules = itr->second.get_rules();
mapnik::rules::const_iterator itr2 = rules.begin(); mapnik::rules::const_iterator itr2 = rules.begin();
for ( ; itr2 != rules.end();++itr2) for (; itr2 != rules.end(); ++itr2)
{ {
node* rule_n = style_n->add_child(new node(rule_node(QString("Rule"),*itr2),style_n)); node* rule_n = style_n->add_child(new node(rule_node(QString("Rule"), *itr2), style_n));
mapnik::rule::symbolizers::const_iterator itr3 = (*itr2).begin(); mapnik::rule::symbolizers::const_iterator itr3 = (*itr2).begin();
for ( ; itr3 !=itr2->end();++itr3) for (; itr3 != itr2->end(); ++itr3)
{ {
rule_n->add_child(new node(symbolizer_node(*itr3),rule_n)); rule_n->add_child(new node(symbolizer_node(*itr3), rule_n));
} }
} }
} }
@ -351,38 +315,39 @@ StyleModel::StyleModel(std::shared_ptr<mapnik::Map> map, QObject * parent)
StyleModel::~StyleModel() {} StyleModel::~StyleModel() {}
// interface // interface
QModelIndex StyleModel::index (int row, int col, QModelIndex const& parent) const QModelIndex StyleModel::index(int row, int col, QModelIndex const& parent) const
{ {
// qDebug("index() row=%d col=%d parent::internalId() = %lld", row,col,parent.internalId()); // qDebug("index() row=%d col=%d parent::internalId() = %lld", row,col,parent.internalId());
node * parent_node; node* parent_node;
if (!parent.isValid()) if (!parent.isValid())
parent_node = root_.get(); parent_node = root_.get();
else else
parent_node = static_cast<node*>(parent.internalPointer()); parent_node = static_cast<node*>(parent.internalPointer());
node * child_node = parent_node->child(row); node* child_node = parent_node->child(row);
if (child_node) if (child_node)
return createIndex(row,col,child_node); return createIndex(row, col, child_node);
else else
return QModelIndex(); return QModelIndex();
} }
QModelIndex StyleModel::parent (QModelIndex const& index) const QModelIndex StyleModel::parent(QModelIndex const& index) const
{ {
node * child_node = static_cast<node*>(index.internalPointer()); node* child_node = static_cast<node*>(index.internalPointer());
node * parent_node = child_node->parent(); node* parent_node = child_node->parent();
if (parent_node == root_.get()) if (parent_node == root_.get())
return QModelIndex(); return QModelIndex();
return createIndex(parent_node->row(),0,parent_node); return createIndex(parent_node->row(), 0, parent_node);
} }
int StyleModel::rowCount(QModelIndex const& parent) const int StyleModel::rowCount(QModelIndex const& parent) const
{ {
//qDebug("rowCount"); // qDebug("rowCount");
node * parent_node; node* parent_node;
if (parent.column() > 0) return 0; if (parent.column() > 0)
return 0;
if (!parent.isValid()) if (!parent.isValid())
parent_node = root_.get(); parent_node = root_.get();
else else
@ -390,25 +355,24 @@ int StyleModel::rowCount(QModelIndex const& parent) const
return parent_node->num_children(); return parent_node->num_children();
} }
int StyleModel::columnCount( QModelIndex const&) const int StyleModel::columnCount(QModelIndex const&) const
{ {
return 1; return 1;
} }
QVariant StyleModel::data(const QModelIndex & index, int role) const QVariant StyleModel::data(const QModelIndex& index, int role) const
{ {
//qDebug("data index::internalId() = %lld", index.internalId()); // qDebug("data index::internalId() = %lld", index.internalId());
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
node * cur_node = static_cast<node*>(index.internalPointer()); node* cur_node = static_cast<node*>(index.internalPointer());
if (cur_node) if (cur_node)
{ {
if (role == Qt::DisplayRole) if (role == Qt::DisplayRole)
{ {
return QVariant(cur_node->name()); return QVariant(cur_node->name());
} }
else if ( role == Qt::DecorationRole) else if (role == Qt::DecorationRole)
{ {
return cur_node->icon(); return cur_node->icon();
} }

View file

@ -17,7 +17,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
#ifndef STYLE_MODEL_HPP #ifndef STYLE_MODEL_HPP
#define STYLE_MODEL_HPP #define STYLE_MODEL_HPP
@ -27,24 +26,23 @@
#include <mapnik/map.hpp> #include <mapnik/map.hpp>
#endif #endif
class node; class node;
class StyleModel : public QAbstractItemModel class StyleModel : public QAbstractItemModel
{ {
Q_OBJECT Q_OBJECT
public: public:
StyleModel(std::shared_ptr<mapnik::Map> map, QObject * parent=0); StyleModel(std::shared_ptr<mapnik::Map> map, QObject* parent = 0);
~StyleModel(); ~StyleModel();
// interface // interface
QModelIndex index (int row, int col, QModelIndex const& parent = QModelIndex()) const; QModelIndex index(int row, int col, QModelIndex const& parent = QModelIndex()) const;
QModelIndex parent (QModelIndex const& child) const; QModelIndex parent(QModelIndex const& child) const;
int rowCount( QModelIndex const& parent = QModelIndex()) const; int rowCount(QModelIndex const& parent = QModelIndex()) const;
int columnCount( QModelIndex const& parent = QModelIndex()) const; int columnCount(QModelIndex const& parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
private:
//std::shared_ptr<mapnik::Map> map_; private:
const std::unique_ptr<node> root_; // std::shared_ptr<mapnik::Map> map_;
const std::unique_ptr<node> root_;
}; };
#endif // STYLE_MODEL_HPP #endif // STYLE_MODEL_HPP