psmap_dialogs.py 265 KB

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