dialogs.py 330 KB

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