frame.py 99 KB

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