dialogs.py 299 KB

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