dialogs.py 301 KB

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