frame.py 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502
  1. """
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011-2012 by Anna Kratochvilova, and the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project)
  11. @author Martin Landa <landa.martin gmail.com> (mentor)
  12. """
  13. import os
  14. import sys
  15. import Queue
  16. from math import sin, cos, pi, sqrt
  17. import wx
  18. try:
  19. import wx.lib.agw.flatnotebook as fnb
  20. except ImportError:
  21. import wx.lib.flatnotebook as fnb
  22. import grass.script as grass
  23. from core import globalvar
  24. from gui_core.menu import Menu
  25. from core.gconsole import CmdThread, EVT_CMD_DONE
  26. from psmap.toolbars import PsMapToolbar
  27. from core.gcmd import RunCommand, GError, GMessage
  28. from core.settings import UserSettings
  29. from core.utils import _, PilImageToWxImage
  30. from gui_core.forms import GUI
  31. from gui_core.dialogs import HyperlinkDialog
  32. from gui_core.ghelp import ShowAboutDialog
  33. from psmap.menudata import PsMapMenuData
  34. from gui_core.toolbars import ToolSwitcher
  35. from psmap.dialogs import *
  36. from psmap.instructions import *
  37. from psmap.utils import *
  38. class PsMapFrame(wx.Frame):
  39. def __init__(self, parent=None, id=wx.ID_ANY,
  40. title=_("GRASS GIS Cartographic Composer"), **kwargs):
  41. """Main window of ps.map GUI
  42. :param parent: parent window
  43. :param id: window id
  44. :param title: window title
  45. :param kwargs: wx.Frames' arguments
  46. """
  47. self.parent = parent
  48. wx.Frame.__init__(
  49. self,
  50. parent=parent,
  51. id=id,
  52. title=title,
  53. name="PsMap",
  54. **kwargs)
  55. self.SetIcon(
  56. wx.Icon(
  57. os.path.join(
  58. globalvar.ICONDIR,
  59. 'grass.ico'),
  60. wx.BITMAP_TYPE_ICO))
  61. # menubar
  62. self.menubar = Menu(
  63. parent=self,
  64. model=PsMapMenuData().GetModel(
  65. separators=True))
  66. self.SetMenuBar(self.menubar)
  67. # toolbar
  68. self._toolSwitcher = ToolSwitcher()
  69. self.toolbar = PsMapToolbar(
  70. parent=self, toolSwitcher=self._toolSwitcher)
  71. # workaround for http://trac.wxwidgets.org/ticket/13888
  72. if sys.platform != 'darwin':
  73. self.SetToolBar(self.toolbar)
  74. self.iconsize = (16, 16)
  75. # satusbar
  76. self.statusbar = self.CreateStatusBar(number=1)
  77. # mouse attributes -- position on the screen, begin and end of
  78. # dragging, and type of drawing
  79. self.mouse = {
  80. 'begin': [0, 0], # screen coordinates
  81. 'end': [0, 0],
  82. 'use': "pointer",
  83. }
  84. # available cursors
  85. self.cursors = {
  86. "default": wx.StockCursor(wx.CURSOR_ARROW),
  87. "cross": wx.StockCursor(wx.CURSOR_CROSS),
  88. "hand": wx.StockCursor(wx.CURSOR_HAND),
  89. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  90. }
  91. # pen and brush
  92. self.pen = {
  93. 'paper': wx.Pen(colour="BLACK", width=1),
  94. 'margins': wx.Pen(colour="GREY", width=1),
  95. 'map': wx.Pen(colour=wx.Colour(86, 122, 17), width=2),
  96. 'rasterLegend': wx.Pen(colour=wx.Colour(219, 216, 4), width=2),
  97. 'vectorLegend': wx.Pen(colour=wx.Colour(219, 216, 4), width=2),
  98. 'mapinfo': wx.Pen(colour=wx.Colour(5, 184, 249), width=2),
  99. 'scalebar': wx.Pen(colour=wx.Colour(150, 150, 150), width=2),
  100. 'image': wx.Pen(colour=wx.Colour(255, 150, 50), width=2),
  101. 'northArrow': wx.Pen(colour=wx.Colour(200, 200, 200), width=2),
  102. 'point': wx.Pen(colour=wx.Colour(100, 100, 100), width=2),
  103. 'line': wx.Pen(colour=wx.Colour(0, 0, 0), width=2),
  104. 'box': wx.Pen(colour='RED', width=2, style=wx.SHORT_DASH),
  105. 'select': wx.Pen(colour='BLACK', width=1, style=wx.SHORT_DASH),
  106. 'resize': wx.Pen(colour='BLACK', width=1)
  107. }
  108. self.brush = {
  109. 'paper': wx.WHITE_BRUSH,
  110. 'margins': wx.TRANSPARENT_BRUSH,
  111. 'map': wx.Brush(wx.Colour(151, 214, 90)),
  112. 'rasterLegend': wx.Brush(wx.Colour(250, 247, 112)),
  113. 'vectorLegend': wx.Brush(wx.Colour(250, 247, 112)),
  114. 'mapinfo': wx.Brush(wx.Colour(127, 222, 252)),
  115. 'scalebar': wx.Brush(wx.Colour(200, 200, 200)),
  116. 'image': wx.Brush(wx.Colour(255, 200, 50)),
  117. 'northArrow': wx.Brush(wx.Colour(255, 255, 255)),
  118. 'point': wx.Brush(wx.Colour(200, 200, 200)),
  119. 'line': wx.TRANSPARENT_BRUSH,
  120. 'box': wx.TRANSPARENT_BRUSH,
  121. 'select': wx.TRANSPARENT_BRUSH,
  122. 'resize': wx.BLACK_BRUSH
  123. }
  124. # list of objects to draw
  125. self.objectId = []
  126. # instructions
  127. self.instruction = Instruction(
  128. parent=self, objectsToDraw=self.objectId)
  129. # open dialogs
  130. self.openDialogs = dict()
  131. self.pageId = wx.NewId()
  132. # current page of flatnotebook
  133. self.currentPage = 0
  134. # canvas for draft mode
  135. self.canvas = PsMapBufferedWindow(
  136. parent=self,
  137. mouse=self.mouse,
  138. pen=self.pen,
  139. brush=self.brush,
  140. cursors=self.cursors,
  141. instruction=self.instruction,
  142. openDialogs=self.openDialogs,
  143. pageId=self.pageId,
  144. objectId=self.objectId,
  145. preview=False)
  146. self.canvas.SetCursor(self.cursors["default"])
  147. self.getInitMap()
  148. # image path
  149. env = grass.gisenv()
  150. self.imgName = grass.tempfile()
  151. # canvas for preview
  152. self.previewCanvas = PsMapBufferedWindow(
  153. parent=self,
  154. mouse=self.mouse,
  155. cursors=self.cursors,
  156. pen=self.pen,
  157. brush=self.brush,
  158. preview=True)
  159. # set WIND_OVERRIDE
  160. grass.use_temp_region()
  161. self.toolbar.SelectDefault()
  162. # create queues
  163. self.requestQ = Queue.Queue()
  164. self.resultQ = Queue.Queue()
  165. # thread
  166. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  167. self._layout()
  168. self.SetMinSize(wx.Size(775, 600))
  169. # workaround for http://trac.wxwidgets.org/ticket/13628
  170. self.SetSize(self.GetBestSize())
  171. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  172. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  173. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  174. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  175. if not havePILImage:
  176. wx.CallAfter(self._showErrMsg)
  177. def _showErrMsg(self):
  178. """Show error message (missing preview)
  179. """
  180. GError(parent=self,
  181. message=_("Python Imaging Library is not available.\n"
  182. "'Preview' functionality won't work."),
  183. showTraceback=False)
  184. def _layout(self):
  185. """Do layout
  186. """
  187. mainSizer = wx.BoxSizer(wx.VERTICAL)
  188. if globalvar.hasAgw:
  189. self.book = fnb.FlatNotebook(parent=self, id=wx.ID_ANY,
  190. agwStyle=fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  191. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  192. else:
  193. self.book = fnb.FlatNotebook(parent=self, id=wx.ID_ANY,
  194. style=fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  195. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  196. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  197. self.book.AddPage(self.canvas, "Draft mode")
  198. self.book.AddPage(self.previewCanvas, "Preview")
  199. self.book.SetSelection(0)
  200. mainSizer.Add(self.book, 1, wx.EXPAND)
  201. self.SetSizer(mainSizer)
  202. mainSizer.Fit(self)
  203. def InstructionFile(self):
  204. """Creates mapping instructions"""
  205. return str(self.instruction)
  206. def OnPSFile(self, event):
  207. """Generate PostScript"""
  208. filename = self.getFile(
  209. wildcard="PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  210. if filename:
  211. self.PSFile(filename)
  212. def OnPsMapDialog(self, event):
  213. """Launch ps.map dialog
  214. """
  215. GUI(parent=self).ParseCommand(cmd=['ps.map'])
  216. def OnPDFFile(self, event):
  217. """Generate PDF from PS with ps2pdf if available"""
  218. if not sys.platform == 'win32':
  219. try:
  220. p = grass.Popen(["ps2pdf"], stderr=grass.PIPE)
  221. p.stderr.close()
  222. except OSError:
  223. GMessage(
  224. parent=self,
  225. message=_(
  226. "Program ps2pdf is not available. Please install it first to create PDF."))
  227. return
  228. filename = self.getFile(wildcard="PDF (*.pdf)|*.pdf")
  229. if filename:
  230. self.PSFile(filename, pdf=True)
  231. def OnPreview(self, event):
  232. """Run ps.map and show result"""
  233. self.PSFile()
  234. def PSFile(self, filename=None, pdf=False):
  235. """Create temporary instructions file and run ps.map with output = filename"""
  236. instrFile = grass.tempfile()
  237. instrFileFd = open(instrFile, mode='w')
  238. instrFileFd.write(self.InstructionFile())
  239. instrFileFd.flush()
  240. instrFileFd.close()
  241. temp = False
  242. regOld = grass.region()
  243. if pdf:
  244. pdfname = filename
  245. else:
  246. pdfname = None
  247. #preview or pdf
  248. if not filename or (filename and pdf):
  249. temp = True
  250. filename = grass.tempfile()
  251. if not pdf: # lower resolution for preview
  252. if self.instruction.FindInstructionByType('map'):
  253. mapId = self.instruction.FindInstructionByType('map').id
  254. SetResolution(dpi=100, width=self.instruction[mapId]['rect'][
  255. 2], height=self.instruction[mapId]['rect'][3])
  256. cmd = ['ps.map', '--overwrite']
  257. if os.path.splitext(filename)[1] == '.eps':
  258. cmd.append('-e')
  259. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  260. cmd.append('-r')
  261. cmd.append('input=%s' % instrFile)
  262. cmd.append('output=%s' % filename)
  263. if pdf:
  264. self.SetStatusText(_('Generating PDF...'), 0)
  265. elif not temp:
  266. self.SetStatusText(_('Generating PostScript...'), 0)
  267. else:
  268. self.SetStatusText(_('Generating preview...'), 0)
  269. self.cmdThread.RunCmd(
  270. cmd,
  271. userData={
  272. 'instrFile': instrFile,
  273. 'filename': filename,
  274. 'pdfname': pdfname,
  275. 'temp': temp,
  276. 'regionOld': regOld})
  277. def OnCmdDone(self, event):
  278. """ps.map process finished"""
  279. if event.returncode != 0:
  280. GMessage(
  281. parent=self,
  282. message=_("Ps.map exited with return code %s") %
  283. event.returncode)
  284. grass.try_remove(event.userData['instrFile'])
  285. if event.userData['temp']:
  286. grass.try_remove(event.userData['filename'])
  287. return
  288. if event.userData['pdfname']:
  289. if sys.platform == 'win32':
  290. command = ['gswin32c',
  291. '-P-', '-dSAFER',
  292. '-dCompatibilityLevel=1.4',
  293. '-q', '-P-',
  294. '-dNOPAUSE', '-dBATCH',
  295. '-sDEVICE=pdfwrite',
  296. '-dPDFSETTINGS=/prepress', '-r1200',
  297. '-sstdout=%stderr',
  298. '-sOutputFile=%s' % event.userData['pdfname'],
  299. '-P-', '-dSAFER',
  300. '-dCompatibilityLevel=1.4',
  301. '-c', '.setpdfwrite', '-f',
  302. event.userData['filename']]
  303. else:
  304. command = [
  305. 'ps2pdf',
  306. '-dPDFSETTINGS=/prepress',
  307. '-r1200',
  308. event.userData['filename'],
  309. event.userData['pdfname']]
  310. try:
  311. proc = grass.Popen(command)
  312. ret = proc.wait()
  313. if ret > 0:
  314. GMessage(
  315. parent=self,
  316. message=_("%(prg)s exited with return code %(code)s") % {
  317. 'prg': command[0],
  318. 'code': ret})
  319. else:
  320. self.SetStatusText(_('PDF generated'), 0)
  321. except OSError as e:
  322. GError(parent=self, message=_(
  323. "Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  324. elif not event.userData['temp']:
  325. self.SetStatusText(_('PostScript file generated'), 0)
  326. # show preview only when user doesn't want to create ps or pdf
  327. if havePILImage and event.userData[
  328. 'temp'] and not event.userData['pdfname']:
  329. RunCommand('g.region', cols=event.userData['regionOld'][
  330. 'cols'], rows=event.userData['regionOld']['rows'])
  331. # wx.BusyInfo does not display the message
  332. busy = wx.BusyInfo(
  333. message=_("Generating preview, wait please"),
  334. parent=self)
  335. wx.Yield()
  336. try:
  337. im = PILImage.open(event.userData['filename'])
  338. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  339. im = im.rotate(270)
  340. # hack for Windows, change method for loading EPS
  341. if sys.platform == 'win32':
  342. import types
  343. im.load = types.MethodType(loadPSForWindows, im)
  344. im.save(self.imgName, format='PNG')
  345. except (IOError, OSError) as e:
  346. del busy
  347. dlg = HyperlinkDialog(
  348. self, title=_("Preview not available"),
  349. message=_(
  350. "Preview is not available probably because Ghostscript is not installed or not on PATH."),
  351. hyperlink='http://trac.osgeo.org/grass/wiki/CompileOnWindows#Ghostscript',
  352. hyperlinkLabel=_(
  353. "Please follow instructions on GRASS Trac Wiki."))
  354. dlg.ShowModal()
  355. dlg.Destroy()
  356. return
  357. rect = self.previewCanvas.ImageRect()
  358. self.previewCanvas.image = wx.Image(
  359. self.imgName, wx.BITMAP_TYPE_PNG)
  360. self.previewCanvas.DrawImage(rect=rect)
  361. del busy
  362. self.SetStatusText(_('Preview generated'), 0)
  363. self.book.SetSelection(1)
  364. self.currentPage = 1
  365. grass.try_remove(event.userData['instrFile'])
  366. if event.userData['temp']:
  367. grass.try_remove(event.userData['filename'])
  368. self.delayedCall = wx.CallLater(
  369. 4000, lambda: self.SetStatusText("", 0))
  370. def getFile(self, wildcard):
  371. suffix = []
  372. for filter in wildcard.split('|')[1::2]:
  373. s = filter.strip('*').split('.')[1]
  374. if s:
  375. s = '.' + s
  376. suffix.append(s)
  377. raster = self.instruction.FindInstructionByType('raster')
  378. if raster:
  379. rasterId = raster.id
  380. else:
  381. rasterId = None
  382. if rasterId and self.instruction[rasterId]['raster']:
  383. mapName = self.instruction[rasterId][
  384. 'raster'].split('@')[0] + suffix[0]
  385. else:
  386. mapName = ''
  387. filename = ''
  388. dlg = wx.FileDialog(
  389. self, message=_("Save file as"),
  390. defaultDir="", defaultFile=mapName, wildcard=wildcard,
  391. style=wx.FD_CHANGE_DIR | wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  392. if dlg.ShowModal() == wx.ID_OK:
  393. filename = dlg.GetPath()
  394. suffix = suffix[dlg.GetFilterIndex()]
  395. if not os.path.splitext(filename)[1]:
  396. filename = filename + suffix
  397. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  398. filename = os.path.splitext(filename)[0] + suffix
  399. dlg.Destroy()
  400. return filename
  401. def OnInstructionFile(self, event):
  402. filename = self.getFile(
  403. wildcard="*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  404. if filename:
  405. instrFile = open(filename, "w")
  406. instrFile.write(self.InstructionFile())
  407. instrFile.close()
  408. def OnLoadFile(self, event):
  409. """Launch file dialog and load selected file"""
  410. # find file
  411. filename = ''
  412. dlg = wx.FileDialog(
  413. self,
  414. message="Find instructions file",
  415. defaultDir="",
  416. defaultFile='',
  417. wildcard="All files (*.*)|*.*",
  418. style=wx.FD_CHANGE_DIR | wx.FD_OPEN)
  419. if dlg.ShowModal() == wx.ID_OK:
  420. filename = dlg.GetPath()
  421. dlg.Destroy()
  422. if not filename:
  423. return
  424. # load instructions
  425. self.LoadFile(filename)
  426. def LoadFile(self, filename):
  427. """Load file and read instructions"""
  428. readObjectId = []
  429. readInstruction = Instruction(parent=self, objectsToDraw=readObjectId)
  430. ok = readInstruction.Read(filename)
  431. if not ok:
  432. GMessage(_("Failed to read file %s.") % filename)
  433. else:
  434. self.instruction = self.canvas.instruction = readInstruction
  435. self.objectId = self.canvas.objectId = readObjectId
  436. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType(
  437. 'page').id
  438. self.canvas.UpdateMapLabel()
  439. self.canvas.dragId = -1
  440. self.canvas.Clear()
  441. self.canvas.SetPage()
  442. # self.canvas.ZoomAll()
  443. self.DialogDataChanged(self.objectId)
  444. def OnPageSetup(self, event=None):
  445. """Specify paper size, margins and orientation"""
  446. id = self.instruction.FindInstructionByType('page').id
  447. dlg = PageSetupDialog(self, id=id, settings=self.instruction)
  448. dlg.CenterOnScreen()
  449. val = dlg.ShowModal()
  450. if val == wx.ID_OK:
  451. self.canvas.SetPage()
  452. self.getInitMap()
  453. self.canvas.RecalculatePosition(ids=self.objectId)
  454. dlg.Destroy()
  455. def OnPointer(self, event):
  456. self.mouse["use"] = "pointer"
  457. self.canvas.SetCursor(self.cursors["default"])
  458. self.previewCanvas.SetCursor(self.cursors["default"])
  459. def OnPan(self, event):
  460. self.mouse["use"] = "pan"
  461. self.canvas.SetCursor(self.cursors["hand"])
  462. self.previewCanvas.SetCursor(self.cursors["hand"])
  463. def OnZoomIn(self, event):
  464. self.mouse["use"] = "zoomin"
  465. self.canvas.SetCursor(self.cursors["cross"])
  466. self.previewCanvas.SetCursor(self.cursors["cross"])
  467. def OnZoomOut(self, event):
  468. self.mouse["use"] = "zoomout"
  469. self.canvas.SetCursor(self.cursors["cross"])
  470. self.previewCanvas.SetCursor(self.cursors["cross"])
  471. def OnZoomAll(self, event):
  472. self.mouseOld = self.mouse['use']
  473. if self.currentPage == 0:
  474. self.cursorOld = self.canvas.GetCursor()
  475. else:
  476. self.cursorOld = self.previewCanvas.GetCursor()
  477. self.previewCanvas.GetCursor()
  478. self.mouse["use"] = "zoomin"
  479. if self.currentPage == 0:
  480. self.canvas.ZoomAll()
  481. else:
  482. self.previewCanvas.ZoomAll()
  483. self.mouse["use"] = self.mouseOld
  484. if self.currentPage == 0:
  485. self.canvas.SetCursor(self.cursorOld)
  486. else:
  487. self.previewCanvas.SetCursor(self.cursorOld)
  488. def OnAddMap(self, event, notebook=False):
  489. """Add or edit map frame"""
  490. if self.instruction.FindInstructionByType('map'):
  491. mapId = self.instruction.FindInstructionByType('map').id
  492. else:
  493. mapId = None
  494. id = [mapId, None, None]
  495. if notebook:
  496. if self.instruction.FindInstructionByType('vector'):
  497. vectorId = self.instruction.FindInstructionByType('vector').id
  498. else:
  499. vectorId = None
  500. if self.instruction.FindInstructionByType('raster'):
  501. rasterId = self.instruction.FindInstructionByType('raster').id
  502. else:
  503. rasterId = None
  504. id[1] = rasterId
  505. id[2] = vectorId
  506. if mapId: # map exists
  507. self.toolbar.SelectDefault()
  508. if notebook:
  509. # check map, raster, vector and save, destroy them
  510. if 'map' in self.openDialogs:
  511. self.openDialogs['map'].OnOK(event=None)
  512. if 'raster' in self.openDialogs:
  513. self.openDialogs['raster'].OnOK(event=None)
  514. if 'vector' in self.openDialogs:
  515. self.openDialogs['vector'].OnOK(event=None)
  516. if 'mapNotebook' not in self.openDialogs:
  517. dlg = MapDialog(
  518. parent=self,
  519. id=id,
  520. settings=self.instruction,
  521. notebook=notebook)
  522. self.openDialogs['mapNotebook'] = dlg
  523. self.openDialogs['mapNotebook'].Show()
  524. else:
  525. if 'mapNotebook' in self.openDialogs:
  526. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  527. else:
  528. if 'map' not in self.openDialogs:
  529. dlg = MapDialog(
  530. parent=self,
  531. id=id,
  532. settings=self.instruction,
  533. notebook=notebook)
  534. self.openDialogs['map'] = dlg
  535. self.openDialogs['map'].Show()
  536. else: # sofar no map
  537. self.mouse["use"] = "addMap"
  538. self.canvas.SetCursor(self.cursors["cross"])
  539. if self.currentPage == 1:
  540. self.book.SetSelection(0)
  541. self.currentPage = 0
  542. def OnAddRaster(self, event):
  543. """Add raster map"""
  544. if self.instruction.FindInstructionByType('raster'):
  545. id = self.instruction.FindInstructionByType('raster').id
  546. else:
  547. id = None
  548. if self.instruction.FindInstructionByType('map'):
  549. mapId = self.instruction.FindInstructionByType('map').id
  550. else:
  551. mapId = None
  552. if not id:
  553. if not mapId:
  554. GMessage(message=_("Please, create map frame first."))
  555. return
  556. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  557. # dlg.ShowModal()
  558. if 'mapNotebook' in self.openDialogs:
  559. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  560. else:
  561. if 'raster' not in self.openDialogs:
  562. dlg = RasterDialog(self, id=id, settings=self.instruction)
  563. self.openDialogs['raster'] = dlg
  564. self.openDialogs['raster'].Show()
  565. def OnAddVect(self, event):
  566. """Add vector map"""
  567. if self.instruction.FindInstructionByType('vector'):
  568. id = self.instruction.FindInstructionByType('vector').id
  569. else:
  570. id = None
  571. if self.instruction.FindInstructionByType('map'):
  572. mapId = self.instruction.FindInstructionByType('map').id
  573. else:
  574. mapId = None
  575. if not id:
  576. if not mapId:
  577. GMessage(message=_("Please, create map frame first."))
  578. return
  579. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  580. # dlg.ShowModal()
  581. if 'mapNotebook' in self.openDialogs:
  582. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  583. else:
  584. if 'vector' not in self.openDialogs:
  585. dlg = MainVectorDialog(self, id=id, settings=self.instruction)
  586. self.openDialogs['vector'] = dlg
  587. self.openDialogs['vector'].Show()
  588. def OnAddScalebar(self, event):
  589. """Add scalebar"""
  590. if projInfo()['proj'] == 'll':
  591. GMessage(
  592. message=_("Scalebar is not appropriate for this projection"))
  593. return
  594. if self.instruction.FindInstructionByType('scalebar'):
  595. id = self.instruction.FindInstructionByType('scalebar').id
  596. else:
  597. id = None
  598. if 'scalebar' not in self.openDialogs:
  599. dlg = ScalebarDialog(self, id=id, settings=self.instruction)
  600. self.openDialogs['scalebar'] = dlg
  601. self.openDialogs['scalebar'].Show()
  602. def OnAddLegend(self, event, page=0):
  603. """Add raster or vector legend"""
  604. if self.instruction.FindInstructionByType('rasterLegend'):
  605. idR = self.instruction.FindInstructionByType('rasterLegend').id
  606. else:
  607. idR = None
  608. if self.instruction.FindInstructionByType('vectorLegend'):
  609. idV = self.instruction.FindInstructionByType('vectorLegend').id
  610. else:
  611. idV = None
  612. if 'rasterLegend' not in self.openDialogs:
  613. dlg = LegendDialog(
  614. self, id=[idR, idV],
  615. settings=self.instruction, page=page)
  616. self.openDialogs['rasterLegend'] = dlg
  617. self.openDialogs['vectorLegend'] = dlg
  618. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  619. self.openDialogs['rasterLegend'].Show()
  620. def OnAddMapinfo(self, event):
  621. if self.instruction.FindInstructionByType('mapinfo'):
  622. id = self.instruction.FindInstructionByType('mapinfo').id
  623. else:
  624. id = None
  625. if 'mapinfo' not in self.openDialogs:
  626. dlg = MapinfoDialog(self, id=id, settings=self.instruction)
  627. self.openDialogs['mapinfo'] = dlg
  628. self.openDialogs['mapinfo'].Show()
  629. def OnAddImage(self, event, id=None):
  630. """Show dialog for image adding and editing"""
  631. position = None
  632. if 'image' in self.openDialogs:
  633. position = self.openDialogs['image'].GetPosition()
  634. self.openDialogs['image'].OnApply(event=None)
  635. self.openDialogs['image'].Destroy()
  636. dlg = ImageDialog(self, id=id, settings=self.instruction)
  637. self.openDialogs['image'] = dlg
  638. if position:
  639. dlg.SetPosition(position)
  640. dlg.Show()
  641. def OnAddNorthArrow(self, event, id=None):
  642. """Show dialog for north arrow adding and editing"""
  643. if self.instruction.FindInstructionByType('northArrow'):
  644. id = self.instruction.FindInstructionByType('northArrow').id
  645. else:
  646. id = None
  647. if 'northArrow' not in self.openDialogs:
  648. dlg = NorthArrowDialog(self, id=id, settings=self.instruction)
  649. self.openDialogs['northArrow'] = dlg
  650. self.openDialogs['northArrow'].Show()
  651. def OnAddText(self, event, id=None):
  652. """Show dialog for text adding and editing"""
  653. position = None
  654. if 'text' in self.openDialogs:
  655. position = self.openDialogs['text'].GetPosition()
  656. self.openDialogs['text'].OnApply(event=None)
  657. self.openDialogs['text'].Destroy()
  658. dlg = TextDialog(self, id=id, settings=self.instruction)
  659. self.openDialogs['text'] = dlg
  660. if position:
  661. dlg.SetPosition(position)
  662. dlg.Show()
  663. def OnAddPoint(self, event):
  664. """Add point action selected"""
  665. self.mouse["use"] = "addPoint"
  666. self.canvas.SetCursor(self.cursors["cross"])
  667. def AddPoint(self, id=None, coordinates=None):
  668. """Add point and open property dialog.
  669. :param id: id point id (None if creating new point)
  670. :param coordinates: coordinates of new point
  671. """
  672. position = None
  673. if 'point' in self.openDialogs:
  674. position = self.openDialogs['point'].GetPosition()
  675. self.openDialogs['point'].OnApply(event=None)
  676. self.openDialogs['point'].Destroy()
  677. dlg = PointDialog(self, id=id, settings=self.instruction,
  678. coordinates=coordinates)
  679. self.openDialogs['point'] = dlg
  680. if position:
  681. dlg.SetPosition(position)
  682. if coordinates:
  683. dlg.OnApply(event=None)
  684. dlg.Show()
  685. def OnAddLine(self, event):
  686. """Add line action selected"""
  687. self.mouse["use"] = "addLine"
  688. self.canvas.SetCursor(self.cursors["cross"])
  689. def AddLine(self, id=None, coordinates=None):
  690. """Add line and open property dialog.
  691. :param id: id line id (None if creating new line)
  692. :param coordinates: coordinates of new line
  693. """
  694. position = None
  695. if 'line' in self.openDialogs:
  696. position = self.openDialogs['line'].GetPosition()
  697. self.openDialogs['line'].OnApply(event=None)
  698. self.openDialogs['line'].Destroy()
  699. dlg = RectangleDialog(self, id=id, settings=self.instruction,
  700. type='line', coordinates=coordinates)
  701. self.openDialogs['line'] = dlg
  702. if position:
  703. dlg.SetPosition(position)
  704. if coordinates:
  705. dlg.OnApply(event=None)
  706. dlg.Show()
  707. def OnAddRectangle(self, event):
  708. """Add rectangle action selected"""
  709. self.mouse["use"] = "addRectangle"
  710. self.canvas.SetCursor(self.cursors["cross"])
  711. def AddRectangle(self, id=None, coordinates=None):
  712. """Add rectangle and open property dialog.
  713. :param id: id rectangle id (None if creating new rectangle)
  714. :param coordinates: coordinates of new rectangle
  715. """
  716. position = None
  717. if 'rectangle' in self.openDialogs:
  718. position = self.openDialogs['rectangle'].GetPosition()
  719. self.openDialogs['rectangle'].OnApply(event=None)
  720. self.openDialogs['rectangle'].Destroy()
  721. dlg = RectangleDialog(self, id=id, settings=self.instruction,
  722. type='rectangle', coordinates=coordinates)
  723. self.openDialogs['rectangle'] = dlg
  724. if position:
  725. dlg.SetPosition(position)
  726. if coordinates:
  727. dlg.OnApply(event=None)
  728. dlg.Show()
  729. def OnAddLabels(self, event, id=None):
  730. """Show dialog for labels"""
  731. if self.instruction.FindInstructionByType('labels'):
  732. id = self.instruction.FindInstructionByType('labels').id
  733. else:
  734. id = None
  735. if 'labels' not in self.openDialogs:
  736. dlg = LabelsDialog(self, id=id, settings=self.instruction)
  737. self.openDialogs['labels'] = dlg
  738. self.openDialogs['labels'].Show()
  739. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  740. """computes bounding box of rotated text, not very precisely"""
  741. w, h = textExtent
  742. rotation = float(rotation) / 180 * pi
  743. H = float(w) * sin(rotation)
  744. W = float(w) * cos(rotation)
  745. X, Y = x, y
  746. if pi / 2 < rotation <= 3 * pi / 2:
  747. X = x + W
  748. if 0 < rotation < pi:
  749. Y = y - H
  750. if rotation == 0:
  751. return wx.Rect(x, y, *textExtent)
  752. else:
  753. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h, h)
  754. def makePSFont(self, textDict):
  755. """creates a wx.Font object from selected postscript font. To be
  756. used for estimating bounding rectangle of text"""
  757. fontsize = textDict['fontsize'] * self.canvas.currScale
  758. fontface = textDict['font'].split('-')[0]
  759. try:
  760. fontstyle = textDict['font'].split('-')[1]
  761. except IndexError:
  762. fontstyle = ''
  763. if fontface == "Times":
  764. family = wx.FONTFAMILY_ROMAN
  765. face = "times"
  766. elif fontface == "Helvetica":
  767. family = wx.FONTFAMILY_SWISS
  768. face = 'helvetica'
  769. elif fontface == "Courier":
  770. family = wx.FONTFAMILY_TELETYPE
  771. face = 'courier'
  772. else:
  773. family = wx.FONTFAMILY_DEFAULT
  774. face = ''
  775. style = wx.FONTSTYLE_NORMAL
  776. weight = wx.FONTWEIGHT_NORMAL
  777. if 'Oblique' in fontstyle:
  778. style = wx.FONTSTYLE_SLANT
  779. if 'Italic' in fontstyle:
  780. style = wx.FONTSTYLE_ITALIC
  781. if 'Bold' in fontstyle:
  782. weight = wx.FONTWEIGHT_BOLD
  783. try:
  784. fn = wx.Font(pointSize=fontsize, family=family, style=style,
  785. weight=weight, face=face)
  786. except:
  787. fn = wx.Font(
  788. pointSize=fontsize,
  789. family=wx.FONTFAMILY_DEFAULT,
  790. style=wx.FONTSTYLE_NORMAL,
  791. weight=wx.FONTWEIGHT_NORMAL)
  792. return fn
  793. def getTextExtent(self, textDict):
  794. """Estimates bounding rectangle of text"""
  795. #fontsize = str(fontsize if fontsize >= 4 else 4)
  796. # dc created because of method GetTextExtent, which pseudoDC lacks
  797. dc = wx.ClientDC(self)
  798. fn = self.makePSFont(textDict)
  799. try:
  800. dc.SetFont(fn)
  801. w, h, lh = dc.GetMultiLineTextExtent(textDict['text'])
  802. return (w, h)
  803. except:
  804. return (0, 0)
  805. def getInitMap(self):
  806. """Create default map frame when no map is selected, needed for coordinates in map units"""
  807. instrFile = grass.tempfile()
  808. instrFileFd = open(instrFile, mode='w')
  809. instrFileFd.write(self.InstructionFile())
  810. instrFileFd.flush()
  811. instrFileFd.close()
  812. page = self.instruction.FindInstructionByType('page')
  813. mapInitRect = GetMapBounds(
  814. instrFile, portrait=(
  815. page['Orientation'] == 'Portrait'))
  816. grass.try_remove(instrFile)
  817. region = grass.region()
  818. units = UnitConversion(self)
  819. realWidth = units.convert(
  820. value=abs(region['w'] - region['e']),
  821. fromUnit='meter', toUnit='inch')
  822. scale = mapInitRect.Get()[2] / realWidth
  823. initMap = self.instruction.FindInstructionByType('initMap')
  824. if initMap:
  825. id = initMap.id
  826. else:
  827. id = None
  828. if not id:
  829. id = wx.NewId()
  830. initMap = InitMap(id)
  831. self.instruction.AddInstruction(initMap)
  832. self.instruction[id].SetInstruction(
  833. dict(rect=mapInitRect, scale=scale))
  834. def OnDelete(self, event):
  835. if self.canvas.dragId != -1 and self.currentPage == 0:
  836. if self.instruction[self.canvas.dragId].type == 'map':
  837. self.deleteObject(self.canvas.dragId)
  838. self.getInitMap()
  839. self.canvas.RecalculateEN()
  840. else:
  841. self.deleteObject(self.canvas.dragId)
  842. def deleteObject(self, id):
  843. """Deletes object, his id and redraws"""
  844. # delete from canvas
  845. self.canvas.pdcObj.RemoveId(id)
  846. if id == self.canvas.dragId:
  847. self.canvas.pdcTmp.RemoveAll()
  848. self.canvas.dragId = -1
  849. self.canvas.Refresh()
  850. # delete from instructions
  851. del self.instruction[id]
  852. def DialogDataChanged(self, id):
  853. ids = id
  854. if isinstance(id, int):
  855. ids = [id]
  856. for id in ids:
  857. itype = self.instruction[id].type
  858. if itype in ('scalebar', 'mapinfo', 'image'):
  859. drawRectangle = self.canvas.CanvasPaperCoordinates(
  860. rect=self.instruction[id]['rect'], canvasToPaper=False)
  861. self.canvas.UpdateLabel(itype=itype, id=id)
  862. self.canvas.Draw(
  863. pen=self.pen[itype],
  864. brush=self.brush[itype],
  865. pdc=self.canvas.pdcObj,
  866. drawid=id,
  867. pdctype='rectText',
  868. bb=drawRectangle)
  869. self.canvas.RedrawSelectBox(id)
  870. if itype == 'northArrow':
  871. self.canvas.UpdateLabel(itype=itype, id=id)
  872. drawRectangle = self.canvas.CanvasPaperCoordinates(
  873. rect=self.instruction[id]['rect'], canvasToPaper=False)
  874. self.canvas.Draw(
  875. pen=self.pen[itype],
  876. brush=self.brush[itype],
  877. pdc=self.canvas.pdcObj,
  878. drawid=id,
  879. pdctype='bitmap',
  880. bb=drawRectangle)
  881. self.canvas.RedrawSelectBox(id)
  882. if itype in ('point', 'line', 'rectangle'):
  883. drawRectangle = self.canvas.CanvasPaperCoordinates(
  884. rect=self.instruction[id]['rect'], canvasToPaper=False)
  885. # coords only for line
  886. coords = None
  887. if itype == 'line':
  888. point1 = self.instruction[id]['where'][0]
  889. point2 = self.instruction[id]['where'][1]
  890. point1Coords = self.canvas.CanvasPaperCoordinates(
  891. rect=Rect2DPS(point1, (0, 0)), canvasToPaper=False)[:2]
  892. point2Coords = self.canvas.CanvasPaperCoordinates(
  893. rect=Rect2DPS(point2, (0, 0)), canvasToPaper=False)[:2]
  894. coords = (point1Coords, point2Coords)
  895. # fill color is not in line
  896. fcolor = None
  897. if 'fcolor' in self.instruction[id].GetInstruction():
  898. fcolor = self.instruction[id]['fcolor']
  899. # width is not in point
  900. width = None
  901. if 'width' in self.instruction[id].GetInstruction():
  902. width = self.instruction[id]['width']
  903. self.canvas.DrawGraphics(
  904. drawid=id,
  905. color=self.instruction[id]['color'],
  906. shape=itype,
  907. fcolor=fcolor,
  908. width=width,
  909. bb=drawRectangle,
  910. lineCoords=coords)
  911. self.canvas.RedrawSelectBox(id)
  912. if itype == 'text':
  913. if self.instruction[id]['rotate']:
  914. rot = float(self.instruction[id]['rotate'])
  915. else:
  916. rot = 0
  917. extent = self.getTextExtent(
  918. textDict=self.instruction[id].GetInstruction())
  919. rect = Rect2DPS(self.instruction[id]['where'], (0, 0))
  920. self.instruction[id]['coords'] = list(
  921. self.canvas.CanvasPaperCoordinates(
  922. rect=rect, canvasToPaper=False)[: 2])
  923. # computes text coordinates according to reference point, not
  924. # precisely
  925. if self.instruction[id]['ref'].split()[0] == 'lower':
  926. self.instruction[id]['coords'][1] -= extent[1]
  927. elif self.instruction[id]['ref'].split()[0] == 'center':
  928. self.instruction[id]['coords'][1] -= extent[1] / 2
  929. if self.instruction[id]['ref'].split()[1] == 'right':
  930. self.instruction[id]['coords'][
  931. 0] -= extent[0] * cos(rot / 180 * pi)
  932. self.instruction[id]['coords'][
  933. 1] += extent[0] * sin(rot / 180 * pi)
  934. elif self.instruction[id]['ref'].split()[1] == 'center':
  935. self.instruction[id]['coords'][
  936. 0] -= extent[0] / 2 * cos(rot / 180 * pi)
  937. self.instruction[id]['coords'][
  938. 1] += extent[0] / 2 * sin(rot / 180 * pi)
  939. self.instruction[id]['coords'][
  940. 0] += self.instruction[id]['xoffset']
  941. self.instruction[id]['coords'][
  942. 1] -= self.instruction[id]['yoffset']
  943. coords = self.instruction[id]['coords']
  944. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(
  945. coords[0], coords[1], extent, rot)
  946. self.canvas.DrawRotText(
  947. pdc=self.canvas.pdcObj, drawId=id,
  948. textDict=self.instruction[id].GetInstruction(),
  949. coords=coords, bounds=bounds)
  950. self.canvas.RedrawSelectBox(id)
  951. if itype in ('map', 'vector', 'raster', 'labels'):
  952. if itype == 'raster': # set resolution
  953. info = grass.raster_info(self.instruction[id]['raster'])
  954. RunCommand(
  955. 'g.region',
  956. nsres=info['nsres'],
  957. ewres=info['ewres'])
  958. # change current raster in raster legend
  959. if 'rasterLegend' in self.openDialogs:
  960. self.openDialogs['rasterLegend'].updateDialog()
  961. id = self.instruction.FindInstructionByType('map').id
  962. # check resolution
  963. if itype == 'raster':
  964. SetResolution(dpi=self.instruction[id]['resolution'],
  965. width=self.instruction[id]['rect'].width,
  966. height=self.instruction[id]['rect'].height)
  967. rectCanvas = self.canvas.CanvasPaperCoordinates(
  968. rect=self.instruction[id]['rect'], canvasToPaper=False)
  969. self.canvas.RecalculateEN()
  970. self.canvas.UpdateMapLabel()
  971. self.canvas.Draw(
  972. pen=self.pen['map'],
  973. brush=self.brush['map'],
  974. pdc=self.canvas.pdcObj,
  975. drawid=id,
  976. pdctype='rectText',
  977. bb=rectCanvas)
  978. # redraw select box
  979. self.canvas.RedrawSelectBox(id)
  980. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  981. # redraw to get map to the bottom layer
  982. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  983. if itype == 'rasterLegend':
  984. if self.instruction[id]['rLegend']:
  985. self.canvas.UpdateLabel(itype=itype, id=id)
  986. drawRectangle = self.canvas.CanvasPaperCoordinates(
  987. rect=self.instruction[id]['rect'], canvasToPaper=False)
  988. self.canvas.Draw(
  989. pen=self.pen[itype],
  990. brush=self.brush[itype],
  991. pdc=self.canvas.pdcObj,
  992. drawid=id,
  993. pdctype='rectText',
  994. bb=drawRectangle)
  995. self.canvas.RedrawSelectBox(id)
  996. else:
  997. self.deleteObject(id)
  998. if itype == 'vectorLegend':
  999. if not self.instruction.FindInstructionByType('vector'):
  1000. self.deleteObject(id)
  1001. elif self.instruction[id]['vLegend']:
  1002. self.canvas.UpdateLabel(itype=itype, id=id)
  1003. drawRectangle = self.canvas.CanvasPaperCoordinates(
  1004. rect=self.instruction[id]['rect'], canvasToPaper=False)
  1005. self.canvas.Draw(
  1006. pen=self.pen[itype],
  1007. brush=self.brush[itype],
  1008. pdc=self.canvas.pdcObj,
  1009. drawid=id,
  1010. pdctype='rectText',
  1011. bb=drawRectangle)
  1012. self.canvas.RedrawSelectBox(id)
  1013. else:
  1014. self.deleteObject(id)
  1015. def OnPageChanged(self, event):
  1016. """Flatnotebook page has changed"""
  1017. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  1018. if self.currentPage == 1:
  1019. self.SetStatusText(
  1020. _("Press button with green triangle icon to generate preview."))
  1021. else:
  1022. self.SetStatusText('')
  1023. def OnPageChanging(self, event):
  1024. """Flatnotebook page is changing"""
  1025. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  1026. event.Veto()
  1027. def OnHelp(self, event):
  1028. """Show help"""
  1029. if self.parent and self.parent.GetName() == 'LayerManager':
  1030. log = self.parent.GetLogWindow()
  1031. log.RunCmd(['g.manual',
  1032. 'entry=wxGUI.psmap'])
  1033. else:
  1034. RunCommand('g.manual',
  1035. quiet=True,
  1036. entry='wxGUI.psmap')
  1037. def OnAbout(self, event):
  1038. """Display About window"""
  1039. ShowAboutDialog(
  1040. prgName=_('wxGUI Cartographic Composer'),
  1041. startYear='2011')
  1042. def OnCloseWindow(self, event):
  1043. """Close window"""
  1044. try:
  1045. os.remove(self.imgName)
  1046. except OSError:
  1047. pass
  1048. grass.set_raise_on_error(False)
  1049. if hasattr(self, 'delayedCall') and self.delayedCall.IsRunning():
  1050. self.delayedCall.Stop()
  1051. self.Destroy()
  1052. class PsMapBufferedWindow(wx.Window):
  1053. """A buffered window class."""
  1054. def __init__(self, parent, id=wx.ID_ANY,
  1055. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  1056. **kwargs):
  1057. """
  1058. :param parent: parent window
  1059. :param kwargs: other wx.Window parameters
  1060. """
  1061. wx.Window.__init__(self, parent, id=id, style=style)
  1062. self.parent = parent
  1063. self.FitInside()
  1064. # store an off screen empty bitmap for saving to file
  1065. self._buffer = None
  1066. # indicates whether or not a resize event has taken place
  1067. self.resize = False
  1068. self.mouse = kwargs['mouse']
  1069. self.cursors = kwargs['cursors']
  1070. self.preview = kwargs['preview']
  1071. self.pen = kwargs['pen']
  1072. self.brush = kwargs['brush']
  1073. if 'instruction' in kwargs:
  1074. self.instruction = kwargs['instruction']
  1075. if 'openDialogs' in kwargs:
  1076. self.openDialogs = kwargs['openDialogs']
  1077. if 'pageId' in kwargs:
  1078. self.pageId = kwargs['pageId']
  1079. if 'objectId' in kwargs:
  1080. self.objectId = kwargs['objectId']
  1081. # labels
  1082. self.itemLabelsDict = {'map': _("MAP FRAME"),
  1083. 'rasterLegend': _("RASTER LEGEND"),
  1084. 'vectorLegend': _("VECTOR LEGEND"),
  1085. 'mapinfo': _("MAP INFO"),
  1086. 'scalebar': _("SCALE BAR"),
  1087. 'image': _("IMAGE"),
  1088. 'northArrow': _("NORTH ARROW")}
  1089. self.itemLabels = {}
  1090. # define PseudoDC
  1091. self.pdc = wx.PseudoDC()
  1092. self.pdcObj = wx.PseudoDC()
  1093. self.pdcPaper = wx.PseudoDC()
  1094. self.pdcTmp = wx.PseudoDC()
  1095. self.pdcImage = wx.PseudoDC()
  1096. self.SetClientSize((700, 510)) # ?
  1097. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  1098. self.idBoxTmp = wx.NewId()
  1099. self.idZoomBoxTmp = wx.NewId()
  1100. self.idResizeBoxTmp = wx.NewId()
  1101. # ids of marks for moving line vertices
  1102. self.idLinePointsTmp = (wx.NewId(), wx.NewId())
  1103. self.resizeBoxSize = wx.Size(8, 8)
  1104. self.showResizeHelp = False # helper for correctly working statusbar
  1105. self.dragId = -1
  1106. if self.preview:
  1107. self.image = None
  1108. self.imageId = 2000
  1109. self.imgName = self.parent.imgName
  1110. self.currScale = None
  1111. self.Clear()
  1112. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  1113. self.Bind(wx.EVT_PAINT, self.OnPaint)
  1114. self.Bind(wx.EVT_SIZE, self.OnSize)
  1115. self.Bind(wx.EVT_IDLE, self.OnIdle)
  1116. # self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  1117. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  1118. def Clear(self):
  1119. """Clear canvas and set paper
  1120. """
  1121. bg = wx.LIGHT_GREY_BRUSH
  1122. self.pdcPaper.BeginDrawing()
  1123. self.pdcPaper.SetBackground(bg)
  1124. self.pdcPaper.Clear()
  1125. self.pdcPaper.EndDrawing()
  1126. self.pdcObj.RemoveAll()
  1127. self.pdcTmp.RemoveAll()
  1128. if not self.preview:
  1129. self.SetPage()
  1130. def CanvasPaperCoordinates(self, rect, canvasToPaper=True):
  1131. """Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  1132. units = UnitConversion(self)
  1133. fromU = 'pixel'
  1134. toU = 'inch'
  1135. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1136. pRectx, pRecty = pRect.x, pRect.y
  1137. scale = 1 / self.currScale
  1138. if not canvasToPaper: # paper -> canvas
  1139. fromU = 'inch'
  1140. toU = 'pixel'
  1141. scale = self.currScale
  1142. pRectx = units.convert(
  1143. value=- pRect.x,
  1144. fromUnit='pixel',
  1145. toUnit='inch') / scale # inch, real, negative
  1146. pRecty = units.convert(
  1147. value=- pRect.y,
  1148. fromUnit='pixel',
  1149. toUnit='inch') / scale
  1150. Width = units.convert(
  1151. value=rect.GetWidth(),
  1152. fromUnit=fromU,
  1153. toUnit=toU) * scale
  1154. Height = units.convert(
  1155. value=rect.GetHeight(),
  1156. fromUnit=fromU,
  1157. toUnit=toU) * scale
  1158. X = units.convert(
  1159. value=(
  1160. rect.GetX() - pRectx),
  1161. fromUnit=fromU,
  1162. toUnit=toU) * scale
  1163. Y = units.convert(
  1164. value=(
  1165. rect.GetY() - pRecty),
  1166. fromUnit=fromU,
  1167. toUnit=toU) * scale
  1168. return Rect2D(X, Y, Width, Height)
  1169. def SetPage(self):
  1170. """Sets and changes page, redraws paper"""
  1171. page = self.instruction[self.pageId]
  1172. if not page:
  1173. page = PageSetup(id=self.pageId)
  1174. self.instruction.AddInstruction(page)
  1175. ppi = wx.ClientDC(self).GetPPI()
  1176. cW, cH = self.GetClientSize()
  1177. pW, pH = page['Width'] * ppi[0], page['Height'] * ppi[1]
  1178. if self.currScale is None:
  1179. self.currScale = min(cW / pW, cH / pH)
  1180. pW = pW * self.currScale
  1181. pH = pH * self.currScale
  1182. x = cW / 2 - pW / 2
  1183. y = cH / 2 - pH / 2
  1184. self.DrawPaper(wx.Rect(x, y, pW, pH))
  1185. def modifyRectangle(self, r):
  1186. """Recalculates rectangle not to have negative size"""
  1187. if r.GetWidth() < 0:
  1188. r.SetX(r.GetX() + r.GetWidth())
  1189. if r.GetHeight() < 0:
  1190. r.SetY(r.GetY() + r.GetHeight())
  1191. r.SetWidth(abs(r.GetWidth()))
  1192. r.SetHeight(abs(r.GetHeight()))
  1193. return r
  1194. def RecalculateEN(self):
  1195. """Recalculate east and north for texts (eps, points) after their or map's movement"""
  1196. try:
  1197. mapId = self.instruction.FindInstructionByType('map').id
  1198. except AttributeError:
  1199. mapId = self.instruction.FindInstructionByType('initMap').id
  1200. for itemType in ('text', 'image', 'northArrow',
  1201. 'point', 'line', 'rectangle'):
  1202. items = self.instruction.FindInstructionByType(itemType, list=True)
  1203. for item in items:
  1204. instr = self.instruction[item.id]
  1205. if itemType in ('line', 'rectangle'):
  1206. if itemType == 'line':
  1207. e1, n1 = PaperMapCoordinates(
  1208. mapInstr=self.instruction[mapId],
  1209. x=instr['where'][0][0],
  1210. y=instr['where'][0][1],
  1211. paperToMap=True)
  1212. e2, n2 = PaperMapCoordinates(
  1213. mapInstr=self.instruction[mapId],
  1214. x=instr['where'][1][0],
  1215. y=instr['where'][1][1],
  1216. paperToMap=True)
  1217. else:
  1218. e1, n1 = PaperMapCoordinates(
  1219. mapInstr=self.instruction[mapId],
  1220. x=instr['rect'].GetLeft(),
  1221. y=instr['rect'].GetTop(),
  1222. paperToMap=True)
  1223. e2, n2 = PaperMapCoordinates(
  1224. mapInstr=self.instruction[mapId],
  1225. x=instr['rect'].GetRight(),
  1226. y=instr['rect'].GetBottom(),
  1227. paperToMap=True)
  1228. instr['east1'] = e1
  1229. instr['north1'] = n1
  1230. instr['east2'] = e2
  1231. instr['north2'] = n2
  1232. else:
  1233. e, n = PaperMapCoordinates(
  1234. mapInstr=self.instruction[mapId],
  1235. x=instr['where'][0],
  1236. y=instr['where'][1],
  1237. paperToMap=True)
  1238. instr['east'], instr['north'] = e, n
  1239. def OnPaint(self, event):
  1240. """Draw pseudo DC to buffer
  1241. """
  1242. if not self._buffer:
  1243. return
  1244. dc = wx.BufferedPaintDC(self, self._buffer)
  1245. # use PrepareDC to set position correctly
  1246. # probably does nothing, removed from wxPython 2.9
  1247. # self.PrepareDC(dc)
  1248. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  1249. dc.Clear()
  1250. # draw paper
  1251. if not self.preview:
  1252. self.pdcPaper.DrawToDC(dc)
  1253. # draw to the DC using the calculated clipping rect
  1254. rgn = self.GetUpdateRegion()
  1255. if not self.preview:
  1256. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  1257. else:
  1258. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  1259. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  1260. def MouseActions(self, event):
  1261. """Mouse motion and button click notifier
  1262. """
  1263. # zoom with mouse wheel
  1264. if event.GetWheelRotation() != 0:
  1265. self.OnMouseWheel(event)
  1266. # left mouse button pressed
  1267. elif event.LeftDown():
  1268. self.OnLeftDown(event)
  1269. # left mouse button released
  1270. elif event.LeftUp():
  1271. self.OnLeftUp(event)
  1272. # dragging
  1273. elif event.Dragging():
  1274. self.OnDragging(event)
  1275. # double click
  1276. elif event.ButtonDClick():
  1277. self.OnButtonDClick(event)
  1278. # middle mouse button pressed
  1279. elif event.MiddleDown():
  1280. self.OnMiddleDown(event)
  1281. elif event.Moving():
  1282. self.OnMouseMoving(event)
  1283. def OnMouseWheel(self, event):
  1284. """Mouse wheel scrolled.
  1285. Changes zoom."""
  1286. if UserSettings.Get(group='display',
  1287. key='mouseWheelZoom',
  1288. subkey='selection') == 2:
  1289. event.Skip()
  1290. return
  1291. zoom = event.GetWheelRotation()
  1292. oldUse = self.mouse['use']
  1293. self.mouse['begin'] = event.GetPosition()
  1294. if UserSettings.Get(group='display',
  1295. key='scrollDirection',
  1296. subkey='selection'):
  1297. zoom *= -1
  1298. if zoom > 0:
  1299. self.mouse['use'] = 'zoomin'
  1300. else:
  1301. self.mouse['use'] = 'zoomout'
  1302. zoomFactor, view = self.ComputeZoom(wx.Rect(0, 0, 0, 0))
  1303. self.Zoom(zoomFactor, view)
  1304. self.mouse['use'] = oldUse
  1305. def OnMouseMoving(self, event):
  1306. """Mouse cursor moving.
  1307. Change cursor when moving over resize marker.
  1308. """
  1309. if self.preview:
  1310. return
  1311. if self.mouse['use'] in ('pointer', 'resize'):
  1312. pos = event.GetPosition()
  1313. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  1314. if foundResize and foundResize[0] in (
  1315. self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1316. self.SetCursor(self.cursors["sizenwse"])
  1317. self.parent.SetStatusText(
  1318. _('Click and drag to resize object'), 0)
  1319. self.showResizeHelp = True
  1320. else:
  1321. if self.showResizeHelp:
  1322. self.parent.SetStatusText('', 0)
  1323. self.SetCursor(self.cursors["default"])
  1324. self.showResizeHelp = False
  1325. def OnLeftDown(self, event):
  1326. """Left mouse button pressed.
  1327. Select objects, redraw, prepare for moving/resizing.
  1328. """
  1329. self.mouse['begin'] = event.GetPosition()
  1330. self.begin = self.mouse['begin']
  1331. # select
  1332. if self.mouse['use'] == 'pointer':
  1333. found = self.pdcObj.FindObjects(
  1334. self.mouse['begin'][0],
  1335. self.mouse['begin'][1])
  1336. foundResize = self.pdcTmp.FindObjects(
  1337. self.mouse['begin'][0], self.mouse['begin'][1])
  1338. if foundResize and foundResize[0] in (
  1339. self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1340. self.mouse['use'] = 'resize'
  1341. # when resizing, proportions match region
  1342. if self.instruction[self.dragId].type == 'map':
  1343. self.constraint = False
  1344. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1345. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1346. self.constraint = True
  1347. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1348. if self.instruction[self.dragId].type == 'line':
  1349. self.currentLinePoint = self.idLinePointsTmp.index(
  1350. foundResize
  1351. [0])
  1352. elif found:
  1353. self.dragId = found[0]
  1354. self.RedrawSelectBox(self.dragId)
  1355. if self.instruction[
  1356. self.dragId].type not in (
  1357. 'map', 'rectangle'):
  1358. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1359. self.Refresh()
  1360. if self.instruction[self.dragId].type != 'line':
  1361. for id in self.idLinePointsTmp:
  1362. self.pdcTmp.RemoveId(id)
  1363. self.Refresh()
  1364. else:
  1365. self.dragId = -1
  1366. self.pdcTmp.RemoveId(self.idBoxTmp)
  1367. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1368. for id in self.idLinePointsTmp:
  1369. self.pdcTmp.RemoveId(id)
  1370. self.Refresh()
  1371. def OnLeftUp(self, event):
  1372. """Left mouse button released.
  1373. Recalculate zooming/resizing/moving and redraw.
  1374. """
  1375. # zoom in, zoom out
  1376. if self.mouse['use'] in ('zoomin', 'zoomout'):
  1377. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1378. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1379. self.Refresh()
  1380. zoomFactor, view = self.ComputeZoom(zoomR)
  1381. self.Zoom(zoomFactor, view)
  1382. # draw map frame
  1383. if self.mouse['use'] == 'addMap':
  1384. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1385. # too small rectangle, it's usually some mistake
  1386. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1387. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1388. self.Refresh()
  1389. return
  1390. rectPaper = self.CanvasPaperCoordinates(
  1391. rect=rectTmp, canvasToPaper=True)
  1392. dlg = MapDialog(
  1393. parent=self.parent, id=[None, None, None],
  1394. settings=self.instruction, rect=rectPaper)
  1395. self.openDialogs['map'] = dlg
  1396. self.openDialogs['map'].Show()
  1397. self.parent.toolbar.SelectDefault()
  1398. return
  1399. # resize resizable objects (map, line, rectangle)
  1400. if self.mouse['use'] == 'resize':
  1401. mapObj = self.instruction.FindInstructionByType('map')
  1402. if not mapObj:
  1403. mapObj = self.instruction.FindInstructionByType('initMap')
  1404. mapId = mapObj.id
  1405. if self.dragId == mapId:
  1406. # necessary to change either map frame (scaleType 0,1,2) or
  1407. # region (scaletype 3)
  1408. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1409. newRectPaper = self.CanvasPaperCoordinates(
  1410. rect=newRectCanvas, canvasToPaper=True)
  1411. self.instruction[mapId]['rect'] = newRectPaper
  1412. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1413. if self.instruction[mapId]['scaleType'] == 0:
  1414. scale, foo, rect = AutoAdjust(
  1415. self, scaleType=0, map=self.instruction[mapId]
  1416. ['map'],
  1417. mapType=self.instruction[mapId]['mapType'],
  1418. rect=self.instruction[mapId]['rect'])
  1419. elif self.instruction[mapId]['scaleType'] == 1:
  1420. scale, foo, rect = AutoAdjust(
  1421. self, scaleType=1,
  1422. region=self.instruction[mapId]['region'],
  1423. rect=self.instruction[mapId]['rect'])
  1424. else:
  1425. scale, foo, rect = AutoAdjust(
  1426. self, scaleType=2, rect=self.instruction[mapId]['rect'])
  1427. self.instruction[mapId]['rect'] = rect
  1428. self.instruction[mapId]['scale'] = scale
  1429. rectCanvas = self.CanvasPaperCoordinates(
  1430. rect=rect, canvasToPaper=False)
  1431. self.Draw(
  1432. pen=self.pen['map'],
  1433. brush=self.brush['map'],
  1434. pdc=self.pdcObj,
  1435. drawid=mapId,
  1436. pdctype='rectText',
  1437. bb=rectCanvas)
  1438. elif self.instruction[mapId]['scaleType'] == 3:
  1439. ComputeSetRegion(
  1440. self, mapDict=self.instruction[mapId].GetInstruction())
  1441. # check resolution
  1442. SetResolution(dpi=self.instruction[mapId]['resolution'],
  1443. width=self.instruction[mapId]['rect'].width,
  1444. height=self.instruction[mapId]['rect'].height)
  1445. self.RedrawSelectBox(mapId)
  1446. self.Zoom(zoomFactor=1, view=(0, 0))
  1447. elif self.instruction[self.dragId].type == 'line':
  1448. points = self.instruction[self.dragId]['where']
  1449. self.instruction[
  1450. self.dragId]['rect'] = Rect2DPP(
  1451. points[0], points[1])
  1452. self.RecalculatePosition(ids=[self.dragId])
  1453. elif self.instruction[self.dragId].type == 'rectangle':
  1454. self.RecalculatePosition(ids=[self.dragId])
  1455. self.mouse['use'] = 'pointer'
  1456. # recalculate the position of objects after dragging
  1457. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1458. if self.mouse['begin'] != event.GetPosition(): # for double click
  1459. self.RecalculatePosition(ids=[self.dragId])
  1460. if self.instruction[self.dragId].type in self.openDialogs:
  1461. self.openDialogs[
  1462. self.instruction[
  1463. self.dragId].type].updateDialog()
  1464. elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
  1465. endCoordinates = self.CanvasPaperCoordinates(rect=wx.Rect(
  1466. event.GetX(), event.GetY(), 0, 0), canvasToPaper=True)[:2]
  1467. diffX = event.GetX() - self.mouse['begin'][0]
  1468. diffY = event.GetY() - self.mouse['begin'][1]
  1469. if self.mouse['use'] == 'addPoint':
  1470. self.parent.AddPoint(coordinates=endCoordinates)
  1471. elif self.mouse['use'] in ('addLine', 'addRectangle'):
  1472. # not too small lines/rectangles
  1473. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1474. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1475. self.Refresh()
  1476. return
  1477. beginCoordinates = self.CanvasPaperCoordinates(
  1478. rect=wx.Rect(
  1479. self.mouse['begin'][0],
  1480. self.mouse['begin'][1],
  1481. 0, 0),
  1482. canvasToPaper=True)[
  1483. : 2]
  1484. if self.mouse['use'] == 'addLine':
  1485. self.parent.AddLine(
  1486. coordinates=[
  1487. beginCoordinates,
  1488. endCoordinates])
  1489. else:
  1490. self.parent.AddRectangle(
  1491. coordinates=[
  1492. beginCoordinates,
  1493. endCoordinates])
  1494. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1495. self.Refresh()
  1496. def OnButtonDClick(self, event):
  1497. """Open object dialog for editing."""
  1498. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1499. itemCall = {'text': self.parent.OnAddText,
  1500. 'mapinfo': self.parent.OnAddMapinfo,
  1501. 'scalebar': self.parent.OnAddScalebar,
  1502. 'image': self.parent.OnAddImage,
  1503. 'northArrow': self.parent.OnAddNorthArrow,
  1504. 'point': self.parent.AddPoint,
  1505. 'line': self.parent.AddLine,
  1506. 'rectangle': self.parent.AddRectangle,
  1507. 'rasterLegend': self.parent.OnAddLegend,
  1508. 'vectorLegend': self.parent.OnAddLegend,
  1509. 'map': self.parent.OnAddMap}
  1510. itemArg = {'text': dict(event=None, id=self.dragId),
  1511. 'mapinfo': dict(event=None),
  1512. 'scalebar': dict(event=None),
  1513. 'image': dict(event=None, id=self.dragId),
  1514. 'northArrow': dict(event=None, id=self.dragId),
  1515. 'point': dict(id=self.dragId),
  1516. 'line': dict(id=self.dragId),
  1517. 'rectangle': dict(id=self.dragId),
  1518. 'rasterLegend': dict(event=None),
  1519. 'vectorLegend': dict(event=None, page=1),
  1520. 'map': dict(event=None, notebook=True)}
  1521. type = self.instruction[self.dragId].type
  1522. itemCall[type](**itemArg[type])
  1523. def OnDragging(self, event):
  1524. """Process panning/resizing/drawing/moving."""
  1525. if event.MiddleIsDown():
  1526. # panning
  1527. self.mouse['end'] = event.GetPosition()
  1528. self.Pan(begin=self.mouse['begin'], end=self.mouse['end'])
  1529. self.mouse['begin'] = event.GetPosition()
  1530. elif event.LeftIsDown():
  1531. # draw box when zooming, creating map
  1532. if self.mouse['use'] in (
  1533. 'zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
  1534. self.mouse['end'] = event.GetPosition()
  1535. r = wx.Rect(
  1536. self.mouse['begin'][0],
  1537. self.mouse['begin'][1],
  1538. self.mouse['end'][0] -
  1539. self.mouse['begin'][0],
  1540. self.mouse['end'][1] -
  1541. self.mouse['begin'][1])
  1542. r = self.modifyRectangle(r)
  1543. if self.mouse['use'] in ('addLine', 'addRectangle'):
  1544. if self.mouse['use'] == 'addLine':
  1545. pdcType = 'line'
  1546. lineCoords = (self.mouse['begin'], self.mouse['end'])
  1547. else:
  1548. pdcType = 'rect'
  1549. lineCoords = None
  1550. if r[2] < 2 or r[3] < 2:
  1551. # to avoid strange behavoiur
  1552. return
  1553. self.Draw(pen=self.pen['line'], brush=self.brush['line'],
  1554. pdc=self.pdcTmp, drawid=self.idZoomBoxTmp,
  1555. pdctype=pdcType, bb=r, lineCoords=lineCoords)
  1556. else:
  1557. self.Draw(pen=self.pen['box'], brush=self.brush['box'],
  1558. pdc=self.pdcTmp, drawid=self.idZoomBoxTmp,
  1559. pdctype='rect', bb=r)
  1560. # panning
  1561. if self.mouse["use"] == 'pan':
  1562. self.mouse['end'] = event.GetPosition()
  1563. self.Pan(begin=self.mouse['begin'], end=self.mouse['end'])
  1564. self.mouse['begin'] = event.GetPosition()
  1565. # move object
  1566. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1567. self.mouse['end'] = event.GetPosition()
  1568. dx, dy = self.mouse['end'][
  1569. 0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1570. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1571. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1572. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1573. for id in self.idLinePointsTmp:
  1574. self.pdcTmp.TranslateId(id, dx, dy)
  1575. if self.instruction[self.dragId].type == 'text':
  1576. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId][
  1577. 'coords'][0] + dx, self.instruction[self.dragId]['coords'][1] + dy
  1578. self.begin = event.GetPosition()
  1579. self.Refresh()
  1580. # resize object
  1581. if self.mouse['use'] == 'resize':
  1582. pos = event.GetPosition()
  1583. diffX = pos[0] - self.mouse['begin'][0]
  1584. diffY = pos[1] - self.mouse['begin'][1]
  1585. if self.instruction[self.dragId].type == 'map':
  1586. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1587. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1588. # match given region
  1589. if self.constraint:
  1590. if width > height:
  1591. newWidth = width + diffX
  1592. newHeight = height + diffX * \
  1593. (float(height) / width)
  1594. else:
  1595. newWidth = width + diffY * (float(width) / height)
  1596. newHeight = height + diffY
  1597. else:
  1598. newWidth = width + diffX
  1599. newHeight = height + diffY
  1600. if newWidth < 10 or newHeight < 10:
  1601. return
  1602. bounds = wx.Rect(x, y, newWidth, newHeight)
  1603. self.Draw(
  1604. pen=self.pen['map'],
  1605. brush=self.brush['map'],
  1606. pdc=self.pdcObj,
  1607. drawid=self.dragId,
  1608. pdctype='rectText',
  1609. bb=bounds)
  1610. elif self.instruction[self.dragId].type == 'rectangle':
  1611. instr = self.instruction[self.dragId]
  1612. rect = self.CanvasPaperCoordinates(
  1613. rect=instr['rect'], canvasToPaper=False)
  1614. rect.SetWidth(rect.GetWidth() + diffX)
  1615. rect.SetHeight(rect.GetHeight() + diffY)
  1616. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1617. return
  1618. self.DrawGraphics(
  1619. drawid=self.dragId,
  1620. shape='rectangle',
  1621. color=instr['color'],
  1622. fcolor=instr['fcolor'],
  1623. width=instr['width'],
  1624. bb=rect)
  1625. elif self.instruction[self.dragId].type == 'line':
  1626. instr = self.instruction[self.dragId]
  1627. points = instr['where']
  1628. # moving point
  1629. if self.currentLinePoint == 0:
  1630. pPaper = points[1]
  1631. else:
  1632. pPaper = points[0]
  1633. pCanvas = self.CanvasPaperCoordinates(
  1634. rect=Rect2DPS(pPaper, (0, 0)), canvasToPaper=False)[:2]
  1635. bounds = wx.RectPP(pCanvas, pos)
  1636. self.DrawGraphics(
  1637. drawid=self.dragId,
  1638. shape='line',
  1639. color=instr['color'],
  1640. width=instr['width'],
  1641. bb=bounds,
  1642. lineCoords=(
  1643. pos,
  1644. pCanvas))
  1645. # update paper coordinates
  1646. points[self.currentLinePoint] = self.CanvasPaperCoordinates(
  1647. rect=wx.RectPS(pos, (0, 0)), canvasToPaper=True)[:2]
  1648. self.RedrawSelectBox(self.dragId)
  1649. def OnMiddleDown(self, event):
  1650. """Middle mouse button pressed."""
  1651. self.mouse['begin'] = event.GetPosition()
  1652. def Pan(self, begin, end):
  1653. """Move canvas while dragging.
  1654. :param begin: x,y coordinates of first point
  1655. :param end: x,y coordinates of second point
  1656. """
  1657. view = begin[0] - end[0], begin[1] - end[1]
  1658. zoomFactor = 1
  1659. self.Zoom(zoomFactor, view)
  1660. def RecalculatePosition(self, ids):
  1661. for id in ids:
  1662. itype = self.instruction[id].type
  1663. if itype in ('map', 'rectangle'):
  1664. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1665. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
  1666. self.RecalculateEN()
  1667. elif itype in ('mapinfo', 'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1668. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1669. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
  1670. self.instruction[id]['where'] = self.CanvasPaperCoordinates(
  1671. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)[:2]
  1672. if itype in ('image', 'northArrow'):
  1673. self.RecalculateEN()
  1674. elif itype == 'point':
  1675. rect = self.pdcObj.GetIdBounds(id)
  1676. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1677. rect=rect, canvasToPaper=True)
  1678. rect.OffsetXY(rect.GetWidth() / 2, rect.GetHeight() / 2)
  1679. self.instruction[id]['where'] = self.CanvasPaperCoordinates(
  1680. rect=rect, canvasToPaper=True)[: 2]
  1681. self.RecalculateEN()
  1682. elif itype == 'line':
  1683. rect = self.pdcObj.GetIdBounds(id)
  1684. oldRect = self.instruction[id]['rect']
  1685. newRect = self.CanvasPaperCoordinates(
  1686. rect=rect, canvasToPaper=True)
  1687. xDiff = newRect[0] - oldRect[0]
  1688. yDiff = newRect[1] - oldRect[1]
  1689. self.instruction[id]['rect'] = newRect
  1690. point1 = wx.Point2D(
  1691. xDiff, yDiff) + self.instruction[id]['where'][0]
  1692. point2 = wx.Point2D(
  1693. xDiff, yDiff) + self.instruction[id]['where'][1]
  1694. self.instruction[id]['where'] = [point1, point2]
  1695. self.RecalculateEN()
  1696. elif itype == 'scalebar':
  1697. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1698. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
  1699. self.instruction[id]['where'] = self.instruction[
  1700. id]['rect'].GetCentre()
  1701. elif itype == 'text':
  1702. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1703. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1704. extent = self.parent.getTextExtent(
  1705. textDict=self.instruction[id])
  1706. if self.instruction[id]['rotate'] is not None:
  1707. rot = float(self.instruction[id]['rotate']) / 180 * pi
  1708. else:
  1709. rot = 0
  1710. if self.instruction[id]['ref'].split()[0] == 'lower':
  1711. y += extent[1]
  1712. elif self.instruction[id]['ref'].split()[0] == 'center':
  1713. y += extent[1] / 2
  1714. if self.instruction[id]['ref'].split()[1] == 'right':
  1715. x += extent[0] * cos(rot)
  1716. y -= extent[0] * sin(rot)
  1717. elif self.instruction[id]['ref'].split()[1] == 'center':
  1718. x += extent[0] / 2 * cos(rot)
  1719. y -= extent[0] / 2 * sin(rot)
  1720. self.instruction[id]['where'] = self.CanvasPaperCoordinates(
  1721. rect=Rect2D(x, y, 0, 0), canvasToPaper=True)[:2]
  1722. self.RecalculateEN()
  1723. def ComputeZoom(self, rect):
  1724. """Computes zoom factor and scroll view"""
  1725. zoomFactor = 1
  1726. cW, cH = self.GetClientSize()
  1727. cW = float(cW)
  1728. if rect.IsEmpty(): # clicked on canvas
  1729. zoomFactor = 1.5
  1730. if self.mouse['use'] == 'zoomout':
  1731. zoomFactor = 1. / zoomFactor
  1732. x, y = self.mouse['begin']
  1733. xView = x - x / zoomFactor # x - cW/(zoomFactor * 2)
  1734. yView = y - y / zoomFactor # y - cH/(zoomFactor * 2)
  1735. else: # dragging
  1736. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1737. try:
  1738. zoomFactor = 1 / max(rW / cW, rH / cH)
  1739. except ZeroDivisionError:
  1740. zoomFactor = 1
  1741. # when zooming to full extent, in some cases, there was zoom
  1742. # 1.01..., which causes problem
  1743. if abs(zoomFactor - 1) > 0.01:
  1744. zoomFactor = zoomFactor
  1745. else:
  1746. zoomFactor = 1.
  1747. if self.mouse['use'] == 'zoomout':
  1748. zoomFactor = min(rW / cW, rH / cH)
  1749. try:
  1750. if rW / rH > cW / cH:
  1751. yView = rect.GetY() - (rW * (cH / cW) - rH) / 2
  1752. xView = rect.GetX()
  1753. if self.mouse['use'] == 'zoomout':
  1754. x, y = rect.GetX() + (rW - (cW / cH) * rH) / 2, rect.GetY()
  1755. xView, yView = -x, -y
  1756. else:
  1757. xView = rect.GetX() - (rH * (cW / cH) - rW) / 2
  1758. yView = rect.GetY()
  1759. if self.mouse['use'] == 'zoomout':
  1760. x, y = rect.GetX(), rect.GetY() + (rH - (cH / cW) * rW) / 2
  1761. xView, yView = -x, -y
  1762. except ZeroDivisionError:
  1763. xView, yView = rect.GetX(), rect.GetY()
  1764. return zoomFactor, (int(xView), int(yView))
  1765. def Zoom(self, zoomFactor, view):
  1766. """Zoom to specified region, scroll view, redraw"""
  1767. if not self.currScale:
  1768. return
  1769. self.currScale = self.currScale * zoomFactor
  1770. if self.currScale > 10 or self.currScale < 0.1:
  1771. self.currScale = self.currScale / zoomFactor
  1772. return
  1773. if not self.preview:
  1774. # redraw paper
  1775. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1776. pRect.OffsetXY(-view[0], -view[1])
  1777. pRect = self.ScaleRect(rect=pRect, scale=zoomFactor)
  1778. self.DrawPaper(pRect)
  1779. # redraw objects
  1780. for id in self.objectId:
  1781. type = self.instruction[id].type
  1782. if type == 'labels': # why it's here? it should not
  1783. continue
  1784. oRect = self.CanvasPaperCoordinates(
  1785. rect=self.instruction[id]['rect'], canvasToPaper=False)
  1786. if type == 'text':
  1787. # recalculate coordinates, they are not equal to BB
  1788. coords = self.instruction[id]['coords']
  1789. self.instruction[id]['coords'] = coords = [
  1790. (int(coord) - view[i]) * zoomFactor for i, coord in enumerate(coords)]
  1791. extent = self.parent.getTextExtent(
  1792. textDict=self.instruction[id])
  1793. if self.instruction[id]['rotate']:
  1794. rot = float(self.instruction[id]['rotate'])
  1795. else:
  1796. rot = 0
  1797. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(
  1798. coords[0], coords[1], extent, rot)
  1799. self.DrawRotText(
  1800. pdc=self.pdcObj,
  1801. drawId=id,
  1802. textDict=self.instruction[id],
  1803. coords=coords,
  1804. bounds=bounds)
  1805. self.pdcObj.SetIdBounds(id, bounds)
  1806. elif type == 'northArrow':
  1807. self.Draw(
  1808. pen=self.pen[type],
  1809. brush=self.brush[type],
  1810. pdc=self.pdcObj,
  1811. drawid=id,
  1812. pdctype='bitmap',
  1813. bb=oRect)
  1814. elif type in ('point', 'line', 'rectangle'):
  1815. instr = self.instruction[id]
  1816. color = self.instruction[id]['color']
  1817. width = fcolor = coords = None
  1818. if type in ('point', 'rectangle'):
  1819. fcolor = self.instruction[id]['fcolor']
  1820. if type in ('line', 'rectangle'):
  1821. width = self.instruction[id]['width']
  1822. if type in ('line'):
  1823. point1, point2 = instr['where'][0], instr['where'][1]
  1824. point1 = self.CanvasPaperCoordinates(
  1825. rect=Rect2DPS(point1, (0, 0)), canvasToPaper=False)[:2]
  1826. point2 = self.CanvasPaperCoordinates(
  1827. rect=Rect2DPS(point2, (0, 0)), canvasToPaper=False)[:2]
  1828. coords = (point1, point2)
  1829. self.DrawGraphics(
  1830. drawid=id,
  1831. shape=type,
  1832. bb=oRect,
  1833. lineCoords=coords,
  1834. color=color,
  1835. fcolor=fcolor,
  1836. width=width)
  1837. else:
  1838. self.Draw(
  1839. pen=self.pen[type],
  1840. brush=self.brush[type],
  1841. pdc=self.pdcObj,
  1842. drawid=id,
  1843. pdctype='rectText',
  1844. bb=oRect)
  1845. # redraw tmp objects
  1846. if self.dragId != -1:
  1847. self.RedrawSelectBox(self.dragId)
  1848. # redraw preview
  1849. else: # preview mode
  1850. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1851. imageRect.OffsetXY(-view[0], -view[1])
  1852. imageRect = self.ScaleRect(rect=imageRect, scale=zoomFactor)
  1853. self.DrawImage(imageRect)
  1854. def ZoomAll(self):
  1855. """Zoom to full extent"""
  1856. if not self.preview:
  1857. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1858. else:
  1859. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1860. zoomP = bounds.Inflate(bounds.width / 20, bounds.height / 20)
  1861. zoomFactor, view = self.ComputeZoom(zoomP)
  1862. self.Zoom(zoomFactor, view)
  1863. def Draw(self, pen, brush, pdc, drawid=None, pdctype='rect',
  1864. bb=wx.Rect(0, 0, 0, 0), lineCoords=None):
  1865. """Draw object with given pen and brush.
  1866. :param pdc: PseudoDC
  1867. :param pdctype: 'bitmap'/'rectText'/'rect'/'point'/'line'
  1868. :param bb: bounding box
  1869. :param lineCoords: coordinates of line start, end points (wx.Point, wx.Point)
  1870. """
  1871. if drawid is None:
  1872. drawid = wx.NewId()
  1873. bb = bb.Get()
  1874. pdc.BeginDrawing()
  1875. pdc.RemoveId(drawid)
  1876. pdc.SetId(drawid)
  1877. pdc.SetPen(pen)
  1878. pdc.SetBrush(brush)
  1879. if pdctype == 'bitmap':
  1880. if havePILImage:
  1881. file = self.instruction[drawid]['epsfile']
  1882. rotation = self.instruction[drawid]['rotate']
  1883. self.DrawBitmap(
  1884. pdc=pdc,
  1885. filePath=file,
  1886. rotation=rotation,
  1887. bbox=bb)
  1888. else: # draw only rectangle with label
  1889. pdctype = 'rectText'
  1890. if pdctype in ('rect', 'rectText'):
  1891. pdc.DrawRectangle(*bb)
  1892. if pdctype == 'rectText':
  1893. # dc created because of method GetTextExtent, which pseudoDC lacks
  1894. dc = wx.ClientDC(self)
  1895. font = dc.GetFont()
  1896. size = 10
  1897. font.SetPointSize(size)
  1898. font.SetStyle(wx.ITALIC)
  1899. dc.SetFont(font)
  1900. pdc.SetFont(font)
  1901. text = '\n'.join(self.itemLabels[drawid])
  1902. w, h, lh = dc.GetMultiLineTextExtent(text)
  1903. textExtent = (w, h)
  1904. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1905. r = map(int, bb)
  1906. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1907. size -= 2
  1908. font.SetPointSize(size)
  1909. dc.SetFont(font)
  1910. pdc.SetFont(font)
  1911. textExtent = dc.GetTextExtent(text)
  1912. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1913. pdc.SetTextForeground(wx.Colour(100, 100, 100, 200))
  1914. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1915. pdc.DrawLabel(text=text, rect=textRect)
  1916. elif pdctype == 'point':
  1917. pdc.DrawCircle(x=bb[0] + bb[2] / 2,
  1918. y=bb[1] + bb[3] / 2,
  1919. radius=bb[2] / 2)
  1920. elif pdctype == 'line':
  1921. pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
  1922. pdc.SetIdBounds(drawid, bb)
  1923. pdc.EndDrawing()
  1924. self.Refresh()
  1925. return drawid
  1926. def DrawGraphics(self, drawid, shape, color, bb,
  1927. width=None, fcolor=None, lineCoords=None):
  1928. """Draw point/line/rectangle with given color and width
  1929. :param drawid: id of drawn object
  1930. :param shape: drawn shape 'point'/'line'/'rectangle'
  1931. :param color: pen outline color ('RRR:GGG:BBB')
  1932. :param fcolor: brush fill color, if meaningful ('RRR:GGG:BBB')
  1933. :param width: pen width
  1934. :param bb: bounding box
  1935. :param lineCoords: line coordinates (for line only)
  1936. """
  1937. pdctype = {'point': 'point',
  1938. 'line': 'line',
  1939. 'rectangle': 'rect'}
  1940. if color == 'none':
  1941. pen = wx.TRANSPARENT_PEN
  1942. else:
  1943. if width is not None:
  1944. units = UnitConversion(self)
  1945. width = int(
  1946. units.convert(
  1947. value=width,
  1948. fromUnit='point',
  1949. toUnit='pixel') *
  1950. self.currScale)
  1951. else:
  1952. width = 2
  1953. pen = wx.Pen(colour=convertRGB(color), width=width)
  1954. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  1955. brush = wx.TRANSPARENT_BRUSH
  1956. if fcolor and fcolor != 'none':
  1957. brush = wx.Brush(colour=convertRGB(fcolor))
  1958. self.Draw(
  1959. pen=pen,
  1960. brush=brush,
  1961. pdc=self.pdcObj,
  1962. pdctype=pdctype[shape],
  1963. drawid=drawid,
  1964. bb=bb,
  1965. lineCoords=lineCoords)
  1966. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1967. """Draw bitmap using PIL"""
  1968. pImg = PILImage.open(filePath)
  1969. if sys.platform == 'win32' and \
  1970. 'eps' in os.path.splitext(filePath)[1].lower():
  1971. import types
  1972. pImg.load = types.MethodType(loadPSForWindows, pImg)
  1973. if rotation:
  1974. # get rid of black background
  1975. pImg = pImg.convert("RGBA")
  1976. rot = pImg.rotate(rotation, expand=1)
  1977. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1978. pImg = PILImage.composite(rot, new, rot)
  1979. pImg = pImg.resize(
  1980. (int(
  1981. bbox[2]), int(
  1982. bbox[3])), resample=PILImage.BICUBIC)
  1983. img = PilImageToWxImage(pImg)
  1984. bitmap = img.ConvertToBitmap()
  1985. mask = wx.Mask(bitmap, wx.WHITE)
  1986. bitmap.SetMask(mask)
  1987. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask=True)
  1988. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1989. if textDict['rotate']:
  1990. rot = float(textDict['rotate'])
  1991. else:
  1992. rot = 0
  1993. if textDict['background'] != 'none':
  1994. background = textDict['background']
  1995. else:
  1996. background = None
  1997. pdc.RemoveId(drawId)
  1998. pdc.SetId(drawId)
  1999. pdc.BeginDrawing()
  2000. # border is not redrawn when zoom changes, why?
  2001. # if textDict['border'] != 'none' and not rot:
  2002. ## units = UnitConversion(self)
  2003. # borderWidth = units.convert(value = textDict['width'],
  2004. # fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  2005. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  2006. # pdc.DrawRectangle(*bounds)
  2007. if background:
  2008. pdc.SetTextBackground(convertRGB(background))
  2009. pdc.SetBackgroundMode(wx.SOLID)
  2010. else:
  2011. pdc.SetBackgroundMode(wx.TRANSPARENT)
  2012. fn = self.parent.makePSFont(textDict)
  2013. pdc.SetFont(fn)
  2014. pdc.SetTextForeground(convertRGB(textDict['color']))
  2015. if rot == 0:
  2016. pdc.DrawLabel(text=textDict['text'], rect=bounds)
  2017. else:
  2018. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  2019. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  2020. self.Refresh()
  2021. pdc.EndDrawing()
  2022. def DrawImage(self, rect):
  2023. """Draw preview image to pseudoDC"""
  2024. self.pdcImage.ClearId(self.imageId)
  2025. self.pdcImage.SetId(self.imageId)
  2026. img = self.image
  2027. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  2028. img = img.Scale(rect.width, rect.height)
  2029. bitmap = img.ConvertToBitmap()
  2030. self.pdcImage.BeginDrawing()
  2031. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  2032. self.pdcImage.SetIdBounds(self.imageId, rect)
  2033. self.pdcImage.EndDrawing()
  2034. self.Refresh()
  2035. def DrawPaper(self, rect):
  2036. """Draw paper and margins"""
  2037. page = self.instruction[self.pageId]
  2038. scale = page['Width'] / rect.GetWidth()
  2039. w = (page['Width'] - page['Right'] - page['Left']) / scale
  2040. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  2041. x = page['Left'] / scale + rect.GetX()
  2042. y = page['Top'] / scale + rect.GetY()
  2043. self.pdcPaper.BeginDrawing()
  2044. self.pdcPaper.RemoveId(self.pageId)
  2045. self.pdcPaper.SetId(self.pageId)
  2046. self.pdcPaper.SetPen(self.pen['paper'])
  2047. self.pdcPaper.SetBrush(self.brush['paper'])
  2048. self.pdcPaper.DrawRectangleRect(rect)
  2049. self.pdcPaper.SetPen(self.pen['margins'])
  2050. self.pdcPaper.SetBrush(self.brush['margins'])
  2051. self.pdcPaper.DrawRectangle(x, y, w, h)
  2052. self.pdcPaper.SetIdBounds(self.pageId, rect)
  2053. self.pdcPaper.EndDrawing()
  2054. self.Refresh()
  2055. def ImageRect(self):
  2056. """Returns image centered in canvas, computes scale"""
  2057. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  2058. cW, cH = self.GetClientSize()
  2059. iW, iH = img.GetWidth(), img.GetHeight()
  2060. self.currScale = min(float(cW) / iW, float(cH) / iH)
  2061. iW = iW * self.currScale
  2062. iH = iH * self.currScale
  2063. x = cW / 2 - iW / 2
  2064. y = cH / 2 - iH / 2
  2065. imageRect = wx.Rect(x, y, iW, iH)
  2066. return imageRect
  2067. def RedrawSelectBox(self, id):
  2068. """Redraws select box when selected object changes its size"""
  2069. if self.dragId == id:
  2070. rect = self.pdcObj.GetIdBounds(id)
  2071. if self.instruction[id].type != 'line':
  2072. rect = rect.Inflate(3, 3)
  2073. # draw select box around object
  2074. self.Draw(
  2075. pen=self.pen['select'],
  2076. brush=self.brush['select'],
  2077. pdc=self.pdcTmp,
  2078. drawid=self.idBoxTmp,
  2079. pdctype='rect',
  2080. bb=rect)
  2081. # draw small marks signalizing resizing
  2082. if self.instruction[id].type in ('map', 'rectangle'):
  2083. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  2084. rect = wx.RectPS(controlP, self.resizeBoxSize)
  2085. self.Draw(
  2086. pen=self.pen['resize'],
  2087. brush=self.brush['resize'],
  2088. pdc=self.pdcTmp,
  2089. drawid=self.idResizeBoxTmp,
  2090. pdctype='rect',
  2091. bb=rect)
  2092. elif self.instruction[id].type == 'line':
  2093. p1Paper = self.instruction[id]['where'][0]
  2094. p2Paper = self.instruction[id]['where'][1]
  2095. p1Canvas = self.CanvasPaperCoordinates(
  2096. rect=Rect2DPS(p1Paper, (0, 0)), canvasToPaper=False)[:2]
  2097. p2Canvas = self.CanvasPaperCoordinates(
  2098. rect=Rect2DPS(p2Paper, (0, 0)), canvasToPaper=False)[:2]
  2099. rect = []
  2100. box = wx.RectS(self.resizeBoxSize)
  2101. rect.append(box.CenterIn(wx.RectPS(p1Canvas, wx.Size())))
  2102. rect.append(box.CenterIn(wx.RectPS(p2Canvas, wx.Size())))
  2103. for i, point in enumerate((p1Canvas, p2Canvas)):
  2104. self.Draw(
  2105. pen=self.pen['resize'],
  2106. brush=self.brush['resize'],
  2107. pdc=self.pdcTmp,
  2108. drawid=self.idLinePointsTmp[i],
  2109. pdctype='rect',
  2110. bb=rect[i])
  2111. def UpdateMapLabel(self):
  2112. """Updates map frame label"""
  2113. vector = self.instruction.FindInstructionByType('vector')
  2114. if vector:
  2115. vectorId = vector.id
  2116. else:
  2117. vectorId = None
  2118. raster = self.instruction.FindInstructionByType('raster')
  2119. if raster:
  2120. rasterId = raster.id
  2121. else:
  2122. rasterId = None
  2123. rasterName = 'None'
  2124. if rasterId:
  2125. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  2126. mapId = self.instruction.FindInstructionByType('map').id
  2127. self.itemLabels[mapId] = []
  2128. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  2129. self.itemLabels[mapId].append("raster: " + rasterName)
  2130. if vectorId:
  2131. for map in self.instruction[vectorId]['list']:
  2132. self.itemLabels[mapId].append(
  2133. 'vector: ' + map[0].split('@')[0])
  2134. labels = self.instruction.FindInstructionByType('labels')
  2135. if labels:
  2136. labelFiles = self.instruction[labels.id]['labels']
  2137. if not labelFiles:
  2138. return
  2139. labelFiles = [lFile.split('@')[0] for lFile in labelFiles]
  2140. self.itemLabels[mapId].append(
  2141. _("labels: ") + ', '.join(labelFiles))
  2142. def UpdateLabel(self, itype, id):
  2143. self.itemLabels[id] = []
  2144. self.itemLabels[id].append(self.itemLabelsDict[itype])
  2145. if itype == 'image':
  2146. file = os.path.basename(self.instruction[id]['epsfile'])
  2147. self.itemLabels[id].append(file)
  2148. def OnSize(self, event):
  2149. """Init image size to match window size
  2150. """
  2151. # not zoom all when notebook page is changed
  2152. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  2153. self.ZoomAll()
  2154. self.OnIdle(None)
  2155. event.Skip()
  2156. def OnIdle(self, event):
  2157. """Only re-render a image during idle time instead of
  2158. multiple times during resizing.
  2159. """
  2160. width, height = self.GetClientSize()
  2161. # Make new off screen bitmap: this bitmap will always have the
  2162. # current drawing in it, so it can be used to save the image
  2163. # to a file, or whatever.
  2164. self._buffer = wx.EmptyBitmap(width, height)
  2165. # re-render image on idle
  2166. self.resize = True
  2167. def ScaleRect(self, rect, scale):
  2168. """Scale rectangle"""
  2169. return wx.Rect(rect.GetLeft() * scale, rect.GetTop() * scale,
  2170. rect.GetSize()[0] * scale, rect.GetSize()[1] * scale)