repo
string
commit
string
message
string
diff
string
ushakov/mapsoft
71cbd42f4b71a29343e75c6626a9e28c33733da3
vmap_get_track/vmap_put_track: keep poit names with "=" prefix
diff --git a/vector/vmap3/vmap_get_track.cpp b/vector/vmap3/vmap_get_track.cpp index 8177206..6c5ba1c 100644 --- a/vector/vmap3/vmap_get_track.cpp +++ b/vector/vmap3/vmap_get_track.cpp @@ -1,74 +1,81 @@ #include <string> #include <cstring> #include "options/m_getopt.h" #include "vmap/vmap.h" #include "vmap/zn.h" #include "fig/fig.h" #include "geo_io/io.h" using namespace std; // extract objects of a single type // and write as geodata int main(int argc, char **argv){ try{ if (argc!=5) { std::cerr << "usage: vmap_get_track <class> <type> <in map> <out geodata>\n"; return 1; } std::string cl(argv[1]); int type = atoi(argv[2]); const char * ifile = argv[3]; const char * ofile = argv[4]; + bool skip_names = true; + const char wpts_pref = '='; + if (cl == "POI"){ } else if (cl == "POLYLINE") type |= zn::line_mask; else if (cl == "POLYGON") type |= zn::area_mask; else throw Err() << "unknown object class: " << cl; vmap::world V = vmap::read(ifile); geo_data data; g_waypoint_list wpts; for (auto const & o:V) { if (o.type != type) continue; if (o.size()<1) continue; - if (cl == "POI" && o[0].size()>0){ + if (cl == "POI"){ for (auto const & l:o) { for (auto const & p:l) { g_waypoint pt; pt.x = p.x; pt.y = p.y; - pt.name = o.text; + if (wpts_pref!=0 && o.text != "") pt.name = wpts_pref + o.text; + else pt.name = o.text wpts.push_back(pt); } } } else { for (auto const & l:o) { + // skip tracks with names: + if (skip_names && o.text!="") continue; g_track tr; + tr.name = o.text; for (auto const & p:l) { g_trackpoint pt; pt.x = p.x; pt.y = p.y; tr.push_back(pt); } data.trks.push_back(tr); } } } if (wpts.size()) data.wpts.push_back(wpts); io::out(ofile, data, Options()); } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; } diff --git a/vector/vmap3/vmap_put_track.cpp b/vector/vmap3/vmap_put_track.cpp index 32348db..11c23d7 100644 --- a/vector/vmap3/vmap_put_track.cpp +++ b/vector/vmap3/vmap_put_track.cpp @@ -1,92 +1,109 @@ #include <string> #include <cstring> #include "options/m_getopt.h" #include "vmap/vmap.h" #include "vmap/zn.h" #include "fig/fig.h" #include "geo_io/io.h" using namespace std; // replace objects of a single type // in a map using geodata int main(int argc, char **argv){ try{ if (argc!=5) { std::cerr << "usage: vmap_put_track <class> <type> <in geodata> <out map> \n"; return 1; } std::string cl(argv[1]); int type = atoi(argv[2]); const char * ifile = argv[3]; const char * ofile = argv[4]; + bool skip_names = true; + const char wpts_pref = '='; + if (cl == "POI"){ } else if (cl == "POLYLINE") type |= zn::line_mask; else if (cl == "POLYGON") type |= zn::area_mask; else throw Err() << "unknown object class: " << cl; vmap::world V = vmap::read(ofile); geo_data data; io::in(ifile, data); - // remove old objects: - vmap::world::iterator i=V.begin(); - while (i!=V.end()){ - if (i->type == type) { - i=V.erase(i); - continue; - } - i++; - } // put objects - if (cl == "POI"){ + split_labels(V); + + // remove old objects: + vmap::world::iterator i=V.begin(); + while (i!=V.end()){ + if (i->type != type) {i++; continue;} + i=V.erase(i); + } + for (auto const & pts:data.wpts) { for (auto const & pt:pts) { vmap::object o; dLine l; l.push_back(pt); o.push_back(l); -// o.text=pt.name; + if (wpts_pref != 0) { + if (pt.name.size()>0 pt.name[0]==wpts_pref) + o.text=pt.name.substr(1); + else + o.text=pt.name; + o.type=type; V.push_back(o); } } + join_labels(V); } else { + + // remove old objects: + vmap::world::iterator i=V.begin(); + while (i!=V.end()){ + if (i->type != type) {i++; continue;} + if (skip_names && i->text != "") {i++; continue;} + i=V.erase(i); + } + for (auto const & t:data.trks) { vmap::object o; -// o.text=t.comm; + if (!skip_names) o.text=t.comm; o.type=type; dLine l; for (auto const & pt:t) { if (pt.start && l.size()){ o.push_back(l); V.push_back(o); l.clear(); o.clear(); } l.push_back(pt); } if (l.size()){ o.push_back(l); V.push_back(o); } } } vmap::write(ofile, V); } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
92e36cccbc3319cecfbe168478d6c8435a08f1e0
styles.m4: smaller labels for 0x2c04 (monuments)
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index fb58062..4c2638a 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,584 +1,584 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam - txt: 4 0 0 40 -1 3 8 0.0000 4 + txt: 4 0 0 40 -1 3 6 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности mp: POI 0x6406 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 24 40 -1 18 6 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 pic: ldp - name: номер ледника mp: POI 0x650B 0 0 fig: 2 1 0 3 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 1 1 40 -1 3 5 0.0000 4 - name: название ледника mp: POI 0x650C 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 6 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala txt: 4 0 0 40 -1 3 6 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp txt: 4 0 0 40 -1 3 6 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 18 6 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор
ushakov/mapsoft
940eb214d992441942c2b88f785a80e365d167b5
programs/mapsoft_geofig: add options for controlling fig masks
diff --git a/programs/mapsoft_geofig.cpp b/programs/mapsoft_geofig.cpp index 1c81fc5..884ca36 100644 --- a/programs/mapsoft_geofig.cpp +++ b/programs/mapsoft_geofig.cpp @@ -1,164 +1,167 @@ #include "options/m_getopt.h" #include "geo_io/geofig.h" #include "geo_io/geo_refs.h" #include "geo_io/io.h" #include "err/err.h" using namespace std; #define OPT_CRE 1 #define OPT_ADD 2 #define OPT_DEL 4 static struct ext_option options[] = { {"geom", 1, 'g', OPT_CRE, ""}, {"datum", 1, 'd', OPT_CRE, ""}, {"proj", 1, 'p', OPT_CRE, ""}, {"lon0", 1, 'l', OPT_CRE, ""}, {"wgs_geom", 1, 'w', OPT_CRE, ""}, {"wgs_brd", 1, 'b', OPT_CRE, ""}, {"trk_brd", 1, 'b', OPT_CRE, ""}, {"nom", 1, 'N', OPT_CRE, ""}, {"google", 1, 'G', OPT_CRE, ""}, {"rscale", 1, 'r', OPT_CRE, ""}, {"mag", 1, 'm', OPT_CRE, ""}, {"swap_y", 0, 'y', OPT_CRE, "\n"}, {"verbose", 0, 'v', OPT_CRE | OPT_ADD | OPT_DEL, "be more verbose"}, {"out", 1, 'o', OPT_CRE | OPT_ADD | OPT_DEL, "set output file name"}, {"help", 0, 'h', OPT_CRE | OPT_ADD | OPT_DEL, "show help message"}, {"pod", 0, 0, OPT_CRE | OPT_ADD | OPT_DEL, "show help message as pod template"}, {"raw", 0, 'R', OPT_ADD, "add raw fig objects, without comments"}, + {"trk_mask", 1, 0, OPT_ADD, "trk mask"}, + {"wpt_mask", 1, 0, OPT_ADD, "wpt mask"}, + {"txt_mask", 1, 0, OPT_ADD, "txt mask"}, {"wpts", 0, 'w', OPT_DEL, "delete waypoints"}, {"trks", 0, 't', OPT_DEL, "delete tracks"}, {"maps", 0, 'm', OPT_DEL, "delete maps"}, {"brds", 0, 'b', OPT_DEL, "delete map borders"}, {"ref", 0, 'r', OPT_DEL, "delete fig reference"}, {0,0,0,0} }; void usage(bool pod=false){ string head = pod? "\n=head1 ":"\n"; const char * prog = "mapsoft_geofig"; cerr << prog << " -- actions with geo-referenced FIG\n" << head << "Usage:\n" << "\t" << prog << " create [<options>] (--out|-o) <output_file>\n" << "\t" << prog << " add [<options>] <file1> ... <fileN> (--out|-o) <output_file>\n" << "\t" << prog << " del [<options>] (--out|-o) <output_file>\n" ; cerr << head << "Options for create action:\n"; print_options(options, OPT_CRE, cerr, pod); cerr << head << "Options for add action:\n"; print_options(options, OPT_ADD, cerr, pod); cerr << head << "Options for del action:\n"; print_options(options, OPT_DEL, cerr, pod); } int main(int argc, char **argv){ try { if (argc<3){ usage(); return 0; } string action = argv[1]; argv++; argc--; /*****************************************/ if (action == "create"){ Options O = parse_options(&argc, &argv, options, OPT_CRE); if (O.exists("help")){ usage(); return 0;} if (O.exists("pod")) { usage(true); return 0;} if (argc>0){ cerr << "error: wrong argument: " << argv[0] << endl; return 1; } if (!O.exists("out")){ cerr << "error: no output files" << endl; return 1; } O.put<string>("dpi", "fig"); fig::fig_world F; fig::set_ref(F, mk_ref(O), Options()); fig::write(O.get<string>("out"), F); } /*****************************************/ else if (action == "add"){ vector<string> infiles; Options O = parse_options_all(&argc, &argv, options, OPT_ADD, infiles); if (O.exists("help")) {usage(); return 0;} if (O.exists("pod")) {usage(true); return 0;} if (!O.exists("out")){ cerr << "no output files.\n"; return 1; } if (O.exists("verbose")) cerr << "Reading data...\n"; geo_data world; for (vector<string>::const_iterator i = infiles.begin(); i!=infiles.end(); i++){ try {io::in(*i, world, O);} catch (Err e) {cerr << e.get_error() << endl;} } if (O.exists("verbose")){ cerr << ", Waypoint lists: " << world.wpts.size() << ", Tracks: " << world.trks.size() << "\n"; } string ofile = O.get<string>("out"); if (O.exists("verbose")) cerr << "Writing data to " << ofile << "\n"; fig::fig_world F; if (!fig::read(ofile.c_str(), F)) { cerr << "error: can't read file: " << ofile << endl; return 1; } g_map ref = fig::get_ref(F); - put_wpts(F, ref, world, O.get<bool>("raw")); - put_trks(F, ref, world, O.get<bool>("raw")); + put_wpts(F, ref, world, O); + put_trks(F, ref, world, O); return !fig::write(ofile.c_str(), F); } /*****************************************/ else if (action == "del"){ Options O = parse_options(&argc, &argv, options, OPT_DEL); if (O.exists("help")) {usage(); return 0;} if (O.exists("pod")) {usage(true); return 0;} if (argc>0){ cerr << "error: wrong argument: " << argv[0] << endl; return 1; } if (!O.exists("out")){ cerr << "error: no output files" << endl; return 1; } string ofile = O.get<string>("out"); fig::fig_world F; if (!fig::read(ofile.c_str(), F)) { cerr << "error: can't read file: " << ofile << endl; return 1; } if (O.exists("wpts")) rem_wpts(F); if (O.exists("trks")) rem_trks(F); if (O.exists("maps")) rem_maps(F); if (O.exists("brds")) rem_brds(F); if (O.exists("ref")) rem_ref(F); return !fig::write(ofile.c_str(), F); } /*****************************************/ else { usage(); return 0;} } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
8c5c85652db097848c7b535a61d56656ba0ccaf8
programs: do not build convs_gtiles (problems with boost/geometry in Altlinux)
diff --git a/programs/SConscript b/programs/SConscript index ca350a7..4301739 100644 --- a/programs/SConscript +++ b/programs/SConscript @@ -1,38 +1,39 @@ Import ('env') progs = Split(""" mapsoft_convert mapsoft_mkmap mapsoft_ref mapsoft_toxyz mapsoft_map2fig mapsoft_srtm2fig mapsoft_fig2fig mapsoft_pano mapsoft_geofig convs_pt2pt convs_map2pt convs_nom - convs_gtiles mapsoft_vmap """) +# convs_gtiles + for p in progs: env.Program(p + '.cpp') env.Install(env.bindir, Split(""" mapsoft_convert mapsoft_vmap mapsoft_geofig mapsoft_toxyz mapsoft_mkmap convs_pt2pt convs_map2pt convs_nom convs_gtiles """)) env.SymLink("mapsoft_vmap", "vmap_copy", env.bindir)
ushakov/mapsoft
7c5d73e8ac8763b0becfa88f844e6f83d819b749
misc/tif2hgt: relax aspect ratio checks (for ALOS data)
diff --git a/misc/tif2hgt/tif2hgt.cpp b/misc/tif2hgt/tif2hgt.cpp index c7e4503..c07fc7a 100644 --- a/misc/tif2hgt/tif2hgt.cpp +++ b/misc/tif2hgt/tif2hgt.cpp @@ -1,100 +1,101 @@ #include <tiffio.h> #include <cstring> #include <cstdio> #include <iostream> // convert TIFF to hgt using namespace std; +int main(int argc, char **argv){ if (argc!=3) { cerr << "Usage: tif2hgt <file.tif> <file.hgt>\n"; return 1; } TIFF* tif = TIFFOpen(argv[1], "rb"); if (!tif){ cerr << "tif2hgt: can't open file: " << argv[1] << endl; return 1; } int tiff_w, tiff_h; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiff_w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiff_h); int scan = TIFFScanlineSize(tif); int bpp = scan/tiff_w; uint8 *cbuf = (uint8 *)_TIFFmalloc(scan); int photometric=0; TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric); if (photometric != PHOTOMETRIC_MINISBLACK){ cerr << "tif2hgt: unsupported photometric type: " << photometric << endl; return 1; } if (bpp != 2){ cerr << "tif2hgt: not a 2 byte-per-pixel tiff\n"; return 1; } FILE *hgt = fopen(argv[2], "w"); if (!hgt){ cerr << "tif2hgt: can't open file: " << argv[2] << "\n"; return 1; } bool packed=false; if (tiff_h==tiff_w) { packed=false; } - else if ((tiff_h-1) == (tiff_w-1)*2){ + else if ((tiff_h-1) == (tiff_w-1)*2 || tiff_h==tiff_w*2){ packed=true; } else { - cerr << "tif2hgt: bad aspect ratio\n"; + cerr << "tif2hgt: bad aspect ratio: " << tiff_w << "x" << tiff_h << "\n"; return 1; } bool addpixel=false; if ((tiff_h%600) == 0 && (tiff_w%600==0)) { addpixel=true; } else if ((tiff_h%600) == 1 && (tiff_w%600==1)) { addpixel=false; } else { - cerr << "tif2hgt: bad size\n"; + cerr << "tif2hgt: bad size: " << tiff_w << "x" << tiff_h << "\n"; return 1; } for (int y = 0; y<tiff_h; y++){ TIFFReadScanline(tif, cbuf, y); for (int x = 0; x<tiff_w; x++){ if (packed){ char c=0; fwrite(cbuf+2*x+1, 1, 1, hgt); fwrite(cbuf+2*x, 1, 1, hgt); if (x<tiff_w-1){ fwrite(cbuf+2*x+1, 1, 1, hgt); fwrite(cbuf+2*x, 1, 1, hgt); } } else { fwrite(cbuf+2*x+1, 1, 1, hgt); fwrite(cbuf+2*x, 1, 1, hgt); } } if (addpixel){ short c=0; fwrite(&c, 1, 2, hgt); } } if (addpixel){ short c=0; for (int x = 0; x<tiff_w+1; x++) fwrite(&c, 1, 2, hgt); } fclose(hgt); _TIFFfree(cbuf); TIFFClose(tif); return 0; }
ushakov/mapsoft
7310086bf8cffb5e346b26139b47e0ab908a08e5
mapsoft_map2fig: allow custom fig masks when adding wpt/trk objects
diff --git a/core/geo_io/geofig.cpp b/core/geo_io/geofig.cpp index 087889a..d671e9c 100644 --- a/core/geo_io/geofig.cpp +++ b/core/geo_io/geofig.cpp @@ -1,403 +1,412 @@ #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_file_iterator.hpp> #include <boost/spirit/include/classic_assign_actor.hpp> #include <boost/spirit/include/classic_push_back_actor.hpp> #include <boost/spirit/include/classic_insert_at_actor.hpp> #include <sstream> #include <iomanip> #include "geofig.h" #include "geo/geo_convs.h" #include "options/options.h" #include "loaders/image_r.h" namespace fig { using namespace std; using namespace boost::spirit::classic; // Get geo-reference from fig g_map get_ref(const fig_world & w){ g_map ret; fig::fig_object brd; // border string proj="tmerc"; // tmerc is the default proj // old-style options -- to be removed for (int n=0; n<w.comment.size(); n++){ parse(w.comment[n].c_str(), str_p("proj:") >> space_p >> (*anychar_p)[assign_a(proj)]); } Options O = w.opts; if (!O.exists("map_proj")) O.put<string>("map_proj", proj); dPoint min(1e99,1e99), max(-1e99,-1e99); fig_world::const_iterator i; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)&&(i->type!=3)) continue; if (i->size()<1) continue; double x,y; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("REF") >> +space_p >> real_p[assign_a(x)] >> +space_p >> real_p[assign_a(y)]).full)){ Options O=i->opts; string key; // old-style options -- to be removed for (int n=1; n<i->comment.size(); n++){ parse(i->comment[n].c_str(), (*(anychar_p-':'-space_p))[assign_a(key)] >> *space_p >> ch_p(':') >> *space_p >> (*(anychar_p-':'-space_p))[insert_at_a(O, key)]); cerr << "Geofig: old-style option: " << key << ": " << O[key] << "\n"; } O.put<double>("x", x); O.put<double>("y", y); O.put<double>("xr", (*i)[0].x); O.put<double>("yr", (*i)[0].y); g_refpoint ref; ref.parse_from_options(O); ret.push_back(ref); continue; } if ((i->comment.size()>0)&&(i->comment[0].size()>3) && (i->comment[0].compare(0,3,"BRD")==0)) ret.border = *i; } // set lon0 if it id not set if (O.get<Proj>("map_proj") == Proj("tmerc") && !O.exists("lon0")){ O.put<double>("lon0", convs::lon2lon0(ret.center().x)); } ret.parse_from_options(O, false); // new-style options return ret; } void rem_ref(fig_world & w){ vector<string>::iterator i = w.comment.begin(); while (i!=w.comment.end()){ if (i->find("map_proj",0)==0) i=w.comment.erase(i); else i++; } fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("REF ",0)==0)) obj=w.erase(obj); else obj++; } } void set_ref(fig_world & w, const g_map & m, const Options & O){ double lon0 = m.range().x + m.range().w/2; lon0 = floor( lon0/6.0 ) * 6 + 3; lon0 = m.proj_opts.get("lon0", lon0); Enum::output_fmt=Enum::xml_fmt; // Если хочется, можно записать точки привязки в нужной проекции string pproj=O.get<string>("proj", "lonlat"); string pdatum=O.get<string>("datum", "wgs84"); convs::pt2wgs cnv(Datum(pdatum), Proj(pproj), O); for (int n=0; n<m.size(); n++){ fig::fig_object o = fig::make_object("2 1 0 4 4 7 1 -1 -1 0.000 0 1 -1 0 0 *"); o.push_back(iPoint( int(m[n].xr), int(m[n].yr) )); dPoint p(m[n]); cnv.bck(p); Enum::output_fmt=Enum::xml_fmt; ostringstream comm; comm << "REF " << fixed << p.x << " " << p.y; o.comment.push_back(comm.str()); comm.str(""); o.opts=O; w.push_back(o); } // добавим в заголовок fig-файла информацию о проекции. w.opts.insert(m.proj_opts.begin(), m.proj_opts.end()); w.opts.put("map_proj", m.map_proj); } void get_wpts(const fig_world & w, const g_map & m, geo_data & d){ // сделаем привязку convs::map2wgs cnv(m); fig_world::const_iterator i; g_waypoint_list pl; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)&&(i->type!=3)) continue; if (i->size()<1) continue; Options O=i->opts; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("WPT") >> +space_p >> (*anychar_p)[insert_at_a(O,"name")]).full)){ string key; // old-style options -- to be removed for (int n=1; n<i->comment.size(); n++){ // Удалил ограничение не позволявшее использовать ' ' и ':' в // комментариях. Тим parse(i->comment[n].c_str(), (*(anychar_p-':'-space_p))[assign_a(key)] >> *space_p >> ch_p(':') >> *space_p >> (*(anychar_p))[insert_at_a(O, key)]); } g_waypoint wp; wp.parse_from_options(O); wp.color = i->pen_color; wp.x=(*i)[0].x; wp.y=(*i)[0].y; cnv.frw(wp); pl.push_back(wp); } } d.wpts.push_back(pl); } void get_trks(const fig_world & w, const g_map & m, geo_data & d){ convs::map2wgs cnv(m); fig_world::const_iterator i; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)&&(i->type!=3)) continue; if (i->size()<1) continue; Options O=i->opts; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("TRK") >> !(+space_p >> (*anychar_p)[insert_at_a(O,"comm")])).full)){ string key; // old-style options -- to be removed for (int n=1; n<i->comment.size(); n++){ parse(i->comment[n].c_str(), (*(anychar_p-':'-space_p))[assign_a(key)] >> *space_p >> ch_p(':') >> *space_p >> (*(anychar_p-':'-space_p))[insert_at_a(O, key)]); } g_track tr; tr.parse_from_options(O); tr.color = i->pen_color; for (int n = 0; n<i->size();n++){ g_trackpoint p; p.x=(*i)[n].x; p.y=(*i)[n].y; cnv.frw(p); tr.push_back(p); } d.trks.push_back(tr); } } } void get_maps(const fig_world & w, const g_map & m, geo_data & d){ convs::map2wgs cnv(m); fig_world::const_iterator i; g_map_list maplist; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)||(i->sub_type!=5)) continue; if (i->size()<3) continue; string comm; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("MAP") >> !(+space_p >> (*anychar_p)[assign_a(comm)])).full)){ // откопируем m и заменим координаты xfig на координаты в растровом файле. // 4 точки fig-объекта соответствуют углам картинки (0,0) (W,0) (W,H) (0,H*) g_map map(m); map.comm = comm; map.file = i->image_file; iPoint WH = image_r::size(i->image_file.c_str()); double x1 = (*i)[0].x; double y1 = (*i)[0].y; double x2 = (*i)[1].x; double y2 = (*i)[1].y; double x4 = (*i)[3].x; double y4 = (*i)[3].y; double a1 = -WH.x*(y4-y1)/(x4*(y2-y1)+x1*(y4-y2)+x2*(y1-y4)); double b1 = WH.x*(x4-x1)/(x4*(y2-y1)+x1*(y4-y2)+x2*(y1-y4)); double c1 = -a1*x1-b1*y1; double a2 = -WH.y*(y2-y1)/(x2*(y4-y1)+x1*(y2-y4)+x4*(y1-y2)); double b2 = WH.y*(x2-x1)/(x2*(y4-y1)+x1*(y2-y4)+x4*(y1-y2)); double c2 = -a2*x1-b2*y1; for (int n=0; n<map.size(); n++){ double xr = map[n].xr; double yr = map[n].yr; map[n].xr = a1*xr+b1*yr+c1; map[n].yr = a2*xr+b2*yr+c2; } // граница: если есть ломаная с комментарием "BRD <имя карты>" - // сделаем границу из нее. Иначе - из размеров растрового файла. map.border.clear(); fig_world::const_iterator j; for (j=w.begin();j!=w.end();j++){ if (j->type!=2) continue; int nn = j->size(); if (nn<3) continue; // если последняя точка совпадает с первой if ((*j)[0]==(*j)[nn-1]) {nn--; if (nn<3) continue;} string brd_comm; if ((j->comment.size()>0)&&(parse(j->comment[0].c_str(), str_p("BRD") >> !(+space_p >> (*anychar_p)[assign_a(brd_comm)])).full)&&(brd_comm==comm)){ for (int n=0;n<nn;n++){ map.border.push_back(dPoint( a1*(*j)[n].x + b1*(*j)[n].y + c1, a2*(*j)[n].x + b2*(*j)[n].y + c2 )); } } } if (map.border.empty()){ map.border.push_back(dPoint(0,0)); map.border.push_back(dPoint(WH.x,0)); map.border.push_back(dPoint(WH.x,WH.y)); map.border.push_back(dPoint(0,WH.y)); } maplist.push_back(map); } } d.maps.push_back(maplist); } void rem_wpts(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("WPT ",0)==0)) obj=w.erase(obj); else obj++; } } void rem_trks(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("TRK ",0)==0)) obj=w.erase(obj); else obj++; } } void rem_maps(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("MAP ",0)==0)) obj=w.erase(obj); else obj++; } } void rem_brds(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("BRD ",0)==0)) obj=w.erase(obj); else obj++; } } #define ADDCOMM(x) {ostringstream s; s << x; f.comment.push_back(s.str());} void -put_wpts(fig_world & F, const g_map & m, const geo_data & world, bool raw){ +put_wpts(fig_world & F, const g_map & m, const geo_data & world, const Options & o){ vector<g_waypoint_list>::const_iterator wl; vector<g_waypoint>::const_iterator w; convs::map2wgs cnv(m); Enum::output_fmt=Enum::xml_fmt; + bool raw = o.get("raw", false); + std::string wpt_mask = o.get<std::string>("wpt_mask", + "2 1 0 2 0 7 6 0 -1 1 1 1 -1 0 0 *"); + std::string txt_mask = o.get<std::string>("txt_mask", + "4 0 8 5 -1 18 6 0.0000 4"); for (wl=world.wpts.begin();wl!=world.wpts.end();wl++){ for (w=wl->begin();w!=wl->end();w++){ dPoint p(w->x, w->y); cnv.bck(p); - fig::fig_object f = fig::make_object("2 1 0 2 0 7 6 0 -1 1 1 1 -1 0 0 *"); + fig::fig_object f = fig::make_object(wpt_mask); ADDCOMM("WPT " << w->name); if (!raw){ f.opts=to_options_skipdef(*w); f.opts.erase("name"); f.opts.erase("lon"); f.opts.erase("lat"); f.opts.erase("color"); } f.push_back(iPoint(int(p.x), int(p.y))); f.pen_color = w->color; F.push_back(f); - fig::fig_object ft = fig::make_object("4 0 8 5 -1 18 6 0.0000 4"); + fig::fig_object ft = fig::make_object(txt_mask); ft.push_back(iPoint(int(p.x)+30, int(p.y)+30)); ft.text = w->name; F.push_back(ft); } } } void -put_trks(fig_world & F, const g_map & m, const geo_data & world, bool raw){ +put_trks(fig_world & F, const g_map & m, const geo_data & world, const Options & o){ vector<g_track>::const_iterator tl; vector<g_trackpoint>::const_iterator t; convs::map2wgs cnv(m); Enum::output_fmt=Enum::xml_fmt; g_track def; + bool raw = o.get("raw", false); + std::string trk_mask = o.get<std::string>("trk_mask", + "2 1 0 1 1 7 7 0 -1 1 1 1 -1 0 0 *"); + for (tl=world.trks.begin();tl!=world.trks.end();tl++){ t=tl->begin(); do { vector<iPoint> pts; do{ dPoint p(t->x, t->y); cnv.bck(p); pts.push_back(iPoint(int(p.x),int(p.y))); t++; } while ((t!=tl->end())&&(!t->start)); - fig::fig_object f = fig::make_object("2 1 0 1 1 7 7 0 -1 1 1 1 -1 0 0 *"); + fig::fig_object f = fig::make_object(trk_mask); if (!raw){ f.opts=to_options_skipdef(*tl); ADDCOMM("TRK " << tl->comm); f.opts.erase("comm"); f.pen_color = tl->color; f.opts.erase("color"); } for (vector<iPoint>::const_iterator p1=pts.begin(); p1!=pts.end(); p1++) f.push_back(*p1); F.push_back(f); } while (t!=tl->end()); } } } // namespace diff --git a/core/geo_io/geofig.h b/core/geo_io/geofig.h index 8cb0fd3..eaf83e6 100644 --- a/core/geo_io/geofig.h +++ b/core/geo_io/geofig.h @@ -1,35 +1,35 @@ #ifndef GEOFIG_H #define GEOFIG_H #include <vector> #include "fig/fig.h" #include "geo/geo_data.h" namespace fig { /// get geo reference from fig_world object g_map get_ref(const fig_world & w); /// remove geo reference from fig_world object void rem_ref(fig_world & w); /// add geo reference to fig_world object void set_ref(fig_world & w, const g_map & m, const Options & o); /// get waypoints, tracks, map refrences from fig void get_wpts(const fig_world & w, const g_map & m, geo_data & d); void get_trks(const fig_world & w, const g_map & m, geo_data & d); void get_maps(const fig_world & w, const g_map & m, geo_data & d); /// remove waypoins, tracks, maps, or map borders: void rem_wpts(fig_world & w); void rem_trks(fig_world & w); void rem_maps(fig_world & w); void rem_brds(fig_world & w); /// Add waypoints or tracks from to fig /// if raw = 1, no geofig comments are added - void put_wpts(fig_world & w, const g_map & m, const geo_data & d, bool raw=true); - void put_trks(fig_world & w, const g_map & m, const geo_data & d, bool raw=true); + void put_wpts(fig_world & w, const g_map & m, const geo_data & d, const Options & o); + void put_trks(fig_world & w, const g_map & m, const geo_data & d, const Options & o); } #endif
ushakov/mapsoft
45fdd650f1fb1d30ac0682550c541bc7a3d368fc
vector/data/styles.m4: revert large labels for some point objects
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index fde6852..fb58062 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,719 +1,719 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности mp: POI 0x6406 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 24 40 -1 18 6 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 pic: ldp - name: номер ледника mp: POI 0x650B 0 0 fig: 2 1 0 3 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 1 1 40 -1 3 5 0.0000 4 - name: название ледника mp: POI 0x650C 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 - txt: 4 0 0 40 -1 3 6 0.0000 4 + txt: 4 0 0 40 -1 3 8 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 0 40 -1 3 6 0.0000 4 + txt: 4 0 0 40 -1 3 8 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 6 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 6 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala txt: 4 0 0 40 -1 3 6 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp txt: 4 0 0 40 -1 3 6 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 18 6 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор mp: POLYLINE 0x19 0 0 fig: 2 1 0 1 20 7 81 -1 -1 0.000 0 0 0 1 0 0 0 0 2.00 90.00 90.00 ocad: 819000 - name: маленькая ЛЭП mp: POLYLINE 0x1A 0 0 fig: 2 1 0 2 8947848 7 83 -1 -1 0.000 0 0 0 0 0 0 ocad: 819001 - name: пешеходный тоннель mp: POLYLINE 0x1B 0 0 fig: 2 1 0 1 3 7 77 -1 -1 0.000 0 0 0 0 0 0 ocad: 819002 - name: просека широкая mp: POLYLINE 0x1C 0 1 fig: 2 1 1 2 0 7 80 -1 -1 6.000 1 0 0 0 0 0 ocad: 819003 - name: граница стран, областей mp: POLYLINE 0x1D 0 2 fig: 2 1 0 7 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница областей, районов mp: POLYLINE 0x36 0 2 fig: 2 1 0 5 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница заповедников, парков mp: POLYLINE 0x37 0 2 fig: 2 1 0 5 2 7 91 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 819004 - name: нижний край обрыва mp: POLYLINE 0x1E 0 0 fig: 2 1 2 1 18 7 79 -1 -1 2.000 1 1 7 0 0 0 - name: пунктирная горизонталь mp: POLYLINE 0x20 0 0 fig: 2 1 1 1 HOR_COL 7 90 -1 -1 4.000 1 1 0 0 0 0 ocad: 820000 curve: 100 - name: горизонтали, бергштрихи mp: POLYLINE 0x21 0 0 fig: 2 1 0 1 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 821000 curve: 100 - name: жирная горизонталь mp: POLYLINE 0x22 0 0 fig: 2 1 0 2 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 822000 curve: 100 - name: контур леса mp: POLYLINE 0x23 0 0 fig: 2 1 2 1 12 7 96 -1 -1 2.000 1 1 0 0 0 0 ocad: 823000 - name: болото mp: POLYLINE 0x24 0 0 fig: 2 1 0 1 5269247 7 87 -1 -1 0.000 0 1 0 0 0 0 ocad: 824000 - name: овраг mp: POLYLINE 0x25 0 0 fig: 2 1 0 2 25 7 89 -1 -1 0.000 1 1 0 0 0 0 ocad: 825000 curve: 50 - name: УЖД mp: POLYLINE 0x0D 0 2 fig: 2 1 0 3 0 7 80 -1 -1 0.000 1 0 0 0 0 0 curve: 100 - name: железная дорога mp: POLYLINE 0x27 0 2 fig: 2 1 0 4 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 827000 curve: 100 - name: газопровод mp: POLYLINE 0x28 0 1 fig: 2 1 1 3 8947848 7 83 -1 -1 4.000 1 0 0 0 0 0 ocad: 828000 - name: ЛЭП mp: POLYLINE 0x29 0 1 fig: 2 1 0 3 8947848 7 83 -1 -1 0.000 1 0 0 0 0 0 ocad: 829000 - name: тропа mp: POLYLINE 0x2A 0 0 fig: 2 1 2 1 0 7 80 -1 -1 2.000 1 0 0 0 0 0 ocad: 829001 curve: 50 - name: сухая канава mp: POLYLINE 0x2B 0 0 fig: 2 1 2 1 26 7 82 -1 -1 2.000 1 1 0 0 0 0 ocad: 829002 - name: вал mp: POLYLINE 0x2C 0 0 fig: 2 1 2 3 26 7 81 -1 -1 2.000 1 1 0 0 0 0 ocad: 829003 - name: заросшая дорога mp: POLYLINE 0x2D 0 0 fig: 2 1 1 1 4210752 7 80 -1 -1 4.000 1 0 7 0 0 0 ocad: 829004 curve: 50 - name: заросшая заметная дорога (знак ММБ) mp: POLYLINE 0x2E 0 0 fig: 2 1 3 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 829004 curve: 50 - name: bad route /не использовать!/ mp: POLYLINE 0x50 0 0 fig: 2 1 1 1 4210700 7 80 -1 -1 4.000 0 0 -1 0 0 0 curve: 50 replace_by: 0x10002D - # note: 0x7F is also hardcoded in core/vmap/vmap.c name: text object mp: POLYLINE 0x7F 0 0 fig: 2 1 0 1 4 7 42 -1 -1 0.000 0 0 7 0 0 0 - # note: 0x7E is also hardcoded in core/vmap/vmap.c name: border object
ushakov/mapsoft
f6c95bde415e4c3fa93c76a8766900aea1cb0699
vector/data/styles.m4: smaller sizes of some point objects
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index 53daf38..fde6852 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,723 +1,723 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности mp: POI 0x6406 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 24 40 -1 18 7 0.0000 4 + txt: 4 0 24 40 -1 18 6 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 1 40 -1 3 7 0.0000 4 + txt: 4 0 1 40 -1 3 6 0.0000 4 pic: ldp - name: номер ледника mp: POI 0x650B 0 0 fig: 2 1 0 3 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 1 1 40 -1 3 5 0.0000 4 - name: название ледника mp: POI 0x650C 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 - txt: 4 0 0 40 -1 3 8 0.0000 4 + txt: 4 0 0 40 -1 3 6 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 1 40 -1 3 8 0.0000 4 + txt: 4 0 1 40 -1 3 6 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 0 40 -1 3 8 0.0000 4 + txt: 4 0 0 40 -1 3 6 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 0 40 -1 3 8 0.0000 4 + txt: 4 0 0 40 -1 3 6 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 - txt: 4 0 1 40 -1 3 8 0.0000 4 + txt: 4 0 1 40 -1 3 6 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 - txt: 4 0 1 40 -1 3 8 0.0000 4 + txt: 4 0 1 40 -1 3 6 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 1 40 -1 3 8 0.0000 4 + txt: 4 0 1 40 -1 3 6 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala - txt: 4 0 0 40 -1 3 8 0.0000 4 + txt: 4 0 0 40 -1 3 6 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp - txt: 4 0 0 40 -1 3 8 0.0000 4 + txt: 4 0 0 40 -1 3 6 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 - txt: 4 0 0 40 -1 18 7 0.0000 4 + txt: 4 0 0 40 -1 18 6 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор mp: POLYLINE 0x19 0 0 fig: 2 1 0 1 20 7 81 -1 -1 0.000 0 0 0 1 0 0 0 0 2.00 90.00 90.00 ocad: 819000 - name: маленькая ЛЭП mp: POLYLINE 0x1A 0 0 fig: 2 1 0 2 8947848 7 83 -1 -1 0.000 0 0 0 0 0 0 ocad: 819001 - name: пешеходный тоннель mp: POLYLINE 0x1B 0 0 fig: 2 1 0 1 3 7 77 -1 -1 0.000 0 0 0 0 0 0 ocad: 819002 - name: просека широкая mp: POLYLINE 0x1C 0 1 fig: 2 1 1 2 0 7 80 -1 -1 6.000 1 0 0 0 0 0 ocad: 819003 - name: граница стран, областей mp: POLYLINE 0x1D 0 2 fig: 2 1 0 7 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница областей, районов mp: POLYLINE 0x36 0 2 fig: 2 1 0 5 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница заповедников, парков mp: POLYLINE 0x37 0 2 fig: 2 1 0 5 2 7 91 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 819004 - name: нижний край обрыва mp: POLYLINE 0x1E 0 0 fig: 2 1 2 1 18 7 79 -1 -1 2.000 1 1 7 0 0 0 - name: пунктирная горизонталь mp: POLYLINE 0x20 0 0 fig: 2 1 1 1 HOR_COL 7 90 -1 -1 4.000 1 1 0 0 0 0 ocad: 820000 curve: 100 - name: горизонтали, бергштрихи mp: POLYLINE 0x21 0 0 fig: 2 1 0 1 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 821000 curve: 100 - name: жирная горизонталь mp: POLYLINE 0x22 0 0 fig: 2 1 0 2 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 822000 curve: 100 - name: контур леса mp: POLYLINE 0x23 0 0 fig: 2 1 2 1 12 7 96 -1 -1 2.000 1 1 0 0 0 0 ocad: 823000 - name: болото mp: POLYLINE 0x24 0 0 fig: 2 1 0 1 5269247 7 87 -1 -1 0.000 0 1 0 0 0 0 ocad: 824000 - name: овраг mp: POLYLINE 0x25 0 0 fig: 2 1 0 2 25 7 89 -1 -1 0.000 1 1 0 0 0 0 ocad: 825000 curve: 50 - name: УЖД mp: POLYLINE 0x0D 0 2 fig: 2 1 0 3 0 7 80 -1 -1 0.000 1 0 0 0 0 0 curve: 100 - name: железная дорога mp: POLYLINE 0x27 0 2 fig: 2 1 0 4 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 827000 curve: 100 - name: газопровод mp: POLYLINE 0x28 0 1 fig: 2 1 1 3 8947848 7 83 -1 -1 4.000 1 0 0 0 0 0 ocad: 828000 - name: ЛЭП mp: POLYLINE 0x29 0 1 fig: 2 1 0 3 8947848 7 83 -1 -1 0.000 1 0 0 0 0 0 ocad: 829000 - name: тропа mp: POLYLINE 0x2A 0 0 fig: 2 1 2 1 0 7 80 -1 -1 2.000 1 0 0 0 0 0 ocad: 829001 curve: 50 - name: сухая канава mp: POLYLINE 0x2B 0 0 fig: 2 1 2 1 26 7 82 -1 -1 2.000 1 1 0 0 0 0 ocad: 829002 - name: вал mp: POLYLINE 0x2C 0 0 fig: 2 1 2 3 26 7 81 -1 -1 2.000 1 1 0 0 0 0 ocad: 829003 - name: заросшая дорога mp: POLYLINE 0x2D 0 0 fig: 2 1 1 1 4210752 7 80 -1 -1 4.000 1 0 7 0 0 0 ocad: 829004 curve: 50 - name: заросшая заметная дорога (знак ММБ) mp: POLYLINE 0x2E 0 0 fig: 2 1 3 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 829004 curve: 50 - name: bad route /не использовать!/ mp: POLYLINE 0x50 0 0 fig: 2 1 1 1 4210700 7 80 -1 -1 4.000 0 0 -1 0 0 0 curve: 50 replace_by: 0x10002D - # note: 0x7F is also hardcoded in core/vmap/vmap.c name: text object mp: POLYLINE 0x7F 0 0 fig: 2 1 0 1 4 7 42 -1 -1 0.000 0 0 7 0 0 0 - # note: 0x7E is also hardcoded in core/vmap/vmap.c name: border object mp: POLYLINE 0x7E 0 0 fig: 2 1 0 1 5 7 41 -1 -1 0.000 0 0 7 0 0 0 ocad: 507000
ushakov/mapsoft
7b5ca2a0737c1bee3ac5202a72bb8f564f25d7a5
vector/data/styles.m4: change text alignment of glacier numbers
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index 6697e64..53daf38 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,682 +1,682 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности mp: POI 0x6406 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 24 40 -1 18 7 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 pic: ldp - name: номер ледника mp: POI 0x650B 0 0 fig: 2 1 0 3 8 7 57 -1 -1 0.000 0 1 7 0 0 1 - txt: 4 0 1 40 -1 3 5 0.0000 4 + txt: 4 1 1 40 -1 3 5 0.0000 4 - name: название ледника mp: POI 0x650C 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 1 7 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp txt: 4 0 0 40 -1 3 8 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 18 7 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор mp: POLYLINE 0x19 0 0 fig: 2 1 0 1 20 7 81 -1 -1 0.000 0 0 0 1 0 0 0 0 2.00 90.00 90.00 ocad: 819000 - name: маленькая ЛЭП mp: POLYLINE 0x1A 0 0 fig: 2 1 0 2 8947848 7 83 -1 -1 0.000 0 0 0 0 0 0 ocad: 819001 - name: пешеходный тоннель mp: POLYLINE 0x1B 0 0 fig: 2 1 0 1 3 7 77 -1 -1 0.000 0 0 0 0 0 0 ocad: 819002 - name: просека широкая mp: POLYLINE 0x1C 0 1 fig: 2 1 1 2 0 7 80 -1 -1 6.000 1 0 0 0 0 0 ocad: 819003 - name: граница стран, областей mp: POLYLINE 0x1D 0 2 fig: 2 1 0 7 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница областей, районов mp: POLYLINE 0x36 0 2 fig: 2 1 0 5 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница заповедников, парков mp: POLYLINE 0x37 0 2 fig: 2 1 0 5 2 7 91 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 819004 - name: нижний край обрыва mp: POLYLINE 0x1E 0 0 fig: 2 1 2 1 18 7 79 -1 -1 2.000 1 1 7 0 0 0 - name: пунктирная горизонталь mp: POLYLINE 0x20 0 0 fig: 2 1 1 1 HOR_COL 7 90 -1 -1 4.000 1 1 0 0 0 0 ocad: 820000 curve: 100 - name: горизонтали, бергштрихи mp: POLYLINE 0x21 0 0 fig: 2 1 0 1 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 821000 curve: 100 - name: жирная горизонталь mp: POLYLINE 0x22 0 0 fig: 2 1 0 2 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 822000 curve: 100 - name: контур леса mp: POLYLINE 0x23 0 0 fig: 2 1 2 1 12 7 96 -1 -1 2.000 1 1 0 0 0 0 ocad: 823000 - name: болото mp: POLYLINE 0x24 0 0 fig: 2 1 0 1 5269247 7 87 -1 -1 0.000 0 1 0 0 0 0 ocad: 824000 - name: овраг mp: POLYLINE 0x25 0 0 fig: 2 1 0 2 25 7 89 -1 -1 0.000 1 1 0 0 0 0 ocad: 825000 curve: 50 - name: УЖД mp: POLYLINE 0x0D 0 2 fig: 2 1 0 3 0 7 80 -1 -1 0.000 1 0 0 0 0 0 curve: 100 - name: железная дорога mp: POLYLINE 0x27 0 2 fig: 2 1 0 4 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 827000 curve: 100 - name: газопровод mp: POLYLINE 0x28 0 1 fig: 2 1 1 3 8947848 7 83 -1 -1 4.000 1 0 0 0 0 0 ocad: 828000 - name: ЛЭП mp: POLYLINE 0x29 0 1 fig: 2 1 0 3 8947848 7 83 -1 -1 0.000 1 0 0 0 0 0 ocad: 829000 - name: тропа mp: POLYLINE 0x2A 0 0 fig: 2 1 2 1 0 7 80 -1 -1 2.000 1 0 0 0 0 0 ocad: 829001
ushakov/mapsoft
adabe528fdfdce6e1d74964f2ba52d42283e9ce4
mapsoft_srtm2fig: sctn operation (finding slope contours)
diff --git a/programs/mapsoft_srtm2fig.cpp b/programs/mapsoft_srtm2fig.cpp index 6045771..c73767f 100644 --- a/programs/mapsoft_srtm2fig.cpp +++ b/programs/mapsoft_srtm2fig.cpp @@ -1,143 +1,171 @@ #include <string> #include <iostream> #include <fstream> #include <map> #include <set> #include <list> #include <stdexcept> #include <cmath> #include "srtm/srtm3.h" #include "2d/line.h" #include "2d/line_utils.h" #include "2d/line_polycrop.h" #include "2d/point_int.h" #include "geo_io/geofig.h" #include "geo/geo_data.h" #include "geo/geo_convs.h" // Перенесение данных srtm в привязанный fig-файл. using namespace std; void usage(){ cerr << "usage: \n" " mapsoft_srtm2fig <fig> hor <srtm_dir> <step1> <step2> [<acc, def=10>]\n" + " mapsoft_srtm2fig <fig> scnt <srtm_dir> <val> [<acc, def=10>]\n" " mapsoft_srtm2fig <fig> ver <srtm_dir> [<DH, def=20> [<PS, def=500>]] \n" " mapsoft_srtm2fig <fig> holes <srtm_dir>\n"; } int main(int argc, char** argv){ if (argc < 4) { usage(); return 0; } std::string fig_name = argv[1]; std::string cmd = argv[2]; std::string srtm_dir = argv[3]; SRTM3 s(srtm_dir, 10); // read fig, build conversion fig -> wgs fig::fig_world F; if (!fig::read(fig_name.c_str(), F)) { std::cerr << "File is not modified, exiting.\n"; return 1; } g_map fig_ref = fig::get_ref(F); convs::map2wgs fig_cnv(fig_ref); dRect range = fig_ref.range(); // fig range (lonlat) dLine border_ll = fig_cnv.line_frw(fig_ref.border); // fig border (lonlat) int count; if (cmd == "hor"){ if (argc < 6){ usage(); return 0; } int step1 = atoi(argv[4]); int step2 = atoi(argv[5]); if (step2<step1) swap(step2,step1); double acc = 10; // "точность", в метрах - для генерализации горизонталей. if (argc>6) acc = atoi(argv[6]); std::cerr << "looking for contours\n"; map<short, dMultiLine> hors = s.find_contours(range, step1); count = 0; cerr << " merge and generalize: "; fig::fig_object o = fig::make_object("2 1 0 1 30453904 7 90 -1 -1 0.000 1 1 0 0 0 0"); for(map<short, dMultiLine>::iterator im = hors.begin(); im!=hors.end(); im++){ std::cerr << im->first << " "; generalize(im->second, acc/6380000/2/M_PI*180.0); split(im->second, 200); dMultiLine tmp; if (border_ll.size()) crop_lines(im->second, tmp, border_ll, true); for(dMultiLine::iterator iv = im->second.begin(); iv!=im->second.end(); iv++){ if (iv->size()<3) continue; o.clear(); if (im->first%step2==0) o.thickness = 2; else o.thickness = 1; o.set_points(fig_cnv.line_bck(*iv)); o.comment.clear(); o.comment.push_back(boost::lexical_cast<std::string>(im->first)); F.push_back(o); count++; } } cerr << " - " << count << " pts\n"; + } + + else if (cmd == "scnt"){ + if (argc < 5){ + usage(); + return 0; + } + double val = atof(argv[4]); + double acc = 10; // "точность", в метрах - для генерализации горизонталей. + if (argc>5) acc = atoi(argv[5]); + + std::cerr << "looking for slope contours\n"; + dMultiLine cnt = s.find_slope_contour(range, val); + + count = 0; + cerr << " merge and generalize: "; + generalize(cnt, acc/6380000/2/M_PI*180.0); + join_polygons1(cnt); + for (const auto & l:cnt){ + fig::fig_object o = fig::make_object("2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0"); + o.set_points(fig_cnv.line_bck(l)); + F.push_back(o); + count++; + } + cerr << " - " << count << " pts\n"; + } + + - } else if (cmd == "ver"){ int DH = 20; int PS = 500; if (argc>4) DH = atoi(argv[4]); if (argc>5) PS = atoi(argv[5]); int count = 0; std::cerr << "looking for mountains: "; map<dPoint, short> peaks = s.find_peaks(range, DH, PS); for(map<dPoint, short>::iterator i = peaks.begin(); i!=peaks.end(); i++){ dPoint p1(i->first); if (border_ll.size() && !test_pt(p1, border_ll)) break; fig::fig_object o = fig::make_object("2 1 0 3 24 7 57 -1 -1 0.000 0 1 -1 0 0 1"); fig_cnv.bck(p1); o.push_back(p1); o.comment.clear(); o.comment.push_back(boost::lexical_cast<std::string>(i->second)); F.push_back(o); count++; } cerr << peaks.size() << " pts\n"; } else if (cmd == "holes"){ // поиск дырок cerr << "looking for srtm holes\n"; dMultiLine aline = s.find_holes(range); dMultiLine tmp; if (border_ll.size()) crop_lines(aline, tmp, border_ll, true); for(dMultiLine::iterator iv = aline.begin(); iv!=aline.end(); iv++){ if (iv->size()<3) continue; dLine l = fig_cnv.line_bck(*iv); fig::fig_object o = fig::make_object("2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0"); o.insert(o.end(), l.begin(), l.end()); F.push_back(o); } cerr << aline.size() << " polygons\n"; } else { usage(); return 0; } fig::write(fig_name, F); return 0; }
ushakov/mapsoft
5b635cb53c7114154be4aeb6420c547f905107c4
core/srtm: add find_slope_contour() method
diff --git a/core/srtm/srtm3.cpp b/core/srtm/srtm3.cpp index d9d83b2..e2a10e8 100644 --- a/core/srtm/srtm3.cpp +++ b/core/srtm/srtm3.cpp @@ -1,566 +1,628 @@ #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <queue> #include <cstdio> #include <2d/point_int.h> #include <2d/line_utils.h> #include "srtm3.h" #include <zlib.h> using namespace std; SRTM3::SRTM3(const string & _srtm_dir, const unsigned cache_size): srtm_dir(_srtm_dir), srtm_cache(cache_size) { set_dir(srtm_dir); } void SRTM3::set_dir(const string & str){ srtm_dir = str; if (srtm_dir == "") srtm_dir = string(getenv("HOME")? getenv("HOME"):"") + "/.srtm_data"; ifstream ws(srtm_dir + "/srtm_width.txt"); if (!ws) srtm_width = 1201; else ws >> srtm_width; if (srtm_width<1) srtm_width = 1201; size0 = 6380e3 * M_PI/srtm_width/180; area0 = pow(6380e3 * M_PI/srtm_width/180, 2); Glib::Mutex::Lock lock(mutex); srtm_cache.clear(); } const string & SRTM3::get_dir(void) const{ return srtm_dir; } const unsigned SRTM3::get_width(void) const{ return srtm_width; } // find tile number and coordinate on the tile void get_crd(int x, int w, int &k, int &c){ if (x>=0) k=x/(w-1); else k=(x+1)/(w-1)-1; c = x - k*(w-1); } short SRTM3::geth(const iPoint & p, const bool interp){ // find tile number and coordinate on the tile iPoint key, crd; get_crd(p.x, srtm_width, key.x, crd.x); get_crd(p.y, srtm_width, key.y, crd.y); crd.y = srtm_width-crd.y-1; int h; { Glib::Mutex::Lock lock(mutex); if ((!srtm_cache.contains(key)) && (!load(key))) return srtm_nofile; if (srtm_cache.get(key).empty()) return srtm_nofile; h = srtm_cache.get(key).safe_get(crd); } if (interp){ if (h>srtm_min_interp) return h - srtm_zer_interp; if (h!=srtm_undef) return h; // найдем всю дырку и заинтерполируем ее! set<iPoint> pset = plane(p); set<iPoint> bord = border(pset); set<iPoint>::iterator pi, bi; for (pi = pset.begin(); pi != pset.end(); pi++){ double Srh = 0; double Sr = 0; for (bi = bord.begin(); bi != bord.end(); bi++){ int bh = geth(*bi); if (bh>srtm_min){ double k = cos(double(pi->y)/srtm_width/180.0*M_PI); double r = 1.0/(pow(k*(bi->x - pi->x),2) + pow(double(bi->y - pi->y),2)); Sr += r; Srh+= bh * r; } } seth(*pi, (short)Srh/Sr+srtm_zer_interp); } return geth(p,true); } else { if (h>srtm_min_interp) return srtm_undef; else return h; } return h; } double SRTM3::slope(const iPoint &p, const bool interp){ short h = geth(p, interp); short h1 = geth(p.x-1, p.y, interp); short h2 = geth(p.x+1, p.y, interp); if (h1 < srtm_min && h > srtm_min && h2 > srtm_min) h1 = 2*h - h2; if (h2 < srtm_min && h > srtm_min && h1 > srtm_min) h1 = 2*h - h2; short h3 = geth(p.x, p.y-1, interp); short h4 = geth(p.x, p.y+1, interp); if (h3 < srtm_min && h > srtm_min && h4 > srtm_min) h3 = 2*h - h4; if (h4 < srtm_min && h > srtm_min && h3 > srtm_min) h4 = 2*h - h3; if (h1 > srtm_min && h2 > srtm_min && h3 > srtm_min && h4 > srtm_min){ const double kx = cos(M_PI*p.y/180/srtm_width); const double U = hypot((h2-h1)/kx, h4-h3)/size0/2.0; return atan(U)*180.0/M_PI; } return 0; } short SRTM3::geth(const int x, const int y, const bool interp){ return geth(iPoint(x,y), interp); } double SRTM3::slope(const int x, const int y, const bool interp){ return slope(iPoint(x,y), interp); } short SRTM3::seth(const iPoint & p, const short h){ // find tile number and coordinate on the tile iPoint key, crd; get_crd(p.x, srtm_width, key.x, crd.x); get_crd(p.y, srtm_width, key.y, crd.y); crd.y = srtm_width-crd.y-1; { Glib::Mutex::Lock lock(mutex); if ((!srtm_cache.contains(key)) && (!load(key))) return srtm_nofile; if (srtm_cache.get(key).empty()) return srtm_nofile; srtm_cache.get(key).safe_set(crd, h); } return h; } short SRTM3::geth4(const dPoint & p, const bool interp){ double x = p.x*(srtm_width-1); double y = p.y*(srtm_width-1); int x1 = floor(x), x2 = x1+1; int y1 = floor(y), y2 = y1+1; short h1=geth(x1,y1,interp); short h2=geth(x1,y2,interp); if ((h1<srtm_min)||(h2<srtm_min)) return srtm_undef; short h12 = (int)( h1+ (h2-h1)*(y-y1) ); short h3=geth(x2,y1,interp); short h4=geth(x2,y2,interp); if ((h3<srtm_min)||(h4<srtm_min)) return srtm_undef; short h34 = (int)( h3 + (h4-h3)*(y-y1) ); return (short)( h12 + (h34-h12)*(x-x1) ); } double SRTM3::slope4(const dPoint & p, const bool interp){ double x = p.x*(srtm_width-1); double y = p.y*(srtm_width-1); int x1 = floor(x), x2 = x1+1; int y1 = floor(y), y2 = y1+1; double h1=slope(x1,y1, interp); double h2=slope(x1,y2, interp); double h3=slope(x2,y1, interp); double h4=slope(x2,y2, interp); double h12 = h1+ (h2-h1)*(y-y1); double h34 = h3 + (h4-h3)*(y-y1); return h12 + (h34-h12)*(x-x1); } short SRTM3::geth16(const dPoint & p, const bool interp){ double x = p.x*(srtm_width-1); double y = p.y*(srtm_width-1); int x0 = floor(x); int y0 = floor(y); double hx[4], hy[4]; for (int i=0; i<4; i++){ for (int j=0; j<4; j++) hx[j]=geth(x0+j-1, y0+i-1, interp); int_holes(hx); hy[i]= cubic_interp(hx, x-x0); } int_holes(hy); return cubic_interp(hy, y-y0); } // найти множество соседних точек одной высоты (не более max точек) set<iPoint> SRTM3::plane(const iPoint& p, size_t max){ set<iPoint> ret; queue<iPoint> q; short h = geth(p); q.push(p); ret.insert(p); while (!q.empty()){ iPoint p1 = q.front(); q.pop(); for (int i=0; i<8; i++){ iPoint p2 = adjacent(p1, i); if ((geth(p2) == h)&&(ret.insert(p2).second)) q.push(p2); } if ((max!=0)&&(ret.size()>max)) break; } return ret; } void SRTM3::move_to_extr(iPoint & p0, bool down, int maxst){ iPoint p1 = p0; int i=0; do { for (int i=0; i<8; i++){ iPoint p=adjacent(p0,i); if ((down && (geth(p,true) < geth(p1,true))) || (!down && (geth(p,true) > geth(p1,true)))) p1=p; } if (p1==p0) break; p0=p1; i++; } while (maxst<0 || i<maxst); } void SRTM3::move_to_min(iPoint & p0, int maxst){ move_to_extr(p0, true, maxst); } void SRTM3::move_to_max(iPoint & p0, int maxst){ move_to_extr(p0, false, maxst); } double SRTM3::area(const iPoint &p) const{ return area0 * cos((double)p.y *M_PI/180.0/srtm_width); } /**********************************************************/ sImage read_zfile(const string & file, const size_t srtm_width){ gzFile F = gzopen(file.c_str(), "rb"); if (!F) return sImage(0,0); sImage im(srtm_width,srtm_width); int length = srtm_width*srtm_width*sizeof(short); if (length != gzread(F, im.data, length)){ cerr << "bad file: " << file << '\n'; return sImage(0,0); } for (int i=0; i<length/2; i++){ // swap bytes int tmp=(unsigned short)im.data[i]; im.data[i] = (tmp >> 8) + (tmp << 8); } gzclose(F); return im; } sImage read_file(const string & file, const size_t srtm_width){ FILE *F = fopen(file.c_str(), "rb"); if (!F) return sImage(0,0); sImage im(srtm_width,srtm_width); size_t length = srtm_width*srtm_width*sizeof(short); if (length != fread(im.data, 1, length, F)){ cerr << "bad file: " << file << '\n'; return sImage(0,0); } for (size_t i=0; i<length/2; i++){ // swap bytes int tmp=(unsigned short)im.data[i]; im.data[i] = (tmp >> 8) + (tmp << 8); } fclose(F); return im; } bool SRTM3::load(const iPoint & key){ if ((key.x < -max_lon) || (key.x >= max_lon) || (key.y < -max_lat) || (key.y >= max_lat)) return false; char NS='N'; char EW='E'; if (key.y<0) {NS='S';} if (key.x<0) {EW='W';} ostringstream file; file << NS << setfill('0') << setw(2) << abs(key.y) << EW << setw(3) << abs(key.x) << ".hgt"; // try f2.gz, f2, f1.gz, f1 sImage im; im = read_zfile(srtm_dir + "/" + file.str() + ".gz", srtm_width); if (!im.empty()) goto read_ok; im = read_file(srtm_dir + "/" + file.str(), srtm_width); if (!im.empty()) goto read_ok; cerr << "can't find file " << file.str() << '\n'; read_ok: srtm_cache.add(key, im); return !im.empty(); } // see http://www.paulinternet.nl/?page=bicubic short SRTM3::cubic_interp(const double h[4], const double x) const{ return h[1] + 0.5 * x*(h[2] - h[0] + x*(2.0*h[0] - 5.0*h[1] + 4.0*h[2] - h[3] + x*(3.0*(h[1] - h[2]) + h[3] - h[0]))); } void SRTM3::int_holes(double h[4]) const{ // interpolate 1-point or 2-points holes // maybe this can be written smarter... if ((h[0]>srtm_min) && (h[1]>srtm_min) && (h[2]>srtm_min) && (h[3]>srtm_min)) return; for (int cnt=0; cnt<2; cnt++){ if ((h[0]<=srtm_min) && (h[1]>srtm_min) && (h[2]>srtm_min)) h[0]=2*h[1]-h[2]; else if ((h[1]<=srtm_min) && (h[0]>srtm_min) && (h[2]>srtm_min)) h[1]=(h[0]+h[2])/2; else if ((h[1]<=srtm_min) && (h[2]>srtm_min) && (h[3]>srtm_min)) h[1]=2*h[2]-h[3]; else if ((h[2]<=srtm_min) && (h[1]>srtm_min) && (h[3]>srtm_min)) h[2]=(h[1]+h[3])/2; else if ((h[2]<=srtm_min) && (h[0]>srtm_min) && (h[1]>srtm_min)) h[2]=2*h[1]-h[0]; else if ((h[3]<=srtm_min) && (h[1]>srtm_min) && (h[2]>srtm_min)) h[3]=2*h[2]-h[1]; else break; } if ((h[1]<=srtm_min) && (h[2]<=srtm_min) && (h[0]>srtm_min) && (h[3]>srtm_min)){ h[1]=(2*h[0] + h[3])/3; h[2]=(h[0] + 2*h[3])/3; } } /**********************************************************/ //координаты угла единичного квадрата по его номеру iPoint crn (int k){ k%=4; return iPoint(k/2, (k%3>0)?1:0); } //направление следующей за углом стороны (единичный вектор) iPoint dir (int k){ return crn(k+1)-crn(k); } map<short, dMultiLine> SRTM3::find_contours(const dRect & range, int step){ int lon1 = int(floor((srtm_width-1)*range.TLC().x)); int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); int lat1 = int(floor((srtm_width-1)*range.TLC().y)); int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); map<short, dMultiLine> ret; int count = 0; for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2; lon++){ iPoint p(lon,lat); // пересечения четырех сторон клетки с горизонталями: // при подсчетах мы опустим все данные на полметра, // чтоб не разбирать кучу случаев с попаданием горизонталей в узлы сетки multimap<short, double> pts; for (int k=0; k<4; k++){ iPoint p1 = p+crn(k); iPoint p2 = p+crn(k+1); short h1 = geth(p1); short h2 = geth(p2); if ((h1<srtm_min) || (h2<srtm_min)) continue; int min = (h1<h2)? h1:h2; int max = (h1<h2)? h2:h1; min = int( floor(double(min)/step)) * step; max = int( ceil(double(max)/step)) * step; if (h2==h1) continue; for (int hh = min; hh<=max; hh+=step){ double x = double(hh-h1+0.1)/double(h2-h1); if ((x<0)||(x>1)) continue; pts.insert(pair<short, double>(hh,x+k)); } } // найдем, какие горизонтали пересекают квадрат дважды, // поместим их в список горизонталей ret short h=srtm_undef; double x1=0,x2=0; for (multimap<short,double>::const_iterator i=pts.begin(); i!=pts.end(); i++){ if (h!=i->first){ h = i->first; x1 = i->second; } else{ x2 = i->second; dPoint p1=(dPoint(p + crn(int(x1))) + dPoint(dir(int(x1)))*double(x1-int(x1)))/(double)(srtm_width-1); dPoint p2=(dPoint(p + crn(int(x2))) + dPoint(dir(int(x2)))*double(x2-int(x2)))/(double)(srtm_width-1); // we found segment p1-p2 with height h // first try to append it to existing line in ret[h] bool done=false; for (dMultiLine::iterator l=ret[h].begin(); l!=ret[h].end(); l++){ int e=l->size()-1; if (e<=0) continue; // we have no 1pt lines! if (pdist((*l)[0], p1) < 1e-4){ l->insert(l->begin(), p2); done=true; break;} if (pdist((*l)[0], p2) < 1e-4){ l->insert(l->begin(), p1); done=true; break;} if (pdist((*l)[e], p1) < 1e-4){ l->push_back(p2); done=true; break;} if (pdist((*l)[e], p2) < 1e-4){ l->push_back(p1); done=true; break;} } if (!done){ // insert new line into ret[h] dLine hor; hor.push_back(p1); hor.push_back(p2); ret[h].push_back(hor); } h=srtm_undef; count++; } } } } // merge contours for(map<short, dMultiLine>::iterator im = ret.begin(); im!=ret.end(); im++) merge(im->second, 1e-4); return ret; } +dMultiLine +SRTM3::find_slope_contour(const dRect & range, double val){ + int lon1 = int(floor((srtm_width-1)*range.TLC().x)); + int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); + int lat1 = int(floor((srtm_width-1)*range.TLC().y)); + int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); + + dMultiLine ret; + for (int lat=lat2+1; lat>=lat1-1; lat--){ + for (int lon=lon1-1; lon<=lon2+1; lon++){ + + iPoint p(lon,lat); + // пересечения четырех сторон клетки с контуром: + std::vector<double> pts; + + for (int k=0; k<4; k++){ + iPoint p1 = p+crn(k); + iPoint p2 = p+crn(k+1); + double h1 = 0, h2 = 0; + if (p1.y>=lat1 && p1.y<=lat2 && p1.x>=lon1 && p1.x<=lon2) h1 = slope(p1); + if (p2.y>=lat1 && p2.y<=lat2 && p2.x>=lon1 && p2.x<=lon2) h2 = slope(p2); + double min = (h1<h2)? h1:h2; + double max = (h1<h2)? h2:h1; + if (min < val && max >= val){ + double x = double(val-h1)/double(h2-h1); + pts.push_back(x+k); + } + } + + // нам интересны случаи 2 или 4 пересечений + for (size_t i=1; i<pts.size(); i+=2){ + double x1 = pts[i-1], x2 = pts[i]; + dPoint p1=(dPoint(p + crn(int(x1))) + dPoint(dir(int(x1)))*double(x1-int(x1)))/(double)(srtm_width-1); + dPoint p2=(dPoint(p + crn(int(x2))) + dPoint(dir(int(x2)))*double(x2-int(x2)))/(double)(srtm_width-1); + // first try to append it to existing line in ret[h] + bool done=false; + for (auto & l:ret){ + int e=l.size()-1; + if (e<=0) continue; // we have no 1pt lines! + if (pdist(l[0], p1) < 1e-4){ l.insert(l.begin(), p2); done=true; break;} + if (pdist(l[0], p2) < 1e-4){ l.insert(l.begin(), p1); done=true; break;} + if (pdist(l[e], p1) < 1e-4){ l.push_back(p2); done=true; break;} + if (pdist(l[e], p2) < 1e-4){ l.push_back(p1); done=true; break;} + } + // insert new line into ret + if (!done){ + dLine hor; + hor.push_back(p1); + hor.push_back(p2); + ret.push_back(hor); + } + } + + } + } + + // merge contours + merge(ret, 1e-4); + return ret; +} + + map<dPoint, short> SRTM3::find_peaks(const dRect & range, int DH, size_t PS){ int lon1 = int(floor((srtm_width-1)*range.TLC().x)); int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); int lat1 = int(floor((srtm_width-1)*range.TLC().y)); int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); // поиск вершин: // 1. найдем все локальные максимумы (не забудем про максимумы из многих точек!) // 2. от каждого будем строить множество точек, добавляя наивысшую точку границы // 3. если высота последней добаленной точки ниже исходной более чем на DH м, // или если размер множества больше PS точек - процедуру прекращаем, // объявляем исходную точку вершиной. // 4. Если высота последней добавленной точки больше исходной - процедуру // прекращаем set<iPoint> done; map<dPoint, short> ret; for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2-1; lon++){ iPoint p(lon,lat); if (done.find(p)!=done.end()) continue; short h = geth(p); if (h<srtm_min) continue; set<iPoint> pts; pts.insert(p); set<iPoint> brd = border(pts); // ищем максимум границы do{ short max = srtm_undef; iPoint maxpt; for (set<iPoint>::const_iterator i = brd.begin(); i!=brd.end(); i++){ short h1 = geth(*i); // исходная точка слишком близка к краю данных if ((h1<srtm_min) && (pdist(*i,p)<1.5)) {max = h1; break;} if (h1>max) {max = h1; maxpt=*i;} } if (max < srtm_min) break; // если максимум выше исходной точки - выходим. if (max > h) { break; } // если мы спустились от исходной точки более чем на DH или размер области более PS if ((h - max > DH ) || (pts.size() > PS)) { ret[dPoint(p)/(double)(srtm_width-1)] = h; break; } add_pb(maxpt, pts, brd); done.insert(maxpt); } while (true); } } return ret; } dMultiLine SRTM3::find_holes(const dRect & range){ int lon1 = int(floor((srtm_width-1)*range.TLC().x)); int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); int lat1 = int(floor((srtm_width-1)*range.TLC().y)); int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); set<iPoint> aset; for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2-1; lon++){ iPoint p(lon,lat); short h = geth(p); if (h!=srtm_undef) continue; aset.insert(p); } } // converting points to polygons return pset2line(aset)/(double)(srtm_width-1); } /* // поиск крутых склонов cerr << "ищем крутые склоны: "; double latdeg = 6380000/(double)(srtm_width-1)/180.0*M_PI; double londeg = latdeg * cos(double(lat2+lat1)/2400.0/180.0*M_PI); for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2-1; lon++){ iPoint p(lon,lat); short h = geth(p); short hx = geth(p+iPoint(1,0)); short hy = geth(p+iPoint(0,1)); if ((h<srtm_min) || (hx<srtm_min) || (hy<srtm_min)) continue; dPoint gr(double(hx-h)/londeg, double(hy-h)/latdeg); double a = atan(pdist(gr))*180/M_PI; if (a > 45) aset.insert(p); } } cerr << aset.size() << " точек\n"; cerr << " преобразуем множество точек в многоугольники: "; aline = pset2line(aset); for(dMultiLine::iterator iv = aline.begin(); iv!=aline.end(); iv++){ if (iv->size()<3) continue; dLine l = (*iv)/(double)(srtm_width-1); mp::mp_object mpo; mpo.Class = "POLYGON"; mpo.Label = "high slope"; mpo.Type = 0x19; mpo.insert(mpo.end(), l.begin(), l.end()); MP.push_back(mpo); } cerr << aline.size() << " шт\n"; */ diff --git a/core/srtm/srtm3.h b/core/srtm/srtm3.h index cc59ecb..34d0fbd 100644 --- a/core/srtm/srtm3.h +++ b/core/srtm/srtm3.h @@ -1,105 +1,106 @@ #ifndef SRTM3_H #define SRTM3_H #include <string> #include <glibmm.h> #include <2d/image.h> #include <cache/cache.h> /* SRTM3 data Original data can be downloaded from ftp://e0mss21u.ecs.nasa.gov/srtm/ Fixed data can be downloaded from http://www.viewfinderpanoramas.org/dem3.html Default data directory is DIR=$HOME/.srtm_data Files are searched in $DIR/fixed/$file.gz, $DIR/fixed/$file, $DIR/$file.gz, $DIR/$file, so you can keep original data in $HOME/.srtm_data and fixed data in $HOME/.srtm_data/fixed */ const short srtm_min = -32000; // value for testing const short srtm_nofile = -32767; // file not found const short srtm_undef = -32768; // hole in srtm data const short srtm_zer_interp = 15000; // добавлено к интерполированным значениям const short srtm_min_interp = 10000; // для проверки const int max_lat = 90; const int max_lon = 180; class SRTM3 { public: SRTM3( const std::string & _srtm_dir=std::string(), // data directory ($HOME/.srtm_data) const unsigned cache_size=4 ); void set_dir(const std::string & str); const std::string & get_dir(void) const; const unsigned get_width(void) const; // вернуть высоту точки short geth(const iPoint & p, const bool interp=false); short geth(const int x, const int y, const bool interp=false); // Slope (degrees) at a given point // Slope is calculated for p+(1/2,1/2) double slope(const iPoint &p, const bool interp=true); double slope(const int x, const int y, const bool interp=true); // change data (in cache only!) short seth(const iPoint & p, const short h); // вернуть высоту точки (вещественные координаты, // простая интерполяция по четырем соседним точкам) short geth4(const dPoint & p, const bool interp=false); // Slope (degrees) at a given point double slope4(const dPoint &p, const bool interp=true); // вернуть высоту точки (вещественные координаты, // интерполяция по 16 соседним точкам) short geth16(const dPoint & p, const bool interp=false); // найти множество соседних точек одной высоты (не более max точек) std::set<iPoint> plane(const iPoint& p, size_t max=1000); // move p0 to the local extremum (interpolation is always on) void move_to_extr(iPoint & p0, bool down, int maxst=-1); void move_to_min(iPoint & p0, int maxst=-1); void move_to_max(iPoint & p0, int maxst=-1); double size0; // size (m) of 1 srtm point lat bow double area0; // area (m^2) of 1x1 srtm point on equator size_t srtm_width; // файлы 1201х1201 // area (km2) of 1x1 srtm point at the given place double area(const iPoint &p) const; // making some vector data: contours, peaks, srtm holes std::map<short, dMultiLine> find_contours(const dRect & range, int step); + dMultiLine find_slope_contour(const dRect & range, double val); std::map<dPoint, short> find_peaks(const dRect & range, int DH, size_t PS); dMultiLine find_holes(const dRect & range); private: // data directories std::string srtm_dir; // data cache. key is lon,lat in degrees Cache<iPoint, sImage > srtm_cache; // load data into cache bool load(const iPoint & key); short cubic_interp(const double h[4], const double x) const; void int_holes(double h[4]) const; Glib::Mutex mutex; }; #endif
ushakov/mapsoft
ecd5e8e82b5f06ddc3e3a9fdca1229e1060b2d3f
20210121-alt1
diff --git a/mapsoft.spec b/mapsoft.spec index 4774235..f1d14fb 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,204 +1,212 @@ Name: mapsoft -Version: 20201212 +Version: 20210121 Release: alt1 License: GPL3.0 Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar Patch1: 0001-skip-convs_gtiles.patch BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man BuildRequires: boost-geometry-devel perl-Text-Iconv %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %patch1 -p1 %build # boost::spirit crashes with -O2 on 32-bit systems %if "%_lib" == "lib64" export CCFLAGS=-O2 %endif scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %_bindir/map_rescale %_bindir/*.sh %_bindir/map_*_gk %_bindir/map_*_nom %_bindir/mapsoft_wp_parse %changelog +* Thu Jan 21 2021 Vladislav Zavjalov <[email protected]> 20210121-alt1 +- scripts/mapsoft_wp_parse: fix name conversions +- skip convs_gtiles program in Altlinux build (build problem with new boost) +- vector/data: add new types: point 0x650B, 0x650C (glacier names) +- vector/vmap3/vmap_mmb_filter: convert glacier names to points +- vector/vmap3: add vmap_put_track and vmap_get_track programs +- programs/mapsoft_map2fig: put images into compound object; add 50px margins + * Sat Dec 12 2020 Vladislav Zavjalov <[email protected]> 20201212-alt1 - img_io/gobj_vmap: draw pattens with solid color at small scales (A.Kazantsev) - fix for gcc-10 - fix a few compilation warnings (with -Wall) and a couple of possible related errors - remove -O2 flag on i586 and armh (problem with new boost::spirit) * Sun Dec 01 2019 Vladislav Zavjalov <[email protected]> 20191201-alt1 - fix a few problems in vmap_render and convs_gtiles (thanks to A.Kazantsev) - add GPL3.0 license (Altlinux requires ambiguous license for all packages) - fix python shebang (python -> python2) * Sun Nov 10 2019 Vladislav Zavjalov <[email protected]> 20191110-alt1 - add more scripts to mapsoft_vmap package * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
f5ad9ca8701b23a9553f24d8d5c12977ffc4cc79
vector/vmap3/vmap_put_track: skip point names
diff --git a/vector/vmap3/vmap_put_track.cpp b/vector/vmap3/vmap_put_track.cpp index 11756bb..32348db 100644 --- a/vector/vmap3/vmap_put_track.cpp +++ b/vector/vmap3/vmap_put_track.cpp @@ -1,92 +1,92 @@ #include <string> #include <cstring> #include "options/m_getopt.h" #include "vmap/vmap.h" #include "vmap/zn.h" #include "fig/fig.h" #include "geo_io/io.h" using namespace std; // replace objects of a single type // in a map using geodata int main(int argc, char **argv){ try{ if (argc!=5) { std::cerr << "usage: vmap_put_track <class> <type> <in geodata> <out map> \n"; return 1; } std::string cl(argv[1]); int type = atoi(argv[2]); const char * ifile = argv[3]; const char * ofile = argv[4]; if (cl == "POI"){ } else if (cl == "POLYLINE") type |= zn::line_mask; else if (cl == "POLYGON") type |= zn::area_mask; else throw Err() << "unknown object class: " << cl; vmap::world V = vmap::read(ofile); geo_data data; io::in(ifile, data); // remove old objects: vmap::world::iterator i=V.begin(); while (i!=V.end()){ if (i->type == type) { i=V.erase(i); continue; } i++; } // put objects if (cl == "POI"){ for (auto const & pts:data.wpts) { for (auto const & pt:pts) { vmap::object o; dLine l; l.push_back(pt); o.push_back(l); - o.text=pt.name; +// o.text=pt.name; o.type=type; V.push_back(o); } } } else { for (auto const & t:data.trks) { vmap::object o; // o.text=t.comm; o.type=type; dLine l; for (auto const & pt:t) { if (pt.start && l.size()){ o.push_back(l); V.push_back(o); l.clear(); o.clear(); } l.push_back(pt); } if (l.size()){ o.push_back(l); V.push_back(o); } } } vmap::write(ofile, V); } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
ae4574dc9fed24c1915d9cd6ab1807b66d42da5c
scripts/mapsoft_wp_parse: fix name conversions
diff --git a/scripts/mapsoft_wp_parse b/scripts/mapsoft_wp_parse index 168f918..382ad9c 100755 --- a/scripts/mapsoft_wp_parse +++ b/scripts/mapsoft_wp_parse @@ -1,97 +1,97 @@ #!/usr/bin/perl use strict; use warnings; use Text::Iconv; # parse kml file downloaded from Westra Passes # (http://westra.ru/passes/kml/passes.php?BBOX=x1,y1,x2,y2) # print txt and mp files ### set_attr is not supported, so use iconv program. #my $cnv_koi = Text::Iconv->new("utf8", "koi8-r"); #my $cnv_win = Text::Iconv->new("utf8", "cp1251"); #$cnv_koi->set_attr("discard_ilseq", 1); #$cnv_win->set_attr("discard_ilseq", 1); my $file = $ARGV[0]; open IN, $file or die "can't open $file: $!\n"; my $text = join ' ', <IN>; close IN; $file=~s/.kml$//; open OUT_TXT, "| iconv -f utf8 -t koi8-r -c > $file.txt" or die "can't open $file.txt: $!\n"; open OUT_MP, "| iconv -f utf8 -t cp1251 -c > $file.mp" or die "can't open $file.mp: $!\n"; printf OUT_TXT "# id lat lon alt title /other title/, cat\n"; printf OUT_MP qq* [IMG ID] ID=0 Name=$file Elevation=M Preprocess=F CodePage=1251 [END-IMG ID]\n *; my @data; while ($text=~s|<Placemark>(.*?)</Placemark>||s){ my $line = $1; my $d; # pass name and type (name can be "вер. Х", "пер. Х", "пик X") $d->{name} = ($line =~ m|<name>(.*?)</name>|s)? $1:""; $d->{type} = "V"; $d->{type} = "P" if $d->{name} =~ s|пер. ||; $d->{name} =~ s|вер. ||; my $point = ($line =~ m|<Point>(.*?)</Point>|s)? $1:""; my $coord = ($point =~ m|<coordinates>(.*?)</coordinates>|s)? $1:""; ($d->{x},$d->{y},$d->{z}) = split(',', $coord); my $descr = ($line =~ m|<description>(.*?)</description>|s)? $1:""; $d->{id} = ($descr =~ m|https://westra.ru/passes/Passes/([0-9]+)|s)? $1:0; $d->{ks} = ($descr =~ m|<tr><th>Категория сложности</th><td>([^<]*)</td></tr>|s)? $1:''; $d->{alt} = ($descr =~ m|<tr><th>Высота</th><td>([^<]*)</td></tr>|s)? $1:0; $d->{var} = ($descr =~ m|<tr><th>Другие названия</th><td>([^<]*)</td></tr>|s)? $1:''; $d->{name_txt} = ($d->{type} eq 'P'? 'пер. ': 'вер. ') . $d->{name} . ($d->{var}? " /$d->{var}/":"") . ($d->{ks}? ", $d->{ks}":""); - $d->{name_mp} = (($d->{type} eq 'V' && $d->{alt} && $d->{name}!~m|^\d+$|)? "$d->{alt} ":'') . $d->{name}; + $d->{name_mp} = (($d->{type} eq 'V' && $d->{alt} && $d->{name}!~m|^[\d\.]+$|)? "$d->{alt} ":'') . $d->{name}; foreach ('name_mp', 'name_txt', 'name'){ $d->{$_} =~ s/№/N/g; $d->{$_} =~ s/&quot;/\"/g; } push @data, $d; } foreach my $d (sort {$a->{id} <=> $b->{id}} @data) { # $d->{name_txt} = $cnv_koi->convert($d->{name_txt}) or print " ERROR: $d->{name_txt}\n"; # $d->{name_mp} = $cnv_win->convert($d->{name_mp}); printf OUT_TXT "%4d %12.7f %12.7f %5d %s\n", $d->{id}, $d->{y}, $d->{x}, $d->{alt}, $d->{name_txt}; # make mp type my $mptype = $d->{type} eq 'P' ? '0x6406':'0x1100'; $mptype='0x6700' if ($d->{type} eq 'P' && ($d->{ks}=~m|н.?к|i)); $mptype='0x6701' if ($d->{type} eq 'P' && ($d->{ks}=~m|1А|i || $d->{ks}=~m|1A|i)); $mptype='0x6702' if ($d->{type} eq 'P' && ($d->{ks}=~m|1Б|i || $d->{ks}=~m|1B|i)); $mptype='0x6703' if ($d->{type} eq 'P' && ($d->{ks}=~m|2А|i || $d->{ks}=~m|2A|i)); $mptype='0x6704' if ($d->{type} eq 'P' && ($d->{ks}=~m|2Б|i || $d->{ks}=~m|2B|i)); $mptype='0x6705' if ($d->{type} eq 'P' && ($d->{ks}=~m|3А|i || $d->{ks}=~m|3A|i)); $mptype='0x6706' if ($d->{type} eq 'P' && ($d->{ks}=~m|3Б|i || $d->{ks}=~m|3B|i)); print OUT_MP "[POI]\n"; print OUT_MP "Type=$mptype\n"; print OUT_MP "Label=$d->{name_mp}\n"; print OUT_MP "Source=westra_passes\n"; print OUT_MP "Data0=($d->{y},$d->{x})\n"; print OUT_MP "[END]\n\n"; }
ushakov/mapsoft
1c497326a9b09d05fe5b89a4e8c3b311f4ebc8c7
skip convs_gtiles problem in Altlinux build (build problem with new boost)
diff --git a/.gear-rules b/.gear-rules index 461a5cb..4aac8f5 100644 --- a/.gear-rules +++ b/.gear-rules @@ -1 +1,2 @@ tar: . +copy: *.patch \ No newline at end of file diff --git a/0001-skip-convs_gtiles.patch b/0001-skip-convs_gtiles.patch new file mode 100644 index 0000000..16f42d9 --- /dev/null +++ b/0001-skip-convs_gtiles.patch @@ -0,0 +1,32 @@ +From ec23abf1536ff4e6b65fb66aef990a7a129629bb Mon Sep 17 00:00:00 2001 +From: Vladislav Zavjalov <[email protected]> +Date: Thu, 21 Jan 2021 21:41:44 +0000 +Subject: [PATCH] skip convs_gtiles program + +--- + programs/SConscript | 2 -- + 1 file changed, 2 deletions(-) + +diff --git a/programs/SConscript b/programs/SConscript +index ca350a71..c91a2229 100644 +--- a/programs/SConscript ++++ b/programs/SConscript +@@ -14,7 +14,6 @@ progs = Split(""" + convs_pt2pt + convs_map2pt + convs_nom +- convs_gtiles + mapsoft_vmap + """) + +@@ -30,7 +29,6 @@ env.Install(env.bindir, Split(""" + convs_pt2pt + convs_map2pt + convs_nom +- convs_gtiles + """)) + + env.SymLink("mapsoft_vmap", "vmap_copy", env.bindir) +-- +2.24.1 + diff --git a/mapsoft.spec b/mapsoft.spec index 59d11f3..4774235 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,202 +1,204 @@ Name: mapsoft Version: 20201212 Release: alt1 License: GPL3.0 Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar +Patch1: 0001-skip-convs_gtiles.patch BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man BuildRequires: boost-geometry-devel perl-Text-Iconv %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q +%patch1 -p1 %build # boost::spirit crashes with -O2 on 32-bit systems %if "%_lib" == "lib64" export CCFLAGS=-O2 %endif scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %_bindir/map_rescale %_bindir/*.sh %_bindir/map_*_gk %_bindir/map_*_nom %_bindir/mapsoft_wp_parse %changelog * Sat Dec 12 2020 Vladislav Zavjalov <[email protected]> 20201212-alt1 - img_io/gobj_vmap: draw pattens with solid color at small scales (A.Kazantsev) - fix for gcc-10 - fix a few compilation warnings (with -Wall) and a couple of possible related errors - remove -O2 flag on i586 and armh (problem with new boost::spirit) * Sun Dec 01 2019 Vladislav Zavjalov <[email protected]> 20191201-alt1 - fix a few problems in vmap_render and convs_gtiles (thanks to A.Kazantsev) - add GPL3.0 license (Altlinux requires ambiguous license for all packages) - fix python shebang (python -> python2) * Sun Nov 10 2019 Vladislav Zavjalov <[email protected]> 20191110-alt1 - add more scripts to mapsoft_vmap package * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
08a1481a07b10adc8b8168ffdaa62d8ab06ada78
vector/vmap3/vmap_mmb_filter: convert glacier names to points
diff --git a/vector/vmap3/vmap_mmb_filter.cpp b/vector/vmap3/vmap_mmb_filter.cpp index cbf1aaa..a49b9a2 100644 --- a/vector/vmap3/vmap_mmb_filter.cpp +++ b/vector/vmap3/vmap_mmb_filter.cpp @@ -1,106 +1,124 @@ #include <string> #include <cstring> #include "options/m_getopt.h" #include "vmap/vmap.h" #include "fig/fig.h" using namespace std; // filter some things for mmb maps int main(int argc, char **argv){ try{ if (argc!=3) { std::cerr << "usage: vmap_mmb_filter in out\n"; return 1; } const char * ifile = argv[1]; const char * ofile = argv[2]; vmap::world V = vmap::read(ifile);; // find labels for each object join_labels(V); // create new labels create_labels(V); /************************/ vmap::world::iterator i=V.begin(); while (i!=V.end()){ if ((i->text == "маг") || (i->text == "маг.") || (i->text == "магазин")){ i->text = ""; i->comm.push_back(string("магазин")); std::cout << " mag fixed\n"; } if ((i->text == "гар") || (i->text == "гар.") || (i->text == "гараж") || (i->text == "гаражи")){ if (!(i->type & zn::area_mask)) {i++; continue;} i->text = ""; i->comm.push_back(string("гаражи")); i->type = 0x4 | zn::area_mask; std::cout << " gar fixed\n"; } if ((i->type == (0x8 | zn::line_mask)) || (i->type == (0x9 | zn::line_mask)) || (i->type == (0xE | zn::line_mask))){ if ((i->text == "Д") || (i->text == "д") || (i->text == "Д.") || (i->text == "д.")){ i->text = ""; std::cout << " d-bridge fixed\n"; } } if ((i->text == "пионерлагерь") || (i->text == "пионерлаг") || (i->text == "пионерлаг.")){ i->text = "п/л"; std::cout << " pionerlag -> p/l\n"; } // точки для населенных пунктов if ((i->type == (0x1 | zn::area_mask)) || (i->type == (0xE | zn::area_mask))){ if (i->text == "") {i++; continue;} vmap::object o; o.type = (i->type == (0x1 | zn::area_mask))? 0x700:0x900; o.text.swap(i->text); dLine l; l.push_back(i->center()); o.push_back(l); o.labels.swap(i->labels); i=V.insert(i, o); std::cout << " point for village\n"; } + // точки для ледников + if (i->type == (0x4D | zn::area_mask)){ + if (i->text == "") {i++; continue;} + + bool num = true; + for (auto const c: i->text) if (c < '0' || c> '9') num= false; + + vmap::object o; + o.type = num? 0x650B : 0x650C; + o.text.swap(i->text); + dLine l; l.push_back(i->center()); + o.push_back(l); + o.labels.swap(i->labels); + for (auto & l: o.labels) l.fsize=0; + i=V.insert(i, o); + std::cout << " point for glacier\n"; + } + // удаляем пустые точки if ((i->type == 0x700) || (i->type == 0x800) || (i->type == 0x900)){ if (i->text == "") { std::cout << " remove pt\n"; i=V.erase(i); continue; } } i++; } /************************/ vmap::write(ofile, V, Options()); } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
f02812e5766a81e168ab34e6021b7753a771f61c
vector/data: add new types: point 0x650B, 0x650C (glacier names)
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index 486f9e7..6697e64 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,677 +1,687 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности mp: POI 0x6406 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 24 40 -1 18 7 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 pic: ldp +- + name: номер ледника + mp: POI 0x650B 0 0 + fig: 2 1 0 3 8 7 57 -1 -1 0.000 0 1 7 0 0 1 + txt: 4 0 1 40 -1 3 5 0.0000 4 +- + name: название ледника + mp: POI 0x650C 0 0 + fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 1 7 0 0 1 + txt: 4 0 1 40 -1 3 7 0.0000 4 - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp txt: 4 0 0 40 -1 3 8 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 18 7 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор mp: POLYLINE 0x19 0 0 fig: 2 1 0 1 20 7 81 -1 -1 0.000 0 0 0 1 0 0 0 0 2.00 90.00 90.00 ocad: 819000 - name: маленькая ЛЭП mp: POLYLINE 0x1A 0 0 fig: 2 1 0 2 8947848 7 83 -1 -1 0.000 0 0 0 0 0 0 ocad: 819001 - name: пешеходный тоннель mp: POLYLINE 0x1B 0 0 fig: 2 1 0 1 3 7 77 -1 -1 0.000 0 0 0 0 0 0 ocad: 819002 - name: просека широкая mp: POLYLINE 0x1C 0 1 fig: 2 1 1 2 0 7 80 -1 -1 6.000 1 0 0 0 0 0 ocad: 819003 - name: граница стран, областей mp: POLYLINE 0x1D 0 2 fig: 2 1 0 7 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница областей, районов mp: POLYLINE 0x36 0 2 fig: 2 1 0 5 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница заповедников, парков mp: POLYLINE 0x37 0 2 fig: 2 1 0 5 2 7 91 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 819004 - name: нижний край обрыва mp: POLYLINE 0x1E 0 0 fig: 2 1 2 1 18 7 79 -1 -1 2.000 1 1 7 0 0 0 - name: пунктирная горизонталь mp: POLYLINE 0x20 0 0 fig: 2 1 1 1 HOR_COL 7 90 -1 -1 4.000 1 1 0 0 0 0 ocad: 820000 curve: 100 - name: горизонтали, бергштрихи mp: POLYLINE 0x21 0 0 fig: 2 1 0 1 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 821000 curve: 100 - name: жирная горизонталь mp: POLYLINE 0x22 0 0 fig: 2 1 0 2 HOR_COL 7 90 -1 -1 0.000 1 1 0 0 0 0 ocad: 822000 curve: 100 - name: контур леса mp: POLYLINE 0x23 0 0 fig: 2 1 2 1 12 7 96 -1 -1 2.000 1 1 0 0 0 0 ocad: 823000 - name: болото mp: POLYLINE 0x24 0 0 fig: 2 1 0 1 5269247 7 87 -1 -1 0.000 0 1 0 0 0 0 ocad: 824000 - name: овраг mp: POLYLINE 0x25 0 0 fig: 2 1 0 2 25 7 89 -1 -1 0.000 1 1 0 0 0 0 ocad: 825000 curve: 50 - name: УЖД mp: POLYLINE 0x0D 0 2 fig: 2 1 0 3 0 7 80 -1 -1 0.000 1 0 0 0 0 0 curve: 100 - name: железная дорога mp: POLYLINE 0x27 0 2 fig: 2 1 0 4 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 827000 curve: 100 - name: газопровод mp: POLYLINE 0x28 0 1 fig: 2 1 1 3 8947848 7 83 -1 -1 4.000 1 0 0 0 0 0 ocad: 828000 - name: ЛЭП mp: POLYLINE 0x29 0 1 fig: 2 1 0 3 8947848 7 83 -1 -1 0.000 1 0 0 0 0 0 ocad: 829000 - name: тропа mp: POLYLINE 0x2A 0 0 fig: 2 1 2 1 0 7 80 -1 -1 2.000 1 0 0 0 0 0 ocad: 829001 curve: 50 - name: сухая канава mp: POLYLINE 0x2B 0 0 fig: 2 1 2 1 26 7 82 -1 -1 2.000 1 1 0 0 0 0
ushakov/mapsoft
5efb1529722ac1cf3b83eb9423545634aeec00d7
vector/vmap3: add vmap_put_track and vmap_get_track programs
diff --git a/vector/vmap3/SConscript b/vector/vmap3/SConscript index 539f01c..b34ae47 100644 --- a/vector/vmap3/SConscript +++ b/vector/vmap3/SConscript @@ -1,10 +1,13 @@ Import ('env') env.Program("vmap_render.cpp") env.Program("vmap_mmb_filter.cpp") env.Program("vmap_1km_filter.cpp") env.Program("vmap_fix_diff.cpp") +env.Program("vmap_get_track.cpp") +env.Program("vmap_put_track.cpp") + env.Install(env.bindir, Split(""" vmap_render """)) diff --git a/vector/vmap3/vmap_get_track.cpp b/vector/vmap3/vmap_get_track.cpp new file mode 100644 index 0000000..8177206 --- /dev/null +++ b/vector/vmap3/vmap_get_track.cpp @@ -0,0 +1,74 @@ +#include <string> +#include <cstring> +#include "options/m_getopt.h" +#include "vmap/vmap.h" +#include "vmap/zn.h" +#include "fig/fig.h" +#include "geo_io/io.h" + +using namespace std; + +// extract objects of a single type +// and write as geodata + +int +main(int argc, char **argv){ +try{ + + if (argc!=5) { + std::cerr << "usage: vmap_get_track <class> <type> <in map> <out geodata>\n"; + return 1; + } + std::string cl(argv[1]); + int type = atoi(argv[2]); + const char * ifile = argv[3]; + const char * ofile = argv[4]; + + if (cl == "POI"){ } + else if (cl == "POLYLINE") type |= zn::line_mask; + else if (cl == "POLYGON") type |= zn::area_mask; + else throw Err() << "unknown object class: " << cl; + + vmap::world V = vmap::read(ifile); + geo_data data; + g_waypoint_list wpts; + + for (auto const & o:V) { + if (o.type != type) continue; + if (o.size()<1) continue; + if (cl == "POI" && o[0].size()>0){ + for (auto const & l:o) { + for (auto const & p:l) { + g_waypoint pt; + pt.x = p.x; + pt.y = p.y; + pt.name = o.text; + wpts.push_back(pt); + } + } + } + else { + for (auto const & l:o) { + g_track tr; + for (auto const & p:l) { + g_trackpoint pt; + pt.x = p.x; + pt.y = p.y; + tr.push_back(pt); + } + data.trks.push_back(tr); + } + } + } + if (wpts.size()) data.wpts.push_back(wpts); + + io::out(ofile, data, Options()); +} +catch (Err e) { + cerr << e.get_error() << endl; + return 1; +} +return 0; +} + + diff --git a/vector/vmap3/vmap_put_track.cpp b/vector/vmap3/vmap_put_track.cpp new file mode 100644 index 0000000..11756bb --- /dev/null +++ b/vector/vmap3/vmap_put_track.cpp @@ -0,0 +1,92 @@ +#include <string> +#include <cstring> +#include "options/m_getopt.h" +#include "vmap/vmap.h" +#include "vmap/zn.h" +#include "fig/fig.h" +#include "geo_io/io.h" + +using namespace std; + +// replace objects of a single type +// in a map using geodata + +int +main(int argc, char **argv){ +try{ + + if (argc!=5) { + std::cerr << "usage: vmap_put_track <class> <type> <in geodata> <out map> \n"; + return 1; + } + std::string cl(argv[1]); + int type = atoi(argv[2]); + const char * ifile = argv[3]; + const char * ofile = argv[4]; + + if (cl == "POI"){ } + else if (cl == "POLYLINE") type |= zn::line_mask; + else if (cl == "POLYGON") type |= zn::area_mask; + else throw Err() << "unknown object class: " << cl; + + vmap::world V = vmap::read(ofile); + geo_data data; + io::in(ifile, data); + + // remove old objects: + vmap::world::iterator i=V.begin(); + while (i!=V.end()){ + if (i->type == type) { + i=V.erase(i); + continue; + } + i++; + } + + // put objects + + if (cl == "POI"){ + for (auto const & pts:data.wpts) { + for (auto const & pt:pts) { + vmap::object o; + dLine l; + l.push_back(pt); + o.push_back(l); + o.text=pt.name; + o.type=type; + V.push_back(o); + } + } + } + else { + for (auto const & t:data.trks) { + vmap::object o; +// o.text=t.comm; + o.type=type; + dLine l; + for (auto const & pt:t) { + if (pt.start && l.size()){ + o.push_back(l); + V.push_back(o); + l.clear(); + o.clear(); + } + l.push_back(pt); + } + if (l.size()){ + o.push_back(l); + V.push_back(o); + } + } + } + + vmap::write(ofile, V); +} +catch (Err e) { + cerr << e.get_error() << endl; + return 1; +} +return 0; +} + +
ushakov/mapsoft
51b65054dbec044343dc55418afbbc462573a22e
programs/mapsoft_map2fig: put images into compound object; add 50px margins
diff --git a/programs/mapsoft_map2fig.cpp b/programs/mapsoft_map2fig.cpp index 9dc4adf..1637a2a 100644 --- a/programs/mapsoft_map2fig.cpp +++ b/programs/mapsoft_map2fig.cpp @@ -1,131 +1,149 @@ #include <string> #include <sstream> #include <fstream> #include <iostream> #include <sys/stat.h> #include "img_io/gobj_map.h" #include "geo_io/io.h" #include "geo/geo_convs.h" #include "loaders/image_r.h" #include "geo_io/geofig.h" #include "err/err.h" using namespace std; // добавление растровой карты в fig-файл. // диапазон карты - по объекту с комментарием BRD или по диапазону точек привязки... // карта режится на куски размером не более tsize x tsize // картинки кладутся в директорию <fig>.img под названиями m1-1.jpg m1-2.jpg и т.д. const int tsize = 1024; void usage(){ cerr << "usage: \n" " mapsoft_map2fig <fig> map <depth> <map file 1> [<map file 2> ...]\n"; } int main(int argc, char **argv){ if (argc<5){ usage(); return 0; } string fig_name = argv[1]; string source = argv[2]; string depth = argv[3]; if (source != "map"){ usage(); return 0; } // read data geo_data *world = new geo_data; for(int i=4;i<argc;i++){ try {io::in(string(argv[i]), *world);} catch (Err e) {cerr << e.get_error() << endl;} } // put all maps into one map_list g_map_list maps; for (vector<g_map_list>::const_iterator mi = world->maps.begin(); mi!=world->maps.end(); mi++) maps.insert(maps.end(), mi->begin(), mi->end()); // create gobj, get ref GObjMAP ml(&maps); g_map map_ref = ml.get_myref(); // read fig fig::fig_world F; if (!fig::read(fig_name.c_str(), F)) { cerr << "Read error. File is not modified, exiting.\n"; return 1; } // нам нужно установить в gobj привязку fig-файла, но перемаштабированную // нужным образом g_map fig_ref = fig::get_ref(F); // rescale > 1, если точки fig меньше точки растра double rescale = convs::map_mpp(map_ref, map_ref.map_proj)/ convs::map_mpp(fig_ref, map_ref.map_proj); // scales in one proj fig_ref/=rescale; // теперь fig_ref - в координатах растра ml.set_ref(fig_ref); // диапазон картинки в координатах растра dRect range = fig_ref.border.range(); + range = rect_pump(range, 50.0,50.0); // создадим директорию для картинок string dir_name = fig_name + ".img"; struct stat st; if (stat(dir_name.c_str(), &st)!=0){ if (mkdir(dir_name.c_str(), 0755)!=0){ cerr << "can't mkdir " << dir_name << "\n"; return 1; } } else if (!S_ISDIR(st.st_mode)){ cerr << dir_name << " is not a directory\n"; return 1; } int nx = int(range.w)/(tsize-1)+1; // число плиток int ny = int(range.h)/(tsize-1)+1; double dx = range.w / double(nx); // размер плиток double dy = range.h / double(ny); cerr << " rescale: " << rescale << "\n"; cerr << " range: " << range << "\n"; cerr << nx << " x " << ny << " tiles\n"; cerr << dx << " x " << dy << " tile_size\n"; + // start compound object + { + fig::fig_object o; + o.type = 6; + o.push_back(range.TLC()*rescale); + o.push_back(range.BRC()*rescale); + F.push_back(o); + } + for (int j = 0; j<ny; j++){ for (int i = 0; i<nx; i++){ dPoint tlc(range.x+i*dx, range.y+j*dy); iImage im = ml.get_image(iRect(tlc, tlc+dPoint(dx,dy))); if (im.empty()) continue; ostringstream fname; fname << dir_name << "/" << source[0] << depth << "-" << i << "-" << j << ".jpg"; image_r::save(im, fname.str().c_str()); fig::fig_object o = fig::make_object("2 5 0 1 0 -1 "+depth+" -1 -1 0.000 0 0 -1 0 0 *"); o.push_back(tlc*rescale); o.push_back((tlc+dPoint(dx,0))*rescale); o.push_back((tlc+dPoint(dx,dy))*rescale); o.push_back((tlc+dPoint(0,dy))*rescale); o.push_back(tlc*rescale); o.image_file = fname.str(); o.comment.push_back("MAP "+fname.str()); F.push_back(o); } } + + // finish compound object + { + fig::fig_object o; + o.type = -6; + F.push_back(o); + } + fig::write(fig_name, F); return 0; }
ushakov/mapsoft
55399c6158b4a57cc08942df2e39d24d3a576ff1
20201212-alt1
diff --git a/mapsoft.spec b/mapsoft.spec index 0bde348..59d11f3 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,196 +1,202 @@ Name: mapsoft -Version: 20191201 +Version: 20201212 Release: alt1 License: GPL3.0 Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man BuildRequires: boost-geometry-devel perl-Text-Iconv %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build # boost::spirit crashes with -O2 on 32-bit systems %if "%_lib" == "lib64" export CCFLAGS=-O2 %endif scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %_bindir/map_rescale %_bindir/*.sh %_bindir/map_*_gk %_bindir/map_*_nom %_bindir/mapsoft_wp_parse %changelog +* Sat Dec 12 2020 Vladislav Zavjalov <[email protected]> 20201212-alt1 +- img_io/gobj_vmap: draw pattens with solid color at small scales (A.Kazantsev) +- fix for gcc-10 +- fix a few compilation warnings (with -Wall) and a couple of possible related errors +- remove -O2 flag on i586 and armh (problem with new boost::spirit) + * Sun Dec 01 2019 Vladislav Zavjalov <[email protected]> 20191201-alt1 - fix a few problems in vmap_render and convs_gtiles (thanks to A.Kazantsev) - add GPL3.0 license (Altlinux requires ambiguous license for all packages) - fix python shebang (python -> python2) * Sun Nov 10 2019 Vladislav Zavjalov <[email protected]> 20191110-alt1 - add more scripts to mapsoft_vmap package * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
1e275af72da3852dc2b38310e19034f429b2ea3c
remove -O2 flag on i586 and armh (problem with boost::spirit)
diff --git a/SConstruct b/SConstruct index 7b2623d..67f5f27 100644 --- a/SConstruct +++ b/SConstruct @@ -1,102 +1,104 @@ ###################################### # What do we want to build subdirs_min = Split("core programs viewer vector man scripts") subdirs_max = subdirs_min + Split("tests misc") ###################################### ## import python libraries import os import platform if platform.python_version()<"2.7": import distutils.sysconfig as sysconfig else: import sysconfig ###################################### # Create environment, add some methods env = Environment () Export('env') # UseLibs -- use pkg-config libraries def UseLibs(env, libs): if isinstance(libs, list): libs = " ".join(libs) env.ParseConfig('pkg-config --cflags --libs %s' % libs) env.AddMethod(UseLibs) # SymLink -- create a symlink # Arguments target and linkname follow standard order (look at ln(1)) # wd is optional base directory for both def SymLink(env, target, linkname, wd=None): if wd: env.Command(wd+'/'+linkname, wd+'/'+target, "ln -s -- %s %s/%s" % (target, wd, linkname)) else: env.Command(linkname, target, "ln -s -- %s %s" % (target, linkname)) env.AddMethod(SymLink) ###################################### ## Add default flags if 'GCCVER' in os.environ: ver = os.environ['GCCVER'] env.Replace (CC = ("gcc-%s" % ver)) env.Replace (CXX = ("g++-%s" % ver)) +if 'CCFLAGS' in os.environ: + env.Append (CCFLAGS=os.environ['CCFLAGS']) + env.Append (CCFLAGS=['-DACCEPT_USE_OF_DEPRECATED_PROJ_API_H=1']) env.Append (CCFLAGS=['-Werror=return-type', '-Wall']) -env.Append (CCFLAGS=['-O2']) env.Append (CCFLAGS='-std=gnu++11') env.Append (ENV = {'PKG_CONFIG_PATH': os.getcwd()+'/core/pc'}) if os.getenv('PKG_CONFIG_PATH'): env.Append (ENV = {'PKG_CONFIG_PATH': [ os.getcwd()+'/core/pc', os.getenv('PKG_CONFIG_PATH')]}) env.Append (CPPPATH = "#core") env.Append (LIBPATH = "#core") env.Append (LIBS = "mapsoft") ###################################### ## Parse command-line arguments: env.PREFIX = ARGUMENTS.get('prefix', '') env.bindir=env.PREFIX+'/usr/bin' env.datadir=env.PREFIX+'/usr/share/mapsoft' env.man1dir=env.PREFIX+'/usr/share/man/man1' env.figlibdir=env.PREFIX+'/usr/share/xfig/Libraries' env.libdir=env.PREFIX+ sysconfig.get_config_var('LIBDIR') env.desktopdir=env.PREFIX+'/usr/share/applications' env.Alias('install', [env.bindir, env.man1dir, env.datadir, env.figlibdir, env.libdir, env.desktopdir]) if ARGUMENTS.get('debug', 0): env.Append (CCFLAGS='-ggdb') env.Append (LINKFLAGS='-ggdb') if ARGUMENTS.get('profile', 0): env.Append (CCFLAGS='-pg') env.Append (LINKFLAGS='-pg') if ARGUMENTS.get('gprofile', 0): env.Append (LINKFLAGS='-lprofiler') if ARGUMENTS.get('gheapcheck', 0): env.Append (LINKFLAGS='-ltcmalloc') if ARGUMENTS.get('minimal', 0): SConscript(list(map(lambda s: s + "/SConscript", subdirs_min))) else: SConscript(list(map(lambda s: s + "/SConscript", subdirs_max))) Help(""" You can build mapsoft with the following options: scons -Q debug=1 // build with -ggdb scons -Q profile=1 // build with -pg scons -Q gheapcheck=1 // build with -ltcmalloc scons -Q minimal=1 // skip misc and tests dirs scons -Q prefix=<prefix> // set installation prefix """) # vim: ft=python tw=0 diff --git a/mapsoft.spec b/mapsoft.spec index 36647a2..0bde348 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,191 +1,196 @@ Name: mapsoft Version: 20191201 Release: alt1 License: GPL3.0 Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man BuildRequires: boost-geometry-devel perl-Text-Iconv %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build +# boost::spirit crashes with -O2 on 32-bit systems +%if "%_lib" == "lib64" +export CCFLAGS=-O2 +%endif + scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %_bindir/map_rescale %_bindir/*.sh %_bindir/map_*_gk %_bindir/map_*_nom %_bindir/mapsoft_wp_parse %changelog * Sun Dec 01 2019 Vladislav Zavjalov <[email protected]> 20191201-alt1 - fix a few problems in vmap_render and convs_gtiles (thanks to A.Kazantsev) - add GPL3.0 license (Altlinux requires ambiguous license for all packages) - fix python shebang (python -> python2) * Sun Nov 10 2019 Vladislav Zavjalov <[email protected]> 20191110-alt1 - add more scripts to mapsoft_vmap package * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
b33a5b9ca19df293b4073343fa77cafa013d7352
core/vmap/zn.cpp: fix error in make_labels (should not have any effect)
diff --git a/core/vmap/zn.cpp b/core/vmap/zn.cpp index a7cfd11..7d263f0 100644 --- a/core/vmap/zn.cpp +++ b/core/vmap/zn.cpp @@ -195,675 +195,675 @@ zn_conv::zn_conv(const string & style_): style(style_){ z.fig=default_fig; z.mp=default_mp; z.ocad=z.ocad_txt=0; state=KEY; } if (event.type == YAML_MAPPING_END_EVENT){ int type = get_type(z.mp); // add label_type if (z.txt.type == 4){ if (z.txt.sub_type==0){ // text on the TR side z.label_type=1; z.label_dir=0; } else if (z.txt.sub_type==2){ // text on the TL side z.label_type=2; z.label_dir=2; } else if (z.txt.sub_type==1) { //centered text z.label_dir=1; if (type & line_mask) z.label_type=4; // text along the line else z.label_type=3; // text on the center } } else{ z.txt=default_txt; z.label_type=0; z.label_dir=0; } znaki.insert(pair<int, zn>(type, z)); state=N; } if ( (event.type == YAML_SCALAR_EVENT) && (state==KEY)){ state=VAL; key.clear(); key.insert(0, (const char *)event.data.scalar.value, event.data.scalar.length); continue; } if ( (event.type == YAML_SCALAR_EVENT) && (state==VAL)){ state=KEY; val.clear(); val.insert(0, (const char *)event.data.scalar.value, event.data.scalar.length); if (key=="name"){ z.name = val; continue; } if (key=="mp"){ z.mp = mp::make_object(val); continue; } if (key=="fig"){ z.fig = fig::make_object(val); if (min_depth>z.fig.depth) min_depth=z.fig.depth; if (max_depth<z.fig.depth) max_depth=z.fig.depth; continue; } if (key=="desc"){ z.desc = val; continue; } if (key=="txt"){ z.txt = fig::make_object(val); if (z.txt.type!=4){ throw Err() << "Error while reading " << conf_file << ": " << "bad txt object in "<< z.name; } continue; } if (key=="pic"){ z.pic = val; if (z.pic!=""){ struct stat st_buf; string g_pd="/usr/share/mapsoft/pics/"; string l_pd="./pics/"; if (stat((l_pd+z.pic+".fig").c_str(), &st_buf) == 0) z.pic=l_pd+z.pic; else if (stat((g_pd+z.pic+".fig").c_str(), &st_buf) == 0) z.pic=g_pd+z.pic; else { throw Err() << "Error while reading " << conf_file << ": " << "can't find zn picture " << z.pic << ".fig" << " in " << l_pd << " or " << g_pd; } } continue; } if (key=="pic_type"){ z.pic_type = val; continue; } if (key=="ocad"){ z.ocad = atoi(val.c_str()); continue; } if (key=="ocad_txt"){ z.ocad_txt = atoi(val.c_str()); continue; } if ((key=="move_to") || (key=="rotate_to")){ istringstream str(val); int i; while (str.good()){ str >> hex >> i; if (str.good() || str.eof()) z.move_to.push_back(i); } z.rotate = (key=="rotate_to"); continue; } if (key=="replace_by"){ istringstream str(val); int i; str >> hex >> i; if (str.good() || str.eof()) z.replace_by = i; continue; } if (key=="curve"){ z.curve = atoi(val.c_str()); continue; } cerr << "Warning while reading " << conf_file << ": " << "unknown field: " << key << "\n"; continue; } yaml_event_delete(&event); } while (history.size()>0); yaml_parser_delete(&parser); assert(!fclose(file)); } // определить тип mp-объекта (почти тривиальная функция :)) int zn_conv::get_type(const mp::mp_object & o) const{ return o.Type + ((o.Class == "POLYLINE")?line_mask:0) + ((o.Class == "POLYGON")?area_mask:0); } // определить тип fig-объекта по внешнему виду. int zn_conv::get_type (const fig::fig_object & o) const { if ((o.type!=2) && (o.type!=3) && (o.type!=4)) return 0; // объект неинтересного вида for (map<int, zn>::const_iterator i = znaki.begin(); i!=znaki.end(); i++){ int c1 = o.pen_color; int c2 = i->second.fig.pen_color; if (((o.type==2) || (o.type==3)) && (o.size()>1)){ // должны совпасть глубина и толщина if ((o.depth != i->second.fig.depth) || (o.thickness != i->second.fig.thickness)) continue; // для линий толщины не 0 - еще и цвет и тип линии if ((o.thickness != 0 ) && ((c1 != c2) || (o.line_style != i->second.fig.line_style))) continue; // заливки int af1 = o.area_fill; int af2 = i->second.fig.area_fill; int fc1 = o.fill_color; int fc2 = i->second.fig.fill_color; // белая заливка бывает двух видов if ((fc1!=0xffffff)&&(af1==40)) {fc1=0xffffff; af1=20;} if ((fc2!=0xffffff)&&(af2==40)) {fc2=0xffffff; af2=20;} // тип заливки должен совпасть if (af1 != af2) continue; // если заливка непрозрачна, то и цвет заливки должен совпасть if ((af1!=-1) && (fc1 != fc2)) continue; // если заливка - штриховка, то и pen_color должен совпасть // (даже для линий толщины 0) if ((af1>41) && (c1 != c2)) continue; // проведя все тесты, мы считаем, что наш объект соответствует // объекту из znaki! return i->first; } else if (((o.type==2) || (o.type==3)) && (o.size()==1)){ // точки // должны совпасть глубина, толщина, цвет, и закругление if ((o.depth == i->second.fig.depth) && (o.thickness == i->second.fig.thickness) && (c1 == c2) && (o.cap_style%2 == i->second.fig.cap_style%2)) return i->first; } else if (o.type==4){ //текст // должны совпасть глубина, цвет, и шрифт if ((o.depth == i->second.fig.depth) && (c1 == c2) && (o.font == i->second.fig.font)) return i->first; } } return 0; } // определить тип по номеру ocad-объекта int zn_conv::get_type(const int ocad_type) const{ for (map<int, zn>::const_iterator i = znaki.begin(); i!=znaki.end(); i++){ if (i->second.ocad == ocad_type) return (i-> first); } return 0; } map<int, zn>::const_iterator zn_conv::find_type(int type){ map<int, zn>::const_iterator ret = znaki.find(type); if (ret == znaki.end()){ if (unknown_types.count(type) == 0){ cerr << "zn: unknown type: 0x" << setbase(16) << type << setbase(10) << "\n"; unknown_types.insert(type); } } return ret; } // Получить заготовку fig-объекта заданного типа fig::fig_object zn_conv::get_fig_template(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.fig; else return default_fig; } // Получить заготовку mp-объекта заданного типа mp::mp_object zn_conv::get_mp_template(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.mp; else return default_mp; } // Получить номер объекта ocad int zn_conv::get_ocad_type(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.ocad; else return default_ocad; } // Получить заготовку fig-подписи заданного типа fig::fig_object zn_conv::get_label_template(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.txt; else return default_txt; } // Получить номер объекта для подписи ocad int zn_conv::get_ocad_label_type(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.ocad_txt; else return default_ocad_txt; } // Получить тип подписи (для несуществующих - 0) int zn_conv::get_label_type(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.label_type; else return 0; } // Получить направление подписи (для несуществующих - 0) int zn_conv::get_label_dir(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.label_dir; else return 0; } // Преобразовать mp-объект в fig-объект // Если тип 0, то он определяется функцией get_type по объекту list<fig::fig_object> zn_conv::mp2fig(const mp::mp_object & mp, convs::map2pt & cnv, int type){ if (type ==0) type = get_type(mp); list<fig::fig_object> ret; fig::fig_object ret_o = get_fig_template(type); if (ret_o.type == 4){ ret_o.text = mp.Label; ret_o.comment.push_back(""); } else { ret_o.comment.push_back(mp.Label); } ret_o.comment.insert(ret_o.comment.end(), mp.Comment.begin(), mp.Comment.end()); string source=mp.Opts.get<string>("Source"); if (source!="") ret_o.opts.put("Source", source); // convert points if (mp.Class == "POLYGON"){ ret_o.set_points(cnv.line_bck(join_polygons(mp))); ret.push_back(ret_o); } else { for (dMultiLine::const_iterator i=mp.begin(); i!=mp.end(); i++){ ret_o.clear(); ret_o.set_points(cnv.line_bck(*i)); // замкнутая линия if ((mp.Class == "POLYLINE") && (ret_o.size()>1) && (ret_o[0]==ret_o[ret_o.size()-1])){ ret_o.resize(ret_o.size()-1); ret_o.close(); } // стрелки fig_dir2arr(ret_o, mp.Opts.get("DirIndicator",0) ); ret.push_back(ret_o); } } return ret; } // преобразовать fig-объект в mp-объект // Если тип 0, то он определяется функцией get_type по объекту mp::mp_object zn_conv::fig2mp(const fig::fig_object & fig, convs::map2pt & cnv, int type){ if (type ==0) type = get_type(fig); mp::mp_object mp = get_mp_template(type); mp.Opts = fig.opts; if (fig.type == 4){ mp.Label = fig.text; mp.Comment=fig.comment; } else if (fig.comment.size()>0){ mp.Label = fig.comment[0]; mp.Comment.insert(mp.Comment.begin(), fig.comment.begin()+1, fig.comment.end()); } string source=fig.opts.get<string>("Source"); if (source != "") mp.Opts.put("Source", source); dLine pts = cnv.line_frw(fig); // если у нас замкнутая линия - добавим в mp еще одну точку: if ((mp.Class == "POLYLINE") && (fig.is_closed()) && (fig.size()>0) && (fig[0]!=fig[fig.size()-1])) pts.push_back(pts[0]); mp.push_back(pts); // если есть стрелка вперед -- установить DirIndicator=1 // если есть стрелка назад -- установить DirIndicator=2 if ((fig.forward_arrow==1)&&(fig.backward_arrow==0)) mp.Opts["DirIndicator"]="1"; if ((fig.forward_arrow==0)&&(fig.backward_arrow==1)) mp.Opts["DirIndicator"]="2"; return mp; } // Поменять параметры в соответствии с типом. // Если тип 0, то он определяется функцией get_type по объекту void zn_conv::fig_update(fig::fig_object & fig, int type){ if (type ==0) type = get_type(fig); fig::fig_object tmp = get_fig_template(type); // копируем разные параметры: fig.line_style = tmp.line_style; fig.thickness = tmp.thickness; fig.pen_color = tmp.pen_color; fig.fill_color = tmp.fill_color; fig.depth = tmp.depth; fig.pen_style = tmp.pen_style; fig.area_fill = tmp.area_fill; fig.style_val = tmp.style_val; fig.cap_style = tmp.cap_style; fig.join_style = tmp.join_style; fig.font = tmp.font; fig.font_size = tmp.font_size; fig.font_flags = tmp.font_flags; } // Поменять параметры подписи в соответствии с типом // (шрифт, размер, цвет) // Если тип 0 - ничего не менять void zn_conv::label_update(fig::fig_object & fig, int type){ fig::fig_object tmp = get_label_template(type); fig.pen_color = tmp.pen_color; fig.font = tmp.font; fig.font_size = tmp.font_size; fig.depth = tmp.depth; } // Создать картинку к объекту в соответствии с типом. list<fig::fig_object> zn_conv::make_pic(const fig::fig_object & fig, int type){ list<fig::fig_object> ret; if (fig.size()==0) return ret; ret.push_back(fig); if (type ==0) type = get_type(fig); map<int, zn>::const_iterator z = find_type(type); if (z == znaki.end()) return ret; if (z->second.pic=="") return ret; // нет картинки if ((type & area_mask) || (type & line_mask)) return ret; fig::fig_world PIC; if (!fig::read((z->second.pic+".fig").c_str(), PIC)) return ret; // нет картинки for (fig::fig_world::iterator i = PIC.begin(); i!=PIC.end(); i++){ (*i) += fig[0]; // if (is_map_depth(*i)){ // cerr << "warning: picture in " << z->second.pic // << " has objects with wrong depth!\n"; // } i->opts["MapType"]="pic"; ret.push_back(*i); } fig::fig_make_comp(ret); if (fig.opts.exists("Angle")){ double a = fig.opts.get<double>("Angle", 0); fig::fig_rotate(ret, M_PI/180.0*a, fig[0]); } // скопируем комментарии из первого объекта в составной объект. if (ret.size()>1) ret.begin()->comment.insert(ret.begin()->comment.begin(), fig.comment.begin(), fig.comment.end()); return ret; } // Создать подписи к объекту. list<fig::fig_object> zn_conv::make_labels(const fig::fig_object & fig, int type){ list<fig::fig_object> ret; if (fig.size() == 0) return ret; // странный объект if (type ==0) type = get_type(fig); map<int, zn>::const_iterator z = find_type(type); if (z==znaki.end()) return ret; int lpos = z->second.label_type; if (!lpos) return ret; // no label for this object if ((fig.comment.size()==0)|| (fig.comment[0].size()==0)) return ret; // empty label fig::fig_object txt = z->second.txt; // label template if (is_map_depth(txt)){ cerr << "Error: label depth " << txt.depth << " is in map object depth range!"; return ret; } int txt_dist = 7 * (fig.thickness+2); // fig units // определим координаты и наклон подписи iPoint p = fig[0]; if (fig.size()>=2){ if (lpos==4){ // label along the line p = (fig[fig.size()/2-1] + fig[fig.size()/2]) / 2; iPoint p1 = fig[fig.size()/2-1] - fig[fig.size()/2]; if ((p1.x == 0) && (p1.y == 0)) p1.x = 1; dPoint v = pnorm(p1); if (v.x<0) v=-v; txt.angle = atan2(-v.y, v.x); p-= iPoint(int(-v.y*txt_dist*2), int(v.x*txt_dist*2)); } else if (lpos==1 ) { // left just.text // ищем точку с максимальным x-y p = fig[0]; int max = p.x-p.y; for (size_t i = 0; i<fig.size(); i++){ if (fig[i].x-fig[i].y > max) { max = fig[i].x-fig[i].y; p = fig[i]; } } p+=iPoint(1,-1)*txt_dist; } else if (lpos==2) { // right just.text // ищем точку с минимальным x+y p = fig[0]; int min = p.x+p.y; for (size_t i = 0; i<fig.size(); i++){ if (fig[i].x+fig[i].y < min) { min = fig[i].x+fig[i].y; p = fig[i]; } } p+=iPoint(-1,-1)*txt_dist; - } else if (lpos=3 ) { // center + } else if (lpos==3 ) { // center // ищем середину объекта iPoint pmin = fig[0]; iPoint pmax = fig[0]; for (size_t i = 0; i<fig.size(); i++){ if (pmin.x > fig[i].x) pmin.x = fig[i].x; if (pmin.y > fig[i].y) pmin.y = fig[i].y; if (pmax.x < fig[i].x) pmax.x = fig[i].x; if (pmax.y < fig[i].y) pmax.y = fig[i].y; } p=(pmin+pmax)/2; } } else { // one-point object if (lpos == 1 ) p += iPoint(1,-1)*txt_dist; else if (lpos == 2 ) p += iPoint(-1,-1)*txt_dist; else if (lpos == 3 ) p += iPoint(0, 0)*txt_dist; else if (lpos == 4 ) p += iPoint(0,-2)*txt_dist; } txt.text = fig.comment[0]; txt.push_back(p); ret.push_back(txt); return(ret); } // Depth region in wich all crtographic objects live. // Its boundaries are minimal and maximum depth of objects in config file bool zn_conv::is_map_depth(const fig::fig_object & o) const{ return ((o.type!=6) && (o.type!=-6) && (o.depth>=min_depth) && (o.depth<=max_depth)); } /// functions for updating fig map int zn_conv::fig_add_pics(fig::fig_world & F){ fig::fig_world::iterator i=F.begin(); int count=0; while (i!=F.end()){ if (is_map_depth(*i)){ std::list<fig::fig_object> l1 = make_pic(*i, get_type(*i)); if (l1.size()>1){ count++; i=F.erase(i); F.insert(i, l1.begin(), l1.end()); continue; } } i++; } return count; } int zn_conv::fig_update_labels(fig::fig_world & F){ double maxd1=1*fig::cm2fig; // for the nearest label with correct text double maxd2=1*fig::cm2fig; // for other labels with correct text double maxd3=0.2*fig::cm2fig; // for other labels fig::fig_world::iterator i; // find all labels std::list<fig::fig_world::iterator> labels; for (i=F.begin(); i!=F.end(); i++){ if ((i->opts.exists("MapType")) && (i->opts["MapType"]=="label") && (i->opts.exists("RefPt")) ){ labels.push_back(i); } } // find all objects with title std::list<std::pair<fig::fig_world::iterator, int> > objs; for (i=F.begin(); i!=F.end(); i++){ if (!is_map_depth(*i) || (i->size() <1)) continue; int type=get_type(*i); if ((znaki.count(type)<1) || !znaki[type].label_type) continue; if ((i->comment.size()>0) && (i->comment[0]!="")) objs.push_back(std::pair<fig::fig_world::iterator, int>(i,0)); } std::list<fig::fig_world::iterator>::iterator l; std::list<std::pair<fig::fig_world::iterator, int> >::iterator o; // one nearest label with correct text for (o=objs.begin(); o!=objs.end(); o++){ double d0=1e99; std::list<fig::fig_world::iterator>::iterator l0; iPoint n0; for (l=labels.begin(); l!=labels.end(); l++){ if ((*l)->text != o->first->comment[0]) continue; iPoint nearest; double d=dist((*l)->opts.get("RefPt", iPoint(0,0)), *(o->first), nearest); if ( d < d0){ d0=d; n0=nearest; l0=l;} } if (d0 < maxd1){ (*l0)->opts.put("RefPt", n0); label_update(**l0, get_type(*(o->first))); o->second++; labels.erase(l0); } } // labels with correct text for (o=objs.begin(); o!=objs.end(); o++){ l=labels.begin(); while (l!=labels.end()){ iPoint nearest; if (((*l)->text == o->first->comment[0]) && (dist((*l)->opts.get("RefPt", iPoint(0,0)), *(o->first), nearest) < maxd2)){ (*l)->opts.put("RefPt", nearest); label_update(**l, get_type(*(o->first))); o->second++; l=labels.erase(l); continue; } l++; } } // labels with changed text for (o=objs.begin(); o!=objs.end(); o++){ l=labels.begin(); while (l!=labels.end()){ iPoint nearest; if (dist((*l)->opts.get("RefPt", iPoint(0,0)), *(o->first), nearest) < maxd3){ (*l)->text=o->first->comment[0]; (*l)->opts.put("RefPt", nearest); label_update(**l, get_type(*(o->first))); o->second++; l=labels.erase(l); continue; } l++; } } // create new labels for (o=objs.begin(); o!=objs.end(); o++){ if (o->second > 0) continue; std::list<fig::fig_object> L=make_labels(*(o->first)); for (std::list<fig::fig_object>::iterator j=L.begin(); j!=L.end(); j++){ if (j->size() < 1) continue; iPoint nearest; dist((*j)[0], *(o->first), nearest); j->opts["MapType"]="label"; j->opts.put("RefPt", nearest); F.push_back(*j); } } // remove unused labels for (l=labels.begin(); l!=labels.end(); l++) F.erase(*l); return 0; } } // namespace
ushakov/mapsoft
c048d1c517bca07226b9f73e40629adda433dc50
fix more warnings
diff --git a/core/mp/mp_io.cpp b/core/mp/mp_io.cpp index 3fac45e..df65852 100644 --- a/core/mp/mp_io.cpp +++ b/core/mp/mp_io.cpp @@ -1,224 +1,223 @@ #include "utils/spirit_utils.h" #include <boost/spirit/include/classic_assign_actor.hpp> #include <boost/spirit/include/classic_push_back_actor.hpp> #include <boost/spirit/include/classic_insert_at_actor.hpp> #include <boost/spirit/include/classic_clear_actor.hpp> #include <boost/spirit/include/classic_erase_actor.hpp> #include <iomanip> #include <fstream> #include <cstring> #include "mp_io.h" #include "utils/iconv_utils.h" namespace mp { using namespace std; using namespace boost::spirit::classic; bool read(const char* filename, mp_world & world, const Options & opts){ mp_world ret; mp_object o, o0; - int l=0; dPoint pt; dLine line; string comm, key, val; rule_t key_ch = anychar_p - eol_p - '='; rule_t ch = anychar_p - eol_p; rule_t comment = ch_p(';') >> (*ch)[assign_a(comm)] >> eol_p; rule_t option = (*key_ch)[assign_a(key)] >> '=' >> (*ch)[assign_a(val)] >> eol_p; rule_t header = *(comment[push_back_a(ret.Comment, comm)] | space_p) >> ("[IMG ID]") >> +eol_p >> *( ( "ID=" >> !uint_p[assign_a(ret.ID)] >> +eol_p) | ( "Name=" >> (*ch)[assign_a(ret.Name)] >> +eol_p) | ( option[erase_a(ret.Opts, key)][insert_at_a(ret.Opts, key, val)] ) ) >> "[END-IMG ID]" >> +eol_p; rule_t pt_r = ch_p('(') >> real_p[assign_a(pt.y)] >> ',' >> real_p[assign_a(pt.x)] >> ch_p(')'); const string sp="POI", sl="POLYLINE", sa="POLYGON"; rule_t object = eps_p[assign_a(o,o0)] >> *(comment[push_back_a(o.Comment, comm)] | space_p) >> ch_p('[') >> ((str_p("POI") | "RGN10" | "RGN20")[assign_a(o.Class, sp)] | (str_p("POLYLINE") | "RGN40")[assign_a(o.Class, sl)] | (str_p("POLYGON") | "RGN80")[assign_a(o.Class, sa)] ) >> ch_p(']') >> +eol_p >> *(( "Type=0x" >> hex_p[assign_a(o.Type)] >> +eol_p) | ( "Label=" >> (*ch)[assign_a(o.Label)] >> +eol_p) | ( "EndLevel=" >> uint_p[assign_a(o.EL)] >> +eol_p) | ( "Endlevel=" >> uint_p[assign_a(o.EL)] >> +eol_p) | ( "Levels=" >> uint_p[assign_a(o.EL)] >> +eol_p) | ((str_p("Data") | "Origin") >> uint_p[assign_a(o.BL)][clear_a(line)] >> "=" >> (+eol_p | (pt_r[push_back_a(line, pt)] >> *(',' >> pt_r[push_back_a(line, pt)]) >> +eol_p) [push_back_a(o,line)] ) ) | ( option[erase_a(ret.Opts, key)][insert_at_a(o.Opts, key, val)] ) ) >> "[END" >> *(ch-ch_p(']')) >> ch_p(']') >> eol_p[push_back_a(ret,o)]; rule_t main_rule = header >> *object >> *space_p >> *(+comment >> *space_p); // комментарии после объектов - теряются! if (!parse_file("mp::read", filename, main_rule)) return false; // converting some fields to UTF8 string codepage="1251"; codepage=ret.Opts.get("CodePage", codepage); // override by file setting codepage=opts.get("mp_in_codepage", codepage); // override by user setting IConv cnv("CP" + codepage); for (mp_world::iterator i = ret.begin(); i != ret.end(); i++){ i->Label = cnv.to_utf8(i->Label); for (Options::iterator o=i->Opts.begin(); o!=i->Opts.end(); o++){ o->second=cnv.to_utf8(o->second); } } ret.Name = cnv.to_utf8(ret.Name); for (Options::iterator o=ret.Opts.begin(); o!=ret.Opts.end(); o++){ o->second=cnv.to_utf8(o->second); } for (vector<string>::iterator c = ret.Comment.begin(); c != ret.Comment.end(); c++){ *c = cnv.to_utf8(*c); } // removing bad objects mp_world::iterator i = ret.begin(); while (i!= ret.end()){ mp_object::iterator l = i->begin(); while (l!= i->end()){ if (l->size()==0){ std::cerr << "MP:read warning: deleting empty object segment\n"; l = i->erase(l); continue; } if ((i->Class!="POI") && (l->size()==1)){ std::cerr << "MP:read warning: deleting line segment with 1 point\n"; l = i->erase(l); continue; } if ((i->Class=="POI") && (l->size()>1)){ std::cerr << "MP:read warning: cropping POI segment with > 1 points\n"; l->resize(1); } l++; } if (i->size()==0){ std::cerr << "MP:read warning: deleting empty object\n"; i = ret.erase(i); } else i++; } // merging world with ret mp::mp_world tmp = world; world=ret; world.insert(world.begin(), tmp.begin(), tmp.end()); return true; } bool write(std::ostream & out, const mp_world & world, const Options & opts){ // converting some fields from UTF8 to default codepage // setting CodePage to default_codepage; string codepage="1251"; codepage=world.Opts.get("CodePage", codepage); // override by file setting codepage=opts.get("mp_out_codepage", codepage); // override by user setting IConv cnv("CP" + codepage); for (vector<string>::const_iterator c = world.Comment.begin(); c!=world.Comment.end(); c++) out << ";" << cnv.from_utf8(*c) << "\n"; //cerr <<"Name" << world.Name << "->" << cnv.from_utf8(world.Name) << "\n"; out << setprecision(6) << fixed << "\r\n[IMG ID]" << "\r\nID=" << world.ID << "\r\nName=" << cnv.from_utf8(world.Name); // we need options to be printed in right order (Levels before Level0...) Options lopts=world.Opts; //copy options const char* names[] = {"ID","Name","Elevation","Preprocess","CodePage", "LblCoding","TreSize","TreMargin","RgnLimit","POIIndex","Levels", "Level0","Level1","Level2","Level3","Level4","Level5","Level6", "Zoom0","Zoom1","Zoom2","Zoom3","Zoom4","Zoom5","Zoom6"}; - for (int i=0; i<sizeof(names)/sizeof(char*); i++){ + for (size_t i=0; i<sizeof(names)/sizeof(char*); i++){ if (lopts.count(names[i])>0){ if (strcmp(names[i],"CodePage")==0) out << "\r\nCodePage=" << codepage; // use our new codepage else out << "\r\n" << names[i] << "=" << cnv.from_utf8(lopts[names[i]]); lopts.erase(names[i]); } } // other options for (Options::const_iterator o=lopts.begin(); o!=lopts.end(); o++){ out << "\r\n" << o->first << "=" << cnv.from_utf8(o->second); } out << "\r\n[END-IMG ID]\r\n"; for (mp_world::const_iterator i=world.begin(); i!=world.end(); i++){ for (vector<string>::const_iterator c = i->Comment.begin(); c!=i->Comment.end(); c++) out << ";" << cnv.from_utf8(*c) << "\n"; out << "\r\n[" << i->Class << "]" << "\r\nType=0x" << setbase(16) << i->Type << setbase(10); if (i->Label != "") out << "\r\nLabel=" << cnv.from_utf8(i->Label); if (i->EL != 0) out << "\r\nEndLevel=" << i->EL; for (Options::const_iterator o=i->Opts.begin(); o!=i->Opts.end(); o++){ out << "\r\n" << o->first << "=" << cnv.from_utf8(o->second); } for (dMultiLine::const_iterator l=i->begin(); l!=i->end(); l++){ out << "\r\nData" << i->BL << "="; - for (int j=0; j<l->size(); j++){ + for (size_t j=0; j<l->size(); j++){ out << ((j!=0)?",":"") << "(" << (*l)[j].y << "," << (*l)[j].x << ")"; } } out << "\r\n[END]\r\n"; } return true; } bool write(const string & file, const mp_world & world, const Options & opts){ ofstream out(file.c_str()); if (!out) { cerr << "Error: can't open mp file \"" << file << "\"\n"; return false; } if (!write(out, world, opts)) { cerr << "Error: can't write to mp file \"" << file << "\"\n"; return false; } return true; } } //namespace diff --git a/core/ocad/ocad_object.cpp b/core/ocad/ocad_object.cpp index 390f611..7335f7a 100644 --- a/core/ocad/ocad_object.cpp +++ b/core/ocad/ocad_object.cpp @@ -1,154 +1,154 @@ #include "ocad_object.h" #include "err/err.h" using namespace std; namespace ocad{ ocad_object::ocad_object(): sym(0), type(3), status(1), viewtype(0), implayer(0), idx_col(-1), ang(0), col(0), width(0), flags(0), extent(0){} // lib2d functions iLine ocad_object::line() const{ iLine ret; for (int i=0; i<coords.size(); i++){ iPoint p(coords[i].getx(),coords[i].gety()); if (!coords[i].is_curve()) ret.push_back(p); } return ret; } void ocad_object::set_coords(const iLine & l){ coords.clear(); coords = vector<ocad_coord>(l.begin(), l.end()); } iRect ocad_object::range() const{ iRect ret; for (int i=0; i<coords.size(); i++){ iPoint p(coords[i].getx(),coords[i].gety()); if (i==0) ret=iRect(p,p); else ret = rect_pump(ret, p); } return rect_pump(ret, (int)extent); } void ocad_object::dump(int verb) const{ if (verb<1) return; cout << "object: " << sym/1000 << "." << sym%1000 << " type: " << (int)type << " col: " << idx_col << " - " << col; if (status!=1) cout << " status: " << (int)status; if (viewtype) cout << " viewtype: " << (int)viewtype; if (implayer) cout << " implayer: " << implayer; if (ang) cout << " ang: " << ang/10.0; if (coords.size()) cout << " points: " << coords.size(); if (text.length()) cout << " text: \"" << text << "\""; cout << "\n"; if (verb<2) return; if (coords.size()){ cout << " coords: "; - for (int i=0; i<coords.size(); i++) coords[i].dump(cout); + for (size_t i=0; i<coords.size(); i++) coords[i].dump(cout); cout << "\n"; } } ocad_coord ocad_object::LLC() const{ if (coords.size() == 0) return ocad_coord(); ocad_coord ret; ret.setx(coords[0].getx()); ret.sety(coords[0].gety()); - for (int i=0; i<coords.size(); i++){ + for (size_t i=0; i<coords.size(); i++){ if (coords[i].getx() < ret.getx()) ret.setx(coords[i].getx()); if (coords[i].gety() < ret.gety()) ret.sety(coords[i].gety()); } ret.setx(ret.getx()-extent); ret.sety(ret.gety()-extent); return ret; } ocad_coord ocad_object::URC() const{ if (coords.size() == 0) return ocad_coord(); ocad_coord ret; ret.setx(coords[0].getx()); ret.sety(coords[0].gety()); - for (int i=0; i<coords.size(); i++){ + for (size_t i=0; i<coords.size(); i++){ if (coords[i].getx() > ret.getx()) ret.setx(coords[i].getx()); if (coords[i].gety() > ret.gety()) ret.sety(coords[i].gety()); } ret.setx(ret.getx()+extent); ret.sety(ret.gety()+extent); return ret; } int ocad_object::txt_blocks(const string & txt) const{ if (txt.length() == 0 ) return 0; return (txt.length()+2)/8+1; } void ocad_object::write_text(const string & txt, FILE *F, int limit) const { - int n=txt_blocks(txt); - if (limit>=0) n=std::min(limit, n); // TODO: this can break unicode letters! + size_t n=txt_blocks(txt); + if (limit>=0) n=std::min((size_t)limit, n); // TODO: this can break unicode letters! if (n){ char *buf = new char [n*8]; memset(buf, 0, n*8); - for (int i=0; i<txt.length(); i++) buf[i] = txt[i]; + for (size_t i=0; i<txt.length(); i++) buf[i] = txt[i]; if (fwrite(buf, 1, n*8, F)!=n*8) throw Err() << "can't write object text"; delete [] buf; } } void ocad_object::write_coords(FILE *F, int limit) const{ - int n = coords.size(); - if (limit>=0) n=std::min(limit, n); + size_t n = coords.size(); + if (limit>=0) n=std::min((size_t)limit, n); if (n){ ocad_coord * buf = new ocad_coord[n]; memset(buf, 0, n*8); - for (int i=0; i<n; i++) buf[i] = coords[i]; + for (size_t i=0; i<n; i++) buf[i] = coords[i]; if (fwrite(buf, sizeof(ocad_coord), n, F)!=n) throw Err() << "can't write object coordinates"; delete [] buf; } } void -ocad_object::read_coords(FILE *F, int n){ +ocad_object::read_coords(FILE *F, size_t n){ if (n){ ocad_coord * buf = new ocad_coord[n]; if (fread(buf, sizeof(ocad_coord), n, F)!=n) throw Err() << "can't read object coordinates"; coords = vector<ocad_coord>(buf, buf+n); delete [] buf; } } void -ocad_object::read_text(FILE *F, int n){ +ocad_object::read_text(FILE *F, size_t n){ if (n){ char *buf = new char [n*8]; if (fread(buf, 1, n*8, F)!=n*8) throw Err() << "can't read object text"; - for (int i=0; i<n*8-1; i++){ + for (size_t i=0; i<n*8-1; i++){ if ((buf[i]==0) && (buf[i+1]==0)) break; // 0x0000-terminated string text.push_back(buf[i]); } delete [] buf; } } } // namespace diff --git a/core/ocad/ocad_object.h b/core/ocad/ocad_object.h index e15ce75..e5c03b6 100644 --- a/core/ocad/ocad_object.h +++ b/core/ocad/ocad_object.h @@ -1,77 +1,77 @@ #ifndef OCAD_OBJECT_H #define OCAD_OBJECT_H #include "ocad_types.h" #include <cstdio> #include <vector> #include <string> #include "2d/point.h" #include "2d/rect.h" #include "2d/line.h" namespace ocad{ // common structure for OCAD object struct ocad_object{ ocad_long sym; ocad_byte type; ocad_byte status; ocad_byte viewtype; ocad_small idx_col; ocad_small implayer; ocad_small ang; ocad_small col; ocad_small width; ocad_small flags; ocad_small extent; // TODO - not here? std::vector<ocad_coord> coords; std::string text; /// Empty constructor. ocad_object(); /// Convert to iLine. /// TODO -- correct holes processing! iLine line() const; /// Set points. /// For creating objects use ocad_file::add_object()! void set_coords(const iLine & l); /// Get range (with extent added). iRect range() const; /// dump all information. void dump(int verb) const; // Functions for internal use: /// Lower-left corner (with extent added). ocad_coord LLC() const; /// Upper-right corner (with extent added). ocad_coord URC() const; /// Get number of 8-byte blocks needed for 0x0000-terminates string txt. int txt_blocks(const std::string & txt) const; /// Write text. void write_text(const std::string & txt, FILE *F, int limit=-1) const; /// Write coordinates. void write_coords(FILE *F, int limit=-1) const; /// Read coordinates. - void read_coords(FILE *F, int n); + void read_coords(FILE *F, size_t n); /// Read text. - void read_text(FILE *F, int n); + void read_text(FILE *F, size_t n); }; } // namespace #endif diff --git a/core/ocad/ocad_symbol9.cpp b/core/ocad/ocad_symbol9.cpp index f500cce..8e5270f 100644 --- a/core/ocad/ocad_symbol9.cpp +++ b/core/ocad/ocad_symbol9.cpp @@ -1,109 +1,109 @@ #include <cassert> #include <iostream> #include "ocad_symbol9.h" #include "err/err.h" using namespace std; namespace ocad{ // Someting wrong with this structure in documentation // (the tail is shifted by 1byte). struct _ocad9_base_symb{ ocad_long size; // size of the symbol in bytes (depends on the type and the number of subsymbols) // Coordinates following the symbol are included. ocad_long sym; // symbol number (101000 for 101.0, 101005 for 101.5, 101123 for 101.123) ocad_byte type; // object type // 1: point, 2: line, 3: area, 4: text // 6: line text, 7: rectangle ocad_byte flags; // 1: rotatable symbol (not oriented to north) // 4: belongs to favorites ocad_bool selected;// symbol is selected in the symbol box ocad_byte status; // status of the symbol: 0: Normal, 1: Protected, 2: Hidden ocad_byte tool; // Preferred drawing tool // 0: off // 1: Curve mode // 2: Ellipse mode // 3: Circle mode // 4: Rectangular mode // 5: Straight line mode // 6: Freehand mode ocad_byte csmode; // Course setting mode: // 0: Not used for course setting // 1: course symbol // 2: control description symbol ocad_byte sctype; // Course setting object type // 0: Start symbol (Point symbol) // 1: Control symbol (Point symbol) // 2: Finish symbol (Point symbol) // 3: Marked route (Line symbol) // 4: Control description symbol (Point symbol) // 5: Course Titel (Text symbol) // 6: Start Number (Text symbol) // 7: Variant (Text symbol) // 8: Text block (Text symbol) // ocad_byte csflags; // Course setting control description flags // a combination of the flags // 32: available in column C // 16: available in column D // 8: available in column E // 4: available in column F // 2: available in column G // 1: available in column H ocad_long extent; // Extent how much the rendered symbols can reach outside the // coordinates of an object with this symbol. For a point // object it tells how far away from the coordinates of the // object anything of the point symbol can appear. ocad_long pos; // used internally ocad_small group; // Group ID in the symbol tree. Lower and higher 8 bit are // used for 2 different symbol trees. ocad_small ncolors; // Number of colors of the symbol max. 14 ///??? // -1: the number of colors is > 14 ocad_small colors[14]; // number of colors of the symbol char desc[32]; // description of the symbol (c-string?!) ocad_byte icon[484]; // 256 color palette (icon 22x22 pixels) _ocad9_base_symb(){ assert(sizeof(*this) ==572); memset(this, 0, sizeof(*this)); } } __attribute__((packed)); ocad9_symbol::ocad9_symbol(){} ocad9_symbol::ocad9_symbol(const ocad_symbol & o):ocad_symbol(o){} void ocad9_symbol::read(FILE * F, ocad9_symbol::index idx, int v){ int pos = ftell(F); _ocad9_base_symb s; if (fread(&s, 1, sizeof(s), F)!=sizeof(s)) throw Err() << "can't read object"; - int size = s.size; + size_t size = s.size; sym = s.sym; type = s.type; extent = s.extent; desc = iconv_win.to_utf8(str_pas2str(s.desc, 32)); blob_version = v; if (fseek(F, pos, SEEK_SET)!=0) throw Err() << "can't seek file to read symbol blob"; char *buf = new char [size]; if (fread(buf, 1, size, F)!=size) throw Err() << "can't read symbol blob"; blob = string(buf, buf+size); delete [] buf; } ocad9_symbol::index ocad9_symbol::write(FILE * F, int v) const{ if (blob_version > 8){ if (fwrite(blob.data(), 1, blob.size(), F)!=blob.size()) throw Err() << "can't write symbol blob"; } else { cerr << "warning: skipping symbol with incompatible version\n"; } return ocad9_symbol::index(); } } // namespace diff --git a/core/ocad/ocad_types.cpp b/core/ocad/ocad_types.cpp index f154dc1..4ad503b 100644 --- a/core/ocad/ocad_types.cpp +++ b/core/ocad/ocad_types.cpp @@ -1,114 +1,114 @@ #include <iostream> #include <iomanip> #include <string> #include <cassert> #include "ocad_types.h" #include "utils/iconv_utils.h" using namespace std; namespace ocad{ void str_pas2c(char * str, int maxlen){ int l = str[0]; if (l>=maxlen){ cerr << "warning: not a pascal-string?\n"; l=maxlen-1; } for (int i=0; i<l; i++) str[i]=str[i+1]; str[l]='\0'; } string str_pas2str(const char * str, int maxlen){ int l = str[0]+1; if (l>maxlen){ cerr << "warning: not a pascal-string? " << "(first byte: " << (int)str[0] << ")\n"; l=maxlen; } if (l<1){ cerr << "warning: not a pascal-string? " << "(first byte: " << (int)str[0] << ")\n"; l=1; } return string(str+1, str+l); } void str_str2pas(char * pas, const string & str, size_t maxlen){ if (str.size() > maxlen-1) cerr << "warning: cropping string."; int size = std::min(str.size(), maxlen-1); pas[0] = size; for (int i=0; i<size; i++) pas[i+1]=str[i]; } const IConv iconv_uni("UTF-16"); const IConv iconv_win("CP1251"); ocad_coord::ocad_coord(){ assert ( sizeof(*this) == 8); memset(this, 0, sizeof(*this)); } ocad_coord::ocad_coord(const iPoint & p){ x = p.x << 8; y = p.y << 8; } int ocad_coord::getx() const{ return x>>8; } int ocad_coord::gety() const{ return y>>8; } int ocad_coord::getf() const{ - return (x & 0xFF) << 8 + (y & 0xFF); + return ((x & 0xFF) << 8) + (y & 0xFF); } void ocad_coord::setx(int v){ - x = (x & 0xFF) + v << 8; + x = (x & 0xFF) + (v << 8); } void ocad_coord::sety(int v){ - y = (y & 0xFF) + v << 8; + y = (y & 0xFF) + (v << 8); } bool ocad_coord::is_curve_f() const { return x & 1; } bool ocad_coord::is_curve_s() const { return x & 2; } bool ocad_coord::is_curve() const { return x & 3; } void ocad_coord::dump(ostream & s) const{ s << " " << getx() << "," << gety(); if (getf()) s << "(" << setbase(16) << getf() << setbase(10) << ")"; } void check_v(int * v){ if ((*v<6)||(*v>9)){ cerr << "unsupported version: " << *v << ", set to 9\n"; *v=9; } } } // namespace diff --git a/core/srtm/srtm3.cpp b/core/srtm/srtm3.cpp index 5ad7f5a..d9d83b2 100644 --- a/core/srtm/srtm3.cpp +++ b/core/srtm/srtm3.cpp @@ -1,568 +1,566 @@ #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <queue> #include <cstdio> #include <2d/point_int.h> #include <2d/line_utils.h> #include "srtm3.h" #include <zlib.h> using namespace std; SRTM3::SRTM3(const string & _srtm_dir, const unsigned cache_size): srtm_dir(_srtm_dir), srtm_cache(cache_size) { set_dir(srtm_dir); } void SRTM3::set_dir(const string & str){ srtm_dir = str; if (srtm_dir == "") srtm_dir = string(getenv("HOME")? getenv("HOME"):"") + "/.srtm_data"; ifstream ws(srtm_dir + "/srtm_width.txt"); if (!ws) srtm_width = 1201; else ws >> srtm_width; if (srtm_width<1) srtm_width = 1201; size0 = 6380e3 * M_PI/srtm_width/180; area0 = pow(6380e3 * M_PI/srtm_width/180, 2); Glib::Mutex::Lock lock(mutex); srtm_cache.clear(); } const string & SRTM3::get_dir(void) const{ return srtm_dir; } const unsigned SRTM3::get_width(void) const{ return srtm_width; } // find tile number and coordinate on the tile void get_crd(int x, int w, int &k, int &c){ if (x>=0) k=x/(w-1); else k=(x+1)/(w-1)-1; c = x - k*(w-1); } short SRTM3::geth(const iPoint & p, const bool interp){ // find tile number and coordinate on the tile iPoint key, crd; get_crd(p.x, srtm_width, key.x, crd.x); get_crd(p.y, srtm_width, key.y, crd.y); crd.y = srtm_width-crd.y-1; int h; { Glib::Mutex::Lock lock(mutex); if ((!srtm_cache.contains(key)) && (!load(key))) return srtm_nofile; if (srtm_cache.get(key).empty()) return srtm_nofile; h = srtm_cache.get(key).safe_get(crd); } if (interp){ if (h>srtm_min_interp) return h - srtm_zer_interp; if (h!=srtm_undef) return h; // найдем всю дырку и заинтерполируем ее! set<iPoint> pset = plane(p); set<iPoint> bord = border(pset); set<iPoint>::iterator pi, bi; for (pi = pset.begin(); pi != pset.end(); pi++){ double Srh = 0; double Sr = 0; for (bi = bord.begin(); bi != bord.end(); bi++){ int bh = geth(*bi); if (bh>srtm_min){ double k = cos(double(pi->y)/srtm_width/180.0*M_PI); double r = 1.0/(pow(k*(bi->x - pi->x),2) + pow(double(bi->y - pi->y),2)); Sr += r; Srh+= bh * r; } } seth(*pi, (short)Srh/Sr+srtm_zer_interp); } return geth(p,true); } else { if (h>srtm_min_interp) return srtm_undef; else return h; } return h; } double SRTM3::slope(const iPoint &p, const bool interp){ short h = geth(p, interp); short h1 = geth(p.x-1, p.y, interp); short h2 = geth(p.x+1, p.y, interp); if (h1 < srtm_min && h > srtm_min && h2 > srtm_min) h1 = 2*h - h2; if (h2 < srtm_min && h > srtm_min && h1 > srtm_min) h1 = 2*h - h2; short h3 = geth(p.x, p.y-1, interp); short h4 = geth(p.x, p.y+1, interp); if (h3 < srtm_min && h > srtm_min && h4 > srtm_min) h3 = 2*h - h4; if (h4 < srtm_min && h > srtm_min && h3 > srtm_min) h4 = 2*h - h3; if (h1 > srtm_min && h2 > srtm_min && h3 > srtm_min && h4 > srtm_min){ const double kx = cos(M_PI*p.y/180/srtm_width); const double U = hypot((h2-h1)/kx, h4-h3)/size0/2.0; return atan(U)*180.0/M_PI; } return 0; } short SRTM3::geth(const int x, const int y, const bool interp){ return geth(iPoint(x,y), interp); } double SRTM3::slope(const int x, const int y, const bool interp){ return slope(iPoint(x,y), interp); } short SRTM3::seth(const iPoint & p, const short h){ // find tile number and coordinate on the tile iPoint key, crd; get_crd(p.x, srtm_width, key.x, crd.x); get_crd(p.y, srtm_width, key.y, crd.y); crd.y = srtm_width-crd.y-1; { Glib::Mutex::Lock lock(mutex); if ((!srtm_cache.contains(key)) && (!load(key))) return srtm_nofile; if (srtm_cache.get(key).empty()) return srtm_nofile; srtm_cache.get(key).safe_set(crd, h); } return h; } short SRTM3::geth4(const dPoint & p, const bool interp){ double x = p.x*(srtm_width-1); double y = p.y*(srtm_width-1); int x1 = floor(x), x2 = x1+1; int y1 = floor(y), y2 = y1+1; short h1=geth(x1,y1,interp); short h2=geth(x1,y2,interp); if ((h1<srtm_min)||(h2<srtm_min)) return srtm_undef; short h12 = (int)( h1+ (h2-h1)*(y-y1) ); short h3=geth(x2,y1,interp); short h4=geth(x2,y2,interp); if ((h3<srtm_min)||(h4<srtm_min)) return srtm_undef; short h34 = (int)( h3 + (h4-h3)*(y-y1) ); return (short)( h12 + (h34-h12)*(x-x1) ); } double SRTM3::slope4(const dPoint & p, const bool interp){ double x = p.x*(srtm_width-1); double y = p.y*(srtm_width-1); int x1 = floor(x), x2 = x1+1; int y1 = floor(y), y2 = y1+1; double h1=slope(x1,y1, interp); double h2=slope(x1,y2, interp); double h3=slope(x2,y1, interp); double h4=slope(x2,y2, interp); double h12 = h1+ (h2-h1)*(y-y1); double h34 = h3 + (h4-h3)*(y-y1); return h12 + (h34-h12)*(x-x1); } short SRTM3::geth16(const dPoint & p, const bool interp){ double x = p.x*(srtm_width-1); double y = p.y*(srtm_width-1); int x0 = floor(x); int y0 = floor(y); double hx[4], hy[4]; for (int i=0; i<4; i++){ for (int j=0; j<4; j++) hx[j]=geth(x0+j-1, y0+i-1, interp); int_holes(hx); hy[i]= cubic_interp(hx, x-x0); } int_holes(hy); return cubic_interp(hy, y-y0); } // найти множество соседних точек одной высоты (не более max точек) set<iPoint> -SRTM3::plane(const iPoint& p, int max){ +SRTM3::plane(const iPoint& p, size_t max){ set<iPoint> ret; queue<iPoint> q; short h = geth(p); q.push(p); ret.insert(p); while (!q.empty()){ iPoint p1 = q.front(); q.pop(); for (int i=0; i<8; i++){ iPoint p2 = adjacent(p1, i); if ((geth(p2) == h)&&(ret.insert(p2).second)) q.push(p2); } if ((max!=0)&&(ret.size()>max)) break; } return ret; } void SRTM3::move_to_extr(iPoint & p0, bool down, int maxst){ iPoint p1 = p0; int i=0; do { - short h = geth(p0, true); for (int i=0; i<8; i++){ iPoint p=adjacent(p0,i); if ((down && (geth(p,true) < geth(p1,true))) || (!down && (geth(p,true) > geth(p1,true)))) p1=p; } if (p1==p0) break; p0=p1; i++; } while (maxst<0 || i<maxst); } void SRTM3::move_to_min(iPoint & p0, int maxst){ move_to_extr(p0, true, maxst); } void SRTM3::move_to_max(iPoint & p0, int maxst){ move_to_extr(p0, false, maxst); } double SRTM3::area(const iPoint &p) const{ return area0 * cos((double)p.y *M_PI/180.0/srtm_width); } /**********************************************************/ sImage read_zfile(const string & file, const size_t srtm_width){ gzFile F = gzopen(file.c_str(), "rb"); if (!F) return sImage(0,0); sImage im(srtm_width,srtm_width); int length = srtm_width*srtm_width*sizeof(short); if (length != gzread(F, im.data, length)){ cerr << "bad file: " << file << '\n'; return sImage(0,0); } for (int i=0; i<length/2; i++){ // swap bytes int tmp=(unsigned short)im.data[i]; im.data[i] = (tmp >> 8) + (tmp << 8); } gzclose(F); return im; } sImage read_file(const string & file, const size_t srtm_width){ FILE *F = fopen(file.c_str(), "rb"); if (!F) return sImage(0,0); sImage im(srtm_width,srtm_width); - int length = srtm_width*srtm_width*sizeof(short); + size_t length = srtm_width*srtm_width*sizeof(short); if (length != fread(im.data, 1, length, F)){ cerr << "bad file: " << file << '\n'; return sImage(0,0); } - for (int i=0; i<length/2; i++){ // swap bytes + for (size_t i=0; i<length/2; i++){ // swap bytes int tmp=(unsigned short)im.data[i]; im.data[i] = (tmp >> 8) + (tmp << 8); } fclose(F); return im; } bool SRTM3::load(const iPoint & key){ if ((key.x < -max_lon) || (key.x >= max_lon) || (key.y < -max_lat) || (key.y >= max_lat)) return false; char NS='N'; char EW='E'; if (key.y<0) {NS='S';} if (key.x<0) {EW='W';} ostringstream file; file << NS << setfill('0') << setw(2) << abs(key.y) << EW << setw(3) << abs(key.x) << ".hgt"; // try f2.gz, f2, f1.gz, f1 sImage im; im = read_zfile(srtm_dir + "/" + file.str() + ".gz", srtm_width); if (!im.empty()) goto read_ok; im = read_file(srtm_dir + "/" + file.str(), srtm_width); if (!im.empty()) goto read_ok; cerr << "can't find file " << file.str() << '\n'; read_ok: srtm_cache.add(key, im); return !im.empty(); } // see http://www.paulinternet.nl/?page=bicubic short SRTM3::cubic_interp(const double h[4], const double x) const{ return h[1] + 0.5 * x*(h[2] - h[0] + x*(2.0*h[0] - 5.0*h[1] + 4.0*h[2] - h[3] + x*(3.0*(h[1] - h[2]) + h[3] - h[0]))); } void SRTM3::int_holes(double h[4]) const{ // interpolate 1-point or 2-points holes // maybe this can be written smarter... if ((h[0]>srtm_min) && (h[1]>srtm_min) && (h[2]>srtm_min) && (h[3]>srtm_min)) return; for (int cnt=0; cnt<2; cnt++){ if ((h[0]<=srtm_min) && (h[1]>srtm_min) && (h[2]>srtm_min)) h[0]=2*h[1]-h[2]; else if ((h[1]<=srtm_min) && (h[0]>srtm_min) && (h[2]>srtm_min)) h[1]=(h[0]+h[2])/2; else if ((h[1]<=srtm_min) && (h[2]>srtm_min) && (h[3]>srtm_min)) h[1]=2*h[2]-h[3]; else if ((h[2]<=srtm_min) && (h[1]>srtm_min) && (h[3]>srtm_min)) h[2]=(h[1]+h[3])/2; else if ((h[2]<=srtm_min) && (h[0]>srtm_min) && (h[1]>srtm_min)) h[2]=2*h[1]-h[0]; else if ((h[3]<=srtm_min) && (h[1]>srtm_min) && (h[2]>srtm_min)) h[3]=2*h[2]-h[1]; else break; } if ((h[1]<=srtm_min) && (h[2]<=srtm_min) && (h[0]>srtm_min) && (h[3]>srtm_min)){ h[1]=(2*h[0] + h[3])/3; h[2]=(h[0] + 2*h[3])/3; } } /**********************************************************/ //координаты угла единичного квадрата по его номеру iPoint crn (int k){ k%=4; return iPoint(k/2, (k%3>0)?1:0); } //направление следующей за углом стороны (единичный вектор) iPoint dir (int k){ return crn(k+1)-crn(k); } map<short, dMultiLine> SRTM3::find_contours(const dRect & range, int step){ int lon1 = int(floor((srtm_width-1)*range.TLC().x)); int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); int lat1 = int(floor((srtm_width-1)*range.TLC().y)); int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); map<short, dMultiLine> ret; int count = 0; for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2; lon++){ iPoint p(lon,lat); // пересечения четырех сторон клетки с горизонталями: // при подсчетах мы опустим все данные на полметра, // чтоб не разбирать кучу случаев с попаданием горизонталей в узлы сетки multimap<short, double> pts; for (int k=0; k<4; k++){ iPoint p1 = p+crn(k); iPoint p2 = p+crn(k+1); short h1 = geth(p1); short h2 = geth(p2); if ((h1<srtm_min) || (h2<srtm_min)) continue; int min = (h1<h2)? h1:h2; int max = (h1<h2)? h2:h1; min = int( floor(double(min)/step)) * step; max = int( ceil(double(max)/step)) * step; if (h2==h1) continue; for (int hh = min; hh<=max; hh+=step){ double x = double(hh-h1+0.1)/double(h2-h1); if ((x<0)||(x>1)) continue; pts.insert(pair<short, double>(hh,x+k)); } } // найдем, какие горизонтали пересекают квадрат дважды, // поместим их в список горизонталей ret short h=srtm_undef; - double x1,x2; + double x1=0,x2=0; for (multimap<short,double>::const_iterator i=pts.begin(); i!=pts.end(); i++){ if (h!=i->first){ h = i->first; x1 = i->second; } else{ x2 = i->second; dPoint p1=(dPoint(p + crn(int(x1))) + dPoint(dir(int(x1)))*double(x1-int(x1)))/(double)(srtm_width-1); dPoint p2=(dPoint(p + crn(int(x2))) + dPoint(dir(int(x2)))*double(x2-int(x2)))/(double)(srtm_width-1); // we found segment p1-p2 with height h // first try to append it to existing line in ret[h] bool done=false; for (dMultiLine::iterator l=ret[h].begin(); l!=ret[h].end(); l++){ int e=l->size()-1; if (e<=0) continue; // we have no 1pt lines! if (pdist((*l)[0], p1) < 1e-4){ l->insert(l->begin(), p2); done=true; break;} if (pdist((*l)[0], p2) < 1e-4){ l->insert(l->begin(), p1); done=true; break;} if (pdist((*l)[e], p1) < 1e-4){ l->push_back(p2); done=true; break;} if (pdist((*l)[e], p2) < 1e-4){ l->push_back(p1); done=true; break;} } if (!done){ // insert new line into ret[h] dLine hor; hor.push_back(p1); hor.push_back(p2); ret[h].push_back(hor); } h=srtm_undef; count++; } } } } // merge contours for(map<short, dMultiLine>::iterator im = ret.begin(); im!=ret.end(); im++) merge(im->second, 1e-4); return ret; } map<dPoint, short> -SRTM3::find_peaks(const dRect & range, int DH, int PS){ +SRTM3::find_peaks(const dRect & range, int DH, size_t PS){ int lon1 = int(floor((srtm_width-1)*range.TLC().x)); int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); int lat1 = int(floor((srtm_width-1)*range.TLC().y)); int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); // поиск вершин: // 1. найдем все локальные максимумы (не забудем про максимумы из многих точек!) // 2. от каждого будем строить множество точек, добавляя наивысшую точку границы // 3. если высота последней добаленной точки ниже исходной более чем на DH м, // или если размер множества больше PS точек - процедуру прекращаем, // объявляем исходную точку вершиной. // 4. Если высота последней добавленной точки больше исходной - процедуру // прекращаем set<iPoint> done; map<dPoint, short> ret; for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2-1; lon++){ iPoint p(lon,lat); if (done.find(p)!=done.end()) continue; short h = geth(p); if (h<srtm_min) continue; set<iPoint> pts; pts.insert(p); set<iPoint> brd = border(pts); // ищем максимум границы do{ short max = srtm_undef; iPoint maxpt; for (set<iPoint>::const_iterator i = brd.begin(); i!=brd.end(); i++){ short h1 = geth(*i); // исходная точка слишком близка к краю данных if ((h1<srtm_min) && (pdist(*i,p)<1.5)) {max = h1; break;} if (h1>max) {max = h1; maxpt=*i;} } if (max < srtm_min) break; // если максимум выше исходной точки - выходим. if (max > h) { break; } // если мы спустились от исходной точки более чем на DH или размер области более PS if ((h - max > DH ) || (pts.size() > PS)) { ret[dPoint(p)/(double)(srtm_width-1)] = h; break; } add_pb(maxpt, pts, brd); done.insert(maxpt); } while (true); } } return ret; } dMultiLine SRTM3::find_holes(const dRect & range){ int lon1 = int(floor((srtm_width-1)*range.TLC().x)); int lon2 = int( ceil((srtm_width-1)*range.BRC().x)); int lat1 = int(floor((srtm_width-1)*range.TLC().y)); int lat2 = int( ceil((srtm_width-1)*range.BRC().y)); set<iPoint> aset; for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2-1; lon++){ iPoint p(lon,lat); short h = geth(p); - dPoint p1 = dPoint(p)/(double)(srtm_width-1); if (h!=srtm_undef) continue; aset.insert(p); } } // converting points to polygons return pset2line(aset)/(double)(srtm_width-1); } /* // поиск крутых склонов cerr << "ищем крутые склоны: "; double latdeg = 6380000/(double)(srtm_width-1)/180.0*M_PI; double londeg = latdeg * cos(double(lat2+lat1)/2400.0/180.0*M_PI); for (int lat=lat2; lat>lat1; lat--){ for (int lon=lon1; lon<lon2-1; lon++){ iPoint p(lon,lat); short h = geth(p); short hx = geth(p+iPoint(1,0)); short hy = geth(p+iPoint(0,1)); if ((h<srtm_min) || (hx<srtm_min) || (hy<srtm_min)) continue; dPoint gr(double(hx-h)/londeg, double(hy-h)/latdeg); double a = atan(pdist(gr))*180/M_PI; if (a > 45) aset.insert(p); } } cerr << aset.size() << " точек\n"; cerr << " преобразуем множество точек в многоугольники: "; aline = pset2line(aset); for(dMultiLine::iterator iv = aline.begin(); iv!=aline.end(); iv++){ if (iv->size()<3) continue; dLine l = (*iv)/(double)(srtm_width-1); mp::mp_object mpo; mpo.Class = "POLYGON"; mpo.Label = "high slope"; mpo.Type = 0x19; mpo.insert(mpo.end(), l.begin(), l.end()); MP.push_back(mpo); } cerr << aline.size() << " шт\n"; */ diff --git a/core/srtm/srtm3.h b/core/srtm/srtm3.h index 9c7fce2..cc59ecb 100644 --- a/core/srtm/srtm3.h +++ b/core/srtm/srtm3.h @@ -1,105 +1,105 @@ #ifndef SRTM3_H #define SRTM3_H #include <string> #include <glibmm.h> #include <2d/image.h> #include <cache/cache.h> /* SRTM3 data Original data can be downloaded from ftp://e0mss21u.ecs.nasa.gov/srtm/ Fixed data can be downloaded from http://www.viewfinderpanoramas.org/dem3.html Default data directory is DIR=$HOME/.srtm_data Files are searched in $DIR/fixed/$file.gz, $DIR/fixed/$file, $DIR/$file.gz, $DIR/$file, so you can keep original data in $HOME/.srtm_data and fixed data in $HOME/.srtm_data/fixed */ const short srtm_min = -32000; // value for testing const short srtm_nofile = -32767; // file not found const short srtm_undef = -32768; // hole in srtm data const short srtm_zer_interp = 15000; // добавлено к интерполированным значениям const short srtm_min_interp = 10000; // для проверки const int max_lat = 90; const int max_lon = 180; class SRTM3 { public: SRTM3( const std::string & _srtm_dir=std::string(), // data directory ($HOME/.srtm_data) const unsigned cache_size=4 ); void set_dir(const std::string & str); const std::string & get_dir(void) const; const unsigned get_width(void) const; // вернуть высоту точки short geth(const iPoint & p, const bool interp=false); short geth(const int x, const int y, const bool interp=false); // Slope (degrees) at a given point // Slope is calculated for p+(1/2,1/2) double slope(const iPoint &p, const bool interp=true); double slope(const int x, const int y, const bool interp=true); // change data (in cache only!) short seth(const iPoint & p, const short h); // вернуть высоту точки (вещественные координаты, // простая интерполяция по четырем соседним точкам) short geth4(const dPoint & p, const bool interp=false); // Slope (degrees) at a given point double slope4(const dPoint &p, const bool interp=true); // вернуть высоту точки (вещественные координаты, // интерполяция по 16 соседним точкам) short geth16(const dPoint & p, const bool interp=false); // найти множество соседних точек одной высоты (не более max точек) - std::set<iPoint> plane(const iPoint& p, int max=1000); + std::set<iPoint> plane(const iPoint& p, size_t max=1000); // move p0 to the local extremum (interpolation is always on) void move_to_extr(iPoint & p0, bool down, int maxst=-1); void move_to_min(iPoint & p0, int maxst=-1); void move_to_max(iPoint & p0, int maxst=-1); double size0; // size (m) of 1 srtm point lat bow double area0; // area (m^2) of 1x1 srtm point on equator size_t srtm_width; // файлы 1201х1201 // area (km2) of 1x1 srtm point at the given place double area(const iPoint &p) const; // making some vector data: contours, peaks, srtm holes std::map<short, dMultiLine> find_contours(const dRect & range, int step); - std::map<dPoint, short> find_peaks(const dRect & range, int DH, int PS); + std::map<dPoint, short> find_peaks(const dRect & range, int DH, size_t PS); dMultiLine find_holes(const dRect & range); private: // data directories std::string srtm_dir; // data cache. key is lon,lat in degrees Cache<iPoint, sImage > srtm_cache; // load data into cache bool load(const iPoint & key); short cubic_interp(const double h[4], const double x) const; void int_holes(double h[4]) const; Glib::Mutex mutex; }; #endif diff --git a/core/utils/cairo_wrapper.cpp b/core/utils/cairo_wrapper.cpp index 1fff321..fb21c72 100644 --- a/core/utils/cairo_wrapper.cpp +++ b/core/utils/cairo_wrapper.cpp @@ -1,205 +1,205 @@ #include <cassert> #include "cairo_wrapper.h" #include "2d/line_utils.h" #include "err/err.h" void CairoExtra::mkpath_smline(const dMultiLine & o, bool close, double curve_l){ for (dMultiLine::const_iterator l=o.begin(); l!=o.end(); l++) mkpath_smline(*l, close, curve_l); } void CairoExtra::mkpath_smline(const dLine & o, bool close, double curve_l){ if (o.size()<1) return; dPoint old; bool first = true; for (dLine::const_iterator p=o.begin(); p!=o.end(); p++){ if (p==o.begin()){ move_to(*p); old=*p; continue; } if (curve_l==0){ line_to(*p); } else { dPoint p1,p2; if (pdist(*p - old) > 2*curve_l){ p1 = old + pnorm(*p - old)*curve_l; p2 = *p - pnorm(*p - old)*curve_l; } else { p1=p2=(*p+old)/2.0; } if (!first){ curve_to(old, old, p1); } else { first=false; } line_to(p2); } old=*p; } if (curve_l!=0) line_to(old); if (close) close_path(); } void CairoExtra::set_fig_font(int font, double fs, double dpi){ std::string face; Cairo::FontSlant slant; Cairo::FontWeight weight; switch(font){ case 0: face="times"; slant=Cairo::FONT_SLANT_NORMAL; weight=Cairo::FONT_WEIGHT_NORMAL; break; case 1: face="times"; slant=Cairo::FONT_SLANT_ITALIC; weight=Cairo::FONT_WEIGHT_NORMAL; break; case 2: face="times"; slant=Cairo::FONT_SLANT_NORMAL; weight=Cairo::FONT_WEIGHT_BOLD; break; case 3: face="times"; slant=Cairo::FONT_SLANT_ITALIC; weight=Cairo::FONT_WEIGHT_BOLD; break; case 16: face="sans"; slant=Cairo::FONT_SLANT_NORMAL; weight=Cairo::FONT_WEIGHT_NORMAL; break; case 17: face="sans"; slant=Cairo::FONT_SLANT_OBLIQUE; weight=Cairo::FONT_WEIGHT_NORMAL; break; case 18: face="sans"; slant=Cairo::FONT_SLANT_NORMAL; weight=Cairo::FONT_WEIGHT_BOLD; break; case 19: face="sans"; slant=Cairo::FONT_SLANT_OBLIQUE; weight=Cairo::FONT_WEIGHT_BOLD; break; default: std::cerr << "warning: unsupported fig font: " << font << "\n"; face="sans"; slant=Cairo::FONT_SLANT_NORMAL; weight=Cairo::FONT_WEIGHT_NORMAL; } if (face=="times") fs/=0.85; Cairo::Context::set_font_size(fs*dpi/89.0); Cairo::Context::set_font_face( Cairo::ToyFontFace::create(face, slant, weight)); } void CairoExtra::render_text(const char *text, dPoint pos, double ang, int color, int fig_font, double font_size, double dpi, int hdir, int vdir){ Cairo::Context::save(); set_color(color); set_fig_font(fig_font, font_size, dpi); dRect ext = get_text_extents(text); move_to(pos); Cairo::Context::rotate(ang); if (hdir == 1) Cairo::Context::rel_move_to(-ext.w/2, 0.0); if (hdir == 2) Cairo::Context::rel_move_to(-ext.w, 0.0); if (vdir == 1) Cairo::Context::rel_move_to(0.0, ext.h/2); if (vdir == 2) Cairo::Context::rel_move_to(0.0, ext.h); Cairo::Context::reset_clip(); Cairo::Context::show_text(text); Cairo::Context::restore(); } void CairoExtra::render_border(const iRect & range, const dLine & brd, const int bgcolor){ // make border path mkpath(brd); if (bgcolor!=0){ // draw border set_source_rgb(0,0,0); set_line_width(2); stroke_preserve(); } // erase everything outside border mkpath(rect2line(rect_pump(range,1))); set_fill_rule(Cairo::FILL_RULE_EVEN_ODD); if (bgcolor==0) set_operator(Cairo::OPERATOR_CLEAR); else set_color(bgcolor); fill(); } Cairo::RefPtr<Cairo::SurfacePattern> CairoExtra::img2patt(const iImage & I, double sc){ try{ const Cairo::Format format = Cairo::FORMAT_ARGB32; assert(Cairo::ImageSurface::format_stride_for_width(format, I.w) == I.w*4); Cairo::RefPtr<Cairo::ImageSurface> patt_surf = Cairo::ImageSurface::create((unsigned char*)I.data, format, I.w, I.h, I.w*4); Cairo::RefPtr<Cairo::SurfacePattern> patt = Cairo::SurfacePattern::create(patt_surf); Cairo::Matrix M=Cairo::identity_matrix(); M.translate(patt_surf->get_width()/2.0, patt_surf->get_height()/2.0); M.scale(sc,sc); patt->set_matrix(M); return patt; } - catch (Cairo::logic_error err){ + catch (Cairo::logic_error & err){ throw Err() << err.what(); } } /* Cairo Wrapper functions */ void CairoWrapper::reset_surface(){ image=iImage(); surface=Cairo::RefPtr<Cairo::ImageSurface>(); Cairo::RefPtr<CairoExtra>::operator=(Cairo::RefPtr<CairoExtra>()); } void CairoWrapper::reset_surface(int w, int h){ image=iImage(); // check if surface raw data compatable with iImage assert(Cairo::ImageSurface::format_stride_for_width(format, w) == w*4); // create surface surface = Cairo::ImageSurface::create(format, w, h); Cairo::RefPtr<CairoExtra>::operator= (cast_static(Cairo::Context::create(surface))); } void CairoWrapper::reset_surface(const iImage & img){ image=img; // increase refcount of image // check if surface raw data compatable with iImage assert(Cairo::ImageSurface::format_stride_for_width(format, img.w) == img.w*4); // create surface surface = Cairo::ImageSurface::create((unsigned char*)img.data, format, img.w, img.h, img.w*4); Cairo::RefPtr<CairoExtra>::operator= (cast_static(Cairo::Context::create(surface))); } const Cairo::Format CairoWrapper::format = Cairo::FORMAT_ARGB32; diff --git a/core/utils/iconv_utils.cpp b/core/utils/iconv_utils.cpp index 9bf03f0..24b6114 100644 --- a/core/utils/iconv_utils.cpp +++ b/core/utils/iconv_utils.cpp @@ -1,88 +1,88 @@ #include "iconv_utils.h" #include <errno.h> #include <iostream> #include <cstring> const std::string IConv_UTF8("UTF-8"); void IConv::print_cnv_err(const std::string & e1, const std::string & e2){ std::cerr << "IConv: Bad conversion from charset \"" << e1 << "\"" << " to \"" << e2 << "\"\n"; } IConv::IConv(const std::string & enc, const std::string & def_enc){ std::string def = def_enc; if (def.size() == 0) def = enc; cd_to_utf8 = iconv_open("UTF-8", enc.c_str()); if (cd_to_utf8 == (iconv_t)-1){ print_cnv_err(enc, "UTF-8"); std::cerr << "Trying default charset \"" << def << "\"\n"; cd_to_utf8 = iconv_open("UTF-8", def.c_str()); if (cd_to_utf8 == (iconv_t)-1){ print_cnv_err(def, "UTF-8"); std::cerr << "Skipping conversion\n"; } } cd_from_utf8 = iconv_open(enc.c_str(), "UTF-8"); if (cd_from_utf8 == (iconv_t)-1){ print_cnv_err("UTF-8", enc); std::cerr << "Trying default charset \"" << def << "\"\n"; cd_from_utf8 = iconv_open(def.c_str(), "UTF-8"); if (cd_from_utf8 == (iconv_t)-1){ print_cnv_err("UTF-8", def); std::cerr << "Skipping conversion\n"; } } } IConv::~IConv(){ if (cd_to_utf8 != (iconv_t)-1) iconv_close(cd_to_utf8); if (cd_from_utf8 != (iconv_t)-1) iconv_close(cd_from_utf8); } std::string IConv::convert_string(iconv_t cd, const std::string & str) const{ if(cd == (iconv_t)-1) return str; std::string ret; const size_t ISIZE = str.length(); char ibuf[ISIZE]; // note: in UTF-16 string can contain zeros! - for (int i=0; i<ISIZE; i++) ibuf[i] = str[i]; + for (size_t i=0; i<ISIZE; i++) ibuf[i] = str[i]; char *ibuf_ptr = ibuf; size_t icnt = ISIZE; const size_t OSIZE = 512; char obuf[OSIZE + 1]; while(icnt){ char *obuf_ptr = obuf; size_t ocnt = OSIZE; size_t res = iconv(cd, &ibuf_ptr, &icnt, &obuf_ptr, &ocnt); - if (( res == -1) && (errno != E2BIG ) && (icnt>0) && (ocnt>0)){ + if (( res == (size_t)-1) && (errno != E2BIG ) && (icnt>0) && (ocnt>0)){ // skip unknown char icnt--; ocnt--; *obuf_ptr=*ibuf_ptr; ibuf_ptr++; obuf_ptr++; } // note: in UTF-16 string can contain zeros! ret += std::string(obuf, obuf+OSIZE-ocnt); } return ret; } std::string IConv::to_utf8(const std::string &str) const{ return convert_string(cd_to_utf8, str); } std::string IConv::from_utf8(const std::string &str) const{ return convert_string(cd_from_utf8, str); } std::string IConv::from_utf8_7bit(const std::string &str) const{ std::string ret = convert_string(cd_from_utf8, str); for (std::string::iterator i=ret.begin(); i!=ret.end(); i++) *i &= 0x7F; return ret; } diff --git a/core/utils/spirit_utils.cpp b/core/utils/spirit_utils.cpp index a23fe87..ba8704b 100644 --- a/core/utils/spirit_utils.cpp +++ b/core/utils/spirit_utils.cpp @@ -1,38 +1,37 @@ #include <iostream> #include "spirit_utils.h" using namespace boost::spirit::classic; /** function for parsing file and reporting errors */ bool parse_file(const char * name, const char *file, const rule_t & rule){ fit_t first(file); if (!first) { std::cerr << name << ": can't read " << file << '\n'; return false; } fit_t last = first.make_end(); if (first==last) { std::cerr << name << ": empty file " << file << '\n'; return false; } info_t res = parse(pit_t(first, last, file), pit_t(), rule); if (!res.full){ pit_t it=res.stop; file_position fpos=it.get_position(); std::cerr << name << ": can't parse: " << fpos.file << " at line: " << fpos.line << " column: " << fpos.column << "\n"; - int i,j; for (int i=0; i<40; i++) { std::cerr << (*it == '\n' ? ' ': *it); it++; } std::cerr << "\n"; return false; } return true; } diff --git a/core/vmap/vmap_vmap.cpp b/core/vmap/vmap_vmap.cpp index aa23674..3ec0f0e 100644 --- a/core/vmap/vmap_vmap.cpp +++ b/core/vmap/vmap_vmap.cpp @@ -1,348 +1,348 @@ #include <list> #include <string> #include <map> #include <iostream> #include <sstream> #include <iomanip> #include <cstdlib> // for atoi #include "2d/line_utils.h" #include "vmap/zn.h" #include "vmap.h" #define CUR_VER 3.2 namespace vmap { const int point_scale = 1000000; using namespace std; /***************************************/ void point_read_cnv(dPoint &p){ p.x = p.x/point_scale; p.y = p.y/point_scale; } void point_write_cnv(dPoint &p){ p.x = round(p.x*point_scale); p.y = round(p.y*point_scale); } // read key-value pair separated by tab char int get_kv(const string &s, string &key, string &val){ if (s=="") return 1; int tab=s.find('\t', 0); if (tab==-1){ cerr << "skipping bad line: " << s << "\n"; return 1; } int st=0; while (s[st]==' ') st++; key=s.substr(st, tab-st); val=s.substr(tab+1, -1); return 0; } // Read label parameters: align, horizontality or angle, font size // v<3.1: <align:0|1|2> <hor:0|1> <ang> // v>=3.1: L|C|R H|<ang> // v>=3.2: L|C|R H|<ang> S<fsize> void get_l_pars(istream & IN, lpos & l, double ver){ if (ver<3.1){ IN >> l.dir >> l.hor >> l.ang; } else { // version 3.1... char c; IN >> c; switch (c){ case 0: case 'l': case 'L': l.dir=0; break; case 1: case 'c': case 'C': l.dir=1; break; case 2: case 'r': case 'R': l.dir=2; break; } string s; IN >> s; - if (s.size() && s[0]=='H' || s[0]=='h'){ + if (s.size() && (s[0]=='H' || s[0]=='h')){ l.hor=1; l.ang=0.0; } else{ l.hor=0; l.ang=atof(s.c_str()); } IN >> s; // version 3.2 if (s.size() && s[0]=='S') l.fsize = atoi(s.c_str()+1); else l.fsize = 0; } } lpos get_lpos(const string & s, double ver){ lpos ret; istringstream IN1(s); IN1 >> ret.pos; get_l_pars(IN1, ret, ver); point_read_cnv(ret.pos); return ret; } lpos_full get_lbuf(const string & s, double ver){ lpos_full ret; istringstream IN1(s); IN1 >> ret.pos; get_l_pars(IN1, ret, ver); IN1 >> ret.ref; getline(IN1, ret.text); point_read_cnv(ret.pos); point_read_cnv(ret.ref); return ret; } dLine read_points(istream & IN, string & s){ dLine ret; string key,val; if (get_kv(s, key, val)!=0){ cerr << "wrong call of read_points()!\n"; return ret; } s=val; do { dPoint p; istringstream IN1(s); while (IN1.good()){ IN1 >> p; point_read_cnv(p); ret.push_back(p); } getline(IN, s); } while (s[0]=='\t'); return ret; } object read_object(istream & IN, string & s, double ver){ object ret; string key,val; bool read_ahead=false; if ((get_kv(s, key, val)!=0) || (key!="OBJECT")){ cerr << "wrong call of read_object()!\n"; return ret; } istringstream IN1(val); IN1 >> setbase(16) >> ret.type >> ws; getline(IN1,ret.text); while (!IN.eof() || read_ahead){ if (!read_ahead) getline(IN, s); else read_ahead=false; if (get_kv(s, key, val)!=0) continue; if (ver<3.1 && key=="TEXT"){ // backward comp ret.text=val; continue; } if (key=="DIR"){ ret.dir=atoi(val.c_str()); continue; } if (key=="OPT"){ string k,v; if (get_kv(val, k, v)!=0){ cerr << "bad options in: " << s << "\n"; continue; } ret.opts.put(k,v); continue; } if (key=="COMM"){ ret.comm.push_back(val); continue; } if (key=="LABEL"){ ret.labels.push_back(get_lpos(val, ver)); continue; } if (key=="DATA"){ ret.push_back(read_points(IN, s)); read_ahead=true; continue; } break; // end of object } return ret; } // read vmap native format world read(istream & IN){ world ret; string s, key, val; bool read_ahead=false; double ver; IN >> s >> ver; if (s!="VMAP"){ cerr << "error: not a VMAP file\n"; return ret; } if (ver>CUR_VER){ cerr << "error: Too new VMAP format. Update mapsoft package.\n"; return ret; } if (ver<CUR_VER){ cerr << "note: reading old VMAP format version: " << fixed << setprecision(1) << ver << " < " << CUR_VER << "\n"; } while (!IN.eof() || read_ahead){ if (!read_ahead) getline(IN, s); else read_ahead=false; if (get_kv(s, key, val)!=0) continue; if (key=="NAME"){ ret.name=val; continue; } if (key=="RSCALE"){ ret.rscale=atof(val.c_str()); continue; } if (key=="STYLE"){ ret.style=val; continue; } if (key=="MP_ID"){ ret.mp_id=atoi(val.c_str()); continue; } if (key=="BRD"){ ret.brd = read_points(IN, s); read_ahead=true; continue; } if (key=="LBUF"){ ret.lbuf.push_back(get_lbuf(val, ver)); continue; } if (key=="OBJECT"){ ret.push_back(read_object(IN, s, ver)); read_ahead=true; continue; } cerr << "skipping bad line: " << s << "\n"; } return ret; } /***************************************/ void print_line(ostream & OUT, const dLine & L){ int n=0; for (dLine::const_iterator i=L.begin(); i!=L.end(); i++){ if ((n>0)&&(n%4==0)) OUT << "\n\t"; else if (n!=0) OUT << " "; OUT << iPoint(*i); n++; } } // write label position void print_lpos(ostream & OUT, const lpos & L){ // coordinates OUT << iPoint(L.pos) << " "; // alignment (left,right,center) switch (L.dir){ case 0: OUT << 'L'; break; case 1: OUT << 'C'; break; case 2: OUT << 'R'; break; } // angle (or H for horizontal labels) if (L.hor) OUT << " H"; else OUT << " " << setprecision(2) << round(L.ang*100)/100; // font size correction if (L.fsize) OUT << " S" << L.fsize; } // write vmap to ostream // put vmap to mp int write(ostream & OUT, const world & W){ world WS (W); // Sort problem: we write rounded values, so order can change! // Rounding values before sort: for (list<lpos_full>::iterator l=WS.lbuf.begin(); l!=WS.lbuf.end(); l++){ point_write_cnv(l->pos); point_write_cnv(l->ref); } for (list<object>::iterator o=WS.begin(); o!=WS.end(); o++){ for (dMultiLine::iterator l=o->begin(); l!=o->end(); l++){ for (dLine::iterator p=l->begin(); p!=l->end(); p++){ point_write_cnv(*p); } } for (list<lpos>::iterator l=o->labels.begin(); l!=o->labels.end(); l++){ point_write_cnv(l->pos); } } for (dLine::iterator p=WS.brd.begin(); p!=WS.brd.end(); p++){ point_write_cnv(*p); } WS.sort(); WS.lbuf.sort(); OUT << "VMAP " << fixed << setprecision(1) << CUR_VER << "\n"; if (WS.name!="") OUT << "NAME\t" << WS.name << "\n"; OUT << "RSCALE\t" << int(WS.rscale) << "\n"; OUT << "STYLE\t" << WS.style << "\n"; OUT << "MP_ID\t" << WS.mp_id << "\n"; if (WS.brd.size()>0){ OUT << "BRD\t"; print_line(OUT, WS.brd); OUT << "\n"; } // lbuf for (list<lpos_full>::const_iterator l=WS.lbuf.begin(); l!=WS.lbuf.end(); l++){ OUT << "LBUF\t"; print_lpos(OUT, *l); OUT << " " << iPoint(l->ref); if (l->text.size()) OUT << " " << l->text; OUT << "\n"; } for (list<object>::iterator o=WS.begin(); o!=WS.end(); o++){ OUT << "OBJECT\t" << "0x" << setbase(16) << o->type << setbase(10); if (o->text != "") OUT << " " << o->text; OUT << "\n"; if (o->dir != 0) OUT << " DIR\t" << o->dir << "\n"; for (Options::const_iterator i=o->opts.begin(); i!=o->opts.end(); i++){ OUT << " OPT\t" << i->first << "\t" << i->second << "\n"; // protect \n! } for (vector<string>::const_iterator i=o->comm.begin(); i!=o->comm.end(); i++){ OUT << " COMM\t" << *i << "\n"; } o->labels.sort(); for (list<lpos>::const_iterator l=o->labels.begin(); l!=o->labels.end(); l++){ OUT << " LABEL\t"; print_lpos(OUT, *l); OUT << "\n"; } for (dMultiLine::const_iterator i=o->begin(); i!=o->end(); i++){ OUT << " DATA\t"; print_line(OUT, *i); OUT << "\n"; } } return 0; } } // namespace diff --git a/core/vmap/zn.cpp b/core/vmap/zn.cpp index 2912fba..a7cfd11 100644 --- a/core/vmap/zn.cpp +++ b/core/vmap/zn.cpp @@ -1,871 +1,869 @@ // now we use libyaml #include <yaml.h> #include <string> #include <fstream> #include <iostream> #include <iomanip> #include <sstream> #include <sys/stat.h> #include "zn.h" #include "2d/point.h" #include "2d/line_utils.h" #include "err/err.h" #include <boost/lexical_cast.hpp> #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_assign_actor.hpp> namespace zn{ using namespace std; // copy comment from compound to the first object in it void fig_copy_comment(const fig::fig_world::iterator & i, const fig::fig_world::iterator & end){ if (i->type == 6){ // составной объект // копируем первые непустые строки комментария в следующий объект // остальное нам не нужно fig::fig_world::iterator j=i; j++; // пропускаем подписи while ((j!=end) && ( ((j->comment.size()>1) && (j->comment[1]=="[skip]")) || (j->opts.get("MapType", std::string()) == "pic") )) j++; if ((j!=end) && (i->comment.size()>0)){ if (j->comment.size()< i->comment.size()) j->comment.resize(i->comment.size()); - for (int n=0; n<i->comment.size(); n++) j->comment[n] = i->comment[n]; + for (size_t n=0; n<i->comment.size(); n++) j->comment[n] = i->comment[n]; } } } // object need to be skipped (compounds, pics, [skip]) bool is_to_skip(fig::fig_object o){ return (o.type==6) || (o.type==-6) || ((o.comment.size()>1) && (o.comment[1]=="[skip]")) || (o.opts.get("MapType", std::string()) == "pic"); } // convert fig arrow to direction // arr text dir(vmap, mp) // -- 1 0 // -> 0 1 // <- 2 2 int fig_arr2dir(const fig::fig_object & f, bool text){ if ((f.forward_arrow==1)&&(f.backward_arrow==0)) return text?0:1; if ((f.forward_arrow==0)&&(f.backward_arrow==1)) return 2; return text?1:0; } void fig_dir2arr(fig::fig_object & f, int dir, bool text){ if (text && (dir<2)) dir=(dir+1)%2; if (dir==1){f.forward_arrow=1; f.backward_arrow=0;} else if (dir==2){f.backward_arrow=1; f.forward_arrow=0;} else {f.backward_arrow=0; f.forward_arrow=0;} } // Remove compounds and objects with [skip] comment void fig_remove_pics(fig::fig_world & F){ fig::fig_world::iterator i=F.begin(); while (i!=F.end()){ if (i->type==6) fig_copy_comment(i, F.end()); if (is_to_skip(*i)){ i=F.erase(i); continue; } i++; } } // Find nearest point in the line double dist( const iPoint & p, const iLine & l, iPoint & nearest){ if (l.size()<1) return 1e99; double ret=pdist(p,l[0]); nearest=l[0]; for (iLine::const_iterator i=l.begin(); i!=l.end(); i++){ if (ret > pdist(p, *i)){ ret=pdist(p, *i); nearest=*i; } } return ret; } // States for our YAML parser typedef enum { N, KEY, VAL } reading_state_t; // zn_conv constructor. Read config file, // build structure with fig and mp objects zn_conv::zn_conv(const string & style_): style(style_){ default_fig = fig::make_object("2 1 2 2 4 7 10 -1 -1 6.000 0 0 -1 0 0 0"); default_txt = fig::make_object("4 0 4 10 -1 18 8 0.0000 4"); default_mp = mp::make_object("POLYLINE 0x0 0 1"); default_ocad = 704001; default_ocad_txt = 780000; yaml_parser_t parser; yaml_event_t event; vector<int> history; - bool first; string key, val; zn z; reading_state_t state=N; min_depth=999; max_depth=0; znaki.clear(); string conf_file; // looking for a style string gf="/usr/share/mapsoft/"+style+".cnf"; string lf="./"+style+".cnf"; struct stat st_buf; if (stat(lf.c_str(), &st_buf) == 0) conf_file=lf; else if (stat(gf.c_str(), &st_buf) == 0) conf_file=gf; else { throw Err() << "Can't find style " << style << " in " << lf << " or " << gf; } // читаем конф.файл. FILE *file = fopen(conf_file.c_str(), "r"); if (!file) { throw Err() << "Error while reading " << conf_file << ": " << "can't read YAML file " << conf_file; } if (!yaml_parser_initialize(&parser)){ throw Err() << "Error while reading " << conf_file << ": " << "can't initialize YAML parser"; } yaml_parser_set_input_file(&parser, file); do { if (!yaml_parser_parse(&parser, &event)) { throw Err() << "Error while reading " << conf_file << ": " << parser.problem << " at line " << parser.problem_mark.line+1; } if ((event.type == YAML_STREAM_START_EVENT) || (event.type == YAML_DOCUMENT_START_EVENT) || (event.type == YAML_SEQUENCE_START_EVENT) || (event.type == YAML_MAPPING_START_EVENT) ){ history.push_back(event.type); - first=true; } if ((event.type == YAML_STREAM_END_EVENT) || (event.type == YAML_DOCUMENT_END_EVENT) || (event.type == YAML_SEQUENCE_END_EVENT) || (event.type == YAML_MAPPING_END_EVENT) ){ if ((history.size()<=0) || (history[history.size()-1] != event.type-1)) { throw Err() << "Error while reading " << conf_file << ": " << "unmatched stop event at line " << event.start_mark.line+1; } history.pop_back(); } if (event.type != YAML_SCALAR_EVENT) state=N; if (event.type == YAML_MAPPING_START_EVENT){ z=zn(); z.fig=default_fig; z.mp=default_mp; z.ocad=z.ocad_txt=0; state=KEY; } if (event.type == YAML_MAPPING_END_EVENT){ int type = get_type(z.mp); // add label_type if (z.txt.type == 4){ if (z.txt.sub_type==0){ // text on the TR side z.label_type=1; z.label_dir=0; } else if (z.txt.sub_type==2){ // text on the TL side z.label_type=2; z.label_dir=2; } else if (z.txt.sub_type==1) { //centered text z.label_dir=1; if (type & line_mask) z.label_type=4; // text along the line else z.label_type=3; // text on the center } } else{ z.txt=default_txt; z.label_type=0; z.label_dir=0; } znaki.insert(pair<int, zn>(type, z)); state=N; } if ( (event.type == YAML_SCALAR_EVENT) && (state==KEY)){ state=VAL; key.clear(); key.insert(0, (const char *)event.data.scalar.value, event.data.scalar.length); continue; } if ( (event.type == YAML_SCALAR_EVENT) && (state==VAL)){ state=KEY; val.clear(); val.insert(0, (const char *)event.data.scalar.value, event.data.scalar.length); if (key=="name"){ z.name = val; continue; } if (key=="mp"){ z.mp = mp::make_object(val); continue; } if (key=="fig"){ z.fig = fig::make_object(val); if (min_depth>z.fig.depth) min_depth=z.fig.depth; if (max_depth<z.fig.depth) max_depth=z.fig.depth; continue; } if (key=="desc"){ z.desc = val; continue; } if (key=="txt"){ z.txt = fig::make_object(val); if (z.txt.type!=4){ throw Err() << "Error while reading " << conf_file << ": " << "bad txt object in "<< z.name; } continue; } if (key=="pic"){ z.pic = val; if (z.pic!=""){ struct stat st_buf; string g_pd="/usr/share/mapsoft/pics/"; string l_pd="./pics/"; if (stat((l_pd+z.pic+".fig").c_str(), &st_buf) == 0) z.pic=l_pd+z.pic; else if (stat((g_pd+z.pic+".fig").c_str(), &st_buf) == 0) z.pic=g_pd+z.pic; else { throw Err() << "Error while reading " << conf_file << ": " << "can't find zn picture " << z.pic << ".fig" << " in " << l_pd << " or " << g_pd; } } continue; } if (key=="pic_type"){ z.pic_type = val; continue; } if (key=="ocad"){ z.ocad = atoi(val.c_str()); continue; } if (key=="ocad_txt"){ z.ocad_txt = atoi(val.c_str()); continue; } if ((key=="move_to") || (key=="rotate_to")){ istringstream str(val); int i; while (str.good()){ str >> hex >> i; if (str.good() || str.eof()) z.move_to.push_back(i); } z.rotate = (key=="rotate_to"); continue; } if (key=="replace_by"){ istringstream str(val); int i; str >> hex >> i; if (str.good() || str.eof()) z.replace_by = i; continue; } if (key=="curve"){ z.curve = atoi(val.c_str()); continue; } cerr << "Warning while reading " << conf_file << ": " << "unknown field: " << key << "\n"; continue; } yaml_event_delete(&event); } while (history.size()>0); yaml_parser_delete(&parser); assert(!fclose(file)); } // определить тип mp-объекта (почти тривиальная функция :)) int zn_conv::get_type(const mp::mp_object & o) const{ return o.Type + ((o.Class == "POLYLINE")?line_mask:0) + ((o.Class == "POLYGON")?area_mask:0); } // определить тип fig-объекта по внешнему виду. int zn_conv::get_type (const fig::fig_object & o) const { if ((o.type!=2) && (o.type!=3) && (o.type!=4)) return 0; // объект неинтересного вида for (map<int, zn>::const_iterator i = znaki.begin(); i!=znaki.end(); i++){ int c1 = o.pen_color; int c2 = i->second.fig.pen_color; if (((o.type==2) || (o.type==3)) && (o.size()>1)){ // должны совпасть глубина и толщина if ((o.depth != i->second.fig.depth) || (o.thickness != i->second.fig.thickness)) continue; // для линий толщины не 0 - еще и цвет и тип линии if ((o.thickness != 0 ) && ((c1 != c2) || (o.line_style != i->second.fig.line_style))) continue; // заливки int af1 = o.area_fill; int af2 = i->second.fig.area_fill; int fc1 = o.fill_color; int fc2 = i->second.fig.fill_color; // белая заливка бывает двух видов if ((fc1!=0xffffff)&&(af1==40)) {fc1=0xffffff; af1=20;} if ((fc2!=0xffffff)&&(af2==40)) {fc2=0xffffff; af2=20;} // тип заливки должен совпасть if (af1 != af2) continue; // если заливка непрозрачна, то и цвет заливки должен совпасть if ((af1!=-1) && (fc1 != fc2)) continue; // если заливка - штриховка, то и pen_color должен совпасть // (даже для линий толщины 0) if ((af1>41) && (c1 != c2)) continue; // проведя все тесты, мы считаем, что наш объект соответствует // объекту из znaki! return i->first; } else if (((o.type==2) || (o.type==3)) && (o.size()==1)){ // точки // должны совпасть глубина, толщина, цвет, и закругление if ((o.depth == i->second.fig.depth) && (o.thickness == i->second.fig.thickness) && (c1 == c2) && (o.cap_style%2 == i->second.fig.cap_style%2)) return i->first; } else if (o.type==4){ //текст // должны совпасть глубина, цвет, и шрифт if ((o.depth == i->second.fig.depth) && (c1 == c2) && (o.font == i->second.fig.font)) return i->first; } } return 0; } // определить тип по номеру ocad-объекта int zn_conv::get_type(const int ocad_type) const{ for (map<int, zn>::const_iterator i = znaki.begin(); i!=znaki.end(); i++){ - if (i->second.ocad == ocad_type) return (i->first); + if (i->second.ocad == ocad_type) return (i-> +first); } return 0; } map<int, zn>::const_iterator zn_conv::find_type(int type){ map<int, zn>::const_iterator ret = znaki.find(type); if (ret == znaki.end()){ if (unknown_types.count(type) == 0){ cerr << "zn: unknown type: 0x" << setbase(16) << type << setbase(10) << "\n"; unknown_types.insert(type); } } return ret; } // Получить заготовку fig-объекта заданного типа fig::fig_object zn_conv::get_fig_template(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.fig; else return default_fig; } // Получить заготовку mp-объекта заданного типа mp::mp_object zn_conv::get_mp_template(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.mp; else return default_mp; } // Получить номер объекта ocad int zn_conv::get_ocad_type(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.ocad; else return default_ocad; } // Получить заготовку fig-подписи заданного типа fig::fig_object zn_conv::get_label_template(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.txt; else return default_txt; } // Получить номер объекта для подписи ocad int zn_conv::get_ocad_label_type(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.ocad_txt; else return default_ocad_txt; } // Получить тип подписи (для несуществующих - 0) int zn_conv::get_label_type(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.label_type; else return 0; } // Получить направление подписи (для несуществующих - 0) int zn_conv::get_label_dir(int type){ map<int, zn>::const_iterator z = find_type(type); if (z != znaki.end()) return z->second.label_dir; else return 0; } // Преобразовать mp-объект в fig-объект // Если тип 0, то он определяется функцией get_type по объекту list<fig::fig_object> zn_conv::mp2fig(const mp::mp_object & mp, convs::map2pt & cnv, int type){ if (type ==0) type = get_type(mp); list<fig::fig_object> ret; fig::fig_object ret_o = get_fig_template(type); if (ret_o.type == 4){ ret_o.text = mp.Label; ret_o.comment.push_back(""); } else { ret_o.comment.push_back(mp.Label); } ret_o.comment.insert(ret_o.comment.end(), mp.Comment.begin(), mp.Comment.end()); string source=mp.Opts.get<string>("Source"); if (source!="") ret_o.opts.put("Source", source); // convert points if (mp.Class == "POLYGON"){ ret_o.set_points(cnv.line_bck(join_polygons(mp))); ret.push_back(ret_o); } else { for (dMultiLine::const_iterator i=mp.begin(); i!=mp.end(); i++){ ret_o.clear(); ret_o.set_points(cnv.line_bck(*i)); // замкнутая линия if ((mp.Class == "POLYLINE") && (ret_o.size()>1) && (ret_o[0]==ret_o[ret_o.size()-1])){ ret_o.resize(ret_o.size()-1); ret_o.close(); } // стрелки fig_dir2arr(ret_o, mp.Opts.get("DirIndicator",0) ); ret.push_back(ret_o); } } return ret; } // преобразовать fig-объект в mp-объект // Если тип 0, то он определяется функцией get_type по объекту mp::mp_object zn_conv::fig2mp(const fig::fig_object & fig, convs::map2pt & cnv, int type){ if (type ==0) type = get_type(fig); mp::mp_object mp = get_mp_template(type); mp.Opts = fig.opts; if (fig.type == 4){ mp.Label = fig.text; mp.Comment=fig.comment; } else if (fig.comment.size()>0){ mp.Label = fig.comment[0]; mp.Comment.insert(mp.Comment.begin(), fig.comment.begin()+1, fig.comment.end()); } string source=fig.opts.get<string>("Source"); if (source != "") mp.Opts.put("Source", source); dLine pts = cnv.line_frw(fig); // если у нас замкнутая линия - добавим в mp еще одну точку: if ((mp.Class == "POLYLINE") && (fig.is_closed()) && (fig.size()>0) && (fig[0]!=fig[fig.size()-1])) pts.push_back(pts[0]); mp.push_back(pts); // если есть стрелка вперед -- установить DirIndicator=1 // если есть стрелка назад -- установить DirIndicator=2 if ((fig.forward_arrow==1)&&(fig.backward_arrow==0)) mp.Opts["DirIndicator"]="1"; if ((fig.forward_arrow==0)&&(fig.backward_arrow==1)) mp.Opts["DirIndicator"]="2"; return mp; } // Поменять параметры в соответствии с типом. // Если тип 0, то он определяется функцией get_type по объекту void zn_conv::fig_update(fig::fig_object & fig, int type){ if (type ==0) type = get_type(fig); fig::fig_object tmp = get_fig_template(type); // копируем разные параметры: fig.line_style = tmp.line_style; fig.thickness = tmp.thickness; fig.pen_color = tmp.pen_color; fig.fill_color = tmp.fill_color; fig.depth = tmp.depth; fig.pen_style = tmp.pen_style; fig.area_fill = tmp.area_fill; fig.style_val = tmp.style_val; fig.cap_style = tmp.cap_style; fig.join_style = tmp.join_style; fig.font = tmp.font; fig.font_size = tmp.font_size; fig.font_flags = tmp.font_flags; } // Поменять параметры подписи в соответствии с типом // (шрифт, размер, цвет) // Если тип 0 - ничего не менять void zn_conv::label_update(fig::fig_object & fig, int type){ fig::fig_object tmp = get_label_template(type); fig.pen_color = tmp.pen_color; fig.font = tmp.font; fig.font_size = tmp.font_size; fig.depth = tmp.depth; } // Создать картинку к объекту в соответствии с типом. list<fig::fig_object> zn_conv::make_pic(const fig::fig_object & fig, int type){ list<fig::fig_object> ret; if (fig.size()==0) return ret; ret.push_back(fig); if (type ==0) type = get_type(fig); map<int, zn>::const_iterator z = find_type(type); if (z == znaki.end()) return ret; if (z->second.pic=="") return ret; // нет картинки if ((type & area_mask) || (type & line_mask)) return ret; fig::fig_world PIC; if (!fig::read((z->second.pic+".fig").c_str(), PIC)) return ret; // нет картинки for (fig::fig_world::iterator i = PIC.begin(); i!=PIC.end(); i++){ (*i) += fig[0]; // if (is_map_depth(*i)){ // cerr << "warning: picture in " << z->second.pic // << " has objects with wrong depth!\n"; // } i->opts["MapType"]="pic"; ret.push_back(*i); } fig::fig_make_comp(ret); if (fig.opts.exists("Angle")){ double a = fig.opts.get<double>("Angle", 0); fig::fig_rotate(ret, M_PI/180.0*a, fig[0]); } // скопируем комментарии из первого объекта в составной объект. if (ret.size()>1) ret.begin()->comment.insert(ret.begin()->comment.begin(), fig.comment.begin(), fig.comment.end()); return ret; } // Создать подписи к объекту. list<fig::fig_object> zn_conv::make_labels(const fig::fig_object & fig, int type){ list<fig::fig_object> ret; if (fig.size() == 0) return ret; // странный объект if (type ==0) type = get_type(fig); map<int, zn>::const_iterator z = find_type(type); if (z==znaki.end()) return ret; int lpos = z->second.label_type; if (!lpos) return ret; // no label for this object if ((fig.comment.size()==0)|| (fig.comment[0].size()==0)) return ret; // empty label fig::fig_object txt = z->second.txt; // label template if (is_map_depth(txt)){ cerr << "Error: label depth " << txt.depth << " is in map object depth range!"; return ret; } int txt_dist = 7 * (fig.thickness+2); // fig units // определим координаты и наклон подписи iPoint p = fig[0]; if (fig.size()>=2){ if (lpos==4){ // label along the line p = (fig[fig.size()/2-1] + fig[fig.size()/2]) / 2; iPoint p1 = fig[fig.size()/2-1] - fig[fig.size()/2]; if ((p1.x == 0) && (p1.y == 0)) p1.x = 1; dPoint v = pnorm(p1); if (v.x<0) v=-v; txt.angle = atan2(-v.y, v.x); p-= iPoint(int(-v.y*txt_dist*2), int(v.x*txt_dist*2)); } else if (lpos==1 ) { // left just.text // ищем точку с максимальным x-y p = fig[0]; int max = p.x-p.y; - for (int i = 0; i<fig.size(); i++){ + for (size_t i = 0; i<fig.size(); i++){ if (fig[i].x-fig[i].y > max) { max = fig[i].x-fig[i].y; p = fig[i]; } } p+=iPoint(1,-1)*txt_dist; } else if (lpos==2) { // right just.text // ищем точку с минимальным x+y p = fig[0]; int min = p.x+p.y; - for (int i = 0; i<fig.size(); i++){ + for (size_t i = 0; i<fig.size(); i++){ if (fig[i].x+fig[i].y < min) { min = fig[i].x+fig[i].y; p = fig[i]; } } p+=iPoint(-1,-1)*txt_dist; } else if (lpos=3 ) { // center // ищем середину объекта iPoint pmin = fig[0]; iPoint pmax = fig[0]; - for (int i = 0; i<fig.size(); i++){ + for (size_t i = 0; i<fig.size(); i++){ if (pmin.x > fig[i].x) pmin.x = fig[i].x; if (pmin.y > fig[i].y) pmin.y = fig[i].y; if (pmax.x < fig[i].x) pmax.x = fig[i].x; if (pmax.y < fig[i].y) pmax.y = fig[i].y; } p=(pmin+pmax)/2; } } else { // one-point object if (lpos == 1 ) p += iPoint(1,-1)*txt_dist; else if (lpos == 2 ) p += iPoint(-1,-1)*txt_dist; else if (lpos == 3 ) p += iPoint(0, 0)*txt_dist; else if (lpos == 4 ) p += iPoint(0,-2)*txt_dist; } txt.text = fig.comment[0]; txt.push_back(p); ret.push_back(txt); return(ret); } // Depth region in wich all crtographic objects live. // Its boundaries are minimal and maximum depth of objects in config file bool zn_conv::is_map_depth(const fig::fig_object & o) const{ return ((o.type!=6) && (o.type!=-6) && (o.depth>=min_depth) && (o.depth<=max_depth)); } /// functions for updating fig map int zn_conv::fig_add_pics(fig::fig_world & F){ fig::fig_world::iterator i=F.begin(); int count=0; while (i!=F.end()){ if (is_map_depth(*i)){ std::list<fig::fig_object> l1 = make_pic(*i, get_type(*i)); if (l1.size()>1){ count++; i=F.erase(i); F.insert(i, l1.begin(), l1.end()); continue; } } i++; } return count; } int zn_conv::fig_update_labels(fig::fig_world & F){ double maxd1=1*fig::cm2fig; // for the nearest label with correct text double maxd2=1*fig::cm2fig; // for other labels with correct text double maxd3=0.2*fig::cm2fig; // for other labels fig::fig_world::iterator i; - int count=0; // find all labels std::list<fig::fig_world::iterator> labels; for (i=F.begin(); i!=F.end(); i++){ if ((i->opts.exists("MapType")) && (i->opts["MapType"]=="label") && (i->opts.exists("RefPt")) ){ labels.push_back(i); } } // find all objects with title std::list<std::pair<fig::fig_world::iterator, int> > objs; for (i=F.begin(); i!=F.end(); i++){ if (!is_map_depth(*i) || (i->size() <1)) continue; int type=get_type(*i); if ((znaki.count(type)<1) || !znaki[type].label_type) continue; if ((i->comment.size()>0) && (i->comment[0]!="")) objs.push_back(std::pair<fig::fig_world::iterator, int>(i,0)); } std::list<fig::fig_world::iterator>::iterator l; std::list<std::pair<fig::fig_world::iterator, int> >::iterator o; // one nearest label with correct text for (o=objs.begin(); o!=objs.end(); o++){ double d0=1e99; std::list<fig::fig_world::iterator>::iterator l0; iPoint n0; for (l=labels.begin(); l!=labels.end(); l++){ if ((*l)->text != o->first->comment[0]) continue; iPoint nearest; double d=dist((*l)->opts.get("RefPt", iPoint(0,0)), *(o->first), nearest); if ( d < d0){ d0=d; n0=nearest; l0=l;} } if (d0 < maxd1){ (*l0)->opts.put("RefPt", n0); label_update(**l0, get_type(*(o->first))); o->second++; labels.erase(l0); } } // labels with correct text for (o=objs.begin(); o!=objs.end(); o++){ l=labels.begin(); while (l!=labels.end()){ iPoint nearest; if (((*l)->text == o->first->comment[0]) && (dist((*l)->opts.get("RefPt", iPoint(0,0)), *(o->first), nearest) < maxd2)){ (*l)->opts.put("RefPt", nearest); label_update(**l, get_type(*(o->first))); o->second++; l=labels.erase(l); continue; } l++; } } // labels with changed text for (o=objs.begin(); o!=objs.end(); o++){ l=labels.begin(); while (l!=labels.end()){ iPoint nearest; if (dist((*l)->opts.get("RefPt", iPoint(0,0)), *(o->first), nearest) < maxd3){ (*l)->text=o->first->comment[0]; (*l)->opts.put("RefPt", nearest); label_update(**l, get_type(*(o->first))); o->second++; l=labels.erase(l); continue; } l++; } } // create new labels for (o=objs.begin(); o!=objs.end(); o++){ if (o->second > 0) continue; std::list<fig::fig_object> L=make_labels(*(o->first)); for (std::list<fig::fig_object>::iterator j=L.begin(); j!=L.end(); j++){ if (j->size() < 1) continue; iPoint nearest; - double d=dist((*j)[0], *(o->first), nearest); + dist((*j)[0], *(o->first), nearest); j->opts["MapType"]="label"; j->opts.put("RefPt", nearest); F.push_back(*j); } } // remove unused labels for (l=labels.begin(); l!=labels.end(); l++) F.erase(*l); return 0; } } // namespace
ushakov/mapsoft
4106ef7df27e7237caa87178b21822c77a0c6e21
core/loaders: fix warnings
diff --git a/core/2d/image_source.h b/core/2d/image_source.h index 4fc12eb..fbdf872 100644 --- a/core/2d/image_source.h +++ b/core/2d/image_source.h @@ -1,101 +1,101 @@ #ifndef IMAGE_SOURCE_H #define IMAGE_SOURCE_H #include "point.h" #include "rect.h" #include <cassert> #include "image.h" ///\addtogroup lib2d ///@{ ///\defgroup image_source ///@{ /// ImageSource<T> interface -- source for image loader template <typename T> struct ImageSource{ /// Image range virtual iRect range() const = 0; /// Get row number - virtual int get_row() const = 0; + virtual size_t get_row() const = 0; /// Skip n rows of input - virtual bool skip(const int n) = 0; + virtual bool skip(const size_t n) = 0; /// Prepare data line in [x..x+len) range of current row - virtual bool read_data(int x, int len) = 0; + virtual bool read_data(size_t x, int len) = 0; /// Get data from the prepared line - virtual T get_value(int x) const = 0; + virtual T get_value(size_t x) const = 0; /// Render src_rect to dst_rect on Image bool render_to_image(iImage & dst_img, iRect src_rect, iRect dst_rect){ assert(get_row()==0); // подрежем прямоугольники clip_rects_for_image_loader( range(), src_rect, dst_img.range(), dst_rect); if (src_rect.empty() || dst_rect.empty()) return false; for (int dst_y = dst_rect.y; dst_y<dst_rect.y+dst_rect.h; dst_y++){ // source row int src_y = src_rect.y + ((dst_y-dst_rect.y)*src_rect.h)/dst_rect.h; // we can get src_y1 = src_rect.BRC.y after conversion! if (src_y == src_rect.BRC().y) src_y--; if ((!skip(src_y - get_row())) || // skip input up to src_y line (!read_data(src_rect.x, src_rect.w))) break; for (int dst_x = dst_rect.x; dst_x<dst_rect.x+dst_rect.w; dst_x++){ int src_x = ((dst_x-dst_rect.x)*src_rect.w)/dst_rect.w; if (src_x == src_rect.w) src_x--; dst_img.set(dst_x, dst_y, get_value(src_x)); } } return true; } }; typedef ImageSource<double> dImageSource; typedef ImageSource<int> iImageSource; // ImageSourceImage -- source from Image template <typename T> struct ImageSourceImage: ImageSource<T>{ const Image<T> & I; - int row, col; + size_t row, col; ImageSourceImage(const Image<T> & _I): I(_I), row(0){ } - iRect range() const{ + iRect range() const override{ return I.range(); } - int get_row() const{ + size_t get_row() const override{ return row; } - bool skip(const int n){ + bool skip(const size_t n) override{ row+=n; return row < I.h; } - bool read_data(int x, int len){ + bool read_data(size_t x, int len) override{ col=x; return skip(1); // go to the next line }; - T get_value(int x) const{ + T get_value(size_t x) const override{ return I.data[row * I.w + col + x]; } }; typedef ImageSourceImage<double> dImageSourceImage; typedef ImageSourceImage<int> iImageSourceImage; #endif diff --git a/core/loaders/image_gif.cpp b/core/loaders/image_gif.cpp index d9a56ff..4b62ffd 100644 --- a/core/loaders/image_gif.cpp +++ b/core/loaders/image_gif.cpp @@ -1,182 +1,182 @@ #include "image_gif.h" #include <gif_lib.h> #include "err/err.h" namespace image_gif{ #if defined(GIFLIB_MAJOR) && defined(GIFLIB_MINOR) #if GIFLIB_MAJOR == 4 && GIFLIB_MINOR >= 2 #define GIFV 420 #endif #if GIFLIB_MAJOR >= 5 #define GIFV 500 #endif #endif #ifndef GIFV #define GIFV 0 #endif // GIFLIB_MAJOR and GIFLIB_MINOR defined in 4.1.6 and later // GifErrorString(code) #if GIFV == 500 GifFileType* GifOpen(const char *file){ int code; GifFileType *gif = DGifOpenFileName(file, &code); if (!gif) throw Err() << GifErrorString(code); return gif; } void GifClose(GifFileType *gif){ int code; DGifCloseFile(gif, &code); if (code) throw Err() << GifErrorString(code); } #endif // 4.2 <= v < 5 // GifErrorString() #if GIFV == 420 GifFileType* GifOpen(const char *file){ GifFileType *gif = DGifOpenFileName(file); if (!gif) throw Err() << GifErrorString(); return gif; } void GifClose(GifFileType *gif){ DGifCloseFile(gif); } #endif // old versions // GifLastError() #if GIFV == 0 GifFileType* GifOpen(const char *file){ GifFileType *gif = DGifOpenFileName(file); if (!gif) throw Err() << GifLastError(); return gif; } void GifClose(GifFileType *gif){ DGifCloseFile(gif); } #endif iPoint size(const char *file){ GifFileType *gif = GifOpen(file); iPoint ret(gif->SWidth, gif->SHeight); GifClose(gif); return ret; } int load(const char *file, iRect src_rect, iImage & image, iRect dst_rect){ // open file and read screen descriptor GifFileType *gif = GifOpen(file); /* Go to the first image, skip all extensions */ GifRecordType RecordType; - int ExtCode, GifLineLen; + int ExtCode; GifByteType *Extension, *GifLine; do { if (DGifGetRecordType(gif, &RecordType) == GIF_ERROR) {GifClose(gif); return 2;} if (RecordType == TERMINATE_RECORD_TYPE) return 2; if (RecordType == EXTENSION_RECORD_TYPE){ if (DGifGetExtension(gif, &ExtCode, &Extension) == GIF_ERROR) {GifClose(gif); return 2;} while (Extension != NULL){ if (DGifGetExtensionNext(gif, &Extension) == GIF_ERROR) {GifClose(gif); return 2;} } } } while (RecordType != IMAGE_DESC_RECORD_TYPE); /* read image description */ if (DGifGetImageDesc(gif) == GIF_ERROR) {GifClose(gif); return 2;} int width = gif->SWidth; int height = gif->SHeight; int w = gif->Image.Width; int h = gif->Image.Height; int dx = gif->Image.Left; int dy = gif->Image.Top; int colors[256]; for (int i=0; i<gif->SColorMap->ColorCount; i++){ colors[i] = gif->SColorMap->Colors[i].Red + (gif->SColorMap->Colors[i].Green << 8) + (gif->SColorMap->Colors[i].Blue << 16) + (0xFF<<24); } int bgcolor = colors[gif->SBackGroundColor]; GifLine = (GifByteType *)malloc(width); if (!GifLine){ std::cerr << "can't allocate memory\n"; GifClose(gif); return 2; } // подрежем прямоугольники clip_rects_for_image_loader( iRect(0,0,width,height), src_rect, iRect(0,0,image.w,image.h), dst_rect); if (src_rect.empty() || dst_rect.empty()){ GifClose(gif); free(GifLine); return 1;} int src_y = 0; for (int dst_y = dst_rect.y; dst_y<dst_rect.y+dst_rect.h; dst_y++){ // откуда мы хотим взять строчку int src_y1 = src_rect.y + ((dst_y-dst_rect.y)*src_rect.h)/dst_rect.h; // при таком делении может выйти src_y1 = src_rect.BRC.y, что плохо! if (src_y1 == src_rect.BRC().y) src_y1--; if (src_y1 < dy || src_y1>=dy+h){ for (int dst_x = dst_rect.x; dst_x<dst_rect.x+dst_rect.w; dst_x++){ image.set(dst_x, dst_y, bgcolor); } src_y++; continue; } // пропустим нужное число строк: while (src_y<=src_y1){ if (DGifGetLine(gif, GifLine, w) == GIF_ERROR) {GifClose(gif); free(GifLine); return 2;} src_y++; } // теперь мы находимся на нужной строке for (int dst_x = dst_rect.x; dst_x<dst_rect.x+dst_rect.w; dst_x++){ int src_x = src_rect.x + ((dst_x-dst_rect.x)*src_rect.w)/dst_rect.w; if (src_x == src_rect.BRC().x) src_x--; if (src_x <dx || src_x>=dx+w) image.set(dst_x, dst_y, bgcolor); else image.set(dst_x, dst_y, colors[GifLine[src_x-dx]]); } } free(GifLine); GifClose(gif); return 0; } iImage load(const char *file, const int scale){ iPoint s = size(file); iImage ret(s.x/scale,s.y/scale); if (s.x*s.y==0) return ret; load(file, iRect(0,0,s.x,s.y), ret, iRect(0,0,s.x/scale,s.y/scale)); return ret; } int save(const iImage & im, const char * file){ std::cerr << "GIF writing is not supported\n"; return 0; } } // namespace diff --git a/core/loaders/image_jpeg.cpp b/core/loaders/image_jpeg.cpp index 7bc2426..e1abcfb 100644 --- a/core/loaders/image_jpeg.cpp +++ b/core/loaders/image_jpeg.cpp @@ -1,207 +1,207 @@ #include "image_jpeg.h" #include "2d/image_source.h" #include <jpeglib.h> #include <stdio.h> namespace image_jpeg{ void my_error_exit (j_common_ptr cinfo) { (*cinfo->err->output_message) (cinfo); throw 2; } iPoint size(const char *file){ struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; try { cinfo.err = jpeg_std_error(&jerr); jerr.error_exit = my_error_exit; jpeg_create_decompress(&cinfo); FILE * infile; if ((infile = fopen(file, "rb")) == NULL) { std::cerr << "Can't open " << file << "\n"; throw 3; } jpeg_stdio_src(&cinfo, infile); jpeg_read_header(&cinfo, TRUE); iPoint p(cinfo.image_width, cinfo.image_height); jpeg_destroy_decompress(&cinfo); fclose(infile); return p; } catch(int x){ return iPoint(0,0);} } struct ImageSourceJPEG : iImageSource { - int row,col; + size_t row,col; unsigned char *buf; struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; FILE * infile; ImageSourceJPEG(const char *file, int denom): row(0),col(0) { // open file, get image size cinfo.err = jpeg_std_error(&jerr); jerr.error_exit = my_error_exit; jpeg_create_decompress(&cinfo); if ((infile = fopen(file, "rb")) == NULL) { std::cerr << "can't open " << file << "\n"; throw 3; } jpeg_stdio_src(&cinfo, infile); jpeg_read_header(&cinfo, TRUE); // load always in RGB mode cinfo.out_color_space = JCS_RGB; assert((denom==1) || (denom==2) || (denom==4) || (denom==8)); cinfo.scale_denom = denom; jpeg_start_decompress(&cinfo); buf = new unsigned char[(cinfo.image_width+1) * 3]; } ~ImageSourceJPEG(){ delete[] buf; jpeg_abort_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(infile); } - iRect range() const{ + iRect range() const override{ return iRect(0,0,cinfo.image_width,cinfo.image_height); } - int get_row() const{ + size_t get_row() const override{ return row; } - bool skip(const int n){ - for (int i=row; i<row+n; i++){ + bool skip(const size_t n) override{ + for (size_t i=row; i<row+n; i++){ if (row>cinfo.image_height) break; jpeg_read_scanlines(&cinfo, (JSAMPLE**)&buf, 1); } row+=n; return (row <= cinfo.image_height) && (buf); } - bool read_data(int x, int len){ + bool read_data(size_t x, int len) override{ col=x; if (len+x > cinfo.image_width) return false; return skip(1); // go to the next line }; - int get_value(int x) const{ + int get_value(size_t x) const override{ return 0xFF000000 + buf[3*(x+col)] + (buf[3*(x+col)+1]<<8) + (buf[3*(x+col)+2]<<16); } }; int load(const char *file, iRect src_rect, iImage & image, iRect dst_rect){ // посмотрим, можно ли загружать сразу уменьшенный jpeg // (поддерживается уменьшение в 1,2,4,8 раз) int xscale = src_rect.w / dst_rect.w; int yscale = src_rect.h / dst_rect.h; int scale = std::min(xscale, yscale); int denom=1; if (scale <2) denom = 1; else if (scale <4) denom = 2; else if (scale <8) denom = 4; else denom = 8; src_rect /= denom; #ifdef DEBUG_JPEG std::cerr << "jpeg: loading at scale 1/" << denom << "\n"; #endif try { ImageSourceJPEG source(file, denom); return source.render_to_image(image, src_rect, dst_rect)? 0:1; } catch(int x) {return x;} } int save(const iImage & im, const iRect & src_rect, const char *file, int quality){ if ((quality<0)||(quality>100)){ std::cerr << "JPEG quality not in range 0..100 (" << quality << ")\n"; return 1; } struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); FILE * outfile; if ((outfile = fopen(file, "wb")) == NULL) { std::cerr << "Can't open " << file << "\n"; return 1; } jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = src_rect.w; cinfo.image_height = src_rect.h; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality (&cinfo, quality, true); jpeg_start_compress(&cinfo, TRUE); unsigned char *buf = new unsigned char[src_rect.w * 3]; for (int y = src_rect.y; y < src_rect.y+src_rect.h; y++){ if ((y<0)||(y>=im.h)){ for (int x = 0; x < src_rect.w*3; x++) buf[x] = 0; } else { for (int x = 0; x < src_rect.w; x++){ int c = 0; if ((x+src_rect.x >= 0) && (x+src_rect.x<im.w)) c = im.get(x+src_rect.x, y); buf[3*x] = c & 0xFF; buf[3*x+1] = (c >> 8) & 0xFF; buf[3*x+2] = (c >> 16) & 0xFF; } } jpeg_write_scanlines(&cinfo, (JSAMPLE**)&buf, 1); } delete [] buf; jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); fclose(outfile); return 0; } iImage load(const char *file, const int scale){ iPoint s = size(file); iImage ret(s.x/scale,s.y/scale); if (s.x*s.y==0) return ret; load(file, iRect(0,0,s.x,s.y), ret, iRect(0,0,s.x/scale,s.y/scale)); return ret; } int save(const iImage & im, const char * file, int quality){ return save(im, im.range(), file, quality); } } diff --git a/core/loaders/image_png.cpp b/core/loaders/image_png.cpp index 1c9e658..e27d2dc 100644 --- a/core/loaders/image_png.cpp +++ b/core/loaders/image_png.cpp @@ -1,376 +1,376 @@ #include "image_png.h" #include <png.h> #include <cstring> namespace image_png{ iPoint size(const char *file){ FILE * infile; if ((infile = fopen(file, "rb")) == NULL) { std::cerr << "Can't open " << file << "\n"; return iPoint(0,0); } png_byte sign[8]; const char sign_size = 8; if ((fread(sign, 1,sign_size,infile)!=sign_size)|| (png_sig_cmp(sign, 0, sign_size)!=0)){ std::cerr << "Not a PNG file: " << file << "\n"; fclose(infile); return iPoint(0,0); } png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,NULL,NULL); if (!png_ptr){ std::cerr << "Can't make png_read_struct\n"; fclose(infile); return iPoint(0,0); } png_infop info_ptr = png_create_info_struct(png_ptr); png_infop end_info = png_create_info_struct(png_ptr); if ((!info_ptr) || (!end_info)) { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); std::cerr << "Can't make png_info_struct\n"; fclose(infile); return iPoint(0,0); } if (setjmp(png_jmpbuf(png_ptr))){ png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); std::cerr << "Can't read PNG file\n"; fclose(infile); return iPoint(0,0); } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, sign_size); png_read_info(png_ptr, info_ptr); int width = png_get_image_width(png_ptr, info_ptr); int height = png_get_image_height(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(infile); return iPoint(width, height); } int load(const char *file, iRect src_rect, iImage & image, iRect dst_rect){ FILE * infile; if ((infile = fopen(file, "rb")) == NULL) return 2; png_byte sign[8]; const char sign_size = 8; if ((fread(sign, 1,sign_size,infile)!=sign_size)|| (png_sig_cmp(sign, 0, sign_size)!=0)){ fclose(infile); return 2; } png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,NULL,NULL); if (!png_ptr){ fclose(infile); return 2; } png_infop info_ptr = png_create_info_struct(png_ptr); png_infop end_info = png_create_info_struct(png_ptr); if ((!info_ptr) || (!end_info)){ png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); fclose(infile); return 2; } if (setjmp(png_jmpbuf(png_ptr))){ png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(infile); return 2; } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, sign_size); png_read_info(png_ptr, info_ptr); png_uint_32 width, height; int bit_depth, color_type, interlace_type; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type ,NULL,NULL); // зададим преобразования if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); if (!(color_type & PNG_COLOR_MASK_ALPHA)) png_set_add_alpha(png_ptr, 0xFF, PNG_FILLER_AFTER); if (bit_depth == 16) png_set_strip_16(png_ptr); // png_read_update_info(png_ptr, info_ptr); png_bytep row_buf = (png_bytep)png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); // подрежем прямоугольники clip_rects_for_image_loader( iRect(0,0,width,height), src_rect, iRect(0,0,image.w,image.h), dst_rect); if (src_rect.empty() || dst_rect.empty()) return 1; if (interlace_type ==PNG_INTERLACE_NONE){ int src_y = 0; for (int dst_y = dst_rect.y; dst_y<dst_rect.y+dst_rect.h; dst_y++){ // откуда мы хотим взять строчку int src_y1 = src_rect.y + ((dst_y-dst_rect.y)*src_rect.h)/dst_rect.h; // при таком делении может выйти src_y1 = src_rect.BRC.y, что плохо! if (src_y1 == src_rect.BRC().y) src_y1--; // пропустим нужное число строк: while (src_y<=src_y1){ png_read_row(png_ptr, row_buf, NULL); src_y++; } // теперь мы находимся на нужной строке for (int dst_x = dst_rect.x; dst_x<dst_rect.x+dst_rect.w; dst_x++){ int src_x = src_rect.x + ((dst_x-dst_rect.x)*src_rect.w)/dst_rect.w; if (src_x == src_rect.BRC().x) src_x--; int r = row_buf[4*src_x]; int g = row_buf[4*src_x+1]; int b = row_buf[4*src_x+2]; int a = row_buf[4*src_x+3]; if (a<255){ r = (r*a)/255; g = (g*a)/255; b = (b*a)/255; } image.set(dst_x, dst_y, r + (g<<8) + (b<<16) + (a<<24)); } } png_free(png_ptr, row_buf); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(infile); return 0; } if (interlace_type == PNG_INTERLACE_ADAM7){ png_free(png_ptr, row_buf); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); std::cerr << "PNG_INTERLACE_ADAM7 not supported yet! Fixme!\n"; fclose(infile); return 2; // Очень заманчиво сделать честную поддержку interlaced картинок! // 1й проход - масштаб 1/8 // 1-3й проход - масштаб 1/4 // 1-5й проход - масштаб 1/2 // PNG_INTERLACE_ADAM7: // Xooooooo ooooXooo oooooooo ooXoooXo oooooooo oXoXoXoX oooooooo // oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo XXXXXXXX // oooooooo oooooooo oooooooo oooooooo XoXoXoXo oXoXoXoX oooooooo // oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo XXXXXXXX // oooooooo oooooooo XoooXooo ooXoooXo oooooooo oXoXoXoX oooooooo // oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo XXXXXXXX // oooooooo oooooooo oooooooo oooooooo XoXoXoXo oXoXoXoX oooooooo // oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo XXXXXXXX // TODO // посмотрим, можно ли загружать сразу уменьшенную картинку // (поддерживается уменьшение в 1,2,4,8 раз) int xscale = src_rect.w / dst_rect.w; int yscale = src_rect.h / dst_rect.h; int scale = std::min(xscale, yscale); if (scale <2) scale = 1; else if (scale <4) scale = 2; else if (scale <8) scale = 4; else scale = 8; // TODO } // других типов PNG_INTERLACE вообще-то не должно быть... png_free(png_ptr, row_buf); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(infile); return 2; } int save(const iImage & im, const iRect & src_rect, const char *file){ FILE *outfile = fopen(file, "wb"); if (!outfile) return 2; png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return 2; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, (png_infopp)NULL); return 2; } if (setjmp(png_jmpbuf(png_ptr))){ png_destroy_write_struct(&png_ptr, &info_ptr); fclose(outfile); return 2; } // scan image for colors and alpha bool alpha = false; bool fulla = false; bool fullc = false; bool color = false; - int colors[256], mc=0; + uint32_t colors[256], mc=0; memset(colors, 0, 256*sizeof(int)); for (int y = src_rect.y; y < src_rect.y+src_rect.h; y++){ if ((y<0)||(y>=im.h)) continue; for (int x = 0; x < src_rect.w; x++){ if ((x+src_rect.x < 0) || (x+src_rect.x>=im.w)) continue; - unsigned int c = im.get(x+src_rect.x, y); + uint32_t c = im.get(x+src_rect.x, y); if (!alpha){ int a = (c >> 24) & 0xFF; if (a<255) alpha=true; } if (!fulla){ int a = (c >> 24) & 0xFF; if (a>0 && a<255) fulla=true; } if (!color){ int r = (c >> 16) & 0xFF; int g = (c >> 8) & 0xFF; int b = c & 0xFF; if (r!=g || r!=b) color=true; } if (!fullc){ bool found=false; - for (int i=0; i<mc; i++) + for (uint32_t i=0; i<mc; i++) if (c==colors[i]){ found=true; break;} if (!found){ if (mc==256) fullc=true; else colors[mc++] = c; } } } } png_init_io(png_ptr, outfile); // png header int color_type = PNG_COLOR_TYPE_PALETTE; if (!color) color_type = PNG_COLOR_TYPE_GRAY; if ((fullc || fulla) && color) color_type = PNG_COLOR_TYPE_RGB; if (alpha && color_type!=PNG_COLOR_TYPE_PALETTE) color_type |= PNG_COLOR_MASK_ALPHA; png_set_IHDR(png_ptr, info_ptr, src_rect.w, src_rect.h, 8, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); // png palette if (color_type == PNG_COLOR_TYPE_PALETTE){ png_color pcolors[256]; - for (int i=0; i<mc; i++){ + for (uint32_t i=0; i<mc; i++){ pcolors[i].red = colors[i] & 0xFF; pcolors[i].green = (colors[i] >>8) & 0xFF; pcolors[i].blue = (colors[i] >>16) & 0xFF; } png_set_PLTE(png_ptr, info_ptr, pcolors, mc); if (alpha){ // tRNS png_byte trans[256]; - for (int i=0; i<mc; i++){ + for (size_t i=0; i<mc; i++){ trans[i] = (colors[i]>>24) & 0xFF; } png_set_tRNS(png_ptr, info_ptr, trans, mc, 0); } } png_write_info(png_ptr, info_ptr); png_bytep buf = (png_bytep)png_malloc(png_ptr, src_rect.w*4); if (!info_ptr) { png_destroy_write_struct(&png_ptr, &info_ptr); return 2; } for (int y = src_rect.y; y < src_rect.y+src_rect.h; y++){ if ((y<0)||(y>=im.h)){ for (int x = 0; x < src_rect.w*4; x++) buf[x] = 0; } else { for (int x = 0; x < src_rect.w; x++){ - int c = 0; + uint32_t c = 0; if ((x+src_rect.x >= 0) && (x+src_rect.x<im.w)) c = im.get(x+src_rect.x, y); switch (color_type){ case PNG_COLOR_TYPE_GRAY: buf[x] = c & 0xFF; break; case PNG_COLOR_TYPE_GRAY_ALPHA: buf[2*x] = c & 0xFF; buf[2*x+1] = (c >> 24) & 0xFF; break; case PNG_COLOR_TYPE_RGB: buf[3*x] = c & 0xFF; buf[3*x+1] = (c >> 8) & 0xFF; buf[3*x+2] = (c >> 16) & 0xFF; break; case PNG_COLOR_TYPE_RGB_ALPHA: buf[4*x] = c & 0xFF; buf[4*x+1] = (c >> 8) & 0xFF; buf[4*x+2] = (c >> 16) & 0xFF; buf[4*x+3] = (c >> 24) & 0xFF; break; case PNG_COLOR_TYPE_PALETTE: - for (int i=0; i<mc; i++) + for (uint32_t i=0; i<mc; i++) if (colors[i] == c) {buf[x] = (unsigned char)i; break;} break; } } } png_write_row(png_ptr, buf); } png_free(png_ptr, buf); png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(outfile); return 0; } iImage load(const char *file, const int scale){ iPoint s = size(file); iImage ret(s.x/scale,s.y/scale); if (s.x*s.y==0) return ret; load(file, iRect(0,0,s.x,s.y), ret, iRect(0,0,s.x/scale,s.y/scale)); return ret; } int save(const iImage & im, const char * file){ return save(im, im.range(), file); } } // namespace diff --git a/core/loaders/image_tiff.cpp b/core/loaders/image_tiff.cpp index 67acaea..0e4cb79 100644 --- a/core/loaders/image_tiff.cpp +++ b/core/loaders/image_tiff.cpp @@ -1,291 +1,291 @@ #include "image_tiff.h" #include <tiffio.h> #include <cstring> namespace image_tiff{ using namespace std; // getting file dimensions iPoint size(const char *file){ TIFF* tif = TIFFOpen(file, "rb"); if (!tif){ // cerr << "image_tiff: can't read " << file << endl; return iPoint(0,0); } uint32 w=0, h=0; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFClose(tif); return iPoint(w,h); } int load(const char *file, iRect src_rect, iImage & image, iRect dst_rect){ TIFF* tif = TIFFOpen(file, "rb"); if (!tif){ cerr << "image_tiff: can't read " << file << endl; return 2; } int tiff_w, tiff_h; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiff_w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiff_h); // подрежем прямоугольники clip_rects_for_image_loader( iRect(0,0,tiff_w,tiff_h), src_rect, iRect(0,0,image.w,image.h), dst_rect); if (src_rect.empty() || dst_rect.empty()) return 1; int scan = TIFFScanlineSize(tif); int bpp = scan/tiff_w; uint8 *cbuf = (uint8 *)_TIFFmalloc(scan); // Мы можем устроить произвольный доступ к строчкам, // если tiff без сжатия или если каждая строчка запакована отдельно. bool can_skip_lines = false; int compression_type, rows_per_strip; TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression_type); TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if ((compression_type==COMPRESSION_NONE)||(rows_per_strip==1)) can_skip_lines = true; #ifdef DEBUG_TIFF cerr << "tiff: can we skip lines: " << can_skip_lines << "\n"; #endif int photometric; uint32 colors[256]; TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric); if (photometric == PHOTOMETRIC_RGB || photometric == PHOTOMETRIC_MINISWHITE || photometric == PHOTOMETRIC_MINISBLACK){} else if (photometric == PHOTOMETRIC_PALETTE){ uint16 *cmap[3]; TIFFGetField(tif, TIFFTAG_COLORMAP, cmap, cmap+1, cmap+2); for (int i=0; i<256; i++){ colors[i] = (((uint32)cmap[0][i] & 0xFF00)>>8) + ((uint32)cmap[1][i] & 0xFF00) + (((uint32)cmap[2][i] & 0xFF00)<<8) + (0xFF<<24); } } else{ cerr << "image_tiff: unsupported photometric type: " << photometric << endl; return 2; } int src_y = 0; for (int dst_y = dst_rect.y; dst_y<dst_rect.y+dst_rect.h; dst_y++){ // откуда мы хотим взять строчку int src_y1 = src_rect.y + ((dst_y-dst_rect.y)*src_rect.h)/dst_rect.h; // при таком делении может выйти src_y1 = src_rect.BRC.y, что плохо! if (src_y1 == src_rect.BRC().y) src_y1--; // пропустим нужное число строк: if (!can_skip_lines){ while (src_y<src_y1){ TIFFReadScanline(tif, cbuf, src_y); src_y++; } } else {src_y=src_y1;} TIFFReadScanline(tif, cbuf, src_y); src_y++; // теперь мы находимся на нужной строке for (int dst_x = dst_rect.x; dst_x<dst_rect.x+dst_rect.w; dst_x++){ int src_x = src_rect.x + ((dst_x-dst_rect.x)*src_rect.w)/dst_rect.w; if (src_x == src_rect.BRC().x) src_x--; if (photometric == PHOTOMETRIC_PALETTE){ image.set(dst_x, dst_y, colors[cbuf[src_x]]); } else if (photometric == PHOTOMETRIC_RGB){ if (bpp==3) // RGB image.set(dst_x, dst_y, cbuf[3*src_x] + (cbuf[3*src_x+1]<<8) + (cbuf[3*src_x+2]<<16) + (0xFF<<24)); else if (bpp==4) // RGBA image.set(dst_x, dst_y, cbuf[4*src_x] + (cbuf[4*src_x+1]<<8) + (cbuf[4*src_x+2]<<16) + (cbuf[4*src_x+3]<<24)); else if (bpp==1) // G image.set(dst_x, dst_y, cbuf[src_x] + (cbuf[src_x]<<8) + (cbuf[src_x]<<16) + (0xFF<<24)); } else if (photometric == PHOTOMETRIC_MINISWHITE){ if (bpp==2) // 16bit image.set(dst_x, dst_y, 0xFFFFFFFFFF - (cbuf[2*src_x+1] + (cbuf[2*src_x+1]<<8) + (cbuf[2*src_x+1]<<16))); else if (bpp==1) // 8bit image.set(dst_x, dst_y, 0xFFFFFFFFFF - (cbuf[src_x] + (cbuf[src_x]<<8) + (cbuf[src_x]<<16))); } else if (photometric == PHOTOMETRIC_MINISBLACK){ if (bpp==2) // 16bit image.set(dst_x, dst_y, cbuf[2*src_x+1] + (cbuf[2*src_x+1]<<8) + (cbuf[2*src_x+1]<<16) + (0xFF<<24)); else if (bpp==1) // 8bit image.set(dst_x, dst_y, cbuf[src_x] + (cbuf[src_x]<<8) + (cbuf[src_x]<<16) + (0xFF<<24)); } } } _TIFFfree(cbuf); TIFFClose(tif); return 0; } // save part of image int save(const iImage & im, const iRect & src_rect, const char *file){ TIFF* tif = TIFFOpen(file, "wb"); if (!tif){ cerr << "image_tiff: can't write " << file << endl; return 1; } // scan image for colors and alpha bool alpha = false; bool fulla = false; bool fullc = false; bool color = false; - uint32 colors[256], mc=0; + uint32_t colors[256], mc=0; memset(colors, 0, 256*sizeof(int)); for (int y = src_rect.y; y < src_rect.y+src_rect.h; y++){ if ((y<0)||(y>=im.h)) continue; for (int x = 0; x < src_rect.w; x++){ if ((x+src_rect.x < 0) || (x+src_rect.x>=im.w)) continue; - unsigned int c = im.get(x+src_rect.x, y); + uint32_t c = im.get(x+src_rect.x, y); if (!alpha){ int a = (c >> 24) & 0xFF; if (a<255) alpha=true; } if (!fulla){ int a = (c >> 24) & 0xFF; if (a>0 && a<255) fulla=true; } if (!color){ int r = (c >> 16) & 0xFF; int g = (c >> 8) & 0xFF; int b = c & 0xFF; if (r!=g || r!=b) color=true; } if (!fullc){ bool found=false; - for (int i=0; i<mc; i++) + for (uint32_t i=0; i<mc; i++) if (c==colors[i]){ found=true; break;} if (!found){ if (mc==256) fullc=true; else colors[mc++] = c; } } } } int bpp = 3; if (!color || !fullc) {bpp=1;} if (alpha) {bpp=4; fullc=true;} int scan = bpp*src_rect.w; TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, src_rect.w); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, src_rect.h); TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, bpp); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, 1); TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1); TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_LZW); uint16 cmap[3][256]; if (fullc){ TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else{ if (color){ for (int i=0; i<256; i++){ cmap[0][i] = (colors[i]<<8)&0xFF00; cmap[1][i] = colors[i] &0xFF00; cmap[2][i] = (colors[i]>>8)&0xFF00; } } else{ for (uint16 i=0; i<256; i++){ cmap[0][i] = cmap[1][i] = cmap[2][i] = i<<8; colors[i] = i; } } TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE); TIFFSetField(tif, TIFFTAG_COLORMAP, cmap, cmap+1, cmap+2); } if (bpp==4){ int type=EXTRASAMPLE_UNASSALPHA; TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, 1, &type); } tdata_t buf = _TIFFmalloc(scan); uint8 *cbuf = (uint8 *)buf; for (int row = 0; row < src_rect.h; row++){ if ((row+src_rect.y <0)||(row+src_rect.y>=im.h)){ for (int col = 0; col < src_rect.w*bpp; col++) cbuf[col] = 0; } else { for (int col = 0; col < src_rect.w; col++){ - int c = 0; + uint32_t c = 0; if ((col+src_rect.x >=0)&&(col+src_rect.x<im.w)) c = im.get(src_rect.x+col,src_rect.y+row); if (bpp==3){ // RGB cbuf[3*col] = c & 0xFF; cbuf[3*col+1] = (c >> 8) & 0xFF; cbuf[3*col+2] = (c >> 16) & 0xFF; } else if (bpp==4){ // RGBA cbuf[4*col] = c & 0xFF; cbuf[4*col+1] = (c >> 8) & 0xFF; cbuf[4*col+2] = (c >> 16) & 0xFF; cbuf[4*col+3] = (c >> 24) & 0xFF; } else if (bpp==1){ if (color){ - for (int i=0; i<mc; i++) + for (size_t i=0; i<mc; i++) if (colors[i] == c) {cbuf[col] = (unsigned char)i; break;} } else{ cbuf[col] = c; } } } } TIFFWriteScanline(tif, buf, row); } _TIFFfree(buf); TIFFClose(tif); return 0; } iImage load(const char *file, const int scale){ iPoint s = size(file); iImage ret(s.x/scale,s.y/scale); if (s.x*s.y==0) return ret; load(file, iRect(0,0,s.x,s.y), ret, iRect(0,0,s.x/scale,s.y/scale)); return ret; } // save the whole image int save(const iImage & im, const char * file){ return save(im, im.range(), file); } } // namespace
ushakov/mapsoft
f4e8d23992f4c23696d9607a62fdf66398af4c41
core/img_io: fix warnings
diff --git a/core/img_io/draw_trk.cpp b/core/img_io/draw_trk.cpp index 818ee31..566c802 100644 --- a/core/img_io/draw_trk.cpp +++ b/core/img_io/draw_trk.cpp @@ -1,167 +1,167 @@ #include <vector> #include <cmath> #include "draw_trk.h" #include "utils/cairo_wrapper.h" #include "2d/line_utils.h" #include "2d/rainbow.h" using namespace std; void draw_trk(iImage & image, const iPoint & origin, const Conv & cnv, const g_track & trk, const Options & opt){ CairoWrapper cr(image); cr->set_line_cap(Cairo::LINE_CAP_ROUND); int w = trk.width; int arr_w = w * 2.0; int dot_w = w * 0.5; int arr_dist = w * 10; // minimal segment with arrow string trk_draw_mode = opt.get<string>("trk_draw_mode", "normal"); if (trk_draw_mode == "normal"){ bool draw_dots = opt.exists("trk_draw_dots"); bool draw_arrows = opt.exists("trk_draw_arrows"); cr->set_color(trk.color); cr->set_line_width(w); if (trk.size()==1){ // draw 1pt tracks even in non-draw_dots mode g_trackpoint p1(trk[0]); cnv.bck(p1); p1-=origin; cr->move_to(p1); cr->circle(p1, dot_w); } - for (int i=0; i<trk.size(); i++){ + for (size_t i=0; i<trk.size(); i++){ g_trackpoint p1,p2; p2 = trk[i]; if (i==0){ if (trk.type==trkType("closed")) p1=trk[trk.size()-1]; else continue; } else p1=trk[i-1]; if (p2.start) continue; cnv.bck(p1); p1-=origin; cnv.bck(p2); p2-=origin; cr->move_to(p1); cr->line_to(p2); if (draw_dots){ if ((i==1) || p1.start) cr->circle(p1, dot_w); cr->circle(p2, dot_w); } if (draw_arrows && (pdist(p1-p2) > arr_dist)){ dPoint p0=(p1+p2)/2; dPoint dp = pnorm(p1-p2) * arr_w; dPoint p3 = p0 + dp + dPoint(dp.y, -dp.x) * 0.5; dPoint p4 = p0 + dp - dPoint(dp.y, -dp.x) * 0.5; cr->move_to(p0); cr->line_to(p3); cr->line_to(p4); cr->line_to(p0); } } cr->stroke(); } if (trk_draw_mode == "speed"){ double trk_speed1 = opt.get<double>("trk_draw_v1", 0); double trk_speed2 = opt.get<double>("trk_draw_v2", 10); cr->set_line_width(2*w); simple_rainbow sr(trk_speed1, trk_speed2); if (trk.size()==1){ // draw 1pt tracks even in non-draw_dots mode g_trackpoint p1(trk[0]); cnv.bck(p1); p1-=origin; cr->set_color(0); cr->move_to(p1); cr->circle(p1, dot_w); } - for (int i=0; i<trk.size(); i++){ + for (size_t i=0; i<trk.size(); i++){ g_trackpoint p1,p2; p2 = trk[i]; if (i==0){ if (trk.type==trkType("closed")) p1=trk[trk.size()-1]; else continue; } else p1=trk[i-1]; if (p2.start) continue; double cc = cos((p1.y + p2.y)/2.0/180.0*M_PI); double dx = (p2.x - p1.x)*cc; double dy = (p2.y - p1.y); double d = sqrt(dx*dx + dy*dy) * 6380e3 * M_PI/180; cnv.bck(p1); p1-=origin; cnv.bck(p2); p2-=origin; double t = p2.t.value - p1.t.value; if (t>0 && t<3600*24) cr->set_color(sr.get(d/t * 3.6)); else cr->set_color(0); cr->move_to(p1); cr->line_to(p2); cr->stroke(); } } if (trk_draw_mode == "height"){ double trk_height1 = opt.get<double>("trk_draw_h1", -200); double trk_height2 = opt.get<double>("trk_draw_h2", 8000); cr->set_line_width(2*w); simple_rainbow sr(trk_height1, trk_height2); if (trk.size()==1){ // draw 1pt tracks even in non-draw_dots mode g_trackpoint p1(trk[0]); cnv.bck(p1); p1-=origin; cr->set_color(0); cr->move_to(p1); cr->circle(p1, dot_w); } - for (int i=0; i<trk.size(); i++){ + for (size_t i=0; i<trk.size(); i++){ g_trackpoint p1,p2; p2 = trk[i]; if (i==0){ if (trk.type==trkType("closed")) p1=trk[trk.size()-1]; else continue; } else p1=trk[i-1]; if (p2.start) continue; cnv.bck(p1); p1-=origin; cnv.bck(p2); p2-=origin; if (!p1.have_alt() || !p2.have_alt()){ cr->set_color(0); cr->move_to(p1); cr->line_to(p2); cr->stroke(); } else { int n = ceil(pdist(p2-p1)/2/w); dPoint dp = (p2-p1)/n; for(int j=0; j< n; j++){ cr->move_to(p1 + j*dp); cr->line_to(p1 + (j+1)*dp); cr->set_color(sr.get( p1.z + double(j*(p2.z - p1.z))/n )); cr->stroke(); } } } } } diff --git a/core/img_io/gobj_geo.h b/core/img_io/gobj_geo.h index e76b4c2..76edae8 100644 --- a/core/img_io/gobj_geo.h +++ b/core/img_io/gobj_geo.h @@ -1,39 +1,39 @@ #ifndef GOBJ_GEO_H #define GOBJ_GEO_H #include "gred/gobj.h" #include "geo/geo_convs.h" /// Abstract class for objects with geo-reference and options class GObjGeo : public GObj { public: Options opt; - convs::map2wgs cnv; g_map ref; + convs::map2wgs cnv; GObjGeo(): ref(get_myref()), cnv(convs::map2wgs(get_myref())) {} // get/set options void set_opt(const Options & o){ opt = o; } Options get_opt(void) const{ return opt; } /// Get some reasonable reference. virtual g_map get_myref() const{ g_map ret; ret.map_proj = Proj("lonlat"); ret.push_back(g_refpoint(0, 90, 0, 0)); ret.push_back(g_refpoint(180, 0, 180*3600,90*3600)); ret.push_back(g_refpoint(0, 0, 0, 90*3600)); return ret; } virtual void set_ref(const g_map & ref_){ ref=ref_; cnv=convs::map2wgs(ref); refresh(); } virtual const g_map* get_ref() const {return &ref;} virtual const convs::map2wgs * get_cnv() {return &cnv;} virtual void rescale(double k){set_ref(ref*k);} virtual void refresh() {} /// Refresh layer. }; #endif diff --git a/core/img_io/gobj_map.cpp b/core/img_io/gobj_map.cpp index e719159..d24cac1 100644 --- a/core/img_io/gobj_map.cpp +++ b/core/img_io/gobj_map.cpp @@ -1,323 +1,323 @@ #include "gobj_map.h" #include <sstream> #include <fstream> #include <cmath> #include "loaders/image_r.h" #include "utils/cairo_wrapper.h" #include "2d/line_utils.h" using namespace std; GObjMAP::GObjMAP(g_map_list *_data, const Options & opt) : data(_data), image_cache(4){ refresh(); status_set(SHOW_BRD, opt.exists("map_show_brd")); } g_map GObjMAP::get_myref() const { // return ref of first map, swapped if needed if (data->size() && (*data)[0].size()){ g_map ret=(*data)[0]; convs::map2wgs c(ret); if (!c.swapped()) return ret; double ym=ret[0].yr; - for (int i=1; i<ret.size(); i++){ if (ret[i].yr>ym) ym=ret[i].yr; } // find max yr - for (int i=0; i<ret.size(); i++){ ret[i].yr = ym-ret[i].yr; } //swap y + for (size_t i=1; i<ret.size(); i++){ if (ret[i].yr>ym) ym=ret[i].yr; } // find max yr + for (size_t i=0; i<ret.size(); i++){ ret[i].yr = ym-ret[i].yr; } //swap y return ret; } // else return some simple ref return GObjGeo::get_myref(); } -int +ssize_t GObjMAP::find_map(const iPoint & pt) const{ - for (int i=0; i< m2ms.size(); i++){ + for (size_t i=0; i< m2ms.size(); i++){ if (point_in_line(pt, borders[i])) return i; } return -1; } -int +ssize_t GObjMAP::find_map(const iRect & r) const{ - for (int i=0; i< m2ms.size(); i++){ + for (size_t i=0; i< m2ms.size(); i++){ if (rect_in_line(r, borders[i])) return i; } return -1; } void GObjMAP::status_set(int mask, bool val, const g_map * m){ if (!m){ map<const g_map*, int>::iterator i; for (i=status.begin(); i!=status.end(); i++){ if (val) i->second |= mask; else i->second &= ~mask; } } else{ if (!status.count(m)) return; if (val) status[m] |= mask; else status[m] &= ~mask; } } int GObjMAP::draw(iImage & image, const iPoint & origin){ iRect src_rect = image.range() + origin; dPoint dorigin(origin); #ifdef DEBUG_LAYER_GEOMAP cerr << "GObjMAP: draw " << src_rect << " my: " << myrange << endl; #endif if (rect_intersect(myrange, src_rect).empty()) return GObj::FILL_NONE; if ((data == NULL)||(data->size()==0)) return GObj::FILL_NONE; int maxscale=32; CairoWrapper cr(image); cr->set_line_width(1); - for (int i=0; i < data->size(); i++){ + for (size_t i=0; i < data->size(); i++){ if (!rect_in_line(src_rect, borders[i])) continue; const g_map * m = &(*data)[i]; int scale = int(scales[i]+0.05); if (scale <=0) scale = 1; // show map if needed if ((scale<=maxscale) && (status[m]&SHOW_MAP)){ // check image file struct stat st_buf; if (stat(m->file.c_str(), &st_buf) != 0){ std::cerr << "Layer_map: can't find image file: " << m->file << endl; continue; } if (S_ISDIR(st_buf.st_mode)){ // tiled map // find/create image cache for this map if (tmap_cache.count(m->file)==0) tmap_cache.insert(make_pair(m->file, Cache<iPoint, iImage>(100))); Cache<iPoint, iImage> & C = tmap_cache.find(m->file)->second; // clear cache if scale have changed if (iscales[i] != scale){ C.clear(); iscales[i] = scale; } iLineTester brd_tester(borders[i]); // look for download script bool download = stat((m->file+"/download").c_str(), &st_buf) == 0 && S_ISREG(st_buf.st_mode) && scale==1; // convert image points for (int y=0; y<image.h; y++){ std::vector<int> cr = brd_tester.get_cr(y+origin.y); for (int x=0; x<image.w; x++){ if (!brd_tester.test_cr(cr, x+origin.x)) continue; dPoint p(x,y); p+=origin; m2ms[i]->bck(p); iPoint tile = iPoint(p)/m->tsize; dPoint p1 = (p - dPoint(tile)*(m->tsize) )/scale; iPoint pt(int(p1.x), int(p1.y)); if (m->tswap) pt.y=m->tsize/scale-pt.y-1; if (!C.contains(tile)){ char fn[PATH_MAX]; snprintf(fn, sizeof(fn), m->tfmt.c_str(), tile.x, tile.y); string tfile = m->file+'/'+fn; iImage img = image_r::load(tfile.c_str(), scale); if (img.empty() && download){ // try to download file ostringstream ss; ss << "./download " << tile.x << " " << tile.y; char cwd[PATH_MAX]; if (getcwd(cwd, PATH_MAX) && chdir(m->file.c_str())==0){ if (system(ss.str().c_str())==0) img = image_r::load(fn, scale); if (chdir(cwd)!=0) cerr << "Layer_map: can't do chdir!\n"; } } C.add(tile, img); } image.set_a(x,y,C.get(tile).safe_get(pt)); } } } else { // normal map m2ms[i]->image_frw( image_cache.get(m->file, scale, m->border), image, origin, 1.0/scale); } } //draw border if ((status[m]&SHOW_BRD) || (scale > maxscale)){ for (iLine::const_iterator p=borders[i].begin(); p!=borders[i].end(); p++){ if (p==borders[i].begin()) cr->move_to((*p)-origin); else cr->line_to((*p)-origin); } cr->close_path(); if (scale > maxscale){ // fill map area cr->set_color_a(0x80000080); cr->fill_preserve(); } cr->set_line_width(3); cr->set_color(0x0000FF); cr->stroke(); } // draw refpoints double dr=10, dg=5; if (status[m]&SHOW_REF){ for (g_map::const_iterator p=(*data)[i].begin(); p!=(*data)[i].end(); p++){ dPoint pr(p->xr, p->yr); // raster coords m2ms[i]->frw(pr); pr-=dorigin; cr->move_to(pr + dPoint(-1,0)*dr); cr->line_to(pr + dPoint(1,0)*dr); cr->move_to(pr + dPoint(0,-1)*dr); cr->line_to(pr + dPoint(0,1)*dr); cr->set_line_width(3); cr->set_color(0xFF0000); cr->stroke(); dPoint pg(p->x, p->y); // geo coords cnv.bck(pg); pg-=dorigin; cr->move_to(pg + dPoint(-1,-1)*dg); cr->line_to(pg + dPoint(1,1)*dg); cr->move_to(pg + dPoint(1,-1)*dg); cr->line_to(pg + dPoint(-1,1)*dg); cr->set_line_width(3); cr->set_color(0x00FF00); cr->stroke(); } } } return GObj::FILL_PART; } double GObjMAP::scale(const dPoint & p, const int m){ return pdist(m2ms[m]->units_frw(p))/sqrt(2.0); } double GObjMAP::scale(const dPoint & p){ int m = find_map(p); if (m<0) return -1; return pdist(m2ms[m]->units_frw(p))/sqrt(2.0); } void GObjMAP::dump_maps(const char *file){ ofstream f(file); f<< "#FIG 3.2\n" << "Portrait\n" << "Center\n" << "Metric\n" << "A4\n" << "100.0\n" << "Single\n" << "-2\n" << "1200 2\n"; - for (int i=0;i<m2ms.size();i++){ + for (size_t i=0;i<m2ms.size();i++){ int bs = borders[i].size(); f << "2 3 0 1 4 29 8 -1 20 0.000 0 0 -1 0 0 " << bs << "\n\t"; double minx=1e99, maxx=-1e99; for (int j=0; j<bs; j++){ double x=borders[i][j].x; double y=borders[i][j].y; if (x<minx) minx=x; if (x>maxx) maxx=x; f << " " << int(x) << " " << int(y); } f << "\n"; if (bs==0) continue; double lettw=190; double letth=400; string s1; - int n=0, l=0; - while (n<(*data)[i].comm.size()>0){ + size_t n=0, l=0; + while (n<(*data)[i].comm.size()){ s1+=(*data)[i].comm[n]; n++; if ((n==(*data)[i].comm.size()) || (s1.size()*lettw > maxx-minx)){ f << "4 0 4 6 -1 18 20 0.0000 4 225 630 " << int(borders[i][0].x+100) << " " << int(borders[i][0].y+500 + l*letth) << " " << s1 << "\\001\n"; s1=""; l++; } } } f.close(); } void GObjMAP::refresh(){ if (!data || !data->size()) return; m2ms.clear(); scales.clear(); borders.clear(); map<const g_map *, int> nstatus; - for (int i=0; i< data->size(); i++){ + for (size_t i=0; i< data->size(); i++){ // map -> layer conversion g_map * m = &(*data)[i]; boost::shared_ptr<Conv> c(new convs::map2map(*m, ref)); if (ref.map_proj == m->map_proj){ // the same proj! map<dPoint,dPoint> points; for (g_map::const_iterator i=m->begin(); i!=m->end(); i++){ dPoint p1(i->xr, i->yr), p2(p1); c->frw(p2); points[p1] = p2; // map->scr } c.reset(new ConvAff(points)); } m2ms.push_back(c); // map scaling factor dPoint p1(0,0), p2(1000,0), p3(0,1000); // on scr c->bck(p1); c->bck(p2); c->bck(p3); double sc = min(pdist(p1,p2)/1000, pdist(p1,p3)/1000); scales.push_back(sc); // border and range if (m->border.size()){ dLine brd = c->line_frw(m->border); if ( i == 0 ) myrange = brd.range(); else myrange = rect_bounding_box(myrange, iRect(brd.range())); borders.push_back(brd); } else{ myrange=GObj::MAX_RANGE; borders.push_back(rect2line(myrange)); } // pump range to include all ref points with some radius const iPoint rr(10,10); - for (int j=0; j<m->size(); j++){ + for (size_t j=0; j<m->size(); j++){ dPoint pr((*m)[j].xr, (*m)[j].yr); c->frw(pr); myrange = rect_bounding_box(myrange, iRect(iPoint(pr)-rr, iPoint(pr)+rr)); } // check old status for this map if (status.count(m)) nstatus[m] = status[m]; else nstatus[m] = SHOW_MAP; } status=nstatus; // старые данные нам тоже интересны (мы можем использовать уже загруженные картинки) if (iscales.size() != data->size()) iscales.resize(data->size(),1); #ifdef DEBUG_LAYER_GEOMAP cerr << "GObjMAP: Setting map conversions. Range: " << myrange << "\n"; #endif } diff --git a/core/img_io/gobj_map.h b/core/img_io/gobj_map.h index ddcd899..a1c602a 100644 --- a/core/img_io/gobj_map.h +++ b/core/img_io/gobj_map.h @@ -1,82 +1,82 @@ #ifndef GOBJ_MAP_H #define GOBJ_MAP_H #include <vector> #include <map> #include "gobj_geo.h" #include "cache/cache.h" #include "2d/point.h" #include "2d/rect.h" #include "2d/image.h" #include "loaders/image_cache.h" #include <boost/shared_ptr.hpp> /// Растровый слой для показа привязанных карт. #define SHOW_MAP 1 #define SHOW_BRD 2 #define SHOW_REF 4 class GObjMAP #ifndef SWIG : public GObjGeo #endif // SWIG { private: g_map_list *data; // привязки карт std::vector< boost::shared_ptr<Conv> > m2ms; // преобразования из каждой карты std::vector<double> scales; // во сколько раз мы сжимаем карты при загрузке std::vector<int> iscales; // во сколько раз мы сжимаем карты при загрузке std::vector<iLine> borders; // границы (в координатах слоя) iRect myrange; // габариты карты std::map<const g_map*, int> status; // visibility of refpoints, border, map image std::map<std::string, Cache<iPoint, iImage> > tmap_cache; ImageCache image_cache; public: GObjMAP (g_map_list *_data, const Options & opt = Options()); g_map get_myref() const; void refresh(); /// Refresh layer. /// Get pointer to the data. g_map_list * get_data() const {return data;} /// Get pointer to the n-th map. g_map * get_map(const int n) const {return &(*data)[n];} /// Find map - int find_map(const iPoint & pt) const; - int find_map(const iRect & r) const; + ssize_t find_map(const iPoint & pt) const; + ssize_t find_map(const iRect & r) const; /// Show/hide reference points and border for a n-th map /// (n=-1 for all maps) void status_set(int mask, bool val=true, const g_map * m = NULL); void show_ref(const g_map * m = NULL) {status_set(SHOW_REF, true, m);} void hide_ref(const g_map * m = NULL) {status_set(SHOW_REF, false, m);} void show_brd(const g_map * m = NULL) {status_set(SHOW_BRD, true, m);} void hide_brd(const g_map * m = NULL) {status_set(SHOW_BRD, false, m);} void show_map(const g_map * m = NULL) {status_set(SHOW_MAP, true, m);} void hide_map(const g_map * m = NULL) {status_set(SHOW_MAP, false, m);} /// Draw on image. int draw(iImage & image, const iPoint & origin); /// Get layer range. iRect range() const {return myrange;} /// Write to a file picture with map borders in fig format. void dump_maps(const char *file); /// Scale of map at a given point (first map or map m). /// > 1 if map pixel is smaller than layer one; /// < 0 if no maps at this point. double scale(const dPoint & p); double scale(const dPoint & p, const int m); }; #endif diff --git a/core/img_io/gobj_pano.cpp b/core/img_io/gobj_pano.cpp index 08eea62..d9daf1e 100644 --- a/core/img_io/gobj_pano.cpp +++ b/core/img_io/gobj_pano.cpp @@ -1,251 +1,251 @@ #include "gobj_pano.h" #include "2d/rainbow.h" using namespace std; -GObjPano::GObjPano(SRTM3 * s): srtm(s), ray_cache(512), rb(0,0){ +GObjPano::GObjPano(SRTM3 * s): srtm(s), rb(0,0), ray_cache(512){ set_opt(Options());} /***********************************************************/ void GObjPano::set_opt(const Options & o){ p0 = o.get<dPoint>("pano_pt"); dh = o.get<double>("pano_alt", 20.0); rb.set_range( o.get<double>("pano_minh", 0), o.get<double>("pano_maxh", 5000)); max_r = o.get<double>("pano_maxr", 60000); width0 = o.get<int>("pano_width", 3600); ray_cache.clear(); } Options GObjPano::get_opt(void) const{ Options o; o.put<dPoint>("pano_pt", p0); o.put<double>("pano_alt", dh); o.put<double>("pano_minh", rb.get_min()); o.put<double>("pano_maxh", rb.get_max()); o.put<double>("pano_maxr", max_r); o.put<int>("pano_width", width0); return o; } /***********************************************************/ // find segments of the ray brocken by srtm grid // these segments must have linear height and slope dependence vector<GObjPano::ray_data> GObjPano::get_ray(int x){ double width=get_width(); while (x<0) x+=width; while (x>=width) x-=width; double a = 2.0*M_PI*x/width; int key=round(a*1000000); if (ray_cache.contains(key)) return ray_cache.get(key); size_t srtmw = srtm->get_width()-1; double sa=sin(a), ca=cos(a), cx=cos(p0.y * M_PI/180.0); dPoint pt= p0*srtmw; // srtm units double m2srtm=srtmw * 180/M_PI/ 6380000; double rM=max_r*m2srtm; // Intersections or ray with x and y lines of srtm grid goes // with constant steps. But we need to sort them by r. double rx,drx,ry,dry; // Initial values and steps if (sa>1/rM) { drx=cx/sa; rx=(ceil(pt.x)-pt.x)*cx/sa; } else if (sa<-1/rM){ drx=-cx/sa; rx=(floor(pt.x)-pt.x)*cx/sa; } else { drx=rx=rM; } if (ca>1/rM) { dry=1/ca; ry=(ceil(pt.y)-pt.y)/ca; } else if (ca<-1/rM){ dry=-1/ca; ry=(floor(pt.y)-pt.y)/ca; } else { dry=ry=rM; } vector<GObjPano::ray_data> ret; while (rx<rM || ry<rM){ // Go from zero to rM while (rx <= ry && rx<rM){ // step in x int x = round(pt.x+rx*sa/cx); // x is a round number double y = pt.y+rx*ca; // y is between two grid points. // assert(abs(pt.x+rx*sa/cx - x) < 1e-9); // check this // Interpolate altitude and slope between two points: int y1 = floor(y); int y2 = ceil(y); double h=srtm_undef,s; if (y1!=y2){ int h1 = srtm->geth(x,y1, false); int h2 = srtm->geth(x,y2, false); double s1 = srtm->slope(x,y1, false); double s2 = srtm->slope(x,y2, false); if ((h1>srtm_min) && (h2>srtm_min)) h = h1 + (h2-h1)*(y-y1)/(y2-y1); s = s1 + (s2-s1)*(y-y1)/(y2-y1); } else { h = srtm->geth(x,y1, false); s = srtm->slope(x,y1, false); } // Save data and do step: if (h>srtm_min) ret.push_back(ray_data(rx/m2srtm, h, s)); rx+=drx; } while (ry <= rx && ry<rM){ // step in y; the same but rx->ry, y is on the grid double x = pt.x+ry*sa/cx; int y = round(pt.y+ry*ca); // assert(abs(pt.y+ry*ca - y) < 1e-9); int x1 = floor(x); int x2 = ceil(x); double h=srtm_undef,s; if (x1!=x2){ int h1 = srtm->geth(x1,y, false); int h2 = srtm->geth(x2,y, false); double s1 = srtm->slope(x1,y, false); double s2 = srtm->slope(x2,y, false); if ((h1>srtm_min) && (h2>srtm_min)) h = h1 + (h2-h1)*(x-x1)/(x2-x1); s = s1 + (s2-s1)*(x-x1)/(x2-x1); } else { h = srtm->geth(x1,y, false); s = srtm->slope(x1,y, false); } if (h>srtm_min) ret.push_back(ray_data(ry/m2srtm, h, s)); ry+=dry; } } ray_cache.add(key,ret); return ret; } /***********************************************************/ iPoint GObjPano::geo2xy(const dPoint & pt){ double width=get_width(); iPoint ret; double cx=cos(p0.y*M_PI/180); ret.x = width * atan2((pt.x-p0.x)*cx, pt.y-p0.y)/2.0/M_PI; double r0 = hypot((pt.x-p0.x)*cx, pt.y-p0.y)*6380000/180.0*M_PI; vector<ray_data> ray = get_ray(ret.x); if (!ray.size()) return iPoint(); int yp, yo; yo=yp=width/2.0; double h0 = ray[0].h+dh; double rp = 0; - for (int i=0; i<ray.size(); i++){ + for (size_t i=0; i<ray.size(); i++){ double hn=ray[i].h; double rn=ray[i].r; double b = atan2(hn-h0, rn); // vertical angle int yn = (1 - 2*b/M_PI) * width/4.0; // y-coord if (rn>r0){ ret.y = yp + (yn-yp)*(rn-r0)/(rn-rp); if (ret.y > yo) ret.y = -ret.y; //invisible return ret; } if (yn<yo) yo=yn; yp=yn; rp=rn; } ret.y = 0; return ret; } dPoint GObjPano::xy2geo(const iPoint & pt){ double width=get_width(); vector<ray_data> ray = get_ray(pt.x); if (!ray.size()) return iPoint(0,180); double h0 = ray[0].h+dh; int yp, yo; yo=yp=width/2.0; double rp = 0; - for (int i=0; i<ray.size(); i++){ + for (size_t i=0; i<ray.size(); i++){ double hn=ray[i].h; double rn=ray[i].r; double b = atan2(hn-h0,rn); // vertical angle int yn = (1 - 2*b/M_PI) * width/4.0; // y-coord if (yn<pt.y){ double r = rp + (rn-rp)*(pt.y-yn)/double(yp-yn); double a = pt.x/double(width)*2*M_PI; double cx=cos(p0.y*M_PI/180.0); return p0 + dPoint(sin(a)/cx, cos(a))*r / 6380000.0 / M_PI * 180.0; } if (yn<yo) yo=yn; yp=yn; rp=rn; } return dPoint(0,180); } /***********************************************************/ int GObjPano::draw(iImage & image, const iPoint & origin){ if (!srtm) return GObj::FILL_NONE; double width=get_width(); double h0 = (double)srtm->geth4(p0) + dh; // altitude of observation point for (int x=0; x < image.w; x++){ // get ray data -- r,h,s values for a giver x-coord vector<ray_data> ray = get_ray(x+origin.x); if (!ray.size()) continue; int yo = image.h; // Old y-coord, previously painted point. // It is used to skip hidden parts. int yp = width/2.0-origin.y; // Previous value, differs from yo on hidden // and partially hydden segments. // It is used to interpolate height and slope. // Y axis goes from top to buttom! - for (int i=1; i<ray.size(); i++){ + for (size_t i=1; i<ray.size(); i++){ double hp=ray[i-1].h; // altitudes and slopes at the end of segment double sp=ray[i-1].s; double hn=ray[i].h; double sn=ray[i].s; double r=ray[i].r; if (r>max_r) break; double b = atan2(hn-h0, r); // vertical angle int yn = (1 - 2*b/M_PI) * width/4.0 - origin.y; // y-coord if (yn<0) {i=ray.size();} // above image -- draw the rest of segment and exit if (yn>=yo) {yp=yn; continue;} // point below image -- skip segment for (int y = yn; y < yp; y++){ if (y<0 || y>=yo) continue; // select visible points double s = sp + (sn-sp)*(y-yp)/double(yn-yp); // Interpolate slope and altitude double h = hp + (hn-hp)*(y-yp)/double(yn-yp); // and calculate point color. int color = color_shade(rb.get(h), (1-r/max_r)*(1-s/90)); image.set_na(x,y, color); } if (yn<yo) yo=yn; yp=yn; } for (int y = 0; y < yo; y++) // dray sky points image.set_na(x,y,0xFFBBBB); } return GObj::FILL_ALL; } diff --git a/core/img_io/gobj_srtm.cpp b/core/img_io/gobj_srtm.cpp index 05d1b46..7fbee66 100644 --- a/core/img_io/gobj_srtm.cpp +++ b/core/img_io/gobj_srtm.cpp @@ -1,99 +1,98 @@ #include "gobj_srtm.h" #include <sstream> #include <fstream> #include "2d/rainbow.h" using namespace std; GObjSRTM::GObjSRTM(SRTM3 *srtm):S(srtm){ opt.put<string>("srtm_mode", "normal"); opt.put<double>("srtm_cnt_step", 50); opt.put<double>("srtm_hmin", 0.0); opt.put<double>("srtm_hmax", 5000.0); opt.put<double>("srtm_smin", 30.0); opt.put<double>("srtm_smax", 55.0); opt.put<string>("srtm_dir", ""); } int GObjSRTM::draw(iImage & image, const iPoint & origin){ if (S==NULL) return GObj::FILL_NONE; - iRect src_rect = image.range() + origin; S->set_dir(opt.get<string>("srtm_dir", "")); string mode = opt.get<string>("srtm_mode", "normal"); int cnt_step = opt.get<int>("srtm_cnt_step", 50); // avoid string comparing strings inside the loop: int m=0; if (mode == "none") m=0; if (mode == "normal") m=1; else if (mode == "slopes") m=2; double min=0, max=0; rainbow_type type = RAINBOW_NORMAL; if (mode == "normal"){ min = opt.get<double>("srtm_hmin", 0.0); max = opt.get<double>("srtm_hmax", 5000.0); } else if (mode == "slopes"){ type=RAINBOW_BURNING; min = opt.get<double>("srtm_smin", 30.0); max = opt.get<double>("srtm_smax", 55.0); } simple_rainbow R(min,max,type), RG(0,90,0xffffff,0x00000); for (int j=0; j<image.h; j++){ for (int i=0; i<image.w; i++){ int c=0xffffff; dPoint p0,px,py; int h0,hx,hy; p0 = origin + iPoint(i,j); cnv.frw(p0); h0 = S->geth4(p0, false); if (h0 < srtm_min){ continue; } if (cnt_step>0){ // contours px = origin + iPoint(i+1,j); py = origin + iPoint(i,j+1); cnv.frw(px); cnv.frw(py); hx = S->geth4(px, false); hy = S->geth4(py, false); // holes if (hx < srtm_min || hy < srtm_min){ continue; } if ((hx/cnt_step - h0/cnt_step) ||(hy/cnt_step - h0/cnt_step)){ c=0; goto print_colors; } } if (m == 1){ double a = S->slope4(p0, false); if (a>90.0) a=90.0; c = R.get(h0); c = color_shade(c, 1-a/90.0); goto print_colors; } if (m == 2){ // slopes c=R.get(S->slope4(p0, false)); goto print_colors; } print_colors: image.set_na(i,j, c); } } return GObj::FILL_ALL; } diff --git a/core/img_io/gobj_trk.cpp b/core/img_io/gobj_trk.cpp index 6c30c00..714c08d 100644 --- a/core/img_io/gobj_trk.cpp +++ b/core/img_io/gobj_trk.cpp @@ -1,69 +1,69 @@ #include <vector> #include <cmath> #include "gobj_trk.h" #include "draw_trk.h" using namespace std; int GObjTRK::draw(iImage & image, const iPoint & origin){ iRect src_rect = image.range() + origin; #ifdef DEBUG_LAYER_TRK cerr << "GObjTRK: draw " << src_rect << " my: " << myrange << "\n"; #endif // FIXME - use correct range instead of +110 if (rect_intersect(myrange, rect_pump(src_rect,110)).empty()) return GObj::FILL_NONE; draw_trk(image, origin, cnv, *data, opt); return GObj::FILL_PART; } int GObjTRK::find_trackpoint (dPoint pt, double radius){ - for (int n = 0; n < data->size(); ++n) { + for (size_t n = 0; n < data->size(); ++n) { dPoint p((*data)[n]); cnv.bck(p); if (pdist(p,pt)<radius) return n; } return -1; } vector<int> GObjTRK::find_trackpoints (const dRect & r){ vector<int> ret; - for (int n = 0; n < data->size(); ++n) { + for (size_t n = 0; n < data->size(); ++n) { dPoint p((*data)[n]); cnv.bck(p); if (point_in_rect(p, r)) ret.push_back(n); } return ret; } int GObjTRK::find_track (dPoint pt, double radius){ int ts=data->size(); if (ts<1) return -1; if (ts<2){ dPoint p((*data)[0]); cnv.bck(p); if (pdist(p,pt)<radius) return 0; else return -1; } for (int n = 0; n < ts-1; ++n) { dPoint p1((*data)[n]), p2((*data)[n+1]); cnv.bck(p1); cnv.bck(p2); double vn = pscal(pt-p1, p2-p1)/pdist(p2-p1); dPoint v1 = pnorm(p2-p1) * vn; if (vn < -radius || vn > pdist(p2-p1) + radius) continue; if (pdist(pt-p1, v1) < radius) return n; } return -1; } diff --git a/core/img_io/o_img.cpp b/core/img_io/o_img.cpp index 98d44a6..729baf0 100644 --- a/core/img_io/o_img.cpp +++ b/core/img_io/o_img.cpp @@ -1,284 +1,284 @@ #include <fstream> #include <string> #include "img_io/gobj_map.h" #include "img_io/gobj_trk.h" #include "img_io/gobj_wpt.h" #include "img_io/gobj_srtm.h" #include "img_io/gobj_vmap.h" #include "loaders/image_r.h" #include "geo/geo_convs.h" #include "geo_io/geo_refs.h" #include "2d/line_utils.h" #include "utils/cairo_wrapper.h" #include "geo_io/geofig.h" #include "geo_io/io_oe.h" #include "err/err.h" #include "gobj_comp.h" using namespace std; namespace img{ void write_file (const char* filename, geo_data & world, vmap::world & vm, Options opt){ // Default scale from vmap or 1:100000. if (!opt.exists("rscale")){ if (!vm.empty()) opt.put("rscale", vm.rscale); else opt.put("rscale", 100000.0); } double rscale=opt.get("rscale", 100000.0); // We want to use source map scale if there is no dpi option bool do_rescale = false; if (!opt.exists("dpi") && !opt.exists("google")){ opt.put("dpi", 100.0); do_rescale = true; } double dpi=opt.get("dpi", 100.0); // set geometry if no --wgs_geom, --wgs_brd, --geom, --nom, --google options bool need_marg=false; if (!opt.exists("geom") && !opt.exists("wgs_geom") && !opt.exists("nom") && !opt.exists("google") && !opt.exists("wgs_brd") && !opt.exists("trk_brd")){ dRect wgs_geom = world.range_geodata(); if (!wgs_geom.empty() && opt.exists("data_marg")) need_marg=true; // fallback: vmap range if (wgs_geom.empty()) wgs_geom=vm.range(); // fallback: map range if (wgs_geom.empty()) wgs_geom=world.range_map(); if (wgs_geom.empty()) throw Err() << "Can't get map geometry."; opt.put("wgs_geom", wgs_geom); } // create g_map g_map ref = mk_ref(opt); ref.file=filename; // set map scale from source maps if needed if (do_rescale){ if (world.maps.size()>0){ double maxscale=-1; dRect box = ref.range(); vector<g_map_list>::const_iterator i; vector<g_map>::const_iterator j; for (i = world.maps.begin(); i!=world.maps.end(); i++){ for (j = i->begin(); j!=i->end(); j++){ if (j->size()<1) continue; convs::map2map cnv(*j, ref); dRect sbox = cnv.bb_bck(box); double sx = sbox.w/box.w; double sy = sbox.h/box.h; if (maxscale<sx) maxscale = sx; if (maxscale<sy) maxscale = sy; } } ref*=maxscale * opt.get("mag", 1.0); } else if (opt.exists("srtm_mode")){ double mpp = 6380000.0 * M_PI /180/1200; double dpi = rscale/mpp / 100.0 * 2.54; double sc=dpi/opt.get("dpi", 100.0) * opt.get("mag", 1.0); ref*=sc; } } // data margin -- only if the range was set from the data bbox if (need_marg){ dRect geom = rect_pump(ref.border.range(), opt.get("data_marg", 0.0)); ref.border=rect2line(geom); } // set margins for text int tm=0, bm=0, lm=0, rm=0; if (opt.get<int>("draw_name", 0) || opt.get<int>("draw_date", 0) || (opt.get<string>("draw_text") != "")) { tm=dpi/3; bm=lm=rm=dpi/6; } int grid_labels = opt.get<int>("grid_labels", 0); if (grid_labels){ bm+=dpi/6; tm+=dpi/6; rm+=dpi/6; lm+=dpi/6; } // image size dRect geom = ref.border.range(); geom.x = geom.y = 0; geom.w+=lm+rm; if (geom.w<0) geom.w=0; geom.h+=tm+bm; if (geom.h<0) geom.h=0; ref+=dPoint(lm,tm); // is output image not too large iPoint max_image = opt.get("max_image", Point<int>(10000,10000)); cerr << "Image size: " << geom.w << "x" << geom.h << "\n"; if ((geom.w>max_image.x) || (geom.h>max_image.y)) throw Err() << "Error: image is too large (" << geom.w << "x" << geom.h << ") pixels. " << "You may change max_image option to pass this test.\n"; // create gobj GObjComp gobj; SRTM3 s(opt.get<string>("srtm_dir")); if (opt.exists("srtm_mode")) gobj.push_back(new GObjSRTM(&s)); - for (int i=0; i<world.maps.size(); i++) + for (size_t i=0; i<world.maps.size(); i++) gobj.push_back(new GObjMAP(&(world.maps[i]), opt)); if (!vm.empty()) gobj.push_back(new GObjVMAP(&vm, opt)); - for (int i=0; i<world.trks.size(); i++) + for (size_t i=0; i<world.trks.size(); i++) gobj.push_back(new GObjTRK(&(world.trks[i]), opt)); - for (int i=0; i<world.wpts.size(); i++) + for (size_t i=0; i<world.wpts.size(); i++) gobj.push_back(new GObjWPT(&(world.wpts[i]), opt)); gobj.set_ref(ref); gobj.set_opt(opt); // draw int bgcolor = opt.get("bgcolor", 0xFFFFFFFF); int tmap = opt.exists("tiles"); int skipempty = opt.exists("tiles_skipempty"); int tsize = 256; if (!tmap){ iImage im(geom.w,geom.h, bgcolor); gobj.draw(im, iPoint(0,0)); // if (ref.border.size()>2){ // clear image outside border // CairoWrapper cr(im); // cr->render_border(geom, ref.border, bgcolor); // } image_r::save(im, filename, opt); } else{ // tiles string fname(filename); string dir = fname; string ext = ".jpg"; - int pos = fname.rfind('.'); + ssize_t pos = fname.rfind('.'); if ((pos>0) && (pos < fname.length()-1)){ ext = fname.substr(pos); dir = fname.substr(0, pos); } int res = mkdir(dir.c_str(), 0755); iRect trect = tiles_on_rect(geom,tsize); iPoint p0(0,0); if (opt.get<string>("tiles_origin", "image") == string("proj")){ dPoint dp0(opt.get("lon0", 0), 0); gobj.cnv.bck(dp0); p0 = iPoint(dp0); trect = tiles_on_rect(geom-p0,tsize); } for (int y=trect.TLC().y; y<=trect.BRC().y; y++){ for (int x=trect.TLC().x; x<=trect.BRC().x; x++){ iImage im(tsize, tsize, bgcolor); iPoint org = iPoint(x,y)*tsize + p0; int res = gobj.draw(im, org); if (res == GObj::FILL_NONE && skipempty) continue; //if (ref.border.size()>2){ // // clear image outside border // CairoWrapper cr(im); // cr->render_border(geom, ref.border-org, bgcolor); //} int wx=0,wy=0; //if (mx > 1) wx = (int) floor (log (1.0 * mx) / log (10.0)) + 1; //if (my > 1) wy = (int) floor (log (1.0 * my) / log (10.0)) + 1; ostringstream fn; fn << dir << "/" << setw(wx) << setfill('0') << x << "_" << setw(wy) << setfill('0') << y << ext; cout << "Writing " << fn.str() << "\n"; image_r::save(im, fn.str().c_str(), opt); } } } // clear gobj for (GObjComp::iterator i = gobj.begin(); i!=gobj.end(); i++) free(*i); // writing html map if needed string htmfile = opt.get<string>("htm"); if (!tmap && htmfile != ""){ ofstream f(htmfile.c_str()); f << "<html><body>\n" << "<img border=\"0\" " << "src=\"" << filename << "\" " << "width=\"" << geom.w << "\" " << "height=\"" << geom.h << "\" " << "usemap=\"#m\">\n" << "<map name=\"m\">\n"; for (vector<g_map_list>::const_iterator li=world.maps.begin(); li!=world.maps.end(); li++){ for (g_map_list::const_iterator i=li->begin(); i!=li->end(); i++){ convs::map2map cnv(*i, ref); dLine brd=cnv.line_frw(i->border); f << "<area shape=\"poly\" " << "href=\"" << i->file << "\" " << "alt=\"" << i->comm << "\" " << "title=\"" << i->comm << "\" " << "coords=\"" << iLine(brd) << "\">\n"; } } f << "</map>\n" << "</body></html>"; f.close(); } // writing fig if needed string figfile = opt.get<string>("fig"); if (!tmap && figfile != ""){ fig::fig_world W; double dpi=opt.get<double>("dpi"); g_map fig_ref= ref * 2.54 / dpi * fig::cm2fig; fig::set_ref(W, fig_ref, Options()); fig::fig_object o = fig::make_object("2 5 0 1 0 -1 500 -1 -1 0.000 0 0 -1 0 0 *"); for (g_map::iterator i=fig_ref.begin(); i!=fig_ref.end(); i++){ o.push_back(iPoint(int(i->xr), int(i->yr))); } o.push_back(iPoint(int(fig_ref[0].xr), int(fig_ref[0].yr))); o.image_file = filename; o.comment.push_back(string("MAP ") + filename); W.push_back(o); fig::write(figfile, W); } // writing map if needed string mapfile = opt.get<string>("map"); if (!tmap && mapfile != ""){ /* simplify border */ ref.border.push_back(*ref.border.begin()); ref.border=generalize(ref.border,1,-1); // 1pt accuracy ref.border.resize(ref.border.size()-1); try {oe::write_map_file(mapfile.c_str(), ref);} catch (Err e) {cerr << e.get_error() << endl;} } } } //namespace
ushakov/mapsoft
5af22d68336f930da27bce30e536a38078fc90be
2d: fix more -Wsign-compare warnings
diff --git a/core/2d/image.h b/core/2d/image.h index c3ec1df..c88a4f6 100644 --- a/core/2d/image.h +++ b/core/2d/image.h @@ -1,308 +1,308 @@ #ifndef IMAGE_H #define IMAGE_H #include "point.h" #include "line_tests.h" #include "rect.h" #include <cassert> #ifdef DEBUG_IMAGE #include <iostream> #endif ///\addtogroup lib2d ///@{ ///\defgroup image ///@{ /// 2-d array of T elements. /// - Image data is not duplicated at copying. /// - Compile with -O1 option to increase speed template <typename T> struct Image{ public: int w,h; T *data; private: int *refcounter; /// create image void create(int _w, int _h){ w=_w; h=_h; assert(w>=0); assert(h>=0); data = new T[w*h]; assert(data); refcounter = new int; *refcounter = 1; #ifdef DEBUG_IMAGE std::cerr << "[create data array]\n"; std::cerr << "Image create:" << " (" << w << "x" << h << ", " << data << " - " << *refcounter << ")\n"; #endif } /// copy image void copy(const Image & other){ w=other.w; h=other.h; data = other.data; refcounter = other.refcounter; (*refcounter)++; assert(*refcounter>0); #ifdef DEBUG_IMAGE std::cerr << "Copy image:" << " (" << w << "x" << h << ", " << data << " - " << *refcounter << ")\n"; #endif } /// destroy image void destroy(void){ #ifdef DEBUG_IMAGE std::cerr << "Image destructor:" << " (" << w << "x" << h << ", " << data << " - " << *refcounter << ")\n"; #endif (*refcounter)--; if (*refcounter<=0){ delete[] data; delete refcounter; #ifdef DEBUG_IMAGE std::cerr << "[delete data array]\n"; #endif } } public: /// Create empty image Image(){ create(0,0); } /// Create image with uninitialized data Image(int _w, int _h){ create(_w, _h); } /// Create image with data set to value Image(int _w, int _h, const T & value){ create(_w, _h); fill(value); } /// Copy constructor Image(const Image & other){ copy(other); } /// Destuctor ~Image(){ destroy(); } /// Assign Image & operator= (const Image & other){ if (&other == this) return *this; destroy(); copy(other); return *this; } /// Create copy of image data Image dup() const{ Image ret(w,h); for (int i=0;i<w*h;i++) ret.data[i]=data[i]; #ifdef DEBUG_IMAGE std::cerr << "Image copy:" << " (" << w << "x" << h << ", " << ret.data << " - " << *ret.refcounter << ")\n"; #endif return ret; } /// Fill image with some value void fill(const T value){ for (int i = 0; i<w*h;i++) data[i]=value; } /// with transparency void fill_a(const T value){ for (int j=0; j<h; j++) for (int i=0; i<w; i++) set_a(i,j,value); } /// Is image empty bool empty() const{ return (w<=0)||(h<=0); } /// Image range iRect range() const{ return iRect(0,0,w,h); } /// get and set functions inline T get(int x, int y) const { return data[y*w+x]; } inline void set(int x, int y, T c){ data[y*w+x]=c; } inline T get(const iPoint & p) const { return data[p.y*w+p.x]; } inline void set(const iPoint & p, T c){ data[p.y*w+p.x]=c; } inline T safe_get(int x, int y, T def = 0) const{ if ((x<0)||(y<0)||(x>=w)||(y>=h)) return def; return get(x,y); } inline void safe_set(int x, int y, T c){ if ((x<0)||(y<0)||(x>=w)||(y>=h)) return; set(x,y,c); } inline T safe_get(const iPoint & p, T def = 0) const{ return safe_get(p.x, p.y, def); } inline void safe_set(const iPoint & p, T c){ safe_set(p.x, p.y, c); } // (Only useful for iImage) inline T get_na(int x, int y, T c) const { return data[y*w+x] | 0xFF000000; } inline void set_na(int x, int y, T c) { data[y*w+x] = (c | 0xff000000); } inline T get_na(const iPoint & p, T c) const { return data[p.y*w+p.x] | 0xFF000000; } inline void set_na(const iPoint & p, T c){ set_na(p.x, p.y, c); } inline T safe_get_na(int x, int y, T def = 0) const{ if ((x<0)||(y<0)||(x>=w)||(y>=h)) return def; return get_na(x,y); } inline void safe_set_na(int x, int y, T c){ if ((x<0)||(y<0)||(x>=w)||(y>=h)) return; set_na(x,y,c); } inline T safe_get_na(const iPoint & p, T def = 0) const{ return safe_get_na(p.x, p.y, def); } inline void safe_set_na(const iPoint & p, T c){ safe_set_na(p.x, p.y, c); } inline void set_a(int x, int y, T c){ unsigned int color = c; int a = color >> 24; if (a == 0xff) { data[y*w+x] = color; } else if (a == 0) { // do nothing } else { int ao = data[y*w+x] >> 24; int an = ao + (255-ao) * a / 255; int r = (((color >> 16) & 0xff) * a + ((data[y*w+x] >> 16) & 0xff) * (255-a)) / 255; int g = (((color >> 8) & 0xff) * a + ((data[y*w+x] >> 8) & 0xff) * (255-a)) / 255; int b = ((color & 0xff) * a + (data[y*w+x] & 0xff) * (255-a)) / 255; data[y*w+x] = (an << 24) + (r << 16) + (g << 8) + b; } } inline void set_a(const iPoint & p, T c){ set_a(p.x, p.y, c); } inline void safe_set_a(int x, int y, T c){ if ((x<0)||(y<0)||(x>=w)||(y>=h)) return; set_a(x,y,c); } inline void safe_set_a(const iPoint & p, T c){ safe_set_a(p.x, p.y, c); } // Set full transparency outside border line, remove transparency inside it. // If border line is empty, remove transparancy on the whole image. // (Only useful for iImage) void set_border(const iLine & brd = iLine()){ iLineTester lt(brd); //process image rows for (int j = 0; j < h; j++){ // remove transparency if border is empty if (brd.size() == 0){ for (int i=0; i<w; i++) data[j*w+i] = data[j*w+i] | 0xFF000000; continue; } // get sorted border crossings for each row std::vector<int> cr = lt.get_cr(j); // set/remove tranparency - int i=0; - for (int k = 0; k < cr.size()+1; k++){ + size_t i=0; + for (size_t k = 0; k < cr.size()+1; k++){ int ic = (k<cr.size())?std::min(cr[k], w) : w; if (ic < 0) continue; - for (int ii=i; ii<ic; ii++){ + for (size_t ii=i; ii<(size_t)ic; ii++){ data[j*w+ii] = (k%2)? data[j*w+ii] | 0xFF000000 : data[j*w+ii] & 0x00FFFFFF ; } i=ic; - if (i>=w) break; + if (i>=(size_t)w) break; } } } inline void render (iPoint offset, Image<T> const & other) { iRect r = rect_intersect(range(), other.range()+offset); for (int y = 0; y < r.h; ++y) { for (int x = 0; x < r.w; ++x) { set_a(x+offset.x, y+offset.y, other.get(x,y)); } } } inline void render (int x, int y, Image<T> const & other) { render(iPoint(x,y), other); } #ifdef SWIG %extend { swig_str(); } #endif // SWIG }; /// \relates Image typedef Image<double> dImage; /// \relates Image typedef Image<int> iImage; /// \relates Image typedef Image<char> cImage; /// \relates Image typedef Image<short int> sImage; /// \relates Image template <typename T> std::ostream & operator<< (std::ostream & s, const Image<T> & i) { s << "Image(" << i.w << "x" << i.h << ")"; return s; } #endif diff --git a/core/2d/line_tests.h b/core/2d/line_tests.h index 67bd64f..30f1d1b 100644 --- a/core/2d/line_tests.h +++ b/core/2d/line_tests.h @@ -1,113 +1,113 @@ #ifndef LINE_TESTS_H #define LINE_TESTS_H #include "line.h" #include <algorithm> ///\addtogroup lib2d ///@{ ///\defgroup line_tests ///@{ /// Find sorted coordinates of crossings of y=y0 and line l /// (or of x=x0 and line l if horiz == false) /// Line is always treated as closed. template <typename T> class LineTester{ std::vector<Point<T> > sb,se; std::vector<double> ss; bool horiz; public: LineTester(const Line<T> & l, bool horiz_ = true): horiz(horiz_){ // collect line sides info: start and end points, slopes. int pts = l.size(); for (int i = 0; i < pts; i++){ Point<T> b(l[i%pts].x, l[i%pts].y), e(l[(i+1)%pts].x, l[(i+1)%pts].y); if (!horiz){ // swap x and y b.y = l[i%pts].x; b.x=l[i%pts].y; e.y = l[(i+1)%pts].x; e.x = l[(i+1)%pts].y; } if (b.y == e.y) continue; // no need for horisontal sides double s = double(e.x-b.x)/double(e.y-b.y); // side slope sb.push_back(b); se.push_back(e); ss.push_back(s); } } /// get coords of crossings of border with y=const (or x=const if horiz=false) line std::vector<T> get_cr(T y){ std::vector<T> cr; - for (int k = 0; k < sb.size(); k++){ + for (size_t k = 0; k < sb.size(); k++){ if ((sb[k].y > y)&&(se[k].y > y)) continue; // side is above the row if ((sb[k].y <= y)&&(se[k].y <= y)) continue; // side is below the row cr.push_back((ss[k] * double(y - sb[k].y)) + sb[k].x); } sort(cr.begin(), cr.end()); return cr; } /// is coord x inside border at cr line bool test_cr(const std::vector<T> & cr, T x) const{ // number of crossings on the ray (x,y) - (inf,y) typename std::vector<T>::const_iterator i = lower_bound(cr.begin(), cr.end(), x); int k=0; while (i!=cr.end()) {i++; k++;} return k%2==1; } }; /// \relates LineTester /// \brief LineTester with double coordinates typedef LineTester<double> dLineTester; /// \relates LineTester /// \brief LineTester with int coordinates typedef LineTester<int> iLineTester; /// Check that point p is inside polygon with boundary l template <typename T> bool point_in_line(const Point<T> & p, const Line<T> & l){ LineTester<T> lt(l); std::vector<T> cr = lt.get_cr(p.y); return lt.test_cr(cr, p.x); } /// Check that rectangle r touches polygon with boundary l template <typename T> bool rect_in_line(const Rect<T> & r, const Line<T> & l){ LineTester<T> lth(l, true), ltv(l,false); // check if there is any crossing at any sides, // or one corner is inside polygon // or one of line points is inside rect std::vector<T> cr; cr = lth.get_cr(r.y); - for (int i=0; i<cr.size(); i++) + for (size_t i=0; i<cr.size(); i++) if (r.x < cr[i] && cr[i] <=r.x+r.w ) return true; cr = lth.get_cr(r.y+r.h); - for (int i=0; i<cr.size(); i++) + for (size_t i=0; i<cr.size(); i++) if (r.x < cr[i] && cr[i] <=r.x+r.w ) return true; cr = ltv.get_cr(r.x); - for (int i=0; i<cr.size(); i++) + for (size_t i=0; i<cr.size(); i++) if (r.y < cr[i] && cr[i] <=r.y+r.h ) return true; cr = ltv.get_cr(r.x+r.w); - for (int i=0; i<cr.size(); i++) + for (size_t i=0; i<cr.size(); i++) if (r.y < cr[i] && cr[i] <=r.y+r.h ) return true; - for (int i=0; i<cr.size(); i++){ + for (size_t i=0; i<cr.size(); i++){ if (r.y < cr[i] ){ if (i%2 == 1) return true; break; } } if (l.size() && point_in_rect(l[0], r)) return true; return false; } #endif
ushakov/mapsoft
23c4c908792c4716840db15361f2cf4ce869d6a3
core/cache: fix -Wsign-compare warning
diff --git a/core/cache/cache.h b/core/cache/cache.h index 6290ec1..d80236d 100644 --- a/core/cache/cache.h +++ b/core/cache/cache.h @@ -1,254 +1,254 @@ #ifndef CACHE_H #define CACHE_H #include <map> #include <vector> #include <set> #include <cassert> #include <iostream> ///\addtogroup libmapsoft ///@{ ///\defgroup Cache ///cache of objects with limited capacity ///@{ template <typename K, typename V> class CacheIterator; /** Cache of objects of type V, keyed by type K. Eviction starts whenever number of elements exceeds some limit (cache size) set at construction and removed least recently used elements. Compiler directives: DEBUG_SCACHE -- log additions/deletions DEBUG_SCACHE_GET -- log gets */ template <typename K, typename V> class Cache { public: typedef CacheIterator<K, V> iterator; /// Constructor: create a cache with size n. - Cache (int n) : capacity (n) { - for (int i = 0; i < capacity; ++i){ + Cache (size_t n) : capacity (n) { + for (size_t i = 0; i < capacity; ++i){ free_list.insert (i); } } /// Copy constructor. Cache (Cache const & other) : capacity (other.capacity), storage (other.storage), index (other.index), free_list (other.free_list), usage (other.usage) { } /// Swap the cache with another one. void swap (Cache<K,V> & other) { std::swap (capacity, other.capacity); storage.swap (other.storage); index.swap (other.index); free_list.swap (other.free_list); usage.swap (other.usage); } /// Assignment. Cache<K,V> & operator= (Cache<K,V> const& other) { Cache<K,V> dummy (other); swap (dummy); return *this; } /// Return number of elements in the cache (Does not work!?). - int size() { + size_t size() { return storage.size(); } /// Add an element to the cache. int add (K const & key, V const & value) { if (contains(key)) { int idx = index[key]; storage[idx].second = value; return 0; } #ifdef DEBUG_CACHE std::cout << "cache: add " << key << " "; #endif if (free_list.size() == 0) { - int to_delete = usage[usage.size() - 1]; + size_t to_delete = usage[usage.size() - 1]; #ifdef DEBUG_CACHE std::cout << "no free space "; std::cout << "usage size " << usage.size() << " to_delete=" << to_delete << " key=" << storage[to_delete].first; #endif index.erase (storage[to_delete].first); free_list.insert (to_delete); } - int free_ind = *(free_list.begin()); + size_t free_ind = *(free_list.begin()); free_list.erase (free_list.begin()); #ifdef DEBUG_CACHE std::cout << std::endl; std::cout << "cache: free_ind=" << free_ind << std::endl; #endif if (storage.size() <= free_ind) { assert (storage.size() == free_ind); storage.push_back (std::make_pair (key, value)); } else { storage[free_ind] = std::make_pair (key, value); } index[key] = free_ind; use (free_ind); #ifdef DEBUG_CACHE std::cout << "cache usage:"; - for (int i = 0; i < usage.size(); ++i) { + for (size_t i = 0; i < usage.size(); ++i) { std::cout << " " << usage[i]; } std::cout << std::endl; #endif return 0; } /// Check whether the cache contains a key. bool contains (K const & key) { return index.count (key) > 0; } /// Get element from the cache. V & get (K const & key) { assert(contains(key)); - int ind = index[key]; + size_t ind = index[key]; #ifdef DEBUG_CACHE_GET std::cout << "cache get: " << key << " ind: " << ind << std::endl; #endif use (ind); return storage[ind].second; } /// Remove an element from the cache. void erase(K const & key) { - int i = index[key]; + size_t i = index[key]; index.erase(key); free_list.insert(i); - for (int k = 0; k < usage.size(); ++k) { + for (size_t k = 0; k < usage.size(); ++k) { if (usage[k] == i) { usage.erase(usage.begin() + k); break; } } } /// Return size of empty space. - int space_remains () { + size_t space_remains () { return free_list.size(); } /// Clear the cache. void clear () { - for (int i = 0; i < capacity; ++i) free_list.insert (i); + for (size_t i = 0; i < capacity; ++i) free_list.insert (i); index.clear(); usage.clear(); } /// Returns an iterator pointing to the first element in the cache. /// Iterator traverses all the cache elements /// in order of increasing keys. All iterators are valid until the /// first cache insert or delete (changing value for existing key /// does not invalidate iterators). iterator begin() { return CacheIterator<K, V>(this, index.begin()); } /// Returns an iterator pointing to the last element in the cache. /// Iterator traverses all the cache elements /// in order of increasing keys. All iterators are valid until the /// first cache insert or delete (changing value for existing key /// does not invalidate iterators). iterator end() { return CacheIterator<K, V>(this, index.end()); } /// Erase an element pointed to by the iterator iterator erase(iterator it) { typename std::map<K, int>::const_iterator it2 = it++; erase(it2->first); return it; } private: - int capacity; + size_t capacity; std::vector<std::pair<K,V> > storage; - std::map<K, int> index; - std::set<int> free_list; - std::vector<int> usage; + std::map<K, size_t> index; + std::set<size_t> free_list; + std::vector<size_t> usage; friend class CacheIterator<K, V>; // index end is removed template <typename T> void push_vector (std::vector<T> & vec, int start, int end) { #ifdef DEBUG_CACHE_GET std::cout << "cache push_vector: start=" << start << " end=" << end << " size=" << vec.size() << std::endl; #endif for (int i = end; i > start; --i) { vec[i] = vec[i-1]; } } - void use (int ind) { - int i; + void use (size_t ind) { + size_t i; for (i = 0; i < usage.size() && usage[i] != ind; ++i); if (i == usage.size()) { usage.resize (usage.size()+1); push_vector (usage, 0, usage.size()-1); usage[0] = ind; } else { push_vector (usage, 0, i); usage[0] = ind; } } }; /// Print cache elements. template <typename K, typename V> std::ostream & operator<< (std::ostream & s, const Cache<K,V> & cache) { s << "Cache(\n"; - for (int i=0; i<cache.storage.size(); i++){ + for (size_t i=0; i<cache.storage.size(); i++){ s << " " << cache.storage[i].first << " => " << cache.storage[i].second << "\n"; } s << ")"; return s; } /// Iterator class for cache template <typename K, typename V> -class CacheIterator : public std::map<K, int>::const_iterator { +class CacheIterator : public std::map<K, size_t>::const_iterator { public: std::pair<K, V>& operator*() { - return cache->storage[std::map<K, int>::const_iterator::operator*().second]; + return cache->storage[std::map<K, size_t>::const_iterator::operator*().second]; } std::pair<K, V>* operator->() { - return &(cache->storage[std::map<K, int>::const_iterator::operator*().second]); + return &(cache->storage[std::map<K, size_t>::const_iterator::operator*().second]); } private: friend class Cache<K, V>; CacheIterator (Cache<K, V>* cache_, - typename std::map<K, int>::const_iterator iter_) - : std::map<K, int>::const_iterator(iter_), + typename std::map<K, size_t>::const_iterator iter_) + : std::map<K, size_t>::const_iterator(iter_), cache(cache_) { } Cache<K, V>* cache; }; #endif /* CACHE_H */
ushakov/mapsoft
5de837822451fa35f56f75a2214a16342a8fc4c4
SConstruct: add -Wall flag
diff --git a/SConstruct b/SConstruct index ddcf739..7b2623d 100644 --- a/SConstruct +++ b/SConstruct @@ -1,102 +1,102 @@ ###################################### # What do we want to build subdirs_min = Split("core programs viewer vector man scripts") subdirs_max = subdirs_min + Split("tests misc") ###################################### ## import python libraries import os import platform if platform.python_version()<"2.7": import distutils.sysconfig as sysconfig else: import sysconfig ###################################### # Create environment, add some methods env = Environment () Export('env') # UseLibs -- use pkg-config libraries def UseLibs(env, libs): if isinstance(libs, list): libs = " ".join(libs) env.ParseConfig('pkg-config --cflags --libs %s' % libs) env.AddMethod(UseLibs) # SymLink -- create a symlink # Arguments target and linkname follow standard order (look at ln(1)) # wd is optional base directory for both def SymLink(env, target, linkname, wd=None): if wd: env.Command(wd+'/'+linkname, wd+'/'+target, "ln -s -- %s %s/%s" % (target, wd, linkname)) else: env.Command(linkname, target, "ln -s -- %s %s" % (target, linkname)) env.AddMethod(SymLink) ###################################### ## Add default flags if 'GCCVER' in os.environ: ver = os.environ['GCCVER'] env.Replace (CC = ("gcc-%s" % ver)) env.Replace (CXX = ("g++-%s" % ver)) env.Append (CCFLAGS=['-DACCEPT_USE_OF_DEPRECATED_PROJ_API_H=1']) -env.Append (CCFLAGS=['-Werror=return-type']) +env.Append (CCFLAGS=['-Werror=return-type', '-Wall']) env.Append (CCFLAGS=['-O2']) env.Append (CCFLAGS='-std=gnu++11') env.Append (ENV = {'PKG_CONFIG_PATH': os.getcwd()+'/core/pc'}) if os.getenv('PKG_CONFIG_PATH'): env.Append (ENV = {'PKG_CONFIG_PATH': [ os.getcwd()+'/core/pc', os.getenv('PKG_CONFIG_PATH')]}) env.Append (CPPPATH = "#core") env.Append (LIBPATH = "#core") env.Append (LIBS = "mapsoft") ###################################### ## Parse command-line arguments: env.PREFIX = ARGUMENTS.get('prefix', '') env.bindir=env.PREFIX+'/usr/bin' env.datadir=env.PREFIX+'/usr/share/mapsoft' env.man1dir=env.PREFIX+'/usr/share/man/man1' env.figlibdir=env.PREFIX+'/usr/share/xfig/Libraries' env.libdir=env.PREFIX+ sysconfig.get_config_var('LIBDIR') env.desktopdir=env.PREFIX+'/usr/share/applications' env.Alias('install', [env.bindir, env.man1dir, env.datadir, env.figlibdir, env.libdir, env.desktopdir]) if ARGUMENTS.get('debug', 0): env.Append (CCFLAGS='-ggdb') env.Append (LINKFLAGS='-ggdb') if ARGUMENTS.get('profile', 0): env.Append (CCFLAGS='-pg') env.Append (LINKFLAGS='-pg') if ARGUMENTS.get('gprofile', 0): env.Append (LINKFLAGS='-lprofiler') if ARGUMENTS.get('gheapcheck', 0): env.Append (LINKFLAGS='-ltcmalloc') if ARGUMENTS.get('minimal', 0): SConscript(list(map(lambda s: s + "/SConscript", subdirs_min))) else: SConscript(list(map(lambda s: s + "/SConscript", subdirs_max))) Help(""" You can build mapsoft with the following options: scons -Q debug=1 // build with -ggdb scons -Q profile=1 // build with -pg scons -Q gheapcheck=1 // build with -ltcmalloc scons -Q minimal=1 // skip misc and tests dirs scons -Q prefix=<prefix> // set installation prefix """) # vim: ft=python tw=0
ushakov/mapsoft
98dc123e7f6db1113c5eeeb3b955aa9b807278f9
core/fig: fix initialization error; fix -Wsign-compare warnings
diff --git a/core/fig/fig_data.cpp b/core/fig/fig_data.cpp index 6fb3ab6..268ef13 100644 --- a/core/fig/fig_data.cpp +++ b/core/fig/fig_data.cpp @@ -1,149 +1,149 @@ #include "fig_data.h" #include <map> #include <string> namespace fig { using namespace std; /*************************************************/ /// static data // fig units, 1.05/1200in (not 1/1200in, I don't know why...) const double cm2fig = 1200.0 / 1.05 / 2.54; const double fig2cm = 1.0 / cm2fig; // fig colors typedef pair<int,int> p_ii; const p_ii colors_a[] = { p_ii(-1, 0x000000), // default p_ii(0, 0x000000), // black p_ii(1, 0xff0000), // blue p_ii(2, 0x00ff00), // green p_ii(3, 0xffff00), // cyan p_ii(4, 0x0000ff), // red p_ii(5, 0xff00ff), // magenta p_ii(6, 0x00ffff), // yellow p_ii(7, 0xffffff), // white p_ii(8, 0x900000), // blue4 p_ii(9, 0xb00000), // blue3 p_ii(10, 0xd00000), // blue2 p_ii(11, 0xffce87), // ltblue p_ii(12, 0x009000), // green4 p_ii(13, 0x00b000), // green3 p_ii(14, 0x00d000), // green2 p_ii(15, 0x909000), // cyan4 p_ii(16, 0xb0b000), // cyan3 p_ii(17, 0xd0d000), // cyan2 p_ii(18, 0x000090), // red4 p_ii(19, 0x0000b0), // red3 p_ii(20, 0x0000d0), // red2 p_ii(21, 0x900090), // magenta4 p_ii(22, 0xb000b0), // magenta3 p_ii(23, 0xd000d0), // magenta2 p_ii(24, 0x003080), // brown4 p_ii(25, 0x0040a0), // brown3 p_ii(26, 0x0060c0), // brown2 p_ii(27, 0x8080ff), // pink4 p_ii(28, 0xa0a0ff), // pink3 p_ii(29, 0xc0c0ff), // pink2 p_ii(30, 0xe0e0ff), // pink p_ii(31, 0x00d7ff) // gold }; const map<int,int> colors(&colors_a[0], &colors_a[sizeof(colors_a)/sizeof(p_ii)]); // fig postscript fonts typedef pair<int,string> p_is; const p_is psfonts_a[] = { p_is(-1, "Default"), p_is( 0, "Times-Roman"), p_is( 1, "Times-Italic"), p_is( 2, "Times-Bold"), p_is( 3, "Times-BoldItalic"), p_is( 4, "AvantGarde-Book"), p_is( 5, "AvantGarde-BookOblique"), p_is( 6, "AvantGarde-Demi"), p_is( 7, "AvantGarde-DemiOblique"), p_is( 8, "Bookman-Light"), p_is( 9, "Bookman-LightItalic"), p_is(10, "Bookman-Demi"), p_is(11, "Bookman-DemiItalic"), p_is(12, "Courier"), p_is(13, "Courier-Oblique"), p_is(14, "Courier-Bold"), p_is(15, "Courier-BoldOblique"), p_is(16, "Helvetica"), p_is(17, "Helvetica-Oblique"), p_is(18, "Helvetica-Bold"), p_is(19, "Helvetica-BoldOblique"), p_is(20, "Helvetica-Narrow"), p_is(21, "Helvetica-Narrow-Oblique"), p_is(22, "Helvetica-Narrow-Bold"), p_is(23, "Helvetica-Narrow-BoldOblique"), p_is(24, "NewCenturySchlbk-Roman"), p_is(25, "NewCenturySchlbk-Italic"), p_is(26, "NewCenturySchlbk-Bold"), p_is(27, "NewCenturySchlbk-BoldItalic"), p_is(28, "Palatino-Roman"), p_is(29, "Palatino-Italic"), p_is(30, "Palatino-Bold"), p_is(31, "Palatino-BoldItalic"), p_is(32, "Symbol"), p_is(33, "ZapfChancery-MediumItalic"), p_is(34, "ZapfDingbats"), }; const map<int,string> psfonts(&psfonts_a[0], &psfonts_a[sizeof(psfonts_a)/sizeof(p_is)]); // fig tex fonts const p_is texfonts_a[] = { p_is( 0, "Default"), p_is( 1, "Roman"), p_is( 2, "Bold"), p_is( 3, "Italic"), p_is( 4, "Sans Serif"), p_is( 5, "Typewriter") }; const map<int,string> texfonts(&texfonts_a[0], &texfonts_a[sizeof(texfonts_a)/sizeof(p_is)]); /*************************************************/ void fig_object::set_points(const dLine & v){ clear(); - for (int i=0;i<v.size();i++) + for (size_t i=0;i<v.size();i++) push_back(iPoint(lround(v[i].x), lround(v[i].y))); } void fig_object::set_points(const iLine & v){ clear(); insert(end(), v.begin(), v.end()); } void fig_world::remove_empty_comp(){ int removed; do{ removed=0; iterator o=begin(); while (o!=end()){ if (o->type==6){ iterator on=o; on++; if ((on!=end()) && (on->type==-6)){ o=erase(o); o=erase(o); removed++; continue; } } o++; } } while(removed>0); } } //namespace diff --git a/core/fig/fig_io.cpp b/core/fig/fig_io.cpp index 84ae116..68065f6 100644 --- a/core/fig/fig_io.cpp +++ b/core/fig/fig_io.cpp @@ -1,581 +1,581 @@ #include "utils/spirit_utils.h" #include <boost/spirit/include/classic_assign_actor.hpp> #include <boost/spirit/include/classic_push_back_actor.hpp> #include <boost/spirit/include/classic_insert_at_actor.hpp> #include <boost/spirit/include/classic_clear_actor.hpp> #include <iomanip> #include <fstream> #include "fig_io.h" #include "utils/iconv_utils.h" namespace fig { using namespace std; using namespace boost::spirit::classic; string default_enc("KOI8-R"); /****************************************************************/ int f_arr, b_arr; bool no_f_arr(){return f_arr==0;} bool no_b_arr(){return b_arr==0;} int npoints, npoints_f; bool point_counter(){npoints--; return npoints>=0;} bool point_f_counter(){npoints_f--; return npoints_f>=0;} int sub_type; bool no_picture(){return sub_type!=5;} // convert fig colors to/from rgb int color_fig2rgb(const int c, const map<int,int> & custom){ map<int,int>::const_iterator i; i=colors.find(c); if (i!=colors.end()) return i->second; i=custom.find(c); if (i!=custom.end()) return i->second; cerr << "Unknown fig color: " << c << "\n"; return c; } int color_rgb2fig(const int c, const map<int,int> & custom){ map<int,int>::const_iterator i; for (i=colors.begin(); i!=colors.end(); i++){ if (i->first == -1 ) continue; // avoid -1 value ("default color") if (i->second == c) return i->first; } for (i=custom.begin(); i!=custom.end(); i++){ if (i->second == c) return i->first; } cerr << "Unknown fig color: " << c << "\n"; return -1; } // Add new rgb color to custom colormap if needed. Return true if color was added bool color_rgbadd(const int c, map<int,int> & custom){ int maxc=0; map<int,int>::const_iterator i; for (i=colors.begin(); i!=colors.end(); i++){ if (i->first > maxc) maxc=i->first; if (i->second == c) return false; } for (i=custom.begin(); i!=custom.end(); i++){ if (i->first > maxc) maxc=i->first; if (i->second == c) return false; } custom.insert(pair<int,int>(maxc+1, c)); return true; } // function for reading objects from file bool read(const char* filename, fig_world & world, const Options & opts){ fig_world ret; fig_object o, o0; iPoint p; vector<string> comment; map<int,int> custom_colors; int color_num=0; string key; Options tmp_opts; rule_t ch = anychar_p - eol_p; rule_t comm = eps_p[clear_a(comment)][clear_a(tmp_opts)] >> *( (str_p("# \\") >> (*(ch-'='))[assign_a(key)] >> '=' >> (*ch)[insert_at_a(tmp_opts,key)] >> eol_p) | (str_p("# \\") >> (*(ch-'='))[assign_a(key)] >> eol_p)[insert_at_a(tmp_opts,key,"1")] | (str_p("# ") >> (*ch)[push_back_a(comment)] >> eol_p) ); rule_t header = str_p("#FIG 3.2") >> *ch >> eol_p >> (*ch)[assign_a(ret.orientation)] >> eol_p >> // orientation ("Landscape" or "Portrait") (*ch)[assign_a(ret.justification)] >> eol_p >> // justification ("Center" or "Flush Left") (*ch)[assign_a(ret.units)] >> eol_p >> // units ("Metric" or "Inches") (*ch)[assign_a(ret.papersize)] >> eol_p >> // papersize ("A4", etc.) ureal_p[assign_a(ret.magnification)] >> eol_p >> // magnification (export and print magnification, %) (*ch)[assign_a(ret.multiple_page)] >> eol_p >> // multiple-page ("Single" or "Multiple" pages) int_p[assign_a(ret.transparent_color)] >> eol_p >> // transparent color comm[assign_a(ret.comment, comment)][assign_a(ret.opts, tmp_opts)] >> // comments and options uint_p[assign_a(ret.resolution)] >> +space_p >> // resolution uint_p[assign_a(ret.coord_system)] >> eol_p; // coord_system /****************************************************************/ rule_t r_sub_type = +blank_p >> uint_p[assign_a(o.sub_type)][assign_a(sub_type)]; rule_t r_line_style = +blank_p >> int_p[assign_a(o.line_style)]; rule_t r_thickness = +blank_p >> int_p[assign_a(o.thickness)]; rule_t r_pen_color = +blank_p >> int_p[assign_a(o.pen_color)]; rule_t r_fill_color = +blank_p >> int_p[assign_a(o.fill_color)]; rule_t r_depth = +blank_p >> uint_p[assign_a(o.depth)]; rule_t r_pen_style = +blank_p >> int_p[assign_a(o.pen_style)]; rule_t r_area_fill = +blank_p >> int_p[assign_a(o.area_fill)]; rule_t r_style_val = +blank_p >> real_p[assign_a(o.style_val)]; rule_t r_cap_style = +blank_p >> int_p[assign_a(o.cap_style)]; rule_t r_join_style = +blank_p >> int_p[assign_a(o.join_style)]; rule_t r_direction = +blank_p >> int_p[assign_a(o.direction)]; rule_t r_radius = +blank_p >> int_p[assign_a(o.radius)]; rule_t r_arrows = +blank_p >> uint_p[assign_a(f_arr)][assign_a(o.forward_arrow)] >> +blank_p >> uint_p[assign_a(b_arr)][assign_a(o.backward_arrow)]; rule_t r_arrows_p = (eps_p(&no_f_arr) | ( +space_p >> int_p[assign_a(o.farrow_type)] >> +blank_p >> int_p[assign_a(o.farrow_style)] >> +blank_p >> real_p[assign_a(o.farrow_thickness)] >> +blank_p >> real_p[assign_a(o.farrow_width)] >> +blank_p >> real_p[assign_a(o.farrow_height)] )) >> (eps_p(&no_b_arr) | ( +space_p >> int_p[assign_a(o.barrow_type)] >> +blank_p >> int_p[assign_a(o.barrow_style)] >> +blank_p >> real_p[assign_a(o.barrow_thickness)] >> +blank_p >> real_p[assign_a(o.barrow_width)] >> +blank_p >> real_p[assign_a(o.barrow_height)] )); rule_t r_angle = +blank_p >> real_p[assign_a(o.angle)]; rule_t r_center_xy = +blank_p >> real_p[assign_a(o.center_x)] >> +blank_p >> real_p[assign_a(o.center_y)]; rule_t r_radius_xy = +blank_p >> int_p[assign_a(o.radius_x)] >> +blank_p >> int_p[assign_a(o.radius_y)]; rule_t r_start_xy = +blank_p >> int_p[assign_a(o.start_x)] >> +blank_p >> int_p[assign_a(o.start_y)]; rule_t r_end_xy = +blank_p >> int_p[assign_a(o.end_x)] >> +blank_p >> int_p[assign_a(o.end_y)]; rule_t r_npoints = +blank_p >> int_p[assign_a(npoints)][assign_a(npoints_f)]; rule_t r_push_xy = +space_p >> int_p[assign_a(p.x)] >> +space_p >> int_p[assign_a(p.y)][push_back_a(o,p)]; rule_t r_image = (eps_p(&no_picture) | ( +space_p >> uint_p[assign_a(o.image_orient)] >> // orientation = normal (0) or flipped (1) +blank_p >> (+ch)[assign_a(o.image_file)])); rule_t r_points = *( eps_p(&point_counter) >> r_push_xy ); rule_t r_fpoints = *( eps_p(&point_f_counter) >> +space_p >> real_p[push_back_a(o.f)] ); /*******************************************/ rule_t c0_color = ch_p('0') >> +blank_p >> uint_p[assign_a(color_num)] >> +blank_p >> '#' >> hex_p[insert_at_a(custom_colors,color_num)] >> eol_p; /*******************************************/ const int type5=5; rule_t c5_arc = ch_p('5')[assign_a(o.type,type5)] // Arc >> r_sub_type >> r_line_style >> r_thickness >> r_pen_color >> r_fill_color >> r_depth >> r_pen_style >> r_area_fill >> r_style_val >> r_cap_style >> r_direction >> r_arrows >> r_center_xy >> r_push_xy >> r_push_xy >> r_push_xy >> r_arrows_p >> eol_p; /*******************************************/ const int type6=6; rule_t c6_compound_start = ch_p('6')[assign_a(o.type,type6)] // Compound >> r_push_xy >> r_push_xy >> eol_p; /*******************************************/ const int typem6=-6; rule_t c6_compound_end = str_p("-6")[assign_a(o.type,typem6)] >> eol_p; /*******************************************/ const int type1=1; rule_t c1_ellipse = ch_p('1')[assign_a(o.type,type1)] // Ellipse >> r_sub_type >> r_line_style >> r_thickness >> r_pen_color >> r_fill_color >> r_depth >> r_pen_style >> r_area_fill >> r_style_val >> r_direction /*(always 1)*/ >> r_angle /*(radians, the angle of the x-axis)*/ >> r_center_xy >> r_radius_xy >> r_start_xy >> r_end_xy >> eol_p; /*******************************************/ const int type2=2; rule_t c2_polyline = ch_p('2')[assign_a(o.type,type2)] // Polyline >> r_sub_type >> r_line_style >> r_thickness >> r_pen_color >> r_fill_color >> r_depth >> r_pen_style >> r_area_fill >> r_style_val >> r_join_style >> r_cap_style >> r_radius >> r_arrows >> r_npoints >> r_arrows_p >> r_image >> r_points >> eol_p; /*******************************************/ const int type3=3; rule_t c3_spline = ch_p('3')[assign_a(o.type,type3)] // Spline >> r_sub_type >> r_line_style >> r_thickness >> r_pen_color >> r_fill_color >> r_depth >> r_pen_style >> r_area_fill >> r_style_val >> r_cap_style >> r_arrows >> r_npoints >> r_arrows_p >> r_points >> r_fpoints >> eol_p; /*******************************************/ const int type4=4; rule_t c4_text = ch_p('4')[assign_a(o.type,type4)] // Text >> r_sub_type >> r_pen_color >> r_depth >> r_pen_style // (not used) >> +blank_p >> int_p[assign_a(o.font)] >> +blank_p >> real_p[assign_a(o.font_size)] >> r_angle >> +blank_p >> int_p[assign_a(o.font_flags)] >> +blank_p >> real_p[assign_a(o.height)] >> +blank_p >> real_p[assign_a(o.length)] >> r_push_xy >> blank_p >> (*(~eps_p("\\001") >> anychar_p))[assign_a(o.text)] >> str_p("\\001") >> eol_p; /*******************************************/ rule_t main_rule = header >> *( eps_p[assign_a(o,o0)] >> comm[assign_a(o.comment, comment)][assign_a(o.opts,tmp_opts)] >> ( c0_color | (c1_ellipse | c2_polyline | c3_spline | c4_text | c5_arc | c6_compound_start | c6_compound_end) [push_back_a(ret,o)]) ); if (!parse_file("fig::read", filename, main_rule)) return false; // convert \??? chars for (fig::fig_world::iterator i=ret.begin(); i!=ret.end(); i++){ string t; - for (int n=0;n<i->text.size();n++){ + for (size_t n=0;n<i->text.size();n++){ if ((i->text[n] == '\\')&&(n+3<i->text.size())){ t+=char((i->text[n+1]-'0')*64 + (i->text[n+2]-'0')*8 + (i->text[n+3]-'0')); n+=3; } else t+=i->text[n]; } i->text=t; } //convert comments, options and text to UTF-8 string enc = opts.get("fig_in_enc", default_enc); IConv cnv(enc); for (fig_world::iterator i=ret.begin(); i!=ret.end(); i++){ i->text = cnv.to_utf8(i->text); for (vector<string>::iterator c = i->comment.begin(); c != i->comment.end(); c++){ *c = cnv.to_utf8(*c); } tmp_opts.clear(); for (Options::iterator o=i->opts.begin();o!=i->opts.end();o++) tmp_opts.put(cnv.to_utf8(o->first), cnv.to_utf8(o->second)); i->opts.swap(tmp_opts); } for (vector<string>::iterator c = ret.comment.begin(); c != ret.comment.end(); c++){ *c = cnv.to_utf8(*c); } tmp_opts.clear(); for (Options::iterator o=ret.opts.begin();o!=ret.opts.end();o++) tmp_opts.put(cnv.to_utf8(o->first), cnv.to_utf8(o->second)); ret.opts.swap(tmp_opts); // convert colors to rgb for (fig::fig_world::iterator i=ret.begin(); i!=ret.end(); i++){ i->pen_color = color_fig2rgb(i->pen_color, custom_colors); i->fill_color = color_fig2rgb(i->fill_color, custom_colors); } // merge world and ret fig::fig_world tmp=world; world=ret; world.insert(world.begin(), tmp.begin(), tmp.end()); for (Options::iterator o=tmp.opts.begin();o!=tmp.opts.end();o++) world.opts.put(o->first, o->second); return true; } /***********************************************************/ bool write(ostream & out, const fig_world & world, const Options & opts){ string enc = opts.get("fig_out_enc", default_enc); IConv cnv(enc); - int n; + size_t n; // writing header out << "#FIG 3.2\n" << world.orientation << "\n" << world.justification << "\n" << world.units << "\n" << world.papersize << "\n" << setprecision(2) << fixed << world.magnification << "\n" << setprecision(3) << world.multiple_page << "\n" << world.transparent_color << "\n"; // writing comments - for (0;n<world.comment.size();n++){ + for (n=0;n<world.comment.size();n++){ if (n>99) {cerr << "fig comment contains > 100 lines! Cutting...\n"; break;} string s = cnv.from_utf8(world.comment[n]); if (s.size()>1022){cerr << "fig comment line is > 1022 chars! Cutting...\n"; s.resize(1022);} out << "# " << s << "\n"; } // writing options (as comments) for (Options::const_iterator o=world.opts.begin();o!=world.opts.end();o++){ if (n++>99) {cerr << "fig comment contains > 100 lines! Cutting...\n"; break;} string s = cnv.from_utf8(o->first) + "=" + cnv.from_utf8(o->second); if (s.size()>1022){cerr << "fig comment line is > 1022 chars! Cutting...\n"; s.resize(1022);} out << "# \\" << s << "\n"; } out << world.resolution << " " << world.coord_system << "\n"; // looking for custom colors map<int,int> custom_colors; for (fig::fig_world::const_iterator i=world.begin(); i!=world.end(); i++){ color_rgbadd(i->pen_color, custom_colors); color_rgbadd(i->fill_color, custom_colors); } // writing custom colors for (map<int,int>::const_iterator i = custom_colors.begin(); i != custom_colors.end(); i++){ out << "0 " << i->first << " #" << setbase(16) << setw(6) << setfill('0') << i->second << setbase(10) << "\n"; } // writing objects for (fig_world::const_iterator i = world.begin(); i != world.end(); i++){ // We don't support color objects! // color object with comment or options breaks all! if (i->type==0) continue; for (n=0;n<i->comment.size();n++){ if (n>99) {cerr << "fig comment contains > 100 lines! Cutting...\n"; break;} string s = cnv.from_utf8(i->comment[n]); if (s.size()>1022){cerr << "fig comment line is > 1022 chars! Cutting...\n"; s.resize(1022);} out << "# " << s << "\n"; } for (Options::const_iterator o=i->opts.begin();o!=i->opts.end();o++){ if (n++>99) {cerr << "fig comment contains > 100 lines! Cutting...\n"; break;} string s = cnv.from_utf8(o->first) + "=" + cnv.from_utf8(o->second); if (s.size()>1022){cerr << "fig comment line is > 1022 chars! Cutting...\n"; s.resize(1022);} out << "# \\" << s << "\n"; } - int nn = i->size(); - int nn1=nn; + size_t nn = i->size(); + size_t nn1=nn; vector<float> f = i->f; int pen_color = color_rgb2fig(i->pen_color, custom_colors); int fill_color = color_rgb2fig(i->fill_color, custom_colors); switch (i->type){ case 0: // Color break; case 1: // Ellipse out << "1 " << i->sub_type << " " << i->line_style << " " << i->thickness << " " << pen_color << " " << fill_color << " " << i->depth << " " << i->pen_style << " " << i->area_fill << " " << i->style_val << " " << i->direction << " " << i->angle << " " << int(i->center_x) << " " << int(i->center_y) << " " << i->radius_x << " " << i->radius_y << " " << i->start_x << " " << i->start_y << " " << i->end_x << " " << i->end_y << "\n"; break; case 2: // Polyline // в замкнутых многоугольниках последняя точка должна совпадать с первой if ((i->sub_type > 1) && (nn>0) && ((*i)[nn-1]!=(*i)[0])){ nn1=nn+1; } out << "2 " << i->sub_type << " " << i->line_style << " " << i->thickness << " " << pen_color << " " << fill_color << " " << i->depth << " " << i->pen_style << " " << i->area_fill << " " << i->style_val << " " << i->join_style << " " << i->cap_style << " " << i->radius << " " << i->forward_arrow << " " << i->backward_arrow << " " << nn1; if (i->forward_arrow) out << "\n\t" << i->farrow_type << " " << i->farrow_style << " " << i->farrow_thickness << " " << i->farrow_width << " " << i->farrow_height; if (i->backward_arrow) out << "\n\t" << i->barrow_type << " " << i->barrow_style << " " << i->barrow_thickness << " " << i->barrow_width << " " << i->barrow_height; if (i->sub_type==5) out << "\n\t" << i->image_orient << " " << i->image_file; for (n=0; n<nn; n++) out << ((n%6==0) ? "\n\t":" ") << (*i)[n].x << " " << (*i)[n].y; if (nn1>nn) out << " " << (*i)[0].x << " " << (*i)[0].y; out << "\n"; break; case 3: // Spline if (nn!=f.size()){ f.resize(nn, 1); cerr << "fig::write (spline): different amount of x,y and f values\n"; } if ((i->sub_type%2==1) && (nn<3)){ cerr << "fig::write (spline): closed spline with <3 points\n"; break; } if ((i->sub_type%2==0) && (nn<2)){ cerr << "fig::write (spline): spline with <2 points\n"; break; } out << "3 " << i->sub_type << " " << i->line_style << " " << i->thickness << " " << pen_color << " " << fill_color << " " << i->depth << " " << i->pen_style << " " << i->area_fill << " " << i->style_val << " " << i->cap_style << " " << i->forward_arrow << " " << i->backward_arrow << " " << nn; if (i->forward_arrow) out << "\n\t" << i->farrow_type << " " << i->farrow_style << " " << i->farrow_thickness << " " << i->farrow_width << " " << i->farrow_height; if (i->backward_arrow) out << "\n\t" << i->barrow_type << " " << i->barrow_style << " " << i->barrow_thickness << " " << i->barrow_width << " " << i->barrow_height; for (n=0; n<nn; n++) out << ((n%6==0) ? "\n\t":" ") << (*i)[n].x << " " << (*i)[n].y; for (n=0; n<nn; n++) out << ((n%6==0) ? "\n\t":" ") << f[n]; out << "\n"; break; case 4: // Text // сделать пересчет размеров (height length)! if (nn<1){ cerr << "fig::write (text): can't get x and y values\n"; break; } out << "4 " << i->sub_type << " " << pen_color << " " << i->depth << " " << i->pen_style << " " << i->font << " " << i->font_size << " " << i->angle << " " << i->font_flags << " " << i->height << " " << i->length << " " << (*i)[0].x << " " << (*i)[0].y << " " << cnv.from_utf8(i->text) << "\\001\n"; break; case 5: // Arc if (nn<3){ cerr << "fig::write (arc): can't get x and y values\n"; break; } out << "5 " << i->sub_type << " " << i->line_style << " " << i->thickness << " " << pen_color << " " << fill_color << " " << i->depth << " " << i->pen_style << " " << i->area_fill << " " << i->style_val << " " << i->cap_style << " " << i->direction << " " << i->forward_arrow << " " << i->backward_arrow << " " << i->center_x << " " << i->center_y << " " << (*i)[0].x << " " << (*i)[0].y << " " << (*i)[1].x << " " << (*i)[1].y << " " << (*i)[2].x << " " << (*i)[2].y; if (i->forward_arrow) out << "\n\t" << i->farrow_type << " " << i->farrow_style << " " << i->farrow_thickness << " " << i->farrow_width << " " << i->farrow_height; if (i->backward_arrow) out << "\n\t" << i->barrow_type << " " << i->barrow_style << " " << i->barrow_thickness << " " << i->barrow_width << " " << i->barrow_height; out << "\n"; break; case 6: // Compound begin // сделать пересчет размеров! int x1,y1,x2,y2; if (nn<2){ cerr << "fig::write (compound): can't get x and y values\n"; x1=y1=x2=y2=0; } else { x1 = (*i)[0].x; y1 = (*i)[0].y; x2 = (*i)[1].x; y2 = (*i)[1].y; } out << "6 " << x1 << " " << y1 << " " << x2 << " " << y2 << "\n"; break; case -6: // Compound end out << "-6\n"; break; default: cerr << "fig::write: bad object type!\n"; break; } } return true; } bool write(const string & file, const fig_world & world, const Options & opts){ ofstream out(file.c_str()); if (!out) { cerr << "Error: can't open fig file \"" << file << "\"\n"; return false; } if (!write(out, world, opts)) { cerr << "Error: can't write to fig file \"" << file << "\"\n"; return false; } return true; } } //namespace diff --git a/core/fig/fig_utils.cpp b/core/fig/fig_utils.cpp index a64d129..dca08ac 100644 --- a/core/fig/fig_utils.cpp +++ b/core/fig/fig_utils.cpp @@ -1,142 +1,142 @@ #include "fig_utils.h" #include "2d/line_rectcrop.h" namespace fig { using namespace std; /****************************************************************/ // размер fig-объектов iRect fig_range(std::list<fig_object> & objects){ if ((objects.size()<1) || (objects.begin()->size()<1)) return iRect(0,0,0,0); int minx=(*objects.begin())[0].x; int maxx=(*objects.begin())[0].x; int miny=(*objects.begin())[0].y; int maxy=(*objects.begin())[0].y; for (std::list<fig_object>::const_iterator i = objects.begin(); i != objects.end(); i++){ if (i->type == 1){ int rx = i->radius_x; int ry = i->radius_y; int cx = i->center_x; int cy = i->center_y; if (minx > cx-rx) minx = cx-rx; if (maxx < cx+rx) maxx = cx+rx; if (miny > cy-ry) miny = cy-ry; if (maxy < cy+ry) maxy = cy+ry; } else { - for (int j = 0; j < i->size(); j++){ + for (size_t j = 0; j < i->size(); j++){ int x = (*i)[j].x; int y = (*i)[j].y; if (minx > x) minx = x; if (maxx < x) maxx = x; if (miny > y) miny = y; if (maxy < y) maxy = y; } } } return iRect(iPoint(minx,miny), iPoint(maxx,maxy)); } // заключить fig-объекты в составной объект. void fig_make_comp(std::list<fig_object> & objects){ if ((objects.size()<1) || (objects.begin()->size()<1)) return; iRect r = fig_range(objects); fig_object o; o.type=6; o.push_back(r.TLC()); o.push_back(r.BRC()); objects.insert(objects.begin(), o); o.type = -6; objects.insert(objects.end(), o); } // повернуть на угол a вокруг точки p0 void fig_rotate(std::list<fig_object> & objects, const double a, const iPoint & p0){ double c = cos(a); double s = sin(a); for (std::list<fig_object>::iterator l = objects.begin(); l!=objects.end(); l++){ for (fig_object::iterator p = l->begin(); p!=l->end(); p++){ double x = p->x-p0.x, y = p->y-p0.y; p->x = x*c - y*s + p0.x; p->y = x*s + y*c + p0.y; } if ((l->type == 4)||(l->type==1)) { l->angle += a; while (l->angle>M_PI) l->angle-=2*M_PI; } if (l->type == 1) { double x = l->center_x-p0.x, y = l->center_y-p0.y; l->center_x = x*c - y*s + p0.x; l->center_y = x*s + y*c + p0.y; } } } // преобразовать ломаную в сплайн void any2xspl(fig_object & o, const double x, const double y){ if (o.size()<3) return; if (o.is_polyline()){ if (o.sub_type==1) o.sub_type = 4; else if (o.sub_type==3) { //в замкнутой ломаной последняя точка совпадает с первой //в замкнутом сплайне - нет! if (o[0]==o[o.size()-1]) o.resize(o.size()-1); o.sub_type = 5; } else return; } else if (o.is_spline()) o.sub_type = o.sub_type%2+4; else return; // добавим точки в соответствии с параметром y // Если звено ломаной длиннее, чем 3y, добавим две точки на // расстоянии y от края. if (y>0){ fig_object::iterator i=o.begin(), j=i; j++; // у нас >3 точек, т.ч. все хорошо do{ double l = pdist(*i,*j); if (l > 3*y){ dPoint p = pnorm(*j-*i) * y; j=o.insert(j, *i + iPoint(p) ); j++; j=o.insert(j, *j - iPoint(p) ); j++; } i=j; j++; } while (j!=o.end()); } o.type = 3; o.f.clear(); - for (int j=0; j<o.size(); j++) o.f.push_back(x); + for (size_t j=0; j<o.size(); j++) o.f.push_back(x); if (o.sub_type==4){ o.f[0]=0; o.f[o.size()-1]=0; } return; } /// обрезка fig-файла по прямоугольнику void rect_crop(const iRect & cutter, std::list<fig_object> & objects){ std::list<fig_object>::iterator o = objects.begin(); while (o!=objects.end()){ iLine l = *o; ::rect_crop(cutter, l, o->is_closed() || (o->area_fill != -1)); o->set_points(l); if (o->size() == 0) o=objects.erase(o); else o++; } } /// Обрезка fig-объекта по прямоугольнику. Объект после обрезки. /// может не содержать точек, т.е. быть плохим с т.з. fig-а! void rect_crop(const iRect & cutter, fig_object & o){ iLine l = o; ::rect_crop(cutter, l, o.is_closed() || (o.area_fill != -1)); o.set_points(l); } } // namespace
ushakov/mapsoft
287070c435b804897851ac94d0972e7b77a0e932
core/geo_io: fix -Wparentheses warning
diff --git a/core/geo_io/io.cpp b/core/geo_io/io.cpp index ea2f375..67af982 100644 --- a/core/geo_io/io.cpp +++ b/core/geo_io/io.cpp @@ -1,201 +1,201 @@ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <cstring> #include <dirent.h> #include <vector> #include <list> #include <map> #include <sys/stat.h> #include <math.h> #include <zip.h> #include "io.h" #include "io_gps.h" #include "io_gu.h" #include "io_xml.h" #include "io_kml.h" #include "io_gpx.h" #include "io_oe.h" #include "io_js.h" #include "io_zip.h" #include "geofig.h" #include "err/err.h" #include "filetype/filetype.h" namespace io { using namespace std; int check_file(const string & name){ struct stat st_buf; if (stat(name.c_str(), &st_buf) != 0) return -1; if (S_ISREG(st_buf.st_mode)) return 0; if (S_ISCHR(st_buf.st_mode)) return 1; return -1; } std::string gps_detect(){ DIR *D = opendir("/sys/bus/usb-serial/drivers/garmin_gps"); if (!D) return ""; dirent * de; - while (de = readdir(D)){ + while ((de = readdir(D))){ if ((strlen(de->d_name) < 1) || (de->d_name[0] == '.')) continue; string fname = string("/dev/") + string(de->d_name); if (check_file(fname) == 1) return fname; } return ""; } void in(const string & in_name, geo_data & world, const Options & opt){ string name(in_name); bool v = opt.exists("verbose"); if (name == "gps:"){ name = gps_detect(); if (name == "") throw Err() << "Can't detect gps device"; } int c = check_file(name); if (c < 0) throw Err() << "Can't access file " << name; if (c == 1) return gps::get_all(name.c_str(), world, opt); if (testext(name, ".xml")) return xml::read_file (name.c_str(), world, opt); if (testext(name, ".gpx")) return gpx::read_file (name.c_str(), world, opt); if (testext(name, ".kml")) return kml::read_file (name.c_str(), world, opt); if (testext(name, ".gu")) return gu::read_file (name.c_str(), world, opt); if (testext(name, ".wpt") || testext(name, ".plt") || testext(name, ".map")) return oe::read_file (name.c_str(), world, opt); if (testext(name, ".zip") || testext(name, ".kmz")) return io_zip::read_file (name.c_str(), world, opt); if (testext(name, ".fig")){ if (v) cerr << "Reading data from Fig file " << name << endl; fig::fig_world F; fig::read(name.c_str(), F); g_map m=fig::get_ref(F); fig::get_wpts(F, m, world); fig::get_trks(F, m, world); fig::get_maps(F, m, world); return; } throw Err() << "Can't determine input format for file " << name; return; } void out(const string & out_name, geo_data const & world, const Options & opt){ string name(out_name); bool v = opt.exists("verbose"); if (name == "gps:"){ name = gps_detect(); if (name == "") throw Err() << "Can't detect gps device"; } // GPS device if (check_file(name) == 1) return gps::put_all (name.c_str(), world, opt); if (testext(name, ".xml")) return xml::write_file (name.c_str(), world, opt); if (testext(name, ".gpx")) return gpx::write_file (name.c_str(), world, opt); if (testext(name, ".js")) return js::write_file (name.c_str(), world, opt); // KML and KMZ formats if (testext(name, ".kml") || testext(name, ".kmz")){ string base(name.begin(), name.begin()+name.rfind('.')); string kml=base+"kml"; kml::write_file (kml.c_str(), world, opt); if (testext(name, ".kmz")){ vector<string> files; files.push_back(kml); io_zip::write_file(name.c_str(), files); } return; } // Garmin-Utils format if (testext(name, ".gu")) return gu::write_file (name.c_str(), world, opt); // OziExplorer format if ((testext(name, "wpt"))|| (testext(name, "plt"))|| (testext(name, "map"))|| (testext(name, "zip"))|| (testext(name, "oe"))){ string base(name.begin(), name.begin()+name.rfind('.')); vector<string> files; // number of files with tracks, waypoints and maps size_t wn = world.wpts.size(); size_t tn = world.trks.size(); size_t mn = world.maps.size(); int ww=0, tw=0, mw=0; if (wn > 1) ww = (int) floor (log (1.0 * wn) / log (10.0)) + 1; if (tn > 1) tw = (int) floor (log (1.0 * tn) / log (10.0)) + 1; if (mn > 1) mw = (int) floor (log (1.0 * mn) / log (10.0)) + 1; for (size_t n = 0; n < wn; ++n){ ostringstream oef; if (ww>0) oef << base << setw(ww) << setfill('0') << n+1 << ".wpt"; else oef << base << ".wpt"; oe::write_wpt_file (oef.str().c_str(), world.wpts[n], opt); if (v) cerr << " " << oef.str() << " -- " << world.wpts[n].size() << " waypoints\n"; files.push_back(oef.str()); } for (size_t n = 0; n < tn; ++n){ ostringstream oef; if (tw > 0) oef << base << setw(tw) << setfill('0') << n+1 << ".plt"; else oef << base << ".plt"; oe::write_plt_file (oef.str().c_str(), world.trks[n], opt); if (v) cerr << " " << oef.str() << " -- " << world.trks[n].size() << " points\n"; files.push_back(oef.str()); } for (size_t n = 0; n < mn; ++n){ size_t mmn = world.maps[n].size(); // map count in this maplist size_t mmw=0; if (mmn > 1) mmw = (size_t) floor (log (1.0 * mmn) / log (10.0)) + 1; for (size_t nn = 0; nn != mmn; ++nn) { ostringstream oef; oef << base; if (mw > 0) oef << setw(mw) << setfill('0') << n+1; if ((mmw > 0) && (mw > 0)) oef << "_"; if (mmw > 0) oef << setw(mmw) << setfill('0') << nn+1; oef << ".map"; oe::write_map_file (oef.str().c_str(), world.maps[n][nn], opt); if (v) cerr << " " << oef.str() << " -- " << world.maps[n][nn].size() << " reference points" << endl; files.push_back(oef.str()); } } if (testext (name, "zip")) io_zip::write_file(name.c_str(), files); return; } throw Err() << "Can't determine output format for file " << name; } } // namespace io
ushakov/mapsoft
4bbc860c4b67f405b0b5ba8f66282a9648c078e9
core/geo_io: fix error handling in io_zip
diff --git a/core/geo_io/io_zip.cpp b/core/geo_io/io_zip.cpp index 2beeb17..5806eff 100644 --- a/core/geo_io/io_zip.cpp +++ b/core/geo_io/io_zip.cpp @@ -1,108 +1,115 @@ #include <iostream> #include <fstream> #include <string> #include <cstring> #include <zip.h> #include "io.h" #include "io_zip.h" #include "err/err.h" namespace io_zip{ using namespace std; string modfname(string s) { string::size_type dir,l; l=s.length(); dir = s.rfind("/", l); if ( dir != string::npos ) s= s.substr(dir+1); const char *tmpdir = getenv("TMPDIR"); if (tmpdir) return string(tmpdir) + "/" + s; return string("/tmp/") + s; } void read_file(const char* filename, geo_data & world, const Options & opt) { struct zip *zip_file; struct zip_file *file_in_zip; const char* fzip_name; int err; int files_total; int r,i; char buffer[1]; string tmp; if (opt.exists("verbose")) cerr << "Reading ZIP file " << filename << endl; zip_file = zip_open(filename, 0, &err); if (!zip_file) throw Err() << "Can't open ZIP file " << filename << ": " << zip_strerror(zip_file); files_total = zip_get_num_files(zip_file); if (!files_total) { zip_close(zip_file); throw Err() << "Can't read ZIP file " << filename << ": " << zip_strerror(zip_file); } for (i = 0; i < files_total; i++) { + + fzip_name=zip_get_name(zip_file,i,0); + if (!fzip_name){ + zip_close(zip_file); + throw Err() << "Can't read ZIP file " + << filename << ": " << zip_strerror(zip_file); + } + file_in_zip = zip_fopen_index(zip_file, i, 0); if (!file_in_zip){ zip_close(zip_file); throw Err() << "Can't read file " << fzip_name << " from ZIP file " << filename << ": " << zip_strerror(zip_file); } - fzip_name=zip_get_name(zip_file,i,0); tmp = modfname(fzip_name); ofstream out(tmp.c_str()); while ( (r = zip_fread(file_in_zip, buffer, sizeof(buffer))) > 0) { out << buffer[0]; } out.close(); zip_fclose(file_in_zip); io::in(tmp,world,opt); if (remove(tmp.c_str())) { zip_close(zip_file); throw Err() << "Can't delete temp file "<< tmp; } } if (zip_close(zip_file)!=0) throw Err() << "Can't write data to ZIP file: " << zip_strerror(zip_file); } void write_file (const char* filename, const std::vector<std::string> & files, const Options & opt){ struct zip *Z; int err; if (opt.exists("verbose")) cerr << "Writing ZIP file " << filename << endl; remove(filename); Z = zip_open(filename, ZIP_CREATE, &err); if (!Z) throw Err() << "Can't open ZIP file " << filename << " for writing"; std::vector<std::string>::const_iterator f; for (f = files.begin(); f!=files.end(); f++){ struct zip_source *s = zip_source_file(Z, f->c_str(),0,0); if ((s == NULL) || (zip_add(Z, f->c_str(), s) < 0)) { zip_source_free(s); zip_close(Z); throw Err() << "Can't write data to ZIP file: " << zip_strerror(Z); } } if (zip_close(Z)!=0) throw Err() << "Can't write data to ZIP file: " << zip_strerror(Z); for (f = files.begin(); f!=files.end(); f++){ if (remove(f->c_str())){ throw Err() << "Can't delete temp file " << *f; } } } }//namespace
ushakov/mapsoft
a00ce3ab039360cce196e616d5fc18ae14c89851
core/geo_io: fix a few sign-compare warning
diff --git a/core/geo_io/geo_refs.cpp b/core/geo_io/geo_refs.cpp index e7b7bc4..fa73a13 100644 --- a/core/geo_io/geo_refs.cpp +++ b/core/geo_io/geo_refs.cpp @@ -1,345 +1,345 @@ // Привязки специальных карт и снимков #include "tiles/tiles.h" #include "geo_refs.h" #include "geo/geo_convs.h" #include "geo/geo_nom.h" #include "2d/line_utils.h" #include "err/err.h" #include <sstream> #include <iomanip> using namespace std; g_map mk_tmerc_ref(const dLine & points, double u_per_m, bool yswap){ g_map ref; if (points.size()<3){ cerr << "error in mk_tmerc_ref: number of points < 3\n"; return g_map(); } // Get refs. // Reduce border to 5 points, remove last one. dLine refs = points; refs.push_back(*refs.begin()); // to assure last=first refs = generalize(refs, -1, 5); refs.resize(4); // Create tmerc->lonlat tmerc conversion with wanted lon0, // convert refs to our map coordinates. Options PrO; PrO.put<double>("lon0", convs::lon2lon0(points.center().x)); convs::pt2wgs cnv(Datum("wgs84"), Proj("tmerc"), PrO); dLine refs_c(refs); cnv.line_bck_p2p(refs_c); refs_c *= u_per_m; // to out units refs_c -= refs_c.range().TLC(); double h = refs_c.range().h; // swap y if needed if (yswap){ - for (int i=0;i<refs_c.size();i++) + for (size_t i=0;i<refs_c.size();i++) refs_c[i].y = h - refs_c[i].y; } // add refpoints to our map - for (int i=0;i<refs.size();i++){ + for (size_t i=0;i<refs.size();i++){ ref.push_back(g_refpoint(refs[i], refs_c[i])); } ref.map_proj=Proj("tmerc"); ref.proj_opts.put("lon0", convs::lon2lon0(refs.range().CNT().x)); // Now we need to convert border to map units. // We can convert them by the same way as refs, but // this is unnecessary duplicating of non-trivial code. // So we constract map2pt conversion from our map. // Set map border convs::map2wgs brd_cnv(ref); ref.border = brd_cnv.line_bck(points); ref.border.push_back(*ref.border.begin()); // to assure last=first ref.border = generalize(ref.border, 1000, -1); // 1 unit accuracy ref.border.resize(ref.border.size()-1); return ref; } void incompat_warning(const Options & o, const string & o1, const string & o2){ if (o.exists(o2)) cerr << "make reference warning: " << "skipping option --" << o2 << "\n" <<" which is incompatable with --" << o1 << "\n"; } vector<int> read_int_vec(const string & str){ istringstream s(str); char sep; int x; vector<int> ret; while (1){ s >> ws >> x; if (!s.fail()){ ret.push_back(x); s >> ws; } if (s.eof()) return ret; s >> ws >> sep; if (sep!=','){ cerr << "error while reading comma separated values\n"; return ret; } } } g_map mk_ref(Options & o){ g_map ret; // default values double dpi=300; double rscale=100000; Datum datum("wgs84"); Proj proj("tmerc"); bool verbose=o.exists("verbose"); bool sw=!o.exists("swap_y"); // first step: process geom, nom, google options // -- create border and 4 refpoints in wgs84 lonlat // -- set map_proj and proj options // -- change defauld dpi and rscale if needed dRect geom; dLine refs; Options proj_opts; // rectangular map if (o.exists("geom")){ incompat_warning (o, "geom", "wgs_geom"); incompat_warning (o, "geom", "wgs_brd"); incompat_warning (o, "geom", "trk_brd"); incompat_warning (o, "geom", "nom"); incompat_warning (o, "geom", "google");\ dRect geom = o.get<dRect>("geom"); if (geom.empty()) throw Err() << "error: bad geometry"; datum = o.get<Datum>("datum", Datum("pulkovo")); proj = o.get<Proj>("proj", Proj("tmerc")); if ((proj == Proj("tmerc")) && (geom.x>=1e6)){ double lon0 = convs::lon_pref2lon0(geom.x); geom.x = convs::lon_delprefix(geom.x); proj_opts.put<double>("lon0", lon0); } if (o.exists("lon0")) proj_opts.put("lon0", o.get<double>("lon0")); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), datum, proj, proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); ret.border = cnv.line_bck(refs, 1e-6); refs.resize(4); cnv.line_bck_p2p(refs); } else if (o.exists("wgs_geom")){ incompat_warning (o, "wgs_geom", "geom"); incompat_warning (o, "wgs_geom", "wgs_brd"); incompat_warning (o, "wgs_geom", "trk_brd"); incompat_warning (o, "wgs_geom", "nom"); incompat_warning (o, "wgs_geom", "google");\ dRect geom = o.get<dRect>("wgs_geom"); if (geom.empty()) throw Err() << "error: bad geometry"; proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(geom.x+geom.w/2))); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), Datum("wgs84"), proj, proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); refs.resize(4); // border is set to be rectanglar in proj: ret.border = cnv.line_bck(rect2line(cnv.bb_frw(geom, 1e-6), true, sw), 1e-6); } else if (o.exists("wgs_brd")){ incompat_warning (o, "wgs_brd", "geom"); incompat_warning (o, "wgs_brd", "wgs_geom"); incompat_warning (o, "wgs_brd", "trk_brd"); incompat_warning (o, "wgs_brd", "nom"); incompat_warning (o, "wgs_brd", "google");\ ret.border = o.get<dLine>("wgs_brd"); if (ret.border.size()<3) throw Err() << "error: bad border line"; ret.border.push_back(ret.border[0]); proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(ret.border.range().CNT().x))); if (verbose) cerr << "mk_ref: brd = " << ret.border << "\n"; refs = generalize(ret.border, -1, 5); // 5pt refs.resize(4); } else if (o.exists("trk_brd")){ incompat_warning (o, "trk_brd", "geom"); incompat_warning (o, "trk_brd", "wgs_geom"); incompat_warning (o, "trk_brd", "wgs_brd"); incompat_warning (o, "trk_brd", "nom"); incompat_warning (o, "trk_brd", "google");\ geo_data W; io::in(o.get<string>("trk_brd"), W); if (W.trks.size()<1) throw Err() << "error: file with a track is expected in trk_brd option"; ret.border = W.trks[0]; if (ret.border.size()<3) throw Err() << "error: bad border line"; ret.border.push_back(ret.border[0]); proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(ret.border.range().CNT().x))); if (verbose) cerr << "mk_ref: brd = " << ret.border << "\n"; refs = generalize(ret.border, -1, 5); // 5pt refs.resize(4); } // nom map else if (o.exists("nom")){ incompat_warning (o, "nom", "geom"); incompat_warning (o, "nom", "wgs_geom"); incompat_warning (o, "nom", "wgs_brd"); incompat_warning (o, "nom", "trk_brd"); incompat_warning (o, "nom", "google"); proj=Proj("tmerc"); datum=Datum("pulkovo"); int rs; string name=o.get<string>("nom", string()); dRect geom = convs::nom_to_range(name, rs); if (geom.empty()) throw Err() << "error: can't get geometry for map name \"" << name << "\""; rscale = rs; double lon0 = convs::lon2lon0(geom.x+geom.w/2.0); proj_opts.put("lon0", lon0); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), datum, Proj("lonlat"), proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); ret.border = cnv.line_bck(refs, 1e-6); refs.resize(4); cnv.line_bck_p2p(refs); } // google tile else if (o.exists("google")){ incompat_warning (o, "google", "geom"); incompat_warning (o, "google", "wgs_geom"); incompat_warning (o, "google", "wgs_brd"); incompat_warning (o, "google", "trk_brd"); incompat_warning (o, "google", "nom"); datum=Datum("wgs84"); proj=Proj("google"); vector<int> crd = read_int_vec(o.get<string>("google")); if (crd.size()!=3) throw Err() << "error: wrong --google coordinates"; int x=crd[0]; int y=crd[1]; int z=crd[2]; // Tiles tcalc; dRect geom = tcalc.gtile_to_range(x,y,z); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true,sw); ret.border = refs; refs.resize(4); dpi=o.get<double>("dpi", dpi); // Change DPI relative to the base level if (z < 14) dpi /= 1 << (14 - z); if (z > 14) dpi *= 1 << (z - 14); rscale = dpi * tcalc.px2m(z) * 100 / 2.54; o.put("dpi", dpi); o.put("rscale", rscale); } else throw Err() << "error: can't make map reference without" << " --geom or --nom or --google setting"; ret.map_proj=proj; ret.map_datum=datum; ret.proj_opts=proj_opts; // step 2: calculate conversion coeff between map proj units and // output map points rscale=o.get<double>("rscale", rscale); if (o.get<string>("dpi", "") == "fig") dpi= 1200/1.05; else dpi=o.get<double>("dpi", dpi); dpi*=o.get<double>("mag", 1.0); // put real dpi and rscale back to options o.put("dpi", dpi); o.put("rscale", rscale); double k = 100.0/2.54 * dpi / rscale; if (verbose) cerr << "mk_ref: rscale = " << rscale << ", dpi = " << dpi << ", k = " << k << "\n"; // step 3: setting refpoints convs::pt2wgs cnv(datum, proj, proj_opts); dLine refs_r(refs); cnv.line_bck_p2p(refs_r); refs_r *= k; // to out units refs_r -= refs_r.range().TLC(); double h = refs_r.range().h; // swap y if needed if (sw) - for (int i=0;i<refs_r.size();i++) + for (size_t i=0;i<refs_r.size();i++) refs_r[i].y = h - refs_r[i].y; // add refpoints to our map - for (int i=0;i<refs.size();i++) + for (size_t i=0;i<refs.size();i++) ret.push_back(g_refpoint(refs[i], refs_r[i])); // step 3: converting border convs::map2wgs brd_cnv(ret); ret.border = brd_cnv.line_bck(ret.border); ret.border = generalize(ret.border, 1, -1); // 1 unit accuracy ret.border.resize(ret.border.size()-1); return ret; } diff --git a/core/geo_io/io.cpp b/core/geo_io/io.cpp index 11040d5..ea2f375 100644 --- a/core/geo_io/io.cpp +++ b/core/geo_io/io.cpp @@ -1,201 +1,201 @@ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <cstring> #include <dirent.h> #include <vector> #include <list> #include <map> #include <sys/stat.h> #include <math.h> #include <zip.h> #include "io.h" #include "io_gps.h" #include "io_gu.h" #include "io_xml.h" #include "io_kml.h" #include "io_gpx.h" #include "io_oe.h" #include "io_js.h" #include "io_zip.h" #include "geofig.h" #include "err/err.h" #include "filetype/filetype.h" namespace io { using namespace std; int check_file(const string & name){ struct stat st_buf; if (stat(name.c_str(), &st_buf) != 0) return -1; if (S_ISREG(st_buf.st_mode)) return 0; if (S_ISCHR(st_buf.st_mode)) return 1; return -1; } std::string gps_detect(){ DIR *D = opendir("/sys/bus/usb-serial/drivers/garmin_gps"); if (!D) return ""; dirent * de; while (de = readdir(D)){ if ((strlen(de->d_name) < 1) || (de->d_name[0] == '.')) continue; string fname = string("/dev/") + string(de->d_name); if (check_file(fname) == 1) return fname; } return ""; } void in(const string & in_name, geo_data & world, const Options & opt){ string name(in_name); bool v = opt.exists("verbose"); if (name == "gps:"){ name = gps_detect(); if (name == "") throw Err() << "Can't detect gps device"; } int c = check_file(name); if (c < 0) throw Err() << "Can't access file " << name; if (c == 1) return gps::get_all(name.c_str(), world, opt); if (testext(name, ".xml")) return xml::read_file (name.c_str(), world, opt); if (testext(name, ".gpx")) return gpx::read_file (name.c_str(), world, opt); if (testext(name, ".kml")) return kml::read_file (name.c_str(), world, opt); if (testext(name, ".gu")) return gu::read_file (name.c_str(), world, opt); if (testext(name, ".wpt") || testext(name, ".plt") || testext(name, ".map")) return oe::read_file (name.c_str(), world, opt); if (testext(name, ".zip") || testext(name, ".kmz")) return io_zip::read_file (name.c_str(), world, opt); if (testext(name, ".fig")){ if (v) cerr << "Reading data from Fig file " << name << endl; fig::fig_world F; fig::read(name.c_str(), F); g_map m=fig::get_ref(F); fig::get_wpts(F, m, world); fig::get_trks(F, m, world); fig::get_maps(F, m, world); return; } throw Err() << "Can't determine input format for file " << name; return; } void out(const string & out_name, geo_data const & world, const Options & opt){ string name(out_name); bool v = opt.exists("verbose"); if (name == "gps:"){ name = gps_detect(); if (name == "") throw Err() << "Can't detect gps device"; } // GPS device if (check_file(name) == 1) return gps::put_all (name.c_str(), world, opt); if (testext(name, ".xml")) return xml::write_file (name.c_str(), world, opt); if (testext(name, ".gpx")) return gpx::write_file (name.c_str(), world, opt); if (testext(name, ".js")) return js::write_file (name.c_str(), world, opt); // KML and KMZ formats if (testext(name, ".kml") || testext(name, ".kmz")){ string base(name.begin(), name.begin()+name.rfind('.')); string kml=base+"kml"; kml::write_file (kml.c_str(), world, opt); if (testext(name, ".kmz")){ vector<string> files; files.push_back(kml); io_zip::write_file(name.c_str(), files); } return; } // Garmin-Utils format if (testext(name, ".gu")) return gu::write_file (name.c_str(), world, opt); // OziExplorer format if ((testext(name, "wpt"))|| (testext(name, "plt"))|| (testext(name, "map"))|| (testext(name, "zip"))|| (testext(name, "oe"))){ string base(name.begin(), name.begin()+name.rfind('.')); vector<string> files; // number of files with tracks, waypoints and maps - int wn = world.wpts.size(); - int tn = world.trks.size(); - int mn = world.maps.size(); + size_t wn = world.wpts.size(); + size_t tn = world.trks.size(); + size_t mn = world.maps.size(); int ww=0, tw=0, mw=0; if (wn > 1) ww = (int) floor (log (1.0 * wn) / log (10.0)) + 1; if (tn > 1) tw = (int) floor (log (1.0 * tn) / log (10.0)) + 1; if (mn > 1) mw = (int) floor (log (1.0 * mn) / log (10.0)) + 1; for (size_t n = 0; n < wn; ++n){ ostringstream oef; if (ww>0) oef << base << setw(ww) << setfill('0') << n+1 << ".wpt"; else oef << base << ".wpt"; oe::write_wpt_file (oef.str().c_str(), world.wpts[n], opt); if (v) cerr << " " << oef.str() << " -- " << world.wpts[n].size() << " waypoints\n"; files.push_back(oef.str()); } for (size_t n = 0; n < tn; ++n){ ostringstream oef; if (tw > 0) oef << base << setw(tw) << setfill('0') << n+1 << ".plt"; else oef << base << ".plt"; oe::write_plt_file (oef.str().c_str(), world.trks[n], opt); if (v) cerr << " " << oef.str() << " -- " << world.trks[n].size() << " points\n"; files.push_back(oef.str()); } for (size_t n = 0; n < mn; ++n){ - int mmn = world.maps[n].size(); // map count in this maplist - int mmw=0; - if (mmn > 1) mmw = (int) floor (log (1.0 * mmn) / log (10.0)) + 1; + size_t mmn = world.maps[n].size(); // map count in this maplist + size_t mmw=0; + if (mmn > 1) mmw = (size_t) floor (log (1.0 * mmn) / log (10.0)) + 1; for (size_t nn = 0; nn != mmn; ++nn) { ostringstream oef; oef << base; if (mw > 0) oef << setw(mw) << setfill('0') << n+1; if ((mmw > 0) && (mw > 0)) oef << "_"; if (mmw > 0) oef << setw(mmw) << setfill('0') << nn+1; oef << ".map"; oe::write_map_file (oef.str().c_str(), world.maps[n][nn], opt); if (v) cerr << " " << oef.str() << " -- " << world.maps[n][nn].size() << " reference points" << endl; files.push_back(oef.str()); } } if (testext (name, "zip")) io_zip::write_file(name.c_str(), files); return; } throw Err() << "Can't determine output format for file " << name; } } // namespace io diff --git a/core/geo_io/io_gpx.cpp b/core/geo_io/io_gpx.cpp index 18b15fb..438e114 100644 --- a/core/geo_io/io_gpx.cpp +++ b/core/geo_io/io_gpx.cpp @@ -1,305 +1,305 @@ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include "io_gpx.h" #include <libxml/xmlreader.h> #include <cstring> #include "err/err.h" namespace gpx { using namespace std; void write_file (const char* filename, const geo_data & world, const Options & opt){ ofstream f(filename); if (opt.exists("verbose")) cerr << "Writing data to GPX file " << filename << endl; if (!f.good()) throw Err() << "Can't open file " << filename << " for writing"; f << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; f << "<gpx xmlns=\"http://www.topografix.com/GPX/1/1\">" << endl; - for (int i = 0; i < world.wpts.size(); i++) { + for (size_t i = 0; i < world.wpts.size(); i++) { for (g_waypoint_list::const_iterator wp = world.wpts[i].begin(); wp != world.wpts[i].end(); ++wp) { f << fixed << setprecision(6) << "<wpt lat=\"" << wp->y << "\" lon=\"" << wp->x << "\">" << endl << setprecision(1) << " <ele>" << wp->z << "</ele>" << endl << " <name>" << wp->name << "</name>" << endl << " <cmt>" << wp->comm << "</cmt>" << endl << " <time>" << wp->t.gpx_str() << "</time>" << endl << "</wpt>" << endl; } } - for (int i = 0; i < world.trks.size(); ++i) { + for (size_t i = 0; i < world.trks.size(); ++i) { f << " <trk>" << endl; f << " <name>" << world.trks[i].comm << "</name>" << endl; for (g_track::const_iterator tp = world.trks[i].begin(); tp != world.trks[i].end(); ++tp) { if (tp->start || tp == world.trks[i].begin()) { if (tp != world.trks[i].begin()) { f << " </trkseg>" << endl; } f << " <trkseg>" << endl; } f << fixed << setprecision(6) << " <trkpt lat=\"" << tp->y << "\" lon=\"" << tp->x << "\">" << endl << setprecision(1) << " <ele>" << tp->z << "</ele>" << endl << " <time>" << tp->t.gpx_str() << "</time>" << endl << " </trkpt>" << endl; } f << " </trkseg>" << endl; f << " </trk>" << endl; } f << "</gpx>" << endl; if (!f.good()) throw Err() << "Can't write to file " << filename; } #define TYPE_ELEM 1 #define TYPE_ELEM_END 15 #define TYPE_TEXT 3 #define TYPE_SWS 14 #define NAMECMP(x) (xmlStrcasecmp(name,(const xmlChar *)x)==0) #define GETATTR(x) (const char *)xmlTextReaderGetAttribute(reader, (const xmlChar *)x) #define GETVAL (const char *)xmlTextReaderConstValue(reader) int read_wpt_node(xmlTextReaderPtr reader, geo_data & world){ g_waypoint wpt; bool is_ele = false, is_name=false, is_comm=false, is_time=false; wpt.y = atof(GETATTR("lat")); wpt.x = atof(GETATTR("lon")); while(1){ int ret =xmlTextReaderRead(reader); if (ret != 1) return ret; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("ele")){ if (type == TYPE_ELEM) is_ele = true; if (type == TYPE_ELEM_END) is_ele = false; } else if (NAMECMP("name")){ if (type == TYPE_ELEM) is_name = true; if (type == TYPE_ELEM_END) is_name = false; } else if (NAMECMP("comm")){ if (type == TYPE_ELEM) is_comm = true; if (type == TYPE_ELEM_END) is_comm = false; } else if (NAMECMP("time")){ if (type == TYPE_ELEM) is_time = true; if (type == TYPE_ELEM_END) is_time = false; } else if (type == TYPE_TEXT){ if (is_ele) wpt.z = atof(GETVAL); if (is_name) wpt.name = GETVAL; if (is_comm) wpt.comm = GETVAL; if (is_time) wpt.t = boost::lexical_cast<Time>(GETVAL); } else if (NAMECMP("wpt") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in wpt (type: " << type << ")\n"; } } if (world.wpts.size()<1) world.wpts.push_back(g_waypoint_list()); world.wpts.back().push_back(wpt); return 1; } int read_trkpt_node(xmlTextReaderPtr reader, g_track & trk, bool start){ g_trackpoint pt; bool is_ele = false, is_time=false; pt.y = atof(GETATTR("lat")); pt.x = atof(GETATTR("lon")); while(1){ int ret =xmlTextReaderRead(reader); if (ret != 1) return ret; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("ele")){ if (type == TYPE_ELEM) is_ele = true; if (type == TYPE_ELEM_END) is_ele = false; } else if (NAMECMP("time")){ if (type == TYPE_ELEM) is_time = true; if (type == TYPE_ELEM_END) is_time = false; } else if (type == TYPE_TEXT){ if (is_ele) pt.z = atof(GETVAL); if (is_time) pt.t = boost::lexical_cast<Time>(GETVAL); } else if (NAMECMP("trkpt") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in trkpt (type: " << type << ")\n"; } } pt.start = start; trk.push_back(pt); return 1; } int read_trkseg_node(xmlTextReaderPtr reader, g_track & trk){ bool start=true; while(1){ int ret =xmlTextReaderRead(reader); if (ret != 1) return ret; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("trkpt") && (type == TYPE_ELEM)){ ret = read_trkpt_node(reader, trk, start); if (ret != 1) return ret; start=false; } else if (NAMECMP("trkseg") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in trkseg (type: " << type << ")\n"; } } return 1; } int read_trk_node(xmlTextReaderPtr reader, geo_data & world){ g_track trk; bool is_name=false; while(1){ int ret =xmlTextReaderRead(reader); if (ret != 1) return ret; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("trkseg") && (type == TYPE_ELEM)){ ret=read_trkseg_node(reader, trk); if (ret != 1) return ret; } else if (NAMECMP("name")){ if (type == TYPE_ELEM) is_name = true; if (type == TYPE_ELEM_END) is_name = false; } else if (type == TYPE_TEXT){ if (is_name) trk.comm = GETVAL; } else if (NAMECMP("trk") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in trk (type: " << type << ")\n"; } } world.trks.push_back(trk); return 1; } int read_gpx_node(xmlTextReaderPtr reader, geo_data & world){ bool is_meta=false; while(1){ int ret =xmlTextReaderRead(reader); if (ret != 1) return ret; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("metadata")){ if (type == TYPE_ELEM) is_meta=true; if (type == TYPE_ELEM_END) is_meta=false; } else if (is_meta) continue; else if (NAMECMP("wpt") && (type == TYPE_ELEM)){ ret=read_wpt_node(reader, world); if (ret != 1) return ret; } else if (NAMECMP("trk") && (type == TYPE_ELEM)){ ret=read_trk_node(reader, world); if (ret != 1) return ret; } else if (NAMECMP("gpx") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in gpx (type: " << type << ")\n"; } } return 1; } void read_file(const char* filename, geo_data & world, const Options & opt) { LIBXML_TEST_VERSION if (opt.exists("verbose")) cerr << "Reading data from GPX file " << filename << endl; xmlTextReaderPtr reader; int ret; reader = xmlReaderForFile(filename, NULL, 0); if (reader == NULL) throw Err() << "Can't open file " << filename << " for reading"; // parse file while (1){ ret = xmlTextReaderRead(reader); if (ret!=1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (NAMECMP("gpx") && (type == TYPE_ELEM)) ret = read_gpx_node(reader, world); if (ret!=1) break; } // free resources xmlFreeTextReader(reader); if (ret != 0) throw Err() << "Can't parse GPX file " << filename; xmlCleanupParser(); xmlMemoryDump(); } } // namespace diff --git a/core/geo_io/io_js.cpp b/core/geo_io/io_js.cpp index f9ea66c..59569d4 100644 --- a/core/geo_io/io_js.cpp +++ b/core/geo_io/io_js.cpp @@ -1,103 +1,103 @@ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include "io_js.h" #include <cstring> #include "err/err.h" namespace js { using namespace std; /* see: * http://geojson.org/ * https://tools.ietf.org/html/rfc7946 * https://leafletjs.com/examples/geojson/ */ void write_file (const char* filename, const geo_data & world, const Options & opt){ ofstream f(filename); if (opt.exists("verbose")) cerr << "Writing data to JS file " << filename << endl; if (!f.good()) throw Err() << "Can't open file " << filename << " for writing"; // write some information dRect rng = world.range(); f << "geojson_data_cnt=[" << fixed << setprecision(6) << rng.CNT().x << "," << rng.CNT().y << "];\n"; f << "geojson_data_tlc=[" << fixed << setprecision(6) << rng.TLC().x << "," << rng.TLC().y << "];\n"; f << "geojson_data_brc=[" << fixed << setprecision(6) << rng.BRC().x << "," << rng.BRC().y << "];\n"; // start a FeatureCollection f << "geojson_data={\"type\": \"FeatureCollection\", \"features\": [\n"; bool first_feature=true; // first-feature marker // tracks // Each track is a feature with MultiLineString objects. // First we write tracks to have them below points on leaflet maps. - for (int i = 0; i < world.trks.size(); ++i) { + for (size_t i = 0; i < world.trks.size(); ++i) { if (!first_feature) f << ",\n"; f << " { \"type\": \"Feature\",\n" << " \"properties\": {\n" << " \"name\": \"" << world.trks[i].comm << "\"\n" << " },\n" << " \"geometry\": {\n" << " \"type\":\"MultiLineString\",\n" << " \"coordinates\":[\n" << " ["; for (g_track::const_iterator tp = world.trks[i].begin(); tp != world.trks[i].end(); ++tp) { if (tp != world.trks[i].begin()) f << (tp->start? "],\n [":","); f << fixed << setprecision(6) << "[" << tp->x << "," << tp->y << "]"; } f << "]\n"; f << " ]\n" << " }\n" << " }"; first_feature=false; } // waypoints - for (int i = 0; i < world.wpts.size(); i++) { + for (size_t i = 0; i < world.wpts.size(); i++) { for (g_waypoint_list::const_iterator wp = world.wpts[i].begin(); wp != world.wpts[i].end(); ++wp) { if (!first_feature) f << ",\n"; f << " { \"type\": \"Feature\",\n" << " \"properties\": {\n" << " \"name\": \"" << wp->name << "\",\n" << " \"cmt\": \"" << wp->comm << "\",\n" << " \"ele\": \"" << fixed << setprecision(1) << wp->z << "\",\n" << " \"time\": \"" << wp->t.gpx_str() << "\"\n" << " },\n" << " \"geometry\": {\n" << " \"type\": \"Point\",\n" << " \"coordinates\": [" << fixed << setprecision(6) << wp->x << "," << wp->y << "]\n" << " }\n" << " }"; first_feature=false; } } // close FeatureCollection f << "\n]};\n"; if (!f.good()) throw Err() << "Can't write to file " << filename; } void read_file(const char* filename, geo_data & world, const Options & opt) { throw Err() << "Reading is not supported"; } } // namespace diff --git a/core/geo_io/io_kml.cpp b/core/geo_io/io_kml.cpp index 19f9c0c..bf4f5cf 100644 --- a/core/geo_io/io_kml.cpp +++ b/core/geo_io/io_kml.cpp @@ -1,556 +1,556 @@ #include <fstream> #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <string> #include <map> #include <libxml/xmlreader.h> #include "io_kml.h" #include <math.h> #include "err/err.h" namespace kml { using namespace std; // Записывает в KML-файл треки и точки // Не записывает карты! (хм, а может, надо?) void write_file (const char* filename, const geo_data & world, const Options & opt){ if (opt.exists("verbose")) cerr << "Writing data to KML file " << filename << endl; ofstream f(filename); if (!f.good()) throw Err() << "Can't open KML file " << filename << " for writing"; f << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; f << "<kml xmlns=\"http://earth.google.com/kml/2.1\">" << endl; f << " <Document>" << endl; - for (int i = 0; i < world.wpts.size(); i++) { + for (size_t i = 0; i < world.wpts.size(); i++) { f << " <Folder>" << endl; f << " <name>WPTS_" << i << "</name>" << endl; g_waypoint_list::const_iterator wp; for (wp = world.wpts[i].begin(); wp != world.wpts[i].end(); ++wp) { f << " <Placemark>" << endl; f << " <name><![CDATA[" << wp->name << "]]></name>" << endl; f << " <description><![CDATA[" << wp->comm << "]]></description>" << endl; f << " <Point>" << endl; f << fixed << setprecision(6) << " <coordinates>" << wp->x << "," << wp->y << "," << setprecision(1) << wp->z << "</coordinates>" << endl; f << " </Point>" << endl; f << " </Placemark>" << endl; } f << " </Folder>" << endl; } - for (int i = 0; i < world.trks.size(); ++i) { + for (size_t i = 0; i < world.trks.size(); ++i) { f << " <Placemark>" << endl; f << " <description><![CDATA[" << world.trks[i].comm << "]]></description>" << endl; f << " <MultiGeometry>" << endl; g_track::const_iterator tp; string linename; for (tp = world.trks[i].begin(); tp != world.trks[i].end(); ++tp) { linename = world.trks[i].type==trkType("closed")? "Polygon":"LineString"; if (tp->start || tp == world.trks[i].begin()) { if (tp != world.trks[i].begin()) { f << " </coordinates>" << endl; f << " </" << linename << ">" << endl; } f << " <" << linename << ">" << endl; f << " <tessellate>1</tessellate>" << endl; f << " <coordinates>" << endl; } f << fixed << setprecision(6) << " " << tp->x << "," << tp->y << "," << setprecision(1) << tp->z << endl; } f << " </coordinates>" << endl; f << " </" << linename << ">" << endl; f << " </MultiGeometry>" << endl; f << " </Placemark>" << endl; } f << " </Document>" << endl; f << "</kml>" << endl; if (!f.good()) throw Err() << "Can't write data to KML file " << filename; } #define TYPE_ELEM 1 #define TYPE_ELEM_END 15 #define TYPE_TEXT 3 #define TYPE_CDATA 4 #define TYPE_SWS 14 #define NAMECMP(x) (xmlStrcasecmp(name,(const xmlChar *)x)==0) #define GETATTR(x) (const char *)xmlTextReaderGetAttribute(reader, (const xmlChar *)x) #define GETVAL (const char *)xmlTextReaderConstValue(reader) int read_text_node(xmlTextReaderPtr reader, const char * nn, string & str){ int ret=1; str.clear(); while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (type == TYPE_TEXT || type == TYPE_CDATA) str += GETVAL; else if (NAMECMP(nn) && (type == TYPE_ELEM_END)) break; else cerr << "Warning: Unknown node \"" << name << "\" in text node (type: " << type << ")\n"; } return ret; } int read_point_node(xmlTextReaderPtr reader, g_waypoint & ww){ int ret=1; while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("coordinates") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "coordinates", str); if (ret != 1) break; char s1,s2; istringstream s(str); s >> std::ws >> ww.x >> std::ws >> s1 >> std::ws >> ww.y >> std::ws >> s2 >> std::ws >> ww.z >> std::ws; if (s1!=',' || s2!=','){ cerr << "Warning: Coord error\n"; ret=0; break; } } else if (NAMECMP("Point") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in Point (type: " << type << ")\n"; } } return ret; } int read_linestring_node(xmlTextReaderPtr reader, g_track & T){ int ret=1; while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("tessellate") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "tessellate", str); if (ret != 1) break; } else if (NAMECMP("coordinates") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "coordinates", str); if (ret != 1) break; char s1,s2; istringstream s(str); g_trackpoint tp; tp.start=true; while (!s.eof()){ s >> std::ws >> tp.x >> std::ws >> s1 >> std::ws >> tp.y >> std::ws >> s2 >> std::ws >> tp.z >> std::ws; if (s1!=',' || s2!=','){ cerr << "Warning: Coord error\n"; break; } T.push_back(tp); tp.start=false; } } else if (NAMECMP("LineString") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in LineString (type: " << type << ")\n"; } } return ret; } /* same as Linestring, but for closed lines */ int read_polygon_node(xmlTextReaderPtr reader, g_track & T){ int ret=1; T.type=trkType("closed"); while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("tessellate") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "tessellate", str); if (ret != 1) break; } else if (NAMECMP("coordinates") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "coordinates", str); if (ret != 1) break; char s1,s2; istringstream s(str); g_trackpoint tp; tp.start=true; while (!s.eof()){ s >> std::ws >> tp.x >> std::ws >> s1 >> std::ws >> tp.y >> std::ws >> s2 >> std::ws >> tp.z >> std::ws; if (s1!=',' || s2!=','){ cerr << "Warning: Coord error\n"; break; } T.push_back(tp); tp.start=false; } } else if (NAMECMP("Polygon") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in Polygon (type: " << type << ")\n"; } } return ret; } int read_gx_track_node(xmlTextReaderPtr reader, g_track & T){ int ret=1; T = g_track(); while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("when") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "when", str); if (ret != 1) break; } else if (NAMECMP("gx:coord") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "gx:coord", str); if (ret != 1) break; istringstream s(str); g_trackpoint tp; s >> std::ws >> tp.x >> std::ws >> std::ws >> tp.y >> std::ws >> std::ws >> tp.z >> std::ws; T.push_back(tp); } else if (NAMECMP("gx:Track") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in gx:Track (type: " << type << ")\n"; } } if (T.size()) T[0].start=true; return ret; } int read_multigeometry_node(xmlTextReaderPtr reader, g_track & T){ int ret=1; while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("LineString") && (type == TYPE_ELEM)){ ret=read_linestring_node(reader, T); if (ret != 1) break; } else if (NAMECMP("Polygon") && (type == TYPE_ELEM)){ ret=read_polygon_node(reader, T); if (ret != 1) break; } else if (NAMECMP("MultiGeometry") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in MultiGeometry (type: " << type << ")\n"; } } return ret; } int read_placemark_node(xmlTextReaderPtr reader, g_waypoint_list & W, g_track & T, g_map_list & M){ g_waypoint ww; g_map mm; T = g_track(); int ot=-1; bool skip=false; int ret=1; while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; // Skip some blocks else if (NAMECMP("Camera") || NAMECMP("LookAt") || NAMECMP("styleUrl") || NAMECMP("visibility")){ if (type == TYPE_ELEM) skip=true; if (type == TYPE_ELEM_END) skip=false; } else if (skip) continue; else if (NAMECMP("name") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "name", str); if (ret != 1) break; ww.name += str; T.comm += str; mm.comm += str; } else if (NAMECMP("description") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "description", str); if (ret != 1) break; ww.comm += str; T.comm += str; mm.comm += str; } // else if (NAMECMP("TimeStamp") && (type == TYPE_ELEM)){ // } else if (NAMECMP("Point") && (type == TYPE_ELEM)){ ot=0; ret=read_point_node(reader, ww); if (ret != 1) break; } else if (NAMECMP("LineString") && (type == TYPE_ELEM)){ ot=1; ret=read_linestring_node(reader, T); if (ret != 1) break; } else if (NAMECMP("Polygon") && (type == TYPE_ELEM)){ ot=1; ret=read_polygon_node(reader, T); if (ret != 1) break; } else if (NAMECMP("MultiGeometry") && (type == TYPE_ELEM)){ ot=1; ret=read_multigeometry_node(reader, T); if (ret != 1) break; } else if (NAMECMP("gx:Track") && (type == TYPE_ELEM)){ ot=1; ret=read_gx_track_node(reader, T); if (ret != 1) break; } else if (NAMECMP("Placemark") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in Placemark (type: " << type << ")\n"; } } if (ot==0) W.push_back(ww); return ret; } int read_folder_node(xmlTextReaderPtr reader, geo_data & world){ // similar to document node g_waypoint_list W; g_track T; g_map_list M; bool skip=false; int ret=1; while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("visibility") || NAMECMP("open")){ if (type == TYPE_ELEM) skip=true; if (type == TYPE_ELEM_END) skip=false; } else if (skip) continue; else if (NAMECMP("name") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "name", str); if (ret != 1) break; W.comm = T.comm = M.comm = str; } else if (NAMECMP("Placemark") && (type == TYPE_ELEM)){ ret=read_placemark_node(reader, W, T, M); if (T.size()) world.trks.push_back(T); if (ret != 1) break; } else if (NAMECMP("Folder") && (type == TYPE_ELEM)){ ret=read_folder_node(reader, world); if (ret != 1) break; } else if (NAMECMP("Folder") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in Folder (type: " << type << ")\n"; } } if (W.size()) world.wpts.push_back(W); if (M.size()) world.maps.push_back(M); return ret; } int read_document_node(xmlTextReaderPtr reader, geo_data & world){ bool skip=false; g_waypoint_list W; g_track T; g_map_list M; int ret=1; while(1){ ret =xmlTextReaderRead(reader); if (ret != 1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; // Skip some blocks else if (NAMECMP("Style") || NAMECMP("StyleMap") || NAMECMP("open") || NAMECMP("visibility") || NAMECMP("name") || NAMECMP("Snippet") || NAMECMP("LookAt")){ if (type == TYPE_ELEM) skip=true; if (type == TYPE_ELEM_END) skip=false; } else if (skip) continue; else if (NAMECMP("name") && (type == TYPE_ELEM)){ string str; ret=read_text_node(reader, "name", str); if (ret != 1) break; W.comm = T.comm = M.comm = str; } else if (NAMECMP("Placemark") && (type == TYPE_ELEM)){ ret=read_placemark_node(reader, W, T, M); if (ret != 1) break; } else if (NAMECMP("Folder") && (type == TYPE_ELEM)){ ret=read_folder_node(reader, world); if (ret != 1) break; } else if (NAMECMP("Document") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in Document (type: " << type << ")\n"; } } if (W.size()) world.wpts.push_back(W); if (T.size()) world.trks.push_back(T); if (M.size()) world.maps.push_back(M); return ret; } int read_kml_node(xmlTextReaderPtr reader, geo_data & world){ while(1){ int ret =xmlTextReaderRead(reader); if (ret != 1) return ret; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (type == TYPE_SWS) continue; else if (NAMECMP("Document") && (type == TYPE_ELEM)){ ret=read_document_node(reader, world); if (ret != 1) return ret; } else if (NAMECMP("kml") && (type == TYPE_ELEM_END)){ break; } else { cerr << "Warning: Unknown node \"" << name << "\" in kml (type: " << type << ")\n"; } } return 1; } void read_file(const char* filename, geo_data & world, const Options & opt) { LIBXML_TEST_VERSION if (opt.exists("verbose")) cerr << "Reading data from KML file " << filename << endl; xmlTextReaderPtr reader; int ret; reader = xmlReaderForFile(filename, NULL, 0); if (reader == NULL) throw Err() << "Can't open file " << filename << " for reading"; // parse file while (1){ ret = xmlTextReaderRead(reader); if (ret!=1) break; const xmlChar *name = xmlTextReaderConstName(reader); int type = xmlTextReaderNodeType(reader); if (NAMECMP("kml") && (type == TYPE_ELEM)) ret = read_kml_node(reader, world); if (ret!=1) break; } // free resources xmlFreeTextReader(reader); if (ret != 0) throw Err() << "Can't parse KML file " << filename; xmlCleanupParser(); xmlMemoryDump(); } } // namespace diff --git a/core/geo_io/io_oe.cpp b/core/geo_io/io_oe.cpp index b976aa5..3503b50 100644 --- a/core/geo_io/io_oe.cpp +++ b/core/geo_io/io_oe.cpp @@ -1,649 +1,648 @@ #include "utils/spirit_utils.h" #include <boost/spirit/include/classic_assign_actor.hpp> #include <boost/spirit/include/classic_push_back_actor.hpp> #include <boost/spirit/include/classic_clear_actor.hpp> #include <fstream> #include <iostream> #include <iomanip> #include <vector> #include <string> #include <cstring> #include <map> #include "io_oe.h" #include "geo/geo_convs.h" #include "options/options.h" #include "2d/line_utils.h" #include "utils/iconv_utils.h" #include <cmath> #include <limits> #include "jeeps/gpsmath.h" #include "jeeps/gpsdatum.h" #include "err/err.h" namespace oe{ const char *default_charset = "WINDOWS-1251"; double const NaN = std::numeric_limits<double>::quiet_NaN(); using namespace std; using namespace boost::spirit::classic; // format-specific data types and conversions to geo_data.h types... struct oe_waypoint{ string name, comm; double lat,lon,time; int symb, map_displ, displ, color, bgcolor, pt_dir; double prox_dist, alt; // alt in feet int font_style, size; double font_size; oe_waypoint(){ // all default values -- in geo_data.h g_waypoint dflt; lat=dflt.y; lon=dflt.x; time=dflt.t.value; symb=dflt.symb.val; displ=dflt.displ; map_displ=dflt.map_displ.val; color=dflt.color; bgcolor=dflt.bgcolor; pt_dir=dflt.pt_dir.val; prox_dist=dflt.prox_dist; alt=-777; font_size=dflt.font_size; font_style=dflt.font_style; size=dflt.size; } operator g_waypoint () const{ g_waypoint ret; ret.name = name; ret.comm = comm; ret.y = lat; ret.x = lon; if (time==0) ret.t = Time(0); else ret.t = Time(int(time* 3600.0 * 24.0 - 2209161600.0)); ret.symb.val = symb; ret.displ = displ; ret.map_displ.val = map_displ; ret.color = color; ret.bgcolor = bgcolor; ret.pt_dir.val = pt_dir; ret.size = size; ret.font_size = font_size; ret.font_style = font_style; if (alt == -777) ret.clear_alt(); else ret.z = alt*0.3048; ret.prox_dist = prox_dist; return ret; } // no datum conversion yet }; struct oe_trackpoint{ double lat, lon, time, alt; bool start; oe_trackpoint(){ g_trackpoint dflt; lat=dflt.y; lon=dflt.x; start=dflt.start; time=dflt.t.value; alt=-777; } operator g_trackpoint () const{ g_trackpoint ret; ret.y = lat; ret.x = lon; ret.start = start; if (time==0) ret.t = Time(0); else ret.t = Time(int(time* 3600.0 * 24.0 - 2209161600.0)); if (alt == -777) ret.clear_alt(); else ret.z = alt*0.3048; return ret; } // здесь еще нет преобразования СК! }; struct oe_waypoint_list{ string symbset; string datum; vector<oe_waypoint> points; operator g_waypoint_list () const{ convs::pt2wgs cnv(Datum(datum), Proj("lonlat")); g_waypoint_list ret; ret.symbset = symbset; vector<oe_waypoint>::const_iterator i, b=points.begin(), e=points.end(); for (i=b; i!=e; i++){ g_waypoint p = *i; // type conversion! cnv.frw(p); ret.push_back(p); } return ret; } }; struct oe_track{ int width, color, skip, type, fill, cfill; string comm; string datum; vector<oe_trackpoint> points; oe_track (){ g_track dflt; width=dflt.width; color=dflt.color; skip=dflt.skip; type=dflt.type.val; fill=dflt.fill.val; cfill=dflt.cfill; } operator g_track () const{ g_track ret; convs::pt2wgs cnv(Datum(datum), Proj("lonlat")); ret.width = width; ret.color = color; ret.skip = skip; ret.type.val = type; ret.fill.val = fill; ret.cfill = cfill; ret.comm = comm; vector<oe_trackpoint>::const_iterator i, b=points.begin(), e=points.end(); for (i=b; i!=e; i++){ g_trackpoint p = *i; // type conversion! cnv.frw(p); ret.push_back(p); } return ret; } }; struct oe_mappoint{ int x,y; char lat_h, lon_h; // +/-1 for N/S, E/W double lat_d, lon_d; double lat_m, lon_m; double grid_x, grid_y; oe_mappoint(){ x=0; y=0; lat_h=1; lon_h=1; lat_d=NaN; lon_d=NaN; lat_m=NaN; lon_m=NaN; grid_x=NaN; grid_y=NaN; } }; struct oe_map{ string comm, file, prefix; string datum; char mag_var_h; // not used int mag_var_d; double mag_var_m; string map_proj; double proj_lat0, proj_lon0, proj_k; double proj_E0, proj_N0; double proj_lat1, proj_lat2, proj_hgt; vector<oe_mappoint> points; dLine border; oe_map () : mag_var_h(0), mag_var_d(0), mag_var_m(0), proj_lat0(0), proj_lon0(0), proj_k(1), proj_E0(0), proj_N0(0), proj_lat1(0), proj_lat2(0), proj_hgt(0) { } // map features etc are not supported. operator g_map () const { g_map ret; ret.comm=comm; // add prefix if path is not absolute if ((file.size()<1)||(file[0]!='/')) ret.file=prefix+file; else ret.file=file; ret.map_proj=Proj(map_proj); ret.map_datum = Datum(datum); Options opts; if(ret.map_proj!=Proj("lonlat")){ if (proj_lat0!=0) opts.put("lat0", proj_lat0); if (proj_lat1!=0) opts.put("lat1", proj_lat1); if (proj_lat2!=0) opts.put("lat2", proj_lat2); if (proj_hgt!=0) opts.put("hgt", proj_hgt); if (proj_lon0!=0) opts.put("lon0", proj_lon0); if (proj_k!=1) opts.put("k", proj_k); if (proj_E0!=0) opts.put("E0", proj_E0); if (proj_N0!=0) opts.put("N0", proj_N0); } ret.proj_opts = opts; //ret.proj_str = convs::mkprojstr(ret.map_datum, ret.map_proj, ret.proj_opts); convs::pt2wgs cnv1(Datum(datum), Proj("lonlat")); convs::pt2wgs *cnv2=NULL; // we need it only if we have greed coordinates // otherwise it can be impossible to build it // convert points vector<oe_mappoint>::const_iterator i, b=points.begin(), e=points.end(); for (i=b; i!=e; i++){ g_refpoint p; p.xr = i->x; p.yr = i->y; if (!std::isnan(i->lon_d) && !std::isnan(i->lat_d) && !std::isnan(i->lon_m) && !std::isnan(i->lat_m)){ p.x = i->lon_d + i->lon_m/60.0; if (i->lon_h<0) p.x=-p.x; p.y = i->lat_d + i->lat_m/60.0; if (i->lat_h<0) p.y=-p.y; cnv1.frw(p); } else if (!std::isnan(i->grid_x) && !std::isnan(i->grid_y)){ p.x=i->grid_x; p.y=i->grid_y; if (!cnv2) cnv2=new convs::pt2wgs(Datum(datum), Proj(map_proj), opts); cnv2->frw(p); } else { continue; } ret.push_back(p); } if (cnv2) free(cnv2); ret.border=border; return ret; } }; // function for reading objects from Ozi file into the world object void read_file(const char* filename, geo_data & world, const Options & opt){ oe_waypoint wpt, wpt0; // wawpoint oe_trackpoint tpt, tpt0; // trackpoint oe_mappoint mpt, mpt0; // map ref point dPoint bpt, bpt0; // map border oe_waypoint_list w; oe_track t; oe_map m; g_map_list ml; geo_data ret; if (opt.exists("verbose")) cerr << "Reading data from OziExplorer file " << filename << endl; // get file prefix to keep correct path for image files char *sl = strrchr((char *)filename, '/'); if (sl!=NULL){ int pos = sl-filename; string fn1(filename); m.prefix = string(fn1.begin(),fn1.begin()+pos) + "/"; } else m.prefix=""; // rules for parsing rule_t pr = anychar_p - ',' - eol_p; rule_t ch = anychar_p - eol_p; rule_t scs = *blank_p >> ',' >> *blank_p; rule_t wpt_head = str_p("OziExplorer Waypoint File Version ") >> str_p("1.1") >> eol_p >> (+ch)[assign_a(w.datum)] >> eol_p >> // Datum !(str_p("Altitude") >> +ch >> eol_p) >> // in old or broken files? +ch >> eol_p >> // Reserved for future use (+ch)[assign_a(w.symbset)] >> +eol_p; // Symbol set (unused) rule_t trk_head = str_p("OziExplorer Track Point File Version ") >> (str_p("2.0") || "2.1") >> eol_p >> (+ch)[assign_a(t.datum)] >> eol_p >> +ch >> eol_p >> // Altitude is in feet +ch >> eol_p >> // Reserved for future use ch_p('0') >> !(scs >> !(int_p[assign_a(t.width)]) >> !(scs >> !(int_p[assign_a(t.color)]) >> !(scs >> !((*pr)[assign_a(t.comm)]) >> !(scs >> !(int_p[assign_a(t.skip)]) >> !(scs >> !(int_p[assign_a(t.type)]) >> !(scs >> !(int_p[assign_a(t.fill)]) >> !(scs >> !(int_p[assign_a(t.cfill)]) >> !(scs >> *ch)))))))) >> +eol_p >> uint_p >> +eol_p; rule_t wpt_point = (*blank_p >> int_p >> // Number, unused scs >> (*pr)[assign_a(wpt.name)] >> scs >> real_p[assign_a(wpt.lat)] >> scs >> real_p[assign_a(wpt.lon)] >> !(scs >> !(real_p[assign_a(wpt.time)]) >> !(scs >> !(int_p[assign_a(wpt.symb)]) >> !(scs >> !(int_p) >> // status, always 1, unused !(scs >> !(int_p[assign_a(wpt.map_displ)]) >> !(scs >> !(int_p[assign_a(wpt.color)]) >> !(scs >> !(int_p[assign_a(wpt.bgcolor)]) >> !(scs >> !((*pr)[assign_a(wpt.comm)]) >> !(scs >> !(int_p[assign_a(wpt.pt_dir)]) >> !(scs >> !(int_p[assign_a(wpt.displ)]) >> !(scs >> !(real_p[assign_a(wpt.prox_dist)]) >> !(scs >> !(real_p[assign_a(wpt.alt)]) >> !(scs >> !(real_p[assign_a(wpt.font_size)]) >> !(scs >> !(int_p[assign_a(wpt.font_style)]) >> !(scs >> !(int_p[assign_a(wpt.size)]) >> !(scs >> *ch))))))))))))))) >> +eol_p) [push_back_a(w.points, wpt)][assign_a(wpt, wpt0)]; rule_t trk_point = (*blank_p >> real_p[assign_a(tpt.lat)] >> scs >> real_p[assign_a(tpt.lon)] >> !(scs >> !(uint_p[assign_a(tpt.start)]) >> !(scs >> !(real_p[assign_a(tpt.alt)]) >> !(scs >> !(real_p[assign_a(tpt.time)]) >> !(scs >> *ch)))) >> +eol_p) [push_back_a(t.points, tpt)][assign_a(tpt, tpt0)]; const int mm=-1; const int pp=+1; rule_t map_point = (*blank_p >> "Point" >> uint_p >> scs >> "xy" >> scs >> !(uint_p[assign_a(mpt.x)]) >> scs >> !(uint_p[assign_a(mpt.y)]) >> scs >> (str_p("in")|"ex") >> scs >> "deg" >> scs >> !(uint_p[assign_a(mpt.lat_d)]) >> scs >> !(ureal_p[assign_a(mpt.lat_m)]) >> scs >> !(ch_p('S')[assign_a(mpt.lat_h,mm)] || ch_p('N')[assign_a(mpt.lat_h,pp)]) >> scs >> !(uint_p[assign_a(mpt.lon_d)]) >> scs >> !(ureal_p[assign_a(mpt.lon_m)]) >> scs >> !(ch_p('W')[assign_a(mpt.lon_h,mm)] || ch_p('E')[assign_a(mpt.lon_h,pp)]) >> scs >> "grid" >> scs >> *pr >> scs >> !(ureal_p[assign_a(mpt.grid_x)]) >> scs >> !(ureal_p[assign_a(mpt.grid_y)]) >> scs >> *ch >> +eol_p) [push_back_a(m.points, mpt)][assign_a(mpt, mpt0)]; rule_t MM = // v2.2 (str_p("MMPNUM") >> scs >> uint_p >> +eol_p >> *("MMPXY" >> scs >> uint_p >> scs >> uint_p[assign_a(bpt.x)] >> scs >> uint_p[assign_a(bpt.y)] >> +eol_p [push_back_a(m.border,bpt)])) || // v2.0 (str_p("MM1A") >> /* why is it here? -- scs >> uint_p >> */ *(scs >> uint_p[assign_a(bpt.x)] >> scs >> uint_p[assign_a(bpt.y)] [push_back_a(m.border,bpt)] ) >> +eol_p); rule_t map_rule = str_p("OziExplorer Map Data File Version ") >> (str_p("2.0") || "2.1" || "2.2") >> eol_p >> (*ch)[assign_a(m.comm)] >> eol_p >> (*ch)[assign_a(m.file)] >> eol_p >> *ch >> eol_p >> // 1 TIFF scale factor -- ignored (*pr)[assign_a(m.datum)] >> !(scs >> *ch) >> eol_p >> *ch >> eol_p >> // Reserved 1 *ch >> eol_p >> // Reserved 2 "Magnetic Variation" >> scs >> !(uint_p[assign_a(m.mag_var_d)]) >> scs >> !(ureal_p[assign_a(m.mag_var_m)]) >> scs >> !(ch_p('W')[assign_a(m.mag_var_h,mm)] || ch_p('E')[assign_a(m.mag_var_h,pp)]) >> eol_p >> "Map Projection" >> scs >> (*pr)[assign_a(m.map_proj)] >> !(scs >> *ch) >> +eol_p >> +(map_point) >> "Projection Setup" >> !(scs >> !(real_p[assign_a(m.proj_lat0)]) >> !(scs >> !(real_p[assign_a(m.proj_lon0)]) >> !(scs >> !(ureal_p[assign_a(m.proj_k)]) >> !(scs >> !(real_p[assign_a(m.proj_E0)]) >> !(scs >> !(real_p[assign_a(m.proj_N0)]) >> !(scs >> !(real_p[assign_a(m.proj_lat1)]) >> !(scs >> !(real_p[assign_a(m.proj_lat2)]) >> !(scs >> !(real_p[assign_a(m.proj_hgt)]) >> !(scs >> *ch))))))))) >> +eol_p >> "Map Feature" >> *ch >> +eol_p >> *( (str_p("MF") >> *ch >> +eol_p >> // MF (3 lines, unsupported) *ch >> +eol_p >> *ch >> +eol_p) || (str_p("MC") >> *ch >> +eol_p >> // MC (2 lines, unsupported) *ch >> +eol_p ) ) >> "Track File" >> *ch >> +eol_p >> *( str_p("TF") >> *ch >> +eol_p ) >> // TF (1 line, unsupported) "Moving Map" >> *ch >> +eol_p >> *( "MM0" >> scs >> *ch >> +eol_p ) >> // Yes or No, does not matter *MM >> *anychar_p; rule_t main_rule = (wpt_head >> *(wpt_point))[push_back_a(ret.wpts, w)] || (trk_head >> *(trk_point))[push_back_a(ret.trks, t)] || map_rule[push_back_a(ml, m)]; if (!parse_file("oe::read", filename, main_rule)) throw Err() << "Can't parse OziExplorer file " << filename; // convert waypoint names and comments to UTF8 IConv cnv(default_charset); for (vector<g_waypoint_list>::iterator l=ret.wpts.begin(); l!=ret.wpts.end(); l++){ for (g_waypoint_list::iterator p=l->begin(); p!=l->end(); p++){ p->name = cnv.to_utf8(p->name); p->comm = cnv.to_utf8(p->comm); } } // convert track comments to UTF8 for (vector<g_track>::iterator l=ret.trks.begin(); l!=ret.trks.end(); l++){ l->comm = cnv.to_utf8(l->comm); } // convert map comments to UTF8 for (vector<g_map>::iterator l=ml.begin(); l!=ml.end(); l++){ l->comm = cnv.to_utf8(l->comm); } if (ml.size()>0) ret.maps.push_back(ml); const char *fn_start=rindex(filename, '/'); for (vector<g_waypoint_list>::iterator i = ret.wpts.begin(); i!= ret.wpts.end(); i++) i->comm=fn_start ? fn_start+1 : ""; world.wpts.insert(world.wpts.end(), ret.wpts.begin(), ret.wpts.end()); world.trks.insert(world.trks.end(), ret.trks.begin(), ret.trks.end()); world.maps.insert(world.maps.end(), ret.maps.begin(), ret.maps.end()); } /***********************************************************/ void write_plt_file (const char *filename, const g_track & trk, const Options & opt){ if (opt.exists("verbose")) cerr << "Writing data to OziExplorer file " << filename << endl; ofstream f(filename); if (!f.good()) throw Err() << "Can't open OziExplorer file " << filename << " for writing"; IConv cnv(default_charset); // date format: days since 12/30/1899 12:00AM GMT // date +%s -d '12/30/1899 12:00AM GMT' = -2209161600 int num = trk.size(); f << "OziExplorer Track Point File Version 2.0\r\n" << "WGS 84\r\n" << "Altitude is in Feet\r\n" << "Reserved 3\r\n" << "0," << trk.width << ',' << (trk.color & 0xFFFFFF) << ',' << cnv.from_utf8(trk.comm) << ',' << trk.skip << ',' << trk.type.val << ',' << trk.fill.val << ',' << (trk.cfill & 0xFFFFFF) << "\r\n" << num << "\r\n"; for (vector<g_trackpoint>::const_iterator p = trk.begin(); p!= trk.end(); p++){ f << right << fixed << setprecision(6) << setfill(' ') << setw(10)<< p->y << ',' << setw(11)<< p->x << ',' << ((p->start)? '1':'0') << ',' << setprecision(1) << setw(6) << (p->have_alt() ? p->z/0.3048 : -777) << ',' << setprecision(7) << setw(13) << (p->t.value+2209161600.0)/3600.0/24.0 << ',' << setfill('0') << p->t << "\r\n"; } if (!f.good()) throw Err() << "Can't write data to OziExplorer file " << filename << " for writing"; } void write_wpt_file (const char *filename, const g_waypoint_list & wpt, const Options & opt){ if (opt.exists("verbose")) cerr << "Writing data to OziExplorer file " << filename << endl; ofstream f(filename); if (!f.good()) throw Err() << "Can't open OziExplorer file " << filename << " for writing"; IConv cnv(default_charset); - int num = wpt.size(); - int n=0; + size_t n=0; f << "OziExplorer Waypoint File Version 1.1\r\n" << "WGS 84\r\n" << "Reserved 2\r\n" << wpt.symbset << "\r\n"; for (vector<g_waypoint>::const_iterator p = wpt.begin(); p!= wpt.end(); p++){ f << right << setw(4) << (++n) << ',' << left << setw(6) << setfill(' ') << cnv.from_utf8(p->name) << ',' << right << fixed << setprecision(6) << setw(10) << p->y << ',' << setw(11) << p->x << ',' << setprecision(7) << setw(13) << (p->t.value+2209161600.0)/3600.0/24.0 << ',' << p->symb.val << ",1," << p->map_displ.val << ',' << (p->color & 0xFFFFFF) << ',' << (p->bgcolor & 0xFFFFFF) << ',' << cnv.from_utf8(p->comm) << ',' << p->pt_dir.val << ',' << p->displ << ',' << p->prox_dist << ',' << (p->have_alt() ? p->z/0.3048 : -777) << ',' << setprecision(2) << setw(5)<< p->font_size << ',' << p->font_style << ',' << p->size << "\r\n"; } if (!f.good()) throw Err() << "Can't write data to OziExplorer file " << filename << " for writing"; } void write_map_file (const char *filename, const g_map & m, const Options & opt){ if (opt.exists("verbose")) cerr << "Writing data to OziExplorer file " << filename << endl; ofstream f(filename); if (!f.good()) throw Err() << "Can't open OziExplorer file " << filename << " for writing"; IConv cnv(default_charset); Enum::output_fmt=Enum::oe_fmt; f << "OziExplorer Map Data File Version 2.2\r\n" << cnv.from_utf8(m.comm) << "\r\n" << m.file << "\r\n" << "1 ,Map Code,\r\n" /// TODO: set correct datum (point conversion needed!) << "WGS 84,, 0.0000, 0.0000,WGS 84\r\n" << "Reserved 1\r\n" << "Reserved 2\r\n" << "Magnetic Variation,,,E\r\n" << "Map Projection," << m.map_proj << ",PolyCal,No,AutoCalOnly,No,BSBUseWPX,No\r\n"; - for (int n=1; n<=30; n++){ + for (size_t n=1; n<=30; n++){ f << "Point" << setw(2) << setfill('0') << n << ",xy,"; - if (n>m.size()){ + if (n>m.size()){ f <<" , ,in, deg, , ,N, , ,W" <<", grid, , , ,N\r\n"; continue; } int x = (int)m[n-1].xr; int y = (int)m[n-1].yr; double lat = m[n-1].y; double lon = m[n-1].x; f << setw(5) << setfill(' ') << x << ',' << setw(5) << setfill(' ') << y << ',' << "in, deg," << fixed << setw(4) << abs(int(lat)) << ',' << fixed << setw(8) << fabs(lat*60) - abs(int(lat))*60 << ',' << (lat<0? 'S':'N') << ',' << fixed << setw(4) << abs(int(lon)) << ',' << fixed << setw(8) << fabs(lon*60) - abs(int(lon))*60 << ',' << (lon<0? 'W':'E') << ',' << " grid, , , ,N\r\n"; } if (m.map_proj == Proj("lonlat")){ f << "Projection Setup,,,,,,,,,,\r\n"; } else { double lon0 = m.proj_opts.get("lon0", 1e90); if (lon0==1e90){ lon0=0; - for (int i=0; i<m.size(); i++) lon0+=m[i].x; + for (size_t i=0; i<m.size(); i++) lon0+=m[i].x; if (m.size()>1) lon0/=m.size(); lon0 = floor( lon0/6.0 ) * 6 + 3; } f << "Projection Setup, " << m.proj_opts.get("lat0", 0.0) << "," << lon0 << "," << m.proj_opts.get("k", 1.0) << "," << m.proj_opts.get("E0", 500000.0) << "," << m.proj_opts.get("N0", 0.0) << "," << m.proj_opts.get("lat1", 0.0) << "," << m.proj_opts.get("lat2", 0.0) << "," << m.proj_opts.get("hgt", 0.0) << ",,\r\n"; } f << "Map Feature = MF ; Map Comment = MC These follow if they exist\r\n" << "Track File = TF These follow if they exist\r\n" << "Moving Map Parameters = MM? These follow if they exist\r\n"; if (m.border.size()>0){ f << "MM0,Yes\r\n" << "MMPNUM," << m.border.size() << "\r\n"; int n=0; for (dLine::const_iterator it =m.border.begin(); it!=m.border.end(); it++){ n++; f << "MMPXY," << n << "," << int(it->x) << "," << int(it->y) << "\r\n"; } n=0; convs::map2wgs cnv(m); f.precision(8); for (dLine::const_iterator it =m.border.begin(); it!=m.border.end(); it++){ n++; dPoint p1=*it; cnv.frw(p1); f << "MMPLL," << n << "," << right << fixed << setprecision(6) << setfill(' ') << setw(10) << p1.x << ',' << setw(11) << p1.y << "\r\n"; } f << "MM1B," << convs::map_mpp(m, m.map_proj) << "\r\n"; } else{ f << "MM0,No\r\n"; } if (!f.good()) throw Err() << "Can't write data to OziExplorer file " << filename << " for writing"; } } // namespace diff --git a/core/geo_io/io_xml.cpp b/core/geo_io/io_xml.cpp index f1b0ab1..18ac4e7 100644 --- a/core/geo_io/io_xml.cpp +++ b/core/geo_io/io_xml.cpp @@ -1,325 +1,325 @@ #include "utils/spirit_utils.h" #include <boost/spirit/include/classic_assign_actor.hpp> #include <boost/spirit/include/classic_push_back_actor.hpp> #include <boost/spirit/include/classic_insert_at_actor.hpp> #include <boost/spirit/include/classic_clear_actor.hpp> #include <iostream> #include <iomanip> #include <string> #include <cstring> #include <time.h> #include "io_xml.h" #include "options/options.h" #include "utils/iconv_utils.h" #include "err/err.h" #include "geo/geo_convs.h" namespace xml { const char *default_charset = "KOI8-R"; using namespace std; using namespace boost::spirit::classic; // function for reading objects from XML file // into the world object void read_file(const char* filename, geo_data & world, const Options & opt){ xml_point pt; xml_point_list pt_list; xml_map_list map_list, top_map_list; geo_data ret; // prefix -- директория, в которой лежит map-файл, на случай, // если в нем относительные названия граф.файлов std::string prefix(""); char *sl = strrchr((char *)filename, '/'); if (sl!=NULL){ int pos = sl-filename; std::string fn1(filename); prefix=std::string(fn1.begin(),fn1.begin()+pos) + "/"; } if (opt.exists("verbose")) cerr << "Reading data from Mapsoft XML file " << filename << endl; string aname, aval; const string oo="1"; rule_t attr_name = (+(alnum_p | '-' | '_'))[assign_a(aname)][assign_a(aval, oo)]; rule_t escaped_symb = (ch_p('\\') >> ch_p('"')) | (ch_p('\\') >> ch_p('\\')) ; rule_t attr_value = ('"' >> (*((anychar_p | escaped_symb ) - '"'))[assign_a(aval)] >> '"') | (*(anychar_p - (space_p | ch_p('"') | '>' | '/' | '\\')))[assign_a(aval)]; rule_t attr = +space_p >> attr_name >> !(*space_p >> '=' >> *space_p >> attr_value); rule_t point_object = str_p("<pt")[clear_a(pt)] >> *attr[insert_at_a(pt, aname, aval)] >> str_p("/>")[push_back_a(pt_list.points, pt)]; rule_t wpt_object = str_p("<waypoints")[clear_a(pt_list)][clear_a(pt_list.points)] >> *attr[insert_at_a(pt_list, aname, aval)] >> ">" >> *(*space_p >> point_object) >> *space_p >> str_p("</waypoints>")[push_back_a(ret.wpts, pt_list)]; rule_t trk_object = str_p("<track")[clear_a(pt_list)][clear_a(pt_list.points)] >> *attr[insert_at_a(pt_list, aname, aval)] >> ">" >> *(*space_p >> point_object) >> *space_p >> str_p("</track>")[push_back_a(ret.trks, pt_list)]; rule_t map_object = str_p("<map")[clear_a(pt_list)][insert_at_a(pt_list, "prefix", prefix)][clear_a(pt_list.points)] >> *attr[insert_at_a(pt_list, aname, aval)] >> ">" >> *(*space_p >> point_object) >> *space_p >> str_p("</map>")[push_back_a(map_list.maps, pt_list)]; // topmap_object is for top-level maps in old-style files rule_t topmap_object = str_p("<map")[clear_a(pt_list)][insert_at_a(pt_list, "prefix", prefix)][clear_a(pt_list.points)] >> *attr[insert_at_a(pt_list, aname, aval)] >> ">" >> *(*space_p >> point_object) >> *space_p >> str_p("</map>")[push_back_a(top_map_list.maps, pt_list)]; rule_t maps_object = str_p("<maps")[clear_a(map_list.maps)] >> *attr[insert_at_a(map_list, aname, aval)] >> ">" >> *(*space_p >> map_object) >> *space_p >> str_p("</maps>")[push_back_a(ret.maps, map_list)]; rule_t main_rule = *(*space_p >> (wpt_object | trk_object | topmap_object | maps_object)) >> *space_p; if (!parse_file("xml::read", filename, main_rule)) throw Err() << "Can't parse mapsoft XML file " << filename; if (top_map_list.maps.size()>0) ret.maps.push_back(top_map_list); // convert wpt names and comments to UTF-8 IConv cnv(default_charset); for (vector<g_waypoint_list>::iterator l=ret.wpts.begin(); l!=ret.wpts.end(); l++){ l->comm = cnv.to_utf8(l->comm); for (g_waypoint_list::iterator p=l->begin(); p!=l->end(); p++){ p->name = cnv.to_utf8(p->name); p->comm = cnv.to_utf8(p->comm); } } // convert track comments to UTF-8 for (vector<g_track>::iterator l=ret.trks.begin(); l!=ret.trks.end(); l++){ l->comm = cnv.to_utf8(l->comm); } // convert map comments to UTF-8, add lon0 if needed for (vector<g_map_list>::iterator ll=ret.maps.begin(); ll!=ret.maps.end(); ll++){ ll->comm = cnv.to_utf8(ll->comm); for (vector<g_map>::iterator l=ll->begin(); l!=ll->end(); l++){ l->comm = cnv.to_utf8(l->comm); // old tmerc xml files does not have lon0 option! if (l->map_proj==Proj("tmerc") && !l->proj_opts.exists("lon0")) l->proj_opts.put("lon0", convs::map_lon0(*l)); } } world.wpts.insert(world.wpts.end(), ret.wpts.begin(), ret.wpts.end()); world.trks.insert(world.trks.end(), ret.trks.begin(), ret.trks.end()); world.maps.insert(world.maps.end(), ret.maps.begin(), ret.maps.end()); } /********************************************/ bool write_track(ofstream & f, const g_track & tr, const Options & opt){ if (!f.good()) return false; IConv cnv(default_charset); Enum::output_fmt=Enum::xml_fmt; g_trackpoint def_pt; g_track def_t; f << "<track points=" << tr.size(); if (tr.width != def_t.width) f << " width=" << tr.width; if (tr.displ != def_t.displ) f << " displ=" << tr.displ; if (tr.color != def_t.color) f << " color=\"#" << hex << tr.color << "\"" << dec; if (tr.skip != def_t.skip) f << " skip=" << tr.skip; if (tr.type != def_t.type) f << " type=" << tr.type; if (tr.fill != def_t.fill) f << " fill=" << tr.fill; if (tr.cfill != def_t.cfill) f << " cfill=\"#" << hex << tr.cfill << "\"" << dec; if (tr.comm != def_t.comm) f << " comm=\"" << cnv.from_utf8(tr.comm) << "\""; f << ">\n"; vector<g_trackpoint>::const_iterator p, b=tr.begin(), e=tr.end(); for (p = b; p != e; p++){ f << " <pt"; if (p->y != def_pt.y) f << " lat=" << fixed << setprecision(6) << p->y; if (p->x != def_pt.x) f << " lon=" << fixed << setprecision(6) << p->x; if (p->have_alt()) f << " alt=" << fixed << setprecision(1) << p->z; if (p->have_depth()) f << " depth=" << fixed << setprecision(1) << p->depth; if (p->t != def_pt.t) f << " time=\"" << p->t << "\""; if (p->start) f << " start"; f << "/>\n"; } f << "</track>\n"; return true; } bool write_waypoint_list(ofstream & f, const g_waypoint_list & wp, const Options & opt){ if (!f.good()) return false; IConv cnv(default_charset); Enum::output_fmt=Enum::xml_fmt; g_waypoint def_pt; g_waypoint_list def_w; f << "<waypoints points=" << wp.size(); if (wp.symbset != def_w.symbset) f << " symbset=" << wp.symbset; if (wp.comm != def_w.comm) f << " comm=\"" << cnv.from_utf8(wp.comm) << "\""; f << ">\n"; vector<g_waypoint>::const_iterator p, b=wp.begin(), e=wp.end(); for (p = b; p!=e; p++){ f << " <pt"; if (p->y != def_pt.y) f << " lat=" << fixed << setprecision(6) << p->y; if (p->x != def_pt.x) f << " lon=" << fixed << setprecision(6) << p->x; if (p->have_alt()) f << " alt=" << fixed << setprecision(1) << p->z; if (p->t != def_pt.t) f << " time=\"" << p->t << "\""; if (p->name != def_pt.name) f << " name=\"" << cnv.from_utf8(p->name) << "\""; if (p->comm != def_pt.comm) f << " comm=\"" << cnv.from_utf8(p->comm) << "\""; if (p->prox_dist != def_pt.prox_dist) f << " prox_dist=" << fixed << setprecision(1) << p->prox_dist; if (p->symb != def_pt.symb) f << " symb=" << p->symb; if (p->displ != def_pt.displ) f << " displ=" << p->displ; if (p->color != def_pt.color) f << " color=\"" << hex << p->color << "\"" << dec; if (p->bgcolor != def_pt.bgcolor) f << " bgcolor=\"" << hex << p->bgcolor << "\"" << dec; if (p->map_displ != def_pt.map_displ) f << " map_displ=" << p->map_displ; if (p->pt_dir != def_pt.pt_dir) f << " pt_dir=" << p->pt_dir; if (p->font_size != def_pt.font_size) f << " font_size=" << p->font_size; if (p->font_style != def_pt.font_style) f << " font_style=" << p->font_style; if (p->size != def_pt.size) f << " size=" << p->size; f << "/>\n"; } f << "</waypoints>\n"; return true; } bool write_map(ofstream & f, const g_map & m, const Options & opt){ if (!f.good()) return false; IConv cnv(default_charset); Enum::output_fmt=Enum::xml_fmt; g_refpoint def_pt; g_map def_m; f << " <map points=" << m.size(); if (m.comm != def_m.comm) f << " comm=\"" << cnv.from_utf8(m.comm) << "\""; if (m.file != def_m.file) f << " file=\"" << m.file << "\""; //if (m.proj_str != def_m.proj_str) f << "\n proj_str=\"" << m.proj_str << "\""; if (m.map_proj != def_m.map_proj) f << "\n map_proj=\"" << m.map_proj << "\""; if (m.map_datum != def_m.map_datum) f << " map_datum=\"" << m.map_datum << "\""; for (Options::const_iterator i=m.proj_opts.begin(); i!=m.proj_opts.end(); i++) f << " " << i->first << "=\"" << i->second << "\""; if (m.tfmt != def_m.tfmt) f << " tile_fmt=\"" << m.tfmt << "\""; if (m.tsize != def_m.tsize) f << " tile_size=\"" << m.tsize << "\""; if (m.tswap != def_m.tswap) f << " tile_swapy=\"" << m.tswap << "\""; if (m.border.size()!=0){ f << "\n border=\""; - for (int i = 0; i<m.border.size(); i++){ + for (size_t i = 0; i<m.border.size(); i++){ if (i!=0) f << ","; f << m.border[i].x << "," << m.border[i].y; } f << "\""; } f << ">\n"; vector<g_refpoint>::const_iterator p, b=m.begin(), e=m.end(); for (p = b; p!=e; p++){ f << " <pt"; if (p->x != def_pt.y) f << " x=" << fixed << setprecision(6) << p->x; if (p->y != def_pt.x) f << " y=" << fixed << setprecision(6) << p->y; if (p->xr != def_pt.xr) f << " xr=" << fixed << setprecision(1) << p->xr; if (p->yr != def_pt.yr) f << " yr=" << fixed << setprecision(1) << p->yr; f << "/>\n"; } f << " </map>\n"; return true; } bool write_map_list(ofstream & f, const g_map_list & m, const Options & opt){ if (!f.good()) return false; IConv cnv(default_charset); g_map_list def_m; f << "<maps"; if (m.comm != def_m.comm) f << " comm=\"" << cnv.from_utf8(m.comm) << "\""; f << ">\n"; g_map_list::const_iterator map, b=m.begin(), e=m.end(); for (map = b; map!=e; map++) write_map (f, *map, opt); f << "</maps>\n"; return true; } void write_file(const char* filename, const geo_data & world, const Options & opt){ if (opt.exists("verbose")) cerr << "Writing data to Mapsoft XML file " << filename << endl; ofstream f(filename); for (vector<g_waypoint_list>::const_iterator i = world.wpts.begin(); i!=world.wpts.end(); i++){ if (!write_waypoint_list(f, *i, opt)) throw Err() << "Can't write data to Mapsoft XML file " << filename; } for (vector<g_track>::const_iterator i = world.trks.begin(); i!=world.trks.end(); i++){ if (!write_track(f, *i, opt)) throw Err() << "Can't write data to Mapsoft XML file " << filename; } for (vector<g_map_list>::const_iterator i = world.maps.begin(); i!=world.maps.end(); i++){ if (!write_map_list(f, *i, opt)) throw Err() << "Can't write data to Mapsoft XML file " << filename; } } /********************************************/ // Для всех типов точек - один map<string,string>, но разные преобразования // Это все вынесено в отдельный h-файл, поскольку используется и при чтении точек из fig xml_point::operator g_waypoint () const { g_waypoint ret; ret.parse_from_options(*this); return ret; } xml_point::operator g_trackpoint () const{ g_trackpoint ret; ret.parse_from_options(*this); return ret; } xml_point::operator g_refpoint () const{ g_refpoint ret; ret.parse_from_options(*this); return ret; } xml_point_list::operator g_waypoint_list () const { g_waypoint_list ret; ret.parse_from_options(*this); for (std::vector<xml_point>::const_iterator i=points.begin(); i!=points.end();i++) ret.push_back(*i); return ret; } xml_point_list::operator g_track () const { g_track ret; ret.parse_from_options(*this); for (std::vector<xml_point>::const_iterator i=points.begin(); i!=points.end();i++) ret.push_back(*i); return ret; } xml_point_list::operator g_map () const { g_map ret; ret.parse_from_options(*this); for (std::vector<xml_point>::const_iterator i=points.begin(); i!=points.end();i++) ret.push_back(*i); return ret; } xml_map_list::operator g_map_list () const { g_map_list ret; ret.vector<g_map>::operator=(maps); ret.parse_from_options(*this); return ret; } }
ushakov/mapsoft
fd74b9a1f617a4849e3e6b91b0f1159e29260a49
core/geo: fix sign-compare warning
diff --git a/core/geo/geo_convs.cpp b/core/geo/geo_convs.cpp index f295647..5a9363f 100644 --- a/core/geo/geo_convs.cpp +++ b/core/geo/geo_convs.cpp @@ -1,440 +1,440 @@ #include "geo_convs.h" #include <cmath> #include <cstring> #include <sstream> #include <cassert> #include <map> #include "2d/line_utils.h" #include "err/err.h" namespace convs{ using namespace std; /*******************************************************************/ /// Create PROJ4 projection object from our D, P and options. string mkprojstr(const Datum & D, const Proj & P, const Options & o){ int old_enum_fmt=Enum::output_fmt; Enum::output_fmt = Enum::proj_fmt; ostringstream projpar; // proj setings // special google case, see http://trac.osgeo.org/proj/wiki/FAQ#ChangingEllipsoidWhycantIconvertfromWGS84toGoogleEarthVirtualGlobeMercator if (P==Proj("google")) // use google_sphere instead of wgs projpar << " +proj=merc +a=6378137 +b=6378137 +nadgrids=@null +no_defs"; else if (P==Proj("ch1904")) projpar << " +proj=somerc +lat_0=46.95240555555556" " +lon_0=7.439583333333333 +x_0=600000 +y_0=200000" " +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0" " +units=m +no_defs"; else projpar << " +proj=" << P; // datum and ellps settings if (D==Datum("pulkovo")) projpar << " +ellps=krass +towgs84=+28,-130,-95"; // Finnish coords, see http://www.kolumbus.fi/eino.uikkanen/geodocsgb/ficoords.htm // http://lists.maptools.org/pipermail/proj/2005-December/001944.html else if (D==Datum("KKJ")) projpar << " +ellps=intl +towgs84=-90.7,-106.1,-119.2,4.09,0.218,-1.05,1.37"; else if (D==Datum("sphere")) projpar << " +ellps=sphere"; // http://spatial-analyst.net/wiki/index.php?title=MGI_/_Balkans_coordinate_systems else if (D==Datum("balkans")) projpar << " +ellps=bessel +towgs84=550.499,164.116,475.142,5.80967,2.07902,-11.62386,0.99999445824"; else if (P!=Proj("google") && P!=Proj("ch1904")) projpar << " +datum=" << D; Enum::output_fmt = old_enum_fmt; switch (P.val){ case 0: // lonlat break; case 1: // tmerc if (o.count("lon0")==0){ throw Err() << "mkproj: can't create proj: \"" << projpar.str() << "\" without lon0"; } projpar << " +lon_0=" << o.get("lon0", 0.0); projpar << " +lat_0=" << o.get("lat0", 0.0); projpar << " +k=" << o.get("k", 1.0); projpar << " +x_0=" << o.get("E0", 500000.0); projpar << " +y_0=" << o.get("N0", 0.0); break; case 3: // merc projpar << " +lon_0=" << o.get("lon0", 0.0); projpar << " +lat_ts=" << o.get("lat0", 0.0); projpar << " +x_0=" << o.get("E0", 0.0); projpar << " +y_0=" << o.get("N0", 0.0); break; case 4: // google case 5: // google break; case 6: // lcc projpar << " +lat_1=" << o.get("lat1", 30.0); projpar << " +lat_2=" << o.get("lat2", 60.0); projpar << " +lon_0=" << o.get("lon0", 0.0); projpar << " +k_0=" << o.get("k", 1.0); projpar << " +x_0=" << o.get("E0", 500000.0); projpar << " +y_0=" << o.get("N0", 0.0); break; case 7: // swiss break; default: throw Err() << "unknown proj: " << P.val; } return projpar.str(); } projPJ mkproj(const Datum & D, const Proj & P, const Options & o){ string str=mkprojstr(D,P,o); projPJ ret=pj_init_plus(str.c_str()); if (!ret) throw Err() << "mkproj: Error: can't create proj: \"" << str << "\""; return ret; } /*******************************************************************/ pt2pt::pt2pt(const Datum & sD, const Proj & sP, const Options & sPo, const Datum & dD, const Proj & dP, const Options & dPo){ pr_src = mkproj(sD, sP, sPo); if (sD==dD && sP==dP && sPo ==dPo) pr_dst=pr_src; else pr_dst = mkproj(dD, dP, dPo); if (pj_is_latlong(pr_src)) sc_src=180.0/M_PI; if (pj_is_latlong(pr_dst)) sc_dst=180.0/M_PI; refcounter = new int; *refcounter = 1; } pt2pt::pt2pt(const pt2pt & other){ copy(other); } pt2pt & pt2pt::operator=(const pt2pt & other){ if (this != &other){ destroy(); copy(other); } return *this; } pt2pt::~pt2pt(){ destroy(); } void pt2pt::copy(const pt2pt & other){ this->Conv::operator=(other); refcounter = other.refcounter; pr_src = other.pr_src; pr_dst = other.pr_dst; (*refcounter)++; assert(*refcounter >0); } void pt2pt::destroy(void){ (*refcounter)--; if (*refcounter<=0){ delete refcounter; if (pr_dst != pr_src) pj_free(pr_dst); pj_free(pr_src); } } /*******************************************************************/ map2pt::map2pt(const g_map & sM, const Datum & dD, const Proj & dP, const Options & dPo){ // proj for reference points (coords in radians!) pr_ref = mkproj(Datum("WGS84"), Proj("lonlat"), Options()); // for ref points // destination projection pr_dst = mkproj(dD, dP, dPo); // map projection if (sM.map_datum==dD && sM.map_proj==dP && sM.proj_opts ==dPo) pr_map = pr_dst; else{ Options o = sM.proj_opts; if (sM.map_proj == Proj("tmerc") && !o.exists("lon0")) o.put<double>("lon0", map_lon0(sM)); pr_map = mkproj(sM.map_datum, sM.map_proj, o); } if (pj_is_latlong(pr_dst)) sc_dst=180.0/M_PI; refcounter = new int; *refcounter = 1; // convert refpoints into map coords and find linear conversion // to raster points. map<dPoint,dPoint> points; for (g_map::const_iterator i=sM.begin(); i!=sM.end(); i++){ dPoint pr(i->xr, i->yr), pl(*i * M_PI/180.0); pj_transform(pr_ref, pr_map, 1, 1, &pl.x, &pl.y, NULL); points[pr] = pl; } lin_cnv.set_from_ref(points); } map2pt::map2pt(const map2pt & other){ copy(other); } map2pt & map2pt::operator=(const map2pt & other){ if (this != &other){ destroy(); copy(other); } return *this; } map2pt::~map2pt(){ destroy(); } void map2pt::copy(const map2pt & other){ this->Conv::operator=(other); refcounter = other.refcounter; pr_ref = other.pr_ref; pr_map = other.pr_map; pr_dst = other.pr_dst; lin_cnv = other.lin_cnv; (*refcounter)++; assert(*refcounter >0); } void map2pt::destroy(void){ (*refcounter)--; if (*refcounter<=0){ delete refcounter; pj_free(pr_ref); if (pr_map != pr_dst) pj_free(pr_map); pj_free(pr_dst); } } void map2pt::rescale_src(const double s){ lin_cnv.rescale_src(s); } /*******************************************************************/ /* input: M1(D1,P1,O1) --ref--> WGS M2(D2,P2,O2) --ref--> WGS ref1 c1 c2 ref2 M1 --> WGS --> P1 --cnv2--> P2 <-- WGS <--- M2 \ / \ / -->cnv1(Aff)- -cnv3(aff)<-- */ map2map::map2map(const Datum & sD, const Proj & sP, const Options & sPo, const Datum & dD, const Proj & dP, const Options & dPo, std::map<dPoint, dPoint> ref1, std::map<dPoint, dPoint> ref2 ) : cnv2(sD, sP, sPo, dD, dP, dPo){ convs::pt2wgs c1(sD, sP, sPo); convs::pt2wgs c2(dD, dP, dPo); std::map<dPoint, dPoint>::iterator i; for (i=ref1.begin(); i!=ref1.end(); i++) c1.bck(i->second); for (i=ref2.begin(); i!=ref2.end(); i++) c2.bck(i->second); cnv1.set_from_ref(ref1); cnv3.set_from_ref(ref2); } Options ref2opt(const std::map<dPoint, dPoint> & ref){ double lon0=0; std::map<dPoint, dPoint>::const_iterator i; for (i=ref.begin(); i!=ref.end(); i++) lon0+=i->second.x; if (ref.size()) lon0/=ref.size(); Options ret; ret.put<double>("lon0", lon0); return ret; } map2map::map2map(const Proj & sP, const Proj & dP, std::map<dPoint, dPoint> ref1, std::map<dPoint, dPoint> ref2 ): cnv2(Datum("wgs84"), sP, ref2opt(ref1), Datum("wgs84"), dP, ref2opt(ref2) ){ convs::pt2wgs c1(Datum("wgs84"), sP, ref2opt(ref1)); convs::pt2wgs c2(Datum("wgs84"), dP, ref2opt(ref2)); std::map<dPoint, dPoint>::iterator i; for (i=ref1.begin(); i!=ref1.end(); i++) c1.bck(i->second); for (i=ref2.begin(); i!=ref2.end(); i++) c2.bck(i->second); cnv1.set_from_ref(ref1); cnv3.set_from_ref(ref2); } map2map::map2map(const g_map & sM, const g_map & dM): cnv2(Datum("wgs84"), sM.map_proj, sM.proj_opts, Datum("wgs84"), dM.map_proj, dM.proj_opts){ convs::pt2wgs c1(Datum("wgs84"), sM.map_proj, sM.proj_opts); convs::pt2wgs c2(Datum("wgs84"), dM.map_proj, dM.proj_opts); std::map<dPoint, dPoint> ref1, ref2; g_map::const_iterator i; for (i=sM.begin(); i!=sM.end(); i++){ dPoint p1(i->xr, i->yr); dPoint p2(i->x, i->y); c1.bck(p2); ref1[p1]=p2; } for (i=dM.begin(); i!=dM.end(); i++){ dPoint p1(i->xr, i->yr); dPoint p2(i->x, i->y); c2.bck(p2); ref2[p1]=p2; } cnv1.set_from_ref(ref1); cnv3.set_from_ref(ref2); } void map2map::rescale_src(const double s){ cnv1.rescale_src(s); } void map2map::rescale_dst(const double s){ cnv3.rescale_src(s); } /*******************************************************************/ // we can't use range() here, because this function // can be used in map2pt constructor. double map_lon0(const g_map &M){ dRect rg = M.range_ref(); dRect rr = M.range_ref_r(); dRect br = M.border.range(); if (br.empty()) return lon2lon0(rg.CNT().x); return lon2lon0( rg.x + rg.w/rr.w * (br.CNT().x-rr.x) ); } g_map mymap(const g_map_list & maplist){ g_map ret; Options O; // proj and proj_options - from the first map ret.map_proj=Proj("lonlat"); if (maplist.size()>0){ ret.map_proj=maplist[0].map_proj; ret.proj_opts=maplist[0].proj_opts; } // set scale from map with minimal scale // or 1/3600 degree if no map exists double mpp=1e99; g_map_list::const_iterator it; for (it = maplist.begin(); it != maplist.end(); it++){ double tmp=map_mpp(*it, it->map_proj); if (mpp>tmp) mpp=tmp; } if ((mpp>1e90)||(mpp<1e-90)) mpp=1/3600.0; // create refpoints pt2pt cnv(Datum("WGS84"), ret.map_proj, ret.proj_opts, Datum("WGS84"), Proj("lonlat"), Options()); dPoint p(maplist.range().CNT()); cnv.bck(p); dPoint p1=p+dPoint(mpp*1000,0); cnv.frw(p1); dPoint p2=p+dPoint(0,mpp*1000); cnv.frw(p2); cnv.frw(p); ret.push_back(g_refpoint(p.x,p.y, 0,1000)); ret.push_back(g_refpoint(p1.x,p1.y, 1000,1000)); ret.push_back(g_refpoint(p2.x,p2.y, 0,0)); return ret; } g_map mymap(const geo_data & world){ g_map ret; Options O; // put all maps into one map_list g_map_list maps; for (vector<g_map_list>::const_iterator ml = world.maps.begin(); ml!=world.maps.end(); ml++){ maps.insert(maps.end(), ml->begin(), ml->end()); } return mymap(maps); } double map_mpp(const g_map &map, Proj P){ if (map.size()<3) return 0; double l1=0, l2=0; g_map map1=map; map1.map_proj=P; if (P==Proj("tmerc") && !map1.proj_opts.exists("lon0")) map1.proj_opts.put("lon0", map_lon0(map1)); convs::pt2wgs c(Datum("wgs84"), P, map1.proj_opts); - for (int i=1; i<map.size();i++){ + for (size_t i=1; i<map.size();i++){ dPoint p1(map[i-1].x,map[i-1].y); dPoint p2(map[i].x, map[i].y); c.bck(p1); c.bck(p2); l1+=pdist(p1,p2); l2+=pdist(dPoint(map[i].xr, map[i].yr), dPoint(map[i-1].xr, map[i-1].yr)); } if (l2==0) return 0; return l1/l2; } double lon2lon0(const double lon){ double lon0 =floor( lon/6.0 ) * 6 + 3; while (lon0>180) lon0-=360; while (lon0<-180) lon0+=360; return lon0; } int lon2pref(const double lon){ double lon0 = lon2lon0(lon); return (lon0<0 ? 60:0) + (lon0-3)/6 + 1; } double lon_pref2lon0(const double lon){ int pref= floor(lon/1e6); if (pref==0) throw Err() << "zero coordinate prefix"; return (pref-(pref>30 ? 60:0))*6-3; } double lon_delprefix(const double lon){ return lon - floor( lon/1e6 ) * 1e6; } }//namespace
ushakov/mapsoft
570832f7f8f6af364158e194257304a116fec8bf
core/2d: fix sign-compare warning
diff --git a/core/2d/conv.cpp b/core/2d/conv.cpp index 7f90876..791cbf9 100644 --- a/core/2d/conv.cpp +++ b/core/2d/conv.cpp @@ -1,180 +1,180 @@ #include "conv.h" #include "line_utils.h" Conv::Conv(){sc_dst=1; sc_src=1;} void Conv::line_frw_p2p(dLine & l) const { for (dLine::iterator i=l.begin(); i!=l.end(); i++) frw(*i); } void Conv::line_frw_p2p(dMultiLine & l) const { for (dMultiLine::iterator i=l.begin(); i!=l.end(); i++) for (dLine::iterator j=i->begin(); j!=i->end(); j++) frw(*j); } void Conv::line_bck_p2p(dLine & l) const { for (dLine::iterator i=l.begin(); i!=l.end(); i++) bck(*i); } void Conv::line_bck_p2p(dMultiLine & l) const { for (dMultiLine::iterator i=l.begin(); i!=l.end(); i++) for (dLine::iterator j=i->begin(); j!=i->end(); j++) bck(*j); } dLine Conv::line_frw(const dLine & l, double acc, int max) const { dLine ret; if (l.size()==0) return ret; dPoint P1 = l[0], P1a =P1; frw(P1a); ret.push_back(P1a); // add first point dPoint P2, P2a; - for (int i=1; i<l.size(); i++){ + for (size_t i=1; i<l.size(); i++){ P1 = l[i-1]; P2 = l[i]; double d = pdist(P1-P2)/(max+1)*1.5; do { P1a = P1; frw(P1a); P2a = P2; frw(P2a); // C1 - is a center of (P1-P2) // C2-C1 is a perpendicular to (P1-P2) with acc length dPoint C1 = (P1+P2)/2.; dPoint C2 = C1 + acc*pnorm(dPoint(P1.y-P2.y, -P1.x+P2.x)); dPoint C1a = C1; frw(C1a); dPoint C2a = C2; frw(C2a); if ((pdist(C1a, (P1a+P2a)/2.) < pdist(C1a,C2a)) || (pdist(P1-P2) < d)){ // go to the rest of line (P2-l[i]) ret.push_back(P2a); P1 = P2; P2 = l[i]; } else { // go to the first half (P1-C1) of current line P2 = C1; } } while (P1!=P2); } return ret; } dLine Conv::line_bck(const dLine & l, double acc, int max) const { dLine ret; if (l.size()==0) return ret; dPoint P1 = l[0], P1a =P1; bck(P1a); ret.push_back(P1a); dPoint P2, P2a; - for (int i=1; i<l.size(); i++){ + for (size_t i=1; i<l.size(); i++){ P1 = l[i-1]; P2 = l[i]; double d = pdist(P1-P2)/(max+1)*1.5; do { P1a = P1; bck(P1a); P2a = P2; bck(P2a); dPoint C1 = (P1+P2)/2.; dPoint C1a = C1; bck(C1a); if ((pdist(C1a, (P1a+P2a)/2.) < acc) || (pdist(P1-P2) < d)){ ret.push_back(P2a); P1 = P2; P2 = l[i]; } else { P2 = C1; } } while (P1!=P2); } return ret; } // convert a rectagle and return bounding box of resulting figure dRect Conv::bb_frw(const dRect & R, double acc, int max) const { dLine l = line_frw(rect2line(R), acc, max); return l.range(); } dRect Conv::bb_bck(const dRect & R, double acc, int max) const { dLine l = line_bck(rect2line(R),acc, max); return l.range(); } double Conv::ang_frw(dPoint p, double a, double dx) const{ dPoint p1 = p + dPoint(dx*cos(a), dx*sin(a)); dPoint p2 = p - dPoint(dx*cos(a), dx*sin(a)); frw(p1); frw(p2); p1-=p2; return atan2(p1.y, p1.x); } double Conv::ang_bck(dPoint p, double a, double dx) const{ dPoint p1 = p + dPoint(dx*cos(a), dx*sin(a)); dPoint p2 = p - dPoint(dx*cos(a), dx*sin(a)); bck(p1); bck(p2); p1-=p2; return atan2(p1.y, p1.x); } double Conv::angd_frw(dPoint p, double a, double dx) const{ return 180.0/M_PI * ang_frw(p, M_PI/180.0*a, dx); } double Conv::angd_bck(dPoint p, double a, double dx) const{ return 180.0/M_PI * ang_bck(p, M_PI/180.0*a, dx); } dPoint Conv::units_frw(dPoint p) const{ dPoint p1 = p + dPoint(1,0); dPoint p2 = p + dPoint(0,1); frw(p), frw(p1), frw(p2); return dPoint(pdist(p1-p), pdist(p2-p)); } dPoint Conv::units_bck(dPoint p) const{ dPoint p1 = p + dPoint(1,0); dPoint p2 = p + dPoint(0,1); bck(p), bck(p1), bck(p2); return dPoint(pdist(p1-p), pdist(p2-p)); } void Conv::image_frw(const iImage & src_img, iImage & dst_img, const iPoint & shift, const double scale) const{ for (int y=0; y<dst_img.h; y++){ for (int x=0; x<dst_img.w; x++){ dPoint p(x,y); p+=shift; bck(p); p*=scale; int c = src_img.safe_get(int(p.x),int(p.y)); dst_img.set_a(x,y,c); } } } void Conv::image_bck(const iImage & src_img, iImage & dst_img, const iPoint & shift, const double scale) const{ for (int y=0; y<dst_img.h; y++){ for (int x=0; x<dst_img.w; x++){ dPoint p(x,y); p+=shift; frw(p); p*=scale; int c = src_img.safe_get(int(p.x),int(p.y)); dst_img.set_a(x,y,c); } } } void Conv::rescale_src(const double s){ sc_src*=s; } void Conv::rescale_dst(const double s){ sc_dst*=s; } diff --git a/core/2d/line_dist.cpp b/core/2d/line_dist.cpp index eb1c849..d5a75c3 100644 --- a/core/2d/line_dist.cpp +++ b/core/2d/line_dist.cpp @@ -1,132 +1,132 @@ #include "line_dist.h" LineDist::LineDist(const dLine & _line): line(_line){ current_l=0; current_n=0; double l=0; ls.push_back(0); - for (int j=1; j<_line.size(); j++){ + for (size_t j=1; j<_line.size(); j++){ dPoint p1 (_line[j-1]); dPoint p2 (_line[j]); if (p1 != p2) l+=pdist(p1,p2); ls.push_back(l); } } double LineDist::length() const { return ls[ls.size()-1]; } dPoint LineDist::pt() const{ if (is_end()) return line[current_n]; else return (line[current_n] + (line[current_n+1]-line[current_n]) * (current_l-ls[current_n])/(ls[current_n+1]-ls[current_n]) ); } double LineDist::dist() const { return current_l; } dPoint LineDist::tang() const{ if (is_end()) return dPoint(1,0); return pnorm(line[current_n+1]-line[current_n]); } dPoint LineDist::norm() const{ dPoint ret = tang(); return dPoint(-ret.y, ret.x); } dLine LineDist::get_points(double dl){ dLine ret; if (dl <= 0) return ret; double l = current_l + dl; // добавим первую точку ret.push_back(pt()); if (is_end()) return ret; while (current_l < l){ if (is_end()) return ret; move_frw_to_node(); // добавим следующий узел ret.push_back(line[current_n]); } // последний узел находится дальше, чем нужная нам длина. // подвинем... current_n--; current_l = l; *ret.rbegin() = pt(); return ret; } void LineDist::move_begin(){ current_l = 0; current_n = 0; } void LineDist::move_end(){ current_n = ls.size()-1; current_l = ls[current_n]; } void LineDist:: move_frw(double dl){ if (dl < 0) {move_bck(-dl); return;} if (dl == 0) return; double l = current_l + dl; while (current_l < l){ if (is_end()) return; move_frw_to_node(); } current_n--; current_l=l; } void LineDist::move_bck(double dl){ if (dl < 0) {move_frw(-dl); return;} if (dl == 0) return; double l = current_l - dl; while (current_l > l){ if (current_n == 0) return; move_bck_to_node(); } current_l=l; } void LineDist::move_frw_to_node(){ if (current_n == ls.size()-1) return; current_n++; current_l=ls[current_n]; } void LineDist::move_bck_to_node(){ if ((current_l==ls[current_n]) && (current_n!=0)) current_n--; current_l=ls[current_n]; } bool LineDist::is_end() const{ return (current_n == ls.size()-1); } bool LineDist::is_begin() const{ return (current_n == 0); } diff --git a/core/2d/line_dist.h b/core/2d/line_dist.h index 3c0aaea..96641e4 100644 --- a/core/2d/line_dist.h +++ b/core/2d/line_dist.h @@ -1,52 +1,52 @@ #ifndef LINE_DIST_H #define LINE_DIST_H #include "line.h" ///\addtogroup lib2d ///@{ ///\defgroup line_dist ///@{ /** Класс, позволяющий перемещаться вдоль линии, получая различные параметры. Сделано для рисования условных обозначений - всяких сложных пунктиров и т.п. Линия параметризуется длиной, по ней можно ходить вперед и назад, получая точки, расположенные через нужные интервалы, направление касательной и нормали в этих точках и т.п. */ class LineDist{ dLine line; // копия линии std::vector<double> ls; // lengths from the beginning to every node - int current_n; // current node + size_t current_n; // current node double current_l; // current distance from the current_n public: LineDist(const dLine & _line); ///< Constructor: create LineDist object from a line. double length() const; ///< Get line length. dPoint pt() const; ///< Get current point. double dist() const; ///< Get current distance from the line beginning. dPoint tang() const; ///< Get unit tangent vector at current point. dPoint norm() const; ///< Get unit normal vector at current point. /// Get part of line with dl length, starting from current point; /// move current point by dl dLine get_points(double dl); void move_begin(); ///< Move current point to the first node. void move_end(); ///< Move current point to the last node. void move_frw(double dl); ///< Move current point forward by dl distance. void move_bck(double dl); ///< Move current point backward by dl distance. void move_frw_to_node(); ///< Move current point forward to the nearest node. void move_bck_to_node(); ///< Move current point backward to the nearest node. bool is_begin() const; ///< Is current point at the first node? bool is_end() const; ///< Is current point at the last node? }; #endif
ushakov/mapsoft
e984a25532b4021a0ac76b2d0cd22280eaf03a7c
core/jeeps: fix multiple definition error (for gcc-10)
diff --git a/core/jeeps/garminusb.h b/core/jeeps/garminusb.h index 9681822..d790966 100644 --- a/core/jeeps/garminusb.h +++ b/core/jeeps/garminusb.h @@ -1,68 +1,74 @@ /* Definitions for Garmin USB protocol and implementation. Copyright (C) 2004, 2005, 2006 Robert Lipe, [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111 USA */ + +#ifndef garminusb_h +#define garminusb_h + #include <stdio.h> #include <string.h> /* This structure is a bit funny looking to avoid variable length * arrays which aren't present in C89. This contains the visible * fields in the USB packets of the Garmin USB receivers (60C, 76C, etc.) * All data are little endian. */ typedef union { struct { unsigned char type; unsigned char reserved1; unsigned char reserved2; unsigned char reserved3; unsigned char pkt_id[2]; unsigned char reserved6; unsigned char reserved7; unsigned char datasz[4]; unsigned char databuf[1]; /* actually an variable length array... */ } gusb_pkt; unsigned char dbuf[1024]; } garmin_usb_packet; /* * Internal interfaces that are common regardless of underlying * OS implementation. */ #define GUSB_MAX_UNITS 20 -struct garmin_unit_info { +struct garmin_unit_info_t { unsigned long serial_number; unsigned long unit_id; unsigned long unit_version; char *os_identifier; /* In case the OS has another name for it. */ char *product_identifier; /* From the hardware itself. */ -} garmin_unit_info[GUSB_MAX_UNITS]; +}; int gusb_cmd_send(const garmin_usb_packet *obuf, size_t sz); int gusb_cmd_get(garmin_usb_packet *ibuf, size_t sz); int gusb_init(const char *portname, gpsdevh **dh); int gusb_close(gpsdevh *); /* * New packet types in USB. */ #define GUSB_SESSION_START 5 /* We request units attention */ #define GUSB_SESSION_ACK 6 /* Unit responds that we have its attention */ #define GUSB_REQUEST_BULK 2 /* Unit requests we read from bulk pipe */ + +#endif \ No newline at end of file diff --git a/core/jeeps/gpsusbcommon.c b/core/jeeps/gpsusbcommon.c index 43433d7..46b87eb 100644 --- a/core/jeeps/gpsusbcommon.c +++ b/core/jeeps/gpsusbcommon.c @@ -1,268 +1,270 @@ /* Garmin USB layer - OS independent component. Copyright (C) 2006 Robert Lipe, [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111 USA */ #include "gps.h" #include "garminusb.h" #include "gpsusbcommon.h" /* * This receive logic is a little convoluted as we go to some efforts here * to hide most of the differences between the bulk only and bulk-interrupt * protocols as exhibited in the handhelds and dashtops. */ enum { rs_fromintr, rs_frombulk } receive_state; static gusb_llops_t *gusb_llops; +struct garmin_unit_info_t garmin_unit_info[GUSB_MAX_UNITS]; + /* Decide when to truncate packets for debug output */ #define DEBUG_THRESH (i > 10) /* Called from OS layer to register its low-level entry points. */ void gusb_register_ll(gusb_llops_t *p) { gusb_llops = p; } int gusb_close(gpsdevh *dh) { garmin_usb_packet scratch; memset(&scratch, 0, sizeof(scratch)); switch (receive_state) { case rs_frombulk: gusb_cmd_get(&scratch, sizeof(scratch)); break; default: break; } gusb_llops->llop_close(dh); return 1; #if BOOGER garmin_usb_packet scratch = {0}; abort(); switch (receive_state) { case rs_frombulk: gusb_cmd_get(dh, &scratch, sizeof(scratch)); break; } return 1; #endif } int gusb_cmd_get(garmin_usb_packet *ibuf, size_t sz) { int rv; unsigned char *buf = (unsigned char *) &ibuf->dbuf; int orig_receive_state; top: orig_receive_state = receive_state; switch (receive_state) { case rs_fromintr: rv = gusb_llops->llop_get_intr(ibuf, sz); break; case rs_frombulk: rv = gusb_llops->llop_get_bulk(ibuf, sz); break; default: fprintf(stderr, "Unknown receiver state %d\n", receive_state); } if (gps_show_bytes) { int i; const char *m1, *m2; unsigned short pkttype = le_read16(&ibuf->gusb_pkt.databuf[0]); GPS_Diag("RX (%s) [%d]:", receive_state == rs_fromintr ? "intr" : "bulk", rv); for(i=0;i<rv;i++) { if (DEBUG_THRESH) { GPS_Diag("[...]"); break; } GPS_Diag("%02x ", buf[i]); } for(i=0;i<rv;i++) { if (DEBUG_THRESH) { GPS_Diag("[...]"); break; } GPS_Diag("%c", isalnum(buf[i])? buf[i] : '.'); } m1 = Get_Pkt_Type(ibuf->gusb_pkt.pkt_id[0], pkttype, &m2); if ((rv == 0) && (receive_state == rs_frombulk) ) {m1= "RET2INTR";m2=NULL;}; GPS_Diag("(%-8s%s)\n", m1, m2 ? m2 : ""); } /* Adjust internal state and retry the read */ if ((rv > 0) && (ibuf->gusb_pkt.pkt_id[0] == GUSB_REQUEST_BULK)) { receive_state = rs_frombulk; goto top; } /* * If we were reading from the bulk pipe and we just got * a zero request, adjust our internal state. * It's tempting to retry the read here to hide this "stray" * packet from our callers, but that only works when you know * there's another packet coming. That works in every case * except the A000 discovery sequence. */ if ((receive_state == rs_frombulk) && (rv <= 0)) { receive_state = rs_fromintr; } return rv; } int gusb_cmd_send(const garmin_usb_packet *opkt, size_t sz) { unsigned int rv, i; unsigned char *obuf = (unsigned char *) &opkt->dbuf; const char *m1, *m2; rv = gusb_llops->llop_send(opkt, sz); if (gps_show_bytes) { const unsigned short pkttype = le_read16(&opkt->gusb_pkt.databuf[0]); GPS_Diag("TX [%d]:", sz); for(i=0;i<sz;i++) GPS_Diag("%02x ", obuf[i]); for(i=0;i<sz;i++) GPS_Diag("%c", isalnum(obuf[i])? obuf[i] : '.'); m1 = Get_Pkt_Type(opkt->gusb_pkt.pkt_id[0], pkttype, &m2); GPS_Diag("(%-8s%s)\n", m1, m2 ? m2 : ""); } /* * Recursion, when used in a disciplined way, can be our friend. * * The Garmin protocol requires that packets that are exactly * a multiple of the max tx size be followed by a zero length * packet. Do that here so we can see it in debugging traces. */ if (sz && !(sz % gusb_llops->max_tx_size)) { gusb_cmd_send(opkt, 0); } return (rv); } void gusb_list_units() { int i; for (i = 0; i < GUSB_MAX_UNITS; i++) { if (garmin_unit_info[i].serial_number) { printf("%d %lu %lu %s\n", i, garmin_unit_info[i].serial_number, garmin_unit_info[i].unit_id, garmin_unit_info[i].product_identifier ); } } } void -gusb_id_unit(struct garmin_unit_info *gu) +gusb_id_unit(struct garmin_unit_info_t *gu) { static const char oid[12] = {20, 0, 0, 0, 0xfe, 0, 0, 0, 0, 0, 0, 0}; garmin_usb_packet iresp; int i; gusb_cmd_send((garmin_usb_packet *)oid, sizeof(oid)); for (i = 0; i < 25; i++) { iresp.gusb_pkt.type = 0; if (gusb_cmd_get(&iresp, sizeof(iresp)) < 0) { return; } if (le_read16(iresp.gusb_pkt.pkt_id) == 0xff) { gu->product_identifier = xstrdup((char *) iresp.gusb_pkt.databuf+4); gu->unit_id = le_read16(iresp.gusb_pkt.databuf+0); gu->unit_version = le_read16(iresp.gusb_pkt.databuf+2); } /* * My goodnesss, this is fragile. During command syncup, * we need to know if we're at the end. The 0xfd packet * is promised by Garmin engineering to be the last. */ if (le_read16(iresp.gusb_pkt.pkt_id) == 0xfd) return; } fprintf(stderr, "Unable to sync with Garmin USB device in %d attempts.", i); } void gusb_syncup(void) { static int unit_number; static const char oinit[12] = {0, 0, 0, 0, GUSB_SESSION_START, 0, 0, 0, 0, 0, 0, 0}; garmin_usb_packet iresp; int i; /* * This is our first communication with the unit. */ receive_state = rs_fromintr; for(i = 0; i < 25; i++) { le_write16(&iresp.gusb_pkt.pkt_id, 0); le_write32(&iresp.gusb_pkt.datasz, 0); le_write32(&iresp.gusb_pkt.databuf, 0); gusb_cmd_send((const garmin_usb_packet *) oinit, sizeof(oinit)); gusb_cmd_get(&iresp, sizeof(iresp)); if ((le_read16(iresp.gusb_pkt.pkt_id) == GUSB_SESSION_ACK) && (le_read32(iresp.gusb_pkt.datasz) == 4)) { unsigned serial_number = le_read32(iresp.gusb_pkt.databuf); garmin_unit_info[unit_number].serial_number = serial_number; gusb_id_unit(&garmin_unit_info[unit_number]); unit_number++; return; } } fprintf(stderr, "Unable to establish USB syncup\n"); }
ushakov/mapsoft
f07ec214b6d470e952e3b72cba7e2471eb05dfee
core/2d/point.h: add missing header (for gcc-10)
diff --git a/core/2d/point.h b/core/2d/point.h index 3c4eeb4..367680d 100644 --- a/core/2d/point.h +++ b/core/2d/point.h @@ -1,193 +1,194 @@ #ifndef POINT_H #define POINT_H #include <boost/operators.hpp> #include <ios> // for << and >> operators #include <iomanip> // for setprecision +#include <istream> // for std::ws #include <cmath> // for rint ///\addtogroup lib2d ///@{ ///\defgroup point ///@{ /// 2-d point template <typename T> struct Point #ifndef SWIG : public boost::additive<Point<T> >, public boost::multiplicative<Point<T>,T>, public boost::less_than_comparable<Point<T> >, public boost::equality_comparable<Point<T> > #endif { T x; ///< x coordinate T y; ///< y coordinate /// Constructors Point(T _x, T _y): x(_x), y(_y) { } Point(): x(0), y(0) { } /// Swap point with other one. void swap (Point & other) { std::swap (x, other.x); std::swap (y, other.y); } /// Subtract corresponding coordinates: p=Point(p.x-other.x, p.y-other.y). Point<T> & operator-= (Point const & other) { x -= other.x; y -= other.y; return *this; } /// Add corresponding coordinates: p=Point(p.x+other.x, p.y+other.y). Point<T> & operator+= (Point const & other) { x += other.x; y += other.y; return *this; } /// Divide coordinates by k: p=Point(p.x/k, p.y/k). Point<T> & operator/= (T k) { x /= k; y /= k; return *this; } /// Multiply coordinates by k: p=Point(p.x*k, p.y*k). Point<T> & operator*= (T k) { x *= k; y *= k; return *this; } /// Invert point coordinates. Point<T> & operator- () { x = -x; y = -y; return *this; } #ifndef SWIG /// Less then operator: (x < other.x) || ((x == other.x) && (y < other.y)). bool operator< (const Point<T> & other) const { return (x<other.x) || ((x==other.x)&&(y<other.y)); } /// Equal opertator: (x==other.x) && (y==other.y). bool operator== (const Point<T> & other) const { return (x==other.x)&&(y==other.y); } /// Cast to Point<double>. operator Point<double>() const{ return Point<double>(double(this->x), double(this->y)); } /// Cast to Point<int>. operator Point<int>() const{ return Point<int>(int(rint(this->x)), int(rint(this->y))); } #else // SWIG // Replace boost added standalone operators. %extend { Point<T> operator+ (Point<T> const & t) { return *$self + t; } Point<T> operator- (Point<T> const & t) { return *$self - t; } Point<T> operator/ (T k) { return *$self / k; } Point<T> operator* (T k) { return *$self * k; } swig_cmp(Point<T>); swig_str(); } #endif // SWIG /// Calculate manhattan length: abs(x)+abs(y). /** \todo remove -- NOT USED! */ T manhattan_length () const { return abs(x) + abs(y); } }; /// \relates Point /// \brief Output operator: print point as a comma-separated pair of coordinartes. template <typename T> std::ostream & operator<< (std::ostream & s, const Point<T> & p){ s << std::noshowpos << std::setprecision(9) << p.x << "," << p.y; return s; } /// \relates Point /// \brief Input operator: read point from a comma-separated pair of coordainates. template <typename T> std::istream & operator>> (std::istream & s, Point<T> & p){ char sep; s >> std::ws >> p.x >> std::ws >> sep; if (sep!=','){ s.setstate(std::ios::failbit); return s; } s >> std::ws >> p.y >> std::ws; s.setstate(std::ios::goodbit); return s; } /// \relates Point /// \brief Scalar multiplication: p1.x*p2.x + p1.y*p2.y. template <typename T> double pscal(const Point<T> & p1, const Point<T> & p2){ return p1.x*p2.x + p1.y*p2.y; } /// \relates Point /// \brief Length: sqrt(double(p.x*p.x + p.y*p.y)). /// \todo move to Point class? template <typename T> double pdist(const Point<T> & p){ return sqrt((double)(pscal(p,p))); } /// \relates Point /// \brief Distance: pdist(p1-p2). template <typename T> double pdist(const Point<T> & p1, const Point<T> & p2){ return pdist(p1-p2); } /// \relates Point /// \brief Normalize. /// \todo move to Point class? template <typename T> Point<double> pnorm(const Point<T> & p){ double l = pdist(p); return Point<double>(double(p.x)/l, double(p.y/l)); } /// \relates Point /// \brief Absolute value. /// \todo move to Point class? template <typename T> Point<T> pabs(const Point<T> & p){ return Point<T>( p.x>0?p.x:-p.x, p.y>0?p.y:-p.y ); } /// \relates Point /// \brief Point with double coordinates typedef Point<double> dPoint; /// \relates Point /// \brief Point with int coordinates typedef Point<int> iPoint; #endif /* POINT_H */
ushakov/mapsoft
ad86a3a317523aa0b5a529619ed1368a5bfbd0d3
vmap3: add missed install targets
diff --git a/vector/vmap3/SConscript b/vector/vmap3/SConscript index 539f01c..bbc4cad 100644 --- a/vector/vmap3/SConscript +++ b/vector/vmap3/SConscript @@ -1,10 +1,13 @@ Import ('env') env.Program("vmap_render.cpp") env.Program("vmap_mmb_filter.cpp") env.Program("vmap_1km_filter.cpp") env.Program("vmap_fix_diff.cpp") env.Install(env.bindir, Split(""" vmap_render + vmap_mmb_filter + vmap_1km_filter + vmap_fix_diff """))
ushakov/mapsoft
23bd02a05ecf86280acbc2f836803699fa6b13b9
img_io/gobj_vmap: draw pattens with solid color at small scales (A.Kazantsev)
diff --git a/core/img_io/gobj_vmap.cpp b/core/img_io/gobj_vmap.cpp index 1e1f699..78016d5 100644 --- a/core/img_io/gobj_vmap.cpp +++ b/core/img_io/gobj_vmap.cpp @@ -1,796 +1,802 @@ #include <string> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include "loaders/image_r.h" #include "gobj_vmap.h" #include <jansson.h> using namespace std; GObjVMAP::GObjVMAP(vmap::world * _W, const Options & O): W(_W), zc(W->style){ pics_dpi = O.get("pics_dpi", 600.0); bgcolor = O.get("bgcolor", 0xFFFFFF); dpi = O.get("dpi", 200.0); lw1 = O.get("line_width", dpi/105.0); cntrs = O.get("contours", true); use_aa = O.get("antialiasing", true); label_marg = O.get("label_marg", 2.5); label_style = O.get("label_style", 2); grid_step = O.get("grid", 0.0); transp = O.get("transp_margins", false); grid_labels = O.get("grid_labels", 0); { // set pattern filter std::string flt = O.get<std::string>("patt_filter", "good"); if (flt == "fast") patt_filter = Cairo::FILTER_FAST; else if (flt == "good") patt_filter = Cairo::FILTER_GOOD; else if (flt == "best") patt_filter = Cairo::FILTER_BEST; else if (flt == "nearest") patt_filter = Cairo::FILTER_NEAREST; else if (flt == "bilinear") patt_filter = Cairo::FILTER_BILINEAR; else throw Err() << "unknown patt_filter setting: " << flt; } // Read render data from json file. (2018-09) // File structure: json array of objects. // Each array element represents an action (draw object type, draw grid etc.) std::string render_data_fname = O.get("render_data", std::string()); if (render_data_fname != ""){ json_error_t e; json_t *J = json_load_file(render_data_fname.c_str(), 0, &e); if (!J) throw Err() << e.text << " in " << e.source << ":" << e.line << ":" << e.column; try { if (!json_is_array(J)) throw Err() << "RenderData should be an array of objects"; size_t i; json_t *c; json_array_foreach(J, i, c){ Opts o; if (!json_is_object(c)) throw Err() << "RenderData should be an array of objects"; const char *k; json_t *v; json_object_foreach(c, k, v){ if (json_is_string(v)) o.put(k, json_string_value(v)); else if (json_is_integer(v)) o.put(k, json_integer_value(v)); else if (json_is_real(v)) o.put(k, json_real_value(v)); else throw Err() << "wrong value type for " << k; } render_data.push_back(o); } } catch (Err e){ json_decref(J); throw e; } json_decref(J); } } int GObjVMAP::draw(iImage &img, const iPoint &org){ if (W->brd.size()>2) ref.border=cnv.line_bck(W->brd)-org; if (ref.border.size()>2 && rect_intersect(iRect(ref.border.range()), img.range()).empty()) return GObj::FILL_NONE; // create Cairo surface and context cr.reset_surface(img); origin = org; if (!use_aa) cr->set_antialias(Cairo::ANTIALIAS_NONE); cr->set_fill_rule(Cairo::FILL_RULE_EVEN_ODD); // old code -- no render_data: if (render_data.size()==0) { // objects render_objects(); // grid if (grid_step>0){ if (ref.map_proj != Proj("tmerc")) cerr << "WARINIG: grid for non-tmerc maps is not supported!\n"; render_pulk_grid(grid_step, grid_step, false, ref); } // labels render_labels(); // border if (ref.border.size()>2) cr->render_border(img.range(), ref.border, transp? 0:bgcolor); // draw grid labels after labels if ((grid_step>0) && grid_labels){ if (ref.map_proj != Proj("tmerc")) cerr << "WARINIG: grid for non-tmerc maps is not supported!\n"; render_pulk_grid(grid_step, grid_step, true, ref); } return GObj::FILL_PART; } // new code std::vector<Opts>::const_iterator data; for (data=render_data.begin(); data!=render_data.end(); data++){ // Draw points. There are two types of points: a simple point and an image. // { point: 0x122, image: "images/file.png"} // { point: 0x122, color: 0x00FF00, size: 4} if (data->exists("point")){ int type = data->get<int>("point"); int size = 4, color = 0; if (data->exists("image")) { std::string fname = data->get("image",std::string()); iImage I = image_r::load(fname.c_str()); if (I.empty()) throw Err() << "Can't read image: " << fname; auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) throw Err() << "Can't create cairo pattern from image: " << fname; patt->set_filter(patt_filter); // each object, each line inside the object, each point for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ for (dLine::const_iterator p=l->begin(); p!=l->end(); p++){ cr->save(); dPoint pp=(*p); cnv.bck(pp); pp-=origin; cr->translate(pp.x, pp.y); if (o->opts.exists("Angle")){ double a = o->opts.get<double>("Angle",0); a = cnv.ang_bck(o->center(), M_PI/180 * a, 0.01); cr->rotate(a); } cr->set_source(patt); cr->paint(); cr->restore(); } } } } else { cr->save(); cr->set_line_width(lw1*data->get<int>("size", size)); cr->set_color(data->get<int>("color", color)); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_points(l-origin); cr->stroke(); } cr->restore(); } }// point } // for data return GObj::FILL_PART; } void GObjVMAP::render_polygons(int type, int col, double curve_l){ if (!cr) return; cr->save(); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::area_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill(); } cr->restore(); } // contoured polygons void GObjVMAP::render_cnt_polygons(int type, int fill_col, int cnt_col, double cnt_th, double curve_l){ cr->save(); cr->set_color(fill_col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!= (type | zn::area_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill_preserve(); cr->save(); cr->set_color(cnt_col); cr->set_line_width(cnt_th*lw1); cr->stroke(); cr->restore(); } cr->restore(); } void GObjVMAP::render_line(int type, int col, double th, double curve_l){ if (!cr) return; cr->save(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 0, curve_l*lw1); cr->stroke(); } cr->restore(); } void GObjVMAP::render_points(int type, int col, double th){ if (!cr) return; cr->save(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_points(l-origin); cr->stroke(); } cr->restore(); } void GObjVMAP::render_img_polygons(int type, double curve_l){ type = type | zn::area_mask; std::map<int, zn::zn>::const_iterator z = zc.find_type(type); if (z==zc.znaki.end()) return; string f = z->second.pic + ".png"; // picture filename iImage I = image_r::load(f.c_str()); if (I.empty()) cerr << "Empty image for type " << type << "\n"; - auto patt = cr->img2patt(I, pics_dpi/dpi); - if (!patt) return; - patt->set_filter(patt_filter); + if (pics_dpi / dpi < 12) { + auto patt = cr->img2patt(I, pics_dpi/dpi); + if (!patt) return; + patt->set_filter(patt_filter); + patt->set_extend(Cairo::EXTEND_REPEAT); + cr->set_source(patt); + } else { + // Use average fill color for too little patterns on this DPI + unsigned int r=0, g=0, b=0, a=0, alpha, c; + for(int i = 0; i < I.h * I.w; i++) { + c = I.data[i]; + alpha = (c >> 24) & 0xff; + a += alpha; + b += alpha * ((c >> 16) & 0xff); + g += alpha * ((c >> 8) & 0xff); + r += alpha * ((c >> 0) & 0xff); + } + if (a != 0) { + b /= a; + g /= a; + r /= a; + } + a /= I.w * I.h; + c = (a << 24) | (b << 16) | (g << 8) | r; + + cr->set_color(c); + } // polygons filled with image pattern if (z->second.pic_type=="fill"){ - patt->set_extend(Cairo::EXTEND_REPEAT); cr->save(); - cr->set_source(patt); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill(); } cr->restore(); } - // place image in the center of polygons - else { - for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ - if (o->type!=type) continue; - for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ - if (l->size()<1) continue; - dPoint p=l->range().CNT(); - cnv.bck(p); p = p-origin; - cr->save(); - cr->translate(p.x, p.y); - cr->set_source(patt); - cr->paint(); - cr->restore(); - } - } - } } // place image in points void GObjVMAP::render_im_in_points(int type){ std::map<int, zn::zn>::const_iterator z = zc.find_type(type); if (z==zc.znaki.end()) return; string f = z->second.pic + ".png"; // picture filename iImage I = image_r::load(f.c_str()); if (I.empty()) cerr << "Empty image for type " << type << "\n"; auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) return; patt->set_filter(patt_filter); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ if (l->size()<1) continue; cr->save(); dPoint p=(*l)[0]; cnv.bck(p); p-=origin; cr->translate(p.x, p.y); if (o->opts.exists("Angle")){ double a = o->opts.get<double>("Angle",0); a = cnv.ang_bck(o->center(), M_PI/180 * a, 0.01); cr->rotate(a); } cr->set_source(patt); cr->paint(); cr->restore(); } } } // paths for bridge sign void GObjVMAP::mkbrpath1(const vmap::object & o){ for (vmap::object::const_iterator l=o.begin(); l!=o.end(); l++){ if (l->size()<2) continue; dPoint p1 = (*l)[0], p2 = (*l)[1]; cnv.bck(p1); cnv.bck(p2); cr->move_to(p1-origin); cr->line_to(p2-origin); } } void GObjVMAP::mkbrpath2(const vmap::object & o, double th, double side){ th*=lw1/2.0; side*=lw1/sqrt(2.0); for (vmap::object::const_iterator l=o.begin(); l!=o.end(); l++){ if (l->size()<2) continue; dPoint p1 = (*l)[0], p2 = (*l)[1]; cnv.bck(p1); cnv.bck(p2); p1-=origin; p2-=origin; dPoint t = pnorm(p2-p1); dPoint n(-t.y, t.x); dPoint P; P = p1 + th*n + side*(n-t); cr->move_to(P); P = p1 + th*n; cr->line_to(P); P = p2 + th*n; cr->line_to(P); P = p2 + th*n + side*(n+t); cr->line_to(P); P = p1 - th*n - side*(n+t); cr->move_to(P); P = p1 - th*n; cr->line_to(P); P = p2 - th*n; cr->line_to(P); P = p2 - th*n - side*(n-t); cr->line_to(P); } } void GObjVMAP::render_bridge(int type, double th1, double th2, double side){ cr->save(); cr->set_line_cap(Cairo::LINE_CAP_BUTT); cr->set_line_join(Cairo::LINE_JOIN_ROUND); if (th1!=0){ cr->set_line_width(th1*lw1); cr->set_color(0xFFFFFF); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; mkbrpath1(*o); cr->stroke(); } th1+=th2; } cr->set_line_width(th2*lw1); cr->set_color(0x0); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; mkbrpath2(*o, th1, side); cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_el(Conv & cnv, int type, int col, double th, double step){ render_line(type, col, th, 0); double width=th*1.2*lw1; step*=lw1; cr->save(); cr->cap_round(); cr->set_line_width(1.8*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); int n=1; while (ld.dist() < ld.length()){ dPoint vn=ld.norm()*width; dPoint vt=ld.tang()*width; dPoint p1,p2,p3; p1=p2=p3=ld.pt(); p1+=vn; p3-=vn; if (n%4 == 1){ p1+=vt; p3+=vt;} if (n%4 == 3){ p1-=vt; p3-=vt;} cr->move_to(p1); cr->line_to(p2); cr->line_to(p3); n++; ld.move_frw(fstep); } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_obr(Conv & cnv, int type, int col, double th){ render_line(type, col, th, 0); double width=th*2*lw1; double step=th*4*lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; int k=1; if (o->dir==2) k=-1; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); while (ld.dist() < ld.length()){ dPoint p=ld.pt(), vn=ld.norm()*width*k; cr->move_to(p); cr->line_to(p+vn); ld.move_frw(fstep); } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_zab(Conv & cnv, int type, int col, double th){ render_line(type, col, th, 0); double width=th*2*lw1; double step=th*8*lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; int k=1; if (o->dir==2) k=-1; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw((fstep-width)/2); int n=0; while (ld.dist() < ld.length()){ dPoint p=ld.pt(), v=(ld.norm()-ld.tang())*width*k; cr->move_to(p); cr->line_to(p+v); ld.move_frw((n%2==0)?width:fstep-width); n++; } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_val(Conv & cnv, int type, int col, double th, double width, double step){ width*=lw1/2; step*=lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); int n=0; while (ld.dist() < ld.length()){ dPoint p=ld.pt(), v=ld.norm()*width, t=ld.tang()*step/2; cr->move_to(p+v); cr->line_to(p+v); cr->move_to(p-v); cr->line_to(p-v); // cr->move_to(p-v); // cr->line_to(p+v); ld.move_frw(fstep); n++; } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_gaz(Conv & cnv, int type, int col, double th, double step){ render_line(type, col, th, 0); double width=th*0.8*lw1; step*=lw1; cr->save(); cr->set_line_width(lw1); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); while (ld.dist() < ld.length()){ dPoint p=ld.pt(); cr->begin_new_sub_path(); cr->arc(p.x, p.y, width, 0.0, 2*M_PI); ld.move_frw(fstep); } } } cr->set_color(0xFFFFFF); cr->fill_preserve(); cr->set_color(col); cr->stroke(); cr->restore(); } void GObjVMAP::render_grid_label(double c, double val, bool horiz, const dLine & border){ ostringstream ss; ss << setprecision(7) << val/1000.0; if (border.size()<1) return; dPoint pmin, pmax; double amin=0, amax=0; dLine::const_iterator i,j; for (i=border.begin(); i!=border.end(); i++){ j=i+1; if (j==border.end()) j=border.begin(); dPoint p1(*i); dPoint p2(*j); if (horiz){ if (p1.x == p2.x) continue; if (p1.x > p2.x) p1.swap(p2); // segment does not cross grid line: if ((p1.x >= c) || (p2.x < c)) continue; double a = atan2(p2.y-p1.y, p2.x-p1.x); // crossing point of grid line with border dPoint pc(c, p1.y + (p2.y-p1.y)*(c-p1.x)/(p2.x-p1.x)); if ((pmin==dPoint()) || (pmin.y > pc.y)) {pmin=pc; amin=a;} if ((pmax==dPoint()) || (pmax.y < pc.y)) {pmax=pc; amax=a;} } else { if (p1.y == p2.y) continue; if (p1.y > p2.y) p1.swap(p2); // segment does not cross grid line: if ((p1.y >= c) || (p2.y < c)) continue; double a = atan2(p2.y-p1.y, p2.x-p1.x); // crossing point of grid line with border dPoint pc(p1.x + (p2.x-p1.x)*(c-p1.y)/(p2.y-p1.y), c); if ((pmin==dPoint()) || (pmin.x > pc.x)) {pmin=pc; amin=a;} if ((pmax==dPoint()) || (pmax.x < pc.x)) {pmax=pc; amax=a;} } } if (amin>M_PI/2) amin-=M_PI; if (amin<-M_PI/2) amin+=M_PI; if (amax>M_PI/2) amax-=M_PI; if (amax<-M_PI/2) amax+=M_PI; bool drawmin, drawmax; int ydir_max=0, ydir_min=0; if (horiz){ drawmin = (pmin!=dPoint()) && (abs(amin) < M_PI* 0.1); drawmax = (pmax!=dPoint()) && (abs(amax) < M_PI* 0.1); pmin+=dPoint(0,-dpi/30); pmax+=dPoint(0,+dpi/30); ydir_max=2; } else{ drawmin = (pmin!=dPoint()) && (abs(amin) > M_PI* 0.4); drawmax = (pmax!=dPoint()) && (abs(amax) > M_PI* 0.4); if (amin>0) amin-=M_PI; if (amax<0) amax+=M_PI; pmin+=dPoint(-dpi/30,0); pmax+=dPoint(dpi/30,0); } if (drawmin) cr->render_text(ss.str().c_str(), pmin, amin, 0, 18, 8, dpi, 1,ydir_min); if (drawmax) cr->render_text(ss.str().c_str(), pmax, amax, 0, 18, 8, dpi, 1,ydir_max); } void GObjVMAP::render_pulk_grid(double dx, double dy, bool labels, const g_map & ref){ convs::map2pt cnv(ref, Datum("pulkovo"), Proj("tmerc"), ref.proj_opts); dRect rng_m = cnv.bb_frw(ref.border.range(), 1)-origin; dPoint pb( rng_m.x, rng_m.y ); dPoint pe( rng_m.x+rng_m.w, rng_m.y+rng_m.h ); dx *= W->rscale/100; dy *= W->rscale/100; double m=dy/10; // skip labels at distance m from horizontal edges dPoint p( dx * floor(rng_m.x/dx), dy * floor(rng_m.y/dy) ); dPoint pbc(pb); cnv.bck(pbc); pbc-=origin; dPoint pec(pe); cnv.bck(pec); pec-=origin; // note: pb.y < pe.y, but pbc.y > pec.y! cr->save(); cr->set_source_rgba(0,0,0,0.5); cr->set_line_width(2); while (p.x<pe.x){ dPoint pc(p); cnv.bck(pc); pc-=origin; if (labels) render_grid_label(pc.x, p.x, true, ref.border); else { cr->Cairo::Context::move_to(pc.x, pbc.y); cr->Cairo::Context::line_to(pc.x, pec.y); } p.x+=dx; } while (p.y<pe.y){ dPoint pc(p); cnv.bck(pc); pc-=origin; if (labels && (p.y > pb.y+m) && (p.y<pe.y-m)) render_grid_label(pc.y, p.y, false, ref.border); else { cr->Cairo::Context::move_to(pbc.x, pc.y); cr->Cairo::Context::line_to(pec.x, pc.y); } p.y+=dy; } cr->stroke(); cr->restore(); } void GObjVMAP::render_objects(){ bool hr = (W->style == "hr"); const int c_forest = 0xAAFFAA; const int c_field = 0xFFFFFF; const int c_fcont = 0x009000; const int c_glac = 0xFFE6C3; const int c_slope = 0xCCCCCC; const int c_way2 = 0x00B400; const int c_way5 = 0x00D8FF; const int c_hor = hr? 0x90B0D0:0x0060C0; const int c_build_gray = 0xB0B0B0; const int c_build_red = 0x8080FF; const int c_build_dred = 0x5959B0; const int c_build_green = 0x557F55; const int c_build_cnt = 0x000000; const int c_brd = 0x0000FF; const int c_brdg = 0x00FF00; const int c_riv_cnt = 0xFF6650; const int c_riv_fill = hr? 0xFFCE87:0xFFFF00; const int c_kanav = 0x0060C0; const int c_ovrag = 0x0040A0; const int c_hreb = hr? 0x0060C0:0x003080; const int c_lines = 0x888888; const int c_road_fill = 0x8080FF; const int c_obr = 0x000090; const int c_pt = hr? 0x003080:0x000000; //******************************* render_polygons(0x16, c_forest); // лес render_polygons(0x52, c_field); // поле render_polygons(0x15, c_forest); // остров леса list<iPoint> cnt; if (cntrs) cnt = make_cnt(c_forest, 2); // контуры леса render_img_polygons(0x4f); // свежая вырубка render_img_polygons(0x50); // старая вырубка render_img_polygons(0x14); // редколесье render_polygons(0x15, c_forest); // остров леса поверх вырубок if (cntrs){ filter_cnt(cnt, c_forest); // убираем контуры, оказавшеся поверх вырубок draw_cnt(cnt, c_fcont, 1); // рисуем контуры } cr->cap_round(); cr->join_round(); cr->set_dash(0, 2*lw1); render_line(0x23, c_fcont, 1, 0); // контуры, нарисованные вручную cr->unset_dash(); render_polygons(0x4d, c_glac, 20.0); // ледник render_polygons(0x19, c_slope, 20.0); // камни, песок render_img_polygons(0x8); // камни, песок render_img_polygons(0xD); // камни, песок //******************************* // извращение с линиями проходимости: // сперва вырезаем место для них в подложке cr->save(); cr->set_operator(Cairo::OPERATOR_CLEAR); cr->cap_butt(); render_line(0x32, c_way2, 3, 10); // плохой путь cr->set_dash(lw1, lw1); render_line(0x33, c_way2, 3, 10); // удовлетворительный путь render_line(0x34, c_way5, 3, 10); // хороший путь cr->unset_dash(); render_line(0x35, c_way2, 3, 10); // отличный путь cr->restore(); //******************************* render_cnt_polygons(0x4, c_build_gray, c_build_cnt, 0.7); // закрытые территории render_cnt_polygons(0xE, c_build_red, c_build_cnt, 0.7); // деревни render_cnt_polygons(0x1, c_build_dred, c_build_cnt, 0.7); // города render_cnt_polygons(0x4E, c_build_green, c_build_cnt, 0.7); // дачи render_cnt_polygons(0x1A, c_build_green, c_build_cnt, 0.7); // кладбища //******************************* cr->set_dash(8*lw1, 3*lw1); render_line(0x20, c_hor, 1, 20); // пунктирные горизонтали cr->unset_dash(); render_line(0x21, c_hor, 1, 20); // горизонтали render_line(0x22, c_hor, 1.6, 20); // жирные горизонтали //******************************* render_img_polygons(0x51); // болота render_img_polygons(0x4C); // болота труднопроходимые render_line(0x24, c_riv_cnt, 1, 0); // старые болота -- не использутся //******************************* cr->join_round(); cr->cap_round(); cr->set_dash(0, 2.5*lw1); render_line(0x2B, c_kanav, 1.6, 0); // сухая канава cr->unset_dash(); render_line(0x25, c_ovrag, 2, 20); // овраг render_line(0xC, c_hreb, 2, 20); // хребет render_line(0xF, c_hreb, 1.5, 20); // малый хребет cr->set_dash(0, 2.5*lw1); render_line(0x2C, c_hor, 2.5, 0); // вал cr->unset_dash();
ushakov/mapsoft
866632367a5e2342138a0d14da1014678b57127a
20191201-alt1
diff --git a/mapsoft.spec b/mapsoft.spec index 0dd4234..36647a2 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,183 +1,191 @@ Name: mapsoft -Version: 20191110 +Version: 20191201 Release: alt1 -License: GPL +License: GPL3.0 + Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man +BuildRequires: boost-geometry-devel perl-Text-Iconv %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %_bindir/map_rescale %_bindir/*.sh %_bindir/map_*_gk %_bindir/map_*_nom +%_bindir/mapsoft_wp_parse %changelog +* Sun Dec 01 2019 Vladislav Zavjalov <[email protected]> 20191201-alt1 +- fix a few problems in vmap_render and convs_gtiles (thanks to A.Kazantsev) +- add GPL3.0 license (Altlinux requires ambiguous license for all packages) +- fix python shebang (python -> python2) + * Sun Nov 10 2019 Vladislav Zavjalov <[email protected]> 20191110-alt1 - add more scripts to mapsoft_vmap package * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
ad645b914e3e754cb1933294e060fe89c5b626e5
scripts: fix python shebang: python -> python2
diff --git a/scripts/map-helper.py b/scripts/map-helper.py index f583c01..f839808 100755 --- a/scripts/map-helper.py +++ b/scripts/map-helper.py @@ -1,61 +1,61 @@ -#!/usr/bin/python +#!/usr/bin/python2 # GIMP plug-in to create map references for soviet nomenclature maps import re from gimpfu import * def helper_do (image, drawable, output_file_name, comment): gimp.progress_init("MapHelper") lst = pdb.gimp_path_list(image) print "lst[0] = " + str(lst[0]) if lst[0] != 1: gimp.progress_init("Bad Path List" + str(lst[0])) return path_name = lst[1][0] points = pdb.gimp_path_get_points (image, path_name) print "points[0] = " + str(points[0]) if points[0] != 1: gimp.progress_init("Bad Path Type " + str(points[0])) return coords = points[3] anchors = [] for i in range(0, len(coords), 3): x = coords[i] y = coords[i+1] t = coords[i + 2] if t == 1: anchors += [(x,y)] orig_file_name = pdb.gimp_image_get_filename(image) print "orig_file_name = " + orig_file_name print "output_file_name = " + output_file_name if orig_file_name == None: gimp.progress_init("Null Orig Filename") return last_slash = orig_file_name.rfind("/") + 1 orig_file_name = orig_file_name[last_slash:] f = open(output_file_name, "a") string = u"" + orig_file_name + " " for i in anchors: string += str(int(i[0])) + " " + str(int(i[1])) + " " string += comment + "\n" print "string = " + string f.write(string.encode("KOI8-R")) f.close() register("python_fu_maphelper", "Convert the only path in the image to a line of map reference", "Convert the only path in the image to a line of map reference", "Max Ushakov <[email protected]>", "Max Ushakov <[email protected]>", "2007", "<Image>/Python-Fu/Maps/Map Helper", "RGB*, GRAY*, INDEXED*", [ (PF_FILE, "output_file_name", "Output File Name", ""), (PF_STRING, "comment", "Map Comment", ""), ], [], helper_do) main() diff --git a/scripts/module-dep.py b/scripts/module-dep.py index 5b1caa7..e65e209 100755 --- a/scripts/module-dep.py +++ b/scripts/module-dep.py @@ -1,99 +1,99 @@ -#!/usr/bin/python +#!/usr/bin/python2 import os import sys import re def GetModules(topdir): for (d, dirs, files) in os.walk(topdir): srcs = [] for f in files: if f.endswith(".cpp") or f.endswith(".h") or f.endswith(".c"): srcs.append(f) yield (d, srcs) def GetIncludes(file): f = open(file, "r") include = re.compile("^ *#include \"(.*)\"") for line in f: m = include.search(line) if m: yield m.group(1) f.close() def GetLinks(top): cd = re.compile("\./(.*)") for (module, files) in GetModules("."): m = cd.match(module) if m: module = m.group(1) for f in files: fn = os.path.join(module, f) for n in GetIncludes(fn): p = os.path.normpath(os.path.join(module, n)) target_module = os.path.dirname(p) yield (module, target_module) def GetUniqLinks(top): t = {} for (s, d) in GetLinks(top): key = "%s %s" % (s, d) t[key] = t.get(key, 0) + 1 for (key, count) in t.iteritems(): (s, d) = key.split() yield s, d, count def AddToClusters(clusters, node, p): if len(p) == 0: if "." not in clusters: clusters["."] = [] clusters["."].append(node) return if p[0] not in clusters: clusters[p[0]] = {} AddToClusters(clusters[p[0]], node, p[1:]) def GatherClusters(all_nodes): clusters = {} for n in all_nodes: p = n.split("/") AddToClusters(clusters, n, p) return clusters def PrintClusters(clusters, prefix=""): for cname, cluster in clusters.iteritems(): if cname == ".": for n in cluster: print '"%s";' % n else: # figure out if we need a cluster for this if "." in cluster: clen = len(cluster) - 1 + len(cluster["."]) else: clen = len(cluster) if clen > 1: print 'subgraph "cluster_%s_%s" {' % (prefix, cname) PrintClusters(cluster, "%s_%s" % (prefix, cname)) print "}" else: PrintClusters(cluster, "%s_%s" % (prefix, cname)) def OmitNode(s): if re.search("experimental", s): return True if re.search("test", s): return True return False all_nodes = {} print "digraph G {" for (s, d, c) in GetUniqLinks("."): if OmitNode(s) or OmitNode(d): continue if s != d: print " \"%s\" -> \"%s\" [label=\"%s\"]" % (s, d, c) all_nodes[s] = 1 all_nodes[d] = 1 clusters = GatherClusters(all_nodes) PrintClusters(clusters) print "}"
ushakov/mapsoft
ab439a51c1a0abf7156eee403d9df7f8eacf4fb4
Add LICENSE (Altlinux requires unambiguous licence in all packages)
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>.
ushakov/mapsoft
52e46a784be3930ad7795fd91d63f1c10052cb5c
geo_io/geo_refs: change dpi calculation for google tiles (only --google mode), by A.Kazantsev
diff --git a/core/geo_io/geo_refs.cpp b/core/geo_io/geo_refs.cpp index a6102d3..e7b7bc4 100644 --- a/core/geo_io/geo_refs.cpp +++ b/core/geo_io/geo_refs.cpp @@ -1,344 +1,345 @@ // Привязки специальных карт и снимков #include "tiles/tiles.h" #include "geo_refs.h" #include "geo/geo_convs.h" #include "geo/geo_nom.h" #include "2d/line_utils.h" #include "err/err.h" #include <sstream> #include <iomanip> using namespace std; g_map mk_tmerc_ref(const dLine & points, double u_per_m, bool yswap){ g_map ref; if (points.size()<3){ cerr << "error in mk_tmerc_ref: number of points < 3\n"; return g_map(); } // Get refs. // Reduce border to 5 points, remove last one. dLine refs = points; refs.push_back(*refs.begin()); // to assure last=first refs = generalize(refs, -1, 5); refs.resize(4); // Create tmerc->lonlat tmerc conversion with wanted lon0, // convert refs to our map coordinates. Options PrO; PrO.put<double>("lon0", convs::lon2lon0(points.center().x)); convs::pt2wgs cnv(Datum("wgs84"), Proj("tmerc"), PrO); dLine refs_c(refs); cnv.line_bck_p2p(refs_c); refs_c *= u_per_m; // to out units refs_c -= refs_c.range().TLC(); double h = refs_c.range().h; // swap y if needed if (yswap){ for (int i=0;i<refs_c.size();i++) refs_c[i].y = h - refs_c[i].y; } // add refpoints to our map for (int i=0;i<refs.size();i++){ ref.push_back(g_refpoint(refs[i], refs_c[i])); } ref.map_proj=Proj("tmerc"); ref.proj_opts.put("lon0", convs::lon2lon0(refs.range().CNT().x)); // Now we need to convert border to map units. // We can convert them by the same way as refs, but // this is unnecessary duplicating of non-trivial code. // So we constract map2pt conversion from our map. // Set map border convs::map2wgs brd_cnv(ref); ref.border = brd_cnv.line_bck(points); ref.border.push_back(*ref.border.begin()); // to assure last=first ref.border = generalize(ref.border, 1000, -1); // 1 unit accuracy ref.border.resize(ref.border.size()-1); return ref; } void incompat_warning(const Options & o, const string & o1, const string & o2){ if (o.exists(o2)) cerr << "make reference warning: " << "skipping option --" << o2 << "\n" <<" which is incompatable with --" << o1 << "\n"; } vector<int> read_int_vec(const string & str){ istringstream s(str); char sep; int x; vector<int> ret; while (1){ s >> ws >> x; if (!s.fail()){ ret.push_back(x); s >> ws; } if (s.eof()) return ret; s >> ws >> sep; if (sep!=','){ cerr << "error while reading comma separated values\n"; return ret; } } } g_map mk_ref(Options & o){ g_map ret; // default values double dpi=300; - double google_dpi=-1; double rscale=100000; - double rs_factor=1.0; // proj units/m Datum datum("wgs84"); Proj proj("tmerc"); bool verbose=o.exists("verbose"); bool sw=!o.exists("swap_y"); // first step: process geom, nom, google options // -- create border and 4 refpoints in wgs84 lonlat // -- set map_proj and proj options // -- change defauld dpi and rscale if needed dRect geom; dLine refs; Options proj_opts; // rectangular map if (o.exists("geom")){ incompat_warning (o, "geom", "wgs_geom"); incompat_warning (o, "geom", "wgs_brd"); incompat_warning (o, "geom", "trk_brd"); incompat_warning (o, "geom", "nom"); incompat_warning (o, "geom", "google");\ dRect geom = o.get<dRect>("geom"); if (geom.empty()) throw Err() << "error: bad geometry"; datum = o.get<Datum>("datum", Datum("pulkovo")); proj = o.get<Proj>("proj", Proj("tmerc")); if ((proj == Proj("tmerc")) && (geom.x>=1e6)){ double lon0 = convs::lon_pref2lon0(geom.x); geom.x = convs::lon_delprefix(geom.x); proj_opts.put<double>("lon0", lon0); } if (o.exists("lon0")) proj_opts.put("lon0", o.get<double>("lon0")); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), datum, proj, proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); ret.border = cnv.line_bck(refs, 1e-6); refs.resize(4); cnv.line_bck_p2p(refs); } else if (o.exists("wgs_geom")){ incompat_warning (o, "wgs_geom", "geom"); incompat_warning (o, "wgs_geom", "wgs_brd"); incompat_warning (o, "wgs_geom", "trk_brd"); incompat_warning (o, "wgs_geom", "nom"); incompat_warning (o, "wgs_geom", "google");\ dRect geom = o.get<dRect>("wgs_geom"); if (geom.empty()) throw Err() << "error: bad geometry"; proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(geom.x+geom.w/2))); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), Datum("wgs84"), proj, proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); refs.resize(4); // border is set to be rectanglar in proj: ret.border = cnv.line_bck(rect2line(cnv.bb_frw(geom, 1e-6), true, sw), 1e-6); } else if (o.exists("wgs_brd")){ incompat_warning (o, "wgs_brd", "geom"); incompat_warning (o, "wgs_brd", "wgs_geom"); incompat_warning (o, "wgs_brd", "trk_brd"); incompat_warning (o, "wgs_brd", "nom"); incompat_warning (o, "wgs_brd", "google");\ ret.border = o.get<dLine>("wgs_brd"); if (ret.border.size()<3) throw Err() << "error: bad border line"; ret.border.push_back(ret.border[0]); proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(ret.border.range().CNT().x))); if (verbose) cerr << "mk_ref: brd = " << ret.border << "\n"; refs = generalize(ret.border, -1, 5); // 5pt refs.resize(4); } else if (o.exists("trk_brd")){ incompat_warning (o, "trk_brd", "geom"); incompat_warning (o, "trk_brd", "wgs_geom"); incompat_warning (o, "trk_brd", "wgs_brd"); incompat_warning (o, "trk_brd", "nom"); incompat_warning (o, "trk_brd", "google");\ geo_data W; io::in(o.get<string>("trk_brd"), W); if (W.trks.size()<1) throw Err() << "error: file with a track is expected in trk_brd option"; ret.border = W.trks[0]; if (ret.border.size()<3) throw Err() << "error: bad border line"; ret.border.push_back(ret.border[0]); proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(ret.border.range().CNT().x))); if (verbose) cerr << "mk_ref: brd = " << ret.border << "\n"; refs = generalize(ret.border, -1, 5); // 5pt refs.resize(4); } // nom map else if (o.exists("nom")){ incompat_warning (o, "nom", "geom"); incompat_warning (o, "nom", "wgs_geom"); incompat_warning (o, "nom", "wgs_brd"); incompat_warning (o, "nom", "trk_brd"); incompat_warning (o, "nom", "google"); proj=Proj("tmerc"); datum=Datum("pulkovo"); int rs; string name=o.get<string>("nom", string()); dRect geom = convs::nom_to_range(name, rs); if (geom.empty()) throw Err() << "error: can't get geometry for map name \"" << name << "\""; rscale = rs; double lon0 = convs::lon2lon0(geom.x+geom.w/2.0); proj_opts.put("lon0", lon0); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), datum, Proj("lonlat"), proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); ret.border = cnv.line_bck(refs, 1e-6); refs.resize(4); cnv.line_bck_p2p(refs); } // google tile else if (o.exists("google")){ incompat_warning (o, "google", "geom"); incompat_warning (o, "google", "wgs_geom"); incompat_warning (o, "google", "wgs_brd"); incompat_warning (o, "google", "trk_brd"); incompat_warning (o, "google", "nom"); datum=Datum("wgs84"); proj=Proj("google"); vector<int> crd = read_int_vec(o.get<string>("google")); if (crd.size()!=3) throw Err() << "error: wrong --google coordinates"; int x=crd[0]; int y=crd[1]; int z=crd[2]; // Tiles tcalc; dRect geom = tcalc.gtile_to_range(x,y,z); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true,sw); ret.border = refs; refs.resize(4); - rscale=o.get<double>("rscale", rscale); + dpi=o.get<double>("dpi", dpi); - double lat=refs.range().CNT().y; - rs_factor = 1/cos(M_PI*lat/180.0); + // Change DPI relative to the base level + if (z < 14) + dpi /= 1 << (14 - z); + if (z > 14) + dpi *= 1 << (z - 14); - // m -> tile pixel - double k = 1/tcalc.px2m(z); - dpi = k * 2.54/100.0*rscale*rs_factor; + rscale = dpi * tcalc.px2m(z) * 100 / 2.54; + o.put("dpi", dpi); + o.put("rscale", rscale); } else throw Err() << "error: can't make map reference without" << " --geom or --nom or --google setting"; ret.map_proj=proj; ret.map_datum=datum; ret.proj_opts=proj_opts; // step 2: calculate conversion coeff between map proj units and // output map points rscale=o.get<double>("rscale", rscale); if (o.get<string>("dpi", "") == "fig") dpi= 1200/1.05; else dpi=o.get<double>("dpi", dpi); dpi*=o.get<double>("mag", 1.0); // put real dpi and rscale back to options o.put("dpi", dpi); o.put("rscale", rscale); - double k = 100.0/2.54 * dpi / rscale / rs_factor; + double k = 100.0/2.54 * dpi / rscale; if (verbose) cerr << "mk_ref: rscale = " << rscale << ", dpi = " << dpi << ", k = " << k << "\n"; // step 3: setting refpoints convs::pt2wgs cnv(datum, proj, proj_opts); dLine refs_r(refs); cnv.line_bck_p2p(refs_r); refs_r *= k; // to out units refs_r -= refs_r.range().TLC(); double h = refs_r.range().h; // swap y if needed if (sw) for (int i=0;i<refs_r.size();i++) refs_r[i].y = h - refs_r[i].y; // add refpoints to our map for (int i=0;i<refs.size();i++) ret.push_back(g_refpoint(refs[i], refs_r[i])); // step 3: converting border convs::map2wgs brd_cnv(ret); ret.border = brd_cnv.line_bck(ret.border); ret.border = generalize(ret.border, 1, -1); // 1 unit accuracy ret.border.resize(ret.border.size()-1); return ret; }
ushakov/mapsoft
da3ff7b17bf6e465aea28e4d5eb2923acca6b55e
programs: fix gitignore; fix convs_gtiles help message (by A.Kazantsev)
diff --git a/programs/.gitignore b/programs/.gitignore index 64dc6ef..d5e8d7d 100644 --- a/programs/.gitignore +++ b/programs/.gitignore @@ -1,15 +1,16 @@ convs_map2pt convs_nom convs_pt2pt +convs_gtiles mapsoft_convert mapsoft_fig2fig mapsoft_geofig mapsoft_map2fig mapsoft_mkmap mapsoft_pano mapsoft_ref mapsoft_srtm2fig mapsoft_toxyz mapsoft_vmap test *.1 \ No newline at end of file diff --git a/programs/convs_gtiles.cpp b/programs/convs_gtiles.cpp index 4db9b1c..a368daf 100644 --- a/programs/convs_gtiles.cpp +++ b/programs/convs_gtiles.cpp @@ -1,158 +1,158 @@ #include "tiles/tiles.h" #include "opts/opts.h" #include "geo_io/geo_refs.h" #include <iostream> #include <cstring> #include <vector> #include <boost/geometry.hpp> using namespace std; void usage(){ cerr << "\n" << "Google tile calculator.\n" - << "usage: convs_tile -p <point> <z> -- tile which covers a WGS84 point\n" - << " convs_tile -r <range> <z> -- tiles which cover a range (return a rectangle)\n" - << " convs_tile -R <range> <z> -- tiles which cover a range (return a list)\n" - << " convs_tile -bi <track> <z> -- tiles which touches the area (return a list)\n" - << " convs_tile -bc <track> <z> -- tiles which fully covered by area (return a list)\n" - << " convs_tile -n x y z -- tile range\n" - << " convs_tile -c x y z -- tile center\n" - << " convs_tile -t x y z <range> -- check if a tile touches a range\n" + << "usage: convs_gtiles -p <point> <z> -- tile which covers a WGS84 point\n" + << " convs_gtiles -r <range> <z> -- tiles which cover a range (return a rectangle)\n" + << " convs_gtiles -R <range> <z> -- tiles which cover a range (return a list)\n" + << " convs_gtiles -bi <track> <z> -- tiles which touches the area (return a list)\n" + << " convs_gtiles -bc <track> <z> -- tiles which fully covered by area (return a list)\n" + << " convs_gtiles -n x y z -- tile range\n" + << " convs_gtiles -c x y z -- tile center\n" + << " convs_gtiles -t x y z <range> -- check if a tile touches a range\n" << "\n" ; } int main(int argc, char** argv){ try{ Tiles calc; if ((argc == 4) && (strcmp(argv[1], "-p") == 0)){ iPoint ret = calc.pt_to_gtile( str_to_type<dPoint>(argv[2]), str_to_type<int>(argv[3])); cout << ret << "\n"; return 0; } if ((argc == 4) && (strcmp(argv[1], "-r") == 0)){ iRect ret = calc.range_to_gtiles( str_to_type<dRect>(argv[2]), str_to_type<int>(argv[3])); cout << ret << "\n"; return 0; } if ((argc == 4) && (strcmp(argv[1], "-R") == 0)){ int z = str_to_type<int>(argv[3]); iRect ret = calc.range_to_gtiles( str_to_type<dRect>(argv[2]),z); for (int y = ret.y; y<ret.y+ret.h; y++) for (int x = ret.x; x<ret.x+ret.w; x++) cout << x << "," << y << "," << z << "\n"; return 0; } if ((argc == 4) && ((strcmp(argv[1], "-bi") == 0) || (strcmp(argv[1], "-bc") == 0))){ using namespace boost::geometry; int zfin = str_to_type<int>(argv[3]); geo_data B; vector<g_track>::const_iterator bi; vector<g_trackpoint>::const_iterator pi; typedef model::d2::point_xy<double> point_t; std::vector<point_t> pts; typedef model::polygon<point_t> polygon_t; polygon_t poly; typedef struct {int x; int y; int z;} tile_s; vector<tile_s> oldtiles, newtiles = {{0, 0, 0}}; vector<tile_s>::const_iterator ti; io::in(string(argv[2]), B); // Прочитаем трек в полигон pts.clear(); bi=B.trks.begin(); for (pi=bi->begin(); pi!=bi->end(); pi++){ pts.push_back(point_t(pi->x, pi->y)); } pts.push_back(point_t(bi->begin()->x, bi->begin()->y)); append(poly, pts); /* Переберём все возможные тайлы методом последовательных приближений */ for (int z = 1; z <= zfin; z++) { oldtiles=newtiles; newtiles.clear(); // Переберём все тайлы с прошлого приближения for (ti=oldtiles.begin(); ti!=oldtiles.end(); ti++) { // Поделим подходящий тайл на 4 новых и проверим каждый из них for (int i = 0; i < 4; i++) { int flag; int x = ti->x * 2 + (i & 1); int y = ti->y * 2 + !!(i & 2); polygon_t tile; dRect tr = calc.gtile_to_range(x, y, z); pts.clear(); pts.push_back(point_t(tr.x, tr.y )); pts.push_back(point_t(tr.x + tr.w, tr.y )); pts.push_back(point_t(tr.x + tr.w, tr.y + tr.h)); pts.push_back(point_t(tr.x , tr.y + tr.h)); pts.push_back(point_t(tr.x, tr.y )); append(tile, pts); if ((z == zfin) && strcmp(argv[1], "-bi") != 0) { /* Полное покрытие */ flag = covered_by(tile, poly); } else { /* Простое пересечение */ flag = intersects(tile, poly); } if (flag) { tile_s tt = {x, y, z}; newtiles.push_back(tt); } } } } for (ti=newtiles.begin(); ti!=newtiles.end(); ti++) { cout << ti->x << " " << ti->y << " " << ti->z << endl; } return 0; } if ((argc == 5) && (strcmp(argv[1], "-n") == 0)){ dRect ret = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); cout << setprecision(9) << ret << "\n"; return 0; } if ((argc == 5) && (strcmp(argv[1], "-c") == 0)){ dRect ret = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); cout << setprecision(9) << ret.CNT() << "\n"; return 0; } if ((argc == 6) && (strcmp(argv[1], "-t") == 0)){ dRect r1 = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); dRect r2 = str_to_type<dRect>(argv[5]); return rect_intersect(r1,r2).empty(); } usage(); } catch(Err e) { cerr << "Error: " << e.get_error() << endl; } return 1; }
ushakov/mapsoft
415ac80d83507e001c28830c2f77eec1ae2c6edf
fix error in vmap rendering introduced by previous commit
diff --git a/core/img_io/gobj_vmap.cpp b/core/img_io/gobj_vmap.cpp index 2d93205..1e1f699 100644 --- a/core/img_io/gobj_vmap.cpp +++ b/core/img_io/gobj_vmap.cpp @@ -1,600 +1,600 @@ #include <string> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include "loaders/image_r.h" #include "gobj_vmap.h" #include <jansson.h> using namespace std; GObjVMAP::GObjVMAP(vmap::world * _W, const Options & O): W(_W), zc(W->style){ pics_dpi = O.get("pics_dpi", 600.0); bgcolor = O.get("bgcolor", 0xFFFFFF); dpi = O.get("dpi", 200.0); lw1 = O.get("line_width", dpi/105.0); cntrs = O.get("contours", true); use_aa = O.get("antialiasing", true); label_marg = O.get("label_marg", 2.5); label_style = O.get("label_style", 2); grid_step = O.get("grid", 0.0); transp = O.get("transp_margins", false); grid_labels = O.get("grid_labels", 0); { // set pattern filter std::string flt = O.get<std::string>("patt_filter", "good"); if (flt == "fast") patt_filter = Cairo::FILTER_FAST; else if (flt == "good") patt_filter = Cairo::FILTER_GOOD; else if (flt == "best") patt_filter = Cairo::FILTER_BEST; else if (flt == "nearest") patt_filter = Cairo::FILTER_NEAREST; else if (flt == "bilinear") patt_filter = Cairo::FILTER_BILINEAR; else throw Err() << "unknown patt_filter setting: " << flt; } // Read render data from json file. (2018-09) // File structure: json array of objects. // Each array element represents an action (draw object type, draw grid etc.) std::string render_data_fname = O.get("render_data", std::string()); if (render_data_fname != ""){ json_error_t e; json_t *J = json_load_file(render_data_fname.c_str(), 0, &e); if (!J) throw Err() << e.text << " in " << e.source << ":" << e.line << ":" << e.column; try { if (!json_is_array(J)) throw Err() << "RenderData should be an array of objects"; size_t i; json_t *c; json_array_foreach(J, i, c){ Opts o; if (!json_is_object(c)) throw Err() << "RenderData should be an array of objects"; const char *k; json_t *v; json_object_foreach(c, k, v){ if (json_is_string(v)) o.put(k, json_string_value(v)); else if (json_is_integer(v)) o.put(k, json_integer_value(v)); else if (json_is_real(v)) o.put(k, json_real_value(v)); else throw Err() << "wrong value type for " << k; } render_data.push_back(o); } } catch (Err e){ json_decref(J); throw e; } json_decref(J); } } int GObjVMAP::draw(iImage &img, const iPoint &org){ if (W->brd.size()>2) ref.border=cnv.line_bck(W->brd)-org; if (ref.border.size()>2 && rect_intersect(iRect(ref.border.range()), img.range()).empty()) return GObj::FILL_NONE; // create Cairo surface and context cr.reset_surface(img); origin = org; - if (use_aa>0) cr->set_antialias(Cairo::ANTIALIAS_NONE); + if (!use_aa) cr->set_antialias(Cairo::ANTIALIAS_NONE); cr->set_fill_rule(Cairo::FILL_RULE_EVEN_ODD); // old code -- no render_data: if (render_data.size()==0) { // objects render_objects(); // grid if (grid_step>0){ if (ref.map_proj != Proj("tmerc")) cerr << "WARINIG: grid for non-tmerc maps is not supported!\n"; render_pulk_grid(grid_step, grid_step, false, ref); } // labels render_labels(); // border if (ref.border.size()>2) cr->render_border(img.range(), ref.border, transp? 0:bgcolor); // draw grid labels after labels if ((grid_step>0) && grid_labels){ if (ref.map_proj != Proj("tmerc")) cerr << "WARINIG: grid for non-tmerc maps is not supported!\n"; render_pulk_grid(grid_step, grid_step, true, ref); } return GObj::FILL_PART; } // new code std::vector<Opts>::const_iterator data; for (data=render_data.begin(); data!=render_data.end(); data++){ // Draw points. There are two types of points: a simple point and an image. // { point: 0x122, image: "images/file.png"} // { point: 0x122, color: 0x00FF00, size: 4} if (data->exists("point")){ int type = data->get<int>("point"); int size = 4, color = 0; if (data->exists("image")) { std::string fname = data->get("image",std::string()); iImage I = image_r::load(fname.c_str()); if (I.empty()) throw Err() << "Can't read image: " << fname; auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) throw Err() << "Can't create cairo pattern from image: " << fname; patt->set_filter(patt_filter); // each object, each line inside the object, each point for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ for (dLine::const_iterator p=l->begin(); p!=l->end(); p++){ cr->save(); dPoint pp=(*p); cnv.bck(pp); pp-=origin; cr->translate(pp.x, pp.y); if (o->opts.exists("Angle")){ double a = o->opts.get<double>("Angle",0); a = cnv.ang_bck(o->center(), M_PI/180 * a, 0.01); cr->rotate(a); } cr->set_source(patt); cr->paint(); cr->restore(); } } } } else { cr->save(); cr->set_line_width(lw1*data->get<int>("size", size)); cr->set_color(data->get<int>("color", color)); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_points(l-origin); cr->stroke(); } cr->restore(); } }// point } // for data return GObj::FILL_PART; } void GObjVMAP::render_polygons(int type, int col, double curve_l){ if (!cr) return; cr->save(); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::area_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill(); } cr->restore(); } // contoured polygons void GObjVMAP::render_cnt_polygons(int type, int fill_col, int cnt_col, double cnt_th, double curve_l){ cr->save(); cr->set_color(fill_col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!= (type | zn::area_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill_preserve(); cr->save(); cr->set_color(cnt_col); cr->set_line_width(cnt_th*lw1); cr->stroke(); cr->restore(); } cr->restore(); } void GObjVMAP::render_line(int type, int col, double th, double curve_l){ if (!cr) return; cr->save(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 0, curve_l*lw1); cr->stroke(); } cr->restore(); } void GObjVMAP::render_points(int type, int col, double th){ if (!cr) return; cr->save(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_points(l-origin); cr->stroke(); } cr->restore(); } void GObjVMAP::render_img_polygons(int type, double curve_l){ type = type | zn::area_mask; std::map<int, zn::zn>::const_iterator z = zc.find_type(type); if (z==zc.znaki.end()) return; string f = z->second.pic + ".png"; // picture filename iImage I = image_r::load(f.c_str()); if (I.empty()) cerr << "Empty image for type " << type << "\n"; auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) return; patt->set_filter(patt_filter); // polygons filled with image pattern if (z->second.pic_type=="fill"){ patt->set_extend(Cairo::EXTEND_REPEAT); cr->save(); cr->set_source(patt); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill(); } cr->restore(); } // place image in the center of polygons else { for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ if (l->size()<1) continue; dPoint p=l->range().CNT(); cnv.bck(p); p = p-origin; cr->save(); cr->translate(p.x, p.y); cr->set_source(patt); cr->paint(); cr->restore(); } } } } // place image in points void GObjVMAP::render_im_in_points(int type){ std::map<int, zn::zn>::const_iterator z = zc.find_type(type); if (z==zc.znaki.end()) return; string f = z->second.pic + ".png"; // picture filename iImage I = image_r::load(f.c_str()); if (I.empty()) cerr << "Empty image for type " << type << "\n"; auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) return; patt->set_filter(patt_filter); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ if (l->size()<1) continue; cr->save(); dPoint p=(*l)[0]; cnv.bck(p); p-=origin; cr->translate(p.x, p.y); if (o->opts.exists("Angle")){ double a = o->opts.get<double>("Angle",0); a = cnv.ang_bck(o->center(), M_PI/180 * a, 0.01); cr->rotate(a); } cr->set_source(patt); cr->paint(); cr->restore(); } } } // paths for bridge sign void GObjVMAP::mkbrpath1(const vmap::object & o){ for (vmap::object::const_iterator l=o.begin(); l!=o.end(); l++){ if (l->size()<2) continue; dPoint p1 = (*l)[0], p2 = (*l)[1]; cnv.bck(p1); cnv.bck(p2); cr->move_to(p1-origin); cr->line_to(p2-origin); } } void GObjVMAP::mkbrpath2(const vmap::object & o, double th, double side){ th*=lw1/2.0; side*=lw1/sqrt(2.0); for (vmap::object::const_iterator l=o.begin(); l!=o.end(); l++){ if (l->size()<2) continue; dPoint p1 = (*l)[0], p2 = (*l)[1]; cnv.bck(p1); cnv.bck(p2); p1-=origin; p2-=origin; dPoint t = pnorm(p2-p1); dPoint n(-t.y, t.x); dPoint P; P = p1 + th*n + side*(n-t); cr->move_to(P); P = p1 + th*n; cr->line_to(P); P = p2 + th*n; cr->line_to(P); P = p2 + th*n + side*(n+t); cr->line_to(P); P = p1 - th*n - side*(n+t); cr->move_to(P); P = p1 - th*n; cr->line_to(P); P = p2 - th*n; cr->line_to(P); P = p2 - th*n - side*(n-t); cr->line_to(P); } } void GObjVMAP::render_bridge(int type, double th1, double th2, double side){ cr->save(); cr->set_line_cap(Cairo::LINE_CAP_BUTT); cr->set_line_join(Cairo::LINE_JOIN_ROUND); if (th1!=0){ cr->set_line_width(th1*lw1); cr->set_color(0xFFFFFF); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; mkbrpath1(*o); cr->stroke(); } th1+=th2; } cr->set_line_width(th2*lw1); cr->set_color(0x0); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; mkbrpath2(*o, th1, side); cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_el(Conv & cnv, int type, int col, double th, double step){ render_line(type, col, th, 0); double width=th*1.2*lw1; step*=lw1; cr->save(); cr->cap_round(); cr->set_line_width(1.8*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); int n=1; while (ld.dist() < ld.length()){ dPoint vn=ld.norm()*width; dPoint vt=ld.tang()*width; dPoint p1,p2,p3; p1=p2=p3=ld.pt(); p1+=vn; p3-=vn; if (n%4 == 1){ p1+=vt; p3+=vt;} if (n%4 == 3){ p1-=vt; p3-=vt;} cr->move_to(p1); cr->line_to(p2); cr->line_to(p3); n++; ld.move_frw(fstep); } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_obr(Conv & cnv, int type, int col, double th){ render_line(type, col, th, 0); double width=th*2*lw1; double step=th*4*lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; int k=1; if (o->dir==2) k=-1; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); while (ld.dist() < ld.length()){ dPoint p=ld.pt(), vn=ld.norm()*width*k; cr->move_to(p); cr->line_to(p+vn); ld.move_frw(fstep); } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_zab(Conv & cnv, int type, int col, double th){ render_line(type, col, th, 0); double width=th*2*lw1; double step=th*8*lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; int k=1; if (o->dir==2) k=-1; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw((fstep-width)/2); int n=0; while (ld.dist() < ld.length()){ dPoint p=ld.pt(), v=(ld.norm()-ld.tang())*width*k; cr->move_to(p); cr->line_to(p+v); ld.move_frw((n%2==0)?width:fstep-width); n++; } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_val(Conv & cnv, int type, int col, double th, double width, double step){ width*=lw1/2; step*=lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); int n=0; while (ld.dist() < ld.length()){ dPoint p=ld.pt(), v=ld.norm()*width, t=ld.tang()*step/2; cr->move_to(p+v); cr->line_to(p+v); cr->move_to(p-v); cr->line_to(p-v); // cr->move_to(p-v); // cr->line_to(p+v); ld.move_frw(fstep); n++; } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_gaz(Conv & cnv, int type, int col, double th, double step){ render_line(type, col, th, 0); double width=th*0.8*lw1; step*=lw1; cr->save(); cr->set_line_width(lw1); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); while (ld.dist() < ld.length()){ dPoint p=ld.pt(); cr->begin_new_sub_path(); cr->arc(p.x, p.y, width, 0.0, 2*M_PI); ld.move_frw(fstep); } } } cr->set_color(0xFFFFFF); cr->fill_preserve(); cr->set_color(col); cr->stroke(); cr->restore(); } void GObjVMAP::render_grid_label(double c, double val, bool horiz, const dLine & border){ ostringstream ss; ss << setprecision(7) << val/1000.0; if (border.size()<1) return; dPoint pmin, pmax; double amin=0, amax=0; dLine::const_iterator i,j; for (i=border.begin(); i!=border.end(); i++){ j=i+1; if (j==border.end()) j=border.begin(); dPoint p1(*i); dPoint p2(*j); if (horiz){ if (p1.x == p2.x) continue; if (p1.x > p2.x) p1.swap(p2); // segment does not cross grid line: if ((p1.x >= c) || (p2.x < c)) continue; double a = atan2(p2.y-p1.y, p2.x-p1.x); // crossing point of grid line with border dPoint pc(c, p1.y + (p2.y-p1.y)*(c-p1.x)/(p2.x-p1.x)); if ((pmin==dPoint()) || (pmin.y > pc.y)) {pmin=pc; amin=a;} if ((pmax==dPoint()) || (pmax.y < pc.y)) {pmax=pc; amax=a;} } else { if (p1.y == p2.y) continue; if (p1.y > p2.y) p1.swap(p2); // segment does not cross grid line: if ((p1.y >= c) || (p2.y < c)) continue; double a = atan2(p2.y-p1.y, p2.x-p1.x); // crossing point of grid line with border dPoint pc(p1.x + (p2.x-p1.x)*(c-p1.y)/(p2.y-p1.y), c); if ((pmin==dPoint()) || (pmin.x > pc.x)) {pmin=pc; amin=a;} if ((pmax==dPoint()) || (pmax.x < pc.x)) {pmax=pc; amax=a;} } } if (amin>M_PI/2) amin-=M_PI;
ushakov/mapsoft
62a7069f5631c86d1ed1fe539de98abf00fffd41
vmap_render: --patt_filter option for controlling Cairo::Pattern filters
diff --git a/core/img_io/gobj_vmap.cpp b/core/img_io/gobj_vmap.cpp index dfe6ce2..2d93205 100644 --- a/core/img_io/gobj_vmap.cpp +++ b/core/img_io/gobj_vmap.cpp @@ -1,800 +1,812 @@ #include <string> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include "loaders/image_r.h" #include "gobj_vmap.h" #include <jansson.h> using namespace std; GObjVMAP::GObjVMAP(vmap::world * _W, const Options & O): W(_W), zc(W->style){ pics_dpi = O.get("pics_dpi", 600.0); bgcolor = O.get("bgcolor", 0xFFFFFF); dpi = O.get("dpi", 200.0); lw1 = O.get("line_width", dpi/105.0); cntrs = O.get("contours", true); use_aa = O.get("antialiasing", true); label_marg = O.get("label_marg", 2.5); label_style = O.get("label_style", 2); grid_step = O.get("grid", 0.0); transp = O.get("transp_margins", false); grid_labels = O.get("grid_labels", 0); + { // set pattern filter + std::string flt = O.get<std::string>("patt_filter", "good"); + if (flt == "fast") patt_filter = Cairo::FILTER_FAST; + else if (flt == "good") patt_filter = Cairo::FILTER_GOOD; + else if (flt == "best") patt_filter = Cairo::FILTER_BEST; + else if (flt == "nearest") patt_filter = Cairo::FILTER_NEAREST; + else if (flt == "bilinear") patt_filter = Cairo::FILTER_BILINEAR; + else throw Err() << "unknown patt_filter setting: " << flt; + } + // Read render data from json file. (2018-09) // File structure: json array of objects. // Each array element represents an action (draw object type, draw grid etc.) std::string render_data_fname = O.get("render_data", std::string()); if (render_data_fname != ""){ json_error_t e; json_t *J = json_load_file(render_data_fname.c_str(), 0, &e); if (!J) throw Err() << e.text << " in " << e.source << ":" << e.line << ":" << e.column; try { if (!json_is_array(J)) throw Err() << "RenderData should be an array of objects"; size_t i; json_t *c; json_array_foreach(J, i, c){ Opts o; if (!json_is_object(c)) throw Err() << "RenderData should be an array of objects"; const char *k; json_t *v; json_object_foreach(c, k, v){ if (json_is_string(v)) o.put(k, json_string_value(v)); else if (json_is_integer(v)) o.put(k, json_integer_value(v)); else if (json_is_real(v)) o.put(k, json_real_value(v)); else throw Err() << "wrong value type for " << k; } render_data.push_back(o); } } catch (Err e){ json_decref(J); throw e; } json_decref(J); } } int GObjVMAP::draw(iImage &img, const iPoint &org){ if (W->brd.size()>2) ref.border=cnv.line_bck(W->brd)-org; if (ref.border.size()>2 && rect_intersect(iRect(ref.border.range()), img.range()).empty()) return GObj::FILL_NONE; // create Cairo surface and context cr.reset_surface(img); origin = org; - if (!use_aa) cr->set_antialias(Cairo::ANTIALIAS_NONE); + if (use_aa>0) cr->set_antialias(Cairo::ANTIALIAS_NONE); cr->set_fill_rule(Cairo::FILL_RULE_EVEN_ODD); // old code -- no render_data: if (render_data.size()==0) { // objects render_objects(); // grid if (grid_step>0){ if (ref.map_proj != Proj("tmerc")) cerr << "WARINIG: grid for non-tmerc maps is not supported!\n"; render_pulk_grid(grid_step, grid_step, false, ref); } // labels render_labels(); // border if (ref.border.size()>2) cr->render_border(img.range(), ref.border, transp? 0:bgcolor); // draw grid labels after labels if ((grid_step>0) && grid_labels){ if (ref.map_proj != Proj("tmerc")) cerr << "WARINIG: grid for non-tmerc maps is not supported!\n"; render_pulk_grid(grid_step, grid_step, true, ref); } return GObj::FILL_PART; } // new code std::vector<Opts>::const_iterator data; for (data=render_data.begin(); data!=render_data.end(); data++){ // Draw points. There are two types of points: a simple point and an image. // { point: 0x122, image: "images/file.png"} // { point: 0x122, color: 0x00FF00, size: 4} if (data->exists("point")){ int type = data->get<int>("point"); int size = 4, color = 0; - Cairo::RefPtr<Cairo::SurfacePattern> patt; if (data->exists("image")) { std::string fname = data->get("image",std::string()); iImage I = image_r::load(fname.c_str()); if (I.empty()) throw Err() << "Can't read image: " << fname; - patt = cr->img2patt(I, pics_dpi/dpi); + auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) throw Err() << "Can't create cairo pattern from image: " << fname; + patt->set_filter(patt_filter); // each object, each line inside the object, each point for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ for (dLine::const_iterator p=l->begin(); p!=l->end(); p++){ cr->save(); dPoint pp=(*p); cnv.bck(pp); pp-=origin; cr->translate(pp.x, pp.y); if (o->opts.exists("Angle")){ double a = o->opts.get<double>("Angle",0); a = cnv.ang_bck(o->center(), M_PI/180 * a, 0.01); cr->rotate(a); } cr->set_source(patt); cr->paint(); cr->restore(); } } } } else { cr->save(); cr->set_line_width(lw1*data->get<int>("size", size)); cr->set_color(data->get<int>("color", color)); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_points(l-origin); cr->stroke(); } cr->restore(); } }// point } // for data return GObj::FILL_PART; } void GObjVMAP::render_polygons(int type, int col, double curve_l){ if (!cr) return; cr->save(); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::area_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill(); } cr->restore(); } // contoured polygons void GObjVMAP::render_cnt_polygons(int type, int fill_col, int cnt_col, double cnt_th, double curve_l){ cr->save(); cr->set_color(fill_col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!= (type | zn::area_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill_preserve(); cr->save(); cr->set_color(cnt_col); cr->set_line_width(cnt_th*lw1); cr->stroke(); cr->restore(); } cr->restore(); } void GObjVMAP::render_line(int type, int col, double th, double curve_l){ if (!cr) return; cr->save(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 0, curve_l*lw1); cr->stroke(); } cr->restore(); } void GObjVMAP::render_points(int type, int col, double th){ if (!cr) return; cr->save(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_points(l-origin); cr->stroke(); } cr->restore(); } void GObjVMAP::render_img_polygons(int type, double curve_l){ type = type | zn::area_mask; std::map<int, zn::zn>::const_iterator z = zc.find_type(type); if (z==zc.znaki.end()) return; string f = z->second.pic + ".png"; // picture filename iImage I = image_r::load(f.c_str()); if (I.empty()) cerr << "Empty image for type " << type << "\n"; - Cairo::RefPtr<Cairo::SurfacePattern> patt = cr->img2patt(I, pics_dpi/dpi); + auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) return; + patt->set_filter(patt_filter); // polygons filled with image pattern if (z->second.pic_type=="fill"){ patt->set_extend(Cairo::EXTEND_REPEAT); cr->save(); cr->set_source(patt); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; dMultiLine l = *o; cnv.line_bck_p2p(l); cr->mkpath_smline(l-origin, 1, curve_l*lw1); cr->fill(); } cr->restore(); } // place image in the center of polygons else { for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ if (l->size()<1) continue; dPoint p=l->range().CNT(); cnv.bck(p); p = p-origin; cr->save(); cr->translate(p.x, p.y); cr->set_source(patt); cr->paint(); cr->restore(); } } } } // place image in points void GObjVMAP::render_im_in_points(int type){ std::map<int, zn::zn>::const_iterator z = zc.find_type(type); if (z==zc.znaki.end()) return; string f = z->second.pic + ".png"; // picture filename iImage I = image_r::load(f.c_str()); if (I.empty()) cerr << "Empty image for type " << type << "\n"; - Cairo::RefPtr<Cairo::SurfacePattern> patt = cr->img2patt(I, pics_dpi/dpi); + auto patt = cr->img2patt(I, pics_dpi/dpi); if (!patt) return; + patt->set_filter(patt_filter); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=type) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ if (l->size()<1) continue; cr->save(); dPoint p=(*l)[0]; cnv.bck(p); p-=origin; cr->translate(p.x, p.y); if (o->opts.exists("Angle")){ double a = o->opts.get<double>("Angle",0); a = cnv.ang_bck(o->center(), M_PI/180 * a, 0.01); cr->rotate(a); } cr->set_source(patt); cr->paint(); cr->restore(); } } } // paths for bridge sign void GObjVMAP::mkbrpath1(const vmap::object & o){ for (vmap::object::const_iterator l=o.begin(); l!=o.end(); l++){ if (l->size()<2) continue; dPoint p1 = (*l)[0], p2 = (*l)[1]; cnv.bck(p1); cnv.bck(p2); cr->move_to(p1-origin); cr->line_to(p2-origin); } } void GObjVMAP::mkbrpath2(const vmap::object & o, double th, double side){ th*=lw1/2.0; side*=lw1/sqrt(2.0); for (vmap::object::const_iterator l=o.begin(); l!=o.end(); l++){ if (l->size()<2) continue; dPoint p1 = (*l)[0], p2 = (*l)[1]; cnv.bck(p1); cnv.bck(p2); p1-=origin; p2-=origin; dPoint t = pnorm(p2-p1); dPoint n(-t.y, t.x); dPoint P; P = p1 + th*n + side*(n-t); cr->move_to(P); P = p1 + th*n; cr->line_to(P); P = p2 + th*n; cr->line_to(P); P = p2 + th*n + side*(n+t); cr->line_to(P); P = p1 - th*n - side*(n+t); cr->move_to(P); P = p1 - th*n; cr->line_to(P); P = p2 - th*n; cr->line_to(P); P = p2 - th*n - side*(n-t); cr->line_to(P); } } void GObjVMAP::render_bridge(int type, double th1, double th2, double side){ cr->save(); cr->set_line_cap(Cairo::LINE_CAP_BUTT); cr->set_line_join(Cairo::LINE_JOIN_ROUND); if (th1!=0){ cr->set_line_width(th1*lw1); cr->set_color(0xFFFFFF); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; mkbrpath1(*o); cr->stroke(); } th1+=th2; } cr->set_line_width(th2*lw1); cr->set_color(0x0); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; mkbrpath2(*o, th1, side); cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_el(Conv & cnv, int type, int col, double th, double step){ render_line(type, col, th, 0); double width=th*1.2*lw1; step*=lw1; cr->save(); cr->cap_round(); cr->set_line_width(1.8*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); int n=1; while (ld.dist() < ld.length()){ dPoint vn=ld.norm()*width; dPoint vt=ld.tang()*width; dPoint p1,p2,p3; p1=p2=p3=ld.pt(); p1+=vn; p3-=vn; if (n%4 == 1){ p1+=vt; p3+=vt;} if (n%4 == 3){ p1-=vt; p3-=vt;} cr->move_to(p1); cr->line_to(p2); cr->line_to(p3); n++; ld.move_frw(fstep); } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_obr(Conv & cnv, int type, int col, double th){ render_line(type, col, th, 0); double width=th*2*lw1; double step=th*4*lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; int k=1; if (o->dir==2) k=-1; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); while (ld.dist() < ld.length()){ dPoint p=ld.pt(), vn=ld.norm()*width*k; cr->move_to(p); cr->line_to(p+vn); ld.move_frw(fstep); } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_zab(Conv & cnv, int type, int col, double th){ render_line(type, col, th, 0); double width=th*2*lw1; double step=th*8*lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; int k=1; if (o->dir==2) k=-1; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw((fstep-width)/2); int n=0; while (ld.dist() < ld.length()){ dPoint p=ld.pt(), v=(ld.norm()-ld.tang())*width*k; cr->move_to(p); cr->line_to(p+v); ld.move_frw((n%2==0)?width:fstep-width); n++; } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_val(Conv & cnv, int type, int col, double th, double width, double step){ width*=lw1/2; step*=lw1; cr->save(); cr->cap_round(); cr->set_line_width(th*lw1); cr->set_color(col); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); int n=0; while (ld.dist() < ld.length()){ dPoint p=ld.pt(), v=ld.norm()*width, t=ld.tang()*step/2; cr->move_to(p+v); cr->line_to(p+v); cr->move_to(p-v); cr->line_to(p-v); // cr->move_to(p-v); // cr->line_to(p+v); ld.move_frw(fstep); n++; } } cr->stroke(); } cr->restore(); } void GObjVMAP::render_line_gaz(Conv & cnv, int type, int col, double th, double step){ render_line(type, col, th, 0); double width=th*0.8*lw1; step*=lw1; cr->save(); cr->set_line_width(lw1); for (vmap::world::const_iterator o=W->begin(); o!=W->end(); o++){ if (o->type!=(type | zn::line_mask)) continue; for (vmap::object::const_iterator l=o->begin(); l!=o->end(); l++){ dLine l1 = *l; cnv.line_bck_p2p(l1); LineDist ld(l1-origin); if (ld.length()<=step) continue; double fstep = ld.length()/ceil(ld.length()/step); ld.move_frw(fstep/2); while (ld.dist() < ld.length()){ dPoint p=ld.pt(); cr->begin_new_sub_path(); cr->arc(p.x, p.y, width, 0.0, 2*M_PI); ld.move_frw(fstep); } } } cr->set_color(0xFFFFFF); cr->fill_preserve(); cr->set_color(col); cr->stroke(); cr->restore(); } void GObjVMAP::render_grid_label(double c, double val, bool horiz, const dLine & border){ ostringstream ss; ss << setprecision(7) << val/1000.0; if (border.size()<1) return; dPoint pmin, pmax; double amin=0, amax=0; dLine::const_iterator i,j; for (i=border.begin(); i!=border.end(); i++){ j=i+1; if (j==border.end()) j=border.begin(); dPoint p1(*i); dPoint p2(*j); if (horiz){ if (p1.x == p2.x) continue; if (p1.x > p2.x) p1.swap(p2); // segment does not cross grid line: if ((p1.x >= c) || (p2.x < c)) continue; double a = atan2(p2.y-p1.y, p2.x-p1.x); // crossing point of grid line with border dPoint pc(c, p1.y + (p2.y-p1.y)*(c-p1.x)/(p2.x-p1.x)); if ((pmin==dPoint()) || (pmin.y > pc.y)) {pmin=pc; amin=a;} if ((pmax==dPoint()) || (pmax.y < pc.y)) {pmax=pc; amax=a;} } else { if (p1.y == p2.y) continue; if (p1.y > p2.y) p1.swap(p2); // segment does not cross grid line: if ((p1.y >= c) || (p2.y < c)) continue; double a = atan2(p2.y-p1.y, p2.x-p1.x); // crossing point of grid line with border dPoint pc(p1.x + (p2.x-p1.x)*(c-p1.y)/(p2.y-p1.y), c); if ((pmin==dPoint()) || (pmin.x > pc.x)) {pmin=pc; amin=a;} if ((pmax==dPoint()) || (pmax.x < pc.x)) {pmax=pc; amax=a;} } } if (amin>M_PI/2) amin-=M_PI; if (amin<-M_PI/2) amin+=M_PI; if (amax>M_PI/2) amax-=M_PI; if (amax<-M_PI/2) amax+=M_PI; bool drawmin, drawmax; int ydir_max=0, ydir_min=0; if (horiz){ drawmin = (pmin!=dPoint()) && (abs(amin) < M_PI* 0.1); drawmax = (pmax!=dPoint()) && (abs(amax) < M_PI* 0.1); pmin+=dPoint(0,-dpi/30); pmax+=dPoint(0,+dpi/30); ydir_max=2; } else{ drawmin = (pmin!=dPoint()) && (abs(amin) > M_PI* 0.4); drawmax = (pmax!=dPoint()) && (abs(amax) > M_PI* 0.4); if (amin>0) amin-=M_PI; if (amax<0) amax+=M_PI; pmin+=dPoint(-dpi/30,0); pmax+=dPoint(dpi/30,0); } if (drawmin) cr->render_text(ss.str().c_str(), pmin, amin, 0, 18, 8, dpi, 1,ydir_min); if (drawmax) cr->render_text(ss.str().c_str(), pmax, amax, 0, 18, 8, dpi, 1,ydir_max); } void GObjVMAP::render_pulk_grid(double dx, double dy, bool labels, const g_map & ref){ convs::map2pt cnv(ref, Datum("pulkovo"), Proj("tmerc"), ref.proj_opts); dRect rng_m = cnv.bb_frw(ref.border.range(), 1)-origin; dPoint pb( rng_m.x, rng_m.y ); dPoint pe( rng_m.x+rng_m.w, rng_m.y+rng_m.h ); dx *= W->rscale/100; dy *= W->rscale/100; double m=dy/10; // skip labels at distance m from horizontal edges dPoint p( dx * floor(rng_m.x/dx), dy * floor(rng_m.y/dy) ); dPoint pbc(pb); cnv.bck(pbc); pbc-=origin; dPoint pec(pe); cnv.bck(pec); pec-=origin; // note: pb.y < pe.y, but pbc.y > pec.y! cr->save(); cr->set_source_rgba(0,0,0,0.5); cr->set_line_width(2); while (p.x<pe.x){ dPoint pc(p); cnv.bck(pc); pc-=origin; if (labels) render_grid_label(pc.x, p.x, true, ref.border); else { cr->Cairo::Context::move_to(pc.x, pbc.y); cr->Cairo::Context::line_to(pc.x, pec.y); } p.x+=dx; } while (p.y<pe.y){ dPoint pc(p); cnv.bck(pc); pc-=origin; if (labels && (p.y > pb.y+m) && (p.y<pe.y-m)) render_grid_label(pc.y, p.y, false, ref.border); else { cr->Cairo::Context::move_to(pbc.x, pc.y); cr->Cairo::Context::line_to(pec.x, pc.y); } p.y+=dy; } cr->stroke(); cr->restore(); } void GObjVMAP::render_objects(){ bool hr = (W->style == "hr"); const int c_forest = 0xAAFFAA; const int c_field = 0xFFFFFF; const int c_fcont = 0x009000; const int c_glac = 0xFFE6C3; const int c_slope = 0xCCCCCC; const int c_way2 = 0x00B400; const int c_way5 = 0x00D8FF; const int c_hor = hr? 0x90B0D0:0x0060C0; const int c_build_gray = 0xB0B0B0; const int c_build_red = 0x8080FF; const int c_build_dred = 0x5959B0; const int c_build_green = 0x557F55; const int c_build_cnt = 0x000000; const int c_brd = 0x0000FF; const int c_brdg = 0x00FF00; const int c_riv_cnt = 0xFF6650; const int c_riv_fill = hr? 0xFFCE87:0xFFFF00; const int c_kanav = 0x0060C0; const int c_ovrag = 0x0040A0; const int c_hreb = hr? 0x0060C0:0x003080; const int c_lines = 0x888888; const int c_road_fill = 0x8080FF; const int c_obr = 0x000090; const int c_pt = hr? 0x003080:0x000000; //******************************* render_polygons(0x16, c_forest); // лес render_polygons(0x52, c_field); // поле render_polygons(0x15, c_forest); // остров леса list<iPoint> cnt; if (cntrs) cnt = make_cnt(c_forest, 2); // контуры леса render_img_polygons(0x4f); // свежая вырубка render_img_polygons(0x50); // старая вырубка render_img_polygons(0x14); // редколесье render_polygons(0x15, c_forest); // остров леса поверх вырубок if (cntrs){ filter_cnt(cnt, c_forest); // убираем контуры, оказавшеся поверх вырубок draw_cnt(cnt, c_fcont, 1); // рисуем контуры } cr->cap_round(); cr->join_round(); cr->set_dash(0, 2*lw1); render_line(0x23, c_fcont, 1, 0); // контуры, нарисованные вручную cr->unset_dash(); render_polygons(0x4d, c_glac, 20.0); // ледник render_polygons(0x19, c_slope, 20.0); // камни, песок render_img_polygons(0x8); // камни, песок render_img_polygons(0xD); // камни, песок //******************************* // извращение с линиями проходимости: // сперва вырезаем место для них в подложке cr->save(); cr->set_operator(Cairo::OPERATOR_CLEAR); cr->cap_butt(); render_line(0x32, c_way2, 3, 10); // плохой путь cr->set_dash(lw1, lw1); render_line(0x33, c_way2, 3, 10); // удовлетворительный путь render_line(0x34, c_way5, 3, 10); // хороший путь cr->unset_dash(); render_line(0x35, c_way2, 3, 10); // отличный путь cr->restore(); //******************************* render_cnt_polygons(0x4, c_build_gray, c_build_cnt, 0.7); // закрытые территории render_cnt_polygons(0xE, c_build_red, c_build_cnt, 0.7); // деревни render_cnt_polygons(0x1, c_build_dred, c_build_cnt, 0.7); // города render_cnt_polygons(0x4E, c_build_green, c_build_cnt, 0.7); // дачи render_cnt_polygons(0x1A, c_build_green, c_build_cnt, 0.7); // кладбища //******************************* cr->set_dash(8*lw1, 3*lw1); render_line(0x20, c_hor, 1, 20); // пунктирные горизонтали cr->unset_dash(); render_line(0x21, c_hor, 1, 20); // горизонтали render_line(0x22, c_hor, 1.6, 20); // жирные горизонтали //******************************* render_img_polygons(0x51); // болота render_img_polygons(0x4C); // болота труднопроходимые render_line(0x24, c_riv_cnt, 1, 0); // старые болота -- не использутся //******************************* cr->join_round(); cr->cap_round(); cr->set_dash(0, 2.5*lw1); render_line(0x2B, c_kanav, 1.6, 0); // сухая канава cr->unset_dash(); render_line(0x25, c_ovrag, 2, 20); // овраг render_line(0xC, c_hreb, 2, 20); // хребет render_line(0xF, c_hreb, 1.5, 20); // малый хребет cr->set_dash(0, 2.5*lw1); render_line(0x2C, c_hor, 2.5, 0); // вал cr->unset_dash(); //******************************* cr->cap_round(); cr->set_dash(4*lw1, 3*lw1); render_line(0x26, c_riv_cnt, 1, 10); // пересыхающая река cr->unset_dash(); render_line(0x15, c_riv_cnt, 1, 10); // река-1 render_line(0x18, c_riv_cnt, 2, 10); // река-2 render_line(0x1F, c_riv_cnt, 3, 10); // река-3 render_cnt_polygons(0x29, c_riv_fill, c_riv_cnt, 1, 20); // водоемы render_cnt_polygons(0x3B, c_riv_fill, c_riv_cnt, 1, 20); // большие водоемы render_cnt_polygons(0x53, c_field, c_riv_cnt, 1, 20); // острова render_line(0x1F, c_riv_fill, 1, 10); // середина реки-3 diff --git a/core/img_io/gobj_vmap.h b/core/img_io/gobj_vmap.h index df1ce63..804bccc 100644 --- a/core/img_io/gobj_vmap.h +++ b/core/img_io/gobj_vmap.h @@ -1,126 +1,127 @@ #ifndef GOBJ_VMAP #define GOBJ_VMAP #include <string> #include <vector> #include <iostream> #include <fstream> #include <list> #include <cstring> #include <utils/cairo_wrapper.h> #include <2d/line_utils.h> #include "2d/line_dist.h" #include <geo/geo_convs.h> #include <geo/geo_nom.h> #include <geo_io/io_oe.h> #include "vmap/zn.h" #include "vmap/vmap.h" #include "opts/opts.h" #include "img_io/gobj_geo.h" #define LABEL_STYLE0 0 #define LABEL_STYLE1 1 #define LABEL_STYLE2 2 class GObjVMAP : public GObjGeo{ private: CairoWrapper cr; vmap::world * W; zn::zn_conv zc; double pics_dpi; double dpi, lw1; int bgcolor; bool cntrs, use_aa; int label_style; double label_marg; double grid_step; bool transp; int grid_labels; dPoint origin; + Cairo::Filter patt_filter; std::vector<Opts> render_data; public: /***/ GObjVMAP(vmap::world * _W, const Options & O = Options()); int draw(iImage &img, const iPoint &origin); vmap::world * get_data() const {return W;} // convert coordinates from meters to pixels void pt_m2pt(dPoint & p); void render_objects(); void render_holes(Conv & cnv); // place image in the center of polygons // polygons filled with image pattern void render_img_polygons(int type, double curve_l=0); // place image in points void render_im_in_points(int type); void render_polygons(int type, int col, double curve_l=0); // contoured polygons void render_cnt_polygons(int type, int fill_col, int cnt_col, double cnt_th, double curve_l=0); void render_line(int type, int col, double th, double curve_l=0); void render_points(int type, int col, double th); // paths for bridge sign void mkbrpath1(const vmap::object & o); void mkbrpath2(const vmap::object & o, double th, double side); // мосты void render_bridge(int type, double th1, double th2, double side); // лэп void render_line_el(Conv & cnv, int type, int col, double th, double step=40); // обрывы void render_line_obr(Conv & cnv, int type, int col, double th); // заборы void render_line_zab(Conv & cnv, int type, int col, double th); // вал void render_line_val(Conv & cnv, int type, int col, double th, double width, double step); // газопроводы void render_line_gaz(Conv & cnv, int type, int col, double th, double step=40); // нарисовать сетку с шагом dx,dy см в координатах Г-К СК1942г void render_pulk_grid(double dx, double dy, bool draw_labels, const g_map & ref); // нарисовать подпись сетки в месте пересейчаения // границы карты и линий с данным x=c или y=c (horiz=false) // todo: merge common code for x and y? void render_grid_label(double c, double val, bool horiz, const dLine & border); void render_labels(); // functions for drawing contours // создание контура -- набор точек на расстоянии dist друг от друга // вокруг областей с цветом col. Цвет в точках = col std::list<iPoint> make_cnt(int c, double dist); // Фильтрация контура - удаляем точки, попавшие в области с // цветом, отличным от col // Прогоняется после изменения картинки, чтобы удалить контуры, // которые были чем-то перекрыты. void filter_cnt(std::list<iPoint> & cnt, int c); // рисование уже готового контура void draw_cnt(const std::list<iPoint> & cnt, int c, double th); }; #endif diff --git a/vector/vmap3/vmap_render.cpp b/vector/vmap3/vmap_render.cpp index ff7d480..e97e2d8 100644 --- a/vector/vmap3/vmap_render.cpp +++ b/vector/vmap3/vmap_render.cpp @@ -1,199 +1,200 @@ #include "img_io/gobj_vmap.h" #include "options/m_getopt.h" #include "options/m_time.h" #include "geo_io/geo_refs.h" #include "loaders/image_r.h" #include "err/err.h" using namespace std; static struct ext_option options[] = { {"verbose", 0, 0, 1, "be more verbose"}, {"help", 0,'h', 1, "show this message"}, {"map", 1,'m', 1, "write OziExplorer map file"}, {"grid", 1,'g', 1, "draw grid with given step [cm]"}, {"grid_labels", 0,'l', 1, "draw grid labels"}, {"draw_name", 0,'N', 1, "draw map name"}, {"draw_date", 0,'D', 1, "draw date stamp"}, {"draw_text", 1,'T', 1, "draw text\n"}, {"bgcolor", 1, 0, 1, "backgound color\n"}, {"nobrd", 1, 0, 1, "ignore border in the file\n"}, {"antialiasing", 1, 0, 1, "do antialiasing (0|1, default 1)"}, + {"patt_filter", 1, 0, 1, "set pattern filter (fast|good|best|nearest|bilinear, default: good)"}, {"transp_margins",1, 0, 1, "transparent margins (0|1, default 0)"}, {"contours", 1, 0, 1, "auto contours (0|1, default 1)"}, {"label_style", 1, 0, 1, "set label style 0..2 (default 2)\n"}, {"pics_dir", 1, 0, 1, "pics folder (default: /usr/share/mapsoft/pics)\n"}, {"pics_dpi", 1, 0, 1, "pics resolution (default: 600.0)\n"}, {"render_data", 1, 0, 1, "Json file with rendering information\n"}, {"geom", 1, 0, 2, ""}, {"datum", 1, 0, 2, ""}, {"proj", 1, 0, 2, ""}, {"lon0", 1, 0, 2, ""}, {"wgs_geom", 1, 0, 2, ""}, {"wgs_brd", 1, 0, 2, ""}, {"trk_brd", 1, 0, 2, ""}, {"nom", 1, 0, 2, ""}, {"google", 1, 0, 2, "google tile, \"x,y,z\""}, {"rscale", 1, 0, 2, "reversed scale (10000 for 1:10000 map)"}, {"dpi", 1,'d', 2, "resolution, dots per inch"}, {"mag", 1, 0, 2, "additional magnification"}, {"swap_y", 0, 0, 2, "\n"}, {0,0,0,0} }; void usage(){ const char * prog = "vmap_render"; cerr << prog << " -- convert vector maps to raster.\n" << "Usage: " << prog << " [<options>] <in_file> <out_file>\n" << "\n" << "Options:\n" ; print_options(options, 1, cerr); cerr << "\n" << "Label styles (0 is fast and 2 is best):\n" << " 0 -- don't erase objects under text\n" << " 1 -- lighten all objects under text\n" << " 2 -- the best erasing [default] \n" << "\n" << "Contours:\n" << " 0 -- no auto contours around forests\n" << " 1 -- draw contours (needs slightly more memory and time) [default]\n" << "\n" << "Antialiasing:\n" << " 0 -- don't do antialiasing (needs 2x time (!))\n" << " 1 -- do antialiasing (needs slightly more memory) [default]\n" << "\n" << "Options to specify map range and projection:\n" ; print_options(options, 2, cerr); cerr << "\n" << "Default projection is tmerc, default range is a map border bounding box.\n" << "\n" ; } int main(int argc, char* argv[]){ try{ if (argc==1) usage(); Options O = parse_options(&argc, &argv, options, 3); if (O.exists("help")) { usage(); return 1;} if (argc<2) {usage(); return 1;} const char * ifile = argv[0]; const char * ofile = argv[1]; // create map vmap::world W=vmap::read(ifile); if (W.size()==0) throw Err() << "Error: empty map\n"; // set geometry if no --wgs_geom, --wgs_brd, --geom, // --nom, --google option exists if (O.exists("nobrd")) W.brd.clear(); if (!O.exists("geom") && !O.exists("wgs_geom") && !O.exists("nom") && !O.exists("google") && !O.exists("wgs_brd")){ if (W.brd.size()>2) O.put("wgs_brd", W.brd); else O.put("wgs_geom", W.range()); } if (!O.exists("rscale")) O.put("rscale", W.rscale); g_map ref = mk_ref(O); ref.comm=W.name; // process other options double dpi=O.get<double>("dpi", 300); // set margins int tm=0, bm=0, lm=0, rm=0; if (O.get<int>("draw_name", 0) || O.get<int>("draw_date", 0) || (O.get<string>("draw_text") != "")) { tm=dpi/3; bm=lm=rm=dpi/6; } int grid_labels = O.get<int>("grid_labels", 0); if (grid_labels){ bm+=dpi/6; tm+=dpi/6; rm+=dpi/6; lm+=dpi/6; } // modify vmap vmap::join_labels(W); vmap::move_pics(W); // calculate picture range, create Image dRect rng = ref.border.range(); rng.x = rng.y = 0; rng.w+=lm+rm; if (rng.w<0) rng.w=0; rng.h+=tm+bm; if (rng.h<0) rng.h=0; ref+=dPoint(lm,tm); cerr << " scale = 1:" << int(W.rscale) << "\n" << " dpi = " << dpi << "\n" << " image = " << int(round(rng.w)) << "x" << int(round(rng.h))<< "\n"; iImage img(round(rng.w), round(rng.h), 0); ref.border.clear(); convs::map2wgs cnv(ref); if (W.size() == 0) cerr << "warning: no objects\n"; GObjVMAP R(&W, O); R.set_ref(ref); R.draw(img, dPoint(0,0)); CairoWrapper cr(img); if (O.get<int>("draw_name", 0)) cr->render_text(W.name.c_str(), dPoint(dpi/5,dpi/15), 0, 0, 18, 14, dpi, 0, 2); if (O.get<int>("draw_date", 0)){ Time t; t.set_current(); cr->render_text(t.date_str().c_str(), dPoint(dpi/30,dpi), -M_PI/2, 0, 18, 10, dpi, 2, 2); } if (O.get<string>("draw_text") != ""){ cr->render_text(O.get<string>("draw_text").c_str(), dPoint(dpi/5,rng.h-dpi/30), 0, 0, 18, 10, dpi, 0, 0); } //******************************* image_r::save(img, ofile); string map = O.get<string>("map"); if (map!=""){ g_map M = ref; M.file = ofile; if (W.brd.size()>2) M.border=cnv.line_bck(W.brd); M.border.push_back(*M.border.begin()); M.border=generalize(M.border,1,-1); // 1pt accuracy M.border.resize(M.border.size()-1); try {oe::write_map_file(map.c_str(), M);} catch (Err e) {cerr << e.get_error() << endl;} } //******************************* } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
397329a1b7ff22bbf561504e1a57383a7410e994
vmap_render: initialize image; do not use border from mk_ref
diff --git a/vector/vmap3/vmap_render.cpp b/vector/vmap3/vmap_render.cpp index 1c2b070..ff7d480 100644 --- a/vector/vmap3/vmap_render.cpp +++ b/vector/vmap3/vmap_render.cpp @@ -1,198 +1,199 @@ #include "img_io/gobj_vmap.h" #include "options/m_getopt.h" #include "options/m_time.h" #include "geo_io/geo_refs.h" #include "loaders/image_r.h" #include "err/err.h" using namespace std; static struct ext_option options[] = { {"verbose", 0, 0, 1, "be more verbose"}, {"help", 0,'h', 1, "show this message"}, {"map", 1,'m', 1, "write OziExplorer map file"}, {"grid", 1,'g', 1, "draw grid with given step [cm]"}, {"grid_labels", 0,'l', 1, "draw grid labels"}, {"draw_name", 0,'N', 1, "draw map name"}, {"draw_date", 0,'D', 1, "draw date stamp"}, {"draw_text", 1,'T', 1, "draw text\n"}, {"bgcolor", 1, 0, 1, "backgound color\n"}, {"nobrd", 1, 0, 1, "ignore border in the file\n"}, {"antialiasing", 1, 0, 1, "do antialiasing (0|1, default 1)"}, {"transp_margins",1, 0, 1, "transparent margins (0|1, default 0)"}, {"contours", 1, 0, 1, "auto contours (0|1, default 1)"}, {"label_style", 1, 0, 1, "set label style 0..2 (default 2)\n"}, {"pics_dir", 1, 0, 1, "pics folder (default: /usr/share/mapsoft/pics)\n"}, {"pics_dpi", 1, 0, 1, "pics resolution (default: 600.0)\n"}, {"render_data", 1, 0, 1, "Json file with rendering information\n"}, {"geom", 1, 0, 2, ""}, {"datum", 1, 0, 2, ""}, {"proj", 1, 0, 2, ""}, {"lon0", 1, 0, 2, ""}, {"wgs_geom", 1, 0, 2, ""}, {"wgs_brd", 1, 0, 2, ""}, {"trk_brd", 1, 0, 2, ""}, {"nom", 1, 0, 2, ""}, {"google", 1, 0, 2, "google tile, \"x,y,z\""}, {"rscale", 1, 0, 2, "reversed scale (10000 for 1:10000 map)"}, {"dpi", 1,'d', 2, "resolution, dots per inch"}, {"mag", 1, 0, 2, "additional magnification"}, {"swap_y", 0, 0, 2, "\n"}, {0,0,0,0} }; void usage(){ const char * prog = "vmap_render"; cerr << prog << " -- convert vector maps to raster.\n" << "Usage: " << prog << " [<options>] <in_file> <out_file>\n" << "\n" << "Options:\n" ; print_options(options, 1, cerr); cerr << "\n" << "Label styles (0 is fast and 2 is best):\n" << " 0 -- don't erase objects under text\n" << " 1 -- lighten all objects under text\n" << " 2 -- the best erasing [default] \n" << "\n" << "Contours:\n" << " 0 -- no auto contours around forests\n" << " 1 -- draw contours (needs slightly more memory and time) [default]\n" << "\n" << "Antialiasing:\n" << " 0 -- don't do antialiasing (needs 2x time (!))\n" << " 1 -- do antialiasing (needs slightly more memory) [default]\n" << "\n" << "Options to specify map range and projection:\n" ; print_options(options, 2, cerr); cerr << "\n" << "Default projection is tmerc, default range is a map border bounding box.\n" << "\n" ; } int main(int argc, char* argv[]){ try{ if (argc==1) usage(); Options O = parse_options(&argc, &argv, options, 3); if (O.exists("help")) { usage(); return 1;} if (argc<2) {usage(); return 1;} const char * ifile = argv[0]; const char * ofile = argv[1]; // create map vmap::world W=vmap::read(ifile); if (W.size()==0) throw Err() << "Error: empty map\n"; // set geometry if no --wgs_geom, --wgs_brd, --geom, // --nom, --google option exists if (O.exists("nobrd")) W.brd.clear(); if (!O.exists("geom") && !O.exists("wgs_geom") && !O.exists("nom") && !O.exists("google") && !O.exists("wgs_brd")){ if (W.brd.size()>2) O.put("wgs_brd", W.brd); else O.put("wgs_geom", W.range()); } if (!O.exists("rscale")) O.put("rscale", W.rscale); g_map ref = mk_ref(O); ref.comm=W.name; // process other options double dpi=O.get<double>("dpi", 300); // set margins int tm=0, bm=0, lm=0, rm=0; if (O.get<int>("draw_name", 0) || O.get<int>("draw_date", 0) || (O.get<string>("draw_text") != "")) { tm=dpi/3; bm=lm=rm=dpi/6; } int grid_labels = O.get<int>("grid_labels", 0); if (grid_labels){ bm+=dpi/6; tm+=dpi/6; rm+=dpi/6; lm+=dpi/6; } // modify vmap vmap::join_labels(W); vmap::move_pics(W); // calculate picture range, create Image dRect rng = ref.border.range(); rng.x = rng.y = 0; rng.w+=lm+rm; if (rng.w<0) rng.w=0; rng.h+=tm+bm; if (rng.h<0) rng.h=0; ref+=dPoint(lm,tm); cerr << " scale = 1:" << int(W.rscale) << "\n" << " dpi = " << dpi << "\n" << " image = " << int(round(rng.w)) << "x" << int(round(rng.h))<< "\n"; - iImage img(round(rng.w), round(rng.h)); + iImage img(round(rng.w), round(rng.h), 0); + ref.border.clear(); convs::map2wgs cnv(ref); if (W.size() == 0) cerr << "warning: no objects\n"; GObjVMAP R(&W, O); R.set_ref(ref); R.draw(img, dPoint(0,0)); CairoWrapper cr(img); if (O.get<int>("draw_name", 0)) cr->render_text(W.name.c_str(), dPoint(dpi/5,dpi/15), 0, 0, 18, 14, dpi, 0, 2); if (O.get<int>("draw_date", 0)){ Time t; t.set_current(); cr->render_text(t.date_str().c_str(), dPoint(dpi/30,dpi), -M_PI/2, 0, 18, 10, dpi, 2, 2); } if (O.get<string>("draw_text") != ""){ cr->render_text(O.get<string>("draw_text").c_str(), dPoint(dpi/5,rng.h-dpi/30), 0, 0, 18, 10, dpi, 0, 0); } //******************************* image_r::save(img, ofile); string map = O.get<string>("map"); if (map!=""){ g_map M = ref; M.file = ofile; if (W.brd.size()>2) M.border=cnv.line_bck(W.brd); M.border.push_back(*M.border.begin()); M.border=generalize(M.border,1,-1); // 1pt accuracy M.border.resize(M.border.size()-1); try {oe::write_map_file(map.c_str(), M);} catch (Err e) {cerr << e.get_error() << endl;} } //******************************* } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
23877648ff79b7a084bc65d208670c8c94c66606
convs_gtiles: catch errors globally
diff --git a/programs/convs_gtiles.cpp b/programs/convs_gtiles.cpp index 41c54a0..4db9b1c 100644 --- a/programs/convs_gtiles.cpp +++ b/programs/convs_gtiles.cpp @@ -1,159 +1,158 @@ #include "tiles/tiles.h" #include "opts/opts.h" #include "geo_io/geo_refs.h" #include <iostream> #include <cstring> #include <vector> #include <boost/geometry.hpp> using namespace std; void usage(){ cerr << "\n" << "Google tile calculator.\n" << "usage: convs_tile -p <point> <z> -- tile which covers a WGS84 point\n" << " convs_tile -r <range> <z> -- tiles which cover a range (return a rectangle)\n" << " convs_tile -R <range> <z> -- tiles which cover a range (return a list)\n" << " convs_tile -bi <track> <z> -- tiles which touches the area (return a list)\n" << " convs_tile -bc <track> <z> -- tiles which fully covered by area (return a list)\n" << " convs_tile -n x y z -- tile range\n" << " convs_tile -c x y z -- tile center\n" << " convs_tile -t x y z <range> -- check if a tile touches a range\n" << "\n" ; } int main(int argc, char** argv){ + try{ - Tiles calc; + Tiles calc; - if ((argc == 4) && (strcmp(argv[1], "-p") == 0)){ - iPoint ret = calc.pt_to_gtile( - str_to_type<dPoint>(argv[2]), - str_to_type<int>(argv[3])); - cout << ret << "\n"; - return 0; - } + if ((argc == 4) && (strcmp(argv[1], "-p") == 0)){ + iPoint ret = calc.pt_to_gtile( + str_to_type<dPoint>(argv[2]), + str_to_type<int>(argv[3])); + cout << ret << "\n"; + return 0; + } - if ((argc == 4) && (strcmp(argv[1], "-r") == 0)){ - iRect ret = calc.range_to_gtiles( - str_to_type<dRect>(argv[2]), - str_to_type<int>(argv[3])); - cout << ret << "\n"; - return 0; - } + if ((argc == 4) && (strcmp(argv[1], "-r") == 0)){ + iRect ret = calc.range_to_gtiles( + str_to_type<dRect>(argv[2]), + str_to_type<int>(argv[3])); + cout << ret << "\n"; + return 0; + } - if ((argc == 4) && (strcmp(argv[1], "-R") == 0)){ - int z = str_to_type<int>(argv[3]); - iRect ret = calc.range_to_gtiles( - str_to_type<dRect>(argv[2]),z); - for (int y = ret.y; y<ret.y+ret.h; y++) - for (int x = ret.x; x<ret.x+ret.w; x++) - cout << x << "," << y << "," << z << "\n"; - return 0; - } + if ((argc == 4) && (strcmp(argv[1], "-R") == 0)){ + int z = str_to_type<int>(argv[3]); + iRect ret = calc.range_to_gtiles( + str_to_type<dRect>(argv[2]),z); + for (int y = ret.y; y<ret.y+ret.h; y++) + for (int x = ret.x; x<ret.x+ret.w; x++) + cout << x << "," << y << "," << z << "\n"; + return 0; + } + + if ((argc == 4) && ((strcmp(argv[1], "-bi") == 0) + || (strcmp(argv[1], "-bc") == 0))){ + using namespace boost::geometry; + int zfin = str_to_type<int>(argv[3]); + geo_data B; + vector<g_track>::const_iterator bi; + vector<g_trackpoint>::const_iterator pi; + typedef model::d2::point_xy<double> point_t; + std::vector<point_t> pts; + typedef model::polygon<point_t> polygon_t; + polygon_t poly; + typedef struct {int x; int y; int z;} tile_s; + vector<tile_s> oldtiles, newtiles = {{0, 0, 0}}; + vector<tile_s>::const_iterator ti; - if ((argc == 4) && ((strcmp(argv[1], "-bi") == 0) - || (strcmp(argv[1], "-bc") == 0))){ - using namespace boost::geometry; - int zfin = str_to_type<int>(argv[3]); - geo_data B; - vector<g_track>::const_iterator bi; - vector<g_trackpoint>::const_iterator pi; - typedef model::d2::point_xy<double> point_t; - std::vector<point_t> pts; - typedef model::polygon<point_t> polygon_t; - polygon_t poly; - typedef struct {int x; int y; int z;} tile_s; - vector<tile_s> oldtiles, newtiles = {{0, 0, 0}}; - vector<tile_s>::const_iterator ti; - - try{ io::in(string(argv[2]), B); - } - catch(Err e) { - cerr << e.get_error() << endl; - return 1; - } - // Прочитаем трек в полигон - pts.clear(); - bi=B.trks.begin(); - for (pi=bi->begin(); pi!=bi->end(); pi++){ - pts.push_back(point_t(pi->x, pi->y)); - } - pts.push_back(point_t(bi->begin()->x, bi->begin()->y)); - append(poly, pts); - - /* Переберём все возможные тайлы - методом последовательных приближений */ - for (int z = 1; z <= zfin; z++) { - oldtiles=newtiles; - newtiles.clear(); - // Переберём все тайлы с прошлого приближения - for (ti=oldtiles.begin(); ti!=oldtiles.end(); ti++) { - // Поделим подходящий тайл на 4 новых и проверим каждый из них - for (int i = 0; i < 4; i++) { - int flag; - int x = ti->x * 2 + (i & 1); - int y = ti->y * 2 + !!(i & 2); - polygon_t tile; - dRect tr = calc.gtile_to_range(x, y, z); - pts.clear(); - pts.push_back(point_t(tr.x, tr.y )); - pts.push_back(point_t(tr.x + tr.w, tr.y )); - pts.push_back(point_t(tr.x + tr.w, tr.y + tr.h)); - pts.push_back(point_t(tr.x , tr.y + tr.h)); - pts.push_back(point_t(tr.x, tr.y )); - append(tile, pts); - - if ((z == zfin) && strcmp(argv[1], "-bi") != 0) { - /* Полное покрытие */ - flag = covered_by(tile, poly); - } else { - /* Простое пересечение */ - flag = intersects(tile, poly); - } - if (flag) { - tile_s tt = {x, y, z}; - newtiles.push_back(tt); + // Прочитаем трек в полигон + pts.clear(); + bi=B.trks.begin(); + for (pi=bi->begin(); pi!=bi->end(); pi++){ + pts.push_back(point_t(pi->x, pi->y)); + } + pts.push_back(point_t(bi->begin()->x, bi->begin()->y)); + append(poly, pts); + + /* Переберём все возможные тайлы + методом последовательных приближений */ + for (int z = 1; z <= zfin; z++) { + oldtiles=newtiles; + newtiles.clear(); + // Переберём все тайлы с прошлого приближения + for (ti=oldtiles.begin(); ti!=oldtiles.end(); ti++) { + // Поделим подходящий тайл на 4 новых и проверим каждый из них + for (int i = 0; i < 4; i++) { + int flag; + int x = ti->x * 2 + (i & 1); + int y = ti->y * 2 + !!(i & 2); + polygon_t tile; + dRect tr = calc.gtile_to_range(x, y, z); + pts.clear(); + pts.push_back(point_t(tr.x, tr.y )); + pts.push_back(point_t(tr.x + tr.w, tr.y )); + pts.push_back(point_t(tr.x + tr.w, tr.y + tr.h)); + pts.push_back(point_t(tr.x , tr.y + tr.h)); + pts.push_back(point_t(tr.x, tr.y )); + append(tile, pts); + + if ((z == zfin) && strcmp(argv[1], "-bi") != 0) { + /* Полное покрытие */ + flag = covered_by(tile, poly); + } else { + /* Простое пересечение */ + flag = intersects(tile, poly); + } + if (flag) { + tile_s tt = {x, y, z}; + newtiles.push_back(tt); + } } } } + for (ti=newtiles.begin(); ti!=newtiles.end(); ti++) { + cout << ti->x << " " << ti->y << " " << ti->z << endl; + } + return 0; } - for (ti=newtiles.begin(); ti!=newtiles.end(); ti++) { - cout << ti->x << " " << ti->y << " " << ti->z << endl; + + if ((argc == 5) && (strcmp(argv[1], "-n") == 0)){ + dRect ret = calc.gtile_to_range( + str_to_type<int>(argv[2]), + str_to_type<int>(argv[3]), + str_to_type<int>(argv[4])); + cout << setprecision(9) << ret << "\n"; + return 0; } - return 0; - } - if ((argc == 5) && (strcmp(argv[1], "-n") == 0)){ - dRect ret = calc.gtile_to_range( - str_to_type<int>(argv[2]), - str_to_type<int>(argv[3]), - str_to_type<int>(argv[4])); - cout << setprecision(9) << ret << "\n"; - return 0; - } + if ((argc == 5) && (strcmp(argv[1], "-c") == 0)){ + dRect ret = calc.gtile_to_range( + str_to_type<int>(argv[2]), + str_to_type<int>(argv[3]), + str_to_type<int>(argv[4])); + cout << setprecision(9) << ret.CNT() << "\n"; + return 0; + } - if ((argc == 5) && (strcmp(argv[1], "-c") == 0)){ - dRect ret = calc.gtile_to_range( - str_to_type<int>(argv[2]), - str_to_type<int>(argv[3]), - str_to_type<int>(argv[4])); - cout << setprecision(9) << ret.CNT() << "\n"; - return 0; - } + if ((argc == 6) && (strcmp(argv[1], "-t") == 0)){ + dRect r1 = calc.gtile_to_range( + str_to_type<int>(argv[2]), + str_to_type<int>(argv[3]), + str_to_type<int>(argv[4])); + dRect r2 = str_to_type<dRect>(argv[5]); + return rect_intersect(r1,r2).empty(); + } - if ((argc == 6) && (strcmp(argv[1], "-t") == 0)){ - dRect r1 = calc.gtile_to_range( - str_to_type<int>(argv[2]), - str_to_type<int>(argv[3]), - str_to_type<int>(argv[4])); - dRect r2 = str_to_type<dRect>(argv[5]); - return rect_intersect(r1,r2).empty(); + usage(); + } + catch(Err e) { + cerr << "Error: " << e.get_error() << endl; } - - usage(); return 1; }
ushakov/mapsoft
df98800ca2ec3a475aeba49267035e70bde0ceff
move convs_gtiles to programs/, add it to the installation
diff --git a/core/SConscript b/core/SConscript index 38dc8d8..fe5f180 100644 --- a/core/SConscript +++ b/core/SConscript @@ -1,226 +1,224 @@ Import ('env') import os #swig = env.Clone() #swig.Append(CPPPATH = [distutils.sysconfig.get_python_inc()]) #swig.Replace(SWIGFLAGS = ['-c++', '-python']) #swig.Replace(SHLIBPREFIX = "") #swig.Append(LIBS = Split("geo_io geo 2d fig utils jeeps loaders tiff jpeg png curl")) #swig.SharedLibrary("_core.so", ["swig.i"]) ################################################## ## build mapsoft library env.UseLibs('libxml-2.0 libzip libproj libgif libjpeg libpng libtiff-4 libcurl zlib yaml-0.1 shp jansson') env.UseLibs('glibmm-2.4 gtkmm-2.4 gthread-2.0') env.UseLibs('cairomm-1.0 pixman-1 freetype2 libusb-1.0') # all source files objects = Split (""" err/err.cpp opts/opts.cpp filetype/filetype.cpp 2d/point_int.cpp 2d/rect.cpp 2d/conv.cpp 2d/conv_aff.cpp 2d/line_dist.cpp 2d/rainbow.cpp fig/fig_io.cpp fig/fig_mask.cpp fig/fig_utils.cpp fig/fig_data.cpp geo_io/filters.cpp geo_io/io.cpp geo_io/io_gps.cpp geo_io/io_gu.cpp geo_io/io_kml.cpp geo_io/io_gpx.cpp geo_io/io_oe.cpp geo_io/io_js.cpp geo_io/io_xml.cpp geo_io/io_zip.cpp geo_io/geofig.cpp geo_io/geo_refs.cpp geo/geo_convs.cpp geo/g_wpt.cpp geo/g_trk.cpp geo/g_map.cpp geo/geo_data.cpp geo/geo_types.cpp geo/geo_nom.cpp gred/gobj.cpp gred/action_manager.cpp gred/rubber.cpp gred/simple_viewer.cpp gred/dthread_viewer.cpp img_io/io.cpp img_io/o_img.cpp img_io/o_tiles.cpp img_io/draw_trk.cpp img_io/draw_wpt.cpp img_io/gobj_map.cpp img_io/gobj_trk.cpp img_io/gobj_wpt.cpp img_io/gobj_srtm.cpp img_io/gobj_srtmv.cpp img_io/gobj_pano.cpp img_io/gobj_vmap.cpp img_io/gobj_grid_pulk.cpp jeeps/gpsapp.c jeeps/gpscom.c jeeps/gpsdatum.c jeeps/gpsdevice.c jeeps/gpsdevice_ser.c jeeps/gpsdevice_usb.c jeeps/gpsfmt.c jeeps/gpsinput.c jeeps/gpslibusb.c jeeps/gpsmath.c jeeps/gpsmem.c jeeps/gpsproj.c jeeps/gpsprot.c jeeps/gpsread.c jeeps/gpsrqst.c jeeps/gpssend.c jeeps/gpsserial.c jeeps/gpsusbcommon.c jeeps/gpsusbread.c jeeps/gpsusbsend.c jeeps/gpsusbstub.c jeeps/gpsusbwin.c jeeps/gpsutil.c jeeps/utils.c loaders/image_jpeg.cpp loaders/image_tiff.cpp loaders/image_png.cpp loaders/image_gif.cpp loaders/image_r.cpp mp/mp_io.cpp mp/mp_mask.cpp mp/mp_data.cpp ocad/ocad_types.cpp ocad/ocad_colors.cpp ocad/ocad_file.cpp ocad/ocad_header.cpp ocad/ocad_fname.cpp ocad/ocad_object.cpp ocad/ocad_object8.cpp ocad/ocad_object9.cpp ocad/ocad_shead.cpp ocad/ocad_string.cpp ocad/ocad_symbol.cpp ocad/ocad_symbol8.cpp ocad/ocad_symbol9.cpp ocad/ocad_geo.cpp options/options.cpp options/m_time.cpp options/m_color.cpp options/m_getopt.cpp srtm/srtm3.cpp utils/log.cpp utils/iconv_utils.cpp utils/spirit_utils.cpp utils/pnm_shifter.cpp utils/cairo_wrapper.cpp vmap/zn.cpp vmap/zn_lists.cpp vmap/vmap.cpp vmap/vmap_file.cpp vmap/vmap_fig.cpp vmap/vmap_mp.cpp vmap/vmap_ocad.cpp vmap/vmap_vmap.cpp vmap/vmap_cnv.cpp vmap/vmap_filt.cpp vmap/vmap_labels.cpp vmap/vmap_ref.cpp vmap/vmap_legend.cpp """) env.StaticLibrary('mapsoft', objects) ################################################## ## strange programs inside the core folder programs=Split(""" - tiles/convs_gtiles.cpp - fig/catfig.cpp geo_io/catgeo.cpp loaders/img_convert.cpp mp/catmp.cpp ocad/ocad_test.cpp """) map(env.Program, programs) ################################################## ## simple tests: fail if error code is not zero simple_tests=Split(""" err/err.test.cpp opts/opts.test.cpp tiles/tiles.test.cpp cache/cache.test.cpp """) def builder_test_simple(target, source, env): prg = str(source[0].abspath) if os.spawnl(os.P_WAIT, prg, prg)==0: open(str(target[0]),'w').write("PASSED\n") else: return 1 # Create a builder for tests env.Append(BUILDERS = {'TestSimple' : Builder(action = builder_test_simple)}) def build_and_run_simple(src): prg = env.Program(src) res = str(prg[0]) + ".passed" env.TestSimple(res, prg) map(build_and_run_simple, simple_tests) ################################################## ## script tests: build a program, then run a script script_tests=Split(""" """) def builder_test_script(target, source, env): prg = str(source[0].abspath) scr = str(source[1].abspath) if os.spawnl(os.P_WAIT, scr, scr)==0: open(str(target[0]),'w').write("PASSED\n") else: return 1 # Create a builder for tests env.Append(BUILDERS = {'TestScript' : Builder(action = builder_test_script)}) def build_and_run_script(src): prg = env.Program(src) res = str(prg[0]) + ".passed" scr = str(prg[0]) + ".script" env.TestScript(res, [prg, scr]) map(build_and_run_script, script_tests) ################################################## diff --git a/programs/SConscript b/programs/SConscript index c91a222..ca350a7 100644 --- a/programs/SConscript +++ b/programs/SConscript @@ -1,36 +1,38 @@ Import ('env') progs = Split(""" mapsoft_convert mapsoft_mkmap mapsoft_ref mapsoft_toxyz mapsoft_map2fig mapsoft_srtm2fig mapsoft_fig2fig mapsoft_pano mapsoft_geofig convs_pt2pt convs_map2pt convs_nom + convs_gtiles mapsoft_vmap """) for p in progs: env.Program(p + '.cpp') env.Install(env.bindir, Split(""" mapsoft_convert mapsoft_vmap mapsoft_geofig mapsoft_toxyz mapsoft_mkmap convs_pt2pt convs_map2pt convs_nom + convs_gtiles """)) env.SymLink("mapsoft_vmap", "vmap_copy", env.bindir) diff --git a/core/tiles/convs_gtiles.cpp b/programs/convs_gtiles.cpp similarity index 99% rename from core/tiles/convs_gtiles.cpp rename to programs/convs_gtiles.cpp index fe418fd..41c54a0 100644 --- a/core/tiles/convs_gtiles.cpp +++ b/programs/convs_gtiles.cpp @@ -1,159 +1,159 @@ -#include "tiles.h" +#include "tiles/tiles.h" #include "opts/opts.h" #include "geo_io/geo_refs.h" #include <iostream> #include <cstring> #include <vector> #include <boost/geometry.hpp> using namespace std; void usage(){ cerr << "\n" << "Google tile calculator.\n" << "usage: convs_tile -p <point> <z> -- tile which covers a WGS84 point\n" << " convs_tile -r <range> <z> -- tiles which cover a range (return a rectangle)\n" << " convs_tile -R <range> <z> -- tiles which cover a range (return a list)\n" << " convs_tile -bi <track> <z> -- tiles which touches the area (return a list)\n" << " convs_tile -bc <track> <z> -- tiles which fully covered by area (return a list)\n" << " convs_tile -n x y z -- tile range\n" << " convs_tile -c x y z -- tile center\n" << " convs_tile -t x y z <range> -- check if a tile touches a range\n" << "\n" ; } int main(int argc, char** argv){ Tiles calc; if ((argc == 4) && (strcmp(argv[1], "-p") == 0)){ iPoint ret = calc.pt_to_gtile( str_to_type<dPoint>(argv[2]), str_to_type<int>(argv[3])); cout << ret << "\n"; return 0; } if ((argc == 4) && (strcmp(argv[1], "-r") == 0)){ iRect ret = calc.range_to_gtiles( str_to_type<dRect>(argv[2]), str_to_type<int>(argv[3])); cout << ret << "\n"; return 0; } if ((argc == 4) && (strcmp(argv[1], "-R") == 0)){ int z = str_to_type<int>(argv[3]); iRect ret = calc.range_to_gtiles( str_to_type<dRect>(argv[2]),z); for (int y = ret.y; y<ret.y+ret.h; y++) for (int x = ret.x; x<ret.x+ret.w; x++) cout << x << "," << y << "," << z << "\n"; return 0; } if ((argc == 4) && ((strcmp(argv[1], "-bi") == 0) || (strcmp(argv[1], "-bc") == 0))){ using namespace boost::geometry; int zfin = str_to_type<int>(argv[3]); geo_data B; vector<g_track>::const_iterator bi; vector<g_trackpoint>::const_iterator pi; typedef model::d2::point_xy<double> point_t; std::vector<point_t> pts; typedef model::polygon<point_t> polygon_t; polygon_t poly; typedef struct {int x; int y; int z;} tile_s; vector<tile_s> oldtiles, newtiles = {{0, 0, 0}}; vector<tile_s>::const_iterator ti; try{ io::in(string(argv[2]), B); } catch(Err e) { cerr << e.get_error() << endl; return 1; } // Прочитаем трек в полигон pts.clear(); bi=B.trks.begin(); for (pi=bi->begin(); pi!=bi->end(); pi++){ pts.push_back(point_t(pi->x, pi->y)); } pts.push_back(point_t(bi->begin()->x, bi->begin()->y)); append(poly, pts); /* Переберём все возможные тайлы методом последовательных приближений */ for (int z = 1; z <= zfin; z++) { oldtiles=newtiles; newtiles.clear(); // Переберём все тайлы с прошлого приближения for (ti=oldtiles.begin(); ti!=oldtiles.end(); ti++) { // Поделим подходящий тайл на 4 новых и проверим каждый из них for (int i = 0; i < 4; i++) { int flag; int x = ti->x * 2 + (i & 1); int y = ti->y * 2 + !!(i & 2); polygon_t tile; dRect tr = calc.gtile_to_range(x, y, z); pts.clear(); pts.push_back(point_t(tr.x, tr.y )); pts.push_back(point_t(tr.x + tr.w, tr.y )); pts.push_back(point_t(tr.x + tr.w, tr.y + tr.h)); pts.push_back(point_t(tr.x , tr.y + tr.h)); pts.push_back(point_t(tr.x, tr.y )); append(tile, pts); if ((z == zfin) && strcmp(argv[1], "-bi") != 0) { /* Полное покрытие */ flag = covered_by(tile, poly); } else { /* Простое пересечение */ flag = intersects(tile, poly); } if (flag) { tile_s tt = {x, y, z}; newtiles.push_back(tt); } } } } for (ti=newtiles.begin(); ti!=newtiles.end(); ti++) { cout << ti->x << " " << ti->y << " " << ti->z << endl; } return 0; } if ((argc == 5) && (strcmp(argv[1], "-n") == 0)){ dRect ret = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); cout << setprecision(9) << ret << "\n"; return 0; } if ((argc == 5) && (strcmp(argv[1], "-c") == 0)){ dRect ret = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); cout << setprecision(9) << ret.CNT() << "\n"; return 0; } if ((argc == 6) && (strcmp(argv[1], "-t") == 0)){ dRect r1 = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); dRect r2 = str_to_type<dRect>(argv[5]); return rect_intersect(r1,r2).empty(); } usage(); return 1; }
ushakov/mapsoft
674cf6c8f235324beb4f69d806210655bf39fd9a
core/tiles/convs_gtiles: add -bi, -bc options, thanks to ioctl@ya
diff --git a/core/tiles/convs_gtiles.cpp b/core/tiles/convs_gtiles.cpp index 94bd68e..fe418fd 100644 --- a/core/tiles/convs_gtiles.cpp +++ b/core/tiles/convs_gtiles.cpp @@ -1,80 +1,159 @@ #include "tiles.h" #include "opts/opts.h" +#include "geo_io/geo_refs.h" #include <iostream> #include <cstring> +#include <vector> +#include <boost/geometry.hpp> using namespace std; void usage(){ cerr << "\n" << "Google tile calculator.\n" << "usage: convs_tile -p <point> <z> -- tile which covers a WGS84 point\n" << " convs_tile -r <range> <z> -- tiles which cover a range (return a rectangle)\n" << " convs_tile -R <range> <z> -- tiles which cover a range (return a list)\n" + << " convs_tile -bi <track> <z> -- tiles which touches the area (return a list)\n" + << " convs_tile -bc <track> <z> -- tiles which fully covered by area (return a list)\n" << " convs_tile -n x y z -- tile range\n" << " convs_tile -c x y z -- tile center\n" << " convs_tile -t x y z <range> -- check if a tile touches a range\n" << "\n" ; } int main(int argc, char** argv){ Tiles calc; if ((argc == 4) && (strcmp(argv[1], "-p") == 0)){ iPoint ret = calc.pt_to_gtile( str_to_type<dPoint>(argv[2]), str_to_type<int>(argv[3])); cout << ret << "\n"; return 0; } if ((argc == 4) && (strcmp(argv[1], "-r") == 0)){ iRect ret = calc.range_to_gtiles( str_to_type<dRect>(argv[2]), str_to_type<int>(argv[3])); cout << ret << "\n"; return 0; } if ((argc == 4) && (strcmp(argv[1], "-R") == 0)){ int z = str_to_type<int>(argv[3]); iRect ret = calc.range_to_gtiles( str_to_type<dRect>(argv[2]),z); for (int y = ret.y; y<ret.y+ret.h; y++) for (int x = ret.x; x<ret.x+ret.w; x++) cout << x << "," << y << "," << z << "\n"; return 0; } + if ((argc == 4) && ((strcmp(argv[1], "-bi") == 0) + || (strcmp(argv[1], "-bc") == 0))){ + using namespace boost::geometry; + int zfin = str_to_type<int>(argv[3]); + geo_data B; + vector<g_track>::const_iterator bi; + vector<g_trackpoint>::const_iterator pi; + typedef model::d2::point_xy<double> point_t; + std::vector<point_t> pts; + typedef model::polygon<point_t> polygon_t; + polygon_t poly; + typedef struct {int x; int y; int z;} tile_s; + vector<tile_s> oldtiles, newtiles = {{0, 0, 0}}; + vector<tile_s>::const_iterator ti; + + try{ + io::in(string(argv[2]), B); + } + catch(Err e) { + cerr << e.get_error() << endl; + return 1; + } + + // Прочитаем трек в полигон + pts.clear(); + bi=B.trks.begin(); + for (pi=bi->begin(); pi!=bi->end(); pi++){ + pts.push_back(point_t(pi->x, pi->y)); + } + pts.push_back(point_t(bi->begin()->x, bi->begin()->y)); + append(poly, pts); + + /* Переберём все возможные тайлы + методом последовательных приближений */ + for (int z = 1; z <= zfin; z++) { + oldtiles=newtiles; + newtiles.clear(); + // Переберём все тайлы с прошлого приближения + for (ti=oldtiles.begin(); ti!=oldtiles.end(); ti++) { + // Поделим подходящий тайл на 4 новых и проверим каждый из них + for (int i = 0; i < 4; i++) { + int flag; + int x = ti->x * 2 + (i & 1); + int y = ti->y * 2 + !!(i & 2); + polygon_t tile; + dRect tr = calc.gtile_to_range(x, y, z); + pts.clear(); + pts.push_back(point_t(tr.x, tr.y )); + pts.push_back(point_t(tr.x + tr.w, tr.y )); + pts.push_back(point_t(tr.x + tr.w, tr.y + tr.h)); + pts.push_back(point_t(tr.x , tr.y + tr.h)); + pts.push_back(point_t(tr.x, tr.y )); + append(tile, pts); + + if ((z == zfin) && strcmp(argv[1], "-bi") != 0) { + /* Полное покрытие */ + flag = covered_by(tile, poly); + } else { + /* Простое пересечение */ + flag = intersects(tile, poly); + } + if (flag) { + tile_s tt = {x, y, z}; + newtiles.push_back(tt); + } + } + } + } + for (ti=newtiles.begin(); ti!=newtiles.end(); ti++) { + cout << ti->x << " " << ti->y << " " << ti->z << endl; + } + return 0; + } + if ((argc == 5) && (strcmp(argv[1], "-n") == 0)){ dRect ret = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); cout << setprecision(9) << ret << "\n"; return 0; } if ((argc == 5) && (strcmp(argv[1], "-c") == 0)){ dRect ret = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); cout << setprecision(9) << ret.CNT() << "\n"; return 0; } if ((argc == 6) && (strcmp(argv[1], "-t") == 0)){ dRect r1 = calc.gtile_to_range( str_to_type<int>(argv[2]), str_to_type<int>(argv[3]), str_to_type<int>(argv[4])); dRect r2 = str_to_type<dRect>(argv[5]); return rect_intersect(r1,r2).empty(); } usage(); return 1; }
ushakov/mapsoft
5c23edab1acc45bd5b6f676e31873e7a04501e12
vmap_render: fix image size calculation (thanks to ioctl@ya)
diff --git a/vector/vmap3/vmap_render.cpp b/vector/vmap3/vmap_render.cpp index 1a795e5..1c2b070 100644 --- a/vector/vmap3/vmap_render.cpp +++ b/vector/vmap3/vmap_render.cpp @@ -1,198 +1,198 @@ #include "img_io/gobj_vmap.h" #include "options/m_getopt.h" #include "options/m_time.h" #include "geo_io/geo_refs.h" #include "loaders/image_r.h" #include "err/err.h" using namespace std; static struct ext_option options[] = { {"verbose", 0, 0, 1, "be more verbose"}, {"help", 0,'h', 1, "show this message"}, {"map", 1,'m', 1, "write OziExplorer map file"}, {"grid", 1,'g', 1, "draw grid with given step [cm]"}, {"grid_labels", 0,'l', 1, "draw grid labels"}, {"draw_name", 0,'N', 1, "draw map name"}, {"draw_date", 0,'D', 1, "draw date stamp"}, {"draw_text", 1,'T', 1, "draw text\n"}, {"bgcolor", 1, 0, 1, "backgound color\n"}, {"nobrd", 1, 0, 1, "ignore border in the file\n"}, {"antialiasing", 1, 0, 1, "do antialiasing (0|1, default 1)"}, {"transp_margins",1, 0, 1, "transparent margins (0|1, default 0)"}, {"contours", 1, 0, 1, "auto contours (0|1, default 1)"}, {"label_style", 1, 0, 1, "set label style 0..2 (default 2)\n"}, {"pics_dir", 1, 0, 1, "pics folder (default: /usr/share/mapsoft/pics)\n"}, {"pics_dpi", 1, 0, 1, "pics resolution (default: 600.0)\n"}, {"render_data", 1, 0, 1, "Json file with rendering information\n"}, {"geom", 1, 0, 2, ""}, {"datum", 1, 0, 2, ""}, {"proj", 1, 0, 2, ""}, {"lon0", 1, 0, 2, ""}, {"wgs_geom", 1, 0, 2, ""}, {"wgs_brd", 1, 0, 2, ""}, {"trk_brd", 1, 0, 2, ""}, {"nom", 1, 0, 2, ""}, {"google", 1, 0, 2, "google tile, \"x,y,z\""}, {"rscale", 1, 0, 2, "reversed scale (10000 for 1:10000 map)"}, {"dpi", 1,'d', 2, "resolution, dots per inch"}, {"mag", 1, 0, 2, "additional magnification"}, {"swap_y", 0, 0, 2, "\n"}, {0,0,0,0} }; void usage(){ const char * prog = "vmap_render"; cerr << prog << " -- convert vector maps to raster.\n" << "Usage: " << prog << " [<options>] <in_file> <out_file>\n" << "\n" << "Options:\n" ; print_options(options, 1, cerr); cerr << "\n" << "Label styles (0 is fast and 2 is best):\n" << " 0 -- don't erase objects under text\n" << " 1 -- lighten all objects under text\n" << " 2 -- the best erasing [default] \n" << "\n" << "Contours:\n" << " 0 -- no auto contours around forests\n" << " 1 -- draw contours (needs slightly more memory and time) [default]\n" << "\n" << "Antialiasing:\n" << " 0 -- don't do antialiasing (needs 2x time (!))\n" << " 1 -- do antialiasing (needs slightly more memory) [default]\n" << "\n" << "Options to specify map range and projection:\n" ; print_options(options, 2, cerr); cerr << "\n" << "Default projection is tmerc, default range is a map border bounding box.\n" << "\n" ; } int main(int argc, char* argv[]){ try{ if (argc==1) usage(); Options O = parse_options(&argc, &argv, options, 3); if (O.exists("help")) { usage(); return 1;} if (argc<2) {usage(); return 1;} const char * ifile = argv[0]; const char * ofile = argv[1]; // create map vmap::world W=vmap::read(ifile); if (W.size()==0) throw Err() << "Error: empty map\n"; // set geometry if no --wgs_geom, --wgs_brd, --geom, // --nom, --google option exists if (O.exists("nobrd")) W.brd.clear(); if (!O.exists("geom") && !O.exists("wgs_geom") && !O.exists("nom") && !O.exists("google") && !O.exists("wgs_brd")){ if (W.brd.size()>2) O.put("wgs_brd", W.brd); else O.put("wgs_geom", W.range()); } if (!O.exists("rscale")) O.put("rscale", W.rscale); g_map ref = mk_ref(O); ref.comm=W.name; // process other options double dpi=O.get<double>("dpi", 300); // set margins int tm=0, bm=0, lm=0, rm=0; if (O.get<int>("draw_name", 0) || O.get<int>("draw_date", 0) || (O.get<string>("draw_text") != "")) { tm=dpi/3; bm=lm=rm=dpi/6; } int grid_labels = O.get<int>("grid_labels", 0); if (grid_labels){ bm+=dpi/6; tm+=dpi/6; rm+=dpi/6; lm+=dpi/6; } // modify vmap vmap::join_labels(W); vmap::move_pics(W); // calculate picture range, create Image dRect rng = ref.border.range(); rng.x = rng.y = 0; rng.w+=lm+rm; if (rng.w<0) rng.w=0; rng.h+=tm+bm; if (rng.h<0) rng.h=0; ref+=dPoint(lm,tm); cerr << " scale = 1:" << int(W.rscale) << "\n" << " dpi = " << dpi << "\n" - << " image = " << int(rng.w) << "x" << int(rng.h)<< "\n"; - iImage img(rng.w, rng.h); + << " image = " << int(round(rng.w)) << "x" << int(round(rng.h))<< "\n"; + iImage img(round(rng.w), round(rng.h)); convs::map2wgs cnv(ref); if (W.size() == 0) cerr << "warning: no objects\n"; GObjVMAP R(&W, O); R.set_ref(ref); R.draw(img, dPoint(0,0)); CairoWrapper cr(img); if (O.get<int>("draw_name", 0)) cr->render_text(W.name.c_str(), dPoint(dpi/5,dpi/15), 0, 0, 18, 14, dpi, 0, 2); if (O.get<int>("draw_date", 0)){ Time t; t.set_current(); cr->render_text(t.date_str().c_str(), dPoint(dpi/30,dpi), -M_PI/2, 0, 18, 10, dpi, 2, 2); } if (O.get<string>("draw_text") != ""){ cr->render_text(O.get<string>("draw_text").c_str(), dPoint(dpi/5,rng.h-dpi/30), 0, 0, 18, 10, dpi, 0, 0); } //******************************* image_r::save(img, ofile); string map = O.get<string>("map"); if (map!=""){ g_map M = ref; M.file = ofile; if (W.brd.size()>2) M.border=cnv.line_bck(W.brd); M.border.push_back(*M.border.begin()); M.border=generalize(M.border,1,-1); // 1pt accuracy M.border.resize(M.border.size()-1); try {oe::write_map_file(map.c_str(), M);} catch (Err e) {cerr << e.get_error() << endl;} } //******************************* } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
7f90d93e5c2f9254ce3d8fa689e5341a978f247e
core/geo_io/geo_refs.cpp: fix error in option checks (thanks to ioctl@ya)
diff --git a/core/geo_io/geo_refs.cpp b/core/geo_io/geo_refs.cpp index 06678d4..a6102d3 100644 --- a/core/geo_io/geo_refs.cpp +++ b/core/geo_io/geo_refs.cpp @@ -1,344 +1,344 @@ // Привязки специальных карт и снимков #include "tiles/tiles.h" #include "geo_refs.h" #include "geo/geo_convs.h" #include "geo/geo_nom.h" #include "2d/line_utils.h" #include "err/err.h" #include <sstream> #include <iomanip> using namespace std; g_map mk_tmerc_ref(const dLine & points, double u_per_m, bool yswap){ g_map ref; if (points.size()<3){ cerr << "error in mk_tmerc_ref: number of points < 3\n"; return g_map(); } // Get refs. // Reduce border to 5 points, remove last one. dLine refs = points; refs.push_back(*refs.begin()); // to assure last=first refs = generalize(refs, -1, 5); refs.resize(4); // Create tmerc->lonlat tmerc conversion with wanted lon0, // convert refs to our map coordinates. Options PrO; PrO.put<double>("lon0", convs::lon2lon0(points.center().x)); convs::pt2wgs cnv(Datum("wgs84"), Proj("tmerc"), PrO); dLine refs_c(refs); cnv.line_bck_p2p(refs_c); refs_c *= u_per_m; // to out units refs_c -= refs_c.range().TLC(); double h = refs_c.range().h; // swap y if needed if (yswap){ for (int i=0;i<refs_c.size();i++) refs_c[i].y = h - refs_c[i].y; } // add refpoints to our map for (int i=0;i<refs.size();i++){ ref.push_back(g_refpoint(refs[i], refs_c[i])); } ref.map_proj=Proj("tmerc"); ref.proj_opts.put("lon0", convs::lon2lon0(refs.range().CNT().x)); // Now we need to convert border to map units. // We can convert them by the same way as refs, but // this is unnecessary duplicating of non-trivial code. // So we constract map2pt conversion from our map. // Set map border convs::map2wgs brd_cnv(ref); ref.border = brd_cnv.line_bck(points); ref.border.push_back(*ref.border.begin()); // to assure last=first ref.border = generalize(ref.border, 1000, -1); // 1 unit accuracy ref.border.resize(ref.border.size()-1); return ref; } void incompat_warning(const Options & o, const string & o1, const string & o2){ if (o.exists(o2)) cerr << "make reference warning: " << "skipping option --" << o2 << "\n" <<" which is incompatable with --" << o1 << "\n"; } vector<int> read_int_vec(const string & str){ istringstream s(str); char sep; int x; vector<int> ret; while (1){ s >> ws >> x; if (!s.fail()){ ret.push_back(x); s >> ws; } if (s.eof()) return ret; s >> ws >> sep; if (sep!=','){ cerr << "error while reading comma separated values\n"; return ret; } } } g_map mk_ref(Options & o){ g_map ret; // default values double dpi=300; double google_dpi=-1; double rscale=100000; double rs_factor=1.0; // proj units/m Datum datum("wgs84"); Proj proj("tmerc"); bool verbose=o.exists("verbose"); bool sw=!o.exists("swap_y"); // first step: process geom, nom, google options // -- create border and 4 refpoints in wgs84 lonlat // -- set map_proj and proj options // -- change defauld dpi and rscale if needed dRect geom; dLine refs; Options proj_opts; // rectangular map if (o.exists("geom")){ incompat_warning (o, "geom", "wgs_geom"); incompat_warning (o, "geom", "wgs_brd"); incompat_warning (o, "geom", "trk_brd"); incompat_warning (o, "geom", "nom"); incompat_warning (o, "geom", "google");\ dRect geom = o.get<dRect>("geom"); if (geom.empty()) throw Err() << "error: bad geometry"; datum = o.get<Datum>("datum", Datum("pulkovo")); proj = o.get<Proj>("proj", Proj("tmerc")); if ((proj == Proj("tmerc")) && (geom.x>=1e6)){ double lon0 = convs::lon_pref2lon0(geom.x); geom.x = convs::lon_delprefix(geom.x); proj_opts.put<double>("lon0", lon0); } if (o.exists("lon0")) proj_opts.put("lon0", o.get<double>("lon0")); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), datum, proj, proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); ret.border = cnv.line_bck(refs, 1e-6); refs.resize(4); cnv.line_bck_p2p(refs); } else if (o.exists("wgs_geom")){ incompat_warning (o, "wgs_geom", "geom"); incompat_warning (o, "wgs_geom", "wgs_brd"); incompat_warning (o, "wgs_geom", "trk_brd"); incompat_warning (o, "wgs_geom", "nom"); incompat_warning (o, "wgs_geom", "google");\ dRect geom = o.get<dRect>("wgs_geom"); if (geom.empty()) throw Err() << "error: bad geometry"; proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(geom.x+geom.w/2))); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), Datum("wgs84"), proj, proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); refs.resize(4); // border is set to be rectanglar in proj: ret.border = cnv.line_bck(rect2line(cnv.bb_frw(geom, 1e-6), true, sw), 1e-6); } else if (o.exists("wgs_brd")){ incompat_warning (o, "wgs_brd", "geom"); incompat_warning (o, "wgs_brd", "wgs_geom"); incompat_warning (o, "wgs_brd", "trk_brd"); incompat_warning (o, "wgs_brd", "nom"); incompat_warning (o, "wgs_brd", "google");\ ret.border = o.get<dLine>("wgs_brd"); if (ret.border.size()<3) throw Err() << "error: bad border line"; ret.border.push_back(ret.border[0]); proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(ret.border.range().CNT().x))); if (verbose) cerr << "mk_ref: brd = " << ret.border << "\n"; refs = generalize(ret.border, -1, 5); // 5pt refs.resize(4); } else if (o.exists("trk_brd")){ - incompat_warning (o, "wgs_brd", "geom"); - incompat_warning (o, "wgs_brd", "wgs_geom"); - incompat_warning (o, "wgs_brd", "wgs_brd"); - incompat_warning (o, "wgs_brd", "nom"); - incompat_warning (o, "wgs_brd", "google");\ + incompat_warning (o, "trk_brd", "geom"); + incompat_warning (o, "trk_brd", "wgs_geom"); + incompat_warning (o, "trk_brd", "wgs_brd"); + incompat_warning (o, "trk_brd", "nom"); + incompat_warning (o, "trk_brd", "google");\ geo_data W; io::in(o.get<string>("trk_brd"), W); if (W.trks.size()<1) throw Err() << "error: file with a track is expected in trk_brd option"; ret.border = W.trks[0]; if (ret.border.size()<3) throw Err() << "error: bad border line"; ret.border.push_back(ret.border[0]); proj = o.get<Proj>("proj", Proj("tmerc")); proj_opts.put<double>("lon0", o.get("lon0", convs::lon2lon0(ret.border.range().CNT().x))); if (verbose) cerr << "mk_ref: brd = " << ret.border << "\n"; refs = generalize(ret.border, -1, 5); // 5pt refs.resize(4); } // nom map else if (o.exists("nom")){ incompat_warning (o, "nom", "geom"); incompat_warning (o, "nom", "wgs_geom"); incompat_warning (o, "nom", "wgs_brd"); incompat_warning (o, "nom", "trk_brd"); incompat_warning (o, "nom", "google"); proj=Proj("tmerc"); datum=Datum("pulkovo"); int rs; string name=o.get<string>("nom", string()); dRect geom = convs::nom_to_range(name, rs); if (geom.empty()) throw Err() << "error: can't get geometry for map name \"" << name << "\""; rscale = rs; double lon0 = convs::lon2lon0(geom.x+geom.w/2.0); proj_opts.put("lon0", lon0); convs::pt2pt cnv(Datum("wgs84"), Proj("lonlat"), Options(), datum, Proj("lonlat"), proj_opts); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true, sw); ret.border = cnv.line_bck(refs, 1e-6); refs.resize(4); cnv.line_bck_p2p(refs); } // google tile else if (o.exists("google")){ incompat_warning (o, "google", "geom"); incompat_warning (o, "google", "wgs_geom"); incompat_warning (o, "google", "wgs_brd"); incompat_warning (o, "google", "trk_brd"); incompat_warning (o, "google", "nom"); datum=Datum("wgs84"); proj=Proj("google"); vector<int> crd = read_int_vec(o.get<string>("google")); if (crd.size()!=3) throw Err() << "error: wrong --google coordinates"; int x=crd[0]; int y=crd[1]; int z=crd[2]; // Tiles tcalc; dRect geom = tcalc.gtile_to_range(x,y,z); if (verbose) cerr << "mk_ref: geom = " << geom << "\n"; refs = rect2line(geom, true,sw); ret.border = refs; refs.resize(4); rscale=o.get<double>("rscale", rscale); double lat=refs.range().CNT().y; rs_factor = 1/cos(M_PI*lat/180.0); // m -> tile pixel double k = 1/tcalc.px2m(z); dpi = k * 2.54/100.0*rscale*rs_factor; } else throw Err() << "error: can't make map reference without" << " --geom or --nom or --google setting"; ret.map_proj=proj; ret.map_datum=datum; ret.proj_opts=proj_opts; // step 2: calculate conversion coeff between map proj units and // output map points rscale=o.get<double>("rscale", rscale); if (o.get<string>("dpi", "") == "fig") dpi= 1200/1.05; else dpi=o.get<double>("dpi", dpi); dpi*=o.get<double>("mag", 1.0); // put real dpi and rscale back to options o.put("dpi", dpi); o.put("rscale", rscale); double k = 100.0/2.54 * dpi / rscale / rs_factor; if (verbose) cerr << "mk_ref: rscale = " << rscale << ", dpi = " << dpi << ", k = " << k << "\n"; // step 3: setting refpoints convs::pt2wgs cnv(datum, proj, proj_opts); dLine refs_r(refs); cnv.line_bck_p2p(refs_r); refs_r *= k; // to out units refs_r -= refs_r.range().TLC(); double h = refs_r.range().h; // swap y if needed if (sw) for (int i=0;i<refs_r.size();i++) refs_r[i].y = h - refs_r[i].y; // add refpoints to our map for (int i=0;i<refs.size();i++) ret.push_back(g_refpoint(refs[i], refs_r[i])); // step 3: converting border convs::map2wgs brd_cnv(ret); ret.border = brd_cnv.line_bck(ret.border); ret.border = generalize(ret.border, 1, -1); // 1 unit accuracy ret.border.resize(ret.border.size()-1); return ret; }
ushakov/mapsoft
7fc8f3fddcaea4058919ddba761cf62b9b22e75b
20191110-alt1
diff --git a/mapsoft.spec b/mapsoft.spec index 4708139..0dd4234 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,180 +1,183 @@ Name: mapsoft -Version: 20190916 -Release: alt2 +Version: 20191110 +Release: alt1 License: GPL Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %_bindir/map_rescale %_bindir/*.sh %_bindir/map_*_gk %_bindir/map_*_nom %changelog +* Sun Nov 10 2019 Vladislav Zavjalov <[email protected]> 20191110-alt1 +- add more scripts to mapsoft_vmap package + * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
20e2c14e478ba6c26bbae326de69719f163f0f3e
install scripts; add scripts to mapsoft_vmap package
diff --git a/mapsoft.spec b/mapsoft.spec index 8028a5f..4708139 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,176 +1,180 @@ Name: mapsoft Version: 20190916 Release: alt2 License: GPL Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* +%_bindir/map_rescale +%_bindir/*.sh +%_bindir/map_*_gk +%_bindir/map_*_nom %changelog * Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 - fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux diff --git a/scripts/SConscript b/scripts/SConscript index afcd721..19cae92 100644 --- a/scripts/SConscript +++ b/scripts/SConscript @@ -1,4 +1,24 @@ Import ('env') +# Making map reference in GIMP env.Install(env.libdir + '/gimp/2.0/plug-ins', 'map-helper.py') + +env.Install(env.bindir, 'map_rescale') + +env.Install(env.bindir, 'mapsoft_crd.sh') + +# Updating glaciers from GLIMS catalog +env.Install(env.bindir, 'mapsoft_gl.sh') +env.Install(env.bindir, 'map_gl_upd_gk') +env.Install(env.bindir, 'map_gl_upd_nom') + +# Updating mountain passes from Westra catalog +env.Install(env.bindir, 'mapsoft_wp.sh') +env.Install(env.bindir, 'map_wp_upd_gk') +env.Install(env.bindir, 'map_wp_upd_nom') +env.Install(env.bindir, 'mapsoft_wp_parse') + +# Downloading Wikimapia data +env.Install(env.bindir, 'mapsoft_wm.sh') +env.Install(env.bindir, 'map_wm_nom')
ushakov/mapsoft
8efde2a0f3617219e645f14dfcf7cca9f8e0d30a
scripts: add comments
diff --git a/scripts/map_gl_upd_gk b/scripts/map_gl_upd_gk index b30a40a..628c71c 100755 --- a/scripts/map_gl_upd_gk +++ b/scripts/map_gl_upd_gk @@ -1,29 +1,29 @@ #!/bin/sh -efux . mapsoft_gl.sh . mapsoft_map.sh -# map_gl_gk_update -- update glaciers in rectangular maps +# map_gl_gk_update -- update glaciers in rectangular maps. # example: map_gl_gk_update elbr.fig pamir.vmap +# Data are put into ./glims/ dir. -# Geometry information is read from maps.txt file: -# <base name> <geometry> <title> -# data is put into ./glims/ dir +# Requires map.txt file with map description (see mapsoft_map.sh). +# At the moment I do not use this script. mkdir -p -- glims for i in "$@"; do base=$(basename ${i%.*}) echo $i geom="$(map_data geom "$base")" cp -f -- "$i" "$i.bak" download_gk_gl "$geom" "glims/$base" mapsoft_vmap -v \ glims/${base}_gl.mp --set_source glims\ --range_datum pulkovo --range_proj tmerc\ --range "$geom" --range_action="select"\ "$i" --split_labels --skip_source glims\ -o "$i" done diff --git a/scripts/map_gl_upd_nom b/scripts/map_gl_upd_nom index 4f78647..cff15b3 100755 --- a/scripts/map_gl_upd_nom +++ b/scripts/map_gl_upd_nom @@ -1,27 +1,26 @@ #!/bin/sh -efu . mapsoft_gl.sh -# map_gl_upd_nom -- update glaciers in nom maps +# map_gl_upd_nom -- update glaciers in nom maps. # example: map_gl_upd_nom j43-061.vmap j43-062.vmap - -# passes data is put into ./glims/ dir +# Data are put into ./glims/ dir. mkdir -p -- glims for i in "$@"; do base=$(basename ${i%.*}) echo $i download_ll_gl "$(nom2ll "$base")" "glims/$base" cp -f -- "$i" "$i.bak" mapsoft_vmap -v \ glims/${base}_gl.mp --set_source glims\ --range_nom "$base" --range_action="select"\ "$i" --split_labels --skip_source glims\ -o "$i" # rm -f -- "glims/${base}_gl.mp" done diff --git a/scripts/map_init_gk b/scripts/map_init_gk index 9665bdc..1a6d532 100755 --- a/scripts/map_init_gk +++ b/scripts/map_init_gk @@ -1,26 +1,30 @@ #!/bin/sh -efu +# Make empty rectangular map in Soviet projection. +# Requires map.txt file with map description (see mapsoft_map.sh). +# At the moment I do not use this script. + [ "$#" = 3 ] || { echo "usage: $0 <map name> <style> <rscale>" echo " map_name: name.vmap, name.fig ... (maps.txt file is needed)" echo " style: hr, mmb" echo " rscale: 50000, 100000 ..." exit 1 } name="$1" style="$2" rscale="$3" base=$(basename ${name%.*}) . mapsoft_map.sh geom="$(map_data geom "$base")" title="$(map_data title "$base")" mapsoft_vmap \ -o "$name"\ --name "$title" --rscale "$rscale" --style "$style"\ --range "$geom" --range_datum "pulkovo" --range_proj "tmerc"\ --set_brd_from_range diff --git a/scripts/map_init_nom b/scripts/map_init_nom index 014841f..a6dcf26 100755 --- a/scripts/map_init_nom +++ b/scripts/map_init_nom @@ -1,21 +1,23 @@ #!/bin/sh -efu +# Make empty Soviet nomenclature map + [ "$#" = 3 ] || { echo "usage: $0 <map name> <style> <rscale>" echo " map_name: j43-061.vmap, j44-001-1.fig ..." echo " style: hr, mmb" echo " rscale: 50000, 100000 ..." exit 1 } name="$1" style="$2" rscale="$3" base=$(basename ${name%.*}) mapsoft_vmap \ -o "$name"\ --name "$base" --rscale "$rscale" --style "$style"\ --range_nom "$base" --set_brd_from_range diff --git a/scripts/map_wm_nom b/scripts/map_wm_nom index 58399ea..02723af 100755 --- a/scripts/map_wm_nom +++ b/scripts/map_wm_nom @@ -1,12 +1,11 @@ #!/bin/sh -efu . mapsoft_wm.sh -. mapsoft_map.sh # map_wp_upd_gk -- get wikimapia data for nom map # example: map_wm_nom h45-110 ... for i in "$@"; do echo $i download_ll_wm "$(nom2ll "$i")" "$i" done diff --git a/scripts/map_wp_upd_gk b/scripts/map_wp_upd_gk index aa6b2e8..847619a 100755 --- a/scripts/map_wp_upd_gk +++ b/scripts/map_wp_upd_gk @@ -1,29 +1,29 @@ #!/bin/sh -efu . mapsoft_wp.sh . mapsoft_map.sh -# map_wp_upd_gk -- update passes in rectangular maps +# map_wp_upd_gk -- update passes in rectangular maps. # example: map_wp_upd_gk elbr.fig pamir.vmap +# Passes data are put into ./wpasses/ dir. -# Geometry information is read from maps.txt file: -# <base name> <geometry> <title> -# passes data is put into ./wpasses/ dir +# Requires map.txt file with map description (see mapsoft_map.sh). +# At the moment I do not use this script. mkdir -p -- wpasses for i in "$@"; do base=$(basename ${i%.*}) echo $i geom="$(map_data geom "$base")" cp -f -- "$i" "$i.bak" download_gk_wp "$geom" "wpasses/$base" mapsoft_vmap -v \ wpasses/${base}_wp.mp --set_source westra_passes\ --range_datum pulkovo --range_proj tmerc\ --range "$geom" --range_action="select"\ "$i" --split_labels --skip_source westra_passes\ -o "$i" done diff --git a/scripts/mapsoft_map.sh b/scripts/mapsoft_map.sh index 9f9317f..cf309e1 100644 --- a/scripts/mapsoft_map.sh +++ b/scripts/mapsoft_map.sh @@ -1,41 +1,45 @@ -## shell functions for reading map data +# Some data about maps are stored in maps.txt file: +# <name> <geometry> <title> +# Geometry describes a rectangular area in Soviet map coordinates. +# Using map_data() func one can get map geometry and title by its name. +# I do not use this library at the moment MAPSOFT_MAP=1 datafile="maps.txt" get_line(){ ## get line from datafile, ## remove duplicated spaces (for cut program) base="$1" file="$2" sed -n "/^[[:space:]]*$base[[:space:]]/{s/[[:space:]]\+/ /g; p}" "$2" } # Geometry or title information is read from maps.txt file: # <base name> <geometry> <title> map_data(){ field="$1" # geom | title base="$2" if [ ! -f "$datafile" ]; then echo "ERROR: can't find $datafile file" > /dev/stderr exit 1 fi dat="$(get_line "$base" "maps.txt")" if [ -z "$dat" ]; then echo "ERROR: can't find map in $datafile: $base" > /dev/stderr exit 1 fi if [ "$field" = "geom" ]; then printf "%s\n" "$dat" | cut -d ' ' -f 2 elif [ "$field" = "title" ]; then printf "%s\n" "$dat" | cut -d ' ' -f 3- else echo "ERROR: unknown field: $field" > /dev/stderr exit 1 fi } diff --git a/scripts/mapsoft_wp.sh b/scripts/mapsoft_wp.sh index 2c3cbdf..4da4b28 100644 --- a/scripts/mapsoft_wp.sh +++ b/scripts/mapsoft_wp.sh @@ -1,43 +1,44 @@ ## Shell funcs for westra passes downloading. ## Uses official kml interface of the Westra catalog. MAPSOFT_WP1=1 [ -n "${MAPSOFT_CRD:-}" ] || . mapsoft_crd.sh # get url for downloading data from westra passes catalog # usage: ll2wp <wgs lonlat geom> ll2wp(){ local geom="$1" echo "$geom" | sed 's/\(^[0-9\.]\+\)x\([0-9\.]\+\)\([\+-][0-9\.]\+\)\([\+-][0-9\.]\+\)/\1 \2 \3 \4/' | { local x1 x2 y1 y2 dx dy read dx dy x1 y1 x2="$(printf -- "${x1#+} + $dx\n" | bc -l)" y2="$(printf -- "${y1#+} + $dy\n" | bc -l)" printf "http://westra.ru/passes/kml/passes.php?BBOX=%f,%f,%f,%f" $x1 $y1 $x2 $y2 } } -# download kml file for a given wgs latlon range -# remove old-style comments +# Download kml file for a given wgs latlon range. +# Convert kml to mp and txt form. download_ll_wp(){ local geom="$1" local name="$2" wget "$(ll2wp "$geom")" -O - > "${name}_wp.kml" mapsoft_wp_parse "${name}_wp.kml" } -# download kml file for a given pulkovo tmerc range +# Download kml file for a given pulkovo tmerc range. +# Convert kml to mp and txt form. download_gk_wp(){ local geom="$1" local name="$2" ll="$(geom2ll "$geom")" download_ll_wp "$ll" "$name" }
ushakov/mapsoft
725b130dc7e1857cc3b9e6e56a574840901dd86e
scripts: move obsolete mapsoft_wp library to obsolete/ folder. Add comments.
diff --git a/scripts/map_wp_upd_gk b/scripts/map_wp_upd_gk index 5a42308..aa6b2e8 100755 --- a/scripts/map_wp_upd_gk +++ b/scripts/map_wp_upd_gk @@ -1,29 +1,29 @@ #!/bin/sh -efu -. mapsoft_wp1.sh +. mapsoft_wp.sh . mapsoft_map.sh # map_wp_upd_gk -- update passes in rectangular maps # example: map_wp_upd_gk elbr.fig pamir.vmap # Geometry information is read from maps.txt file: # <base name> <geometry> <title> # passes data is put into ./wpasses/ dir mkdir -p -- wpasses for i in "$@"; do base=$(basename ${i%.*}) echo $i geom="$(map_data geom "$base")" cp -f -- "$i" "$i.bak" download_gk_wp "$geom" "wpasses/$base" mapsoft_vmap -v \ wpasses/${base}_wp.mp --set_source westra_passes\ --range_datum pulkovo --range_proj tmerc\ --range "$geom" --range_action="select"\ "$i" --split_labels --skip_source westra_passes\ -o "$i" done diff --git a/scripts/map_wp_upd_nom b/scripts/map_wp_upd_nom index cac0217..85b2d25 100755 --- a/scripts/map_wp_upd_nom +++ b/scripts/map_wp_upd_nom @@ -1,31 +1,31 @@ #!/bin/sh -efu -. mapsoft_wp1.sh +. mapsoft_wp.sh # map_wp_upd_nom -- update passes in nom maps # example: map_wp_upd_nom j43-061.vmap j43-062.vmap # passes data is put into ./wpasses/ dir mkdir -p -- wpasses for i in "$@"; do base=$(basename ${i%.*}) echo $i download_ll_wp "$(nom2ll "$base")" "wpasses/$base" cp -f -- "$i" "$i.bak" mapsoft_vmap -v \ wpasses/${base}_wp.mp --set_source westra_passes\ --range_nom "$base" --range_action="select"\ "$i" --split_labels --skip_source westra_passes\ -o "$i" if [ -f "wpasses/${base}_wp.sed" ]; then sed -i --file "wpasses/${base}_wp.sed" "$i" fi rm -f -- "wpasses/${base}_wp.mp" done diff --git a/scripts/mapsoft_wp.sh b/scripts/mapsoft_wp.sh index 3616847..2c3cbdf 100644 --- a/scripts/mapsoft_wp.sh +++ b/scripts/mapsoft_wp.sh @@ -1,50 +1,43 @@ -## shell functions for westra passes downloading +## Shell funcs for westra passes downloading. +## Uses official kml interface of the Westra catalog. -MAPSOFT_WP=1 +MAPSOFT_WP1=1 [ -n "${MAPSOFT_CRD:-}" ] || . mapsoft_crd.sh # get url for downloading data from westra passes catalog -# usage: geom2wp <wgs lonlat geom> (mp|txt|wpt) +# usage: ll2wp <wgs lonlat geom> ll2wp(){ local geom="$1" - local fmt="${2:-mp}" echo "$geom" | sed 's/\(^[0-9\.]\+\)x\([0-9\.]\+\)\([\+-][0-9\.]\+\)\([\+-][0-9\.]\+\)/\1 \2 \3 \4/' | { local x1 x2 y1 y2 dx dy read dx dy x1 y1 x2="$(printf -- "${x1#+} + $dx\n" | bc -l)" y2="$(printf -- "${y1#+} + $dy\n" | bc -l)" - printf "http://www.westra.ru/cgi-bin/show_pass.pl?lat1=%f&lat2=%f&lon1=%f&lon2=%f&searchbtn=1&fmt=$fmt"\ - $y1 $y2 $x1 $x2 + printf "http://westra.ru/passes/kml/passes.php?BBOX=%f,%f,%f,%f" $x1 $y1 $x2 $y2 } } -# download mp, wpt, txt files for a given wgs latlon range +# download kml file for a given wgs latlon range # remove old-style comments download_ll_wp(){ local geom="$1" local name="$2" - date="$(date +"%F %T")" - wget "$(ll2wp "$geom")" -O - | - sed "/^;[[:space:]]*\([0-9]\+@westra_passes\)/d; - s/&quot;/\"/g" > "${name}_wp.mp" - wget "$(ll2wp "$geom" txt)" -O - | - iconv -f utf-8 -c | sort -k1,1 -n > "${name}_wp.txt" - wget "$(ll2wp "$geom" wpt)" -O - > "${name}_wp.wpt" + wget "$(ll2wp "$geom")" -O - > "${name}_wp.kml" + mapsoft_wp_parse "${name}_wp.kml" } -# download mp, wpt, txt files for a given pulkovo tmerc range -# fix old style comments, add Source=westra_passes +# download kml file for a given pulkovo tmerc range download_gk_wp(){ local geom="$1" local name="$2" ll="$(geom2ll "$geom")" download_ll_wp "$ll" "$name" } diff --git a/scripts/mapsoft_wp1.sh b/scripts/obsolete/mapsoft_wp.sh similarity index 66% rename from scripts/mapsoft_wp1.sh rename to scripts/obsolete/mapsoft_wp.sh index db9e2f4..3616847 100644 --- a/scripts/mapsoft_wp1.sh +++ b/scripts/obsolete/mapsoft_wp.sh @@ -1,45 +1,50 @@ ## shell functions for westra passes downloading -## official kml interface -MAPSOFT_WP1=1 +MAPSOFT_WP=1 [ -n "${MAPSOFT_CRD:-}" ] || . mapsoft_crd.sh # get url for downloading data from westra passes catalog # usage: geom2wp <wgs lonlat geom> (mp|txt|wpt) ll2wp(){ local geom="$1" + local fmt="${2:-mp}" echo "$geom" | sed 's/\(^[0-9\.]\+\)x\([0-9\.]\+\)\([\+-][0-9\.]\+\)\([\+-][0-9\.]\+\)/\1 \2 \3 \4/' | { local x1 x2 y1 y2 dx dy read dx dy x1 y1 x2="$(printf -- "${x1#+} + $dx\n" | bc -l)" y2="$(printf -- "${y1#+} + $dy\n" | bc -l)" - printf "http://westra.ru/passes/kml/passes.php?BBOX=%f,%f,%f,%f" $x1 $y1 $x2 $y2 + printf "http://www.westra.ru/cgi-bin/show_pass.pl?lat1=%f&lat2=%f&lon1=%f&lon2=%f&searchbtn=1&fmt=$fmt"\ + $y1 $y2 $x1 $x2 } } # download mp, wpt, txt files for a given wgs latlon range # remove old-style comments download_ll_wp(){ local geom="$1" local name="$2" date="$(date +"%F %T")" - wget "$(ll2wp "$geom")" -O - > "${name}_wp.kml" - mapsoft_wp_parse "${name}_wp.kml" + wget "$(ll2wp "$geom")" -O - | + sed "/^;[[:space:]]*\([0-9]\+@westra_passes\)/d; + s/&quot;/\"/g" > "${name}_wp.mp" + wget "$(ll2wp "$geom" txt)" -O - | + iconv -f utf-8 -c | sort -k1,1 -n > "${name}_wp.txt" + wget "$(ll2wp "$geom" wpt)" -O - > "${name}_wp.wpt" } # download mp, wpt, txt files for a given pulkovo tmerc range # fix old style comments, add Source=westra_passes download_gk_wp(){ local geom="$1" local name="$2" ll="$(geom2ll "$geom")" download_ll_wp "$ll" "$name" }
ushakov/mapsoft
ed2a737de12f9056214799713ad7f7854c16e2ec
add Readme.md (EN) (closes #3)
diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..411f095 --- /dev/null +++ b/Readme.md @@ -0,0 +1,27 @@ +## Mapsoft + +Mapsoft is a set of libraries and tools for working with geodata, raster +and vector maps etc. It was is not too accurate, but it was used for +many our projects including making vector maps for Moscow region ( +https://nakarte.me/#m=7/55.61249/37.65564&l=O/Z ) and some mountain +regions ( https://nakarte.me/#m=2/20.13847/57.48047&l=O/Q ). + +Git repositary: https://github.com/ushakov/mapsoft + +At the moment the project is not developing. I'm trying to rewrite it +fixing some fundamental problems and improving the code ( +https://github.com/slazav/mapsoft2 ), but this work is far from its end. + +Main mapsoft programs (man-pages are available): + +- mapsoft_convert: Geodata and raster map converter. + Supports a few formats: OziExplorer, GPX, GeoJSON, GarminUtils, KML, custom + XML-like format. Supports SRTM data. Supports geo-referenced extension for + xfig file format. + +- mapsoft_mapview: viewer/editor for geodata, raster maps, SRTM data. + +- mapsoft_vmap: vector map converter. Supports MP vector map format, + geo-referenced extension for xfig file format, custom VMAP format. + +- vmap_render: vector map rendering.
ushakov/mapsoft
49f945b22fe2e944326f9e0b026816ca859db125
fix PKG_CONFIG_PATH setting in SConstruct (thanks to suntar@github)
diff --git a/SConstruct b/SConstruct index 88a90cd..ddcf739 100644 --- a/SConstruct +++ b/SConstruct @@ -1,102 +1,102 @@ ###################################### # What do we want to build subdirs_min = Split("core programs viewer vector man scripts") subdirs_max = subdirs_min + Split("tests misc") ###################################### ## import python libraries import os import platform if platform.python_version()<"2.7": import distutils.sysconfig as sysconfig else: import sysconfig ###################################### # Create environment, add some methods env = Environment () Export('env') # UseLibs -- use pkg-config libraries def UseLibs(env, libs): if isinstance(libs, list): libs = " ".join(libs) env.ParseConfig('pkg-config --cflags --libs %s' % libs) env.AddMethod(UseLibs) # SymLink -- create a symlink # Arguments target and linkname follow standard order (look at ln(1)) # wd is optional base directory for both def SymLink(env, target, linkname, wd=None): if wd: env.Command(wd+'/'+linkname, wd+'/'+target, "ln -s -- %s %s/%s" % (target, wd, linkname)) else: env.Command(linkname, target, "ln -s -- %s %s" % (target, linkname)) env.AddMethod(SymLink) ###################################### ## Add default flags if 'GCCVER' in os.environ: ver = os.environ['GCCVER'] env.Replace (CC = ("gcc-%s" % ver)) env.Replace (CXX = ("g++-%s" % ver)) env.Append (CCFLAGS=['-DACCEPT_USE_OF_DEPRECATED_PROJ_API_H=1']) env.Append (CCFLAGS=['-Werror=return-type']) env.Append (CCFLAGS=['-O2']) env.Append (CCFLAGS='-std=gnu++11') env.Append (ENV = {'PKG_CONFIG_PATH': os.getcwd()+'/core/pc'}) if os.getenv('PKG_CONFIG_PATH'): - env_loc.Append (ENV = {'PKG_CONFIG_PATH': + env.Append (ENV = {'PKG_CONFIG_PATH': [ os.getcwd()+'/core/pc', os.getenv('PKG_CONFIG_PATH')]}) env.Append (CPPPATH = "#core") env.Append (LIBPATH = "#core") env.Append (LIBS = "mapsoft") ###################################### ## Parse command-line arguments: env.PREFIX = ARGUMENTS.get('prefix', '') env.bindir=env.PREFIX+'/usr/bin' env.datadir=env.PREFIX+'/usr/share/mapsoft' env.man1dir=env.PREFIX+'/usr/share/man/man1' env.figlibdir=env.PREFIX+'/usr/share/xfig/Libraries' env.libdir=env.PREFIX+ sysconfig.get_config_var('LIBDIR') env.desktopdir=env.PREFIX+'/usr/share/applications' env.Alias('install', [env.bindir, env.man1dir, env.datadir, env.figlibdir, env.libdir, env.desktopdir]) if ARGUMENTS.get('debug', 0): env.Append (CCFLAGS='-ggdb') env.Append (LINKFLAGS='-ggdb') if ARGUMENTS.get('profile', 0): env.Append (CCFLAGS='-pg') env.Append (LINKFLAGS='-pg') if ARGUMENTS.get('gprofile', 0): env.Append (LINKFLAGS='-lprofiler') if ARGUMENTS.get('gheapcheck', 0): env.Append (LINKFLAGS='-ltcmalloc') if ARGUMENTS.get('minimal', 0): SConscript(list(map(lambda s: s + "/SConscript", subdirs_min))) else: SConscript(list(map(lambda s: s + "/SConscript", subdirs_max))) Help(""" You can build mapsoft with the following options: scons -Q debug=1 // build with -ggdb scons -Q profile=1 // build with -pg scons -Q gheapcheck=1 // build with -ltcmalloc scons -Q minimal=1 // skip misc and tests dirs scons -Q prefix=<prefix> // set installation prefix """) # vim: ft=python tw=0
ushakov/mapsoft
6e9d17931ea2512cba1e218daf8a3d77bcfc4be0
20190916-alt2
diff --git a/SConstruct b/SConstruct index 192a83f..88a90cd 100644 --- a/SConstruct +++ b/SConstruct @@ -1,101 +1,102 @@ ###################################### # What do we want to build subdirs_min = Split("core programs viewer vector man scripts") subdirs_max = subdirs_min + Split("tests misc") ###################################### ## import python libraries import os import platform if platform.python_version()<"2.7": import distutils.sysconfig as sysconfig else: import sysconfig ###################################### # Create environment, add some methods env = Environment () Export('env') # UseLibs -- use pkg-config libraries def UseLibs(env, libs): if isinstance(libs, list): libs = " ".join(libs) env.ParseConfig('pkg-config --cflags --libs %s' % libs) env.AddMethod(UseLibs) # SymLink -- create a symlink # Arguments target and linkname follow standard order (look at ln(1)) # wd is optional base directory for both def SymLink(env, target, linkname, wd=None): if wd: env.Command(wd+'/'+linkname, wd+'/'+target, "ln -s -- %s %s/%s" % (target, wd, linkname)) else: env.Command(linkname, target, "ln -s -- %s %s" % (target, linkname)) env.AddMethod(SymLink) ###################################### ## Add default flags if 'GCCVER' in os.environ: ver = os.environ['GCCVER'] env.Replace (CC = ("gcc-%s" % ver)) env.Replace (CXX = ("g++-%s" % ver)) +env.Append (CCFLAGS=['-DACCEPT_USE_OF_DEPRECATED_PROJ_API_H=1']) env.Append (CCFLAGS=['-Werror=return-type']) env.Append (CCFLAGS=['-O2']) env.Append (CCFLAGS='-std=gnu++11') env.Append (ENV = {'PKG_CONFIG_PATH': os.getcwd()+'/core/pc'}) if os.getenv('PKG_CONFIG_PATH'): env_loc.Append (ENV = {'PKG_CONFIG_PATH': [ os.getcwd()+'/core/pc', os.getenv('PKG_CONFIG_PATH')]}) env.Append (CPPPATH = "#core") env.Append (LIBPATH = "#core") env.Append (LIBS = "mapsoft") ###################################### ## Parse command-line arguments: env.PREFIX = ARGUMENTS.get('prefix', '') env.bindir=env.PREFIX+'/usr/bin' env.datadir=env.PREFIX+'/usr/share/mapsoft' env.man1dir=env.PREFIX+'/usr/share/man/man1' env.figlibdir=env.PREFIX+'/usr/share/xfig/Libraries' env.libdir=env.PREFIX+ sysconfig.get_config_var('LIBDIR') env.desktopdir=env.PREFIX+'/usr/share/applications' env.Alias('install', [env.bindir, env.man1dir, env.datadir, env.figlibdir, env.libdir, env.desktopdir]) if ARGUMENTS.get('debug', 0): env.Append (CCFLAGS='-ggdb') env.Append (LINKFLAGS='-ggdb') if ARGUMENTS.get('profile', 0): env.Append (CCFLAGS='-pg') env.Append (LINKFLAGS='-pg') if ARGUMENTS.get('gprofile', 0): env.Append (LINKFLAGS='-lprofiler') if ARGUMENTS.get('gheapcheck', 0): env.Append (LINKFLAGS='-ltcmalloc') if ARGUMENTS.get('minimal', 0): SConscript(list(map(lambda s: s + "/SConscript", subdirs_min))) else: SConscript(list(map(lambda s: s + "/SConscript", subdirs_max))) Help(""" You can build mapsoft with the following options: scons -Q debug=1 // build with -ggdb scons -Q profile=1 // build with -pg scons -Q gheapcheck=1 // build with -ltcmalloc scons -Q minimal=1 // skip misc and tests dirs scons -Q prefix=<prefix> // set installation prefix """) # vim: ft=python tw=0 diff --git a/mapsoft.spec b/mapsoft.spec index 8dfbb69..8028a5f 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,173 +1,176 @@ Name: mapsoft Version: 20190916 -Release: alt1 +Release: alt2 License: GPL Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %changelog +* Fri Oct 04 2019 Vladislav Zavjalov <[email protected]> 20190916-alt2 +- fix build with libproj 6.2.0 (use DACCEPT_USE_OF_DEPRECATED_PROJ_API_H) + * Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 - Fix build with new scons/python - mapsoft_geofig: --raw option - mapsoft_mapview: add desktop file - mapsoft_vmap: fix error in label creation introduced in 2018-06-16 * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
7b04752e09ec25048c94cf353ad6b9c955176c95
20190916-alt1
diff --git a/mapsoft.spec b/mapsoft.spec index 6e9ba6b..8dfbb69 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,167 +1,173 @@ Name: mapsoft -Version: 20190213 -Release: alt2 +Version: 20190916 +Release: alt1 License: GPL Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* %_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %changelog +* Mon Sep 16 2019 Vladislav Zavjalov <[email protected]> 20190916-alt1 +- Fix build with new scons/python +- mapsoft_geofig: --raw option +- mapsoft_mapview: add desktop file +- mapsoft_vmap: fix error in label creation introduced in 2018-06-16 + * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux
ushakov/mapsoft
8bf479b4995322f1026dca821e8ac9438a8dced3
mapsoft_mapview: install desktop file
diff --git a/SConstruct b/SConstruct index e3bda78..192a83f 100644 --- a/SConstruct +++ b/SConstruct @@ -1,100 +1,101 @@ ###################################### # What do we want to build subdirs_min = Split("core programs viewer vector man scripts") subdirs_max = subdirs_min + Split("tests misc") ###################################### ## import python libraries import os import platform if platform.python_version()<"2.7": import distutils.sysconfig as sysconfig else: import sysconfig ###################################### # Create environment, add some methods env = Environment () Export('env') # UseLibs -- use pkg-config libraries def UseLibs(env, libs): if isinstance(libs, list): libs = " ".join(libs) env.ParseConfig('pkg-config --cflags --libs %s' % libs) env.AddMethod(UseLibs) # SymLink -- create a symlink # Arguments target and linkname follow standard order (look at ln(1)) # wd is optional base directory for both def SymLink(env, target, linkname, wd=None): if wd: env.Command(wd+'/'+linkname, wd+'/'+target, "ln -s -- %s %s/%s" % (target, wd, linkname)) else: env.Command(linkname, target, "ln -s -- %s %s" % (target, linkname)) env.AddMethod(SymLink) ###################################### ## Add default flags if 'GCCVER' in os.environ: ver = os.environ['GCCVER'] env.Replace (CC = ("gcc-%s" % ver)) env.Replace (CXX = ("g++-%s" % ver)) env.Append (CCFLAGS=['-Werror=return-type']) env.Append (CCFLAGS=['-O2']) env.Append (CCFLAGS='-std=gnu++11') env.Append (ENV = {'PKG_CONFIG_PATH': os.getcwd()+'/core/pc'}) if os.getenv('PKG_CONFIG_PATH'): env_loc.Append (ENV = {'PKG_CONFIG_PATH': [ os.getcwd()+'/core/pc', os.getenv('PKG_CONFIG_PATH')]}) env.Append (CPPPATH = "#core") env.Append (LIBPATH = "#core") env.Append (LIBS = "mapsoft") ###################################### ## Parse command-line arguments: env.PREFIX = ARGUMENTS.get('prefix', '') env.bindir=env.PREFIX+'/usr/bin' env.datadir=env.PREFIX+'/usr/share/mapsoft' env.man1dir=env.PREFIX+'/usr/share/man/man1' env.figlibdir=env.PREFIX+'/usr/share/xfig/Libraries' env.libdir=env.PREFIX+ sysconfig.get_config_var('LIBDIR') +env.desktopdir=env.PREFIX+'/usr/share/applications' env.Alias('install', [env.bindir, env.man1dir, - env.datadir, env.figlibdir, env.libdir]) + env.datadir, env.figlibdir, env.libdir, env.desktopdir]) if ARGUMENTS.get('debug', 0): env.Append (CCFLAGS='-ggdb') env.Append (LINKFLAGS='-ggdb') if ARGUMENTS.get('profile', 0): env.Append (CCFLAGS='-pg') env.Append (LINKFLAGS='-pg') if ARGUMENTS.get('gprofile', 0): env.Append (LINKFLAGS='-lprofiler') if ARGUMENTS.get('gheapcheck', 0): env.Append (LINKFLAGS='-ltcmalloc') if ARGUMENTS.get('minimal', 0): SConscript(list(map(lambda s: s + "/SConscript", subdirs_min))) else: SConscript(list(map(lambda s: s + "/SConscript", subdirs_max))) Help(""" You can build mapsoft with the following options: scons -Q debug=1 // build with -ggdb scons -Q profile=1 // build with -pg scons -Q gheapcheck=1 // build with -ltcmalloc scons -Q minimal=1 // skip misc and tests dirs scons -Q prefix=<prefix> // set installation prefix """) # vim: ft=python tw=0 diff --git a/mapsoft.spec b/mapsoft.spec index 4335412..6e9ba6b 100644 --- a/mapsoft.spec +++ b/mapsoft.spec @@ -1,166 +1,167 @@ Name: mapsoft Version: 20190213 Release: alt2 License: GPL Summary: mapsoft - programs for working with maps and geodata Group: Sciences/Geosciences Url: http://github.org/ushakov/mapsoft Packager: Vladislav Zavjalov <[email protected]> Source: %name-%version.tar BuildRequires: boost-devel gcc-c++ libcurl-devel libzip-devel zlib-devel BuildRequires: libcairomm-devel libpixman-devel libgtkmm2-devel BuildRequires: libpng-devel libjpeg-devel libtiff-devel libgif-devel BuildRequires: libusb-devel libyaml-devel libxml2-devel proj-devel BuildRequires: libjansson-devel libshape-devel BuildRequires: python-devel scons swig m4 BuildRequires: /usr/bin/gs netpbm transfig ImageMagick-tools /usr/bin/pod2man %package tools Summary: mapsoft-tools - rarely-used tools from mapsoft package Group: Sciences/Geosciences Requires: %name = %version-%release %package vmap Summary: mapsoft-vmap - programs for working with vector maps Group: Sciences/Geosciences Requires: %name = %version-%release %description mapsoft - programs for working with maps and geodata %description tools mapsoft-tools - rarely-used tools from mapsoft package %description vmap mapsoft-vmap - programs for working with vector maps %prep %setup -q %build scons -Q minimal=1 %install scons -Q minimal=1 -Q prefix=%buildroot install %files %_bindir/mapsoft_convert %_bindir/mapsoft_mapview %_mandir/man1/mapsoft_convert.* %_mandir/man1/mapsoft_mapview.* +%_desktopdir/mapsoft_mapview.* %files tools %_bindir/convs_* %_bindir/mapsoft_toxyz %_bindir/mapsoft_geofig %_bindir/mapsoft_mkmap %_mandir/man1/mapsoft_geofig.* %_libdir/gimp/2.0/plug-ins/map-helper.py %files vmap %_bindir/mapsoft_vmap %_bindir/vmap_copy %_bindir/vmap_render %dir %_datadir/mapsoft %_datadir/mapsoft/* %_datadir/xfig/Libraries/* %_mandir/man1/mapsoft_vmap.* %changelog * Fri Feb 15 2019 Vladislav Zavjalov <[email protected]> 20190213-alt2 - rebuild with libproj 5.2.0 * Wed Feb 13 2019 Vladislav Zavjalov <[email protected]> 20190213-alt1 - current snapshot * Sun Jul 22 2018 Vladislav Zavjalov <[email protected]> 20180722-alt1 - current snapshot * Wed Feb 03 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1.1 - rebuild with new libproj * Tue Feb 02 2016 Vladislav Zavjalov <[email protected]> 20160202-alt1 - build fix (man page extensions, .gz -> .*) * Mon Oct 19 2015 Anton V. Boyarshinov <[email protected]> 20150103-alt1.2 - build fixed * Fri Jun 12 2015 Gleb F-Malinovskiy <[email protected]> 20150103-alt1.1 - Rebuilt for gcc5 C++11 ABI. * Sat Jan 03 2015 Vladislav Zavjalov <[email protected]> 20150103-alt1 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt2 - current snapshot * Wed Mar 05 2014 Vladislav Zavjalov <[email protected]> 20140305-alt1 - current snapshot * Tue Apr 09 2013 Vladislav Zavjalov <[email protected]> 20130409-alt1 - current snapshot: * Thu Nov 29 2012 Vladislav Zavjalov <[email protected]> 20121129-alt1 - current snapshot - viewer projection change from menu - conic projection support - improve large maps handling - kml read/write support - some fixes * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt2 - one more fix for new gcc * Tue Oct 09 2012 Vladislav Zavjalov <[email protected]> 20121009-alt1 - current snapshot, fix for new gcc * Wed Sep 19 2012 Vladislav Zavjalov <[email protected]> 20120919-alt1 - rebuld with libpng15 - current snapshot: - partial read/write kml support - fix errors in save_image action * Mon Jun 25 2012 Vladislav Zavjalov <[email protected]> 20120625-alt1 - current snapshot - simple navigation mode - support for tiled maps, some examples - faster map rescaling - support for finnish KKJ maps - add map-helper and mapsoft_mkmap to mapsoft-tools package - increase thickness of viewer marks * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120620-alt1 - current snapshot (more bugs fixed) * Wed Jun 20 2012 Vladislav Zavjalov <[email protected]> 20120619-alt1 - build current snapshot (some bugs fixed) * Sun Jun 17 2012 Vladislav Zavjalov <[email protected]> 20120617-alt1 - build current snapshot * Sun May 06 2012 Vladislav Zavjalov <[email protected]> 20120506-alt1 - build current snapshot * Mon Mar 05 2012 Vladislav Zavjalov <[email protected]> 20120304-alt1 - build current snapshot * Thu Feb 16 2012 Vladislav Zavjalov <[email protected]> 20120222-alt1 - build current snapshot (16-02-2012) * Sun Feb 12 2012 Vladislav Zavjalov <[email protected]> 20120221-alt1 - build current snapshot (12-02-2012) * Wed Feb 08 2012 Vladislav Zavjalov <[email protected]> 20120220-alt1 - build current snapshot (08-02-2012) * Tue Jan 10 2012 Vladislav Zavjalov <[email protected]> 20120110-alt1 - build current snapshot * Tue Nov 22 2011 Vladislav Zavjalov <[email protected]> 20111122-alt1 - build current snapshot * Thu Nov 19 2009 Vladislav Zavjalov <[email protected]> 20091119-alt1 - first build for altlinux diff --git a/viewer/SConscript b/viewer/SConscript index df46457..ac2dde0 100644 --- a/viewer/SConscript +++ b/viewer/SConscript @@ -1,52 +1,52 @@ Import ('env') SConscript("images/SConscript") e=env.Clone() e.Library("viewer", Split (""" mapview.cpp actions/action_manager.cpp widgets/comboboxes.cpp widgets/coord_box.cpp widgets/nom_box.cpp widgets/page_box.cpp widgets/rainbow.cpp dialogs/ch_conf.cpp dialogs/err.cpp dialogs/map.cpp dialogs/wpt.cpp dialogs/trk.cpp dialogs/trk_pt.cpp dialogs/show_pt.cpp dialogs/download.cpp dialogs/trk_filter.cpp dialogs/trk_mark.cpp dialogs/draw_opt.cpp dialogs/save_img.cpp dialogs/srtm_opt.cpp dialogs/pano.cpp dialogs/nav.cpp dialogs/trace.cpp panels/workplane.cpp panels/wpts_panel.cpp panels/trks_panel.cpp panels/maps_panel.cpp panels/vmap_panel.cpp """)) e.Prepend(LIBPATH=["."]) e.Prepend(LIBS=["viewer"]) e.Program("mapsoft_mapview.cpp") # e.Program("test_widgets.cpp") -env.Install(env.bindir, Split(""" - mapsoft_mapview -""")) +env.Install(env.bindir, "mapsoft_mapview") + +env.Install(env.desktopdir, "mapsoft_mapview.desktop") # e.Program("test_gp.cpp")
ushakov/mapsoft
ae6b98626c4df6a6b36d72af44dbfe233d688333
raw flag in mapsoft_geofig program
diff --git a/core/geo_io/geofig.cpp b/core/geo_io/geofig.cpp index 6c09b94..087889a 100644 --- a/core/geo_io/geofig.cpp +++ b/core/geo_io/geofig.cpp @@ -1,399 +1,403 @@ #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_file_iterator.hpp> #include <boost/spirit/include/classic_assign_actor.hpp> #include <boost/spirit/include/classic_push_back_actor.hpp> #include <boost/spirit/include/classic_insert_at_actor.hpp> #include <sstream> #include <iomanip> #include "geofig.h" #include "geo/geo_convs.h" #include "options/options.h" #include "loaders/image_r.h" namespace fig { using namespace std; using namespace boost::spirit::classic; // Get geo-reference from fig g_map get_ref(const fig_world & w){ g_map ret; fig::fig_object brd; // border string proj="tmerc"; // tmerc is the default proj // old-style options -- to be removed for (int n=0; n<w.comment.size(); n++){ parse(w.comment[n].c_str(), str_p("proj:") >> space_p >> (*anychar_p)[assign_a(proj)]); } Options O = w.opts; if (!O.exists("map_proj")) O.put<string>("map_proj", proj); dPoint min(1e99,1e99), max(-1e99,-1e99); fig_world::const_iterator i; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)&&(i->type!=3)) continue; if (i->size()<1) continue; double x,y; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("REF") >> +space_p >> real_p[assign_a(x)] >> +space_p >> real_p[assign_a(y)]).full)){ Options O=i->opts; string key; // old-style options -- to be removed for (int n=1; n<i->comment.size(); n++){ parse(i->comment[n].c_str(), (*(anychar_p-':'-space_p))[assign_a(key)] >> *space_p >> ch_p(':') >> *space_p >> (*(anychar_p-':'-space_p))[insert_at_a(O, key)]); cerr << "Geofig: old-style option: " << key << ": " << O[key] << "\n"; } O.put<double>("x", x); O.put<double>("y", y); O.put<double>("xr", (*i)[0].x); O.put<double>("yr", (*i)[0].y); g_refpoint ref; ref.parse_from_options(O); ret.push_back(ref); continue; } if ((i->comment.size()>0)&&(i->comment[0].size()>3) && (i->comment[0].compare(0,3,"BRD")==0)) ret.border = *i; } // set lon0 if it id not set if (O.get<Proj>("map_proj") == Proj("tmerc") && !O.exists("lon0")){ O.put<double>("lon0", convs::lon2lon0(ret.center().x)); } ret.parse_from_options(O, false); // new-style options return ret; } void rem_ref(fig_world & w){ vector<string>::iterator i = w.comment.begin(); while (i!=w.comment.end()){ if (i->find("map_proj",0)==0) i=w.comment.erase(i); else i++; } fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("REF ",0)==0)) obj=w.erase(obj); else obj++; } } void set_ref(fig_world & w, const g_map & m, const Options & O){ double lon0 = m.range().x + m.range().w/2; lon0 = floor( lon0/6.0 ) * 6 + 3; lon0 = m.proj_opts.get("lon0", lon0); Enum::output_fmt=Enum::xml_fmt; // Если хочется, можно записать точки привязки в нужной проекции string pproj=O.get<string>("proj", "lonlat"); string pdatum=O.get<string>("datum", "wgs84"); convs::pt2wgs cnv(Datum(pdatum), Proj(pproj), O); for (int n=0; n<m.size(); n++){ fig::fig_object o = fig::make_object("2 1 0 4 4 7 1 -1 -1 0.000 0 1 -1 0 0 *"); o.push_back(iPoint( int(m[n].xr), int(m[n].yr) )); dPoint p(m[n]); cnv.bck(p); Enum::output_fmt=Enum::xml_fmt; ostringstream comm; comm << "REF " << fixed << p.x << " " << p.y; o.comment.push_back(comm.str()); comm.str(""); o.opts=O; w.push_back(o); } // добавим в заголовок fig-файла информацию о проекции. w.opts.insert(m.proj_opts.begin(), m.proj_opts.end()); w.opts.put("map_proj", m.map_proj); } void get_wpts(const fig_world & w, const g_map & m, geo_data & d){ // сделаем привязку convs::map2wgs cnv(m); fig_world::const_iterator i; g_waypoint_list pl; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)&&(i->type!=3)) continue; if (i->size()<1) continue; Options O=i->opts; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("WPT") >> +space_p >> (*anychar_p)[insert_at_a(O,"name")]).full)){ string key; // old-style options -- to be removed for (int n=1; n<i->comment.size(); n++){ // Удалил ограничение не позволявшее использовать ' ' и ':' в // комментариях. Тим parse(i->comment[n].c_str(), (*(anychar_p-':'-space_p))[assign_a(key)] >> *space_p >> ch_p(':') >> *space_p >> (*(anychar_p))[insert_at_a(O, key)]); } g_waypoint wp; wp.parse_from_options(O); wp.color = i->pen_color; wp.x=(*i)[0].x; wp.y=(*i)[0].y; cnv.frw(wp); pl.push_back(wp); } } d.wpts.push_back(pl); } void get_trks(const fig_world & w, const g_map & m, geo_data & d){ convs::map2wgs cnv(m); fig_world::const_iterator i; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)&&(i->type!=3)) continue; if (i->size()<1) continue; Options O=i->opts; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("TRK") >> !(+space_p >> (*anychar_p)[insert_at_a(O,"comm")])).full)){ string key; // old-style options -- to be removed for (int n=1; n<i->comment.size(); n++){ parse(i->comment[n].c_str(), (*(anychar_p-':'-space_p))[assign_a(key)] >> *space_p >> ch_p(':') >> *space_p >> (*(anychar_p-':'-space_p))[insert_at_a(O, key)]); } g_track tr; tr.parse_from_options(O); tr.color = i->pen_color; for (int n = 0; n<i->size();n++){ g_trackpoint p; p.x=(*i)[n].x; p.y=(*i)[n].y; cnv.frw(p); tr.push_back(p); } d.trks.push_back(tr); } } } void get_maps(const fig_world & w, const g_map & m, geo_data & d){ convs::map2wgs cnv(m); fig_world::const_iterator i; g_map_list maplist; for (i=w.begin();i!=w.end();i++){ if ((i->type!=2)||(i->sub_type!=5)) continue; if (i->size()<3) continue; string comm; if ((i->comment.size()>0)&&(parse(i->comment[0].c_str(), str_p("MAP") >> !(+space_p >> (*anychar_p)[assign_a(comm)])).full)){ // откопируем m и заменим координаты xfig на координаты в растровом файле. // 4 точки fig-объекта соответствуют углам картинки (0,0) (W,0) (W,H) (0,H*) g_map map(m); map.comm = comm; map.file = i->image_file; iPoint WH = image_r::size(i->image_file.c_str()); double x1 = (*i)[0].x; double y1 = (*i)[0].y; double x2 = (*i)[1].x; double y2 = (*i)[1].y; double x4 = (*i)[3].x; double y4 = (*i)[3].y; double a1 = -WH.x*(y4-y1)/(x4*(y2-y1)+x1*(y4-y2)+x2*(y1-y4)); double b1 = WH.x*(x4-x1)/(x4*(y2-y1)+x1*(y4-y2)+x2*(y1-y4)); double c1 = -a1*x1-b1*y1; double a2 = -WH.y*(y2-y1)/(x2*(y4-y1)+x1*(y2-y4)+x4*(y1-y2)); double b2 = WH.y*(x2-x1)/(x2*(y4-y1)+x1*(y2-y4)+x4*(y1-y2)); double c2 = -a2*x1-b2*y1; for (int n=0; n<map.size(); n++){ double xr = map[n].xr; double yr = map[n].yr; map[n].xr = a1*xr+b1*yr+c1; map[n].yr = a2*xr+b2*yr+c2; } // граница: если есть ломаная с комментарием "BRD <имя карты>" - // сделаем границу из нее. Иначе - из размеров растрового файла. map.border.clear(); fig_world::const_iterator j; for (j=w.begin();j!=w.end();j++){ if (j->type!=2) continue; int nn = j->size(); if (nn<3) continue; // если последняя точка совпадает с первой if ((*j)[0]==(*j)[nn-1]) {nn--; if (nn<3) continue;} string brd_comm; if ((j->comment.size()>0)&&(parse(j->comment[0].c_str(), str_p("BRD") >> !(+space_p >> (*anychar_p)[assign_a(brd_comm)])).full)&&(brd_comm==comm)){ for (int n=0;n<nn;n++){ map.border.push_back(dPoint( a1*(*j)[n].x + b1*(*j)[n].y + c1, a2*(*j)[n].x + b2*(*j)[n].y + c2 )); } } } if (map.border.empty()){ map.border.push_back(dPoint(0,0)); map.border.push_back(dPoint(WH.x,0)); map.border.push_back(dPoint(WH.x,WH.y)); map.border.push_back(dPoint(0,WH.y)); } maplist.push_back(map); } } d.maps.push_back(maplist); } void rem_wpts(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("WPT ",0)==0)) obj=w.erase(obj); else obj++; } } void rem_trks(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("TRK ",0)==0)) obj=w.erase(obj); else obj++; } } void rem_maps(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("MAP ",0)==0)) obj=w.erase(obj); else obj++; } } void rem_brds(fig_world & w){ fig_world::iterator obj = w.begin(); while (obj!=w.end()){ if ((obj->comment.size()>0) && (obj->comment[0].find("BRD ",0)==0)) obj=w.erase(obj); else obj++; } } #define ADDCOMM(x) {ostringstream s; s << x; f.comment.push_back(s.str());} void -put_wpts(fig_world & F, const g_map & m, const geo_data & world){ +put_wpts(fig_world & F, const g_map & m, const geo_data & world, bool raw){ vector<g_waypoint_list>::const_iterator wl; vector<g_waypoint>::const_iterator w; convs::map2wgs cnv(m); Enum::output_fmt=Enum::xml_fmt; for (wl=world.wpts.begin();wl!=world.wpts.end();wl++){ for (w=wl->begin();w!=wl->end();w++){ dPoint p(w->x, w->y); cnv.bck(p); fig::fig_object f = fig::make_object("2 1 0 2 0 7 6 0 -1 1 1 1 -1 0 0 *"); ADDCOMM("WPT " << w->name); - f.opts=to_options_skipdef(*w); - f.opts.erase("name"); - f.opts.erase("lon"); - f.opts.erase("lat"); - f.opts.erase("color"); + if (!raw){ + f.opts=to_options_skipdef(*w); + f.opts.erase("name"); + f.opts.erase("lon"); + f.opts.erase("lat"); + f.opts.erase("color"); + } f.push_back(iPoint(int(p.x), int(p.y))); f.pen_color = w->color; F.push_back(f); fig::fig_object ft = fig::make_object("4 0 8 5 -1 18 6 0.0000 4"); ft.push_back(iPoint(int(p.x)+30, int(p.y)+30)); ft.text = w->name; F.push_back(ft); } } } void -put_trks(fig_world & F, const g_map & m, const geo_data & world){ +put_trks(fig_world & F, const g_map & m, const geo_data & world, bool raw){ vector<g_track>::const_iterator tl; vector<g_trackpoint>::const_iterator t; convs::map2wgs cnv(m); Enum::output_fmt=Enum::xml_fmt; g_track def; for (tl=world.trks.begin();tl!=world.trks.end();tl++){ t=tl->begin(); do { vector<iPoint> pts; do{ dPoint p(t->x, t->y); cnv.bck(p); pts.push_back(iPoint(int(p.x),int(p.y))); t++; } while ((t!=tl->end())&&(!t->start)); fig::fig_object f = fig::make_object("2 1 0 1 1 7 7 0 -1 1 1 1 -1 0 0 *"); - f.opts=to_options_skipdef(*tl); - ADDCOMM("TRK " << tl->comm); - f.opts.erase("comm"); - f.pen_color = tl->color; - f.opts.erase("color"); + if (!raw){ + f.opts=to_options_skipdef(*tl); + ADDCOMM("TRK " << tl->comm); + f.opts.erase("comm"); + f.pen_color = tl->color; + f.opts.erase("color"); + } for (vector<iPoint>::const_iterator p1=pts.begin(); p1!=pts.end(); p1++) f.push_back(*p1); F.push_back(f); } while (t!=tl->end()); } } } // namespace diff --git a/core/geo_io/geofig.h b/core/geo_io/geofig.h index b3329b3..8cb0fd3 100644 --- a/core/geo_io/geofig.h +++ b/core/geo_io/geofig.h @@ -1,34 +1,35 @@ #ifndef GEOFIG_H #define GEOFIG_H #include <vector> #include "fig/fig.h" #include "geo/geo_data.h" namespace fig { /// get geo reference from fig_world object g_map get_ref(const fig_world & w); /// remove geo reference from fig_world object void rem_ref(fig_world & w); /// add geo reference to fig_world object void set_ref(fig_world & w, const g_map & m, const Options & o); /// get waypoints, tracks, map refrences from fig void get_wpts(const fig_world & w, const g_map & m, geo_data & d); void get_trks(const fig_world & w, const g_map & m, geo_data & d); void get_maps(const fig_world & w, const g_map & m, geo_data & d); /// remove waypoins, tracks, maps, or map borders: void rem_wpts(fig_world & w); void rem_trks(fig_world & w); void rem_maps(fig_world & w); void rem_brds(fig_world & w); - /// add waypoints or tracks from to fig - void put_wpts(fig_world & w, const g_map & m, const geo_data & d); - void put_trks(fig_world & w, const g_map & m, const geo_data & d); + /// Add waypoints or tracks from to fig + /// if raw = 1, no geofig comments are added + void put_wpts(fig_world & w, const g_map & m, const geo_data & d, bool raw=true); + void put_trks(fig_world & w, const g_map & m, const geo_data & d, bool raw=true); } #endif diff --git a/programs/mapsoft_geofig.cpp b/programs/mapsoft_geofig.cpp index 0794d68..1c81fc5 100644 --- a/programs/mapsoft_geofig.cpp +++ b/programs/mapsoft_geofig.cpp @@ -1,162 +1,164 @@ #include "options/m_getopt.h" #include "geo_io/geofig.h" #include "geo_io/geo_refs.h" #include "geo_io/io.h" #include "err/err.h" using namespace std; #define OPT_CRE 1 #define OPT_ADD 2 #define OPT_DEL 4 static struct ext_option options[] = { {"geom", 1, 'g', OPT_CRE, ""}, {"datum", 1, 'd', OPT_CRE, ""}, {"proj", 1, 'p', OPT_CRE, ""}, {"lon0", 1, 'l', OPT_CRE, ""}, {"wgs_geom", 1, 'w', OPT_CRE, ""}, {"wgs_brd", 1, 'b', OPT_CRE, ""}, {"trk_brd", 1, 'b', OPT_CRE, ""}, {"nom", 1, 'N', OPT_CRE, ""}, {"google", 1, 'G', OPT_CRE, ""}, {"rscale", 1, 'r', OPT_CRE, ""}, {"mag", 1, 'm', OPT_CRE, ""}, {"swap_y", 0, 'y', OPT_CRE, "\n"}, {"verbose", 0, 'v', OPT_CRE | OPT_ADD | OPT_DEL, "be more verbose"}, {"out", 1, 'o', OPT_CRE | OPT_ADD | OPT_DEL, "set output file name"}, {"help", 0, 'h', OPT_CRE | OPT_ADD | OPT_DEL, "show help message"}, {"pod", 0, 0, OPT_CRE | OPT_ADD | OPT_DEL, "show help message as pod template"}, + {"raw", 0, 'R', OPT_ADD, "add raw fig objects, without comments"}, + {"wpts", 0, 'w', OPT_DEL, "delete waypoints"}, {"trks", 0, 't', OPT_DEL, "delete tracks"}, {"maps", 0, 'm', OPT_DEL, "delete maps"}, {"brds", 0, 'b', OPT_DEL, "delete map borders"}, {"ref", 0, 'r', OPT_DEL, "delete fig reference"}, {0,0,0,0} }; void usage(bool pod=false){ string head = pod? "\n=head1 ":"\n"; const char * prog = "mapsoft_geofig"; cerr << prog << " -- actions with geo-referenced FIG\n" << head << "Usage:\n" << "\t" << prog << " create [<options>] (--out|-o) <output_file>\n" << "\t" << prog << " add [<options>] <file1> ... <fileN> (--out|-o) <output_file>\n" << "\t" << prog << " del [<options>] (--out|-o) <output_file>\n" ; cerr << head << "Options for create action:\n"; print_options(options, OPT_CRE, cerr, pod); cerr << head << "Options for add action:\n"; print_options(options, OPT_ADD, cerr, pod); cerr << head << "Options for del action:\n"; print_options(options, OPT_DEL, cerr, pod); } int main(int argc, char **argv){ try { if (argc<3){ usage(); return 0; } string action = argv[1]; argv++; argc--; /*****************************************/ if (action == "create"){ Options O = parse_options(&argc, &argv, options, OPT_CRE); if (O.exists("help")){ usage(); return 0;} if (O.exists("pod")) { usage(true); return 0;} if (argc>0){ cerr << "error: wrong argument: " << argv[0] << endl; return 1; } if (!O.exists("out")){ cerr << "error: no output files" << endl; return 1; } O.put<string>("dpi", "fig"); fig::fig_world F; fig::set_ref(F, mk_ref(O), Options()); fig::write(O.get<string>("out"), F); } /*****************************************/ else if (action == "add"){ vector<string> infiles; Options O = parse_options_all(&argc, &argv, options, OPT_ADD, infiles); if (O.exists("help")) {usage(); return 0;} if (O.exists("pod")) {usage(true); return 0;} if (!O.exists("out")){ cerr << "no output files.\n"; return 1; } if (O.exists("verbose")) cerr << "Reading data...\n"; geo_data world; for (vector<string>::const_iterator i = infiles.begin(); i!=infiles.end(); i++){ try {io::in(*i, world, O);} catch (Err e) {cerr << e.get_error() << endl;} } if (O.exists("verbose")){ cerr << ", Waypoint lists: " << world.wpts.size() << ", Tracks: " << world.trks.size() << "\n"; } string ofile = O.get<string>("out"); if (O.exists("verbose")) cerr << "Writing data to " << ofile << "\n"; fig::fig_world F; if (!fig::read(ofile.c_str(), F)) { cerr << "error: can't read file: " << ofile << endl; return 1; } g_map ref = fig::get_ref(F); - put_wpts(F, ref, world); - put_trks(F, ref, world); + put_wpts(F, ref, world, O.get<bool>("raw")); + put_trks(F, ref, world, O.get<bool>("raw")); return !fig::write(ofile.c_str(), F); } /*****************************************/ else if (action == "del"){ Options O = parse_options(&argc, &argv, options, OPT_DEL); if (O.exists("help")) {usage(); return 0;} if (O.exists("pod")) {usage(true); return 0;} if (argc>0){ cerr << "error: wrong argument: " << argv[0] << endl; return 1; } if (!O.exists("out")){ cerr << "error: no output files" << endl; return 1; } string ofile = O.get<string>("out"); fig::fig_world F; if (!fig::read(ofile.c_str(), F)) { cerr << "error: can't read file: " << ofile << endl; return 1; } if (O.exists("wpts")) rem_wpts(F); if (O.exists("trks")) rem_trks(F); if (O.exists("maps")) rem_maps(F); if (O.exists("brds")) rem_brds(F); if (O.exists("ref")) rem_ref(F); return !fig::write(ofile.c_str(), F); } /*****************************************/ else { usage(); return 0;} } catch (Err e) { cerr << e.get_error() << endl; return 1; } return 0; }
ushakov/mapsoft
e379b1d1d2134f0cb52fc9b877de2eb963a3e845
mapsoft_wp_parse: fix charset conversions
diff --git a/scripts/mapsoft_wp_parse b/scripts/mapsoft_wp_parse index d176475..168f918 100755 --- a/scripts/mapsoft_wp_parse +++ b/scripts/mapsoft_wp_parse @@ -1,94 +1,97 @@ #!/usr/bin/perl use strict; use warnings; use Text::Iconv; # parse kml file downloaded from Westra Passes # (http://westra.ru/passes/kml/passes.php?BBOX=x1,y1,x2,y2) # print txt and mp files -my $cnv_koi = Text::Iconv->new("utf8", "koi8-r"); -my $cnv_win = Text::Iconv->new("utf8", "cp1251"); +### set_attr is not supported, so use iconv program. +#my $cnv_koi = Text::Iconv->new("utf8", "koi8-r"); +#my $cnv_win = Text::Iconv->new("utf8", "cp1251"); #$cnv_koi->set_attr("discard_ilseq", 1); #$cnv_win->set_attr("discard_ilseq", 1); my $file = $ARGV[0]; open IN, $file or die "can't open $file: $!\n"; my $text = join ' ', <IN>; close IN; $file=~s/.kml$//; -open OUT_TXT, "> $file.txt" or die "can't open $file.txt: $!\n"; -open OUT_MP, "> $file.mp" or die "can't open $file.mp: $!\n"; +open OUT_TXT, "| iconv -f utf8 -t koi8-r -c > $file.txt" or die "can't open $file.txt: $!\n"; +open OUT_MP, "| iconv -f utf8 -t cp1251 -c > $file.mp" or die "can't open $file.mp: $!\n"; -printf OUT_TXT "#%4s %12s %12s %5s %s\n", - 'id', 'lat', 'lon', 'alt', 'title /other title/, cat'; +printf OUT_TXT "# id lat lon alt title /other title/, cat\n"; printf OUT_MP qq* [IMG ID] ID=0 Name=$file Elevation=M Preprocess=F CodePage=1251 [END-IMG ID]\n *; my @data; while ($text=~s|<Placemark>(.*?)</Placemark>||s){ my $line = $1; my $d; # pass name and type (name can be "вер. Х", "пер. Х", "пик X") $d->{name} = ($line =~ m|<name>(.*?)</name>|s)? $1:""; - $d->{type} = "V"; $d->{type} = "P" if $d->{name} =~ s|пер. ||; $d->{name} =~ s|вер. ||; my $point = ($line =~ m|<Point>(.*?)</Point>|s)? $1:""; my $coord = ($point =~ m|<coordinates>(.*?)</coordinates>|s)? $1:""; ($d->{x},$d->{y},$d->{z}) = split(',', $coord); my $descr = ($line =~ m|<description>(.*?)</description>|s)? $1:""; - $d->{id} = ($descr =~ m|http://westra.ru/passes/Passes/([0-9]+)|s)? $1:0; - $d->{ks} = ($descr =~ m|<tr><th>Категория сложности</th><td>([^<]*</td></tr>)|s)? $1:''; + $d->{id} = ($descr =~ m|https://westra.ru/passes/Passes/([0-9]+)|s)? $1:0; + $d->{ks} = ($descr =~ m|<tr><th>Категория сложности</th><td>([^<]*)</td></tr>|s)? $1:''; $d->{alt} = ($descr =~ m|<tr><th>Высота</th><td>([^<]*)</td></tr>|s)? $1:0; $d->{var} = ($descr =~ m|<tr><th>Другие названия</th><td>([^<]*)</td></tr>|s)? $1:''; $d->{name_txt} = ($d->{type} eq 'P'? 'пер. ': 'вер. ') . $d->{name} . ($d->{var}? " /$d->{var}/":"") . ($d->{ks}? ", $d->{ks}":""); $d->{name_mp} = (($d->{type} eq 'V' && $d->{alt} && $d->{name}!~m|^\d+$|)? "$d->{alt} ":'') . $d->{name}; + foreach ('name_mp', 'name_txt', 'name'){ + $d->{$_} =~ s/№/N/g; + $d->{$_} =~ s/&quot;/\"/g; + } push @data, $d; } foreach my $d (sort {$a->{id} <=> $b->{id}} @data) { - $d->{name_txt} = $cnv_koi->convert($d->{name_txt}); - $d->{name_mp} = $cnv_win->convert($d->{name_mp}); +# $d->{name_txt} = $cnv_koi->convert($d->{name_txt}) or print " ERROR: $d->{name_txt}\n"; +# $d->{name_mp} = $cnv_win->convert($d->{name_mp}); printf OUT_TXT "%4d %12.7f %12.7f %5d %s\n", $d->{id}, $d->{y}, $d->{x}, $d->{alt}, $d->{name_txt}; # make mp type my $mptype = $d->{type} eq 'P' ? '0x6406':'0x1100'; $mptype='0x6700' if ($d->{type} eq 'P' && ($d->{ks}=~m|н.?к|i)); $mptype='0x6701' if ($d->{type} eq 'P' && ($d->{ks}=~m|1А|i || $d->{ks}=~m|1A|i)); $mptype='0x6702' if ($d->{type} eq 'P' && ($d->{ks}=~m|1Б|i || $d->{ks}=~m|1B|i)); $mptype='0x6703' if ($d->{type} eq 'P' && ($d->{ks}=~m|2А|i || $d->{ks}=~m|2A|i)); $mptype='0x6704' if ($d->{type} eq 'P' && ($d->{ks}=~m|2Б|i || $d->{ks}=~m|2B|i)); $mptype='0x6705' if ($d->{type} eq 'P' && ($d->{ks}=~m|3А|i || $d->{ks}=~m|3A|i)); $mptype='0x6706' if ($d->{type} eq 'P' && ($d->{ks}=~m|3Б|i || $d->{ks}=~m|3B|i)); print OUT_MP "[POI]\n"; print OUT_MP "Type=$mptype\n"; print OUT_MP "Label=$d->{name_mp}\n"; print OUT_MP "Source=westra_passes\n"; print OUT_MP "Data0=($d->{y},$d->{x})\n"; print OUT_MP "[END]\n\n"; }
ushakov/mapsoft
dcadce8a49a5563828fe17904fbc81563e7341cc
Revert "vector/data/styles.m4: change MP type for unknown pass"
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index 6b286d6..486f9e7 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,612 +1,612 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности - mp: POI 0x6407 0 0 + mp: POI 0x6406 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 24 40 -1 18 7 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 pic: ldp - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp txt: 4 0 0 40 -1 3 8 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 18 7 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор mp: POLYLINE 0x19 0 0 fig: 2 1 0 1 20 7 81 -1 -1 0.000 0 0 0 1 0 0 0 0 2.00 90.00 90.00 ocad: 819000 - name: маленькая ЛЭП mp: POLYLINE 0x1A 0 0 fig: 2 1 0 2 8947848 7 83 -1 -1 0.000 0 0 0 0 0 0 ocad: 819001 - name: пешеходный тоннель mp: POLYLINE 0x1B 0 0 fig: 2 1 0 1 3 7 77 -1 -1 0.000 0 0 0 0 0 0 ocad: 819002 - name: просека широкая mp: POLYLINE 0x1C 0 1 fig: 2 1 1 2 0 7 80 -1 -1 6.000 1 0 0 0 0 0 ocad: 819003 - name: граница стран, областей mp: POLYLINE 0x1D 0 2 fig: 2 1 0 7 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница областей, районов mp: POLYLINE 0x36 0 2 fig: 2 1 0 5 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница заповедников, парков mp: POLYLINE 0x37 0 2 fig: 2 1 0 5 2 7 91 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 819004 - name: нижний край обрыва mp: POLYLINE 0x1E 0 0 fig: 2 1 2 1 18 7 79 -1 -1 2.000 1 1 7 0 0 0
ushakov/mapsoft
4f948e313a80ca3913b7a9427d56a936a2951ef9
scripts/mapsoft_wp_parse: add s modifier to all regexps to allow multiline data
diff --git a/scripts/mapsoft_wp_parse b/scripts/mapsoft_wp_parse index e22ede2..d176475 100755 --- a/scripts/mapsoft_wp_parse +++ b/scripts/mapsoft_wp_parse @@ -1,94 +1,94 @@ #!/usr/bin/perl use strict; use warnings; use Text::Iconv; # parse kml file downloaded from Westra Passes # (http://westra.ru/passes/kml/passes.php?BBOX=x1,y1,x2,y2) # print txt and mp files my $cnv_koi = Text::Iconv->new("utf8", "koi8-r"); my $cnv_win = Text::Iconv->new("utf8", "cp1251"); #$cnv_koi->set_attr("discard_ilseq", 1); #$cnv_win->set_attr("discard_ilseq", 1); my $file = $ARGV[0]; open IN, $file or die "can't open $file: $!\n"; my $text = join ' ', <IN>; close IN; $file=~s/.kml$//; open OUT_TXT, "> $file.txt" or die "can't open $file.txt: $!\n"; open OUT_MP, "> $file.mp" or die "can't open $file.mp: $!\n"; printf OUT_TXT "#%4s %12s %12s %5s %s\n", 'id', 'lat', 'lon', 'alt', 'title /other title/, cat'; printf OUT_MP qq* [IMG ID] ID=0 Name=$file Elevation=M Preprocess=F CodePage=1251 [END-IMG ID]\n *; my @data; -while ($text=~s|<Placemark>(.*?)</Placemark>||){ +while ($text=~s|<Placemark>(.*?)</Placemark>||s){ my $line = $1; my $d; # pass name and type (name can be "вер. Х", "пер. Х", "пик X") - $d->{name} = ($line =~ m|<name>(.*?)</name>|)? $1:""; + $d->{name} = ($line =~ m|<name>(.*?)</name>|s)? $1:""; $d->{type} = "V"; $d->{type} = "P" if $d->{name} =~ s|пер. ||; $d->{name} =~ s|вер. ||; - my $point = ($line =~ m|<Point>(.*?)</Point>|)? $1:""; - my $coord = ($point =~ m|<coordinates>(.*?)</coordinates>|)? $1:""; + my $point = ($line =~ m|<Point>(.*?)</Point>|s)? $1:""; + my $coord = ($point =~ m|<coordinates>(.*?)</coordinates>|s)? $1:""; ($d->{x},$d->{y},$d->{z}) = split(',', $coord); - my $descr = ($line =~ m|<description>(.*?)</description>|)? $1:""; - $d->{id} = ($descr =~ m|http://westra.ru/passes/Passes/([0-9]+)|)? $1:0; - $d->{ks} = ($descr =~ m|<tr><th>Категория сложности</th><td>([^<]*</td></tr>)|)? $1:''; - $d->{alt} = ($descr =~ m|<tr><th>Высота</th><td>([^<]*)</td></tr>|)? $1:0; - $d->{var} = ($descr =~ m|<tr><th>Другие названия</th><td>([^<]*)</td></tr>|)? $1:''; + my $descr = ($line =~ m|<description>(.*?)</description>|s)? $1:""; + $d->{id} = ($descr =~ m|http://westra.ru/passes/Passes/([0-9]+)|s)? $1:0; + $d->{ks} = ($descr =~ m|<tr><th>Категория сложности</th><td>([^<]*</td></tr>)|s)? $1:''; + $d->{alt} = ($descr =~ m|<tr><th>Высота</th><td>([^<]*)</td></tr>|s)? $1:0; + $d->{var} = ($descr =~ m|<tr><th>Другие названия</th><td>([^<]*)</td></tr>|s)? $1:''; $d->{name_txt} = ($d->{type} eq 'P'? 'пер. ': 'вер. ') . $d->{name} . ($d->{var}? " /$d->{var}/":"") . ($d->{ks}? ", $d->{ks}":""); $d->{name_mp} = (($d->{type} eq 'V' && $d->{alt} && $d->{name}!~m|^\d+$|)? "$d->{alt} ":'') . $d->{name}; push @data, $d; } foreach my $d (sort {$a->{id} <=> $b->{id}} @data) { $d->{name_txt} = $cnv_koi->convert($d->{name_txt}); $d->{name_mp} = $cnv_win->convert($d->{name_mp}); printf OUT_TXT "%4d %12.7f %12.7f %5d %s\n", $d->{id}, $d->{y}, $d->{x}, $d->{alt}, $d->{name_txt}; # make mp type my $mptype = $d->{type} eq 'P' ? '0x6406':'0x1100'; $mptype='0x6700' if ($d->{type} eq 'P' && ($d->{ks}=~m|н.?к|i)); $mptype='0x6701' if ($d->{type} eq 'P' && ($d->{ks}=~m|1А|i || $d->{ks}=~m|1A|i)); $mptype='0x6702' if ($d->{type} eq 'P' && ($d->{ks}=~m|1Б|i || $d->{ks}=~m|1B|i)); $mptype='0x6703' if ($d->{type} eq 'P' && ($d->{ks}=~m|2А|i || $d->{ks}=~m|2A|i)); $mptype='0x6704' if ($d->{type} eq 'P' && ($d->{ks}=~m|2Б|i || $d->{ks}=~m|2B|i)); $mptype='0x6705' if ($d->{type} eq 'P' && ($d->{ks}=~m|3А|i || $d->{ks}=~m|3A|i)); - $mptype='0x6706' if ($d->{type} eq 'P' && ($d->{ks}=~m|4Б|i || $d->{ks}=~m|3B|i)); + $mptype='0x6706' if ($d->{type} eq 'P' && ($d->{ks}=~m|3Б|i || $d->{ks}=~m|3B|i)); print OUT_MP "[POI]\n"; print OUT_MP "Type=$mptype\n"; print OUT_MP "Label=$d->{name_mp}\n"; print OUT_MP "Source=westra_passes\n"; print OUT_MP "Data0=($d->{y},$d->{x})\n"; print OUT_MP "[END]\n\n"; }
ushakov/mapsoft
a2b5f598328c7e1bef3a2f4be5a8253c511157ff
vector/data/styles.m4: change MP type for unknown pass
diff --git a/vector/data/styles.m4 b/vector/data/styles.m4 index 486f9e7..6b286d6 100644 --- a/vector/data/styles.m4 +++ b/vector/data/styles.m4 @@ -1,612 +1,612 @@ divert(-1) # Source for mmb and hr style files. Same types but different colors define(VYS_COL, ifelse(STYLE,hr, 24,0)) # цвет отметок высот define(HOR_COL, ifelse(STYLE,hr, 30453904,26)) # цвет горизонталей define(VOD_COL, ifelse(STYLE,hr, 11,3)) # цвет рек define(HRE_COL, ifelse(STYLE,hr, 26,24)) # цвет хребта define(TRE_PIC, ifelse(STYLE,hr, trig_hr,trig)) # цвет хребта divert - name: деревня mp: POI 0x0700 0 0 fig: 2 1 0 5 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 770000 - name: крупная деревня mp: POI 0x0800 0 0 fig: 2 1 0 4 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: город mp: POI 0x0900 0 0 fig: 2 1 0 3 18 7 50 -1 -1 0.000 1 1 7 0 0 1 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad_txt: 790000 - name: триангуляционный знак mp: POI 0x0F00 0 0 fig: 2 1 0 2 VYS_COL 7 57 -1 20 0.000 1 1 -1 0 0 1 pic: TRE_PIC txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 196000 ocad_txt: 710000 - name: отметка высоты mp: POI 0x1100 0 0 fig: 2 1 0 4 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 7 0.0000 4 ocad: 110000 ocad_txt: 710000 - name: маленькая отметка высоты desc: взятая автоматически из srtm и т.п. mp: POI 0x0D00 0 0 fig: 2 1 0 3 VYS_COL 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 VYS_COL 40 -1 18 6 0.0000 4 - name: отметка уреза воды mp: POI 0x1000 0 0 fig: 2 1 0 4 1 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 18 6 0.0000 4 ocad: 100000 ocad_txt: 700000 move_to: 0x100026 0x100015 0x100018 0x10001F 0x200029 0x20003B 0x200053 pic: ur_vod - name: магазин mp: POI 0x2E00 0 0 fig: 2 1 0 2 4 7 50 -1 -1 0.000 1 0 7 0 0 1 - name: подпись лесного квартала, урочища mp: POI 0x2800 0 0 fig: 2 1 0 4 12 7 55 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: памятник mp: POI 0x2c04 0 0 fig: 2 1 0 1 4 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pam txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293004 ocad_txt: 780000 - name: церковь mp: POI 0x2C0B 0 0 fig: 2 1 0 1 11 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: cerkov txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 293009 ocad_txt: 780000 - name: остановка автобуса mp: POI 0x2F08 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 1 -1 0 0 1 pic: avt ocad: 296008 - name: ж/д станция mp: POI 0x5905 0 0 fig: 2 1 0 4 4 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: zd ocad: 590005 ocad_txt: 780000 rotate_to: 0x10000D 0x100027 - name: перевал неизвестной сложности - mp: POI 0x6406 0 0 + mp: POI 0x6407 0 0 fig: 2 1 0 1 1 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per rotate_to: 0x10000C - name: перевал н/к mp: POI 0x6700 0 0 fig: 2 1 0 1 2 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: pernk rotate_to: 0x10000C - name: перевал 1А mp: POI 0x6701 0 0 fig: 2 1 0 1 3 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1a rotate_to: 0x10000C - name: перевал 1Б mp: POI 0x6702 0 0 fig: 2 1 0 1 4 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per1b rotate_to: 0x10000C - name: перевал 2А mp: POI 0x6703 0 0 fig: 2 1 0 1 5 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2a rotate_to: 0x10000C - name: перевал 2Б mp: POI 0x6704 0 0 fig: 2 1 0 1 6 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per2b rotate_to: 0x10000C - name: перевал 3А mp: POI 0x6705 0 0 fig: 2 1 0 1 7 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3a rotate_to: 0x10000C - name: перевал 3Б mp: POI 0x6706 0 0 fig: 2 1 0 1 8 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 15 40 -1 18 7 0.0000 4 pic: per3b rotate_to: 0x10000C - name: каньон mp: POI 0x660B 0 0 fig: 2 1 0 1 9 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 24 40 -1 18 7 0.0000 4 pic: kan - name: ледопад mp: POI 0x650A 0 0 fig: 2 1 0 1 10 7 158 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 7 0.0000 4 pic: ldp - name: дом mp: POI 0x6402 0 1 fig: 2 1 0 4 0 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: dom ocad: 640002 ocad_txt: 780000 - name: кладбище mp: POI 0x6403 0 1 fig: 2 1 0 1 12 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: kladb ocad: 640003 - name: башня mp: POI 0x6411 0 0 fig: 2 1 0 1 5 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: bash ocad: 641001 - name: родник mp: POI 0x6414 0 0 fig: 2 1 0 4 5269247 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad: 641004 ocad_txt: 729000 - name: развалины mp: POI 0x6415 0 1 fig: 2 1 0 1 0 7 156 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: razv ocad: 641005 ocad_txt: 780000 - name: шахты mp: POI 0x640C 0 1 fig: 2 1 0 1 0 7 155 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 3 8 0.0000 4 pic: shaht ocad_txt: 780000 - name: водопад mp: POI 0x6508 0 0 fig: 2 1 0 4 17 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F pic: vdp - name: порог /не использовать!/ mp: POI 0x650E 0 0 fig: 2 1 0 4 8 7 57 -1 -1 0.000 0 0 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 rotate_to: 0x100026 0x100015 0x100018 0x10001F replace_by: 0x6508 pic: por - name: пещера mp: POI 0x6601 0 0 fig: 2 1 0 1 24 7 157 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 1 40 -1 3 8 0.0000 4 pic: pesch ocad: 660001 - name: яма mp: POI 0x6603 0 0 fig: 2 1 0 1 25 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: yama ocad: 660003 - name: охотничья вышка, кормушка и т.п. mp: POI 0x6606 0 0 fig: 2 1 0 1 6 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: ohotn ocad: 660006 - name: курган mp: POI 0x6613 0 0 fig: 2 1 0 1 26 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: pupyr ocad: 661003 - name: скала-останец mp: POI 0x6616 0 0 fig: 2 1 0 1 20 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: skala txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 661006 ocad_txt: 780000 - name: место стоянки mp: POI 0x2B03 0 0 fig: 2 1 0 1 21 7 157 -1 -1 0.000 0 1 -1 0 0 1 pic: camp txt: 4 0 0 40 -1 3 8 0.0000 4 - name: одиночное дерево, внемасштабный лес mp: POI 0x660A 0 0 fig: 2 1 0 4 14 7 57 -1 -1 0.000 0 1 -1 0 0 1 txt: 4 0 0 40 -1 18 7 0.0000 4 - name: лес mp: POLYGON 0x16 0 1 fig: 2 3 0 0 12 11206570 100 -1 20 0.000 0 1 -1 0 0 0 ocad: 916000 - name: поле mp: POLYGON 0x52 0 1 fig: 2 3 0 0 12 11206570 99 -1 40 0.000 0 1 -1 0 0 0 ocad: 952000 - name: остров леса mp: POLYGON 0x15 0 1 fig: 2 3 0 0 12 11206570 97 -1 20 0.000 0 1 -1 0 0 0 ocad: 915000 - name: свежая вырубка mp: POLYGON 0x4F 0 1 fig: 2 3 0 0 12 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 949006 ocad_txt: 780000 pic: vyr_n pic_type: fill - name: стар.вырубка mp: POLYGON 0x50 0 1 fig: 2 3 0 0 12 11206570 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 950000 ocad_txt: 780000 pic: vyr_o pic_type: fill - name: редколесье mp: POLYGON 0x14 0 1 fig: 2 3 0 0 11206570 7 98 -1 43 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 914000 ocad_txt: 780000 pic: redk pic_type: fill - name: закрытые территории mp: POLYGON 0x04 0 1 fig: 2 3 0 1 0 7 95 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 904000 ocad_txt: 780000 - name: деревни mp: POLYGON 0x0E 0 1 fig: 2 3 0 1 0 27 94 -1 20 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 909005 ocad_txt: 790000 - name: города mp: POLYGON 0x01 0 2 fig: 2 3 0 1 0 27 94 -1 15 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 18 8 0.0000 4 ocad: 901000 ocad_txt: 770000 - name: дачи, сад.уч., д/о, п/л mp: POLYGON 0x4E 0 1 fig: 2 3 0 1 0 11206570 93 -1 10 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 949005 ocad_txt: 780000 - name: кладбище mp: POLYGON 0x1A 0 1 fig: 2 3 0 1 0 11206570 92 -1 5 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 919001 ocad_txt: 780000 pic: cross - name: водоемы mp: POLYGON 0x29 0 1 fig: 2 3 0 1 5269247 VOD_COL 85 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 929000 ocad_txt: 729000 - name: крупные водоемы mp: POLYGON 0x3B 0 2 fig: 2 3 0 1 5269247 VOD_COL 85 -1 15 0.000 0 0 -1 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 729000 - name: остров mp: POLYGON 0x53 0 1 fig: 2 3 0 1 5269247 VOD_COL 84 -1 40 0.000 0 0 -1 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 953000 ocad_txt: 729000 - name: заболоченность mp: POLYGON 0x51 0 1 fig: 2 3 0 0 5269247 VOD_COL 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 951000 ocad_txt: 780000 pic: bol_l pic_type: fill - name: болото mp: POLYGON 0x4C 0 1 fig: 2 3 0 0 VOD_COL 5269247 87 -1 49 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 310000 ocad_txt: 780000 pic: bol_h pic_type: fill - name: ледник mp: POLYGON 0x4D 0 1 fig: 2 3 0 0 11 11 96 -1 35 0.000 0 0 7 0 0 1 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad_txt: 780000 pic: ledn pic_type: fill - name: крутой склон mp: POLYGON 0x19 0 1 fig: 2 3 0 0 0 24 91 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: дырка в srtm-данных mp: POLYGON 0xA 0 1 fig: 2 3 0 0 0 4 110 -1 20 0.000 0 0 -1 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad_txt: 780000 - name: осыпь, галька, песок mp: POLYGON 0x8 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand pic_type: fill ocad_txt: 780000 - name: песок mp: POLYGON 0xD 0 1 fig: 2 2 0 0 26 26 95 -1 35 0.000 0 0 7 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 pic: sand_ov pic_type: fill ocad_txt: 780000 - name: отличный путь mp: POLYLINE 0x35 0 0 fig: 2 1 0 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 835000 curve: 50 - name: хороший путь mp: POLYLINE 0x34 0 0 fig: 2 1 2 3 31 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 834000 curve: 50 - name: удовлетворительный путь mp: POLYLINE 0x33 0 0 fig: 2 1 2 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 833000 curve: 50 - name: плохой путь mp: POLYLINE 0x32 0 0 fig: 2 1 0 3 13 7 88 -1 -1 6.000 0 2 -1 0 0 0 ocad: 832000 curve: 50 - name: кривая надпись mp: POLYLINE 0x00 0 0 fig: 2 1 0 4 1 7 55 -1 -1 0.000 0 0 0 0 0 0 - name: автомагистраль mp: POLYLINE 0x01 0 2 fig: 2 1 0 7 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 801000 curve: 100 - name: большое шоссе mp: POLYLINE 0x0B 0 2 fig: 2 1 0 5 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809002 curve: 100 - name: шоссе mp: POLYLINE 0x02 0 2 fig: 2 1 0 4 4210752 27 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 802000 curve: 100 - name: верхний край обрыва mp: POLYLINE 0x03 0 0 fig: 2 1 0 1 18 7 79 -1 -1 0.000 1 1 7 0 0 0 ocad: 803000 - name: проезжий грейдер mp: POLYLINE 0x04 0 1 fig: 2 1 0 3 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 804000 curve: 100 - name: отдельные строения mp: POLYLINE 0x05 0 1 fig: 2 1 0 3 0 7 81 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 805000 ocad_txt: 780000 - name: проезжая грунтовка mp: POLYLINE 0x06 0 1 fig: 2 1 0 1 0 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 806000 curve: 50 - name: непроезжий грейдер mp: POLYLINE 0x07 0 1 fig: 2 1 1 3 4210752 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 807000 curve: 100 - name: мост-1 (пешеходный) mp: POLYLINE 0x08 0 1 fig: 2 1 0 1 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 808000 ocad_txt: 780000 - name: мост-2 (автомобильный) mp: POLYLINE 0x09 0 1 fig: 2 1 0 2 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809000 ocad_txt: 780000 - name: мост-5 (на автомагистралях) mp: POLYLINE 0x0E 0 1 fig: 2 1 0 5 7 7 77 -1 -1 0.000 0 0 0 0 0 0 txt: 4 0 0 40 -1 3 8 0.0000 4 ocad: 809005 ocad_txt: 780000 - name: непроезжая грунтовка mp: POLYLINE 0x0A 0 1 fig: 2 1 0 1 4210752 7 80 -1 -1 0.000 1 0 0 0 0 0 ocad: 809001 curve: 50 - name: хребет mp: POLYLINE 0x0C 0 1 fig: 2 1 0 2 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: малый хребет mp: POLYLINE 0x0F 0 1 fig: 2 1 0 1 HRE_COL 7 89 -1 -1 0.000 1 1 0 0 0 0 curve: 50 - name: пересыхающий ручей mp: POLYLINE 0x26 0 0 fig: 2 1 1 1 5269247 7 86 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 826000 ocad_txt: 718000 - name: река-1 mp: POLYLINE 0x15 0 1 fig: 2 1 0 1 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 815000 ocad_txt: 718000 - name: река-2 mp: POLYLINE 0x18 0 2 fig: 2 1 0 2 5269247 7 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 818000 ocad_txt: 718000 - name: река-3 mp: POLYLINE 0x1F 0 2 fig: 2 1 0 3 5269247 VOD_COL 86 -1 -1 0.000 1 1 0 0 0 0 txt: 4 1 1 40 -1 3 8 0.0000 4 ocad: 819006 ocad_txt: 718000 - name: просека mp: POLYLINE 0x16 0 1 fig: 2 1 1 1 0 7 80 -1 -1 4.000 1 0 0 0 0 0 ocad: 816000 - name: забор mp: POLYLINE 0x19 0 0 fig: 2 1 0 1 20 7 81 -1 -1 0.000 0 0 0 1 0 0 0 0 2.00 90.00 90.00 ocad: 819000 - name: маленькая ЛЭП mp: POLYLINE 0x1A 0 0 fig: 2 1 0 2 8947848 7 83 -1 -1 0.000 0 0 0 0 0 0 ocad: 819001 - name: пешеходный тоннель mp: POLYLINE 0x1B 0 0 fig: 2 1 0 1 3 7 77 -1 -1 0.000 0 0 0 0 0 0 ocad: 819002 - name: просека широкая mp: POLYLINE 0x1C 0 1 fig: 2 1 1 2 0 7 80 -1 -1 6.000 1 0 0 0 0 0 ocad: 819003 - name: граница стран, областей mp: POLYLINE 0x1D 0 2 fig: 2 1 0 7 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница областей, районов mp: POLYLINE 0x36 0 2 fig: 2 1 0 5 4 7 91 -1 -1 4.000 1 1 0 0 0 0 ocad: 819004 - name: граница заповедников, парков mp: POLYLINE 0x37 0 2 fig: 2 1 0 5 2 7 91 -1 -1 4.000 1 1 0 0 0 0 txt: 4 1 0 40 -1 3 8 0.0000 4 ocad: 819004 - name: нижний край обрыва mp: POLYLINE 0x1E 0 0 fig: 2 1 2 1 18 7 79 -1 -1 2.000 1 1 7 0 0 0
quetzalzun/TianguisCabal
1d142515c48ac134ec6942cec6a72c3434013c16
segundo commit cambios de Richard
diff --git a/MensajeError.php b/MensajeError.php index da08c66..82d6731 100644 --- a/MensajeError.php +++ b/MensajeError.php @@ -1,502 +1,552 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="FixAnotherMSIEBug.xsl"?> <?php include( "includes/TianguisCabalROEnviron.inc" ); // Este Archivo: MensajeError.php include( "includes/TianguisCabalROEnviron.inc"); $Block = "<p class=\"SubTitleFont\" style=\"font-weight:bold; color:#0000aa; text-align:center;\">"; switch( $_GET{'Errno'} ) { case 1001: $Block .= "&iexcl;Faltan EMail! <br />"; break; case 1002: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 1007: $Block .= "ERROR de sistema <br /> Envi&eacute; notificaci&oacute;n a el <br /> administrador de sistema <br /> Disculpa <br />"; break; case 1008: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 1009: $Block .= "No puede Select Login y EMail en la base de datos <br />"; break; case 1012: $Block .= "ERROR de sistema <br /> Envi&eacute; notificaci&oacute;n a el <br /> administrador de sistema <br /> Disculpa <br />"; break; case 1013: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 1015: $Block .= "ERROR de sistema <br /> Envi&eacute; notificaci&oacute;n a el <br /> administrador de sistema <br /> Disculpa <br />"; break; case 1017: $Block .= "ERROR de sistema <br /> Envi&eacute; notificaci&oacute;n a el <br /> administrador de sistema <br /> Disculpa <br />"; break; case 2001: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 2002: $Block .= "No puedo select from Vendedores <br />"; break; case 2003: $Block .= "Un usuario con este nombre existe <br />&iquest;Olvidaste tu contrase&ntilde;a? <br />"; break; case 2004: $Block .= "El \"Password Nuevo\" y el \"Verificar Password\" no son igual <br />"; break; case 2005: $Block .= "No puedo insert into Vendedores <br />"; break; case 2006: $Block .= "No puedo insert/update Vendedores <br />"; break; case 2008: $Block .= "&iexcl;El Password no es aceptable! </p> <p style=\"font-weight:bold; color:#000090; text-align:center;\" class=\"LargeTextFont\"> Tu Password debe tener: </p> <p style=\"font-weight:bold; color:#000090; text-align:center;\" class=\"LargeTextFont\"> 6 caracteres, como minimo </p> <p style=\"font-weight:bold; color:#000090; text-align:center;\" class=\"LargeTextFont\"> que son una combinaci&oacute;n de </p> <p style=\"font-weight:bold; color:#000090; text-align:center;\" class=\"LargeTextFont\"> min&uacute;sculas, <br /> MAY&Uacute;SCULAS, <br /> N&uacute;meros <br /> y <br /> Signos de puctuaci&oacute;n. <br />"; break; case 2009: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 2010: $Block .= "No puedo select UserID from Vendedores <br />"; break; case 2011: $Block .= "&iexcl;No tienes una cuenta! <br /> Si quieres vender, debes registrarte como un vendedor <br />"; break; case 2012: $Block .= "No puedo select PWD from Vendedores <br />"; break; case 2013: $Block .= "&iexcl;No tienes una cuenta! <br /> Si quieres vender, debes regiistrarte <br />"; break; case 2014: $Block .= "Entrada Denegada <br /> Tu Login y/o tu password son invalidos <br />"; break; case 2015: $Block .= "No puede select PWD from Vendedores <br />"; break; case 2016: $Block .= "&iexcl;Tu contrase&ntilde;a est&aacute; invalido! <br />"; break; case 2017: $Block .= "&iexcl;Faltan Campos Obligatorios! <br />"; break; case 2018: $Block .= "No puedo select UserID from Vendedores <br />"; break; case 2019: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 2020: $Block .= "&iexcl;Faltan Campos Obligatorios! <br />"; break; case 2021: $Block .= "&iexcl;Faltan Campos Obligatorios! <br />"; break; case 2022: $Block .= "No puedo update en Vendedores <br />"; break; case 2023: $Block .= "\"{$_GET{'Var'}}\" es tan corto. <br />"; break; case 2024: $Block .= "\"{$_GET{'Var'}}\" no es un n&uacute;mero de Tel&eacute;fono valido. <br />"; break; case 2025: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 2026: $Block .= "No puedo select UserID from Vendedores <br />"; break; case 2101: // CatProdArtNuevo.php $Block .= "No puede conexionar a la base de datos <br />"; break; case 2102: $Block .= "No puede borrar el Art&iacute;culo - &iquest;Tal vez se usa para otro registro? <br />"; break; case 2103: $Block .= "No puede commit borrado del Art&iacute;culo &iquest;Tal vez se usa para otro registro? <br />"; break; case 2104: $Block .= "No puede conexionar a la base de datos <br />"; break; case 2105: $Block .= "No puede Insert/Update a la base de datos &iquest;Tal vez el registro existe? <br />"; break; case 2106: $Block .= "No puede Commit Insert/Update a la base de datos <br />"; break; case 2107: $Block .= "No puede borrar Art&iacute;culo 1 - es parte del sistema <br />"; break; case 2108: $Block .= "No puede conexionar a la base de datos <br />"; break; case 2109: $Block .= "Debe seleccionar TODOS los campos que se marca con <B>*</B> para continuar <br />"; break; case 2110: $Block .= "Debe seleccionar un Art&iacute;culo y una ACCI&Oacute;N para continuar <br />"; break; case 2111: $Block .= "No puede \"select * from Art&iacute;culo where ArtID...\" <br />"; break; case 2112: $Block .= "No puede \"Select * from Proveedor...\" <br />"; break; case 2113: $Block .= "No puede \"Select * from Linea...\" <br />"; break; case 2114: $Block .= "No puede \"Select * from Familia...\" <br />"; break; case 2115: $Block .= "No puede \"Select * from Sub Familia...\" <br />"; break; case 2116: $Block .= "No puede modificar Art&iacute;culo 1 - es parte del sistema <br />"; break; case 2118: $Block .= "&iexcl;Faltan Campos Obligatorios! <br /> Debe utilizar \"&iquest;Intercambiar para que?\" cuando eliges \"Quiero Intercambiar\" <br />"; break; case 2119: $Block .= "&iexcl;Faltan Campos Obligatorios! <br /> Debe elegir \"Quiero Intercambiar\" cuando utilizas \"&iquest;Intercambiar para que?\" <br />"; break; case 2120: $Block .= "No puedo select Categor&iacute;a <br />"; break; case 2121: $Block .= "No puedo select Categor&iacute;a <br />"; break; case 2122: $Block .= "No puedo verificar tu humanidad - Regressa para enviar las dos Palabras ye te pide <br />"; break; case 2123: $Block .= "No puedo verificar tu humanidad - Regressa para enviar las dos Palabras ye te pide <br />"; break; case 2124: $Block .= "No puedo select from Vendedores <br />"; break; case 2125: $Block .= "Tu Correo: &quot;{$_GET{'Var'}}&quot;, es &iexcl;&nbsp;INVALIDO&nbsp;! <br />"; break; case 2201: $Block .= "No puedo conexionar a la base de datos: TianguisCabal <br />"; break; case 2202: $Block .= "Falta E-Mail. No puedo continuar <br />"; break; case 2203: $Block .= "No puedo verificar tu humanidad - Regressa para enviar las dos Palabras ye te pide <br />"; break; case 2204: $Block .= "No puedo select from Vendedores <br />"; break; case 2205: $Block .= "No tiene \"{$_GET{'Var'}}\" registrado <br />"; break; + case 2206: + $Block .= "No puedo conexionar a la base de datos: TianguisCabal + <br />"; + break; + case 2207: + $Block .= "&iexcl;Faltan Campos Obligatorios! + <br />"; + break; + case 2208: + $Block .= "El \"Password Nuevo\" y el \"Verificar Password\" no son + igual + <br />"; + break; + case 2209: + $Block .= "&iexcl;El Password no es aceptable! + </p> + <p style=\"font-weight:bold; color:#000090; + text-align:center;\" class=\"LargeTextFont\"> + Tu Password debe tener: + </p> + <p style=\"font-weight:bold; color:#000090; + text-align:center;\" class=\"LargeTextFont\"> + 6 caracteres, como minimo + </p> + <p style=\"font-weight:bold; color:#000090; + text-align:center;\" class=\"LargeTextFont\"> + que son una combinaci&oacute;n de + </p> + <p style=\"font-weight:bold; color:#000090; + text-align:center;\" class=\"LargeTextFont\"> + min&uacute;sculas, + <br /> + MAY&Uacute;SCULAS, + <br /> + N&uacute;meros + <br /> + y + <br /> + Signos de puctuaci&oacute;n. + <br />"; + break; + case 2210: + $Block .= "No puedo insert/update Vendedores + <br />"; + break; + case 2211: + $Block .= "Faltan Datos Obligatorios del sistema - Disculpa pero no + podemos continuar + <br />"; + break; case 3001: // CatProdArtDesc.php $Block .= "No tiene registros para desplegar <br />"; break; case 3002: $Block .= "No puede conexionar a la base de datos <br />"; break; case 3003: $Block .= "No puede \"Select Proveedor from Proveedor...\" <br />"; break; case 3004: $Block .= "No puede \"Select Descrip from Linea...\" <br />"; break; case 3005: $Block .= "No puede \"Select Descrip from Familia...\" <br />"; break; case 3006: $Block .= "No puede \"Select Descrip from SubFamilia...\" <br />"; break; case 3007: $Block .= "No tiene registros para desplegar <br />"; break; case 6001: // Functions.inc $Block .= "D&iacute;gitos en exceso en \"{$_GET{'Var'}}\" <br />"; break; case 6002: $Block .= "Caracteres ilegales en \"{$_GET{'Var'}}\" <br />"; break; case 6003: $Block .= "Caracteres en exceso en \"{$_GET{'Var'}}\" <br />"; break; case 6004: $Block .= "D&iacute;gitos en exceso antes del punto en \"{$_GET{'Var'}}\" <br />"; break; case 6005: $Block .= "Caracteres ilegales en \"{$_GET{'Var'}}\" <br />"; break; case 6006: $Block .= "D&iacute;gitos en exceso en \"{$_GET{'Var'}}\" <br />"; break; case 6007: $Block .= "No se permiten mas de un punto en \"{$_GET{'Var'}}\" <br />"; break; case 6008: $Block .= "D&iacute;gitos en exceso despu&eacute;s del punto en \"{$_GET{'Var'}}\" <br />"; break; case 18003: $Block .= "\"{$_GET{'Var'}}\"No puede conexionar a la base de datos: TianguisCabal <br />"; break; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es"> <head> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" /> <meta http-equiv="expires" content="-1" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta name="keywords" content="linux cabal, linuxcabal, TianguisCabal, open source, free software, F/OSS, FOSS, GNU, GNU/Linux, Linux, GNU &amp; Linux, Free and Open Source Software, Free y Open Source Software, CoffeeNet, Coffee Net, Richard Couture, Guadalajara, Jalisco, Mexico, M&eacute;xico, Software Freedom Day, SFD, FLISoL, resumen del mes, Mandriva, Fedora, CentOS, Red Hat, Ubuntu, Kubuntu, Edubuntu, Xubuntu, Debian, Puppy, SUSE, Damn Small, Yellow Dog, Moblin, OpenSuSE, Linux From Scratch, OpenBSD, BSD, NetBSD, DesktopBSD, FreeBSD" /> <title> TianguisCabal On Line - Un Lugar Donde Confiar </title> <link rel="stylesheet" type="text/css" href="includes/org.css" /> </head> <body> <?php include( "./includes/Environ.php" ); ?> <div class="menu"> <?php include( "./includes/incMenu.php" ); echo( "$DisplayBlock" ); ?> </div> <div class="content"> <div class="content-head"> <div class="content-head-before"> <img src="images/UpperCornerLeft.gif" alt="UpperCornerLeft.gif" /> <?php include( "./includes/incCommonHeader.php" ); ?> <p class="TitleFont"> -=&nbsp;Mensaje de <span style="color:#bb0000; text-decoration:blink;"> ERROR </span> &nbsp;=- <br/><br /> <?php print( "Error Numero: <em>{$_GET{'Errno'}}</em>" ); ?> </p> </div> </div> <div class="content-main"> <?php include( "./includes/incMenu.php" ); echo( "$Block" ); ?> </p> <p style="text-align: center;" class="LargeTextFont"> Presiona el b&oacute;ton, en tu navegador, <br /> para regresar a la ultima p&aacute;gina <br /> para corregir el problema </p> <?php session_start(); if( @$_SESSION{'PHPSESSID'} ) print("<p> <a href=\"TianguisCabalOnLine.php?LOC=DeMira&amp;Lang=$Lang&amp;From=Tianguis\">&nbsp;&nbsp;Men&uacute;&nbsp;&nbsp;</a> <br /> <a href=\"TianguisCabalOnLine.php?Accion=LogOut&amp;Lang=$Lang&amp;From=Tianguis\">&nbsp;&nbsp;Log Out&nbsp;&nbsp;</a> </p>" ); ?> <p style="text-align: center;"> LinuxCabal no se hace responsable; cada usuario ser&aacute; responsable de sus compras y/o ventas. </p> <p style="text-align: center;"> CAVEAT EMPTOR </p> <div class="content-main-after"> <img src="images/LowerCornerLeft.gif" alt="LowerCornerLeft.gif" /> </div> </div> <div class="content-footer"> <?php include( "./includes/incCommonFooter.php" ); ?> </div> </div> </body> </html> diff --git a/TianguisCabalCambiarPWDHead.php b/TianguisCabalCambiarPWDHead.php new file mode 100644 index 0000000..fbc6876 --- /dev/null +++ b/TianguisCabalCambiarPWDHead.php @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?xml-stylesheet type="text/xsl" href="../includes/FixAnotherMSIEBug.xsl"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es"> + <head> + <meta http-equiv="Content-Type" content="application/xhtml+xml; + charset=UTF-8" /> + <meta http-equiv="expires" content="-1" /> + <meta http-equiv="Content-Style-Type" content="text/css" /> + <meta name="keywords" content="linux cabal, linuxcabal, TianguisCabal, + open source, free software, F/OSS, FOSS, GNU, + GNU/Linux, Linux, GNU &amp; Linux, Free and Open Source + Software, Free y Open Source Software, CoffeeNet, Coffee Net, + Richard Couture, Guadalajara, Jalisco, Mexico, M&eacute;xico, + Software Freedom Day, SFD, FLISoL, resumen del mes, Mandriva, + Fedora, CentOS, Red Hat, Ubuntu, Kubuntu, Edubuntu, Xubuntu, + Debian, Puppy, SUSE, Damn Small, Yellow Dog, Moblin, OpenSuSE, + Linux From Scratch, OpenBSD, BSD, NetBSD, DesktopBSD, + FreeBSD, TianguisCabal" /> + <script type="text/javascript"> + var RecaptchaOptions = { + theme : 'blackglass', + lang : 'es', + tabindex : 2 + }; + </script> + + <title> + TianguisCabal On Line - Un Lugar Donde Confiar + </title> + <link rel="stylesheet" type="text/css" href="../includes/org.css" /> + </head> + <body> + <?php + include( "../includes/Environ.php" ); + ?> + <div class="menu"> + <?php + include( "../includes/incMenu.php" ); + echo( "$DisplayBlock" ); + ?> + </div> + <div class="content"> + <div class="content-head"> + <div class="content-head-before"> + <img src="../images/UpperCornerLeft.gif" alt="UpperCornerLeft.gif" /> + <?php + include( "../includes/incCommonHeader.php" ); + ?> + <p class="TitleFont"> + <?php + if( $Lang == 'en' ) + echo( "TianguisCabal - Change Password" ); + else + echo( "TianguisCabal - Cambiar Contrase&ntilde;a" ); + ?> + </p> + </div> + </div> + <div class="content-main"> diff --git a/TianguisCabalMaint/images/valid-xhtml10.png b/TianguisCabalMaint/images/valid-xhtml10.png new file mode 100644 index 0000000..b81de91 Binary files /dev/null and b/TianguisCabalMaint/images/valid-xhtml10.png differ diff --git a/TianguisCabalOlvidarPass.php b/TianguisCabalOlvidarPass.php index 100dede..81d180c 100644 --- a/TianguisCabalOlvidarPass.php +++ b/TianguisCabalOlvidarPass.php @@ -1,362 +1,400 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="FixAnotherMSIEBug.xsl"?> <?php include( "includes/TianguisCabalFunctions.inc" ); include( "includes/TianguisCabalROEnviron.inc" ); require_once( "/etc/TianguisCabal.inc" ); - /* - if( @$_POST{'Sibmit'} || - ( @$_GET{'Accion'} && @$_GET{'Accion'} != "LogOut" ) ) + if( @$_POST{'Accion'} == "CambiaPWD" ) { - if( $_SERVER{'SERVER_PORT'} != 443 ) + if( !@$_POST{'UserID'} ) { - if( $_SERVER{'HTTP_HOST'} == "www.linuxcabal.org" ) - header( "Location: https://www.imat.com/linuxcabal.org/TianguisCabalOnLine.php?Lang=$Lang&From=Tianguis" ); - else if( $_SERVER{'HTTP_HOST'} == "localhost" ) - header( "Location: https://localhost/linuxcabal.org/TianguisCabalOnLine.php?Lang=$Lang&From=Tianguis" ); + header( "Location: MensajeError.php?Errno=2211&Lang=$Lang&From=$From" ); + //Falta Non User suplied Campos Obligatorios exit(); } - } - */ - if( $_POST{'Accion'} == "EnviarLiga" ) + if( !@$_POST{'PNuevo'} || !@$_POST{'PVer'} ) + { + header( "Location: MensajeError.php?Errno=2207&Lang=$Lang&From=$From" ); + //Falta Campos Obligatorios + exit(); + } + + if( @$_POST{'PNuevo'} !== $_POST{'PVer'} ) + { + header( "Location: MensajeError.php?Errno=2208&Lang=$Lang&From=$From" ); + //Contraseñas No son Egual + exit(); + } + + if( !IsPWDSeguro( $_POST{'PNuevo'} ) ) + { + header( "Location: MensajeError.php?Errno=2209&Lang=$Lang&From=$From" ); + //PWD no está Seguro + exit(); + } + + $PWD = md5( $_POST{'PNuevo'} ); + + $Conn = mysqli_init(); + mysqli_options($Conn, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=1"); + mysqli_options($Conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5); + mysqli_real_connect( $Conn, 'localhost', $Clase, $AccessType, + 'TianguisCabal', MYSQLI_CLIENT_SSL ); + + if( mysqli_connect_errno() ) + { + mysqli_close( $Conn ); + header( "Location: MensajeError.php?Errno=2206&Lang=$Lang&From=$From" ); + exit(); + } + $Query = "update Vendedores set PWD = '{$PWD}', Fecha = CURDATE() + where UserID = {$_POST{'UserID'}}"; + + + if( !$QueryRes = mysqli_query( $Conn, $Query ) ) + { + mysqli_close( $Conn ); + header( "Location: MensajeError.php?Errno=2210&Lang=$Lang&From=$From" ); + //No puede insert PWD + exit(); + } + + unlink( $_POST{'FileName'} ); + + $Block = " <p class=\"SubTitleFont\" style=\"font-weight:bold; + color:#0000aa; text-align:center;\">"; + if( $Lang == ' en' ) + $Block .= "-=&nbsp;Cambio de Tu Contrase&ntilde;a&nbsp;=- + <br /> + &iexcl;&nbsp;CONFIRMADA&nbsp;!"; + else + $Block .= "-=&nbsp;Password Change&nbsp;=- + <br /> + CONFIRMED!"; + $Block .= "<br /> + </p>"; + } + elseif( @$_POST{'Accion'} == "EnviarLiga" ) { if( !@$_POST{'Correo'} ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2202&Lang=$Lang&From=$From" ); exit(); } require_once('recaptchalib.php'); $publickey = $CaptchaPubKey; $privatekey = $CaptchaPrivKey; $resp = recaptcha_check_answer ($privatekey, $_SERVER{'REMOTE_ADDR'}, $_POST{'recaptcha_challenge_field'}, $_POST{'recaptcha_response_field'}); if (!$resp->is_valid) { header( "Location: MensajeError.php?Errno=2203&Lang=$Lang&From=$From" ); //Captcha Validation Error exit(); } $Conn = mysqli_init(); mysqli_options($Conn, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=1"); mysqli_options($Conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5); mysqli_real_connect( $Conn, 'localhost', $ClaseRO, $AccessTypeRO, 'TianguisCabal', MYSQLI_CLIENT_SSL ); if( mysqli_connect_errno() ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2201&Lang=$Lang&From=$From" ); exit(); } $Query = "select UserID, Nombres, Login from Vendedores where Correo = '{$_POST{'Correo'}}'"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2204&Lang=$Lang&From=$From" ); //No Puede select exit(); } if( ( mysqli_num_rows( $QueryRes ) ) != 1 ) { header( "Location:MensajeError.php?Errno=2205&Var={$_POST{'Correo'}}" ); // No Tengo este E-Mail exit(); } $Pedidor = mysqli_fetch_array( $QueryRes ); - $LigaBase = md5( time() ); + $LigaBase = md5( ( time() . $Pedidor{'UserID'} ) ); $LigaArchivo = "TianguisCabalMaint/{$LigaBase}.php"; $LigaURL = "https://www.imat.com/linuxcabal.org/{$LigaArchivo}?Lang=$Lang&From=$From&DD=../"; copy( "TianguisCabalCambiarPWDHead.php", $LigaArchivo ); $Handle = fopen( "/var/www/html/linuxcabal.org/{$LigaArchivo}", "a+" ); $CambiarPWDBody = " <?php echo( \"<p class=\\\"SubTitleFont\\\" style=\\\"text-align:center;\\\"> Del Usuario {$Pedidor{'Nombres'}} </p> <form method=\\\"post\\\" action=\\\"{$_SERVER{'PHP_SELF'}}?Lang=$Lang&From=Tianguis\\\"> <p class=\\\"LargeTextFont\\\" style=\\\"text-align:center;\\\"> Contrase&ntilde;a Nueva: <input type=\\\"password\\\" name=\\\"PNuevo\\\" size=\\\"25\\\" maxlength=\\\"50\\\" /> </p> <p class=\\\"LargeTextFont\\\" style=\\\"text-align:center;\\\"> Verificar Contrase&ntilde;a: <input type=\\\"password\\\" name=\\\"PVer\\\" size=\\\"25\\\" maxlength=\\\"50\\\" /> </p> <p class=\\\"LargeTextFont\\\" style=\\\"text-align:center;\\\"> <br /> <input type=\\\"hidden\\\" name=\\\"Accion\\\" value=\\\"CambiaPWD\\\" /> + <input type=\\\"hidden\\\" name=\\\"FileName\\\" + value=\\\"/var/www/html/linuxcabal.org/{$LigaArchivo}\\\" /> <input type=\\\"hidden\\\" name=\\\"UserID\\\" value={$Pedidor{'UserID'}} /> <input type=\\\"submit\\\" name=\\\"Submit\\\" style=\\\"font-weight:bold\\\" value =\\\"A P L I C A R\\\" /> &nbsp;&nbsp;&nbsp;&nbsp; <input type=\\\"reset\\\" value=\\\"Reset\\\" /> </p> </form>\" ); ?>"; fwrite( $Handle, $CambiarPWDBody ); $CambiarPWDFoot = "<div class=\"content-main-after\"> <img src=\"../images/LowerCornerLeft.gif\" alt=\"LowerCornerLeft.gif\" /> </div> </div> <div class=\"content-footer\"> <?php include( \"../includes/incCommonFooter.php\" ); ?> </div> </div> </body> </html>"; fwrite( $Handle, $CambiarPWDFoot ); $Mensaje ="Saludos {$Pedidor{'Nombres'}}\r\n Recibimos una petición a cambiar la contraseña del usuario qeu tiene tu E-Mail\r\n - \r\n Si quieres cambiar la contraseña del usuario \"{$Pedidor{'Login'}}\", haga click en la URL:\r\n {$LigaURL}\r\n \r\n Este URL expire en 1 (una) hora\r\n \r\n - Gracias para usar el TianguisCabal\r\n\r\n\r\n + Gracias para usar el TianguisCabal\r\n\r\n [email protected]"; $Headers = "From: [email protected]"; $Resultado = mail( "{$_POST{'Correo'}}", 'Recuperar TianguiCabal Acceso', $Mensaje, $Headers ); if( $Resultado ) $Block = "<p class=\"SubTitleFont\" style=\"text-align:center;\"> Correo enviado a {$_POST{'Correo'}} con &eacute;xito"; else $Block = "<p class=\"SubTitleFont\" style=\"text-align:center;\"> Envio de Correo a {$_POST{'Correo'}} fall&oacute;"; } else { - $Block = "<p class=\"SubTitleFont\" style=\"text-align:center;\"> - <img src=\"images/construction.gif\" - alt=\"construction.gif\" />"; - if( $Lang == 'en' ) - $Block .= " This page is presently under construction - <br /> - and is therefore disfunctional. - <br /> - Please excuse our dust - <br /> - while we improve the system - </p>"; - else - $Block .= " Esta p&aacute;gina est&aacute; en construcci&oacute;n - <br /> - entonces est&aacute; disfuncional - <br /> - Por favor disculpa las molestias - </p>"; if( $Lang == 'en' ) $Block .= "<p class=\"LargeTextFont\" style=\"text-align:center;\"> It is not possible to recover your existing password <br /> but, <br /> we can help you in re-assigning a new password. </p> <p class=\"LargeTextFont\" style=\"text-align:center;\"> Use the form below to send us your E-Mail address. <br /> If it corresponds to an E-Mail address in our database <br /> we will send you a link which will enable you <br /> to assign a new password to your account </p>"; else $Block .= "<p class=\"LargeTextFont\" style=\"text-align:center;\"> No es posible para nosotros a recuperar tu contrase&ntilde;a, <br /> pero, <br /> podemos facilitarte a re-asignar una contrase&ntilde;a nueva. </p> <p class=\"LargeTextFont\" style=\"text-align:center;\"> Usa la forma que sigue para enviarnos la <br /> direcci&oacute;n de tu correo electr&oacute;nico. <br /> Si el corresponde a una direcci&oacute;n en nuestra base de datos, <br /> vamos enviarte una liga que <br /> te permitir&aacute; asignar una contrase&ntilde;a nueva. </p>"; $Block .= "<form method=\"post\" action=\"{$_SERVER{'PHP_SELF'}}?Lang=$Lang&amp;From=$From\"> <table cellspacing=\"20\" cellpadding=\"0\" style=\"margin: 2%; width:95%;\"> <tr> <td align = \"center\"> E-Mail: <input type=\"text\" name=\"Correo\" size=\"25\" maxlength=\"50\" /> <br /> </td> </tr>"; require_once('recaptchalib.php'); $publickey = $CaptchaPubKey; $Block .= "<tr> <td align=\"center\">" . recaptcha_get_html($publickey, $use_ssl=true ) . "</td> </tr> <tr> <td align=\"center\"> <input type=\"hidden\" name=\"Accion\" value=\"EnviarLiga\" /> <input type=\"submit\" name=\"Submit\" style=\"font-weight:bold\""; if( $Lang == 'en' ) $Block .= " value =\"S E N D\" />"; else $Block .= " value =\"E N V I A R\" />"; $Block .= " &nbsp;&nbsp;&nbsp;&nbsp; <input type=\"reset\" value=\"Reset\" /> </td> </tr> </table> </form>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es"> <head> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" /> <meta http-equiv="expires" content="-1" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta name="keywords" content="linux cabal, linuxcabal, TianguisCabal, open source, free software, F/OSS, FOSS, GNU, GNU/Linux, Linux, GNU &amp; Linux, Free and Open Source Software, Free y Open Source Software, CoffeeNet, Coffee Net, Richard Couture, Guadalajara, Jalisco, Mexico, M&eacute;xico, Software Freedom Day, SFD, FLISoL, resumen del mes, Mandriva, Fedora, CentOS, Red Hat, Ubuntu, Kubuntu, Edubuntu, Xubuntu, Debian, Puppy, SUSE, Damn Small, Yellow Dog, Moblin, OpenSuSE, Linux From Scratch, OpenBSD, BSD, NetBSD, DesktopBSD, FreeBSD, TianguisCabal" /> <script type="text/javascript"> var RecaptchaOptions = { theme : 'blackglass', lang : 'es', tabindex : 2 }; </script> <title> TianguisCabal On Line - Un Lugar Donde Confiar </title> <link rel="stylesheet" type="text/css" href="includes/org.css" /> </head> <body> <?php include( "./includes/Environ.php" ); ?> <div class="menu"> <?php include( "./includes/incMenu.php" ); echo( "$DisplayBlock" ); ?> </div> <div class="content"> <div class="content-head"> <div class="content-head-before"> <img src="images/UpperCornerLeft.gif" alt="UpperCornerLeft.gif" /> <?php include( "./includes/incCommonHeader.php" ); ?> <p class="TitleFont"> <?php if( $Lang == 'en' ) echo( "Recover Access to My Account" ); else echo( "Recuperar Acceso a Mi Cuenta" ); ?> </p> </div> </div> <div class="content-main"> <?php echo( "$Block" ); ?> <p style="text-align: center;"> <?php if( $Lang == 'en' ) print( "LinuxCabal accepts absolutely no responsiblity what-so-ever as to the servicabilty of items bought and sold via this system. <br /> Each buyer and seller is solely and individually responsible." ); else print( "LinuxCabal no se hace responsable; cada usuario ser&aacute; responsable de sus compras y/o ventas." ); ?> </p> <p style="text-align: center; font-weight:bold;" class="LargeTextFont"> CAVEAT EMPTOR </p> <p style="text-align: center;"> <?php if( $Lang == 'en' ) print( "You may download the <a href=\"TianguisCabalOnLine.tar.bz\">Source Code of TianguisCabalOnLine</a> here" ); else print( "&iexcl;Puedes descargar el <a href=\"TianguisCabalOnLine.tar.bz\">Codigo Fuente de TianguisCabalOnLine</a> aqu&iacute;" ); ?> </p> <div class="content-main-after"> <img src="images/LowerCornerLeft.gif" alt="LowerCornerLeft.gif" /> </div> </div> <div class="content-footer"> <?php include( "./includes/incCommonFooter.php" ); ?> </div> </div> </body> </html> diff --git a/TianguisCabalOnLine.php b/TianguisCabalOnLine.php index 84f7f8a..3d3d769 100644 --- a/TianguisCabalOnLine.php +++ b/TianguisCabalOnLine.php @@ -1,573 +1,576 @@ <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="FixAnotherMSIEBug.xsl"?> <?php /* use TianguisCabal; CREATE TABLE `Categoria` ( `CatID` tinyint(4) NOT NULL auto_increment, `Categoria` varchar(50) NOT NULL default '', - PRIMARY KEY (`CatID`) + PRIMARY KEY (`CatID`), + UNIQUE KEY `Categoria` (`Categoria`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `Categoria` VALUES (1,'Almacenamiento'),(2,'Audio/Sonido'), (3,'Cables'), (4,'Camaras'), (5,'Copiadoras'), (6,'Energia'), (7,'FAX'), (8,'Gabinetes'), (9,'Impresoras'), (10,'Memoria'), (11,'Miscelanea'), (12,'Monitores'), (13,'Mouse'), (14,'Muebles'), (15,'Notebooks'), (16,'PCs'), (17,'PDAs'), (18,'Redes'), (19,'Scanners'), (20,'Tarjetas Madres'), (21,'Teclados'), (22,'Telefonia'), (23,'Video'), (26,'No Computacional'); CREATE TABLE `Vendedores` ( `UserID` int(7) NOT NULL auto_increment, `ApellidoPaterno` varchar(25) NOT NULL default '', `ApellidoMaterno` varchar(25) default '', `Nombres` varchar(30) NOT NULL default '', `Login` varchar(25) NOT NULL default '', `PWD` varchar(50) NOT NULL default '', `Fecha` date NOT NULL default '0000-00-00', `Correo` varchar(75) NOT NULL default '', `MexTelLada` varchar(2) NOT NULL default '0', `MexTelFront` varchar(4) NOT NULL default '0', `MexTelBack` varchar(4) NOT NULL default '0', PRIMARY KEY (`UserID`), UNIQUE KEY `Login` (`Login`) UNIQUE KEY `Correo` (`Correo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `Ventas` ( `VentaID` int(7) NOT NULL auto_increment, `UserID` int(7) NOT NULL default '0', `Fecha` date NOT NULL default '0000-00-00', `Articulo` varchar(175) NOT NULL default '', `Cantidad` tinyint(4) NOT NULL default '1', `Descripcion` varchar(250) NOT NULL default '', `Calidad` enum('Excelente','Muy Buena','Buena','Regular','Partes') default 'Muy Buena', `Precio` varchar(10) NOT NULL default '00.00', `LinkFoto` varchar(175) default '', - `CompraVenta` enum('Se Vende','Quiero Comprar') default 'Se Vende', - `InterCambiar` varchar(12) default '', + `CompraVenta` enum('Se Vende','Quiero Comprar') default 'Se Vende', `InterCambiar` varchar(12) default '', `CambiarParaQue` varchar(250) default '', `Categoria` varchar(50) NOT NULL default '', PRIMARY KEY (`VentaID`), KEY `UserID` (`UserID`), + KEY `Categoria` (`Categoria`), + CONSTRAINT `Ventas_ibfk_2` FOREIGN KEY (`Categoria`) REFERENCES `Categoria` (`Categoria`), CONSTRAINT `Ventas_ibfk_1` FOREIGN KEY (`UserID`) REFERENCES `Vendedores` (`UserID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; + */ include( "includes/TianguisCabalFunctions.inc" ); require_once( "/etc/TianguisCabal.inc" ); if( @$_POST{'Sibmit'} || ( @$_GET{'Accion'} && @$_GET{'Accion'} != "LogOut" ) ) { if( $_SERVER{'SERVER_PORT'} != 443 ) { if( $_SERVER{'HTTP_HOST'} == "www.linuxcabal.org" ) header( "Location: https://www.imat.com/linuxcabal.org/TianguisCabalOnLine.php?Lang=$Lang&From=Tianguis" ); else if( $_SERVER{'HTTP_HOST'} == "localhost" ) header( "Location: https://localhost/linuxcabal.org/TianguisCabalOnLine.php?Lang=$Lang&From=Tianguis" ); exit(); } } // <<<<---- LOGOUT ---->>>>> if( @$_GET{'Accion'} == "LogOut" ) { DestruyeSession(); } // <<<--- APLICAR PWD --->>>> if( @$_POST{'Submit'} && @$_POST{'Accion'} == "AplicarPWD" ) { $Conn = mysqli_init(); mysqli_options($Conn, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=1"); mysqli_options($Conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5); mysqli_real_connect( $Conn, 'localhost', $Clase, $AccessType, 'TianguisCabal', MYSQLI_CLIENT_SSL ); if( mysqli_connect_errno() ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2001&Lang=$Lang&From=$From" ); exit(); } if( !@$_POST{'CambioPWD'} && !@$_POST{'ManPerfil'} ) { require_once('recaptchalib.php'); $publickey = $CaptchaPubKey; $privatekey = $CaptchaPrivKey; $resp = recaptcha_check_answer ($privatekey, $_SERVER{'REMOTE_ADDR'}, $_POST{'recaptcha_challenge_field'}, $_POST{'recaptcha_response_field'}); if (!$resp->is_valid) { header( "Location: MensajeError.php?Errno=2122&Lang=$Lang&From=$From" ); //Captcha Validation Error exit(); } include( "includes/TianguisCabalROEnviron.inc" ); $Query = "select UserID from Vendedores where Login = '{$_POST{'Login'}}'"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2002&Lang=$Lang&From=$From" ); //No Puede select exit(); } if( mysqli_num_rows( $QueryRes ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2003&Lang=$Lang&From=$From" ); //Cuenta Existe exit(); } } if( @$_POST{'CambioPWD'} || @$_POST{'ManPerfil'} ) { require( "includes/TianguisCabalEnviron.inc" ); $Query = "select PWD from Vendedores where UserID = '{$_SESSION{'UID'}}'"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2015&Lang=$Lang&From=$From" ); //No Puede select exit(); } $PWDRec = mysqli_fetch_Array( $QueryRes ); $PCur = $PWDRec{'PWD'}; if( md5( $_POST{'PCur'} ) != $PCur ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2016&Lang=$Lang&From=$From" ); //PWD No está Valido exit(); } } if( !@$_POST{'ManPerfil'} && !@$_POST{'CambioPWD'} ) { IsValidMexTel( "MexTelBack", $_POST{'MexTelBack'}, 4 ); IsValidMexTel( "MexTelFront", $_POST{'MexTelFront'}, 4 ); if( !@$_POST{'ApellidoPaterno'} || !@$_POST{'Nombres'} || !@$_POST{'Correo'} || !@$_POST{'MexTelLada'} || !@$_POST{'MexTelFront'} || !@$_POST{'MexTelBack'} || !@$_POST{'Login'} || !@$_POST{'PNuevo'} || !@$_POST{'PVer'} ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2017&Lang=$Lang&From=$From" ); //Falta Campos Obligatorios exit(); } } elseif( @$_POST{'ManPerfil'} ) { IsValidInt( "MexTelBack", $_POST{'MexTelBack'}, 4 ); IsValidInt( "MexTelFront", $_POST{'MexTelFront'}, 4 ); if( !@$_POST{'ApellidoPaterno'} || !@$_POST{'Nombres'} || !@$_POST{'Correo'} || !@$_POST{'MexTelLada'} || !@$_POST{'MexTelFront'} || !@$_POST{'MexTelBack'} || !@$_POST{'Login'} ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2020&Lang=$Lang&From=$From" ); //Falta Campos Obligatorios exit(); } } else { if( !@$_POST{'PNuevo'} || !@$_POST{'PVer'} ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2021&Lang=$Lang&From=$From" ); //Falta Campos Obligatorios exit(); } } if( !@$_POST{'ManPerfil'} ) { if( @$_POST{'PNuevo'} !== $_POST{'PVer'} ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2004&Lang=$Lang&From=$From" ); //Contraseñas No son Egual exit(); } if( !IsPWDSeguro( $_POST{'PNuevo'} ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2008&Lang=$Lang&From=$From" ); //PWD no está Seguro exit(); } $PWD = md5( $_POST{'PNuevo'} ); } if( !@$_POST{'CambioPWD'} && !@$_POST{'ManPerfil'} ) { $ApellidoPaterno = htmlspecialchars( $_POST{'ApellidoPaterno'}, ENT_QUOTES, "UTF-8" ); $ApellidoMaterno = htmlspecialchars( $_POST{'ApellidoMaterno'}, ENT_QUOTES, "UTF-8" ); $Nombres = htmlspecialchars( $_POST{'Nombres'}, ENT_QUOTES, "UTF-8" ); $Login = htmlspecialchars( $_POST{'Login'}, ENT_QUOTES, "UTF-8" ); if( IsValidCorreo( $_POST{'Correo'} ) ) $Correo = $_POST{'Correo'}; else { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2125&Lang=$Lang&From=$From&Var={$_POST{'Correo'}}" ); //Correo Invalido exit(); } $Query = "insert into Vendedores values ( NULL, '{$ApellidoPaterno}', '{$ApellidoMaterno}', '{$Nombres}', '{$Login}', '{$PWD}', CURDATE(), '{$Correo}', '{$_POST{'MexTelLada'}}', '{$_POST{'MexTelFront'}}', '{$_POST{'MexTelBack'}}' )"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2005&Lang=$Lang&From=$From" ); //No Puede insert exit(); } } elseif( @$_POST{'ManPerfil'} ) { $ApellidoPaterno = htmlspecialchars( $_POST{'ApellidoPaterno'}, ENT_QUOTES, "UTF-8" ); $ApellidoMaterno = htmlspecialchars( $_POST{'ApellidoMaterno'}, ENT_QUOTES, "UTF-8" ); $Nombres = htmlspecialchars( $_POST{'Nombres'}, ENT_QUOTES, "UTF-8" ); $Correo = htmlspecialchars( $_POST{'Correo'}, ENT_QUOTES, "UTF-8" ); $Query = "update Vendedores set ApellidoPaterno = '{$ApellidoPaterno}', ApellidoMaterno = '{$ApellidoMaterno}', Nombres = '{$Nombres}', Fecha = CURDATE(), Correo = '{$Correo}', MexTelLada = '{$_POST{'MexTelLada'}}', MexTelFront = '{$_POST{'MexTelFront'}}', MexTelBack = '{$_POST{'MexTelBack'}}' where UserID = {$_SESSION{'UID'}}"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2022&Lang=$Lang&From=$From" ); //No Puede update exit(); } } else { $Query = "update Vendedores set PWD = '{$PWD}', Fecha = CURDATE() where UserID = {$_SESSION{'UID'}}"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2006&Lang=$Lang&From=$From" ); //No puede insert PWD exit(); } } $UsuarioID = mysqli_insert_id( $Conn ); mysqli_free_result( $QueryRes ); mysqli_close( $Conn ); if( !@$_POST{'CambioPWD'} && !@$_POST{'ManPerfil'} ) { ini_set( "session.cache_expire", "30" ); ini_set( "session.cookie_lifetime", "1800" ); ini_set( "session.gc_maxlifetime", "1820" ); include( "includes/TianguisCabalROEnviron.inc"); session_start(); $_SESSION{'PHPSESSID'} = session_id(); $_SESSION{'Login'} = $_POST{'Login'}; $_SESSION{'UID'} = $UsuarioID; setcookie( "Login", $_POST{'Login'} ); } $Block = " <p class=\"SubTitleFont\" style=\"font-weight:bold; color:#0000aa; text-align:center;\">"; if( !@$_POST{'CambioPWD'} && !@$_POST{'ManPerfil'} ) { if( $Lang == 'en' ) $Block .= "-=&nbsp;Creation of Your New Account&nbsp;=-"; else $Block .= "-=&nbsp;Creaci&oacute;n de Tu Cuenta Nueva&nbsp;=-"; } elseif( @$_POST{'CambioPWD'} ) { if( $Lang == 'en' ) $Block .= "-=&nbsp;Password Change&nbsp;=-"; else $Block .= "-=&nbsp;Cambio de Tu Contrase&ntilde;a&nbsp;=-"; } else { if( $Lang == 'en' ) $Block .= "-=&nbsp;Updating of Your Profile&nbsp;=-"; else $Block .= "-=&nbsp;Actualizaci&oacute;n de Tu Perfil&nbsp;=-"; } $Block .= " <br />"; if( $Lang == 'en' ) $Block .= "CONFIRMED!"; else $Block .= "&iexcl;&nbsp;CONFIRMADA&nbsp;!"; $Block .= " <br /><br /> </p> <form method=\"post\" action=\"{$_SERVER{'PHP_SELF'}}?Lang=$Lang&amp;From=Tianguis\"> <p style=\"text-align: center;\"> <input type=\"hidden\" name=\"Accion\" value=\"Entra\" /> <input type=\"submit\" name=\"Submit\" class=\"SubTitleFont\" style=\"font-weight:bold; color:#0000aa;\""; if( $Lang == 'en' ) $Block .= " value=\"Click here to Continue\" />"; else $Block .= " value=\"Presiona aqu&iacute; para Continuar\" />"; $Block .= " </p> </form>"; } // <<<<---- PICK PARA MODIFICAR ---->>>> elseif( @$_GET{'Accion'} == 'PickMod' ) { include( "includes/TianguisCabalEnviron.inc" ); $Conn = mysqli_init(); mysqli_options($Conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5); mysqli_real_connect( $Conn, 'localhost', $ClaseRO, $AccessTypeRO, 'TianguisCabal', MYSQLI_CLIENT_SSL ); if( mysqli_connect_errno() ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2025&Lang=$Lang&From=$From" ); //No puedo connect exit(); } $Query = "select VentaID, Articulo, Cantidad, Precio from Ventas where UserID = {$_SESSION{'UID'}}"; if( !$VentasRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2026&Lang=$Lang&From=$From" ); //No Puede select exit(); } $Block = " <form method=\"post\" action=\"TianguisCabalOnLineArtNuevo.php?Lang=$Lang&amp;From=$From\">"; if( ( $NumRows = mysqli_num_rows( $VentasRes ) ) < 1 ) { header( "Location:MensajeError.php?Errno=3007" ); // No Tiene Ventas a mostrar exit(); } else { $Block .= " <p style=\"font-weight:bold; color:#7700AA; text-align: center;\" class=\"SubTitleFont\">"; if( $Lang == 'en' ) $Block .= " Choose a record to Delete or Modify"; else $Block .= " Elige un registro para Editar o Borrar"; $Block .= " <br /> </p> <table cellspacing=\"0\" cellpadding=\"0\" border=\"1\" style=\"width:95%; background:#aaaaaa; text-align:center; margin-left:2%\"> <tr style=\"background:url(images/logoBG.jpg);\"> <th style=\"white-space:nowrap;\">"; if( $Lang == 'en' ) $Block .= " &nbsp;Artcle&nbsp;"; else $Block .= " &nbsp;Art&iacute;culo&nbsp;"; $Block .= " </th> <th style=\"white-space:nowrap;\">"; if( $Lang == 'en' ) $Block .= " &nbsp;Quantity&nbsp;"; else $Block .= " &nbsp;Cantidad&nbsp;"; $Block .= " </th> <th style=\"white-space:nowrap;\">"; if( $Lang == 'en' ) $Block .= " Price"; else $Block .= " Precio"; $Block .= " </th> </tr>"; $LineCount = 0; while( $Articulo = mysqli_fetch_array( $VentasRes ) ) { $Block .= " <tr> <td style=\"white-space:nowrap; text-align:left;\"> <input type=\"radio\" name=\"CheckArtID\" value=\"{$Articulo{'VentaID'}}\" /> &nbsp;{$Articulo{'Articulo'}}&nbsp; </td> <td style=\"text-align:center; white-space:nowrap;\"> &nbsp;{$Articulo{'Cantidad'}}&nbsp; </td> <td style=\"white-space:nowrap;\"> &nbsp;{$Articulo{'Precio'}}&nbsp; </td> </tr>"; $LineCount++; if( !( $LineCount % 20 ) || $NumRows == $LineCount ) { $Block .= " <tr style=\"background:url(images/logoBG.jpg)\"> <th colspan=\"3\" style=\"white-space:nowrap;\">"; if( $Lang == 'en' ) $Block .= " &nbsp;&nbsp;&nbsp;&nbsp;Edit"; else $Block .= " &nbsp;&nbsp;&nbsp;&nbsp;Editar"; $Block .= " <input type=\"radio\" name=\"ActionArtID\" value=\"EditArtID\" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type=\"submit\" name=\"Submit\""; if( $Lang == 'en' ) $Block .= " value=\"A P P L Y\" />"; else $Block .= " value=\"A P L I C A R\" />"; $Block .= " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type=\"radio\" name=\"ActionArtID\" value=\"BorraArtID\" />"; if( $Lang == 'en' ) $Block .= " Delete&nbsp;&nbsp;&nbsp;&nbsp;"; else $Block .= " Borrar&nbsp;&nbsp;&nbsp;&nbsp;"; $Block .= " </th> </tr>"; } } $Block .= " </table> </form> <p> <a href=\"TianguisCabalOnLine.php?LOC=DeMira&amp;Lang=$Lang&amp;From=$From\">"; if( $Lang == 'en' ) $Block .= " &nbsp;&nbsp;Menu&nbsp;&nbsp;</a>"; else $Block .= " &nbsp;&nbsp;Men&uacute;&nbsp;&nbsp;</a>"; $Block .= " <br /> <a href=\"TianguisCabalOnLine.php?Accion=LogOut&amp;Lang=$Lang&amp;From=$From\">&nbsp;&nbsp;LogOut&nbsp;&nbsp;</a> </p>"; } mysqli_free_result( $VentasRes ); mysqli_close( $Conn ); } // <<<<---- UNIRTE ---->>>> elseif( ( @$_POST{'Submit'} && @$_POST{'Unirte'} ) || @$_GET{'Accion'} == "CambioPWD" || @$_GET{'Accion'} == "ManPerfil" ) { if( @$_POST{'Unirte'} ) include( "includes/TianguisCabalROEnviron.inc" ); else include( "includes/TianguisCabalEnviron.inc" ); $Block = " <p style=\"font-weigth:bold; color:#000055; text-align: center;\" class=\"SubTitleFont\">"; if( @$_GET{'Accion'} != "CambioPWD" && @$_GET{'Accion'} != "ManPerfil" ) { if( $Lang == 'en' ) $Block .= " Register As a Seller"; else $Block .= " Registrar Como un Vendedor"; } elseif( @$_GET{'Accion'} == "CambioPWD" ) { if( $Lang == 'en' ) $Block .= " Change Your Password"; else $Block .= " Cambiar Tu Contrase&ntilde;a"; } else { if( $Lang == 'en' ) $Block .= " Manage Your Personal Profile"; else $Block .= " Manejar tu Perfil Personal"; } $Block .= " </p> <form method=\"post\" action=\"{$_SERVER{'PHP_SELF'}}?Lang=$Lang&amp;From=$From\"> <table cellspacing=\"20\" cellpadding=\"0\" style=\"margin: 2%; width:95%;\">"; if( @$_GET{'Accion'} == "CambioPWD" || @$_GET{'Accion'} == "ManPerfil" ) { $Block .= "<tr> <td>"; if( $Lang == 'en' ) $Block .= " <em>*</em> Your present password"; else $Block .= " <em>*</em> Tu Contrase&ntilde;a Ahora"; $Block .= " </td> <td> <input type=\"password\" name=\"PCur\" size=\"25\" maxlength=\"50\" /> </td> </tr>"; $Conn = mysqli_init(); mysqli_options($Conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5); mysqli_real_connect( $Conn, 'localhost', $ClaseRO, $AccessTypeRO, 'TianguisCabal', MYSQLI_CLIENT_SSL ); if( mysqli_connect_errno() ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2019&Lang=$Lang&From=$From" ); //No puedo connect exit(); } $Query = "select * from Vendedores where UserID = {$_SESSION{'UID'}}"; if( !$QueryRes = mysqli_query( $Conn, $Query ) ) { mysqli_close( $Conn ); header( "Location: MensajeError.php?Errno=2018&Lang=$Lang&From=$From" ); //No Puede select exit(); } $UIDRec = mysqli_fetch_Array( $QueryRes ); }
mdavid/Rx.NET
1cb2a97fde2c028f1810d4c86d968869efe3d892
Injection of v1.0.2838.0 redistributables
diff --git a/Net35/System.CoreEx.dll b/Net35/System.CoreEx.dll index 0226e73..b096ad9 100644 Binary files a/Net35/System.CoreEx.dll and b/Net35/System.CoreEx.dll differ diff --git a/Net35/System.Interactive.dll b/Net35/System.Interactive.dll index b6f8ddf..7edef6c 100644 Binary files a/Net35/System.Interactive.dll and b/Net35/System.Interactive.dll differ diff --git a/Net35/System.Linq.Async.dll b/Net35/System.Linq.Async.dll index 0afed5a..9160063 100644 Binary files a/Net35/System.Linq.Async.dll and b/Net35/System.Linq.Async.dll differ diff --git a/Net35/System.Observable.dll b/Net35/System.Observable.dll index 3933d99..dd06394 100644 Binary files a/Net35/System.Observable.dll and b/Net35/System.Observable.dll differ diff --git a/Net35/System.Reactive.ClientProfile.dll b/Net35/System.Reactive.ClientProfile.dll index efad06b..076d373 100644 Binary files a/Net35/System.Reactive.ClientProfile.dll and b/Net35/System.Reactive.ClientProfile.dll differ diff --git a/Net35/System.Reactive.ExtendedProfile.dll b/Net35/System.Reactive.ExtendedProfile.dll index a8cd1ef..4cebfcb 100644 Binary files a/Net35/System.Reactive.ExtendedProfile.dll and b/Net35/System.Reactive.ExtendedProfile.dll differ diff --git a/Net35/System.Reactive.Testing.dll b/Net35/System.Reactive.Testing.dll index 3ebb5a2..ea8a33f 100644 Binary files a/Net35/System.Reactive.Testing.dll and b/Net35/System.Reactive.Testing.dll differ diff --git a/Net35/System.Reactive.dll b/Net35/System.Reactive.dll index be23267..b1d7fa6 100644 Binary files a/Net35/System.Reactive.dll and b/Net35/System.Reactive.dll differ diff --git a/Net35/System.Threading.dll b/Net35/System.Threading.dll index 9c89a85..add01e0 100644 Binary files a/Net35/System.Threading.dll and b/Net35/System.Threading.dll differ diff --git a/Net35/redist.txt b/Net35/redist.txt index 69c9db7..c7972d8 100644 --- a/Net35/redist.txt +++ b/Net35/redist.txt @@ -1,7 +1,11 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -System.Observable.dll -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll -System.Threading.dll \ No newline at end of file +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Threading.dll +System.Linq.Async.dll +System.Reactive.Testing.dll +System.Reactive.ClientProfile.dll +System.Reactive.ExtendedProfile.dll diff --git a/Net4/System.CoreEx.dll b/Net4/System.CoreEx.dll index 8267bbc..766f0dd 100644 Binary files a/Net4/System.CoreEx.dll and b/Net4/System.CoreEx.dll differ diff --git a/Net4/System.Interactive.dll b/Net4/System.Interactive.dll index 554e3d6..da0132f 100644 Binary files a/Net4/System.Interactive.dll and b/Net4/System.Interactive.dll differ diff --git a/Net4/System.Linq.Async.dll b/Net4/System.Linq.Async.dll index cf0337c..e4958e0 100644 Binary files a/Net4/System.Linq.Async.dll and b/Net4/System.Linq.Async.dll differ diff --git a/Net4/System.Reactive.ClientProfile.dll b/Net4/System.Reactive.ClientProfile.dll index 1025e8c..2038ef4 100644 Binary files a/Net4/System.Reactive.ClientProfile.dll and b/Net4/System.Reactive.ClientProfile.dll differ diff --git a/Net4/System.Reactive.ExtendedProfile.dll b/Net4/System.Reactive.ExtendedProfile.dll index e6ef616..5d3fe58 100644 Binary files a/Net4/System.Reactive.ExtendedProfile.dll and b/Net4/System.Reactive.ExtendedProfile.dll differ diff --git a/Net4/System.Reactive.Testing.dll b/Net4/System.Reactive.Testing.dll index e5304f5..4548457 100644 Binary files a/Net4/System.Reactive.Testing.dll and b/Net4/System.Reactive.Testing.dll differ diff --git a/Net4/System.Reactive.dll b/Net4/System.Reactive.dll index fdc58dc..d0fb35d 100644 Binary files a/Net4/System.Reactive.dll and b/Net4/System.Reactive.dll differ diff --git a/Net4/redist.txt b/Net4/redist.txt index 5f39ea2..fcb9065 100644 --- a/Net4/redist.txt +++ b/Net4/redist.txt @@ -1,5 +1,9 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Linq.Async.dll +System.Reactive.Testing.dll +System.Reactive.ClientProfile.dll +System.Reactive.ExtendedProfile.dll diff --git a/RX_JS/RxJS.dll b/RX_JS/RxJS.dll deleted file mode 100644 index 0c58dfb..0000000 Binary files a/RX_JS/RxJS.dll and /dev/null differ diff --git a/RxJS/l2o.js b/RxJS/l2o.js new file mode 100755 index 0000000..7001e04 --- /dev/null +++ b/RxJS/l2o.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a;var b;var c=this;var d="Index out of range";var e="Sequence contains no elements.";var f="Invalid operation";if(typeof ProvideCustomL2ORootObject =="undefined")b=c.L2O={}; else b=ProvideCustomL2ORootObject();var g=function(){};var h=function(){return new Date().getTime();};var i=function(I,J){return I===J;};var j=function(I){return I;};var k=function(I){var J=[];for(var K=0;K<I.length;K++) J.push(I[K]);return J;};var l=b.Enumerable=function(I){this.GetEnumerator=I;};var m=l.Create=function(I){return new l(I);};var n=l.Return=function(I){return m(function(){var J=false;return H(function(){if(J)return false;J=true;return true;},function(){return I;},j);});};var o=l.Never=function(){return m(function(){return H(function(){while(true);},j,j);});};var p=l.Throw=function(I){return m(function(){return H(function(){throw I;},j,j);});};var q=l.Empty=function(){return m(function(){return H(function(){return false;},j,j);});};var r=l.FromArray=function(I){return m(function(){var J=0;var K;return H(function(){if(J<I.length){K=I[J++];return true;}return false;},function(){return K;},j);});};var s=l.Concat=function(){return r(arguments).SelectMany(j);};var t=l.If=function(I,J,K){if(elseSoure===a)K=q();return EnumerableEx.Defer(function(){return I()?J:K;});};var u=l.While=function(I,J){return A(J).TakeWhile(I).SelectMany(j);};var v=l.DoWhile=function(I,J){return I.Concat(u(J,I));};var w=l.Case=function(I,J,K){if(K===a)K=q();return B(function(){var L=J[I()];if(L===a)L=K;return L;});};var x=l.For=function(I,J){return I.Select(J).SelectMany(j);};var y=l.Let=function(I,J){return B(function(){return J(I);});};var z=l.Range=function(I,J){return m(function(){var K=I-1;var L=I+J-1;return H(function(){if(K<L){K++;return true;}else return false;},function(){return K;},j);});};var A=l.Repeat=function(I,J){return m(function(){var K=J;if(K===a)K=-1;return H(function(){if(K!=0){K--;return true;}else return false;},function(){return I;},j);});};var B=l.Defer=function(I){return m(function(){var J;return H(function(){if(J===a)J=I().GetEnumerator();return J.MoveNext();},function(){return J.GetCurrent();},function(){J.Dispose();});});};var C=l.Using=function(I,J){return B(function(){var K=I();return J(K).Finally(function(){K.Dispose();});});};var D=l.Generate=function(I,J,K,L){return m(function(){var M;var N;var O=false;return H(function(){if(!O){M=I;O=true;}else{M=K(M);if(!J(M))return false;}N=L(M);return true;},function(){return N;},j);});};var E=l.Catch=function(){var I=arguments;return m(function(){var J;var K=0;var L;return H(function(){while(K<I.length){if(L===a)L=I[K++].GetEnumerator();try{var M=L.MoveNext();if(M)J=L.GetCurrent();return M;}catch(N){L.Dispose();L=a;}}},function(){return J;},function(){if(L!==a)L.Dispose();});});};var F=l.OnErrorResumeNext=function(){var I=arguments;return m(function(){var J;var K=0;var L;return H(function(){while(K<I.length){if(L===a)L=I[K++].GetEnumerator();try{var M=L.MoveNext();if(M){J=L.GetCurrent();return true;}}catch(N){}L.Dispose();L=a;}return false;},function(){return J;},function(){if(L!==a)L.Dispose();});});};l.prototype={Select:function(I){var J=this;return m(function(){var K;var L=0;var M;return H(function(){if(M===a)M=J.GetEnumerator();if(!M.MoveNext())return false;K=I(M.GetCurrent(),L++);return true;},function(){return K;},function(){M.Dispose();});});},Where:function(I){var J=this;return m(function(){var K;var L=0;var M;return H(function(){if(M===a)M=J.GetEnumerator();while(true){if(!M.MoveNext())return false;K=M.GetCurrent();if(I(K,L++))return true;}},function(){return K;},function(){M.Dispose();});});},SelectMany:function(I){var J=this;return m(function(){var K;var L=0;var M;var N;return H(function(){if(M===a)M=J.GetEnumerator();while(true){if(N===a){if(!M.MoveNext())return false;N=I(M.GetCurrent()).GetEnumerator();}if(N.MoveNext()){K=N.GetCurrent();return true;}else{N.Dispose();N=a;}}},function(){return K;},function(){if(N!==a)N.Dispose();M.Dispose();});});},ForEach:function(I){var J=this.GetEnumerator();try{while(J.MoveNext())I(J.GetCurrent());}finally{J.Dispose();}},a:function(I,J){var K=k(J);K.unshift(this);return I.apply(undefined,K);},Concat:function(){return this.a(s,arguments);},Zip:function(I,J){var K=this;return m(function(){var L;var M;var N;return H(function(){if(L===a){L=K.GetEnumerator();M=I.GetEnumerator();}if(L.MoveNext()&&M.MoveNext()){N=J(L.GetCurrent(),M.GetCurrent());return true;}return false;},function(){return N;},function(){L.Dispose();M.Dispose();});});},Take:function(I){var J=this;return m(function(){var K;var L;var M=I;return H(function(){if(L===a)L=J.GetEnumerator();if(M==0)return false;if(!L.MoveNext()){M=0;return false;}M--;K=L.GetCurrent();return true;},function(){return K;},function(){L.Dispose();});});},TakeWhile:function(I){var J=this;return m(function(){var K;var L=0;var M;return H(function(){if(M===a)M=J.GetEnumerator();if(!M.MoveNext())return false;K=M.GetCurrent();if(!I(K,L++))return false;return true;},function(){return K;},function(){M.Dispose();});});},Skip:function(I){var J=this;return m(function(){var K;var L=false;var M;return H(function(){if(M===a)M=J.GetEnumerator();if(!L){for(var N=0;N<I;N++){if(!M.MoveNext())return false;}L=true;}if(!M.MoveNext())return false;K=M.GetCurrent();return true;},function(){return K;},function(){M.Dispose();});});},SkipWhile:function(I){var J=this;return m(function(){var K;var L=false;var M;return H(function(){if(M===a)M=J.GetEnumerator();if(!L){while(true){if(!M.MoveNext())return false;if(!I(M.GetCurrent())){K=M.GetCurrent();return true;}}L=true;}if(!M.MoveNext())return false;K=M.GetCurrent();return true;},function(){return K;},function(){M.Dispose();});});},Do:function(I){var J=this;return m(function(){var K;var L;return H(function(){if(L===a)L=J.GetEnumerator();if(!L.MoveNext())return false;K=L.GetCurrent();I(K);return true;},function(){return K;},function(){L.Dispose();});});},First:function(I){var J=this.GetEnumerator();while(J.MoveNext()){var K=J.GetCurrent();if(I===a||I(K))return K;}throw e;},FirstOrDefault:function(I){var J=this.GetEnumerator();while(J.MoveNext()){var K=J.GetCurrent();if(I===a||I(K))return K;}return a;},Last:function(I){var J=false;var K;var L=this.GetEnumerator();while(L.MoveNext()){var M=L.GetCurrent();if(I===a||I(M)){J=true;K=M;}}if(J)return K;throw e;},LastOrDefault:function(I){var J=false;var K;var L=this.GetEnumerator();while(L.MoveNext()){var M=L.GetCurrent();if(I===a||I(M)){J=true;K=M;}}if(J)return K;throw a;},Single:function(I){if(I)return this.Where(I).Single();var J=this.GetEnumerator();while(J.MoveNext()){var K=J.GetCurrent();if(J.MoveNext())throw f;return K;}throw e;},SingleOrDefault:function(I){if(I)return this.Where(I).Single();var J=this.GetEnumerator();while(J.MoveNext()){var K=J.GetCurrent();if(J.MoveNext())throw f;return K;}return a;},ElementAt:function(I){return this.Skip(I).First();},ElementAtOrDefault:function(I){return this.Skip(I).FirstOrDefault();},ToArray:function(){var I=[];var J=this.GetEnumerator();while(J.MoveNext())I.push(J.GetCurrent());J.Dispose();return I;},Reverse:function(){var I=[];var J=this.GetEnumerator();while(J.MoveNext())I.unshift(J.GetCurrent());J.Dispose();return r(I);},Finally:function(I){var J=this;return m(function(){var K=J.GetEnumerator();return H(function(){return K.MoveNext();},function(){return K.GetCurrent();},function(){K.Dispose();I();});});},Retry:function(I){var J=this;return m(function(){var K;var L;var M=I;if(M===a)M=-1;return H(function(){if(L===a)L=J.GetEnumerator();while(true)try{if(L.MoveNext()){K=L.GetCurrent();return true;}else return false;}catch(N){if(M--==0)throw N;}},function(){return K;},function(){L.Dispose();});});},StartWith:function(){return s(r(arguments),this);},DistinctUntilChanged:function(I,J){if(J===a)J=i;var K=this;return m(function(){var L;var M=0;var N;return H(function(){if(N===a)N=K.GetEnumerator();while(true){if(!N.MoveNext())return false;var O=N.GetCurrent();if(!i(L,O)){L=O;return true;}}},function(){return L;},function(){N.Dispose();});});},BufferWithCount:function(I){var J=this;return m(function(){var K;var L;return H(function(){if(L===a)L=J.GetEnumerator();K=[];for(var M=0;M<I;M++){if(!L.MoveNext())return M>0;K.push(L.GetCurrent());}return true;},function(){return K;},function(){L.Dispose();});});},SkipLast:function(I){var J=this;return m(function(){var K;var L;var M=[];return H(function(){if(L===a)L=J.GetEnumerator();while(true){if(!L.MoveNext())return false;M.push(L.GetCurrent());if(M.length>I){K=M.shift();return true;}}},function(){return K;},function(){L.Dispose();});});},TakeLast:function(I){var J=this;return m(function(){var K;var L;var M;return H(function(){if(L===a)L=J.GetEnumerator();if(M===a){M=[];while(L.MoveNext()){M.push(L.GetCurrent());if(M.length>I)M.shift();}}if(M.length==0)return false;K=M.shift();return true;},function(){return K;},function(){L.Dispose();});});},Repeat:function(I){var J=this;return A(0,I).SelectMany(function(){return J;});},Scan:function(I,J){var K=this;return B(function(){var L;var M=false;return K.Select(function(N){if(M)L=J(L,N); else{L=J(I,N);M=true;}return L;});});},Scan0:function(I,J){return this.Scan(I,J).StartWith(I);},Scan1:function(I){var J=this;return B(function(){var K;var L=false;return J.Select(function(M){if(L)K=I(K,M); else{K=M;L=true;}return K;});});}};var G=b.Enumerator=function(I,J,K){this.MoveNext=I;this.GetCurrent=J;this.Dispose=K;};var H=G.Create=function(I,J,K){var L=false;return new G(function(){if(L)return false;var M=I();if(!M){L=true;K();}return M;},J,function(){if(!L){K();L=true;}});};})(); \ No newline at end of file diff --git a/RX_JS/redist.txt b/RxJS/redist.txt old mode 100644 new mode 100755 similarity index 97% rename from RX_JS/redist.txt rename to RxJS/redist.txt index 3716934..bd07b53 --- a/RX_JS/redist.txt +++ b/RxJS/redist.txt @@ -1,3 +1,3 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -rx.js +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +rx.js diff --git a/RX_JS/rx.aggregates.js b/RxJS/rx.aggregates.js old mode 100644 new mode 100755 similarity index 99% rename from RX_JS/rx.aggregates.js rename to RxJS/rx.aggregates.js index 5e38f68..383eb32 --- a/RX_JS/rx.aggregates.js +++ b/RxJS/rx.aggregates.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c=undefined;var d=function(m,n){return m===n;};var e=function(m){return m;};var f=b.Observable;var g=f.prototype;var h="Sequence contains no elements.";var i=f.CreateWithDisposable;var j=Rx.Scheduler.CurrentThread;var k=function(m){if(m.length==0)throw h;return m[0];};g.Aggregate=function(m,n){return this.Scan0(m,n).Final();};g.Aggregate1=function(m){return this.Scan1(m).Final();};g.IsEmpty=function(){var m=this;return i(function(n){return m.Subscribe(function(){n.OnNext(false);n.OnCompleted();},function(o){n.OnError(o);},function(){n.OnNext(true);n.OnCompleted();});});};g.Any=function(m){if(m===c)return this.IsEmpty().Select(function(n){return !n;});return this.Where(m).Any();};g.All=function(m){if(m===c)m=e;return this.Where(function(n){return !m(n);}).IsEmpty();};g.Contains=function(m,n){if(n===c)n=d;return this.Where(function(o){return n(o,m);}).Any();};g.Count=function(){return this.Aggregate(0,function(m,n){return m+1;});};g.Sum=function(){return this.Aggregate(0,function(m,n){return m+n;});};g.Average=function(){return this.Scan({sum:0,count:0},function(m,n){return {sum:m.sum+n,count:m.count+1};}).Final().Select(function(m){return m.sum/m.count;});};g.Final=function(){var m=this;return i(function(n){var o;var p=false;return m.Subscribe(function(q){p=true;o=q;},function(q){n.OnError(q);},function(){if(!p)n.OnError(h);n.OnNext(o);n.OnCompleted();});});};var l=function(m,n,o){return i(function(p){var q=false;var r;var s=[];return m.Subscribe(function(t){var u;try{u=n(t);}catch(w){p.OnError(w);return;}var v=0;if(!q){q=true;r=u;}else try{v=o(u,r);}catch(w){p.OnError(w);return;}if(v>0){r=u;s=[];}if(v>=0)s.push(t);},function(t){p.OnError(t);},function(){p.OnNext(s);p.OnCompleted();});});};g.MinBy=function(m,n){if(m===c)m=e;var o;if(n===c)o=function(p,q){return q-p;}; else o=function(p,q){return n(p,q)*-1;};return l(this,m,o);};g.Min=function(m,n){return this.MinBy(m,n).Select(k);};g.MaxBy=function(m,n){if(m===c)m=e;if(n===c)n=function(o,p){return o-p;};return l(this,m,n);};g.Max=function(m,n){return this.MaxBy(m,n).Select(k);};})(); \ No newline at end of file diff --git a/RX_JS/rx.dojo.js b/RxJS/rx.dojo.js old mode 100644 new mode 100755 similarity index 96% rename from RX_JS/rx.dojo.js rename to RxJS/rx.dojo.js index e880bb9..954b979 --- a/RX_JS/rx.dojo.js +++ b/RxJS/rx.dojo.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=Rx.Observable.FromDojoEvent=function(b,c,d,e){return Rx.Observable.Create(function(f){var g=function(i){f.OnNext(i);};var h=dojo.connect(b,c,d,g,e);return function(){dojo.disconnect(h);};});};dojo.xhrGetAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrGet(c);return e;};dojo.xhrPostAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrPost(c);return e;};dojo.xhrPutAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrPut(c);return e;};dojo.xhrDeleteAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrDelete(c);return e;};dojo.Deferred.prototype.asObservable=function(){var b=new Rx.AsyncSubject();this.then(function(c){b.OnNext(c);b.OnCompleted();},function(c){b.OnError(c);});return b;};Rx.AsyncSubject.prototype.AsDeferred=function(){var b=new dojo.Deferred();this.Subscribe(function(c){b.callback(c);},function(c){b.errback(c);});return b;};})(); \ No newline at end of file diff --git a/RX_JS/rx.extjs.js b/RxJS/rx.extjs.js old mode 100644 new mode 100755 similarity index 94% rename from RX_JS/rx.extjs.js rename to RxJS/rx.extjs.js index f5d888a..3fc7111 --- a/RX_JS/rx.extjs.js +++ b/RxJS/rx.extjs.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a;if(typeof ProvideCustomRxRootObject =="undefined")a=this.Rx; else a=ProvideCustomRxRootObject();var b=a.Observable;var c=Ext;var d=function(e,f,g,h){return b.Create(function(i){var j=c.EventManager;var k=function(l){i.OnNext(l);};j.on(e,f,k,g,h);return function(){j.un(e,f,k,g);};});};c.Element.prototype.toObservable=function(e,f,g){return d(this,e,f,g);};c.util.Observable.prototype.toObservable=function(e,f,g){var h=this;return b.Create(function(i){var j=function(k){i.OnNext(k);};h.on(e,j,f,g);return function(){h.un(e,j,f);};});};c.Ajax.observableRequest=function(e){var f={};for(var g in e) f[g]=e[g];var h=new a.AsyncSubject();f.success=function(i,j){h.OnNext({response:i,options:j});h.OnCompleted();};f.failure=function(i,j){h.OnError({response:i,options:j});};c.Ajax.request(f);return h;};})(); \ No newline at end of file diff --git a/RX_JS/rx.google.language.js b/RxJS/rx.google.language.js old mode 100644 new mode 100755 similarity index 92% rename from RX_JS/rx.google.language.js rename to RxJS/rx.google.language.js index 1f54176..c6f5903 --- a/RX_JS/rx.google.language.js +++ b/RxJS/rx.google.language.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=google.language;var b=this;var c;if(typeof ProvideCustomRxRootObject =="undefined")c=b.Rx; else c=ProvideCustomRxRootObject();var d=c.AsyncSubject;a.detectAsObservable=function(e){var f=new d();var g=function(h){if(!h.error){f.OnNext(h);f.OnCompleted();}else f.OnError(h.error);};a.detect(e,g);return f;};a.translateAsObservable=function(e,f,g){var h=new d();var i=function(j){if(!j.error){h.OnNext(j);h.OnCompleted();}else h.OnError(j.error);};a.translate(e,f,g,i);return h;};})(); \ No newline at end of file diff --git a/RX_JS/rx.googlemaps.js b/RxJS/rx.googlemaps.js old mode 100644 new mode 100755 similarity index 97% rename from RX_JS/rx.googlemaps.js rename to RxJS/rx.googlemaps.js index 553f124..017418c --- a/RX_JS/rx.googlemaps.js +++ b/RxJS/rx.googlemaps.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=google.maps;var b=a.event;var c;var d=this;if(typeof ProvideCustomRxRootObject =="undefined")c=d.Rx; else c=ProvideCustomRxRootObject();var e=c.Observable;var f=e.Create;var g=c.AsyncSubject;b.addListenerAsObservable=function(h,i){return f(function(j){var k=b.addListener(h,i,function(l){j.OnNext(l);});return function(){b.removeListener(k);};});};b.addDomListenerAsObservable=function(h,i){return f(function(j){var k=b.addDomListener(h,i,function(l){j.OnNext(l);});return function(){b.removeListener(k);};});};a.ElevationService.prototype.getElevationAlongPathAsObservable=function(h){var i=new g();this.getElevationAlongPath(h,function(j,k){if(k!=a.ElevationStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.ElevationService.prototype.getElevationForLocationsAsObservable=function(h){var i=new g();this.getElevationForLocations(h,function(j,k){if(k!=a.ElevationStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.Geocoder.prototype.geocodeAsObservable=function(h){var i=new g();this.geocode(h,function(j,k){if(k!=a.GeocoderStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.DirectionsService.prototype.routeAsObservable=function(h){var i=new g();this.route(h,function(j,k){if(k!=a.DirectionsStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.StreetViewService.prototype.getPanoramaById=function(h){var i=new g();this.getPanoramaById(h,function(j,k){if(k!=a.StreetViewStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.StreetViewService.prototype.getPanoramaByLocation=function(h,i){var j=new g();this.getPanoramaByByLocation(h,i,function(k,l){if(l!=a.StreetViewStatus.OK)j.OnError(l); else{j.OnNext(k);j.OnCompleted();}});return j;};a.MVCArray.prototype.ToObservable=function(h){if(h===a)h=currentThreadScheduler;var i=this;return observableCreateWithDisposable(function(j){var k=0;return h.ScheduleRecursive(function(l){if(k<i.getLength()){j.OnNext(i.getAt(k));l();}else j.OnCompleted();});});};})(); \ No newline at end of file diff --git a/RX_JS/rx.html.js b/RxJS/rx.html.js old mode 100644 new mode 100755 similarity index 99% rename from RX_JS/rx.html.js rename to RxJS/rx.html.js index acdfb61..5e29d88 --- a/RX_JS/rx.html.js +++ b/RxJS/rx.html.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c=undefined;var d=b.Observable;var e=b.AsyncSubject;var f=d.Create;var g=function(j){var k={};for(var l in j) k[l]=j[l];return k;};var h=d.FromIEEvent=function(j,k){return f(function(l){var m=function(){l.OnNext(g(a.event));};j.attachEvent(k,m);return function(){j.detachEvent(k,m);};});};d.FromHtmlEvent=function(j,k){if(j.attachEvent!==c)return h(j,"on"+k); else return i(j,k);};var i=d.FromDOMEvent=function(j,k){return f(function(l){var m=function(n){l.OnNext(g(n));};j.addEventListener(k,m,false);return function(){j.removeEventListener(k,m,false);};});};d.XmlHttpRequest=function(j){if(typeof j =="string")j={Method:"GET",Url:j};var k=new e();try{var l=new XMLHttpRequest();if(j.Headers!==c){var m=j.Headers;for(var n in m) l.setRequestHeader(n,m[n]);}l.open(j.Method,j.Url,true,j.User,j.Password);l.onreadystatechange=function(){if(l.readyState==4){var p=l.status;if(p>=200&&p<300||p==0||p==""){k.OnNext(l);k.OnCompleted();}else k.OnError(l);}};l.send(j.Body);}catch(p){k.OnError(p);}var o=new b.RefCountDisposable(b.Disposable.Create(function(){if(l.readyState!=4){l.abort();k.OnError(l);}}));return d.CreateWithDisposable(function(p){return new b.CompositeDisposable(k.Subscribe(p),o.GetDisposable());});};})(); \ No newline at end of file diff --git a/RX_JS/rx.jQuery.js b/RxJS/rx.jQuery.js old mode 100644 new mode 100755 similarity index 99% rename from RX_JS/rx.jQuery.js rename to RxJS/rx.jQuery.js index 0432f6f..f4db7d9 --- a/RX_JS/rx.jQuery.js +++ b/RxJS/rx.jQuery.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=jQuery;var b=a.fn;var c=this;var d;if(typeof ProvideCustomRxRootObject =="undefined")d=c.Rx; else d=ProvideCustomRxRootObject();var e=d.Observable;var f=d.AsyncSubject;var g=e.Create;var h=d.Disposable.Empty;b.toObservable=function(j,k){var l=this;return g(function(m){var n=function(o){m.OnNext(o);};l.bind(j,k,n);return function(){l.unbind(j,n);};});};b.toLiveObservable=function(j,k){var l=this;return g(function(m){var n=function(o){m.OnNext(o);};l.live(j,k,n);return function(){l.die(j,n);};});};b.hideAsObservable=function(j){var k=new f();this.hide(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.showAsObservable=function(j){var k=new f();this.show(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.animateAsObservable=function(j,k,l){var m=new f();this.animate(j,k,l,function(){m.OnNext(this);m.OnCompleted();});return m;};b.fadeInAsObservable=function(j){var k=new f();this.fadeIn(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.fadeToAsObservable=function(j,k){var l=new f();this.fadeTo(j,k,function(){l.OnNext(this);l.OnCompleted();});return l;};b.fadeOutAsObservable=function(j){var k=new f();this.fadeOut(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.slideDownAsObservable=function(j){var k=new f();this.slideDown(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.slideUpAsObservable=function(j){var k=new f();this.slideUp(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.slideToggleAsObservable=function(j){var k=new f();this.slideToggle(j,function(){k.OnNext(this);k.OnCompleted();});return k;};var i=a.ajaxAsObservable=function(j){var k={};for(var l in j) k[l]=j[l];var m=new f();k.success=function(n,o,p){m.OnNext({data:n,textStatus:o,xmlHttpRequest:p});m.OnCompleted();};k.error=function(n,o,p){m.OnError({xmlHttpRequest:n,textStatus:o,errorThrown:p});};a.ajax(k);return m;};a.getJSONAsObservable=function(j,k){return i({url:j,dataType:"json",data:k});};a.getScriptAsObservable=function(j,k){return i({url:j,dataType:"script",data:k});};a.postAsObservable=function(j,k){return i({url:j,type:"POST",data:k});};b.loadAsObservable=function(j,k){var l=new f();var m=function(n,o,p){if(o==="error")l.OnError({response:n,status:o,xmlHttpRequest:p}); else{l.OnNext({response:n,status:o,xmlHttpRequest:p});l.OnCompleted();}};this.load(j,k,m);return l;};a.getScriptAsObservable=function(j){return i({url:j,dataType:"script"});};a.postAsObservable=function(j,k,l){return i({url:j,dataType:l,data:k,type:"POST"});};})(); \ No newline at end of file diff --git a/RX_JS/rx.joins.js b/RxJS/rx.joins.js old mode 100644 new mode 100755 similarity index 98% rename from RX_JS/rx.joins.js rename to RxJS/rx.joins.js index 1b9bed4..0082886 --- a/RX_JS/rx.joins.js +++ b/RxJS/rx.joins.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c;var d=b.Observable;var e=function(u,v){return u===v;};var f=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647];var g=3;var h="no such key";var i="duplicate key";var j=function(u,v){return v>0&&u/v<2;};var k=function(u){for(var v=0;v<f.length;v++){var w=f[v];if(!j(w,u))return w;}throw "map is too large";};var l=function(u,v){if(u===c)u=e;this.a=u;this.b=0;var w;if(v===c||v==0)w=c; else if(v<g)w=new Array(v); else w=new Array(k(v));this.c=w;};l.prototype={d:function(){return this.b;},e:function(u,v){var w=this.c;if(w===c)throw h; else if(this.b<g){for(var D=0;D<this.b;D++){var y=w[D];if(this.a(y.f,u)){y.g=v;return;}}throw h;}else{var z=w.length;var A=n(u);var B=1+A%(z-1);var C=A%z;for(var D=0;D<z;D++){var E=w[C];if(E===c)throw h; else{if(this.a(E.f,u)){E.g=v;return;}}C=(C+B)%z;}throw h;}},h:function(u,v){var w=this.c;if(w===c){this.c=w=new Array(1);w[0]={f:u,g:v};}else{var x=this.b;if(x+1<g){for(var E=0;E<x;E++){if(this.a(w[E].f,u))throw i;}if(x<w.length)w[x]={f:u,g:v}; else{var D=new Array(w.length*2);for(var E=0;E<x;E++) D[E]=w[E];D[x]={f:u,g:v};this.c=w=D;}}else if(x<g){var D=new Array(k(x+1));for(var E=0;E<x;E++) o(D,w[E].f,w[E].g);o(D,u,v);this.c=w=D;}else if(j(w.length,x+1)){var D=new Array(k(x+1));for(var E=0;E<w.length;E++){var F=w[E];if(F!==c)o(D,F.f,F.g);}o(D,u,v);this.c=w=D;}else o(w,u,v);}this.b++;},i:function(u){var v=this.c;var w=this.b;var x=this.a;if(v!==c)if(w<g)for(var D=0;D<w;D++){if(x(v[D].f,u))return {Key:v[D].f,Value:v[D].g};} else{var z=v.length;var A=n(u);var B=1+A%(z-1);var C=A%z;for(var D=0;D<v.length;D++){if(v[C]==null)break; else{if(x(v[C].f,u))return {Key:v[C].f,Value:v[C].g};}C=(C+B)%z;}}return c;},j:function(u){var v=this.i(u);if(v===c)throw h;return v.Value;},k:function(u){var v=this.i(u);return v!==c;},l:function(){var u=[];for(var v=0;v<this.c.length;v++){var w=this.c[v];if(w!==c)u.push(w.g);}return u;},m:function(){var u=[];for(var v=0;v<this.c.length;v++){var w=this.c[v];if(w!==c)u.push(w.f);}return u;},n:function(){var u=[];for(var v=0;v<this.c.length;v++){var w=this.c[v];if(w!==c)u.push(new {Key:w.f,Value:w.g});}return u;}};var m=0;var n=function(u){if(u===c)throw h;if(u.getHashCode!==c)return u.getHashCode();var v=17*m++;u.getHashCode=function(){return v;};return v;};var o=function(u,v,w,x){var y=u.length;var z=n(v);var A=1+z%(y-1);var B=z%y;for(var C=0;C<u.length;C++){if(u[B]==null){u[B]={f:v,g:w};return;}else{if(x(u[B].f,v))throw i;}B=(B+A)%y;}throw "map full";};var p=function(u,v){this.o=[];for(var w=0;w<u.length;w++) this.o.push(u[w]);if(v!==undefined)this.o.push(v);};p.prototype={And:function(u){return new p(this.o,u);},Then:function(u){return {o:this.o,p:u};}};d.prototype.And=function(u){return new p([this],u);};d.prototype.Then=function(u){return {o:[this],p:u};};d.Join=function(){var u=arguments;return d.CreateWithDisposable(function(v){var w=new l();var x=new b.List();var y=new b.Observer(function(E){v.OnNext(E);},function(E){var F=w.l();for(var G=0;G<F.length;G++) F[G].Dispose();v.OnError(E);},function(){v.OnCompleted();});try{for(var C=0;C<u.length;C++) (function(E){var F=u[E];var G;G=q(F,w,y,function(H){x.Remove(G);if(x.GetCount()==0)y.OnCompleted();});x.Add(G);})(C);}catch(E){return d.Throw(E).Subscribe(v);}var A=new b.CompositeDisposable();var B=w.l();for(var C=0;C<B.length;C++){var D=B[C];D.Subscribe();A.Add(D);}return A;});};var q=function(u,v,w,x){var y=function(D){w.OnError(D);};var z=[];for(var C=0;C<u.o.length;C++) z.push(r(v,u.o[C],y));var B=new s(z,w,u.p,function(){for(var D=0;D<z.length;D++) z[D].RemoveActivePlan(B);x();});for(var C=0;C<z.length;C++) z[C].addActivePlan(B);return B;};var r=function(u,v,w){var x=u.i(v);if(x===c){var y=new t(v,w);u.h(v,y);return y;}return x.Value;};var s=function(u,v,w,x){this.Match=function(){var y=[];var z=true;var A=false;for(var D=0;D<u.length;D++){if(u[D].queue.length==0){A=true;continue;}var C=u[D].queue[0];z&=C.Kind=="N";if(z)y.push(C.Value);}if(!z)x(); else if(A)return; else{for(var D=0;D<u.length;D++) u[D].queue.shift();var E;try{E=w.apply(null,y);}catch(F){v.OnError(F);return;}v.OnNext(E);}};};var t=function(u,v){this.queue=[];var w=new b.MutableDisposable();var x=false;var y=new b.List();var z=false;this.addActivePlan=function(A){y.Add(A);};this.Subscribe=function(){x=true;w.Replace(u.Materialize().Subscribe(this));};this.OnNext=function(A){if(!z){if(A.Kind=="E"){v(A.Value);return;}this.queue.push(A);var B=y.ToArray();for(var C=0;C<B.length;C++) B[C].Match();}};this.OnError=function(A){};this.OnCompleted=function(){};this.RemoveActivePlan=function(A){y.Remove(A);if(y.GetCount()==0)this.Dispose();};this.Dispose=function(){if(!z){z=true;w.Dispose();}};};})(); \ No newline at end of file diff --git a/RX_JS/rx.js b/RxJS/rx.js old mode 100644 new mode 100755 similarity index 70% rename from RX_JS/rx.js rename to RxJS/rx.js index 0afb241..ab0d09f --- a/RX_JS/rx.js +++ b/RxJS/rx.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - -(function(){var a;var b;var c=this;var d="Index out of range";if(typeof ProvideCustomRxRootObject =="undefined")b=c.Rx={}; else b=ProvideCustomRxRootObject();var e=function(){};var f=function(){return new Date().getTime();};var g=function(r0,s0){return r0===s0;};var h=function(r0){return r0;};var i=function(r0){return {Dispose:r0};};var j={Dispose:e};b.Disposable={Create:i,Empty:j};var k=b.BooleanDisposable=function(){var r0=false;this.GetIsDisposed=function(){return r0;};this.Dispose=function(){r0=true;};};var l=function(r0){var s0=false;r0.a++;this.Dispose=function(){var t0=false;if(!r0.b){if(!this.c){this.c=true;r0.a--;if(r0.a==0&&r0.d){r0.b=true;t0=true;}}}if(t0)r0.e.Dispose();};};var m=b.RefCountDisposable=function(r0){this.d=false;this.b=false;this.e=r0;this.a=0;this.Dispose=function(){var s0=false;if(!this.b){if(!this.d){this.d=true;if(this.a==0){this.b=true;s0=true;}}}if(s0)this.e.Dispose();};this.GetDisposable=function(){if(this.b)return j; else return new l(this);};};var n=b.CompositeDisposable=function(){var r0=new q();for(var s0=0;s0<arguments.length;s0++) r0.Add(arguments[s0]);var t0=false;this.GetCount=function(){return r0.GetCount();};this.Add=function(u0){if(!t0)r0.Add(u0); else u0.Dispose();};this.Remove=function(u0,v0){if(!t0){var w0=r0.Remove(u0);if(!v0&w0)u0.Dispose();}};this.Dispose=function(){if(!t0){t0=true;this.Clear();}};this.Clear=function(){for(var u0=0;u0<r0.GetCount();u0++) r0.GetItem(u0).Dispose();r0.Clear();};};var o=b.MutableDisposable=function(){var r0=false;var s0;this.Get=function(){return s0;},this.Replace=function(t0){if(r0&&t0!==a)t0.Dispose(); else{if(s0!==a)s0.Dispose();s0=t0;}};this.Dispose=function(){if(!r0){r0=true;if(s0!==a)s0.Dispose();}};};var p=function(r0){var s0=[];for(var t0=0;t0<r0.length;t0++) s0.push(r0[t0]);return s0;};var q=b.List=function(r0){var s0=[];var t0=0;var u0=r0!==a?r0:g;this.Add=function(v0){s0[t0]=v0;t0++;};this.RemoveAt=function(v0){if(v0<0||v0>=t0)throw d;if(v0==0){s0.shift();t0--;}else{s0.splice(v0,1);t0--;}};this.IndexOf=function(v0){for(var w0=0;w0<t0;w0++){if(u0(v0,s0[w0]))return w0;}return -1;};this.Remove=function(v0){var w0=this.IndexOf(v0);if(w0==-1)return false;this.RemoveAt(w0);return true;};this.Clear=function(){s0=[];t0=0;};this.GetCount=function(){return t0;};this.GetItem=function(v0){if(v0<0||v0>=t0)throw d;return s0[v0];};this.SetItem=function(v0,w0){if(v0<0||v0>=t0)throw d;s0[v0]=w0;};this.ToArray=function(){var v0=[];for(var w0=0;w0<this.GetCount();w0++) v0.push(this.GetItem(w0));return v0;};};var r=function(r0){if(r0===null)r0=g;this.f=r0;var s0=4;this.g=new Array(s0);this.h=0;};r.prototype.i=function(r0,s0){return this.f(this.g[r0],this.g[s0])<0;};r.prototype.j=function(r0){if(r0>=this.h||r0<0)return;var s0=r0-1>>1;if(s0<0||s0==r0)return;if(this.i(r0,s0)){var t0=this.g[r0];this.g[r0]=this.g[s0];this.g[s0]=t0;this.j(s0);}};r.prototype.k=function(r0){if(r0===a)r0=0;var s0=2*r0+1;var t0=2*r0+2;var u0=r0;if(s0<this.h&&this.i(s0,u0))u0=s0;if(t0<this.h&&this.i(t0,u0))u0=t0;if(u0!=r0){var v0=this.g[r0];this.g[r0]=this.g[u0];this.g[u0]=v0;this.k(u0);}};r.prototype.GetCount=function(){return this.h;};r.prototype.Peek=function(){if(this.h==0)throw "Heap is empty.";return this.g[0];};r.prototype.Dequeue=function(){var r0=this.Peek();this.g[0]=this.g[--this.h];delete this.g[this.h];this.k();return r0;};r.prototype.Enqueue=function(r0){var s0=this.h++;this.g[s0]=r0;this.j(s0);};var s=b.Scheduler=function(r0,s0,t0){this.Schedule=r0;this.ScheduleWithTime=s0;this.Now=t0;this.ScheduleRecursive=function(u0){var v0=this;var w0=new n();var x0;x0=function(){u0(function(){var y0=false;var z0=false;var A0;A0=v0.Schedule(function(){x0();if(y0)w0.Remove(A0); else z0=true;});if(!z0){w0.Add(A0);y0=true;}});};w0.Add(v0.Schedule(x0));return w0;};this.ScheduleRecursiveWithTime=function(u0,v0){var w0=this;var x0=new n();var y0;y0=function(){u0(function(z0){var A0=false;var B0=false;var C0;C0=w0.ScheduleWithTime(function(){y0();if(A0)x0.Remove(C0); else B0=true;},z0);if(!B0){x0.Add(C0);A0=true;}});};x0.Add(w0.ScheduleWithTime(y0,v0));return x0;};};var t=b.VirtualScheduler=function(r0,s0,t0,u0){var v0=new s(function(w0){return this.ScheduleWithTime(w0,0);},function(w0,x0){return this.ScheduleVirtual(w0,u0(x0));},function(){return t0(this.l);});v0.ScheduleVirtual=function(w0,x0){var y0=new k();var z0=s0(this.l,x0);var A0=function(){if(!y0.IsDisposed)w0();};var B0=new y(A0,z0);this.m.Enqueue(B0);return y0;};v0.Run=function(){while(this.m.GetCount()>0){var w0=this.m.Dequeue();this.l=w0.n;w0.o();}};v0.RunTo=function(w0){while(this.m.GetCount()>0&&this.f(this.m.Peek().n,w0)<=0){var x0=this.m.Dequeue();this.l=x0.n;x0.o();}};v0.GetTicks=function(){return this.l;};v0.l=0;v0.m=new r(function(w0,x0){return r0(w0.n,x0.n);});v0.f=r0;return v0;};var u=b.TestScheduler=function(){var r0=new t(function(s0,t0){return s0-t0;},function(s0,t0){return s0+t0;},function(s0){return new Date(s0);},function(s0){if(s0<=0)return 1;return s0;});return r0;};var v=new s(function(r0){return this.ScheduleWithTime(r0,0);},function(r0,s0){var t0=this.Now()+s0;var u0=new y(r0,t0);if(this.m===a){var v0=new w();try{this.m.Enqueue(u0);v0.p();}finally{v0.q();}}else this.m.Enqueue(u0);return u0.r();},f);v.s=function(r0){if(this.m===a){var s0=new w();try{r0();s0.p();}finally{s0.q();}}else r0();};s.CurrentThread=v;var w=function(){v.m=new r(function(r0,s0){try{return r0.n-s0.n;}catch(t0){debugger;}});this.q=function(){v.m=a;};this.p=function(){while(v.m.GetCount()>0){var r0=v.m.Dequeue();if(!r0.t()){while(r0.n-v.Now()>0);if(!r0.t())r0.o();}}};};var x=0;var y=function(r0,s0){this.u=x++;this.o=r0;this.n=s0;this.v=new k();this.t=function(){return this.v.GetIsDisposed();};this.r=function(){return this.v;};};var z=new s(function(r0){r0();return j;},function(r0,s0){while(this.Now<s0);r0();},f);s.Immediate=z;var A=new s(function(r0){var s0=c.setTimeout(r0,0);return i(function(){c.clearTimeout(s0);});},function(r0,s0){var t0=c.setTimeout(r0,s0);return i(function(){c.clearTimeout(t0);});},f);s.Timeout=A;var B=b.Observer=function(r0,s0,t0){this.OnNext=r0===a?e:r0;this.OnError=s0===a?function(u0){throw u0;}:s0;this.OnCompleted=t0===a?e:t0;this.AsObserver=function(){var u0=this;return new B(function(v0){u0.OnNext(v0);},function(v0){u0.OnError(v0);},function(){u0.OnCompleted();});};};var C=B.Create=function(r0,s0,t0){return new B(r0,s0,t0);};var D=b.Observable=function(r0){this.w=r0;};var E=D.CreateWithDisposable=function(r0){return new D(r0);};var F=D.Create=function(r0){return E(function(s0){return i(r0(s0));});};var G=function(){return this.Select(function(r0){return r0.Value;});};D.prototype={Subscribe:function(r0,s0,t0){var u0;if(arguments.length==0||arguments.length>1||typeof r0 =="function")u0=new B(r0,s0,t0); else u0=r0;return this.x(u0);},x:function(r0){var s0=false;var t0=new o();var u0=this;v.s(function(){var v0=new B(function(w0){if(!s0)r0.OnNext(w0);},function(w0){if(!s0){s0=true;t0.Dispose();r0.OnError(w0);}},function(){if(!s0){s0=true;t0.Dispose();r0.OnCompleted();}});t0.Replace(u0.w(v0));});return new n(t0,i(function(){s0=true;}));},Select:function(r0){var s0=this;return E(function(t0){var u0=0;return s0.Subscribe(new B(function(v0){var w0;try{w0=r0(v0,u0++);}catch(x0){t0.OnError(x0);return;}t0.OnNext(w0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Let:function(r0,s0){if(s0===a)return r0(this);var t0=this;return E(function(u0){var v0=s0();var w0;try{w0=r0(v0);}catch(A0){return L(A0).Subscribe(u0);}var x0=new o();var y0=new o();var z0=new n(y0,x0);x0.Replace(w0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){u0.OnError(A0);z0.Dispose();},function(){u0.OnCompleted();z0.Dispose();}));y0.Replace(t0.Subscribe(v0));return z0;});},MergeObservable:function(){var r0=this;return E(function(s0){var t0=false;var u0=new n();var v0=new o();u0.Add(v0);v0.Replace(r0.Subscribe(function(w0){var x0=new o();u0.Add(x0);x0.Replace(w0.Subscribe(function(y0){s0.OnNext(y0);},function(y0){s0.OnError(y0);},function(){u0.Remove(x0);if(u0.GetCount()==1&&t0)s0.OnCompleted();}));},function(w0){s0.OnError(w0);},function(){t0=true;if(u0.GetCount()==1)s0.OnCompleted();}));return u0;});},y:function(r0,s0){var t0=p(s0);t0.unshift(this);return r0(t0);},Concat:function(){return this.y(I,arguments);},Merge:function(){return this.y(H,arguments);},Catch:function(){return this.y(P,arguments);},OnErrorResumeNext:function(){return this.y(V,arguments);},Zip:function(r0,s0){var t0=this;return E(function(u0){var v0=false;var w0=[];var x0=[];var y0=false;var z0=false;var A0=new n();var B0=function(C0){A0.Dispose();w0=a;x0=a;u0.OnError(C0);};A0.Add(t0.Subscribe(function(C0){if(z0){u0.OnCompleted();return;}if(x0.length>0){var D0=x0.shift();var E0;try{E0=s0(C0,D0);}catch(F0){A0.Dispose();u0.OnError(F0);return;}u0.OnNext(E0);}else w0.push(C0);},B0,function(){if(z0){u0.OnCompleted();return;}y0=true;}));A0.Add(r0.Subscribe(function(C0){if(y0){u0.OnCompleted();return;}if(w0.length>0){var D0=w0.shift();var E0;try{E0=s0(D0,C0);}catch(F0){A0.Dispose();u0.OnError(F0);return;}u0.OnNext(E0);}else x0.push(C0);},B0,function(){if(y0){u0.OnCompleted();return;}z0=true;}));return A0;});},CombineLatest:function(r0,s0){var t0=this;return E(function(u0){var v0=false;var w0=false;var x0=false;var y0;var z0;var A0=false;var B0=false;var C0=new n();var D0=function(E0){C0.Dispose();u0.OnError(E0);};C0.Add(t0.Subscribe(function(E0){if(B0){u0.OnCompleted();return;}if(x0){var F0;try{F0=s0(E0,z0);}catch(G0){C0.Dispose();u0.OnError(G0);return;}u0.OnNext(F0);}y0=E0;w0=true;},D0,function(){if(B0){u0.OnCompleted();return;}A0=true;}));C0.Add(r0.Subscribe(function(E0){if(A0){u0.OnCompleted();return;}if(w0){var F0;try{F0=s0(y0,E0);}catch(G0){C0.Dispose();u0.OnError(G0);return;}u0.OnNext(F0);}z0=E0;x0=true;},D0,function(){if(A0){u0.OnCompleted();return;}B0=true;}));});},Switch:function(){var r0=this;return E(function(s0){var t0=false;var u0=new o();var v0=new o();v0.Replace(r0.Subscribe(function(w0){if(!t0){var x0=new o();x0.Replace(w0.Subscribe(function(y0){s0.OnNext(y0);},function(y0){v0.Dispose();u0.Dispose();s0.OnError(y0);},function(){u0.Replace(a);if(t0)s0.OnCompleted();}));u0.Replace(x0);}},function(w0){u0.Dispose();s0.OnError(w0);},function(){t0=true;if(u0.Get()===a)s0.OnCompleted();}));return new n(v0,u0);});},TakeUntil:function(r0){var s0=this;return E(function(t0){var u0=new n();u0.Add(r0.Subscribe(function(){t0.OnCompleted();u0.Dispose();},function(v0){t0.OnError(v0);},function(){}));u0.Add(s0.Subscribe(t0));return u0;});},SkipUntil:function(r0){var s0=this;return E(function(t0){var u0=true;var v0=new n();v0.Add(r0.Subscribe(function(){u0=false;},function(w0){t0.OnError(w0);},e));v0.Add(s0.Subscribe(new B(function(w0){if(!u0)t0.OnNext(w0);},function(w0){t0.OnError(w0);},function(){if(!u0)t0.OnCompleted();})));return v0;});},Scan1:function(r0){var s0=this;return O(function(){var t0;var u0=false;return s0.Select(function(v0){if(u0)t0=r0(t0,v0); else{t0=v0;u0=true;}return t0;});});},Scan:function(r0,s0){var t0=this;return O(function(){var u0;var v0=false;return t0.Select(function(w0){if(v0)u0=s0(u0,w0); else{u0=s0(r0,w0);v0=true;}return u0;});});},Scan0:function(r0,s0){var t0=this;return E(function(u0){var v0=r0;var w0=true;return t0.Subscribe(function(x0){if(w0){w0=false;u0.OnNext(v0);}try{v0=s0(v0,x0);}catch(y0){u0.OnError(y0);return;}u0.OnNext(v0);},function(x0){if(w0)u0.OnNext(v0);u0.OnError(x0);},function(){if(w0)u0.OnNext(v0);u0.OnCompleted();});});},Finally:function(r0){var s0=this;return F(function(t0){var u0=s0.Subscribe(t0);return function(){try{u0.Dispose();r0();}catch(v0){r0();throw v0;}};});},Do:function(r0,s0,t0){var u0;if(arguments.length==0||arguments.length>1||typeof r0 =="function")u0=new B(r0,s0!==a?s0:e,t0); else u0=r0;var v0=this;return E(function(w0){return v0.Subscribe(new B(function(x0){try{u0.OnNext(x0);}catch(y0){w0.OnError(y0);return;}w0.OnNext(x0);},function(x0){if(s0!==a)try{u0.OnError(x0);}catch(y0){w0.OnError(y0);return;}w0.OnError(x0);},function(){if(t0!==a)try{u0.OnCompleted();}catch(x0){w0.OnError(x0);return;}w0.OnCompleted();}));});},Where:function(r0){var s0=this;return E(function(t0){var u0=0;return s0.Subscribe(new B(function(v0){var w0=false;try{w0=r0(v0,u0++);}catch(x0){t0.OnError(x0);return;}if(w0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Take:function(r0,s0){if(s0===a)s0=z;var t0=this;return E(function(u0){if(r0<=0){t0.Subscribe().Dispose();return N(s0).Subscribe(u0);}var v0=r0;return t0.Subscribe(new B(function(w0){if(v0-->0){u0.OnNext(w0);if(v0==0)u0.OnCompleted();}},function(w0){u0.OnError(w0);},function(){u0.OnCompleted();}));});},GroupBy:function(r0,s0,t0){if(r0===a)r0=h;if(s0===a)s0=h;if(t0===a)t0=function(v0){return v0.toString();};var u0=this;return E(function(v0){var w0={};var x0=new o();var y0=new m(x0);x0.Replace(u0.Subscribe(function(z0){var A0;try{A0=r0(z0);}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}var B0=false;var C0;try{var D0=t0(A0);if(w0[D0]===a){C0=new i0();w0[D0]=C0;B0=true;}else C0=w0[D0];}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}if(B0){var E0=E(function(G0){return new n(y0.GetDisposable(),C0.Subscribe(G0));});E0.Key=A0;v0.OnNext(E0);}var F0;try{F0=s0(z0);}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}C0.OnNext(F0);},function(z0){for(var A0 in w0) w0[A0].OnError(z0);v0.OnError(z0);},function(){for(var z0 in w0) w0[z0].OnCompleted();v0.OnCompleted();}));return y0;});},TakeWhile:function(r0){var s0=this;return E(function(t0){var u0=true;return s0.Subscribe(new B(function(v0){if(u0){try{u0=r0(v0);}catch(w0){t0.OnError(w0);return;}if(u0)t0.OnNext(v0); else t0.OnCompleted();}},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},SkipWhile:function(r0){var s0=this;return E(function(t0){var u0=false;return s0.Subscribe(new B(function(v0){if(!u0)try{u0=!r0(v0);}catch(w0){t0.OnError(w0);return;}if(u0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Skip:function(r0){var s0=this;return E(function(t0){var u0=r0;return s0.Subscribe(new B(function(v0){if(u0--<=0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},SelectMany:function(r0){return this.Select(r0).MergeObservable();},TimeInterval:function(r0){if(r0===a)r0=z;var s0=this;return O(function(){var t0=r0.Now();return s0.Select(function(u0){var v0=r0.Now();var w0=v0-t0;t0=v0;return {Interval:w0,Value:u0};});});},RemoveInterval:G,Timestamp:function(r0){if(r0===a)r0=z;return this.Select(function(s0){return {Timestamp:r0.Now(),Value:s0};});},RemoveTimestamp:G,Materialize:function(){var r0=this;return E(function(s0){return r0.Subscribe(new B(function(t0){s0.OnNext(new h0("N",t0));},function(t0){s0.OnNext(new h0("E",t0));s0.OnCompleted();},function(){s0.OnNext(new h0("C"));s0.OnCompleted();}));});},Dematerialize:function(){return this.SelectMany(function(r0){return r0;});},AsObservable:function(){var r0=this;return E(function(s0){return r0.Subscribe(s0);});},Delay:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0=[];var w0=false;var x0=new o();var y0=t0.Materialize().Timestamp().Subscribe(function(z0){if(z0.Value.Kind=="E"){u0.OnError(z0.Value.Value);v0=[];if(w0)x0.Dispose();return;}v0.push({Timestamp:s0.Now()+r0,Value:z0.Value});if(!w0){x0.Replace(s0.ScheduleRecursiveWithTime(function(A0){var B0;do{B0=a;if(v0.length>0&&v0[0].Timestamp<=s0.Now())B0=v0.shift().Value;if(B0!==a)B0.Accept(u0);}while(B0!==a);if(v0.length>0){A0(Math.max(0,v0[0].Timestamp-s0.Now()));w0=true;}else w0=false;},r0));w0=true;}});return new n(y0,x0);});},Throttle:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0;var w0=false;var x0=new o();var y0=0;var z0=t0.Subscribe(function(A0){w0=true;v0=A0;y0++;var B0=y0;x0.Replace(s0.ScheduleWithTime(function(){if(w0&&y0==B0)u0.OnNext(v0);w0=false;},r0));},function(A0){x0.Dispose();u0.OnError(A0);w0=false;y0++;},function(){x0.Dispose();if(w0)u0.OnNext(v0);u0.OnCompleted();w0=false;y0++;});return new n(z0,x0);});},Timeout:function(r0,s0,t0){if(t0===a)t0=A;if(s0===a)s0=L("Timeout",t0);var u0=this;return E(function(v0){var w0=new o();var x0=new o();var y0=0;var z0=y0;var A0=false;x0.Replace(t0.ScheduleWithTime(function(){A0=y0==z0;if(A0)w0.Replace(s0.Subscribe(v0));},r0));w0.Replace(u0.Subscribe(function(B0){var C0=0;if(!A0){y0++;C0=y0;v0.OnNext(B0);x0.Replace(t0.ScheduleWithTime(function(){A0=y0==C0;if(A0)w0.Replace(s0.Subscribe(v0));},r0));}},function(B0){if(!A0){y0++;v0.OnError(B0);}},function(){if(!A0){y0++;v0.OnCompleted();}}));return new n(w0,x0);});},Sample:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0=false;var w0;var x0=false;var y0=new n();y0.Add(Y(r0,s0).Subscribe(function(z0){if(v0){u0.OnNext(w0);v0=false;}if(x0)u0.OnCompleted();},function(z0){u0.OnError(z0);},function(){u0.OnCompleted();}));y0.Add(t0.Subscribe(function(z0){v0=true;w0=z0;},function(z0){u0.OnError(z0);y0.Dispose();},function(){x0=true;}));return y0;});},Repeat:function(r0,s0){var t0=this;if(s0===a)s0=z;if(r0===a)r0=-1;return E(function(u0){var v0=r0;var w0=new o();var x0=new n(w0);var y0=function(z0){w0.Replace(t0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){u0.OnError(A0);},function(){if(v0>0){v0--;if(v0==0){u0.OnCompleted();return;}}z0();}));};x0.Add(s0.ScheduleRecursive(y0));return x0;});},Retry:function(r0,s0){var t0=this;if(s0===a)s0=z;if(r0===a)r0=-1;return E(function(u0){var v0=r0;var w0=new o();var x0=new n(w0);var y0=function(z0){w0.Replace(t0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){if(v0>0){v0--;if(v0==0){u0.OnError(A0);return;}}z0();},function(){u0.OnCompleted();}));};x0.Add(s0.ScheduleRecursive(y0));return x0;});},BufferWithTime:function(r0,s0,t0){if(t0===a)t0=A;if(s0===a)s0=r0;var u0=this;return E(function(v0){var w0=new q();var x0=t0.Now();var y0=function(){var C0=[];for(var D0=0;D0<w0.GetCount();D0++){var E0=w0.GetItem(D0);if(E0.Timestamp-x0>=0)C0.push(E0.Value);}return C0;};var z0=new n();var A0=function(C0){v0.OnError(C0);};var B0=function(){v0.OnNext(y0());v0.OnCompleted();};z0.Add(u0.Subscribe(function(C0){w0.Add({Value:C0,Timestamp:t0.Now()});},A0,B0));z0.Add(a0(r0,s0,t0).Subscribe(function(C0){var D0=y0();var E0=t0.Now()+s0-r0;while(w0.GetCount()>0&&w0.GetItem(0).Timestamp-E0<=0)w0.RemoveAt(0);v0.OnNext(D0);x0=E0;},A0,B0));return z0;});},BufferWithTimeOrCount:function(r0,s0,t0){if(t0===a)t0=A;var u0=this;return E(function(v0){var w0=0;var x0=new q();var y0=function(){v0.OnNext(x0.ToArray());x0.Clear();w0++;};var z0=new o();var A0;A0=function(C0){var D0=t0.ScheduleWithTime(function(){var E0=false;var F0=0;if(C0==w0){y0();F0=w0;E0=true;}if(E0)A0(F0);},r0);z0.Replace(D0);};A0(w0);var B0=u0.Subscribe(function(C0){var D0=false;var E0=0;x0.Add(C0);if(x0.GetCount()==s0){y0();E0=w0;D0=true;}if(D0)A0(E0);},function(C0){v0.OnError(C0);x0.Clear();},function(){v0.OnNext(x0.ToArray());w0++;v0.OnCompleted();x0.Clear();});return new n(B0,z0);});},BufferWithCount:function(r0,s0){if(s0===a)s0=r0;var t0=this;return E(function(u0){var v0=[];var w0=0;return t0.Subscribe(function(x0){if(w0==0)v0.push(x0); else w0--;var y0=v0.length;if(y0==r0){var z0=v0;v0=[];var A0=Math.min(s0,y0);for(var B0=A0;B0<y0;B0++) v0.push(z0[B0]);w0=Math.max(0,s0-r0);u0.OnNext(z0);}},function(x0){u0.OnError(x0);},function(){if(v0.length>0)u0.OnNext(v0);u0.OnCompleted();});});},StartWith:function(r0,s0){if(!(r0 instanceof Array))r0=[r0];if(s0===a)s0=z;var t0=this;return E(function(u0){var v0=new n();var w0=0;v0.Add(s0.ScheduleRecursive(function(x0){if(w0<r0.length){u0.OnNext(r0[w0]);w0++;x0();}else v0.Add(t0.Subscribe(u0));}));return v0;});},DistinctUntilChanged:function(r0,s0){if(r0===a)r0=h;if(s0===a)s0=g;var t0=this;return E(function(u0){var v0;var w0=false;return t0.Subscribe(function(x0){var y0;try{y0=r0(x0);}catch(A0){u0.OnError(A0);return;}var z0=false;if(w0)try{z0=s0(v0,y0);}catch(A0){u0.OnError(A0);return;}if(!w0||!z0){w0=true;v0=y0;u0.OnNext(x0);}},function(x0){u0.OnError(x0);},function(){u0.OnCompleted();});});},Publish:function(r0){if(r0===a)return new q0(this,new i0());var s0=this;return E(function(t0){var u0=new q0(s0,new i0());return new n(r0(u0).Subscribe(B),u0.Connect());});},Prune:function(r0,s0){if(s0===a)s0=z;if(r0===a)return new q0(this,new k0(s0));var t0=this;return E(function(u0){var v0=new q0(t0,new k0(s0));return new n(r0(v0).Subscribe(B),v0.Connect());});},Replay:function(r0,s0,t0,u0){if(u0===a)u0=v;if(r0===a)return new q0(this,new m0(s0,t0,u0));var v0=this;return E(function(w0){var x0=new q0(v0,new m0(s0,t0,u0));return new n(r0(x0).Subscribe(B),x0.Connect());});},SkipLast:function(r0){var s0=this;return E(function(t0){var u0=[];return s0.Subscribe(function(v0){u0.push(v0);if(u0.length>r0)t0.OnNext(u0.shift());},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();});});},TakeLast:function(r0){var s0=this;return E(function(t0){var u0=[];return s0.Subscribe(function(v0){u0.push(v0);if(u0.length>r0)u0.shift();},function(v0){t0.OnError(v0);},function(){while(u0.length>0)t0.OnNext(u0.shift());t0.OnCompleted();});});}};var H=D.Merge=function(r0,s0){if(s0===a)s0=z;return J(r0,s0).MergeObservable();};var I=D.Concat=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){if(v0<r0.length){var y0=r0[v0];v0++;u0.Replace(y0.Subscribe(function(z0){t0.OnNext(z0);},function(z0){t0.OnError(z0);},x0));}else t0.OnCompleted();});return new n(u0,w0);});};var J=D.FromArray=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=0;return s0.ScheduleRecursive(function(v0){if(u0<r0.length){t0.OnNext(r0[u0++]);v0();}else t0.OnCompleted();});});};var K=D.Return=function(r0,s0){if(s0===a)s0=z;return E(function(t0){return s0.Schedule(function(){t0.OnNext(r0);t0.OnCompleted();});});};var L=D.Throw=function(r0,s0){if(s0===a)s0=z;return E(function(t0){return s0.Schedule(function(){t0.OnError(r0);});});};var M=D.Never=function(){return E(function(r0){return j;});};var N=D.Empty=function(r0){if(r0===a)r0=z;return E(function(s0){return r0.Schedule(function(){s0.OnCompleted();});});};var O=D.Defer=function(r0){return E(function(s0){var t0;try{t0=r0();}catch(u0){s0.OnError(u0);return j;}return t0.Subscribe(s0);});};var P=D.Catch=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){var y0=r0[v0];v0++;u0.Replace(y0.Subscribe(function(z0){t0.OnNext(z0);},function(z0){if(v0<r0.length)x0(); else t0.OnError(z0);},function(){t0.OnCompleted();}));});return new n(u0,w0);});};var Q=D.Using=function(r0,s0){return E(function(t0){var u0;var v0=j;try{var w0=r0();if(w0!==a)v0=w0;u0=s0(w0);}catch(x0){return new n(Throw(x0).Subscribe(t0),v0);}return new n(u0.Subscribe(t0),v0);});};var R=D.Range=function(r0,s0,t0){if(t0===a)t0=z;var u0=r0+s0-1;return T(r0,function(v0){return v0<=u0;},function(v0){return v0+1;},h,t0);};var S=D.Repeat=function(r0,s0,t0){if(t0===a)t0=z;if(s0===a)s0=-1;var u0=s0;return E(function(v0){return t0.ScheduleRecursive(function(w0){v0.OnNext(r0);if(u0>0){u0--;if(u0==0){v0.OnCompleted();return;}}w0();});});};var T=D.Generate=function(r0,s0,t0,u0,v0){if(v0===a)v0=z;return E(function(w0){var x0=r0;var y0=true;return v0.ScheduleRecursive(function(z0){var A0=false;var B0;try{if(y0)y0=false; else x0=t0(x0);A0=s0(x0);if(A0)B0=u0(x0);}catch(C0){w0.OnError(C0);return;}if(A0){w0.OnNext(B0);z0();}else w0.OnCompleted();});});};var U=D.GenerateWithTime=function(r0,s0,t0,u0,v0,w0){if(w0===a)w0=A;return new E(function(x0){var y0=r0;var z0=true;var A0=false;var B0;var C0;return w0.ScheduleRecursiveWithTime(function(D0){if(A0)x0.OnNext(B0);try{if(z0)z0=false; else y0=t0(y0);A0=s0(y0);if(A0){B0=u0(y0);C0=v0(y0);}}catch(E0){x0.OnError(E0);return;}if(A0)D0(C0); else x0.OnCompleted();},0);});};var V=D.OnErrorResumeNext=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){if(v0<r0.length){var y0=r0[v0];v0++;u0.Replace(y0.Subscribe(function(z0){t0.OnNext(z0);},x0,x0));}else t0.OnCompleted();});return new n(u0,w0);});};var W=D.Amb=function(){var r0=arguments;return E(function(s0){var t0=new n();var u0=new o();u0.Replace(t0);var v0=false;for(var w0=0;w0<r0.length;w0++){var x0=r0[w0];var y0=new o();var z0=new B(function(A0){if(!v0){t0.Remove(this.z,true);t0.Dispose();u0.Replace(this.z);v0=true;}s0.OnNext(A0);},function(A0){s0.OnError(A0);u0.Dispose();},function(){s0.OnCompleted();u0.Dispose();});z0.z=y0;y0.Replace(x0.Subscribe(z0));t0.Add(y0);}return u0;});};var X=D.ForkJoin=function(){var r0=arguments;return E(function(s0){var t0=[];var u0=[];var v0=[];var w0=new n();for(var x0=0;x0<r0.length;x0++) (function(y0){w0.Add(r0[y0].Subscribe(function(z0){t0[y0]=true;v0[y0]=z0;},function(z0){s0.OnError(z0);},function(z0){if(!t0[y0]){s0.OnCompleted();v0=a;t0=a;return;}u0[y0]=true;var A0=true;for(var B0=0;B0<r0.length;B0++){if(!u0[B0])A0=false;}if(A0){s0.OnNext(v0);s0.OnCompleted();v0=a;u0=a;t0=a;}}));})(x0);return w0;});};var Y=D.Interval=function(r0,s0){return a0(r0,r0,s0);};var Z=function(r0){return Math.max(0,r0);};var a0=D.Timer=function(r0,s0,t0){if(t0===a)t0=A;if(r0===a)return M();if(r0 instanceof Date)return O(function(){return D.Timer(r0-new Date(),s0,t0);});var u0=Z(r0);if(s0===a)return E(function(w0){return t0.ScheduleWithTime(function(){w0.OnNext(0);w0.OnCompleted();},u0);});var v0=Z(s0);return E(function(w0){var x0=0;return t0.ScheduleRecursiveWithTime(function(y0){w0.OnNext(x0++);y0(v0);},u0);});};var b0=D.While=function(r0,s0){return E(function(t0){var u0=new o();var v0=new n(u0);v0.Add(z.ScheduleRecursive(function(w0){var x0;try{x0=r0();}catch(y0){t0.OnError(y0);return;}if(x0)u0.Replace(s0.Subscribe(function(y0){t0.OnNext(y0);},function(y0){t0.OnError(y0);},function(){w0();})); else t0.OnCompleted();}));return v0;});};var c0=D.If=function(r0,s0,t0){return O(function(){return r0()?s0:t0;});};var d0=D.DoWhile=function(r0,s0){return I([r0,b0(s0,r0)]);};var e0=D.Case=function(r0,s0,t0,u0){if(u0===a)u0=z;if(t0===a)t0=N(u0);return O(function(){var v0=s0[r0()];if(v0===a)v0=t0;return v0;});};var f0=D.For=function(r0,s0){return E(function(t0){var u0=new n();var v0=0;u0.Add(z.ScheduleRecursive(function(w0){if(v0<r0.length){var x0;try{x0=s0(r0[v0]);}catch(y0){t0.OnError(y0);return;}u0.Add(x0.Subscribe(function(y0){t0.OnNext(y0);},function(y0){t0.OnError(y0);},function(){v0++;w0();}));}else t0.OnCompleted();}));return u0;});};var g0=D.Let=function(r0,s0){return O(function(){return s0(r0);});};var h0=b.Notification=function(r0,s0){this.Kind=r0;this.Value=s0;this.toString=function(){return this.Kind+": "+this.Value;};this.Accept=function(t0){switch(this.Kind){case "N":t0.OnNext(this.Value);break;case "E":t0.OnError(this.Value);break;case "C":t0.OnCompleted();break;}return j;};this.w=function(t0){var u0=this.Accept(t0);if(r0=="N")t0.OnCompleted();return u0;};};h0.prototype=new D;var i0=b.Subject=function(){var r0=new q();var s0=false;this.OnNext=function(t0){if(!s0){var u0=r0.ToArray();for(var v0=0;v0<u0.length;v0++){var w0=u0[v0];w0.OnNext(t0);}}};this.OnError=function(t0){if(!s0){var u0=r0.ToArray();for(var v0=0;v0<u0.length;v0++){var w0=u0[v0];w0.OnError(t0);}s0=true;r0.Clear();}};this.OnCompleted=function(){if(!s0){var t0=r0.ToArray();for(var u0=0;u0<t0.length;u0++){var v0=t0[u0];v0.OnCompleted();}s0=true;r0.Clear();}};this.w=function(t0){if(!s0){r0.Add(t0);return i(function(){r0.Remove(t0);});}else return j;};};i0.prototype=new D;for(var j0 in B.prototype) i0.prototype[j0]=B.prototype[j0];var k0=b.AsyncSubject=function(r0){var s0=new q();var t0;var u0=false;if(r0===a)r0=z;this.OnNext=function(v0){if(!u0)t0=new h0("N",v0);};this.OnError=function(v0){if(!u0){t0=new h0("E",v0);var w0=s0.ToArray();for(var x0=0;x0<w0.length;x0++){var y0=w0[x0];if(y0!==a)y0.OnError(v0);}u0=true;s0.Clear();}};this.OnCompleted=function(){if(!u0){if(t0===a)t0=new h0("C");var v0=s0.ToArray();for(var w0=0;w0<v0.length;w0++){var x0=v0[w0];if(x0!==a)t0.w(x0);}u0=true;s0.Clear();}};this.w=function(v0){if(!u0){s0.Add(v0);return i(function(){s0.Remove(v0);});}else return r0.Schedule(function(){t0.w(v0);});};};k0.prototype=new i0;var l0=b.BehaviorSubject=function(r0,s0){var t0=new m0(1,-1,s0);t0.OnNext(r0);return t0;};var m0=b.ReplaySubject=function(r0,s0,t0){var u0=new q();var v0=new q();var w0=false;if(t0===a)t0=v;var x0=s0>0;var y0=function(z0,A0){v0.Add({Value:new h0(z0,A0),Timestamp:t0.Now()});};this.A=function(){if(r0!==a)while(v0.GetCount()>r0)v0.RemoveAt(0);if(x0)while(v0.GetCount()>0&&t0.Now()-v0.GetItem(0).Timestamp>s0)v0.RemoveAt(0);};this.OnNext=function(z0){if(!w0){var A0=u0.ToArray();for(var B0=0;B0<A0.length;B0++){var C0=A0[B0];C0.OnNext(z0);}y0("N",z0);}};this.OnError=function(z0){if(!w0){var A0=u0.ToArray();for(var B0=0;B0<A0.length;B0++){var C0=A0[B0];C0.OnError(z0);}w0=true;u0.Clear();y0("E",z0);}};this.OnCompleted=function(){if(!w0){var z0=u0.ToArray();for(var A0=0;A0<z0.length;A0++){var B0=z0[A0];B0.OnCompleted();}w0=true;u0.Clear();y0("C");}};this.w=function(z0){var A0=new n0(this,z0);var B0=new n(A0);var C0=this;B0.Add(t0.Schedule(function(){if(!A0.B){C0.A();for(var D0=0;D0<v0.GetCount();D0++) v0.GetItem(D0).Value.Accept(z0);u0.Add(z0);A0.C=true;}}));return B0;};this.D=function(z0){u0.Remove(z0);};};m0.prototype=new i0;var n0=function(r0,s0){this.E=r0;this.F=s0;this.C=false;this.B=false;this.Dispose=function(){if(this.C)this.E.D(this.F);this.B=true;};};var o0=D.ToAsync=function(r0,s0){if(s0===a)s0=A;return function(){var t0=new k0(s0);var u0=function(){var x0;try{x0=r0.apply(this,arguments);}catch(y0){t0.OnError(y0);return;}t0.OnNext(x0);t0.OnCompleted();};var v0=this;var w0=p(arguments);s0.Schedule(function(){u0.apply(v0,w0);});return t0;};};var p0=D.Start=function(r0,s0,t0,u0){if(t0===a)t0=[];return o0(r0,u0).apply(s0,t0);};var q0=b.ConnectableObservable=function(r0,s0){if(s0===a)s0=new i0();this.E=s0;this.G=r0;this.H=false;this.Connect=function(){var t0;var u0=false;if(!this.H){this.H=true;var v0=this;t0=new n(i(function(){v0.H=false;}));this.I=t0;t0.Add(r0.Subscribe(this.E));}return this.I;};this.w=function(t0){return this.E.Subscribe(t0);};this.RefCount=function(){var t0=0;var u0=this;var v0;return F(function(w0){var x0=false;t0++;x0=t0==1;var y0=u0.Subscribe(w0);if(x0)v0=u0.Connect();return function(){y0.Dispose();t0--;if(t0==0)v0.Dispose();};});};};q0.prototype=new D;})(); \ No newline at end of file +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a;var b;var c=this;var d="Index out of range";if(typeof ProvideCustomRxRootObject =="undefined")b=c.Rx={}; else b=ProvideCustomRxRootObject();var e=function(){};var f=function(){return new Date().getTime();};var g=function(r0,s0){return r0===s0;};var h=function(r0){return r0;};var i=function(r0){return {Dispose:r0};};var j={Dispose:e};b.Disposable={Create:i,Empty:j};var k=b.BooleanDisposable=function(){var r0=false;this.GetIsDisposed=function(){return r0;};this.Dispose=function(){r0=true;};};var l=function(r0){var s0=false;r0.a++;this.Dispose=function(){var t0=false;if(!r0.b){if(!this.c){this.c=true;r0.a--;if(r0.a==0&&r0.d){r0.b=true;t0=true;}}}if(t0)r0.e.Dispose();};};var m=b.RefCountDisposable=function(r0){this.d=false;this.b=false;this.e=r0;this.a=0;this.Dispose=function(){var s0=false;if(!this.b){if(!this.d){this.d=true;if(this.a==0){this.b=true;s0=true;}}}if(s0)this.e.Dispose();};this.GetDisposable=function(){if(this.b)return j; else return new l(this);};};var n=b.CompositeDisposable=function(){var r0=new q();for(var s0=0;s0<arguments.length;s0++) r0.Add(arguments[s0]);var t0=false;this.GetCount=function(){return r0.GetCount();};this.Add=function(u0){if(!t0)r0.Add(u0); else u0.Dispose();};this.Remove=function(u0,v0){if(!t0){var w0=r0.Remove(u0);if(!v0&w0)u0.Dispose();}};this.Dispose=function(){if(!t0){t0=true;this.Clear();}};this.Clear=function(){for(var u0=0;u0<r0.GetCount();u0++) r0.GetItem(u0).Dispose();r0.Clear();};};var o=b.MutableDisposable=function(){var r0=false;var s0;this.Get=function(){return s0;},this.Replace=function(t0){if(r0&&t0!==a)t0.Dispose(); else{if(s0!==a)s0.Dispose();s0=t0;}};this.Dispose=function(){if(!r0){r0=true;if(s0!==a)s0.Dispose();}};};var p=function(r0){var s0=[];for(var t0=0;t0<r0.length;t0++) s0.push(r0[t0]);return s0;};var q=b.List=function(r0){var s0=[];var t0=0;var u0=r0!==a?r0:g;this.Add=function(v0){s0[t0]=v0;t0++;};this.RemoveAt=function(v0){if(v0<0||v0>=t0)throw d;if(v0==0){s0.shift();t0--;}else{s0.splice(v0,1);t0--;}};this.IndexOf=function(v0){for(var w0=0;w0<t0;w0++){if(u0(v0,s0[w0]))return w0;}return -1;};this.Remove=function(v0){var w0=this.IndexOf(v0);if(w0==-1)return false;this.RemoveAt(w0);return true;};this.Clear=function(){s0=[];t0=0;};this.GetCount=function(){return t0;};this.GetItem=function(v0){if(v0<0||v0>=t0)throw d;return s0[v0];};this.SetItem=function(v0,w0){if(v0<0||v0>=t0)throw d;s0[v0]=w0;};this.ToArray=function(){var v0=[];for(var w0=0;w0<this.GetCount();w0++) v0.push(this.GetItem(w0));return v0;};};var r=function(r0){if(r0===null)r0=g;this.f=r0;var s0=4;this.g=new Array(s0);this.h=0;};r.prototype.i=function(r0,s0){return this.f(this.g[r0],this.g[s0])<0;};r.prototype.j=function(r0){if(r0>=this.h||r0<0)return;var s0=r0-1>>1;if(s0<0||s0==r0)return;if(this.i(r0,s0)){var t0=this.g[r0];this.g[r0]=this.g[s0];this.g[s0]=t0;this.j(s0);}};r.prototype.k=function(r0){if(r0===a)r0=0;var s0=2*r0+1;var t0=2*r0+2;var u0=r0;if(s0<this.h&&this.i(s0,u0))u0=s0;if(t0<this.h&&this.i(t0,u0))u0=t0;if(u0!=r0){var v0=this.g[r0];this.g[r0]=this.g[u0];this.g[u0]=v0;this.k(u0);}};r.prototype.GetCount=function(){return this.h;};r.prototype.Peek=function(){if(this.h==0)throw "Heap is empty.";return this.g[0];};r.prototype.Dequeue=function(){var r0=this.Peek();this.g[0]=this.g[--this.h];delete this.g[this.h];this.k();return r0;};r.prototype.Enqueue=function(r0){var s0=this.h++;this.g[s0]=r0;this.j(s0);};var s=b.Scheduler=function(r0,s0,t0){this.Schedule=r0;this.ScheduleWithTime=s0;this.Now=t0;this.ScheduleRecursive=function(u0){var v0=this;var w0=new n();var x0;x0=function(){u0(function(){var y0=false;var z0=false;var A0;A0=v0.Schedule(function(){x0();if(y0)w0.Remove(A0); else z0=true;});if(!z0){w0.Add(A0);y0=true;}});};w0.Add(v0.Schedule(x0));return w0;};this.ScheduleRecursiveWithTime=function(u0,v0){var w0=this;var x0=new n();var y0;y0=function(){u0(function(z0){var A0=false;var B0=false;var C0;C0=w0.ScheduleWithTime(function(){y0();if(A0)x0.Remove(C0); else B0=true;},z0);if(!B0){x0.Add(C0);A0=true;}});};x0.Add(w0.ScheduleWithTime(y0,v0));return x0;};};var t=b.VirtualScheduler=function(r0,s0,t0,u0){var v0=new s(function(w0){return this.ScheduleWithTime(w0,0);},function(w0,x0){return this.ScheduleVirtual(w0,u0(x0));},function(){return t0(this.l);});v0.ScheduleVirtual=function(w0,x0){var y0=new k();var z0=s0(this.l,x0);var A0=function(){if(!y0.IsDisposed)w0();};var B0=new y(A0,z0);this.m.Enqueue(B0);return y0;};v0.Run=function(){while(this.m.GetCount()>0){var w0=this.m.Dequeue();this.l=w0.n;w0.o();}};v0.RunTo=function(w0){while(this.m.GetCount()>0&&this.f(this.m.Peek().n,w0)<=0){var x0=this.m.Dequeue();this.l=x0.n;x0.o();}};v0.GetTicks=function(){return this.l;};v0.l=0;v0.m=new r(function(w0,x0){return r0(w0.n,x0.n);});v0.f=r0;return v0;};var u=b.TestScheduler=function(){var r0=new t(function(s0,t0){return s0-t0;},function(s0,t0){return s0+t0;},function(s0){return new Date(s0);},function(s0){if(s0<=0)return 1;return s0;});return r0;};var v=new s(function(r0){return this.ScheduleWithTime(r0,0);},function(r0,s0){var t0=this.Now()+s0;var u0=new y(r0,t0);if(this.m===a){var v0=new w();try{this.m.Enqueue(u0);v0.p();}finally{v0.q();}}else this.m.Enqueue(u0);return u0.r();},f);v.s=function(r0){if(this.m===a){var s0=new w();try{r0();s0.p();}finally{s0.q();}}else r0();};s.CurrentThread=v;var w=function(){v.m=new r(function(r0,s0){try{return r0.n-s0.n;}catch(t0){debugger;}});this.q=function(){v.m=a;};this.p=function(){while(v.m.GetCount()>0){var r0=v.m.Dequeue();if(!r0.t()){while(r0.n-v.Now()>0);if(!r0.t())r0.o();}}};};var x=0;var y=function(r0,s0){this.u=x++;this.o=r0;this.n=s0;this.v=new k();this.t=function(){return this.v.GetIsDisposed();};this.r=function(){return this.v;};};var z=new s(function(r0){r0();return j;},function(r0,s0){while(this.Now<s0);r0();},f);s.Immediate=z;var A=new s(function(r0){var s0=c.setTimeout(r0,0);return i(function(){c.clearTimeout(s0);});},function(r0,s0){var t0=c.setTimeout(r0,s0);return i(function(){c.clearTimeout(t0);});},f);s.Timeout=A;var B=b.Observer=function(r0,s0,t0){this.OnNext=r0===a?e:r0;this.OnError=s0===a?function(u0){throw u0;}:s0;this.OnCompleted=t0===a?e:t0;this.AsObserver=function(){var u0=this;return new B(function(v0){u0.OnNext(v0);},function(v0){u0.OnError(v0);},function(){u0.OnCompleted();});};};var C=B.Create=function(r0,s0,t0){return new B(r0,s0,t0);};var D=b.Observable=function(r0){this.w=r0;};var E=D.CreateWithDisposable=function(r0){return new D(r0);};var F=D.Create=function(r0){return E(function(s0){return i(r0(s0));});};var G=function(){return this.Select(function(r0){return r0.Value;});};D.prototype={Subscribe:function(r0,s0,t0){var u0;if(arguments.length==0||arguments.length>1||typeof r0 =="function")u0=new B(r0,s0,t0); else u0=r0;return this.x(u0);},x:function(r0){var s0=false;var t0=new o();var u0=this;v.s(function(){var v0=new B(function(w0){if(!s0)r0.OnNext(w0);},function(w0){if(!s0){s0=true;t0.Dispose();r0.OnError(w0);}},function(){if(!s0){s0=true;t0.Dispose();r0.OnCompleted();}});t0.Replace(u0.w(v0));});return new n(t0,i(function(){s0=true;}));},Select:function(r0){var s0=this;return E(function(t0){var u0=0;return s0.Subscribe(new B(function(v0){var w0;try{w0=r0(v0,u0++);}catch(x0){t0.OnError(x0);return;}t0.OnNext(w0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Let:function(r0,s0){if(s0===a)return r0(this);var t0=this;return E(function(u0){var v0=s0();var w0;try{w0=r0(v0);}catch(A0){return L(A0).Subscribe(u0);}var x0=new o();var y0=new o();var z0=new n(y0,x0);x0.Replace(w0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){u0.OnError(A0);z0.Dispose();},function(){u0.OnCompleted();z0.Dispose();}));y0.Replace(t0.Subscribe(v0));return z0;});},MergeObservable:function(){var r0=this;return E(function(s0){var t0=false;var u0=new n();var v0=new o();u0.Add(v0);v0.Replace(r0.Subscribe(function(w0){var x0=new o();u0.Add(x0);x0.Replace(w0.Subscribe(function(y0){s0.OnNext(y0);},function(y0){s0.OnError(y0);},function(){u0.Remove(x0);if(u0.GetCount()==1&&t0)s0.OnCompleted();}));},function(w0){s0.OnError(w0);},function(){t0=true;if(u0.GetCount()==1)s0.OnCompleted();}));return u0;});},y:function(r0,s0){var t0=p(s0);t0.unshift(this);return r0(t0);},Concat:function(){return this.y(I,arguments);},Merge:function(){return this.y(H,arguments);},Catch:function(){return this.y(P,arguments);},OnErrorResumeNext:function(){return this.y(V,arguments);},Zip:function(r0,s0){var t0=this;return E(function(u0){var v0=false;var w0=[];var x0=[];var y0=false;var z0=false;var A0=new n();var B0=function(C0){A0.Dispose();w0=a;x0=a;u0.OnError(C0);};A0.Add(t0.Subscribe(function(C0){if(z0){u0.OnCompleted();return;}if(x0.length>0){var D0=x0.shift();var E0;try{E0=s0(C0,D0);}catch(F0){A0.Dispose();u0.OnError(F0);return;}u0.OnNext(E0);}else w0.push(C0);},B0,function(){if(z0){u0.OnCompleted();return;}y0=true;}));A0.Add(r0.Subscribe(function(C0){if(y0){u0.OnCompleted();return;}if(w0.length>0){var D0=w0.shift();var E0;try{E0=s0(D0,C0);}catch(F0){A0.Dispose();u0.OnError(F0);return;}u0.OnNext(E0);}else x0.push(C0);},B0,function(){if(y0){u0.OnCompleted();return;}z0=true;}));return A0;});},CombineLatest:function(r0,s0){var t0=this;return E(function(u0){var v0=false;var w0=false;var x0=false;var y0;var z0;var A0=false;var B0=false;var C0=new n();var D0=function(E0){C0.Dispose();u0.OnError(E0);};C0.Add(t0.Subscribe(function(E0){if(B0){u0.OnCompleted();return;}if(x0){var F0;try{F0=s0(E0,z0);}catch(G0){C0.Dispose();u0.OnError(G0);return;}u0.OnNext(F0);}y0=E0;w0=true;},D0,function(){if(B0){u0.OnCompleted();return;}A0=true;}));C0.Add(r0.Subscribe(function(E0){if(A0){u0.OnCompleted();return;}if(w0){var F0;try{F0=s0(y0,E0);}catch(G0){C0.Dispose();u0.OnError(G0);return;}u0.OnNext(F0);}z0=E0;x0=true;},D0,function(){if(A0){u0.OnCompleted();return;}B0=true;}));});},Switch:function(){var r0=this;return E(function(s0){var t0=false;var u0=new o();var v0=new o();v0.Replace(r0.Subscribe(function(w0){if(!t0){var x0=new o();x0.Replace(w0.Subscribe(function(y0){s0.OnNext(y0);},function(y0){v0.Dispose();u0.Dispose();s0.OnError(y0);},function(){u0.Replace(a);if(t0)s0.OnCompleted();}));u0.Replace(x0);}},function(w0){u0.Dispose();s0.OnError(w0);},function(){t0=true;if(u0.Get()===a)s0.OnCompleted();}));return new n(v0,u0);});},TakeUntil:function(r0){var s0=this;return E(function(t0){var u0=new n();u0.Add(r0.Subscribe(function(){t0.OnCompleted();u0.Dispose();},function(v0){t0.OnError(v0);},function(){}));u0.Add(s0.Subscribe(t0));return u0;});},SkipUntil:function(r0){var s0=this;return E(function(t0){var u0=true;var v0=new n();v0.Add(r0.Subscribe(function(){u0=false;},function(w0){t0.OnError(w0);},e));v0.Add(s0.Subscribe(new B(function(w0){if(!u0)t0.OnNext(w0);},function(w0){t0.OnError(w0);},function(){if(!u0)t0.OnCompleted();})));return v0;});},Scan1:function(r0){var s0=this;return O(function(){var t0;var u0=false;return s0.Select(function(v0){if(u0)t0=r0(t0,v0); else{t0=v0;u0=true;}return t0;});});},Scan:function(r0,s0){var t0=this;return O(function(){var u0;var v0=false;return t0.Select(function(w0){if(v0)u0=s0(u0,w0); else{u0=s0(r0,w0);v0=true;}return u0;});});},Scan0:function(r0,s0){var t0=this;return E(function(u0){var v0=r0;var w0=true;return t0.Subscribe(function(x0){if(w0){w0=false;u0.OnNext(v0);}try{v0=s0(v0,x0);}catch(y0){u0.OnError(y0);return;}u0.OnNext(v0);},function(x0){if(w0)u0.OnNext(v0);u0.OnError(x0);},function(){if(w0)u0.OnNext(v0);u0.OnCompleted();});});},Finally:function(r0){var s0=this;return F(function(t0){var u0=s0.Subscribe(t0);return function(){try{u0.Dispose();r0();}catch(v0){r0();throw v0;}};});},Do:function(r0,s0,t0){var u0;if(arguments.length==0||arguments.length>1||typeof r0 =="function")u0=new B(r0,s0!==a?s0:e,t0); else u0=r0;var v0=this;return E(function(w0){return v0.Subscribe(new B(function(x0){try{u0.OnNext(x0);}catch(y0){w0.OnError(y0);return;}w0.OnNext(x0);},function(x0){if(s0!==a)try{u0.OnError(x0);}catch(y0){w0.OnError(y0);return;}w0.OnError(x0);},function(){if(t0!==a)try{u0.OnCompleted();}catch(x0){w0.OnError(x0);return;}w0.OnCompleted();}));});},Where:function(r0){var s0=this;return E(function(t0){var u0=0;return s0.Subscribe(new B(function(v0){var w0=false;try{w0=r0(v0,u0++);}catch(x0){t0.OnError(x0);return;}if(w0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Take:function(r0,s0){if(s0===a)s0=z;var t0=this;return E(function(u0){if(r0<=0){t0.Subscribe().Dispose();return N(s0).Subscribe(u0);}var v0=r0;return t0.Subscribe(new B(function(w0){if(v0-->0){u0.OnNext(w0);if(v0==0)u0.OnCompleted();}},function(w0){u0.OnError(w0);},function(){u0.OnCompleted();}));});},GroupBy:function(r0,s0,t0){if(r0===a)r0=h;if(s0===a)s0=h;if(t0===a)t0=function(v0){return v0.toString();};var u0=this;return E(function(v0){var w0={};var x0=new o();var y0=new m(x0);x0.Replace(u0.Subscribe(function(z0){var A0;try{A0=r0(z0);}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}var B0=false;var C0;try{var D0=t0(A0);if(w0[D0]===a){C0=new i0();w0[D0]=C0;B0=true;}else C0=w0[D0];}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}if(B0){var E0=E(function(G0){return new n(y0.GetDisposable(),C0.Subscribe(G0));});E0.Key=A0;v0.OnNext(E0);}var F0;try{F0=s0(z0);}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}C0.OnNext(F0);},function(z0){for(var A0 in w0) w0[A0].OnError(z0);v0.OnError(z0);},function(){for(var z0 in w0) w0[z0].OnCompleted();v0.OnCompleted();}));return y0;});},TakeWhile:function(r0){var s0=this;return E(function(t0){var u0=true;return s0.Subscribe(new B(function(v0){if(u0){try{u0=r0(v0);}catch(w0){t0.OnError(w0);return;}if(u0)t0.OnNext(v0); else t0.OnCompleted();}},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},SkipWhile:function(r0){var s0=this;return E(function(t0){var u0=false;return s0.Subscribe(new B(function(v0){if(!u0)try{u0=!r0(v0);}catch(w0){t0.OnError(w0);return;}if(u0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Skip:function(r0){var s0=this;return E(function(t0){var u0=r0;return s0.Subscribe(new B(function(v0){if(u0--<=0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},SelectMany:function(r0){return this.Select(r0).MergeObservable();},TimeInterval:function(r0){if(r0===a)r0=z;var s0=this;return O(function(){var t0=r0.Now();return s0.Select(function(u0){var v0=r0.Now();var w0=v0-t0;t0=v0;return {Interval:w0,Value:u0};});});},RemoveInterval:G,Timestamp:function(r0){if(r0===a)r0=z;return this.Select(function(s0){return {Timestamp:r0.Now(),Value:s0};});},RemoveTimestamp:G,Materialize:function(){var r0=this;return E(function(s0){return r0.Subscribe(new B(function(t0){s0.OnNext(new h0("N",t0));},function(t0){s0.OnNext(new h0("E",t0));s0.OnCompleted();},function(){s0.OnNext(new h0("C"));s0.OnCompleted();}));});},Dematerialize:function(){return this.SelectMany(function(r0){return r0;});},AsObservable:function(){var r0=this;return E(function(s0){return r0.Subscribe(s0);});},Delay:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0=[];var w0=false;var x0=new o();var y0=t0.Materialize().Timestamp().Subscribe(function(z0){if(z0.Value.Kind=="E"){u0.OnError(z0.Value.Value);v0=[];if(w0)x0.Dispose();return;}v0.push({Timestamp:s0.Now()+r0,Value:z0.Value});if(!w0){x0.Replace(s0.ScheduleRecursiveWithTime(function(A0){var B0;do{B0=a;if(v0.length>0&&v0[0].Timestamp<=s0.Now())B0=v0.shift().Value;if(B0!==a)B0.Accept(u0);}while(B0!==a);if(v0.length>0){A0(Math.max(0,v0[0].Timestamp-s0.Now()));w0=true;}else w0=false;},r0));w0=true;}});return new n(y0,x0);});},Throttle:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0;var w0=false;var x0=new o();var y0=0;var z0=t0.Subscribe(function(A0){w0=true;v0=A0;y0++;var B0=y0;x0.Replace(s0.ScheduleWithTime(function(){if(w0&&y0==B0)u0.OnNext(v0);w0=false;},r0));},function(A0){x0.Dispose();u0.OnError(A0);w0=false;y0++;},function(){x0.Dispose();if(w0)u0.OnNext(v0);u0.OnCompleted();w0=false;y0++;});return new n(z0,x0);});},Timeout:function(r0,s0,t0){if(t0===a)t0=A;if(s0===a)s0=L("Timeout",t0);var u0=this;return E(function(v0){var w0=new o();var x0=new o();var y0=0;var z0=y0;var A0=false;x0.Replace(t0.ScheduleWithTime(function(){A0=y0==z0;if(A0)w0.Replace(s0.Subscribe(v0));},r0));w0.Replace(u0.Subscribe(function(B0){var C0=0;if(!A0){y0++;C0=y0;v0.OnNext(B0);x0.Replace(t0.ScheduleWithTime(function(){A0=y0==C0;if(A0)w0.Replace(s0.Subscribe(v0));},r0));}},function(B0){if(!A0){y0++;v0.OnError(B0);}},function(){if(!A0){y0++;v0.OnCompleted();}}));return new n(w0,x0);});},Sample:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0=false;var w0;var x0=false;var y0=new n();y0.Add(Y(r0,s0).Subscribe(function(z0){if(v0){u0.OnNext(w0);v0=false;}if(x0)u0.OnCompleted();},function(z0){u0.OnError(z0);},function(){u0.OnCompleted();}));y0.Add(t0.Subscribe(function(z0){v0=true;w0=z0;},function(z0){u0.OnError(z0);y0.Dispose();},function(){x0=true;}));return y0;});},Repeat:function(r0,s0){var t0=this;if(s0===a)s0=z;if(r0===a)r0=-1;return E(function(u0){var v0=r0;var w0=new o();var x0=new n(w0);var y0=function(z0){w0.Replace(t0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){u0.OnError(A0);},function(){if(v0>0){v0--;if(v0==0){u0.OnCompleted();return;}}z0();}));};x0.Add(s0.ScheduleRecursive(y0));return x0;});},Retry:function(r0,s0){var t0=this;if(s0===a)s0=z;if(r0===a)r0=-1;return E(function(u0){var v0=r0;var w0=new o();var x0=new n(w0);var y0=function(z0){w0.Replace(t0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){if(v0>0){v0--;if(v0==0){u0.OnError(A0);return;}}z0();},function(){u0.OnCompleted();}));};x0.Add(s0.ScheduleRecursive(y0));return x0;});},BufferWithTime:function(r0,s0,t0){if(t0===a)t0=A;if(s0===a)s0=r0;var u0=this;return E(function(v0){var w0=new q();var x0=t0.Now();var y0=function(){var C0=[];for(var D0=0;D0<w0.GetCount();D0++){var E0=w0.GetItem(D0);if(E0.Timestamp-x0>=0)C0.push(E0.Value);}return C0;};var z0=new n();var A0=function(C0){v0.OnError(C0);};var B0=function(){v0.OnNext(y0());v0.OnCompleted();};z0.Add(u0.Subscribe(function(C0){w0.Add({Value:C0,Timestamp:t0.Now()});},A0,B0));z0.Add(a0(r0,s0,t0).Subscribe(function(C0){var D0=y0();var E0=t0.Now()+s0-r0;while(w0.GetCount()>0&&w0.GetItem(0).Timestamp-E0<=0)w0.RemoveAt(0);v0.OnNext(D0);x0=E0;},A0,B0));return z0;});},BufferWithTimeOrCount:function(r0,s0,t0){if(t0===a)t0=A;var u0=this;return E(function(v0){var w0=0;var x0=new q();var y0=function(){v0.OnNext(x0.ToArray());x0.Clear();w0++;};var z0=new o();var A0;A0=function(C0){var D0=t0.ScheduleWithTime(function(){var E0=false;var F0=0;if(C0==w0){y0();F0=w0;E0=true;}if(E0)A0(F0);},r0);z0.Replace(D0);};A0(w0);var B0=u0.Subscribe(function(C0){var D0=false;var E0=0;x0.Add(C0);if(x0.GetCount()==s0){y0();E0=w0;D0=true;}if(D0)A0(E0);},function(C0){v0.OnError(C0);x0.Clear();},function(){v0.OnNext(x0.ToArray());w0++;v0.OnCompleted();x0.Clear();});return new n(B0,z0);});},BufferWithCount:function(r0,s0){if(s0===a)s0=r0;var t0=this;return E(function(u0){var v0=[];var w0=0;return t0.Subscribe(function(x0){if(w0==0)v0.push(x0); else w0--;var y0=v0.length;if(y0==r0){var z0=v0;v0=[];var A0=Math.min(s0,y0);for(var B0=A0;B0<y0;B0++) v0.push(z0[B0]);w0=Math.max(0,s0-r0);u0.OnNext(z0);}},function(x0){u0.OnError(x0);},function(){if(v0.length>0)u0.OnNext(v0);u0.OnCompleted();});});},StartWith:function(r0,s0){if(!(r0 instanceof Array))r0=[r0];if(s0===a)s0=z;var t0=this;return E(function(u0){var v0=new n();var w0=0;v0.Add(s0.ScheduleRecursive(function(x0){if(w0<r0.length){u0.OnNext(r0[w0]);w0++;x0();}else v0.Add(t0.Subscribe(u0));}));return v0;});},DistinctUntilChanged:function(r0,s0){if(r0===a)r0=h;if(s0===a)s0=g;var t0=this;return E(function(u0){var v0;var w0=false;return t0.Subscribe(function(x0){var y0;try{y0=r0(x0);}catch(A0){u0.OnError(A0);return;}var z0=false;if(w0)try{z0=s0(v0,y0);}catch(A0){u0.OnError(A0);return;}if(!w0||!z0){w0=true;v0=y0;u0.OnNext(x0);}},function(x0){u0.OnError(x0);},function(){u0.OnCompleted();});});},Publish:function(r0){if(r0===a)return new q0(this,new i0());var s0=this;return E(function(t0){var u0=new q0(s0,new i0());return new n(r0(u0).Subscribe(B),u0.Connect());});},Prune:function(r0,s0){if(s0===a)s0=z;if(r0===a)return new q0(this,new k0(s0));var t0=this;return E(function(u0){var v0=new q0(t0,new k0(s0));return new n(r0(v0).Subscribe(B),v0.Connect());});},Replay:function(r0,s0,t0,u0){if(u0===a)u0=v;if(r0===a)return new q0(this,new m0(s0,t0,u0));var v0=this;return E(function(w0){var x0=new q0(v0,new m0(s0,t0,u0));return new n(r0(x0).Subscribe(B),x0.Connect());});},SkipLast:function(r0){var s0=this;return E(function(t0){var u0=[];return s0.Subscribe(function(v0){u0.push(v0);if(u0.length>r0)t0.OnNext(u0.shift());},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();});});},TakeLast:function(r0){var s0=this;return E(function(t0){var u0=[];return s0.Subscribe(function(v0){u0.push(v0);if(u0.length>r0)u0.shift();},function(v0){t0.OnError(v0);},function(){while(u0.length>0)t0.OnNext(u0.shift());t0.OnCompleted();});});}};var H=D.Merge=function(r0,s0){if(s0===a)s0=z;return J(r0,s0).MergeObservable();};var I=D.Concat=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){if(v0<r0.length){var y0=r0[v0];v0++;var z0=new o();u0.Replace(z0);z0.Replace(y0.Subscribe(function(A0){t0.OnNext(A0);},function(A0){t0.OnError(A0);},x0));}else t0.OnCompleted();});return new n(u0,w0);});};var J=D.FromArray=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=0;return s0.ScheduleRecursive(function(v0){if(u0<r0.length){t0.OnNext(r0[u0++]);v0();}else t0.OnCompleted();});});};var K=D.Return=function(r0,s0){if(s0===a)s0=z;return E(function(t0){return s0.Schedule(function(){t0.OnNext(r0);t0.OnCompleted();});});};var L=D.Throw=function(r0,s0){if(s0===a)s0=z;return E(function(t0){return s0.Schedule(function(){t0.OnError(r0);});});};var M=D.Never=function(){return E(function(r0){return j;});};var N=D.Empty=function(r0){if(r0===a)r0=z;return E(function(s0){return r0.Schedule(function(){s0.OnCompleted();});});};var O=D.Defer=function(r0){return E(function(s0){var t0;try{t0=r0();}catch(u0){s0.OnError(u0);return j;}return t0.Subscribe(s0);});};var P=D.Catch=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){var y0=r0[v0];v0++;var z0=new o();u0.Replace(z0);z0.Replace(y0.Subscribe(function(A0){t0.OnNext(A0);},function(A0){if(v0<r0.length)x0(); else t0.OnError(A0);},function(){t0.OnCompleted();}));});return new n(u0,w0);});};var Q=D.Using=function(r0,s0){return E(function(t0){var u0;var v0=j;try{var w0=r0();if(w0!==a)v0=w0;u0=s0(w0);}catch(x0){return new n(Throw(x0).Subscribe(t0),v0);}return new n(u0.Subscribe(t0),v0);});};var R=D.Range=function(r0,s0,t0){if(t0===a)t0=z;var u0=r0+s0-1;return T(r0,function(v0){return v0<=u0;},function(v0){return v0+1;},h,t0);};var S=D.Repeat=function(r0,s0,t0){if(t0===a)t0=z;if(s0===a)s0=-1;var u0=s0;return E(function(v0){return t0.ScheduleRecursive(function(w0){v0.OnNext(r0);if(u0>0){u0--;if(u0==0){v0.OnCompleted();return;}}w0();});});};var T=D.Generate=function(r0,s0,t0,u0,v0){if(v0===a)v0=z;return E(function(w0){var x0=r0;var y0=true;return v0.ScheduleRecursive(function(z0){var A0=false;var B0;try{if(y0)y0=false; else x0=t0(x0);A0=s0(x0);if(A0)B0=u0(x0);}catch(C0){w0.OnError(C0);return;}if(A0){w0.OnNext(B0);z0();}else w0.OnCompleted();});});};var U=D.GenerateWithTime=function(r0,s0,t0,u0,v0,w0){if(w0===a)w0=A;return new E(function(x0){var y0=r0;var z0=true;var A0=false;var B0;var C0;return w0.ScheduleRecursiveWithTime(function(D0){if(A0)x0.OnNext(B0);try{if(z0)z0=false; else y0=t0(y0);A0=s0(y0);if(A0){B0=u0(y0);C0=v0(y0);}}catch(E0){x0.OnError(E0);return;}if(A0)D0(C0); else x0.OnCompleted();},0);});};var V=D.OnErrorResumeNext=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){if(v0<r0.length){var y0=r0[v0];v0++;var z0=new o();u0.Replace(z0);z0.Replace(y0.Subscribe(function(A0){t0.OnNext(A0);},x0,x0));}else t0.OnCompleted();});return new n(u0,w0);});};var W=D.Amb=function(){var r0=arguments;return E(function(s0){var t0=new n();var u0=new o();u0.Replace(t0);var v0=false;for(var w0=0;w0<r0.length;w0++){var x0=r0[w0];var y0=new o();var z0=new B(function(A0){if(!v0){t0.Remove(this.z,true);t0.Dispose();u0.Replace(this.z);v0=true;}s0.OnNext(A0);},function(A0){s0.OnError(A0);u0.Dispose();},function(){s0.OnCompleted();u0.Dispose();});z0.z=y0;y0.Replace(x0.Subscribe(z0));t0.Add(y0);}return u0;});};var X=D.ForkJoin=function(){var r0=arguments;return E(function(s0){var t0=[];var u0=[];var v0=[];var w0=new n();for(var x0=0;x0<r0.length;x0++) (function(y0){w0.Add(r0[y0].Subscribe(function(z0){t0[y0]=true;v0[y0]=z0;},function(z0){s0.OnError(z0);},function(z0){if(!t0[y0]){s0.OnCompleted();v0=a;t0=a;return;}u0[y0]=true;var A0=true;for(var B0=0;B0<r0.length;B0++){if(!u0[B0])A0=false;}if(A0){s0.OnNext(v0);s0.OnCompleted();v0=a;u0=a;t0=a;}}));})(x0);return w0;});};var Y=D.Interval=function(r0,s0){return a0(r0,r0,s0);};var Z=function(r0){return Math.max(0,r0);};var a0=D.Timer=function(r0,s0,t0){if(t0===a)t0=A;if(r0===a)return M();if(r0 instanceof Date)return O(function(){return D.Timer(r0-new Date(),s0,t0);});var u0=Z(r0);if(s0===a)return E(function(w0){return t0.ScheduleWithTime(function(){w0.OnNext(0);w0.OnCompleted();},u0);});var v0=Z(s0);return E(function(w0){var x0=0;return t0.ScheduleRecursiveWithTime(function(y0){w0.OnNext(x0++);y0(v0);},u0);});};var b0=D.While=function(r0,s0){return E(function(t0){var u0=new o();var v0=new n(u0);v0.Add(z.ScheduleRecursive(function(w0){var x0;try{x0=r0();}catch(y0){t0.OnError(y0);return;}if(x0)u0.Replace(s0.Subscribe(function(y0){t0.OnNext(y0);},function(y0){t0.OnError(y0);},function(){w0();})); else t0.OnCompleted();}));return v0;});};var c0=D.If=function(r0,s0,t0){if(t0===a)t0=N();return O(function(){return r0()?s0:t0;});};var d0=D.DoWhile=function(r0,s0){return I([r0,b0(s0,r0)]);};var e0=D.Case=function(r0,s0,t0,u0){if(u0===a)u0=z;if(t0===a)t0=N(u0);return O(function(){var v0=s0[r0()];if(v0===a)v0=t0;return v0;});};var f0=D.For=function(r0,s0){return E(function(t0){var u0=new n();var v0=0;u0.Add(z.ScheduleRecursive(function(w0){if(v0<r0.length){var x0;try{x0=s0(r0[v0]);}catch(y0){t0.OnError(y0);return;}u0.Add(x0.Subscribe(function(y0){t0.OnNext(y0);},function(y0){t0.OnError(y0);},function(){v0++;w0();}));}else t0.OnCompleted();}));return u0;});};var g0=D.Let=function(r0,s0){return O(function(){return s0(r0);});};var h0=b.Notification=function(r0,s0){this.Kind=r0;this.Value=s0;this.toString=function(){return this.Kind+": "+this.Value;};this.Accept=function(t0){switch(this.Kind){case "N":t0.OnNext(this.Value);break;case "E":t0.OnError(this.Value);break;case "C":t0.OnCompleted();break;}return j;};this.w=function(t0){var u0=this.Accept(t0);if(r0=="N")t0.OnCompleted();return u0;};};h0.prototype=new D;var i0=b.Subject=function(){var r0=new q();var s0=false;this.OnNext=function(t0){if(!s0){var u0=r0.ToArray();for(var v0=0;v0<u0.length;v0++){var w0=u0[v0];w0.OnNext(t0);}}};this.OnError=function(t0){if(!s0){var u0=r0.ToArray();for(var v0=0;v0<u0.length;v0++){var w0=u0[v0];w0.OnError(t0);}s0=true;r0.Clear();}};this.OnCompleted=function(){if(!s0){var t0=r0.ToArray();for(var u0=0;u0<t0.length;u0++){var v0=t0[u0];v0.OnCompleted();}s0=true;r0.Clear();}};this.w=function(t0){if(!s0){r0.Add(t0);return i(function(){r0.Remove(t0);});}else return j;};};i0.prototype=new D;for(var j0 in B.prototype) i0.prototype[j0]=B.prototype[j0];var k0=b.AsyncSubject=function(r0){var s0=new q();var t0;var u0=false;if(r0===a)r0=z;this.OnNext=function(v0){if(!u0)t0=new h0("N",v0);};this.OnError=function(v0){if(!u0){t0=new h0("E",v0);var w0=s0.ToArray();for(var x0=0;x0<w0.length;x0++){var y0=w0[x0];if(y0!==a)y0.OnError(v0);}u0=true;s0.Clear();}};this.OnCompleted=function(){if(!u0){if(t0===a)t0=new h0("C");var v0=s0.ToArray();for(var w0=0;w0<v0.length;w0++){var x0=v0[w0];if(x0!==a)t0.w(x0);}u0=true;s0.Clear();}};this.w=function(v0){if(!u0){s0.Add(v0);return i(function(){s0.Remove(v0);});}else return r0.Schedule(function(){t0.w(v0);});};};k0.prototype=new i0;var l0=b.BehaviorSubject=function(r0,s0){var t0=new m0(1,-1,s0);t0.OnNext(r0);return t0;};var m0=b.ReplaySubject=function(r0,s0,t0){var u0=new q();var v0=new q();var w0=false;if(t0===a)t0=v;var x0=s0>0;var y0=function(z0,A0){v0.Add({Value:new h0(z0,A0),Timestamp:t0.Now()});};this.A=function(){if(r0!==a)while(v0.GetCount()>r0)v0.RemoveAt(0);if(x0)while(v0.GetCount()>0&&t0.Now()-v0.GetItem(0).Timestamp>s0)v0.RemoveAt(0);};this.OnNext=function(z0){if(!w0){var A0=u0.ToArray();for(var B0=0;B0<A0.length;B0++){var C0=A0[B0];C0.OnNext(z0);}y0("N",z0);}};this.OnError=function(z0){if(!w0){var A0=u0.ToArray();for(var B0=0;B0<A0.length;B0++){var C0=A0[B0];C0.OnError(z0);}w0=true;u0.Clear();y0("E",z0);}};this.OnCompleted=function(){if(!w0){var z0=u0.ToArray();for(var A0=0;A0<z0.length;A0++){var B0=z0[A0];B0.OnCompleted();}w0=true;u0.Clear();y0("C");}};this.w=function(z0){var A0=new n0(this,z0);var B0=new n(A0);var C0=this;B0.Add(t0.Schedule(function(){if(!A0.B){C0.A();for(var D0=0;D0<v0.GetCount();D0++) v0.GetItem(D0).Value.Accept(z0);u0.Add(z0);A0.C=true;}}));return B0;};this.D=function(z0){u0.Remove(z0);};};m0.prototype=new i0;var n0=function(r0,s0){this.E=r0;this.F=s0;this.C=false;this.B=false;this.Dispose=function(){if(this.C)this.E.D(this.F);this.B=true;};};var o0=D.ToAsync=function(r0,s0){if(s0===a)s0=A;return function(){var t0=new k0(s0);var u0=function(){var x0;try{x0=r0.apply(this,arguments);}catch(y0){t0.OnError(y0);return;}t0.OnNext(x0);t0.OnCompleted();};var v0=this;var w0=p(arguments);s0.Schedule(function(){u0.apply(v0,w0);});return t0;};};var p0=D.Start=function(r0,s0,t0,u0){if(t0===a)t0=[];return o0(r0,u0).apply(s0,t0);};var q0=b.ConnectableObservable=function(r0,s0){if(s0===a)s0=new i0();this.E=s0;this.G=r0;this.H=false;this.Connect=function(){var t0;var u0=false;if(!this.H){this.H=true;var v0=this;t0=new n(i(function(){v0.H=false;}));this.I=t0;t0.Add(r0.Subscribe(this.E));}return this.I;};this.w=function(t0){return this.E.Subscribe(t0);};this.RefCount=function(){var t0=0;var u0=this;var v0;return F(function(w0){var x0=false;t0++;x0=t0==1;var y0=u0.Subscribe(w0);if(x0)v0=u0.Connect();return function(){y0.Dispose();t0--;if(t0==0)v0.Dispose();};});};};q0.prototype=new D;})(); \ No newline at end of file diff --git a/RX_JS/rx.microsoft.translator.js b/RxJS/rx.microsoft.translator.js old mode 100644 new mode 100755 similarity index 98% rename from RX_JS/rx.microsoft.translator.js rename to RxJS/rx.microsoft.translator.js index 6ad9bca..7403ae4 --- a/RX_JS/rx.microsoft.translator.js +++ b/RxJS/rx.microsoft.translator.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=jQuery;var b=a.fn;var c=this;var d;var e;if(!c.Microsoft)d=c.Microsoft={}; else d=c.Microsoft;var f="http://api.microsofttranslator.com/V2/Ajax.svc/";var g=function(i){return i.data;};var h=d.Translator=function(i){this.addTranslation=function(j,k,l,m,n){return a.ajaxAsObservable({url:f+"AddTranslation",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,originalText:j,translatedText:k,from:l,to:m,user:n.user,rating:n.rating,contentType:n.contentType,category:n.category,uri:n.uri}}).Select(g);};this.addTranslationArray=function(j,k,l,m){var n=JSON.stringify(j);var o=JSON.stringify(m);return a.ajaxAsObservable({url:f+"AddTranslationArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,translations:n,from:k,to:l,options:o}}).Select(g);};this.breakSentences=function(j,k){return a.ajaxAsObservable({url:f+"BreakSentences",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,language:k}}).Select(g);};this.detect=function(j){return a.ajaxAsObservable({url:f+"Detect",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j}}).Select(g);};this.detectArray=function(j){var k=JSON.stringify(j);return a.ajaxAsObservable({url:f+"DetectArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,texts:k}}).Select(g);};this.getLanguageNames=function(j,k){var l=JSON.stringify(k);return a.ajaxAsObservable({url:f+"GetLanguageNames",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,locale:j,languageCodes:l}}).Select(g);};this.getLanguagesForSpeak=function(){return a.ajaxAsObservable({url:f+"GetLanguagesForSpeak",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i}}).Select(g);};this.getLanguagesForTranslate=function(){return a.ajaxAsObservable({url:f+"GetLanguagesForTranslate",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i}}).Select(g);};this.getTranslations=function(j,k,l,m,n){var o=JSON.stringify(n);return a.ajaxAsObservable({url:f+"GetTranslations",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,from:k,to:l,maxTranslations:m,options:o}}).Select(g);};this.getTranslationsArray=function(j,k,l,m,n){var o=JSON.stringify(j);var p=JSON.stringify(n);return a.ajaxAsObservable({url:f+"GetTranslationsArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,texts:o,from:k,to:l,maxTranslations:m,options:p}}).Select(g);};this.speak=function(j,k,l){if(l==null)l="audio/wav";return a.ajaxAsObservable({url:f+"Speak",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,language:k,format:l}}).Select(g);};this.translate=function(j,k,l){return a.ajaxAsObservable({url:f+"Translate",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,from:k,to:l}}).Select(g);};this.translateArray=function(j,k,l,m){var n=JSON.stringify(j);var o=JSON.stringify(m);return a.ajaxAsObservable({url:f+"TranslateArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,texts:n,from:k,to:l,options:o}}).Select(g);};};d.Translator.getAppIdToken=function(i,j,k,l){return a.ajaxAsObservable({url:f+"GetAppIdToken",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,minRatingRead:j,maxRatingRead:k,expireSeconds:l}}).Select(g);};})(); \ No newline at end of file diff --git a/RX_JS/rx.mootools.js b/RxJS/rx.mootools.js old mode 100644 new mode 100755 similarity index 98% rename from RX_JS/rx.mootools.js rename to RxJS/rx.mootools.js index 630b415..59cbafe --- a/RX_JS/rx.mootools.js +++ b/RxJS/rx.mootools.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a;if(typeof ProvideCustomRxRootObject =="undefined")a=this.Rx; else a=ProvideCustomRxRootObject();var b=a.Observable;var c=b.FromMooToolsEvent=function(f,g){return b.Create(function(h){var i=function(j){h.OnNext(j);};f.addEvent(g,i);return function(){f.removeEvent(g,i);};});};var d=function(f){return c(this,f);};Window.implement({addEventAsObservable:d});Document.implement({addEventAsObservable:d});Element.implement({addEventAsObservable:d});Elements.implement({addEventAsObservable:d});Events.implement({addEventAsObservable:d});var e=b.MooToolsRequest=function(f){var g=new a.AsyncSubject();var h=null;try{newOptions.onSuccess=function(j,k){g.OnNext({responseText:j,responseXML:k});g.OnCompleted();};newOptions.onFailure=function(j){g.OnError({kind:"failure",xhr:j});};newOptions.onException=function(j,k){g.OnError({kind:"exception",headerName:j,value:k});};h=new Request(newOptions);h.send();}catch(j){g.OnError(j);}var i=new a.RefCountDisposable(a.Disposable.Create(function(){if(h)h.cancel();}));return b.CreateWithDisposable(function(j){return new a.CompositeDisposable(g.Subscribe(j),i.GetDisposable());});};Request.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i,j){f.OnNext({responseXML:j,responseText:i});f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});b.MooToolsJSONRequest=function(f){var g=new a.AsyncSubject();var h=null;try{newOptions.onSuccess=function(j,k){g.OnNext({responseJSON:j,responseText:k});g.OnCompleted();};newOptions.onFailure=function(j){g.OnError({kind:"failure",xhr:j});};newOptions.onException=function(j,k){g.OnError({kind:"exception",headerName:j,value:k});};h=new Request(newOptions);h.send();}catch(j){g.OnError(j);}var i=new a.RefCountDisposable(a.Disposable.Create(function(){if(h)h.cancel();}));return b.CreateWithDisposable(function(j){return new a.CompositeDisposable(g.Subscribe(j),i.GetDisposable());});};Request.JSON.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i,j){f.OnNext({responseJSON:i,responseText:j});f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});b.MooToolsHTMLRequest=function(f){var g={};for(var h in f) g[h]=f[h];var i=new a.AsyncSubject();var j=null;try{g.onSuccess=function(l){i.OnNext(l);i.OnCompleted();};g.onFailure=function(l){i.OnError({kind:"failure",xhr:l});};g.onException=function(l,m){i.OnError({kind:"exception",headerName:l,value:m});};j=new Request.HTML(g);j.send();}catch(l){i.OnError(l);}var k=new a.RefCountDisposable(a.Disposable.Create(function(){if(j)j.cancel();}));return b.CreateWithDisposable(function(l){return new a.CompositeDisposable(i.Subscribe(l),k.GetDisposable());});};Request.HTML.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i){f.OnNext(i);f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});b.MooToolsJSONPRequest=function(f){var g=new a.AsyncSubject();var h=null;try{f.onSuccess=function(j){g.OnNext(j);g.OnCompleted();};f.onFailure=function(j){g.OnError({kind:"failure",xhr:j});};f.onException=function(j,k){g.OnError({kind:"exception",headerName:j,value:k});};h=new Request.JSONP(f);h.send();}catch(j){g.OnError(j);}var i=new a.RefCountDisposable(a.Disposable.Create(function(){if(h)h.cancel();}));return b.CreateWithDisposable(function(j){return new a.CompositeDisposable(g.Subscribe(j),i.GetDisposable());});};Request.JSONP.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i){f.OnNext(i);f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});})(); \ No newline at end of file diff --git a/RX_JS/rx.prototype.js b/RxJS/rx.prototype.js old mode 100644 new mode 100755 similarity index 97% rename from RX_JS/rx.prototype.js rename to RxJS/rx.prototype.js index 0400a33..dfe99f2 --- a/RX_JS/rx.prototype.js +++ b/RxJS/rx.prototype.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a;if(typeof ProvideCustomRxRootObject =="undefined")a=this.Rx; else a=ProvideCustomRxRootObject();var b=a.Observable;var c=function(d,e){return b.Create(function(f){var g=function(h){f.OnNext(h);};Element.observe(d,e,g);return function(){Element.stopObserving(d,e,g);};});};Element.addMethods({toObservable:function(d,e){return c(d,e);}});Ajax.observableRequest=function(d,e){var f={};for(var g in e) f[g]=e[g];var h=new a.AsyncSubject();f.onSuccess=function(j){h.OnNext(j);h.OnCompleted();};f.onFailure=function(j){h.OnError(j);};var i=new Ajax.Request(d,f);return h;};Enumerable.addMethods({toObservable:function(d){if(d===undefined)d=a.Scheduler.Immediate;return b.FromArray(this.toArray());}});})(); \ No newline at end of file diff --git a/RX_JS/rx.raphael.js b/RxJS/rx.raphael.js old mode 100644 new mode 100755 similarity index 92% rename from RX_JS/rx.raphael.js rename to RxJS/rx.raphael.js index 1b1226d..8871633 --- a/RX_JS/rx.raphael.js +++ b/RxJS/rx.raphael.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c=b.Observable;var d=c.Create;Raphael.el.toObservable=function(e){var f=this;return d(function(g){var h=function(i){g.OnNext(i);};f[e](h);return function(){f["un"+e](h);};});};Raphael.el.hoverAsObservable=function(e){var f=this;return d(function(g){var h=function(j){j=j||window.event;g.OnNext({hit:true,event:j});};var i=function(j){j=j||window.event;g.OnNext({hit:false,event:j});};f.hover(h,i);return function(){f.unhover(h,i);};});};})(); \ No newline at end of file diff --git a/RX_JS/rx.virtualearth.js b/RxJS/rx.virtualearth.js old mode 100644 new mode 100755 similarity index 98% rename from RX_JS/rx.virtualearth.js rename to RxJS/rx.virtualearth.js index 721c289..bf8b489 --- a/RX_JS/rx.virtualearth.js +++ b/RxJS/rx.virtualearth.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=VEMap;var b;var c=this;if(typeof ProvideCustomRxRootObject =="undefined")b=c.Rx; else b=ProvideCustomRxRootObject();var d=b.Observable;var e=d.Create;var f=b.AsyncSubject;a.prototype.ToObservable=function(g){var h=this;return e(function(i){var j=function(k){i.OnNext(k);};h.AttachEvent(g,j);return function(){h.DetachEvent(g,j);};});};a.prototype.FindAsObservable=function(g,h,i,j,k,l,m,n,o,p){var q=new f();this.Find(g,h,i,j,k,l,m,n,o,p,function(r,s,t,u,v){if(v)q.OnError(v); else{q.OnNext({ShapeLayer:r,FindResults:s,Places:t,HasMoreResults:u});q.OnCompleted();}});return q;};a.prototype.FindLocationsAsObservable=function(g){var h=new f();this.FindLocations(g,function(i){h.OnNext(i);h.OnCompleted();});return h;};a.prototype.GetDirectionsAsObservable=function(g,h){var i=new VERouteOptions();for(var j in h) i[j]=h[j];var k=new f();i.RouteCallback=function(l){k.OnNext(l);k.OnCompleted();};this.GetDirections(g,i);return k;};a.prototype.ImportShapeLayerDataAsObservable=function(g,h){var i=new f();this.ImportShapeLayerData(g,function(j){i.OnNext(j);i.OnCompleted();},h);return i;};})(); \ No newline at end of file diff --git a/RX_JS/rx.yui3.js b/RxJS/rx.yui3.js old mode 100644 new mode 100755 similarity index 99% rename from RX_JS/rx.yui3.js rename to RxJS/rx.yui3.js index c9f1448..4278e40 --- a/RX_JS/rx.yui3.js +++ b/RxJS/rx.yui3.js @@ -1,6 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// This code is licensed by Microsoft Corporation under the terms -// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. -// See http://go.microsoft.com/fwlink/?LinkId=186234. - +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + (function(){var a=Rx.Observable.YUI3Use=function(d){return Rx.Observable.CreateWithDisposable(function(e){var f=function(h){e.OnNext(h);};var g=YUI().use(d,f);return Rx.Disposable.Empty;});};var b=Rx.Observable.FromYUI3Event=function(d,e){return a("node-base").SelectMany(function(f){return Rx.Observable.Create(function(g){var h=function(i){g.OnNext(i);};f.on(e,h,d);return function(){f.detach(e,h,d);};});});};var c=Rx.Observable.FromYUI3IO=function(d,e){return a("io-base").SelectMany(function(f){var g={};for(var h in e) g[h]=e[h];var i=new Rx.AsyncSubject();g.on={success:function(j,k,l){i.OnNext({transactionid:j,response:k,arguments:l});i.OnCompleted();},failure:function(j,k,l){i.OnError({transactionid:j,response:k,arguments:l});}};f.io(d,g);return i;});};})(); \ No newline at end of file diff --git a/Rx_XNA31_XBOX360/System.CoreEx.dll b/Rx_XNA31_XBOX360/System.CoreEx.dll index 2c015c7..3e5cd62 100644 Binary files a/Rx_XNA31_XBOX360/System.CoreEx.dll and b/Rx_XNA31_XBOX360/System.CoreEx.dll differ diff --git a/Rx_XNA31_XBOX360/System.Interactive.dll b/Rx_XNA31_XBOX360/System.Interactive.dll index 2d5e064..7fc38fa 100644 Binary files a/Rx_XNA31_XBOX360/System.Interactive.dll and b/Rx_XNA31_XBOX360/System.Interactive.dll differ diff --git a/Rx_XNA31_XBOX360/System.Observable.dll b/Rx_XNA31_XBOX360/System.Observable.dll index f37ca32..be7ee0c 100644 Binary files a/Rx_XNA31_XBOX360/System.Observable.dll and b/Rx_XNA31_XBOX360/System.Observable.dll differ diff --git a/Rx_XNA31_XBOX360/System.Reactive.Testing.dll b/Rx_XNA31_XBOX360/System.Reactive.Testing.dll index 6f3c5c6..d2016be 100644 Binary files a/Rx_XNA31_XBOX360/System.Reactive.Testing.dll and b/Rx_XNA31_XBOX360/System.Reactive.Testing.dll differ diff --git a/Rx_XNA31_XBOX360/System.Reactive.dll b/Rx_XNA31_XBOX360/System.Reactive.dll index 143dede..a16701f 100644 Binary files a/Rx_XNA31_XBOX360/System.Reactive.dll and b/Rx_XNA31_XBOX360/System.Reactive.dll differ diff --git a/Rx_XNA31_XBOX360/redist.txt b/Rx_XNA31_XBOX360/redist.txt index ea05186..94ab8fc 100644 --- a/Rx_XNA31_XBOX360/redist.txt +++ b/Rx_XNA31_XBOX360/redist.txt @@ -1,6 +1,7 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -System.Observable.dll -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Reactive.Testing.dll diff --git a/Rx_XNA31_Zune/System.CoreEx.dll b/Rx_XNA31_Zune/System.CoreEx.dll index c299d7c..552bd46 100644 Binary files a/Rx_XNA31_Zune/System.CoreEx.dll and b/Rx_XNA31_Zune/System.CoreEx.dll differ diff --git a/Rx_XNA31_Zune/System.Interactive.dll b/Rx_XNA31_Zune/System.Interactive.dll index 2fc9074..40bbb26 100644 Binary files a/Rx_XNA31_Zune/System.Interactive.dll and b/Rx_XNA31_Zune/System.Interactive.dll differ diff --git a/Rx_XNA31_Zune/System.Observable.dll b/Rx_XNA31_Zune/System.Observable.dll index 0520a1c..ed7d84a 100644 Binary files a/Rx_XNA31_Zune/System.Observable.dll and b/Rx_XNA31_Zune/System.Observable.dll differ diff --git a/Rx_XNA31_Zune/System.Reactive.Testing.dll b/Rx_XNA31_Zune/System.Reactive.Testing.dll index 14580b9..118b874 100644 Binary files a/Rx_XNA31_Zune/System.Reactive.Testing.dll and b/Rx_XNA31_Zune/System.Reactive.Testing.dll differ diff --git a/Rx_XNA31_Zune/System.Reactive.dll b/Rx_XNA31_Zune/System.Reactive.dll index 77b5379..77ad4aa 100644 Binary files a/Rx_XNA31_Zune/System.Reactive.dll and b/Rx_XNA31_Zune/System.Reactive.dll differ diff --git a/Rx_XNA31_Zune/redist.txt b/Rx_XNA31_Zune/redist.txt index ea05186..94ab8fc 100644 --- a/Rx_XNA31_Zune/redist.txt +++ b/Rx_XNA31_Zune/redist.txt @@ -1,6 +1,7 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -System.Observable.dll -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Reactive.Testing.dll diff --git a/SL3/System.CoreEx.dll b/SL3/System.CoreEx.dll index 1c323d2..d5f8ca9 100644 Binary files a/SL3/System.CoreEx.dll and b/SL3/System.CoreEx.dll differ diff --git a/SL3/System.Interactive.dll b/SL3/System.Interactive.dll index 591134a..274b862 100644 Binary files a/SL3/System.Interactive.dll and b/SL3/System.Interactive.dll differ diff --git a/SL3/System.Observable.dll b/SL3/System.Observable.dll index 8dde4a8..7d20fca 100644 Binary files a/SL3/System.Observable.dll and b/SL3/System.Observable.dll differ diff --git a/SL3/System.Reactive.Testing.dll b/SL3/System.Reactive.Testing.dll index c09ea8b..1013fa5 100644 Binary files a/SL3/System.Reactive.Testing.dll and b/SL3/System.Reactive.Testing.dll differ diff --git a/SL3/System.Reactive.dll b/SL3/System.Reactive.dll index 5dc4bb5..d2910c7 100644 Binary files a/SL3/System.Reactive.dll and b/SL3/System.Reactive.dll differ diff --git a/SL3/redist.txt b/SL3/redist.txt index ea05186..057f2a3 100644 --- a/SL3/redist.txt +++ b/SL3/redist.txt @@ -1,6 +1,8 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -System.Observable.dll -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Reactive.Testing.dll + diff --git a/SL4/System.CoreEx.dll b/SL4/System.CoreEx.dll index f4567fe..bc2104a 100644 Binary files a/SL4/System.CoreEx.dll and b/SL4/System.CoreEx.dll differ diff --git a/SL4/System.Interactive.dll b/SL4/System.Interactive.dll index fd661ee..4381b8d 100644 Binary files a/SL4/System.Interactive.dll and b/SL4/System.Interactive.dll differ diff --git a/SL4/System.Observable.dll b/SL4/System.Observable.dll index 2468e20..4953480 100644 Binary files a/SL4/System.Observable.dll and b/SL4/System.Observable.dll differ diff --git a/SL4/System.Reactive.Testing.dll b/SL4/System.Reactive.Testing.dll index bd28500..ca28d2d 100644 Binary files a/SL4/System.Reactive.Testing.dll and b/SL4/System.Reactive.Testing.dll differ diff --git a/SL4/System.Reactive.dll b/SL4/System.Reactive.dll index 91659b7..638909e 100644 Binary files a/SL4/System.Reactive.dll and b/SL4/System.Reactive.dll differ diff --git a/SL4/redist.txt b/SL4/redist.txt index ea05186..94ab8fc 100644 --- a/SL4/redist.txt +++ b/SL4/redist.txt @@ -1,6 +1,7 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. - -System.Observable.dll -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Reactive.Testing.dll diff --git a/WP7/System.CoreEx.dll b/WP7/System.CoreEx.dll index e328f24..1808e41 100644 Binary files a/WP7/System.CoreEx.dll and b/WP7/System.CoreEx.dll differ diff --git a/WP7/System.Interactive.dll b/WP7/System.Interactive.dll index 9912e6b..2b5257c 100644 Binary files a/WP7/System.Interactive.dll and b/WP7/System.Interactive.dll differ diff --git a/WP7/System.Reactive.Testing.dll b/WP7/System.Reactive.Testing.dll index 9be7270..b84470b 100644 Binary files a/WP7/System.Reactive.Testing.dll and b/WP7/System.Reactive.Testing.dll differ diff --git a/WP7/System.Reactive.dll b/WP7/System.Reactive.dll index 1ce01c1..e5e451e 100644 Binary files a/WP7/System.Reactive.dll and b/WP7/System.Reactive.dll differ diff --git a/WP7/redist.txt b/WP7/redist.txt index 6c12c70..71d4c92 100644 --- a/WP7/redist.txt +++ b/WP7/redist.txt @@ -1,5 +1,6 @@ -The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License - -System.CoreEx.dll -System.Reactive.dll -System.Interactive.dll +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License + +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Reactive.Testing.dll
mdavid/Rx.NET
cc4dd1d616ceeb672f7078e3fe9ab999fea53337
Injection of the latest release of the Rx.NET framework redistributable files from 9.10.2010
diff --git a/Net35/System.CoreEx.dll b/Net35/System.CoreEx.dll new file mode 100644 index 0000000..3e72878 Binary files /dev/null and b/Net35/System.CoreEx.dll differ diff --git a/Net35/System.Interactive.dll b/Net35/System.Interactive.dll new file mode 100644 index 0000000..2c245d9 Binary files /dev/null and b/Net35/System.Interactive.dll differ diff --git a/Net35/System.Observable.dll b/Net35/System.Observable.dll new file mode 100644 index 0000000..7cdab10 Binary files /dev/null and b/Net35/System.Observable.dll differ diff --git a/Net35/System.Reactive.dll b/Net35/System.Reactive.dll new file mode 100644 index 0000000..1369ad8 Binary files /dev/null and b/Net35/System.Reactive.dll differ diff --git a/Net35/System.Threading.dll b/Net35/System.Threading.dll new file mode 100644 index 0000000..81f9be2 Binary files /dev/null and b/Net35/System.Threading.dll differ diff --git a/Net35/redist.txt b/Net35/redist.txt new file mode 100644 index 0000000..69c9db7 --- /dev/null +++ b/Net35/redist.txt @@ -0,0 +1,7 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll +System.Threading.dll \ No newline at end of file diff --git a/Net4/System.CoreEx.dll b/Net4/System.CoreEx.dll new file mode 100644 index 0000000..bfdf554 Binary files /dev/null and b/Net4/System.CoreEx.dll differ diff --git a/Net4/System.Interactive.dll b/Net4/System.Interactive.dll new file mode 100644 index 0000000..f2ce79c Binary files /dev/null and b/Net4/System.Interactive.dll differ diff --git a/Net4/System.Reactive.Testing.dll b/Net4/System.Reactive.Testing.dll new file mode 100644 index 0000000..bac0ef2 Binary files /dev/null and b/Net4/System.Reactive.Testing.dll differ diff --git a/Net4/System.Reactive.dll b/Net4/System.Reactive.dll new file mode 100644 index 0000000..c12da0b Binary files /dev/null and b/Net4/System.Reactive.dll differ diff --git a/Net4/redist.txt b/Net4/redist.txt new file mode 100644 index 0000000..5f39ea2 --- /dev/null +++ b/Net4/redist.txt @@ -0,0 +1,5 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll diff --git a/README b/README index e69de29..72a78aa 100644 --- a/README +++ b/README @@ -0,0 +1,14 @@ +From "DevLabs: Reactive Extensions for .NET (Rx)" at http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx + +About Rx +Rx is a library for composing asynchronous and event-based programs using observable collections. + +The “A” in “AJAX” stands for asynchronous, and indeed modern Web-based and Cloud-based applications are fundamentally asynchronous. In fact, Silverlight bans all blocking networking and threading operations. Asynchronous programming is by no means restricted to Web and Cloud scenarios, however. Traditional desktop applications also have to maintain responsiveness in the face of long latency IO operations and other expensive background tasks. + +Another common attribute of interactive applications, whether Web/Cloud or client-based, is that they are event-driven. The user interacts with the application via a GUI that receives event streams asynchronously from the mouse, keyboard, and other inputs. + +Rx is a superset of the standard LINQ sequence operators that exposes asynchronous and event-based computations as push-based, observable collections via the new .NET 4.0 interfaces IObservable<T> and IObserver<T>. These are the mathematical dual of the familiar IEnumerable<T> and IEnumerator<T> interfaces for pull-based, enumerable collections in the .NET Framework. + +The IEnumerable<T> and IEnumerator<T> interfaces allow developers to create reusable abstractions to consume and transform values from a wide range of concrete enumerable collections such as arrays, lists, database tables, and XML documents. Similarly, Rx allows programmers to glue together complex event processing and asynchronous computations using LINQ queries over observable collections such as .NET events and APM-based computations, PFx concurrent Task<T>, the Windows 7 Sensor and Location APIs, SQL StreamInsight temporal event streams, F# first-class events, and async workflows. + +Play with Rx, stress it, evaluate it, and tell us what you think. diff --git a/RX_JS/redist.txt b/RX_JS/redist.txt new file mode 100644 index 0000000..3716934 --- /dev/null +++ b/RX_JS/redist.txt @@ -0,0 +1,3 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +rx.js diff --git a/RX_JS/rx.aggregates.js b/RX_JS/rx.aggregates.js new file mode 100644 index 0000000..5e38f68 --- /dev/null +++ b/RX_JS/rx.aggregates.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c=undefined;var d=function(m,n){return m===n;};var e=function(m){return m;};var f=b.Observable;var g=f.prototype;var h="Sequence contains no elements.";var i=f.CreateWithDisposable;var j=Rx.Scheduler.CurrentThread;var k=function(m){if(m.length==0)throw h;return m[0];};g.Aggregate=function(m,n){return this.Scan0(m,n).Final();};g.Aggregate1=function(m){return this.Scan1(m).Final();};g.IsEmpty=function(){var m=this;return i(function(n){return m.Subscribe(function(){n.OnNext(false);n.OnCompleted();},function(o){n.OnError(o);},function(){n.OnNext(true);n.OnCompleted();});});};g.Any=function(m){if(m===c)return this.IsEmpty().Select(function(n){return !n;});return this.Where(m).Any();};g.All=function(m){if(m===c)m=e;return this.Where(function(n){return !m(n);}).IsEmpty();};g.Contains=function(m,n){if(n===c)n=d;return this.Where(function(o){return n(o,m);}).Any();};g.Count=function(){return this.Aggregate(0,function(m,n){return m+1;});};g.Sum=function(){return this.Aggregate(0,function(m,n){return m+n;});};g.Average=function(){return this.Scan({sum:0,count:0},function(m,n){return {sum:m.sum+n,count:m.count+1};}).Final().Select(function(m){return m.sum/m.count;});};g.Final=function(){var m=this;return i(function(n){var o;var p=false;return m.Subscribe(function(q){p=true;o=q;},function(q){n.OnError(q);},function(){if(!p)n.OnError(h);n.OnNext(o);n.OnCompleted();});});};var l=function(m,n,o){return i(function(p){var q=false;var r;var s=[];return m.Subscribe(function(t){var u;try{u=n(t);}catch(w){p.OnError(w);return;}var v=0;if(!q){q=true;r=u;}else try{v=o(u,r);}catch(w){p.OnError(w);return;}if(v>0){r=u;s=[];}if(v>=0)s.push(t);},function(t){p.OnError(t);},function(){p.OnNext(s);p.OnCompleted();});});};g.MinBy=function(m,n){if(m===c)m=e;var o;if(n===c)o=function(p,q){return q-p;}; else o=function(p,q){return n(p,q)*-1;};return l(this,m,o);};g.Min=function(m,n){return this.MinBy(m,n).Select(k);};g.MaxBy=function(m,n){if(m===c)m=e;if(n===c)n=function(o,p){return o-p;};return l(this,m,n);};g.Max=function(m,n){return this.MaxBy(m,n).Select(k);};})(); \ No newline at end of file diff --git a/RX_JS/rx.dojo.js b/RX_JS/rx.dojo.js new file mode 100644 index 0000000..e880bb9 --- /dev/null +++ b/RX_JS/rx.dojo.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=Rx.Observable.FromDojoEvent=function(b,c,d,e){return Rx.Observable.Create(function(f){var g=function(i){f.OnNext(i);};var h=dojo.connect(b,c,d,g,e);return function(){dojo.disconnect(h);};});};dojo.xhrGetAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrGet(c);return e;};dojo.xhrPostAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrPost(c);return e;};dojo.xhrPutAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrPut(c);return e;};dojo.xhrDeleteAsObservable=function(b){var c={};for(var d in b) c[d]=b[d];var e=new root.AsyncSubject();c.load=function(f,g){e.OnNext({data:f,ioArg:g});e.OnCompleted();};c.error=function(f,g){e.OnNext({error:f,ioArg:g});e.OnCompleted();};dojo.xhrDelete(c);return e;};dojo.Deferred.prototype.asObservable=function(){var b=new Rx.AsyncSubject();this.then(function(c){b.OnNext(c);b.OnCompleted();},function(c){b.OnError(c);});return b;};Rx.AsyncSubject.prototype.AsDeferred=function(){var b=new dojo.Deferred();this.Subscribe(function(c){b.callback(c);},function(c){b.errback(c);});return b;};})(); \ No newline at end of file diff --git a/RX_JS/rx.extjs.js b/RX_JS/rx.extjs.js new file mode 100644 index 0000000..f5d888a --- /dev/null +++ b/RX_JS/rx.extjs.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a;if(typeof ProvideCustomRxRootObject =="undefined")a=this.Rx; else a=ProvideCustomRxRootObject();var b=a.Observable;var c=Ext;var d=function(e,f,g,h){return b.Create(function(i){var j=c.EventManager;var k=function(l){i.OnNext(l);};j.on(e,f,k,g,h);return function(){j.un(e,f,k,g);};});};c.Element.prototype.toObservable=function(e,f,g){return d(this,e,f,g);};c.util.Observable.prototype.toObservable=function(e,f,g){var h=this;return b.Create(function(i){var j=function(k){i.OnNext(k);};h.on(e,j,f,g);return function(){h.un(e,j,f);};});};c.Ajax.observableRequest=function(e){var f={};for(var g in e) f[g]=e[g];var h=new a.AsyncSubject();f.success=function(i,j){h.OnNext({response:i,options:j});h.OnCompleted();};f.failure=function(i,j){h.OnError({response:i,options:j});};c.Ajax.request(f);return h;};})(); \ No newline at end of file diff --git a/RX_JS/rx.google.language.js b/RX_JS/rx.google.language.js new file mode 100644 index 0000000..1f54176 --- /dev/null +++ b/RX_JS/rx.google.language.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=google.language;var b=this;var c;if(typeof ProvideCustomRxRootObject =="undefined")c=b.Rx; else c=ProvideCustomRxRootObject();var d=c.AsyncSubject;a.detectAsObservable=function(e){var f=new d();var g=function(h){if(!h.error){f.OnNext(h);f.OnCompleted();}else f.OnError(h.error);};a.detect(e,g);return f;};a.translateAsObservable=function(e,f,g){var h=new d();var i=function(j){if(!j.error){h.OnNext(j);h.OnCompleted();}else h.OnError(j.error);};a.translate(e,f,g,i);return h;};})(); \ No newline at end of file diff --git a/RX_JS/rx.googlemaps.js b/RX_JS/rx.googlemaps.js new file mode 100644 index 0000000..553f124 --- /dev/null +++ b/RX_JS/rx.googlemaps.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=google.maps;var b=a.event;var c;var d=this;if(typeof ProvideCustomRxRootObject =="undefined")c=d.Rx; else c=ProvideCustomRxRootObject();var e=c.Observable;var f=e.Create;var g=c.AsyncSubject;b.addListenerAsObservable=function(h,i){return f(function(j){var k=b.addListener(h,i,function(l){j.OnNext(l);});return function(){b.removeListener(k);};});};b.addDomListenerAsObservable=function(h,i){return f(function(j){var k=b.addDomListener(h,i,function(l){j.OnNext(l);});return function(){b.removeListener(k);};});};a.ElevationService.prototype.getElevationAlongPathAsObservable=function(h){var i=new g();this.getElevationAlongPath(h,function(j,k){if(k!=a.ElevationStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.ElevationService.prototype.getElevationForLocationsAsObservable=function(h){var i=new g();this.getElevationForLocations(h,function(j,k){if(k!=a.ElevationStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.Geocoder.prototype.geocodeAsObservable=function(h){var i=new g();this.geocode(h,function(j,k){if(k!=a.GeocoderStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.DirectionsService.prototype.routeAsObservable=function(h){var i=new g();this.route(h,function(j,k){if(k!=a.DirectionsStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.StreetViewService.prototype.getPanoramaById=function(h){var i=new g();this.getPanoramaById(h,function(j,k){if(k!=a.StreetViewStatus.OK)i.OnError(k); else{i.OnNext(j);i.OnCompleted();}});return i;};a.StreetViewService.prototype.getPanoramaByLocation=function(h,i){var j=new g();this.getPanoramaByByLocation(h,i,function(k,l){if(l!=a.StreetViewStatus.OK)j.OnError(l); else{j.OnNext(k);j.OnCompleted();}});return j;};a.MVCArray.prototype.ToObservable=function(h){if(h===a)h=currentThreadScheduler;var i=this;return observableCreateWithDisposable(function(j){var k=0;return h.ScheduleRecursive(function(l){if(k<i.getLength()){j.OnNext(i.getAt(k));l();}else j.OnCompleted();});});};})(); \ No newline at end of file diff --git a/RX_JS/rx.html.js b/RX_JS/rx.html.js new file mode 100644 index 0000000..acdfb61 --- /dev/null +++ b/RX_JS/rx.html.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c=undefined;var d=b.Observable;var e=b.AsyncSubject;var f=d.Create;var g=function(j){var k={};for(var l in j) k[l]=j[l];return k;};var h=d.FromIEEvent=function(j,k){return f(function(l){var m=function(){l.OnNext(g(a.event));};j.attachEvent(k,m);return function(){j.detachEvent(k,m);};});};d.FromHtmlEvent=function(j,k){if(j.attachEvent!==c)return h(j,"on"+k); else return i(j,k);};var i=d.FromDOMEvent=function(j,k){return f(function(l){var m=function(n){l.OnNext(g(n));};j.addEventListener(k,m,false);return function(){j.removeEventListener(k,m,false);};});};d.XmlHttpRequest=function(j){if(typeof j =="string")j={Method:"GET",Url:j};var k=new e();try{var l=new XMLHttpRequest();if(j.Headers!==c){var m=j.Headers;for(var n in m) l.setRequestHeader(n,m[n]);}l.open(j.Method,j.Url,true,j.User,j.Password);l.onreadystatechange=function(){if(l.readyState==4){var p=l.status;if(p>=200&&p<300||p==0||p==""){k.OnNext(l);k.OnCompleted();}else k.OnError(l);}};l.send(j.Body);}catch(p){k.OnError(p);}var o=new b.RefCountDisposable(b.Disposable.Create(function(){if(l.readyState!=4){l.abort();k.OnError(l);}}));return d.CreateWithDisposable(function(p){return new b.CompositeDisposable(k.Subscribe(p),o.GetDisposable());});};})(); \ No newline at end of file diff --git a/RX_JS/rx.jQuery.js b/RX_JS/rx.jQuery.js new file mode 100644 index 0000000..0432f6f --- /dev/null +++ b/RX_JS/rx.jQuery.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=jQuery;var b=a.fn;var c=this;var d;if(typeof ProvideCustomRxRootObject =="undefined")d=c.Rx; else d=ProvideCustomRxRootObject();var e=d.Observable;var f=d.AsyncSubject;var g=e.Create;var h=d.Disposable.Empty;b.toObservable=function(j,k){var l=this;return g(function(m){var n=function(o){m.OnNext(o);};l.bind(j,k,n);return function(){l.unbind(j,n);};});};b.toLiveObservable=function(j,k){var l=this;return g(function(m){var n=function(o){m.OnNext(o);};l.live(j,k,n);return function(){l.die(j,n);};});};b.hideAsObservable=function(j){var k=new f();this.hide(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.showAsObservable=function(j){var k=new f();this.show(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.animateAsObservable=function(j,k,l){var m=new f();this.animate(j,k,l,function(){m.OnNext(this);m.OnCompleted();});return m;};b.fadeInAsObservable=function(j){var k=new f();this.fadeIn(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.fadeToAsObservable=function(j,k){var l=new f();this.fadeTo(j,k,function(){l.OnNext(this);l.OnCompleted();});return l;};b.fadeOutAsObservable=function(j){var k=new f();this.fadeOut(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.slideDownAsObservable=function(j){var k=new f();this.slideDown(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.slideUpAsObservable=function(j){var k=new f();this.slideUp(j,function(){k.OnNext(this);k.OnCompleted();});return k;};b.slideToggleAsObservable=function(j){var k=new f();this.slideToggle(j,function(){k.OnNext(this);k.OnCompleted();});return k;};var i=a.ajaxAsObservable=function(j){var k={};for(var l in j) k[l]=j[l];var m=new f();k.success=function(n,o,p){m.OnNext({data:n,textStatus:o,xmlHttpRequest:p});m.OnCompleted();};k.error=function(n,o,p){m.OnError({xmlHttpRequest:n,textStatus:o,errorThrown:p});};a.ajax(k);return m;};a.getJSONAsObservable=function(j,k){return i({url:j,dataType:"json",data:k});};a.getScriptAsObservable=function(j,k){return i({url:j,dataType:"script",data:k});};a.postAsObservable=function(j,k){return i({url:j,type:"POST",data:k});};b.loadAsObservable=function(j,k){var l=new f();var m=function(n,o,p){if(o==="error")l.OnError({response:n,status:o,xmlHttpRequest:p}); else{l.OnNext({response:n,status:o,xmlHttpRequest:p});l.OnCompleted();}};this.load(j,k,m);return l;};a.getScriptAsObservable=function(j){return i({url:j,dataType:"script"});};a.postAsObservable=function(j,k,l){return i({url:j,dataType:l,data:k,type:"POST"});};})(); \ No newline at end of file diff --git a/RX_JS/rx.joins.js b/RX_JS/rx.joins.js new file mode 100644 index 0000000..1b9bed4 --- /dev/null +++ b/RX_JS/rx.joins.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c;var d=b.Observable;var e=function(u,v){return u===v;};var f=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647];var g=3;var h="no such key";var i="duplicate key";var j=function(u,v){return v>0&&u/v<2;};var k=function(u){for(var v=0;v<f.length;v++){var w=f[v];if(!j(w,u))return w;}throw "map is too large";};var l=function(u,v){if(u===c)u=e;this.a=u;this.b=0;var w;if(v===c||v==0)w=c; else if(v<g)w=new Array(v); else w=new Array(k(v));this.c=w;};l.prototype={d:function(){return this.b;},e:function(u,v){var w=this.c;if(w===c)throw h; else if(this.b<g){for(var D=0;D<this.b;D++){var y=w[D];if(this.a(y.f,u)){y.g=v;return;}}throw h;}else{var z=w.length;var A=n(u);var B=1+A%(z-1);var C=A%z;for(var D=0;D<z;D++){var E=w[C];if(E===c)throw h; else{if(this.a(E.f,u)){E.g=v;return;}}C=(C+B)%z;}throw h;}},h:function(u,v){var w=this.c;if(w===c){this.c=w=new Array(1);w[0]={f:u,g:v};}else{var x=this.b;if(x+1<g){for(var E=0;E<x;E++){if(this.a(w[E].f,u))throw i;}if(x<w.length)w[x]={f:u,g:v}; else{var D=new Array(w.length*2);for(var E=0;E<x;E++) D[E]=w[E];D[x]={f:u,g:v};this.c=w=D;}}else if(x<g){var D=new Array(k(x+1));for(var E=0;E<x;E++) o(D,w[E].f,w[E].g);o(D,u,v);this.c=w=D;}else if(j(w.length,x+1)){var D=new Array(k(x+1));for(var E=0;E<w.length;E++){var F=w[E];if(F!==c)o(D,F.f,F.g);}o(D,u,v);this.c=w=D;}else o(w,u,v);}this.b++;},i:function(u){var v=this.c;var w=this.b;var x=this.a;if(v!==c)if(w<g)for(var D=0;D<w;D++){if(x(v[D].f,u))return {Key:v[D].f,Value:v[D].g};} else{var z=v.length;var A=n(u);var B=1+A%(z-1);var C=A%z;for(var D=0;D<v.length;D++){if(v[C]==null)break; else{if(x(v[C].f,u))return {Key:v[C].f,Value:v[C].g};}C=(C+B)%z;}}return c;},j:function(u){var v=this.i(u);if(v===c)throw h;return v.Value;},k:function(u){var v=this.i(u);return v!==c;},l:function(){var u=[];for(var v=0;v<this.c.length;v++){var w=this.c[v];if(w!==c)u.push(w.g);}return u;},m:function(){var u=[];for(var v=0;v<this.c.length;v++){var w=this.c[v];if(w!==c)u.push(w.f);}return u;},n:function(){var u=[];for(var v=0;v<this.c.length;v++){var w=this.c[v];if(w!==c)u.push(new {Key:w.f,Value:w.g});}return u;}};var m=0;var n=function(u){if(u===c)throw h;if(u.getHashCode!==c)return u.getHashCode();var v=17*m++;u.getHashCode=function(){return v;};return v;};var o=function(u,v,w,x){var y=u.length;var z=n(v);var A=1+z%(y-1);var B=z%y;for(var C=0;C<u.length;C++){if(u[B]==null){u[B]={f:v,g:w};return;}else{if(x(u[B].f,v))throw i;}B=(B+A)%y;}throw "map full";};var p=function(u,v){this.o=[];for(var w=0;w<u.length;w++) this.o.push(u[w]);if(v!==undefined)this.o.push(v);};p.prototype={And:function(u){return new p(this.o,u);},Then:function(u){return {o:this.o,p:u};}};d.prototype.And=function(u){return new p([this],u);};d.prototype.Then=function(u){return {o:[this],p:u};};d.Join=function(){var u=arguments;return d.CreateWithDisposable(function(v){var w=new l();var x=new b.List();var y=new b.Observer(function(E){v.OnNext(E);},function(E){var F=w.l();for(var G=0;G<F.length;G++) F[G].Dispose();v.OnError(E);},function(){v.OnCompleted();});try{for(var C=0;C<u.length;C++) (function(E){var F=u[E];var G;G=q(F,w,y,function(H){x.Remove(G);if(x.GetCount()==0)y.OnCompleted();});x.Add(G);})(C);}catch(E){return d.Throw(E).Subscribe(v);}var A=new b.CompositeDisposable();var B=w.l();for(var C=0;C<B.length;C++){var D=B[C];D.Subscribe();A.Add(D);}return A;});};var q=function(u,v,w,x){var y=function(D){w.OnError(D);};var z=[];for(var C=0;C<u.o.length;C++) z.push(r(v,u.o[C],y));var B=new s(z,w,u.p,function(){for(var D=0;D<z.length;D++) z[D].RemoveActivePlan(B);x();});for(var C=0;C<z.length;C++) z[C].addActivePlan(B);return B;};var r=function(u,v,w){var x=u.i(v);if(x===c){var y=new t(v,w);u.h(v,y);return y;}return x.Value;};var s=function(u,v,w,x){this.Match=function(){var y=[];var z=true;var A=false;for(var D=0;D<u.length;D++){if(u[D].queue.length==0){A=true;continue;}var C=u[D].queue[0];z&=C.Kind=="N";if(z)y.push(C.Value);}if(!z)x(); else if(A)return; else{for(var D=0;D<u.length;D++) u[D].queue.shift();var E;try{E=w.apply(null,y);}catch(F){v.OnError(F);return;}v.OnNext(E);}};};var t=function(u,v){this.queue=[];var w=new b.MutableDisposable();var x=false;var y=new b.List();var z=false;this.addActivePlan=function(A){y.Add(A);};this.Subscribe=function(){x=true;w.Replace(u.Materialize().Subscribe(this));};this.OnNext=function(A){if(!z){if(A.Kind=="E"){v(A.Value);return;}this.queue.push(A);var B=y.ToArray();for(var C=0;C<B.length;C++) B[C].Match();}};this.OnError=function(A){};this.OnCompleted=function(){};this.RemoveActivePlan=function(A){y.Remove(A);if(y.GetCount()==0)this.Dispose();};this.Dispose=function(){if(!z){z=true;w.Dispose();}};};})(); \ No newline at end of file diff --git a/RX_JS/rx.js b/RX_JS/rx.js new file mode 100644 index 0000000..c838e32 --- /dev/null +++ b/RX_JS/rx.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a;var b;var c=this;var d="Index out of range";if(typeof ProvideCustomRxRootObject =="undefined")b=c.Rx={}; else b=ProvideCustomRxRootObject();var e=function(){};var f=function(){return new Date().getTime();};var g=function(r0,s0){return r0===s0;};var h=function(r0){return r0;};var i=function(r0){return {Dispose:r0};};var j={Dispose:e};b.Disposable={Create:i,Empty:j};var k=b.BooleanDisposable=function(){var r0=false;this.GetIsDisposed=function(){return r0;};this.Dispose=function(){r0=true;};};var l=function(r0){var s0=false;r0.a++;this.Dispose=function(){var t0=false;if(!r0.b){if(!this.c){this.c=true;r0.a--;if(r0.a==0&&r0.d){r0.b=true;t0=true;}}}if(t0)r0.e.Dispose();};};var m=b.RefCountDisposable=function(r0){this.d=false;this.b=false;this.e=r0;this.a=0;this.Dispose=function(){var s0=false;if(!this.b){if(!this.d){this.d=true;if(this.a==0){this.b=true;s0=true;}}}if(s0)this.e.Dispose();};this.GetDisposable=function(){if(this.b)return j; else return new l(this);};};var n=b.CompositeDisposable=function(){var r0=new q();for(var s0=0;s0<arguments.length;s0++) r0.Add(arguments[s0]);var t0=false;this.GetCount=function(){return r0.GetCount();};this.Add=function(u0){if(!t0)r0.Add(u0); else u0.Dispose();};this.Remove=function(u0,v0){if(!t0){var w0=r0.Remove(u0);if(!v0&w0)u0.Dispose();}};this.Dispose=function(){if(!t0){t0=true;this.Clear();}};this.Clear=function(){for(var u0=0;u0<r0.GetCount();u0++) r0.GetItem(u0).Dispose();r0.Clear();};};var o=b.MutableDisposable=function(){var r0=false;var s0;this.Get=function(){return s0;},this.Replace=function(t0){if(r0&&t0!==a)t0.Dispose(); else{if(s0!==a)s0.Dispose();s0=t0;}};this.Dispose=function(){if(!r0){r0=true;if(s0!==a)s0.Dispose();}};};var p=function(r0){var s0=[];for(var t0=0;t0<r0.length;t0++) s0.push(r0[t0]);return s0;};var q=b.List=function(r0){var s0=[];var t0=0;var u0=r0!==a?r0:g;this.Add=function(v0){s0[t0]=v0;t0++;};this.RemoveAt=function(v0){if(v0<0||v0>=t0)throw d;if(v0==0){s0.shift();t0--;}else{s0.splice(v0,1);t0--;}};this.IndexOf=function(v0){for(var w0=0;w0<t0;w0++){if(u0(v0,s0[w0]))return w0;}return -1;};this.Remove=function(v0){var w0=this.IndexOf(v0);if(w0==-1)return false;this.RemoveAt(w0);return true;};this.Clear=function(){s0=[];t0=0;};this.GetCount=function(){return t0;};this.GetItem=function(v0){if(v0<0||v0>=t0)throw d;return s0[v0];};this.SetItem=function(v0,w0){if(v0<0||v0>=t0)throw d;s0[v0]=w0;};this.ToArray=function(){var v0=[];for(var w0=0;w0<this.GetCount();w0++) v0.push(this.GetItem(w0));return v0;};};var r=function(r0){if(r0===null)r0=g;this.f=r0;var s0=4;this.g=new Array(s0);this.h=0;};r.prototype.i=function(r0,s0){return this.f(this.g[r0],this.g[s0])<0;};r.prototype.j=function(r0){if(r0>=this.h||r0<0)return;var s0=r0-1>>1;if(s0<0||s0==r0)return;if(this.i(r0,s0)){var t0=this.g[r0];this.g[r0]=this.g[s0];this.g[s0]=t0;this.j(s0);}};r.prototype.k=function(r0){if(r0===a)r0=0;var s0=2*r0+1;var t0=2*r0+2;var u0=r0;if(s0<this.h&&this.i(s0,u0))u0=s0;if(t0<this.h&&this.i(t0,u0))u0=t0;if(u0!=r0){var v0=this.g[r0];this.g[r0]=this.g[u0];this.g[u0]=v0;this.k(u0);}};r.prototype.GetCount=function(){return this.h;};r.prototype.Peek=function(){if(this.h==0)throw "Heap is empty.";return this.g[0];};r.prototype.Dequeue=function(){var r0=this.Peek();this.g[0]=this.g[--this.h];delete this.g[this.h];this.k();return r0;};r.prototype.Enqueue=function(r0){var s0=this.h++;this.g[s0]=r0;this.j(s0);};var s=b.Scheduler=function(r0,s0,t0){this.Schedule=r0;this.ScheduleWithTime=s0;this.Now=t0;this.ScheduleRecursive=function(u0){var v0=this;var w0=new n();var x0;x0=function(){u0(function(){var y0=false;var z0=false;var A0;A0=v0.Schedule(function(){x0();if(y0)w0.Remove(A0); else z0=true;});if(!z0){w0.Add(A0);y0=true;}});};w0.Add(v0.Schedule(x0));return w0;};this.ScheduleRecursiveWithTime=function(u0,v0){var w0=this;var x0=new n();var y0;y0=function(){u0(function(z0){var A0=false;var B0=false;var C0;C0=w0.ScheduleWithTime(function(){y0();if(A0)x0.Remove(C0); else B0=true;},z0);if(!B0){x0.Add(C0);A0=true;}});};x0.Add(w0.ScheduleWithTime(y0,v0));return x0;};};var t=b.VirtualScheduler=function(r0,s0,t0,u0){var v0=new s(function(w0){return this.ScheduleWithTime(w0,0);},function(w0,x0){return this.ScheduleVirtual(w0,u0(x0));},function(){return t0(this.l);});v0.ScheduleVirtual=function(w0,x0){var y0=new k();var z0=s0(this.l,x0);var A0=function(){if(!y0.IsDisposed)w0();};var B0=new y(A0,z0);this.m.Enqueue(B0);return y0;};v0.Run=function(){while(this.m.GetCount()>0){var w0=this.m.Dequeue();this.l=w0.n;w0.o();}};v0.RunTo=function(w0){while(this.m.GetCount()>0&&this.f(this.m.Peek().n,w0)<=0){var x0=this.m.Dequeue();this.l=x0.n;x0.o();}};v0.GetTicks=function(){return this.l;};v0.l=0;v0.m=new r(function(w0,x0){return r0(w0.n,x0.n);});v0.f=r0;return v0;};var u=b.TestScheduler=function(){var r0=new t(function(s0,t0){return s0-t0;},function(s0,t0){return s0+t0;},function(s0){return new Date(s0);},function(s0){if(s0<=0)return 1;return s0;});return r0;};var v=new s(function(r0){return this.ScheduleWithTime(r0,0);},function(r0,s0){var t0=this.Now()+s0;var u0=new y(r0,t0);if(this.m===a){var v0=new w();try{this.m.Enqueue(u0);v0.p();}finally{v0.q();}}else this.m.Enqueue(u0);return u0.r();},f);v.s=function(r0){if(this.m===a){var s0=new w();try{r0();s0.p();}finally{s0.q();}}else r0();};s.CurrentThread=v;var w=function(){v.m=new r(function(r0,s0){try{return r0.n-s0.n;}catch(t0){debugger;}});this.q=function(){v.m=a;};this.p=function(){while(v.m.GetCount()>0){var r0=v.m.Dequeue();if(!r0.t()){while(r0.n-v.Now()>0);if(!r0.t())r0.o();}}};};var x=0;var y=function(r0,s0){this.u=x++;this.o=r0;this.n=s0;this.v=new k();this.t=function(){return this.v.GetIsDisposed();};this.r=function(){return this.v;};};var z=new s(function(r0){r0();return j;},function(r0,s0){while(this.Now<s0);r0();},f);s.Immediate=z;var A=new s(function(r0){var s0=c.setTimeout(r0,0);return i(function(){c.clearTimeout(s0);});},function(r0,s0){var t0=c.setTimeout(r0,s0);return i(function(){c.clearTimeout(t0);});},f);s.Timeout=A;var B=b.Observer=function(r0,s0,t0){this.OnNext=r0===a?e:r0;this.OnError=s0===a?function(u0){throw u0;}:s0;this.OnCompleted=t0===a?e:t0;this.AsObserver=function(){var u0=this;return new B(function(v0){u0.OnNext(v0);},function(v0){u0.OnError(v0);},function(){u0.OnCompleted();});};};var C=B.Create=function(r0,s0,t0){return new B(r0,s0,t0);};var D=b.Observable=function(r0){this.w=r0;};var E=D.CreateWithDisposable=function(r0){return new D(r0);};var F=D.Create=function(r0){return E(function(s0){return i(r0(s0));});};var G=function(){return this.Select(function(r0){return r0.Value;});};D.prototype={Subscribe:function(r0,s0,t0){var u0;if(arguments.length==0||arguments.length>1||typeof r0 =="function")u0=new B(r0,s0,t0); else u0=r0;return this.x(u0);},x:function(r0){var s0=false;var t0=new o();var u0=this;v.s(function(){var v0=new B(function(w0){if(!s0)r0.OnNext(w0);},function(w0){if(!s0){s0=true;t0.Dispose();r0.OnError(w0);}},function(){if(!s0){s0=true;t0.Dispose();r0.OnCompleted();}});t0.Replace(u0.w(v0));});return new n(t0,i(function(){s0=true;}));},Select:function(r0){var s0=this;return E(function(t0){var u0=0;return s0.Subscribe(new B(function(v0){var w0;try{w0=r0(v0,u0++);}catch(x0){t0.OnError(x0);return;}t0.OnNext(w0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Let:function(r0,s0){if(s0===a)return r0(this);var t0=this;return E(function(u0){var v0=s0();var w0;try{w0=r0(v0);}catch(A0){return L(A0).Subscribe(u0);}var x0=new o();var y0=new o();var z0=new n(y0,x0);x0.Replace(w0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){u0.OnError(A0);z0.Dispose();},function(){u0.OnCompleted();z0.Dispose();}));y0.Replace(t0.Subscribe(v0));return z0;});},MergeObservable:function(){var r0=this;return E(function(s0){var t0=false;var u0=new n();var v0=new o();u0.Add(v0);v0.Replace(r0.Subscribe(function(w0){var x0=new o();u0.Add(x0);x0.Replace(w0.Subscribe(function(y0){s0.OnNext(y0);},function(y0){s0.OnError(y0);},function(){u0.Remove(x0);if(u0.GetCount()==1&&t0)s0.OnCompleted();}));},function(w0){s0.OnError(w0);},function(){t0=true;if(u0.GetCount()==1)s0.OnCompleted();}));return u0;});},y:function(r0,s0){var t0=p(s0);t0.unshift(this);return r0(t0);},Concat:function(){return this.y(I,arguments);},Merge:function(){return this.y(H,arguments);},Catch:function(){return this.y(P,arguments);},OnErrorResumeNext:function(){return this.y(V,arguments);},Zip:function(r0,s0){var t0=this;return E(function(u0){var v0=false;var w0=[];var x0=[];var y0=false;var z0=false;var A0=new n();var B0=function(C0){A0.Dispose();w0=a;x0=a;u0.OnError(C0);};A0.Add(t0.Subscribe(function(C0){if(z0){u0.OnCompleted();return;}if(x0.length>0){var D0=x0.shift();var E0;try{E0=s0(C0,D0);}catch(F0){A0.Dispose();u0.OnError(F0);return;}u0.OnNext(E0);}else w0.push(C0);},B0,function(){if(z0){u0.OnCompleted();return;}y0=true;}));A0.Add(r0.Subscribe(function(C0){if(y0){u0.OnCompleted();return;}if(w0.length>0){var D0=w0.shift();var E0;try{E0=s0(D0,C0);}catch(F0){A0.Dispose();u0.OnError(F0);return;}u0.OnNext(E0);}else x0.push(C0);},B0,function(){if(y0){u0.OnCompleted();return;}z0=true;}));return A0;});},CombineLatest:function(r0,s0){var t0=this;return E(function(u0){var v0=false;var w0=false;var x0=false;var y0;var z0;var A0=false;var B0=false;var C0=new n();var D0=function(E0){C0.Dispose();u0.OnError(E0);};C0.Add(t0.Subscribe(function(E0){if(B0){u0.OnCompleted();return;}if(x0){var F0;try{F0=s0(E0,z0);}catch(G0){C0.Dispose();u0.OnError(G0);return;}u0.OnNext(F0);}y0=E0;w0=true;},D0,function(){if(B0){u0.OnCompleted();return;}A0=true;}));C0.Add(r0.Subscribe(function(E0){if(A0){u0.OnCompleted();return;}if(w0){var F0;try{F0=s0(y0,E0);}catch(G0){C0.Dispose();u0.OnError(G0);return;}u0.OnNext(F0);}z0=E0;x0=true;},D0,function(){if(A0){u0.OnCompleted();return;}B0=true;}));});},Switch:function(){var r0=this;return E(function(s0){var t0=false;var u0=new o();var v0=new o();v0.Replace(r0.Subscribe(function(w0){if(!t0){var x0=new o();x0.Replace(w0.Subscribe(function(y0){s0.OnNext(y0);},function(y0){v0.Dispose();u0.Dispose();s0.OnError(y0);},function(){u0.Replace(a);if(t0)s0.OnCompleted();}));u0.Replace(x0);}},function(w0){u0.Dispose();s0.OnError(w0);},function(){t0=true;if(u0.Get()===a)s0.OnCompleted();}));return new n(v0,u0);});},TakeUntil:function(r0){var s0=this;return E(function(t0){var u0=new n();u0.Add(r0.Subscribe(function(){t0.OnCompleted();u0.Dispose();},function(v0){t0.OnError(v0);},function(){}));u0.Add(s0.Subscribe(t0));return u0;});},SkipUntil:function(r0){var s0=this;return E(function(t0){var u0=true;var v0=new n();v0.Add(r0.Subscribe(function(){u0=false;},function(w0){t0.OnError(w0);},e));v0.Add(s0.Subscribe(new B(function(w0){if(!u0)t0.OnNext(w0);},function(w0){t0.OnError(w0);},function(){if(!u0)t0.OnCompleted();})));return v0;});},Scan1:function(r0){var s0=this;return O(function(){var t0;var u0=false;return s0.Select(function(v0){if(u0)t0=r0(t0,v0); else{t0=v0;u0=true;}return t0;});});},Scan:function(r0,s0){var t0=this;return O(function(){var u0;var v0=false;return t0.Select(function(w0){if(v0)u0=s0(u0,w0); else{u0=s0(r0,w0);v0=true;}return u0;});});},Scan0:function(r0,s0){var t0=this;return E(function(u0){var v0=r0;var w0=true;return t0.Subscribe(function(x0){if(w0){w0=false;u0.OnNext(v0);}try{v0=s0(v0,x0);}catch(y0){u0.OnError(y0);return;}u0.OnNext(v0);},function(x0){if(w0)u0.OnNext(v0);u0.OnError(x0);},function(){if(w0)u0.OnNext(v0);u0.OnCompleted();});});},Finally:function(r0){var s0=this;return F(function(t0){var u0=s0.Subscribe(t0);return function(){try{u0.Dispose();r0();}catch(v0){r0();throw v0;}};});},Do:function(r0,s0,t0){var u0;if(arguments.length==0||arguments.length>1||typeof r0 =="function")u0=new B(r0,s0!==a?s0:e,t0); else u0=r0;var v0=this;return E(function(w0){return v0.Subscribe(new B(function(x0){try{u0.OnNext(x0);}catch(y0){w0.OnError(y0);return;}w0.OnNext(x0);},function(x0){if(s0!==a)try{u0.OnError(x0);}catch(y0){w0.OnError(y0);return;}w0.OnError(x0);},function(){if(t0!==a)try{u0.OnCompleted();}catch(x0){w0.OnError(x0);return;}w0.OnCompleted();}));});},Where:function(r0){var s0=this;return E(function(t0){var u0=0;return s0.Subscribe(new B(function(v0){var w0=false;try{w0=r0(v0,u0++);}catch(x0){t0.OnError(x0);return;}if(w0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Take:function(r0,s0){if(s0===a)s0=z;var t0=this;return E(function(u0){if(r0<=0){t0.Subscribe().Dispose();return N(s0).Subscribe(u0);}var v0=r0;return t0.Subscribe(new B(function(w0){if(v0-->0){u0.OnNext(w0);if(v0==0)u0.OnCompleted();}},function(w0){u0.OnError(w0);},function(){u0.OnCompleted();}));});},GroupBy:function(r0,s0,t0){if(r0===a)r0=h;if(s0===a)s0=h;if(t0===a)t0=function(v0){return v0.toString();};var u0=this;return E(function(v0){var w0={};var x0=new o();var y0=new m(x0);x0.Replace(u0.Subscribe(function(z0){var A0;try{A0=r0(z0);}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}var B0=false;var C0;try{var D0=t0(A0);if(w0[D0]===a){C0=new i0();w0[D0]=C0;B0=true;}else C0=w0[D0];}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}if(B0){var E0=E(function(G0){return new n(y0.GetDisposable(),C0.Subscribe(G0));});E0.Key=A0;v0.OnNext(E0);}var F0;try{F0=s0(z0);}catch(G0){for(var H0 in w0) w0[H0].OnError(G0);v0.OnError(G0);return;}C0.OnNext(F0);},function(z0){for(var A0 in w0) w0[A0].OnError(z0);v0.OnError(z0);},function(){for(var z0 in w0) w0[z0].OnCompleted();v0.OnCompleted();}));return y0;});},TakeWhile:function(r0){var s0=this;return E(function(t0){var u0=true;return s0.Subscribe(new B(function(v0){if(u0){try{u0=r0(v0);}catch(w0){t0.OnError(w0);return;}if(u0)t0.OnNext(v0); else t0.OnCompleted();}},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},SkipWhile:function(r0){var s0=this;return E(function(t0){var u0=false;return s0.Subscribe(new B(function(v0){if(!u0)try{u0=!r0(v0);}catch(w0){t0.OnError(w0);return;}if(u0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},Skip:function(r0){var s0=this;return E(function(t0){var u0=r0;return s0.Subscribe(new B(function(v0){if(u0--<=0)t0.OnNext(v0);},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();}));});},SelectMany:function(r0){return this.Select(r0).MergeObservable();},TimeInterval:function(r0){if(r0===a)r0=z;var s0=this;return O(function(){var t0=r0.Now();return s0.Select(function(u0){var v0=r0.Now();var w0=v0-t0;t0=v0;return {Interval:w0,Value:u0};});});},RemoveInterval:G,Timestamp:function(r0){if(r0===a)r0=z;return this.Select(function(s0){return {Timestamp:r0.Now(),Value:s0};});},RemoveTimestamp:G,Materialize:function(){var r0=this;return E(function(s0){return r0.Subscribe(new B(function(t0){s0.OnNext(new h0("N",t0));},function(t0){s0.OnNext(new h0("E",t0));s0.OnCompleted();},function(){s0.OnNext(new h0("C"));s0.OnCompleted();}));});},Dematerialize:function(){return this.SelectMany(function(r0){return r0;});},AsObservable:function(){var r0=this;return E(function(s0){return r0.Subscribe(s0);});},Delay:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0=[];var w0=false;var x0=new o();var y0=t0.Materialize().Timestamp().Subscribe(function(z0){if(z0.Value.Kind=="E"){u0.OnError(z0.Value.Value);v0=[];if(w0)x0.Dispose();return;}v0.push({Timestamp:s0.Now()+r0,Value:z0.Value});if(!w0){x0.Replace(s0.ScheduleRecursiveWithTime(function(A0){var B0;do{B0=a;if(v0.length>0&&v0[0].Timestamp<=s0.Now())B0=v0.shift().Value;if(B0!==a)B0.Accept(u0);}while(B0!==a);if(v0.length>0){A0(Math.max(0,v0[0].Timestamp-s0.Now()));w0=true;}else w0=false;},r0));w0=true;}});return new n(y0,x0);});},Throttle:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0;var w0=false;var x0=new o();var y0=0;var z0=t0.Subscribe(function(A0){w0=true;v0=A0;y0++;var B0=y0;x0.Replace(s0.ScheduleWithTime(function(){if(w0&&y0==B0)u0.OnNext(v0);w0=false;},r0));},function(A0){x0.Dispose();u0.OnError(A0);w0=false;y0++;},function(){x0.Dispose();if(w0)u0.OnNext(v0);u0.OnCompleted();w0=false;y0++;});return new n(z0,x0);});},Timeout:function(r0,s0,t0){if(t0===a)t0=A;if(s0===a)s0=L("Timeout",t0);var u0=this;return E(function(v0){var w0=new o();var x0=new o();var y0=0;var z0=y0;var A0=false;x0.Replace(t0.ScheduleWithTime(function(){A0=y0==z0;if(A0)w0.Replace(s0.Subscribe(v0));},r0));w0.Replace(u0.Subscribe(function(B0){var C0=0;if(!A0){y0++;C0=y0;v0.OnNext(B0);x0.Replace(t0.ScheduleWithTime(function(){A0=y0==C0;if(A0)w0.Replace(s0.Subscribe(v0));},r0));}},function(B0){if(!A0){y0++;v0.OnError(B0);}},function(){if(!A0){y0++;v0.OnCompleted();}}));return new n(w0,x0);});},Sample:function(r0,s0){if(s0===a)s0=A;var t0=this;return E(function(u0){var v0=false;var w0;var x0=false;var y0=new n();y0.Add(Y(r0,s0).Subscribe(function(z0){if(v0){u0.OnNext(w0);v0=false;}if(x0)u0.OnCompleted();},function(z0){u0.OnError(z0);},function(){u0.OnCompleted();}));y0.Add(t0.Subscribe(function(z0){v0=true;w0=z0;},function(z0){u0.OnError(z0);y0.Dispose();},function(){x0=true;}));return y0;});},Repeat:function(r0,s0){var t0=this;if(s0===a)s0=z;if(r0===a)r0=-1;return E(function(u0){var v0=r0;var w0=new o();var x0=new n(w0);var y0=function(z0){w0.Replace(t0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){u0.OnError(A0);},function(){if(v0>0){v0--;if(v0==0){u0.OnCompleted();return;}}z0();}));};x0.Add(s0.ScheduleRecursive(y0));return x0;});},Retry:function(r0,s0){var t0=this;if(s0===a)s0=z;if(r0===a)r0=-1;return E(function(u0){var v0=r0;var w0=new o();var x0=new n(w0);var y0=function(z0){w0.Replace(t0.Subscribe(function(A0){u0.OnNext(A0);},function(A0){if(v0>0){v0--;if(v0==0){u0.OnError(A0);return;}}z0();},function(){u0.OnCompleted();}));};x0.Add(s0.ScheduleRecursive(y0));return x0;});},BufferWithTime:function(r0,s0,t0){if(t0===a)t0=A;if(s0===a)s0=r0;var u0=this;return E(function(v0){var w0=new q();var x0=t0.Now();var y0=function(){var C0=[];for(var D0=0;D0<w0.GetCount();D0++){var E0=w0.GetItem(D0);if(E0.Timestamp-x0>=0)C0.push(E0.Value);}return C0;};var z0=new n();var A0=function(C0){v0.OnError(C0);};var B0=function(){v0.OnNext(y0());v0.OnCompleted();};z0.Add(u0.Subscribe(function(C0){w0.Add({Value:C0,Timestamp:t0.Now()});},A0,B0));z0.Add(a0(r0,s0,t0).Subscribe(function(C0){var D0=y0();var E0=t0.Now()+s0-r0;while(w0.GetCount()>0&&w0.GetItem(0).Timestamp-E0<=0)w0.RemoveAt(0);v0.OnNext(D0);x0=E0;},A0,B0));return z0;});},BufferWithTimeOrCount:function(r0,s0,t0){if(t0===a)t0=A;var u0=this;return E(function(v0){var w0=0;var x0=new q();var y0=function(){v0.OnNext(x0.ToArray());x0.Clear();w0++;};var z0=new o();var A0;A0=function(C0){var D0=t0.ScheduleWithTime(function(){var E0=false;var F0=0;if(C0==w0){y0();F0=w0;E0=true;}if(E0)A0(F0);},r0);z0.Replace(D0);};A0(w0);var B0=u0.Subscribe(function(C0){var D0=false;var E0=0;x0.Add(C0);if(x0.GetCount()==s0){y0();E0=w0;D0=true;}if(D0)A0(E0);},function(C0){v0.OnError(C0);x0.Clear();},function(){v0.OnNext(x0.ToArray());w0++;v0.OnCompleted();x0.Clear();});return new n(B0,z0);});},BufferWithCount:function(r0,s0){if(s0===a)s0=r0;var t0=this;return E(function(u0){var v0=[];var w0=0;return t0.Subscribe(function(x0){if(w0==0)v0.push(x0); else w0--;var y0=v0.length;if(y0==r0){var z0=v0;v0=[];var A0=Math.min(s0,y0);for(var B0=A0;B0<y0;B0++) v0.push(z0[B0]);w0=Math.max(0,s0-r0);u0.OnNext(z0);}},function(x0){u0.OnError(x0);},function(){if(v0.length>0)u0.OnNext(v0);u0.OnCompleted();});});},StartWith:function(r0,s0){if(!(r0 instanceof Array))r0=[r0];if(s0===a)s0=z;var t0=this;return E(function(u0){var v0=new n();var w0=0;v0.Add(s0.ScheduleRecursive(function(x0){if(w0<r0.length){u0.OnNext(r0[w0]);w0++;x0();}else v0.Add(t0.Subscribe(u0));}));return v0;});},DistinctUntilChanged:function(r0,s0){if(r0===a)r0=h;if(s0===a)s0=g;var t0=this;return E(function(u0){var v0;var w0=false;return t0.Subscribe(function(x0){var y0;try{y0=r0(x0);}catch(A0){u0.OnError(A0);return;}var z0=false;if(w0)try{z0=s0(v0,y0);}catch(A0){u0.OnError(A0);return;}if(!w0||!z0){w0=true;v0=y0;u0.OnNext(x0);}},function(x0){u0.OnError(x0);},function(){u0.OnCompleted();});});},Publish:function(r0){if(r0===a)return new q0(this,new i0());var s0=this;return E(function(t0){var u0=new q0(s0,new i0());return new n(r0(u0).Subscribe(B),u0.Connect());});},Prune:function(r0,s0){if(s0===a)s0=v;if(r0===a)return new q0(this,new k0(s0));var t0=this;return E(function(u0){var v0=new q0(t0,new k0(s0));return new n(r0(v0).Subscribe(B),v0.Connect());});},Replay:function(r0,s0,t0,u0){if(u0===a)u0=v;if(r0===a)return new q0(this,new m0(s0,t0,u0));var v0=this;return E(function(w0){var x0=new q0(v0,new m0(s0,t0,u0));return new n(r0(x0).Subscribe(B),x0.Connect());});},SkipLast:function(r0){var s0=this;return E(function(t0){var u0=[];return s0.Subscribe(function(v0){u0.push(v0);if(u0.length>r0)t0.OnNext(u0.shift());},function(v0){t0.OnError(v0);},function(){t0.OnCompleted();});});},TakeLast:function(r0){var s0=this;return E(function(t0){var u0=[];return s0.Subscribe(function(v0){u0.push(v0);if(u0.length>r0)u0.shift();},function(v0){t0.OnError(v0);},function(){while(u0.length>0)t0.OnNext(u0.shift());t0.OnCompleted();});});}};var H=D.Merge=function(r0,s0){if(s0===a)s0=v;return J(r0,s0).MergeObservable();};var I=D.Concat=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){if(v0<r0.length){var y0=r0[v0];v0++;u0.Replace(y0.Subscribe(function(z0){t0.OnNext(z0);},function(z0){t0.OnError(z0);},x0));}else t0.OnCompleted();});return new n(u0,w0);});};var J=D.FromArray=function(r0,s0){if(s0===a)s0=v;return E(function(t0){var u0=0;return s0.ScheduleRecursive(function(v0){if(u0<r0.length){t0.OnNext(r0[u0++]);v0();}else t0.OnCompleted();});});};var K=D.Return=function(r0,s0){if(s0===a)s0=v;return E(function(t0){return s0.Schedule(function(){t0.OnNext(r0);t0.OnCompleted();});});};var L=D.Throw=function(r0,s0){if(s0===a)s0=v;return E(function(t0){return s0.Schedule(function(){t0.OnError(r0);});});};var M=D.Never=function(){return E(function(r0){return j;});};var N=D.Empty=function(r0){if(r0===a)r0=v;return E(function(s0){return r0.Schedule(function(){s0.OnCompleted();});});};var O=D.Defer=function(r0){return E(function(s0){var t0;try{t0=r0();}catch(u0){s0.OnError(u0);return j;}return t0.Subscribe(s0);});};var P=D.Catch=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){var y0=r0[v0];v0++;u0.Replace(y0.Subscribe(function(z0){t0.OnNext(z0);},function(z0){if(v0<r0.length)x0(); else t0.OnError(z0);},function(){t0.OnCompleted();}));});return new n(u0,w0);});};var Q=D.Using=function(r0,s0){return E(function(t0){var u0;var v0=j;try{var w0=r0();if(w0!==a)v0=w0;u0=s0(w0);}catch(x0){return new n(Throw(x0).Subscribe(t0),v0);}return new n(u0.Subscribe(t0),v0);});};var R=D.Range=function(r0,s0,t0){if(t0===a)t0=v;var u0=r0+s0-1;return T(r0,function(v0){return v0<=u0;},function(v0){return v0+1;},h,t0);};var S=D.Repeat=function(r0,s0,t0){if(t0===a)t0=v;if(s0===a)s0=-1;var u0=s0;return E(function(v0){return t0.ScheduleRecursive(function(w0){v0.OnNext(r0);if(u0>0){u0--;if(u0==0){v0.OnCompleted();return;}}w0();});});};var T=D.Generate=function(r0,s0,t0,u0,v0){if(v0===a)v0=v;return E(function(w0){var x0=r0;var y0=true;return v0.ScheduleRecursive(function(z0){var A0=false;var B0;try{if(y0)y0=false; else x0=t0(x0);A0=s0(x0);if(A0)B0=u0(x0);}catch(C0){w0.OnError(C0);return;}if(A0){w0.OnNext(B0);z0();}else w0.OnCompleted();});});};var U=D.GenerateWithTime=function(r0,s0,t0,u0,v0,w0){if(w0===a)w0=A;return new E(function(x0){var y0=r0;var z0=true;var A0=false;var B0;var C0;return w0.ScheduleRecursiveWithTime(function(D0){if(A0)x0.OnNext(B0);try{if(z0)z0=false; else y0=t0(y0);A0=s0(y0);if(A0){B0=u0(y0);C0=v0(y0);}}catch(E0){x0.OnError(E0);return;}if(A0)D0(C0); else x0.OnCompleted();},0);});};var V=D.OnErrorResumeNext=function(r0,s0){if(s0===a)s0=z;return E(function(t0){var u0=new o();var v0=0;var w0=s0.ScheduleRecursive(function(x0){if(v0<r0.length){var y0=r0[v0];v0++;u0.Replace(y0.Subscribe(function(z0){t0.OnNext(z0);},x0,x0));}else t0.OnCompleted();});return new n(u0,w0);});};var W=D.Amb=function(){var r0=arguments;return E(function(s0){var t0=new n();var u0=new o();u0.Replace(t0);var v0=false;for(var w0=0;w0<r0.length;w0++){var x0=r0[w0];var y0=new o();var z0=new B(function(A0){if(!v0){t0.Remove(this.z,true);t0.Dispose();u0.Replace(this.z);v0=true;}s0.OnNext(A0);},function(A0){s0.OnError(A0);u0.Dispose();},function(){s0.OnCompleted();u0.Dispose();});z0.z=y0;y0.Replace(x0.Subscribe(z0));t0.Add(y0);}return u0;});};var X=D.ForkJoin=function(){var r0=arguments;return E(function(s0){var t0=[];var u0=[];var v0=[];var w0=new n();for(var x0=0;x0<r0.length;x0++) (function(y0){w0.Add(r0[y0].Subscribe(function(z0){t0[y0]=true;v0[y0]=z0;},function(z0){s0.OnError(z0);},function(z0){if(!t0[y0]){s0.OnCompleted();v0=a;t0=a;return;}u0[y0]=true;var A0=true;for(var B0=0;B0<r0.length;B0++){if(!u0[B0])A0=false;}if(A0){s0.OnNext(v0);s0.OnCompleted();v0=a;u0=a;t0=a;}}));})(x0);return w0;});};var Y=D.Interval=function(r0,s0){return a0(r0,r0,s0);};var Z=function(r0){return Math.max(0,r0);};var a0=D.Timer=function(r0,s0,t0){if(t0===a)t0=A;if(r0===a)return M();if(r0 instanceof Date)return O(function(){return D.Timer(r0-new Date(),s0,t0);});var u0=Z(r0);if(s0===a)return E(function(w0){return t0.ScheduleWithTime(function(){w0.OnNext(0);w0.OnCompleted();},u0);});var v0=Z(s0);return E(function(w0){var x0=0;return t0.ScheduleRecursiveWithTime(function(y0){w0.OnNext(x0++);y0(v0);},u0);});};var b0=D.While=function(r0,s0){return E(function(t0){var u0=new o();var v0=new n(u0);v0.Add(z.ScheduleRecursive(function(w0){var x0;try{x0=r0();}catch(y0){t0.OnError(y0);return;}if(x0)u0.Replace(s0.Subscribe(function(y0){t0.OnNext(y0);},function(y0){t0.OnError(y0);},function(){w0();})); else t0.OnCompleted();}));return v0;});};var c0=D.If=function(r0,s0,t0){return O(function(){return r0()?s0:t0;});};var d0=D.DoWhile=function(r0,s0){return I([r0,b0(s0,r0)]);};var e0=D.Case=function(r0,s0,t0,u0){if(u0===a)u0=z;if(t0===a)t0=N(u0);return O(function(){var v0=s0[r0()];if(v0===a)v0=t0;return v0;});};var f0=D.For=function(r0,s0){return E(function(t0){var u0=new n();var v0=0;u0.Add(z.ScheduleRecursive(function(w0){if(v0<r0.length){var x0;try{x0=s0(r0[v0]);}catch(y0){t0.OnError(y0);return;}u0.Add(x0.Subscribe(function(y0){t0.OnNext(y0);},function(y0){t0.OnError(y0);},function(){v0++;w0();}));}else t0.OnCompleted();}));return u0;});};var g0=D.Let=function(r0,s0){return O(function(){return s0(r0);});};var h0=b.Notification=function(r0,s0){this.Kind=r0;this.Value=s0;this.toString=function(){return this.Kind+": "+this.Value;};this.Accept=function(t0){switch(this.Kind){case "N":t0.OnNext(this.Value);break;case "E":t0.OnError(this.Value);break;case "C":t0.OnCompleted();break;}return j;};this.w=function(t0){var u0=this.Accept(t0);if(r0=="N")t0.OnCompleted();return u0;};};h0.prototype=new D;var i0=b.Subject=function(){var r0=new q();var s0=false;this.OnNext=function(t0){if(!s0){var u0=r0.ToArray();for(var v0=0;v0<u0.length;v0++){var w0=u0[v0];w0.OnNext(t0);}}};this.OnError=function(t0){if(!s0){var u0=r0.ToArray();for(var v0=0;v0<u0.length;v0++){var w0=u0[v0];w0.OnError(t0);}s0=true;r0.Clear();}};this.OnCompleted=function(){if(!s0){var t0=r0.ToArray();for(var u0=0;u0<t0.length;u0++){var v0=t0[u0];v0.OnCompleted();}s0=true;r0.Clear();}};this.w=function(t0){if(!s0){r0.Add(t0);return i(function(){r0.Remove(t0);});}else return j;};};i0.prototype=new D;for(var j0 in B.prototype) i0.prototype[j0]=B.prototype[j0];var k0=b.AsyncSubject=function(r0){var s0=new q();var t0;var u0=false;if(r0===a)r0=v;this.OnNext=function(v0){if(!u0)t0=new h0("N",v0);};this.OnError=function(v0){if(!u0){t0=new h0("E",v0);var w0=s0.ToArray();for(var x0=0;x0<w0.length;x0++){var y0=w0[x0];if(y0!==a)y0.OnError(v0);}u0=true;s0.Clear();}};this.OnCompleted=function(){if(!u0){if(t0===a)t0=new h0("C");var v0=s0.ToArray();for(var w0=0;w0<v0.length;w0++){var x0=v0[w0];if(x0!==a)t0.w(x0);}u0=true;s0.Clear();}};this.w=function(v0){if(!u0){s0.Add(v0);return i(function(){s0.Remove(v0);});}else return r0.Schedule(function(){t0.w(v0);});};};k0.prototype=new i0;var l0=b.BehaviorSubject=function(r0,s0){var t0=new m0(1,-1,s0);t0.OnNext(r0);return t0;};var m0=b.ReplaySubject=function(r0,s0,t0){var u0=new q();var v0=new q();var w0=false;if(t0===a)t0=v;var x0=s0>0;var y0=function(z0,A0){v0.Add({Value:new h0(z0,A0),Timestamp:t0.Now()});};this.A=function(){if(r0!==a)while(v0.GetCount()>r0)v0.RemoveAt(0);if(x0)while(v0.GetCount()>0&&t0.Now()-v0.GetItem(0).Timestamp>s0)v0.RemoveAt(0);};this.OnNext=function(z0){if(!w0){var A0=u0.ToArray();for(var B0=0;B0<A0.length;B0++){var C0=A0[B0];C0.OnNext(z0);}y0("N",z0);}};this.OnError=function(z0){if(!w0){var A0=u0.ToArray();for(var B0=0;B0<A0.length;B0++){var C0=A0[B0];C0.OnError(z0);}w0=true;u0.Clear();y0("E",z0);}};this.OnCompleted=function(){if(!w0){var z0=u0.ToArray();for(var A0=0;A0<z0.length;A0++){var B0=z0[A0];B0.OnCompleted();}w0=true;u0.Clear();y0("C");}};this.w=function(z0){var A0=new n0(this,z0);var B0=new n(A0);var C0=this;B0.Add(t0.Schedule(function(){if(!A0.B){C0.A();for(var D0=0;D0<v0.GetCount();D0++) v0.GetItem(D0).Value.Accept(z0);u0.Add(z0);A0.C=true;}}));return B0;};this.D=function(z0){u0.Remove(z0);};};m0.prototype=new i0;var n0=function(r0,s0){this.E=r0;this.F=s0;this.C=false;this.B=false;this.Dispose=function(){if(this.C)this.E.D(this.F);this.B=true;};};var o0=D.ToAsync=function(r0,s0){if(s0===a)s0=A;return function(){var t0=new k0(s0);var u0=function(){var x0;try{x0=r0.apply(this,arguments);}catch(y0){t0.OnError(y0);return;}t0.OnNext(x0);t0.OnCompleted();};var v0=this;var w0=p(arguments);s0.Schedule(function(){u0.apply(v0,w0);});return t0;};};var p0=D.Start=function(r0,s0,t0,u0){if(t0===a)t0=[];return o0(r0,u0).apply(s0,t0);};var q0=b.ConnectableObservable=function(r0,s0){if(s0===a)s0=new i0();this.E=s0;this.G=r0;this.H=false;this.Connect=function(){var t0;var u0=false;if(!this.H){this.H=true;var v0=this;t0=new n(i(function(){v0.H=false;}));this.I=t0;t0.Add(r0.Subscribe(this.E));}return this.I;};this.w=function(t0){return this.E.Subscribe(t0);};this.RefCount=function(){var t0=0;var u0=this;var v0;return F(function(w0){var x0=false;t0++;x0=t0==1;var y0=u0.Subscribe(w0);if(x0)v0=u0.Connect();return function(){y0.Dispose();t0--;if(t0==0)v0.Dispose();};});};};q0.prototype=new D;})(); \ No newline at end of file diff --git a/RX_JS/rx.microsoft.translator.js b/RX_JS/rx.microsoft.translator.js new file mode 100644 index 0000000..6ad9bca --- /dev/null +++ b/RX_JS/rx.microsoft.translator.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=jQuery;var b=a.fn;var c=this;var d;var e;if(!c.Microsoft)d=c.Microsoft={}; else d=c.Microsoft;var f="http://api.microsofttranslator.com/V2/Ajax.svc/";var g=function(i){return i.data;};var h=d.Translator=function(i){this.addTranslation=function(j,k,l,m,n){return a.ajaxAsObservable({url:f+"AddTranslation",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,originalText:j,translatedText:k,from:l,to:m,user:n.user,rating:n.rating,contentType:n.contentType,category:n.category,uri:n.uri}}).Select(g);};this.addTranslationArray=function(j,k,l,m){var n=JSON.stringify(j);var o=JSON.stringify(m);return a.ajaxAsObservable({url:f+"AddTranslationArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,translations:n,from:k,to:l,options:o}}).Select(g);};this.breakSentences=function(j,k){return a.ajaxAsObservable({url:f+"BreakSentences",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,language:k}}).Select(g);};this.detect=function(j){return a.ajaxAsObservable({url:f+"Detect",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j}}).Select(g);};this.detectArray=function(j){var k=JSON.stringify(j);return a.ajaxAsObservable({url:f+"DetectArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,texts:k}}).Select(g);};this.getLanguageNames=function(j,k){var l=JSON.stringify(k);return a.ajaxAsObservable({url:f+"GetLanguageNames",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,locale:j,languageCodes:l}}).Select(g);};this.getLanguagesForSpeak=function(){return a.ajaxAsObservable({url:f+"GetLanguagesForSpeak",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i}}).Select(g);};this.getLanguagesForTranslate=function(){return a.ajaxAsObservable({url:f+"GetLanguagesForTranslate",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i}}).Select(g);};this.getTranslations=function(j,k,l,m,n){var o=JSON.stringify(n);return a.ajaxAsObservable({url:f+"GetTranslations",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,from:k,to:l,maxTranslations:m,options:o}}).Select(g);};this.getTranslationsArray=function(j,k,l,m,n){var o=JSON.stringify(j);var p=JSON.stringify(n);return a.ajaxAsObservable({url:f+"GetTranslationsArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,texts:o,from:k,to:l,maxTranslations:m,options:p}}).Select(g);};this.speak=function(j,k,l){if(l==null)l="audio/wav";return a.ajaxAsObservable({url:f+"Speak",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,language:k,format:l}}).Select(g);};this.translate=function(j,k,l){return a.ajaxAsObservable({url:f+"Translate",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,text:j,from:k,to:l}}).Select(g);};this.translateArray=function(j,k,l,m){var n=JSON.stringify(j);var o=JSON.stringify(m);return a.ajaxAsObservable({url:f+"TranslateArray",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,texts:n,from:k,to:l,options:o}}).Select(g);};};d.Translator.getAppIdToken=function(i,j,k,l){return a.ajaxAsObservable({url:f+"GetAppIdToken",dataType:"jsonp",jsonp:"oncomplete",data:{appId:i,minRatingRead:j,maxRatingRead:k,expireSeconds:l}}).Select(g);};})(); \ No newline at end of file diff --git a/RX_JS/rx.mootools.js b/RX_JS/rx.mootools.js new file mode 100644 index 0000000..630b415 --- /dev/null +++ b/RX_JS/rx.mootools.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a;if(typeof ProvideCustomRxRootObject =="undefined")a=this.Rx; else a=ProvideCustomRxRootObject();var b=a.Observable;var c=b.FromMooToolsEvent=function(f,g){return b.Create(function(h){var i=function(j){h.OnNext(j);};f.addEvent(g,i);return function(){f.removeEvent(g,i);};});};var d=function(f){return c(this,f);};Window.implement({addEventAsObservable:d});Document.implement({addEventAsObservable:d});Element.implement({addEventAsObservable:d});Elements.implement({addEventAsObservable:d});Events.implement({addEventAsObservable:d});var e=b.MooToolsRequest=function(f){var g=new a.AsyncSubject();var h=null;try{newOptions.onSuccess=function(j,k){g.OnNext({responseText:j,responseXML:k});g.OnCompleted();};newOptions.onFailure=function(j){g.OnError({kind:"failure",xhr:j});};newOptions.onException=function(j,k){g.OnError({kind:"exception",headerName:j,value:k});};h=new Request(newOptions);h.send();}catch(j){g.OnError(j);}var i=new a.RefCountDisposable(a.Disposable.Create(function(){if(h)h.cancel();}));return b.CreateWithDisposable(function(j){return new a.CompositeDisposable(g.Subscribe(j),i.GetDisposable());});};Request.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i,j){f.OnNext({responseXML:j,responseText:i});f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});b.MooToolsJSONRequest=function(f){var g=new a.AsyncSubject();var h=null;try{newOptions.onSuccess=function(j,k){g.OnNext({responseJSON:j,responseText:k});g.OnCompleted();};newOptions.onFailure=function(j){g.OnError({kind:"failure",xhr:j});};newOptions.onException=function(j,k){g.OnError({kind:"exception",headerName:j,value:k});};h=new Request(newOptions);h.send();}catch(j){g.OnError(j);}var i=new a.RefCountDisposable(a.Disposable.Create(function(){if(h)h.cancel();}));return b.CreateWithDisposable(function(j){return new a.CompositeDisposable(g.Subscribe(j),i.GetDisposable());});};Request.JSON.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i,j){f.OnNext({responseJSON:i,responseText:j});f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});b.MooToolsHTMLRequest=function(f){var g={};for(var h in f) g[h]=f[h];var i=new a.AsyncSubject();var j=null;try{g.onSuccess=function(l){i.OnNext(l);i.OnCompleted();};g.onFailure=function(l){i.OnError({kind:"failure",xhr:l});};g.onException=function(l,m){i.OnError({kind:"exception",headerName:l,value:m});};j=new Request.HTML(g);j.send();}catch(l){i.OnError(l);}var k=new a.RefCountDisposable(a.Disposable.Create(function(){if(j)j.cancel();}));return b.CreateWithDisposable(function(l){return new a.CompositeDisposable(i.Subscribe(l),k.GetDisposable());});};Request.HTML.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i){f.OnNext(i);f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});b.MooToolsJSONPRequest=function(f){var g=new a.AsyncSubject();var h=null;try{f.onSuccess=function(j){g.OnNext(j);g.OnCompleted();};f.onFailure=function(j){g.OnError({kind:"failure",xhr:j});};f.onException=function(j,k){g.OnError({kind:"exception",headerName:j,value:k});};h=new Request.JSONP(f);h.send();}catch(j){g.OnError(j);}var i=new a.RefCountDisposable(a.Disposable.Create(function(){if(h)h.cancel();}));return b.CreateWithDisposable(function(j){return new a.CompositeDisposable(g.Subscribe(j),i.GetDisposable());});};Request.JSONP.implement({toObservable:function(){var f=new a.AsyncSubject();var g=this;try{g.addEvents({success:function(i){f.OnNext(i);f.OnCompleted();},failure:function(i){f.OnError({kind:"failure",xhr:i});},exception:function(i,j){f.OnError({kind:"exception",headerName:i,value:j});}});g.send();}catch(i){f.OnError(i);}var h=new a.RefCountDisposable(a.Disposable.Create(function(){g.cancel();}));return b.CreateWithDisposable(function(i){return new a.CompositeDisposable(f.Subscribe(i),h.GetDisposable());});}});})(); \ No newline at end of file diff --git a/RX_JS/rx.prototype.js b/RX_JS/rx.prototype.js new file mode 100644 index 0000000..0400a33 --- /dev/null +++ b/RX_JS/rx.prototype.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a;if(typeof ProvideCustomRxRootObject =="undefined")a=this.Rx; else a=ProvideCustomRxRootObject();var b=a.Observable;var c=function(d,e){return b.Create(function(f){var g=function(h){f.OnNext(h);};Element.observe(d,e,g);return function(){Element.stopObserving(d,e,g);};});};Element.addMethods({toObservable:function(d,e){return c(d,e);}});Ajax.observableRequest=function(d,e){var f={};for(var g in e) f[g]=e[g];var h=new a.AsyncSubject();f.onSuccess=function(j){h.OnNext(j);h.OnCompleted();};f.onFailure=function(j){h.OnError(j);};var i=new Ajax.Request(d,f);return h;};Enumerable.addMethods({toObservable:function(d){if(d===undefined)d=a.Scheduler.Immediate;return b.FromArray(this.toArray());}});})(); \ No newline at end of file diff --git a/RX_JS/rx.raphael.js b/RX_JS/rx.raphael.js new file mode 100644 index 0000000..1b1226d --- /dev/null +++ b/RX_JS/rx.raphael.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=this;var b;if(typeof ProvideCustomRxRootObject =="undefined")b=a.Rx; else b=ProvideCustomRxRootObject();var c=b.Observable;var d=c.Create;Raphael.el.toObservable=function(e){var f=this;return d(function(g){var h=function(i){g.OnNext(i);};f[e](h);return function(){f["un"+e](h);};});};Raphael.el.hoverAsObservable=function(e){var f=this;return d(function(g){var h=function(j){j=j||window.event;g.OnNext({hit:true,event:j});};var i=function(j){j=j||window.event;g.OnNext({hit:false,event:j});};f.hover(h,i);return function(){f.unhover(h,i);};});};})(); \ No newline at end of file diff --git a/RX_JS/rx.virtualearth.js b/RX_JS/rx.virtualearth.js new file mode 100644 index 0000000..721c289 --- /dev/null +++ b/RX_JS/rx.virtualearth.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=VEMap;var b;var c=this;if(typeof ProvideCustomRxRootObject =="undefined")b=c.Rx; else b=ProvideCustomRxRootObject();var d=b.Observable;var e=d.Create;var f=b.AsyncSubject;a.prototype.ToObservable=function(g){var h=this;return e(function(i){var j=function(k){i.OnNext(k);};h.AttachEvent(g,j);return function(){h.DetachEvent(g,j);};});};a.prototype.FindAsObservable=function(g,h,i,j,k,l,m,n,o,p){var q=new f();this.Find(g,h,i,j,k,l,m,n,o,p,function(r,s,t,u,v){if(v)q.OnError(v); else{q.OnNext({ShapeLayer:r,FindResults:s,Places:t,HasMoreResults:u});q.OnCompleted();}});return q;};a.prototype.FindLocationsAsObservable=function(g){var h=new f();this.FindLocations(g,function(i){h.OnNext(i);h.OnCompleted();});return h;};a.prototype.GetDirectionsAsObservable=function(g,h){var i=new VERouteOptions();for(var j in h) i[j]=h[j];var k=new f();i.RouteCallback=function(l){k.OnNext(l);k.OnCompleted();};this.GetDirections(g,i);return k;};a.prototype.ImportShapeLayerDataAsObservable=function(g,h){var i=new f();this.ImportShapeLayerData(g,function(j){i.OnNext(j);i.OnCompleted();},h);return i;};})(); \ No newline at end of file diff --git a/RX_JS/rx.yui3.js b/RX_JS/rx.yui3.js new file mode 100644 index 0000000..c9f1448 --- /dev/null +++ b/RX_JS/rx.yui3.js @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// This code is licensed by Microsoft Corporation under the terms +// of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. +// See http://go.microsoft.com/fwlink/?LinkId=186234. + +(function(){var a=Rx.Observable.YUI3Use=function(d){return Rx.Observable.CreateWithDisposable(function(e){var f=function(h){e.OnNext(h);};var g=YUI().use(d,f);return Rx.Disposable.Empty;});};var b=Rx.Observable.FromYUI3Event=function(d,e){return a("node-base").SelectMany(function(f){return Rx.Observable.Create(function(g){var h=function(i){g.OnNext(i);};f.on(e,h,d);return function(){f.detach(e,h,d);};});});};var c=Rx.Observable.FromYUI3IO=function(d,e){return a("io-base").SelectMany(function(f){var g={};for(var h in e) g[h]=e[h];var i=new Rx.AsyncSubject();g.on={success:function(j,k,l){i.OnNext({transactionid:j,response:k,arguments:l});i.OnCompleted();},failure:function(j,k,l){i.OnError({transactionid:j,response:k,arguments:l});}};f.io(d,g);return i;});};})(); \ No newline at end of file diff --git a/Rx_XNA31_XBOX360/System.CoreEx.dll b/Rx_XNA31_XBOX360/System.CoreEx.dll new file mode 100644 index 0000000..bdb212f Binary files /dev/null and b/Rx_XNA31_XBOX360/System.CoreEx.dll differ diff --git a/Rx_XNA31_XBOX360/System.Interactive.dll b/Rx_XNA31_XBOX360/System.Interactive.dll new file mode 100644 index 0000000..fdd996d Binary files /dev/null and b/Rx_XNA31_XBOX360/System.Interactive.dll differ diff --git a/Rx_XNA31_XBOX360/System.Observable.dll b/Rx_XNA31_XBOX360/System.Observable.dll new file mode 100644 index 0000000..95d5c80 Binary files /dev/null and b/Rx_XNA31_XBOX360/System.Observable.dll differ diff --git a/Rx_XNA31_XBOX360/System.Reactive.dll b/Rx_XNA31_XBOX360/System.Reactive.dll new file mode 100644 index 0000000..3191e00 Binary files /dev/null and b/Rx_XNA31_XBOX360/System.Reactive.dll differ diff --git a/Rx_XNA31_XBOX360/redist.txt b/Rx_XNA31_XBOX360/redist.txt new file mode 100644 index 0000000..ea05186 --- /dev/null +++ b/Rx_XNA31_XBOX360/redist.txt @@ -0,0 +1,6 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll diff --git a/Rx_XNA31_Zune/System.CoreEx.dll b/Rx_XNA31_Zune/System.CoreEx.dll new file mode 100644 index 0000000..ffa3d01 Binary files /dev/null and b/Rx_XNA31_Zune/System.CoreEx.dll differ diff --git a/Rx_XNA31_Zune/System.Interactive.dll b/Rx_XNA31_Zune/System.Interactive.dll new file mode 100644 index 0000000..3b31f58 Binary files /dev/null and b/Rx_XNA31_Zune/System.Interactive.dll differ diff --git a/Rx_XNA31_Zune/System.Observable.dll b/Rx_XNA31_Zune/System.Observable.dll new file mode 100644 index 0000000..ddd6951 Binary files /dev/null and b/Rx_XNA31_Zune/System.Observable.dll differ diff --git a/Rx_XNA31_Zune/System.Reactive.dll b/Rx_XNA31_Zune/System.Reactive.dll new file mode 100644 index 0000000..3a1cdcc Binary files /dev/null and b/Rx_XNA31_Zune/System.Reactive.dll differ diff --git a/Rx_XNA31_Zune/redist.txt b/Rx_XNA31_Zune/redist.txt new file mode 100644 index 0000000..ea05186 --- /dev/null +++ b/Rx_XNA31_Zune/redist.txt @@ -0,0 +1,6 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll diff --git a/SL3/System.CoreEx.dll b/SL3/System.CoreEx.dll new file mode 100644 index 0000000..93cae5a Binary files /dev/null and b/SL3/System.CoreEx.dll differ diff --git a/SL3/System.Interactive.dll b/SL3/System.Interactive.dll new file mode 100644 index 0000000..0c61b58 Binary files /dev/null and b/SL3/System.Interactive.dll differ diff --git a/SL3/System.Observable.dll b/SL3/System.Observable.dll new file mode 100644 index 0000000..ca2f861 Binary files /dev/null and b/SL3/System.Observable.dll differ diff --git a/SL3/System.Reactive.dll b/SL3/System.Reactive.dll new file mode 100644 index 0000000..19c4f18 Binary files /dev/null and b/SL3/System.Reactive.dll differ diff --git a/SL3/redist.txt b/SL3/redist.txt new file mode 100644 index 0000000..ea05186 --- /dev/null +++ b/SL3/redist.txt @@ -0,0 +1,6 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll diff --git a/SL4/System.CoreEx.dll b/SL4/System.CoreEx.dll new file mode 100644 index 0000000..246af55 Binary files /dev/null and b/SL4/System.CoreEx.dll differ diff --git a/SL4/System.Interactive.dll b/SL4/System.Interactive.dll new file mode 100644 index 0000000..ec345a0 Binary files /dev/null and b/SL4/System.Interactive.dll differ diff --git a/SL4/System.Observable.dll b/SL4/System.Observable.dll new file mode 100644 index 0000000..71b902f Binary files /dev/null and b/SL4/System.Observable.dll differ diff --git a/SL4/System.Reactive.dll b/SL4/System.Reactive.dll new file mode 100644 index 0000000..6a32c4f Binary files /dev/null and b/SL4/System.Reactive.dll differ diff --git a/SL4/redist.txt b/SL4/redist.txt new file mode 100644 index 0000000..ea05186 --- /dev/null +++ b/SL4/redist.txt @@ -0,0 +1,6 @@ +The files below can be distributed as described in the MICROSOFT REACTIVE EXTENSTIONS FOR JAVASCRIPT AND .NET LIBRARIES License. + +System.Observable.dll +System.CoreEx.dll +System.Reactive.dll +System.Interactive.dll
fkhan/mupdf_fareed
432d2f140b052e8db6b44d76339988262c0f9f40
Some updated APIs
diff --git a/apps/kno_pdfapp.c b/apps/kno_pdfapp.c index d49ab79..eec4def 100644 --- a/apps/kno_pdfapp.c +++ b/apps/kno_pdfapp.c @@ -1,165 +1,246 @@ #include <fitz.h> #include <mupdf.h> #include "pdfapp.h" #include "kno_pdfapp.h" -void kno_addHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1) +int kno_addHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1) { app->selr.x0 = x0; app->selr.x1 = x1; app->selr.y0 = y0; app->selr.y1 = y1; kno_onselect(app); winrepaint(app); + return 1; } -void kno_changeHighlightColor(pdfapp_t *app, unsigned long color) +void kno_setHighlightColor(pdfapp_t *app, unsigned long color) { app->highlightedcolor = color; } void kno_UpdateHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1) { - kno_addHighlight(app, x0, y0, x1, y1); + //bool abc = kno_addHighlight(app, x0, y0, x1, y1); } kno_highlightedtext * kno_getHighlightedText(pdfapp_t *app) { kno_highlightedtext *result = fz_malloc(sizeof(kno_highlightedtext)); return result; } fz_textspan *pdfapp_gettextline(pdfapp_t *app, int linenum) { /* lines numbered from 1 */ fz_textspan *ln = app->text; int n = 1; while (ln && n!=linenum) { n++; ln = ln->next; } return ln; } void kno_clearselect(pdfapp_t *app) { printf("clearSelect\n"); app->firstline = app->lastline = 0; app->firstchar = app->firstchar = -1; app->sellen = 0; } void kno_applyselect(pdfapp_t *app) { fz_textspan *firstline, *lastline, *ln; int i,n=0; if (!app->firstline) return; firstline = pdfapp_gettextline(app, app->firstline); if (firstline) { XRectangle box; box.x = firstline->text[app->firstchar].x; box.y = firstline->bbox.y0; box.height = firstline->bbox.y1 - firstline->bbox.y0 + 1; lastline = pdfapp_gettextline(app, app->lastline); if (lastline != firstline) { box.width = firstline->bbox.x1 - box.x + 1; app->selrects[n++] = box; ln = firstline->next; while (ln != lastline) { app->selrects[n].x = ln->bbox.x0; app->selrects[n].y = ln->bbox.y0; app->selrects[n].width = ln->bbox.x1 - ln->bbox.x0 + 1; app->selrects[n].height = ln->bbox.y1 - ln->bbox.y0 + 1; ln = ln->next; n++; } box.x = lastline->bbox.x0; box.width = lastline->text[app->lastchar].x - lastline->text[0].x + lastline->text[app->lastchar].w; box.y = lastline->bbox.y0; box.height = lastline->bbox.y1 - lastline->bbox.y0 + 1; app->selrects[n++] = box; } else { box.width = lastline->text[app->lastchar].x - box.x + lastline->text[app->lastchar].w; app->selrects[n++] = box; } } for (i=0; i<n; i++) { app->selrects[i].x += app->panx; app->selrects[i].y += app->pany; } app->sellen = n; } void kno_onselect(pdfapp_t *app) { fz_textspan *ln; int x0 = app->image->x + app->selr.x0 - app->panx; int x1 = app->image->x + app->selr.x1 - app->panx; int y0 = app->image->y + app->selr.y0 - app->pany; int y1 = app->image->y + app->selr.y1 - app->pany; int n, i; int firstline, lastline, firstchar, lastchar; int linenum = 0; n=0; firstline = lastline = firstchar = lastchar = 0; for (ln = app->text; ln; ln = ln->next) { linenum++; if (ln->len > 0) { for (i = 0; i < ln->len; i++) { int x = ln->text[i].x; int y = ln->text[i].y; if (x >= x0 && x <= x1 && y >= y0 && y <= y1) { if (!firstline) { firstchar = i; firstline = linenum; } lastchar = i; lastline = linenum; } } } } app->firstline = firstline; app->lastline = lastline; app->firstchar = firstchar; app->lastchar = lastchar; kno_applyselect(app); } - void kno_allocselection(pdfapp_t *app) { /* JB: do something smarter */ if (!app->selrects) app->selrects = malloc(sizeof(*app->selrects) * 16000); } + +int kno_ishighlightable(pdfapp_t *app, int x, int y, int *closestx, int *closesty) +{ + fz_textspan *ln; + int lx0 = app->image->x + x - app->panx; + int ly0 = app->image->y + y - app->pany; + int i, difx, dify; + difx = dify = 0; + + for (ln = app->text; ln; ln = ln->next) { + if (ln->len > 0) { + for (i = 0; i < ln->len; i++) + { + int x0 = ln->text[i].x; + int x1 = ln->text[i].x + ln->text[i].w; + int y0 = ln->bbox.y0;//ln->text[i].y; + int y1 = ln->bbox.y1; + + if (lx0 >= x0 && lx0 <= x1 && ly0 >= y0 && ly0 <= y1) + { + return 1; //Found + } + else + { + if (MAX(x0, lx0) - MIN(x0, lx0) < difx || difx==0) + { + difx = MAX(x0, lx0) - MIN(x0, lx0); + *closestx = x0; + } + if (MAX(y0, ly0) - MIN(y0, ly0) < dify || dify == 0) + { + dify = MAX(y0, ly0) - MIN(y0, ly0); + *closesty = y0; + } + } + //else if (x < lx0 || y < ly0) return 0; //not found + // it can't be acievable becuase lines are placed in list in reverse order + } + } + } + + return 0; //not found +} + +kno_hitdata *kno_gethitdata(pdfapp_t *app, int x, int y) +{ + fz_textspan *ln; + kno_hitdata *hitdata; + hitdata = fz_malloc(sizeof(kno_hitdata)); + hitdata->x = -1; + hitdata->y = -1; + hitdata->ucs = -1; + + int i; + + int lx = app->image->x + x - app->panx; + int ly = app->image->y + y - app->pany; + + for (ln = app->text; ln; ln = ln->next) { + if (ln->len > 0) { + for (i = 0; i < ln->len; i++) { + + int x0 = ln->text[i].x; + int x1 = ln->text[i].x + ln->text[i].w; + int y0 = ln->text[i].y; + int y1 = ln->bbox.y1; + if (lx >= x0 && lx <= x1 && ly >= y0 && ly <= y1) + { + hitdata->x = x0; + hitdata->y = y0; + hitdata->ucs = ln->text[i].c; + return hitdata; //found + } + } + } + } + + return hitdata; //not found +} + + diff --git a/apps/kno_pdfapp.h b/apps/kno_pdfapp.h index 907c963..1ab57e7 100644 --- a/apps/kno_pdfapp.h +++ b/apps/kno_pdfapp.h @@ -1,23 +1,36 @@ /* * Utility object for handling a pdf application / view * Takes care of PDF loading and displaying and navigation, * uses a number of callbacks to the GUI app. */ #include <X11/Xlib.h> typedef struct kno_highlightedtext_s kno_highlightedtext; +typedef struct kno_hitdata_s kno_hitdata; struct kno_highlightedtext_s { fz_textspan *text; }; +struct kno_hitdata_s +{ + int x, y; + int ucs; +}; + void kno_onselect(pdfapp_t *app); void kno_clearselect(pdfapp_t *app); void kno_applyselect(pdfapp_t *app); -void kno_addHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1); -void kno_changeHighlightColor(pdfapp_t *app, unsigned long color); +int kno_addHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1); +void kno_setHighlightColor(pdfapp_t *app, unsigned long color); void kno_UpdateHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1); kno_highlightedtext *getHighlightedText(pdfapp_t *app); void kno_allocselection(pdfapp_t *app); + +kno_hitdata *kno_gethitdata(pdfapp_t *app, int x, int y); +int kno_ishighlightable(pdfapp_t *app, int x, int y, int *closestx, int *closesty); +//kno_highlightid *kno_gethighlightid(int x, int y); +//kno_highlightinfo *kno_gethighlightinfo(kno_highlightid id); + diff --git a/apps/pdfapp.c b/apps/pdfapp.c index 77c486e..737bf2a 100644 --- a/apps/pdfapp.c +++ b/apps/pdfapp.c @@ -1,689 +1,707 @@ #include <fitz.h> #include <mupdf.h> #include "pdfapp.h" #include "kno_pdfapp.h" enum panning { DONT_PAN = 0, PAN_TO_TOP, PAN_TO_BOTTOM }; static void pdfapp_showpage(pdfapp_t *app, int loadpage, int drawpage); static void pdfapp_warn(pdfapp_t *app, const char *fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); winwarn(app, buf); } static void pdfapp_error(pdfapp_t *app, fz_error error) { winerror(app, error); } char *pdfapp_usage(pdfapp_t *app) { return " l <\t\t-- rotate left\n" " r >\t\t-- rotate right\n" " u up\t\t-- scroll up\n" " d down\t-- scroll down\n" " = +\t\t-- zoom in\n" " -\t\t-- zoom out\n" " w\t\t-- shrinkwrap\n" "\n" " n pgdn space\t-- next page\n" " b pgup back\t-- previous page\n" " right\t\t-- next page\n" " left\t\t-- previous page\n" " N F\t\t-- next 10\n" " B\t\t-- back 10\n" " m\t\t-- mark page for snap back\n" " t\t\t-- pop back to last mark\n" " 123g\t\t-- go to page\n" "\n" " left drag to pan, right drag to copy text\n"; } void pdfapp_init(pdfapp_t *app) { memset(app, 0, sizeof(pdfapp_t)); app->scrw = 640; app->scrh = 480; app->zoom = 1.0; app->cache = fz_newglyphcache(); } void pdfapp_open(pdfapp_t *app, char *filename) { fz_obj *obj; fz_obj *info; char *password = ""; /* * Open PDF and load xref table */ app->filename = filename; app->xref = pdf_openxref(filename); if (!app->xref) pdfapp_error(app, -1); /* * Handle encrypted PDF files */ if (pdf_needspassword(app->xref)) { int okay = pdf_authenticatepassword(app->xref, password); while (!okay) { password = winpassword(app, filename); if (!password) exit(1); okay = pdf_authenticatepassword(app->xref, password); if (!okay) pdfapp_warn(app, "Invalid password."); } } /* * Load meta information */ app->outline = pdf_loadoutline(app->xref); app->doctitle = filename; if (strrchr(app->doctitle, '\\')) app->doctitle = strrchr(app->doctitle, '\\') + 1; if (strrchr(app->doctitle, '/')) app->doctitle = strrchr(app->doctitle, '/') + 1; info = fz_dictgets(app->xref->trailer, "Info"); if (info) { obj = fz_dictgets(info, "Title"); if (obj) app->doctitle = pdf_toutf8(obj); } /* * Start at first page */ app->pagecount = pdf_getpagecount(app->xref); app->shrinkwrap = 1; if (app->pageno < 1) app->pageno = 1; if (app->zoom < 0.1) app->zoom = 0.1; if (app->zoom > 3.0) app->zoom = 3.0; app->rotate = 0; app->panx = 0; app->pany = 0; - kno_changeHighlightColor(app, 0xff00ff00); + + //code change by kakai + //highlight color settings + kno_setHighlightColor(app, 0x00ffff00); + //code change by kakai + pdfapp_showpage(app, 1, 1); } void pdfapp_close(pdfapp_t *app) { if (app->cache) fz_freeglyphcache(app->cache); app->cache = nil; if (app->page) pdf_droppage(app->page); app->page = nil; if (app->image) fz_droppixmap(app->image); app->image = nil; if (app->text) fz_freetextspan(app->text); app->text = nil; if (app->outline) pdf_dropoutline(app->outline); app->outline = nil; if (app->xref->store) pdf_dropstore(app->xref->store); app->xref->store = nil; pdf_closexref(app->xref); app->xref = nil; } static fz_matrix pdfapp_viewctm(pdfapp_t *app) { fz_matrix ctm; ctm = fz_identity(); ctm = fz_concat(ctm, fz_translate(0, -app->page->mediabox.y1)); ctm = fz_concat(ctm, fz_scale(app->zoom, -app->zoom)); ctm = fz_concat(ctm, fz_rotate(app->rotate + app->page->rotate)); return ctm; } static void pdfapp_panview(pdfapp_t *app, int newx, int newy) { if (newx > 0) newx = 0; if (newy > 0) newy = 0; if (newx + app->image->w < app->winw) newx = app->winw - app->image->w; if (newy + app->image->h < app->winh) newy = app->winh - app->image->h; if (app->winw >= app->image->w) newx = (app->winw - app->image->w) / 2; if (app->winh >= app->image->h) newy = (app->winh - app->image->h) / 2; if (newx != app->panx || newy != app->pany) winrepaint(app); app->panx = newx; app->pany = newy; } static void pdfapp_showpage(pdfapp_t *app, int loadpage, int drawpage) { char buf[256]; fz_error error; fz_device *idev, *tdev, *mdev; fz_displaylist *list; fz_matrix ctm; fz_bbox bbox; fz_obj *obj; if (loadpage) { wincursor(app, WAIT); if (app->page) pdf_droppage(app->page); app->page = nil; //code change by kakai kno_clearselect(app); //code change by kakai pdf_flushxref(app->xref, 0); obj = pdf_getpageobject(app->xref, app->pageno); error = pdf_loadpage(&app->page, app->xref, obj); if (error) pdfapp_error(app, error); sprintf(buf, "%s - %d/%d", app->doctitle, app->pageno, app->pagecount); wintitle(app, buf); } if (drawpage) { wincursor(app, WAIT); ctm = pdfapp_viewctm(app); bbox = fz_roundrect(fz_transformrect(ctm, app->page->mediabox)); list = fz_newdisplaylist(); mdev = fz_newlistdevice(list); error = pdf_runcontentstream(mdev, fz_identity(), app->xref, app->page->resources, app->page->contents); if (error) pdfapp_error(app, error); fz_freedevice(mdev); if (app->image) fz_droppixmap(app->image); app->image = fz_newpixmapwithrect(pdf_devicergb, bbox); fz_clearpixmap(app->image, 0xFF); idev = fz_newdrawdevice(app->cache, app->image); fz_executedisplaylist(list, idev, ctm); fz_freedevice(idev); if (app->text) fz_freetextspan(app->text); app->text = fz_newtextspan(); tdev = fz_newtextdevice(app->text); fz_executedisplaylist(list, tdev, ctm); fz_freedevice(tdev); fz_freedisplaylist(list); //code change by kakai kno_allocselection(app); kno_applyselect(app); //code change by kakai winconvert(app, app->image); } pdfapp_panview(app, app->panx, app->pany); if (app->shrinkwrap) { int w = app->image->w; int h = app->image->h; if (app->winw == w) app->panx = 0; if (app->winh == h) app->pany = 0; if (w > app->scrw * 90 / 100) w = app->scrw * 90 / 100; if (h > app->scrh * 90 / 100) h = app->scrh * 90 / 100; if (w != app->winw || h != app->winh) winresize(app, w, h); } winrepaint(app); wincursor(app, ARROW); } static void pdfapp_gotouri(pdfapp_t *app, fz_obj *uri) { char *buf; buf = fz_malloc(fz_tostrlen(uri) + 1); memcpy(buf, fz_tostrbuf(uri), fz_tostrlen(uri)); buf[fz_tostrlen(uri)] = 0; winopenuri(app, buf); fz_free(buf); } static void pdfapp_gotopage(pdfapp_t *app, fz_obj *obj) { int page; page = pdf_findpageobject(app->xref, obj); if (app->histlen + 1 == 256) { memmove(app->hist, app->hist + 1, sizeof(int) * 255); app->histlen --; } app->hist[app->histlen++] = app->pageno; app->pageno = page; pdfapp_showpage(app, 1, 1); } void pdfapp_onresize(pdfapp_t *app, int w, int h) { if (app->winw != w || app->winh != h) { app->winw = w; app->winh = h; pdfapp_panview(app, app->panx, app->pany); winrepaint(app); } } void pdfapp_onkey(pdfapp_t *app, int c) { int oldpage = app->pageno; enum panning panto = PAN_TO_TOP; /* * Save numbers typed for later */ if (c >= '0' && c <= '9') { app->number[app->numberlen++] = c; app->number[app->numberlen] = '\0'; } switch (c) { /* * Zoom and rotate */ case '+': case '=': app->zoom += 0.1; if (app->zoom > 3.0) app->zoom = 3.0; pdfapp_showpage(app, 0, 1); break; case '-': app->zoom -= 0.1; if (app->zoom < 0.1) app->zoom = 0.1; pdfapp_showpage(app, 0, 1); break; case 'l': case '<': app->rotate -= 90; pdfapp_showpage(app, 0, 1); break; case 'r': case '>': app->rotate += 90; pdfapp_showpage(app, 0, 1); break; case 'a': app->rotate -= 15; pdfapp_showpage(app, 0, 1); break; case 's': app->rotate += 15; pdfapp_showpage(app, 0, 1); break; /* * Pan view, but dont need to repaint image */ case 'w': app->shrinkwrap = 1; app->panx = app->pany = 0; pdfapp_showpage(app, 0, 0); break; case 'd': app->pany -= app->image->h / 10; pdfapp_showpage(app, 0, 0); break; case 'u': app->pany += app->image->h / 10; pdfapp_showpage(app, 0, 0); break; case ',': app->panx += app->image->w / 10; pdfapp_showpage(app, 0, 0); break; case '.': app->panx -= app->image->w / 10; pdfapp_showpage(app, 0, 0); break; /* * Page navigation */ case 'g': case '\n': case '\r': if (app->numberlen > 0) app->pageno = atoi(app->number); break; case 'G': app->pageno = app->pagecount; break; case 'm': if (app->histlen + 1 == 256) { memmove(app->hist, app->hist + 1, sizeof(int) * 255); app->histlen --; } app->hist[app->histlen++] = app->pageno; break; case 't': if (app->histlen > 0) app->pageno = app->hist[--app->histlen]; break; /* * Back and forth ... */ case 'p': panto = PAN_TO_BOTTOM; if (app->numberlen > 0) app->pageno -= atoi(app->number); else app->pageno--; break; case 'n': panto = PAN_TO_TOP; if (app->numberlen > 0) app->pageno += atoi(app->number); else app->pageno++; break; case 'b': case '\b': panto = DONT_PAN; if (app->numberlen > 0) app->pageno -= atoi(app->number); else app->pageno--; break; case 'f': case ' ': panto = DONT_PAN; if (app->numberlen > 0) app->pageno += atoi(app->number); else app->pageno++; break; case 'B': panto = PAN_TO_TOP; app->pageno -= 10; break; case 'F': panto = PAN_TO_TOP; app->pageno += 10; break; } if (c < '0' || c > '9') app->numberlen = 0; if (app->pageno < 1) app->pageno = 1; if (app->pageno > app->pagecount) app->pageno = app->pagecount; if (app->pageno != oldpage) { switch (panto) { case PAN_TO_TOP: app->pany = 0; break; case PAN_TO_BOTTOM: app->pany = -2000; break; case DONT_PAN: break; } pdfapp_showpage(app, 1, 1); } } void pdfapp_onmouse(pdfapp_t *app, int x, int y, int btn, int modifiers, int state) { pdf_link *link; fz_matrix ctm; fz_point p; p.x = x - app->panx + app->image->x; p.y = y - app->pany + app->image->y; ctm = pdfapp_viewctm(app); ctm = fz_invertmatrix(ctm); p = fz_transformpoint(ctm, p); for (link = app->page->links; link; link = link->next) { if (p.x >= link->rect.x0 && p.x <= link->rect.x1) if (p.y >= link->rect.y0 && p.y <= link->rect.y1) break; } if (link) { wincursor(app, HAND); if (btn == 1 && state == 1) { if (link->kind == PDF_LURI) pdfapp_gotouri(app, link->dest); else if (link->kind == PDF_LGOTO) pdfapp_gotopage(app, link->dest); return; } } else { wincursor(app, ARROW); } if (state == 1) { if (btn == 1 && !app->iscopying) { app->ispanning = 1; app->selx = x; app->sely = y; } if (btn == 3 && !app->ispanning) { kno_clearselect(app); //code change by kakai app->iscopying = 1; app->selx = x; app->sely = y; app->selr.x0 = x; app->selr.x1 = x; app->selr.y0 = y; app->selr.y1 = y; } if (btn == 4 || btn == 5) /* scroll wheel */ { int dir = btn == 4 ? 1 : -1; app->ispanning = app->iscopying = 0; if (modifiers & (1<<2)) { /* zoom in/out if ctrl is pressed */ app->zoom += 0.1 * dir; if (app->zoom > 3.0) app->zoom = 3.0; if (app->zoom < 0.1) app->zoom = 0.1; pdfapp_showpage(app, 0, 1); } else { /* scroll up/down, or left/right if shift is pressed */ int isx = (modifiers & (1<<0)); int xstep = isx ? 20 * dir : 0; int ystep = !isx ? 20 * dir : 0; pdfapp_panview(app, app->panx + xstep, app->pany + ystep); } } } else if (state == -1) { + //Code change by Kakai + //Hit testing + kno_hitdata *hitdata = kno_gethitdata(app, x, y); + printf("hit test char is: %c\n", hitdata->ucs); + //Code change by Kakai if (app->iscopying) { app->iscopying = 0; app->selr.x0 = MIN(app->selx, x); app->selr.x1 = MAX(app->selx, x); app->selr.y0 = MIN(app->sely, y); app->selr.y1 = MAX(app->sely, y); winrepaint(app); if (app->selr.x0 < app->selr.x1 && app->selr.y0 < app->selr.y1) windocopy(app); } if (app->ispanning) app->ispanning = 0; } else if (app->ispanning) { int newx = app->panx + x - app->selx; int newy = app->pany + y - app->sely; pdfapp_panview(app, newx, newy); app->selx = x; app->sely = y; } else if (app->iscopying) { app->selr.x0 = MIN(app->selx, x); app->selr.x1 = MAX(app->selx, x); app->selr.y0 = MIN(app->sely, y); app->selr.y1 = MAX(app->sely, y); - kno_onselect(app); //code change by kakai + //code change by kakai + //IsHighlightable and selection testing + int closestx, closesty; + closestx = closesty = 0; + if (kno_ishighlightable(app, x, y, &closestx, &closesty) == 1) + kno_onselect(app); //code change by kakai + else +{ printf("x is %d\n", closestx); printf("y is %d\n", closesty); } + //code change by kakai winrepaint(app); } } void pdfapp_oncopy(pdfapp_t *app, unsigned short *ucsbuf, int ucslen) { ucsbuf[0] = 0; fz_textspan *ln; int x, y, c; int i, p; int x0 = app->image->x + app->selr.x0 - app->panx; int x1 = app->image->x + app->selr.x1 - app->panx; int y0 = app->image->y + app->selr.y0 - app->pany; int y1 = app->image->y + app->selr.y1 - app->pany; p = 0; for (ln = app->text; ln; ln = ln->next) { if (ln->len > 0) { y = y0 - 1; for (i = 0; i < ln->len; i++) { #if 0 int bx0, bx1, by0, by1; bx0 = ln->text[i].bbox.x0; bx1 = ln->text[i].bbox.x1; by0 = ln->text[i].bbox.y0; by1 = ln->text[i].bbox.y1; c = ln->text[i].c; if (c < 32) c = '?'; if (bx1 >= x0 && bx0 <= x1 && by1 >= y0 && by0 <= y1) if (p < ucslen - 1) ucsbuf[p++] = c; #endif c = ln->text[i].c; x = ln->text[i].x; y = ln->text[i].y; if (c < 32) c = '?'; if (x >= x0 && x <= x1 && y >= y0 && y <= y1) if (p < ucslen - 1) ucsbuf[p++] = c; } if (y >= y0 && y <= y1) { #ifdef _WIN32 if (p < ucslen - 1) ucsbuf[p++] = '\r'; #endif if (p < ucslen - 1) ucsbuf[p++] = '\n'; } } } ucsbuf[p] = 0; } diff --git a/fitz/dev_text.c b/fitz/dev_text.c index a73af5a..04fa665 100644 --- a/fitz/dev_text.c +++ b/fitz/dev_text.c @@ -1,240 +1,241 @@ #include "fitz.h" #include <ft2build.h> #include FT_FREETYPE_H #if ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 1)) || \ ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 2)) || \ ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 3) && (FREETYPE_PATCH < 8)) int FT_Get_Advance(FT_Face face, int gid, int masks, FT_Fixed *out) { int fterr; fterr = FT_Load_Glyph(face, gid, masks | FT_LOAD_IGNORE_TRANSFORM); if (fterr) return fterr; *out = face->glyph->advance.x * 1024; return 0; } #else #include FT_ADVANCES_H #endif typedef struct fz_textdevice_s fz_textdevice; struct fz_textdevice_s { fz_point point; fz_textspan *line; }; fz_textspan * fz_newtextspan(void) { fz_textspan *line; line = fz_malloc(sizeof(fz_textspan)); line->len = 0; line->cap = 0; //code change by Kakai line->bbox.x0 = 0; line->bbox.x1 = 0; line->bbox.y0 = 0; line->bbox.y1 = 0; //code change by Kakai line->text = nil; line->next = nil; return line; } void fz_freetextspan(fz_textspan *line) { if (line->next) fz_freetextspan(line->next); fz_free(line->text); fz_free(line); } static void fz_addtextchar(fz_textspan *line, int x, int y, int w, int h, int c) { if (line->len + 1 >= line->cap) { line->cap = line->cap ? (line->cap * 3) / 2 : 80; line->text = fz_realloc(line->text, sizeof(fz_textchar) * line->cap); } line->text[line->len].x = x; line->text[line->len].y = y; line->text[line->len].c = c; line->text[line->len].w = w; if (!line->bbox.x0) { line->bbox.x0 = x; line->bbox.y0 = y; line->bbox.y1 = y+h; } else { int y0, y1; y0 = y; y1 = y+h; if (y0 < line->bbox.y0) line->bbox.y0 = y0; if (y1 > line->bbox.y1) line->bbox.y1 = y1; } line->bbox.x1 = x + w; line->len ++; } void fz_debugtextspan(fz_textspan *line) { char buf[10]; int c, n, k, i; for (i = 0; i < line->len; i++) { c = line->text[i].c; if (c < 128) putchar(c); else { n = runetochar(buf, &c); for (k = 0; k < n; k++) putchar(buf[k]); } } putchar('\n'); if (line->next) fz_debugtextspan(line->next); } static void fz_textextractline(fz_textspan **line, fz_text *text, fz_matrix ctm, fz_point *oldpt) { fz_font *font = text->font; fz_matrix tm = text->trm; fz_matrix inv = fz_invertmatrix(text->trm); fz_matrix trm; fz_matrix foo = tm; fz_rect bbox; float dx, dy; fz_point p; float adv; int i, x, y, w, h, fterr; if (font->ftface) { FT_Set_Transform(font->ftface, NULL, NULL); fterr = FT_Set_Char_Size(font->ftface, 64, 64, 72, 72); if (fterr) fz_warn("freetype set character size: %s", ft_errorstring(fterr)); } for (i = 0; i < text->len; i++) { tm.e = text->els[i].x; tm.f = text->els[i].y; trm = fz_concat(tm, ctm); x = trm.e; y = trm.f; trm.e = 0; trm.f = 0; p.x = text->els[i].x; p.y = text->els[i].y; p = fz_transformpoint(inv, p); dx = oldpt->x - p.x; dy = oldpt->y - p.y; *oldpt = p; /* TODO: flip advance and test for vertical writing */ if (font->ftface) { FT_Fixed ftadv; fterr = FT_Get_Advance(font->ftface, text->els[i].gid, FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING, &ftadv); if (fterr) fz_warn("freetype get advance (gid %d): %s", text->els[i].gid, ft_errorstring(fterr)); adv = ftadv / 65536.0; oldpt->x += adv; } else { adv = font->t3widths[text->els[i].gid]; oldpt->x += adv; } bbox.x0 = font->bbox.x0 / 1000.0; bbox.x1 = bbox.x0 + adv; bbox.y0 = font->bbox.y0 / 1000.0; bbox.y1 = font->bbox.y1 / 1000.0; bbox = fz_transformrect(foo, bbox); w = bbox.x1 - bbox.x0; h = bbox.y1 - bbox.y0; x += bbox.x0; y = y - h - bbox.y0; if (fabs(dy) > 0.2) { fz_textspan *newline; newline = fz_newtextspan(); (*line)->next = newline; *line = newline; } else if (fabs(dx) > 0.2) { fz_addtextchar(*line, x, y, w, h, ' '); } - +//Code change by Kakai +//line->listitemid = text->id; fz_addtextchar(*line, x, y, w, h, text->els[i].ucs); } } static void fz_textfilltext(void *user, fz_text *text, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_textdevice *tdev = user; fz_textextractline(&tdev->line, text, ctm, &tdev->point); } static void fz_textignoretext(void *user, fz_text *text, fz_matrix ctm) { fz_textdevice *tdev = user; fz_textextractline(&tdev->line, text, ctm, &tdev->point); } static void fz_textfreeuser(void *user) { fz_textdevice *tdev = user; fz_free(tdev); } fz_device * fz_newtextdevice(fz_textspan *root) { fz_textdevice *tdev = fz_malloc(sizeof(fz_textdevice)); tdev->line = root; tdev->point.x = -1; tdev->point.y = -1; fz_device *dev = fz_newdevice(tdev); dev->freeuser = fz_textfreeuser; dev->filltext = fz_textfilltext; dev->ignoretext = fz_textignoretext; return dev; } diff --git a/fitz/fitz_res.h b/fitz/fitz_res.h index eb8df7e..e5bc70b 100644 --- a/fitz/fitz_res.h +++ b/fitz/fitz_res.h @@ -1,373 +1,376 @@ /* * Resources and other graphics related objects. */ typedef struct fz_pixmap_s fz_pixmap; typedef struct fz_colorspace_s fz_colorspace; typedef struct fz_path_s fz_path; typedef struct fz_text_s fz_text; typedef struct fz_font_s fz_font; typedef struct fz_shade_s fz_shade; enum { FZ_MAXCOLORS = 32 }; typedef enum fz_blendkind_e { /* PDF 1.4 -- standard separable */ FZ_BNORMAL, FZ_BMULTIPLY, FZ_BSCREEN, FZ_BOVERLAY, FZ_BDARKEN, FZ_BLIGHTEN, FZ_BCOLORDODGE, FZ_BCOLORBURN, FZ_BHARDLIGHT, FZ_BSOFTLIGHT, FZ_BDIFFERENCE, FZ_BEXCLUSION, /* PDF 1.4 -- standard non-separable */ FZ_BHUE, FZ_BSATURATION, FZ_BCOLOR, FZ_BLUMINOSITY } fz_blendkind; /* pixmaps have n components per pixel. the first is always alpha. premultiplied alpha when rendering, but non-premultiplied for colorspace conversions and rescaling. */ extern fz_colorspace *pdf_devicegray; extern fz_colorspace *pdf_devicergb; extern fz_colorspace *pdf_devicecmyk; extern fz_colorspace *pdf_devicelab; extern fz_colorspace *pdf_devicepattern; struct fz_pixmap_s { int refs; int x, y, w, h, n; fz_colorspace *colorspace; unsigned char *samples; }; fz_pixmap * fz_newpixmapwithrect(fz_colorspace *, fz_bbox bbox); fz_pixmap * fz_newpixmap(fz_colorspace *, int x, int y, int w, int h); fz_pixmap *fz_keeppixmap(fz_pixmap *map); void fz_droppixmap(fz_pixmap *map); void fz_debugpixmap(fz_pixmap *map, char *prefix); void fz_clearpixmap(fz_pixmap *map, unsigned char value); fz_pixmap * fz_scalepixmap(fz_pixmap *src, int xdenom, int ydenom); /* * The device interface. */ typedef struct fz_device_s fz_device; struct fz_device_s { void *user; void (*freeuser)(void *); void (*fillpath)(void *, fz_path *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*strokepath)(void *, fz_path *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*clippath)(void *, fz_path *, fz_matrix); void (*filltext)(void *, fz_text *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*stroketext)(void *, fz_text *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*cliptext)(void *, fz_text *, fz_matrix); void (*ignoretext)(void *, fz_text *, fz_matrix); void (*fillshade)(void *, fz_shade *shd, fz_matrix ctm); void (*fillimage)(void *, fz_pixmap *img, fz_matrix ctm); void (*fillimagemask)(void *, fz_pixmap *img, fz_matrix ctm, fz_colorspace *, float *color, float alpha); void (*clipimagemask)(void *, fz_pixmap *img, fz_matrix ctm); void (*popclip)(void *); }; fz_device *fz_newdevice(void *user); void fz_freedevice(fz_device *dev); fz_device *fz_newtracedevice(void); /* Text extraction device */ typedef struct fz_textspan_s fz_textspan; typedef struct fz_textchar_s fz_textchar; struct fz_textchar_s { int c, x, y, w; }; struct fz_textspan_s { int ascender, descender; int len, cap; + //code change by kakai fz_bbox bbox; + int listitemid; + //code change by kakai fz_textchar *text; fz_textspan *next; }; fz_textspan * fz_newtextspan(void); void fz_freetextspan(fz_textspan *line); void fz_debugtextspan(fz_textspan *line); fz_device *fz_newtextdevice(fz_textspan *text); /* Display list device -- record and play back device commands. */ typedef struct fz_displaylist_s fz_displaylist; typedef struct fz_displaynode_s fz_displaynode; typedef enum fz_displaycommand_e { FZ_CMDFILLPATH, FZ_CMDSTROKEPATH, FZ_CMDCLIPPATH, FZ_CMDFILLTEXT, FZ_CMDSTROKETEXT, FZ_CMDCLIPTEXT, FZ_CMDIGNORETEXT, FZ_CMDFILLSHADE, FZ_CMDFILLIMAGE, FZ_CMDFILLIMAGEMASK, FZ_CMDCLIPIMAGEMASK, FZ_CMDPOPCLIP, } fz_displaycommand; struct fz_displaylist_s { fz_displaynode *first; fz_displaynode *last; }; struct fz_displaynode_s { fz_displaycommand cmd; fz_displaynode *next; union { fz_path *path; fz_text *text; fz_shade *shade; fz_pixmap *image; } item; //code change by kakai int id; int ishighlighted; int isunderline; int isbookmark; //code change by kakai fz_matrix ctm; fz_colorspace *colorspace; float alpha; float color[FZ_MAXCOLORS]; }; fz_displaylist *fz_newdisplaylist(void); void fz_freedisplaylist(fz_displaylist *list); fz_device *fz_newlistdevice(fz_displaylist *list); void fz_executedisplaylist(fz_displaylist *list, fz_device *dev, fz_matrix ctm); /* * Vector path buffer. * It can be stroked and dashed, or be filled. * It has a fill rule (nonzero or evenodd). * * When rendering, they are flattened, stroked and dashed straight * into the Global Edge List. */ typedef struct fz_stroke_s fz_stroke; typedef union fz_pathel_s fz_pathel; typedef enum fz_pathelkind_e { FZ_MOVETO, FZ_LINETO, FZ_CURVETO, FZ_CLOSEPATH } fz_pathelkind; union fz_pathel_s { fz_pathelkind k; float v; }; struct fz_path_s { int evenodd; int linecap; int linejoin; float linewidth; float miterlimit; float dashphase; int dashlen; float dashlist[32]; int len, cap; fz_pathel *els; }; fz_path *fz_newpath(void); void fz_moveto(fz_path*, float x, float y); void fz_lineto(fz_path*, float x, float y); void fz_curveto(fz_path*, float, float, float, float, float, float); void fz_curvetov(fz_path*, float, float, float, float); void fz_curvetoy(fz_path*, float, float, float, float); void fz_closepath(fz_path*); void fz_resetpath(fz_path *path); void fz_freepath(fz_path *path); fz_path *fz_clonepath(fz_path *old); fz_rect fz_boundpath(fz_path *path, fz_matrix ctm, int dostroke); void fz_debugpath(fz_path *, int indent); /* * Text buffer. * * The trm field contains the a, b, c and d coefficients. * The e and f coefficients come from the individual elements, * together they form the transform matrix for the glyph. * * Glyphs are referenced by glyph ID. * The Unicode text equivalent is kept in a separate array * with indexes into the glyph array. */ typedef struct fz_textel_s fz_textel; struct fz_textel_s { float x, y; int gid; int ucs; }; struct fz_text_s { fz_font *font; fz_matrix trm; int len, cap; fz_textel *els; }; fz_text * fz_newtext(fz_font *face); void fz_addtext(fz_text *text, int gid, int ucs, float x, float y); void fz_endtext(fz_text *text); void fz_resettext(fz_text *text); void fz_freetext(fz_text *text); void fz_debugtext(fz_text*, int indent); fz_text *fz_clonetext(fz_text *old); /* * Colorspace resources. * * TODO: use lcms */ struct fz_colorspace_s { int refs; char name[16]; int n; void (*convpixmap)(fz_colorspace *ss, fz_pixmap *sp, fz_colorspace *ds, fz_pixmap *dp); void (*convcolor)(fz_colorspace *ss, float *sv, fz_colorspace *ds, float *dv); void (*toxyz)(fz_colorspace *, float *src, float *xyz); void (*fromxyz)(fz_colorspace *, float *xyz, float *dst); void (*freefunc)(fz_colorspace *); }; fz_colorspace *fz_keepcolorspace(fz_colorspace *cs); void fz_dropcolorspace(fz_colorspace *cs); void fz_convertcolor(fz_colorspace *srcs, float *srcv, fz_colorspace *dsts, float *dstv); void fz_convertpixmap(fz_colorspace *srcs, fz_pixmap *srcv, fz_colorspace *dsts, fz_pixmap *dstv); void fz_stdconvcolor(fz_colorspace *srcs, float *srcv, fz_colorspace *dsts, float *dstv); void fz_stdconvpixmap(fz_colorspace *srcs, fz_pixmap *srcv, fz_colorspace *dsts, fz_pixmap *dstv); /* * Fonts. * * Fonts come in three variants: * Regular fonts are handled by FreeType. * Type 3 fonts have callbacks to the interpreter. * Substitute fonts are a thin wrapper over a regular font that adjusts metrics. */ char *ft_errorstring(int err); struct fz_font_s { int refs; char name[32]; void *ftface; /* has an FT_Face if used */ int ftsubstitute; /* ... substitute metrics */ int fthint; /* ... force hinting for DynaLab fonts */ fz_matrix t3matrix; fz_obj *t3resources; fz_buffer **t3procs; /* has 256 entries if used */ float *t3widths; /* has 256 entries if used */ void *t3xref; /* a pdf_xref for the callback */ fz_error (*t3runcontentstream)(fz_device *dev, fz_matrix ctm, struct pdf_xref_s *xref, fz_obj *resources, fz_buffer *contents); fz_rect bbox; }; fz_error fz_newfreetypefont(fz_font **fontp, char *name, int substitute); fz_error fz_loadfreetypefontfile(fz_font *font, char *path, int index); fz_error fz_loadfreetypefontbuffer(fz_font *font, unsigned char *data, int len, int index); fz_font * fz_newtype3font(char *name, fz_matrix matrix); fz_error fz_newfontfrombuffer(fz_font **fontp, unsigned char *data, int len, int index); fz_error fz_newfontfromfile(fz_font **fontp, char *path, int index); fz_font * fz_keepfont(fz_font *font); void fz_dropfont(fz_font *font); void fz_debugfont(fz_font *font); void fz_setfontbbox(fz_font *font, float xmin, float ymin, float xmax, float ymax); /* * The shading code is in rough shape but the general architecture is sound. */ struct fz_shade_s { int refs; fz_rect bbox; /* can be fz_infiniterect */ fz_colorspace *cs; fz_matrix matrix; /* matrix from pattern dict */ int usebackground; /* background color for fills but not 'sh' */ float background[FZ_MAXCOLORS]; int usefunction; float function[256][FZ_MAXCOLORS]; int meshlen; int meshcap; float *mesh; /* [x y t] or [x y c1 ... cn] * 3 * meshlen */ }; fz_shade *fz_keepshade(fz_shade *shade); void fz_dropshade(fz_shade *shade); fz_rect fz_boundshade(fz_shade *shade, fz_matrix ctm); void fz_rendershade(fz_shade *shade, fz_matrix ctm, fz_colorspace *dsts, fz_pixmap *dstp);
fkhan/mupdf_fareed
e3f65eb0771b5bd34522e8e511953b1f4fc5f6e4
muPDF api functions
diff --git a/apps/kno_pdfapp.c b/apps/kno_pdfapp.c new file mode 100644 index 0000000..d49ab79 --- /dev/null +++ b/apps/kno_pdfapp.c @@ -0,0 +1,165 @@ +#include <fitz.h> +#include <mupdf.h> +#include "pdfapp.h" +#include "kno_pdfapp.h" + +void kno_addHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1) +{ + app->selr.x0 = x0; + app->selr.x1 = x1; + app->selr.y0 = y0; + app->selr.y1 = y1; + kno_onselect(app); + winrepaint(app); +} + +void kno_changeHighlightColor(pdfapp_t *app, unsigned long color) +{ + app->highlightedcolor = color; +} + +void kno_UpdateHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1) +{ + kno_addHighlight(app, x0, y0, x1, y1); +} + +kno_highlightedtext * +kno_getHighlightedText(pdfapp_t *app) +{ +kno_highlightedtext *result = fz_malloc(sizeof(kno_highlightedtext)); +return result; +} + + +fz_textspan *pdfapp_gettextline(pdfapp_t *app, int linenum) +{ + /* lines numbered from 1 */ + fz_textspan *ln = app->text; + int n = 1; + while (ln && n!=linenum) { + n++; + ln = ln->next; + } + + return ln; + +} + +void kno_clearselect(pdfapp_t *app) +{ + printf("clearSelect\n"); + app->firstline = app->lastline = 0; + app->firstchar = app->firstchar = -1; + app->sellen = 0; +} + +void kno_applyselect(pdfapp_t *app) +{ + fz_textspan *firstline, *lastline, *ln; + int i,n=0; + + if (!app->firstline) + return; + + firstline = pdfapp_gettextline(app, app->firstline); + if (firstline) { + XRectangle box; + box.x = firstline->text[app->firstchar].x; + box.y = firstline->bbox.y0; + box.height = firstline->bbox.y1 - firstline->bbox.y0 + 1; + lastline = pdfapp_gettextline(app, app->lastline); + if (lastline != firstline) { + box.width = firstline->bbox.x1 - box.x + 1; + + app->selrects[n++] = box; + + ln = firstline->next; + while (ln != lastline) { + app->selrects[n].x = ln->bbox.x0; + app->selrects[n].y = ln->bbox.y0; + app->selrects[n].width = ln->bbox.x1 - ln->bbox.x0 + 1; + app->selrects[n].height = ln->bbox.y1 - ln->bbox.y0 + 1; + ln = ln->next; + n++; + } + + + box.x = lastline->bbox.x0; + box.width = lastline->text[app->lastchar].x - lastline->text[0].x + + lastline->text[app->lastchar].w; + + box.y = lastline->bbox.y0; + box.height = lastline->bbox.y1 - lastline->bbox.y0 + 1; + app->selrects[n++] = box; + } + else { + box.width = lastline->text[app->lastchar].x - box.x + + lastline->text[app->lastchar].w; + + app->selrects[n++] = box; + + } + + } + + + + for (i=0; i<n; i++) { + app->selrects[i].x += app->panx; + app->selrects[i].y += app->pany; + } + + app->sellen = n; +} + + +void kno_onselect(pdfapp_t *app) +{ + fz_textspan *ln; + int x0 = app->image->x + app->selr.x0 - app->panx; + int x1 = app->image->x + app->selr.x1 - app->panx; + int y0 = app->image->y + app->selr.y0 - app->pany; + int y1 = app->image->y + app->selr.y1 - app->pany; + int n, i; + + int firstline, lastline, firstchar, lastchar; + int linenum = 0; + + n=0; + firstline = lastline = firstchar = lastchar = 0; + for (ln = app->text; ln; ln = ln->next) { + linenum++; + if (ln->len > 0) { + for (i = 0; i < ln->len; i++) { + + int x = ln->text[i].x; + int y = ln->text[i].y; + if (x >= x0 && x <= x1 && y >= y0 && y <= y1) { + + if (!firstline) { + firstchar = i; + firstline = linenum; + } + lastchar = i; + lastline = linenum; + + } + } + } + } + + app->firstline = firstline; + app->lastline = lastline; + app->firstchar = firstchar; + app->lastchar = lastchar; + + kno_applyselect(app); +} + + +void kno_allocselection(pdfapp_t *app) +{ + /* JB: do something smarter */ + if (!app->selrects) + app->selrects = malloc(sizeof(*app->selrects) * 16000); +} diff --git a/apps/kno_pdfapp.h b/apps/kno_pdfapp.h new file mode 100644 index 0000000..907c963 --- /dev/null +++ b/apps/kno_pdfapp.h @@ -0,0 +1,23 @@ +/* + * Utility object for handling a pdf application / view + * Takes care of PDF loading and displaying and navigation, + * uses a number of callbacks to the GUI app. + */ + +#include <X11/Xlib.h> + +typedef struct kno_highlightedtext_s kno_highlightedtext; + +struct kno_highlightedtext_s +{ + fz_textspan *text; +}; + +void kno_onselect(pdfapp_t *app); +void kno_clearselect(pdfapp_t *app); +void kno_applyselect(pdfapp_t *app); +void kno_addHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1); +void kno_changeHighlightColor(pdfapp_t *app, unsigned long color); +void kno_UpdateHighlight(pdfapp_t *app, int x0, int y0, int x1, int y1); +kno_highlightedtext *getHighlightedText(pdfapp_t *app); +void kno_allocselection(pdfapp_t *app);
fkhan/mupdf_fareed
0fcbacb28558dfb145ddb5011ae7ad7248f788a8
With muPDF api's
diff --git a/Makefile b/Makefile index de4298b..db134d3 100644 --- a/Makefile +++ b/Makefile @@ -1,360 +1,361 @@ # GNU Makefile for MuPDF # # make build=release prefix=$HOME install # prefix ?= /usr/local build ?= debug default: all # # Compiler and configuration # OS := $(shell uname) OS := $(OS:MINGW%=MINGW) LIBS := -ljbig2dec -lopenjpeg -lfreetype -ljpeg -lz CFLAGS := -Wall --std=gnu99 -Ifitz -Imupdf LDFLAGS = CC = cc LD = $(CC) AR = ar ifeq "$(build)" "debug" CFLAGS += -g -O0 endif ifeq "$(build)" "release" CFLAGS += -O2 endif ifeq "$(OS)" "Linux" CFLAGS += `pkg-config --cflags freetype2` LDFLAGS += `pkg-config --libs freetype2` X11LIBS = -lX11 -lXext PDFVIEW_EXE = $(X11VIEW_EXE) endif ifeq "$(OS)" "Darwin" CFLAGS += -I$(HOME)/include -I/usr/X11R6/include -I/usr/X11R6/include/freetype2 -DARCH_X86_64 LDFLAGS += -L$(HOME)/lib -L/usr/X11R6/lib X11LIBS = -lX11 -lXext PDFVIEW_EXE = $(X11VIEW_EXE) ARCH_SRC = archx86.c endif ifeq "$(OS)" "MINGW" CC = gcc CFLAGS += -Ic:/msys/1.0/local/include LDFLAGS += -Lc:/msys/1.0/local/lib W32LIBS = -lgdi32 -lcomdlg32 -luser32 -ladvapi32 -lshell32 -mwindows PDFVIEW_EXE = $(WINVIEW_EXE) endif # Edit these if you are cross compiling: HOSTCC ?= $(CC) HOSTLD ?= $(HOSTCC) HOSTCFLAGS ?= $(CFLAGS) HOSTLDFLAGS ?= $(LDFLAGS) # # Build commands # HOSTCC_CMD = @ echo HOSTCC $@ && $(HOSTCC) -o $@ -c $< $(HOSTCFLAGS) HOSTLD_CMD = @ echo HOSTLD $@ && $(HOSTLD) -o $@ $^ $(HOSTLDFLAGS) GENFILE_CMD = @ echo GENFILE $@ && $(firstword $^) $@ $(wordlist 2, 999, $^) CC_CMD = @ echo CC $@ && $(CC) -o $@ -c $< $(CFLAGS) LD_CMD = @ echo LD $@ && $(LD) -o $@ $^ $(LDFLAGS) $(LIBS) AR_CMD = @ echo AR $@ && $(AR) cru $@ $^ # # Directories # OBJDIR = build/$(build) GENDIR = build/generated HOSTDIR = build/host DIRS = $(OBJDIR) $(GENDIR) $(HOSTDIR) $(DIRS): mkdir -p $@ # # Sources # FITZ_HDR=fitz/fitz.h fitz/fitz_base.h fitz/fitz_draw.h fitz/fitz_stream.h fitz/fitz_res.h fitz/kno_fitz_res.h FITZ_SRC=$(addprefix fitz/, \ base_cpudep.c \ base_error.c base_memory.c base_string.c base_unicode.c \ base_hash.c base_matrix.c base_rect.c \ crypt_aes.c crypt_arc4.c crypt_md5.c \ filt_aesd.c filt_arc4.c filt_basic.c filt_dctd.c filt_faxd.c filt_faxdtab.c filt_flate.c \ filt_jbig2d.c filt_jpxd.c filt_lzwd.c filt_pipeline.c filt_predict.c \ dev_null.c dev_text.c dev_draw.c dev_list.c dev_trace.c kno_dev_list.c \ obj_array.c obj_dict.c obj_print.c obj_simple.c \ res_colorspace.c res_font.c res_shade.c res_pixmap.c \ res_path.c res_text.c \ stm_buffer.c stm_filter.c stm_misc.c stm_open.c stm_read.c \ util_getopt.c util_gettimeofday.c ) FITZ_OBJ=$(FITZ_SRC:fitz/%.c=$(OBJDIR)/%.o) FITZ_LIB=$(OBJDIR)/libfitz.a $(FITZ_OBJ): $(FITZ_HDR) $(FITZ_LIB): $(FITZ_OBJ) $(AR_CMD) DRAW_SRC=$(addprefix draw/, $(ARCH_SRC) \ blendmodes.c glyphcache.c imagedraw.c imagescale.c imageunpack.c meshdraw.c \ pathfill.c pathscan.c pathstroke.c porterduff.c ) DRAW_OBJ=$(DRAW_SRC:draw/%.c=$(OBJDIR)/%.o) DRAW_LIB=$(OBJDIR)/libdraw.a $(DRAW_OBJ): $(FITZ_HDR) $(DRAW_LIB): $(DRAW_OBJ) $(AR_CMD) MUPDF_HDR=$(FITZ_HDR) mupdf/mupdf.h MUPDF_SRC=$(addprefix mupdf/, \ pdf_annot.c pdf_build.c pdf_cmap.c pdf_cmap_load.c pdf_cmap_parse.c \ pdf_cmap_table.c pdf_colorspace.c pdf_crypt.c pdf_debug.c \ pdf_font.c pdf_fontagl.c pdf_fontenc.c pdf_fontfile.c pdf_fontmtx.c \ pdf_function.c pdf_image.c pdf_interpret.c pdf_lex.c pdf_nametree.c pdf_open.c \ pdf_outline.c pdf_page.c pdf_pagetree.c pdf_parse.c pdf_pattern.c pdf_repair.c \ pdf_shade.c pdf_store.c pdf_stream.c pdf_type3.c \ pdf_unicode.c pdf_xobject.c pdf_xref.c ) MUPDF_OBJ=$(MUPDF_SRC:mupdf/%.c=$(OBJDIR)/%.o) MUPDF_LIB=$(OBJDIR)/libmupdf.a $(MUPDF_OBJ): $(MUPDF_HDR) $(MUPDF_LIB): $(MUPDF_OBJ) $(AR_CMD) $(OBJDIR)/%.o: fitz/%.c $(CC_CMD) $(OBJDIR)/%.o: draw/%.c $(CC_CMD) $(OBJDIR)/%.o: mupdf/%.c $(CC_CMD) # # Code generation tools run on the host # FONTDUMP_EXE=$(HOSTDIR)/fontdump CMAPDUMP_EXE=$(HOSTDIR)/cmapdump $(FONTDUMP_EXE): $(HOSTDIR)/fontdump.o $(HOSTLD_CMD) $(CMAPDUMP_EXE): $(HOSTDIR)/cmapdump.o $(HOSTLD_CMD) $(HOSTDIR)/%.o: mupdf/%.c $(HOSTCC_CMD) $(OBJDIR)/%.o: $(GENDIR)/%.c $(CC_CMD) # # Generated font file dumps # BASEFONT_FILES=$(addprefix fonts/, \ Dingbats.cff NimbusMonL-Bold.cff NimbusMonL-BoldObli.cff NimbusMonL-Regu.cff \ NimbusMonL-ReguObli.cff NimbusRomNo9L-Medi.cff NimbusRomNo9L-MediItal.cff \ NimbusRomNo9L-Regu.cff NimbusRomNo9L-ReguItal.cff NimbusSanL-Bold.cff \ NimbusSanL-BoldItal.cff NimbusSanL-Regu.cff NimbusSanL-ReguItal.cff \ StandardSymL.cff URWChanceryL-MediItal.cff ) CJKFONT_FILES=fonts/droid/DroidSansFallback.ttf $(GENDIR)/font_base14.c: $(FONTDUMP_EXE) $(BASEFONT_FILES) $(GENFILE_CMD) $(GENDIR)/font_cjk.c: $(FONTDUMP_EXE) $(CJKFONT_FILES) $(GENFILE_CMD) FONT_SRC=\ $(GENDIR)/font_base14.c \ $(GENDIR)/font_cjk.c FONT_OBJ=$(FONT_SRC:$(GENDIR)/%.c=$(OBJDIR)/%.o) FONT_LIB=$(OBJDIR)/libfonts.a $(FONT_LIB): $(FONT_OBJ) $(AR_CMD) # # Generated CMap file dumps # CMAP_UNICODE_FILES=$(addprefix cmaps/, \ Adobe-CNS1-UCS2 Adobe-GB1-UCS2 \ Adobe-Japan1-UCS2 Adobe-Korea1-UCS2 ) CMAP_CNS_FILES=$(addprefix cmaps/, \ Adobe-CNS1-0 Adobe-CNS1-1 Adobe-CNS1-2 Adobe-CNS1-3 \ Adobe-CNS1-4 Adobe-CNS1-5 Adobe-CNS1-6 B5-H B5-V B5pc-H B5pc-V \ CNS-EUC-H CNS-EUC-V CNS1-H CNS1-V CNS2-H CNS2-V ETen-B5-H \ ETen-B5-V ETenms-B5-H ETenms-B5-V ETHK-B5-H ETHK-B5-V \ HKdla-B5-H HKdla-B5-V HKdlb-B5-H HKdlb-B5-V HKgccs-B5-H \ HKgccs-B5-V HKm314-B5-H HKm314-B5-V HKm471-B5-H HKm471-B5-V \ HKscs-B5-H HKscs-B5-V UniCNS-UCS2-H UniCNS-UCS2-V \ UniCNS-UTF16-H UniCNS-UTF16-V ) CMAP_GB_FILES=$(addprefix cmaps/, \ Adobe-GB1-0 Adobe-GB1-1 Adobe-GB1-2 Adobe-GB1-3 Adobe-GB1-4 \ Adobe-GB1-5 GB-EUC-H GB-EUC-V GB-H GB-V GBK-EUC-H GBK-EUC-V \ GBK2K-H GBK2K-V GBKp-EUC-H GBKp-EUC-V GBpc-EUC-H GBpc-EUC-V \ GBT-EUC-H GBT-EUC-V GBT-H GBT-V GBTpc-EUC-H GBTpc-EUC-V \ UniGB-UCS2-H UniGB-UCS2-V UniGB-UTF16-H UniGB-UTF16-V ) CMAP_JAPAN_FILES=$(addprefix cmaps/, \ 78-EUC-H 78-EUC-V 78-H 78-RKSJ-H 78-RKSJ-V 78-V 78ms-RKSJ-H \ 78ms-RKSJ-V 83pv-RKSJ-H 90ms-RKSJ-H 90ms-RKSJ-V 90msp-RKSJ-H \ 90msp-RKSJ-V 90pv-RKSJ-H 90pv-RKSJ-V Add-H Add-RKSJ-H \ Add-RKSJ-V Add-V Adobe-Japan1-0 Adobe-Japan1-1 Adobe-Japan1-2 \ Adobe-Japan1-3 Adobe-Japan1-4 Adobe-Japan1-5 Adobe-Japan1-6 \ EUC-H EUC-V Ext-H Ext-RKSJ-H Ext-RKSJ-V Ext-V H Hankaku \ Hiragana Katakana NWP-H NWP-V RKSJ-H RKSJ-V Roman \ UniJIS-UCS2-H UniJIS-UCS2-HW-H UniJIS-UCS2-HW-V UniJIS-UCS2-V \ UniJISPro-UCS2-HW-V UniJISPro-UCS2-V V WP-Symbol \ Adobe-Japan2-0 Hojo-EUC-H Hojo-EUC-V Hojo-H Hojo-V \ UniHojo-UCS2-H UniHojo-UCS2-V UniHojo-UTF16-H UniHojo-UTF16-V \ UniJIS-UTF16-H UniJIS-UTF16-V ) CMAP_KOREA_FILES=$(addprefix cmaps/, \ Adobe-Korea1-0 Adobe-Korea1-1 Adobe-Korea1-2 KSC-EUC-H \ KSC-EUC-V KSC-H KSC-Johab-H KSC-Johab-V KSC-V KSCms-UHC-H \ KSCms-UHC-HW-H KSCms-UHC-HW-V KSCms-UHC-V KSCpc-EUC-H \ KSCpc-EUC-V UniKS-UCS2-H UniKS-UCS2-V UniKS-UTF16-H UniKS-UTF16-V ) $(GENDIR)/cmap_unicode.c: $(CMAPDUMP_EXE) $(CMAP_UNICODE_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_cns.c: $(CMAPDUMP_EXE) $(CMAP_CNS_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_gb.c: $(CMAPDUMP_EXE) $(CMAP_GB_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_japan.c: $(CMAPDUMP_EXE) $(CMAP_JAPAN_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_korea.c: $(CMAPDUMP_EXE) $(CMAP_KOREA_FILES) $(GENFILE_CMD) CMAP_SRC=\ $(GENDIR)/cmap_unicode.c \ $(GENDIR)/cmap_cns.c \ $(GENDIR)/cmap_gb.c \ $(GENDIR)/cmap_japan.c \ $(GENDIR)/cmap_korea.c CMAP_OBJ=$(CMAP_SRC:$(GENDIR)/%.c=$(OBJDIR)/%.o) CMAP_LIB=$(OBJDIR)/libcmaps.a $(CMAP_OBJ): $(MUPDF_HDR) $(CMAP_LIB): $(CMAP_OBJ) $(AR_CMD) # # Apps # APPS = $(PDFSHOW_EXE) $(PDFCLEAN_EXE) $(PDFDRAW_EXE) $(PDFEXTRACT_EXE) $(PDFINFO_EXE) $(PDFVIEW_EXE) +PDFKNOAPP_HDR = apps/kno_pdfapp.h PDFAPP_HDR = apps/pdfapp.h PDFTOOL_HDR = apps/pdftool.h $(OBJDIR)/%.o: apps/%.c $(CC_CMD) PDFSHOW_SRC=apps/pdfshow.c apps/pdftool.c PDFSHOW_OBJ=$(PDFSHOW_SRC:apps/%.c=$(OBJDIR)/%.o) PDFSHOW_EXE=$(OBJDIR)/pdfshow $(PDFSHOW_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFSHOW_EXE): $(PDFSHOW_OBJ) $(MUPDF_LIB) $(FITZ_LIB) $(LD_CMD) PDFCLEAN_SRC=apps/pdfclean.c apps/pdftool.c PDFCLEAN_OBJ=$(PDFCLEAN_SRC:apps/%.c=$(OBJDIR)/%.o) PDFCLEAN_EXE=$(OBJDIR)/pdfclean $(PDFCLEAN_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFCLEAN_EXE): $(PDFCLEAN_OBJ) $(MUPDF_LIB) $(FITZ_LIB) $(LD_CMD) PDFDRAW_SRC=apps/pdfdraw.c apps/pdftool.c PDFDRAW_OBJ=$(PDFDRAW_SRC:apps/%.c=$(OBJDIR)/%.o) PDFDRAW_EXE=$(OBJDIR)/pdfdraw $(PDFDRAW_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFDRAW_EXE): $(PDFDRAW_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) PDFEXTRACT_SRC=apps/pdfextract.c apps/pdftool.c PDFEXTRACT_OBJ=$(PDFEXTRACT_SRC:apps/%.c=$(OBJDIR)/%.o) PDFEXTRACT_EXE=$(OBJDIR)/pdfextract $(PDFEXTRACT_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFEXTRACT_EXE): $(PDFEXTRACT_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) PDFINFO_SRC=apps/pdfinfo.c apps/pdftool.c PDFINFO_OBJ=$(PDFINFO_SRC:apps/%.c=$(OBJDIR)/%.o) PDFINFO_EXE=$(OBJDIR)/pdfinfo $(PDFINFO_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFINFO_EXE): $(PDFINFO_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) -X11VIEW_SRC=apps/x11_main.c apps/x11_image.c apps/pdfapp.c +X11VIEW_SRC=apps/x11_main.c apps/x11_image.c apps/kno_pdfapp.c apps/pdfapp.c X11VIEW_OBJ=$(X11VIEW_SRC:apps/%.c=$(OBJDIR)/%.o) X11VIEW_EXE=$(OBJDIR)/mupdf -$(X11VIEW_OBJ): $(MUPDF_HDR) $(PDFAPP_HDR) +$(X11VIEW_OBJ): $(MUPDF_HDR) $(PDFKNOAPP_HDR) $(PDFAPP_HDR) $(X11VIEW_EXE): $(X11VIEW_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) $(X11LIBS) -WINVIEW_SRC=apps/win_main.c apps/pdfapp.c +WINVIEW_SRC=apps/win_main.c apps/kno_pdfapp.c apps/pdfapp.c WINVIEW_RES=apps/win_res.rc WINVIEW_OBJ=$(WINVIEW_SRC:apps/%.c=$(OBJDIR)/%.o) $(WINVIEW_RES:apps/%.rc=$(OBJDIR)/%.o) WINVIEW_EXE=$(OBJDIR)/mupdf.exe $(OBJDIR)/%.o: apps/%.rc windres -i $< -o $@ --include-dir=apps -$(WINVIEW_OBJ): $(MUPDF_HDR) $(PDFAPP_HDR) +$(WINVIEW_OBJ): $(MUPDF_HDR) $(PDFKNOAPP_HDR) $(PDFAPP_HDR) $(WINVIEW_EXE): $(WINVIEW_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) $(W32LIBS) # # Installation and tarball packaging # dist: $(DIRS) $(APPS) mkdir -p mupdf-dist cp README COPYING $(APPS) mupdf-dist tar cvf mupdf-dist.tar mupdf-dist rm -rf mupdf-dist # # Default rules # all: $(DIRS) $(APPS) clean: rm -rf $(OBJDIR)/* rm -rf $(GENDIR)/* rm -rf $(HOSTDIR)/* nuke: rm -rf build install: $(DIRS) $(APPS) install $(APPS) $(prefix)/bin diff --git a/apps/pdfapp.c b/apps/pdfapp.c index 79edfe4..77c486e 100644 --- a/apps/pdfapp.c +++ b/apps/pdfapp.c @@ -1,678 +1,689 @@ #include <fitz.h> #include <mupdf.h> #include "pdfapp.h" +#include "kno_pdfapp.h" enum panning { DONT_PAN = 0, PAN_TO_TOP, PAN_TO_BOTTOM }; static void pdfapp_showpage(pdfapp_t *app, int loadpage, int drawpage); + static void pdfapp_warn(pdfapp_t *app, const char *fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); winwarn(app, buf); } static void pdfapp_error(pdfapp_t *app, fz_error error) { winerror(app, error); } char *pdfapp_usage(pdfapp_t *app) { return " l <\t\t-- rotate left\n" " r >\t\t-- rotate right\n" " u up\t\t-- scroll up\n" " d down\t-- scroll down\n" " = +\t\t-- zoom in\n" " -\t\t-- zoom out\n" " w\t\t-- shrinkwrap\n" "\n" " n pgdn space\t-- next page\n" " b pgup back\t-- previous page\n" " right\t\t-- next page\n" " left\t\t-- previous page\n" " N F\t\t-- next 10\n" " B\t\t-- back 10\n" " m\t\t-- mark page for snap back\n" " t\t\t-- pop back to last mark\n" " 123g\t\t-- go to page\n" "\n" " left drag to pan, right drag to copy text\n"; } void pdfapp_init(pdfapp_t *app) { memset(app, 0, sizeof(pdfapp_t)); app->scrw = 640; app->scrh = 480; app->zoom = 1.0; app->cache = fz_newglyphcache(); } void pdfapp_open(pdfapp_t *app, char *filename) { fz_obj *obj; fz_obj *info; char *password = ""; /* * Open PDF and load xref table */ app->filename = filename; app->xref = pdf_openxref(filename); if (!app->xref) pdfapp_error(app, -1); /* * Handle encrypted PDF files */ if (pdf_needspassword(app->xref)) { int okay = pdf_authenticatepassword(app->xref, password); while (!okay) { password = winpassword(app, filename); if (!password) exit(1); okay = pdf_authenticatepassword(app->xref, password); if (!okay) pdfapp_warn(app, "Invalid password."); } } /* * Load meta information */ app->outline = pdf_loadoutline(app->xref); app->doctitle = filename; if (strrchr(app->doctitle, '\\')) app->doctitle = strrchr(app->doctitle, '\\') + 1; if (strrchr(app->doctitle, '/')) app->doctitle = strrchr(app->doctitle, '/') + 1; info = fz_dictgets(app->xref->trailer, "Info"); if (info) { obj = fz_dictgets(info, "Title"); if (obj) app->doctitle = pdf_toutf8(obj); } /* * Start at first page */ app->pagecount = pdf_getpagecount(app->xref); app->shrinkwrap = 1; if (app->pageno < 1) app->pageno = 1; if (app->zoom < 0.1) app->zoom = 0.1; if (app->zoom > 3.0) app->zoom = 3.0; app->rotate = 0; app->panx = 0; app->pany = 0; - + kno_changeHighlightColor(app, 0xff00ff00); pdfapp_showpage(app, 1, 1); } void pdfapp_close(pdfapp_t *app) { if (app->cache) fz_freeglyphcache(app->cache); app->cache = nil; if (app->page) pdf_droppage(app->page); app->page = nil; if (app->image) fz_droppixmap(app->image); app->image = nil; if (app->text) fz_freetextspan(app->text); app->text = nil; if (app->outline) pdf_dropoutline(app->outline); app->outline = nil; if (app->xref->store) pdf_dropstore(app->xref->store); app->xref->store = nil; pdf_closexref(app->xref); app->xref = nil; } static fz_matrix pdfapp_viewctm(pdfapp_t *app) { fz_matrix ctm; ctm = fz_identity(); ctm = fz_concat(ctm, fz_translate(0, -app->page->mediabox.y1)); ctm = fz_concat(ctm, fz_scale(app->zoom, -app->zoom)); ctm = fz_concat(ctm, fz_rotate(app->rotate + app->page->rotate)); return ctm; } static void pdfapp_panview(pdfapp_t *app, int newx, int newy) { if (newx > 0) newx = 0; if (newy > 0) newy = 0; if (newx + app->image->w < app->winw) newx = app->winw - app->image->w; if (newy + app->image->h < app->winh) newy = app->winh - app->image->h; if (app->winw >= app->image->w) newx = (app->winw - app->image->w) / 2; if (app->winh >= app->image->h) newy = (app->winh - app->image->h) / 2; if (newx != app->panx || newy != app->pany) winrepaint(app); app->panx = newx; app->pany = newy; } static void pdfapp_showpage(pdfapp_t *app, int loadpage, int drawpage) { char buf[256]; fz_error error; fz_device *idev, *tdev, *mdev; fz_displaylist *list; fz_matrix ctm; fz_bbox bbox; fz_obj *obj; if (loadpage) { wincursor(app, WAIT); if (app->page) pdf_droppage(app->page); app->page = nil; - + //code change by kakai + kno_clearselect(app); + //code change by kakai pdf_flushxref(app->xref, 0); obj = pdf_getpageobject(app->xref, app->pageno); error = pdf_loadpage(&app->page, app->xref, obj); if (error) pdfapp_error(app, error); sprintf(buf, "%s - %d/%d", app->doctitle, app->pageno, app->pagecount); wintitle(app, buf); } if (drawpage) { wincursor(app, WAIT); ctm = pdfapp_viewctm(app); bbox = fz_roundrect(fz_transformrect(ctm, app->page->mediabox)); list = fz_newdisplaylist(); mdev = fz_newlistdevice(list); error = pdf_runcontentstream(mdev, fz_identity(), app->xref, app->page->resources, app->page->contents); if (error) pdfapp_error(app, error); fz_freedevice(mdev); if (app->image) fz_droppixmap(app->image); app->image = fz_newpixmapwithrect(pdf_devicergb, bbox); fz_clearpixmap(app->image, 0xFF); idev = fz_newdrawdevice(app->cache, app->image); fz_executedisplaylist(list, idev, ctm); fz_freedevice(idev); if (app->text) fz_freetextspan(app->text); app->text = fz_newtextspan(); tdev = fz_newtextdevice(app->text); fz_executedisplaylist(list, tdev, ctm); fz_freedevice(tdev); fz_freedisplaylist(list); + //code change by kakai + kno_allocselection(app); + kno_applyselect(app); + //code change by kakai + winconvert(app, app->image); } pdfapp_panview(app, app->panx, app->pany); if (app->shrinkwrap) { int w = app->image->w; int h = app->image->h; if (app->winw == w) app->panx = 0; if (app->winh == h) app->pany = 0; if (w > app->scrw * 90 / 100) w = app->scrw * 90 / 100; if (h > app->scrh * 90 / 100) h = app->scrh * 90 / 100; if (w != app->winw || h != app->winh) winresize(app, w, h); } winrepaint(app); wincursor(app, ARROW); } static void pdfapp_gotouri(pdfapp_t *app, fz_obj *uri) { char *buf; buf = fz_malloc(fz_tostrlen(uri) + 1); memcpy(buf, fz_tostrbuf(uri), fz_tostrlen(uri)); buf[fz_tostrlen(uri)] = 0; winopenuri(app, buf); fz_free(buf); } static void pdfapp_gotopage(pdfapp_t *app, fz_obj *obj) { int page; page = pdf_findpageobject(app->xref, obj); if (app->histlen + 1 == 256) { memmove(app->hist, app->hist + 1, sizeof(int) * 255); app->histlen --; } app->hist[app->histlen++] = app->pageno; app->pageno = page; pdfapp_showpage(app, 1, 1); } void pdfapp_onresize(pdfapp_t *app, int w, int h) { if (app->winw != w || app->winh != h) { app->winw = w; app->winh = h; pdfapp_panview(app, app->panx, app->pany); winrepaint(app); } } void pdfapp_onkey(pdfapp_t *app, int c) { int oldpage = app->pageno; enum panning panto = PAN_TO_TOP; /* * Save numbers typed for later */ if (c >= '0' && c <= '9') { app->number[app->numberlen++] = c; app->number[app->numberlen] = '\0'; } switch (c) { /* * Zoom and rotate */ case '+': case '=': app->zoom += 0.1; if (app->zoom > 3.0) app->zoom = 3.0; pdfapp_showpage(app, 0, 1); break; case '-': app->zoom -= 0.1; if (app->zoom < 0.1) app->zoom = 0.1; pdfapp_showpage(app, 0, 1); break; case 'l': case '<': app->rotate -= 90; pdfapp_showpage(app, 0, 1); break; case 'r': case '>': app->rotate += 90; pdfapp_showpage(app, 0, 1); break; case 'a': app->rotate -= 15; pdfapp_showpage(app, 0, 1); break; case 's': app->rotate += 15; pdfapp_showpage(app, 0, 1); break; /* * Pan view, but dont need to repaint image */ case 'w': app->shrinkwrap = 1; app->panx = app->pany = 0; pdfapp_showpage(app, 0, 0); break; case 'd': app->pany -= app->image->h / 10; pdfapp_showpage(app, 0, 0); break; case 'u': app->pany += app->image->h / 10; pdfapp_showpage(app, 0, 0); break; case ',': app->panx += app->image->w / 10; pdfapp_showpage(app, 0, 0); break; case '.': app->panx -= app->image->w / 10; pdfapp_showpage(app, 0, 0); break; /* * Page navigation */ case 'g': case '\n': case '\r': if (app->numberlen > 0) app->pageno = atoi(app->number); break; case 'G': app->pageno = app->pagecount; break; case 'm': if (app->histlen + 1 == 256) { memmove(app->hist, app->hist + 1, sizeof(int) * 255); app->histlen --; } app->hist[app->histlen++] = app->pageno; break; case 't': if (app->histlen > 0) app->pageno = app->hist[--app->histlen]; break; /* * Back and forth ... */ case 'p': panto = PAN_TO_BOTTOM; if (app->numberlen > 0) app->pageno -= atoi(app->number); else app->pageno--; break; case 'n': panto = PAN_TO_TOP; if (app->numberlen > 0) app->pageno += atoi(app->number); else app->pageno++; break; case 'b': case '\b': panto = DONT_PAN; if (app->numberlen > 0) app->pageno -= atoi(app->number); else app->pageno--; break; case 'f': case ' ': panto = DONT_PAN; if (app->numberlen > 0) app->pageno += atoi(app->number); else app->pageno++; break; case 'B': panto = PAN_TO_TOP; app->pageno -= 10; break; case 'F': panto = PAN_TO_TOP; app->pageno += 10; break; } if (c < '0' || c > '9') app->numberlen = 0; if (app->pageno < 1) app->pageno = 1; if (app->pageno > app->pagecount) app->pageno = app->pagecount; if (app->pageno != oldpage) { switch (panto) { case PAN_TO_TOP: app->pany = 0; break; case PAN_TO_BOTTOM: app->pany = -2000; break; case DONT_PAN: break; } pdfapp_showpage(app, 1, 1); } } void pdfapp_onmouse(pdfapp_t *app, int x, int y, int btn, int modifiers, int state) { pdf_link *link; fz_matrix ctm; fz_point p; p.x = x - app->panx + app->image->x; p.y = y - app->pany + app->image->y; ctm = pdfapp_viewctm(app); ctm = fz_invertmatrix(ctm); p = fz_transformpoint(ctm, p); for (link = app->page->links; link; link = link->next) { if (p.x >= link->rect.x0 && p.x <= link->rect.x1) if (p.y >= link->rect.y0 && p.y <= link->rect.y1) break; } if (link) { wincursor(app, HAND); if (btn == 1 && state == 1) { if (link->kind == PDF_LURI) pdfapp_gotouri(app, link->dest); else if (link->kind == PDF_LGOTO) pdfapp_gotopage(app, link->dest); return; } } else { wincursor(app, ARROW); } if (state == 1) { if (btn == 1 && !app->iscopying) { app->ispanning = 1; app->selx = x; app->sely = y; } if (btn == 3 && !app->ispanning) { + kno_clearselect(app); //code change by kakai app->iscopying = 1; app->selx = x; app->sely = y; app->selr.x0 = x; app->selr.x1 = x; app->selr.y0 = y; app->selr.y1 = y; } if (btn == 4 || btn == 5) /* scroll wheel */ { int dir = btn == 4 ? 1 : -1; app->ispanning = app->iscopying = 0; if (modifiers & (1<<2)) { /* zoom in/out if ctrl is pressed */ app->zoom += 0.1 * dir; if (app->zoom > 3.0) app->zoom = 3.0; if (app->zoom < 0.1) app->zoom = 0.1; pdfapp_showpage(app, 0, 1); } else { /* scroll up/down, or left/right if shift is pressed */ int isx = (modifiers & (1<<0)); int xstep = isx ? 20 * dir : 0; int ystep = !isx ? 20 * dir : 0; pdfapp_panview(app, app->panx + xstep, app->pany + ystep); } } } else if (state == -1) { if (app->iscopying) { app->iscopying = 0; app->selr.x0 = MIN(app->selx, x); app->selr.x1 = MAX(app->selx, x); app->selr.y0 = MIN(app->sely, y); app->selr.y1 = MAX(app->sely, y); winrepaint(app); if (app->selr.x0 < app->selr.x1 && app->selr.y0 < app->selr.y1) windocopy(app); } if (app->ispanning) app->ispanning = 0; } else if (app->ispanning) { int newx = app->panx + x - app->selx; int newy = app->pany + y - app->sely; pdfapp_panview(app, newx, newy); app->selx = x; app->sely = y; } else if (app->iscopying) { app->selr.x0 = MIN(app->selx, x); app->selr.x1 = MAX(app->selx, x); app->selr.y0 = MIN(app->sely, y); app->selr.y1 = MAX(app->sely, y); + kno_onselect(app); //code change by kakai winrepaint(app); } } void pdfapp_oncopy(pdfapp_t *app, unsigned short *ucsbuf, int ucslen) { ucsbuf[0] = 0; fz_textspan *ln; int x, y, c; int i, p; int x0 = app->image->x + app->selr.x0 - app->panx; int x1 = app->image->x + app->selr.x1 - app->panx; int y0 = app->image->y + app->selr.y0 - app->pany; int y1 = app->image->y + app->selr.y1 - app->pany; p = 0; for (ln = app->text; ln; ln = ln->next) { if (ln->len > 0) { y = y0 - 1; for (i = 0; i < ln->len; i++) { #if 0 int bx0, bx1, by0, by1; bx0 = ln->text[i].bbox.x0; bx1 = ln->text[i].bbox.x1; by0 = ln->text[i].bbox.y0; by1 = ln->text[i].bbox.y1; c = ln->text[i].c; if (c < 32) c = '?'; if (bx1 >= x0 && bx0 <= x1 && by1 >= y0 && by0 <= y1) if (p < ucslen - 1) ucsbuf[p++] = c; #endif c = ln->text[i].c; x = ln->text[i].x; y = ln->text[i].y; if (c < 32) c = '?'; if (x >= x0 && x <= x1 && y >= y0 && y <= y1) if (p < ucslen - 1) ucsbuf[p++] = c; } if (y >= y0 && y <= y1) { #ifdef _WIN32 if (p < ucslen - 1) ucsbuf[p++] = '\r'; #endif if (p < ucslen - 1) ucsbuf[p++] = '\n'; } } } ucsbuf[p] = 0; } diff --git a/apps/pdfapp.h b/apps/pdfapp.h index 1c80ee4..354d9ff 100644 --- a/apps/pdfapp.h +++ b/apps/pdfapp.h @@ -1,76 +1,90 @@ /* * Utility object for handling a pdf application / view * Takes care of PDF loading and displaying and navigation, * uses a number of callbacks to the GUI app. */ +#include <X11/Xlib.h> + + typedef struct pdfapp_s pdfapp_t; + enum { ARROW, HAND, WAIT }; extern void winwarn(pdfapp_t*, char *s); extern void winerror(pdfapp_t*, fz_error error); extern void wintitle(pdfapp_t*, char *title); extern void winresize(pdfapp_t*, int w, int h); extern void winconvert(pdfapp_t*, fz_pixmap *image); extern void winrepaint(pdfapp_t*); extern char* winpassword(pdfapp_t*, char *filename); extern void winopenuri(pdfapp_t*, char *s); extern void wincursor(pdfapp_t*, int curs); extern void windocopy(pdfapp_t*); struct pdfapp_s { /* current document params */ char *filename; char *doctitle; pdf_xref *xref; pdf_outline *outline; int pagecount; fz_glyphcache *cache; /* current view params */ float zoom; int rotate; fz_pixmap *image; fz_textspan *text; /* current page params */ int pageno; pdf_page *page; /* snapback history */ int hist[256]; int histlen; /* window system sizes */ int winw, winh; int scrw, scrh; int shrinkwrap; /* event handling state */ char number[256]; int numberlen; int ispanning; int panx, pany; int iscopying; int selx, sely; fz_bbox selr; + //code change by kakai + XRectangle *selrects; + int sellen; + + /* simple, one page selection for now */ + int firstline, lastline; + int firstchar, lastchar; + + unsigned long highlightedcolor; + //code change by kakai + /* client context storage */ void *userdata; }; void pdfapp_init(pdfapp_t *app); void pdfapp_open(pdfapp_t *app, char *filename); void pdfapp_close(pdfapp_t *app); char *pdfapp_usage(pdfapp_t *app); void pdfapp_onkey(pdfapp_t *app, int c); void pdfapp_onmouse(pdfapp_t *app, int x, int y, int btn, int modifiers, int state); void pdfapp_oncopy(pdfapp_t *app, unsigned short *ucsbuf, int ucslen); void pdfapp_onresize(pdfapp_t *app, int w, int h); - diff --git a/apps/x11_main.c b/apps/x11_main.c index 1c31475..b14a0c6 100644 --- a/apps/x11_main.c +++ b/apps/x11_main.c @@ -1,662 +1,680 @@ #include "fitz.h" #include "mupdf.h" #include "pdfapp.h" #include "x11_icon.xbm" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/cursorfont.h> #include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #ifndef timeradd #define timeradd(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((result)->tv_usec >= 1000000) \ { \ ++(result)->tv_sec; \ (result)->tv_usec -= 1000000; \ } \ } while (0) #endif #ifndef timersub #define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif extern int ximage_init(Display *display, int screen, Visual *visual); extern int ximage_get_depth(void); extern Visual *ximage_get_visual(void); extern Colormap ximage_get_colormap(void); extern void ximage_blit(Drawable d, GC gc, int dstx, int dsty, unsigned char *srcdata, int srcx, int srcy, int srcw, int srch, int srcstride); static Display *xdpy; static Atom XA_TARGETS; static Atom XA_TIMESTAMP; static Atom XA_UTF8_STRING; static int x11fd; static int xscr; static Window xwin; static GC xgc; static XEvent xevt; static int mapped = 0; static Cursor xcarrow, xchand, xcwait; static int justcopied = 0; static int isshowingpage = 0; static int dirty = 0; static char *password = ""; static XColor xbgcolor; static XColor xshcolor; static int reqw = 0; static int reqh = 0; static char copylatin1[1024 * 16] = ""; static char copyutf8[1024 * 48] = ""; static Time copytime; static pdfapp_t gapp; /* * Dialog boxes */ void winwarn(pdfapp_t *app, char *msg) { fprintf(stderr, "mupdf: %s\n", msg); } void winerror(pdfapp_t *app, fz_error error) { fz_catch(error, "aborting"); exit(1); } char *winpassword(pdfapp_t *app, char *filename) { char *r = password; password = NULL; return r; } /* * X11 magic */ static void winopen(void) { XWMHints *wmhints; XClassHint *classhint; xdpy = XOpenDisplay(nil); if (!xdpy) winerror(&gapp, fz_throw("could not open display")); XA_TARGETS = XInternAtom(xdpy, "TARGETS", False); XA_TIMESTAMP = XInternAtom(xdpy, "TIMESTAMP", False); XA_UTF8_STRING = XInternAtom(xdpy, "UTF8_STRING", False); xscr = DefaultScreen(xdpy); ximage_init(xdpy, xscr, DefaultVisual(xdpy, xscr)); xcarrow = XCreateFontCursor(xdpy, XC_left_ptr); xchand = XCreateFontCursor(xdpy, XC_hand2); xcwait = XCreateFontCursor(xdpy, XC_watch); xbgcolor.red = 0x7000; xbgcolor.green = 0x7000; xbgcolor.blue = 0x7000; xshcolor.red = 0x4000; xshcolor.green = 0x4000; xshcolor.blue = 0x4000; XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xbgcolor); XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xshcolor); xwin = XCreateWindow(xdpy, DefaultRootWindow(xdpy), 10, 10, 200, 100, 1, ximage_get_depth(), InputOutput, ximage_get_visual(), 0, nil); XSetWindowColormap(xdpy, xwin, ximage_get_colormap()); XSelectInput(xdpy, xwin, StructureNotifyMask | ExposureMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask); mapped = 0; xgc = XCreateGC(xdpy, xwin, 0, nil); XDefineCursor(xdpy, xwin, xcarrow); wmhints = XAllocWMHints(); if (wmhints) { wmhints->flags = IconPixmapHint; wmhints->icon_pixmap = XCreateBitmapFromData(xdpy, xwin, (char *) gs_l_xbm_bits, gs_l_xbm_width, gs_l_xbm_height); if (wmhints->icon_pixmap) { XSetWMHints(xdpy, xwin, wmhints); } XFree(wmhints); } classhint = XAllocClassHint(); if (classhint) { classhint->res_name = "mupdf"; classhint->res_class = "MuPDF"; XSetClassHint(xdpy, xwin, classhint); XFree(classhint); } x11fd = ConnectionNumber(xdpy); } void wincursor(pdfapp_t *app, int curs) { if (curs == ARROW) XDefineCursor(xdpy, xwin, xcarrow); if (curs == HAND) XDefineCursor(xdpy, xwin, xchand); if (curs == WAIT) XDefineCursor(xdpy, xwin, xcwait); XFlush(xdpy); } void wintitle(pdfapp_t *app, char *s) { #ifdef X_HAVE_UTF8_STRING Xutf8SetWMProperties(xdpy, xwin, s, s, nil, 0, nil, nil, nil); #else XmbSetWMProperties(xdpy, xwin, s, s, nil, 0, nil, nil, nil); #endif } void winconvert(pdfapp_t *app, fz_pixmap *image) { /* never mind */ } void winresize(pdfapp_t *app, int w, int h) { XWindowChanges values; int mask; mask = CWWidth | CWHeight; values.width = w; values.height = h; XConfigureWindow(xdpy, xwin, mask, &values); reqw = w; reqh = h; if (!mapped) { gapp.winw = w; gapp.winh = h; XMapWindow(xdpy, xwin); XFlush(xdpy); while (1) { XNextEvent(xdpy, &xevt); if (xevt.type == MapNotify) break; } XSetForeground(xdpy, xgc, WhitePixel(xdpy, xscr)); XFillRectangle(xdpy, xwin, xgc, 0, 0, gapp.image->w, gapp.image->h); XFlush(xdpy); mapped = 1; } } static void fillrect(int x, int y, int w, int h) { if (w > 0 && h > 0) XFillRectangle(xdpy, xwin, xgc, x, y, w, h); } static void invertcopyrect() { unsigned *p; int x, y; int x0 = gapp.selr.x0 - gapp.panx; int x1 = gapp.selr.x1 - gapp.panx; int y0 = gapp.selr.y0 - gapp.pany; int y1 = gapp.selr.y1 - gapp.pany; x0 = CLAMP(x0, 0, gapp.image->w - 1); x1 = CLAMP(x1, 0, gapp.image->w - 1); y0 = CLAMP(y0, 0, gapp.image->h - 1); y1 = CLAMP(y1, 0, gapp.image->h - 1); for (y = y0; y < y1; y++) { p = (unsigned *)(gapp.image->samples + (y * gapp.image->w + x0) * 4); for (x = x0; x < x1; x++) { *p = ~0 - *p; p ++; } } justcopied = 1; } +static void drawselection(pdfapp_t *app, Pixmap pix) +{ + if (app->sellen) { + XSetFunction(xdpy, xgc, GXand); + + XSetForeground(xdpy, xgc, app->highlightedcolor); + XFillRectangles(xdpy, pix, xgc, app->selrects, app->sellen); + XSetFunction(xdpy, xgc, GXcopy); + } +} + static void winblit(pdfapp_t *app) { - int x0 = gapp.panx; + int x0 = gapp.panx; int y0 = gapp.pany; int x1 = gapp.panx + gapp.image->w; int y1 = gapp.pany + gapp.image->h; + Pixmap pix; + + XSetForeground(xdpy, xgc, xbgcolor.pixel); fillrect(0, 0, x0, gapp.winh); fillrect(x1, 0, gapp.winw - x1, gapp.winh); fillrect(0, 0, gapp.winw, y0); fillrect(0, y1, gapp.winw, gapp.winh - y1); XSetForeground(xdpy, xgc, xshcolor.pixel); fillrect(x0+2, y1, gapp.image->w, 2); fillrect(x1, y0+2, 2, gapp.image->h); - if (gapp.iscopying || justcopied) - invertcopyrect(); + pix = XCreatePixmap(xdpy, xwin, + app->image->w, app->image->h, + ximage_get_depth()); - ximage_blit(xwin, xgc, + ximage_blit(pix, xgc, x0, y0, gapp.image->samples, 0, 0, gapp.image->w, gapp.image->h, gapp.image->w * gapp.image->n); - if (gapp.iscopying || justcopied) - invertcopyrect(); + + drawselection(app, pix); + + XCopyArea(xdpy, pix, xwin, xgc, 0,0,gapp.image->w, gapp.image->h,0,0); + XFreePixmap(xdpy,pix); } void winrepaint(pdfapp_t *app) { dirty = 1; } static void windrawstring(pdfapp_t *app, char *s, int x, int y) { int prevfunction; XGCValues xgcv; XGetGCValues(xdpy, xgc, GCFunction, &xgcv); prevfunction = xgcv.function; xgcv.function = GXxor; XChangeGC(xdpy, xgc, GCFunction, &xgcv); XSetForeground(xdpy, xgc, WhitePixel(xdpy, DefaultScreen(xdpy))); XDrawString(xdpy, xwin, xgc, x, y, s, strlen(s)); XFlush(xdpy); XGetGCValues(xdpy, xgc, GCFunction, &xgcv); xgcv.function = prevfunction; XChangeGC(xdpy, xgc, GCFunction, &xgcv); } static void windrawpageno(pdfapp_t *app) { char s[100]; int ret = snprintf(s, 100, "Page %d/%d", gapp.pageno, gapp.pagecount); if (ret >= 0) { isshowingpage = 1; windrawstring(&gapp, s, 10, 20); } } void windocopy(pdfapp_t *app) { unsigned short copyucs2[16 * 1024]; char *latin1 = copylatin1; char *utf8 = copyutf8; unsigned short *ucs2; int ucs; pdfapp_oncopy(&gapp, copyucs2, 16 * 1024); for (ucs2 = copyucs2; ucs2[0] != 0; ucs2++) { ucs = ucs2[0]; utf8 += runetochar(utf8, &ucs); if (ucs < 256) *latin1++ = ucs; else *latin1++ = '?'; } *utf8 = 0; *latin1 = 0; printf("oncopy utf8=%zd latin1=%zd\n", strlen(copyutf8), strlen(copylatin1)); XSetSelectionOwner(xdpy, XA_PRIMARY, xwin, copytime); justcopied = 1; } void onselreq(Window requestor, Atom selection, Atom target, Atom property, Time time) { XEvent nevt; printf("onselreq\n"); if (property == None) property = target; nevt.xselection.type = SelectionNotify; nevt.xselection.send_event = True; nevt.xselection.display = xdpy; nevt.xselection.requestor = requestor; nevt.xselection.selection = selection; nevt.xselection.target = target; nevt.xselection.property = property; nevt.xselection.time = time; if (target == XA_TARGETS) { Atom atomlist[4]; atomlist[0] = XA_TARGETS; atomlist[1] = XA_TIMESTAMP; atomlist[2] = XA_STRING; atomlist[3] = XA_UTF8_STRING; printf(" -> targets\n"); XChangeProperty(xdpy, requestor, property, target, 32, PropModeReplace, (unsigned char *)atomlist, sizeof(atomlist)/sizeof(Atom)); } else if (target == XA_STRING) { printf(" -> string %zd\n", strlen(copylatin1)); XChangeProperty(xdpy, requestor, property, target, 8, PropModeReplace, (unsigned char *)copylatin1, strlen(copylatin1)); } else if (target == XA_UTF8_STRING) { printf(" -> utf8string\n"); XChangeProperty(xdpy, requestor, property, target, 8, PropModeReplace, (unsigned char *)copyutf8, strlen(copyutf8)); } else { printf(" -> unknown\n"); nevt.xselection.property = None; } XSendEvent(xdpy, requestor, False, SelectionNotify, &nevt); } void winopenuri(pdfapp_t *app, char *buf) { char *browser = getenv("BROWSER"); if (!browser) browser = "open"; if (fork() == 0) execlp(browser, browser, buf, (char*)0); } static void onkey(int c) { if (justcopied) { justcopied = 0; winrepaint(&gapp); } if (c == 'P') windrawpageno(&gapp); else if (c == 'q') exit(0); else pdfapp_onkey(&gapp, c); } static void onmouse(int x, int y, int btn, int modifiers, int state) { if (state != 0 && justcopied) { justcopied = 0; winrepaint(&gapp); } pdfapp_onmouse(&gapp, x, y, btn, modifiers, state); } static void usage(void) { fprintf(stderr, "usage: mupdf [-d password] [-z zoom%%] [-p pagenumber] file.pdf\n"); exit(1); } static void winawaitevent(struct timeval *tmo, struct timeval *tmo_at) { if (tmo_at->tv_sec == 0 && tmo_at->tv_usec == 0 && tmo->tv_sec == 0 && tmo->tv_usec == 0) XNextEvent(xdpy, &xevt); else { fd_set fds; struct timeval now; FD_ZERO(&fds); FD_SET(x11fd, &fds); if (select(x11fd + 1, &fds, nil, nil, tmo)) { gettimeofday(&now, nil); timersub(tmo_at, &now, tmo); XNextEvent(xdpy, &xevt); } } } static void winsettmo(struct timeval *tmo, struct timeval *tmo_at) { struct timeval now; tmo->tv_sec = 2; tmo->tv_usec = 0; gettimeofday(&now, nil); timeradd(&now, tmo, tmo_at); } static void winresettmo(struct timeval *tmo, struct timeval *tmo_at) { tmo->tv_sec = 0; tmo->tv_usec = 0; tmo_at->tv_sec = 0; tmo_at->tv_usec = 0; } int main(int argc, char **argv) { char *filename; int c; int len; char buf[128]; KeySym keysym; int oldx = 0; int oldy = 0; int zoom = 100; int pageno = 1; int wasshowingpage; struct timeval tmo, tmo_at; while ((c = fz_getopt(argc, argv, "d:z:p:")) != -1) { switch (c) { case 'd': password = fz_optarg; break; case 'z': zoom = atoi(fz_optarg); break; case 'p': pageno = atoi(fz_optarg); break; default: usage(); } } if (zoom < 100) zoom = 100; if (zoom > 300) zoom = 300; if (argc - fz_optind == 0) usage(); filename = argv[fz_optind++]; fz_cpudetect(); fz_accelerate(); winopen(); pdfapp_init(&gapp); gapp.scrw = DisplayWidth(xdpy, xscr); gapp.scrh = DisplayHeight(xdpy, xscr); gapp.zoom = zoom / 100.0; gapp.pageno = pageno; pdfapp_open(&gapp, filename); winresettmo(&tmo, &tmo_at); while (1) { do { winawaitevent(&tmo, &tmo_at); if (tmo_at.tv_sec != 0 && tmo_at.tv_usec != 0 && tmo.tv_sec == 0 && tmo.tv_usec == 0) { /* redraw page */ winblit(&gapp); isshowingpage = 0; winresettmo(&tmo, &tmo_at); continue; } switch (xevt.type) { case Expose: dirty = 1; break; case ConfigureNotify: if (gapp.image) { if (xevt.xconfigure.width != reqw || xevt.xconfigure.height != reqh) gapp.shrinkwrap = 0; } pdfapp_onresize(&gapp, xevt.xconfigure.width, xevt.xconfigure.height); break; case KeyPress: wasshowingpage = isshowingpage; len = XLookupString(&xevt.xkey, buf, sizeof buf, &keysym, nil); if (len) onkey(buf[0]); onmouse(oldx, oldy, 0, 0, 0); if (dirty) { winblit(&gapp); dirty = 0; if (isshowingpage) { isshowingpage = 0; winresettmo(&tmo, &tmo_at); } } if (!wasshowingpage && isshowingpage) winsettmo(&tmo, &tmo_at); break; case MotionNotify: oldx = xevt.xbutton.x; oldy = xevt.xbutton.y; onmouse(xevt.xbutton.x, xevt.xbutton.y, xevt.xbutton.button, xevt.xbutton.state, 0); break; case ButtonPress: onmouse(xevt.xbutton.x, xevt.xbutton.y, xevt.xbutton.button, xevt.xbutton.state, 1); break; case ButtonRelease: copytime = xevt.xbutton.time; onmouse(xevt.xbutton.x, xevt.xbutton.y, xevt.xbutton.button, xevt.xbutton.state, -1); break; case SelectionRequest: onselreq(xevt.xselectionrequest.requestor, xevt.xselectionrequest.selection, xevt.xselectionrequest.target, xevt.xselectionrequest.property, xevt.xselectionrequest.time); break; } } while (XPending(xdpy)); if (dirty) { winblit(&gapp); dirty = 0; if (isshowingpage) { isshowingpage = 0; winresettmo(&tmo, &tmo_at); } } } pdfapp_close(&gapp); return 0; } diff --git a/fitz/dev_text.c b/fitz/dev_text.c index a3b01d4..a73af5a 100644 --- a/fitz/dev_text.c +++ b/fitz/dev_text.c @@ -1,201 +1,240 @@ #include "fitz.h" #include <ft2build.h> #include FT_FREETYPE_H #if ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 1)) || \ ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 2)) || \ ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 3) && (FREETYPE_PATCH < 8)) int FT_Get_Advance(FT_Face face, int gid, int masks, FT_Fixed *out) { int fterr; fterr = FT_Load_Glyph(face, gid, masks | FT_LOAD_IGNORE_TRANSFORM); if (fterr) return fterr; *out = face->glyph->advance.x * 1024; return 0; } #else #include FT_ADVANCES_H #endif typedef struct fz_textdevice_s fz_textdevice; struct fz_textdevice_s { fz_point point; fz_textspan *line; }; fz_textspan * fz_newtextspan(void) { fz_textspan *line; line = fz_malloc(sizeof(fz_textspan)); line->len = 0; line->cap = 0; + //code change by Kakai + line->bbox.x0 = 0; + line->bbox.x1 = 0; + line->bbox.y0 = 0; + line->bbox.y1 = 0; + //code change by Kakai line->text = nil; line->next = nil; return line; } void fz_freetextspan(fz_textspan *line) { if (line->next) fz_freetextspan(line->next); fz_free(line->text); fz_free(line); } static void -fz_addtextchar(fz_textspan *line, int x, int y, int c) +fz_addtextchar(fz_textspan *line, int x, int y, int w, int h, int c) { if (line->len + 1 >= line->cap) { line->cap = line->cap ? (line->cap * 3) / 2 : 80; line->text = fz_realloc(line->text, sizeof(fz_textchar) * line->cap); } line->text[line->len].x = x; line->text[line->len].y = y; line->text[line->len].c = c; - line->len ++; + line->text[line->len].w = w; + + if (!line->bbox.x0) { + line->bbox.x0 = x; + line->bbox.y0 = y; + line->bbox.y1 = y+h; + } + else { + int y0, y1; + y0 = y; + y1 = y+h; + if (y0 < line->bbox.y0) + line->bbox.y0 = y0; + if (y1 > line->bbox.y1) + line->bbox.y1 = y1; + } + + line->bbox.x1 = x + w; + line->len ++; } void fz_debugtextspan(fz_textspan *line) { char buf[10]; int c, n, k, i; for (i = 0; i < line->len; i++) { c = line->text[i].c; if (c < 128) putchar(c); else { n = runetochar(buf, &c); for (k = 0; k < n; k++) putchar(buf[k]); } } putchar('\n'); if (line->next) fz_debugtextspan(line->next); } static void fz_textextractline(fz_textspan **line, fz_text *text, fz_matrix ctm, fz_point *oldpt) { - fz_font *font = text->font; +fz_font *font = text->font; fz_matrix tm = text->trm; fz_matrix inv = fz_invertmatrix(text->trm); fz_matrix trm; + fz_matrix foo = tm; + fz_rect bbox; float dx, dy; fz_point p; float adv; - int i, x, y, fterr; + int i, x, y, w, h, fterr; if (font->ftface) { FT_Set_Transform(font->ftface, NULL, NULL); fterr = FT_Set_Char_Size(font->ftface, 64, 64, 72, 72); if (fterr) fz_warn("freetype set character size: %s", ft_errorstring(fterr)); } for (i = 0; i < text->len; i++) { tm.e = text->els[i].x; tm.f = text->els[i].y; trm = fz_concat(tm, ctm); - x = trm.e; + + x = trm.e; y = trm.f; trm.e = 0; trm.f = 0; p.x = text->els[i].x; p.y = text->els[i].y; p = fz_transformpoint(inv, p); dx = oldpt->x - p.x; dy = oldpt->y - p.y; *oldpt = p; /* TODO: flip advance and test for vertical writing */ if (font->ftface) { FT_Fixed ftadv; fterr = FT_Get_Advance(font->ftface, text->els[i].gid, FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING, &ftadv); if (fterr) fz_warn("freetype get advance (gid %d): %s", text->els[i].gid, ft_errorstring(fterr)); adv = ftadv / 65536.0; oldpt->x += adv; } else { adv = font->t3widths[text->els[i].gid]; oldpt->x += adv; } - if (fabs(dy) > 0.2) + + bbox.x0 = font->bbox.x0 / 1000.0; + bbox.x1 = bbox.x0 + adv; + bbox.y0 = font->bbox.y0 / 1000.0; + bbox.y1 = font->bbox.y1 / 1000.0; + bbox = fz_transformrect(foo, bbox); + + w = bbox.x1 - bbox.x0; + h = bbox.y1 - bbox.y0; + x += bbox.x0; + y = y - h - bbox.y0; + + if (fabs(dy) > 0.2) { fz_textspan *newline; newline = fz_newtextspan(); (*line)->next = newline; *line = newline; } else if (fabs(dx) > 0.2) { - fz_addtextchar(*line, x, y, ' '); + fz_addtextchar(*line, x, y, w, h, ' '); } - fz_addtextchar(*line, x, y, text->els[i].ucs); + fz_addtextchar(*line, x, y, w, h, text->els[i].ucs); } } static void fz_textfilltext(void *user, fz_text *text, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_textdevice *tdev = user; fz_textextractline(&tdev->line, text, ctm, &tdev->point); } static void fz_textignoretext(void *user, fz_text *text, fz_matrix ctm) { fz_textdevice *tdev = user; fz_textextractline(&tdev->line, text, ctm, &tdev->point); } static void fz_textfreeuser(void *user) { fz_textdevice *tdev = user; fz_free(tdev); } fz_device * fz_newtextdevice(fz_textspan *root) { fz_textdevice *tdev = fz_malloc(sizeof(fz_textdevice)); tdev->line = root; tdev->point.x = -1; tdev->point.y = -1; fz_device *dev = fz_newdevice(tdev); dev->freeuser = fz_textfreeuser; dev->filltext = fz_textfilltext; dev->ignoretext = fz_textignoretext; return dev; } diff --git a/fitz/fitz_res.h b/fitz/fitz_res.h index 082bc35..eb8df7e 100644 --- a/fitz/fitz_res.h +++ b/fitz/fitz_res.h @@ -1,372 +1,373 @@ /* * Resources and other graphics related objects. */ typedef struct fz_pixmap_s fz_pixmap; typedef struct fz_colorspace_s fz_colorspace; typedef struct fz_path_s fz_path; typedef struct fz_text_s fz_text; typedef struct fz_font_s fz_font; typedef struct fz_shade_s fz_shade; enum { FZ_MAXCOLORS = 32 }; typedef enum fz_blendkind_e { /* PDF 1.4 -- standard separable */ FZ_BNORMAL, FZ_BMULTIPLY, FZ_BSCREEN, FZ_BOVERLAY, FZ_BDARKEN, FZ_BLIGHTEN, FZ_BCOLORDODGE, FZ_BCOLORBURN, FZ_BHARDLIGHT, FZ_BSOFTLIGHT, FZ_BDIFFERENCE, FZ_BEXCLUSION, /* PDF 1.4 -- standard non-separable */ FZ_BHUE, FZ_BSATURATION, FZ_BCOLOR, FZ_BLUMINOSITY } fz_blendkind; /* pixmaps have n components per pixel. the first is always alpha. premultiplied alpha when rendering, but non-premultiplied for colorspace conversions and rescaling. */ extern fz_colorspace *pdf_devicegray; extern fz_colorspace *pdf_devicergb; extern fz_colorspace *pdf_devicecmyk; extern fz_colorspace *pdf_devicelab; extern fz_colorspace *pdf_devicepattern; struct fz_pixmap_s { int refs; int x, y, w, h, n; fz_colorspace *colorspace; unsigned char *samples; }; fz_pixmap * fz_newpixmapwithrect(fz_colorspace *, fz_bbox bbox); fz_pixmap * fz_newpixmap(fz_colorspace *, int x, int y, int w, int h); fz_pixmap *fz_keeppixmap(fz_pixmap *map); void fz_droppixmap(fz_pixmap *map); void fz_debugpixmap(fz_pixmap *map, char *prefix); void fz_clearpixmap(fz_pixmap *map, unsigned char value); fz_pixmap * fz_scalepixmap(fz_pixmap *src, int xdenom, int ydenom); /* * The device interface. */ typedef struct fz_device_s fz_device; struct fz_device_s { void *user; void (*freeuser)(void *); void (*fillpath)(void *, fz_path *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*strokepath)(void *, fz_path *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*clippath)(void *, fz_path *, fz_matrix); void (*filltext)(void *, fz_text *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*stroketext)(void *, fz_text *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*cliptext)(void *, fz_text *, fz_matrix); void (*ignoretext)(void *, fz_text *, fz_matrix); void (*fillshade)(void *, fz_shade *shd, fz_matrix ctm); void (*fillimage)(void *, fz_pixmap *img, fz_matrix ctm); void (*fillimagemask)(void *, fz_pixmap *img, fz_matrix ctm, fz_colorspace *, float *color, float alpha); void (*clipimagemask)(void *, fz_pixmap *img, fz_matrix ctm); void (*popclip)(void *); }; fz_device *fz_newdevice(void *user); void fz_freedevice(fz_device *dev); fz_device *fz_newtracedevice(void); /* Text extraction device */ typedef struct fz_textspan_s fz_textspan; typedef struct fz_textchar_s fz_textchar; struct fz_textchar_s { int c, x, y, w; }; struct fz_textspan_s { int ascender, descender; int len, cap; + fz_bbox bbox; fz_textchar *text; fz_textspan *next; }; fz_textspan * fz_newtextspan(void); void fz_freetextspan(fz_textspan *line); void fz_debugtextspan(fz_textspan *line); fz_device *fz_newtextdevice(fz_textspan *text); /* Display list device -- record and play back device commands. */ typedef struct fz_displaylist_s fz_displaylist; typedef struct fz_displaynode_s fz_displaynode; typedef enum fz_displaycommand_e { FZ_CMDFILLPATH, FZ_CMDSTROKEPATH, FZ_CMDCLIPPATH, FZ_CMDFILLTEXT, FZ_CMDSTROKETEXT, FZ_CMDCLIPTEXT, FZ_CMDIGNORETEXT, FZ_CMDFILLSHADE, FZ_CMDFILLIMAGE, FZ_CMDFILLIMAGEMASK, FZ_CMDCLIPIMAGEMASK, FZ_CMDPOPCLIP, } fz_displaycommand; struct fz_displaylist_s { fz_displaynode *first; fz_displaynode *last; }; struct fz_displaynode_s { fz_displaycommand cmd; fz_displaynode *next; union { fz_path *path; fz_text *text; fz_shade *shade; fz_pixmap *image; } item; //code change by kakai int id; int ishighlighted; int isunderline; int isbookmark; //code change by kakai fz_matrix ctm; fz_colorspace *colorspace; float alpha; float color[FZ_MAXCOLORS]; }; fz_displaylist *fz_newdisplaylist(void); void fz_freedisplaylist(fz_displaylist *list); fz_device *fz_newlistdevice(fz_displaylist *list); void fz_executedisplaylist(fz_displaylist *list, fz_device *dev, fz_matrix ctm); /* * Vector path buffer. * It can be stroked and dashed, or be filled. * It has a fill rule (nonzero or evenodd). * * When rendering, they are flattened, stroked and dashed straight * into the Global Edge List. */ typedef struct fz_stroke_s fz_stroke; typedef union fz_pathel_s fz_pathel; typedef enum fz_pathelkind_e { FZ_MOVETO, FZ_LINETO, FZ_CURVETO, FZ_CLOSEPATH } fz_pathelkind; union fz_pathel_s { fz_pathelkind k; float v; }; struct fz_path_s { int evenodd; int linecap; int linejoin; float linewidth; float miterlimit; float dashphase; int dashlen; float dashlist[32]; int len, cap; fz_pathel *els; }; fz_path *fz_newpath(void); void fz_moveto(fz_path*, float x, float y); void fz_lineto(fz_path*, float x, float y); void fz_curveto(fz_path*, float, float, float, float, float, float); void fz_curvetov(fz_path*, float, float, float, float); void fz_curvetoy(fz_path*, float, float, float, float); void fz_closepath(fz_path*); void fz_resetpath(fz_path *path); void fz_freepath(fz_path *path); fz_path *fz_clonepath(fz_path *old); fz_rect fz_boundpath(fz_path *path, fz_matrix ctm, int dostroke); void fz_debugpath(fz_path *, int indent); /* * Text buffer. * * The trm field contains the a, b, c and d coefficients. * The e and f coefficients come from the individual elements, * together they form the transform matrix for the glyph. * * Glyphs are referenced by glyph ID. * The Unicode text equivalent is kept in a separate array * with indexes into the glyph array. */ typedef struct fz_textel_s fz_textel; struct fz_textel_s { float x, y; int gid; int ucs; }; struct fz_text_s { fz_font *font; fz_matrix trm; int len, cap; fz_textel *els; }; fz_text * fz_newtext(fz_font *face); void fz_addtext(fz_text *text, int gid, int ucs, float x, float y); void fz_endtext(fz_text *text); void fz_resettext(fz_text *text); void fz_freetext(fz_text *text); void fz_debugtext(fz_text*, int indent); fz_text *fz_clonetext(fz_text *old); /* * Colorspace resources. * * TODO: use lcms */ struct fz_colorspace_s { int refs; char name[16]; int n; void (*convpixmap)(fz_colorspace *ss, fz_pixmap *sp, fz_colorspace *ds, fz_pixmap *dp); void (*convcolor)(fz_colorspace *ss, float *sv, fz_colorspace *ds, float *dv); void (*toxyz)(fz_colorspace *, float *src, float *xyz); void (*fromxyz)(fz_colorspace *, float *xyz, float *dst); void (*freefunc)(fz_colorspace *); }; fz_colorspace *fz_keepcolorspace(fz_colorspace *cs); void fz_dropcolorspace(fz_colorspace *cs); void fz_convertcolor(fz_colorspace *srcs, float *srcv, fz_colorspace *dsts, float *dstv); void fz_convertpixmap(fz_colorspace *srcs, fz_pixmap *srcv, fz_colorspace *dsts, fz_pixmap *dstv); void fz_stdconvcolor(fz_colorspace *srcs, float *srcv, fz_colorspace *dsts, float *dstv); void fz_stdconvpixmap(fz_colorspace *srcs, fz_pixmap *srcv, fz_colorspace *dsts, fz_pixmap *dstv); /* * Fonts. * * Fonts come in three variants: * Regular fonts are handled by FreeType. * Type 3 fonts have callbacks to the interpreter. * Substitute fonts are a thin wrapper over a regular font that adjusts metrics. */ char *ft_errorstring(int err); struct fz_font_s { int refs; char name[32]; void *ftface; /* has an FT_Face if used */ int ftsubstitute; /* ... substitute metrics */ int fthint; /* ... force hinting for DynaLab fonts */ fz_matrix t3matrix; fz_obj *t3resources; fz_buffer **t3procs; /* has 256 entries if used */ float *t3widths; /* has 256 entries if used */ void *t3xref; /* a pdf_xref for the callback */ fz_error (*t3runcontentstream)(fz_device *dev, fz_matrix ctm, struct pdf_xref_s *xref, fz_obj *resources, fz_buffer *contents); fz_rect bbox; }; fz_error fz_newfreetypefont(fz_font **fontp, char *name, int substitute); fz_error fz_loadfreetypefontfile(fz_font *font, char *path, int index); fz_error fz_loadfreetypefontbuffer(fz_font *font, unsigned char *data, int len, int index); fz_font * fz_newtype3font(char *name, fz_matrix matrix); fz_error fz_newfontfrombuffer(fz_font **fontp, unsigned char *data, int len, int index); fz_error fz_newfontfromfile(fz_font **fontp, char *path, int index); fz_font * fz_keepfont(fz_font *font); void fz_dropfont(fz_font *font); void fz_debugfont(fz_font *font); void fz_setfontbbox(fz_font *font, float xmin, float ymin, float xmax, float ymax); /* * The shading code is in rough shape but the general architecture is sound. */ struct fz_shade_s { int refs; fz_rect bbox; /* can be fz_infiniterect */ fz_colorspace *cs; fz_matrix matrix; /* matrix from pattern dict */ int usebackground; /* background color for fills but not 'sh' */ float background[FZ_MAXCOLORS]; int usefunction; float function[256][FZ_MAXCOLORS]; int meshlen; int meshcap; float *mesh; /* [x y t] or [x y c1 ... cn] * 3 * meshlen */ }; fz_shade *fz_keepshade(fz_shade *shade); void fz_dropshade(fz_shade *shade); fz_rect fz_boundshade(fz_shade *shade, fz_matrix ctm); void fz_rendershade(fz_shade *shade, fz_matrix ctm, fz_colorspace *dsts, fz_pixmap *dstp);
fkhan/mupdf_fareed
be0efa438b227c810b8b413fc64dcdf3cb47a880
Separate from muPDF files.
diff --git a/Makefile b/Makefile index 2060f29..de4298b 100644 --- a/Makefile +++ b/Makefile @@ -1,360 +1,360 @@ # GNU Makefile for MuPDF # # make build=release prefix=$HOME install # prefix ?= /usr/local build ?= debug default: all # # Compiler and configuration # OS := $(shell uname) OS := $(OS:MINGW%=MINGW) LIBS := -ljbig2dec -lopenjpeg -lfreetype -ljpeg -lz CFLAGS := -Wall --std=gnu99 -Ifitz -Imupdf LDFLAGS = CC = cc LD = $(CC) AR = ar ifeq "$(build)" "debug" CFLAGS += -g -O0 endif ifeq "$(build)" "release" CFLAGS += -O2 endif ifeq "$(OS)" "Linux" CFLAGS += `pkg-config --cflags freetype2` LDFLAGS += `pkg-config --libs freetype2` X11LIBS = -lX11 -lXext PDFVIEW_EXE = $(X11VIEW_EXE) endif ifeq "$(OS)" "Darwin" CFLAGS += -I$(HOME)/include -I/usr/X11R6/include -I/usr/X11R6/include/freetype2 -DARCH_X86_64 LDFLAGS += -L$(HOME)/lib -L/usr/X11R6/lib X11LIBS = -lX11 -lXext PDFVIEW_EXE = $(X11VIEW_EXE) ARCH_SRC = archx86.c endif ifeq "$(OS)" "MINGW" CC = gcc CFLAGS += -Ic:/msys/1.0/local/include LDFLAGS += -Lc:/msys/1.0/local/lib W32LIBS = -lgdi32 -lcomdlg32 -luser32 -ladvapi32 -lshell32 -mwindows PDFVIEW_EXE = $(WINVIEW_EXE) endif # Edit these if you are cross compiling: HOSTCC ?= $(CC) HOSTLD ?= $(HOSTCC) HOSTCFLAGS ?= $(CFLAGS) HOSTLDFLAGS ?= $(LDFLAGS) # # Build commands # HOSTCC_CMD = @ echo HOSTCC $@ && $(HOSTCC) -o $@ -c $< $(HOSTCFLAGS) HOSTLD_CMD = @ echo HOSTLD $@ && $(HOSTLD) -o $@ $^ $(HOSTLDFLAGS) GENFILE_CMD = @ echo GENFILE $@ && $(firstword $^) $@ $(wordlist 2, 999, $^) CC_CMD = @ echo CC $@ && $(CC) -o $@ -c $< $(CFLAGS) LD_CMD = @ echo LD $@ && $(LD) -o $@ $^ $(LDFLAGS) $(LIBS) AR_CMD = @ echo AR $@ && $(AR) cru $@ $^ # # Directories # OBJDIR = build/$(build) GENDIR = build/generated HOSTDIR = build/host DIRS = $(OBJDIR) $(GENDIR) $(HOSTDIR) $(DIRS): mkdir -p $@ # # Sources # -FITZ_HDR=fitz/fitz.h fitz/fitz_base.h fitz/fitz_draw.h fitz/fitz_stream.h fitz/fitz_res.h +FITZ_HDR=fitz/fitz.h fitz/fitz_base.h fitz/fitz_draw.h fitz/fitz_stream.h fitz/fitz_res.h fitz/kno_fitz_res.h FITZ_SRC=$(addprefix fitz/, \ base_cpudep.c \ base_error.c base_memory.c base_string.c base_unicode.c \ base_hash.c base_matrix.c base_rect.c \ crypt_aes.c crypt_arc4.c crypt_md5.c \ filt_aesd.c filt_arc4.c filt_basic.c filt_dctd.c filt_faxd.c filt_faxdtab.c filt_flate.c \ filt_jbig2d.c filt_jpxd.c filt_lzwd.c filt_pipeline.c filt_predict.c \ - dev_null.c dev_text.c dev_draw.c dev_list.c dev_trace.c \ + dev_null.c dev_text.c dev_draw.c dev_list.c dev_trace.c kno_dev_list.c \ obj_array.c obj_dict.c obj_print.c obj_simple.c \ res_colorspace.c res_font.c res_shade.c res_pixmap.c \ res_path.c res_text.c \ stm_buffer.c stm_filter.c stm_misc.c stm_open.c stm_read.c \ util_getopt.c util_gettimeofday.c ) FITZ_OBJ=$(FITZ_SRC:fitz/%.c=$(OBJDIR)/%.o) FITZ_LIB=$(OBJDIR)/libfitz.a $(FITZ_OBJ): $(FITZ_HDR) $(FITZ_LIB): $(FITZ_OBJ) $(AR_CMD) DRAW_SRC=$(addprefix draw/, $(ARCH_SRC) \ blendmodes.c glyphcache.c imagedraw.c imagescale.c imageunpack.c meshdraw.c \ pathfill.c pathscan.c pathstroke.c porterduff.c ) DRAW_OBJ=$(DRAW_SRC:draw/%.c=$(OBJDIR)/%.o) DRAW_LIB=$(OBJDIR)/libdraw.a $(DRAW_OBJ): $(FITZ_HDR) $(DRAW_LIB): $(DRAW_OBJ) $(AR_CMD) MUPDF_HDR=$(FITZ_HDR) mupdf/mupdf.h MUPDF_SRC=$(addprefix mupdf/, \ pdf_annot.c pdf_build.c pdf_cmap.c pdf_cmap_load.c pdf_cmap_parse.c \ pdf_cmap_table.c pdf_colorspace.c pdf_crypt.c pdf_debug.c \ pdf_font.c pdf_fontagl.c pdf_fontenc.c pdf_fontfile.c pdf_fontmtx.c \ pdf_function.c pdf_image.c pdf_interpret.c pdf_lex.c pdf_nametree.c pdf_open.c \ pdf_outline.c pdf_page.c pdf_pagetree.c pdf_parse.c pdf_pattern.c pdf_repair.c \ pdf_shade.c pdf_store.c pdf_stream.c pdf_type3.c \ pdf_unicode.c pdf_xobject.c pdf_xref.c ) MUPDF_OBJ=$(MUPDF_SRC:mupdf/%.c=$(OBJDIR)/%.o) MUPDF_LIB=$(OBJDIR)/libmupdf.a $(MUPDF_OBJ): $(MUPDF_HDR) $(MUPDF_LIB): $(MUPDF_OBJ) $(AR_CMD) $(OBJDIR)/%.o: fitz/%.c $(CC_CMD) $(OBJDIR)/%.o: draw/%.c $(CC_CMD) $(OBJDIR)/%.o: mupdf/%.c $(CC_CMD) # # Code generation tools run on the host # FONTDUMP_EXE=$(HOSTDIR)/fontdump CMAPDUMP_EXE=$(HOSTDIR)/cmapdump $(FONTDUMP_EXE): $(HOSTDIR)/fontdump.o $(HOSTLD_CMD) $(CMAPDUMP_EXE): $(HOSTDIR)/cmapdump.o $(HOSTLD_CMD) $(HOSTDIR)/%.o: mupdf/%.c $(HOSTCC_CMD) $(OBJDIR)/%.o: $(GENDIR)/%.c $(CC_CMD) # # Generated font file dumps # BASEFONT_FILES=$(addprefix fonts/, \ Dingbats.cff NimbusMonL-Bold.cff NimbusMonL-BoldObli.cff NimbusMonL-Regu.cff \ NimbusMonL-ReguObli.cff NimbusRomNo9L-Medi.cff NimbusRomNo9L-MediItal.cff \ NimbusRomNo9L-Regu.cff NimbusRomNo9L-ReguItal.cff NimbusSanL-Bold.cff \ NimbusSanL-BoldItal.cff NimbusSanL-Regu.cff NimbusSanL-ReguItal.cff \ StandardSymL.cff URWChanceryL-MediItal.cff ) CJKFONT_FILES=fonts/droid/DroidSansFallback.ttf $(GENDIR)/font_base14.c: $(FONTDUMP_EXE) $(BASEFONT_FILES) $(GENFILE_CMD) $(GENDIR)/font_cjk.c: $(FONTDUMP_EXE) $(CJKFONT_FILES) $(GENFILE_CMD) FONT_SRC=\ $(GENDIR)/font_base14.c \ $(GENDIR)/font_cjk.c FONT_OBJ=$(FONT_SRC:$(GENDIR)/%.c=$(OBJDIR)/%.o) FONT_LIB=$(OBJDIR)/libfonts.a $(FONT_LIB): $(FONT_OBJ) $(AR_CMD) # # Generated CMap file dumps # CMAP_UNICODE_FILES=$(addprefix cmaps/, \ Adobe-CNS1-UCS2 Adobe-GB1-UCS2 \ Adobe-Japan1-UCS2 Adobe-Korea1-UCS2 ) CMAP_CNS_FILES=$(addprefix cmaps/, \ Adobe-CNS1-0 Adobe-CNS1-1 Adobe-CNS1-2 Adobe-CNS1-3 \ Adobe-CNS1-4 Adobe-CNS1-5 Adobe-CNS1-6 B5-H B5-V B5pc-H B5pc-V \ CNS-EUC-H CNS-EUC-V CNS1-H CNS1-V CNS2-H CNS2-V ETen-B5-H \ ETen-B5-V ETenms-B5-H ETenms-B5-V ETHK-B5-H ETHK-B5-V \ HKdla-B5-H HKdla-B5-V HKdlb-B5-H HKdlb-B5-V HKgccs-B5-H \ HKgccs-B5-V HKm314-B5-H HKm314-B5-V HKm471-B5-H HKm471-B5-V \ HKscs-B5-H HKscs-B5-V UniCNS-UCS2-H UniCNS-UCS2-V \ UniCNS-UTF16-H UniCNS-UTF16-V ) CMAP_GB_FILES=$(addprefix cmaps/, \ Adobe-GB1-0 Adobe-GB1-1 Adobe-GB1-2 Adobe-GB1-3 Adobe-GB1-4 \ Adobe-GB1-5 GB-EUC-H GB-EUC-V GB-H GB-V GBK-EUC-H GBK-EUC-V \ GBK2K-H GBK2K-V GBKp-EUC-H GBKp-EUC-V GBpc-EUC-H GBpc-EUC-V \ GBT-EUC-H GBT-EUC-V GBT-H GBT-V GBTpc-EUC-H GBTpc-EUC-V \ UniGB-UCS2-H UniGB-UCS2-V UniGB-UTF16-H UniGB-UTF16-V ) CMAP_JAPAN_FILES=$(addprefix cmaps/, \ 78-EUC-H 78-EUC-V 78-H 78-RKSJ-H 78-RKSJ-V 78-V 78ms-RKSJ-H \ 78ms-RKSJ-V 83pv-RKSJ-H 90ms-RKSJ-H 90ms-RKSJ-V 90msp-RKSJ-H \ 90msp-RKSJ-V 90pv-RKSJ-H 90pv-RKSJ-V Add-H Add-RKSJ-H \ Add-RKSJ-V Add-V Adobe-Japan1-0 Adobe-Japan1-1 Adobe-Japan1-2 \ Adobe-Japan1-3 Adobe-Japan1-4 Adobe-Japan1-5 Adobe-Japan1-6 \ EUC-H EUC-V Ext-H Ext-RKSJ-H Ext-RKSJ-V Ext-V H Hankaku \ Hiragana Katakana NWP-H NWP-V RKSJ-H RKSJ-V Roman \ UniJIS-UCS2-H UniJIS-UCS2-HW-H UniJIS-UCS2-HW-V UniJIS-UCS2-V \ UniJISPro-UCS2-HW-V UniJISPro-UCS2-V V WP-Symbol \ Adobe-Japan2-0 Hojo-EUC-H Hojo-EUC-V Hojo-H Hojo-V \ UniHojo-UCS2-H UniHojo-UCS2-V UniHojo-UTF16-H UniHojo-UTF16-V \ UniJIS-UTF16-H UniJIS-UTF16-V ) CMAP_KOREA_FILES=$(addprefix cmaps/, \ Adobe-Korea1-0 Adobe-Korea1-1 Adobe-Korea1-2 KSC-EUC-H \ KSC-EUC-V KSC-H KSC-Johab-H KSC-Johab-V KSC-V KSCms-UHC-H \ KSCms-UHC-HW-H KSCms-UHC-HW-V KSCms-UHC-V KSCpc-EUC-H \ KSCpc-EUC-V UniKS-UCS2-H UniKS-UCS2-V UniKS-UTF16-H UniKS-UTF16-V ) $(GENDIR)/cmap_unicode.c: $(CMAPDUMP_EXE) $(CMAP_UNICODE_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_cns.c: $(CMAPDUMP_EXE) $(CMAP_CNS_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_gb.c: $(CMAPDUMP_EXE) $(CMAP_GB_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_japan.c: $(CMAPDUMP_EXE) $(CMAP_JAPAN_FILES) $(GENFILE_CMD) $(GENDIR)/cmap_korea.c: $(CMAPDUMP_EXE) $(CMAP_KOREA_FILES) $(GENFILE_CMD) CMAP_SRC=\ $(GENDIR)/cmap_unicode.c \ $(GENDIR)/cmap_cns.c \ $(GENDIR)/cmap_gb.c \ $(GENDIR)/cmap_japan.c \ $(GENDIR)/cmap_korea.c CMAP_OBJ=$(CMAP_SRC:$(GENDIR)/%.c=$(OBJDIR)/%.o) CMAP_LIB=$(OBJDIR)/libcmaps.a $(CMAP_OBJ): $(MUPDF_HDR) $(CMAP_LIB): $(CMAP_OBJ) $(AR_CMD) # # Apps # APPS = $(PDFSHOW_EXE) $(PDFCLEAN_EXE) $(PDFDRAW_EXE) $(PDFEXTRACT_EXE) $(PDFINFO_EXE) $(PDFVIEW_EXE) PDFAPP_HDR = apps/pdfapp.h PDFTOOL_HDR = apps/pdftool.h $(OBJDIR)/%.o: apps/%.c $(CC_CMD) PDFSHOW_SRC=apps/pdfshow.c apps/pdftool.c PDFSHOW_OBJ=$(PDFSHOW_SRC:apps/%.c=$(OBJDIR)/%.o) PDFSHOW_EXE=$(OBJDIR)/pdfshow $(PDFSHOW_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFSHOW_EXE): $(PDFSHOW_OBJ) $(MUPDF_LIB) $(FITZ_LIB) $(LD_CMD) PDFCLEAN_SRC=apps/pdfclean.c apps/pdftool.c PDFCLEAN_OBJ=$(PDFCLEAN_SRC:apps/%.c=$(OBJDIR)/%.o) PDFCLEAN_EXE=$(OBJDIR)/pdfclean $(PDFCLEAN_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFCLEAN_EXE): $(PDFCLEAN_OBJ) $(MUPDF_LIB) $(FITZ_LIB) $(LD_CMD) PDFDRAW_SRC=apps/pdfdraw.c apps/pdftool.c PDFDRAW_OBJ=$(PDFDRAW_SRC:apps/%.c=$(OBJDIR)/%.o) PDFDRAW_EXE=$(OBJDIR)/pdfdraw $(PDFDRAW_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFDRAW_EXE): $(PDFDRAW_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) PDFEXTRACT_SRC=apps/pdfextract.c apps/pdftool.c PDFEXTRACT_OBJ=$(PDFEXTRACT_SRC:apps/%.c=$(OBJDIR)/%.o) PDFEXTRACT_EXE=$(OBJDIR)/pdfextract $(PDFEXTRACT_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFEXTRACT_EXE): $(PDFEXTRACT_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) PDFINFO_SRC=apps/pdfinfo.c apps/pdftool.c PDFINFO_OBJ=$(PDFINFO_SRC:apps/%.c=$(OBJDIR)/%.o) PDFINFO_EXE=$(OBJDIR)/pdfinfo $(PDFINFO_OBJ): $(MUPDF_HDR) $(PDFTOOL_HDR) $(PDFINFO_EXE): $(PDFINFO_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) X11VIEW_SRC=apps/x11_main.c apps/x11_image.c apps/pdfapp.c X11VIEW_OBJ=$(X11VIEW_SRC:apps/%.c=$(OBJDIR)/%.o) X11VIEW_EXE=$(OBJDIR)/mupdf $(X11VIEW_OBJ): $(MUPDF_HDR) $(PDFAPP_HDR) $(X11VIEW_EXE): $(X11VIEW_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) $(X11LIBS) WINVIEW_SRC=apps/win_main.c apps/pdfapp.c WINVIEW_RES=apps/win_res.rc WINVIEW_OBJ=$(WINVIEW_SRC:apps/%.c=$(OBJDIR)/%.o) $(WINVIEW_RES:apps/%.rc=$(OBJDIR)/%.o) WINVIEW_EXE=$(OBJDIR)/mupdf.exe $(OBJDIR)/%.o: apps/%.rc windres -i $< -o $@ --include-dir=apps $(WINVIEW_OBJ): $(MUPDF_HDR) $(PDFAPP_HDR) $(WINVIEW_EXE): $(WINVIEW_OBJ) $(MUPDF_LIB) $(FONT_LIB) $(CMAP_LIB) $(FITZ_LIB) $(DRAW_LIB) $(LD_CMD) $(W32LIBS) # # Installation and tarball packaging # dist: $(DIRS) $(APPS) mkdir -p mupdf-dist cp README COPYING $(APPS) mupdf-dist tar cvf mupdf-dist.tar mupdf-dist rm -rf mupdf-dist # # Default rules # all: $(DIRS) $(APPS) clean: rm -rf $(OBJDIR)/* rm -rf $(GENDIR)/* rm -rf $(HOSTDIR)/* nuke: rm -rf build install: $(DIRS) $(APPS) install $(APPS) $(prefix)/bin diff --git a/fitz/dev_list.c b/fitz/dev_list.c index 26f3690..605e335 100644 --- a/fitz/dev_list.c +++ b/fitz/dev_list.c @@ -1,381 +1,328 @@ #include "fitz.h" static fz_displaynode * fz_newdisplaynode(fz_displaycommand cmd, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_displaynode *node; int i; node = fz_malloc(sizeof(fz_displaynode)); node->cmd = cmd; node->next = nil; node->ctm = ctm; if (colorspace) { node->colorspace = fz_keepcolorspace(colorspace); for (i = 0; i < node->colorspace->n; i++) node->color[i] = color[i]; } else { node->colorspace = nil; } node->alpha = alpha; //code change by kakai node->id = -1; node->ishighlighted = -1; node->isbookmark = -1; node->isunderline = -1; //code change by kakai return node; } static void fz_appenddisplaynode(fz_displaylist *list, fz_displaynode *node) { if (!list->first) { list->first = node; list->last = node; } else { list->last->next = node; list->last = node; } } static void fz_freedisplaynode(fz_displaynode *node) { switch (node->cmd) { case FZ_CMDFILLPATH: case FZ_CMDSTROKEPATH: case FZ_CMDCLIPPATH: fz_freepath(node->item.path); break; case FZ_CMDFILLTEXT: case FZ_CMDSTROKETEXT: case FZ_CMDCLIPTEXT: case FZ_CMDIGNORETEXT: fz_freetext(node->item.text); break; case FZ_CMDFILLSHADE: fz_dropshade(node->item.shade); break; case FZ_CMDFILLIMAGE: case FZ_CMDFILLIMAGEMASK: case FZ_CMDCLIPIMAGEMASK: fz_droppixmap(node->item.image); break; case FZ_CMDPOPCLIP: break; } if (node->colorspace) fz_dropcolorspace(node->colorspace); fz_free(node); } -//code change by kakai -int -fz_listnewid(fz_displaylist *list) -{ - if (list->last) - { - return list->last->id + 1; - } - else if (list->first) - { - return list->first->id + 1; - } - return 0; -} - -void -fz_addhighlightednode(fz_displaynode *node) -{ - node->ishighlighted = 1; -} - -void -fz_removehighlightednode(fz_displaynode *node) -{ - node->ishighlighted = 0; -} - -void -fz_addlinknode(fz_displaynode *node) -{ - node->isunderline = 1; -} - -void -fz_removelinknode(fz_displaynode *node) -{ - node->isunderline = 0; -} - -void -fz_addbookmarknode(fz_displaynode *node) -{ - node->isbookmark = 1; -} - -void -fz_removebookmarknode(fz_displaynode *node) -{ - node->isbookmark = 0; -} - -//code change by kakai - static void fz_listfillpath(void *user, fz_path *path, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDFILLPATH, ctm, colorspace, color, alpha); node->item.path = fz_clonepath(path); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_liststrokepath(void *user, fz_path *path, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDSTROKEPATH, ctm, colorspace, color, alpha); node->item.path = fz_clonepath(path); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listclippath(void *user, fz_path *path, fz_matrix ctm) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDCLIPPATH, ctm, nil, nil, 0.0); node->item.path = fz_clonepath(path); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listfilltext(void *user, fz_text *text, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDFILLTEXT, ctm, colorspace, color, alpha); node->item.text = fz_clonetext(text); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_liststroketext(void *user, fz_text *text, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDSTROKETEXT, ctm, colorspace, color, alpha); node->item.text = fz_clonetext(text); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listcliptext(void *user, fz_text *text, fz_matrix ctm) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDCLIPTEXT, ctm, nil, nil, 0.0); node->item.text = fz_clonetext(text); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listignoretext(void *user, fz_text *text, fz_matrix ctm) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDIGNORETEXT, ctm, nil, nil, 0.0); node->item.text = fz_clonetext(text); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listpopclip(void *user) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDPOPCLIP, fz_identity(), nil, nil, 0.0); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listfillshade(void *user, fz_shade *shade, fz_matrix ctm) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDFILLSHADE, ctm, nil, nil, 0.0); node->item.shade = fz_keepshade(shade); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listfillimage(void *user, fz_pixmap *image, fz_matrix ctm) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDFILLIMAGE, ctm, nil, nil, 0.0); node->item.image = fz_keeppixmap(image); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listfillimagemask(void *user, fz_pixmap *image, fz_matrix ctm, fz_colorspace *colorspace, float *color, float alpha) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDFILLIMAGEMASK, ctm, colorspace, color, alpha); node->item.image = fz_keeppixmap(image); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } static void fz_listclipimagemask(void *user, fz_pixmap *image, fz_matrix ctm) { fz_displaynode *node; node = fz_newdisplaynode(FZ_CMDCLIPIMAGEMASK, ctm, nil, nil, 0.0); node->item.image = fz_keeppixmap(image); //code change by kakai - node->id = fz_listnewid(user); + node->id = kno_listnewid(user); //code change by kakai fz_appenddisplaynode(user, node); } fz_device * fz_newlistdevice(fz_displaylist *list) { fz_device *dev = fz_newdevice(list); dev->fillpath = fz_listfillpath; dev->strokepath = fz_liststrokepath; dev->clippath = fz_listclippath; dev->filltext = fz_listfilltext; dev->stroketext = fz_liststroketext; dev->cliptext = fz_listcliptext; dev->ignoretext = fz_listignoretext; dev->fillshade = fz_listfillshade; dev->fillimage = fz_listfillimage; dev->fillimagemask = fz_listfillimagemask; dev->clipimagemask = fz_listclipimagemask; dev->popclip = fz_listpopclip; return dev; } fz_displaylist * fz_newdisplaylist(void) { fz_displaylist *list = fz_malloc(sizeof(fz_displaylist)); list->first = nil; list->last = nil; return list; } void fz_freedisplaylist(fz_displaylist *list) { fz_displaynode *node = list->first; while (node) { fz_displaynode *next = node->next; fz_freedisplaynode(node); node = next; } } void fz_executedisplaylist(fz_displaylist *list, fz_device *dev, fz_matrix topctm) { fz_displaynode *node; for (node = list->first; node; node = node->next) { fz_matrix ctm = fz_concat(node->ctm, topctm); switch (node->cmd) { case FZ_CMDFILLPATH: dev->fillpath(dev->user, node->item.path, ctm, node->colorspace, node->color, node->alpha); break; case FZ_CMDSTROKEPATH: dev->strokepath(dev->user, node->item.path, ctm, node->colorspace, node->color, node->alpha); break; case FZ_CMDCLIPPATH: dev->clippath(dev->user, node->item.path, ctm); break; case FZ_CMDFILLTEXT: dev->filltext(dev->user, node->item.text, ctm, node->colorspace, node->color, node->alpha); break; case FZ_CMDSTROKETEXT: dev->stroketext(dev->user, node->item.text, ctm, node->colorspace, node->color, node->alpha); break; case FZ_CMDCLIPTEXT: dev->cliptext(dev->user, node->item.text, ctm); break; case FZ_CMDIGNORETEXT: dev->ignoretext(dev->user, node->item.text, ctm); break; case FZ_CMDFILLSHADE: dev->fillshade(dev->user, node->item.shade, ctm); break; case FZ_CMDFILLIMAGE: dev->fillimage(dev->user, node->item.image, ctm); break; case FZ_CMDFILLIMAGEMASK: dev->fillimagemask(dev->user, node->item.image, ctm, node->colorspace, node->color, node->alpha); break; case FZ_CMDCLIPIMAGEMASK: dev->clipimagemask(dev->user, node->item.image, ctm); break; case FZ_CMDPOPCLIP: dev->popclip(dev->user); break; } } } diff --git a/fitz/fitz_res.h b/fitz/fitz_res.h index 60512c7..082bc35 100644 --- a/fitz/fitz_res.h +++ b/fitz/fitz_res.h @@ -1,381 +1,372 @@ /* * Resources and other graphics related objects. */ typedef struct fz_pixmap_s fz_pixmap; typedef struct fz_colorspace_s fz_colorspace; typedef struct fz_path_s fz_path; typedef struct fz_text_s fz_text; typedef struct fz_font_s fz_font; typedef struct fz_shade_s fz_shade; enum { FZ_MAXCOLORS = 32 }; typedef enum fz_blendkind_e { /* PDF 1.4 -- standard separable */ FZ_BNORMAL, FZ_BMULTIPLY, FZ_BSCREEN, FZ_BOVERLAY, FZ_BDARKEN, FZ_BLIGHTEN, FZ_BCOLORDODGE, FZ_BCOLORBURN, FZ_BHARDLIGHT, FZ_BSOFTLIGHT, FZ_BDIFFERENCE, FZ_BEXCLUSION, /* PDF 1.4 -- standard non-separable */ FZ_BHUE, FZ_BSATURATION, FZ_BCOLOR, FZ_BLUMINOSITY } fz_blendkind; /* pixmaps have n components per pixel. the first is always alpha. premultiplied alpha when rendering, but non-premultiplied for colorspace conversions and rescaling. */ extern fz_colorspace *pdf_devicegray; extern fz_colorspace *pdf_devicergb; extern fz_colorspace *pdf_devicecmyk; extern fz_colorspace *pdf_devicelab; extern fz_colorspace *pdf_devicepattern; struct fz_pixmap_s { int refs; int x, y, w, h, n; fz_colorspace *colorspace; unsigned char *samples; }; fz_pixmap * fz_newpixmapwithrect(fz_colorspace *, fz_bbox bbox); fz_pixmap * fz_newpixmap(fz_colorspace *, int x, int y, int w, int h); fz_pixmap *fz_keeppixmap(fz_pixmap *map); void fz_droppixmap(fz_pixmap *map); void fz_debugpixmap(fz_pixmap *map, char *prefix); void fz_clearpixmap(fz_pixmap *map, unsigned char value); fz_pixmap * fz_scalepixmap(fz_pixmap *src, int xdenom, int ydenom); /* * The device interface. */ typedef struct fz_device_s fz_device; struct fz_device_s { void *user; void (*freeuser)(void *); void (*fillpath)(void *, fz_path *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*strokepath)(void *, fz_path *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*clippath)(void *, fz_path *, fz_matrix); void (*filltext)(void *, fz_text *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*stroketext)(void *, fz_text *, fz_matrix, fz_colorspace *, float *color, float alpha); void (*cliptext)(void *, fz_text *, fz_matrix); void (*ignoretext)(void *, fz_text *, fz_matrix); void (*fillshade)(void *, fz_shade *shd, fz_matrix ctm); void (*fillimage)(void *, fz_pixmap *img, fz_matrix ctm); void (*fillimagemask)(void *, fz_pixmap *img, fz_matrix ctm, fz_colorspace *, float *color, float alpha); void (*clipimagemask)(void *, fz_pixmap *img, fz_matrix ctm); void (*popclip)(void *); }; fz_device *fz_newdevice(void *user); void fz_freedevice(fz_device *dev); fz_device *fz_newtracedevice(void); /* Text extraction device */ typedef struct fz_textspan_s fz_textspan; typedef struct fz_textchar_s fz_textchar; struct fz_textchar_s { int c, x, y, w; }; struct fz_textspan_s { int ascender, descender; int len, cap; fz_textchar *text; fz_textspan *next; }; fz_textspan * fz_newtextspan(void); void fz_freetextspan(fz_textspan *line); void fz_debugtextspan(fz_textspan *line); fz_device *fz_newtextdevice(fz_textspan *text); /* Display list device -- record and play back device commands. */ typedef struct fz_displaylist_s fz_displaylist; typedef struct fz_displaynode_s fz_displaynode; typedef enum fz_displaycommand_e { FZ_CMDFILLPATH, FZ_CMDSTROKEPATH, FZ_CMDCLIPPATH, FZ_CMDFILLTEXT, FZ_CMDSTROKETEXT, FZ_CMDCLIPTEXT, FZ_CMDIGNORETEXT, FZ_CMDFILLSHADE, FZ_CMDFILLIMAGE, FZ_CMDFILLIMAGEMASK, FZ_CMDCLIPIMAGEMASK, FZ_CMDPOPCLIP, } fz_displaycommand; struct fz_displaylist_s { fz_displaynode *first; fz_displaynode *last; }; struct fz_displaynode_s { fz_displaycommand cmd; fz_displaynode *next; union { fz_path *path; fz_text *text; fz_shade *shade; fz_pixmap *image; } item; //code change by kakai int id; int ishighlighted; int isunderline; int isbookmark; //code change by kakai fz_matrix ctm; fz_colorspace *colorspace; float alpha; float color[FZ_MAXCOLORS]; }; fz_displaylist *fz_newdisplaylist(void); void fz_freedisplaylist(fz_displaylist *list); fz_device *fz_newlistdevice(fz_displaylist *list); void fz_executedisplaylist(fz_displaylist *list, fz_device *dev, fz_matrix ctm); -//code change by kakai -int fz_listnewid(fz_displaylist *list); -void fz_addhighlightednode(fz_displaynode *node); -void fz_removehighlightednode(fz_displaynode *node); -void fz_addlinknode(fz_displaynode *node); -void fz_removelinknode(fz_displaynode *node); -void fz_addbookmarknode(fz_displaynode *node); -void fz_removebookmarknode(fz_displaynode *node); -//code change by kakai /* * Vector path buffer. * It can be stroked and dashed, or be filled. * It has a fill rule (nonzero or evenodd). * * When rendering, they are flattened, stroked and dashed straight * into the Global Edge List. */ typedef struct fz_stroke_s fz_stroke; typedef union fz_pathel_s fz_pathel; typedef enum fz_pathelkind_e { FZ_MOVETO, FZ_LINETO, FZ_CURVETO, FZ_CLOSEPATH } fz_pathelkind; union fz_pathel_s { fz_pathelkind k; float v; }; struct fz_path_s { int evenodd; int linecap; int linejoin; float linewidth; float miterlimit; float dashphase; int dashlen; float dashlist[32]; int len, cap; fz_pathel *els; }; fz_path *fz_newpath(void); void fz_moveto(fz_path*, float x, float y); void fz_lineto(fz_path*, float x, float y); void fz_curveto(fz_path*, float, float, float, float, float, float); void fz_curvetov(fz_path*, float, float, float, float); void fz_curvetoy(fz_path*, float, float, float, float); void fz_closepath(fz_path*); void fz_resetpath(fz_path *path); void fz_freepath(fz_path *path); fz_path *fz_clonepath(fz_path *old); fz_rect fz_boundpath(fz_path *path, fz_matrix ctm, int dostroke); void fz_debugpath(fz_path *, int indent); /* * Text buffer. * * The trm field contains the a, b, c and d coefficients. * The e and f coefficients come from the individual elements, * together they form the transform matrix for the glyph. * * Glyphs are referenced by glyph ID. * The Unicode text equivalent is kept in a separate array * with indexes into the glyph array. */ typedef struct fz_textel_s fz_textel; struct fz_textel_s { float x, y; int gid; int ucs; }; struct fz_text_s { fz_font *font; fz_matrix trm; int len, cap; fz_textel *els; }; fz_text * fz_newtext(fz_font *face); void fz_addtext(fz_text *text, int gid, int ucs, float x, float y); void fz_endtext(fz_text *text); void fz_resettext(fz_text *text); void fz_freetext(fz_text *text); void fz_debugtext(fz_text*, int indent); fz_text *fz_clonetext(fz_text *old); /* * Colorspace resources. * * TODO: use lcms */ struct fz_colorspace_s { int refs; char name[16]; int n; void (*convpixmap)(fz_colorspace *ss, fz_pixmap *sp, fz_colorspace *ds, fz_pixmap *dp); void (*convcolor)(fz_colorspace *ss, float *sv, fz_colorspace *ds, float *dv); void (*toxyz)(fz_colorspace *, float *src, float *xyz); void (*fromxyz)(fz_colorspace *, float *xyz, float *dst); void (*freefunc)(fz_colorspace *); }; fz_colorspace *fz_keepcolorspace(fz_colorspace *cs); void fz_dropcolorspace(fz_colorspace *cs); void fz_convertcolor(fz_colorspace *srcs, float *srcv, fz_colorspace *dsts, float *dstv); void fz_convertpixmap(fz_colorspace *srcs, fz_pixmap *srcv, fz_colorspace *dsts, fz_pixmap *dstv); void fz_stdconvcolor(fz_colorspace *srcs, float *srcv, fz_colorspace *dsts, float *dstv); void fz_stdconvpixmap(fz_colorspace *srcs, fz_pixmap *srcv, fz_colorspace *dsts, fz_pixmap *dstv); /* * Fonts. * * Fonts come in three variants: * Regular fonts are handled by FreeType. * Type 3 fonts have callbacks to the interpreter. * Substitute fonts are a thin wrapper over a regular font that adjusts metrics. */ char *ft_errorstring(int err); struct fz_font_s { int refs; char name[32]; void *ftface; /* has an FT_Face if used */ int ftsubstitute; /* ... substitute metrics */ int fthint; /* ... force hinting for DynaLab fonts */ fz_matrix t3matrix; fz_obj *t3resources; fz_buffer **t3procs; /* has 256 entries if used */ float *t3widths; /* has 256 entries if used */ void *t3xref; /* a pdf_xref for the callback */ fz_error (*t3runcontentstream)(fz_device *dev, fz_matrix ctm, struct pdf_xref_s *xref, fz_obj *resources, fz_buffer *contents); fz_rect bbox; }; fz_error fz_newfreetypefont(fz_font **fontp, char *name, int substitute); fz_error fz_loadfreetypefontfile(fz_font *font, char *path, int index); fz_error fz_loadfreetypefontbuffer(fz_font *font, unsigned char *data, int len, int index); fz_font * fz_newtype3font(char *name, fz_matrix matrix); fz_error fz_newfontfrombuffer(fz_font **fontp, unsigned char *data, int len, int index); fz_error fz_newfontfromfile(fz_font **fontp, char *path, int index); fz_font * fz_keepfont(fz_font *font); void fz_dropfont(fz_font *font); void fz_debugfont(fz_font *font); void fz_setfontbbox(fz_font *font, float xmin, float ymin, float xmax, float ymax); /* * The shading code is in rough shape but the general architecture is sound. */ struct fz_shade_s { int refs; fz_rect bbox; /* can be fz_infiniterect */ fz_colorspace *cs; fz_matrix matrix; /* matrix from pattern dict */ int usebackground; /* background color for fills but not 'sh' */ float background[FZ_MAXCOLORS]; int usefunction; float function[256][FZ_MAXCOLORS]; int meshlen; int meshcap; float *mesh; /* [x y t] or [x y c1 ... cn] * 3 * meshlen */ }; fz_shade *fz_keepshade(fz_shade *shade); void fz_dropshade(fz_shade *shade); fz_rect fz_boundshade(fz_shade *shade, fz_matrix ctm); void fz_rendershade(fz_shade *shade, fz_matrix ctm, fz_colorspace *dsts, fz_pixmap *dstp); diff --git a/fitz/kno_dev_list.c b/fitz/kno_dev_list.c new file mode 100644 index 0000000..ea6206b --- /dev/null +++ b/fitz/kno_dev_list.c @@ -0,0 +1,54 @@ +#include "fitz.h" + +//code change by kakai +int +kno_listnewid(fz_displaylist *list) +{ + if (list->last) + { + return list->last->id + 1; + } + else if (list->first) + { + return list->first->id + 1; + } + return 0; +} + +void +kno_addhighlightednode(fz_displaynode *node) +{ + node->ishighlighted = 1; +} + +void +kno_removehighlightednode(fz_displaynode *node) +{ + node->ishighlighted = 0; +} + +void +kno_addlinknode(fz_displaynode *node) +{ + node->isunderline = 1; +} + +void +kno_removelinknode(fz_displaynode *node) +{ + node->isunderline = 0; +} + +void +kno_addbookmarknode(fz_displaynode *node) +{ + node->isbookmark = 1; +} + +void +kno_removebookmarknode(fz_displaynode *node) +{ + node->isbookmark = 0; +} + +//code change by kakai diff --git a/fitz/kno_fitz_res.h b/fitz/kno_fitz_res.h new file mode 100644 index 0000000..43ba2af --- /dev/null +++ b/fitz/kno_fitz_res.h @@ -0,0 +1,13 @@ +/* + * Resources and other graphics related objects. + */ + +//code change by kakai +int fz_listnewid(fz_displaylist *list); +void fz_addhighlightednode(fz_displaynode *node); +void fz_removehighlightednode(fz_displaynode *node); +void fz_addlinknode(fz_displaynode *node); +void fz_removelinknode(fz_displaynode *node); +void fz_addbookmarknode(fz_displaynode *node); +void fz_removebookmarknode(fz_displaynode *node); +//code change by kakai
clairvy/localenv
971d228c9cc2b4c65340ff50dad838bba38dc2a1
ZSH use lsd
diff --git a/.zshrc b/.zshrc index 1e60e2e..67c345e 100644 --- a/.zshrc +++ b/.zshrc @@ -1,772 +1,772 @@ #!/usr/bin/env zsh # -*- coding: utf-8-unix; sh-basic-offset: 2; -*- stty -ixon stty -istrip bindkey -e bindkey '^W' kill-region HISTFILE=~/.zhistory HISTSIZE=100000000 SAVEHIST=100000000 autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey "^P" history-beginning-search-backward-end bindkey "^N" history-beginning-search-forward-end autoload is-at-least if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward bindkey "^S" history-incremental-pattern-search-forward else bindkey "^R" history-incremental-search-backward bindkey "^S" history-incremental-search-forward fi # 複数の zsh を同時に使う時など history ファイルに上書きせず追加 setopt append_history # シェルのプロセスごとに履歴を共有 setopt share_history # 履歴ファイルに時刻を記録 setopt extended_history # history (fc -l) コマンドをヒストリリストから取り除く。 setopt hist_no_store # 直前と同じコマンドラインはヒストリに追加しない setopt hist_ignore_dups # 重複したヒストリは追加しない setopt hist_ignore_all_dups # incremental append setopt inc_append_history # ディレクトリ名だけで、ディレクトリの移動をする。 setopt auto_cd # cdのタイミングで自動的にpushd setopt auto_pushd setopt pushd_ignore_dups # fpath の追加 fpath=(~/.zfunctions/Completion ${fpath}) # unfunction して,autoload する function reload_function() { local f f=($HOME/.zfunctions/Completion/*(.)) unfunction $f:t 2> /dev/null autoload -U $f:t } # 補完設定 autoload -Uz compinit; compinit -u # ファイルリスト補完でもlsと同様に色をつける。 export LSCOLORS=GxFxCxdxBxegedabagacad export LS_COLORS='di=01;36:ln=01;35:so=01;32:ex=01;31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30' zstyle ':completion:*:default' group-name '' zstyle ':completion:*:default' use-cache true zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:default' menu select=1 zstyle ':completion:*:default' verbose yes zstyle ':completion:*:descriptions' format '%B%d%b' zstyle ':completion:*:messages' format '%d' zstyle ':completion:*:warnings' format 'No matches for: %d' zstyle ':compinstall' filename '/home/nagaya/.zshrc' zstyle ':completion:*:processes' command 'ps x' # sudo でも補完の対象 zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin \ /usr/sbin /usr/bin /sbin /bin # 補完候補が複数ある時に、一覧表示 setopt auto_list # 補完キー(Tab, Ctrl+I) を連打するだけで順に補完候補を自動で補完 setopt auto_menu # ファイル名で #, ~, ^ の 3 文字を正規表現として扱う setopt extended_glob # C-s, C-qを無効にする。 setopt NO_flow_control # 8 ビット目を通すようになり、日本語のファイル名を表示可能 setopt print_eight_bit # カッコの対応などを自動的に補完 setopt auto_param_keys # ディレクトリ名の補完で末尾の / を自動的に付加し、次の補完に備える setopt auto_param_slash # 最後がディレクトリ名で終わっている場合末尾の / を自動的に取り除く setopt auto_remove_slash # {a-c} を a b c に展開する機能を使えるようにする setopt brace_ccl # コマンドのスペルチェックをする setopt correct # =command を command のパス名に展開する setopt equals # シェルが終了しても裏ジョブに HUP シグナルを送らないようにする setopt NO_hup # Ctrl+D では終了しないようになる(exit, logout などを使う) setopt ignore_eof # コマンドラインでも # 以降をコメントと見なす setopt interactive_comments # auto_list の補完候補一覧で、ls -F のようにファイルの種別をマーク表示しない setopt list_types # 内部コマンド jobs の出力をデフォルトで jobs -l にする setopt long_list_jobs # コマンドラインの引数で --prefix=/usr などの = 以降でも補完できる setopt magic_equal_subst # ファイル名の展開でディレクトリにマッチした場合末尾に / を付加する setopt mark_dirs # 複数のリダイレクトやパイプなど、必要に応じて tee や cat の機能が使われる setopt multios # ファイル名の展開で、辞書順ではなく数値的にソートされるようになる setopt numeric_glob_sort # for, repeat, select, if, function などで簡略文法が使えるようになる setopt short_loops #コピペの時rpromptを非表示する setopt transient_rprompt # 文字列末尾に改行コードが無い場合でも表示する unsetopt promptcr # リダイレクトでファイルを消さない setopt no_clobber setopt notify setopt print_exit_value # 状態変数 local os='unknown' local uname_s=`uname -s` if [[ $uname_s == "Darwin" ]]; then os='mac' elif [[ $uname_s == "SunOS" ]]; then os='sun' elif [[ $uname_s == "FreeBSD" ]]; then os='bsd' elif [[ $uname_s == "Linux" ]]; then os='lin' elif [[ $uname_s == "CYGWIN_NT-5.1" ]]; then os='win' fi [ -z "$HOSTNAME" ] && HOSTNAME=`uname -n` # すごいプロンプト setopt prompt_subst autoload -U colors; colors autoload -Uz add-zsh-hook if [[ $ZSH_VERSION != [1-3].* && $ZSH_VERSION != 4.[12].* ]]; then autoload -Uz vcs_info zstyle ':vcs_info:*' enable git svn hg bzr zstyle ':vcs_info:*' formats '(%s)-[%b]' zstyle ':vcs_info:*' actionformats '(%s)-[%b|%a]' zstyle ':vcs_info:(svn|bzr):*' branchformat '%b:r%r' zstyle ':vcs_info:bzr:*' use-simple true if is-at-least 4.3.10; then zstyle ':vcs_info:git:*' check-for-changes true zstyle ':vcs_info:git:*' stagedstr '+' zstyle ':vcs_info:git:*' unstagedstr '-' zstyle ':vcs_info:git:*' formats '(%s)-[%c%u%b]' zstyle ':vcs_info:git:*' actionformats '(%s)-[%c%u%b|%a]' fi function _update_vcs_info_msg() { psvar=() LANG=en_US.UTF-8 vcs_info psvar[2]=$(_git_not_pushed) [[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_" } add-zsh-hook precmd _update_vcs_info_msg function _git_not_pushed() { if [[ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = "true" ]]; then head="$(git rev-parse HEAD)" for x in $(git rev-parse --remotes); do if [[ "$head" = "$x" ]]; then return 0 fi done echo "{?}" fi return 0 } fi if [[ x"$os" == x"win" ]]; then export TERM=cygwin fi if [[ x"$TERM" == x"dumb" || x"$TERM" == x"sun" || x"$TERM" == x"emacs" ]]; then use_color= else use_color='true' fi if [[ x"$use_color" != x"true" ]]; then PROMPT='%U%B%n@%m%b %h %#%u ' RPROMPT= else local prompt_color='%{%}' local clear_color='%{%}' local rprompt_color='%{%}' # yellow  local vcs_prompot_color='%{%}' # green  local prompt_char='$' if [[ x"$USER" == x"s-nag" || x"$USER" == x"nagaya" || x"$USER" == x"s_nag" || x"$USER" == x"nag" ]]; then prompt_color='%{%}' # green  elif [[ x"$USER" == x"root" ]]; then prompt_color='%{%}' # white  prompt_char='#' else prompt_color='%{%}' # pink  fi PROMPT=$prompt_color'%U%B%n'$rprompt_color'%U@'$prompt_color'%B%m%b %h '$prompt_char$clear_color'%u ' RPROMPT=$vcs_prompot_color'%1(v|%1v%2v|)${vcs_info_git_pushed} '$rprompt_color'[%~]'$clear_color fi ### path settings # default path path=(/usr/bin /bin) # for sbin if [[ -d /sbin ]];then path=($path /sbin) fi if [[ -d /usr/sbin ]];then path=($path /usr/sbin) fi # /usr/local if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' -if whence -p exa 2>&1 > /dev/null; then - alias ls='exa -F' +if whence -p lsd 2>&1 > /dev/null; then + alias ls='lsd --icon never -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git switch' alias gcob='git switch --no-track --create' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gsw='git switch' alias gswo='git switch --orphan' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi # Settings for fzf if whence -p fzf 2>&1 > /dev/null; then if whence -p rg 2>&1 > /dev/null; then export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' fi export FZF_DEFAULT_OPTS='--height 30% --border' if [[ -f $HOME/.fzf.zsh ]]; then source ~/.fzf.zsh # replace ^R -> ^O bindkey '^O' fzf-history-widget if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward else bindkey "^R" history-incremental-search-backward fi fi fi # rg if whence -p rg 2>&1 > /dev/null; then export RG_DEFAULT_OPT=(-p --hidden) function rg() { # separated by : typeset -a glob; for p in ${(@s.:.)$(git config grep.defaultFile)}; do glob+=(--glob $p) done command rg $RG_DEFAULT_OPT "$@" "${(@)glob}" } fi # vim: sw=2
clairvy/localenv
bfd728af51eb8c021392cfb6fb640ef23b807cd5
ZSH unuse ruby opt
diff --git a/.zshrc b/.zshrc index a0b86da..1e60e2e 100644 --- a/.zshrc +++ b/.zshrc @@ -1,775 +1,772 @@ #!/usr/bin/env zsh # -*- coding: utf-8-unix; sh-basic-offset: 2; -*- stty -ixon stty -istrip bindkey -e bindkey '^W' kill-region HISTFILE=~/.zhistory HISTSIZE=100000000 SAVEHIST=100000000 autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey "^P" history-beginning-search-backward-end bindkey "^N" history-beginning-search-forward-end autoload is-at-least if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward bindkey "^S" history-incremental-pattern-search-forward else bindkey "^R" history-incremental-search-backward bindkey "^S" history-incremental-search-forward fi # 複数の zsh を同時に使う時など history ファイルに上書きせず追加 setopt append_history # シェルのプロセスごとに履歴を共有 setopt share_history # 履歴ファイルに時刻を記録 setopt extended_history # history (fc -l) コマンドをヒストリリストから取り除く。 setopt hist_no_store # 直前と同じコマンドラインはヒストリに追加しない setopt hist_ignore_dups # 重複したヒストリは追加しない setopt hist_ignore_all_dups # incremental append setopt inc_append_history # ディレクトリ名だけで、ディレクトリの移動をする。 setopt auto_cd # cdのタイミングで自動的にpushd setopt auto_pushd setopt pushd_ignore_dups # fpath の追加 fpath=(~/.zfunctions/Completion ${fpath}) # unfunction して,autoload する function reload_function() { local f f=($HOME/.zfunctions/Completion/*(.)) unfunction $f:t 2> /dev/null autoload -U $f:t } # 補完設定 autoload -Uz compinit; compinit -u # ファイルリスト補完でもlsと同様に色をつける。 export LSCOLORS=GxFxCxdxBxegedabagacad export LS_COLORS='di=01;36:ln=01;35:so=01;32:ex=01;31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30' zstyle ':completion:*:default' group-name '' zstyle ':completion:*:default' use-cache true zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:default' menu select=1 zstyle ':completion:*:default' verbose yes zstyle ':completion:*:descriptions' format '%B%d%b' zstyle ':completion:*:messages' format '%d' zstyle ':completion:*:warnings' format 'No matches for: %d' zstyle ':compinstall' filename '/home/nagaya/.zshrc' zstyle ':completion:*:processes' command 'ps x' # sudo でも補完の対象 zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin \ /usr/sbin /usr/bin /sbin /bin # 補完候補が複数ある時に、一覧表示 setopt auto_list # 補完キー(Tab, Ctrl+I) を連打するだけで順に補完候補を自動で補完 setopt auto_menu # ファイル名で #, ~, ^ の 3 文字を正規表現として扱う setopt extended_glob # C-s, C-qを無効にする。 setopt NO_flow_control # 8 ビット目を通すようになり、日本語のファイル名を表示可能 setopt print_eight_bit # カッコの対応などを自動的に補完 setopt auto_param_keys # ディレクトリ名の補完で末尾の / を自動的に付加し、次の補完に備える setopt auto_param_slash # 最後がディレクトリ名で終わっている場合末尾の / を自動的に取り除く setopt auto_remove_slash # {a-c} を a b c に展開する機能を使えるようにする setopt brace_ccl # コマンドのスペルチェックをする setopt correct # =command を command のパス名に展開する setopt equals # シェルが終了しても裏ジョブに HUP シグナルを送らないようにする setopt NO_hup # Ctrl+D では終了しないようになる(exit, logout などを使う) setopt ignore_eof # コマンドラインでも # 以降をコメントと見なす setopt interactive_comments # auto_list の補完候補一覧で、ls -F のようにファイルの種別をマーク表示しない setopt list_types # 内部コマンド jobs の出力をデフォルトで jobs -l にする setopt long_list_jobs # コマンドラインの引数で --prefix=/usr などの = 以降でも補完できる setopt magic_equal_subst # ファイル名の展開でディレクトリにマッチした場合末尾に / を付加する setopt mark_dirs # 複数のリダイレクトやパイプなど、必要に応じて tee や cat の機能が使われる setopt multios # ファイル名の展開で、辞書順ではなく数値的にソートされるようになる setopt numeric_glob_sort # for, repeat, select, if, function などで簡略文法が使えるようになる setopt short_loops #コピペの時rpromptを非表示する setopt transient_rprompt # 文字列末尾に改行コードが無い場合でも表示する unsetopt promptcr # リダイレクトでファイルを消さない setopt no_clobber setopt notify setopt print_exit_value # 状態変数 local os='unknown' local uname_s=`uname -s` if [[ $uname_s == "Darwin" ]]; then os='mac' elif [[ $uname_s == "SunOS" ]]; then os='sun' elif [[ $uname_s == "FreeBSD" ]]; then os='bsd' elif [[ $uname_s == "Linux" ]]; then os='lin' elif [[ $uname_s == "CYGWIN_NT-5.1" ]]; then os='win' fi [ -z "$HOSTNAME" ] && HOSTNAME=`uname -n` # すごいプロンプト setopt prompt_subst autoload -U colors; colors autoload -Uz add-zsh-hook if [[ $ZSH_VERSION != [1-3].* && $ZSH_VERSION != 4.[12].* ]]; then autoload -Uz vcs_info zstyle ':vcs_info:*' enable git svn hg bzr zstyle ':vcs_info:*' formats '(%s)-[%b]' zstyle ':vcs_info:*' actionformats '(%s)-[%b|%a]' zstyle ':vcs_info:(svn|bzr):*' branchformat '%b:r%r' zstyle ':vcs_info:bzr:*' use-simple true if is-at-least 4.3.10; then zstyle ':vcs_info:git:*' check-for-changes true zstyle ':vcs_info:git:*' stagedstr '+' zstyle ':vcs_info:git:*' unstagedstr '-' zstyle ':vcs_info:git:*' formats '(%s)-[%c%u%b]' zstyle ':vcs_info:git:*' actionformats '(%s)-[%c%u%b|%a]' fi function _update_vcs_info_msg() { psvar=() LANG=en_US.UTF-8 vcs_info psvar[2]=$(_git_not_pushed) [[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_" } add-zsh-hook precmd _update_vcs_info_msg function _git_not_pushed() { if [[ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = "true" ]]; then head="$(git rev-parse HEAD)" for x in $(git rev-parse --remotes); do if [[ "$head" = "$x" ]]; then return 0 fi done echo "{?}" fi return 0 } fi if [[ x"$os" == x"win" ]]; then export TERM=cygwin fi if [[ x"$TERM" == x"dumb" || x"$TERM" == x"sun" || x"$TERM" == x"emacs" ]]; then use_color= else use_color='true' fi if [[ x"$use_color" != x"true" ]]; then PROMPT='%U%B%n@%m%b %h %#%u ' RPROMPT= else local prompt_color='%{%}' local clear_color='%{%}' local rprompt_color='%{%}' # yellow  local vcs_prompot_color='%{%}' # green  local prompt_char='$' if [[ x"$USER" == x"s-nag" || x"$USER" == x"nagaya" || x"$USER" == x"s_nag" || x"$USER" == x"nag" ]]; then prompt_color='%{%}' # green  elif [[ x"$USER" == x"root" ]]; then prompt_color='%{%}' # white  prompt_char='#' else prompt_color='%{%}' # pink  fi PROMPT=$prompt_color'%U%B%n'$rprompt_color'%U@'$prompt_color'%B%m%b %h '$prompt_char$clear_color'%u ' RPROMPT=$vcs_prompot_color'%1(v|%1v%2v|)${vcs_info_git_pushed} '$rprompt_color'[%~]'$clear_color fi ### path settings # default path path=(/usr/bin /bin) # for sbin if [[ -d /sbin ]];then path=($path /sbin) fi if [[ -d /usr/sbin ]];then path=($path /usr/sbin) fi # /usr/local if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi -if [[ $os == 'mac' ]]; then - export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix [email protected])" -fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git switch' alias gcob='git switch --no-track --create' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gsw='git switch' alias gswo='git switch --orphan' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi # Settings for fzf if whence -p fzf 2>&1 > /dev/null; then if whence -p rg 2>&1 > /dev/null; then export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' fi export FZF_DEFAULT_OPTS='--height 30% --border' if [[ -f $HOME/.fzf.zsh ]]; then source ~/.fzf.zsh # replace ^R -> ^O bindkey '^O' fzf-history-widget if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward else bindkey "^R" history-incremental-search-backward fi fi fi # rg if whence -p rg 2>&1 > /dev/null; then export RG_DEFAULT_OPT=(-p --hidden) function rg() { # separated by : typeset -a glob; for p in ${(@s.:.)$(git config grep.defaultFile)}; do glob+=(--glob $p) done command rg $RG_DEFAULT_OPT "$@" "${(@)glob}" } fi # vim: sw=2
clairvy/localenv
2ae680589f794d3e5463e9f22485e4dc4e0c5dec
ZSH expand history
diff --git a/.zshrc b/.zshrc index f62d0ae..a0b86da 100644 --- a/.zshrc +++ b/.zshrc @@ -1,523 +1,523 @@ #!/usr/bin/env zsh # -*- coding: utf-8-unix; sh-basic-offset: 2; -*- stty -ixon stty -istrip bindkey -e bindkey '^W' kill-region HISTFILE=~/.zhistory -HISTSIZE=100000 -SAVEHIST=10000000 +HISTSIZE=100000000 +SAVEHIST=100000000 autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey "^P" history-beginning-search-backward-end bindkey "^N" history-beginning-search-forward-end autoload is-at-least if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward bindkey "^S" history-incremental-pattern-search-forward else bindkey "^R" history-incremental-search-backward bindkey "^S" history-incremental-search-forward fi # 複数の zsh を同時に使う時など history ファイルに上書きせず追加 setopt append_history # シェルのプロセスごとに履歴を共有 setopt share_history # 履歴ファイルに時刻を記録 setopt extended_history # history (fc -l) コマンドをヒストリリストから取り除く。 setopt hist_no_store # 直前と同じコマンドラインはヒストリに追加しない setopt hist_ignore_dups # 重複したヒストリは追加しない setopt hist_ignore_all_dups # incremental append setopt inc_append_history # ディレクトリ名だけで、ディレクトリの移動をする。 setopt auto_cd # cdのタイミングで自動的にpushd setopt auto_pushd setopt pushd_ignore_dups # fpath の追加 fpath=(~/.zfunctions/Completion ${fpath}) # unfunction して,autoload する function reload_function() { local f f=($HOME/.zfunctions/Completion/*(.)) unfunction $f:t 2> /dev/null autoload -U $f:t } # 補完設定 autoload -Uz compinit; compinit -u # ファイルリスト補完でもlsと同様に色をつける。 export LSCOLORS=GxFxCxdxBxegedabagacad export LS_COLORS='di=01;36:ln=01;35:so=01;32:ex=01;31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30' zstyle ':completion:*:default' group-name '' zstyle ':completion:*:default' use-cache true zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:default' menu select=1 zstyle ':completion:*:default' verbose yes zstyle ':completion:*:descriptions' format '%B%d%b' zstyle ':completion:*:messages' format '%d' zstyle ':completion:*:warnings' format 'No matches for: %d' zstyle ':compinstall' filename '/home/nagaya/.zshrc' zstyle ':completion:*:processes' command 'ps x' # sudo でも補完の対象 zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin \ /usr/sbin /usr/bin /sbin /bin # 補完候補が複数ある時に、一覧表示 setopt auto_list # 補完キー(Tab, Ctrl+I) を連打するだけで順に補完候補を自動で補完 setopt auto_menu # ファイル名で #, ~, ^ の 3 文字を正規表現として扱う setopt extended_glob # C-s, C-qを無効にする。 setopt NO_flow_control # 8 ビット目を通すようになり、日本語のファイル名を表示可能 setopt print_eight_bit # カッコの対応などを自動的に補完 setopt auto_param_keys # ディレクトリ名の補完で末尾の / を自動的に付加し、次の補完に備える setopt auto_param_slash # 最後がディレクトリ名で終わっている場合末尾の / を自動的に取り除く setopt auto_remove_slash # {a-c} を a b c に展開する機能を使えるようにする setopt brace_ccl # コマンドのスペルチェックをする setopt correct # =command を command のパス名に展開する setopt equals # シェルが終了しても裏ジョブに HUP シグナルを送らないようにする setopt NO_hup # Ctrl+D では終了しないようになる(exit, logout などを使う) setopt ignore_eof # コマンドラインでも # 以降をコメントと見なす setopt interactive_comments # auto_list の補完候補一覧で、ls -F のようにファイルの種別をマーク表示しない setopt list_types # 内部コマンド jobs の出力をデフォルトで jobs -l にする setopt long_list_jobs # コマンドラインの引数で --prefix=/usr などの = 以降でも補完できる setopt magic_equal_subst # ファイル名の展開でディレクトリにマッチした場合末尾に / を付加する setopt mark_dirs # 複数のリダイレクトやパイプなど、必要に応じて tee や cat の機能が使われる setopt multios # ファイル名の展開で、辞書順ではなく数値的にソートされるようになる setopt numeric_glob_sort # for, repeat, select, if, function などで簡略文法が使えるようになる setopt short_loops #コピペの時rpromptを非表示する setopt transient_rprompt # 文字列末尾に改行コードが無い場合でも表示する unsetopt promptcr # リダイレクトでファイルを消さない setopt no_clobber setopt notify setopt print_exit_value # 状態変数 local os='unknown' local uname_s=`uname -s` if [[ $uname_s == "Darwin" ]]; then os='mac' elif [[ $uname_s == "SunOS" ]]; then os='sun' elif [[ $uname_s == "FreeBSD" ]]; then os='bsd' elif [[ $uname_s == "Linux" ]]; then os='lin' elif [[ $uname_s == "CYGWIN_NT-5.1" ]]; then os='win' fi [ -z "$HOSTNAME" ] && HOSTNAME=`uname -n` # すごいプロンプト setopt prompt_subst autoload -U colors; colors autoload -Uz add-zsh-hook if [[ $ZSH_VERSION != [1-3].* && $ZSH_VERSION != 4.[12].* ]]; then autoload -Uz vcs_info zstyle ':vcs_info:*' enable git svn hg bzr zstyle ':vcs_info:*' formats '(%s)-[%b]' zstyle ':vcs_info:*' actionformats '(%s)-[%b|%a]' zstyle ':vcs_info:(svn|bzr):*' branchformat '%b:r%r' zstyle ':vcs_info:bzr:*' use-simple true if is-at-least 4.3.10; then zstyle ':vcs_info:git:*' check-for-changes true zstyle ':vcs_info:git:*' stagedstr '+' zstyle ':vcs_info:git:*' unstagedstr '-' zstyle ':vcs_info:git:*' formats '(%s)-[%c%u%b]' zstyle ':vcs_info:git:*' actionformats '(%s)-[%c%u%b|%a]' fi function _update_vcs_info_msg() { psvar=() LANG=en_US.UTF-8 vcs_info psvar[2]=$(_git_not_pushed) [[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_" } add-zsh-hook precmd _update_vcs_info_msg function _git_not_pushed() { if [[ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = "true" ]]; then head="$(git rev-parse HEAD)" for x in $(git rev-parse --remotes); do if [[ "$head" = "$x" ]]; then return 0 fi done echo "{?}" fi return 0 } fi if [[ x"$os" == x"win" ]]; then export TERM=cygwin fi if [[ x"$TERM" == x"dumb" || x"$TERM" == x"sun" || x"$TERM" == x"emacs" ]]; then use_color= else use_color='true' fi if [[ x"$use_color" != x"true" ]]; then PROMPT='%U%B%n@%m%b %h %#%u ' RPROMPT= else local prompt_color='%{%}' local clear_color='%{%}' local rprompt_color='%{%}' # yellow  local vcs_prompot_color='%{%}' # green  local prompt_char='$' if [[ x"$USER" == x"s-nag" || x"$USER" == x"nagaya" || x"$USER" == x"s_nag" || x"$USER" == x"nag" ]]; then prompt_color='%{%}' # green  elif [[ x"$USER" == x"root" ]]; then prompt_color='%{%}' # white  prompt_char='#' else prompt_color='%{%}' # pink  fi PROMPT=$prompt_color'%U%B%n'$rprompt_color'%U@'$prompt_color'%B%m%b %h '$prompt_char$clear_color'%u ' RPROMPT=$vcs_prompot_color'%1(v|%1v%2v|)${vcs_info_git_pushed} '$rprompt_color'[%~]'$clear_color fi ### path settings # default path path=(/usr/bin /bin) # for sbin if [[ -d /sbin ]];then path=($path /sbin) fi if [[ -d /usr/sbin ]];then path=($path /usr/sbin) fi # /usr/local if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi if [[ $os == 'mac' ]]; then export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix [email protected])" fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git switch' alias gcob='git switch --no-track --create' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gsw='git switch' alias gswo='git switch --orphan' alias gurm='git update-ref -d refs/original/refs/heads/master'
clairvy/localenv
831e46a16e0cbe33debe646782184d143c720a83
TMUX change path to zsh
diff --git a/.tmux.conf b/.tmux.conf index 42ebe27..8e5660b 100644 --- a/.tmux.conf +++ b/.tmux.conf @@ -1,36 +1,36 @@ # tmux起動時のシェルをzshにする -set-option -g default-shell /usr/local/bin/zsh +set-option -g default-shell /bin/zsh ## アクティブなペインのみ白っぽく変更(真っ黒は232) #set -g window-style 'bg=colour239' #set -g window-active-style 'bg=colour234' # バックスクロール set -g history-limit 100000 # prefixキーをC-qに変更 set -g prefix C-z bind ^Z send-prefix # C-bのキーバインドを解除 unbind C-b set-window-option -g mode-keys vi # tmp プラグインの設定 # tmp プラグインの設定 # 最初にリポジトリをクローンする必要がある # $ git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm # prefix + I でplugin をインストールするので追加したりしたときは実行 # これらの設定は最後に配置する必要がある # List of plugins set -g @tpm_plugins '\ tmux-plugins/tpm \ tmux-plugins/tmux-sensible \ tmux-plugins/tmux-pain-control \ tmux-plugins/tmux-resurrect \ tmux-plugins/tmux-continuum \ ' run '~/.tmux/plugins/tpm/tpm'
clairvy/localenv
0cd8a24cc1f2f47310e89f256af84e433882db1d
BREW update brew file
diff --git a/Brewfile b/Brewfile index 4dd02ed..c7f8f61 100644 --- a/Brewfile +++ b/Brewfile @@ -1,34 +1,26 @@ -tap "greymd/tools" -tap "homebrew/bundle" -tap "homebrew/cask" -tap "homebrew/core" -brew "emacs", args: ["HEAD", "cocoa", "srgb", "use-git-head"] -brew "exa" brew "fzf" -brew "gist" brew "git" -brew "go" +brew "lsd" brew "lv" brew "macvim" brew "mas" brew "nodebrew" -brew "ruby-build" brew "rbenv" brew "ripgrep" brew "rlwrap" +brew "ruby-build" brew "tig" brew "tmux" -brew "zsh" -brew "greymd/tools/tmux-xpanes" +brew "universal-ctags" cask "alfred" cask "aquaskk" cask "bettertouchtool" cask "docker" +cask "emacs" cask "evernote" cask "iterm2" cask "karabiner-elements" cask "slack" -cask "virtualbox" cask "yujitach-menumeters" mas "Memory Clean 2", id: 1114591412 mas "Xcode", id: 497799835
clairvy/localenv
f965c71858d55902e8028829c2536ca652cb1f2c
VIM some settings
diff --git a/.vim/userautoload/dein/lazy.toml b/.vim/userautoload/dein/lazy.toml index 2b0e999..49b41af 100644 --- a/.vim/userautoload/dein/lazy.toml +++ b/.vim/userautoload/dein/lazy.toml @@ -1,3 +1,24 @@ [[plugins]] repo = 'cespare/vim-toml' on_ft = ['toml'] + +[[plugins]] +repo = 'puremourning/vimspector' +on_ft = ['rust'] +hook_add = ''' + nnoremap <Leader>dd :call vimspector#Launch()<CR> + nnoremap <Leader>de :call vimspector#Reset()<CR> + nnoremap <Leader>dc :call vimspector#Continue()<CR> + + nnoremap <Leader>dt :call vimspector#ToggleBreakpoint()<CR> + nnoremap <Leader>dT :call vimspector#ClearBreakpoints()<CR> + + nmap <Leader>dk <Plug>VimspectorRestart + nmap <Leader>dh <Plug>VimspectorStepOut + nmap <Leader>dl <Plug>VimspectorStepInto + nmap <Leader>dj <Plug>VimspectorStepOver + + function! LaunchFileDebug() + call vimspector#LaunchWithSettings({'configuration': &filetype.'_file'}) + endfunction +''' diff --git a/.vim/userautoload/dein/plugins.toml b/.vim/userautoload/dein/plugins.toml index 1179f6c..a09f9ad 100644 --- a/.vim/userautoload/dein/plugins.toml +++ b/.vim/userautoload/dein/plugins.toml @@ -1,157 +1,215 @@ [[plugins]] repo = 'Shougo/dein.vim' [[plugins]] repo = 'Shougo/neosnippet.vim' [[plugins]] repo = 'Shougo/neosnippet-snippets' [[plugins]] repo = 'dense-analysis/ale' hook_add = ''' let g:ale_linters = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } let g:ale_fixers = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } "let g:ale_sign_column_always = 1 "let g:ale_open_list = 1 "let g:ale_keep_list_window_open = 1 " Set this. Airline will handle the rest. let g:airline#extensions#ale#enabled = 1 ''' [[plugins]] repo = 'vim-airline/vim-airline' [[plugins]] repo = 'vim-airline/vim-airline-themes' depends = 'vim-airline' hook_add = ''' let g:airline_theme = 'onedark' " タブバーをかっこよく let g:airline#extensions#tabline#enabled = 1 " Lintツールによるエラー、警告を表示(ALEの拡張) let g:airline#extensions#ale#enabled = 1 let g:airline#extensions#ale#error_symbol = 'E:' let g:airline#extensions#ale#warning_symbol = 'W:' " , キーで次タブのバッファを表示 nnoremap <silent> < :bprev<CR> " . キーで前タブのバッファを表示 nnoremap <silent> > :bnext<CR> ''' [[plugins]] repo='prabirshrestha/async.vim' [[plugins]] repo='prabirshrestha/vim-lsp' depends = ['async.vim'] hook_add = ''' let g:lsp_log_verbose = 1 let g:lsp_log_file = expand('~/vim-lsp.log') + let g:lsp_diagnostics_echo_cursor = 1 + let g:lsp_diagnostics_echo_delay = 200 + let g:lsp_diagnostics_virtual_text_enabled = 0 + let g:lsp_diagnostics_signs_enabled = 1 + + function! s:on_lsp_buffer_enabled() abort + setlocal omnifunc=lsp#complete + setlocal signcolumn=yes + if exists('+tagfunc') | setlocal tagfunc=lsp#tagfunc | endif + nmap <buffer> gc <plug>(lsp-code-action) + nmap <buffer> gl <plug>(lsp-code-lens) + nmap <buffer> gd <plug>(lsp-definition) + nmap <buffer> gr <plug>(lsp-references) + nmap <buffer> gi <plug>(lsp-implementation) + nmap <buffer> gt <plug>(lsp-type-definition) + nmap <buffer> <leader>rn <plug>(lsp-rename) + nmap <buffer> [g <Plug>(lsp-previous-diagnostic) + nmap <buffer> ]g <Plug>(lsp-next-diagnostic) + nmap <buffer> K <plug>(lsp-hover) + + " refer to doc to add more commands + endfunction + + augroup lsp_install + au! + " call s:on_lsp_buffer_enabled only for languages that has the server registered. + autocmd User lsp_buffer_enabled call s:on_lsp_buffer_enabled() + augroup END ''' [[plugins]] repo='mattn/vim-lsp-settings' [[plugins]] repo='prabirshrestha/asyncomplete.vim' hook_add = ''' inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>" inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>" inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<cr>" imap <c-space> <Plug>(asyncomplete_force_refresh) ''' [[plugins]] repo='prabirshrestha/asyncomplete-lsp.vim' depends = ['vim-lsp'] on_source = ['asyncomplete.vim'] #[[plugins]] #repo='prabirshrestha/asyncomplete-neosnippet.vim' #hook_add=''' #call asyncomplete#register_source(asyncomplete#sources#neosnippet#get_source_options({ # \ 'name': 'neosnippet', # \ 'whitelist': ['*'], # \ 'completor': function('asyncomplete#sources#neosnippet#completor'), # \ })) #imap <C-k> <Plug>(neosnippet_expand_or_jump) #smap <C-k> <Plug>(neosnippet_expand_or_jump) #xmap <C-k> <Plug>(neosnippet_expand_target) #''' [[plugins]] repo = 'leafgarland/typescript-vim' [[plugins]] repo = 'tmux-plugins/vim-tmux' [[plugins]] repo = 'scrooloose/nerdtree' hook_add = ''' let NERDTreeShowHidden=1 nnoremap <silent><C-a> :NERDTreeFind<CR>:vertical res 30<CR> ''' [[plugins]] repo = 'nathanaelkane/vim-indent-guides' hook_add = ''' let g:indent_guides_enable_on_vim_startup = 1 let g:indent_guides_exclude_filetypes = ['help', 'nerdtree'] let g:indent_guides_auto_colors = 0 autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd ctermbg=237 autocmd VimEnter,Colorscheme * :hi IndentGuidesEven ctermbg=240 ''' [[plugins]] repo = 'airblade/vim-gitgutter' hook_add = ''' set signcolumn=yes let g:gitgutter_async = 1 let g:gitgutter_sign_modified = 'rw' highlight GitGutterAdd ctermfg=green highlight GitGutterChange ctermfg=yellow highlight GitGutterDelete ctermfg=red highlight GitGutterChangeDelete ctermfg=yellow ''' [[plugins]] repo = 'luochen1990/rainbow' hook_add = ''' let g:rainbow_active = 1 ''' [[plugins]] repo = 'simeji/winresizer' # fzf [[plugins]] repo = 'junegunn/fzf' hook_post_update = './install --all' merged = 0 # fzf.vim [[plugins]] repo = 'junegunn/fzf.vim' depends = 'fzf' hook_add = ''' command! -bang -nargs=* Rg \ call fzf#vim#grep( \ 'rg --column --line-number --hidden --ignore-case --no-heading --color=always '.shellescape(<q-args>), 1, \ <bang>0 ? fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}, 'up:60%') \ : fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}, 'right:50%:hidden', '?'), \ <bang>0) nnoremap <C-g> :Rg<Space> nnoremap <C-p> :GFiles<CR> nnoremap <C-h> :History<CR> ''' + +[[plugins]] +repo = 'qpkorr/vim-bufkill' +hook_add = ''' +''' + +[[plugins]] +repo = 'tpope/vim-surround' +hook_add = ''' + " ダブルコーテーション→シングルコーテーション + nmap ff <Plug>Csurround"' + " シングルコーテーション→ダブルコーテーション + nmap tt <Plug>Csurround'" +''' + +[[plugins]] +repo = 'preservim/nerdcommenter' +hook_add = ''' + " Add spaces after comment delimiters by default + let g:NERDSpaceDelims = 1 + " Use compact syntax for prettified multi-line comments + let g:NERDCompactSexyComs = 1 + " Allow commenting and inverting empty lines (useful when commenting a region) + let g:NERDCommentEmptyLines = 1 + " Align line-wise comment delimiters flush left instead of following code indentation + let g:NERDDefaultAlign='left' + + nnoremap <silent> <leader>c} V}:call nerdcommenter#Comment('x', 'toggle')<CR> + nnoremap <silent> <leader>c{ V{:call nerdcommenter#Comment('x', 'toggle')<CR> +''' diff --git a/.vimrc b/.vimrc index 05be9d4..366fef2 100644 --- a/.vimrc +++ b/.vimrc @@ -1,279 +1,270 @@ filetype on "dein Scripts----------------------------- if &compatible set nocompatible " Be iMproved endif let s:dein_dir = $HOME . '/.cache/dein' let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim' let s:dein_toml_dir = $HOME . '/.vim/userautoload/dein' let s:dein_enabled = 0 " dein.vim ディレクトリがruntimepathに入っていない場合、追加 if match(&runtimepath, '/dein.vim') == -1 " dein_repo_dir で指定した場所に dein.vim が無い場合、git cloneしてくる if !isdirectory(s:dein_repo_dir) execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir endif execute 'set runtimepath+=' . fnamemodify(s:dein_repo_dir, ':p') endif " Required: if dein#load_state(s:dein_dir) let s:dein_enabled = 1 call dein#begin(s:dein_dir) call dein#load_toml(s:dein_toml_dir . '/plugins.toml', {'lazy': 0}) call dein#load_toml(s:dein_toml_dir . '/lazy.toml', {'lazy': 1}) " Required: call dein#end() call dein#save_state() endif " Required: filetype plugin indent on syntax enable colorscheme pablo " If you want to install not installed plugins on startup. if dein#check_install() call dein#install() endif "End dein Scripts------------------------- " vundle を使う {{{1 set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' " Vundle Plugin 'elixir-lang/vim-elixir' Plugin 'rust-lang/rust.vim' Plugin 'fatih/vim-go' Plugin 'nsf/gocode', {'rtp': 'vim/'} call vundle#end() filetype plugin indent on "}}} " .vim/bundle を使う {{{1 call pathogen#runtime_append_all_bundles() call pathogen#infect() "}}} " Vim の流儀 より. {{{1 filetype plugin on filetype indent on syntax enable " VIMRC 編集/ロード設定 nnoremap <Space> :<C-u>edit $MYVIMRC<Enter> nnoremap <Space>s. :<C-u>source $MYVIMRC<Enter> " バックスペースが特殊な文字を削除できる set backspace=indent,eol,start " 検索に使う文字 set ignorecase set smartcase " 検索 set incsearch set hlsearch " ステータスライン "set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P "set statusline=%F%m%r%h%w\ [%{&fenc!=''?&fenc:&enc},%{&ff},%Y]\ [\%03.3b,0x\%2.2B]\ (%04l,%04v)[%LL/%p%%]\ %{strftime('%Y/%m/%d(%a)%H:%M')} "set laststatus=2 " コマンドの入力状況の表示 set showcmd " インデント関連 set tabstop=8 set softtabstop=4 set shiftwidth=4 set expandtab " time for redraw set redrawtime=100000 " }}} +" ペースト設定 +vnoremap <silent> <C-p> "0p<CR> " leader {{{1 let mapleader = "," "set encoding=utf-8 "set fileencoding=utf-8 "set fileencodings=utf-8,utf-16,japan "set fileformats=unix,dos,mac "}}} " モードライン(ファイルのコメントからの読み込み) {{{1 set modeline set modelines=5 set backspace=2 set tabstop=4 set shiftwidth=4 set expandtab highlight tabs ctermbg=green guibg=green set list set listchars=tab:>- set number set ruler set smartindent "set laststatus=2 set wildmenu set wildmode=longest:full,full "}}} " 文字コードの自動認識 {{{1 set fileformats=unix,dos,mac set termencoding=utf-8 set encoding=utf-8 set fileencoding=utf-8 set fileencodings=utf-8 " 文字コードの自動認識 if &encoding !=# 'utf-8' set encoding=japan set fileencoding=japan endif if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがeucJP-msに対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'eucjp-ms' let s:enc_jis = 'iso-2022-jp-3' " iconvがJISX0213に対応しているかをチェック elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = s:fileencodings_default . ',' . &fileencodings unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 set fileencodings-=eucjp-ms let &encoding = s:enc_euc let &fileencoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " 日本語を含まない場合は fileencoding に encoding を使うようにする if has('autocmd') function! AU_ReCheck_FENC() if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0 let &fileencoding=&encoding endif endfunction autocmd BufReadPost * call AU_ReCheck_FENC() endif " 改行コードの自動認識 set fileformats=unix,dos,mac " □とか○の文字があってもカーソル位置がずれないようにする if exists('&ambiwidth') set ambiwidth=double endif " PHPManual {{{1 " PHP マニュアルを設置している場合 let g:ref_phpmanual_path = $HOME . '/local/share/phpman/php-chunked-xhtml/' let g:ref_phpmanual_cmd = 'w3m -dump %s' "let phpmanual_dir = $HOME . '/.vim/manual/php_manual_ja/' " マニュアルの拡張子 "let phpmanual_file_ext = 'html' " マニュアルのカラー表示 let phpmanual_color = 1 " iconv 変換をしない let phpmanual_convfilter = '' " w3m の表示形式を utf-8 にし、auto detect を on にする let phpmanual_htmlviewer = 'w3m -o display_charset=utf-8 -o auto_detect=2 -T text/html' " phpmanual.vim を置いているパスを指定 "source $HOME/.vim/ftplugin/phpmanual.vim "}}} " eskk {{{1 if has('vim_starting') if has('mac') let g:eskk#large_dictionary = "~/Library/Application\ Support/AquaSKK/SKK-JISYO.L" endif endif let g:eskk_debug = 0 "}}} " カーソル行をハイライト {{{1 set cursorline augroup cch autocmd! cch autocmd WinLeave * setlocal nocursorline autocmd WinEnter,BufRead * setlocal cursorline augroup END "}}} -" symofny {{{1 -nnoremap <silent> <Leader>v :<C-u>STview<CR> -nnoremap <silent> <Leader>m :<C-u>STmodel<CR> -nnoremap <silent> <Leader>a :<C-u>STaction<CR> -nnoremap <silent> <Leader>p :<C-u>STpartial<CR> -nnoremap <Leader>V :<C-u>STview -nnoremap <Leader>M :<C-u>STmodel -nnoremap <Leader>A :<C-u>STaction -nnoremap <Leader>P :<C-u>STpartial -"}}} - " git. {{{1 nnoremap <Leader>gg :<C-u>GitGrep "}}} " vim: foldmethod=marker " window {{{1 nnoremap sj <C-w>j nnoremap sk <C-w>k nnoremap sl <C-w>l nnoremap sh <C-w>h nnoremap ss :<C-u>sp<CR><C-w>j nnoremap sv :<C-u>vs<CR><C-w>l "}}} " Indent width if has("autocmd") "ファイルタイプの検索を有効にする filetype plugin on "ファイルタイプに合わせたインデントを利用 filetype indent on "sw=softtabstop, sts=shiftwidth, ts=tabstop, et=expandtabの略 autocmd FileType ruby setlocal sw=2 sts=2 ts=2 et autocmd FileType js setlocal sw=2 sts=2 ts=2 et autocmd FileType zsh setlocal sw=2 sts=2 ts=2 et autocmd FileType json setlocal sw=2 sts=2 ts=2 et autocmd FileType yml setlocal sw=2 sts=2 ts=2 et autocmd FileType yaml setlocal sw=2 sts=2 ts=2 et autocmd FileType javascript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescriptreact setlocal sw=2 sts=2 ts=2 et autocmd FileType vim setlocal sw=2 sts=2 ts=2 et endif
clairvy/localenv
80e6d3f69a2537e27b64af56be3f31faa2e84d22
VIM add color theme
diff --git a/.vimrc b/.vimrc index 8a62e4c..05be9d4 100644 --- a/.vimrc +++ b/.vimrc @@ -1,278 +1,279 @@ filetype on "dein Scripts----------------------------- if &compatible set nocompatible " Be iMproved endif let s:dein_dir = $HOME . '/.cache/dein' let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim' let s:dein_toml_dir = $HOME . '/.vim/userautoload/dein' let s:dein_enabled = 0 " dein.vim ディレクトリがruntimepathに入っていない場合、追加 if match(&runtimepath, '/dein.vim') == -1 " dein_repo_dir で指定した場所に dein.vim が無い場合、git cloneしてくる if !isdirectory(s:dein_repo_dir) execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir endif execute 'set runtimepath+=' . fnamemodify(s:dein_repo_dir, ':p') endif " Required: if dein#load_state(s:dein_dir) let s:dein_enabled = 1 call dein#begin(s:dein_dir) call dein#load_toml(s:dein_toml_dir . '/plugins.toml', {'lazy': 0}) call dein#load_toml(s:dein_toml_dir . '/lazy.toml', {'lazy': 1}) " Required: call dein#end() call dein#save_state() endif " Required: filetype plugin indent on syntax enable +colorscheme pablo " If you want to install not installed plugins on startup. if dein#check_install() call dein#install() endif "End dein Scripts------------------------- " vundle を使う {{{1 set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' " Vundle Plugin 'elixir-lang/vim-elixir' Plugin 'rust-lang/rust.vim' Plugin 'fatih/vim-go' Plugin 'nsf/gocode', {'rtp': 'vim/'} call vundle#end() filetype plugin indent on "}}} " .vim/bundle を使う {{{1 call pathogen#runtime_append_all_bundles() call pathogen#infect() "}}} " Vim の流儀 より. {{{1 filetype plugin on filetype indent on syntax enable " VIMRC 編集/ロード設定 nnoremap <Space> :<C-u>edit $MYVIMRC<Enter> nnoremap <Space>s. :<C-u>source $MYVIMRC<Enter> " バックスペースが特殊な文字を削除できる set backspace=indent,eol,start " 検索に使う文字 set ignorecase set smartcase " 検索 set incsearch set hlsearch " ステータスライン "set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P "set statusline=%F%m%r%h%w\ [%{&fenc!=''?&fenc:&enc},%{&ff},%Y]\ [\%03.3b,0x\%2.2B]\ (%04l,%04v)[%LL/%p%%]\ %{strftime('%Y/%m/%d(%a)%H:%M')} "set laststatus=2 " コマンドの入力状況の表示 set showcmd " インデント関連 set tabstop=8 set softtabstop=4 set shiftwidth=4 set expandtab " time for redraw set redrawtime=100000 " }}} " leader {{{1 let mapleader = "," "set encoding=utf-8 "set fileencoding=utf-8 "set fileencodings=utf-8,utf-16,japan "set fileformats=unix,dos,mac "}}} " モードライン(ファイルのコメントからの読み込み) {{{1 set modeline set modelines=5 set backspace=2 set tabstop=4 set shiftwidth=4 set expandtab highlight tabs ctermbg=green guibg=green set list set listchars=tab:>- set number set ruler set smartindent "set laststatus=2 set wildmenu set wildmode=longest:full,full "}}} " 文字コードの自動認識 {{{1 set fileformats=unix,dos,mac set termencoding=utf-8 set encoding=utf-8 set fileencoding=utf-8 set fileencodings=utf-8 " 文字コードの自動認識 if &encoding !=# 'utf-8' set encoding=japan set fileencoding=japan endif if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがeucJP-msに対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'eucjp-ms' let s:enc_jis = 'iso-2022-jp-3' " iconvがJISX0213に対応しているかをチェック elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = s:fileencodings_default . ',' . &fileencodings unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 set fileencodings-=eucjp-ms let &encoding = s:enc_euc let &fileencoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " 日本語を含まない場合は fileencoding に encoding を使うようにする if has('autocmd') function! AU_ReCheck_FENC() if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0 let &fileencoding=&encoding endif endfunction autocmd BufReadPost * call AU_ReCheck_FENC() endif " 改行コードの自動認識 set fileformats=unix,dos,mac " □とか○の文字があってもカーソル位置がずれないようにする if exists('&ambiwidth') set ambiwidth=double endif " PHPManual {{{1 " PHP マニュアルを設置している場合 let g:ref_phpmanual_path = $HOME . '/local/share/phpman/php-chunked-xhtml/' let g:ref_phpmanual_cmd = 'w3m -dump %s' "let phpmanual_dir = $HOME . '/.vim/manual/php_manual_ja/' " マニュアルの拡張子 "let phpmanual_file_ext = 'html' " マニュアルのカラー表示 let phpmanual_color = 1 " iconv 変換をしない let phpmanual_convfilter = '' " w3m の表示形式を utf-8 にし、auto detect を on にする let phpmanual_htmlviewer = 'w3m -o display_charset=utf-8 -o auto_detect=2 -T text/html' " phpmanual.vim を置いているパスを指定 "source $HOME/.vim/ftplugin/phpmanual.vim "}}} " eskk {{{1 if has('vim_starting') if has('mac') let g:eskk#large_dictionary = "~/Library/Application\ Support/AquaSKK/SKK-JISYO.L" endif endif let g:eskk_debug = 0 "}}} " カーソル行をハイライト {{{1 set cursorline augroup cch autocmd! cch autocmd WinLeave * setlocal nocursorline autocmd WinEnter,BufRead * setlocal cursorline augroup END "}}} " symofny {{{1 nnoremap <silent> <Leader>v :<C-u>STview<CR> nnoremap <silent> <Leader>m :<C-u>STmodel<CR> nnoremap <silent> <Leader>a :<C-u>STaction<CR> nnoremap <silent> <Leader>p :<C-u>STpartial<CR> nnoremap <Leader>V :<C-u>STview nnoremap <Leader>M :<C-u>STmodel nnoremap <Leader>A :<C-u>STaction nnoremap <Leader>P :<C-u>STpartial "}}} " git. {{{1 nnoremap <Leader>gg :<C-u>GitGrep "}}} " vim: foldmethod=marker " window {{{1 nnoremap sj <C-w>j nnoremap sk <C-w>k nnoremap sl <C-w>l nnoremap sh <C-w>h nnoremap ss :<C-u>sp<CR><C-w>j nnoremap sv :<C-u>vs<CR><C-w>l "}}} " Indent width if has("autocmd") "ファイルタイプの検索を有効にする filetype plugin on "ファイルタイプに合わせたインデントを利用 filetype indent on "sw=softtabstop, sts=shiftwidth, ts=tabstop, et=expandtabの略 autocmd FileType ruby setlocal sw=2 sts=2 ts=2 et autocmd FileType js setlocal sw=2 sts=2 ts=2 et autocmd FileType zsh setlocal sw=2 sts=2 ts=2 et autocmd FileType json setlocal sw=2 sts=2 ts=2 et autocmd FileType yml setlocal sw=2 sts=2 ts=2 et autocmd FileType yaml setlocal sw=2 sts=2 ts=2 et autocmd FileType javascript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescriptreact setlocal sw=2 sts=2 ts=2 et autocmd FileType vim setlocal sw=2 sts=2 ts=2 et endif
clairvy/localenv
2bba23f77c0cbcbc5c900fc5c7fb0ebbc641066b
ZSH Add git switch command alias
diff --git a/.zshrc b/.zshrc index 10fbe2f..f62d0ae 100644 --- a/.zshrc +++ b/.zshrc @@ -1,773 +1,775 @@ #!/usr/bin/env zsh # -*- coding: utf-8-unix; sh-basic-offset: 2; -*- stty -ixon stty -istrip bindkey -e bindkey '^W' kill-region HISTFILE=~/.zhistory HISTSIZE=100000 SAVEHIST=10000000 autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey "^P" history-beginning-search-backward-end bindkey "^N" history-beginning-search-forward-end autoload is-at-least if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward bindkey "^S" history-incremental-pattern-search-forward else bindkey "^R" history-incremental-search-backward bindkey "^S" history-incremental-search-forward fi # 複数の zsh を同時に使う時など history ファイルに上書きせず追加 setopt append_history # シェルのプロセスごとに履歴を共有 setopt share_history # 履歴ファイルに時刻を記録 setopt extended_history # history (fc -l) コマンドをヒストリリストから取り除く。 setopt hist_no_store # 直前と同じコマンドラインはヒストリに追加しない setopt hist_ignore_dups # 重複したヒストリは追加しない setopt hist_ignore_all_dups # incremental append setopt inc_append_history # ディレクトリ名だけで、ディレクトリの移動をする。 setopt auto_cd # cdのタイミングで自動的にpushd setopt auto_pushd setopt pushd_ignore_dups # fpath の追加 fpath=(~/.zfunctions/Completion ${fpath}) # unfunction して,autoload する function reload_function() { local f f=($HOME/.zfunctions/Completion/*(.)) unfunction $f:t 2> /dev/null autoload -U $f:t } # 補完設定 autoload -Uz compinit; compinit -u # ファイルリスト補完でもlsと同様に色をつける。 export LSCOLORS=GxFxCxdxBxegedabagacad export LS_COLORS='di=01;36:ln=01;35:so=01;32:ex=01;31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30' zstyle ':completion:*:default' group-name '' zstyle ':completion:*:default' use-cache true zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:default' menu select=1 zstyle ':completion:*:default' verbose yes zstyle ':completion:*:descriptions' format '%B%d%b' zstyle ':completion:*:messages' format '%d' zstyle ':completion:*:warnings' format 'No matches for: %d' zstyle ':compinstall' filename '/home/nagaya/.zshrc' zstyle ':completion:*:processes' command 'ps x' # sudo でも補完の対象 zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin \ /usr/sbin /usr/bin /sbin /bin # 補完候補が複数ある時に、一覧表示 setopt auto_list # 補完キー(Tab, Ctrl+I) を連打するだけで順に補完候補を自動で補完 setopt auto_menu # ファイル名で #, ~, ^ の 3 文字を正規表現として扱う setopt extended_glob # C-s, C-qを無効にする。 setopt NO_flow_control # 8 ビット目を通すようになり、日本語のファイル名を表示可能 setopt print_eight_bit # カッコの対応などを自動的に補完 setopt auto_param_keys # ディレクトリ名の補完で末尾の / を自動的に付加し、次の補完に備える setopt auto_param_slash # 最後がディレクトリ名で終わっている場合末尾の / を自動的に取り除く setopt auto_remove_slash # {a-c} を a b c に展開する機能を使えるようにする setopt brace_ccl # コマンドのスペルチェックをする setopt correct # =command を command のパス名に展開する setopt equals # シェルが終了しても裏ジョブに HUP シグナルを送らないようにする setopt NO_hup # Ctrl+D では終了しないようになる(exit, logout などを使う) setopt ignore_eof # コマンドラインでも # 以降をコメントと見なす setopt interactive_comments # auto_list の補完候補一覧で、ls -F のようにファイルの種別をマーク表示しない setopt list_types # 内部コマンド jobs の出力をデフォルトで jobs -l にする setopt long_list_jobs # コマンドラインの引数で --prefix=/usr などの = 以降でも補完できる setopt magic_equal_subst # ファイル名の展開でディレクトリにマッチした場合末尾に / を付加する setopt mark_dirs # 複数のリダイレクトやパイプなど、必要に応じて tee や cat の機能が使われる setopt multios # ファイル名の展開で、辞書順ではなく数値的にソートされるようになる setopt numeric_glob_sort # for, repeat, select, if, function などで簡略文法が使えるようになる setopt short_loops #コピペの時rpromptを非表示する setopt transient_rprompt # 文字列末尾に改行コードが無い場合でも表示する unsetopt promptcr # リダイレクトでファイルを消さない setopt no_clobber setopt notify setopt print_exit_value # 状態変数 local os='unknown' local uname_s=`uname -s` if [[ $uname_s == "Darwin" ]]; then os='mac' elif [[ $uname_s == "SunOS" ]]; then os='sun' elif [[ $uname_s == "FreeBSD" ]]; then os='bsd' elif [[ $uname_s == "Linux" ]]; then os='lin' elif [[ $uname_s == "CYGWIN_NT-5.1" ]]; then os='win' fi [ -z "$HOSTNAME" ] && HOSTNAME=`uname -n` # すごいプロンプト setopt prompt_subst autoload -U colors; colors autoload -Uz add-zsh-hook if [[ $ZSH_VERSION != [1-3].* && $ZSH_VERSION != 4.[12].* ]]; then autoload -Uz vcs_info zstyle ':vcs_info:*' enable git svn hg bzr zstyle ':vcs_info:*' formats '(%s)-[%b]' zstyle ':vcs_info:*' actionformats '(%s)-[%b|%a]' zstyle ':vcs_info:(svn|bzr):*' branchformat '%b:r%r' zstyle ':vcs_info:bzr:*' use-simple true if is-at-least 4.3.10; then zstyle ':vcs_info:git:*' check-for-changes true zstyle ':vcs_info:git:*' stagedstr '+' zstyle ':vcs_info:git:*' unstagedstr '-' zstyle ':vcs_info:git:*' formats '(%s)-[%c%u%b]' zstyle ':vcs_info:git:*' actionformats '(%s)-[%c%u%b|%a]' fi function _update_vcs_info_msg() { psvar=() LANG=en_US.UTF-8 vcs_info psvar[2]=$(_git_not_pushed) [[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_" } add-zsh-hook precmd _update_vcs_info_msg function _git_not_pushed() { if [[ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = "true" ]]; then head="$(git rev-parse HEAD)" for x in $(git rev-parse --remotes); do if [[ "$head" = "$x" ]]; then return 0 fi done echo "{?}" fi return 0 } fi if [[ x"$os" == x"win" ]]; then export TERM=cygwin fi if [[ x"$TERM" == x"dumb" || x"$TERM" == x"sun" || x"$TERM" == x"emacs" ]]; then use_color= else use_color='true' fi if [[ x"$use_color" != x"true" ]]; then PROMPT='%U%B%n@%m%b %h %#%u ' RPROMPT= else local prompt_color='%{%}' local clear_color='%{%}' local rprompt_color='%{%}' # yellow  local vcs_prompot_color='%{%}' # green  local prompt_char='$' if [[ x"$USER" == x"s-nag" || x"$USER" == x"nagaya" || x"$USER" == x"s_nag" || x"$USER" == x"nag" ]]; then prompt_color='%{%}' # green  elif [[ x"$USER" == x"root" ]]; then prompt_color='%{%}' # white  prompt_char='#' else prompt_color='%{%}' # pink  fi PROMPT=$prompt_color'%U%B%n'$rprompt_color'%U@'$prompt_color'%B%m%b %h '$prompt_char$clear_color'%u ' RPROMPT=$vcs_prompot_color'%1(v|%1v%2v|)${vcs_info_git_pushed} '$rprompt_color'[%~]'$clear_color fi ### path settings # default path path=(/usr/bin /bin) # for sbin if [[ -d /sbin ]];then path=($path /sbin) fi if [[ -d /usr/sbin ]];then path=($path /usr/sbin) fi # /usr/local if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi if [[ $os == 'mac' ]]; then export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix [email protected])" fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' - alias gco='git checkout' - alias gcob='git checkout --no-track -b' + alias gco='git switch' + alias gcob='git switch --no-track --create' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more - alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' + alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else - alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' + alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%D%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' + alias gsw='git switch' + alias gswo='git switch --orphan' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi # Settings for fzf if whence -p fzf 2>&1 > /dev/null; then if whence -p rg 2>&1 > /dev/null; then export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' fi export FZF_DEFAULT_OPTS='--height 30% --border' if [[ -f $HOME/.fzf.zsh ]]; then source ~/.fzf.zsh # replace ^R -> ^O bindkey '^O' fzf-history-widget if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward else bindkey "^R" history-incremental-search-backward fi fi fi # rg if whence -p rg 2>&1 > /dev/null; then export RG_DEFAULT_OPT=(-p --hidden) function rg() { # separated by : typeset -a glob; for p in ${(@s.:.)$(git config grep.defaultFile)}; do glob+=(--glob $p) done command rg $RG_DEFAULT_OPT "$@" "${(@)glob}" } fi # vim: sw=2
clairvy/localenv
ad19e3e4f670ae20fc9b95bc048fc9988e653f39
VIM expand redrawtime
diff --git a/.vimrc b/.vimrc index e14977b..8a62e4c 100644 --- a/.vimrc +++ b/.vimrc @@ -1,276 +1,278 @@ filetype on "dein Scripts----------------------------- if &compatible set nocompatible " Be iMproved endif let s:dein_dir = $HOME . '/.cache/dein' let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim' let s:dein_toml_dir = $HOME . '/.vim/userautoload/dein' let s:dein_enabled = 0 " dein.vim ディレクトリがruntimepathに入っていない場合、追加 if match(&runtimepath, '/dein.vim') == -1 " dein_repo_dir で指定した場所に dein.vim が無い場合、git cloneしてくる if !isdirectory(s:dein_repo_dir) execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir endif execute 'set runtimepath+=' . fnamemodify(s:dein_repo_dir, ':p') endif " Required: if dein#load_state(s:dein_dir) let s:dein_enabled = 1 call dein#begin(s:dein_dir) call dein#load_toml(s:dein_toml_dir . '/plugins.toml', {'lazy': 0}) call dein#load_toml(s:dein_toml_dir . '/lazy.toml', {'lazy': 1}) " Required: call dein#end() call dein#save_state() endif " Required: filetype plugin indent on syntax enable " If you want to install not installed plugins on startup. if dein#check_install() call dein#install() endif "End dein Scripts------------------------- " vundle を使う {{{1 set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' " Vundle Plugin 'elixir-lang/vim-elixir' Plugin 'rust-lang/rust.vim' Plugin 'fatih/vim-go' Plugin 'nsf/gocode', {'rtp': 'vim/'} call vundle#end() filetype plugin indent on "}}} " .vim/bundle を使う {{{1 call pathogen#runtime_append_all_bundles() call pathogen#infect() "}}} " Vim の流儀 より. {{{1 filetype plugin on filetype indent on syntax enable " VIMRC 編集/ロード設定 nnoremap <Space> :<C-u>edit $MYVIMRC<Enter> nnoremap <Space>s. :<C-u>source $MYVIMRC<Enter> " バックスペースが特殊な文字を削除できる set backspace=indent,eol,start " 検索に使う文字 set ignorecase set smartcase " 検索 set incsearch set hlsearch " ステータスライン "set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P "set statusline=%F%m%r%h%w\ [%{&fenc!=''?&fenc:&enc},%{&ff},%Y]\ [\%03.3b,0x\%2.2B]\ (%04l,%04v)[%LL/%p%%]\ %{strftime('%Y/%m/%d(%a)%H:%M')} "set laststatus=2 " コマンドの入力状況の表示 set showcmd " インデント関連 set tabstop=8 set softtabstop=4 set shiftwidth=4 set expandtab +" time for redraw +set redrawtime=100000 " }}} " leader {{{1 let mapleader = "," "set encoding=utf-8 "set fileencoding=utf-8 "set fileencodings=utf-8,utf-16,japan "set fileformats=unix,dos,mac "}}} " モードライン(ファイルのコメントからの読み込み) {{{1 set modeline set modelines=5 set backspace=2 set tabstop=4 set shiftwidth=4 set expandtab highlight tabs ctermbg=green guibg=green set list set listchars=tab:>- set number set ruler set smartindent "set laststatus=2 set wildmenu set wildmode=longest:full,full "}}} " 文字コードの自動認識 {{{1 set fileformats=unix,dos,mac set termencoding=utf-8 set encoding=utf-8 set fileencoding=utf-8 set fileencodings=utf-8 " 文字コードの自動認識 if &encoding !=# 'utf-8' set encoding=japan set fileencoding=japan endif if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがeucJP-msに対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'eucjp-ms' let s:enc_jis = 'iso-2022-jp-3' " iconvがJISX0213に対応しているかをチェック elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = s:fileencodings_default . ',' . &fileencodings unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 set fileencodings-=eucjp-ms let &encoding = s:enc_euc let &fileencoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " 日本語を含まない場合は fileencoding に encoding を使うようにする if has('autocmd') function! AU_ReCheck_FENC() if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0 let &fileencoding=&encoding endif endfunction autocmd BufReadPost * call AU_ReCheck_FENC() endif " 改行コードの自動認識 set fileformats=unix,dos,mac " □とか○の文字があってもカーソル位置がずれないようにする if exists('&ambiwidth') set ambiwidth=double endif " PHPManual {{{1 " PHP マニュアルを設置している場合 let g:ref_phpmanual_path = $HOME . '/local/share/phpman/php-chunked-xhtml/' let g:ref_phpmanual_cmd = 'w3m -dump %s' "let phpmanual_dir = $HOME . '/.vim/manual/php_manual_ja/' " マニュアルの拡張子 "let phpmanual_file_ext = 'html' " マニュアルのカラー表示 let phpmanual_color = 1 " iconv 変換をしない let phpmanual_convfilter = '' " w3m の表示形式を utf-8 にし、auto detect を on にする let phpmanual_htmlviewer = 'w3m -o display_charset=utf-8 -o auto_detect=2 -T text/html' " phpmanual.vim を置いているパスを指定 "source $HOME/.vim/ftplugin/phpmanual.vim "}}} " eskk {{{1 if has('vim_starting') if has('mac') let g:eskk#large_dictionary = "~/Library/Application\ Support/AquaSKK/SKK-JISYO.L" endif endif let g:eskk_debug = 0 "}}} " カーソル行をハイライト {{{1 set cursorline augroup cch autocmd! cch autocmd WinLeave * setlocal nocursorline autocmd WinEnter,BufRead * setlocal cursorline augroup END "}}} " symofny {{{1 nnoremap <silent> <Leader>v :<C-u>STview<CR> nnoremap <silent> <Leader>m :<C-u>STmodel<CR> nnoremap <silent> <Leader>a :<C-u>STaction<CR> nnoremap <silent> <Leader>p :<C-u>STpartial<CR> nnoremap <Leader>V :<C-u>STview nnoremap <Leader>M :<C-u>STmodel nnoremap <Leader>A :<C-u>STaction nnoremap <Leader>P :<C-u>STpartial "}}} " git. {{{1 nnoremap <Leader>gg :<C-u>GitGrep "}}} " vim: foldmethod=marker " window {{{1 nnoremap sj <C-w>j nnoremap sk <C-w>k nnoremap sl <C-w>l nnoremap sh <C-w>h nnoremap ss :<C-u>sp<CR><C-w>j nnoremap sv :<C-u>vs<CR><C-w>l "}}} " Indent width if has("autocmd") "ファイルタイプの検索を有効にする filetype plugin on "ファイルタイプに合わせたインデントを利用 filetype indent on "sw=softtabstop, sts=shiftwidth, ts=tabstop, et=expandtabの略 autocmd FileType ruby setlocal sw=2 sts=2 ts=2 et autocmd FileType js setlocal sw=2 sts=2 ts=2 et autocmd FileType zsh setlocal sw=2 sts=2 ts=2 et autocmd FileType json setlocal sw=2 sts=2 ts=2 et autocmd FileType yml setlocal sw=2 sts=2 ts=2 et autocmd FileType yaml setlocal sw=2 sts=2 ts=2 et autocmd FileType javascript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescriptreact setlocal sw=2 sts=2 ts=2 et autocmd FileType vim setlocal sw=2 sts=2 ts=2 et endif
clairvy/localenv
baa31a687b1786383fb93309f586635376aee98e
KARABINER update version
diff --git a/.config/karabiner/.gitignore b/.config/karabiner/.gitignore new file mode 100644 index 0000000..63c8467 --- /dev/null +++ b/.config/karabiner/.gitignore @@ -0,0 +1 @@ +/automatic_backups diff --git a/.config/karabiner/karabiner.json b/.config/karabiner/karabiner.json index 090316e..790efed 100644 --- a/.config/karabiner/karabiner.json +++ b/.config/karabiner/karabiner.json @@ -1,611 +1,770 @@ { "global": { "check_for_updates_on_startup": true, "show_in_menu_bar": true, "show_profile_name_in_menu_bar": false }, "profiles": [ { "complex_modifications": { "parameters": { - "basic.to_if_alone_timeout_milliseconds": 1000 + "basic.simultaneous_threshold_milliseconds": 50, + "basic.to_delayed_action_delay_milliseconds": 500, + "basic.to_if_alone_timeout_milliseconds": 1000, + "basic.to_if_held_down_threshold_milliseconds": 500, + "mouse_motion_to_scroll.speed": 100 }, "rules": [ { "description": "Emacs key bindings [control+keys] (rev 6)", "manipulators": [ { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "d", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "option" ] } }, "to": [ { "key_code": "delete_forward" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "h", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "option" ] } }, "to": [ { "key_code": "delete_or_backspace" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "i", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift" ] } }, "to": [ { "key_code": "tab" } ], "type": "basic" }, { "from": { "key_code": "open_bracket", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock" ] } }, "to": [ { "key_code": "escape" } ], "type": "basic" }, { "from": { "key_code": "m", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift", "option" ] } }, "to": [ { "key_code": "return_or_enter" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "b", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift", "option" ] } }, "to": [ { "key_code": "left_arrow" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "f", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift", "option" ] } }, "to": [ { "key_code": "right_arrow" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "n", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift", "option" ] } }, "to": [ { "key_code": "down_arrow" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "p", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift", "option" ] } }, "to": [ { "key_code": "up_arrow" } ], "type": "basic" }, { "conditions": [ { "bundle_identifiers": [ "^org\\.gnu\\.Emacs$", "^org\\.gnu\\.AquamacsEmacs$", "^org\\.gnu\\.Aquamacs$", "^org\\.pqrs\\.unknownapp.conkeror$", "^com\\.microsoft\\.rdc$", "^com\\.microsoft\\.rdc\\.mac$", "^com\\.microsoft\\.rdc\\.osx\\.beta$", "^net\\.sf\\.cord$", "^com\\.thinomenon\\.RemoteDesktopConnection$", "^com\\.itap-mobile\\.qmote$", "^com\\.nulana\\.remotixmac$", "^com\\.p5sys\\.jump\\.mac\\.viewer$", "^com\\.p5sys\\.jump\\.mac\\.viewer\\.web$", "^com\\.vmware\\.horizon$", "^com\\.2X\\.Client\\.Mac$", "^com\\.apple\\.Terminal$", "^com\\.googlecode\\.iterm2$", "^co\\.zeit\\.hyperterm$", "^co\\.zeit\\.hyper$", "^org\\.vim\\.", "^com\\.vmware\\.fusion$", "^com\\.vmware\\.horizon$", "^com\\.vmware\\.view$", "^com\\.parallels\\.desktop$", "^com\\.parallels\\.vm$", "^com\\.parallels\\.desktop\\.console$", "^org\\.virtualbox\\.app\\.VirtualBoxVM$", "^com\\.vmware\\.proxyApp\\.", "^com\\.parallels\\.winapp\\.", "^org\\.x\\.X11$", "^com\\.apple\\.x11$", "^org\\.macosforge\\.xquartz\\.X11$", "^org\\.macports\\.X11$" ], "type": "frontmost_application_unless" } ], "from": { "key_code": "v", "modifiers": { "mandatory": [ "control" ], "optional": [ "caps_lock", "shift" ] } }, "to": [ { "key_code": "page_down" } ], "type": "basic" } ] }, + { + "description": "SHIFT + Space を押したときに、かなキーを送信する。", + "manipulators": [ + { + "from": { + "key_code": "spacebar", + "modifiers": { + "mandatory": [ + "shift" + ], + "optional": [ + "any" + ] + } + }, + "to": [ + { + "key_code": "japanese_kana" + } + ], + "to_if_alone": [ + { + "key_code": "spacebar" + } + ], + "type": "basic" + } + ] + }, { "description": "SHIFT + Space を押したときに、かなキーを送信する。", "manipulators": [ { "from": { "key_code": "spacebar", "modifiers": { "mandatory": [ "shift" ], "optional": [ "any" ] } }, "to": [ { "key_code": "japanese_kana" } ], "to_if_alone": [ { "key_code": "spacebar" } ], "type": "basic" } ] } ] }, "devices": [ { "disable_built_in_keyboard_if_exists": false, + "fn_function_keys": [], "identifiers": { "is_keyboard": true, "is_pointing_device": false, "product_id": 38929, "vendor_id": 3526 }, - "ignore": false + "ignore": false, + "manipulate_caps_lock_led": false, + "simple_modifications": [] + } + ], + "fn_function_keys": [ + { + "from": { + "key_code": "f1" + }, + "to": [ + { + "key_code": "display_brightness_decrement" + } + ] + }, + { + "from": { + "key_code": "f2" + }, + "to": [ + { + "key_code": "display_brightness_increment" + } + ] + }, + { + "from": { + "key_code": "f3" + }, + "to": [ + { + "key_code": "mission_control" + } + ] + }, + { + "from": { + "key_code": "f4" + }, + "to": [ + { + "key_code": "launchpad" + } + ] + }, + { + "from": { + "key_code": "f5" + }, + "to": [ + { + "key_code": "illumination_decrement" + } + ] + }, + { + "from": { + "key_code": "f6" + }, + "to": [ + { + "key_code": "illumination_increment" + } + ] + }, + { + "from": { + "key_code": "f7" + }, + "to": [ + { + "key_code": "rewind" + } + ] + }, + { + "from": { + "key_code": "f8" + }, + "to": [ + { + "key_code": "play_or_pause" + } + ] + }, + { + "from": { + "key_code": "f9" + }, + "to": [ + { + "key_code": "fastforward" + } + ] + }, + { + "from": { + "key_code": "f10" + }, + "to": [ + { + "key_code": "mute" + } + ] + }, + { + "from": { + "key_code": "f11" + }, + "to": [ + { + "key_code": "volume_decrement" + } + ] + }, + { + "from": { + "key_code": "f12" + }, + "to": [ + { + "key_code": "volume_increment" + } + ] } ], - "fn_function_keys": { - "f1": "display_brightness_decrement", - "f10": "mute", - "f11": "volume_decrement", - "f12": "volume_increment", - "f2": "display_brightness_increment", - "f3": "mission_control", - "f4": "launchpad", - "f5": "illumination_decrement", - "f6": "illumination_increment", - "f7": "rewind", - "f8": "play_or_pause", - "f9": "fastforward" - }, "name": "Default profile", - "selected": true, - "simple_modifications": { - "caps_lock": "left_control" + "parameters": { + "delay_milliseconds_before_open_device": 1000 }, + "selected": true, + "simple_modifications": [ + { + "from": { + "key_code": "caps_lock" + }, + "to": [ + { + "key_code": "left_control" + } + ] + } + ], "virtual_hid_keyboard": { "caps_lock_delay_milliseconds": 0, - "keyboard_type": "ansi" + "country_code": 0, + "indicate_sticky_modifier_keys_state": true, + "keyboard_type": "ansi", + "mouse_key_xy_scale": 100 } } ] -} +} \ No newline at end of file
clairvy/localenv
f1cee3fdf96e17a8bbf980da4c15f47df99687f1
ZSH rg to use default option
diff --git a/.zshrc b/.zshrc index 6e96c10..10fbe2f 100644 --- a/.zshrc +++ b/.zshrc @@ -248,513 +248,526 @@ if [[ $os == 'bsd' ]]; then manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi if [[ $os == 'mac' ]]; then export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix [email protected])" fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git checkout' alias gcob='git checkout --no-track -b' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi # Settings for fzf if whence -p fzf 2>&1 > /dev/null; then if whence -p rg 2>&1 > /dev/null; then export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' fi export FZF_DEFAULT_OPTS='--height 30% --border' if [[ -f $HOME/.fzf.zsh ]]; then source ~/.fzf.zsh # replace ^R -> ^O bindkey '^O' fzf-history-widget if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward else bindkey "^R" history-incremental-search-backward fi fi fi +# rg +if whence -p rg 2>&1 > /dev/null; then + export RG_DEFAULT_OPT=(-p --hidden) + function rg() { + # separated by : + typeset -a glob; + for p in ${(@s.:.)$(git config grep.defaultFile)}; do + glob+=(--glob $p) + done + command rg $RG_DEFAULT_OPT "$@" "${(@)glob}" + } +fi + # vim: sw=2
clairvy/localenv
774ecb9195844b133007f1dd0a2da669f06594b6
VIM Add vim-lsp-settings and some test code
diff --git a/.vim/userautoload/dein/plugins.toml b/.vim/userautoload/dein/plugins.toml index 24e6631..1179f6c 100644 --- a/.vim/userautoload/dein/plugins.toml +++ b/.vim/userautoload/dein/plugins.toml @@ -1,141 +1,157 @@ [[plugins]] repo = 'Shougo/dein.vim' [[plugins]] repo = 'Shougo/neosnippet.vim' [[plugins]] repo = 'Shougo/neosnippet-snippets' [[plugins]] repo = 'dense-analysis/ale' hook_add = ''' let g:ale_linters = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } let g:ale_fixers = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } "let g:ale_sign_column_always = 1 "let g:ale_open_list = 1 "let g:ale_keep_list_window_open = 1 " Set this. Airline will handle the rest. let g:airline#extensions#ale#enabled = 1 ''' [[plugins]] repo = 'vim-airline/vim-airline' [[plugins]] repo = 'vim-airline/vim-airline-themes' depends = 'vim-airline' hook_add = ''' let g:airline_theme = 'onedark' " タブバーをかっこよく let g:airline#extensions#tabline#enabled = 1 " Lintツールによるエラー、警告を表示(ALEの拡張) let g:airline#extensions#ale#enabled = 1 let g:airline#extensions#ale#error_symbol = 'E:' let g:airline#extensions#ale#warning_symbol = 'W:' " , キーで次タブのバッファを表示 nnoremap <silent> < :bprev<CR> " . キーで前タブのバッファを表示 nnoremap <silent> > :bnext<CR> ''' [[plugins]] repo='prabirshrestha/async.vim' [[plugins]] repo='prabirshrestha/vim-lsp' +depends = ['async.vim'] +hook_add = ''' + let g:lsp_log_verbose = 1 + let g:lsp_log_file = expand('~/vim-lsp.log') +''' + +[[plugins]] +repo='mattn/vim-lsp-settings' [[plugins]] repo='prabirshrestha/asyncomplete.vim' +hook_add = ''' + inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>" + inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>" + inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<cr>" + imap <c-space> <Plug>(asyncomplete_force_refresh) +''' [[plugins]] repo='prabirshrestha/asyncomplete-lsp.vim' +depends = ['vim-lsp'] +on_source = ['asyncomplete.vim'] #[[plugins]] #repo='prabirshrestha/asyncomplete-neosnippet.vim' #hook_add=''' #call asyncomplete#register_source(asyncomplete#sources#neosnippet#get_source_options({ # \ 'name': 'neosnippet', # \ 'whitelist': ['*'], # \ 'completor': function('asyncomplete#sources#neosnippet#completor'), # \ })) #imap <C-k> <Plug>(neosnippet_expand_or_jump) #smap <C-k> <Plug>(neosnippet_expand_or_jump) #xmap <C-k> <Plug>(neosnippet_expand_target) #''' [[plugins]] repo = 'leafgarland/typescript-vim' [[plugins]] repo = 'tmux-plugins/vim-tmux' [[plugins]] repo = 'scrooloose/nerdtree' hook_add = ''' let NERDTreeShowHidden=1 nnoremap <silent><C-a> :NERDTreeFind<CR>:vertical res 30<CR> ''' [[plugins]] repo = 'nathanaelkane/vim-indent-guides' hook_add = ''' let g:indent_guides_enable_on_vim_startup = 1 let g:indent_guides_exclude_filetypes = ['help', 'nerdtree'] let g:indent_guides_auto_colors = 0 autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd ctermbg=237 autocmd VimEnter,Colorscheme * :hi IndentGuidesEven ctermbg=240 ''' [[plugins]] repo = 'airblade/vim-gitgutter' hook_add = ''' set signcolumn=yes let g:gitgutter_async = 1 let g:gitgutter_sign_modified = 'rw' highlight GitGutterAdd ctermfg=green highlight GitGutterChange ctermfg=yellow highlight GitGutterDelete ctermfg=red highlight GitGutterChangeDelete ctermfg=yellow ''' [[plugins]] repo = 'luochen1990/rainbow' hook_add = ''' let g:rainbow_active = 1 ''' [[plugins]] repo = 'simeji/winresizer' # fzf [[plugins]] repo = 'junegunn/fzf' hook_post_update = './install --all' merged = 0 # fzf.vim [[plugins]] repo = 'junegunn/fzf.vim' depends = 'fzf' hook_add = ''' command! -bang -nargs=* Rg \ call fzf#vim#grep( \ 'rg --column --line-number --hidden --ignore-case --no-heading --color=always '.shellescape(<q-args>), 1, \ <bang>0 ? fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}, 'up:60%') \ : fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}, 'right:50%:hidden', '?'), \ <bang>0) nnoremap <C-g> :Rg<Space> nnoremap <C-p> :GFiles<CR> nnoremap <C-h> :History<CR> ''' diff --git a/.vimrc b/.vimrc index 6d1dbfd..e14977b 100644 --- a/.vimrc +++ b/.vimrc @@ -1,284 +1,276 @@ filetype on "dein Scripts----------------------------- if &compatible set nocompatible " Be iMproved endif let s:dein_dir = $HOME . '/.cache/dein' let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim' let s:dein_toml_dir = $HOME . '/.vim/userautoload/dein' let s:dein_enabled = 0 " dein.vim ディレクトリがruntimepathに入っていない場合、追加 if match(&runtimepath, '/dein.vim') == -1 " dein_repo_dir で指定した場所に dein.vim が無い場合、git cloneしてくる if !isdirectory(s:dein_repo_dir) execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir endif execute 'set runtimepath+=' . fnamemodify(s:dein_repo_dir, ':p') endif " Required: if dein#load_state(s:dein_dir) let s:dein_enabled = 1 call dein#begin(s:dein_dir) call dein#load_toml(s:dein_toml_dir . '/plugins.toml', {'lazy': 0}) call dein#load_toml(s:dein_toml_dir . '/lazy.toml', {'lazy': 1}) " Required: call dein#end() call dein#save_state() endif " Required: filetype plugin indent on syntax enable " If you want to install not installed plugins on startup. if dein#check_install() call dein#install() endif "End dein Scripts------------------------- " vundle を使う {{{1 set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' " Vundle Plugin 'elixir-lang/vim-elixir' Plugin 'rust-lang/rust.vim' Plugin 'fatih/vim-go' Plugin 'nsf/gocode', {'rtp': 'vim/'} call vundle#end() filetype plugin indent on "}}} " .vim/bundle を使う {{{1 call pathogen#runtime_append_all_bundles() call pathogen#infect() "}}} " Vim の流儀 より. {{{1 filetype plugin on filetype indent on syntax enable " VIMRC 編集/ロード設定 nnoremap <Space> :<C-u>edit $MYVIMRC<Enter> nnoremap <Space>s. :<C-u>source $MYVIMRC<Enter> " バックスペースが特殊な文字を削除できる set backspace=indent,eol,start " 検索に使う文字 set ignorecase set smartcase " 検索 set incsearch set hlsearch " ステータスライン "set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P "set statusline=%F%m%r%h%w\ [%{&fenc!=''?&fenc:&enc},%{&ff},%Y]\ [\%03.3b,0x\%2.2B]\ (%04l,%04v)[%LL/%p%%]\ %{strftime('%Y/%m/%d(%a)%H:%M')} "set laststatus=2 " コマンドの入力状況の表示 set showcmd " インデント関連 set tabstop=8 set softtabstop=4 set shiftwidth=4 set expandtab " }}} " leader {{{1 let mapleader = "," "set encoding=utf-8 "set fileencoding=utf-8 "set fileencodings=utf-8,utf-16,japan "set fileformats=unix,dos,mac "}}} " モードライン(ファイルのコメントからの読み込み) {{{1 set modeline set modelines=5 set backspace=2 set tabstop=4 set shiftwidth=4 set expandtab highlight tabs ctermbg=green guibg=green set list set listchars=tab:>- set number set ruler set smartindent "set laststatus=2 set wildmenu set wildmode=longest:full,full "}}} " 文字コードの自動認識 {{{1 set fileformats=unix,dos,mac set termencoding=utf-8 set encoding=utf-8 set fileencoding=utf-8 set fileencodings=utf-8 " 文字コードの自動認識 if &encoding !=# 'utf-8' set encoding=japan set fileencoding=japan endif if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがeucJP-msに対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'eucjp-ms' let s:enc_jis = 'iso-2022-jp-3' " iconvがJISX0213に対応しているかをチェック elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = s:fileencodings_default . ',' . &fileencodings unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 set fileencodings-=eucjp-ms let &encoding = s:enc_euc let &fileencoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " 日本語を含まない場合は fileencoding に encoding を使うようにする if has('autocmd') function! AU_ReCheck_FENC() if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0 let &fileencoding=&encoding endif endfunction autocmd BufReadPost * call AU_ReCheck_FENC() endif " 改行コードの自動認識 set fileformats=unix,dos,mac " □とか○の文字があってもカーソル位置がずれないようにする if exists('&ambiwidth') set ambiwidth=double endif " PHPManual {{{1 " PHP マニュアルを設置している場合 let g:ref_phpmanual_path = $HOME . '/local/share/phpman/php-chunked-xhtml/' let g:ref_phpmanual_cmd = 'w3m -dump %s' "let phpmanual_dir = $HOME . '/.vim/manual/php_manual_ja/' " マニュアルの拡張子 "let phpmanual_file_ext = 'html' " マニュアルのカラー表示 let phpmanual_color = 1 " iconv 変換をしない let phpmanual_convfilter = '' " w3m の表示形式を utf-8 にし、auto detect を on にする let phpmanual_htmlviewer = 'w3m -o display_charset=utf-8 -o auto_detect=2 -T text/html' " phpmanual.vim を置いているパスを指定 "source $HOME/.vim/ftplugin/phpmanual.vim "}}} -" neocmplcache {{{1 -imap <TAB> <Plug>(neocomplcache_snippets_expand) -smap <TAB> <Plug>(neocomplcache_snippets_expand) -"imap <expr><TAB> neocomplcache#sources#snippets_complete#expandable() ? "\<Plug>(neocomplcache_snippets_expand)" : pumvisible() ? "\<C-n>" : "\<TAB>" -inoremap <expr><C-g> neocomplcache#undo_completion() -inoremap <expr><C-l> neocomplcache#complete_common_string() -"}}} - " eskk {{{1 if has('vim_starting') if has('mac') let g:eskk#large_dictionary = "~/Library/Application\ Support/AquaSKK/SKK-JISYO.L" endif endif let g:eskk_debug = 0 "}}} " カーソル行をハイライト {{{1 set cursorline augroup cch autocmd! cch autocmd WinLeave * setlocal nocursorline autocmd WinEnter,BufRead * setlocal cursorline augroup END "}}} " symofny {{{1 nnoremap <silent> <Leader>v :<C-u>STview<CR> nnoremap <silent> <Leader>m :<C-u>STmodel<CR> nnoremap <silent> <Leader>a :<C-u>STaction<CR> nnoremap <silent> <Leader>p :<C-u>STpartial<CR> nnoremap <Leader>V :<C-u>STview nnoremap <Leader>M :<C-u>STmodel nnoremap <Leader>A :<C-u>STaction nnoremap <Leader>P :<C-u>STpartial "}}} " git. {{{1 nnoremap <Leader>gg :<C-u>GitGrep "}}} " vim: foldmethod=marker " window {{{1 nnoremap sj <C-w>j nnoremap sk <C-w>k nnoremap sl <C-w>l nnoremap sh <C-w>h nnoremap ss :<C-u>sp<CR><C-w>j nnoremap sv :<C-u>vs<CR><C-w>l "}}} " Indent width if has("autocmd") "ファイルタイプの検索を有効にする filetype plugin on "ファイルタイプに合わせたインデントを利用 filetype indent on "sw=softtabstop, sts=shiftwidth, ts=tabstop, et=expandtabの略 autocmd FileType ruby setlocal sw=2 sts=2 ts=2 et autocmd FileType js setlocal sw=2 sts=2 ts=2 et autocmd FileType zsh setlocal sw=2 sts=2 ts=2 et autocmd FileType json setlocal sw=2 sts=2 ts=2 et autocmd FileType yml setlocal sw=2 sts=2 ts=2 et autocmd FileType yaml setlocal sw=2 sts=2 ts=2 et autocmd FileType javascript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescript setlocal sw=2 sts=2 ts=2 et autocmd FileType typescriptreact setlocal sw=2 sts=2 ts=2 et autocmd FileType vim setlocal sw=2 sts=2 ts=2 et endif
clairvy/localenv
e63862f85c6a283b61ad92fe6de11ffcaa7abb18
BREW Add some tools
diff --git a/Brewfile b/Brewfile index 24225a3..4dd02ed 100644 --- a/Brewfile +++ b/Brewfile @@ -1,30 +1,34 @@ tap "greymd/tools" tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/core" brew "emacs", args: ["HEAD", "cocoa", "srgb", "use-git-head"] +brew "exa" brew "fzf" brew "gist" brew "git" brew "go" brew "lv" brew "macvim" brew "mas" +brew "nodebrew" +brew "ruby-build" +brew "rbenv" brew "ripgrep" brew "rlwrap" brew "tig" brew "tmux" brew "zsh" brew "greymd/tools/tmux-xpanes" cask "alfred" cask "aquaskk" cask "bettertouchtool" cask "docker" cask "evernote" cask "iterm2" cask "karabiner-elements" cask "slack" cask "virtualbox" cask "yujitach-menumeters" mas "Memory Clean 2", id: 1114591412 mas "Xcode", id: 497799835
clairvy/localenv
214c3c24f5924a8f957d004a49658a5daa1b9c5b
ZSH Add path to openssl for ruby build
diff --git a/.zshrc b/.zshrc index 853c467..6e96c10 100644 --- a/.zshrc +++ b/.zshrc @@ -1,757 +1,760 @@ #!/usr/bin/env zsh # -*- coding: utf-8-unix; sh-basic-offset: 2; -*- stty -ixon stty -istrip bindkey -e bindkey '^W' kill-region HISTFILE=~/.zhistory HISTSIZE=100000 SAVEHIST=10000000 autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey "^P" history-beginning-search-backward-end bindkey "^N" history-beginning-search-forward-end autoload is-at-least if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward bindkey "^S" history-incremental-pattern-search-forward else bindkey "^R" history-incremental-search-backward bindkey "^S" history-incremental-search-forward fi # 複数の zsh を同時に使う時など history ファイルに上書きせず追加 setopt append_history # シェルのプロセスごとに履歴を共有 setopt share_history # 履歴ファイルに時刻を記録 setopt extended_history # history (fc -l) コマンドをヒストリリストから取り除く。 setopt hist_no_store # 直前と同じコマンドラインはヒストリに追加しない setopt hist_ignore_dups # 重複したヒストリは追加しない setopt hist_ignore_all_dups # incremental append setopt inc_append_history # ディレクトリ名だけで、ディレクトリの移動をする。 setopt auto_cd # cdのタイミングで自動的にpushd setopt auto_pushd setopt pushd_ignore_dups # fpath の追加 fpath=(~/.zfunctions/Completion ${fpath}) # unfunction して,autoload する function reload_function() { local f f=($HOME/.zfunctions/Completion/*(.)) unfunction $f:t 2> /dev/null autoload -U $f:t } # 補完設定 autoload -Uz compinit; compinit -u # ファイルリスト補完でもlsと同様に色をつける。 export LSCOLORS=GxFxCxdxBxegedabagacad export LS_COLORS='di=01;36:ln=01;35:so=01;32:ex=01;31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30' zstyle ':completion:*:default' group-name '' zstyle ':completion:*:default' use-cache true zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:default' menu select=1 zstyle ':completion:*:default' verbose yes zstyle ':completion:*:descriptions' format '%B%d%b' zstyle ':completion:*:messages' format '%d' zstyle ':completion:*:warnings' format 'No matches for: %d' zstyle ':compinstall' filename '/home/nagaya/.zshrc' zstyle ':completion:*:processes' command 'ps x' # sudo でも補完の対象 zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin \ /usr/sbin /usr/bin /sbin /bin # 補完候補が複数ある時に、一覧表示 setopt auto_list # 補完キー(Tab, Ctrl+I) を連打するだけで順に補完候補を自動で補完 setopt auto_menu # ファイル名で #, ~, ^ の 3 文字を正規表現として扱う setopt extended_glob # C-s, C-qを無効にする。 setopt NO_flow_control # 8 ビット目を通すようになり、日本語のファイル名を表示可能 setopt print_eight_bit # カッコの対応などを自動的に補完 setopt auto_param_keys # ディレクトリ名の補完で末尾の / を自動的に付加し、次の補完に備える setopt auto_param_slash # 最後がディレクトリ名で終わっている場合末尾の / を自動的に取り除く setopt auto_remove_slash # {a-c} を a b c に展開する機能を使えるようにする setopt brace_ccl # コマンドのスペルチェックをする setopt correct # =command を command のパス名に展開する setopt equals # シェルが終了しても裏ジョブに HUP シグナルを送らないようにする setopt NO_hup # Ctrl+D では終了しないようになる(exit, logout などを使う) setopt ignore_eof # コマンドラインでも # 以降をコメントと見なす setopt interactive_comments # auto_list の補完候補一覧で、ls -F のようにファイルの種別をマーク表示しない setopt list_types # 内部コマンド jobs の出力をデフォルトで jobs -l にする setopt long_list_jobs # コマンドラインの引数で --prefix=/usr などの = 以降でも補完できる setopt magic_equal_subst # ファイル名の展開でディレクトリにマッチした場合末尾に / を付加する setopt mark_dirs # 複数のリダイレクトやパイプなど、必要に応じて tee や cat の機能が使われる setopt multios # ファイル名の展開で、辞書順ではなく数値的にソートされるようになる setopt numeric_glob_sort # for, repeat, select, if, function などで簡略文法が使えるようになる setopt short_loops #コピペの時rpromptを非表示する setopt transient_rprompt # 文字列末尾に改行コードが無い場合でも表示する unsetopt promptcr # リダイレクトでファイルを消さない setopt no_clobber setopt notify setopt print_exit_value # 状態変数 local os='unknown' local uname_s=`uname -s` if [[ $uname_s == "Darwin" ]]; then os='mac' elif [[ $uname_s == "SunOS" ]]; then os='sun' elif [[ $uname_s == "FreeBSD" ]]; then os='bsd' elif [[ $uname_s == "Linux" ]]; then os='lin' elif [[ $uname_s == "CYGWIN_NT-5.1" ]]; then os='win' fi [ -z "$HOSTNAME" ] && HOSTNAME=`uname -n` # すごいプロンプト setopt prompt_subst autoload -U colors; colors autoload -Uz add-zsh-hook if [[ $ZSH_VERSION != [1-3].* && $ZSH_VERSION != 4.[12].* ]]; then autoload -Uz vcs_info zstyle ':vcs_info:*' enable git svn hg bzr zstyle ':vcs_info:*' formats '(%s)-[%b]' zstyle ':vcs_info:*' actionformats '(%s)-[%b|%a]' zstyle ':vcs_info:(svn|bzr):*' branchformat '%b:r%r' zstyle ':vcs_info:bzr:*' use-simple true if is-at-least 4.3.10; then zstyle ':vcs_info:git:*' check-for-changes true zstyle ':vcs_info:git:*' stagedstr '+' zstyle ':vcs_info:git:*' unstagedstr '-' zstyle ':vcs_info:git:*' formats '(%s)-[%c%u%b]' zstyle ':vcs_info:git:*' actionformats '(%s)-[%c%u%b|%a]' fi function _update_vcs_info_msg() { psvar=() LANG=en_US.UTF-8 vcs_info psvar[2]=$(_git_not_pushed) [[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_" } add-zsh-hook precmd _update_vcs_info_msg function _git_not_pushed() { if [[ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = "true" ]]; then head="$(git rev-parse HEAD)" for x in $(git rev-parse --remotes); do if [[ "$head" = "$x" ]]; then return 0 fi done echo "{?}" fi return 0 } fi if [[ x"$os" == x"win" ]]; then export TERM=cygwin fi if [[ x"$TERM" == x"dumb" || x"$TERM" == x"sun" || x"$TERM" == x"emacs" ]]; then use_color= else use_color='true' fi if [[ x"$use_color" != x"true" ]]; then PROMPT='%U%B%n@%m%b %h %#%u ' RPROMPT= else local prompt_color='%{%}' local clear_color='%{%}' local rprompt_color='%{%}' # yellow  local vcs_prompot_color='%{%}' # green  local prompt_char='$' if [[ x"$USER" == x"s-nag" || x"$USER" == x"nagaya" || x"$USER" == x"s_nag" || x"$USER" == x"nag" ]]; then prompt_color='%{%}' # green  elif [[ x"$USER" == x"root" ]]; then prompt_color='%{%}' # white  prompt_char='#' else prompt_color='%{%}' # pink  fi PROMPT=$prompt_color'%U%B%n'$rprompt_color'%U@'$prompt_color'%B%m%b %h '$prompt_char$clear_color'%u ' RPROMPT=$vcs_prompot_color'%1(v|%1v%2v|)${vcs_info_git_pushed} '$rprompt_color'[%~]'$clear_color fi ### path settings # default path path=(/usr/bin /bin) # for sbin if [[ -d /sbin ]];then path=($path /sbin) fi if [[ -d /usr/sbin ]];then path=($path /usr/sbin) fi # /usr/local if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi +if [[ $os == 'mac' ]]; then + export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix [email protected])" +fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git checkout' alias gcob='git checkout --no-track -b' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi # Settings for fzf if whence -p fzf 2>&1 > /dev/null; then if whence -p rg 2>&1 > /dev/null; then export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' fi export FZF_DEFAULT_OPTS='--height 30% --border' if [[ -f $HOME/.fzf.zsh ]]; then source ~/.fzf.zsh # replace ^R -> ^O bindkey '^O' fzf-history-widget if is-at-least 4.3.10; then bindkey "^R" history-incremental-pattern-search-backward else bindkey "^R" history-incremental-search-backward fi fi fi # vim: sw=2
clairvy/localenv
0c01c13146342b1230abbe9055187dc5cc326ceb
ZSH Bindkey Ctrl-O to fzf
diff --git a/.zshrc b/.zshrc index b44bbc9..853c467 100644 --- a/.zshrc +++ b/.zshrc @@ -229,523 +229,529 @@ if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git checkout' alias gcob='git checkout --no-track -b' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi # Settings for fzf if whence -p fzf 2>&1 > /dev/null; then - path=($path $HOME/.fzf/bin) if whence -p rg 2>&1 > /dev/null; then export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' fi export FZF_DEFAULT_OPTS='--height 30% --border' if [[ -f $HOME/.fzf.zsh ]]; then source ~/.fzf.zsh + # replace ^R -> ^O + bindkey '^O' fzf-history-widget + if is-at-least 4.3.10; then + bindkey "^R" history-incremental-pattern-search-backward + else + bindkey "^R" history-incremental-search-backward + fi fi fi # vim: sw=2
clairvy/localenv
010be2d2340d02502d7b6f4043080cef5eef6f88
VIM Add indent setting
diff --git a/.vimrc b/.vimrc index da94713..6d1dbfd 100644 --- a/.vimrc +++ b/.vimrc @@ -1,265 +1,284 @@ filetype on "dein Scripts----------------------------- if &compatible set nocompatible " Be iMproved endif let s:dein_dir = $HOME . '/.cache/dein' let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim' let s:dein_toml_dir = $HOME . '/.vim/userautoload/dein' let s:dein_enabled = 0 " dein.vim ディレクトリがruntimepathに入っていない場合、追加 if match(&runtimepath, '/dein.vim') == -1 " dein_repo_dir で指定した場所に dein.vim が無い場合、git cloneしてくる if !isdirectory(s:dein_repo_dir) execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir endif execute 'set runtimepath+=' . fnamemodify(s:dein_repo_dir, ':p') endif " Required: if dein#load_state(s:dein_dir) let s:dein_enabled = 1 call dein#begin(s:dein_dir) call dein#load_toml(s:dein_toml_dir . '/plugins.toml', {'lazy': 0}) call dein#load_toml(s:dein_toml_dir . '/lazy.toml', {'lazy': 1}) " Required: call dein#end() call dein#save_state() endif " Required: filetype plugin indent on syntax enable " If you want to install not installed plugins on startup. if dein#check_install() call dein#install() endif "End dein Scripts------------------------- " vundle を使う {{{1 set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' " Vundle Plugin 'elixir-lang/vim-elixir' Plugin 'rust-lang/rust.vim' Plugin 'fatih/vim-go' Plugin 'nsf/gocode', {'rtp': 'vim/'} call vundle#end() filetype plugin indent on "}}} " .vim/bundle を使う {{{1 call pathogen#runtime_append_all_bundles() call pathogen#infect() "}}} " Vim の流儀 より. {{{1 filetype plugin on filetype indent on syntax enable " VIMRC 編集/ロード設定 nnoremap <Space> :<C-u>edit $MYVIMRC<Enter> nnoremap <Space>s. :<C-u>source $MYVIMRC<Enter> " バックスペースが特殊な文字を削除できる set backspace=indent,eol,start " 検索に使う文字 set ignorecase set smartcase " 検索 set incsearch set hlsearch " ステータスライン "set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P "set statusline=%F%m%r%h%w\ [%{&fenc!=''?&fenc:&enc},%{&ff},%Y]\ [\%03.3b,0x\%2.2B]\ (%04l,%04v)[%LL/%p%%]\ %{strftime('%Y/%m/%d(%a)%H:%M')} "set laststatus=2 " コマンドの入力状況の表示 set showcmd " インデント関連 set tabstop=8 set softtabstop=4 set shiftwidth=4 set expandtab " }}} " leader {{{1 let mapleader = "," "set encoding=utf-8 "set fileencoding=utf-8 "set fileencodings=utf-8,utf-16,japan "set fileformats=unix,dos,mac "}}} " モードライン(ファイルのコメントからの読み込み) {{{1 set modeline set modelines=5 set backspace=2 set tabstop=4 set shiftwidth=4 set expandtab highlight tabs ctermbg=green guibg=green set list set listchars=tab:>- set number set ruler set smartindent "set laststatus=2 set wildmenu set wildmode=longest:full,full "}}} " 文字コードの自動認識 {{{1 set fileformats=unix,dos,mac set termencoding=utf-8 set encoding=utf-8 set fileencoding=utf-8 set fileencodings=utf-8 " 文字コードの自動認識 if &encoding !=# 'utf-8' set encoding=japan set fileencoding=japan endif if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがeucJP-msに対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'eucjp-ms' let s:enc_jis = 'iso-2022-jp-3' " iconvがJISX0213に対応しているかをチェック elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = s:fileencodings_default . ',' . &fileencodings unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 set fileencodings-=eucjp-ms let &encoding = s:enc_euc let &fileencoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " 日本語を含まない場合は fileencoding に encoding を使うようにする if has('autocmd') function! AU_ReCheck_FENC() if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0 let &fileencoding=&encoding endif endfunction autocmd BufReadPost * call AU_ReCheck_FENC() endif " 改行コードの自動認識 set fileformats=unix,dos,mac " □とか○の文字があってもカーソル位置がずれないようにする if exists('&ambiwidth') set ambiwidth=double endif " PHPManual {{{1 " PHP マニュアルを設置している場合 let g:ref_phpmanual_path = $HOME . '/local/share/phpman/php-chunked-xhtml/' let g:ref_phpmanual_cmd = 'w3m -dump %s' "let phpmanual_dir = $HOME . '/.vim/manual/php_manual_ja/' " マニュアルの拡張子 "let phpmanual_file_ext = 'html' " マニュアルのカラー表示 let phpmanual_color = 1 " iconv 変換をしない let phpmanual_convfilter = '' " w3m の表示形式を utf-8 にし、auto detect を on にする let phpmanual_htmlviewer = 'w3m -o display_charset=utf-8 -o auto_detect=2 -T text/html' " phpmanual.vim を置いているパスを指定 "source $HOME/.vim/ftplugin/phpmanual.vim "}}} " neocmplcache {{{1 imap <TAB> <Plug>(neocomplcache_snippets_expand) smap <TAB> <Plug>(neocomplcache_snippets_expand) "imap <expr><TAB> neocomplcache#sources#snippets_complete#expandable() ? "\<Plug>(neocomplcache_snippets_expand)" : pumvisible() ? "\<C-n>" : "\<TAB>" inoremap <expr><C-g> neocomplcache#undo_completion() inoremap <expr><C-l> neocomplcache#complete_common_string() "}}} " eskk {{{1 if has('vim_starting') if has('mac') let g:eskk#large_dictionary = "~/Library/Application\ Support/AquaSKK/SKK-JISYO.L" endif endif let g:eskk_debug = 0 "}}} " カーソル行をハイライト {{{1 set cursorline augroup cch autocmd! cch autocmd WinLeave * setlocal nocursorline autocmd WinEnter,BufRead * setlocal cursorline augroup END "}}} " symofny {{{1 nnoremap <silent> <Leader>v :<C-u>STview<CR> nnoremap <silent> <Leader>m :<C-u>STmodel<CR> nnoremap <silent> <Leader>a :<C-u>STaction<CR> nnoremap <silent> <Leader>p :<C-u>STpartial<CR> nnoremap <Leader>V :<C-u>STview nnoremap <Leader>M :<C-u>STmodel nnoremap <Leader>A :<C-u>STaction nnoremap <Leader>P :<C-u>STpartial "}}} " git. {{{1 nnoremap <Leader>gg :<C-u>GitGrep "}}} " vim: foldmethod=marker " window {{{1 nnoremap sj <C-w>j nnoremap sk <C-w>k nnoremap sl <C-w>l nnoremap sh <C-w>h nnoremap ss :<C-u>sp<CR><C-w>j nnoremap sv :<C-u>vs<CR><C-w>l "}}} + +" Indent width +if has("autocmd") + "ファイルタイプの検索を有効にする + filetype plugin on + "ファイルタイプに合わせたインデントを利用 + filetype indent on + "sw=softtabstop, sts=shiftwidth, ts=tabstop, et=expandtabの略 + autocmd FileType ruby setlocal sw=2 sts=2 ts=2 et + autocmd FileType js setlocal sw=2 sts=2 ts=2 et + autocmd FileType zsh setlocal sw=2 sts=2 ts=2 et + autocmd FileType json setlocal sw=2 sts=2 ts=2 et + autocmd FileType yml setlocal sw=2 sts=2 ts=2 et + autocmd FileType yaml setlocal sw=2 sts=2 ts=2 et + autocmd FileType javascript setlocal sw=2 sts=2 ts=2 et + autocmd FileType typescript setlocal sw=2 sts=2 ts=2 et + autocmd FileType typescriptreact setlocal sw=2 sts=2 ts=2 et + autocmd FileType vim setlocal sw=2 sts=2 ts=2 et +endif
clairvy/localenv
b6b9a8404d6f5b85f2a2b2c7a56f424ff1460478
TIG add move command and view setting
diff --git a/.tigrc b/.tigrc index 0ea54e9..292a446 100644 --- a/.tigrc +++ b/.tigrc @@ -1,33 +1,69 @@ #--------------------------------------------------------------# ## tig settings ## #--------------------------------------------------------------# set main-view = id:yes date:default,local=yes author commit-title:graph=yes,refs=yes,overflow=false set blame-view = date:default id:yes,color line-number:yes,interval=1 text -set pager-view = text -set stage-view = text -set log-view = text -set blob-view = text -set diff-view = text:yes,commit-title-overflow=no +set pager-view = line-number:yes,interval=1 text +set stage-view = line-number:yes,interval=1 text +set log-view = line-number:yes,interval=1 text +set blob-view = line-number:yes,interval=1 text +set diff-view = line-number:yes,interval=1 text:yes,commit-title-overflow=no set tab-size = 2 set ignore-case = true set split-view-width = 80% set split-view-height = 80% set diff-options = -m --first-parent set refresh-mode = auto +# utf-8 文字で画面描画する (~でトグル) +set line-graphics = utf-8 + #--------------------------------------------------------------# ## key bind ## #--------------------------------------------------------------# + +# g をファイル先頭に移動に変更、 view-grep を再割当て +bind generic g move-first-line +bind generic E view-grep + +# G でファイル末尾に移動 (default: :toggle commit-title-graph) +bind generic G move-last-line +bind main G move-last-line + +# n / p を上下移動に割り当て (default: find-next / view-pager) +bind generic n move-down +bind generic p move-up + +# # n / p で単位ごとの移動 +bind diff n :/^@@ +bind diff p :?^@@ +bind diff <Esc>n :/^diff --(git|cc) +bind diff <Esc>p :?^diff --(git|cc) +bind stage n :/^@@ +bind stage p :?^@@ +bind stage <Esc>n :/^diff --(git|cc) +bind stage <Esc>p :?^diff --(git|cc) +bind pager n :/^@@ +bind pager p :?^@@ +bind pager <Esc>n :/^diff --(git|cc) +bind pager <Esc>p :?^diff --(git|cc) +bind log n :/^commit +bind log p :?^commit + +# Ctrl-v, Alt-v でページ単位移動 (ターミナルに食われるので Ctrl-v は2度押しが必要) +bind generic <Ctrl-v> move-page-down +bind generic <Esc>v move-page-up + # Pで現在のブランチへpush bind generic P ?@!git push origin %(repo:head) # Dでstatus viewのuntracked fileを削除できるようにする # https://github.com/jonas/tig/issues/31 見るとおもしろい # https://github.com/jonas/tig/issues/393 見るとおもしろい bind status D ?@rm %(file) # そのほかのGitコマンド bind generic F ?@!git fetch %(remote) bind generic U ?@!git pull %(remote) color cursor black white bold
clairvy/localenv
b71974a53500793fe6b6167bfbfbc67c960a3ca0
VIM Add fzf conf
diff --git a/.vim/userautoload/dein/plugins.toml b/.vim/userautoload/dein/plugins.toml index dfb3d86..24e6631 100644 --- a/.vim/userautoload/dein/plugins.toml +++ b/.vim/userautoload/dein/plugins.toml @@ -1,119 +1,141 @@ [[plugins]] repo = 'Shougo/dein.vim' [[plugins]] repo = 'Shougo/neosnippet.vim' [[plugins]] repo = 'Shougo/neosnippet-snippets' [[plugins]] repo = 'dense-analysis/ale' hook_add = ''' let g:ale_linters = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } let g:ale_fixers = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } "let g:ale_sign_column_always = 1 "let g:ale_open_list = 1 "let g:ale_keep_list_window_open = 1 " Set this. Airline will handle the rest. let g:airline#extensions#ale#enabled = 1 ''' [[plugins]] repo = 'vim-airline/vim-airline' [[plugins]] repo = 'vim-airline/vim-airline-themes' depends = 'vim-airline' hook_add = ''' let g:airline_theme = 'onedark' " タブバーをかっこよく let g:airline#extensions#tabline#enabled = 1 " Lintツールによるエラー、警告を表示(ALEの拡張) let g:airline#extensions#ale#enabled = 1 let g:airline#extensions#ale#error_symbol = 'E:' let g:airline#extensions#ale#warning_symbol = 'W:' " , キーで次タブのバッファを表示 nnoremap <silent> < :bprev<CR> " . キーで前タブのバッファを表示 nnoremap <silent> > :bnext<CR> ''' [[plugins]] repo='prabirshrestha/async.vim' [[plugins]] repo='prabirshrestha/vim-lsp' [[plugins]] repo='prabirshrestha/asyncomplete.vim' [[plugins]] repo='prabirshrestha/asyncomplete-lsp.vim' #[[plugins]] #repo='prabirshrestha/asyncomplete-neosnippet.vim' #hook_add=''' #call asyncomplete#register_source(asyncomplete#sources#neosnippet#get_source_options({ # \ 'name': 'neosnippet', # \ 'whitelist': ['*'], # \ 'completor': function('asyncomplete#sources#neosnippet#completor'), # \ })) #imap <C-k> <Plug>(neosnippet_expand_or_jump) #smap <C-k> <Plug>(neosnippet_expand_or_jump) #xmap <C-k> <Plug>(neosnippet_expand_target) #''' [[plugins]] repo = 'leafgarland/typescript-vim' [[plugins]] repo = 'tmux-plugins/vim-tmux' [[plugins]] repo = 'scrooloose/nerdtree' hook_add = ''' let NERDTreeShowHidden=1 nnoremap <silent><C-a> :NERDTreeFind<CR>:vertical res 30<CR> ''' [[plugins]] repo = 'nathanaelkane/vim-indent-guides' hook_add = ''' let g:indent_guides_enable_on_vim_startup = 1 let g:indent_guides_exclude_filetypes = ['help', 'nerdtree'] let g:indent_guides_auto_colors = 0 autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd ctermbg=237 autocmd VimEnter,Colorscheme * :hi IndentGuidesEven ctermbg=240 ''' [[plugins]] repo = 'airblade/vim-gitgutter' hook_add = ''' set signcolumn=yes let g:gitgutter_async = 1 let g:gitgutter_sign_modified = 'rw' highlight GitGutterAdd ctermfg=green highlight GitGutterChange ctermfg=yellow highlight GitGutterDelete ctermfg=red highlight GitGutterChangeDelete ctermfg=yellow ''' [[plugins]] repo = 'luochen1990/rainbow' hook_add = ''' let g:rainbow_active = 1 ''' [[plugins]] repo = 'simeji/winresizer' + +# fzf +[[plugins]] +repo = 'junegunn/fzf' +hook_post_update = './install --all' +merged = 0 + +# fzf.vim +[[plugins]] +repo = 'junegunn/fzf.vim' +depends = 'fzf' +hook_add = ''' + command! -bang -nargs=* Rg + \ call fzf#vim#grep( + \ 'rg --column --line-number --hidden --ignore-case --no-heading --color=always '.shellescape(<q-args>), 1, + \ <bang>0 ? fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}, 'up:60%') + \ : fzf#vim#with_preview({'options': '--delimiter : --nth 4..'}, 'right:50%:hidden', '?'), + \ <bang>0) + nnoremap <C-g> :Rg<Space> + nnoremap <C-p> :GFiles<CR> + nnoremap <C-h> :History<CR> +'''
clairvy/localenv
1317a633c81509db2b60a9f9074fe0c03258f90a
ZSH Add fzf conf
diff --git a/.zshrc b/.zshrc index af6b121..b44bbc9 100644 --- a/.zshrc +++ b/.zshrc @@ -227,513 +227,525 @@ fi # /usr/local if [[ -d /usr/local/sbin ]]; then path=(/usr/local/sbin $path) fi if [[ -d /usr/local/bin ]]; then path=(/usr/local/bin $path) fi if [[ -d /usr/local/share/man ]]; then manpath=(/usr/local/share/man $manpath) fi # path settings for Mac ports if [[ $os == 'mac' ]]; then export LC_ALL=ja_JP.UTF-8 if [[ -d /opt/local/bin ]]; then path=(/opt/local/bin /opt/local/sbin $path) manpath=(/opt/local/share/man $manpath) fi fi # for BSDPAN and local path if [[ $os == 'bsd' ]]; then path=($path /usr/local/bin:/usr/local/sbin) manpath=($manpath /usr/local/share/man /usr/local/man) export PKG_DBDIR=$HOME/local/var/db/pkg export PORT_DBDIR=$HOME/local/var/db/pkg export INSTALL_AS_USER export LD_LIBRARY_PATH=$HOME/local/lib fi # for csw if [[ $os == 'sun' && -d /opt/csw/bin ]]; then path=(/opt/csw/bin $path) fi # for local::lib #local_lib_path="$HOME/perl5" #function _set_perl_env () { # export PERL_LOCAL_LIB_ROOT="${local_lib_path}"; # export PERL_MM_OPT="INSTALL_BASE=${local_lib_path}" # export PERL_MB_OPT="--install_base ${local_lib_path}" # export PERL5LIB="${local_lib_path}/lib/perl5:${local_lib_path}/lib/perl5/$site" # export PERL_CPANM_OPT="--local-lib=${local_lib_path}" # path=(${local_lib_path}/bin $path) #} #if [[ "x$HOSTNAME" == "xdv1" ]]; then # function set_perl_env () { # local site='i486-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ $os == 'mac' ]]; then # function set_perl_env () { # local site='darwin-multi-2level' # _set_perl_env # } # function set_perl_env_wx () { # local site='darwin-thread-multi-2level' # _set_perl_env # } # set_perl_env #elif [[ $os == 'bsd' ]]; then # function set_perl_env () { # local site='i386-freebsd-64int' # _set_perl_env # } # set_perl_env #elif [[ x"$HOSTNAME" == x'kaname' ]]; then # function set_perl_env() { # local site='i686-linux-gnu-thread-multi' # _set_perl_env # } # set_perl_env #elif [[ -d $local_lib_path ]]; then # function set_perl_env() { # local site=`perl -V:archname | awk -F\' '{print $2}'` # _set_perl_env # } # set_perl_env #fi # path settings for ~/local if [[ -d $HOME/local ]]; then path=($HOME/local/bin $HOME/local/sbin $path) manpath=($HOME/local/man $manpath) fi # for cabal if [[ -d $HOME/.cabal/bin ]]; then path=($HOME/.cabal/bin $path) fi # for gems if [[ -d /var/lib/gems/1.8/bin ]]; then path=($path /var/lib/gems/1.8/bin) fi ### command settings if whence -p lv 2>&1 > /dev/null; then if [[ $TERM_PROGRAM == "iTerm.app" ]]; then alias lv='command lv -Ou' fi export PAGER='lv -Ou' alias lc='lv | cat' fi if whence -p tmux 2>&1 > /dev/null; then function tmux() { if [ $# -le 0 ] && command tmux list-clients > /dev/null; then command tmux attach; else command tmux $*; fi } alias tml='command tmux list-sessions' fi if whence -p xsbt 2>&1 > /dev/null; then function sbt() { if [ *.sbt(N) ]; then command xsbt "$@"; else command sbt "$@"; fi } fi # rbenv if [[ -d /usr/local/opt/rbenv ]]; then export RBENV_ROOT=/usr/local/opt/rbenv if [[ -r /usr/local/opt/rbenv/completions/rbenv.zsh ]]; then source "/usr/local/opt/rbenv/completions/rbenv.zsh" fi if which rbenv > /dev/null; then eval "$(rbenv init -)" fi fi if [[ -d $HOME/.rbenv/bin ]]; then path=($HOME/.rbenv/bin $path) eval "$(rbenv init -)" if [[ -r $HOME/.rbenv/completions/rbenv.zsh ]]; then source "$HOME/.rbenv/completions/rbenv.zsh" fi fi if [[ -f /etc/profile.d/rbenv.sh ]]; then . /etc/profile.d/rbenv.sh fi # for gisty export GISTY_DIR="$HOME/work/gists" # for perl Devel::Cover alias cover='cover -test -ignore "^inc/"' # for perl Test::Pod::Coverage export TEST_POD=1 # for perldoc if [[ $os == 'mac' ]]; then alias perldoc='perldoc -t' fi # for scaladoc export SCALA_DOC_HOME=/Users/s_nag/s/app/InteractiveHelp/scala-2.7.5-apidocs-fixed/ # ignore mailcheck export MAILCHECK=0 # set tmpdir export TMPDIR=/var/tmp # alias alias mv='nocorrect mv -i' alias cp='nocorrect cp -ip' alias ln='nocorrect ln' alias mkdir='nocorrect mkdir' alias mgdir='nocorrect mkdir -m 775' alias rm='rm -i' alias history='builtin history -Di' alias his='history | tail' if whence -p exa 2>&1 > /dev/null; then alias ls='exa -F' else if [[ $use_color == 'true' ]]; then if [[ $os == 'mac' || $os == 'bsd' ]]; then alias ls='command ls -AFG' elif [[ $os == 'sun' ]]; then alias ls='command ls -AF' else alias ls='command ls -AF --color=auto --show-control-chars' fi else alias ls='command ls -AF' fi fi alias ln='ln -n' alias x='exit' alias first_release="perl -mModule::CoreList -le 'print Module::CoreList->first_release(@ARGV)'" alias first_number_sort="perl -e '@l=<>;print(map{\$_->[1]}sort{\$a->[0]<=>\$b->[0]}map{[do{m/(\d+)/;\$1},\$_]}@l)'" alias screen='command screen -U' alias scc='screen' alias scx='screen -x' alias hex='perl -le "print unpack q(H*), shift"' alias grep='grep --color' alias egrep='egrep --color' alias snh='sort -nr | head' alias suc='sort | uniq -c' if whence -p vim 2>&1 > /dev/null; then alias vi=vim export EDITOR=vim else export EDITOR=vi fi if [[ $os == 'mac' ]]; then if [[ -f /opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/opt/local/var/macports/software/emacs-app/23.1_1/Applications/MacPorts/Emacs.app/Contents/MacOS/bin/emacsclient' elif [[ -f /usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs ]]; then alias emacs-app='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/Emacs' alias emacsclient='/usr/local/Cellar/emacs/HEAD/Emacs.app/Contents/MacOS/bin/emacsclient' fi local jfe='-Dfile.encoding=UTF-8' alias javac="javac -J$jfe -Xlint:unchecked -Xlint:deprecation" alias java="java $jfe" alias jarsigner="jarsigner -J$jfe" export ANT_OPTS="$jfe" export MAVEN_OPTS="$jfe" export SETUP_SH_VMARGS="$jfe" if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]; then alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' export EDITOR='/Applications/MacVim.app/Contents/MacOS/Vim' fi if [[ -d /usr/share/terminfo ]]; then export TERMINFO='/usr/share/terminfo' fi alias bluetooth-fix='sudo kextunload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport; sudo kextload -b com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport' fi if whence -p vim 2>&1 > /dev/null; then alias vi=vim if [[ x"$EDITOR" = x"" ]]; then export EDITOR=vim fi fi export MYSQL_PS1='(\u@\h) [\d] > ' if whence -p mysql 2>&1 > /dev/null; then alias mysql='mysql --auto-rehash' fi alias phpcs='phpcs --standard=Symfony' if whence -p git 2>&1 > /dev/null; then alias -g S160=--stat=160 alias -g SS=--stat=160 alias g1="git log --graph -n 20 --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(green)- %an, %cr%Creset'" alias ga='git add' alias gad='git add .' alias galias='( alias | egrep git\ ; gsa )' alias gap='git add -p' alias gb='git branch' alias gbD='git branch -D' alias gbd='git branch -d' alias gc='git commit' alias gca='git commit --amend' alias gcm='git commit -m' alias gco='git checkout' alias gcob='git checkout --no-track -b' alias gd1='git diff HEAD~' alias gd='git diff' alias gdel='git rm' alias gds='git diff --staged' alias gdsw='git diff --staged -w' alias gdw='git diff -w' alias gf='git fetch' alias gfp='git fetch --prune' alias gfb="git filter-branch --commit-filter 'GIT_AUTHOR_NAME=clairvy; [email protected]; GIT_COMMITTER_NAME=clairvy; [email protected]; git commit-tree \"\$@\"' HEAD" alias gg='git grep' alias ghh='git reset --hard' alias gl='git log' if [[ 2006 -le `git --version | awk '{print $3}' | awk -F. '{printf "%d%03d", $1, $2}' 2> /dev/null` ]]; then # 2.6 or more alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %ad%Creset c:%cn:%ce a:%an:%ae" --date=format:"%Y/%m/%d %H:%M:%S%z"' else alias gla='git log --graph --all --color --pretty="%x09%h %s %Cred%d%Creset %C(green)- %cr%Creset c:%cn:%ce a:%an:%ae"' fi alias gls='git status' # for gnu ls not to use alias gp='git push' alias gpn='git push -n' alias gpd='git push --delete' alias gr='git rebase' alias gra='git rebase --abort' alias grc='git rebase --continue' alias gri='git rebase -i' alias grm='git rebase master' function gro { git rebase origin/$1 $1 } alias grom='git rebase origin/master master' alias gs='git status' alias gsa='git config -l | egrep alias' alias gsc='git config -l' alias gshow='git show' alias gslocal='git config user.email [email protected]; git config user.name clairvy' alias gsshow='git config user.email; git config user.name' alias gst='git status -sb' alias gsu='git submodule update' alias gsui='git submodule update --init' alias gurm='git update-ref -d refs/original/refs/heads/master' alias gw='git diff -w' alias gx='git rm' fi for c in ocaml gosh clisp; do if whence -p $c 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias $c="command rlwrap $c" fi fi done if whence -p scala 2>&1 > /dev/null; then if whence -p rlwrap 2>&1 > /dev/null; then alias scala='rlwrap scala -deprecation' else alias scala='scala -deprecation' fi fi if whence -p dart 2>&1 > /dev/null; then alias dart='dart --checked' fi # boot2docker if whence -p VBoxManage 2>&1 > /dev/null; then alias boot2dockershowpf='VBoxManage showvminfo boot2docker-vm | egrep "NIC.*Rule" | perl -lpe '\''s/NIC (\d+) Rule\(\d+\)/natpf\1/;s/,[^,]+ = /,/g;s/:[^:]+ = / /g'\''' alias boot2dockershowpf-name='boot2dockershowpf | awk -F, '\''{print $1}'\' function boot2docker-add-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <port>" else VBoxManage controlvm boot2docker-vm natpf1 "tp$1,tcp,,$1,,$1" fi } function boot2docker-del-pf { if [[ $# -lt 1 ]]; then echo "usage : $0 <name>" else VBoxManage controlvm boot2docker-vm natpf1 delete $1 fi } fi # 補完するかの質問は画面を超える時にのみに行う。 LISTMAX=0 # Ctrl+wで、直前の/までを削除する。 WORDCHARS='*?_-.[]~=&;!#$%^(){}<>' # href の補完 compctl -K _href href functions _href () { local href_datadir=`href_datadir` reply=(`cat $href_datadir/comptable|awk -F, '{print $2}'|sort|uniq`) # /usr/share/href/comptable の Path は自分の環境に書き換える } typeset -U path typeset -U manpath typeset -U fpath # keychain if whence -p keychain 2>&1 > /dev/null; then keychain id_rsa if [ -f $HOME/.keychain/$HOSTNAME-sh ]; then . $HOME/.keychain/$HOSTNAME-sh fi if [ -f $HOME/.keychain/$HOSTNAME-sh-gpg ]; then . $HOME/.keychain/$HOSTNAME-sh-gpg fi fi # z.sh if [[ -f ~/.zfunctions/z/z.sh ]]; then _Z_CMD=j source ~/.zfunctions/z/z.sh precmd() { _z --add "$(pwd -P)" } fi # load host local settings if [[ -f $HOME/.zshrc.local ]]; then . $HOME/.zshrc.local fi # git if [[ -d /usr/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/share/git-core/Git-Hooks if [[ -f /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -d /usr/local/share/git-core/Git-Hooks ]]; then export GIT_HOOKS_HOME=/usr/local/share/git-core/Git-Hooks if [[ -f /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh ]]; then source /usr/local/share/git-core/Git-Hooks/git-hooks-completion.zsh fi fi if [[ -f $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh ]]; then source $HOME/.zfunctions/git-flow-completion/git-flow-completion.zsh fi # perlbrew if [[ -f $HOME/perl5/perlbrew/etc/bashrc ]]; then source $HOME/perl5/perlbrew/etc/bashrc fi # plenv if [[ -d $HOME/.plenv/bin ]]; then path=($path $HOME/.plenv/bin) eval "$(plenv init -)" fi # pythonbrew if [[ -f $HOME/.pythonbrew/etc/bashrc ]]; then source $HOME/.pythonbrew/etc/bashrc fi # Homebrew if whence -p brew 2>&1 > /dev/null; then alias brew-bundle="cat ~/Brewfile | grep '^[a-z]' | sed -e 's/^/brew /' | bash -x" fi # rvm if [[ -f $HOME/.rvm/scripts/rvm ]]; then source $HOME/.rvm/scripts/rvm fi # node.js if [[ -d /usr/local/lib/node_modules ]]; then export NODE_PATH=/usr/local/lib/node_modules fi if [[ -d $HOME/.nodebrew/current/bin ]]; then export PATH=$HOME/.nodebrew/current/bin:$PATH fi if [[ -d $HOME/.nodebrew/current/lib/node_modules ]]; then export NODE_PATH=$HOME/.nodebrew/current/lib/node_modules fi # haskell if [[ -d $HOME/Library/Haskell/bin ]]; then path=($path $HOME/Library/Haskell/bin) fi # smlnj if [[ -d /usr/local/Cellar/smlnj/110.73/libexec/bin ]]; then path=($path /usr/local/Cellar/smlnj/110.73/libexec/bin) fi # byobu if whence -p brew 2>&1 > /dev/null; then export BYOBU_PREFIX=$(brew --prefix) fi # peco if which peco > /dev/null 2>&1; then function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(builtin history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^x^r' peco-select-history fi # go if [[ -d $HOME/w/gopath ]]; then export GOPATH=$HOME/w/gopath path=($path $GOPATH/bin) fi # tex if [[ -d /usr/texbin ]]; then path=($path /usr/texbin) fi if [[ -d $HOME/google-cloud-sdk ]]; then # The next line updates PATH for the Google Cloud SDK. source "$HOME/google-cloud-sdk/path.zsh.inc" # The next line enables zsh completion for gcloud. source "$HOME/google-cloud-sdk/completion.zsh.inc" fi test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" # pyenv if [[ -d $HOME/.pyenv ]]; then path=($HOME/.pyenv/bin $path) eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" fi # tex if [[ -d /Library/TeX/texbin ]]; then path=($path /Library/TeX/texbin) fi # zplug if [[ -f $HOME/.zplug/init.zsh ]]; then source $HOME/.zplug/init.zsh zplug "greymd/tmux-xpanes" fi # kubernetes if whence -p kubectl 2>&1 > /dev/null; then source <(kubectl completion zsh) fi # rust if [[ -d $HOME/.cargo ]]; then path=($path $HOME/.cargo/bin) fi +# Settings for fzf +if whence -p fzf 2>&1 > /dev/null; then + path=($path $HOME/.fzf/bin) + if whence -p rg 2>&1 > /dev/null; then + export FZF_DEFAULT_COMMAND='rg --files --hidden --glob "!.git"' + fi + export FZF_DEFAULT_OPTS='--height 30% --border' + if [[ -f $HOME/.fzf.zsh ]]; then + source ~/.fzf.zsh + fi +fi + # vim: sw=2
clairvy/localenv
c13b14324f013096a4b2fcd60d344fa345298e9f
BREW Add ripgrep
diff --git a/Brewfile b/Brewfile index c37183c..24225a3 100644 --- a/Brewfile +++ b/Brewfile @@ -1,29 +1,30 @@ tap "greymd/tools" tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/core" brew "emacs", args: ["HEAD", "cocoa", "srgb", "use-git-head"] brew "fzf" brew "gist" brew "git" brew "go" brew "lv" brew "macvim" brew "mas" +brew "ripgrep" brew "rlwrap" brew "tig" brew "tmux" brew "zsh" brew "greymd/tools/tmux-xpanes" cask "alfred" cask "aquaskk" cask "bettertouchtool" cask "docker" cask "evernote" cask "iterm2" cask "karabiner-elements" cask "slack" cask "virtualbox" cask "yujitach-menumeters" mas "Memory Clean 2", id: 1114591412 mas "Xcode", id: 497799835
clairvy/localenv
f0e35493cca6f072a21476ad13425dfeabe2c931
BREW Update format for bundle dump
diff --git a/Brewfile b/Brewfile index d046d3c..c37183c 100644 --- a/Brewfile +++ b/Brewfile @@ -1,32 +1,29 @@ -update - -upgrade - -install zsh 2>&1 | egrep -v '^Warning: ' || true -install git 2>&1 | egrep -v '^Warning: ' || true -install lv 2>&1 | egrep -v '^Warning: ' || true -install rlwrap 2>&1 | egrep -v '^Warning: ' || true -install emacs --cocoa 2>&1 | egrep -v '^Warning: ' || true -linkapps emacs -install macvim -install tig - -#uninstall --force brew-cask -tap caskroom/cask -tap homebrew/versions - -# tmux-xpane -tap greymd/tools -install tmux-xpanes - -cask install alfred 2>&1 | egrep -v ' already installed.' || true -#cask install karabiner 2>&1 | egrep -v ' already installed.' || true -cask install karabiner-elements 2>&1 | egrep -v ' already installed.' || true -cask install iterm2 2>&1 | egrep -v ' already installed.' || true -cask install evernote 2>&1 | egrep -v ' already installed.' || true -cask install bettertouchtool 2>&1 | egrep -v ' already installed.' || true -cask install aquaskk 2>&1 | egrep -v ' already installed.' || true -cask install limechat 2>&1 | egrep -v ' already installed.' || true -cask install yujitach-menumeters 2>&1 | egrep -v ' already installed.' || true - -cleanup +tap "greymd/tools" +tap "homebrew/bundle" +tap "homebrew/cask" +tap "homebrew/core" +brew "emacs", args: ["HEAD", "cocoa", "srgb", "use-git-head"] +brew "fzf" +brew "gist" +brew "git" +brew "go" +brew "lv" +brew "macvim" +brew "mas" +brew "rlwrap" +brew "tig" +brew "tmux" +brew "zsh" +brew "greymd/tools/tmux-xpanes" +cask "alfred" +cask "aquaskk" +cask "bettertouchtool" +cask "docker" +cask "evernote" +cask "iterm2" +cask "karabiner-elements" +cask "slack" +cask "virtualbox" +cask "yujitach-menumeters" +mas "Memory Clean 2", id: 1114591412 +mas "Xcode", id: 497799835
clairvy/localenv
b2e769070118ddb5444c167a45e81b3aedbd68d2
Ignore history file.
diff --git a/.gitignore b/.gitignore index c38d3fa..a28371e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,9 @@ *~ .emacs.d/auto-save-list .emacs.d/js2-mode/build/ .emacs.d/url *.elc /.emacs.d/ac-comphist.dat /.emacs.d/anything-c-adaptive-history /.config/gcloud +/.vim/.netrwhist
clairvy/localenv
66ca37344bca09b6f35e7eb66dbe0b12fb3a72a8
BREW Add vim, tig
diff --git a/Brewfile b/Brewfile index be74256..d046d3c 100644 --- a/Brewfile +++ b/Brewfile @@ -1,32 +1,32 @@ update upgrade install zsh 2>&1 | egrep -v '^Warning: ' || true install git 2>&1 | egrep -v '^Warning: ' || true install lv 2>&1 | egrep -v '^Warning: ' || true install rlwrap 2>&1 | egrep -v '^Warning: ' || true install emacs --cocoa 2>&1 | egrep -v '^Warning: ' || true linkapps emacs +install macvim +install tig #uninstall --force brew-cask tap caskroom/cask tap homebrew/versions # tmux-xpane tap greymd/tools install tmux-xpanes cask install alfred 2>&1 | egrep -v ' already installed.' || true #cask install karabiner 2>&1 | egrep -v ' already installed.' || true cask install karabiner-elements 2>&1 | egrep -v ' already installed.' || true cask install iterm2 2>&1 | egrep -v ' already installed.' || true cask install evernote 2>&1 | egrep -v ' already installed.' || true cask install bettertouchtool 2>&1 | egrep -v ' already installed.' || true cask install aquaskk 2>&1 | egrep -v ' already installed.' || true cask install limechat 2>&1 | egrep -v ' already installed.' || true cask install yujitach-menumeters 2>&1 | egrep -v ' already installed.' || true -install homebrew/completions/tmuxinator-completion 2>&1 | egrep -v ' already installed' || true - cleanup
clairvy/localenv
388f35ec4c8973a0ead9d0cdc15e715c9238a925
TIG Add tig config
diff --git a/.tigrc b/.tigrc new file mode 100644 index 0000000..0ea54e9 --- /dev/null +++ b/.tigrc @@ -0,0 +1,33 @@ +#--------------------------------------------------------------# +## tig settings ## +#--------------------------------------------------------------# +set main-view = id:yes date:default,local=yes author commit-title:graph=yes,refs=yes,overflow=false +set blame-view = date:default id:yes,color line-number:yes,interval=1 text +set pager-view = text +set stage-view = text +set log-view = text +set blob-view = text +set diff-view = text:yes,commit-title-overflow=no +set tab-size = 2 +set ignore-case = true +set split-view-width = 80% +set split-view-height = 80% +set diff-options = -m --first-parent +set refresh-mode = auto + +#--------------------------------------------------------------# +## key bind ## +#--------------------------------------------------------------# +# Pで現在のブランチへpush +bind generic P ?@!git push origin %(repo:head) + +# Dでstatus viewのuntracked fileを削除できるようにする +# https://github.com/jonas/tig/issues/31 見るとおもしろい +# https://github.com/jonas/tig/issues/393 見るとおもしろい +bind status D ?@rm %(file) + +# そのほかのGitコマンド +bind generic F ?@!git fetch %(remote) +bind generic U ?@!git pull %(remote) + +color cursor black white bold
clairvy/localenv
641fdedea9a0833f0078c19dab2766d9edc990ed
VIM Add window shortcut
diff --git a/.vimrc b/.vimrc index d76b34f..da94713 100644 --- a/.vimrc +++ b/.vimrc @@ -1,255 +1,265 @@ filetype on "dein Scripts----------------------------- if &compatible set nocompatible " Be iMproved endif let s:dein_dir = $HOME . '/.cache/dein' let s:dein_repo_dir = s:dein_dir . '/repos/github.com/Shougo/dein.vim' let s:dein_toml_dir = $HOME . '/.vim/userautoload/dein' let s:dein_enabled = 0 " dein.vim ディレクトリがruntimepathに入っていない場合、追加 if match(&runtimepath, '/dein.vim') == -1 " dein_repo_dir で指定した場所に dein.vim が無い場合、git cloneしてくる if !isdirectory(s:dein_repo_dir) execute '!git clone https://github.com/Shougo/dein.vim' s:dein_repo_dir endif execute 'set runtimepath+=' . fnamemodify(s:dein_repo_dir, ':p') endif " Required: if dein#load_state(s:dein_dir) let s:dein_enabled = 1 call dein#begin(s:dein_dir) call dein#load_toml(s:dein_toml_dir . '/plugins.toml', {'lazy': 0}) call dein#load_toml(s:dein_toml_dir . '/lazy.toml', {'lazy': 1}) " Required: call dein#end() call dein#save_state() endif " Required: filetype plugin indent on syntax enable " If you want to install not installed plugins on startup. if dein#check_install() call dein#install() endif "End dein Scripts------------------------- " vundle を使う {{{1 set nocompatible filetype off set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() Plugin 'VundleVim/Vundle.vim' " Vundle Plugin 'elixir-lang/vim-elixir' Plugin 'rust-lang/rust.vim' Plugin 'fatih/vim-go' Plugin 'nsf/gocode', {'rtp': 'vim/'} call vundle#end() filetype plugin indent on "}}} " .vim/bundle を使う {{{1 call pathogen#runtime_append_all_bundles() call pathogen#infect() "}}} " Vim の流儀 より. {{{1 filetype plugin on filetype indent on syntax enable " VIMRC 編集/ロード設定 nnoremap <Space> :<C-u>edit $MYVIMRC<Enter> nnoremap <Space>s. :<C-u>source $MYVIMRC<Enter> " バックスペースが特殊な文字を削除できる set backspace=indent,eol,start " 検索に使う文字 set ignorecase set smartcase " 検索 set incsearch set hlsearch " ステータスライン "set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P "set statusline=%F%m%r%h%w\ [%{&fenc!=''?&fenc:&enc},%{&ff},%Y]\ [\%03.3b,0x\%2.2B]\ (%04l,%04v)[%LL/%p%%]\ %{strftime('%Y/%m/%d(%a)%H:%M')} "set laststatus=2 " コマンドの入力状況の表示 set showcmd " インデント関連 set tabstop=8 set softtabstop=4 set shiftwidth=4 set expandtab " }}} " leader {{{1 let mapleader = "," "set encoding=utf-8 "set fileencoding=utf-8 "set fileencodings=utf-8,utf-16,japan "set fileformats=unix,dos,mac "}}} " モードライン(ファイルのコメントからの読み込み) {{{1 set modeline set modelines=5 set backspace=2 set tabstop=4 set shiftwidth=4 set expandtab highlight tabs ctermbg=green guibg=green set list set listchars=tab:>- set number set ruler set smartindent "set laststatus=2 set wildmenu set wildmode=longest:full,full "}}} " 文字コードの自動認識 {{{1 set fileformats=unix,dos,mac set termencoding=utf-8 set encoding=utf-8 set fileencoding=utf-8 set fileencodings=utf-8 " 文字コードの自動認識 if &encoding !=# 'utf-8' set encoding=japan set fileencoding=japan endif if has('iconv') let s:enc_euc = 'euc-jp' let s:enc_jis = 'iso-2022-jp' " iconvがeucJP-msに対応しているかをチェック if iconv("\x87\x64\x87\x6a", 'cp932', 'eucjp-ms') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'eucjp-ms' let s:enc_jis = 'iso-2022-jp-3' " iconvがJISX0213に対応しているかをチェック elseif iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb" let s:enc_euc = 'euc-jisx0213' let s:enc_jis = 'iso-2022-jp-3' endif " fileencodingsを構築 if &encoding ==# 'utf-8' let s:fileencodings_default = &fileencodings let &fileencodings = s:enc_jis .','. s:enc_euc .',cp932' let &fileencodings = s:fileencodings_default . ',' . &fileencodings unlet s:fileencodings_default else let &fileencodings = &fileencodings .','. s:enc_jis set fileencodings+=utf-8,ucs-2le,ucs-2 if &encoding =~# '^\(euc-jp\|euc-jisx0213\|eucjp-ms\)$' set fileencodings+=cp932 set fileencodings-=euc-jp set fileencodings-=euc-jisx0213 set fileencodings-=eucjp-ms let &encoding = s:enc_euc let &fileencoding = s:enc_euc else let &fileencodings = &fileencodings .','. s:enc_euc endif endif " 定数を処分 unlet s:enc_euc unlet s:enc_jis endif " 日本語を含まない場合は fileencoding に encoding を使うようにする if has('autocmd') function! AU_ReCheck_FENC() if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0 let &fileencoding=&encoding endif endfunction autocmd BufReadPost * call AU_ReCheck_FENC() endif " 改行コードの自動認識 set fileformats=unix,dos,mac " □とか○の文字があってもカーソル位置がずれないようにする if exists('&ambiwidth') set ambiwidth=double endif " PHPManual {{{1 " PHP マニュアルを設置している場合 let g:ref_phpmanual_path = $HOME . '/local/share/phpman/php-chunked-xhtml/' let g:ref_phpmanual_cmd = 'w3m -dump %s' "let phpmanual_dir = $HOME . '/.vim/manual/php_manual_ja/' " マニュアルの拡張子 "let phpmanual_file_ext = 'html' " マニュアルのカラー表示 let phpmanual_color = 1 " iconv 変換をしない let phpmanual_convfilter = '' " w3m の表示形式を utf-8 にし、auto detect を on にする let phpmanual_htmlviewer = 'w3m -o display_charset=utf-8 -o auto_detect=2 -T text/html' " phpmanual.vim を置いているパスを指定 "source $HOME/.vim/ftplugin/phpmanual.vim "}}} " neocmplcache {{{1 imap <TAB> <Plug>(neocomplcache_snippets_expand) smap <TAB> <Plug>(neocomplcache_snippets_expand) "imap <expr><TAB> neocomplcache#sources#snippets_complete#expandable() ? "\<Plug>(neocomplcache_snippets_expand)" : pumvisible() ? "\<C-n>" : "\<TAB>" inoremap <expr><C-g> neocomplcache#undo_completion() inoremap <expr><C-l> neocomplcache#complete_common_string() "}}} " eskk {{{1 if has('vim_starting') if has('mac') let g:eskk#large_dictionary = "~/Library/Application\ Support/AquaSKK/SKK-JISYO.L" endif endif let g:eskk_debug = 0 "}}} " カーソル行をハイライト {{{1 set cursorline augroup cch autocmd! cch autocmd WinLeave * setlocal nocursorline autocmd WinEnter,BufRead * setlocal cursorline augroup END "}}} " symofny {{{1 nnoremap <silent> <Leader>v :<C-u>STview<CR> nnoremap <silent> <Leader>m :<C-u>STmodel<CR> nnoremap <silent> <Leader>a :<C-u>STaction<CR> nnoremap <silent> <Leader>p :<C-u>STpartial<CR> nnoremap <Leader>V :<C-u>STview nnoremap <Leader>M :<C-u>STmodel nnoremap <Leader>A :<C-u>STaction nnoremap <Leader>P :<C-u>STpartial "}}} " git. {{{1 nnoremap <Leader>gg :<C-u>GitGrep +"}}} " vim: foldmethod=marker + +" window {{{1 +nnoremap sj <C-w>j +nnoremap sk <C-w>k +nnoremap sl <C-w>l +nnoremap sh <C-w>h +nnoremap ss :<C-u>sp<CR><C-w>j +nnoremap sv :<C-u>vs<CR><C-w>l +"}}}
clairvy/localenv
4d025b0807fccdcf41e3061593a430687956f135
VIM Add plugin for window resize.
diff --git a/.vim/userautoload/dein/plugins.toml b/.vim/userautoload/dein/plugins.toml index 95605bb..dfb3d86 100644 --- a/.vim/userautoload/dein/plugins.toml +++ b/.vim/userautoload/dein/plugins.toml @@ -1,116 +1,119 @@ [[plugins]] repo = 'Shougo/dein.vim' [[plugins]] repo = 'Shougo/neosnippet.vim' [[plugins]] repo = 'Shougo/neosnippet-snippets' [[plugins]] repo = 'dense-analysis/ale' hook_add = ''' let g:ale_linters = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } let g:ale_fixers = { \ 'ruby': ['rubocop'], \ 'typescript': ['eslint'], \ } "let g:ale_sign_column_always = 1 "let g:ale_open_list = 1 "let g:ale_keep_list_window_open = 1 " Set this. Airline will handle the rest. let g:airline#extensions#ale#enabled = 1 ''' [[plugins]] repo = 'vim-airline/vim-airline' [[plugins]] repo = 'vim-airline/vim-airline-themes' depends = 'vim-airline' hook_add = ''' let g:airline_theme = 'onedark' " タブバーをかっこよく let g:airline#extensions#tabline#enabled = 1 " Lintツールによるエラー、警告を表示(ALEの拡張) let g:airline#extensions#ale#enabled = 1 let g:airline#extensions#ale#error_symbol = 'E:' let g:airline#extensions#ale#warning_symbol = 'W:' " , キーで次タブのバッファを表示 nnoremap <silent> < :bprev<CR> " . キーで前タブのバッファを表示 nnoremap <silent> > :bnext<CR> ''' [[plugins]] repo='prabirshrestha/async.vim' [[plugins]] repo='prabirshrestha/vim-lsp' [[plugins]] repo='prabirshrestha/asyncomplete.vim' [[plugins]] repo='prabirshrestha/asyncomplete-lsp.vim' #[[plugins]] #repo='prabirshrestha/asyncomplete-neosnippet.vim' #hook_add=''' #call asyncomplete#register_source(asyncomplete#sources#neosnippet#get_source_options({ # \ 'name': 'neosnippet', # \ 'whitelist': ['*'], # \ 'completor': function('asyncomplete#sources#neosnippet#completor'), # \ })) #imap <C-k> <Plug>(neosnippet_expand_or_jump) #smap <C-k> <Plug>(neosnippet_expand_or_jump) #xmap <C-k> <Plug>(neosnippet_expand_target) #''' [[plugins]] repo = 'leafgarland/typescript-vim' [[plugins]] repo = 'tmux-plugins/vim-tmux' [[plugins]] repo = 'scrooloose/nerdtree' hook_add = ''' let NERDTreeShowHidden=1 nnoremap <silent><C-a> :NERDTreeFind<CR>:vertical res 30<CR> ''' [[plugins]] repo = 'nathanaelkane/vim-indent-guides' hook_add = ''' let g:indent_guides_enable_on_vim_startup = 1 let g:indent_guides_exclude_filetypes = ['help', 'nerdtree'] let g:indent_guides_auto_colors = 0 autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd ctermbg=237 autocmd VimEnter,Colorscheme * :hi IndentGuidesEven ctermbg=240 ''' [[plugins]] repo = 'airblade/vim-gitgutter' hook_add = ''' set signcolumn=yes let g:gitgutter_async = 1 let g:gitgutter_sign_modified = 'rw' highlight GitGutterAdd ctermfg=green highlight GitGutterChange ctermfg=yellow highlight GitGutterDelete ctermfg=red highlight GitGutterChangeDelete ctermfg=yellow ''' [[plugins]] repo = 'luochen1990/rainbow' hook_add = ''' let g:rainbow_active = 1 ''' + +[[plugins]] +repo = 'simeji/winresizer'
clairvy/localenv
a0c3dbce4fbfa13898398705b3ed55a56b179975
Ignore gcloud files.
diff --git a/.gitignore b/.gitignore index eba2dd0..c38d3fa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ *~ .emacs.d/auto-save-list .emacs.d/js2-mode/build/ .emacs.d/url *.elc /.emacs.d/ac-comphist.dat /.emacs.d/anything-c-adaptive-history +/.config/gcloud
clairvy/localenv
e24cfa1660c562b72ce2f4d29d7a6897b1f4a08f
VIM Add some plugins
diff --git a/.vim/userautoload/dein/plugins.toml b/.vim/userautoload/dein/plugins.toml index dd9587e..95605bb 100644 --- a/.vim/userautoload/dein/plugins.toml +++ b/.vim/userautoload/dein/plugins.toml @@ -1,81 +1,116 @@ [[plugins]] repo = 'Shougo/dein.vim' [[plugins]] repo = 'Shougo/neosnippet.vim' [[plugins]] repo = 'Shougo/neosnippet-snippets' [[plugins]] repo = 'dense-analysis/ale' hook_add = ''' let g:ale_linters = { - \ 'ruby': ['rubocop'], - \ 'typescript': ['eslint'], - \ } + \ 'ruby': ['rubocop'], + \ 'typescript': ['eslint'], + \ } let g:ale_fixers = { - \ 'ruby': ['rubocop'], - \ 'typescript': ['eslint'], - \ } + \ 'ruby': ['rubocop'], + \ 'typescript': ['eslint'], + \ } "let g:ale_sign_column_always = 1 "let g:ale_open_list = 1 "let g:ale_keep_list_window_open = 1 " Set this. Airline will handle the rest. let g:airline#extensions#ale#enabled = 1 ''' [[plugins]] repo = 'vim-airline/vim-airline' -depends = ['vim-airline-themes'] [[plugins]] repo = 'vim-airline/vim-airline-themes' +depends = 'vim-airline' hook_add = ''' + let g:airline_theme = 'onedark' " タブバーをかっこよく let g:airline#extensions#tabline#enabled = 1 " Lintツールによるエラー、警告を表示(ALEの拡張) let g:airline#extensions#ale#enabled = 1 let g:airline#extensions#ale#error_symbol = 'E:' let g:airline#extensions#ale#warning_symbol = 'W:' + + " , キーで次タブのバッファを表示 + nnoremap <silent> < :bprev<CR> + " . キーで前タブのバッファを表示 + nnoremap <silent> > :bnext<CR> ''' [[plugins]] repo='prabirshrestha/async.vim' [[plugins]] repo='prabirshrestha/vim-lsp' [[plugins]] repo='prabirshrestha/asyncomplete.vim' [[plugins]] repo='prabirshrestha/asyncomplete-lsp.vim' #[[plugins]] #repo='prabirshrestha/asyncomplete-neosnippet.vim' #hook_add=''' #call asyncomplete#register_source(asyncomplete#sources#neosnippet#get_source_options({ # \ 'name': 'neosnippet', # \ 'whitelist': ['*'], # \ 'completor': function('asyncomplete#sources#neosnippet#completor'), # \ })) #imap <C-k> <Plug>(neosnippet_expand_or_jump) #smap <C-k> <Plug>(neosnippet_expand_or_jump) #xmap <C-k> <Plug>(neosnippet_expand_target) #''' [[plugins]] repo = 'leafgarland/typescript-vim' [[plugins]] repo = 'tmux-plugins/vim-tmux' [[plugins]] repo = 'scrooloose/nerdtree' hook_add = ''' let NERDTreeShowHidden=1 - nnoremap <silent><C-a> :NERDTreeFind<CR>:vertical res 30<CR> + nnoremap <silent><C-a> :NERDTreeFind<CR>:vertical res 30<CR> +''' + +[[plugins]] +repo = 'nathanaelkane/vim-indent-guides' +hook_add = ''' + let g:indent_guides_enable_on_vim_startup = 1 + let g:indent_guides_exclude_filetypes = ['help', 'nerdtree'] + let g:indent_guides_auto_colors = 0 + autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd ctermbg=237 + autocmd VimEnter,Colorscheme * :hi IndentGuidesEven ctermbg=240 +''' + + +[[plugins]] +repo = 'airblade/vim-gitgutter' +hook_add = ''' + set signcolumn=yes + let g:gitgutter_async = 1 + let g:gitgutter_sign_modified = 'rw' + highlight GitGutterAdd ctermfg=green + highlight GitGutterChange ctermfg=yellow + highlight GitGutterDelete ctermfg=red + highlight GitGutterChangeDelete ctermfg=yellow +''' + +[[plugins]] +repo = 'luochen1990/rainbow' +hook_add = ''' + let g:rainbow_active = 1 '''