dialogs.py 300 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454
  1. """!
  2. @package psmap.dialogs
  3. @brief Map feature objects and dialogs for wxPsMap
  4. Classes:
  5. - dialogs::UnitConversion
  6. - dialogs::TCValidator
  7. - dialogs::PenStyleComboBox
  8. - dialogs::CheckListCtrl
  9. - dialogs::Instruction
  10. - dialogs::InstructionObject
  11. - dialogs::InitMap
  12. - dialogs::MapFrame
  13. - dialogs::PageSetup
  14. - dialogs::Mapinfo
  15. - dialogs::Text
  16. - dialogs::Image
  17. - dialogs::NorthArrow
  18. - dialogs::Scalebar
  19. - dialogs::RasterLegend
  20. - dialogs::VectorLegend
  21. - dialogs::Raster
  22. - dialogs::Vector
  23. - dialogs::VProperties
  24. - dialogs::PsmapDialog
  25. - dialogs::PageSetupDialog
  26. - dialogs::MapDialog
  27. - dialogs::MapFramePanel
  28. - dialogs::RasterPanel
  29. - dialogs::VectorPanel
  30. - dialogs::RasterDialog
  31. - dialogs::MainVectorDialog
  32. - dialogs::VPropertiesDialog
  33. - dialogs::LegendDialog
  34. - dialogs::MapinfoDialog
  35. - dialogs::ScalebarDialog
  36. - dialogs::TextDialog
  37. - dialogs::ImageDialog
  38. - dialogs::NorthArrowDialog
  39. (C) 2011 by Anna Kratochvilova, and the GRASS Development Team
  40. This program is free software under the GNU General Public License
  41. (>=v2). Read the file COPYING that comes with GRASS for details.
  42. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project)
  43. @author Martin Landa <landa.martin gmail.com> (mentor)
  44. """
  45. import os
  46. import sys
  47. import string
  48. from math import ceil, floor, sin, cos, pi
  49. from copy import deepcopy
  50. from time import strftime, localtime
  51. try:
  52. import Image as PILImage
  53. havePILImage = True
  54. except ImportError:
  55. havePILImage = False
  56. import wx
  57. import wx.lib.scrolledpanel as scrolled
  58. import wx.lib.filebrowsebutton as filebrowse
  59. from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
  60. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  61. try:
  62. import wx.lib.agw.floatspin as fs
  63. except ImportError:
  64. fs = None
  65. import grass.script as grass
  66. from core import globalvar
  67. from dbmgr.vinfo import VectorDBInfo
  68. from core.utils import CmdToTuple, GetCmdString
  69. from gui_core.gselect import Select
  70. from core.gcmd import RunCommand, GError, GMessage, GWarning
  71. from gui_core.dialogs import SymbolDialog
  72. # grass.set_raise_on_error(True)
  73. PSMAP_COLORS = ['aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'grey', 'green', 'indigo',
  74. 'magenta','orange', 'purple', 'red', 'violet', 'white', 'yellow']
  75. class UnitConversion:
  76. """! Class for converting units"""
  77. def __init__(self, parent = None):
  78. self.parent = parent
  79. if self.parent:
  80. ppi = wx.ClientDC(self.parent).GetPPI()
  81. else:
  82. ppi = (72, 72)
  83. self._unitsPage = { 'inch' : {'val': 1.0, 'tr' : _("inch")},
  84. 'point' : {'val': 72.0, 'tr' : _("point")},
  85. 'centimeter' : {'val': 2.54, 'tr' : _("centimeter")},
  86. 'millimeter' : {'val': 25.4, 'tr' : _("millimeter")}}
  87. self._unitsMap = { 'meters' : {'val': 0.0254, 'tr' : _("meters")},
  88. 'kilometers' : {'val': 2.54e-5, 'tr' : _("kilometers")},
  89. 'feet' : {'val': 1./12, 'tr' : _("feet")},
  90. 'miles' : {'val': 1./63360, 'tr' : _("miles")},
  91. 'nautical miles': {'val': 1/72913.386, 'tr' : _("nautical miles")}}
  92. self._units = { 'pixel' : {'val': ppi[0], 'tr' : _("pixel")},
  93. 'meter' : {'val': 0.0254, 'tr' : _("meter")},
  94. 'nautmiles' : {'val': 1/72913.386, 'tr' :_("nautical miles")},
  95. 'degrees' : {'val': 0.0254 , 'tr' : _("degree")} #like 1 meter, incorrect
  96. }
  97. self._units.update(self._unitsPage)
  98. self._units.update(self._unitsMap)
  99. def getPageUnitsNames(self):
  100. return sorted(self._unitsPage[unit]['tr'] for unit in self._unitsPage.keys())
  101. def getMapUnitsNames(self):
  102. return sorted(self._unitsMap[unit]['tr'] for unit in self._unitsMap.keys())
  103. def getAllUnits(self):
  104. return sorted(self._units.keys())
  105. def findUnit(self, name):
  106. """!Returns unit by its tr. string"""
  107. for unit in self._units.keys():
  108. if self._units[unit]['tr'] == name:
  109. return unit
  110. return None
  111. def findName(self, unit):
  112. """!Returns tr. string of a unit"""
  113. try:
  114. return self._units[unit]['tr']
  115. except KeyError:
  116. return None
  117. def convert(self, value, fromUnit = None, toUnit = None):
  118. return float(value)/self._units[fromUnit]['val']*self._units[toUnit]['val']
  119. class TCValidator(wx.PyValidator):
  120. """!validates input in textctrls, combobox, taken from wxpython demo"""
  121. def __init__(self, flag = None):
  122. wx.PyValidator.__init__(self)
  123. self.flag = flag
  124. self.Bind(wx.EVT_CHAR, self.OnChar)
  125. def Clone(self):
  126. return TCValidator(self.flag)
  127. def Validate(self, win):
  128. tc = self.GetWindow()
  129. val = tc.GetValue()
  130. if self.flag == 'DIGIT_ONLY':
  131. for x in val:
  132. if x not in string.digits:
  133. return False
  134. return True
  135. def OnChar(self, event):
  136. key = event.GetKeyCode()
  137. if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
  138. event.Skip()
  139. return
  140. if self.flag == 'DIGIT_ONLY' and chr(key) in string.digits + '.':
  141. event.Skip()
  142. return
  143. ## if self.flag == 'SCALE' and chr(key) in string.digits + ':':
  144. ## event.Skip()
  145. ## return
  146. if self.flag == 'ZERO_AND_ONE_ONLY' and chr(key) in '01':
  147. event.Skip()
  148. return
  149. if not wx.Validator_IsSilent():
  150. wx.Bell()
  151. # Returning without calling even.Skip eats the event before it
  152. # gets to the text control
  153. return
  154. class PenStyleComboBox(wx.combo.OwnerDrawnComboBox):
  155. """!Combo for selecting line style, taken from wxpython demo"""
  156. # Overridden from OwnerDrawnComboBox, called to draw each
  157. # item in the list
  158. def OnDrawItem(self, dc, rect, item, flags):
  159. if item == wx.NOT_FOUND:
  160. # painting the control, but there is no valid item selected yet
  161. return
  162. r = wx.Rect(*rect) # make a copy
  163. r.Deflate(3, 5)
  164. penStyle = wx.SOLID
  165. if item == 1:
  166. penStyle = wx.LONG_DASH
  167. elif item == 2:
  168. penStyle = wx.DOT
  169. elif item == 3:
  170. penStyle = wx.DOT_DASH
  171. pen = wx.Pen(dc.GetTextForeground(), 3, penStyle)
  172. dc.SetPen(pen)
  173. # for painting the items in the popup
  174. dc.DrawText(self.GetString(item ),
  175. r.x + 3,
  176. (r.y + 0) + ((r.height/2) - dc.GetCharHeight() )/2
  177. )
  178. dc.DrawLine(r.x+5, r.y+((r.height/4)*3)+1, r.x+r.width - 5, r.y+((r.height/4)*3)+1 )
  179. def OnDrawBackground(self, dc, rect, item, flags):
  180. """!Overridden from OwnerDrawnComboBox, called for drawing the
  181. background area of each item."""
  182. # If the item is selected, or its item # iseven, or we are painting the
  183. # combo control itself, then use the default rendering.
  184. if (item & 1 == 0 or flags & (wx.combo.ODCB_PAINTING_CONTROL |
  185. wx.combo.ODCB_PAINTING_SELECTED)):
  186. wx.combo.OwnerDrawnComboBox.OnDrawBackground(self, dc, rect, item, flags)
  187. return
  188. # Otherwise, draw every other background with different colour.
  189. bgCol = wx.Colour(240,240,250)
  190. dc.SetBrush(wx.Brush(bgCol))
  191. dc.SetPen(wx.Pen(bgCol))
  192. dc.DrawRectangleRect(rect);
  193. def OnMeasureItem(self, item):
  194. """!Overridden from OwnerDrawnComboBox, should return the height
  195. needed to display an item in the popup, or -1 for default"""
  196. return 30
  197. def OnMeasureItemWidth(self, item):
  198. """!Overridden from OwnerDrawnComboBox. Callback for item width, or
  199. -1 for default/undetermined"""
  200. return -1; # default - will be measured from text width
  201. class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin):
  202. """!List control for managing order and labels of vector maps in legend"""
  203. def __init__(self, parent):
  204. wx.ListCtrl.__init__(self, parent, id = wx.ID_ANY,
  205. style = wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.BORDER_SUNKEN|wx.LC_VRULES|wx.LC_HRULES)
  206. CheckListCtrlMixin.__init__(self)
  207. ListCtrlAutoWidthMixin.__init__(self)
  208. class Instruction:
  209. """!Class which represents instruction file"""
  210. def __init__(self, parent, objectsToDraw):
  211. self.parent = parent
  212. self.objectsToDraw = objectsToDraw
  213. #here are kept objects like mapinfo, rasterlegend, etc.
  214. self.instruction = list()
  215. def __str__(self):
  216. """!Returns text for instruction file"""
  217. comment = "# timestamp: " + strftime("%Y-%m-%d %H:%M", localtime()) + '\n'
  218. env = grass.gisenv()
  219. comment += "# location: %s\n" % env['LOCATION_NAME']
  220. comment += "# mapset: %s\n" % env['MAPSET']
  221. comment += "# page orientation: %s\n" % self.FindInstructionByType('page')['Orientation']
  222. border = ''
  223. if not self.FindInstructionByType('map'):
  224. border = 'border n\n'
  225. text = [str(each) for each in self.instruction]
  226. return comment + border + '\n'.join(text) + '\nend'
  227. def __getitem__(self, id):
  228. for each in self.instruction:
  229. if each.id == id:
  230. return each
  231. return None
  232. def __contains__(self, id):
  233. """!Test if instruction is included"""
  234. for each in self.instruction:
  235. if each.id == id:
  236. return True
  237. return False
  238. def __delitem__(self, id):
  239. """!Delete instruction"""
  240. for each in self.instruction:
  241. if each.id == id:
  242. if each.type == 'map':
  243. #must remove raster, vector layers too
  244. vektor = self.FindInstructionByType('vector', list = True)
  245. vProperties = self.FindInstructionByType('vProperties', list = True)
  246. raster = self.FindInstructionByType('raster', list = True)
  247. for item in vektor + vProperties + raster:
  248. if item in self.instruction:
  249. self.instruction.remove(item)
  250. self.instruction.remove(each)
  251. if id in self.objectsToDraw:
  252. self.objectsToDraw.remove(id)
  253. return
  254. def AddInstruction(self, instruction):
  255. """!Add instruction"""
  256. # add to instructions
  257. if instruction.type == 'map':
  258. self.instruction.insert(0, instruction)
  259. else:
  260. self.instruction.append(instruction)
  261. # add to drawable objects
  262. if instruction.type not in ('page', 'raster', 'vector', 'vProperties', 'initMap'):
  263. if instruction.type == 'map':
  264. self.objectsToDraw.insert(0, instruction.id)
  265. else:
  266. self.objectsToDraw.append(instruction.id)
  267. def FindInstructionByType(self, type, list = False):
  268. """!Find instruction(s) with the given type"""
  269. inst = []
  270. for each in self.instruction:
  271. if each.type == type:
  272. inst.append(each)
  273. if len(inst) == 1 and not list:
  274. return inst[0]
  275. return inst
  276. def Read(self, filename):
  277. """!Reads instruction file and creates instruction objects"""
  278. self.filename = filename
  279. # open file
  280. try:
  281. file = open(filename, 'r')
  282. except IOError:
  283. GError(message = _("Unable to open file\n%s") % filename)
  284. return
  285. # first read file to get information about region and scaletype
  286. isRegionComment = False
  287. orientation = 'Portrait'
  288. for line in file:
  289. if '# g.region' in line:
  290. self.SetRegion(regionInstruction = line)
  291. isRegionComment = True
  292. break
  293. if '# page orientation' in line:
  294. orientation = line.split(':')[-1].strip()
  295. if not isRegionComment:
  296. self.SetRegion(regionInstruction = None)
  297. # then run ps.map -b to get information for maploc
  298. # compute scale and center
  299. map = self.FindInstructionByType('map')
  300. region = grass.region()
  301. map['center'] = (region['n'] + region['s']) / 2, (region['w'] + region['e']) / 2
  302. mapRect = GetMapBounds(self.filename, portrait = (orientation == 'Portrait'))
  303. map['rect'] = mapRect
  304. proj = projInfo()
  305. toM = 1.0
  306. if proj['units']:
  307. toM = float(proj['meters'])
  308. units = UnitConversion(self.parent)
  309. w = units.convert(value = mapRect.Get()[2], fromUnit = 'inch', toUnit = 'meter') / toM
  310. map['scale'] = w / abs((region['w'] - region['e']))
  311. SetResolution(dpi = 300, width = map['rect'].width, height = map['rect'].height)
  312. # read file again, now with information about map bounds
  313. isBuffer = False
  314. buffer = []
  315. instruction = None
  316. vectorMapNumber = 1
  317. file.seek(0)
  318. for line in file:
  319. if not line.strip():
  320. continue
  321. line = line.strip()
  322. if isBuffer:
  323. buffer.append(line)
  324. if 'end' in line:
  325. isBuffer = False
  326. kwargs = {}
  327. if instruction == 'scalebar':
  328. kwargs['scale'] = map['scale']
  329. elif instruction in ('text', 'eps'):
  330. kwargs['mapInstruction'] = map
  331. elif instruction in ('vpoints', 'vlines', 'vareas'):
  332. kwargs['id'] = wx.NewId()
  333. kwargs['vectorMapNumber'] = vectorMapNumber
  334. vectorMapNumber += 1
  335. elif instruction == 'paper':
  336. kwargs['Orientation'] = orientation
  337. ok = self.SendToRead(instruction, buffer, **kwargs)
  338. if not ok: return False
  339. buffer = []
  340. continue
  341. elif line.startswith('paper'):
  342. instruction = 'paper'
  343. isBuffer = True
  344. buffer.append(line)
  345. elif line.startswith('border'):
  346. if line.split()[1].lower() in ('n', 'no', 'none'):
  347. ok = self.SendToRead('border', [line])
  348. if not ok: return False
  349. elif line.split()[1].lower() in ('y', 'yes'):
  350. instruction = 'border'
  351. isBuffer = True
  352. buffer.append(line)
  353. elif line.startswith('scale '):
  354. if isBuffer:
  355. continue
  356. ok = self.SendToRead('scale', line, isRegionComment = isRegionComment)
  357. if not ok: return False
  358. elif line.startswith('maploc'):
  359. ok = self.SendToRead(instruction = 'maploc', text = line)
  360. if not ok: return False
  361. elif line.startswith('raster'):
  362. ok = self.SendToRead(instruction = 'raster', text = line)
  363. if not ok: return False
  364. elif line.startswith('mapinfo'):
  365. instruction = 'mapinfo'
  366. isBuffer = True
  367. buffer.append(line)
  368. elif line.startswith('scalebar'):
  369. instruction = 'scalebar'
  370. isBuffer = True
  371. buffer.append(line)
  372. elif line.startswith('text'):
  373. instruction = 'text'
  374. isBuffer = True
  375. buffer.append(line)
  376. elif line.startswith('eps'):
  377. instruction = 'eps'
  378. isBuffer = True
  379. buffer.append(line)
  380. elif line.startswith('colortable'):
  381. if len(line.split()) == 2 and line.split()[1].lower() in ('n', 'no', 'none'):
  382. break
  383. instruction = 'colortable'
  384. isBuffer = True
  385. buffer.append(line)
  386. elif line.startswith('vlegend'):
  387. instruction = 'vlegend'
  388. isBuffer = True
  389. buffer.append(line)
  390. elif line.startswith('vpoints'):
  391. instruction = 'vpoints'
  392. isBuffer = True
  393. buffer.append(line)
  394. elif line.startswith('vlines'):
  395. instruction = 'vlines'
  396. isBuffer = True
  397. buffer.append(line)
  398. elif line.startswith('vareas'):
  399. instruction = 'vareas'
  400. isBuffer = True
  401. buffer.append(line)
  402. rasterLegend = self.FindInstructionByType('rasterLegend')
  403. raster = self.FindInstructionByType('raster')
  404. page = self.FindInstructionByType('page')
  405. vector = self.FindInstructionByType('vector')
  406. vectorLegend = self.FindInstructionByType('vectorLegend')
  407. vectorMaps = self.FindInstructionByType('vProperties', list = True)
  408. # check (in case of scaletype 0) if map is drawn also
  409. map['drawMap'] = False
  410. if map['scaleType'] == 0:
  411. mapForRegion = map['map']
  412. if map['mapType'] == 'raster' and raster:
  413. if mapForRegion == raster['raster']:
  414. map['drawMap'] = True
  415. elif map['mapType'] == 'vector' and vector:
  416. for vmap in vector['list']:
  417. if mapForRegion == vmap[0]:
  418. map['drawMap'] = True
  419. # rasterLegend
  420. if rasterLegend:
  421. if rasterLegend['rasterDefault'] and raster:
  422. rasterLegend['raster'] = raster['raster']
  423. if not rasterLegend['discrete']:
  424. rasterType = getRasterType(map = rasterLegend['raster'])
  425. if rasterType == 'CELL':
  426. rasterLegend['discrete'] = 'y'
  427. else:
  428. rasterLegend['discrete'] = 'n'
  429. #estimate size
  430. height = rasterLegend.EstimateHeight(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'],
  431. fontsize = rasterLegend['fontsize'],
  432. cols = rasterLegend['cols'],
  433. height = rasterLegend['height'])
  434. width = rasterLegend.EstimateWidth(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'],
  435. fontsize = rasterLegend['fontsize'],
  436. cols = rasterLegend['cols'] ,
  437. width = rasterLegend['width'],
  438. paperInstr = page)
  439. rasterLegend['rect'] = wx.Rect2D(x = float(rasterLegend['where'][0]), y = float(rasterLegend['where'][1]),
  440. w = width, h = height)
  441. # vectors, vlegend
  442. if vector:
  443. for vmap in vectorMaps:
  444. for i, each in enumerate(vector['list']):
  445. if each[2] == vmap.id:
  446. vector['list'][i][4] = vmap['label']
  447. vector['list'][i][3] = vmap['lpos']
  448. if vectorLegend:
  449. size = vectorLegend.EstimateSize(vectorInstr = vector, fontsize = vectorLegend['fontsize'],
  450. width = vectorLegend['width'], cols = vectorLegend['cols'])
  451. vectorLegend['rect'] = wx.Rect2D(x = float(vectorLegend['where'][0]), y = float(vectorLegend['where'][1]),
  452. w = size[0], h = size[1])
  453. page = self.FindInstructionByType('page')
  454. if not page:
  455. page = PageSetup(wx.NewId())
  456. self.AddInstruction(page)
  457. else:
  458. page['Orientation'] = orientation
  459. #
  460. return True
  461. def SendToRead(self, instruction, text, **kwargs):
  462. psmapInstrDict = dict(paper = ['page'],
  463. maploc = ['map'],
  464. scale = ['map'],
  465. border = ['map'],
  466. raster = ['raster'],
  467. mapinfo = ['mapinfo'],
  468. scalebar = ['scalebar'],
  469. text = ['text'],
  470. eps = ['image', 'northArrow'],
  471. vpoints = ['vector', 'vProperties'],
  472. vlines = ['vector', 'vProperties'],
  473. vareas = ['vector', 'vProperties'],
  474. colortable = ['rasterLegend'],
  475. vlegend = ['vectorLegend']
  476. )
  477. myInstrDict = dict(page = PageSetup,
  478. map = MapFrame,
  479. raster = Raster,
  480. mapinfo = Mapinfo,
  481. scalebar = Scalebar,
  482. text = Text,
  483. image = Image,
  484. northArrow = NorthArrow,
  485. rasterLegend = RasterLegend,
  486. vectorLegend = VectorLegend,
  487. vector = Vector,
  488. vProperties = VProperties
  489. )
  490. myInstruction = psmapInstrDict[instruction]
  491. for i in myInstruction:
  492. instr = self.FindInstructionByType(i)
  493. if i in ('text', 'vProperties', 'image', 'northArrow') or not instr:
  494. id = wx.NewId() #!vProperties expect subtype
  495. if i == 'vProperties':
  496. id = kwargs['id']
  497. newInstr = myInstrDict[i](id, subType = instruction[1:])
  498. elif i in ('image', 'northArrow'):
  499. commentFound = False
  500. for line in text:
  501. if line.find("# north arrow") >= 0:
  502. commentFound = True
  503. if i == 'image' and commentFound or \
  504. i == 'northArrow' and not commentFound:
  505. continue
  506. newInstr = myInstrDict[i](id, settings = self)
  507. else:
  508. newInstr = myInstrDict[i](id)
  509. ok = newInstr.Read(instruction, text, **kwargs)
  510. if ok:
  511. self.AddInstruction(newInstr)
  512. else:
  513. return False
  514. else:
  515. ok = instr.Read(instruction, text, **kwargs)
  516. if not ok:
  517. return False
  518. return True
  519. def SetRegion(self, regionInstruction):
  520. """!Sets region from file comment or sets current region in case of no comment"""
  521. map = MapFrame(wx.NewId())
  522. self.AddInstruction(map)
  523. if regionInstruction:
  524. cmd = CmdToTuple(regionInstruction.strip('# ').split())
  525. # define scaleType
  526. if len(cmd[1]) <= 3:
  527. if 'rast' in cmd[1]:
  528. map['scaleType'] = 0
  529. map['mapType'] = 'raster'
  530. map['map'] = cmd[1]['rast']
  531. elif 'vect' in cmd[1]:
  532. map['scaleType'] = 0
  533. map['mapType'] = 'vector'
  534. map['map'] = cmd[1]['vect']
  535. elif 'region' in cmd[1]:
  536. map['scaleType'] = 1
  537. map['region'] = cmd[1]['region']
  538. else:
  539. map['scaleType'] = 2
  540. else:
  541. map['scaleType'] = 2
  542. grass.del_temp_region()
  543. region = grass.region()
  544. grass.use_temp_region()
  545. cmd = ['g.region', region]
  546. cmdString = GetCmdString(cmd).replace('g.region', '')
  547. GMessage(_("Instruction file will be loaded with following region: %s\n") % cmdString)
  548. try:
  549. RunCommand(cmd[0], **cmd[1])
  550. except grass.ScriptError, e:
  551. GError(_("Region cannot be set\n%s") % e)
  552. return False
  553. class InstructionObject:
  554. """!Abtract class representing single instruction"""
  555. def __init__(self, id):
  556. self.id = id
  557. # default values
  558. self.defaultInstruction = dict()
  559. # current values
  560. self.instruction = self.defaultInstruction
  561. # converting units
  562. self.unitConv = UnitConversion()
  563. def __str__(self):
  564. """!Returns particular part of text instruction"""
  565. return ''
  566. def __getitem__(self, key):
  567. for each in self.instruction.keys():
  568. if each == key:
  569. return self.instruction[key]
  570. return None
  571. def __setitem__(self, key, value):
  572. self.instruction[key] = value
  573. def GetInstruction(self):
  574. """!Get current values"""
  575. return self.instruction
  576. def SetInstruction(self, instruction):
  577. """!Set default values"""
  578. self.instruction = instruction
  579. def Read(self, instruction, text, **kwargs):
  580. """!Read instruction and save them"""
  581. pass
  582. class InitMap(InstructionObject):
  583. """!Class representing virtual map"""
  584. def __init__(self, id):
  585. InstructionObject.__init__(self, id = id)
  586. self.type = 'initMap'
  587. # default values
  588. self.defaultInstruction = dict(rect = None, scale = None)
  589. # current values
  590. self.instruction = dict(self.defaultInstruction)
  591. class MapFrame(InstructionObject):
  592. """!Class representing map (instructions maploc, scale, border)"""
  593. def __init__(self, id):
  594. InstructionObject.__init__(self, id = id)
  595. self.type = 'map'
  596. # default values
  597. self.defaultInstruction = dict(map = None, mapType = None, drawMap = True, region = None,
  598. rect = wx.Rect2D(), scaleType = 0, scale = None, center = None,
  599. resolution = 300, border = 'y', width = 1, color = '0:0:0')
  600. # current values
  601. self.instruction = dict(self.defaultInstruction)
  602. def __str__(self):
  603. instr = ''
  604. comment = ''
  605. #region settings
  606. region = grass.region()
  607. if self.instruction['scaleType'] == 0: #match map
  608. map = self.instruction['map']
  609. if self.instruction['mapType'] == 'raster':
  610. comment = "# g.region rast=%s nsres=%s ewres=%s\n" % (map, region['nsres'], region['ewres'])
  611. else:
  612. comment = "# g.region vect=%s\n" % (map)
  613. elif self.instruction['scaleType'] == 1:# saved region
  614. region = self.instruction['region']
  615. comment = "# g.region region=%s\n" % region
  616. elif self.instruction['scaleType'] in (2, 3): #current region, fixed scale
  617. comment = string.Template("# g.region n=$n s=$s e=$e w=$w rows=$rows cols=$cols \n").substitute(**region)
  618. instr += comment
  619. instr += '\n'
  620. # maploc
  621. maplocInstruction = "maploc %.3f %.3f" % (self.instruction['rect'].x, self.instruction['rect'].y)
  622. if self.instruction['scaleType'] != 3:
  623. maplocInstruction += " %.3f %.3f"% (self.instruction['rect'].width, self.instruction['rect'].height)
  624. instr += maplocInstruction
  625. instr += '\n'
  626. # scale
  627. if self.instruction['scaleType'] == 3: #fixed scale
  628. scaleInstruction = "scale 1:%.0f" % (1/self.instruction['scale'])
  629. instr += scaleInstruction
  630. instr += '\n'
  631. # border
  632. borderInstruction = ''
  633. if self.instruction['border'] == 'n':
  634. borderInstruction = "border n"
  635. else:
  636. borderInstruction = "border y\n"
  637. borderInstruction += string.Template(" width $width\n color $color\n").substitute(self.instruction)
  638. borderInstruction += " end"
  639. instr += borderInstruction
  640. instr += '\n'
  641. return instr
  642. def Read(self, instruction, text, **kwargs):
  643. """!Read instruction and save information"""
  644. if 'isRegionComment' in kwargs:
  645. isRegionComment = kwargs['isRegionComment']
  646. instr = {}
  647. if instruction == 'border':
  648. for line in text:
  649. if line.startswith('end'):
  650. break
  651. try:
  652. if line.split()[1].lower() in ('n', 'no', 'none'):
  653. instr['border'] = 'n'
  654. break
  655. elif line.split()[1].lower() in ('y', 'yes'):
  656. instr['border'] = 'y'
  657. elif line.startswith('width'):
  658. instr['width'] = line.split()[1]
  659. elif line.startswith('color'):
  660. instr['color'] = line.split()[1]
  661. except IndexError:
  662. GError(_("Failed to read instruction %s") % instruction)
  663. return False
  664. elif instruction == 'scale':
  665. try:
  666. scaleText = text.strip('scale ').split(':')[1]
  667. # when scale instruction given and region comment also, then scaletype is fixed scale
  668. if not isRegionComment:
  669. instr['scaleType'] = 2
  670. else:
  671. instr['scaleType'] = 3
  672. scale = 1/float(scaleText)
  673. if abs(scale - self.instruction['scale']) > (0.01 * scale):
  674. GWarning(_("Scale has changed, old value: %(old)s\nnew value: %(new)s") % \
  675. { 'old' : scale, 'new' : self.instruction['scale'] })
  676. except (ValueError, IndexError):
  677. GError(_("Failed to read instruction %s.\nUse 1:25000 notation.") % instruction)
  678. return False
  679. elif instruction == 'maploc':
  680. maploc = text.strip('maploc ').split()
  681. if len(maploc) >= 2:
  682. if abs(self.instruction['rect'].Get()[0] - float(maploc[0])) > 0.5 or \
  683. abs(self.instruction['rect'].Get()[1] - float(maploc[1])) > 0.5:
  684. GWarning(_("Map frame position changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \
  685. { 'old1' : maploc[0], 'old2' : maploc[1],
  686. 'new1' : self.instruction['rect'].Get()[0], 'new2' : self.instruction['rect'].Get()[1] })
  687. #instr['rect'] = wx.Rect2D(float(maploc[0]), float(maploc[1]), self.instruction['rect'][2], self.instruction['rect'][3])
  688. if len(maploc) == 4:
  689. if abs(self.instruction['rect'].Get()[2] - float(maploc[2])) > 0.5 or \
  690. abs(self.instruction['rect'].Get()[3] - float(maploc[3])) > 0.5:
  691. GWarning(_("Map frame size changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \
  692. { 'old1' : maploc[2], 'old2' : maploc[3],
  693. 'new1' : self.instruction['rect'].Get()[2], 'new2' : self.instruction['rect'].Get()[3] })
  694. #instr['rect'] = wx.Rect2D(*map(float, maploc))
  695. self.instruction.update(instr)
  696. return True
  697. class PageSetup(InstructionObject):
  698. """!Class representing page instruction"""
  699. def __init__(self, id):
  700. InstructionObject.__init__(self, id = id)
  701. self.type = 'page'
  702. # default values
  703. self.defaultInstruction = dict(Units = 'inch', Format = 'a4', Orientation = 'Portrait',
  704. Width = 8.268, Height = 11.693, Left = 0.5, Right = 0.5, Top = 1, Bottom = 1)
  705. # current values
  706. self.instruction = dict(self.defaultInstruction)
  707. def __str__(self):
  708. if self.instruction['Format'] == 'custom':
  709. instr = string.Template("paper\n width $Width\n height $Height\n").substitute(self.instruction)
  710. else:
  711. instr = string.Template("paper $Format\n").substitute(self.instruction)
  712. instr += string.Template(" left $Left\n right $Right\n bottom $Bottom\n top $Top\n end").substitute(self.instruction)
  713. return instr
  714. def Read(self, instruction, text, **kwargs):
  715. """!Read instruction and save information"""
  716. instr = {}
  717. self.cats = ['Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
  718. self.subInstr = dict(zip(['width', 'height', 'left', 'right', 'top', 'bottom'], self.cats))
  719. if instruction == 'paper': # just for sure
  720. for line in text:
  721. if line.startswith('paper'):
  722. if len(line.split()) > 1:
  723. pformat = line.split()[1]
  724. availableFormats = self._toDict(grass.read_command('ps.map', flags = 'p',
  725. quiet = True))
  726. # e.g. paper a3
  727. try:
  728. instr['Format'] = pformat
  729. for key, value in availableFormats[pformat].iteritems():
  730. instr[key] = float(value)
  731. break
  732. except KeyError:
  733. GError(_("Failed to read instruction %(file)s.\nUnknown format %(for)s") % \
  734. { 'file' : instruction, 'for' : format })
  735. return False
  736. else:
  737. # paper
  738. # width ...
  739. instr['Format'] = 'custom'
  740. # read subinstructions
  741. elif instr['Format'] == 'custom' and not line.startswith('end'):
  742. text = line.split()
  743. try:
  744. instr[self.subInstr[text[0]]] = float(text[1])
  745. except (IndexError, KeyError):
  746. GError(_("Failed to read instruction %s.") % instruction)
  747. return False
  748. if 'Orientation' in kwargs and kwargs['Orientation'] == 'Landscape':
  749. instr['Width'], instr['Height'] = instr['Height'], instr['Width']
  750. self.instruction.update(instr)
  751. return True
  752. def _toDict(self, paperStr):
  753. sizeDict = dict()
  754. # cats = self.subInstr[ 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
  755. for line in paperStr.strip().split('\n'):
  756. d = dict(zip(self.cats, line.split()[1:]))
  757. sizeDict[line.split()[0]] = d
  758. return sizeDict
  759. class Mapinfo(InstructionObject):
  760. """!Class representing mapinfo instruction"""
  761. def __init__(self, id):
  762. InstructionObject.__init__(self, id = id)
  763. self.type = 'mapinfo'
  764. # default values
  765. self.defaultInstruction = dict(unit = 'inch', where = (0, 0),
  766. font = 'Helvetica', fontsize = 10, color = '0:0:0', background = 'none',
  767. border = 'none', rect = None)
  768. # current values
  769. self.instruction = dict(self.defaultInstruction)
  770. def __str__(self):
  771. instr = "mapinfo\n"
  772. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  773. instr += string.Template(" font $font\n fontsize $fontsize\n color $color\n").substitute(self.instruction)
  774. instr += string.Template(" background $background\n border $border\n").substitute(self.instruction)
  775. instr += " end"
  776. return instr
  777. def Read(self, instruction, text):
  778. """!Read instruction and save information"""
  779. instr = {}
  780. try:
  781. for line in text:
  782. sub = line.split(None,1)
  783. if sub[0] == 'font':
  784. instr['font'] = sub[1]
  785. elif sub[0] == 'fontsize':
  786. instr['fontsize'] = int(sub[1])
  787. elif sub[0] == 'color':
  788. instr['color'] = sub[1]
  789. elif sub[0] == 'background':
  790. instr['background'] = sub[1]
  791. elif sub[0] == 'border':
  792. instr['border'] = sub[1]
  793. elif sub[0] == 'where':
  794. instr['where'] = float(sub[1].split()[0]), float(sub[1].split()[1])
  795. except (ValueError, IndexError):
  796. GError(_("Failed to read instruction %s") % instruction)
  797. return False
  798. self.instruction.update(instr)
  799. self.instruction['rect'] = self.EstimateRect(mapinfoDict = self.instruction)
  800. return True
  801. def EstimateRect(self, mapinfoDict):
  802. """!Estimate size to draw mapinfo"""
  803. w = mapinfoDict['fontsize'] * 20 # any better estimation?
  804. h = mapinfoDict['fontsize'] * 7
  805. width = self.unitConv.convert(value = w, fromUnit = 'point', toUnit = 'inch')
  806. height = self.unitConv.convert(value = h, fromUnit = 'point', toUnit = 'inch')
  807. return wx.Rect2D(x = float(mapinfoDict['where'][0]), y = float(mapinfoDict['where'][1]), w = width, h = height)
  808. class Text(InstructionObject):
  809. """!Class representing text instruction"""
  810. def __init__(self, id):
  811. InstructionObject.__init__(self, id = id)
  812. self.type = 'text'
  813. # default values
  814. self.defaultInstruction = dict(text = "", font = "Helvetica", fontsize = 10, color = 'black', background = 'none',
  815. hcolor = 'none', hwidth = 1, border = 'none', width = '1', XY = True,
  816. where = (0,0), unit = 'inch', rotate = None,
  817. ref = "center center", xoffset = 0, yoffset = 0, east = None, north = None)
  818. # current values
  819. self.instruction = dict(self.defaultInstruction)
  820. def __str__(self):
  821. text = self.instruction['text'].replace('\n','\\n')
  822. instr = u"text %s %s" % (self.instruction['east'], self.instruction['north'])
  823. instr += " %s\n" % text
  824. instr += (string.Template(" font $font\n fontsize $fontsize\n color $color\n").
  825. substitute(self.instruction))
  826. instr += string.Template(" hcolor $hcolor\n").substitute(self.instruction)
  827. if self.instruction['hcolor'] != 'none':
  828. instr += string.Template(" hwidth $hwidth\n").substitute(self.instruction)
  829. instr += string.Template(" border $border\n").substitute(self.instruction)
  830. if self.instruction['border'] != 'none':
  831. instr += string.Template(" width $width\n").substitute(self.instruction)
  832. instr += string.Template(" background $background\n").substitute(self.instruction)
  833. if self.instruction["ref"] != '0':
  834. instr += string.Template(" ref $ref\n").substitute(self.instruction)
  835. if self.instruction["rotate"]:
  836. instr += string.Template(" rotate $rotate\n").substitute(self.instruction)
  837. if float(self.instruction["xoffset"]) or float(self.instruction["yoffset"]):
  838. instr += (string.Template(" xoffset $xoffset\n yoffset $yoffset\n").
  839. substitute(self.instruction))
  840. instr += " end"
  841. try:
  842. instr = instr.encode('latin1')
  843. except UnicodeEncodeError, err:
  844. try:
  845. print err
  846. pos = str(err).split('position')[1].split(':')[0].strip()
  847. except IndexError:
  848. pos = ''
  849. if pos:
  850. message = _("Characters on position %s are not supported "
  851. "by ISO-8859-1 (Latin 1) encoding "
  852. "which is required by module ps.map.") % pos
  853. else:
  854. message = _("Not all characters are supported "
  855. "by ISO-8859-1 (Latin 1) encoding "
  856. "which is required by module ps.map.")
  857. GMessage(message = message)
  858. return ''
  859. return instr
  860. def Read(self, instruction, text, **kwargs):
  861. """!Read instruction and save information"""
  862. map = kwargs['mapInstruction']
  863. instr = {}
  864. for line in text:
  865. try:
  866. sub = line.split(None, 1)[0]
  867. if sub == 'text':
  868. e, n = line.split(None, 3)[1:3]
  869. if '%' in e and '%' in n:
  870. instr['XY'] = True
  871. instr['east'], instr['north'] = self.PercentToReal(e, n)
  872. else:
  873. instr['XY'] = False
  874. instr['east'], instr['north'] = float(e), float(n)
  875. instr['text'] = line.split(None, 3)[3].decode('latin_1')
  876. elif sub == 'font':
  877. instr['font'] = line.split(None, 1)[1]
  878. elif sub == 'fontsize':
  879. instr['fontsize'] = float(line.split(None, 1)[1])
  880. elif sub == 'color':
  881. instr['color'] = line.split(None, 1)[1]
  882. elif sub == 'width':
  883. instr['width'] = line.split(None, 1)[1]
  884. elif sub == 'hcolor':
  885. instr['hcolor'] = line.split(None, 1)[1]
  886. elif sub == 'hwidth':
  887. instr['hwidth'] = line.split(None, 1)[1]
  888. elif sub == 'background':
  889. instr['background'] = line.split(None, 1)[1]
  890. elif sub == 'border':
  891. instr['border'] = line.split(None, 1)[1]
  892. elif sub == 'ref':
  893. instr['ref'] = line.split(None, 1)[1]
  894. elif sub == 'rotate':
  895. instr['rotate'] = float(line.split(None, 1)[1])
  896. elif sub == 'xoffset':
  897. instr['xoffset'] = int(line.split(None, 1)[1])
  898. elif sub == 'yoffset':
  899. instr['yoffset'] = int(line.split(None, 1)[1])
  900. elif sub == 'opaque':
  901. if line.split(None, 1)[1].lower() in ('n', 'none'):
  902. instr['background'] = 'none'
  903. except(IndexError, ValueError):
  904. GError(_("Failed to read instruction %s") % instruction)
  905. return False
  906. instr['where'] = PaperMapCoordinates(map = map, x = instr['east'], y = instr['north'], paperToMap = False)
  907. self.instruction.update(instr)
  908. return True
  909. def PercentToReal(self, e, n):
  910. """!Converts text coordinates from percent of region to map coordinates"""
  911. e, n = float(e.strip('%')), float(n.strip('%'))
  912. region = grass.region()
  913. N = region['s'] + (region['n'] - region['s']) / 100 * n
  914. E = region['w'] + (region['e'] - region['w']) / 100 * e
  915. return E, N
  916. class Image(InstructionObject):
  917. """!Class representing eps instruction - image"""
  918. def __init__(self, id, settings):
  919. InstructionObject.__init__(self, id = id)
  920. self.settings = settings
  921. self.type = 'image'
  922. # default values
  923. self.defaultInstruction = dict(epsfile = "", XY = True, where = (0,0), unit = 'inch',
  924. east = None, north = None,
  925. rotate = None, scale = 1)
  926. # current values
  927. self.instruction = dict(self.defaultInstruction)
  928. def __str__(self):
  929. self.ChangeRefPoint(toCenter = True)
  930. instr = "eps %s %s\n" % (self.instruction['east'], self.instruction['north'])
  931. instr += string.Template(" epsfile $epsfile\n").substitute(self.instruction)
  932. if self.instruction["rotate"]:
  933. instr += string.Template(" rotate $rotate\n").substitute(self.instruction)
  934. if self.instruction["scale"]:
  935. instr += string.Template(" scale $scale\n").substitute(self.instruction)
  936. instr += " end"
  937. return instr
  938. def Read(self, instruction, text, **kwargs):
  939. """!Read instruction and save information"""
  940. mapInstr = kwargs['mapInstruction']
  941. instr = {}
  942. for line in text:
  943. try:
  944. sub = line.split(None, 1)[0]
  945. if sub == 'eps':
  946. e, n = line.split(None, 3)[1:3]
  947. if '%' in e and '%' in n:
  948. instr['XY'] = True
  949. instr['east'], instr['north'] = self.PercentToReal(e, n)
  950. else:
  951. instr['XY'] = False
  952. instr['east'], instr['north'] = float(e), float(n)
  953. elif sub == 'epsfile':
  954. instr['epsfile'] = line.split(None, 1)[1]
  955. elif sub == 'rotate':
  956. instr['rotate'] = float(line.split(None, 1)[1])
  957. elif sub == 'scale':
  958. instr['scale'] = float(line.split(None, 1)[1])
  959. except(IndexError, ValueError):
  960. GError(_("Failed to read instruction %s") % instruction)
  961. return False
  962. if not os.path.exists(instr['epsfile']):
  963. GError(_("Failed to read instruction %s: file %s not found.") % instruction, instr['epsfile'])
  964. return False
  965. instr['epsfile'] = os.path.abspath(instr['epsfile'])
  966. instr['size'] = self.GetImageOrigSize(instr['epsfile'])
  967. if 'rotate' in instr:
  968. instr['size'] = BBoxAfterRotation(instr['size'][0], instr['size'][1], instr['rotate'])
  969. self.instruction.update(instr)
  970. self.ChangeRefPoint(toCenter = False)
  971. instr['where'] = PaperMapCoordinates(map = mapInstr, x = self.instruction['east'],
  972. y = self.instruction['north'], paperToMap = False)
  973. w = self.unitConv.convert(value = instr['size'][0], fromUnit = 'point', toUnit = 'inch')
  974. h = self.unitConv.convert(value = instr['size'][1], fromUnit = 'point', toUnit = 'inch')
  975. instr['rect'] = wx.Rect2D(x = float(instr['where'][0]), y = float(instr['where'][1]),
  976. w = w * self.instruction['scale'], h = h * self.instruction['scale'])
  977. self.instruction.update(instr)
  978. return True
  979. def PercentToReal(self, e, n):
  980. """!Converts eps coordinates from percent of region to map coordinates"""
  981. e, n = float(e.strip('%')), float(n.strip('%'))
  982. region = grass.region()
  983. N = region['s'] + (region['n'] - region['s']) / 100 * n
  984. E = region['w'] + (region['e'] - region['w']) / 100 * e
  985. return E, N
  986. def ChangeRefPoint(self, toCenter):
  987. """!Change reference point (left top x center)"""
  988. mapInstr = self.settings.FindInstructionByType('map')
  989. if not mapInstr:
  990. mapInstr = self.settings.FindInstructionByType('initMap')
  991. mapId = mapInstr.id
  992. if toCenter:
  993. center = self.instruction['rect'].GetCentre()
  994. ENCenter = PaperMapCoordinates(map = self.settings[mapId],
  995. x = center[0], y = center[1], paperToMap = True)
  996. self.instruction['east'], self.instruction['north'] = ENCenter
  997. else:
  998. x, y = PaperMapCoordinates(map = self.settings[mapId], x = self.instruction['east'],
  999. y = self.instruction['north'], paperToMap = False)
  1000. w = self.unitConv.convert(value = self.instruction['size'][0], fromUnit = 'point', toUnit = 'inch')
  1001. h = self.unitConv.convert(value = self.instruction['size'][1], fromUnit = 'point', toUnit = 'inch')
  1002. x -= w * self.instruction['scale'] / 2
  1003. y -= h * self.instruction['scale'] / 2
  1004. e, n = PaperMapCoordinates(map = self.settings[mapId], x = x, y = y, paperToMap = True)
  1005. self.instruction['east'], self.instruction['north'] = e, n
  1006. def GetImageOrigSize(self, imagePath):
  1007. """!Get image size.
  1008. If eps, size is read from image header.
  1009. """
  1010. fileName = os.path.split(imagePath)[1]
  1011. # if eps, read info from header
  1012. if os.path.splitext(fileName)[1].lower() == '.eps':
  1013. bbInfo = "%%BoundingBox"
  1014. file = open(imagePath,"r")
  1015. w = h = 0
  1016. while file:
  1017. line = file.readline()
  1018. if line.find(bbInfo) == 0:
  1019. w, h = line.split()[3:5]
  1020. break
  1021. file.close()
  1022. return float(w), float(h)
  1023. else: # we can use wx.Image
  1024. img = wx.Image(fileName, type=wx.BITMAP_TYPE_ANY)
  1025. return img.GetWidth(), img.GetHeight()
  1026. class NorthArrow(Image):
  1027. """!Class representing eps instruction -- North Arrow"""
  1028. def __init__(self, id, settings):
  1029. Image.__init__(self, id = id, settings = settings)
  1030. self.type = 'northArrow'
  1031. def __str__(self):
  1032. self.ChangeRefPoint(toCenter = True)
  1033. instr = "eps %s %s\n" % (self.instruction['east'], self.instruction['north'])
  1034. instr += "# north arrow\n"
  1035. instr += string.Template(" epsfile $epsfile\n").substitute(self.instruction)
  1036. if self.instruction["rotate"]:
  1037. instr += string.Template(" rotate $rotate\n").substitute(self.instruction)
  1038. if self.instruction["scale"]:
  1039. instr += string.Template(" scale $scale\n").substitute(self.instruction)
  1040. instr += " end"
  1041. return instr
  1042. class Scalebar(InstructionObject):
  1043. """!Class representing scalebar instruction"""
  1044. def __init__(self, id):
  1045. InstructionObject.__init__(self, id = id)
  1046. self.type = 'scalebar'
  1047. # default values
  1048. self.defaultInstruction = dict(unit = 'inch', where = (1,1),
  1049. unitsLength = 'auto', unitsHeight = 'inch',
  1050. length = None, height = 0.1, rect = None,
  1051. fontsize = 10, background = 'y',
  1052. scalebar = 'f', segment = 4, numbers = 1)
  1053. # current values
  1054. self.instruction = dict(self.defaultInstruction)
  1055. def __str__(self):
  1056. instr = string.Template("scalebar $scalebar\n").substitute(self.instruction)
  1057. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  1058. instr += string.Template(" length $length\n units $unitsLength\n").substitute(self.instruction)
  1059. instr += string.Template(" height $height\n").substitute(self.instruction)
  1060. instr += string.Template(" segment $segment\n numbers $numbers\n").substitute(self.instruction)
  1061. instr += string.Template(" fontsize $fontsize\n background $background\n").substitute(self.instruction)
  1062. instr += " end"
  1063. return instr
  1064. def Read(self, instruction, text, **kwargs):
  1065. """!Read instruction and save information"""
  1066. scale = kwargs['scale']
  1067. instr = {}
  1068. for line in text:
  1069. try:
  1070. if line.startswith('scalebar'):
  1071. if 'scalebar s' in line:
  1072. instr['scalebar'] = 's'
  1073. else:
  1074. instr['scalebar'] = 'f'
  1075. elif line.startswith('where'):
  1076. instr['where'] = map(float, line.split()[1:3])
  1077. elif line.startswith('length'):
  1078. instr['length'] = float(line.split()[1])
  1079. elif line.startswith('units'):
  1080. if line.split()[1] in ['auto', 'meters', 'kilometers', 'feet', 'miles', 'nautmiles']:
  1081. instr['unitsLength'] = line.split()[1]
  1082. elif line.startswith('height'):
  1083. instr['height'] = float(line.split()[1])
  1084. elif line.startswith('fontsize'):
  1085. instr['fontsize'] = float(line.split()[1])
  1086. elif line.startswith('numbers'):
  1087. instr['numbers'] = int(line.split()[1])
  1088. elif line.startswith('segment'):
  1089. instr['segment'] = int(line.split()[1])
  1090. elif line.startswith('background'):
  1091. if line.split()[1].strip().lower() in ('y','yes'):
  1092. instr['background'] = 'y'
  1093. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1094. instr['background'] = 'n'
  1095. except(IndexError, ValueError):
  1096. GError(_("Failed to read instruction %s") % instruction)
  1097. return False
  1098. self.instruction.update(instr)
  1099. w, h = self.EstimateSize(scalebarDict = self.instruction, scale = scale)
  1100. x = self.instruction['where'][0] - w / 2
  1101. y = self.instruction['where'][1] - h / 2
  1102. self.instruction['rect'] = wx.Rect2D(x, y, w, h)
  1103. return True
  1104. def EstimateSize(self, scalebarDict, scale):
  1105. """!Estimate size to draw scalebar"""
  1106. units = projInfo()['units']
  1107. if not units or units not in self.unitConv.getAllUnits():
  1108. units = 'meters'
  1109. if scalebarDict['unitsLength'] != 'auto':
  1110. length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = scalebarDict['unitsLength'], toUnit = 'inch')
  1111. else:
  1112. length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = units, toUnit = 'inch')
  1113. length *= scale
  1114. length *= 1.1 #for numbers on the edge
  1115. height = scalebarDict['height'] + 2 * self.unitConv.convert(value = scalebarDict['fontsize'], fromUnit = 'point', toUnit = 'inch')
  1116. return (length, height)
  1117. class RasterLegend(InstructionObject):
  1118. """!Class representing colortable instruction"""
  1119. def __init__(self, id):
  1120. InstructionObject.__init__(self, id = id)
  1121. self.type = 'rasterLegend'
  1122. # default values
  1123. self.defaultInstruction = dict(rLegend = False, unit = 'inch', rasterDefault = True, raster = None,
  1124. discrete = None, type = None,
  1125. where = (0, 0),
  1126. width = None, height = None, cols = 1, font = "Helvetica", fontsize = 10,
  1127. #color = '0:0:0', tickbar = False, range = False, min = 0, max = 0,
  1128. color = 'black', tickbar = 'n', range = False, min = 0, max = 0,
  1129. nodata = 'n')
  1130. # current values
  1131. self.instruction = dict(self.defaultInstruction)
  1132. def __str__(self):
  1133. instr = "colortable y\n"
  1134. instr += string.Template(" raster $raster\n").substitute(self.instruction)
  1135. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  1136. if self.instruction['width']:
  1137. instr += string.Template(" width $width\n").substitute(self.instruction)
  1138. instr += string.Template(" discrete $discrete\n").substitute(self.instruction)
  1139. if self.instruction['discrete'] == 'n':
  1140. if self.instruction['height']:
  1141. instr += string.Template(" height $height\n").substitute(self.instruction)
  1142. instr += string.Template(" tickbar $tickbar\n").substitute(self.instruction)
  1143. if self.instruction['range']:
  1144. instr += string.Template(" range $min $max\n").substitute(self.instruction)
  1145. else:
  1146. instr += string.Template(" cols $cols\n").substitute(self.instruction)
  1147. instr += string.Template(" nodata $nodata\n").substitute(self.instruction)
  1148. instr += string.Template(" font $font\n fontsize $fontsize\n color $color\n")\
  1149. .substitute(self.instruction)
  1150. instr += " end"
  1151. return instr
  1152. def Read(self, instruction, text, **kwargs):
  1153. """!Read instruction and save information"""
  1154. instr = {}
  1155. instr['rLegend'] = True
  1156. for line in text:
  1157. try:
  1158. if line.startswith('where'):
  1159. instr['where'] = map(float, line.split()[1:3])
  1160. elif line.startswith('font '):
  1161. instr['font'] = line.split()[1]
  1162. elif line.startswith('fontsize'):
  1163. instr['fontsize'] = float(line.split()[1])
  1164. elif line.startswith('color '):
  1165. instr['color'] = line.split()[1]
  1166. elif line.startswith('raster'):
  1167. instr['raster'] = line.split()[1]
  1168. elif line.startswith('width'):
  1169. instr['width'] = float(line.split()[1])
  1170. elif line.startswith('height'):
  1171. instr['height'] = float(line.split()[1])
  1172. elif line.startswith('cols'):
  1173. instr['cols'] = int(line.split()[1])
  1174. elif line.startswith('range'):
  1175. instr['range'] = True
  1176. instr['min'] = float(line.split()[1])
  1177. instr['max'] = float(line.split()[2])
  1178. elif line.startswith('nodata'):
  1179. if line.split()[1].strip().lower() in ('y','yes'):
  1180. instr['nodata'] = 'y'
  1181. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1182. instr['nodata'] = 'n'
  1183. elif line.startswith('tickbar'):
  1184. if line.split()[1].strip().lower() in ('y','yes'):
  1185. instr['tickbar'] = 'y'
  1186. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1187. instr['tickbar'] = 'n'
  1188. elif line.startswith('discrete'):
  1189. if line.split()[1].strip().lower() in ('y','yes'):
  1190. instr['discrete'] = 'y'
  1191. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1192. instr['discrete'] = 'n'
  1193. except(IndexError, ValueError):
  1194. GError(_("Failed to read instruction %s") % instruction)
  1195. return False
  1196. if 'raster' in instr:
  1197. instr['rasterDefault'] = False
  1198. if 'discrete' not in instr:
  1199. rasterType = getRasterType(map = instr['raster'])
  1200. instr['type'] = rasterType
  1201. if rasterType == 'CELL':
  1202. instr['discrete'] = 'y'
  1203. else:
  1204. instr['discrete'] = 'n'
  1205. else:
  1206. instr['rasterDefault'] = True
  1207. self.instruction.update(instr)
  1208. # add 'rect' in the end
  1209. return True
  1210. def EstimateHeight(self, raster, discrete, fontsize, cols = None, height = None):
  1211. """!Estimate height to draw raster legend"""
  1212. if discrete == 'n':
  1213. if height:
  1214. height = height
  1215. else:
  1216. height = self.unitConv.convert(value = fontsize * 10,
  1217. fromUnit = 'point', toUnit = 'inch')
  1218. if discrete == 'y':
  1219. if cols:
  1220. cols = cols
  1221. else:
  1222. cols = 1
  1223. rinfo = grass.raster_info(raster)
  1224. if rinfo['datatype'] in ('DCELL', 'FCELL'):
  1225. minim, maxim = rinfo['min'], rinfo['max']
  1226. rows = ceil(maxim / cols )
  1227. else:
  1228. cat = grass.read_command('r.category', map = raster,
  1229. fs = ':').strip().split('\n')
  1230. rows = ceil(float(len(cat)) / cols )
  1231. height = self.unitConv.convert(value = 1.5 * rows * fontsize, fromUnit = 'point', toUnit = 'inch')
  1232. return height
  1233. def EstimateWidth(self, raster, discrete, fontsize, cols = None, width = None, paperInstr = None):
  1234. """!Estimate size to draw raster legend"""
  1235. if discrete == 'n':
  1236. rinfo = grass.raster_info(raster)
  1237. minim, maxim = rinfo['min'], rinfo['max']
  1238. if width:
  1239. width = width
  1240. else:
  1241. width = self.unitConv.convert(value = fontsize * 2,
  1242. fromUnit = 'point', toUnit = 'inch')
  1243. text = len(max(str(minim), str(maxim), key = len))
  1244. textPart = self.unitConv.convert(value = text * fontsize / 2,
  1245. fromUnit = 'point', toUnit = 'inch')
  1246. width += textPart
  1247. elif discrete == 'y':
  1248. if cols:
  1249. cols = cols
  1250. else:
  1251. cols = 1
  1252. if width:
  1253. width = width
  1254. else:
  1255. paperWidth = paperInstr['Width'] - paperInstr['Right'] - paperInstr['Left']
  1256. width = (paperWidth / cols) * (cols - 1) + 1
  1257. return width
  1258. class VectorLegend(InstructionObject):
  1259. """!Class representing colortable instruction"""
  1260. def __init__(self, id):
  1261. InstructionObject.__init__(self, id = id)
  1262. self.type = 'vectorLegend'
  1263. # default values
  1264. self.defaultInstruction = dict(vLegend = False, unit = 'inch', where = (0, 0),
  1265. defaultSize = True, width = 0.4, cols = 1, span = None,
  1266. font = "Helvetica", fontsize = 10,
  1267. border = 'none')
  1268. # current values
  1269. self.instruction = dict(self.defaultInstruction)
  1270. def __str__(self):
  1271. instr = "vlegend\n"
  1272. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  1273. instr += string.Template(" font $font\n fontsize $fontsize\n").substitute(self.instruction)
  1274. instr += string.Template(" width $width\n cols $cols\n").substitute(self.instruction)
  1275. if self.instruction['span']:
  1276. instr += string.Template(" span $span\n").substitute(self.instruction)
  1277. instr += string.Template(" border $border\n").substitute(self.instruction)
  1278. instr += " end"
  1279. return instr
  1280. def Read(self, instruction, text, **kwargs):
  1281. """!Read instruction and save information"""
  1282. instr = {}
  1283. instr['vLegend'] = True
  1284. for line in text:
  1285. try:
  1286. if line.startswith('where'):
  1287. instr['where'] = map(float, line.split()[1:3])
  1288. elif line.startswith('font '):
  1289. instr['font'] = line.split()[1]
  1290. elif line.startswith('fontsize'):
  1291. instr['fontsize'] = float(line.split()[1])
  1292. elif line.startswith('width'):
  1293. instr['width'] = float(line.split()[1])
  1294. elif line.startswith('cols'):
  1295. instr['cols'] = int(line.split()[1])
  1296. elif line.startswith('span'):
  1297. instr['span'] = float(line.split()[1])
  1298. elif line.startswith('border'):
  1299. instr['border'] = line.split()[1]
  1300. except(IndexError, ValueError):
  1301. GError(_("Failed to read instruction %s") % instruction)
  1302. return False
  1303. self.instruction.update(instr)
  1304. return True
  1305. def EstimateSize(self, vectorInstr, fontsize, width = None, cols = None):
  1306. """!Estimate size to draw vector legend"""
  1307. if width:
  1308. width = width
  1309. else:
  1310. width = fontsize/24.0
  1311. if cols:
  1312. cols = cols
  1313. else:
  1314. cols = 1
  1315. vectors = vectorInstr['list']
  1316. labels = [vector[4] for vector in vectors if vector[3] != 0]
  1317. extent = (len(max(labels, key = len)) * fontsize / 2, fontsize)
  1318. wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'point', toUnit = 'inch')
  1319. hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'point', toUnit = 'inch')
  1320. w = (width + wExtent) * cols
  1321. h = len(labels) * hExtent / cols
  1322. h *= 1.1
  1323. return (w, h)
  1324. class Raster(InstructionObject):
  1325. """!Class representing raster instruction"""
  1326. def __init__(self, id):
  1327. InstructionObject.__init__(self, id = id)
  1328. self.type = 'raster'
  1329. # default values
  1330. self.defaultInstruction = dict(isRaster = False, raster = None)
  1331. # current values
  1332. self.instruction = dict(self.defaultInstruction)
  1333. def __str__(self):
  1334. instr = string.Template("raster $raster").substitute(self.instruction)
  1335. return instr
  1336. def Read(self, instruction, text):
  1337. """!Read instruction and save information"""
  1338. instr = {}
  1339. instr['isRaster'] = True
  1340. try:
  1341. map = text.split()[1]
  1342. except IndexError:
  1343. GError(_("Failed to read instruction %s") % instruction)
  1344. return False
  1345. try:
  1346. info = grass.find_file(map, element = 'cell')
  1347. except grass.ScriptError, e:
  1348. GError(message = e.value)
  1349. return False
  1350. instr['raster'] = info['fullname']
  1351. self.instruction.update(instr)
  1352. return True
  1353. class Vector(InstructionObject):
  1354. """!Class keeps vector layers"""
  1355. def __init__(self, id):
  1356. InstructionObject.__init__(self, id = id)
  1357. self.type = 'vector'
  1358. # default values
  1359. self.defaultInstruction = dict(list = None)# [vmap, type, id, lpos, label]
  1360. # current values
  1361. self.instruction = dict(self.defaultInstruction)
  1362. def __str__(self):
  1363. return ''
  1364. def Read(self, instruction, text, **kwargs):
  1365. """!Read instruction and save information"""
  1366. instr = {}
  1367. for line in text:
  1368. if line.startswith('vpoints') or line.startswith('vlines') or line.startswith('vareas'):
  1369. # subtype
  1370. if line.startswith('vpoints'):
  1371. subType = 'points'
  1372. elif line.startswith('vlines'):
  1373. subType = 'lines'
  1374. elif line.startswith('vareas'):
  1375. subType = 'areas'
  1376. # name of vector map
  1377. vmap = line.split()[1]
  1378. try:
  1379. info = grass.find_file(vmap, element = 'vector')
  1380. except grass.ScriptError, e:
  1381. GError(message = e.value)
  1382. return False
  1383. vmap = info['fullname']
  1384. # id
  1385. id = kwargs['id']
  1386. # lpos
  1387. lpos = kwargs['vectorMapNumber']
  1388. #label
  1389. label = '('.join(vmap.split('@')) + ')'
  1390. break
  1391. instr = [vmap, subType, id, lpos, label]
  1392. if not self.instruction['list']:
  1393. self.instruction['list'] = []
  1394. self.instruction['list'].append(instr)
  1395. return True
  1396. class VProperties(InstructionObject):
  1397. """!Class represents instructions vareas, vlines, vpoints"""
  1398. def __init__(self, id, subType):
  1399. InstructionObject.__init__(self, id = id)
  1400. self.type = 'vProperties'
  1401. self.subType = subType
  1402. # default values
  1403. if self.subType == 'points':
  1404. dd = dict(subType = 'points', name = None, type = 'point or centroid', connection = False, layer = '1',
  1405. masked = 'n', color = '0:0:0', width = 1,
  1406. fcolor = '255:0:0', rgbcolumn = None, symbol = os.path.join('basic', 'x'), eps = None,
  1407. size = 5, sizecolumn = None, scale = None,
  1408. rotation = False, rotate = 0, rotatecolumn = None, label = None, lpos = None)
  1409. elif self.subType == 'lines':
  1410. dd = dict(subType = 'lines', name = None, type = 'line or boundary', connection = False, layer = '1',
  1411. masked = 'n', color = '0:0:0', hwidth = 1,
  1412. hcolor = 'none', rgbcolumn = None,
  1413. width = 1, cwidth = None,
  1414. style = 'solid', linecap = 'butt', label = None, lpos = None)
  1415. else: # areas
  1416. dd = dict(subType = 'areas', name = None, connection = False, layer = '1',
  1417. masked = 'n', color = '0:0:0', width = 1,
  1418. fcolor = 'none', rgbcolumn = None,
  1419. pat = None, pwidth = 1, scale = 1, label = None, lpos = None)
  1420. self.defaultInstruction = dd
  1421. # current values
  1422. self.instruction = dict(self.defaultInstruction)
  1423. def __str__(self):
  1424. dic = self.instruction
  1425. vInstruction = string.Template("v$subType $name\n").substitute(dic)
  1426. #data selection
  1427. if self.subType in ('points', 'lines'):
  1428. vInstruction += string.Template(" type $type\n").substitute(dic)
  1429. if dic['connection']:
  1430. vInstruction += string.Template(" layer $layer\n").substitute(dic)
  1431. if dic.has_key('cats'):
  1432. vInstruction += string.Template(" cats $cats\n").substitute(dic)
  1433. elif dic.has_key('where'):
  1434. vInstruction += string.Template(" where $where\n").substitute(dic)
  1435. vInstruction += string.Template(" masked $masked\n").substitute(dic)
  1436. #colors
  1437. vInstruction += string.Template(" color $color\n").substitute(dic)
  1438. if self.subType in ('points', 'areas'):
  1439. if dic['color'] != 'none':
  1440. vInstruction += string.Template(" width $width\n").substitute(dic)
  1441. if dic['rgbcolumn']:
  1442. vInstruction += string.Template(" rgbcolumn $rgbcolumn\n").substitute(dic)
  1443. vInstruction += string.Template(" fcolor $fcolor\n").substitute(dic)
  1444. else:
  1445. if dic['rgbcolumn']:
  1446. vInstruction += string.Template(" rgbcolumn $rgbcolumn\n").substitute(dic)
  1447. elif dic['hcolor'] != 'none':
  1448. vInstruction += string.Template(" hwidth $hwidth\n").substitute(dic)
  1449. vInstruction += string.Template(" hcolor $hcolor\n").substitute(dic)
  1450. # size and style
  1451. if self.subType == 'points':
  1452. if not dic['eps']:
  1453. vInstruction += string.Template(" symbol $symbol\n").substitute(dic)
  1454. else: #eps
  1455. vInstruction += string.Template(" eps $eps\n").substitute(dic)
  1456. if dic['size']:
  1457. vInstruction += string.Template(" size $size\n").substitute(dic)
  1458. else: # sizecolumn
  1459. vInstruction += string.Template(" sizecolumn $sizecolumn\n").substitute(dic)
  1460. vInstruction += string.Template(" scale $scale\n").substitute(dic)
  1461. if dic['rotation']:
  1462. if dic['rotate'] is not None:
  1463. vInstruction += string.Template(" rotate $rotate\n").substitute(dic)
  1464. else:
  1465. vInstruction += string.Template(" rotatecolumn $rotatecolumn\n").substitute(dic)
  1466. if self.subType == 'areas':
  1467. if dic['pat'] is not None:
  1468. vInstruction += string.Template(" pat $pat\n").substitute(dic)
  1469. vInstruction += string.Template(" pwidth $pwidth\n").substitute(dic)
  1470. vInstruction += string.Template(" scale $scale\n").substitute(dic)
  1471. if self.subType == 'lines':
  1472. if dic['width'] is not None:
  1473. vInstruction += string.Template(" width $width\n").substitute(dic)
  1474. else:
  1475. vInstruction += string.Template(" cwidth $cwidth\n").substitute(dic)
  1476. vInstruction += string.Template(" style $style\n").substitute(dic)
  1477. vInstruction += string.Template(" linecap $linecap\n").substitute(dic)
  1478. #position and label in vlegend
  1479. vInstruction += string.Template(" label $label\n lpos $lpos\n").substitute(dic)
  1480. vInstruction += " end"
  1481. try:
  1482. vInstruction = vInstruction.encode('Latin_1')
  1483. except UnicodeEncodeError, err:
  1484. try:
  1485. print err
  1486. pos = str(err).split('position')[1].split(':')[0].strip()
  1487. except IndexError:
  1488. pos = ''
  1489. if pos:
  1490. message = _("Characters on position %s are not supported "
  1491. "by ISO-8859-1 (Latin 1) encoding "
  1492. "which is required by module ps.map.") % pos
  1493. else:
  1494. message = _("Not all characters are supported "
  1495. "by ISO-8859-1 (Latin 1) encoding "
  1496. "which is required by module ps.map.")
  1497. GMessage(message = message)
  1498. return ''
  1499. return vInstruction
  1500. def Read(self, instruction, text, **kwargs):
  1501. """!Read instruction and save information"""
  1502. instr = {}
  1503. try:
  1504. info = grass.find_file(name = text[0].split()[1], element = 'vector')
  1505. except grass.ScriptError, e:
  1506. GError(message = e.value)
  1507. return False
  1508. instr['name'] = info['fullname']
  1509. #connection
  1510. instr['connection'] = True
  1511. self.mapDBInfo = VectorDBInfo(instr['name'])
  1512. self.layers = self.mapDBInfo.layers.keys()
  1513. if not self.layers:
  1514. instr['connection'] = False
  1515. # points
  1516. if text[0].startswith('vpoints'):
  1517. for line in text[1:]:
  1518. if line.startswith('type'):
  1519. tp = []
  1520. if line.find('point') != -1:
  1521. tp.append('point')
  1522. if line.find('centroid') != -1:
  1523. tp.append('centroid')
  1524. instr['type'] = ' or '.join(tp)
  1525. elif line.startswith('fcolor'):
  1526. instr['fcolor'] = line.split()[1]
  1527. elif line.startswith('rgbcolumn'):
  1528. instr['rgbcolumn'] = line.split()[1]
  1529. elif line.startswith('symbol'):
  1530. instr['symbol'] = line.split()[1]
  1531. elif line.startswith('eps'):
  1532. instr['eps'] = line.split()[1]
  1533. elif line.startswith('size '):
  1534. instr['size'] = line.split()[1]
  1535. elif line.startswith('sizecolumn'):
  1536. instr['size'] = None
  1537. instr['sizecolumn'] = line.split()[1]
  1538. elif line.startswith('scale '):
  1539. instr['scale'] = float(line.split()[1])
  1540. elif line.startswith('rotate '):
  1541. instr['rotation'] = True
  1542. instr['rotate'] = line.split()[1]
  1543. elif line.startswith('rotatecolumn'):
  1544. instr['rotatecolumn'] = line.split()[1]
  1545. instr['rotation'] = True
  1546. instr['rotate'] = None
  1547. # lines
  1548. elif text[0].startswith('vlines'):
  1549. for line in text[1:]:
  1550. if line.startswith('type'):
  1551. tp = []
  1552. if line.find('line') != -1:
  1553. tp.append('line')
  1554. if line.find('boundary') != -1:
  1555. tp.append('boundary')
  1556. instr['type'] = ' or '.join(tp)
  1557. elif line.startswith('hwidth'):
  1558. instr['hwidth'] = float(line.split()[1])
  1559. elif line.startswith('hcolor'):
  1560. instr['hcolor'] = line.split()[1]
  1561. elif line.startswith('rgbcolumn'):
  1562. instr['rgbcolumn'] = line.split()[1]
  1563. elif line.startswith('cwidth'):
  1564. instr['cwidth'] = float(line.split()[1])
  1565. instr['width'] = None
  1566. elif line.startswith('style'):
  1567. instr['style'] = line.split()[1]
  1568. elif line.startswith('linecap'):
  1569. instr['linecap'] = line.split()[1]
  1570. elif text[0].startswith('vareas'):
  1571. for line in text[1:]:
  1572. if line.startswith('fcolor'):
  1573. instr['fcolor'] = line.split()[1]
  1574. elif line.startswith('pat'):
  1575. instr['pat'] = line.split()[1]
  1576. elif line.startswith('pwidth'):
  1577. instr['pwidth'] = float(line.split()[1])
  1578. elif line.startswith('scale'):
  1579. instr['scale'] = float(line.split()[1])
  1580. # same properties for all
  1581. for line in text[1:]:
  1582. if line.startswith('lpos'):
  1583. instr['lpos'] = int(line.split()[1])
  1584. elif line.startswith('label'):
  1585. instr['label'] = line.split(None, 1)[1].decode('latin_1')
  1586. elif line.startswith('layer'):
  1587. instr['layer'] = line.split()[1]
  1588. elif line.startswith('masked'):
  1589. if line.split()[1].lower() in ('y', 'yes'):
  1590. instr['masked'] = 'y'
  1591. else:
  1592. instr['masked'] = 'n'
  1593. elif line.startswith('color'):
  1594. instr['color'] = line.split()[1]
  1595. elif line.startswith('rgbcolumn'):
  1596. instr['rgbcolumn'] = line.split()[1]
  1597. elif line.startswith('width'):
  1598. instr['width'] = float(line.split()[1])
  1599. if 'label' not in instr:
  1600. instr['label'] = '('.join(instr['name'].split('@')) + ')'
  1601. if 'lpos' not in instr:
  1602. instr['lpos'] = kwargs['vectorMapNumber']
  1603. self.instruction.update(instr)
  1604. return True
  1605. class PsmapDialog(wx.Dialog):
  1606. def __init__(self, parent, id, title, settings, apply = True):
  1607. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY,
  1608. title = title, size = wx.DefaultSize,
  1609. style = wx.CAPTION|wx.MINIMIZE_BOX|wx.CLOSE_BOX)
  1610. self.apply = apply
  1611. self.id = id
  1612. self.parent = parent
  1613. self.instruction = settings
  1614. self.objectType = None
  1615. self.unitConv = UnitConversion(self)
  1616. self.spinCtrlSize = (65, -1)
  1617. self.Bind(wx.EVT_CLOSE, self.OnClose)
  1618. def AddUnits(self, parent, dialogDict):
  1619. parent.units = dict()
  1620. parent.units['unitsLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Units:"))
  1621. choices = self.unitConv.getPageUnitsNames()
  1622. parent.units['unitsCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = choices)
  1623. parent.units['unitsCtrl'].SetStringSelection(self.unitConv.findName(dialogDict['unit']))
  1624. def AddPosition(self, parent, dialogDict):
  1625. if not hasattr(parent, "position"):
  1626. parent.position = dict()
  1627. parent.position['comment'] = wx.StaticText(parent, id = wx.ID_ANY,\
  1628. label = _("Position of the top left corner\nfrom the top left edge of the paper"))
  1629. parent.position['xLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("X:"))
  1630. parent.position['yLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Y:"))
  1631. parent.position['xCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][0]), validator = TCValidator(flag = 'DIGIT_ONLY'))
  1632. parent.position['yCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][1]), validator = TCValidator(flag = 'DIGIT_ONLY'))
  1633. if dialogDict.has_key('unit'):
  1634. x = self.unitConv.convert(value = dialogDict['where'][0], fromUnit = 'inch', toUnit = dialogDict['unit'])
  1635. y = self.unitConv.convert(value = dialogDict['where'][1], fromUnit = 'inch', toUnit = dialogDict['unit'])
  1636. parent.position['xCtrl'].SetValue("%5.3f" % x)
  1637. parent.position['yCtrl'].SetValue("%5.3f" % y)
  1638. def AddExtendedPosition(self, panel, gridBagSizer, dialogDict):
  1639. """!Add widgets for setting position relative to paper and to map"""
  1640. panel.position = dict()
  1641. positionLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Position is given:"))
  1642. panel.position['toPaper'] = wx.RadioButton(panel, id = wx.ID_ANY, label = _("relatively to paper"), style = wx.RB_GROUP)
  1643. panel.position['toMap'] = wx.RadioButton(panel, id = wx.ID_ANY, label = _("by map coordinates"))
  1644. panel.position['toPaper'].SetValue(dialogDict['XY'])
  1645. panel.position['toMap'].SetValue(not dialogDict['XY'])
  1646. gridBagSizer.Add(positionLabel, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  1647. gridBagSizer.Add(panel.position['toPaper'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  1648. gridBagSizer.Add(panel.position['toMap'], pos = (1,1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  1649. # first box - paper coordinates
  1650. box1 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
  1651. sizerP = wx.StaticBoxSizer(box1, wx.VERTICAL)
  1652. self.gridBagSizerP = wx.GridBagSizer (hgap = 5, vgap = 5)
  1653. self.gridBagSizerP.AddGrowableCol(1)
  1654. self.gridBagSizerP.AddGrowableRow(3)
  1655. self.AddPosition(parent = panel, dialogDict = dialogDict)
  1656. panel.position['comment'].SetLabel(_("Position from the top left\nedge of the paper"))
  1657. self.AddUnits(parent = panel, dialogDict = dialogDict)
  1658. self.gridBagSizerP.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1659. self.gridBagSizerP.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1660. self.gridBagSizerP.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1661. self.gridBagSizerP.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1662. self.gridBagSizerP.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1663. self.gridBagSizerP.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1664. self.gridBagSizerP.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag = wx.ALIGN_BOTTOM, border = 0)
  1665. sizerP.Add(self.gridBagSizerP, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  1666. gridBagSizer.Add(sizerP, pos = (2,0),span = (1,1), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
  1667. # second box - map coordinates
  1668. box2 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
  1669. sizerM = wx.StaticBoxSizer(box2, wx.VERTICAL)
  1670. self.gridBagSizerM = wx.GridBagSizer (hgap = 5, vgap = 5)
  1671. self.gridBagSizerM.AddGrowableCol(0)
  1672. self.gridBagSizerM.AddGrowableCol(1)
  1673. eastingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "E:")
  1674. northingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "N:")
  1675. panel.position['eCtrl'] = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  1676. panel.position['nCtrl'] = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  1677. east, north = PaperMapCoordinates(map = self.instruction[self.mapId], x = dialogDict['where'][0], y = dialogDict['where'][1], paperToMap = True)
  1678. panel.position['eCtrl'].SetValue(str(east))
  1679. panel.position['nCtrl'].SetValue(str(north))
  1680. self.gridBagSizerM.Add(eastingLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1681. self.gridBagSizerM.Add(northingLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1682. self.gridBagSizerM.Add(panel.position['eCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1683. self.gridBagSizerM.Add(panel.position['nCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1684. sizerM.Add(self.gridBagSizerM, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  1685. gridBagSizer.Add(sizerM, pos = (2,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
  1686. def AddFont(self, parent, dialogDict, color = True):
  1687. parent.font = dict()
  1688. ## parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose font:"))
  1689. ## parent.font['fontCtrl'] = wx.FontPickerCtrl(parent, id = wx.ID_ANY)
  1690. ##
  1691. ## parent.font['fontCtrl'].SetSelectedFont(
  1692. ## wx.FontFromNativeInfoString(dialogDict['font'] + " " + str(dialogDict['fontsize'])))
  1693. ## parent.font['fontCtrl'].SetMaxPointSize(50)
  1694. ##
  1695. ## if color:
  1696. ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:"))
  1697. ## parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL)
  1698. ## parent.font['colorCtrl'].SetColour(dialogDict['color'])
  1699. ## parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color']))
  1700. parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font:"))
  1701. parent.font['fontSizeLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font size:"))
  1702. fontChoices = [ 'Times-Roman', 'Times-Italic', 'Times-Bold', 'Times-BoldItalic', 'Helvetica',\
  1703. 'Helvetica-Oblique', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Courier',\
  1704. 'Courier-Oblique', 'Courier-Bold', 'Courier-BoldOblique']
  1705. parent.font['fontCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = fontChoices)
  1706. if dialogDict['font'] in fontChoices:
  1707. parent.font['fontCtrl'].SetStringSelection(dialogDict['font'])
  1708. else:
  1709. parent.font['fontCtrl'].SetStringSelection('Helvetica')
  1710. parent.font['fontSizeCtrl'] = wx.SpinCtrl(parent, id = wx.ID_ANY, min = 4, max = 50, initial = 10)
  1711. parent.font['fontSizeCtrl'].SetValue(dialogDict['fontsize'])
  1712. if color:
  1713. parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:"))
  1714. parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY)
  1715. parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color']))
  1716. ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Color:"))
  1717. ## colorChoices = [ 'aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'green', 'indigo', 'magenta',\
  1718. ## 'orange', 'purple', 'red', 'violet', 'white', 'yellow']
  1719. ## parent.colorCtrl = wx.Choice(parent, id = wx.ID_ANY, choices = colorChoices)
  1720. ## parent.colorCtrl.SetStringSelection(parent.rLegendDict['color'])
  1721. ## parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY)
  1722. ## parent.font['colorCtrl'].SetColour(dialogDict['color'])
  1723. def OnApply(self, event):
  1724. ok = self.update()
  1725. if ok:
  1726. self.parent.DialogDataChanged(id = self.id)
  1727. return True
  1728. else:
  1729. return False
  1730. def OnOK(self, event):
  1731. """!Apply changes, close dialog"""
  1732. ok = self.OnApply(event)
  1733. if ok:
  1734. self.Close()
  1735. def OnCancel(self, event):
  1736. """!Close dialog"""
  1737. self.Close()
  1738. def OnClose(self, event):
  1739. """!Destroy dialog and delete it from open dialogs"""
  1740. if self.objectType:
  1741. for each in self.objectType:
  1742. if each in self.parent.openDialogs:
  1743. del self.parent.openDialogs[each]
  1744. event.Skip()
  1745. self.Destroy()
  1746. def _layout(self, panel):
  1747. #buttons
  1748. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1749. btnOK = wx.Button(self, wx.ID_OK)
  1750. btnOK.SetDefault()
  1751. if self.apply:
  1752. btnApply = wx.Button(self, wx.ID_APPLY)
  1753. # bindigs
  1754. btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
  1755. btnOK.SetToolTipString(_("Close dialog and apply changes"))
  1756. #btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1757. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1758. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1759. if self.apply:
  1760. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1761. btnApply.SetToolTipString(_("Apply changes"))
  1762. # sizers
  1763. btnSizer = wx.StdDialogButtonSizer()
  1764. btnSizer.AddButton(btnCancel)
  1765. if self.apply:
  1766. btnSizer.AddButton(btnApply)
  1767. btnSizer.AddButton(btnOK)
  1768. btnSizer.Realize()
  1769. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1770. mainSizer.Add(item = panel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  1771. mainSizer.Add(item = btnSizer, proportion = 0,
  1772. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  1773. self.SetSizer(mainSizer)
  1774. mainSizer.Layout()
  1775. mainSizer.Fit(self)
  1776. class PageSetupDialog(PsmapDialog):
  1777. def __init__(self, parent, id, settings):
  1778. PsmapDialog.__init__(self, parent = parent, id = id, title = "Page setup", settings = settings)
  1779. self.cat = ['Units', 'Format', 'Orientation', 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
  1780. labels = [_('Units'), _('Format'), _('Orientation'), _('Width'), _('Height'),
  1781. _('Left'), _('Right'), _('Top'), _('Bottom')]
  1782. self.catsLabels = dict(zip(self.cat, labels))
  1783. paperString = RunCommand('ps.map', flags = 'p', read = True, quiet = True)
  1784. self.paperTable = self._toList(paperString)
  1785. self.unitsList = self.unitConv.getPageUnitsNames()
  1786. self.pageSetupDict = settings[id].GetInstruction()
  1787. self._layout()
  1788. if self.pageSetupDict:
  1789. self.getCtrl('Units').SetStringSelection(self.unitConv.findName(self.pageSetupDict['Units']))
  1790. if self.pageSetupDict['Format'] == 'custom':
  1791. self.getCtrl('Format').SetSelection(self.getCtrl('Format').GetCount() - 1)
  1792. else:
  1793. self.getCtrl('Format').SetStringSelection(self.pageSetupDict['Format'])
  1794. if self.pageSetupDict['Orientation'] == 'Portrait':
  1795. self.getCtrl('Orientation').SetSelection(0)
  1796. else:
  1797. self.getCtrl('Orientation').SetSelection(1)
  1798. for item in self.cat[3:]:
  1799. val = self.unitConv.convert(value = self.pageSetupDict[item],
  1800. fromUnit = 'inch', toUnit = self.pageSetupDict['Units'])
  1801. self.getCtrl(item).SetValue("%4.3f" % val)
  1802. if self.getCtrl('Format').GetSelection() != self.getCtrl('Format').GetCount() - 1: # custom
  1803. self.getCtrl('Width').Disable()
  1804. self.getCtrl('Height').Disable()
  1805. else:
  1806. self.getCtrl('Orientation').Disable()
  1807. # events
  1808. self.getCtrl('Units').Bind(wx.EVT_CHOICE, self.OnChoice)
  1809. self.getCtrl('Format').Bind(wx.EVT_CHOICE, self.OnChoice)
  1810. self.getCtrl('Orientation').Bind(wx.EVT_CHOICE, self.OnChoice)
  1811. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOK)
  1812. def update(self):
  1813. self.pageSetupDict['Units'] = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection())
  1814. self.pageSetupDict['Format'] = self.paperTable[self.getCtrl('Format').GetSelection()]['Format']
  1815. if self.getCtrl('Orientation').GetSelection() == 0:
  1816. self.pageSetupDict['Orientation'] = 'Portrait'
  1817. else:
  1818. self.pageSetupDict['Orientation'] = 'Landscape'
  1819. for item in self.cat[3:]:
  1820. self.pageSetupDict[item] = self.unitConv.convert(value = float(self.getCtrl(item).GetValue()),
  1821. fromUnit = self.pageSetupDict['Units'], toUnit = 'inch')
  1822. def OnOK(self, event):
  1823. try:
  1824. self.update()
  1825. except ValueError:
  1826. wx.MessageBox(message = _("Literal is not allowed!"), caption = _('Invalid input'),
  1827. style = wx.OK|wx.ICON_ERROR)
  1828. else:
  1829. event.Skip()
  1830. def _layout(self):
  1831. size = (110,-1)
  1832. #sizers
  1833. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1834. pageBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Page size"))
  1835. pageSizer = wx.StaticBoxSizer(pageBox, wx.VERTICAL)
  1836. marginBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Margins"))
  1837. marginSizer = wx.StaticBoxSizer(marginBox, wx.VERTICAL)
  1838. horSizer = wx.BoxSizer(wx.HORIZONTAL)
  1839. #staticText + choice
  1840. choices = [self.unitsList, [item['Format'] for item in self.paperTable], [_('Portrait'), _('Landscape')]]
  1841. propor = [0,1,1]
  1842. border = [5,3,3]
  1843. self.hBoxDict={}
  1844. for i, item in enumerate(self.cat[:3]):
  1845. hBox = wx.BoxSizer(wx.HORIZONTAL)
  1846. stText = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':')
  1847. choice = wx.Choice(self, id = wx.ID_ANY, choices = choices[i], size = size)
  1848. hBox.Add(stText, proportion = propor[i], flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = border[i])
  1849. hBox.Add(choice, proportion = 0, flag = wx.ALL, border = border[i])
  1850. if item == 'Units':
  1851. hBox.Add(size,1)
  1852. self.hBoxDict[item] = hBox
  1853. #staticText + TextCtrl
  1854. for item in self.cat[3:]:
  1855. hBox = wx.BoxSizer(wx.HORIZONTAL)
  1856. label = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':')
  1857. textctrl = wx.TextCtrl(self, id = wx.ID_ANY, size = size, value = '')
  1858. hBox.Add(label, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3)
  1859. hBox.Add(textctrl, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 3)
  1860. self.hBoxDict[item] = hBox
  1861. sizer = list([mainSizer] + [pageSizer]*4 + [marginSizer]*4)
  1862. for i, item in enumerate(self.cat):
  1863. sizer[i].Add(self.hBoxDict[item], 0, wx.GROW|wx.RIGHT|wx.LEFT,5)
  1864. # OK button
  1865. btnSizer = wx.StdDialogButtonSizer()
  1866. self.btnOk = wx.Button(self, wx.ID_OK)
  1867. self.btnOk.SetDefault()
  1868. btnSizer.AddButton(self.btnOk)
  1869. btn = wx.Button(self, wx.ID_CANCEL)
  1870. btnSizer.AddButton(btn)
  1871. btnSizer.Realize()
  1872. horSizer.Add(pageSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM, border = 10)
  1873. horSizer.Add(marginSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border = 10)
  1874. mainSizer.Add(horSizer, proportion = 0, border = 10)
  1875. mainSizer.Add(btnSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT|wx.ALL, border = 10)
  1876. self.SetSizer(mainSizer)
  1877. mainSizer.Fit(self)
  1878. def OnChoice(self, event):
  1879. currPaper = self.paperTable[self.getCtrl('Format').GetSelection()]
  1880. currUnit = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection())
  1881. currOrientIdx = self.getCtrl('Orientation').GetSelection()
  1882. newSize = dict()
  1883. for item in self.cat[3:]:
  1884. newSize[item] = self.unitConv.convert(float(currPaper[item]), fromUnit = 'inch', toUnit = currUnit)
  1885. enable = True
  1886. if currPaper['Format'] != _('custom'):
  1887. if currOrientIdx == 1: # portrait
  1888. newSize['Width'], newSize['Height'] = newSize['Height'], newSize['Width']
  1889. for item in self.cat[3:]:
  1890. self.getCtrl(item).ChangeValue("%4.3f" % newSize[item])
  1891. enable = False
  1892. self.getCtrl('Width').Enable(enable)
  1893. self.getCtrl('Height').Enable(enable)
  1894. self.getCtrl('Orientation').Enable(not enable)
  1895. def getCtrl(self, item):
  1896. return self.hBoxDict[item].GetItem(1).GetWindow()
  1897. def _toList(self, paperStr):
  1898. sizeList = list()
  1899. for line in paperStr.strip().split('\n'):
  1900. d = dict(zip([self.cat[1]]+ self.cat[3:],line.split()))
  1901. sizeList.append(d)
  1902. d = {}.fromkeys([self.cat[1]]+ self.cat[3:], 100)
  1903. d.update(Format = _('custom'))
  1904. sizeList.append(d)
  1905. return sizeList
  1906. class MapDialog(PsmapDialog):
  1907. """!Dialog for map frame settings and optionally raster and vector map selection"""
  1908. def __init__(self, parent, id, settings, rect = None, notebook = False):
  1909. PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings)
  1910. self.isNotebook = notebook
  1911. if self.isNotebook:
  1912. self.objectType = ('mapNotebook',)
  1913. else:
  1914. self.objectType = ('map',)
  1915. #notebook
  1916. if self.isNotebook:
  1917. self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  1918. self.mPanel = MapFramePanel(parent = self.notebook, id = self.id[0], settings = self.instruction,
  1919. rect = rect, notebook = True)
  1920. self.id[0] = self.mPanel.getId()
  1921. self.rPanel = RasterPanel(parent = self.notebook, id = self.id[1], settings = self.instruction,
  1922. notebook = True)
  1923. self.id[1] = self.rPanel.getId()
  1924. self.vPanel = VectorPanel(parent = self.notebook, id = self.id[2], settings = self.instruction,
  1925. notebook = True)
  1926. self.id[2] = self.vPanel.getId()
  1927. self._layout(self.notebook)
  1928. self.SetTitle(_("Map settings"))
  1929. else:
  1930. self.mPanel = MapFramePanel(parent = self, id = self.id[0], settings = self.instruction,
  1931. rect = rect, notebook = False)
  1932. self.id[0] = self.mPanel.getId()
  1933. self._layout(self.mPanel)
  1934. self.SetTitle(_("Map frame settings"))
  1935. def OnApply(self, event):
  1936. """!Apply changes"""
  1937. if self.isNotebook:
  1938. okV = self.vPanel.update()
  1939. okR = self.rPanel.update()
  1940. if okV and self.id[2] in self.instruction:
  1941. self.parent.DialogDataChanged(id = self.id[2])
  1942. if okR and self.id[1] in self.instruction:
  1943. self.parent.DialogDataChanged(id = self.id[1])
  1944. if not okR or not okV:
  1945. return False
  1946. ok = self.mPanel.update()
  1947. if ok:
  1948. self.parent.DialogDataChanged(id = self.id[0])
  1949. return True
  1950. return False
  1951. def OnCancel(self, event):
  1952. """!Close dialog and remove tmp red box"""
  1953. self.parent.canvas.pdcTmp.RemoveId(self.parent.canvas.idZoomBoxTmp)
  1954. self.parent.canvas.Refresh()
  1955. self.Close()
  1956. def updateDialog(self):
  1957. """!Update raster and vector information"""
  1958. if self.mPanel.scaleChoice.GetSelection() == 0:
  1959. if self.mPanel.rasterTypeRadio.GetValue():
  1960. if 'raster' in self.parent.openDialogs:
  1961. if self.parent.openDialogs['raster'].rPanel.rasterYesRadio.GetValue() and \
  1962. self.parent.openDialogs['raster'].rPanel.rasterSelect.GetValue() == self.mPanel.select.GetValue():
  1963. self.mPanel.drawMap.SetValue(True)
  1964. else:
  1965. self.mPanel.drawMap.SetValue(False)
  1966. else:
  1967. if 'vector' in self.parent.openDialogs:
  1968. found = False
  1969. for each in self.parent.openDialogs['vector'].vPanel.vectorList:
  1970. if each[0] == self.mPanel.select.GetValue():
  1971. found = True
  1972. self.mPanel.drawMap.SetValue(found)
  1973. class MapFramePanel(wx.Panel):
  1974. """!wx.Panel with map (scale, region, border) settings"""
  1975. def __init__(self, parent, id, settings, rect, notebook = True):
  1976. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  1977. self.id = id
  1978. self.instruction = settings
  1979. if notebook:
  1980. self.book = parent
  1981. self.book.AddPage(page = self, text = _("Map frame"))
  1982. self.mapDialog = self.book.GetParent()
  1983. else:
  1984. self.mapDialog = parent
  1985. if self.id is not None:
  1986. self.mapFrameDict = self.instruction[self.id].GetInstruction()
  1987. else:
  1988. self.id = wx.NewId()
  1989. mapFrame = MapFrame(self.id)
  1990. self.mapFrameDict = mapFrame.GetInstruction()
  1991. self.mapFrameDict['rect'] = rect
  1992. self._layout()
  1993. self.scale = [None]*4
  1994. self.center = [None]*4
  1995. self.selectedMap = self.mapFrameDict['map']
  1996. self.selectedRegion = self.mapFrameDict['region']
  1997. self.scaleType = self.mapFrameDict['scaleType']
  1998. self.mapType = self.mapFrameDict['mapType']
  1999. self.scaleChoice.SetSelection(self.mapFrameDict['scaleType'])
  2000. if self.instruction[self.id]:
  2001. self.drawMap.SetValue(self.mapFrameDict['drawMap'])
  2002. else:
  2003. self.drawMap.SetValue(True)
  2004. if self.mapFrameDict['scaleType'] == 0 and self.mapFrameDict['map']:
  2005. self.select.SetValue(self.mapFrameDict['map'])
  2006. if self.mapFrameDict['mapType'] == 'raster':
  2007. self.rasterTypeRadio.SetValue(True)
  2008. self.vectorTypeRadio.SetValue(False)
  2009. else:
  2010. self.rasterTypeRadio.SetValue(False)
  2011. self.vectorTypeRadio.SetValue(True)
  2012. elif self.mapFrameDict['scaleType'] == 1 and self.mapFrameDict['region']:
  2013. self.select.SetValue(self.mapFrameDict['region'])
  2014. self.OnMap(None)
  2015. self.scale[self.mapFrameDict['scaleType']] = self.mapFrameDict['scale']
  2016. self.center[self.mapFrameDict['scaleType']] = self.mapFrameDict['center']
  2017. self.OnScaleChoice(None)
  2018. self.OnElementType(None)
  2019. self.OnBorder(None)
  2020. def _layout(self):
  2021. """!Do layout"""
  2022. border = wx.BoxSizer(wx.VERTICAL)
  2023. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map frame"))
  2024. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2025. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2026. #scale options
  2027. frameText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map frame options:"))
  2028. scaleChoices = [_("fit frame to match selected map"),
  2029. _("fit frame to match saved region"),
  2030. _("fit frame to match current computational region"),
  2031. _("fixed scale and map center")]
  2032. self.scaleChoice = wx.Choice(self, id = wx.ID_ANY, choices = scaleChoices)
  2033. gridBagSizer.Add(frameText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2034. gridBagSizer.Add(self.scaleChoice, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2035. #map and region selection
  2036. self.staticBox = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map selection"))
  2037. sizerM = wx.StaticBoxSizer(self.staticBox, wx.HORIZONTAL)
  2038. self.mapSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2039. self.rasterTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("raster"), style = wx.RB_GROUP)
  2040. self.vectorTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("vector"))
  2041. self.drawMap = wx.CheckBox(self, id = wx.ID_ANY, label = "add selected map")
  2042. self.mapOrRegionText = [_("Map:"), _("Region:")]
  2043. dc = wx.ClientDC(self)# determine size of labels
  2044. width = max(dc.GetTextExtent(self.mapOrRegionText[0])[0], dc.GetTextExtent(self.mapOrRegionText[1])[0])
  2045. self.mapText = wx.StaticText(self, id = wx.ID_ANY, label = self.mapOrRegionText[0], size = (width, -1))
  2046. self.select = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  2047. type = 'raster', multiple = False,
  2048. updateOnPopup = True, onPopup = None)
  2049. self.mapSizer.Add(self.rasterTypeRadio, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2050. self.mapSizer.Add(self.vectorTypeRadio, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2051. self.mapSizer.Add(self.drawMap, pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2052. self.mapSizer.Add(self.mapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2053. self.mapSizer.Add(self.select, pos = (1, 1), span = (1, 3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2054. sizerM.Add(self.mapSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2055. gridBagSizer.Add(sizerM, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2056. #map scale and center
  2057. boxC = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map scale and center"))
  2058. sizerC = wx.StaticBoxSizer(boxC, wx.HORIZONTAL)
  2059. self.centerSizer = wx.FlexGridSizer(rows = 2, cols = 5, hgap = 5, vgap = 5)
  2060. centerText = wx.StaticText(self, id = wx.ID_ANY, label = _("Center:"))
  2061. self.eastingText = wx.StaticText(self, id = wx.ID_ANY, label = _("E:"))
  2062. self.northingText = wx.StaticText(self, id = wx.ID_ANY, label = _("N:"))
  2063. self.eastingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY'))
  2064. self.northingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY'))
  2065. scaleText = wx.StaticText(self, id = wx.ID_ANY, label = _("Scale:"))
  2066. scalePrefixText = wx.StaticText(self, id = wx.ID_ANY, label = _("1 :"))
  2067. self.scaleTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, value = "", style = wx.TE_RIGHT, validator = TCValidator('DIGIT_ONLY'))
  2068. self.centerSizer.Add(centerText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10)
  2069. self.centerSizer.Add(self.eastingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2070. self.centerSizer.Add(self.eastingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2071. self.centerSizer.Add(self.northingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2072. self.centerSizer.Add(self.northingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2073. self.centerSizer.Add(scaleText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10)
  2074. self.centerSizer.Add(scalePrefixText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2075. self.centerSizer.Add(self.scaleTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2076. sizerC.Add(self.centerSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2077. gridBagSizer.Add(sizerC, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2078. #resolution
  2079. flexSizer = wx.FlexGridSizer(rows = 1, cols = 2, hgap = 5, vgap = 5)
  2080. resolutionText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map max resolution (dpi):"))
  2081. self.resolutionSpin = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 1000, initial = 300)
  2082. flexSizer.Add(resolutionText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2083. flexSizer.Add(self.resolutionSpin, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2084. self.resolutionSpin.SetValue(self.mapFrameDict['resolution'])
  2085. gridBagSizer.Add(flexSizer, pos = (4, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2086. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2087. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2088. # border
  2089. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Border"))
  2090. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2091. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2092. self.borderCheck = wx.CheckBox(self, id = wx.ID_ANY, label = (_("draw border around map frame")))
  2093. if self.mapFrameDict['border'] == 'y':
  2094. self.borderCheck.SetValue(True)
  2095. else:
  2096. self.borderCheck.SetValue(False)
  2097. self.borderColorText = wx.StaticText(self, id = wx.ID_ANY, label = _("border color:"))
  2098. self.borderWidthText = wx.StaticText(self, id = wx.ID_ANY, label = _("border width (pts):"))
  2099. self.borderColourPicker = wx.ColourPickerCtrl(self, id = wx.ID_ANY)
  2100. self.borderWidthCtrl = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 100, initial = 1)
  2101. if self.mapFrameDict['border'] == 'y':
  2102. self.borderWidthCtrl.SetValue(int(self.mapFrameDict['width']))
  2103. self.borderColourPicker.SetColour(convertRGB(self.mapFrameDict['color']))
  2104. gridBagSizer.Add(self.borderCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2105. gridBagSizer.Add(self.borderColorText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2106. gridBagSizer.Add(self.borderWidthText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2107. gridBagSizer.Add(self.borderColourPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2108. gridBagSizer.Add(self.borderWidthCtrl, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2109. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2110. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2111. self.SetSizer(border)
  2112. self.Fit()
  2113. if projInfo()['proj'] == 'll':
  2114. self.scaleChoice.SetItems(self.scaleChoice.GetItems()[0:3])
  2115. boxC.Hide()
  2116. for each in self.centerSizer.GetChildren():
  2117. each.GetWindow().Hide()
  2118. # bindings
  2119. self.scaleChoice.Bind(wx.EVT_CHOICE, self.OnScaleChoice)
  2120. self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnMap)
  2121. self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.vectorTypeRadio)
  2122. self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.rasterTypeRadio)
  2123. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
  2124. def OnMap(self, event):
  2125. """!Selected map or region changing"""
  2126. if self.select.GetValue():
  2127. self.selected = self.select.GetValue()
  2128. else:
  2129. self.selected = None
  2130. if self.scaleChoice.GetSelection() == 0:
  2131. self.selectedMap = self.selected
  2132. if self.rasterTypeRadio.GetValue():
  2133. mapType = 'raster'
  2134. else:
  2135. mapType = 'vector'
  2136. self.scale[0], self.center[0], foo = AutoAdjust(self, scaleType = 0, map = self.selected,
  2137. mapType = mapType, rect = self.mapFrameDict['rect'])
  2138. #self.center[0] = self.RegionCenter(self.RegionDict(scaleType = 0))
  2139. elif self.scaleChoice.GetSelection() == 1:
  2140. self.selectedRegion = self.selected
  2141. self.scale[1], self.center[1], foo = AutoAdjust(self, scaleType = 1, region = self.selected, rect = self.mapFrameDict['rect'])
  2142. #self.center[1] = self.RegionCenter(self.RegionDict(scaleType = 1))
  2143. elif self.scaleChoice.GetSelection() == 2:
  2144. self.scale[2], self.center[2], foo = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect'])
  2145. #self.center[2] = self.RegionCenter(self.RegionDict(scaleType = 2))
  2146. else:
  2147. self.scale[3] = None
  2148. self.center[3] = None
  2149. self.OnScaleChoice(None)
  2150. def OnScaleChoice(self, event):
  2151. """!Selected scale type changing"""
  2152. scaleType = self.scaleChoice.GetSelection()
  2153. if self.scaleType != scaleType:
  2154. self.scaleType = scaleType
  2155. self.select.SetValue("")
  2156. if scaleType in (0, 1): # automatic - region from raster map, saved region
  2157. if scaleType == 0:
  2158. # set map selection
  2159. self.rasterTypeRadio.Show()
  2160. self.vectorTypeRadio.Show()
  2161. self.drawMap.Show()
  2162. self.staticBox.SetLabel(" %s " % _("Map selection"))
  2163. if self.rasterTypeRadio.GetValue():
  2164. stype = 'raster'
  2165. else:
  2166. stype = 'vector'
  2167. self.select.SetElementList(type = stype)
  2168. self.mapText.SetLabel(self.mapOrRegionText[0])
  2169. self.select.SetToolTipString(_("Region is set to match this map,\nraster or vector map must be added later"))
  2170. if scaleType == 1:
  2171. # set region selection
  2172. self.rasterTypeRadio.Hide()
  2173. self.vectorTypeRadio.Hide()
  2174. self.drawMap.Hide()
  2175. self.staticBox.SetLabel(" %s " % _("Region selection"))
  2176. stype = 'region'
  2177. self.select.SetElementList(type = stype)
  2178. self.mapText.SetLabel(self.mapOrRegionText[1])
  2179. self.select.SetToolTipString("")
  2180. for each in self.mapSizer.GetChildren():
  2181. each.GetWindow().Enable()
  2182. for each in self.centerSizer.GetChildren():
  2183. each.GetWindow().Disable()
  2184. if self.scale[scaleType]:
  2185. self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
  2186. if self.center[scaleType]:
  2187. self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
  2188. self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
  2189. elif scaleType == 2:
  2190. for each in self.mapSizer.GetChildren():
  2191. each.GetWindow().Disable()
  2192. for each in self.centerSizer.GetChildren():
  2193. each.GetWindow().Disable()
  2194. if self.scale[scaleType]:
  2195. self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
  2196. if self.center[scaleType]:
  2197. self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
  2198. self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
  2199. else: # fixed
  2200. for each in self.mapSizer.GetChildren():
  2201. each.GetWindow().Disable()
  2202. for each in self.centerSizer.GetChildren():
  2203. each.GetWindow().Enable()
  2204. if self.scale[scaleType]:
  2205. self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
  2206. if self.center[scaleType]:
  2207. self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
  2208. self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
  2209. def OnElementType(self, event):
  2210. """!Changes data in map selection tree ctrl popup"""
  2211. if self.rasterTypeRadio.GetValue():
  2212. mapType = 'raster'
  2213. else:
  2214. mapType = 'vector'
  2215. self.select.SetElementList(type = mapType)
  2216. if self.mapType != mapType and event is not None:
  2217. self.mapType = mapType
  2218. self.select.SetValue('')
  2219. self.mapType = mapType
  2220. def OnBorder(self, event):
  2221. """!Enables/disable the part relating to border of map frame"""
  2222. for each in (self.borderColorText, self.borderWidthText, self.borderColourPicker, self.borderWidthCtrl):
  2223. each.Enable(self.borderCheck.GetValue())
  2224. def getId(self):
  2225. """!Returns id of raster map"""
  2226. return self.id
  2227. def update(self):
  2228. """!Save changes"""
  2229. mapFrameDict = dict(self.mapFrameDict)
  2230. # resolution
  2231. mapFrameDict['resolution'] = self.resolutionSpin.GetValue()
  2232. #scale
  2233. scaleType = self.scaleType
  2234. mapFrameDict['scaleType'] = scaleType
  2235. if mapFrameDict['scaleType'] == 0:
  2236. if self.select.GetValue():
  2237. mapFrameDict['drawMap'] = self.drawMap.GetValue()
  2238. mapFrameDict['map'] = self.select.GetValue()
  2239. mapFrameDict['mapType'] = self.mapType
  2240. mapFrameDict['region'] = None
  2241. if mapFrameDict['drawMap']:
  2242. if mapFrameDict['mapType'] == 'raster':
  2243. mapFile = grass.find_file(mapFrameDict['map'], element = 'cell')
  2244. if mapFile['file'] == '':
  2245. GMessage("Raster %s not found" % mapFrameDict['map'])
  2246. return False
  2247. raster = self.instruction.FindInstructionByType('raster')
  2248. if raster:
  2249. raster['raster'] = mapFrameDict['map']
  2250. else:
  2251. raster = Raster(wx.NewId())
  2252. raster['raster'] = mapFrameDict['map']
  2253. raster['isRaster'] = True
  2254. self.instruction.AddInstruction(raster)
  2255. elif mapFrameDict['mapType'] == 'vector':
  2256. mapFile = grass.find_file(mapFrameDict['map'], element = 'vector')
  2257. if mapFile['file'] == '':
  2258. GMessage("Vector %s not found" % mapFrameDict['map'])
  2259. return False
  2260. vector = self.instruction.FindInstructionByType('vector')
  2261. isAdded = False
  2262. if vector:
  2263. for each in vector['list']:
  2264. if each[0] == mapFrameDict['map']:
  2265. isAdded = True
  2266. if not isAdded:
  2267. topoInfo = grass.vector_info_topo(map = mapFrameDict['map'])
  2268. if topoInfo:
  2269. if bool(topoInfo['areas']):
  2270. topoType = 'areas'
  2271. elif bool(topoInfo['lines']):
  2272. topoType = 'lines'
  2273. else:
  2274. topoType = 'points'
  2275. label = '('.join(mapFrameDict['map'].split('@')) + ')'
  2276. if not vector:
  2277. vector = Vector(wx.NewId())
  2278. vector['list'] = []
  2279. self.instruction.AddInstruction(vector)
  2280. id = wx.NewId()
  2281. vector['list'].insert(0, [mapFrameDict['map'], topoType, id, 1, label])
  2282. vProp = VProperties(id, topoType)
  2283. vProp['name'], vProp['label'], vProp['lpos'] = mapFrameDict['map'], label, 1
  2284. self.instruction.AddInstruction(vProp)
  2285. else:
  2286. return False
  2287. self.scale[0], self.center[0], self.rectAdjusted = AutoAdjust(self, scaleType = 0, map = mapFrameDict['map'],
  2288. mapType = self.mapType, rect = self.mapFrameDict['rect'])
  2289. if self.rectAdjusted:
  2290. mapFrameDict['rect'] = self.rectAdjusted
  2291. else:
  2292. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2293. mapFrameDict['scale'] = self.scale[0]
  2294. mapFrameDict['center'] = self.center[0]
  2295. # set region
  2296. if self.mapType == 'raster':
  2297. RunCommand('g.region', rast = mapFrameDict['map'])
  2298. if self.mapType == 'vector':
  2299. raster = self.instruction.FindInstructionByType('raster')
  2300. if raster:
  2301. rasterId = raster.id
  2302. else:
  2303. rasterId = None
  2304. if rasterId:
  2305. RunCommand('g.region', vect = mapFrameDict['map'], rast = self.instruction[rasterId]['raster'])
  2306. else:
  2307. RunCommand('g.region', vect = mapFrameDict['map'])
  2308. else:
  2309. wx.MessageBox(message = _("No map selected!"),
  2310. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  2311. return False
  2312. elif mapFrameDict['scaleType'] == 1:
  2313. if self.select.GetValue():
  2314. mapFrameDict['drawMap'] = False
  2315. mapFrameDict['map'] = None
  2316. mapFrameDict['mapType'] = None
  2317. mapFrameDict['region'] = self.select.GetValue()
  2318. self.scale[1], self.center[1], self.rectAdjusted = AutoAdjust(self, scaleType = 1, region = mapFrameDict['region'],
  2319. rect = self.mapFrameDict['rect'])
  2320. if self.rectAdjusted:
  2321. mapFrameDict['rect'] = self.rectAdjusted
  2322. else:
  2323. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2324. mapFrameDict['scale'] = self.scale[1]
  2325. mapFrameDict['center'] = self.center[1]
  2326. # set region
  2327. RunCommand('g.region', region = mapFrameDict['region'])
  2328. else:
  2329. wx.MessageBox(message = _("No region selected!"),
  2330. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  2331. return False
  2332. elif scaleType == 2:
  2333. mapFrameDict['drawMap'] = False
  2334. mapFrameDict['map'] = None
  2335. mapFrameDict['mapType'] = None
  2336. mapFrameDict['region'] = None
  2337. self.scale[2], self.center[2], self.rectAdjusted = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect'])
  2338. if self.rectAdjusted:
  2339. mapFrameDict['rect'] = self.rectAdjusted
  2340. else:
  2341. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2342. mapFrameDict['scale'] = self.scale[2]
  2343. mapFrameDict['center'] = self.center[2]
  2344. env = grass.gisenv()
  2345. windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND')
  2346. try:
  2347. windFile = open(windFilePath, 'r').read()
  2348. region = grass.parse_key_val(windFile, sep = ':', val_type = float)
  2349. except IOError:
  2350. region = grass.region()
  2351. raster = self.instruction.FindInstructionByType('raster')
  2352. if raster:
  2353. rasterId = raster.id
  2354. else:
  2355. rasterId = None
  2356. if rasterId: # because of resolution
  2357. RunCommand('g.region', n = region['north'], s = region['south'],
  2358. e = region['east'], w = region['west'], rast = self.instruction[rasterId]['raster'])
  2359. else:
  2360. RunCommand('g.region', n = region['north'], s = region['south'],
  2361. e = region['east'], w = region['west'])
  2362. elif scaleType == 3:
  2363. mapFrameDict['drawMap'] = False
  2364. mapFrameDict['map'] = None
  2365. mapFrameDict['mapType'] = None
  2366. mapFrameDict['region'] = None
  2367. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2368. try:
  2369. scaleNumber = float(self.scaleTextCtrl.GetValue())
  2370. centerE = float(self.eastingTextCtrl.GetValue())
  2371. centerN = float(self.northingTextCtrl.GetValue())
  2372. except (ValueError, SyntaxError):
  2373. wx.MessageBox(message = _("Invalid scale or map center!"),
  2374. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  2375. return False
  2376. mapFrameDict['scale'] = 1/scaleNumber
  2377. mapFrameDict['center'] = centerE, centerN
  2378. ComputeSetRegion(self, mapDict = mapFrameDict)
  2379. # check resolution
  2380. SetResolution(dpi = mapFrameDict['resolution'], width = mapFrameDict['rect'].width,
  2381. height = mapFrameDict['rect'].height)
  2382. # border
  2383. if self.borderCheck.GetValue():
  2384. mapFrameDict['border'] = 'y'
  2385. else:
  2386. mapFrameDict['border'] = 'n'
  2387. if mapFrameDict['border'] == 'y':
  2388. mapFrameDict['width'] = self.borderWidthCtrl.GetValue()
  2389. mapFrameDict['color'] = convertRGB(self.borderColourPicker.GetColour())
  2390. if self.id not in self.instruction:
  2391. mapFrame = MapFrame(self.id)
  2392. self.instruction.AddInstruction(mapFrame)
  2393. self.instruction[self.id].SetInstruction(mapFrameDict)
  2394. if self.id not in self.mapDialog.parent.objectId:
  2395. self.mapDialog.parent.objectId.insert(0, self.id)# map frame is drawn first
  2396. return True
  2397. class RasterPanel(wx.Panel):
  2398. """!Panel for raster map settings"""
  2399. def __init__(self, parent, id, settings, notebook = True):
  2400. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  2401. self.instruction = settings
  2402. if notebook:
  2403. self.book = parent
  2404. self.book.AddPage(page = self, text = _("Raster map"))
  2405. self.mainDialog = self.book.GetParent()
  2406. else:
  2407. self.mainDialog = parent
  2408. if id:
  2409. self.id = id
  2410. self.rasterDict = self.instruction[self.id].GetInstruction()
  2411. else:
  2412. self.id = wx.NewId()
  2413. raster = Raster(self.id)
  2414. self.rasterDict = raster.GetInstruction()
  2415. self._layout()
  2416. self.OnRaster(None)
  2417. def _layout(self):
  2418. """!Do layout"""
  2419. border = wx.BoxSizer(wx.VERTICAL)
  2420. # choose raster map
  2421. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Choose raster map"))
  2422. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2423. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  2424. self.rasterNoRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("no raster map"), style = wx.RB_GROUP)
  2425. self.rasterYesRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("raster:"))
  2426. self.rasterSelect = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  2427. type = 'raster', multiple = False,
  2428. updateOnPopup = True, onPopup = None)
  2429. if self.rasterDict['isRaster']:
  2430. self.rasterYesRadio.SetValue(True)
  2431. self.rasterNoRadio.SetValue(False)
  2432. self.rasterSelect.SetValue(self.rasterDict['raster'])
  2433. else:
  2434. self.rasterYesRadio.SetValue(False)
  2435. self.rasterNoRadio.SetValue(True)
  2436. mapId = self.instruction.FindInstructionByType('map').id
  2437. if self.instruction[mapId]['map'] and self.instruction[mapId]['mapType'] == 'raster':
  2438. self.rasterSelect.SetValue(self.instruction[mapId]['map'])# raster map from map frame dialog if possible
  2439. else:
  2440. self.rasterSelect.SetValue('')
  2441. gridBagSizer.Add(self.rasterNoRadio, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2442. gridBagSizer.Add(self.rasterYesRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2443. gridBagSizer.Add(self.rasterSelect, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2444. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2445. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2446. #self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
  2447. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterNoRadio)
  2448. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterYesRadio)
  2449. self.SetSizer(border)
  2450. self.Fit()
  2451. def OnRaster(self, event):
  2452. """!Enable/disable raster selection"""
  2453. self.rasterSelect.Enable(self.rasterYesRadio.GetValue())
  2454. def update(self):
  2455. #draw raster
  2456. mapInstr = self.instruction.FindInstructionByType('map')
  2457. if not mapInstr: # no map frame
  2458. GMessage(message = _("Please, create map frame first."))
  2459. return
  2460. if self.rasterNoRadio.GetValue() or not self.rasterSelect.GetValue():
  2461. self.rasterDict['isRaster'] = False
  2462. self.rasterDict['raster'] = None
  2463. mapInstr['drawMap'] = False
  2464. if self.id in self.instruction:
  2465. del self.instruction[self.id]
  2466. else:
  2467. self.rasterDict['isRaster'] = True
  2468. self.rasterDict['raster'] = self.rasterSelect.GetValue()
  2469. if self.rasterDict['raster'] != mapInstr['drawMap']:
  2470. mapInstr['drawMap'] = False
  2471. raster = self.instruction.FindInstructionByType('raster')
  2472. if not raster:
  2473. raster = Raster(self.id)
  2474. self.instruction.AddInstruction(raster)
  2475. self.instruction[self.id].SetInstruction(self.rasterDict)
  2476. else:
  2477. self.instruction[raster.id].SetInstruction(self.rasterDict)
  2478. if 'map' in self.mainDialog.parent.openDialogs:
  2479. self.mainDialog.parent.openDialogs['map'].updateDialog()
  2480. return True
  2481. def getId(self):
  2482. return self.id
  2483. class VectorPanel(wx.Panel):
  2484. """!Panel for vector maps settings"""
  2485. def __init__(self, parent, id, settings, notebook = True):
  2486. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  2487. self.parent = parent
  2488. self.instruction = settings
  2489. self.tmpDialogDict = {}
  2490. vectors = self.instruction.FindInstructionByType('vProperties', list = True)
  2491. for vector in vectors:
  2492. self.tmpDialogDict[vector.id] = dict(self.instruction[vector.id].GetInstruction())
  2493. if id:
  2494. self.id = id
  2495. self.vectorList = deepcopy(self.instruction[id]['list'])
  2496. else:
  2497. self.id = wx.NewId()
  2498. self.vectorList = []
  2499. vLegend = self.instruction.FindInstructionByType('vectorLegend')
  2500. if vLegend:
  2501. self.vLegendId = vLegend.id
  2502. else:
  2503. self.vLegendId = None
  2504. self._layout()
  2505. if notebook:
  2506. self.parent.AddPage(page = self, text = _("Vector maps"))
  2507. self.parent = self.parent.GetParent()
  2508. def _layout(self):
  2509. """!Do layout"""
  2510. border = wx.BoxSizer(wx.VERTICAL)
  2511. # choose vector map
  2512. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Add map"))
  2513. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2514. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  2515. text = wx.StaticText(self, id = wx.ID_ANY, label = _("Map:"))
  2516. self.select = Select(self, id = wx.ID_ANY,# size = globalvar.DIALOG_GSELECT_SIZE,
  2517. type = 'vector', multiple = False,
  2518. updateOnPopup = True, onPopup = None)
  2519. topologyTypeTr = [_("points"), _("lines"), _("areas")]
  2520. self.topologyTypeList = ["points", "lines", "areas"]
  2521. self.vectorType = wx.RadioBox(self, id = wx.ID_ANY, label = " %s " % _("Data Type"), choices = topologyTypeTr,
  2522. majorDimension = 3, style = wx.RA_SPECIFY_COLS)
  2523. self.AddVector = wx.Button(self, id = wx.ID_ANY, label = _("Add"))
  2524. gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2525. gridBagSizer.Add(self.select, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2526. gridBagSizer.Add(self.vectorType, pos = (1,1), flag = wx.ALIGN_CENTER, border = 0)
  2527. gridBagSizer.Add(self.AddVector, pos = (1,2), flag = wx.ALIGN_BOTTOM|wx.ALIGN_RIGHT, border = 0)
  2528. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2529. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2530. # manage vector layers
  2531. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Manage vector maps"))
  2532. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2533. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  2534. gridBagSizer.AddGrowableCol(0,2)
  2535. gridBagSizer.AddGrowableCol(1,1)
  2536. text = wx.StaticText(self, id = wx.ID_ANY, label = _("The topmost vector map overlaps the others"))
  2537. self.listbox = wx.ListBox(self, id = wx.ID_ANY, choices = [], style = wx.LB_SINGLE|wx.LB_NEEDED_SB)
  2538. self.btnUp = wx.Button(self, id = wx.ID_ANY, label = _("Up"))
  2539. self.btnDown = wx.Button(self, id = wx.ID_ANY, label = _("Down"))
  2540. self.btnDel = wx.Button(self, id = wx.ID_ANY, label = _("Delete"))
  2541. self.btnProp = wx.Button(self, id = wx.ID_ANY, label = _("Properties..."))
  2542. self.updateListBox(selected=0)
  2543. gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2544. gridBagSizer.Add(self.listbox, pos = (1,0), span = (4, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2545. gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2546. gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2547. gridBagSizer.Add(self.btnDel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2548. gridBagSizer.Add(self.btnProp, pos = (4,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2549. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALL, border = 5)
  2550. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2551. self.Bind(wx.EVT_BUTTON, self.OnAddVector, self.AddVector)
  2552. self.Bind(wx.EVT_BUTTON, self.OnDelete, self.btnDel)
  2553. self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
  2554. self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
  2555. self.Bind(wx.EVT_BUTTON, self.OnProperties, self.btnProp)
  2556. self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnVector)
  2557. self.SetSizer(border)
  2558. self.Fit()
  2559. self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnProperties, self.listbox)
  2560. def OnVector(self, event):
  2561. """!Gets info about toplogy and enables/disables choices point/line/area"""
  2562. vmap = self.select.GetValue()
  2563. try:
  2564. topoInfo = grass.vector_info_topo(map = vmap)
  2565. except grass.ScriptError:
  2566. return
  2567. if topoInfo:
  2568. self.vectorType.EnableItem(2, bool(topoInfo['areas']))
  2569. self.vectorType.EnableItem(1, bool(topoInfo['boundaries']) or bool(topoInfo['lines']))
  2570. self.vectorType.EnableItem(0, bool(topoInfo['centroids'] or bool(topoInfo['points']) ))
  2571. for item in range(2,-1,-1):
  2572. if self.vectorType.IsItemEnabled(item):
  2573. self.vectorType.SetSelection(item)
  2574. break
  2575. self.AddVector.SetFocus()
  2576. def OnAddVector(self, event):
  2577. """!Adds vector map to list"""
  2578. vmap = self.select.GetValue()
  2579. if vmap:
  2580. mapname = vmap.split('@')[0]
  2581. try:
  2582. mapset = '(' + vmap.split('@')[1] + ')'
  2583. except IndexError:
  2584. mapset = ''
  2585. idx = self.vectorType.GetSelection()
  2586. ttype = self.topologyTypeList[idx]
  2587. record = "%s - %s" % (vmap, ttype)
  2588. id = wx.NewId()
  2589. lpos = 1
  2590. label = mapname + mapset
  2591. self.vectorList.insert(0, [vmap, ttype, id, lpos, label])
  2592. self.reposition()
  2593. self.listbox.InsertItems([record], 0)
  2594. vector = VProperties(id, ttype)
  2595. self.tmpDialogDict[id] = vector.GetInstruction()
  2596. self.tmpDialogDict[id]['name'] = vmap
  2597. self.listbox.SetSelection(0)
  2598. self.listbox.EnsureVisible(0)
  2599. self.btnProp.SetFocus()
  2600. self.enableButtons()
  2601. def OnDelete(self, event):
  2602. """!Deletes vector map from the list"""
  2603. if self.listbox.GetSelections():
  2604. pos = self.listbox.GetSelection()
  2605. id = self.vectorList[pos][2]
  2606. del self.vectorList[pos]
  2607. del self.tmpDialogDict[id]
  2608. for i in range(pos, len(self.vectorList)):
  2609. if self.vectorList[i][3]:# can be 0
  2610. self.vectorList[i][3] -= 1
  2611. if pos < len(self.vectorList) -1:
  2612. selected = pos
  2613. else:
  2614. selected = len(self.vectorList) -1
  2615. self.updateListBox(selected = selected)
  2616. if self.listbox.IsEmpty():
  2617. self.enableButtons(False)
  2618. def OnUp(self, event):
  2619. """!Moves selected map to top"""
  2620. if self.listbox.GetSelections():
  2621. pos = self.listbox.GetSelection()
  2622. if pos:
  2623. self.vectorList.insert(pos - 1, self.vectorList.pop(pos))
  2624. if not self.vLegendId:
  2625. self.reposition()
  2626. if pos > 0:
  2627. self.updateListBox(selected = (pos - 1))
  2628. else:
  2629. self.updateListBox(selected = 0)
  2630. def OnDown(self, event):
  2631. """!Moves selected map to bottom"""
  2632. if self.listbox.GetSelections():
  2633. pos = self.listbox.GetSelection()
  2634. if pos != len(self.vectorList) - 1:
  2635. self.vectorList.insert(pos + 1, self.vectorList.pop(pos))
  2636. if not self.vLegendId:
  2637. self.reposition()
  2638. if pos < len(self.vectorList) -1:
  2639. self.updateListBox(selected = (pos + 1))
  2640. else:
  2641. self.updateListBox(selected = len(self.vectorList) -1)
  2642. def OnProperties(self, event):
  2643. """!Opens vector map properties dialog"""
  2644. if self.listbox.GetSelections():
  2645. pos = self.listbox.GetSelection()
  2646. id = self.vectorList[pos][2]
  2647. dlg = VPropertiesDialog(self, id = id, settings = self.instruction,
  2648. vectors = self.vectorList, tmpSettings = self.tmpDialogDict[id])
  2649. dlg.ShowModal()
  2650. self.parent.FindWindowById(wx.ID_OK).SetFocus()
  2651. def enableButtons(self, enable = True):
  2652. """!Enable/disable up, down, properties, delete buttons"""
  2653. self.btnUp.Enable(enable)
  2654. self.btnDown.Enable(enable)
  2655. self.btnProp.Enable(enable)
  2656. self.btnDel.Enable(enable)
  2657. def updateListBox(self, selected = None):
  2658. mapList = ["%s - %s" % (item[0], item[1]) for item in self.vectorList]
  2659. self.listbox.Set(mapList)
  2660. if self.listbox.IsEmpty():
  2661. self.enableButtons(False)
  2662. else:
  2663. self.enableButtons(True)
  2664. if selected is not None:
  2665. self.listbox.SetSelection(selected)
  2666. self.listbox.EnsureVisible(selected)
  2667. def reposition(self):
  2668. """!Update position in legend, used only if there is no vlegend yet"""
  2669. for i in range(len(self.vectorList)):
  2670. if self.vectorList[i][3]:
  2671. self.vectorList[i][3] = i + 1
  2672. def getId(self):
  2673. return self.id
  2674. def update(self):
  2675. vectors = self.instruction.FindInstructionByType('vProperties', list = True)
  2676. for vector in vectors:
  2677. del self.instruction[vector.id]
  2678. if self.id in self.instruction:
  2679. del self.instruction[self.id]
  2680. if len(self.vectorList) > 0:
  2681. vector = Vector(self.id)
  2682. self.instruction.AddInstruction(vector)
  2683. vector.SetInstruction({'list': deepcopy(self.vectorList)})
  2684. # save new vectors
  2685. for item in self.vectorList:
  2686. id = item[2]
  2687. vLayer = VProperties(id, item[1])
  2688. self.instruction.AddInstruction(vLayer)
  2689. vLayer.SetInstruction(self.tmpDialogDict[id])
  2690. vLayer['name'] = item[0]
  2691. vLayer['label'] = item[4]
  2692. vLayer['lpos'] = item[3]
  2693. else:
  2694. if self.id in self.instruction:
  2695. del self.instruction[self.id]
  2696. if 'map' in self.parent.parent.openDialogs:
  2697. self.parent.parent.openDialogs['map'].updateDialog()
  2698. return True
  2699. class RasterDialog(PsmapDialog):
  2700. def __init__(self, parent, id, settings):
  2701. PsmapDialog.__init__(self, parent = parent, id = id, title = _("Raster map settings"), settings = settings)
  2702. self.objectType = ('raster',)
  2703. self.rPanel = RasterPanel(parent = self, id = self.id, settings = self.instruction, notebook = False)
  2704. self.id = self.rPanel.getId()
  2705. self._layout(self.rPanel)
  2706. def update(self):
  2707. ok = self.rPanel.update()
  2708. if ok:
  2709. return True
  2710. return False
  2711. def OnApply(self, event):
  2712. ok = self.update()
  2713. if not ok:
  2714. return False
  2715. if self.id in self.instruction:
  2716. self.parent.DialogDataChanged(id = self.id)
  2717. else:
  2718. mapId = self.instruction.FindInstructionByType('map').id
  2719. self.parent.DialogDataChanged(id = mapId)
  2720. return True
  2721. def updateDialog(self):
  2722. """!Update information (not used)"""
  2723. pass
  2724. ## if 'map' in self.parent.openDialogs:
  2725. ## if self.parent.openDialogs['map'].mPanel.rasterTypeRadio.GetValue()\
  2726. ## and self.parent.openDialogs['map'].mPanel.select.GetValue():
  2727. ## if self.parent.openDialogs['map'].mPanel.drawMap.IsChecked():
  2728. ## self.rPanel.rasterSelect.SetValue(self.parent.openDialogs['map'].mPanel.select.GetValue())
  2729. class MainVectorDialog(PsmapDialog):
  2730. def __init__(self, parent, id, settings):
  2731. PsmapDialog.__init__(self, parent = parent, id = id, title = _("Vector maps settings"), settings = settings)
  2732. self.objectType = ('vector',)
  2733. self.vPanel = VectorPanel(parent = self, id = self.id, settings = self.instruction, notebook = False)
  2734. self.id = self.vPanel.getId()
  2735. self._layout(self.vPanel)
  2736. def update(self):
  2737. self.vPanel.update()
  2738. def OnApply(self, event):
  2739. self.update()
  2740. if self.id in self.instruction:
  2741. self.parent.DialogDataChanged(id = self.id)
  2742. else:
  2743. mapId = self.instruction.FindInstructionByType('map').id
  2744. self.parent.DialogDataChanged(id = mapId)
  2745. return True
  2746. def updateDialog(self):
  2747. """!Update information (not used)"""
  2748. pass
  2749. class VPropertiesDialog(PsmapDialog):
  2750. def __init__(self, parent, id, settings, vectors, tmpSettings):
  2751. PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings, apply = False)
  2752. vectorList = vectors
  2753. self.vPropertiesDict = tmpSettings
  2754. # determine map and its type
  2755. for item in vectorList:
  2756. if id == item[2]:
  2757. self.vectorName = item[0]
  2758. self.type = item[1]
  2759. self.SetTitle(_("%s properties") % self.vectorName)
  2760. #vector map info
  2761. self.connection = True
  2762. try:
  2763. self.mapDBInfo = VectorDBInfo(self.vectorName)
  2764. self.layers = self.mapDBInfo.layers.keys()
  2765. except grass.ScriptError:
  2766. self.connection = False
  2767. self.layers = []
  2768. if not self.layers:
  2769. self.connection = False
  2770. self.layers = []
  2771. self.currLayer = self.vPropertiesDict['layer']
  2772. #path to symbols, patterns
  2773. gisbase = os.getenv("GISBASE")
  2774. self.symbolPath = os.path.join(gisbase, 'etc', 'symbol')
  2775. self.symbols = []
  2776. for dir in os.listdir(self.symbolPath):
  2777. for symbol in os.listdir(os.path.join(self.symbolPath, dir)):
  2778. self.symbols.append(os.path.join(dir, symbol))
  2779. self.patternPath = os.path.join(gisbase, 'etc', 'paint', 'patterns')
  2780. #notebook
  2781. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  2782. self.DSpanel = self._DataSelectionPanel(notebook)
  2783. self.EnableLayerSelection(enable = self.connection)
  2784. selectPanel = { 'points': [self._ColorsPointAreaPanel, self._StylePointPanel],
  2785. 'lines': [self._ColorsLinePanel, self._StyleLinePanel],
  2786. 'areas': [self._ColorsPointAreaPanel, self._StyleAreaPanel]}
  2787. self.ColorsPanel = selectPanel[self.type][0](notebook)
  2788. self.OnOutline(None)
  2789. if self.type in ('points', 'areas'):
  2790. self.OnFill(None)
  2791. self.OnColor(None)
  2792. self.StylePanel = selectPanel[self.type][1](notebook)
  2793. if self.type == 'points':
  2794. self.OnSize(None)
  2795. self.OnRotation(None)
  2796. self.OnSymbology(None)
  2797. if self.type == 'areas':
  2798. self.OnPattern(None)
  2799. self._layout(notebook)
  2800. def _DataSelectionPanel(self, notebook):
  2801. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  2802. notebook.AddPage(page = panel, text = _("Data selection"))
  2803. border = wx.BoxSizer(wx.VERTICAL)
  2804. # data type
  2805. self.checkType1 = self.checkType2 = None
  2806. if self.type in ('lines', 'points'):
  2807. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Feature type"))
  2808. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2809. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2810. if self.type == 'points':
  2811. label = (_("points"), _("centroids"))
  2812. else:
  2813. label = (_("lines"), _("boundaries"))
  2814. if self.type == 'points':
  2815. name = ("point", "centroid")
  2816. else:
  2817. name = ("line", "boundary")
  2818. self.checkType1 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[0], name = name[0])
  2819. self.checkType2 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[1], name = name[1])
  2820. self.checkType1.SetValue(self.vPropertiesDict['type'].find(name[0]) >= 0)
  2821. self.checkType2.SetValue(self.vPropertiesDict['type'].find(name[1]) >= 0)
  2822. gridBagSizer.Add(self.checkType1, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2823. gridBagSizer.Add(self.checkType2, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2824. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2825. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2826. # layer selection
  2827. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Layer selection"))
  2828. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2829. self.gridBagSizerL = wx.GridBagSizer(hgap = 5, vgap = 5)
  2830. self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = "")
  2831. if not self.connection:
  2832. self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = _("Database connection is not defined in DB file."))
  2833. text = wx.StaticText(panel, id = wx.ID_ANY, label = _("Select layer:"))
  2834. self.layerChoice = wx.Choice(panel, id = wx.ID_ANY, choices = map(str, self.layers), size = self.spinCtrlSize)
  2835. self.layerChoice.SetStringSelection(self.currLayer)
  2836. if self.connection:
  2837. table = self.mapDBInfo.layers[int(self.currLayer)]['table']
  2838. else:
  2839. table = ""
  2840. self.radioWhere = wx.RadioButton(panel, id = wx.ID_ANY, label = "SELECT * FROM %s WHERE" % table, style = wx.RB_GROUP)
  2841. self.textCtrlWhere = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  2842. if self.connection:
  2843. cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table'])
  2844. else:
  2845. cols = []
  2846. self.choiceColumns = wx.Choice(panel, id = wx.ID_ANY, choices = cols)
  2847. self.radioCats = wx.RadioButton(panel, id = wx.ID_ANY, label = "Choose categories ")
  2848. self.textCtrlCats = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  2849. self.textCtrlCats.SetToolTipString(_("list of categories (e.g. 1,3,5-7)"))
  2850. if self.vPropertiesDict.has_key('cats'):
  2851. self.radioCats.SetValue(True)
  2852. self.textCtrlCats.SetValue(self.vPropertiesDict['cats'])
  2853. if self.vPropertiesDict.has_key('where'):
  2854. self.radioWhere.SetValue(True)
  2855. where = self.vPropertiesDict['where'].strip().split(" ",1)
  2856. self.choiceColumns.SetStringSelection(where[0])
  2857. self.textCtrlWhere.SetValue(where[1])
  2858. row = 0
  2859. if not self.connection:
  2860. self.gridBagSizerL.Add(self.warning, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2861. row = 1
  2862. self.gridBagSizerL.Add(text, pos = (0 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2863. self.gridBagSizerL.Add(self.layerChoice, pos = (0 + row,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2864. self.gridBagSizerL.Add(self.radioWhere, pos = (1 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2865. self.gridBagSizerL.Add(self.choiceColumns, pos = (1 + row,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2866. self.gridBagSizerL.Add(self.textCtrlWhere, pos = (1 + row,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2867. self.gridBagSizerL.Add(self.radioCats, pos = (2 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2868. self.gridBagSizerL.Add(self.textCtrlCats, pos = (2 + row,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2869. sizer.Add(self.gridBagSizerL, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2870. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2871. #mask
  2872. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Mask"))
  2873. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2874. self.mask = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use current mask"))
  2875. if self.vPropertiesDict['masked'] == 'y':
  2876. self.mask.SetValue(True)
  2877. else:
  2878. self.mask.SetValue(False)
  2879. sizer.Add(self.mask, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2880. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2881. self.Bind(wx.EVT_CHOICE, self.OnLayer, self.layerChoice)
  2882. panel.SetSizer(border)
  2883. panel.Fit()
  2884. return panel
  2885. def _ColorsPointAreaPanel(self, notebook):
  2886. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  2887. notebook.AddPage(page = panel, text = _("Colors"))
  2888. border = wx.BoxSizer(wx.VERTICAL)
  2889. #colors - outline
  2890. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline"))
  2891. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2892. self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2)
  2893. self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline"))
  2894. self.outlineCheck.SetValue(self.vPropertiesDict['color'] != 'none')
  2895. widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  2896. if fs:
  2897. self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
  2898. increment = 0.5, value = 1, style = fs.FS_RIGHT)
  2899. self.widthSpin.SetFormat("%f")
  2900. self.widthSpin.SetDigits(2)
  2901. else:
  2902. self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1,
  2903. size = self.spinCtrlSize)
  2904. if self.vPropertiesDict['color'] == None:
  2905. self.vPropertiesDict['color'] = 'none'
  2906. if self.vPropertiesDict['color'] != 'none':
  2907. self.widthSpin.SetValue(self.vPropertiesDict['width'] )
  2908. else:
  2909. self.widthSpin.SetValue(1)
  2910. colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:"))
  2911. self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2912. if self.vPropertiesDict['color'] != 'none':
  2913. self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['color']))
  2914. else:
  2915. self.colorPicker.SetColour(convertRGB('black'))
  2916. self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2917. self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2918. self.gridBagSizerO.Add(self.widthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2919. self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2920. self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2921. sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2922. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2923. self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck)
  2924. #colors - fill
  2925. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill"))
  2926. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2927. self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2)
  2928. self.fillCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("fill color"))
  2929. self.fillCheck.SetValue(self.vPropertiesDict['fcolor'] != 'none' or self.vPropertiesDict['rgbcolumn'] is not None)
  2930. self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP)
  2931. #set choose color option if there is no db connection
  2932. if self.connection:
  2933. self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn'])
  2934. else:
  2935. self.colorPickerRadio.SetValue(False)
  2936. self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2937. if self.vPropertiesDict['fcolor'] != 'none':
  2938. self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['fcolor']))
  2939. else:
  2940. self.fillColorPicker.SetColour(convertRGB('red'))
  2941. self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:"))
  2942. self.colorColChoice = self.getColsChoice(parent = panel)
  2943. if self.connection:
  2944. if self.vPropertiesDict['rgbcolumn']:
  2945. self.colorColRadio.SetValue(True)
  2946. self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn'])
  2947. else:
  2948. self.colorColRadio.SetValue(False)
  2949. self.colorColChoice.SetSelection(0)
  2950. self.colorColChoice.Enable(self.connection)
  2951. self.colorColRadio.Enable(self.connection)
  2952. self.gridBagSizerF.Add(self.fillCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2953. self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2954. self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2955. self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2956. self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2957. sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2958. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2959. self.Bind(wx.EVT_CHECKBOX, self.OnFill, self.fillCheck)
  2960. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio)
  2961. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio)
  2962. panel.SetSizer(border)
  2963. panel.Fit()
  2964. return panel
  2965. def _ColorsLinePanel(self, notebook):
  2966. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  2967. notebook.AddPage(page = panel, text = _("Colors"))
  2968. border = wx.BoxSizer(wx.VERTICAL)
  2969. #colors - outline
  2970. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline"))
  2971. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2972. self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2)
  2973. if self.vPropertiesDict['hcolor'] == None:
  2974. self.vPropertiesDict['hcolor'] = 'none'
  2975. if self.vPropertiesDict['color'] == None:
  2976. self.vPropertiesDict['color'] = 'none'
  2977. self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline"))
  2978. self.outlineCheck.SetValue(self.vPropertiesDict['hcolor'] != 'none')
  2979. self.outlineCheck.SetToolTipString(_("No effect for fill color from table column"))
  2980. widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  2981. if fs:
  2982. self.outWidthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
  2983. increment = 0.5, value = 1, style = fs.FS_RIGHT)
  2984. self.outWidthSpin.SetFormat("%f")
  2985. self.outWidthSpin.SetDigits(1)
  2986. else:
  2987. self.outWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1,
  2988. size = self.spinCtrlSize)
  2989. if self.vPropertiesDict['hcolor'] != 'none':
  2990. self.outWidthSpin.SetValue(self.vPropertiesDict['hwidth'] )
  2991. else:
  2992. self.outWidthSpin.SetValue(1)
  2993. colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:"))
  2994. self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2995. if self.vPropertiesDict['hcolor'] != 'none':
  2996. self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['hcolor']) )
  2997. else:
  2998. self.colorPicker.SetColour(convertRGB('black'))
  2999. self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3000. self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3001. self.gridBagSizerO.Add(self.outWidthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3002. self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3003. self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3004. sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3005. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3006. self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck)
  3007. #colors - fill
  3008. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill"))
  3009. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3010. self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2)
  3011. fillText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color of lines:"))
  3012. self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP)
  3013. #set choose color option if there is no db connection
  3014. if self.connection:
  3015. self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn'])
  3016. else:
  3017. self.colorPickerRadio.SetValue(False)
  3018. self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  3019. if self.vPropertiesDict['color'] != 'none':
  3020. self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['color']) )
  3021. else:
  3022. self.fillColorPicker.SetColour(convertRGB('black'))
  3023. self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:"))
  3024. self.colorColChoice = self.getColsChoice(parent = panel)
  3025. if self.connection:
  3026. if self.vPropertiesDict['rgbcolumn']:
  3027. self.colorColRadio.SetValue(True)
  3028. self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn'])
  3029. else:
  3030. self.colorColRadio.SetValue(False)
  3031. self.colorColChoice.SetSelection(0)
  3032. self.colorColChoice.Enable(self.connection)
  3033. self.colorColRadio.Enable(self.connection)
  3034. self.gridBagSizerF.Add(fillText, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3035. self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3036. self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3037. self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3038. self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3039. sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3040. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3041. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio)
  3042. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio)
  3043. panel.SetSizer(border)
  3044. panel.Fit()
  3045. return panel
  3046. def _StylePointPanel(self, notebook):
  3047. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3048. notebook.AddPage(page = panel, text = _("Size and style"))
  3049. border = wx.BoxSizer(wx.VERTICAL)
  3050. #symbology
  3051. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Symbology"))
  3052. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3053. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3054. gridBagSizer.AddGrowableCol(1)
  3055. self.symbolRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("symbol:"), style = wx.RB_GROUP)
  3056. self.symbolRadio.SetValue(bool(self.vPropertiesDict['symbol']))
  3057. self.symbolName = wx.StaticText(panel, id = wx.ID_ANY)
  3058. self.symbolName.SetLabel(self.vPropertiesDict['symbol'])
  3059. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR,
  3060. self.vPropertiesDict['symbol']) + '.png')
  3061. self.symbolButton = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bitmap)
  3062. self.epsRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("eps file:"))
  3063. self.epsRadio.SetValue(bool(self.vPropertiesDict['eps']))
  3064. self.epsFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = '',
  3065. buttonText = _("Browse"), toolTip = _("Type filename or click browse to choose file"),
  3066. dialogTitle = _("Choose a file"), startDirectory = '', initialValue = '',
  3067. fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.OPEN)
  3068. if not self.vPropertiesDict['eps']:
  3069. self.epsFileCtrl.SetValue('')
  3070. else: #eps chosen
  3071. self.epsFileCtrl.SetValue(self.vPropertiesDict['eps'])
  3072. gridBagSizer.AddGrowableCol(2)
  3073. gridBagSizer.Add(self.symbolRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3074. gridBagSizer.Add(self.symbolName, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border = 10)
  3075. gridBagSizer.Add(self.symbolButton, pos = (0, 2), flag = wx.ALIGN_RIGHT , border = 0)
  3076. gridBagSizer.Add(self.epsRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3077. gridBagSizer.Add(self.epsFileCtrl, pos = (1, 1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3078. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3079. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3080. self.Bind(wx.EVT_BUTTON, self.OnSymbolSelection, self.symbolButton)
  3081. self.Bind(wx.EVT_RADIOBUTTON, self.OnSymbology, self.symbolRadio)
  3082. self.Bind(wx.EVT_RADIOBUTTON, self.OnSymbology, self.epsRadio)
  3083. #size
  3084. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  3085. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3086. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3087. gridBagSizer.AddGrowableCol(0)
  3088. self.sizeRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size:"), style = wx.RB_GROUP)
  3089. self.sizeSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 50, initial = 1)
  3090. self.sizecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size from map table column:"))
  3091. self.sizeColChoice = self.getColsChoice(panel)
  3092. self.scaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("scale:"))
  3093. self.scaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
  3094. self.sizeRadio.SetValue(self.vPropertiesDict['size'] is not None)
  3095. self.sizecolumnRadio.SetValue(bool(self.vPropertiesDict['sizecolumn']))
  3096. if self.vPropertiesDict['size']:
  3097. self.sizeSpin.SetValue(self.vPropertiesDict['size'])
  3098. else: self.sizeSpin.SetValue(5)
  3099. if self.vPropertiesDict['sizecolumn']:
  3100. self.scaleSpin.SetValue(self.vPropertiesDict['scale'])
  3101. self.sizeColChoice.SetStringSelection(self.vPropertiesDict['sizecolumn'])
  3102. else:
  3103. self.scaleSpin.SetValue(1)
  3104. self.sizeColChoice.SetSelection(0)
  3105. if not self.connection:
  3106. for each in (self.sizecolumnRadio, self.sizeColChoice, self.scaleSpin, self.scaleText):
  3107. each.Disable()
  3108. gridBagSizer.Add(self.sizeRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3109. gridBagSizer.Add(self.sizeSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3110. gridBagSizer.Add(self.sizecolumnRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3111. gridBagSizer.Add(self.sizeColChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3112. gridBagSizer.Add(self.scaleText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3113. gridBagSizer.Add(self.scaleSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3114. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3115. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3116. self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizeRadio)
  3117. self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizecolumnRadio)
  3118. #rotation
  3119. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Rotation"))
  3120. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3121. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3122. gridBagSizer.AddGrowableCol(1)
  3123. self.rotateCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate symbols:"))
  3124. self.rotateRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("counterclockwise in degrees:"), style = wx.RB_GROUP)
  3125. self.rotateSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 0, max = 360, initial = 0)
  3126. self.rotatecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("from map table column:"))
  3127. self.rotateColChoice = self.getColsChoice(panel)
  3128. self.rotateCheck.SetValue(self.vPropertiesDict['rotation'])
  3129. self.rotateRadio.SetValue(self.vPropertiesDict['rotate'] is not None)
  3130. self.rotatecolumnRadio.SetValue(bool(self.vPropertiesDict['rotatecolumn']))
  3131. if self.vPropertiesDict['rotate']:
  3132. self.rotateSpin.SetValue(self.vPropertiesDict['rotate'])
  3133. else:
  3134. self.rotateSpin.SetValue(0)
  3135. if self.vPropertiesDict['rotatecolumn']:
  3136. self.rotateColChoice.SetStringSelection(self.vPropertiesDict['rotatecolumn'])
  3137. else:
  3138. self.rotateColChoice.SetSelection(0)
  3139. gridBagSizer.Add(self.rotateCheck, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3140. gridBagSizer.Add(self.rotateRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3141. gridBagSizer.Add(self.rotateSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3142. gridBagSizer.Add(self.rotatecolumnRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3143. gridBagSizer.Add(self.rotateColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3144. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3145. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3146. self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotateCheck)
  3147. self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotateRadio)
  3148. self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotatecolumnRadio)
  3149. panel.SetSizer(border)
  3150. panel.Fit()
  3151. return panel
  3152. def _StyleLinePanel(self, notebook):
  3153. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3154. notebook.AddPage(page = panel, text = _("Size and style"))
  3155. border = wx.BoxSizer(wx.VERTICAL)
  3156. #width
  3157. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Width"))
  3158. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3159. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3160. widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Set width (pts):"))
  3161. if fs:
  3162. self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
  3163. increment = 0.5, value = 1, style = fs.FS_RIGHT)
  3164. self.widthSpin.SetFormat("%f")
  3165. self.widthSpin.SetDigits(1)
  3166. else:
  3167. self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
  3168. self.cwidthCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("multiply width by category value"))
  3169. if self.vPropertiesDict['width']:
  3170. self.widthSpin.SetValue(self.vPropertiesDict['width'])
  3171. self.cwidthCheck.SetValue(False)
  3172. else:
  3173. self.widthSpin.SetValue(self.vPropertiesDict['cwidth'])
  3174. self.cwidthCheck.SetValue(True)
  3175. gridBagSizer.Add(widthText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3176. gridBagSizer.Add(self.widthSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3177. gridBagSizer.Add(self.cwidthCheck, pos = (1, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3178. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3179. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3180. #style
  3181. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Line style"))
  3182. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3183. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3184. styleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose line style:"))
  3185. penStyles = ["solid", "dashed", "dotted", "dashdotted"]
  3186. self.styleCombo = PenStyleComboBox(panel, choices = penStyles, validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
  3187. ## self.styleCombo = wx.ComboBox(panel, id = wx.ID_ANY,
  3188. ## choices = ["solid", "dashed", "dotted", "dashdotted"],
  3189. ## validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
  3190. ## self.styleCombo.SetToolTipString(_("It's possible to enter a series of 0's and 1's too. "\
  3191. ## "The first block of repeated zeros or ones represents 'draw', "\
  3192. ## "the second block represents 'blank'. An even number of blocks "\
  3193. ## "will repeat the pattern, an odd number of blocks will alternate the pattern."))
  3194. linecapText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose linecap:"))
  3195. self.linecapChoice = wx.Choice(panel, id = wx.ID_ANY, choices = ["butt", "round", "extended_butt"])
  3196. self.styleCombo.SetValue(self.vPropertiesDict['style'])
  3197. self.linecapChoice.SetStringSelection(self.vPropertiesDict['linecap'])
  3198. gridBagSizer.Add(styleText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3199. gridBagSizer.Add(self.styleCombo, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3200. gridBagSizer.Add(linecapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3201. gridBagSizer.Add(self.linecapChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3202. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3203. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3204. panel.SetSizer(border)
  3205. panel.Fit()
  3206. return panel
  3207. def _StyleAreaPanel(self, notebook):
  3208. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3209. notebook.AddPage(page = panel, text = _("Size and style"))
  3210. border = wx.BoxSizer(wx.VERTICAL)
  3211. #pattern
  3212. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Pattern"))
  3213. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3214. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3215. gridBagSizer.AddGrowableCol(1)
  3216. self.patternCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use pattern:"))
  3217. self.patFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = _("Choose pattern file:"),
  3218. buttonText = _("Browse"), toolTip = _("Type filename or click browse to choose file"),
  3219. dialogTitle = _("Choose a file"), startDirectory = self.patternPath, initialValue = '',
  3220. fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.OPEN)
  3221. self.patWidthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern line width (pts):"))
  3222. self.patWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
  3223. self.patScaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern scale factor:"))
  3224. self.patScaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
  3225. self.patternCheck.SetValue(bool(self.vPropertiesDict['pat']))
  3226. if self.patternCheck.GetValue():
  3227. self.patFileCtrl.SetValue(self.vPropertiesDict['pat'])
  3228. self.patWidthSpin.SetValue(self.vPropertiesDict['pwidth'])
  3229. self.patScaleSpin.SetValue(self.vPropertiesDict['scale'])
  3230. gridBagSizer.Add(self.patternCheck, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3231. gridBagSizer.Add(self.patFileCtrl, pos = (1, 0), span = (1, 2),flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3232. gridBagSizer.Add(self.patWidthText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3233. gridBagSizer.Add(self.patWidthSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3234. gridBagSizer.Add(self.patScaleText, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3235. gridBagSizer.Add(self.patScaleSpin, pos = (3, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3236. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3237. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3238. self.Bind(wx.EVT_CHECKBOX, self.OnPattern, self.patternCheck)
  3239. panel.SetSizer(border)
  3240. panel.Fit()
  3241. return panel
  3242. def OnLayer(self, event):
  3243. """!Change columns on layer change """
  3244. if self.layerChoice.GetStringSelection() == self.currLayer:
  3245. return
  3246. self.currLayer = self.layerChoice.GetStringSelection()
  3247. if self.connection:
  3248. cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table'])
  3249. else:
  3250. cols = []
  3251. self.choiceColumns.SetItems(cols)
  3252. self.choiceColumns.SetSelection(0)
  3253. if self.type in ('points', 'lines'):
  3254. self.colorColChoice.SetItems(cols)
  3255. self.colorColChoice.SetSelection(0)
  3256. def OnOutline(self, event):
  3257. for widget in self.gridBagSizerO.GetChildren():
  3258. if widget.GetWindow() != self.outlineCheck:
  3259. widget.GetWindow().Enable(self.outlineCheck.GetValue())
  3260. def OnFill(self, event):
  3261. enable = self.fillCheck.GetValue()
  3262. self.colorColChoice.Enable(enable)
  3263. self.colorColRadio.Enable(enable)
  3264. self.fillColorPicker.Enable(enable)
  3265. self.colorPickerRadio.Enable(enable)
  3266. if enable:
  3267. self.OnColor(None)
  3268. if not self.connection:
  3269. self.colorColChoice.Disable()
  3270. self.colorColRadio.Disable()
  3271. def OnColor(self, event):
  3272. self.colorColChoice.Enable(self.colorColRadio.GetValue())
  3273. self.fillColorPicker.Enable(self.colorPickerRadio.GetValue())
  3274. def OnSize(self, event):
  3275. self.sizeSpin.Enable(self.sizeRadio.GetValue())
  3276. self.sizeColChoice.Enable(self.sizecolumnRadio.GetValue())
  3277. self.scaleText.Enable(self.sizecolumnRadio.GetValue())
  3278. self.scaleSpin.Enable(self.sizecolumnRadio.GetValue())
  3279. def OnRotation(self, event):
  3280. for each in (self.rotateRadio, self.rotatecolumnRadio, self.rotateColChoice, self.rotateSpin):
  3281. if self.rotateCheck.GetValue():
  3282. each.Enable()
  3283. self.OnRotationType(event = None)
  3284. else:
  3285. each.Disable()
  3286. def OnRotationType(self, event):
  3287. self.rotateSpin.Enable(self.rotateRadio.GetValue())
  3288. self.rotateColChoice.Enable(self.rotatecolumnRadio.GetValue())
  3289. def OnPattern(self, event):
  3290. for each in (self.patFileCtrl, self.patWidthText, self.patWidthSpin, self.patScaleText, self.patScaleSpin):
  3291. each.Enable(self.patternCheck.GetValue())
  3292. def OnSymbology(self, event):
  3293. useSymbol = self.symbolRadio.GetValue()
  3294. self.symbolButton.Enable(useSymbol)
  3295. self.symbolName.Enable(useSymbol)
  3296. self.epsFileCtrl.Enable(not useSymbol)
  3297. def OnSymbolSelection(self, event):
  3298. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  3299. currentSymbol = self.symbolName.GetLabel())
  3300. if dlg.ShowModal() == wx.ID_OK:
  3301. img = dlg.GetSelectedSymbol(fullPath = True)
  3302. name = dlg.GetSelectedSymbol(fullPath = False)
  3303. self.symbolButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  3304. self.symbolName.SetLabel(name)
  3305. dlg.Destroy()
  3306. def EnableLayerSelection(self, enable = True):
  3307. for widget in self.gridBagSizerL.GetChildren():
  3308. if widget.GetWindow() != self.warning:
  3309. widget.GetWindow().Enable(enable)
  3310. def getColsChoice(self, parent):
  3311. """!Returns a wx.Choice with table columns"""
  3312. if self.connection:
  3313. cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table'])
  3314. else:
  3315. cols = []
  3316. choice = wx.Choice(parent = parent, id = wx.ID_ANY, choices = cols)
  3317. return choice
  3318. def update(self):
  3319. #feature type
  3320. if self.type in ('lines', 'points'):
  3321. featureType = None
  3322. if self.checkType1.GetValue():
  3323. featureType = self.checkType1.GetName()
  3324. if self.checkType2.GetValue():
  3325. featureType += " or " + self.checkType2.GetName()
  3326. elif self.checkType2.GetValue():
  3327. featureType = self.checkType2.GetName()
  3328. if featureType:
  3329. self.vPropertiesDict['type'] = featureType
  3330. # is connection
  3331. self.vPropertiesDict['connection'] = self.connection
  3332. if self.connection:
  3333. self.vPropertiesDict['layer'] = self.layerChoice.GetStringSelection()
  3334. if self.radioCats.GetValue() and not self.textCtrlCats.IsEmpty():
  3335. self.vPropertiesDict['cats'] = self.textCtrlCats.GetValue()
  3336. elif self.radioWhere.GetValue() and not self.textCtrlWhere.IsEmpty():
  3337. self.vPropertiesDict['where'] = self.choiceColumns.GetStringSelection() + " " \
  3338. + self.textCtrlWhere.GetValue()
  3339. #mask
  3340. if self.mask.GetValue():
  3341. self.vPropertiesDict['masked'] = 'y'
  3342. else:
  3343. self.vPropertiesDict['masked'] = 'n'
  3344. #colors
  3345. if self.type in ('points', 'areas'):
  3346. if self.outlineCheck.GetValue():
  3347. self.vPropertiesDict['color'] = convertRGB(self.colorPicker.GetColour())
  3348. self.vPropertiesDict['width'] = self.widthSpin.GetValue()
  3349. else:
  3350. self.vPropertiesDict['color'] = 'none'
  3351. if self.fillCheck.GetValue():
  3352. if self.colorPickerRadio.GetValue():
  3353. self.vPropertiesDict['fcolor'] = convertRGB(self.fillColorPicker.GetColour())
  3354. self.vPropertiesDict['rgbcolumn'] = None
  3355. if self.colorColRadio.GetValue():
  3356. self.vPropertiesDict['fcolor'] = 'none'# this color is taken in case of no record in rgb column
  3357. self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection()
  3358. else:
  3359. self.vPropertiesDict['fcolor'] = 'none'
  3360. if self.type == 'lines':
  3361. #hcolor only when no rgbcolumn
  3362. if self.outlineCheck.GetValue():# and self.fillCheck.GetValue() and self.colorColRadio.GetValue():
  3363. self.vPropertiesDict['hcolor'] = convertRGB(self.colorPicker.GetColour())
  3364. self.vPropertiesDict['hwidth'] = self.outWidthSpin.GetValue()
  3365. else:
  3366. self.vPropertiesDict['hcolor'] = 'none'
  3367. if self.colorPickerRadio.GetValue():
  3368. self.vPropertiesDict['color'] = convertRGB(self.fillColorPicker.GetColour())
  3369. self.vPropertiesDict['rgbcolumn'] = None
  3370. if self.colorColRadio.GetValue():
  3371. self.vPropertiesDict['color'] = 'none'# this color is taken in case of no record in rgb column
  3372. self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection()
  3373. #
  3374. #size and style
  3375. #
  3376. if self.type == 'points':
  3377. #symbols
  3378. if self.symbolRadio.GetValue():
  3379. self.vPropertiesDict['symbol'] = self.symbolName.GetLabel()
  3380. self.vPropertiesDict['eps'] = None
  3381. else:
  3382. self.vPropertiesDict['eps'] = self.epsFileCtrl.GetValue()
  3383. #size
  3384. if self.sizeRadio.GetValue():
  3385. self.vPropertiesDict['size'] = self.sizeSpin.GetValue()
  3386. self.vPropertiesDict['sizecolumn'] = None
  3387. self.vPropertiesDict['scale'] = None
  3388. else:
  3389. self.vPropertiesDict['sizecolumn'] = self.sizeColChoice.GetStringSelection()
  3390. self.vPropertiesDict['scale'] = self.scaleSpin.GetValue()
  3391. self.vPropertiesDict['size'] = None
  3392. #rotation
  3393. self.vPropertiesDict['rotate'] = None
  3394. self.vPropertiesDict['rotatecolumn'] = None
  3395. self.vPropertiesDict['rotation'] = False
  3396. if self.rotateCheck.GetValue():
  3397. self.vPropertiesDict['rotation'] = True
  3398. if self.rotateRadio.GetValue():
  3399. self.vPropertiesDict['rotate'] = self.rotateSpin.GetValue()
  3400. else:
  3401. self.vPropertiesDict['rotatecolumn'] = self.rotateColChoice.GetStringSelection()
  3402. if self.type == 'areas':
  3403. #pattern
  3404. self.vPropertiesDict['pat'] = None
  3405. if self.patternCheck.GetValue() and bool(self.patFileCtrl.GetValue()):
  3406. self.vPropertiesDict['pat'] = self.patFileCtrl.GetValue()
  3407. self.vPropertiesDict['pwidth'] = self.patWidthSpin.GetValue()
  3408. self.vPropertiesDict['scale'] = self.patScaleSpin.GetValue()
  3409. if self.type == 'lines':
  3410. #width
  3411. if self.cwidthCheck.GetValue():
  3412. self.vPropertiesDict['cwidth'] = self.widthSpin.GetValue()
  3413. self.vPropertiesDict['width'] = None
  3414. else:
  3415. self.vPropertiesDict['width'] = self.widthSpin.GetValue()
  3416. self.vPropertiesDict['cwidth'] = None
  3417. #line style
  3418. if self.styleCombo.GetValue():
  3419. self.vPropertiesDict['style'] = self.styleCombo.GetValue()
  3420. else:
  3421. self.vPropertiesDict['style'] = 'solid'
  3422. self.vPropertiesDict['linecap'] = self.linecapChoice.GetStringSelection()
  3423. def OnOK(self, event):
  3424. self.update()
  3425. event.Skip()
  3426. class LegendDialog(PsmapDialog):
  3427. def __init__(self, parent, id, settings, page):
  3428. PsmapDialog.__init__(self, parent = parent, id = id, title = "Legend settings", settings = settings)
  3429. self.objectType = ('rasterLegend', 'vectorLegend')
  3430. self.instruction = settings
  3431. map = self.instruction.FindInstructionByType('map')
  3432. if map:
  3433. self.mapId = map.id
  3434. else:
  3435. self.mapId = None
  3436. vector = self.instruction.FindInstructionByType('vector')
  3437. if vector:
  3438. self.vectorId = vector.id
  3439. else:
  3440. self.vectorId = None
  3441. raster = self.instruction.FindInstructionByType('raster')
  3442. if raster:
  3443. self.rasterId = raster.id
  3444. else:
  3445. self.rasterId = None
  3446. self.pageId = self.instruction.FindInstructionByType('page').id
  3447. currPage = self.instruction[self.pageId].GetInstruction()
  3448. #raster legend
  3449. if self.id[0] is not None:
  3450. self.rasterLegend = self.instruction[self.id[0]]
  3451. self.rLegendDict = self.rasterLegend.GetInstruction()
  3452. else:
  3453. self.id[0] = wx.NewId()
  3454. self.rasterLegend = RasterLegend(self.id[0])
  3455. self.rLegendDict = self.rasterLegend.GetInstruction()
  3456. self.rLegendDict['where'] = currPage['Left'], currPage['Top']
  3457. #vector legend
  3458. if self.id[1] is not None:
  3459. self.vLegendDict = self.instruction[self.id[1]].GetInstruction()
  3460. else:
  3461. self.id[1] = wx.NewId()
  3462. vectorLegend = VectorLegend(self.id[1])
  3463. self.vLegendDict = vectorLegend.GetInstruction()
  3464. self.vLegendDict['where'] = currPage['Left'], currPage['Top']
  3465. if self.rasterId:
  3466. self.currRaster = self.instruction[self.rasterId]['raster']
  3467. else:
  3468. self.currRaster = None
  3469. #notebook
  3470. self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  3471. self.panelRaster = self._rasterLegend(self.notebook)
  3472. self.panelVector = self._vectorLegend(self.notebook)
  3473. self.OnRaster(None)
  3474. self.OnRange(None)
  3475. self.OnIsLegend(None)
  3476. self.OnSpan(None)
  3477. self.OnBorder(None)
  3478. self._layout(self.notebook)
  3479. self.notebook.ChangeSelection(page)
  3480. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  3481. def OnPageChanging(self, event):
  3482. """!Workaround to scroll up to see the checkbox"""
  3483. wx.CallAfter(self.FindWindowByName('rasterPanel').ScrollChildIntoView,
  3484. self.FindWindowByName('showRLegend'))
  3485. wx.CallAfter(self.FindWindowByName('vectorPanel').ScrollChildIntoView,
  3486. self.FindWindowByName('showVLegend'))
  3487. def _rasterLegend(self, notebook):
  3488. panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
  3489. panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3490. panel.SetName('rasterPanel')
  3491. notebook.AddPage(page = panel, text = _("Raster legend"))
  3492. border = wx.BoxSizer(wx.VERTICAL)
  3493. # is legend
  3494. self.isRLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show raster legend"))
  3495. self.isRLegend.SetValue(self.rLegendDict['rLegend'])
  3496. self.isRLegend.SetName("showRLegend")
  3497. border.Add(item = self.isRLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3498. # choose raster
  3499. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source raster"))
  3500. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3501. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3502. flexSizer.AddGrowableCol(1)
  3503. self.rasterDefault = wx.RadioButton(panel, id = wx.ID_ANY, label = _("current raster"), style = wx.RB_GROUP)
  3504. self.rasterOther = wx.RadioButton(panel, id = wx.ID_ANY, label = _("select raster"))
  3505. self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])#
  3506. self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])#
  3507. rasterType = getRasterType(map = self.currRaster)
  3508. self.rasterCurrent = wx.StaticText(panel, id = wx.ID_ANY,
  3509. label = _("%(rast)s: type %(type)s") % { 'rast' : self.currRaster,
  3510. 'type' : rasterType })
  3511. self.rasterSelect = Select(panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  3512. type = 'raster', multiple = False,
  3513. updateOnPopup = True, onPopup = None)
  3514. if not self.rLegendDict['rasterDefault']:
  3515. self.rasterSelect.SetValue(self.rLegendDict['raster'])
  3516. else:
  3517. self.rasterSelect.SetValue('')
  3518. flexSizer.Add(self.rasterDefault, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3519. flexSizer.Add(self.rasterCurrent, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
  3520. flexSizer.Add(self.rasterOther, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3521. flexSizer.Add(self.rasterSelect, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3522. sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3523. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3524. # type of legend
  3525. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Type of legend"))
  3526. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3527. vbox = wx.BoxSizer(wx.VERTICAL)
  3528. self.discrete = wx.RadioButton(parent = panel, id = wx.ID_ANY,
  3529. label = " %s " % _("discrete legend (categorical maps)"), style = wx.RB_GROUP)
  3530. self.continuous = wx.RadioButton(parent = panel, id = wx.ID_ANY,
  3531. label = " %s " % _("continuous color gradient legend (floating point map)"))
  3532. vbox.Add(self.discrete, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
  3533. vbox.Add(self.continuous, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
  3534. sizer.Add(item = vbox, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3535. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3536. # size, position and font
  3537. self.sizePositionFont(legendType = 'raster', parent = panel, mainSizer = border)
  3538. # advanced settings
  3539. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Advanced legend settings"))
  3540. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3541. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3542. # no data
  3543. self.nodata = wx.CheckBox(panel, id = wx.ID_ANY, label = _('draw "no data" box'))
  3544. if self.rLegendDict['nodata'] == 'y':
  3545. self.nodata.SetValue(True)
  3546. else:
  3547. self.nodata.SetValue(False)
  3548. #tickbar
  3549. self.ticks = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw ticks across color table"))
  3550. if self.rLegendDict['tickbar'] == 'y':
  3551. self.ticks.SetValue(True)
  3552. else:
  3553. self.ticks.SetValue(False)
  3554. # range
  3555. if self.rasterId and self.instruction[self.rasterId]['raster']:
  3556. rinfo = grass.raster_info(self.instruction[self.rasterId]['raster'])
  3557. self.minim, self.maxim = rinfo['min'], rinfo['max']
  3558. else:
  3559. self.minim, self.maxim = 0,0
  3560. self.range = wx.CheckBox(panel, id = wx.ID_ANY, label = _("range"))
  3561. self.range.SetValue(self.rLegendDict['range'])
  3562. self.minText = wx.StaticText(panel, id = wx.ID_ANY, label = "min (%s)" % self.minim)
  3563. self.maxText = wx.StaticText(panel, id = wx.ID_ANY, label = "max (%s)" % self.maxim)
  3564. self.min = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['min']))
  3565. self.max = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['max']))
  3566. gridBagSizer.Add(self.nodata, pos = (0,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3567. gridBagSizer.Add(self.ticks, pos = (1,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3568. gridBagSizer.Add(self.range, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3569. gridBagSizer.Add(self.minText, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3570. gridBagSizer.Add(self.min, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3571. gridBagSizer.Add(self.maxText, pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3572. gridBagSizer.Add(self.max, pos = (2,4), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3573. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3574. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3575. panel.SetSizer(border)
  3576. panel.Fit()
  3577. # bindings
  3578. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterDefault)
  3579. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterOther)
  3580. self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isRLegend)
  3581. self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.discrete)
  3582. self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.continuous)
  3583. ## self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize)
  3584. self.Bind(wx.EVT_CHECKBOX, self.OnRange, self.range)
  3585. self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
  3586. return panel
  3587. def _vectorLegend(self, notebook):
  3588. panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
  3589. panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3590. panel.SetName('vectorPanel')
  3591. notebook.AddPage(page = panel, text = _("Vector legend"))
  3592. border = wx.BoxSizer(wx.VERTICAL)
  3593. # is legend
  3594. self.isVLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show vector legend"))
  3595. self.isVLegend.SetValue(self.vLegendDict['vLegend'])
  3596. self.isVLegend.SetName("showVLegend")
  3597. border.Add(item = self.isVLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3598. #vector maps, their order, labels
  3599. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source vector maps"))
  3600. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3601. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3602. gridBagSizer.AddGrowableCol(0,3)
  3603. gridBagSizer.AddGrowableCol(1,1)
  3604. vectorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose vector maps and their order in legend"))
  3605. self.vectorListCtrl = CheckListCtrl(panel)
  3606. self.vectorListCtrl.InsertColumn(0, _("Vector map"))
  3607. self.vectorListCtrl.InsertColumn(1, _("Label"))
  3608. if self.vectorId:
  3609. vectors = sorted(self.instruction[self.vectorId]['list'], key = lambda x: x[3])
  3610. for vector in vectors:
  3611. index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
  3612. self.vectorListCtrl.SetStringItem(index, 1, vector[4])
  3613. self.vectorListCtrl.SetItemData(index, index)
  3614. self.vectorListCtrl.CheckItem(index, True)
  3615. if vector[3] == 0:
  3616. self.vectorListCtrl.CheckItem(index, False)
  3617. if not self.vectorId:
  3618. self.vectorListCtrl.SetColumnWidth(0, 100)
  3619. else:
  3620. self.vectorListCtrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
  3621. self.vectorListCtrl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
  3622. self.btnUp = wx.Button(panel, id = wx.ID_ANY, label = _("Up"))
  3623. self.btnDown = wx.Button(panel, id = wx.ID_ANY, label = _("Down"))
  3624. self.btnLabel = wx.Button(panel, id = wx.ID_ANY, label = _("Edit label"))
  3625. gridBagSizer.Add(vectorText, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3626. gridBagSizer.Add(self.vectorListCtrl, pos = (1,0), span = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3627. gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3628. gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3629. gridBagSizer.Add(self.btnLabel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3630. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3631. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3632. # size, position and font
  3633. self.sizePositionFont(legendType = 'vector', parent = panel, mainSizer = border)
  3634. # border
  3635. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Border"))
  3636. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3637. flexGridSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
  3638. self.borderCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw border around legend"))
  3639. self.borderColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY, style = wx.FNTP_FONTDESC_AS_LABEL)
  3640. if self.vLegendDict['border'] == 'none':
  3641. self.borderColorCtrl.SetColour(wx.BLACK)
  3642. self.borderCheck.SetValue(False)
  3643. else:
  3644. self.borderColorCtrl.SetColour(convertRGB(self.vLegendDict['border']))
  3645. self.borderCheck.SetValue(True)
  3646. flexGridSizer.Add(self.borderCheck, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3647. flexGridSizer.Add(self.borderColorCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3648. sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3649. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3650. self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
  3651. self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
  3652. self.Bind(wx.EVT_BUTTON, self.OnEditLabel, self.btnLabel)
  3653. self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isVLegend)
  3654. self.Bind(wx.EVT_CHECKBOX, self.OnSpan, panel.spanRadio)
  3655. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
  3656. self.Bind(wx.EVT_FONTPICKER_CHANGED, self.OnFont, panel.font['fontCtrl'])
  3657. panel.SetSizer(border)
  3658. panel.Fit()
  3659. return panel
  3660. def sizePositionFont(self, legendType, parent, mainSizer):
  3661. """!Insert widgets for size, position and font control"""
  3662. if legendType == 'raster':
  3663. legendDict = self.rLegendDict
  3664. else:
  3665. legendDict = self.vLegendDict
  3666. panel = parent
  3667. border = mainSizer
  3668. # size and position
  3669. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size and position"))
  3670. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3671. #unit
  3672. self.AddUnits(parent = panel, dialogDict = legendDict)
  3673. unitBox = wx.BoxSizer(wx.HORIZONTAL)
  3674. unitBox.Add(panel.units['unitsLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
  3675. unitBox.Add(panel.units['unitsCtrl'], proportion = 1, flag = wx.ALL, border = 5)
  3676. sizer.Add(unitBox, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3677. hBox = wx.BoxSizer(wx.HORIZONTAL)
  3678. posBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Position"))
  3679. posSizer = wx.StaticBoxSizer(posBox, wx.VERTICAL)
  3680. sizeBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  3681. sizeSizer = wx.StaticBoxSizer(sizeBox, wx.VERTICAL)
  3682. posGridBagSizer = wx.GridBagSizer(hgap = 10, vgap = 5)
  3683. posGridBagSizer.AddGrowableRow(2)
  3684. #position
  3685. self.AddPosition(parent = panel, dialogDict = legendDict)
  3686. posGridBagSizer.Add(panel.position['xLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3687. posGridBagSizer.Add(panel.position['xCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3688. posGridBagSizer.Add(panel.position['yLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3689. posGridBagSizer.Add(panel.position['yCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3690. posGridBagSizer.Add(panel.position['comment'], pos = (2,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  3691. posSizer.Add(posGridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3692. #size
  3693. width = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width:"))
  3694. if legendDict['width']:
  3695. w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3696. else:
  3697. w = ''
  3698. panel.widthCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(w), validator = TCValidator("DIGIT_ONLY"))
  3699. panel.widthCtrl.SetToolTipString(_("Leave the edit field empty, to use default values."))
  3700. if legendType == 'raster':
  3701. ## panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
  3702. ## panel.defaultSize.SetValue(legendDict['defaultSize'])
  3703. panel.heightOrColumnsLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
  3704. if legendDict['height']:
  3705. h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3706. else:
  3707. h = ''
  3708. panel.heightOrColumnsCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY"))
  3709. self.rSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3710. ## self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3711. self.rSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3712. self.rSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3713. self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3714. self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3715. sizeSizer.Add(self.rSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3716. if legendType == 'vector':
  3717. panel.widthCtrl.SetToolTipString(_("Width of the color symbol (for lines)\nin front of the legend text"))
  3718. #columns
  3719. minVect, maxVect = 0, 0
  3720. if self.vectorId:
  3721. minVect = 1
  3722. maxVect = min(10, len(self.instruction[self.vectorId]['list']))
  3723. cols = wx.StaticText(panel, id = wx.ID_ANY, label = _("Columns:"))
  3724. panel.colsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, value = "",
  3725. min = minVect, max = maxVect, initial = legendDict['cols'])
  3726. #span
  3727. panel.spanRadio = wx.CheckBox(panel, id = wx.ID_ANY, label = _("column span:"))
  3728. panel.spanTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = '')
  3729. panel.spanTextCtrl.SetToolTipString(_("Column separation distance between the left edges\n"\
  3730. "of two columns in a multicolumn legend"))
  3731. if legendDict['span']:
  3732. panel.spanRadio.SetValue(True)
  3733. s = self.unitConv.convert(value = float(legendDict['span']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3734. panel.spanTextCtrl.SetValue(str(s))
  3735. else:
  3736. panel.spanRadio.SetValue(False)
  3737. self.vSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3738. self.vSizeGBSizer.AddGrowableCol(1)
  3739. self.vSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3740. self.vSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3741. self.vSizeGBSizer.Add(cols, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3742. self.vSizeGBSizer.Add(panel.colsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3743. self.vSizeGBSizer.Add(panel.spanRadio, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3744. self.vSizeGBSizer.Add(panel.spanTextCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3745. sizeSizer.Add(self.vSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3746. hBox.Add(posSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
  3747. hBox.Add(sizeSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
  3748. sizer.Add(hBox, proportion = 0, flag = wx.EXPAND, border = 0)
  3749. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3750. # font
  3751. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  3752. fontSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3753. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3754. flexSizer.AddGrowableCol(1)
  3755. if legendType == 'raster':
  3756. self.AddFont(parent = panel, dialogDict = legendDict, color = True)
  3757. else:
  3758. self.AddFont(parent = panel, dialogDict = legendDict, color = False)
  3759. flexSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3760. flexSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3761. flexSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3762. flexSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3763. if legendType == 'raster':
  3764. flexSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3765. flexSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3766. fontSizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3767. border.Add(item = fontSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3768. # some enable/disable methods
  3769. def OnIsLegend(self, event):
  3770. """!Enables and disables controls, it depends if raster or vector legend is checked"""
  3771. page = self.notebook.GetSelection()
  3772. if page == 0 or event is None:
  3773. children = self.panelRaster.GetChildren()
  3774. if self.isRLegend.GetValue():
  3775. for i,widget in enumerate(children):
  3776. widget.Enable()
  3777. self.OnRaster(None)
  3778. self.OnRange(None)
  3779. self.OnDiscrete(None)
  3780. else:
  3781. for widget in children:
  3782. if widget.GetName() != 'showRLegend':
  3783. widget.Disable()
  3784. if page == 1 or event is None:
  3785. children = self.panelVector.GetChildren()
  3786. if self.isVLegend.GetValue():
  3787. for i, widget in enumerate(children):
  3788. widget.Enable()
  3789. self.OnSpan(None)
  3790. self.OnBorder(None)
  3791. else:
  3792. for widget in children:
  3793. if widget.GetName() != 'showVLegend':
  3794. widget.Disable()
  3795. def OnRaster(self, event):
  3796. if self.rasterDefault.GetValue():#default
  3797. self.rasterSelect.Disable()
  3798. type = getRasterType(self.currRaster)
  3799. else:#select raster
  3800. self.rasterSelect.Enable()
  3801. map = self.rasterSelect.GetValue()
  3802. type = getRasterType(map)
  3803. if type == 'CELL':
  3804. self.discrete.SetValue(True)
  3805. elif type in ('FCELL', 'DCELL'):
  3806. self.continuous.SetValue(True)
  3807. if event is None:
  3808. if self.rLegendDict['discrete'] == 'y':
  3809. self.discrete.SetValue(True)
  3810. elif self.rLegendDict['discrete'] == 'n':
  3811. self.continuous.SetValue(True)
  3812. self.OnDiscrete(None)
  3813. def OnDiscrete(self, event):
  3814. """! Change control according to the type of legend"""
  3815. enabledSize = self.panelRaster.heightOrColumnsCtrl.IsEnabled()
  3816. self.panelRaster.heightOrColumnsCtrl.Destroy()
  3817. if self.discrete.GetValue():
  3818. self.panelRaster.heightOrColumnsLabel.SetLabel(_("Columns:"))
  3819. self.panelRaster.heightOrColumnsCtrl = wx.SpinCtrl(self.panelRaster, id = wx.ID_ANY, value = "", min = 1, max = 10, initial = self.rLegendDict['cols'])
  3820. self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
  3821. self.nodata.Enable()
  3822. self.range.Disable()
  3823. self.min.Disable()
  3824. self.max.Disable()
  3825. self.minText.Disable()
  3826. self.maxText.Disable()
  3827. self.ticks.Disable()
  3828. else:
  3829. self.panelRaster.heightOrColumnsLabel.SetLabel(_("Height:"))
  3830. if self.rLegendDict['height']:
  3831. h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit'])
  3832. else:
  3833. h = ''
  3834. self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(self.panelRaster, id = wx.ID_ANY,
  3835. value = str(h), validator = TCValidator("DIGIT_ONLY"))
  3836. self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
  3837. self.nodata.Disable()
  3838. self.range.Enable()
  3839. if self.range.GetValue():
  3840. self.minText.Enable()
  3841. self.maxText.Enable()
  3842. self.min.Enable()
  3843. self.max.Enable()
  3844. self.ticks.Enable()
  3845. self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3846. self.panelRaster.Layout()
  3847. self.panelRaster.Fit()
  3848. def OnRange(self, event):
  3849. if not self.range.GetValue():
  3850. self.min.Disable()
  3851. self.max.Disable()
  3852. self.minText.Disable()
  3853. self.maxText.Disable()
  3854. else:
  3855. self.min.Enable()
  3856. self.max.Enable()
  3857. self.minText.Enable()
  3858. self.maxText.Enable()
  3859. def OnUp(self, event):
  3860. """!Moves selected map up, changes order in vector legend"""
  3861. if self.vectorListCtrl.GetFirstSelected() != -1:
  3862. pos = self.vectorListCtrl.GetFirstSelected()
  3863. if pos:
  3864. idx1 = self.vectorListCtrl.GetItemData(pos) - 1
  3865. idx2 = self.vectorListCtrl.GetItemData(pos - 1) + 1
  3866. self.vectorListCtrl.SetItemData(pos, idx1)
  3867. self.vectorListCtrl.SetItemData(pos - 1, idx2)
  3868. self.vectorListCtrl.SortItems(cmp)
  3869. if pos > 0:
  3870. selected = (pos - 1)
  3871. else:
  3872. selected = 0
  3873. self.vectorListCtrl.Select(selected)
  3874. def OnDown(self, event):
  3875. """!Moves selected map down, changes order in vector legend"""
  3876. if self.vectorListCtrl.GetFirstSelected() != -1:
  3877. pos = self.vectorListCtrl.GetFirstSelected()
  3878. if pos != self.vectorListCtrl.GetItemCount() - 1:
  3879. idx1 = self.vectorListCtrl.GetItemData(pos) + 1
  3880. idx2 = self.vectorListCtrl.GetItemData(pos + 1) - 1
  3881. self.vectorListCtrl.SetItemData(pos, idx1)
  3882. self.vectorListCtrl.SetItemData(pos + 1, idx2)
  3883. self.vectorListCtrl.SortItems(cmp)
  3884. if pos < self.vectorListCtrl.GetItemCount() -1:
  3885. selected = (pos + 1)
  3886. else:
  3887. selected = self.vectorListCtrl.GetItemCount() -1
  3888. self.vectorListCtrl.Select(selected)
  3889. def OnEditLabel(self, event):
  3890. """!Change legend label of vector map"""
  3891. if self.vectorListCtrl.GetFirstSelected() != -1:
  3892. idx = self.vectorListCtrl.GetFirstSelected()
  3893. default = self.vectorListCtrl.GetItem(idx, 1).GetText()
  3894. dlg = wx.TextEntryDialog(self, message = _("Edit legend label:"), caption = _("Edit label"),
  3895. defaultValue = default, style = wx.OK|wx.CANCEL|wx.CENTRE)
  3896. if dlg.ShowModal() == wx.ID_OK:
  3897. new = dlg.GetValue()
  3898. self.vectorListCtrl.SetStringItem(idx, 1, new)
  3899. dlg.Destroy()
  3900. def OnSpan(self, event):
  3901. self.panelVector.spanTextCtrl.Enable(self.panelVector.spanRadio.GetValue())
  3902. def OnFont(self, event):
  3903. """!Changes default width according to fontsize, width [inch] = fontsize[pt]/24"""
  3904. ## fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize()
  3905. fontsize = self.panelVector.font['fontSizeCtrl'].GetValue()
  3906. unit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
  3907. w = fontsize/24.
  3908. width = self.unitConv.convert(value = w, fromUnit = 'inch', toUnit = unit)
  3909. self.panelVector.widthCtrl.SetValue("%3.2f" % width)
  3910. def OnBorder(self, event):
  3911. """!Enables/disables colorPickerCtrl for border"""
  3912. self.borderColorCtrl.Enable(self.borderCheck.GetValue())
  3913. def updateRasterLegend(self):
  3914. """!Save information from raster legend dialog to dictionary"""
  3915. #is raster legend
  3916. if not self.isRLegend.GetValue():
  3917. self.rLegendDict['rLegend'] = False
  3918. else:
  3919. self.rLegendDict['rLegend'] = True
  3920. #units
  3921. currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection())
  3922. self.rLegendDict['unit'] = currUnit
  3923. # raster
  3924. if self.rasterDefault.GetValue():
  3925. self.rLegendDict['rasterDefault'] = True
  3926. self.rLegendDict['raster'] = self.currRaster
  3927. else:
  3928. self.rLegendDict['rasterDefault'] = False
  3929. self.rLegendDict['raster'] = self.rasterSelect.GetValue()
  3930. if self.rLegendDict['rLegend'] and not self.rLegendDict['raster']:
  3931. wx.MessageBox(message = _("No raster map selected!"),
  3932. caption = _('No raster'), style = wx.OK|wx.ICON_ERROR)
  3933. return False
  3934. if self.rLegendDict['raster']:
  3935. # type and range of map
  3936. rasterType = getRasterType(self.rLegendDict['raster'])
  3937. if rasterType is None:
  3938. return False
  3939. self.rLegendDict['type'] = rasterType
  3940. #discrete
  3941. if self.discrete.GetValue():
  3942. self.rLegendDict['discrete'] = 'y'
  3943. else:
  3944. self.rLegendDict['discrete'] = 'n'
  3945. # font
  3946. self.rLegendDict['font'] = self.panelRaster.font['fontCtrl'].GetStringSelection()
  3947. self.rLegendDict['fontsize'] = self.panelRaster.font['fontSizeCtrl'].GetValue()
  3948. color = self.panelRaster.font['colorCtrl'].GetColour()
  3949. self.rLegendDict['color'] = convertRGB(color)
  3950. # position
  3951. x = self.unitConv.convert(value = float(self.panelRaster.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3952. y = self.unitConv.convert(value = float(self.panelRaster.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3953. self.rLegendDict['where'] = (x, y)
  3954. # estimated size
  3955. width = self.panelRaster.widthCtrl.GetValue()
  3956. try:
  3957. width = float(width)
  3958. width = self.unitConv.convert(value = width, fromUnit = currUnit, toUnit = 'inch')
  3959. except ValueError:
  3960. width = None
  3961. self.rLegendDict['width'] = width
  3962. if self.rLegendDict['discrete'] == 'n':
  3963. height = self.panelRaster.heightOrColumnsCtrl.GetValue()
  3964. try:
  3965. height = float(height)
  3966. height = self.unitConv.convert(value = height, fromUnit = currUnit, toUnit = 'inch')
  3967. except ValueError:
  3968. height = None
  3969. self.rLegendDict['height'] = height
  3970. else:
  3971. cols = self.panelRaster.heightOrColumnsCtrl.GetValue()
  3972. self.rLegendDict['cols'] = cols
  3973. drawHeight = self.rasterLegend.EstimateHeight(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
  3974. fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
  3975. height = self.rLegendDict['height'])
  3976. drawWidth = self.rasterLegend.EstimateWidth(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
  3977. fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
  3978. width = self.rLegendDict['width'], paperInstr = self.instruction[self.pageId])
  3979. self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
  3980. # no data
  3981. if self.rLegendDict['discrete'] == 'y':
  3982. if self.nodata.GetValue():
  3983. self.rLegendDict['nodata'] = 'y'
  3984. else:
  3985. self.rLegendDict['nodata'] = 'n'
  3986. # tickbar
  3987. elif self.rLegendDict['discrete'] == 'n':
  3988. if self.ticks.GetValue():
  3989. self.rLegendDict['tickbar'] = 'y'
  3990. else:
  3991. self.rLegendDict['tickbar'] = 'n'
  3992. # range
  3993. if self.range.GetValue():
  3994. self.rLegendDict['range'] = True
  3995. self.rLegendDict['min'] = self.min.GetValue()
  3996. self.rLegendDict['max'] = self.max.GetValue()
  3997. else:
  3998. self.rLegendDict['range'] = False
  3999. if not self.id[0] in self.instruction:
  4000. rasterLegend = RasterLegend(self.id[0])
  4001. self.instruction.AddInstruction(rasterLegend)
  4002. self.instruction[self.id[0]].SetInstruction(self.rLegendDict)
  4003. if self.id[0] not in self.parent.objectId:
  4004. self.parent.objectId.append(self.id[0])
  4005. return True
  4006. def updateVectorLegend(self):
  4007. """!Save information from vector legend dialog to dictionary"""
  4008. vector = self.instruction.FindInstructionByType('vector')
  4009. if vector:
  4010. self.vectorId = vector.id
  4011. else:
  4012. self.vectorId = None
  4013. #is vector legend
  4014. if not self.isVLegend.GetValue():
  4015. self.vLegendDict['vLegend'] = False
  4016. else:
  4017. self.vLegendDict['vLegend'] = True
  4018. if self.vLegendDict['vLegend'] == True and self.vectorId is not None:
  4019. # labels
  4020. #reindex order
  4021. idx = 1
  4022. for item in range(self.vectorListCtrl.GetItemCount()):
  4023. if self.vectorListCtrl.IsChecked(item):
  4024. self.vectorListCtrl.SetItemData(item, idx)
  4025. idx += 1
  4026. else:
  4027. self.vectorListCtrl.SetItemData(item, 0)
  4028. if idx == 1:
  4029. self.vLegendDict['vLegend'] = False
  4030. else:
  4031. vList = self.instruction[self.vectorId]['list']
  4032. for i, vector in enumerate(vList):
  4033. item = self.vectorListCtrl.FindItem(start = -1, str = vector[0].split('@')[0])
  4034. vList[i][3] = self.vectorListCtrl.GetItemData(item)
  4035. vList[i][4] = self.vectorListCtrl.GetItem(item, 1).GetText()
  4036. vmaps = self.instruction.FindInstructionByType('vProperties', list = True)
  4037. for vmap, vector in zip(vmaps, vList):
  4038. self.instruction[vmap.id]['lpos'] = vector[3]
  4039. self.instruction[vmap.id]['label'] = vector[4]
  4040. #units
  4041. currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
  4042. self.vLegendDict['unit'] = currUnit
  4043. # position
  4044. x = self.unitConv.convert(value = float(self.panelVector.position['xCtrl'].GetValue()),
  4045. fromUnit = currUnit, toUnit = 'inch')
  4046. y = self.unitConv.convert(value = float(self.panelVector.position['yCtrl'].GetValue()),
  4047. fromUnit = currUnit, toUnit = 'inch')
  4048. self.vLegendDict['where'] = (x, y)
  4049. # font
  4050. self.vLegendDict['font'] = self.panelVector.font['fontCtrl'].GetStringSelection()
  4051. self.vLegendDict['fontsize'] = self.panelVector.font['fontSizeCtrl'].GetValue()
  4052. dc = wx.ClientDC(self)
  4053. font = dc.GetFont()
  4054. dc.SetFont(wx.Font(pointSize = self.vLegendDict['fontsize'], family = font.GetFamily(),
  4055. style = font.GetStyle(), weight = wx.FONTWEIGHT_NORMAL))
  4056. #size
  4057. width = self.unitConv.convert(value = float(self.panelVector.widthCtrl.GetValue()),
  4058. fromUnit = currUnit, toUnit = 'inch')
  4059. self.vLegendDict['width'] = width
  4060. self.vLegendDict['cols'] = self.panelVector.colsCtrl.GetValue()
  4061. if self.panelVector.spanRadio.GetValue() and self.panelVector.spanTextCtrl.GetValue():
  4062. self.vLegendDict['span'] = self.panelVector.spanTextCtrl.GetValue()
  4063. else:
  4064. self.vLegendDict['span'] = None
  4065. # size estimation
  4066. vectors = self.instruction[self.vectorId]['list']
  4067. labels = [vector[4] for vector in vectors if vector[3] != 0]
  4068. extent = dc.GetTextExtent(max(labels, key = len))
  4069. wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'pixel', toUnit = 'inch')
  4070. hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'pixel', toUnit = 'inch')
  4071. w = (width + wExtent) * self.vLegendDict['cols']
  4072. h = len(labels) * hExtent / self.vLegendDict['cols']
  4073. h *= 1.1
  4074. self.vLegendDict['rect'] = wx.Rect2D(x, y, w, h)
  4075. #border
  4076. if self.borderCheck.GetValue():
  4077. color = self.borderColorCtrl.GetColour()
  4078. self.vLegendDict['border'] = convertRGB(color)
  4079. else:
  4080. self.vLegendDict['border'] = 'none'
  4081. if not self.id[1] in self.instruction:
  4082. vectorLegend = VectorLegend(self.id[1])
  4083. self.instruction.AddInstruction(vectorLegend)
  4084. self.instruction[self.id[1]].SetInstruction(self.vLegendDict)
  4085. if self.id[1] not in self.parent.objectId:
  4086. self.parent.objectId.append(self.id[1])
  4087. return True
  4088. def update(self):
  4089. okR = self.updateRasterLegend()
  4090. okV = self.updateVectorLegend()
  4091. if okR and okV:
  4092. return True
  4093. return False
  4094. def updateDialog(self):
  4095. """!Update legend coordinates after moving"""
  4096. # raster legend
  4097. if 'rect' in self.rLegendDict:
  4098. x, y = self.rLegendDict['rect'][:2]
  4099. currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection())
  4100. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4101. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4102. self.panelRaster.position['xCtrl'].SetValue("%5.3f" % x)
  4103. self.panelRaster.position['yCtrl'].SetValue("%5.3f" % y)
  4104. #update name and type of raster
  4105. raster = self.instruction.FindInstructionByType('raster')
  4106. if raster:
  4107. self.rasterId = raster.id
  4108. else:
  4109. self.rasterId = None
  4110. if raster:
  4111. currRaster = raster['raster']
  4112. else:
  4113. currRaster = None
  4114. rasterType = getRasterType(map = currRaster)
  4115. self.rasterCurrent.SetLabel(_("%(rast)s: type %(type)s") % \
  4116. { 'rast' : currRaster, 'type' : str(rasterType) })
  4117. # vector legend
  4118. if 'rect' in self.vLegendDict:
  4119. x, y = self.vLegendDict['rect'][:2]
  4120. currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
  4121. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4122. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4123. self.panelVector.position['xCtrl'].SetValue("%5.3f" % x)
  4124. self.panelVector.position['yCtrl'].SetValue("%5.3f" % y)
  4125. # update vector maps
  4126. if self.instruction.FindInstructionByType('vector'):
  4127. vectors = sorted(self.instruction.FindInstructionByType('vector')['list'], key = lambda x: x[3])
  4128. self.vectorListCtrl.DeleteAllItems()
  4129. for vector in vectors:
  4130. index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
  4131. self.vectorListCtrl.SetStringItem(index, 1, vector[4])
  4132. self.vectorListCtrl.SetItemData(index, index)
  4133. self.vectorListCtrl.CheckItem(index, True)
  4134. if vector[3] == 0:
  4135. self.vectorListCtrl.CheckItem(index, False)
  4136. self.panelVector.colsCtrl.SetRange(1, min(10, len(self.instruction.FindInstructionByType('vector')['list'])))
  4137. self.panelVector.colsCtrl.SetValue(1)
  4138. else:
  4139. self.vectorListCtrl.DeleteAllItems()
  4140. self.panelVector.colsCtrl.SetRange(0,0)
  4141. self.panelVector.colsCtrl.SetValue(0)
  4142. class MapinfoDialog(PsmapDialog):
  4143. def __init__(self, parent, id, settings):
  4144. PsmapDialog.__init__(self, parent = parent, id = id, title = "Mapinfo settings", settings = settings)
  4145. self.objectType = ('mapinfo',)
  4146. if self.id is not None:
  4147. self.mapinfo = self.instruction[self.id]
  4148. self.mapinfoDict = self.mapinfo.GetInstruction()
  4149. else:
  4150. self.id = wx.NewId()
  4151. self.mapinfo = Mapinfo(self.id)
  4152. self.mapinfoDict = self.mapinfo.GetInstruction()
  4153. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4154. self.mapinfoDict['where'] = page['Left'], page['Top']
  4155. self.panel = self._mapinfoPanel()
  4156. self._layout(self.panel)
  4157. self.OnIsBackground(None)
  4158. self.OnIsBorder(None)
  4159. def _mapinfoPanel(self):
  4160. panel = wx.Panel(parent = self, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  4161. #panel.SetupScrolling(scroll_x = False, scroll_y = True)
  4162. border = wx.BoxSizer(wx.VERTICAL)
  4163. # position
  4164. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4165. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4166. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4167. gridBagSizer.AddGrowableCol(1)
  4168. self.AddPosition(parent = panel, dialogDict = self.mapinfoDict)
  4169. self.AddUnits(parent = panel, dialogDict = self.mapinfoDict)
  4170. gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4171. gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4172. gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4173. gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4174. gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4175. gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4176. gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  4177. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4178. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4179. # font
  4180. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  4181. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4182. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4183. gridBagSizer.AddGrowableCol(1)
  4184. self.AddFont(parent = panel, dialogDict = self.mapinfoDict)#creates font color too, used below
  4185. gridBagSizer.Add(panel.font['fontLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4186. gridBagSizer.Add(panel.font['fontCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4187. gridBagSizer.Add(panel.font['fontSizeLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4188. gridBagSizer.Add(panel.font['fontSizeCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4189. gridBagSizer.Add(panel.font['colorLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4190. gridBagSizer.Add(panel.font['colorCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4191. sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4192. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4193. # colors
  4194. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Color settings"))
  4195. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4196. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  4197. flexSizer.AddGrowableCol(1)
  4198. self.colors = {}
  4199. self.colors['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use border color:"))
  4200. self.colors['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use background color:"))
  4201. self.colors['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4202. self.colors['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4203. if self.mapinfoDict['border'] == None:
  4204. self.mapinfoDict['border'] = 'none'
  4205. if self.mapinfoDict['border'] != 'none':
  4206. self.colors['borderCtrl'].SetValue(True)
  4207. self.colors['borderColor'].SetColour(convertRGB(self.mapinfoDict['border']))
  4208. else:
  4209. self.colors['borderCtrl'].SetValue(False)
  4210. self.colors['borderColor'].SetColour(convertRGB('black'))
  4211. if self.mapinfoDict['background'] == None:
  4212. self.mapinfoDict['background'] == 'none'
  4213. if self.mapinfoDict['background'] != 'none':
  4214. self.colors['backgroundCtrl'].SetValue(True)
  4215. self.colors['backgroundColor'].SetColour(convertRGB(self.mapinfoDict['background']))
  4216. else:
  4217. self.colors['backgroundCtrl'].SetValue(False)
  4218. self.colors['backgroundColor'].SetColour(convertRGB('white'))
  4219. flexSizer.Add(self.colors['borderCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4220. flexSizer.Add(self.colors['borderColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4221. flexSizer.Add(self.colors['backgroundCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4222. flexSizer.Add(self.colors['backgroundColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4223. sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4224. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4225. panel.SetSizer(border)
  4226. self.Bind(wx.EVT_CHECKBOX, self.OnIsBorder, self.colors['borderCtrl'])
  4227. self.Bind(wx.EVT_CHECKBOX, self.OnIsBackground, self.colors['backgroundCtrl'])
  4228. return panel
  4229. def OnIsBackground(self, event):
  4230. if self.colors['backgroundCtrl'].GetValue():
  4231. self.colors['backgroundColor'].Enable()
  4232. self.update()
  4233. else:
  4234. self.colors['backgroundColor'].Disable()
  4235. def OnIsBorder(self, event):
  4236. if self.colors['borderCtrl'].GetValue():
  4237. self.colors['borderColor'].Enable()
  4238. self.update()
  4239. else:
  4240. self.colors['borderColor'].Disable()
  4241. def update(self):
  4242. #units
  4243. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4244. self.mapinfoDict['unit'] = currUnit
  4245. # position
  4246. if self.panel.position['xCtrl'].GetValue():
  4247. x = self.panel.position['xCtrl'].GetValue()
  4248. else:
  4249. x = self.mapinfoDict['where'][0]
  4250. if self.panel.position['yCtrl'].GetValue():
  4251. y = self.panel.position['yCtrl'].GetValue()
  4252. else:
  4253. y = self.mapinfoDict['where'][1]
  4254. x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4255. y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4256. self.mapinfoDict['where'] = (x, y)
  4257. # font
  4258. self.mapinfoDict['font'] = self.panel.font['fontCtrl'].GetStringSelection()
  4259. self.mapinfoDict['fontsize'] = self.panel.font['fontSizeCtrl'].GetValue()
  4260. #colors
  4261. color = self.panel.font['colorCtrl'].GetColour()
  4262. self.mapinfoDict['color'] = convertRGB(color)
  4263. if self.colors['backgroundCtrl'].GetValue():
  4264. background = self.colors['backgroundColor'].GetColour()
  4265. self.mapinfoDict['background'] = convertRGB(background)
  4266. else:
  4267. self.mapinfoDict['background'] = 'none'
  4268. if self.colors['borderCtrl'].GetValue():
  4269. border = self.colors['borderColor'].GetColour()
  4270. self.mapinfoDict['border'] = convertRGB(border)
  4271. else:
  4272. self.mapinfoDict['border'] = 'none'
  4273. # estimation of size
  4274. self.mapinfoDict['rect'] = self.mapinfo.EstimateRect(self.mapinfoDict)
  4275. if self.id not in self.instruction:
  4276. mapinfo = Mapinfo(self.id)
  4277. self.instruction.AddInstruction(mapinfo)
  4278. self.instruction[self.id].SetInstruction(self.mapinfoDict)
  4279. if self.id not in self.parent.objectId:
  4280. self.parent.objectId.append(self.id)
  4281. self.updateDialog()
  4282. return True
  4283. def updateDialog(self):
  4284. """!Update mapinfo coordinates, after moving"""
  4285. x, y = self.mapinfoDict['where']
  4286. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4287. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4288. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4289. self.panel.position['xCtrl'].SetValue("%5.3f" % x)
  4290. self.panel.position['yCtrl'].SetValue("%5.3f" % y)
  4291. class ScalebarDialog(PsmapDialog):
  4292. """!Dialog for scale bar"""
  4293. def __init__(self, parent, id, settings):
  4294. PsmapDialog.__init__(self, parent = parent, id = id, title = "Scale bar settings", settings = settings)
  4295. self.objectType = ('scalebar',)
  4296. if self.id is not None:
  4297. self.scalebar = self.instruction[id]
  4298. self.scalebarDict = self.scalebar.GetInstruction()
  4299. else:
  4300. self.id = wx.NewId()
  4301. self.scalebar = Scalebar(self.id)
  4302. self.scalebarDict = self.scalebar.GetInstruction()
  4303. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4304. self.scalebarDict['where'] = page['Left'], page['Top']
  4305. self.panel = self._scalebarPanel()
  4306. self._layout(self.panel)
  4307. self.mapUnit = projInfo()['units'].lower()
  4308. if projInfo()['proj'] == 'xy':
  4309. self.mapUnit = 'meters'
  4310. if self.mapUnit not in self.unitConv.getAllUnits():
  4311. wx.MessageBox(message = _("Units of current projection are not supported,\n meters will be used!"),
  4312. caption = _('Unsupported units'),
  4313. style = wx.OK|wx.ICON_ERROR)
  4314. self.mapUnit = 'meters'
  4315. def _scalebarPanel(self):
  4316. panel = wx.Panel(parent = self, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4317. border = wx.BoxSizer(wx.VERTICAL)
  4318. #
  4319. # position
  4320. #
  4321. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4322. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4323. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4324. gridBagSizer.AddGrowableCol(1)
  4325. self.AddUnits(parent = panel, dialogDict = self.scalebarDict)
  4326. self.AddPosition(parent = panel, dialogDict = self.scalebarDict)
  4327. if self.scalebarDict['rect']: # set position, ref point is center and not left top corner
  4328. x = self.unitConv.convert(value = self.scalebarDict['where'][0] - self.scalebarDict['rect'].Get()[2]/2,
  4329. fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
  4330. y = self.unitConv.convert(value = self.scalebarDict['where'][1] - self.scalebarDict['rect'].Get()[3]/2,
  4331. fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
  4332. panel.position['xCtrl'].SetValue("%5.3f" % x)
  4333. panel.position['yCtrl'].SetValue("%5.3f" % y)
  4334. gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4335. gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4336. gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4337. gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4338. gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4339. gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4340. gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  4341. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4342. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4343. #
  4344. # size
  4345. #
  4346. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  4347. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4348. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4349. gridBagSizer.AddGrowableCol(1)
  4350. lengthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Length:"))
  4351. heightText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
  4352. self.lengthTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
  4353. self.lengthTextCtrl.SetToolTipString(_("Scalebar length is given in map units"))
  4354. self.heightTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
  4355. self.heightTextCtrl.SetToolTipString(_("Scalebar height is real height on paper"))
  4356. choices = [_('default')] + self.unitConv.getMapUnitsNames()
  4357. self.unitsLength = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
  4358. choices = self.unitConv.getPageUnitsNames()
  4359. self.unitsHeight = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
  4360. # set values
  4361. unitName = self.unitConv.findName(self.scalebarDict['unitsLength'])
  4362. if unitName:
  4363. self.unitsLength.SetStringSelection(unitName)
  4364. else:
  4365. if self.scalebarDict['unitsLength'] == 'auto':
  4366. self.unitsLength.SetSelection(0)
  4367. elif self.scalebarDict['unitsLength'] == 'nautmiles':
  4368. self.unitsLength.SetStringSelection(self.unitConv.findName("nautical miles"))
  4369. self.unitsHeight.SetStringSelection(self.unitConv.findName(self.scalebarDict['unitsHeight']))
  4370. if self.scalebarDict['length']:
  4371. self.lengthTextCtrl.SetValue(str(self.scalebarDict['length']))
  4372. else: #estimate default
  4373. reg = grass.region()
  4374. w = int((reg['e'] - reg['w'])/3)
  4375. w = round(w, -len(str(w)) + 2) #12345 -> 12000
  4376. self.lengthTextCtrl.SetValue(str(w))
  4377. h = self.unitConv.convert(value = self.scalebarDict['height'], fromUnit = 'inch',
  4378. toUnit = self.scalebarDict['unitsHeight'])
  4379. self.heightTextCtrl.SetValue(str(h))
  4380. gridBagSizer.Add(lengthText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4381. gridBagSizer.Add(self.lengthTextCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4382. gridBagSizer.Add(self.unitsLength, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4383. gridBagSizer.Add(heightText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4384. gridBagSizer.Add(self.heightTextCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4385. gridBagSizer.Add(self.unitsHeight, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4386. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4387. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4388. #
  4389. #style
  4390. #
  4391. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Style"))
  4392. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4393. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4394. sbTypeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Type:"))
  4395. self.sbCombo = wx.combo.BitmapComboBox(panel, style = wx.CB_READONLY)
  4396. # only temporary, images must be moved away
  4397. imagePath = os.path.join(globalvar.ETCIMGDIR, "scalebar-fancy.png"), os.path.join(globalvar.ETCIMGDIR, "scalebar-simple.png")
  4398. for item, path in zip(['fancy', 'simple'], imagePath):
  4399. if not os.path.exists(path):
  4400. bitmap = wx.EmptyBitmap(0,0)
  4401. else:
  4402. bitmap = wx.Bitmap(path)
  4403. self.sbCombo.Append(item = '', bitmap = bitmap, clientData = item[0])
  4404. #self.sbCombo.Append(item = 'simple', bitmap = wx.Bitmap("./images/scalebar-simple.png"), clientData = 's')
  4405. if self.scalebarDict['scalebar'] == 'f':
  4406. self.sbCombo.SetSelection(0)
  4407. elif self.scalebarDict['scalebar'] == 's':
  4408. self.sbCombo.SetSelection(1)
  4409. sbSegmentsText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Number of segments:"))
  4410. self.sbSegmentsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 4)
  4411. self.sbSegmentsCtrl.SetValue(self.scalebarDict['segment'])
  4412. sbLabelsText1 = wx.StaticText(panel, id = wx.ID_ANY, label = _("Label every "))
  4413. sbLabelsText2 = wx.StaticText(panel, id = wx.ID_ANY, label = _("segments"))
  4414. self.sbLabelsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
  4415. self.sbLabelsCtrl.SetValue(self.scalebarDict['numbers'])
  4416. #font
  4417. fontsizeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Font size:"))
  4418. self.fontsizeCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 4, max = 30, initial = 10)
  4419. self.fontsizeCtrl.SetValue(self.scalebarDict['fontsize'])
  4420. self.backgroundCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent text background"))
  4421. if self.scalebarDict['background'] == 'y':
  4422. self.backgroundCheck.SetValue(False)
  4423. else:
  4424. self.backgroundCheck.SetValue(True)
  4425. gridBagSizer.Add(sbTypeText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4426. gridBagSizer.Add(self.sbCombo, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4427. gridBagSizer.Add(sbSegmentsText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4428. gridBagSizer.Add(self.sbSegmentsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4429. gridBagSizer.Add(sbLabelsText1, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4430. gridBagSizer.Add(self.sbLabelsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4431. gridBagSizer.Add(sbLabelsText2, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4432. gridBagSizer.Add(fontsizeText, pos = (3,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4433. gridBagSizer.Add(self.fontsizeCtrl, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4434. gridBagSizer.Add(self.backgroundCheck, pos = (4, 0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4435. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL, border = 5)
  4436. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4437. panel.SetSizer(border)
  4438. return panel
  4439. def update(self):
  4440. """!Save information from dialog"""
  4441. #units
  4442. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4443. self.scalebarDict['unit'] = currUnit
  4444. # position
  4445. if self.panel.position['xCtrl'].GetValue():
  4446. x = self.panel.position['xCtrl'].GetValue()
  4447. else:
  4448. x = self.scalebarDict['where'][0]
  4449. if self.panel.position['yCtrl'].GetValue():
  4450. y = self.panel.position['yCtrl'].GetValue()
  4451. else:
  4452. y = self.scalebarDict['where'][1]
  4453. x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4454. y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4455. #style
  4456. self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection())
  4457. self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue()
  4458. self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue()
  4459. self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue()
  4460. if self.backgroundCheck.GetValue():
  4461. self.scalebarDict['background'] = 'n'
  4462. else:
  4463. self.scalebarDict['background'] = 'y'
  4464. # size
  4465. # height
  4466. self.scalebarDict['unitsHeight'] = self.unitConv.findUnit(self.unitsHeight.GetStringSelection())
  4467. try:
  4468. height = float(self.heightTextCtrl.GetValue())
  4469. height = self.unitConv.convert(value = height, fromUnit = self.scalebarDict['unitsHeight'], toUnit = 'inch')
  4470. except (ValueError, SyntaxError):
  4471. height = 0.1 #default in inch
  4472. self.scalebarDict['height'] = height
  4473. #length
  4474. if self.unitsLength.GetSelection() == 0:
  4475. selected = 'auto'
  4476. else:
  4477. selected = self.unitConv.findUnit(self.unitsLength.GetStringSelection())
  4478. if selected == 'nautical miles':
  4479. selected = 'nautmiles'
  4480. self.scalebarDict['unitsLength'] = selected
  4481. try:
  4482. length = float(self.lengthTextCtrl.GetValue())
  4483. except (ValueError, SyntaxError):
  4484. wx.MessageBox(message = _("Length of scale bar is not defined"),
  4485. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  4486. return False
  4487. self.scalebarDict['length'] = length
  4488. # estimation of size
  4489. map = self.instruction.FindInstructionByType('map')
  4490. if not map:
  4491. map = self.instruction.FindInstructionByType('initMap')
  4492. mapId = map.id
  4493. rectSize = self.scalebar.EstimateSize(scalebarDict = self.scalebarDict,
  4494. scale = self.instruction[mapId]['scale'])
  4495. self.scalebarDict['rect'] = wx.Rect2D(x = x, y = y, w = rectSize[0], h = rectSize[1])
  4496. self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre()
  4497. if self.id not in self.instruction:
  4498. scalebar = Scalebar(self.id)
  4499. self.instruction.AddInstruction(scalebar)
  4500. self.instruction[self.id].SetInstruction(self.scalebarDict)
  4501. if self.id not in self.parent.objectId:
  4502. self.parent.objectId.append(self.id)
  4503. return True
  4504. def updateDialog(self):
  4505. """!Update scalebar coordinates, after moving"""
  4506. x, y = self.scalebarDict['rect'][:2]
  4507. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4508. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4509. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4510. self.panel.position['xCtrl'].SetValue("%5.3f" % x)
  4511. self.panel.position['yCtrl'].SetValue("%5.3f" % y)
  4512. class TextDialog(PsmapDialog):
  4513. def __init__(self, parent, id, settings):
  4514. PsmapDialog.__init__(self, parent = parent, id = id, title = "Text settings", settings = settings)
  4515. self.objectType = ('text',)
  4516. if self.id is not None:
  4517. self.textDict = self.instruction[id].GetInstruction()
  4518. else:
  4519. self.id = wx.NewId()
  4520. text = Text(self.id)
  4521. self.textDict = text.GetInstruction()
  4522. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4523. self.textDict['where'] = page['Left'], page['Top']
  4524. map = self.instruction.FindInstructionByType('map')
  4525. if not map:
  4526. map = self.instruction.FindInstructionByType('initMap')
  4527. self.mapId = map.id
  4528. self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(map = map, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
  4529. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  4530. self.textPanel = self._textPanel(notebook)
  4531. self.positionPanel = self._positionPanel(notebook)
  4532. self.OnBackground(None)
  4533. self.OnHighlight(None)
  4534. self.OnBorder(None)
  4535. self.OnPositionType(None)
  4536. self.OnRotation(None)
  4537. self._layout(notebook)
  4538. def _textPanel(self, notebook):
  4539. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4540. notebook.AddPage(page = panel, text = _("Text"))
  4541. border = wx.BoxSizer(wx.VERTICAL)
  4542. # text entry
  4543. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text"))
  4544. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4545. textLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Enter text:"))
  4546. self.textCtrl = ExpandoTextCtrl(panel, id = wx.ID_ANY, value = self.textDict['text'])
  4547. sizer.Add(textLabel, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4548. sizer.Add(self.textCtrl, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4549. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4550. #font
  4551. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  4552. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4553. flexGridSizer = wx.FlexGridSizer (rows = 3, cols = 2, hgap = 5, vgap = 5)
  4554. flexGridSizer.AddGrowableCol(1)
  4555. self.AddFont(parent = panel, dialogDict = self.textDict)
  4556. flexGridSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4557. flexGridSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4558. flexGridSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4559. flexGridSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4560. flexGridSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4561. flexGridSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4562. sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4563. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4564. #text effects
  4565. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text effects"))
  4566. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4567. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4568. self.effect = {}
  4569. self.effect['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text background"))
  4570. self.effect['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4571. self.effect['highlightCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("highlight"))
  4572. self.effect['highlightColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4573. self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 0, max = 5, initial = 1)
  4574. self.effect['highlightWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  4575. self.effect['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text border"))
  4576. self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4577. self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 1, max = 25, initial = 1)
  4578. self.effect['borderWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  4579. #set values
  4580. if self.textDict['background'] == None:
  4581. self.textDict['background'] = 'none'
  4582. if self.textDict['background'] != 'none':
  4583. self.effect['backgroundCtrl'].SetValue(True)
  4584. self.effect['backgroundColor'].SetColour(convertRGB(self.textDict['background']))
  4585. else:
  4586. self.effect['backgroundCtrl'].SetValue(False)
  4587. self.effect['backgroundColor'].SetColour(convertRGB('white'))
  4588. if self.textDict['hcolor'] == None:
  4589. self.textDict['hcolor'] = 'none'
  4590. if self.textDict['hcolor'] != 'none':
  4591. self.effect['highlightCtrl'].SetValue(True)
  4592. self.effect['highlightColor'].SetColour(convertRGB(self.textDict['hcolor']))
  4593. else:
  4594. self.effect['highlightCtrl'].SetValue(False)
  4595. self.effect['highlightColor'].SetColour(convertRGB('grey'))
  4596. self.effect['highlightWidth'].SetValue(float(self.textDict['hwidth']))
  4597. if self.textDict['border'] == None:
  4598. self.textDict['border'] = 'none'
  4599. if self.textDict['border'] != 'none':
  4600. self.effect['borderCtrl'].SetValue(True)
  4601. self.effect['borderColor'].SetColour(convertRGB(self.textDict['border']))
  4602. else:
  4603. self.effect['borderCtrl'].SetValue(False)
  4604. self.effect['borderColor'].SetColour(convertRGB('black'))
  4605. self.effect['borderWidth'].SetValue(float(self.textDict['width']))
  4606. gridBagSizer.Add(self.effect['backgroundCtrl'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4607. gridBagSizer.Add(self.effect['backgroundColor'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4608. gridBagSizer.Add(self.effect['highlightCtrl'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4609. gridBagSizer.Add(self.effect['highlightColor'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4610. gridBagSizer.Add(self.effect['highlightWidthLabel'], pos = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4611. gridBagSizer.Add(self.effect['highlightWidth'], pos = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4612. gridBagSizer.Add(self.effect['borderCtrl'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4613. gridBagSizer.Add(self.effect['borderColor'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4614. gridBagSizer.Add(self.effect['borderWidthLabel'], pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4615. gridBagSizer.Add(self.effect['borderWidth'], pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4616. sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4617. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4618. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textCtrl)
  4619. self.Bind(wx.EVT_CHECKBOX, self.OnBackground, self.effect['backgroundCtrl'])
  4620. self.Bind(wx.EVT_CHECKBOX, self.OnHighlight, self.effect['highlightCtrl'])
  4621. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.effect['borderCtrl'])
  4622. panel.SetSizer(border)
  4623. panel.Fit()
  4624. return panel
  4625. def _positionPanel(self, notebook):
  4626. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4627. notebook.AddPage(page = panel, text = _("Position"))
  4628. border = wx.BoxSizer(wx.VERTICAL)
  4629. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4630. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4631. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4632. gridBagSizer.AddGrowableCol(0)
  4633. gridBagSizer.AddGrowableCol(1)
  4634. #Position
  4635. self.AddExtendedPosition(panel, gridBagSizer, self.textDict)
  4636. #offset
  4637. box3 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Offset"))
  4638. sizerO = wx.StaticBoxSizer(box3, wx.VERTICAL)
  4639. gridBagSizerO = wx.GridBagSizer (hgap = 5, vgap = 5)
  4640. self.xoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("horizontal (pts):"))
  4641. self.yoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("vertical (pts):"))
  4642. self.xoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
  4643. self.yoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
  4644. self.xoffCtrl.SetValue(self.textDict['xoffset'])
  4645. self.yoffCtrl.SetValue(self.textDict['yoffset'])
  4646. gridBagSizerO.Add(self.xoffLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4647. gridBagSizerO.Add(self.yoffLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4648. gridBagSizerO.Add(self.xoffCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4649. gridBagSizerO.Add(self.yoffCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4650. sizerO.Add(gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4651. gridBagSizer.Add(sizerO, pos = (3,0), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
  4652. # reference point
  4653. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_(" Reference point"))
  4654. sizerR = wx.StaticBoxSizer(box, wx.VERTICAL)
  4655. flexSizer = wx.FlexGridSizer(rows = 3, cols = 3, hgap = 5, vgap = 5)
  4656. flexSizer.AddGrowableCol(0)
  4657. flexSizer.AddGrowableCol(1)
  4658. flexSizer.AddGrowableCol(2)
  4659. ref = []
  4660. for row in ["upper", "center", "lower"]:
  4661. for col in ["left", "center", "right"]:
  4662. ref.append(row + " " + col)
  4663. self.radio = [wx.RadioButton(panel, id = wx.ID_ANY, label = '', style = wx.RB_GROUP, name = ref[0])]
  4664. self.radio[0].SetValue(False)
  4665. flexSizer.Add(self.radio[0], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4666. for i in range(1,9):
  4667. self.radio.append(wx.RadioButton(panel, id = wx.ID_ANY, label = '', name = ref[i]))
  4668. self.radio[-1].SetValue(False)
  4669. flexSizer.Add(self.radio[-1], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4670. self.FindWindowByName(self.textDict['ref']).SetValue(True)
  4671. sizerR.Add(flexSizer, proportion = 1, flag = wx.EXPAND, border = 0)
  4672. gridBagSizer.Add(sizerR, pos = (3,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
  4673. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4674. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4675. #rotation
  4676. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text rotation"))
  4677. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4678. self.rotCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate text (counterclockwise)"))
  4679. self.rotValue = wx.SpinCtrl(panel, wx.ID_ANY, size = (50, -1), min = 0, max = 360, initial = 0)
  4680. if self.textDict['rotate']:
  4681. self.rotValue.SetValue(int(self.textDict['rotate']))
  4682. self.rotCtrl.SetValue(True)
  4683. else:
  4684. self.rotValue.SetValue(0)
  4685. self.rotCtrl.SetValue(False)
  4686. sizer.Add(self.rotCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
  4687. sizer.Add(self.rotValue, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
  4688. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4689. panel.SetSizer(border)
  4690. panel.Fit()
  4691. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper'])
  4692. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
  4693. self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotCtrl)
  4694. return panel
  4695. def OnRefit(self, event):
  4696. self.Fit()
  4697. def OnRotation(self, event):
  4698. if self.rotCtrl.GetValue():
  4699. self.rotValue.Enable()
  4700. else:
  4701. self.rotValue.Disable()
  4702. def OnPositionType(self, event):
  4703. if self.positionPanel.position['toPaper'].GetValue():
  4704. for widget in self.gridBagSizerP.GetChildren():
  4705. widget.GetWindow().Enable()
  4706. for widget in self.gridBagSizerM.GetChildren():
  4707. widget.GetWindow().Disable()
  4708. else:
  4709. for widget in self.gridBagSizerM.GetChildren():
  4710. widget.GetWindow().Enable()
  4711. for widget in self.gridBagSizerP.GetChildren():
  4712. widget.GetWindow().Disable()
  4713. def OnBackground(self, event):
  4714. if self.effect['backgroundCtrl'].GetValue():
  4715. self.effect['backgroundColor'].Enable()
  4716. self.update()
  4717. else:
  4718. self.effect['backgroundColor'].Disable()
  4719. def OnHighlight(self, event):
  4720. if self.effect['highlightCtrl'].GetValue():
  4721. self.effect['highlightColor'].Enable()
  4722. self.effect['highlightWidth'].Enable()
  4723. self.effect['highlightWidthLabel'].Enable()
  4724. self.update()
  4725. else:
  4726. self.effect['highlightColor'].Disable()
  4727. self.effect['highlightWidth'].Disable()
  4728. self.effect['highlightWidthLabel'].Disable()
  4729. def OnBorder(self, event):
  4730. if self.effect['borderCtrl'].GetValue():
  4731. self.effect['borderColor'].Enable()
  4732. self.effect['borderWidth'].Enable()
  4733. self.effect['borderWidthLabel'].Enable()
  4734. self.update()
  4735. else:
  4736. self.effect['borderColor'].Disable()
  4737. self.effect['borderWidth'].Disable()
  4738. self.effect['borderWidthLabel'].Disable()
  4739. def update(self):
  4740. #text
  4741. self.textDict['text'] = self.textCtrl.GetValue()
  4742. if not self.textDict['text']:
  4743. wx.MessageBox(_("No text entered!"), _("Error"))
  4744. return False
  4745. #font
  4746. self.textDict['font'] = self.textPanel.font['fontCtrl'].GetStringSelection()
  4747. self.textDict['fontsize'] = self.textPanel.font['fontSizeCtrl'].GetValue()
  4748. color = self.textPanel.font['colorCtrl'].GetColour()
  4749. self.textDict['color'] = convertRGB(color)
  4750. #effects
  4751. if self.effect['backgroundCtrl'].GetValue():
  4752. background = self.effect['backgroundColor'].GetColour()
  4753. self.textDict['background'] = convertRGB(background)
  4754. else:
  4755. self.textDict['background'] = 'none'
  4756. if self.effect['borderCtrl'].GetValue():
  4757. border = self.effect['borderColor'].GetColour()
  4758. self.textDict['border'] = convertRGB(border)
  4759. else:
  4760. self.textDict['border'] = 'none'
  4761. self.textDict['width'] = self.effect['borderWidth'].GetValue()
  4762. if self.effect['highlightCtrl'].GetValue():
  4763. highlight = self.effect['highlightColor'].GetColour()
  4764. self.textDict['hcolor'] = convertRGB(highlight)
  4765. else:
  4766. self.textDict['hcolor'] = 'none'
  4767. self.textDict['hwidth'] = self.effect['highlightWidth'].GetValue()
  4768. #offset
  4769. self.textDict['xoffset'] = self.xoffCtrl.GetValue()
  4770. self.textDict['yoffset'] = self.yoffCtrl.GetValue()
  4771. #position
  4772. if self.positionPanel.position['toPaper'].GetValue():
  4773. self.textDict['XY'] = True
  4774. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  4775. self.textDict['unit'] = currUnit
  4776. if self.positionPanel.position['xCtrl'].GetValue():
  4777. x = self.positionPanel.position['xCtrl'].GetValue()
  4778. else:
  4779. x = self.textDict['where'][0]
  4780. if self.positionPanel.position['yCtrl'].GetValue():
  4781. y = self.positionPanel.position['yCtrl'].GetValue()
  4782. else:
  4783. y = self.textDict['where'][1]
  4784. x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
  4785. y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
  4786. self.textDict['where'] = x, y
  4787. self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self.instruction[self.mapId], x, y, paperToMap = True)
  4788. else:
  4789. self.textDict['XY'] = False
  4790. if self.positionPanel.position['eCtrl'].GetValue():
  4791. self.textDict['east'] = self.positionPanel.position['eCtrl'].GetValue()
  4792. else:
  4793. self.textDict['east'] = self.textDict['east']
  4794. if self.positionPanel.position['nCtrl'].GetValue():
  4795. self.textDict['north'] = self.positionPanel.position['nCtrl'].GetValue()
  4796. else:
  4797. self.textDict['north'] = self.textDict['north']
  4798. self.textDict['where'] = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.textDict['east']),
  4799. y = float(self.textDict['north']), paperToMap = False)
  4800. #rotation
  4801. if self.rotCtrl.GetValue():
  4802. self.textDict['rotate'] = self.rotValue.GetValue()
  4803. else:
  4804. self.textDict['rotate'] = None
  4805. #reference point
  4806. for radio in self.radio:
  4807. if radio.GetValue() == True:
  4808. self.textDict['ref'] = radio.GetName()
  4809. if self.id not in self.instruction:
  4810. text = Text(self.id)
  4811. self.instruction.AddInstruction(text)
  4812. self.instruction[self.id].SetInstruction(self.textDict)
  4813. if self.id not in self.parent.objectId:
  4814. self.parent.objectId.append(self.id)
  4815. # self.updateDialog()
  4816. return True
  4817. def updateDialog(self):
  4818. """!Update text coordinates, after moving"""
  4819. # XY coordinates
  4820. x, y = self.textDict['where'][:2]
  4821. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  4822. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4823. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4824. self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
  4825. self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
  4826. # EN coordinates
  4827. e, n = self.textDict['east'], self.textDict['north']
  4828. self.positionPanel.position['eCtrl'].SetValue(str(self.textDict['east']))
  4829. self.positionPanel.position['nCtrl'].SetValue(str(self.textDict['north']))
  4830. class ImageDialog(PsmapDialog):
  4831. """!Dialog for setting image properties.
  4832. It's base dialog for North Arrow dialog.
  4833. """
  4834. def __init__(self, parent, id, settings, imagePanelName = _("Image")):
  4835. PsmapDialog.__init__(self, parent = parent, id = id, title = "Image settings",
  4836. settings = settings)
  4837. self.objectType = ('image',)
  4838. if self.id is not None:
  4839. self.imageObj = self.instruction[self.id]
  4840. self.imageDict = self.instruction[id].GetInstruction()
  4841. else:
  4842. self.id = wx.NewId()
  4843. self.imageObj = self._newObject()
  4844. self.imageDict = self.imageObj.GetInstruction()
  4845. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4846. self.imageDict['where'] = page['Left'], page['Top']
  4847. map = self.instruction.FindInstructionByType('map')
  4848. if not map:
  4849. map = self.instruction.FindInstructionByType('initMap')
  4850. self.mapId = map.id
  4851. self.imageDict['east'], self.imageDict['north'] = PaperMapCoordinates(map = map, x = self.imageDict['where'][0], y = self.imageDict['where'][1], paperToMap = True)
  4852. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  4853. self.imagePanelName = imagePanelName
  4854. self.imagePanel = self._imagePanel(notebook)
  4855. self.positionPanel = self._positionPanel(notebook)
  4856. self.OnPositionType(None)
  4857. if self.imageDict['epsfile']:
  4858. self.imagePanel.image['dir'].SetValue(os.path.dirname(self.imageDict['epsfile']))
  4859. else:
  4860. self.imagePanel.image['dir'].SetValue(self._getImageDirectory())
  4861. self.OnDirChanged(None)
  4862. self._layout(notebook)
  4863. def _newObject(self):
  4864. """!Create corresponding instruction object"""
  4865. return Image(self.id, self.instruction)
  4866. def _imagePanel(self, notebook):
  4867. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  4868. notebook.AddPage(page = panel, text = self.imagePanelName)
  4869. border = wx.BoxSizer(wx.VERTICAL)
  4870. #
  4871. # choose image
  4872. #
  4873. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Image"))
  4874. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4875. # choose directory
  4876. panel.image = {}
  4877. if self.imageDict['epsfile']:
  4878. startDir = os.path.dirname(self.imageDict['epsfile'])
  4879. else:
  4880. startDir = self._getImageDirectory()
  4881. dir = filebrowse.DirBrowseButton(parent = panel, id = wx.ID_ANY,
  4882. labelText = _("Choose a directory:"),
  4883. dialogTitle = _("Choose a directory with images"),
  4884. buttonText = _('Browse'),
  4885. startDirectory = startDir,
  4886. changeCallback = self.OnDirChanged)
  4887. panel.image['dir'] = dir
  4888. sizer.Add(item = dir, proportion = 0, flag = wx.EXPAND, border = 0)
  4889. # image list
  4890. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  4891. imageList = wx.ListBox(parent = panel, id = wx.ID_ANY)
  4892. panel.image['list'] = imageList
  4893. imageList.Bind(wx.EVT_LISTBOX, self.OnImageSelectionChanged)
  4894. hSizer.Add(item = imageList, proportion = 1, flag = wx.EXPAND | wx.RIGHT, border = 10)
  4895. # image preview
  4896. vSizer = wx.BoxSizer(wx.VERTICAL)
  4897. self.previewSize = (150, 150)
  4898. img = wx.EmptyImage(*self.previewSize)
  4899. panel.image['preview'] = wx.StaticBitmap(parent = panel, id = wx.ID_ANY,
  4900. bitmap = wx.BitmapFromImage(img))
  4901. vSizer.Add(item = panel.image['preview'], proportion = 0, flag = wx.EXPAND | wx.BOTTOM, border = 5)
  4902. panel.image['sizeInfo'] = wx.StaticText(parent = panel, id = wx.ID_ANY)
  4903. vSizer.Add(item = panel.image['sizeInfo'], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4904. hSizer.Add(item = vSizer, proportion = 0, flag = wx.EXPAND, border = 0)
  4905. sizer.Add(item = hSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 3)
  4906. epsInfo = wx.StaticText(parent = panel, id = wx.ID_ANY,
  4907. label = _("Note: only EPS format supported"))
  4908. sizer.Add(item = epsInfo, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 3)
  4909. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4910. #
  4911. # rotation
  4912. #
  4913. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Scale And Rotation"))
  4914. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4915. gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4916. scaleLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Scale:"))
  4917. if fs:
  4918. panel.image['scale'] = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 50,
  4919. increment = 0.5, value = 1, style = fs.FS_RIGHT, size = self.spinCtrlSize)
  4920. panel.image['scale'].SetFormat("%f")
  4921. panel.image['scale'].SetDigits(1)
  4922. else:
  4923. panel.image['scale'] = wx.TextCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize,
  4924. validator = TCValidator(flag = 'DIGIT_ONLY'))
  4925. if self.imageDict['scale']:
  4926. if fs:
  4927. value = float(self.imageDict['scale'])
  4928. else:
  4929. value = str(self.imageDict['scale'])
  4930. else:
  4931. if fs:
  4932. value = 0
  4933. else:
  4934. value = '0'
  4935. panel.image['scale'].SetValue(value)
  4936. gridSizer.Add(item = scaleLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  4937. gridSizer.Add(item = panel.image['scale'], pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
  4938. rotLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Rotation angle (deg):"))
  4939. if fs:
  4940. panel.image['rotate'] = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 360,
  4941. increment = 0.5, value = 0, style = fs.FS_RIGHT, size = self.spinCtrlSize)
  4942. panel.image['rotate'].SetFormat("%f")
  4943. panel.image['rotate'].SetDigits(1)
  4944. else:
  4945. panel.image['rotate'] = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = self.spinCtrlSize,
  4946. min = 0, max = 359, initial = 0)
  4947. panel.image['rotate'].SetToolTipString(_("Counterclockwise rotation in degrees"))
  4948. if self.imageDict['rotate']:
  4949. panel.image['rotate'].SetValue(int(self.imageDict['rotate']))
  4950. else:
  4951. panel.image['rotate'].SetValue(0)
  4952. gridSizer.Add(item = rotLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4953. gridSizer.Add(item = panel.image['rotate'], pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
  4954. self._addConvergence(panel = panel, gridBagSizer = gridSizer)
  4955. sizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
  4956. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4957. panel.SetSizer(border)
  4958. panel.Fit()
  4959. return panel
  4960. def _positionPanel(self, notebook):
  4961. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  4962. notebook.AddPage(page = panel, text = _("Position"))
  4963. border = wx.BoxSizer(wx.VERTICAL)
  4964. #
  4965. # set position
  4966. #
  4967. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4968. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4969. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4970. gridBagSizer.AddGrowableCol(0)
  4971. gridBagSizer.AddGrowableCol(1)
  4972. self.AddExtendedPosition(panel, gridBagSizer, self.imageDict)
  4973. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper'])
  4974. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
  4975. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL| wx.ALL, border = 5)
  4976. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4977. panel.SetSizer(border)
  4978. panel.Fit()
  4979. return panel
  4980. def OnDirChanged(self, event):
  4981. """!Image directory changed"""
  4982. path = self.imagePanel.image['dir'].GetValue()
  4983. try:
  4984. files = os.listdir(path)
  4985. except OSError: # no such directory
  4986. files = []
  4987. imageList = []
  4988. # no setter for startDirectory?
  4989. try:
  4990. self.imagePanel.image['dir'].startDirectory = path
  4991. except AttributeError: # for sure
  4992. pass
  4993. for file in files:
  4994. if os.path.splitext(file)[1].lower() == '.eps':
  4995. imageList.append(file)
  4996. imageList.sort()
  4997. self.imagePanel.image['list'].SetItems(imageList)
  4998. if self.imageDict['epsfile']:
  4999. file = os.path.basename(self.imageDict['epsfile'])
  5000. self.imagePanel.image['list'].SetStringSelection(file)
  5001. elif imageList:
  5002. self.imagePanel.image['list'].SetSelection(0)
  5003. self.OnImageSelectionChanged(None)
  5004. def OnPositionType(self, event):
  5005. if self.positionPanel.position['toPaper'].GetValue():
  5006. for widget in self.gridBagSizerP.GetChildren():
  5007. widget.GetWindow().Enable()
  5008. for widget in self.gridBagSizerM.GetChildren():
  5009. widget.GetWindow().Disable()
  5010. else:
  5011. for widget in self.gridBagSizerM.GetChildren():
  5012. widget.GetWindow().Enable()
  5013. for widget in self.gridBagSizerP.GetChildren():
  5014. widget.GetWindow().Disable()
  5015. def _getImageDirectory(self):
  5016. """!Default image directory"""
  5017. return os.getcwd()
  5018. def _addConvergence(self, panel, gridBagSizer):
  5019. pass
  5020. def OnImageSelectionChanged(self, event):
  5021. """!Image selected, show preview and size"""
  5022. if not self.imagePanel.image['dir']: # event is emitted when closing dialog an it causes error
  5023. return
  5024. if not havePILImage:
  5025. self.DrawWarningText(_("PIL\nmissing"))
  5026. return
  5027. imageName = self.imagePanel.image['list'].GetStringSelection()
  5028. if not imageName:
  5029. self.ClearPreview()
  5030. return
  5031. basePath = self.imagePanel.image['dir'].GetValue()
  5032. file = os.path.join(basePath, imageName)
  5033. if not os.path.exists(file):
  5034. return
  5035. if os.path.splitext(file)[1].lower() == '.eps':
  5036. try:
  5037. pImg = PILImage.open(file)
  5038. img = PilImageToWxImage(pImg)
  5039. except IOError, e:
  5040. GError(message = _("Unable to read file %s") % file)
  5041. self.ClearPreview()
  5042. return
  5043. self.SetSizeInfoLabel(img)
  5044. img = self.ScaleToPreview(img)
  5045. bitmap = img.ConvertToBitmap()
  5046. self.DrawBitmap(bitmap)
  5047. else:
  5048. # TODO: read other formats and convert by PIL to eps
  5049. pass
  5050. def ScaleToPreview(self, img):
  5051. """!Scale image to preview size"""
  5052. w = img.GetWidth()
  5053. h = img.GetHeight()
  5054. if w <= self.previewSize[0] and h <= self.previewSize[1]:
  5055. return img
  5056. if w > h:
  5057. newW = self.previewSize[0]
  5058. newH = self.previewSize[0] * h / w
  5059. else:
  5060. newH = self.previewSize[0]
  5061. newW = self.previewSize[0] * w / h
  5062. return img.Scale(newW, newH, wx.IMAGE_QUALITY_HIGH)
  5063. def DrawWarningText(self, warning):
  5064. """!Draw text on preview window"""
  5065. buffer = wx.EmptyBitmap(*self.previewSize)
  5066. dc = wx.MemoryDC()
  5067. dc.SelectObject(buffer)
  5068. dc.SetBrush(wx.Brush(wx.Color(250, 250, 250)))
  5069. dc.Clear()
  5070. extent = dc.GetTextExtent(warning)
  5071. posX = self.previewSize[0] / 2 - extent[0] / 2
  5072. posY = self.previewSize[1] / 2 - extent[1] / 2
  5073. dc.DrawText(warning, posX, posY)
  5074. self.imagePanel.image['preview'].SetBitmap(buffer)
  5075. dc.SelectObject(wx.NullBitmap)
  5076. def DrawBitmap(self, bitmap):
  5077. """!Draw bitmap, center it if smaller than preview size"""
  5078. if bitmap.GetWidth() <= self.previewSize[0] and bitmap.GetHeight() <= self.previewSize[1]:
  5079. buffer = wx.EmptyBitmap(*self.previewSize)
  5080. dc = wx.MemoryDC()
  5081. dc.SelectObject(buffer)
  5082. dc.SetBrush(dc.GetBrush())
  5083. dc.Clear()
  5084. posX = self.previewSize[0] / 2 - bitmap.GetWidth() / 2
  5085. posY = self.previewSize[1] / 2 - bitmap.GetHeight() / 2
  5086. dc.DrawBitmap(bitmap, posX, posY)
  5087. self.imagePanel.image['preview'].SetBitmap(buffer)
  5088. dc.SelectObject(wx.NullBitmap)
  5089. else:
  5090. self.imagePanel.image['preview'].SetBitmap(bitmap)
  5091. def SetSizeInfoLabel(self, image):
  5092. """!Update image size label"""
  5093. self.imagePanel.image['sizeInfo'].SetLabel(_("size: %s x %s pts") % (image.GetWidth(), image.GetHeight()))
  5094. self.imagePanel.image['sizeInfo'].GetContainingSizer().Layout()
  5095. def ClearPreview(self):
  5096. """!Clear preview window"""
  5097. buffer = wx.EmptyBitmap(*self.previewSize)
  5098. dc = wx.MemoryDC()
  5099. dc.SelectObject(buffer)
  5100. dc.SetBrush(wx.WHITE_BRUSH)
  5101. dc.Clear()
  5102. mask = wx.Mask(buffer, wx.WHITE)
  5103. buffer.SetMask(mask)
  5104. self.imagePanel.image['preview'].SetBitmap(buffer)
  5105. dc.SelectObject(wx.NullBitmap)
  5106. def update(self):
  5107. # epsfile
  5108. selected = self.imagePanel.image['list'].GetStringSelection()
  5109. basePath = self.imagePanel.image['dir'].GetValue()
  5110. if not selected:
  5111. gcmd.GMessage(parent = self, message = _("No image selected."))
  5112. return False
  5113. self.imageDict['epsfile'] = os.path.join(basePath, selected)
  5114. #position
  5115. if self.positionPanel.position['toPaper'].GetValue():
  5116. self.imageDict['XY'] = True
  5117. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  5118. self.imageDict['unit'] = currUnit
  5119. if self.positionPanel.position['xCtrl'].GetValue():
  5120. x = self.positionPanel.position['xCtrl'].GetValue()
  5121. else:
  5122. x = self.imageDict['where'][0]
  5123. if self.positionPanel.position['yCtrl'].GetValue():
  5124. y = self.positionPanel.position['yCtrl'].GetValue()
  5125. else:
  5126. y = self.imageDict['where'][1]
  5127. x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
  5128. y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
  5129. self.imageDict['where'] = x, y
  5130. else:
  5131. self.imageDict['XY'] = False
  5132. if self.positionPanel.position['eCtrl'].GetValue():
  5133. e = self.positionPanel.position['eCtrl'].GetValue()
  5134. else:
  5135. self.imageDict['east'] = self.imageDict['east']
  5136. if self.positionPanel.position['nCtrl'].GetValue():
  5137. n = self.positionPanel.position['nCtrl'].GetValue()
  5138. else:
  5139. self.imageDict['north'] = self.imageDict['north']
  5140. x, y = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.imageDict['east']),
  5141. y = float(self.imageDict['north']), paperToMap = False)
  5142. #rotation
  5143. rot = self.imagePanel.image['rotate'].GetValue()
  5144. if rot == 0:
  5145. self.imageDict['rotate'] = None
  5146. else:
  5147. self.imageDict['rotate'] = rot
  5148. #scale
  5149. self.imageDict['scale'] = self.imagePanel.image['scale'].GetValue()
  5150. # scale
  5151. w, h = self.imageObj.GetImageOrigSize(self.imageDict['epsfile'])
  5152. if self.imageDict['rotate']:
  5153. self.imageDict['size'] = BBoxAfterRotation(w, h, self.imageDict['rotate'])
  5154. else:
  5155. self.imageDict['size'] = w, h
  5156. w = self.unitConv.convert(value = self.imageDict['size'][0],
  5157. fromUnit = 'point', toUnit = 'inch')
  5158. h = self.unitConv.convert(value = self.imageDict['size'][1],
  5159. fromUnit = 'point', toUnit = 'inch')
  5160. self.imageDict['rect'] = wx.Rect2D(x = x, y = y,
  5161. w = w * self.imageDict['scale'],
  5162. h = h * self.imageDict['scale'])
  5163. if self.id not in self.instruction:
  5164. image = self._newObject()
  5165. self.instruction.AddInstruction(image)
  5166. self.instruction[self.id].SetInstruction(self.imageDict)
  5167. if self.id not in self.parent.objectId:
  5168. self.parent.objectId.append(self.id)
  5169. return True
  5170. def updateDialog(self):
  5171. """!Update text coordinates, after moving"""
  5172. # XY coordinates
  5173. x, y = self.imageDict['where'][:2]
  5174. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  5175. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  5176. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  5177. self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
  5178. self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
  5179. # EN coordinates
  5180. e, n = self.imageDict['east'], self.imageDict['north']
  5181. self.positionPanel.position['eCtrl'].SetValue(str(self.imageDict['east']))
  5182. self.positionPanel.position['nCtrl'].SetValue(str(self.imageDict['north']))
  5183. class NorthArrowDialog(ImageDialog):
  5184. def __init__(self, parent, id, settings):
  5185. ImageDialog.__init__(self, parent = parent, id = id, settings = settings,
  5186. imagePanelName = _("North Arrow"))
  5187. self.objectType = ('northArrow',)
  5188. self.SetTitle(_("North Arrow settings"))
  5189. def _newObject(self):
  5190. return NorthArrow(self.id, self.instruction)
  5191. def _getImageDirectory(self):
  5192. gisbase = os.getenv("GISBASE")
  5193. return os.path.join(gisbase, 'etc', 'paint', 'decorations')
  5194. def _addConvergence(self, panel, gridBagSizer):
  5195. convergence = wx.Button(parent = panel, id = wx.ID_ANY,
  5196. label = _("Compute convergence"))
  5197. gridBagSizer.Add(item = convergence, pos = (1, 2),
  5198. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  5199. convergence.Bind(wx.EVT_BUTTON, self.OnConvergence)
  5200. panel.image['convergence'] = convergence
  5201. def OnConvergence(self, event):
  5202. ret = RunCommand('g.region', read = True, flags = 'ng')
  5203. if ret:
  5204. convergence = float(ret.strip().split('=')[1])
  5205. if convergence < 0:
  5206. self.imagePanel.image['rotate'].SetValue(abs(convergence))
  5207. else:
  5208. self.imagePanel.image['rotate'].SetValue(360 - convergence)
  5209. def convertRGB(rgb):
  5210. """!Converts wx.Colour(r,g,b,a) to string 'r:g:b' or named color,
  5211. or named color/r:g:b string to wx.Colour, depending on input"""
  5212. # transform a wx.Colour tuple into an r:g:b string
  5213. if type(rgb) == wx.Colour:
  5214. for name, color in grass.named_colors.items():
  5215. if rgb.Red() == int(color[0] * 255) and\
  5216. rgb.Green() == int(color[1] * 255) and\
  5217. rgb.Blue() == int(color[2] * 255):
  5218. return name
  5219. return str(rgb.Red()) + ':' + str(rgb.Green()) + ':' + str(rgb.Blue())
  5220. # transform a GRASS named color or an r:g:b string into a wx.Colour tuple
  5221. else:
  5222. color = (grass.parse_color(rgb)[0]*255,
  5223. grass.parse_color(rgb)[1]*255,
  5224. grass.parse_color(rgb)[2]*255)
  5225. color = wx.Color(*color)
  5226. if color.IsOk():
  5227. return color
  5228. else:
  5229. return None
  5230. def PaperMapCoordinates(map, x, y, paperToMap = True):
  5231. """!Converts paper (inch) coordinates -> map coordinates"""
  5232. unitConv = UnitConversion()
  5233. currRegionDict = grass.region()
  5234. cornerEasting, cornerNorthing = currRegionDict['w'], currRegionDict['n']
  5235. xMap = map['rect'][0]
  5236. yMap = map['rect'][1]
  5237. widthMap = map['rect'][2] * 0.0254 # to meter
  5238. heightMap = map['rect'][3] * 0.0254
  5239. xScale = widthMap / abs(currRegionDict['w'] - currRegionDict['e'])
  5240. yScale = heightMap / abs(currRegionDict['n'] - currRegionDict['s'])
  5241. currScale = (xScale + yScale) / 2
  5242. if not paperToMap:
  5243. textEasting, textNorthing = x, y
  5244. eastingDiff = textEasting - cornerEasting
  5245. if currRegionDict['w'] > currRegionDict['e']:
  5246. eastingDiff = - eastingDiff
  5247. else:
  5248. eastingDiff = eastingDiff
  5249. northingDiff = textNorthing - cornerNorthing
  5250. if currRegionDict['n'] > currRegionDict['s']:
  5251. northingDiff = - northingDiff
  5252. else:
  5253. northingDiff = northingDiff
  5254. xPaper = xMap + unitConv.convert(value = eastingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale
  5255. yPaper = yMap + unitConv.convert(value = northingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale
  5256. return xPaper, yPaper
  5257. else:
  5258. if currRegionDict['w'] < currRegionDict['e']:
  5259. eastingDiff = (x - xMap)
  5260. else:
  5261. eastingDiff = (xMap - x)
  5262. if currRegionDict['n'] < currRegionDict['s']:
  5263. northingDiff = (y - yMap)
  5264. else:
  5265. northingDiff = (yMap - y)
  5266. textEasting = cornerEasting + unitConv.convert(value = eastingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale
  5267. textNorthing = cornerNorthing + unitConv.convert(value = northingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale
  5268. return int(textEasting), int(textNorthing)
  5269. def AutoAdjust(self, scaleType, rect, map = None, mapType = None, region = None):
  5270. """!Computes map scale, center and map frame rectangle to fit region (scale is not fixed)"""
  5271. currRegionDict = {}
  5272. if scaleType == 0 and map:# automatic, region from raster or vector
  5273. res = ''
  5274. if mapType == 'raster':
  5275. try:
  5276. res = grass.read_command("g.region", flags = 'gu', rast = map)
  5277. except grass.ScriptError:
  5278. pass
  5279. elif mapType == 'vector':
  5280. res = grass.read_command("g.region", flags = 'gu', vect = map)
  5281. currRegionDict = grass.parse_key_val(res, val_type = float)
  5282. elif scaleType == 1 and region: # saved region
  5283. res = grass.read_command("g.region", flags = 'gu', region = region)
  5284. currRegionDict = grass.parse_key_val(res, val_type = float)
  5285. elif scaleType == 2: # current region
  5286. env = grass.gisenv()
  5287. windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND')
  5288. try:
  5289. windFile = open(windFilePath, 'r').read()
  5290. except IOError:
  5291. currRegionDict = grass.region()
  5292. regionDict = grass.parse_key_val(windFile, sep = ':', val_type = float)
  5293. region = grass.read_command("g.region", flags = 'gu', n = regionDict['north'], s = regionDict['south'],
  5294. e = regionDict['east'], w = regionDict['west'])
  5295. currRegionDict = grass.parse_key_val(region, val_type = float)
  5296. else:
  5297. return None, None, None
  5298. if not currRegionDict:
  5299. return None, None, None
  5300. rX = rect.x
  5301. rY = rect.y
  5302. rW = rect.width
  5303. rH = rect.height
  5304. if not hasattr(self, 'unitConv'):
  5305. self.unitConv = UnitConversion(self)
  5306. toM = 1
  5307. if projInfo()['proj'] != 'xy':
  5308. toM = float(projInfo()['meters'])
  5309. mW = self.unitConv.convert(value = (currRegionDict['e'] - currRegionDict['w']) * toM, fromUnit = 'meter', toUnit = 'inch')
  5310. mH = self.unitConv.convert(value = (currRegionDict['n'] - currRegionDict['s']) * toM, fromUnit = 'meter', toUnit = 'inch')
  5311. scale = min(rW/mW, rH/mH)
  5312. if rW/rH > mW/mH:
  5313. x = rX - (rH*(mW/mH) - rW)/2
  5314. y = rY
  5315. rWNew = rH*(mW/mH)
  5316. rHNew = rH
  5317. else:
  5318. x = rX
  5319. y = rY - (rW*(mH/mW) - rH)/2
  5320. rHNew = rW*(mH/mW)
  5321. rWNew = rW
  5322. # center
  5323. cE = (currRegionDict['w'] + currRegionDict['e'])/2
  5324. cN = (currRegionDict['n'] + currRegionDict['s'])/2
  5325. return scale, (cE, cN), wx.Rect2D(x, y, rWNew, rHNew) #inch
  5326. def SetResolution(dpi, width, height):
  5327. """!If resolution is too high, lower it
  5328. @param dpi max DPI
  5329. @param width map frame width
  5330. @param height map frame height
  5331. """
  5332. region = grass.region()
  5333. if region['cols'] > width * dpi or region['rows'] > height * dpi:
  5334. rows = height * dpi
  5335. cols = width * dpi
  5336. RunCommand('g.region', rows = rows, cols = cols)
  5337. def ComputeSetRegion(self, mapDict):
  5338. """!Computes and sets region from current scale, map center coordinates and map rectangle"""
  5339. if mapDict['scaleType'] == 3: # fixed scale
  5340. scale = mapDict['scale']
  5341. if not hasattr(self, 'unitConv'):
  5342. self.unitConv = UnitConversion(self)
  5343. fromM = 1
  5344. if projInfo()['proj'] != 'xy':
  5345. fromM = float(projInfo()['meters'])
  5346. rectHalfInch = (mapDict['rect'].width/2, mapDict['rect'].height/2)
  5347. rectHalfMeter = (self.unitConv.convert(value = rectHalfInch[0], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale,
  5348. self.unitConv.convert(value = rectHalfInch[1], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale)
  5349. centerE = mapDict['center'][0]
  5350. centerN = mapDict['center'][1]
  5351. raster = self.instruction.FindInstructionByType('raster')
  5352. if raster:
  5353. rasterId = raster.id
  5354. else:
  5355. rasterId = None
  5356. if rasterId:
  5357. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  5358. s = floor(centerN - rectHalfMeter[1]),
  5359. e = ceil(centerE + rectHalfMeter[0]),
  5360. w = floor(centerE - rectHalfMeter[0]),
  5361. rast = self.instruction[rasterId]['raster'])
  5362. else:
  5363. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  5364. s = floor(centerN - rectHalfMeter[1]),
  5365. e = ceil(centerE + rectHalfMeter[0]),
  5366. w = floor(centerE - rectHalfMeter[0]))
  5367. def projInfo():
  5368. """!Return region projection and map units information,
  5369. taken from render.py"""
  5370. projinfo = dict()
  5371. ret = RunCommand('g.proj', read = True, flags = 'p')
  5372. if not ret:
  5373. return projinfo
  5374. for line in ret.splitlines():
  5375. if ':' in line:
  5376. key, val = line.split(':')
  5377. projinfo[key.strip()] = val.strip()
  5378. elif "XY location (unprojected)" in line:
  5379. projinfo['proj'] = 'xy'
  5380. projinfo['units'] = ''
  5381. break
  5382. return projinfo
  5383. def GetMapBounds(filename, portrait = True):
  5384. """!Run ps.map -b to get information about map bounding box
  5385. @param filename psmap input file
  5386. @param portrait page orientation"""
  5387. orient = ''
  5388. if not portrait:
  5389. orient = 'r'
  5390. try:
  5391. bb = map(float, grass.read_command('ps.map',
  5392. flags = 'b' + orient,
  5393. quiet = True,
  5394. input = filename).strip().split('=')[1].split(','))
  5395. except (grass.ScriptError, IndexError):
  5396. GError(message = _("Unable to run `ps.map -b`"))
  5397. return None
  5398. return wx.Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3])
  5399. def getRasterType(map):
  5400. """!Returns type of raster map (CELL, FCELL, DCELL)"""
  5401. if map is None:
  5402. map = ''
  5403. file = grass.find_file(name = map, element = 'cell')
  5404. if file['file']:
  5405. rasterType = grass.raster_info(map)['datatype']
  5406. return rasterType
  5407. else:
  5408. return None
  5409. def PilImageToWxImage(pilImage, copyAlpha = True):
  5410. """!Convert PIL image to wx.Image
  5411. Based on http://wiki.wxpython.org/WorkingWithImages
  5412. """
  5413. hasAlpha = pilImage.mode[-1] == 'A'
  5414. if copyAlpha and hasAlpha : # Make sure there is an alpha layer copy.
  5415. wxImage = wx.EmptyImage( *pilImage.size )
  5416. pilImageCopyRGBA = pilImage.copy()
  5417. pilImageCopyRGB = pilImageCopyRGBA.convert('RGB') # RGBA --> RGB
  5418. pilImageRgbData = pilImageCopyRGB.tostring()
  5419. wxImage.SetData(pilImageRgbData)
  5420. wxImage.SetAlphaData(pilImageCopyRGBA.tostring()[3::4]) # Create layer and insert alpha values.
  5421. else : # The resulting image will not have alpha.
  5422. wxImage = wx.EmptyImage(*pilImage.size)
  5423. pilImageCopy = pilImage.copy()
  5424. pilImageCopyRGB = pilImageCopy.convert('RGB') # Discard any alpha from the PIL image.
  5425. pilImageRgbData = pilImageCopyRGB.tostring()
  5426. wxImage.SetData(pilImageRgbData)
  5427. return wxImage
  5428. def BBoxAfterRotation(w, h, angle):
  5429. """!Compute bounding box or rotated rectangle
  5430. @param w rectangle width
  5431. @param h rectangle height
  5432. @param angle angle (0, 360) in degrees
  5433. """
  5434. angleRad = angle / 180. * pi
  5435. ct = cos(angleRad)
  5436. st = sin(angleRad)
  5437. hct = h * ct
  5438. wct = w * ct
  5439. hst = h * st
  5440. wst = w * st
  5441. y = x = 0
  5442. if 0 < angle <= 90:
  5443. y_min = y
  5444. y_max = y + hct + wst
  5445. x_min = x - hst
  5446. x_max = x + wct
  5447. elif 90 < angle <= 180:
  5448. y_min = y + hct
  5449. y_max = y + wst
  5450. x_min = x - hst + wct
  5451. x_max = x
  5452. elif 180 < angle <= 270:
  5453. y_min = y + wst + hct
  5454. y_max = y
  5455. x_min = x + wct
  5456. x_max = x - hst
  5457. elif 270 < angle <= 360:
  5458. y_min = y + wst
  5459. y_max = y + hct
  5460. x_min = x
  5461. x_max = x + wct - hst
  5462. width = int(ceil(abs(x_max) + abs(x_min)))
  5463. height = int(ceil(abs(y_max) + abs(y_min)))
  5464. return width, height