frame.py 96 KB

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