FlatCAMGeoEditor.py 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. ############################################################ #
  9. # File Modified: Marius Adrian Stanciu (c) #
  10. # Date: 3/10/2019 #
  11. ############################################################
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, QSettings
  14. from camlib import *
  15. from FlatCAMTool import FlatCAMTool
  16. from flatcamGUI.ObjectUI import LengthEntry, RadioSet
  17. from shapely.geometry import LineString, LinearRing, MultiLineString
  18. from shapely.ops import cascaded_union
  19. import shapely.affinity as affinity
  20. from numpy import arctan2, Inf, array, sqrt, sign, dot
  21. from numpy.linalg import norm as numpy_norm
  22. from rtree import index as rtindex
  23. from flatcamGUI.GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCComboBox, FCTextAreaRich, \
  24. FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog
  25. from flatcamParsers.ParseFont import *
  26. import gettext
  27. import FlatCAMTranslation as fcTranslate
  28. fcTranslate.apply_language('strings')
  29. import builtins
  30. if '_' not in builtins.__dict__:
  31. _ = gettext.gettext
  32. class BufferSelectionTool(FlatCAMTool):
  33. """
  34. Simple input for buffer distance.
  35. """
  36. toolName = "Buffer Selection"
  37. def __init__(self, app, draw_app):
  38. FlatCAMTool.__init__(self, app)
  39. self.draw_app = draw_app
  40. # Title
  41. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  42. title_label.setStyleSheet("""
  43. QLabel
  44. {
  45. font-size: 16px;
  46. font-weight: bold;
  47. }
  48. """)
  49. self.layout.addWidget(title_label)
  50. # this way I can hide/show the frame
  51. self.buffer_tool_frame = QtWidgets.QFrame()
  52. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  53. self.layout.addWidget(self.buffer_tool_frame)
  54. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  55. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  56. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  57. # Form Layout
  58. form_layout = QtWidgets.QFormLayout()
  59. self.buffer_tools_box.addLayout(form_layout)
  60. # Buffer distance
  61. self.buffer_distance_entry = FCEntry()
  62. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  63. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  64. self.buffer_corner_lbl.setToolTip(
  65. _("There are 3 types of corners:\n"
  66. " - 'Round': the corner is rounded for exterior buffer.\n"
  67. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  68. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  69. )
  70. self.buffer_corner_cb = FCComboBox()
  71. self.buffer_corner_cb.addItem(_("Round"))
  72. self.buffer_corner_cb.addItem(_("Square"))
  73. self.buffer_corner_cb.addItem(_("Beveled"))
  74. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  75. # Buttons
  76. hlay = QtWidgets.QHBoxLayout()
  77. self.buffer_tools_box.addLayout(hlay)
  78. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  79. hlay.addWidget(self.buffer_int_button)
  80. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  81. hlay.addWidget(self.buffer_ext_button)
  82. hlay1 = QtWidgets.QHBoxLayout()
  83. self.buffer_tools_box.addLayout(hlay1)
  84. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  85. hlay1.addWidget(self.buffer_button)
  86. self.layout.addStretch()
  87. # Signals
  88. self.buffer_button.clicked.connect(self.on_buffer)
  89. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  90. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  91. # Init GUI
  92. self.buffer_distance_entry.set_value(0.01)
  93. def run(self):
  94. self.app.report_usage("Geo Editor ToolBuffer()")
  95. FlatCAMTool.run(self)
  96. # if the splitter us hidden, display it
  97. if self.app.ui.splitter.sizes()[0] == 0:
  98. self.app.ui.splitter.setSizes([1, 1])
  99. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  100. def on_buffer(self):
  101. try:
  102. buffer_distance = float(self.buffer_distance_entry.get_value())
  103. except ValueError:
  104. # try to convert comma to decimal point. if it's still not working error message and return
  105. try:
  106. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  107. self.buffer_distance_entry.set_value(buffer_distance)
  108. except ValueError:
  109. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  110. "Add it and retry."))
  111. return
  112. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  113. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  114. join_style = self.buffer_corner_cb.currentIndex() + 1
  115. self.draw_app.buffer(buffer_distance, join_style)
  116. def on_buffer_int(self):
  117. try:
  118. buffer_distance = float(self.buffer_distance_entry.get_value())
  119. except ValueError:
  120. # try to convert comma to decimal point. if it's still not working error message and return
  121. try:
  122. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  123. self.buffer_distance_entry.set_value(buffer_distance)
  124. except ValueError:
  125. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  126. "Add it and retry."))
  127. return
  128. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  129. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  130. join_style = self.buffer_corner_cb.currentIndex() + 1
  131. self.draw_app.buffer_int(buffer_distance, join_style)
  132. def on_buffer_ext(self):
  133. try:
  134. buffer_distance = float(self.buffer_distance_entry.get_value())
  135. except ValueError:
  136. # try to convert comma to decimal point. if it's still not working error message and return
  137. try:
  138. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  139. self.buffer_distance_entry.set_value(buffer_distance)
  140. except ValueError:
  141. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  142. "Add it and retry."))
  143. return
  144. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  145. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  146. join_style = self.buffer_corner_cb.currentIndex() + 1
  147. self.draw_app.buffer_ext(buffer_distance, join_style)
  148. def hide_tool(self):
  149. self.buffer_tool_frame.hide()
  150. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  151. class TextInputTool(FlatCAMTool):
  152. """
  153. Simple input for buffer distance.
  154. """
  155. toolName = "Text Input Tool"
  156. def __init__(self, app):
  157. FlatCAMTool.__init__(self, app)
  158. self.app = app
  159. self.text_path = []
  160. self.f_parse = ParseFont(self)
  161. self.f_parse.get_fonts_by_types()
  162. # this way I can hide/show the frame
  163. self.text_tool_frame = QtWidgets.QFrame()
  164. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  165. self.layout.addWidget(self.text_tool_frame)
  166. self.text_tools_box = QtWidgets.QVBoxLayout()
  167. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  168. self.text_tool_frame.setLayout(self.text_tools_box)
  169. # Title
  170. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  171. title_label.setStyleSheet("""
  172. QLabel
  173. {
  174. font-size: 16px;
  175. font-weight: bold;
  176. }
  177. """)
  178. self.text_tools_box.addWidget(title_label)
  179. # Form Layout
  180. self.form_layout = QtWidgets.QFormLayout()
  181. self.text_tools_box.addLayout(self.form_layout)
  182. # Font type
  183. if sys.platform == "win32":
  184. f_current = QtGui.QFont("Arial")
  185. elif sys.platform == "linux":
  186. f_current = QtGui.QFont("FreeMono")
  187. else:
  188. f_current = QtGui.QFont("Helvetica Neue")
  189. self.font_name = f_current.family()
  190. self.font_type_cb = QtWidgets.QFontComboBox(self)
  191. self.font_type_cb.setCurrentFont(f_current)
  192. self.form_layout.addRow("Font:", self.font_type_cb)
  193. # Flag variables to show if font is bold, italic, both or none (regular)
  194. self.font_bold = False
  195. self.font_italic = False
  196. # # Create dictionaries with the filenames of the fonts
  197. # # Key: Fontname
  198. # # Value: Font File Name.ttf
  199. #
  200. # # regular fonts
  201. # self.ff_names_regular ={}
  202. # # bold fonts
  203. # self.ff_names_bold = {}
  204. # # italic fonts
  205. # self.ff_names_italic = {}
  206. # # bold and italic fonts
  207. # self.ff_names_bi = {}
  208. #
  209. # if sys.platform == 'win32':
  210. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  211. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  212. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  213. # try:
  214. # i = 0
  215. # while 1:
  216. # name_font, value, type = EnumValue(font_key, i)
  217. # k = name_font.replace(" (TrueType)", '')
  218. # if 'Bold' in k and 'Italic' in k:
  219. # k = k.replace(" Bold Italic", '')
  220. # self.ff_names_bi.update({k: value})
  221. # elif 'Bold' in k:
  222. # k = k.replace(" Bold", '')
  223. # self.ff_names_bold.update({k: value})
  224. # elif 'Italic' in k:
  225. # k = k.replace(" Italic", '')
  226. # self.ff_names_italic.update({k: value})
  227. # else:
  228. # self.ff_names_regular.update({k: value})
  229. # i += 1
  230. # except WindowsError:
  231. # pass
  232. # Font size
  233. self.font_size_cb = FCComboBox()
  234. self.font_size_cb.setEditable(True)
  235. self.font_size_cb.setMinimumContentsLength(3)
  236. self.font_size_cb.setMaximumWidth(70)
  237. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  238. '15', '16', '18', '20', '22', '24', '26', '28',
  239. '32', '36', '40', '44', '48', '54', '60', '66',
  240. '72', '80', '88', '96']
  241. for i in font_sizes:
  242. self.font_size_cb.addItem(i)
  243. self.font_size_cb.setCurrentIndex(4)
  244. hlay = QtWidgets.QHBoxLayout()
  245. hlay.addWidget(self.font_size_cb)
  246. hlay.addStretch()
  247. self.font_bold_tb = QtWidgets.QToolButton()
  248. self.font_bold_tb.setCheckable(True)
  249. self.font_bold_tb.setIcon(QtGui.QIcon('share/bold32.png'))
  250. hlay.addWidget(self.font_bold_tb)
  251. self.font_italic_tb = QtWidgets.QToolButton()
  252. self.font_italic_tb.setCheckable(True)
  253. self.font_italic_tb.setIcon(QtGui.QIcon('share/italic32.png'))
  254. hlay.addWidget(self.font_italic_tb)
  255. self.form_layout.addRow("Size:", hlay)
  256. # Text input
  257. self.text_input_entry = FCTextAreaRich()
  258. self.text_input_entry.setTabStopWidth(12)
  259. self.text_input_entry.setMinimumHeight(200)
  260. # self.text_input_entry.setMaximumHeight(150)
  261. self.text_input_entry.setCurrentFont(f_current)
  262. self.text_input_entry.setFontPointSize(10)
  263. self.form_layout.addRow("Text:", self.text_input_entry)
  264. # Buttons
  265. hlay1 = QtWidgets.QHBoxLayout()
  266. self.form_layout.addRow("", hlay1)
  267. hlay1.addStretch()
  268. self.apply_button = QtWidgets.QPushButton("Apply")
  269. hlay1.addWidget(self.apply_button)
  270. # self.layout.addStretch()
  271. # Signals
  272. self.apply_button.clicked.connect(self.on_apply_button)
  273. self.font_type_cb.currentFontChanged.connect(self.font_family)
  274. self.font_size_cb.activated.connect(self.font_size)
  275. self.font_bold_tb.clicked.connect(self.on_bold_button)
  276. self.font_italic_tb.clicked.connect(self.on_italic_button)
  277. def run(self):
  278. self.app.report_usage("Geo Editor TextInputTool()")
  279. FlatCAMTool.run(self)
  280. # if the splitter us hidden, display it
  281. if self.app.ui.splitter.sizes()[0] == 0:
  282. self.app.ui.splitter.setSizes([1, 1])
  283. self.app.ui.notebook.setTabText(2, _("Text Tool"))
  284. def on_apply_button(self):
  285. font_to_geo_type = ""
  286. if self.font_bold is True:
  287. font_to_geo_type = 'bold'
  288. elif self.font_italic is True:
  289. font_to_geo_type = 'italic'
  290. elif self.font_bold is True and self.font_italic is True:
  291. font_to_geo_type = 'bi'
  292. elif self.font_bold is False and self.font_italic is False:
  293. font_to_geo_type = 'regular'
  294. string_to_geo = self.text_input_entry.get_value()
  295. font_to_geo_size = self.font_size_cb.get_value()
  296. self.text_path = self.f_parse.font_to_geometry(
  297. char_string=string_to_geo,
  298. font_name=self.font_name,
  299. font_size=font_to_geo_size,
  300. font_type=font_to_geo_type,
  301. units=self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper())
  302. def font_family(self, font):
  303. self.text_input_entry.selectAll()
  304. font.setPointSize(float(self.font_size_cb.get_value()))
  305. self.text_input_entry.setCurrentFont(font)
  306. self.font_name = self.font_type_cb.currentFont().family()
  307. def font_size(self):
  308. self.text_input_entry.selectAll()
  309. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  310. def on_bold_button(self):
  311. if self.font_bold_tb.isChecked():
  312. self.text_input_entry.selectAll()
  313. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  314. self.font_bold = True
  315. else:
  316. self.text_input_entry.selectAll()
  317. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  318. self.font_bold = False
  319. def on_italic_button(self):
  320. if self.font_italic_tb.isChecked():
  321. self.text_input_entry.selectAll()
  322. self.text_input_entry.setFontItalic(True)
  323. self.font_italic = True
  324. else:
  325. self.text_input_entry.selectAll()
  326. self.text_input_entry.setFontItalic(False)
  327. self.font_italic = False
  328. def hide_tool(self):
  329. self.text_tool_frame.hide()
  330. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  331. self.app.ui.splitter.setSizes([0, 1])
  332. self.app.ui.notebook.setTabText(2, _("Tool"))
  333. class PaintOptionsTool(FlatCAMTool):
  334. """
  335. Inputs to specify how to paint the selected polygons.
  336. """
  337. toolName = "Paint Tool"
  338. def __init__(self, app, fcdraw):
  339. FlatCAMTool.__init__(self, app)
  340. self.app = app
  341. self.fcdraw = fcdraw
  342. ## Title
  343. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  344. title_label.setStyleSheet("""
  345. QLabel
  346. {
  347. font-size: 16px;
  348. font-weight: bold;
  349. }
  350. """)
  351. self.layout.addWidget(title_label)
  352. grid = QtWidgets.QGridLayout()
  353. self.layout.addLayout(grid)
  354. # Tool dia
  355. ptdlabel = QtWidgets.QLabel(_('Tool dia:'))
  356. ptdlabel.setToolTip(
  357. _( "Diameter of the tool to\n"
  358. "be used in the operation.")
  359. )
  360. grid.addWidget(ptdlabel, 0, 0)
  361. self.painttooldia_entry = FCEntry()
  362. grid.addWidget(self.painttooldia_entry, 0, 1)
  363. # Overlap
  364. ovlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  365. ovlabel.setToolTip(
  366. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  367. "Example:\n"
  368. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  369. "Adjust the value starting with lower values\n"
  370. "and increasing it if areas that should be painted are still \n"
  371. "not painted.\n"
  372. "Lower values = faster processing, faster execution on PCB.\n"
  373. "Higher values = slow processing and slow execution on CNC\n"
  374. "due of too many paths.")
  375. )
  376. grid.addWidget(ovlabel, 1, 0)
  377. self.paintoverlap_entry = FCEntry()
  378. self.paintoverlap_entry.setValidator(QtGui.QDoubleValidator(0.0000, 1.0000, 4))
  379. grid.addWidget(self.paintoverlap_entry, 1, 1)
  380. # Margin
  381. marginlabel = QtWidgets.QLabel(_('Margin:'))
  382. marginlabel.setToolTip(
  383. _( "Distance by which to avoid\n"
  384. "the edges of the polygon to\n"
  385. "be painted.")
  386. )
  387. grid.addWidget(marginlabel, 2, 0)
  388. self.paintmargin_entry = FCEntry()
  389. grid.addWidget(self.paintmargin_entry, 2, 1)
  390. # Method
  391. methodlabel = QtWidgets.QLabel(_('Method:'))
  392. methodlabel.setToolTip(
  393. _("Algorithm to paint the polygon:<BR>"
  394. "<B>Standard</B>: Fixed step inwards.<BR>"
  395. "<B>Seed-based</B>: Outwards from seed.")
  396. )
  397. grid.addWidget(methodlabel, 3, 0)
  398. self.paintmethod_combo = RadioSet([
  399. {"label": _("Standard"), "value": "standard"},
  400. {"label": _("Seed-based"), "value": "seed"},
  401. {"label": _("Straight lines"), "value": "lines"}
  402. ], orientation='vertical', stretch=False)
  403. grid.addWidget(self.paintmethod_combo, 3, 1)
  404. # Connect lines
  405. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  406. pathconnectlabel.setToolTip(
  407. _( "Draw lines between resulting\n"
  408. "segments to minimize tool lifts.")
  409. )
  410. grid.addWidget(pathconnectlabel, 4, 0)
  411. self.pathconnect_cb = FCCheckBox()
  412. grid.addWidget(self.pathconnect_cb, 4, 1)
  413. contourlabel = QtWidgets.QLabel(_("Contour:"))
  414. contourlabel.setToolTip(
  415. _("Cut around the perimeter of the polygon\n"
  416. "to trim rough edges.")
  417. )
  418. grid.addWidget(contourlabel, 5, 0)
  419. self.paintcontour_cb = FCCheckBox()
  420. grid.addWidget(self.paintcontour_cb, 5, 1)
  421. ## Buttons
  422. hlay = QtWidgets.QHBoxLayout()
  423. self.layout.addLayout(hlay)
  424. hlay.addStretch()
  425. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  426. hlay.addWidget(self.paint_button)
  427. self.layout.addStretch()
  428. ## Signals
  429. self.paint_button.clicked.connect(self.on_paint)
  430. self.set_tool_ui()
  431. def run(self):
  432. self.app.report_usage("Geo Editor ToolPaint()")
  433. FlatCAMTool.run(self)
  434. # if the splitter us hidden, display it
  435. if self.app.ui.splitter.sizes()[0] == 0:
  436. self.app.ui.splitter.setSizes([1, 1])
  437. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  438. def set_tool_ui(self):
  439. ## Init GUI
  440. if self.app.defaults["tools_painttooldia"]:
  441. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  442. else:
  443. self.painttooldia_entry.set_value(0.0)
  444. if self.app.defaults["tools_paintoverlap"]:
  445. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  446. else:
  447. self.paintoverlap_entry.set_value(0.0)
  448. if self.app.defaults["tools_paintmargin"]:
  449. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  450. else:
  451. self.paintmargin_entry.set_value(0.0)
  452. if self.app.defaults["tools_paintmethod"]:
  453. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  454. else:
  455. self.paintmethod_combo.set_value("seed")
  456. if self.app.defaults["tools_pathconnect"]:
  457. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  458. else:
  459. self.pathconnect_cb.set_value(False)
  460. if self.app.defaults["tools_paintcontour"]:
  461. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  462. else:
  463. self.paintcontour_cb.set_value(False)
  464. def on_paint(self):
  465. if not self.fcdraw.selected:
  466. self.app.inform.emit(_("[WARNING_NOTCL] Paint cancelled. No shape selected."))
  467. return
  468. try:
  469. tooldia = float(self.painttooldia_entry.get_value())
  470. except ValueError:
  471. # try to convert comma to decimal point. if it's still not working error message and return
  472. try:
  473. tooldia = float(self.painttooldia_entry.get_value().replace(',', '.'))
  474. self.painttooldia_entry.set_value(tooldia)
  475. except ValueError:
  476. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  477. "Add it and retry."))
  478. return
  479. try:
  480. overlap = float(self.paintoverlap_entry.get_value())
  481. except ValueError:
  482. # try to convert comma to decimal point. if it's still not working error message and return
  483. try:
  484. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  485. self.paintoverlap_entry.set_value(overlap)
  486. except ValueError:
  487. self.app.inform.emit(_("[WARNING_NOTCL] Overlap value is missing or wrong format. "
  488. "Add it and retry."))
  489. return
  490. try:
  491. margin = float(self.paintmargin_entry.get_value())
  492. except ValueError:
  493. # try to convert comma to decimal point. if it's still not working error message and return
  494. try:
  495. margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  496. self.paintmargin_entry.set_value(margin)
  497. except ValueError:
  498. self.app.inform.emit(_("[WARNING_NOTCL] Margin distance value is missing or wrong format. "
  499. "Add it and retry."))
  500. return
  501. method = self.paintmethod_combo.get_value()
  502. contour = self.paintcontour_cb.get_value()
  503. connect = self.pathconnect_cb.get_value()
  504. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  505. self.fcdraw.select_tool("select")
  506. self.app.ui.notebook.setTabText(2, _("Tools"))
  507. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  508. self.app.ui.splitter.setSizes([0, 1])
  509. class TransformEditorTool(FlatCAMTool):
  510. """
  511. Inputs to specify how to paint the selected polygons.
  512. """
  513. toolName = _("Transform Tool")
  514. rotateName = _("Rotate")
  515. skewName = _("Skew/Shear")
  516. scaleName = _("Scale")
  517. flipName = _("Mirror (Flip)")
  518. offsetName = _("Offset")
  519. def __init__(self, app, draw_app):
  520. FlatCAMTool.__init__(self, app)
  521. self.app = app
  522. self.draw_app = draw_app
  523. self.transform_lay = QtWidgets.QVBoxLayout()
  524. self.layout.addLayout(self.transform_lay)
  525. ## Title
  526. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  527. title_label.setStyleSheet("""
  528. QLabel
  529. {
  530. font-size: 16px;
  531. font-weight: bold;
  532. }
  533. """)
  534. self.transform_lay.addWidget(title_label)
  535. self.empty_label = QtWidgets.QLabel("")
  536. self.empty_label.setFixedWidth(50)
  537. self.empty_label1 = QtWidgets.QLabel("")
  538. self.empty_label1.setFixedWidth(70)
  539. self.empty_label2 = QtWidgets.QLabel("")
  540. self.empty_label2.setFixedWidth(70)
  541. self.empty_label3 = QtWidgets.QLabel("")
  542. self.empty_label3.setFixedWidth(70)
  543. self.empty_label4 = QtWidgets.QLabel("")
  544. self.empty_label4.setFixedWidth(70)
  545. self.transform_lay.addWidget(self.empty_label)
  546. ## Rotate Title
  547. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  548. self.transform_lay.addWidget(rotate_title_label)
  549. ## Layout
  550. form_layout = QtWidgets.QFormLayout()
  551. self.transform_lay.addLayout(form_layout)
  552. form_child = QtWidgets.QHBoxLayout()
  553. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  554. self.rotate_label.setToolTip(
  555. _( "Angle for Rotation action, in degrees.\n"
  556. "Float number between -360 and 359.\n"
  557. "Positive numbers for CW motion.\n"
  558. "Negative numbers for CCW motion.")
  559. )
  560. self.rotate_label.setFixedWidth(50)
  561. self.rotate_entry = FCEntry()
  562. # self.rotate_entry.setFixedWidth(60)
  563. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  564. self.rotate_button = FCButton()
  565. self.rotate_button.set_value(_("Rotate"))
  566. self.rotate_button.setToolTip(
  567. _("Rotate the selected shape(s).\n"
  568. "The point of reference is the middle of\n"
  569. "the bounding box for all selected shapes.")
  570. )
  571. self.rotate_button.setFixedWidth(60)
  572. form_child.addWidget(self.rotate_entry)
  573. form_child.addWidget(self.rotate_button)
  574. form_layout.addRow(self.rotate_label, form_child)
  575. self.transform_lay.addWidget(self.empty_label1)
  576. ## Skew Title
  577. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  578. self.transform_lay.addWidget(skew_title_label)
  579. ## Form Layout
  580. form1_layout = QtWidgets.QFormLayout()
  581. self.transform_lay.addLayout(form1_layout)
  582. form1_child_1 = QtWidgets.QHBoxLayout()
  583. form1_child_2 = QtWidgets.QHBoxLayout()
  584. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  585. self.skewx_label.setToolTip(
  586. _( "Angle for Skew action, in degrees.\n"
  587. "Float number between -360 and 359.")
  588. )
  589. self.skewx_label.setFixedWidth(50)
  590. self.skewx_entry = FCEntry()
  591. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  592. # self.skewx_entry.setFixedWidth(60)
  593. self.skewx_button = FCButton()
  594. self.skewx_button.set_value(_("Skew X"))
  595. self.skewx_button.setToolTip(
  596. _( "Skew/shear the selected shape(s).\n"
  597. "The point of reference is the middle of\n"
  598. "the bounding box for all selected shapes."))
  599. self.skewx_button.setFixedWidth(60)
  600. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  601. self.skewy_label.setToolTip(
  602. _( "Angle for Skew action, in degrees.\n"
  603. "Float number between -360 and 359.")
  604. )
  605. self.skewy_label.setFixedWidth(50)
  606. self.skewy_entry = FCEntry()
  607. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  608. # self.skewy_entry.setFixedWidth(60)
  609. self.skewy_button = FCButton()
  610. self.skewy_button.set_value(_("Skew Y"))
  611. self.skewy_button.setToolTip(
  612. _("Skew/shear the selected shape(s).\n"
  613. "The point of reference is the middle of\n"
  614. "the bounding box for all selected shapes."))
  615. self.skewy_button.setFixedWidth(60)
  616. form1_child_1.addWidget(self.skewx_entry)
  617. form1_child_1.addWidget(self.skewx_button)
  618. form1_child_2.addWidget(self.skewy_entry)
  619. form1_child_2.addWidget(self.skewy_button)
  620. form1_layout.addRow(self.skewx_label, form1_child_1)
  621. form1_layout.addRow(self.skewy_label, form1_child_2)
  622. self.transform_lay.addWidget(self.empty_label2)
  623. ## Scale Title
  624. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  625. self.transform_lay.addWidget(scale_title_label)
  626. ## Form Layout
  627. form2_layout = QtWidgets.QFormLayout()
  628. self.transform_lay.addLayout(form2_layout)
  629. form2_child_1 = QtWidgets.QHBoxLayout()
  630. form2_child_2 = QtWidgets.QHBoxLayout()
  631. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  632. self.scalex_label.setToolTip(
  633. _("Factor for Scale action over X axis.")
  634. )
  635. self.scalex_label.setFixedWidth(50)
  636. self.scalex_entry = FCEntry()
  637. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  638. # self.scalex_entry.setFixedWidth(60)
  639. self.scalex_button = FCButton()
  640. self.scalex_button.set_value(_("Scale X"))
  641. self.scalex_button.setToolTip(
  642. _( "Scale the selected shape(s).\n"
  643. "The point of reference depends on \n"
  644. "the Scale reference checkbox state."))
  645. self.scalex_button.setFixedWidth(60)
  646. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  647. self.scaley_label.setToolTip(
  648. _("Factor for Scale action over Y axis.")
  649. )
  650. self.scaley_label.setFixedWidth(50)
  651. self.scaley_entry = FCEntry()
  652. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  653. # self.scaley_entry.setFixedWidth(60)
  654. self.scaley_button = FCButton()
  655. self.scaley_button.set_value(_("Scale Y"))
  656. self.scaley_button.setToolTip(
  657. _( "Scale the selected shape(s).\n"
  658. "The point of reference depends on \n"
  659. "the Scale reference checkbox state."))
  660. self.scaley_button.setFixedWidth(60)
  661. self.scale_link_cb = FCCheckBox()
  662. self.scale_link_cb.set_value(True)
  663. self.scale_link_cb.setText(_("Link"))
  664. self.scale_link_cb.setToolTip(
  665. _("Scale the selected shape(s)\n"
  666. "using the Scale Factor X for both axis."))
  667. self.scale_link_cb.setFixedWidth(50)
  668. self.scale_zero_ref_cb = FCCheckBox()
  669. self.scale_zero_ref_cb.set_value(True)
  670. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  671. self.scale_zero_ref_cb.setToolTip(
  672. _("Scale the selected shape(s)\n"
  673. "using the origin reference when checked,\n"
  674. "and the center of the biggest bounding box\n"
  675. "of the selected shapes when unchecked."))
  676. form2_child_1.addWidget(self.scalex_entry)
  677. form2_child_1.addWidget(self.scalex_button)
  678. form2_child_2.addWidget(self.scaley_entry)
  679. form2_child_2.addWidget(self.scaley_button)
  680. form2_layout.addRow(self.scalex_label, form2_child_1)
  681. form2_layout.addRow(self.scaley_label, form2_child_2)
  682. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  683. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  684. self.transform_lay.addWidget(self.empty_label3)
  685. ## Offset Title
  686. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  687. self.transform_lay.addWidget(offset_title_label)
  688. ## Form Layout
  689. form3_layout = QtWidgets.QFormLayout()
  690. self.transform_lay.addLayout(form3_layout)
  691. form3_child_1 = QtWidgets.QHBoxLayout()
  692. form3_child_2 = QtWidgets.QHBoxLayout()
  693. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  694. self.offx_label.setToolTip(
  695. _("Value for Offset action on X axis.")
  696. )
  697. self.offx_label.setFixedWidth(50)
  698. self.offx_entry = FCEntry()
  699. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  700. # self.offx_entry.setFixedWidth(60)
  701. self.offx_button = FCButton()
  702. self.offx_button.set_value(_("Offset X"))
  703. self.offx_button.setToolTip(
  704. _( "Offset the selected shape(s).\n"
  705. "The point of reference is the middle of\n"
  706. "the bounding box for all selected shapes.\n")
  707. )
  708. self.offx_button.setFixedWidth(60)
  709. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  710. self.offy_label.setToolTip(
  711. _("Value for Offset action on Y axis.")
  712. )
  713. self.offy_label.setFixedWidth(50)
  714. self.offy_entry = FCEntry()
  715. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  716. # self.offy_entry.setFixedWidth(60)
  717. self.offy_button = FCButton()
  718. self.offy_button.set_value(_("Offset Y"))
  719. self.offy_button.setToolTip(
  720. _("Offset the selected shape(s).\n"
  721. "The point of reference is the middle of\n"
  722. "the bounding box for all selected shapes.\n")
  723. )
  724. self.offy_button.setFixedWidth(60)
  725. form3_child_1.addWidget(self.offx_entry)
  726. form3_child_1.addWidget(self.offx_button)
  727. form3_child_2.addWidget(self.offy_entry)
  728. form3_child_2.addWidget(self.offy_button)
  729. form3_layout.addRow(self.offx_label, form3_child_1)
  730. form3_layout.addRow(self.offy_label, form3_child_2)
  731. self.transform_lay.addWidget(self.empty_label4)
  732. ## Flip Title
  733. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  734. self.transform_lay.addWidget(flip_title_label)
  735. ## Form Layout
  736. form4_layout = QtWidgets.QFormLayout()
  737. form4_child_hlay = QtWidgets.QHBoxLayout()
  738. self.transform_lay.addLayout(form4_child_hlay)
  739. self.transform_lay.addLayout(form4_layout)
  740. form4_child_1 = QtWidgets.QHBoxLayout()
  741. self.flipx_button = FCButton()
  742. self.flipx_button.set_value(_("Flip on X"))
  743. self.flipx_button.setToolTip(
  744. _("Flip the selected shape(s) over the X axis.\n"
  745. "Does not create a new shape.")
  746. )
  747. self.flipx_button.setFixedWidth(60)
  748. self.flipy_button = FCButton()
  749. self.flipy_button.set_value(_("Flip on Y"))
  750. self.flipy_button.setToolTip(
  751. _("Flip the selected shape(s) over the X axis.\n"
  752. "Does not create a new shape.")
  753. )
  754. self.flipy_button.setFixedWidth(60)
  755. self.flip_ref_cb = FCCheckBox()
  756. self.flip_ref_cb.set_value(True)
  757. self.flip_ref_cb.setText(_("Ref Pt"))
  758. self.flip_ref_cb.setToolTip(
  759. _("Flip the selected shape(s)\n"
  760. "around the point in Point Entry Field.\n"
  761. "\n"
  762. "The point coordinates can be captured by\n"
  763. "left click on canvas together with pressing\n"
  764. "SHIFT key. \n"
  765. "Then click Add button to insert coordinates.\n"
  766. "Or enter the coords in format (x, y) in the\n"
  767. "Point Entry field and click Flip on X(Y)")
  768. )
  769. self.flip_ref_cb.setFixedWidth(50)
  770. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  771. self.flip_ref_label.setToolTip(
  772. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  773. "The 'x' in (x, y) will be used when using Flip on X and\n"
  774. "the 'y' in (x, y) will be used when using Flip on Y.")
  775. )
  776. self.flip_ref_label.setFixedWidth(50)
  777. self.flip_ref_entry = EvalEntry2("(0, 0)")
  778. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  779. # self.flip_ref_entry.setFixedWidth(60)
  780. self.flip_ref_button = FCButton()
  781. self.flip_ref_button.set_value(_("Add"))
  782. self.flip_ref_button.setToolTip(
  783. _( "The point coordinates can be captured by\n"
  784. "left click on canvas together with pressing\n"
  785. "SHIFT key. Then click Add button to insert.")
  786. )
  787. self.flip_ref_button.setFixedWidth(60)
  788. form4_child_hlay.addStretch()
  789. form4_child_hlay.addWidget(self.flipx_button)
  790. form4_child_hlay.addWidget(self.flipy_button)
  791. form4_child_1.addWidget(self.flip_ref_entry)
  792. form4_child_1.addWidget(self.flip_ref_button)
  793. form4_layout.addRow(self.flip_ref_cb)
  794. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  795. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  796. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  797. self.transform_lay.addStretch()
  798. ## Signals
  799. self.rotate_button.clicked.connect(self.on_rotate)
  800. self.skewx_button.clicked.connect(self.on_skewx)
  801. self.skewy_button.clicked.connect(self.on_skewy)
  802. self.scalex_button.clicked.connect(self.on_scalex)
  803. self.scaley_button.clicked.connect(self.on_scaley)
  804. self.offx_button.clicked.connect(self.on_offx)
  805. self.offy_button.clicked.connect(self.on_offy)
  806. self.flipx_button.clicked.connect(self.on_flipx)
  807. self.flipy_button.clicked.connect(self.on_flipy)
  808. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  809. self.rotate_entry.returnPressed.connect(self.on_rotate)
  810. self.skewx_entry.returnPressed.connect(self.on_skewx)
  811. self.skewy_entry.returnPressed.connect(self.on_skewy)
  812. self.scalex_entry.returnPressed.connect(self.on_scalex)
  813. self.scaley_entry.returnPressed.connect(self.on_scaley)
  814. self.offx_entry.returnPressed.connect(self.on_offx)
  815. self.offy_entry.returnPressed.connect(self.on_offy)
  816. self.set_tool_ui()
  817. def run(self):
  818. self.app.report_usage("Geo Editor Transform Tool()")
  819. FlatCAMTool.run(self)
  820. self.set_tool_ui()
  821. # if the splitter us hidden, display it
  822. if self.app.ui.splitter.sizes()[0] == 0:
  823. self.app.ui.splitter.setSizes([1, 1])
  824. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  825. def install(self, icon=None, separator=None, **kwargs):
  826. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  827. def set_tool_ui(self):
  828. ## Initialize form
  829. if self.app.defaults["tools_transform_rotate"]:
  830. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  831. else:
  832. self.rotate_entry.set_value(0.0)
  833. if self.app.defaults["tools_transform_skew_x"]:
  834. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  835. else:
  836. self.skewx_entry.set_value(0.0)
  837. if self.app.defaults["tools_transform_skew_y"]:
  838. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  839. else:
  840. self.skewy_entry.set_value(0.0)
  841. if self.app.defaults["tools_transform_scale_x"]:
  842. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  843. else:
  844. self.scalex_entry.set_value(1.0)
  845. if self.app.defaults["tools_transform_scale_y"]:
  846. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  847. else:
  848. self.scaley_entry.set_value(1.0)
  849. if self.app.defaults["tools_transform_scale_link"]:
  850. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  851. else:
  852. self.scale_link_cb.set_value(True)
  853. if self.app.defaults["tools_transform_scale_reference"]:
  854. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  855. else:
  856. self.scale_zero_ref_cb.set_value(True)
  857. if self.app.defaults["tools_transform_offset_x"]:
  858. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  859. else:
  860. self.offx_entry.set_value(0.0)
  861. if self.app.defaults["tools_transform_offset_y"]:
  862. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  863. else:
  864. self.offy_entry.set_value(0.0)
  865. if self.app.defaults["tools_transform_mirror_reference"]:
  866. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  867. else:
  868. self.flip_ref_cb.set_value(False)
  869. if self.app.defaults["tools_transform_mirror_point"]:
  870. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  871. else:
  872. self.flip_ref_entry.set_value((0, 0))
  873. def template(self):
  874. if not self.fcdraw.selected:
  875. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  876. return
  877. self.draw_app.select_tool("select")
  878. self.app.ui.notebook.setTabText(2, "Tools")
  879. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  880. self.app.ui.splitter.setSizes([0, 1])
  881. def on_rotate(self, sig=None, val=None):
  882. if val:
  883. value = val
  884. else:
  885. try:
  886. value = float(self.rotate_entry.get_value())
  887. except ValueError:
  888. # try to convert comma to decimal point. if it's still not working error message and return
  889. try:
  890. value = float(self.rotate_entry.get_value().replace(',', '.'))
  891. except ValueError:
  892. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Rotate, "
  893. "use a number."))
  894. return
  895. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  896. 'params': [value]})
  897. # self.on_rotate_action(value)
  898. return
  899. def on_flipx(self):
  900. # self.on_flip("Y")
  901. axis = 'Y'
  902. self.app.worker_task.emit({'fcn': self.on_flip,
  903. 'params': [axis]})
  904. return
  905. def on_flipy(self):
  906. # self.on_flip("X")
  907. axis = 'X'
  908. self.app.worker_task.emit({'fcn': self.on_flip,
  909. 'params': [axis]})
  910. return
  911. def on_flip_add_coords(self):
  912. val = self.app.clipboard.text()
  913. self.flip_ref_entry.set_value(val)
  914. def on_skewx(self, sig=None, val=None):
  915. if val:
  916. value = val
  917. else:
  918. try:
  919. value = float(self.skewx_entry.get_value())
  920. except ValueError:
  921. # try to convert comma to decimal point. if it's still not working error message and return
  922. try:
  923. value = float(self.skewx_entry.get_value().replace(',', '.'))
  924. except ValueError:
  925. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew X, "
  926. "use a number."))
  927. return
  928. # self.on_skew("X", value)
  929. axis = 'X'
  930. self.app.worker_task.emit({'fcn': self.on_skew,
  931. 'params': [axis, value]})
  932. return
  933. def on_skewy(self, sig=None, val=None):
  934. if val:
  935. value = val
  936. else:
  937. try:
  938. value = float(self.skewy_entry.get_value())
  939. except ValueError:
  940. # try to convert comma to decimal point. if it's still not working error message and return
  941. try:
  942. value = float(self.skewy_entry.get_value().replace(',', '.'))
  943. except ValueError:
  944. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Skew Y, "
  945. "use a number."))
  946. return
  947. # self.on_skew("Y", value)
  948. axis = 'Y'
  949. self.app.worker_task.emit({'fcn': self.on_skew,
  950. 'params': [axis, value]})
  951. return
  952. def on_scalex(self, sig=None, val=None):
  953. if val:
  954. xvalue = val
  955. else:
  956. try:
  957. xvalue = float(self.scalex_entry.get_value())
  958. except ValueError:
  959. # try to convert comma to decimal point. if it's still not working error message and return
  960. try:
  961. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  962. except ValueError:
  963. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale X, "
  964. "use a number."))
  965. return
  966. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  967. if xvalue == 0:
  968. xvalue = 1
  969. if self.scale_link_cb.get_value():
  970. yvalue = xvalue
  971. else:
  972. yvalue = 1
  973. axis = 'X'
  974. point = (0, 0)
  975. if self.scale_zero_ref_cb.get_value():
  976. self.app.worker_task.emit({'fcn': self.on_scale,
  977. 'params': [axis, xvalue, yvalue, point]})
  978. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  979. else:
  980. # self.on_scale("X", xvalue, yvalue)
  981. self.app.worker_task.emit({'fcn': self.on_scale,
  982. 'params': [axis, xvalue, yvalue]})
  983. return
  984. def on_scaley(self, sig=None, val=None):
  985. xvalue = 1
  986. if val:
  987. yvalue = val
  988. else:
  989. try:
  990. yvalue = float(self.scaley_entry.get_value())
  991. except ValueError:
  992. # try to convert comma to decimal point. if it's still not working error message and return
  993. try:
  994. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  995. except ValueError:
  996. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Scale Y, "
  997. "use a number."))
  998. return
  999. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  1000. if yvalue == 0:
  1001. yvalue = 1
  1002. axis = 'Y'
  1003. point = (0, 0)
  1004. if self.scale_zero_ref_cb.get_value():
  1005. self.app.worker_task.emit({'fcn': self.on_scale,
  1006. 'params': [axis, xvalue, yvalue, point]})
  1007. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  1008. else:
  1009. # self.on_scale("Y", xvalue, yvalue)
  1010. self.app.worker_task.emit({'fcn': self.on_scale,
  1011. 'params': [axis, xvalue, yvalue]})
  1012. return
  1013. def on_offx(self, sig=None, val=None):
  1014. if val:
  1015. value = val
  1016. else:
  1017. try:
  1018. value = float(self.offx_entry.get_value())
  1019. except ValueError:
  1020. # try to convert comma to decimal point. if it's still not working error message and return
  1021. try:
  1022. value = float(self.offx_entry.get_value().replace(',', '.'))
  1023. except ValueError:
  1024. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset X, "
  1025. "use a number."))
  1026. return
  1027. # self.on_offset("X", value)
  1028. axis = 'X'
  1029. self.app.worker_task.emit({'fcn': self.on_offset,
  1030. 'params': [axis, value]})
  1031. return
  1032. def on_offy(self, sig=None, val=None):
  1033. if val:
  1034. value = val
  1035. else:
  1036. try:
  1037. value = float(self.offy_entry.get_value())
  1038. except ValueError:
  1039. # try to convert comma to decimal point. if it's still not working error message and return
  1040. try:
  1041. value = float(self.offy_entry.get_value().replace(',', '.'))
  1042. except ValueError:
  1043. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered for Offset Y, "
  1044. "use a number."))
  1045. return
  1046. # self.on_offset("Y", value)
  1047. axis = 'Y'
  1048. self.app.worker_task.emit({'fcn': self.on_offset,
  1049. 'params': [axis, value]})
  1050. return
  1051. def on_rotate_action(self, num):
  1052. shape_list = self.draw_app.selected
  1053. xminlist = []
  1054. yminlist = []
  1055. xmaxlist = []
  1056. ymaxlist = []
  1057. if not shape_list:
  1058. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  1059. return
  1060. else:
  1061. with self.app.proc_container.new(_("Appying Rotate")):
  1062. try:
  1063. # first get a bounding box to fit all
  1064. for sha in shape_list:
  1065. xmin, ymin, xmax, ymax = sha.bounds()
  1066. xminlist.append(xmin)
  1067. yminlist.append(ymin)
  1068. xmaxlist.append(xmax)
  1069. ymaxlist.append(ymax)
  1070. # get the minimum x,y and maximum x,y for all objects selected
  1071. xminimal = min(xminlist)
  1072. yminimal = min(yminlist)
  1073. xmaximal = max(xmaxlist)
  1074. ymaximal = max(ymaxlist)
  1075. self.app.progress.emit(20)
  1076. for sel_sha in shape_list:
  1077. px = 0.5 * (xminimal + xmaximal)
  1078. py = 0.5 * (yminimal + ymaximal)
  1079. sel_sha.rotate(-num, point=(px, py))
  1080. self.draw_app.replot()
  1081. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1082. # self.draw_app.transform_complete.emit()
  1083. self.app.inform.emit(_("[success] Done. Rotate completed."))
  1084. self.app.progress.emit(100)
  1085. except Exception as e:
  1086. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  1087. return
  1088. def on_flip(self, axis):
  1089. shape_list = self.draw_app.selected
  1090. xminlist = []
  1091. yminlist = []
  1092. xmaxlist = []
  1093. ymaxlist = []
  1094. if not shape_list:
  1095. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  1096. return
  1097. else:
  1098. with self.app.proc_container.new(_("Applying Flip")):
  1099. try:
  1100. # get mirroring coords from the point entry
  1101. if self.flip_ref_cb.isChecked():
  1102. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1103. # get mirroing coords from the center of an all-enclosing bounding box
  1104. else:
  1105. # first get a bounding box to fit all
  1106. for sha in shape_list:
  1107. xmin, ymin, xmax, ymax = sha.bounds()
  1108. xminlist.append(xmin)
  1109. yminlist.append(ymin)
  1110. xmaxlist.append(xmax)
  1111. ymaxlist.append(ymax)
  1112. # get the minimum x,y and maximum x,y for all objects selected
  1113. xminimal = min(xminlist)
  1114. yminimal = min(yminlist)
  1115. xmaximal = max(xmaxlist)
  1116. ymaximal = max(ymaxlist)
  1117. px = 0.5 * (xminimal + xmaximal)
  1118. py = 0.5 * (yminimal + ymaximal)
  1119. self.app.progress.emit(20)
  1120. # execute mirroring
  1121. for sha in shape_list:
  1122. if axis is 'X':
  1123. sha.mirror('X', (px, py))
  1124. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  1125. elif axis is 'Y':
  1126. sha.mirror('Y', (px, py))
  1127. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  1128. self.draw_app.replot()
  1129. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1130. #
  1131. # self.draw_app.transform_complete.emit()
  1132. self.app.progress.emit(100)
  1133. except Exception as e:
  1134. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  1135. return
  1136. def on_skew(self, axis, num):
  1137. shape_list = self.draw_app.selected
  1138. xminlist = []
  1139. yminlist = []
  1140. if not shape_list:
  1141. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  1142. return
  1143. else:
  1144. with self.app.proc_container.new(_("Applying Skew")):
  1145. try:
  1146. # first get a bounding box to fit all
  1147. for sha in shape_list:
  1148. xmin, ymin, xmax, ymax = sha.bounds()
  1149. xminlist.append(xmin)
  1150. yminlist.append(ymin)
  1151. # get the minimum x,y and maximum x,y for all objects selected
  1152. xminimal = min(xminlist)
  1153. yminimal = min(yminlist)
  1154. self.app.progress.emit(20)
  1155. for sha in shape_list:
  1156. if axis is 'X':
  1157. sha.skew(num, 0, point=(xminimal, yminimal))
  1158. elif axis is 'Y':
  1159. sha.skew(0, num, point=(xminimal, yminimal))
  1160. self.draw_app.replot()
  1161. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1162. #
  1163. # self.draw_app.transform_complete.emit()
  1164. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  1165. self.app.progress.emit(100)
  1166. except Exception as e:
  1167. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  1168. return
  1169. def on_scale(self, axis, xfactor, yfactor, point=None):
  1170. shape_list = self.draw_app.selected
  1171. xminlist = []
  1172. yminlist = []
  1173. xmaxlist = []
  1174. ymaxlist = []
  1175. if not shape_list:
  1176. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  1177. return
  1178. else:
  1179. with self.app.proc_container.new(_("Applying Scale")):
  1180. try:
  1181. # first get a bounding box to fit all
  1182. for sha in shape_list:
  1183. xmin, ymin, xmax, ymax = sha.bounds()
  1184. xminlist.append(xmin)
  1185. yminlist.append(ymin)
  1186. xmaxlist.append(xmax)
  1187. ymaxlist.append(ymax)
  1188. # get the minimum x,y and maximum x,y for all objects selected
  1189. xminimal = min(xminlist)
  1190. yminimal = min(yminlist)
  1191. xmaximal = max(xmaxlist)
  1192. ymaximal = max(ymaxlist)
  1193. self.app.progress.emit(20)
  1194. if point is None:
  1195. px = 0.5 * (xminimal + xmaximal)
  1196. py = 0.5 * (yminimal + ymaximal)
  1197. else:
  1198. px = 0
  1199. py = 0
  1200. for sha in shape_list:
  1201. sha.scale(xfactor, yfactor, point=(px, py))
  1202. self.draw_app.replot()
  1203. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1204. #
  1205. # self.draw_app.transform_complete.emit()
  1206. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  1207. self.app.progress.emit(100)
  1208. except Exception as e:
  1209. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  1210. return
  1211. def on_offset(self, axis, num):
  1212. shape_list = self.draw_app.selected
  1213. xminlist = []
  1214. yminlist = []
  1215. if not shape_list:
  1216. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  1217. return
  1218. else:
  1219. with self.app.proc_container.new(_("Applying Offset")):
  1220. try:
  1221. # first get a bounding box to fit all
  1222. for sha in shape_list:
  1223. xmin, ymin, xmax, ymax = sha.bounds()
  1224. xminlist.append(xmin)
  1225. yminlist.append(ymin)
  1226. # get the minimum x,y and maximum x,y for all objects selected
  1227. xminimal = min(xminlist)
  1228. yminimal = min(yminlist)
  1229. self.app.progress.emit(20)
  1230. for sha in shape_list:
  1231. if axis is 'X':
  1232. sha.offset((num, 0))
  1233. elif axis is 'Y':
  1234. sha.offset((0, num))
  1235. self.draw_app.replot()
  1236. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1237. #
  1238. # self.draw_app.transform_complete.emit()
  1239. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  1240. self.app.progress.emit(100)
  1241. except Exception as e:
  1242. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  1243. return
  1244. def on_rotate_key(self):
  1245. val_box = FCInputDialog(title=_("Rotate ..."),
  1246. text=_('Enter an Angle Value (degrees):'),
  1247. min=-359.9999, max=360.0000, decimals=4,
  1248. init_val=float(self.app.defaults['tools_transform_rotate']))
  1249. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  1250. val, ok = val_box.get_value()
  1251. if ok:
  1252. self.on_rotate(val=val)
  1253. self.app.inform.emit(
  1254. _("[success] Geometry shape rotate done...")
  1255. )
  1256. return
  1257. else:
  1258. self.app.inform.emit(
  1259. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  1260. )
  1261. def on_offx_key(self):
  1262. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1263. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1264. text=(_('Enter a distance Value (%s):') % str(units)),
  1265. min=-9999.9999, max=10000.0000, decimals=4,
  1266. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1267. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  1268. val, ok = val_box.get_value()
  1269. if ok:
  1270. self.on_offx(val=val)
  1271. self.app.inform.emit(
  1272. _("[success] Geometry shape offset on X axis done..."))
  1273. return
  1274. else:
  1275. self.app.inform.emit(
  1276. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  1277. def on_offy_key(self):
  1278. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1279. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1280. text=(_('Enter a distance Value (%s):') % str(units)),
  1281. min=-9999.9999, max=10000.0000, decimals=4,
  1282. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1283. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  1284. val, ok = val_box.get_value()
  1285. if ok:
  1286. self.on_offx(val=val)
  1287. self.app.inform.emit(
  1288. _("[success] Geometry shape offset on Y axis done..."))
  1289. return
  1290. else:
  1291. self.app.inform.emit(
  1292. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  1293. def on_skewx_key(self):
  1294. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1295. text=_('Enter an Angle Value (degrees):'),
  1296. min=-359.9999, max=360.0000, decimals=4,
  1297. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1298. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  1299. val, ok = val_box.get_value()
  1300. if ok:
  1301. self.on_skewx(val=val)
  1302. self.app.inform.emit(
  1303. _("[success] Geometry shape skew on X axis done..."))
  1304. return
  1305. else:
  1306. self.app.inform.emit(
  1307. _( "[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  1308. def on_skewy_key(self):
  1309. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1310. text=_('Enter an Angle Value (degrees):'),
  1311. min=-359.9999, max=360.0000, decimals=4,
  1312. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1313. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  1314. val, ok = val_box.get_value()
  1315. if ok:
  1316. self.on_skewx(val=val)
  1317. self.app.inform.emit(
  1318. _( "[success] Geometry shape skew on Y axis done..."))
  1319. return
  1320. else:
  1321. self.app.inform.emit(
  1322. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))
  1323. class DrawToolShape(object):
  1324. """
  1325. Encapsulates "shapes" under a common class.
  1326. """
  1327. tolerance = None
  1328. @staticmethod
  1329. def get_pts(o):
  1330. """
  1331. Returns a list of all points in the object, where
  1332. the object can be a Polygon, Not a polygon, or a list
  1333. of such. Search is done recursively.
  1334. :param: geometric object
  1335. :return: List of points
  1336. :rtype: list
  1337. """
  1338. pts = []
  1339. ## Iterable: descend into each item.
  1340. try:
  1341. for subo in o:
  1342. pts += DrawToolShape.get_pts(subo)
  1343. ## Non-iterable
  1344. except TypeError:
  1345. if o is not None:
  1346. ## DrawToolShape: descend into .geo.
  1347. if isinstance(o, DrawToolShape):
  1348. pts += DrawToolShape.get_pts(o.geo)
  1349. ## Descend into .exerior and .interiors
  1350. elif type(o) == Polygon:
  1351. pts += DrawToolShape.get_pts(o.exterior)
  1352. for i in o.interiors:
  1353. pts += DrawToolShape.get_pts(i)
  1354. elif type(o) == MultiLineString:
  1355. for line in o:
  1356. pts += DrawToolShape.get_pts(line)
  1357. ## Has .coords: list them.
  1358. else:
  1359. if DrawToolShape.tolerance is not None:
  1360. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1361. else:
  1362. pts += list(o.coords)
  1363. else:
  1364. return
  1365. return pts
  1366. def __init__(self, geo=[]):
  1367. # Shapely type or list of such
  1368. self.geo = geo
  1369. self.utility = False
  1370. def get_all_points(self):
  1371. return DrawToolShape.get_pts(self)
  1372. def bounds(self):
  1373. """
  1374. Returns coordinates of rectangular bounds
  1375. of geometry: (xmin, ymin, xmax, ymax).
  1376. """
  1377. # fixed issue of getting bounds only for one level lists of objects
  1378. # now it can get bounds for nested lists of objects
  1379. def bounds_rec(shape):
  1380. if type(shape) is list:
  1381. minx = Inf
  1382. miny = Inf
  1383. maxx = -Inf
  1384. maxy = -Inf
  1385. for k in shape:
  1386. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1387. minx = min(minx, minx_)
  1388. miny = min(miny, miny_)
  1389. maxx = max(maxx, maxx_)
  1390. maxy = max(maxy, maxy_)
  1391. return minx, miny, maxx, maxy
  1392. else:
  1393. # it's a Shapely object, return it's bounds
  1394. return shape.bounds
  1395. bounds_coords = bounds_rec(self.geo)
  1396. return bounds_coords
  1397. def mirror(self, axis, point):
  1398. """
  1399. Mirrors the shape around a specified axis passing through
  1400. the given point.
  1401. :param axis: "X" or "Y" indicates around which axis to mirror.
  1402. :type axis: str
  1403. :param point: [x, y] point belonging to the mirror axis.
  1404. :type point: list
  1405. :return: None
  1406. """
  1407. px, py = point
  1408. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1409. def mirror_geom(shape):
  1410. if type(shape) is list:
  1411. new_obj = []
  1412. for g in shape:
  1413. new_obj.append(mirror_geom(g))
  1414. return new_obj
  1415. else:
  1416. return affinity.scale(shape, xscale, yscale, origin=(px,py))
  1417. try:
  1418. self.geo = mirror_geom(self.geo)
  1419. except AttributeError:
  1420. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1421. def rotate(self, angle, point):
  1422. """
  1423. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1424. Parameters
  1425. ----------
  1426. The angle of rotation are specified in degrees (default). Positive angles are
  1427. counter-clockwise and negative are clockwise rotations.
  1428. The point of origin can be a keyword 'center' for the bounding box
  1429. center (default), 'centroid' for the geometry's centroid, a Point object
  1430. or a coordinate tuple (x0, y0).
  1431. See shapely manual for more information:
  1432. http://toblerity.org/shapely/manual.html#affine-transformations
  1433. """
  1434. px, py = point
  1435. def rotate_geom(shape):
  1436. if type(shape) is list:
  1437. new_obj = []
  1438. for g in shape:
  1439. new_obj.append(rotate_geom(g))
  1440. return new_obj
  1441. else:
  1442. return affinity.rotate(shape, angle, origin=(px, py))
  1443. try:
  1444. self.geo = rotate_geom(self.geo)
  1445. except AttributeError:
  1446. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1447. def skew(self, angle_x, angle_y, point):
  1448. """
  1449. Shear/Skew a shape by angles along x and y dimensions.
  1450. Parameters
  1451. ----------
  1452. angle_x, angle_y : float, float
  1453. The shear angle(s) for the x and y axes respectively. These can be
  1454. specified in either degrees (default) or radians by setting
  1455. use_radians=True.
  1456. point: tuple of coordinates (x,y)
  1457. See shapely manual for more information:
  1458. http://toblerity.org/shapely/manual.html#affine-transformations
  1459. """
  1460. px, py = point
  1461. def skew_geom(shape):
  1462. if type(shape) is list:
  1463. new_obj = []
  1464. for g in shape:
  1465. new_obj.append(skew_geom(g))
  1466. return new_obj
  1467. else:
  1468. return affinity.skew(shape, angle_x, angle_y, origin=(px, py))
  1469. try:
  1470. self.geo = skew_geom(self.geo)
  1471. except AttributeError:
  1472. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1473. def offset(self, vect):
  1474. """
  1475. Offsets all shapes by a given vector/
  1476. :param vect: (x, y) vector by which to offset the shape geometry
  1477. :type vect: tuple
  1478. :return: None
  1479. :rtype: None
  1480. """
  1481. try:
  1482. dx, dy = vect
  1483. except TypeError:
  1484. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1485. "Probable you entered only one value in the Offset field.")
  1486. return
  1487. def translate_recursion(geom):
  1488. if type(geom) == list:
  1489. geoms=list()
  1490. for local_geom in geom:
  1491. geoms.append(translate_recursion(local_geom))
  1492. return geoms
  1493. else:
  1494. return affinity.translate(geom, xoff=dx, yoff=dy)
  1495. try:
  1496. self.geo = translate_recursion(self.geo)
  1497. except AttributeError:
  1498. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1499. def scale(self, xfactor, yfactor=None, point=None):
  1500. """
  1501. Scales all shape geometry by a given factor.
  1502. :param xfactor: Factor by which to scale the shape's geometry/
  1503. :type xfactor: float
  1504. :param yfactor: Factor by which to scale the shape's geometry/
  1505. :type yfactor: float
  1506. :return: None
  1507. :rtype: None
  1508. """
  1509. try:
  1510. xfactor = float(xfactor)
  1511. except:
  1512. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1513. return
  1514. if yfactor is None:
  1515. yfactor = xfactor
  1516. else:
  1517. try:
  1518. yfactor = float(yfactor)
  1519. except:
  1520. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1521. return
  1522. if point is None:
  1523. px = 0
  1524. py = 0
  1525. else:
  1526. px, py = point
  1527. def scale_recursion(geom):
  1528. if type(geom) == list:
  1529. geoms=list()
  1530. for local_geom in geom:
  1531. geoms.append(scale_recursion(local_geom))
  1532. return geoms
  1533. else:
  1534. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1535. try:
  1536. self.geo = scale_recursion(self.geo)
  1537. except AttributeError:
  1538. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1539. class DrawToolUtilityShape(DrawToolShape):
  1540. """
  1541. Utility shapes are temporary geometry in the editor
  1542. to assist in the creation of shapes. For example it
  1543. will show the outline of a rectangle from the first
  1544. point to the current mouse pointer before the second
  1545. point is clicked and the final geometry is created.
  1546. """
  1547. def __init__(self, geo=[]):
  1548. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1549. self.utility = True
  1550. class DrawTool(object):
  1551. """
  1552. Abstract Class representing a tool in the drawing
  1553. program. Can generate geometry, including temporary
  1554. utility geometry that is updated on user clicks
  1555. and mouse motion.
  1556. """
  1557. def __init__(self, draw_app):
  1558. self.draw_app = draw_app
  1559. self.complete = False
  1560. self.start_msg = "Click on 1st point..."
  1561. self.points = []
  1562. self.geometry = None # DrawToolShape or None
  1563. def click(self, point):
  1564. """
  1565. :param point: [x, y] Coordinate pair.
  1566. """
  1567. return ""
  1568. def click_release(self, point):
  1569. """
  1570. :param point: [x, y] Coordinate pair.
  1571. """
  1572. return ""
  1573. def on_key(self, key):
  1574. return None
  1575. def utility_geometry(self, data=None):
  1576. return None
  1577. def bounds(self, obj):
  1578. def bounds_rec(o):
  1579. if type(o) is list:
  1580. minx = Inf
  1581. miny = Inf
  1582. maxx = -Inf
  1583. maxy = -Inf
  1584. for k in o:
  1585. try:
  1586. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1587. except Exception as e:
  1588. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1589. return
  1590. minx = min(minx, minx_)
  1591. miny = min(miny, miny_)
  1592. maxx = max(maxx, maxx_)
  1593. maxy = max(maxy, maxy_)
  1594. return minx, miny, maxx, maxy
  1595. else:
  1596. # it's a Shapely object, return it's bounds
  1597. return o.geo.bounds
  1598. bounds_coords = bounds_rec(obj)
  1599. return bounds_coords
  1600. class FCShapeTool(DrawTool):
  1601. """
  1602. Abstract class for tools that create a shape.
  1603. """
  1604. def __init__(self, draw_app):
  1605. DrawTool.__init__(self, draw_app)
  1606. def make(self):
  1607. pass
  1608. class FCCircle(FCShapeTool):
  1609. """
  1610. Resulting type: Polygon
  1611. """
  1612. def __init__(self, draw_app):
  1613. DrawTool.__init__(self, draw_app)
  1614. self.name = 'circle'
  1615. try:
  1616. QtGui.QGuiApplication.restoreOverrideCursor()
  1617. except:
  1618. pass
  1619. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_circle.png'))
  1620. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1621. self.start_msg = _("Click on Center point ...")
  1622. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1623. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1624. def click(self, point):
  1625. self.points.append(point)
  1626. if len(self.points) == 1:
  1627. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  1628. return "Click on perimeter to complete ..."
  1629. if len(self.points) == 2:
  1630. self.make()
  1631. return "Done."
  1632. return ""
  1633. def utility_geometry(self, data=None):
  1634. if len(self.points) == 1:
  1635. p1 = self.points[0]
  1636. p2 = data
  1637. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1638. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1639. return None
  1640. def make(self):
  1641. try:
  1642. QtGui.QGuiApplication.restoreOverrideCursor()
  1643. except:
  1644. pass
  1645. p1 = self.points[0]
  1646. p2 = self.points[1]
  1647. radius = distance(p1, p2)
  1648. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1649. self.complete = True
  1650. self.draw_app.app.inform.emit(_("[success] Done. Adding Circle completed."))
  1651. class FCArc(FCShapeTool):
  1652. def __init__(self, draw_app):
  1653. DrawTool.__init__(self, draw_app)
  1654. self.name = 'arc'
  1655. self.start_msg = _("Click on Center point ...")
  1656. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1657. # Direction of rotation between point 1 and 2.
  1658. # 'cw' or 'ccw'. Switch direction by hitting the
  1659. # 'o' key.
  1660. self.direction = "cw"
  1661. # Mode
  1662. # C12 = Center, p1, p2
  1663. # 12C = p1, p2, Center
  1664. # 132 = p1, p3, p2
  1665. self.mode = "c12" # Center, p1, p2
  1666. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1667. def click(self, point):
  1668. self.points.append(point)
  1669. if len(self.points) == 1:
  1670. if self.mode == 'c12':
  1671. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1672. elif self.mode == '132':
  1673. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1674. else:
  1675. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  1676. return "Click on 1st point ..."
  1677. if len(self.points) == 2:
  1678. if self.mode == 'c12':
  1679. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1680. elif self.mode == '132':
  1681. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  1682. else:
  1683. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1684. return "Click on 2nd point to complete ..."
  1685. if len(self.points) == 3:
  1686. self.make()
  1687. return "Done."
  1688. return ""
  1689. def on_key(self, key):
  1690. if key == 'D' or key == QtCore.Qt.Key_D:
  1691. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1692. return _('Direction: %s') % self.direction.upper()
  1693. if key == 'M' or key == QtCore.Qt.Key_M:
  1694. # delete the possible points made before this action; we want to start anew
  1695. self.points[:] = []
  1696. # and delete the utility geometry made up until this point
  1697. self.draw_app.delete_utility_geometry()
  1698. if self.mode == 'c12':
  1699. self.mode = '12c'
  1700. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1701. elif self.mode == '12c':
  1702. self.mode = '132'
  1703. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1704. else:
  1705. self.mode = 'c12'
  1706. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1707. def utility_geometry(self, data=None):
  1708. if len(self.points) == 1: # Show the radius
  1709. center = self.points[0]
  1710. p1 = data
  1711. return DrawToolUtilityShape(LineString([center, p1]))
  1712. if len(self.points) == 2: # Show the arc
  1713. if self.mode == 'c12':
  1714. center = self.points[0]
  1715. p1 = self.points[1]
  1716. p2 = data
  1717. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1718. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1719. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1720. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1721. self.direction, self.steps_per_circ)),
  1722. Point(center)])
  1723. elif self.mode == '132':
  1724. p1 = array(self.points[0])
  1725. p3 = array(self.points[1])
  1726. p2 = array(data)
  1727. try:
  1728. center, radius, t = three_point_circle(p1, p2, p3)
  1729. except TypeError:
  1730. return
  1731. direction = 'cw' if sign(t) > 0 else 'ccw'
  1732. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1733. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1734. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1735. direction, self.steps_per_circ)),
  1736. Point(center), Point(p1), Point(p3)])
  1737. else: # '12c'
  1738. p1 = array(self.points[0])
  1739. p2 = array(self.points[1])
  1740. # Midpoint
  1741. a = (p1 + p2) / 2.0
  1742. # Parallel vector
  1743. c = p2 - p1
  1744. # Perpendicular vector
  1745. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1746. b /= numpy_norm(b)
  1747. # Distance
  1748. t = distance(data, a)
  1749. # Which side? Cross product with c.
  1750. # cross(M-A, B-A), where line is AB and M is test point.
  1751. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1752. t *= sign(side)
  1753. # Center = a + bt
  1754. center = a + b * t
  1755. radius = numpy_norm(center - p1)
  1756. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1757. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1758. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1759. self.direction, self.steps_per_circ)),
  1760. Point(center)])
  1761. return None
  1762. def make(self):
  1763. if self.mode == 'c12':
  1764. center = self.points[0]
  1765. p1 = self.points[1]
  1766. p2 = self.points[2]
  1767. radius = distance(center, p1)
  1768. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1769. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1770. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1771. self.direction, self.steps_per_circ)))
  1772. elif self.mode == '132':
  1773. p1 = array(self.points[0])
  1774. p3 = array(self.points[1])
  1775. p2 = array(self.points[2])
  1776. center, radius, t = three_point_circle(p1, p2, p3)
  1777. direction = 'cw' if sign(t) > 0 else 'ccw'
  1778. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1779. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1780. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1781. direction, self.steps_per_circ)))
  1782. else: # self.mode == '12c'
  1783. p1 = array(self.points[0])
  1784. p2 = array(self.points[1])
  1785. pc = array(self.points[2])
  1786. # Midpoint
  1787. a = (p1 + p2) / 2.0
  1788. # Parallel vector
  1789. c = p2 - p1
  1790. # Perpendicular vector
  1791. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1792. b /= numpy_norm(b)
  1793. # Distance
  1794. t = distance(pc, a)
  1795. # Which side? Cross product with c.
  1796. # cross(M-A, B-A), where line is AB and M is test point.
  1797. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1798. t *= sign(side)
  1799. # Center = a + bt
  1800. center = a + b * t
  1801. radius = numpy_norm(center - p1)
  1802. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1803. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1804. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1805. self.direction, self.steps_per_circ)))
  1806. self.complete = True
  1807. self.draw_app.app.inform.emit(_("[success] Done. Arc completed."))
  1808. class FCRectangle(FCShapeTool):
  1809. """
  1810. Resulting type: Polygon
  1811. """
  1812. def __init__(self, draw_app):
  1813. DrawTool.__init__(self, draw_app)
  1814. self.name = 'rectangle'
  1815. try:
  1816. QtGui.QGuiApplication.restoreOverrideCursor()
  1817. except:
  1818. pass
  1819. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  1820. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1821. self.start_msg = _("Click on 1st corner ...")
  1822. def click(self, point):
  1823. self.points.append(point)
  1824. if len(self.points) == 1:
  1825. return "Click on opposite corner to complete ..."
  1826. if len(self.points) == 2:
  1827. self.make()
  1828. return "Done."
  1829. return ""
  1830. def utility_geometry(self, data=None):
  1831. if len(self.points) == 1:
  1832. p1 = self.points[0]
  1833. p2 = data
  1834. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1835. return None
  1836. def make(self):
  1837. try:
  1838. QtGui.QGuiApplication.restoreOverrideCursor()
  1839. except:
  1840. pass
  1841. p1 = self.points[0]
  1842. p2 = self.points[1]
  1843. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1844. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1845. self.complete = True
  1846. self.draw_app.app.inform.emit(_("[success] Done. Rectangle completed."))
  1847. class FCPolygon(FCShapeTool):
  1848. """
  1849. Resulting type: Polygon
  1850. """
  1851. def __init__(self, draw_app):
  1852. DrawTool.__init__(self, draw_app)
  1853. self.name = 'polygon'
  1854. try:
  1855. QtGui.QGuiApplication.restoreOverrideCursor()
  1856. except:
  1857. pass
  1858. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero.png'))
  1859. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1860. self.start_msg = _("Click on 1st point ...")
  1861. def click(self, point):
  1862. self.draw_app.in_action = True
  1863. self.points.append(point)
  1864. if len(self.points) > 0:
  1865. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  1866. return "Click on next point or hit ENTER to complete ..."
  1867. return ""
  1868. def utility_geometry(self, data=None):
  1869. if len(self.points) == 1:
  1870. temp_points = [x for x in self.points]
  1871. temp_points.append(data)
  1872. return DrawToolUtilityShape(LineString(temp_points))
  1873. if len(self.points) > 1:
  1874. temp_points = [x for x in self.points]
  1875. temp_points.append(data)
  1876. return DrawToolUtilityShape(LinearRing(temp_points))
  1877. return None
  1878. def make(self):
  1879. try:
  1880. QtGui.QGuiApplication.restoreOverrideCursor()
  1881. except:
  1882. pass
  1883. # self.geometry = LinearRing(self.points)
  1884. self.geometry = DrawToolShape(Polygon(self.points))
  1885. self.draw_app.in_action = False
  1886. self.complete = True
  1887. self.draw_app.app.inform.emit(_("[success] Done. Polygon completed."))
  1888. def on_key(self, key):
  1889. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1890. if len(self.points) > 0:
  1891. self.points = self.points[0:-1]
  1892. # Remove any previous utility shape
  1893. self.draw_app.tool_shape.clear(update=False)
  1894. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1895. self.draw_app.draw_utility_geometry(geo=geo)
  1896. return _("Backtracked one point ...")
  1897. class FCPath(FCPolygon):
  1898. """
  1899. Resulting type: LineString
  1900. """
  1901. def __init__(self, draw_app):
  1902. FCPolygon.__init__(self, draw_app)
  1903. try:
  1904. QtGui.QGuiApplication.restoreOverrideCursor()
  1905. except:
  1906. pass
  1907. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_path.png'))
  1908. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1909. def make(self):
  1910. self.geometry = DrawToolShape(LineString(self.points))
  1911. self.name = 'path'
  1912. try:
  1913. QtGui.QGuiApplication.restoreOverrideCursor()
  1914. except:
  1915. pass
  1916. self.draw_app.in_action = False
  1917. self.complete = True
  1918. self.draw_app.app.inform.emit(_("[success] Done. Path completed."))
  1919. def utility_geometry(self, data=None):
  1920. if len(self.points) > 0:
  1921. temp_points = [x for x in self.points]
  1922. temp_points.append(data)
  1923. return DrawToolUtilityShape(LineString(temp_points))
  1924. return None
  1925. def on_key(self, key):
  1926. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1927. if len(self.points) > 0:
  1928. self.points = self.points[0:-1]
  1929. # Remove any previous utility shape
  1930. self.draw_app.tool_shape.clear(update=False)
  1931. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1932. self.draw_app.draw_utility_geometry(geo=geo)
  1933. return _("Backtracked one point ...")
  1934. class FCSelect(DrawTool):
  1935. def __init__(self, draw_app):
  1936. DrawTool.__init__(self, draw_app)
  1937. self.name = 'select'
  1938. try:
  1939. QtGui.QGuiApplication.restoreOverrideCursor()
  1940. except:
  1941. pass
  1942. self.storage = self.draw_app.storage
  1943. # self.shape_buffer = self.draw_app.shape_buffer
  1944. # self.selected = self.draw_app.selected
  1945. def click_release(self, point):
  1946. self.select_shapes(point)
  1947. return ""
  1948. def select_shapes(self, pos):
  1949. # list where we store the overlapped shapes under our mouse left click position
  1950. over_shape_list = []
  1951. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1952. for obj_shape in self.storage.get_objects():
  1953. # first method of click selection -> inconvenient
  1954. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1955. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1956. # over_shape_list.append(obj_shape)
  1957. # second method of click selection -> slow
  1958. # outside = obj_shape.geo.buffer(0.1)
  1959. # inside = obj_shape.geo.buffer(-0.1)
  1960. # shape_band = outside.difference(inside)
  1961. # if Point(pos).within(shape_band):
  1962. # over_shape_list.append(obj_shape)
  1963. # 3rd method of click selection -> inconvenient
  1964. try:
  1965. _, closest_shape = self.storage.nearest(pos)
  1966. except StopIteration:
  1967. return ""
  1968. over_shape_list.append(closest_shape)
  1969. try:
  1970. # if there is no shape under our click then deselect all shapes
  1971. # it will not work for 3rd method of click selection
  1972. if not over_shape_list:
  1973. self.draw_app.selected = []
  1974. FlatCAMGeoEditor.draw_shape_idx = -1
  1975. else:
  1976. # if there are shapes under our click then advance through the list of them, one at the time in a
  1977. # circular way
  1978. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1979. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1980. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1981. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  1982. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1983. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1984. if key_modifier == Qt.ControlModifier:
  1985. if obj_to_add in self.draw_app.selected:
  1986. self.draw_app.selected.remove(obj_to_add)
  1987. else:
  1988. self.draw_app.selected.append(obj_to_add)
  1989. else:
  1990. self.draw_app.selected = []
  1991. self.draw_app.selected.append(obj_to_add)
  1992. else:
  1993. if key_modifier == Qt.ShiftModifier:
  1994. if obj_to_add in self.draw_app.selected:
  1995. self.draw_app.selected.remove(obj_to_add)
  1996. else:
  1997. self.draw_app.selected.append(obj_to_add)
  1998. else:
  1999. self.draw_app.selected = []
  2000. self.draw_app.selected.append(obj_to_add)
  2001. except Exception as e:
  2002. log.error("[ERROR] Something went bad. %s" % str(e))
  2003. raise
  2004. class FCMove(FCShapeTool):
  2005. def __init__(self, draw_app):
  2006. FCShapeTool.__init__(self, draw_app)
  2007. self.name = 'move'
  2008. # self.shape_buffer = self.draw_app.shape_buffer
  2009. if not self.draw_app.selected:
  2010. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2011. return
  2012. self.origin = None
  2013. self.destination = None
  2014. self.start_msg = _("Click on reference point.")
  2015. def set_origin(self, origin):
  2016. self.draw_app.app.inform.emit(_("Click on destination point."))
  2017. self.origin = origin
  2018. def click(self, point):
  2019. if len(self.draw_app.get_selected()) == 0:
  2020. return "Nothing to move."
  2021. if self.origin is None:
  2022. self.set_origin(point)
  2023. return "Click on final location."
  2024. else:
  2025. self.destination = point
  2026. self.make()
  2027. return "Done."
  2028. def make(self):
  2029. # Create new geometry
  2030. dx = self.destination[0] - self.origin[0]
  2031. dy = self.destination[1] - self.origin[1]
  2032. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2033. for geom in self.draw_app.get_selected()]
  2034. # Delete old
  2035. self.draw_app.delete_selected()
  2036. # # Select the new
  2037. # for g in self.geometry:
  2038. # # Note that g is not in the app's buffer yet!
  2039. # self.draw_app.set_selected(g)
  2040. self.complete = True
  2041. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Move completed."))
  2042. def utility_geometry(self, data=None):
  2043. """
  2044. Temporary geometry on screen while using this tool.
  2045. :param data:
  2046. :return:
  2047. """
  2048. geo_list = []
  2049. if self.origin is None:
  2050. return None
  2051. if len(self.draw_app.get_selected()) == 0:
  2052. return None
  2053. dx = data[0] - self.origin[0]
  2054. dy = data[1] - self.origin[1]
  2055. try:
  2056. for geom in self.draw_app.get_selected():
  2057. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2058. except AttributeError:
  2059. self.draw_app.select_tool('select')
  2060. self.draw_app.selected = []
  2061. return
  2062. return DrawToolUtilityShape(geo_list)
  2063. # return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  2064. # for geom in self.draw_app.get_selected()])
  2065. class FCCopy(FCMove):
  2066. def __init__(self, draw_app):
  2067. FCMove.__init__(self, draw_app)
  2068. self.name = 'copy'
  2069. def make(self):
  2070. # Create new geometry
  2071. dx = self.destination[0] - self.origin[0]
  2072. dy = self.destination[1] - self.origin[1]
  2073. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2074. for geom in self.draw_app.get_selected()]
  2075. self.complete = True
  2076. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Copy completed."))
  2077. class FCText(FCShapeTool):
  2078. def __init__(self, draw_app):
  2079. FCShapeTool.__init__(self, draw_app)
  2080. self.name = 'text'
  2081. # self.shape_buffer = self.draw_app.shape_buffer
  2082. self.draw_app = draw_app
  2083. self.app = draw_app.app
  2084. self.start_msg = _("Click on the Destination point...")
  2085. self.origin = (0, 0)
  2086. self.text_gui = TextInputTool(self.app)
  2087. self.text_gui.run()
  2088. def click(self, point):
  2089. # Create new geometry
  2090. dx = point[0]
  2091. dy = point[1]
  2092. try:
  2093. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2094. except Exception as e:
  2095. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2096. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2097. "supported. Error: %s") % str(e))
  2098. self.text_gui.text_path = []
  2099. self.text_gui.hide_tool()
  2100. self.draw_app.select_tool('select')
  2101. return
  2102. self.text_gui.text_path = []
  2103. self.text_gui.hide_tool()
  2104. self.complete = True
  2105. self.draw_app.app.inform.emit(_("[success] Done. Adding Text completed."))
  2106. def utility_geometry(self, data=None):
  2107. """
  2108. Temporary geometry on screen while using this tool.
  2109. :param data: mouse position coords
  2110. :return:
  2111. """
  2112. dx = data[0] - self.origin[0]
  2113. dy = data[1] - self.origin[1]
  2114. try:
  2115. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2116. except:
  2117. return
  2118. class FCBuffer(FCShapeTool):
  2119. def __init__(self, draw_app):
  2120. FCShapeTool.__init__(self, draw_app)
  2121. self.name = 'buffer'
  2122. # self.shape_buffer = self.draw_app.shape_buffer
  2123. self.draw_app = draw_app
  2124. self.app = draw_app.app
  2125. self.start_msg = _("Create buffer geometry ...")
  2126. self.origin = (0, 0)
  2127. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2128. self.buff_tool.run()
  2129. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2130. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2131. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2132. self.activate()
  2133. def on_buffer(self):
  2134. if not self.draw_app.selected:
  2135. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2136. return
  2137. try:
  2138. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2139. except ValueError:
  2140. # try to convert comma to decimal point. if it's still not working error message and return
  2141. try:
  2142. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2143. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2144. except ValueError:
  2145. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2146. "Add it and retry."))
  2147. return
  2148. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2149. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2150. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2151. self.draw_app.buffer(buffer_distance, join_style)
  2152. self.app.ui.notebook.setTabText(2, _("Tools"))
  2153. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2154. self.disactivate()
  2155. self.draw_app.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  2156. def on_buffer_int(self):
  2157. if not self.draw_app.selected:
  2158. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2159. return
  2160. try:
  2161. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2162. except ValueError:
  2163. # try to convert comma to decimal point. if it's still not working error message and return
  2164. try:
  2165. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2166. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2167. except ValueError:
  2168. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2169. "Add it and retry."))
  2170. return
  2171. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2172. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2173. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2174. self.draw_app.buffer_int(buffer_distance, join_style)
  2175. self.app.ui.notebook.setTabText(2, _("Tools"))
  2176. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2177. self.disactivate()
  2178. self.draw_app.app.inform.emit(_("[success] Done. Buffer Int Tool completed."))
  2179. def on_buffer_ext(self):
  2180. if not self.draw_app.selected:
  2181. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2182. return
  2183. try:
  2184. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2185. except ValueError:
  2186. # try to convert comma to decimal point. if it's still not working error message and return
  2187. try:
  2188. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2189. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2190. except ValueError:
  2191. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2192. "Add it and retry."))
  2193. return
  2194. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2195. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2196. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2197. self.draw_app.buffer_ext(buffer_distance, join_style)
  2198. self.app.ui.notebook.setTabText(2, _("Tools"))
  2199. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2200. self.disactivate()
  2201. self.draw_app.app.inform.emit(_("[success] Done. Buffer Ext Tool completed."))
  2202. def activate(self):
  2203. self.buff_tool.buffer_button.clicked.disconnect()
  2204. self.buff_tool.buffer_int_button.clicked.disconnect()
  2205. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2206. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2207. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2208. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2209. def disactivate(self):
  2210. self.buff_tool.buffer_button.clicked.disconnect()
  2211. self.buff_tool.buffer_int_button.clicked.disconnect()
  2212. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2213. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2214. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2215. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2216. self.complete = True
  2217. self.draw_app.select_tool("select")
  2218. self.buff_tool.hide_tool()
  2219. class FCPaint(FCShapeTool):
  2220. def __init__(self, draw_app):
  2221. FCShapeTool.__init__(self, draw_app)
  2222. self.name = 'paint'
  2223. # self.shape_buffer = self.draw_app.shape_buffer
  2224. self.draw_app = draw_app
  2225. self.app = draw_app.app
  2226. self.start_msg = _("Create Paint geometry ...")
  2227. self.origin = (0, 0)
  2228. self.draw_app.paint_tool.run()
  2229. class FCTransform(FCShapeTool):
  2230. def __init__(self, draw_app):
  2231. FCShapeTool.__init__(self, draw_app)
  2232. self.name = 'transformation'
  2233. # self.shape_buffer = self.draw_app.shape_buffer
  2234. self.draw_app = draw_app
  2235. self.app = draw_app.app
  2236. self.start_msg = _("Shape transformations ...")
  2237. self.origin = (0, 0)
  2238. self.draw_app.transform_tool.run()
  2239. ########################
  2240. ### Main Application ###
  2241. ########################
  2242. class FlatCAMGeoEditor(QtCore.QObject):
  2243. transform_complete = QtCore.pyqtSignal()
  2244. draw_shape_idx = -1
  2245. def __init__(self, app, disabled=False):
  2246. assert isinstance(app, FlatCAMApp.App), \
  2247. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2248. super(FlatCAMGeoEditor, self).__init__()
  2249. self.app = app
  2250. self.canvas = app.plotcanvas
  2251. ## Toolbar events and properties
  2252. self.tools = {
  2253. "select": {"button": self.app.ui.geo_select_btn,
  2254. "constructor": FCSelect},
  2255. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2256. "constructor": FCArc},
  2257. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2258. "constructor": FCCircle},
  2259. "path": {"button": self.app.ui.geo_add_path_btn,
  2260. "constructor": FCPath},
  2261. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2262. "constructor": FCRectangle},
  2263. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2264. "constructor": FCPolygon},
  2265. "text": {"button": self.app.ui.geo_add_text_btn,
  2266. "constructor": FCText},
  2267. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2268. "constructor": FCBuffer},
  2269. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2270. "constructor": FCPaint},
  2271. "move": {"button": self.app.ui.geo_move_btn,
  2272. "constructor": FCMove},
  2273. "transform": {"button": self.app.ui.geo_transform_btn,
  2274. "constructor": FCTransform},
  2275. "copy": {"button": self.app.ui.geo_copy_btn,
  2276. "constructor": FCCopy}
  2277. }
  2278. ### Data
  2279. self.active_tool = None
  2280. self.storage = FlatCAMGeoEditor.make_storage()
  2281. self.utility = []
  2282. # VisPy visuals
  2283. self.fcgeometry = None
  2284. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2285. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2286. self.app.pool_recreated.connect(self.pool_recreated)
  2287. # Remove from scene
  2288. self.shapes.enabled = False
  2289. self.tool_shape.enabled = False
  2290. ## List of selected shapes.
  2291. self.selected = []
  2292. self.flat_geo = []
  2293. self.move_timer = QtCore.QTimer()
  2294. self.move_timer.setSingleShot(True)
  2295. # this var will store the state of the toolbar before starting the editor
  2296. self.toolbar_old_state = False
  2297. self.key = None # Currently pressed key
  2298. self.geo_key_modifiers = None
  2299. self.x = None # Current mouse cursor pos
  2300. self.y = None
  2301. # if we edit a multigeo geometry store here the tool number
  2302. self.multigeo_tool = None
  2303. # Current snapped mouse pos
  2304. self.snap_x = None
  2305. self.snap_y = None
  2306. self.pos = None
  2307. # signal that there is an action active like polygon or path
  2308. self.in_action = False
  2309. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2310. self.launched_from_shortcuts = False
  2311. def make_callback(thetool):
  2312. def f():
  2313. self.on_tool_select(thetool)
  2314. return f
  2315. for tool in self.tools:
  2316. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2317. self.tools[tool]["button"].setCheckable(True) # Checkable
  2318. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2319. self.app.ui.corner_snap_btn.setCheckable(True)
  2320. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2321. self.options = {
  2322. "global_gridx": 0.1,
  2323. "global_gridy": 0.1,
  2324. "global_snap_max": 0.05,
  2325. "grid_snap": True,
  2326. "corner_snap": False,
  2327. "grid_gap_link": True
  2328. }
  2329. self.app.options_read_form()
  2330. for option in self.options:
  2331. if option in self.app.options:
  2332. self.options[option] = self.app.options[option]
  2333. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2334. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2335. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2336. self.app.ui.grid_gap_link_cb.setChecked(True)
  2337. self.rtree_index = rtindex.Index()
  2338. def entry2option(option, entry):
  2339. try:
  2340. self.options[option] = float(entry.text())
  2341. except Exception as e:
  2342. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2343. return
  2344. def gridx_changed(goption, gentry):
  2345. entry2option(option=goption, entry=gentry)
  2346. # if the grid link is checked copy the value in the GridX field to GridY
  2347. if self.app.ui.grid_gap_link_cb.isChecked():
  2348. self.app.ui.grid_gap_y_entry.set_value(self.app.ui.grid_gap_x_entry.get_value())
  2349. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2350. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2351. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2352. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2353. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2354. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2355. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2356. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2357. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2358. # if using Paint store here the tool diameter used
  2359. self.paint_tooldia = None
  2360. self.paint_tool = PaintOptionsTool(self.app, self)
  2361. self.transform_tool = TransformEditorTool(self.app, self)
  2362. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2363. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2364. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2365. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2366. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2367. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2368. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2369. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2370. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2371. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2372. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2373. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2374. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2375. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2376. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2377. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2378. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2379. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2380. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2381. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2382. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2383. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2384. self.transform_complete.connect(self.on_transform_complete)
  2385. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2386. self.editor_active = False
  2387. def pool_recreated(self, pool):
  2388. self.shapes.pool = pool
  2389. self.tool_shape.pool = pool
  2390. def on_transform_complete(self):
  2391. self.delete_selected()
  2392. self.replot()
  2393. def activate(self):
  2394. # adjust the status of the menu entries related to the editor
  2395. self.app.ui.menueditedit.setDisabled(True)
  2396. self.app.ui.menueditok.setDisabled(False)
  2397. # adjust the visibility of some of the canvas context menu
  2398. self.app.ui.popmenu_edit.setVisible(False)
  2399. self.app.ui.popmenu_save.setVisible(True)
  2400. self.connect_canvas_event_handlers()
  2401. # initialize working objects
  2402. self.storage = FlatCAMGeoEditor.make_storage()
  2403. self.utility = []
  2404. self.selected = []
  2405. self.shapes.enabled = True
  2406. self.tool_shape.enabled = True
  2407. self.app.app_cursor.enabled = True
  2408. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2409. self.app.ui.corner_snap_btn.setEnabled(True)
  2410. self.app.ui.snap_magnet.setVisible(True)
  2411. self.app.ui.corner_snap_btn.setVisible(True)
  2412. self.app.ui.geo_editor_menu.setDisabled(False)
  2413. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2414. self.app.ui.update_obj_btn.setEnabled(True)
  2415. self.app.ui.g_editor_cmenu.setEnabled(True)
  2416. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2417. self.app.ui.geo_edit_toolbar.setVisible(True)
  2418. self.app.ui.snap_toolbar.setDisabled(False)
  2419. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2420. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2421. for w in sel_tab_widget_list:
  2422. w.setEnabled(False)
  2423. # Tell the App that the editor is active
  2424. self.editor_active = True
  2425. def deactivate(self):
  2426. # adjust the status of the menu entries related to the editor
  2427. self.app.ui.menueditedit.setDisabled(False)
  2428. self.app.ui.menueditok.setDisabled(True)
  2429. # adjust the visibility of some of the canvas context menu
  2430. self.app.ui.popmenu_edit.setVisible(True)
  2431. self.app.ui.popmenu_save.setVisible(False)
  2432. self.disconnect_canvas_event_handlers()
  2433. self.clear()
  2434. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2435. settings = QSettings("Open Source", "FlatCAM")
  2436. if settings.contains("layout"):
  2437. layout = settings.value('layout', type=str)
  2438. if layout == 'standard':
  2439. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2440. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2441. self.app.ui.corner_snap_btn.setEnabled(False)
  2442. self.app.ui.snap_magnet.setVisible(False)
  2443. self.app.ui.corner_snap_btn.setVisible(False)
  2444. elif layout == 'compact':
  2445. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2446. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2447. self.app.ui.corner_snap_btn.setEnabled(False)
  2448. else:
  2449. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2450. self.app.ui.snap_magnet.setVisible(False)
  2451. self.app.ui.corner_snap_btn.setVisible(False)
  2452. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2453. self.app.ui.corner_snap_btn.setEnabled(False)
  2454. # set the Editor Toolbar visibility to what was before entering in the Editor
  2455. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2456. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2457. # Disable visuals
  2458. self.shapes.enabled = False
  2459. self.tool_shape.enabled = False
  2460. self.app.app_cursor.enabled = False
  2461. self.app.ui.geo_editor_menu.setDisabled(True)
  2462. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2463. self.app.ui.update_obj_btn.setEnabled(False)
  2464. self.app.ui.g_editor_cmenu.setEnabled(False)
  2465. self.app.ui.e_editor_cmenu.setEnabled(False)
  2466. # Tell the app that the editor is no longer active
  2467. self.editor_active = False
  2468. try:
  2469. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2470. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2471. for w in sel_tab_widget_list:
  2472. w.setEnabled(True)
  2473. except Exception as e:
  2474. log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2475. # Show original geometry
  2476. if self.fcgeometry:
  2477. self.fcgeometry.visible = True
  2478. def connect_canvas_event_handlers(self):
  2479. ## Canvas events
  2480. # first connect to new, then disconnect the old handlers
  2481. # don't ask why but if there is nothing connected I've seen issues
  2482. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2483. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2484. self.canvas.vis_connect('mouse_release', self.on_geo_click_release)
  2485. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2486. # but those from FlatCAMGeoEditor
  2487. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2488. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2489. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2490. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2491. self.app.collection.view.clicked.disconnect()
  2492. def disconnect_canvas_event_handlers(self):
  2493. # we restore the key and mouse control to FlatCAMApp method
  2494. # first connect to new, then disconnect the old handlers
  2495. # don't ask why but if there is nothing connected I've seen issues
  2496. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2497. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2498. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2499. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2500. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2501. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2502. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2503. self.canvas.vis_disconnect('mouse_release', self.on_geo_click_release)
  2504. def add_shape(self, shape):
  2505. """
  2506. Adds a shape to the shape storage.
  2507. :param shape: Shape to be added.
  2508. :type shape: DrawToolShape
  2509. :return: None
  2510. """
  2511. # List of DrawToolShape?
  2512. if isinstance(shape, list):
  2513. for subshape in shape:
  2514. self.add_shape(subshape)
  2515. return
  2516. assert isinstance(shape, DrawToolShape), \
  2517. "Expected a DrawToolShape, got %s" % type(shape)
  2518. assert shape.geo is not None, \
  2519. "Shape object has empty geometry (None)"
  2520. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2521. not isinstance(shape.geo, list), \
  2522. "Shape objects has empty geometry ([])"
  2523. if isinstance(shape, DrawToolUtilityShape):
  2524. self.utility.append(shape)
  2525. else:
  2526. self.storage.insert(shape) # TODO: Check performance
  2527. def delete_utility_geometry(self):
  2528. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2529. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2530. for_deletion = [shape for shape in self.utility]
  2531. for shape in for_deletion:
  2532. self.delete_shape(shape)
  2533. self.tool_shape.clear(update=True)
  2534. self.tool_shape.redraw()
  2535. def cutpath(self):
  2536. selected = self.get_selected()
  2537. tools = selected[1:]
  2538. toolgeo = cascaded_union([shp.geo for shp in tools])
  2539. target = selected[0]
  2540. if type(target.geo) == Polygon:
  2541. for ring in poly2rings(target.geo):
  2542. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2543. self.delete_shape(target)
  2544. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2545. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2546. self.delete_shape(target)
  2547. elif type(target.geo) == MultiLineString:
  2548. try:
  2549. for linestring in target.geo:
  2550. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2551. except:
  2552. self.app.log.warning("Current LinearString does not intersect the target")
  2553. self.delete_shape(target)
  2554. else:
  2555. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2556. self.replot()
  2557. def toolbar_tool_toggle(self, key):
  2558. self.options[key] = self.sender().isChecked()
  2559. if self.options[key] == True:
  2560. return 1
  2561. else:
  2562. return 0
  2563. def clear(self):
  2564. self.active_tool = None
  2565. # self.shape_buffer = []
  2566. self.selected = []
  2567. self.shapes.clear(update=True)
  2568. self.tool_shape.clear(update=True)
  2569. # self.storage = FlatCAMGeoEditor.make_storage()
  2570. self.replot()
  2571. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  2572. """
  2573. Imports the geometry from the given FlatCAM Geometry object
  2574. into the editor.
  2575. :param fcgeometry: FlatCAMGeometry
  2576. :return: None
  2577. """
  2578. assert isinstance(fcgeometry, Geometry), \
  2579. "Expected a Geometry, got %s" % type(fcgeometry)
  2580. self.deactivate()
  2581. self.activate()
  2582. # Hide original geometry
  2583. self.fcgeometry = fcgeometry
  2584. fcgeometry.visible = False
  2585. # Set selection tolerance
  2586. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2587. self.select_tool("select")
  2588. # Link shapes into editor.
  2589. if multigeo_tool:
  2590. self.multigeo_tool = multigeo_tool
  2591. geo_to_edit = fcgeometry.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'])
  2592. self.app.inform.emit(_("[WARNING] Editing MultiGeo Geometry, tool: {tool} with diameter: {dia}").
  2593. format(tool=self.multigeo_tool, dia=fcgeometry.tools[self.multigeo_tool]['tooldia']))
  2594. else:
  2595. geo_to_edit = fcgeometry.flatten()
  2596. for shape in geo_to_edit:
  2597. if shape is not None: # TODO: Make flatten never create a None
  2598. if type(shape) == Polygon:
  2599. self.add_shape(DrawToolShape(shape.exterior))
  2600. for inter in shape.interiors:
  2601. self.add_shape(DrawToolShape(inter))
  2602. else:
  2603. self.add_shape(DrawToolShape(shape))
  2604. self.replot()
  2605. # start with GRID toolbar activated
  2606. if self.app.ui.grid_snap_btn.isChecked() == False:
  2607. self.app.ui.grid_snap_btn.trigger()
  2608. def on_buffer_tool(self):
  2609. buff_tool = BufferSelectionTool(self.app, self)
  2610. buff_tool.run()
  2611. def on_paint_tool(self):
  2612. paint_tool = PaintOptionsTool(self.app, self)
  2613. paint_tool.run()
  2614. def on_tool_select(self, tool):
  2615. """
  2616. Behavior of the toolbar. Tool initialization.
  2617. :rtype : None
  2618. """
  2619. self.app.log.debug("on_tool_select('%s')" % tool)
  2620. # This is to make the group behave as radio group
  2621. if tool in self.tools:
  2622. if self.tools[tool]["button"].isChecked():
  2623. self.app.log.debug("%s is checked." % tool)
  2624. for t in self.tools:
  2625. if t != tool:
  2626. self.tools[t]["button"].setChecked(False)
  2627. self.active_tool = self.tools[tool]["constructor"](self)
  2628. if not isinstance(self.active_tool, FCSelect):
  2629. self.app.inform.emit(self.active_tool.start_msg)
  2630. else:
  2631. self.app.log.debug("%s is NOT checked." % tool)
  2632. for t in self.tools:
  2633. self.tools[t]["button"].setChecked(False)
  2634. self.select_tool('select')
  2635. self.active_tool = FCSelect(self)
  2636. def draw_tool_path(self):
  2637. self.select_tool('path')
  2638. return
  2639. def draw_tool_rectangle(self):
  2640. self.select_tool('rectangle')
  2641. return
  2642. def on_grid_toggled(self):
  2643. self.toolbar_tool_toggle("grid_snap")
  2644. # make sure that the cursor shape is enabled/disabled, too
  2645. if self.options['grid_snap'] is True:
  2646. self.app.app_cursor.enabled = True
  2647. else:
  2648. self.app.app_cursor.enabled = False
  2649. def on_canvas_click(self, event):
  2650. """
  2651. event.x and .y have canvas coordinates
  2652. event.xdaya and .ydata have plot coordinates
  2653. :param event: Event object dispatched by Matplotlib
  2654. :return: None
  2655. """
  2656. if event.button is 1:
  2657. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2658. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2659. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2660. ### Snap coordinates
  2661. x, y = self.snap(self.pos[0], self.pos[1])
  2662. self.pos = (x, y)
  2663. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2664. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2665. if modifiers == QtCore.Qt.ShiftModifier:
  2666. self.app.clipboard.setText(
  2667. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2668. return
  2669. # Selection with left mouse button
  2670. if self.active_tool is not None and event.button is 1:
  2671. # Dispatch event to active_tool
  2672. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  2673. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  2674. # If it is a shape generating tool
  2675. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2676. self.on_shape_complete()
  2677. # MS: always return to the Select Tool if modifier key is not pressed
  2678. # else return to the current tool
  2679. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2680. if self.app.defaults["global_mselect_key"] == 'Control':
  2681. modifier_to_use = Qt.ControlModifier
  2682. else:
  2683. modifier_to_use = Qt.ShiftModifier
  2684. # if modifier key is pressed then we add to the selected list the current shape but if
  2685. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  2686. if key_modifier == modifier_to_use:
  2687. self.select_tool(self.active_tool.name)
  2688. else:
  2689. self.select_tool("select")
  2690. return
  2691. if isinstance(self.active_tool, FCSelect):
  2692. # self.app.log.debug("Replotting after click.")
  2693. self.replot()
  2694. else:
  2695. self.app.log.debug("No active tool to respond to click!")
  2696. def on_canvas_move(self, event):
  2697. """
  2698. Called on 'mouse_move' event
  2699. event.pos have canvas screen coordinates
  2700. :param event: Event object dispatched by VisPy SceneCavas
  2701. :return: None
  2702. """
  2703. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2704. event.xdata, event.ydata = pos[0], pos[1]
  2705. self.x = event.xdata
  2706. self.y = event.ydata
  2707. # Prevent updates on pan
  2708. # if len(event.buttons) > 0:
  2709. # return
  2710. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2711. if event.button == 2:
  2712. self.app.panning_action = True
  2713. return
  2714. else:
  2715. self.app.panning_action = False
  2716. try:
  2717. x = float(event.xdata)
  2718. y = float(event.ydata)
  2719. except TypeError:
  2720. return
  2721. if self.active_tool is None:
  2722. return
  2723. ### Snap coordinates
  2724. x, y = self.snap(x, y)
  2725. self.snap_x = x
  2726. self.snap_y = y
  2727. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2728. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2729. "<b>Y</b>: %.4f" % (x, y))
  2730. if self.pos is None:
  2731. self.pos = (0, 0)
  2732. dx = x - self.pos[0]
  2733. dy = y - self.pos[1]
  2734. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2735. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2736. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2737. ### Utility geometry (animated)
  2738. geo = self.active_tool.utility_geometry(data=(x, y))
  2739. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2740. # Remove any previous utility shape
  2741. self.tool_shape.clear(update=True)
  2742. self.draw_utility_geometry(geo=geo)
  2743. ### Selection area on canvas section ###
  2744. dx = pos[0] - self.pos[0]
  2745. if event.is_dragging == 1 and event.button == 1:
  2746. self.app.delete_selection_shape()
  2747. if dx < 0:
  2748. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2749. color=self.app.defaults["global_alt_sel_line"],
  2750. face_color=self.app.defaults['global_alt_sel_fill'])
  2751. self.app.selection_type = False
  2752. else:
  2753. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2754. self.app.selection_type = True
  2755. else:
  2756. self.app.selection_type = None
  2757. # Update cursor
  2758. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2759. def on_geo_click_release(self, event):
  2760. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2761. if self.app.grid_status():
  2762. pos = self.snap(pos_canvas[0], pos_canvas[1])
  2763. else:
  2764. pos = (pos_canvas[0], pos_canvas[1])
  2765. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2766. # canvas menu
  2767. try:
  2768. if event.button == 2: # right click
  2769. if self.app.panning_action is True:
  2770. self.app.panning_action = False
  2771. else:
  2772. if self.in_action is False:
  2773. self.app.cursor = QtGui.QCursor()
  2774. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2775. else:
  2776. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2777. # right mouse click will finish the action
  2778. if isinstance(self.active_tool, FCShapeTool):
  2779. self.active_tool.click(self.snap(self.x, self.y))
  2780. self.active_tool.make()
  2781. if self.active_tool.complete:
  2782. self.on_shape_complete()
  2783. self.app.inform.emit(_("[success] Done."))
  2784. # MS: always return to the Select Tool if modifier key is not pressed
  2785. # else return to the current tool
  2786. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2787. if self.app.defaults["global_mselect_key"] == 'Control':
  2788. modifier_to_use = Qt.ControlModifier
  2789. else:
  2790. modifier_to_use = Qt.ShiftModifier
  2791. if key_modifier == modifier_to_use:
  2792. self.select_tool(self.active_tool.name)
  2793. else:
  2794. self.select_tool("select")
  2795. except Exception as e:
  2796. log.warning("Error: %s" % str(e))
  2797. return
  2798. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2799. # selection and then select a type of selection ("enclosing" or "touching")
  2800. try:
  2801. if event.button == 1: # left click
  2802. if self.app.selection_type is not None:
  2803. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2804. self.app.selection_type = None
  2805. elif isinstance(self.active_tool, FCSelect):
  2806. # Dispatch event to active_tool
  2807. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  2808. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  2809. # self.app.inform.emit(msg)
  2810. self.replot()
  2811. except Exception as e:
  2812. log.warning("Error: %s" % str(e))
  2813. return
  2814. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2815. """
  2816. :param start_pos: mouse position when the selection LMB click was done
  2817. :param end_pos: mouse position when the left mouse button is released
  2818. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2819. :type Bool
  2820. :return:
  2821. """
  2822. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2823. self.app.delete_selection_shape()
  2824. for obj in self.storage.get_objects():
  2825. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2826. (sel_type is False and poly_selection.intersects(obj.geo)):
  2827. if self.key == self.app.defaults["global_mselect_key"]:
  2828. if obj in self.selected:
  2829. self.selected.remove(obj)
  2830. else:
  2831. # add the object to the selected shapes
  2832. self.selected.append(obj)
  2833. else:
  2834. if obj not in self.selected:
  2835. self.selected.append(obj)
  2836. self.replot()
  2837. def draw_utility_geometry(self, geo):
  2838. # Add the new utility shape
  2839. try:
  2840. # this case is for the Font Parse
  2841. for el in list(geo.geo):
  2842. if type(el) == MultiPolygon:
  2843. for poly in el:
  2844. self.tool_shape.add(
  2845. shape=poly,
  2846. color=(self.app.defaults["global_draw_color"] + '80'),
  2847. update=False,
  2848. layer=0,
  2849. tolerance=None
  2850. )
  2851. elif type(el) == MultiLineString:
  2852. for linestring in el:
  2853. self.tool_shape.add(
  2854. shape=linestring,
  2855. color=(self.app.defaults["global_draw_color"] + '80'),
  2856. update=False,
  2857. layer=0,
  2858. tolerance=None
  2859. )
  2860. else:
  2861. self.tool_shape.add(
  2862. shape=el,
  2863. color=(self.app.defaults["global_draw_color"] + '80'),
  2864. update=False,
  2865. layer=0,
  2866. tolerance=None
  2867. )
  2868. except TypeError:
  2869. self.tool_shape.add(
  2870. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2871. update=False, layer=0, tolerance=None)
  2872. self.tool_shape.redraw()
  2873. def on_delete_btn(self):
  2874. self.delete_selected()
  2875. self.replot()
  2876. def delete_selected(self):
  2877. tempref = [s for s in self.selected]
  2878. for shape in tempref:
  2879. self.delete_shape(shape)
  2880. self.selected = []
  2881. def delete_shape(self, shape):
  2882. if shape in self.utility:
  2883. self.utility.remove(shape)
  2884. return
  2885. self.storage.remove(shape)
  2886. if shape in self.selected:
  2887. self.selected.remove(shape) # TODO: Check performance
  2888. def on_move(self):
  2889. self.app.ui.geo_move_btn.setChecked(True)
  2890. self.on_tool_select('move')
  2891. def on_move_click(self):
  2892. if not self.selected:
  2893. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2894. return
  2895. self.on_move()
  2896. self.active_tool.set_origin(self.snap(self.x, self.y))
  2897. def on_copy_click(self):
  2898. if not self.selected:
  2899. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  2900. return
  2901. self.app.ui.geo_copy_btn.setChecked(True)
  2902. self.app.geo_editor.on_tool_select('copy')
  2903. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  2904. self.app.geo_editor.x, self.app.geo_editor.y))
  2905. self.app.inform.emit(_("Click on target point."))
  2906. def on_corner_snap(self):
  2907. self.app.ui.corner_snap_btn.trigger()
  2908. def get_selected(self):
  2909. """
  2910. Returns list of shapes that are selected in the editor.
  2911. :return: List of shapes.
  2912. """
  2913. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2914. return self.selected
  2915. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2916. """
  2917. Plots a geometric object or list of objects without rendering. Plotted objects
  2918. are returned as a list. This allows for efficient/animated rendering.
  2919. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2920. :param color: Shape color
  2921. :param linewidth: Width of lines in # of pixels.
  2922. :return: List of plotted elements.
  2923. """
  2924. plot_elements = []
  2925. if geometry is None:
  2926. geometry = self.active_tool.geometry
  2927. try:
  2928. for geo in geometry:
  2929. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2930. ## Non-iterable
  2931. except TypeError:
  2932. ## DrawToolShape
  2933. if isinstance(geometry, DrawToolShape):
  2934. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2935. ## Polygon: Descend into exterior and each interior.
  2936. if type(geometry) == Polygon:
  2937. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2938. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2939. if type(geometry) == LineString or type(geometry) == LinearRing:
  2940. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  2941. tolerance=self.fcgeometry.drawing_tolerance))
  2942. if type(geometry) == Point:
  2943. pass
  2944. return plot_elements
  2945. def plot_all(self):
  2946. """
  2947. Plots all shapes in the editor.
  2948. :return: None
  2949. :rtype: None
  2950. """
  2951. # self.app.log.debug("plot_all()")
  2952. self.shapes.clear(update=True)
  2953. for shape in self.storage.get_objects():
  2954. if shape.geo is None: # TODO: This shouldn't have happened
  2955. continue
  2956. if shape in self.selected:
  2957. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2958. continue
  2959. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2960. for shape in self.utility:
  2961. self.plot_shape(geometry=shape.geo, linewidth=1)
  2962. continue
  2963. self.shapes.redraw()
  2964. def replot(self):
  2965. self.plot_all()
  2966. def on_shape_complete(self):
  2967. self.app.log.debug("on_shape_complete()")
  2968. # Add shape
  2969. self.add_shape(self.active_tool.geometry)
  2970. # Remove any utility shapes
  2971. self.delete_utility_geometry()
  2972. self.tool_shape.clear(update=True)
  2973. # Replot and reset tool.
  2974. self.replot()
  2975. # self.active_tool = type(self.active_tool)(self)
  2976. @staticmethod
  2977. def make_storage():
  2978. ## Shape storage.
  2979. storage = FlatCAMRTreeStorage()
  2980. storage.get_points = DrawToolShape.get_pts
  2981. return storage
  2982. def select_tool(self, toolname):
  2983. """
  2984. Selects a drawing tool. Impacts the object and GUI.
  2985. :param toolname: Name of the tool.
  2986. :return: None
  2987. """
  2988. self.tools[toolname]["button"].setChecked(True)
  2989. self.on_tool_select(toolname)
  2990. def set_selected(self, shape):
  2991. # Remove and add to the end.
  2992. if shape in self.selected:
  2993. self.selected.remove(shape)
  2994. self.selected.append(shape)
  2995. def set_unselected(self, shape):
  2996. if shape in self.selected:
  2997. self.selected.remove(shape)
  2998. def snap(self, x, y):
  2999. """
  3000. Adjusts coordinates to snap settings.
  3001. :param x: Input coordinate X
  3002. :param y: Input coordinate Y
  3003. :return: Snapped (x, y)
  3004. """
  3005. snap_x, snap_y = (x, y)
  3006. snap_distance = Inf
  3007. ### Object (corner?) snap
  3008. ### No need for the objects, just the coordinates
  3009. ### in the index.
  3010. if self.options["corner_snap"]:
  3011. try:
  3012. nearest_pt, shape = self.storage.nearest((x, y))
  3013. nearest_pt_distance = distance((x, y), nearest_pt)
  3014. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3015. snap_distance = nearest_pt_distance
  3016. snap_x, snap_y = nearest_pt
  3017. except (StopIteration, AssertionError):
  3018. pass
  3019. ### Grid snap
  3020. if self.options["grid_snap"]:
  3021. if self.options["global_gridx"] != 0:
  3022. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3023. else:
  3024. snap_x_ = x
  3025. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3026. # and it will use the snap distance from GridX entry
  3027. if self.app.ui.grid_gap_link_cb.isChecked():
  3028. if self.options["global_gridx"] != 0:
  3029. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3030. else:
  3031. snap_y_ = y
  3032. else:
  3033. if self.options["global_gridy"] != 0:
  3034. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3035. else:
  3036. snap_y_ = y
  3037. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3038. if nearest_grid_distance < snap_distance:
  3039. snap_x, snap_y = (snap_x_, snap_y_)
  3040. return snap_x, snap_y
  3041. def update_fcgeometry(self, fcgeometry):
  3042. """
  3043. Transfers the geometry tool shape buffer to the selected geometry
  3044. object. The geometry already in the object are removed.
  3045. :param fcgeometry: FlatCAMGeometry
  3046. :return: None
  3047. """
  3048. if self.multigeo_tool:
  3049. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  3050. # for shape in self.shape_buffer:
  3051. for shape in self.storage.get_objects():
  3052. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  3053. self.multigeo_tool = None
  3054. else:
  3055. fcgeometry.solid_geometry = []
  3056. # for shape in self.shape_buffer:
  3057. for shape in self.storage.get_objects():
  3058. fcgeometry.solid_geometry.append(shape.geo)
  3059. def update_options(self, obj):
  3060. if self.paint_tooldia:
  3061. obj.options['cnctooldia'] = self.paint_tooldia
  3062. self.paint_tooldia = None
  3063. return True
  3064. else:
  3065. return False
  3066. def union(self):
  3067. """
  3068. Makes union of selected polygons. Original polygons
  3069. are deleted.
  3070. :return: None.
  3071. """
  3072. results = cascaded_union([t.geo for t in self.get_selected()])
  3073. # Delete originals.
  3074. for_deletion = [s for s in self.get_selected()]
  3075. for shape in for_deletion:
  3076. self.delete_shape(shape)
  3077. # Selected geometry is now gone!
  3078. self.selected = []
  3079. self.add_shape(DrawToolShape(results))
  3080. self.replot()
  3081. def intersection(self):
  3082. """
  3083. Makes intersectino of selected polygons. Original polygons are deleted.
  3084. :return: None
  3085. """
  3086. shapes = self.get_selected()
  3087. try:
  3088. results = shapes[0].geo
  3089. except Exception as e:
  3090. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3091. self.app.inform.emit(_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  3092. self.select_tool('select')
  3093. return
  3094. for shape in shapes[1:]:
  3095. results = results.intersection(shape.geo)
  3096. # Delete originals.
  3097. for_deletion = [s for s in self.get_selected()]
  3098. for shape in for_deletion:
  3099. self.delete_shape(shape)
  3100. # Selected geometry is now gone!
  3101. self.selected = []
  3102. self.add_shape(DrawToolShape(results))
  3103. self.replot()
  3104. def subtract(self):
  3105. selected = self.get_selected()
  3106. try:
  3107. tools = selected[1:]
  3108. toolgeo = cascaded_union([shp.geo for shp in tools])
  3109. result = selected[0].geo.difference(toolgeo)
  3110. self.delete_shape(selected[0])
  3111. self.add_shape(DrawToolShape(result))
  3112. self.replot()
  3113. except Exception as e:
  3114. log.debug(str(e))
  3115. def buffer(self, buf_distance, join_style):
  3116. selected = self.get_selected()
  3117. if buf_distance < 0:
  3118. self.app.inform.emit(
  3119. _( "[ERROR_NOTCL] Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  3120. # deselect everything
  3121. self.selected = []
  3122. self.replot()
  3123. return
  3124. if len(selected) == 0:
  3125. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3126. return
  3127. if not isinstance(buf_distance, float):
  3128. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3129. # deselect everything
  3130. self.selected = []
  3131. self.replot()
  3132. return
  3133. pre_buffer = cascaded_union([t.geo for t in selected])
  3134. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3135. if results.is_empty:
  3136. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3137. # deselect everything
  3138. self.selected = []
  3139. self.replot()
  3140. return
  3141. self.add_shape(DrawToolShape(results))
  3142. self.replot()
  3143. self.app.inform.emit(_("[success] Full buffer geometry created."))
  3144. def buffer_int(self, buf_distance, join_style):
  3145. selected = self.get_selected()
  3146. if buf_distance < 0:
  3147. self.app.inform.emit(
  3148. _("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3149. "Use Buffer interior to generate an 'inside' shape")
  3150. )
  3151. # deselect everything
  3152. self.selected = []
  3153. self.replot()
  3154. return
  3155. if len(selected) == 0:
  3156. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3157. return
  3158. if not isinstance(buf_distance, float):
  3159. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3160. # deselect everything
  3161. self.selected = []
  3162. self.replot()
  3163. return
  3164. pre_buffer = cascaded_union([t.geo for t in selected])
  3165. results = pre_buffer.buffer(buf_distance + 1e-10, resolution=32, join_style=join_style)
  3166. if results.is_empty:
  3167. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a smaller buffer value."))
  3168. # deselect everything
  3169. self.selected = []
  3170. self.replot()
  3171. return
  3172. if type(results) == MultiPolygon:
  3173. for poly in results:
  3174. for interior in poly.interiors:
  3175. self.add_shape(DrawToolShape(interior))
  3176. else:
  3177. for interior in results:
  3178. self.add_shape(DrawToolShape(interior))
  3179. self.replot()
  3180. self.app.inform.emit(_("[success] Interior buffer geometry created."))
  3181. # selected = self.get_selected()
  3182. #
  3183. # if len(selected) == 0:
  3184. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3185. # return
  3186. #
  3187. # if not isinstance(buf_distance, float):
  3188. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3189. # return
  3190. #
  3191. # pre_buffer = cascaded_union([t.geo for t in selected])
  3192. # results = pre_buffer.buffer(buf_distance)
  3193. # if results.is_empty:
  3194. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3195. # return
  3196. #
  3197. # int_geo = []
  3198. # if type(results) == MultiPolygon:
  3199. # for poly in results:
  3200. # for g in poly.interiors:
  3201. # int_geo.append(g)
  3202. # res = cascaded_union(int_geo)
  3203. # self.add_shape(DrawToolShape(res))
  3204. # else:
  3205. # print(results.interiors)
  3206. # for g in results.interiors:
  3207. # int_geo.append(g)
  3208. # res = cascaded_union(int_geo)
  3209. # self.add_shape(DrawToolShape(res))
  3210. #
  3211. # self.replot()
  3212. # self.app.inform.emit("Interior buffer geometry created.")
  3213. def buffer_ext(self, buf_distance, join_style):
  3214. selected = self.get_selected()
  3215. if buf_distance < 0:
  3216. self.app.inform.emit(_("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3217. "Use Buffer interior to generate an 'inside' shape"))
  3218. # deselect everything
  3219. self.selected = []
  3220. self.replot()
  3221. return
  3222. if len(selected) == 0:
  3223. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3224. return
  3225. if not isinstance(buf_distance, float):
  3226. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3227. # deselect everything
  3228. self.selected = []
  3229. self.replot()
  3230. return
  3231. pre_buffer = cascaded_union([t.geo for t in selected])
  3232. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3233. if results.is_empty:
  3234. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3235. # deselect everything
  3236. self.selected = []
  3237. self.replot()
  3238. return
  3239. if type(results) == MultiPolygon:
  3240. for poly in results:
  3241. self.add_shape(DrawToolShape(poly.exterior))
  3242. else:
  3243. self.add_shape(DrawToolShape(results.exterior))
  3244. self.replot()
  3245. self.app.inform.emit(_("[success] Exterior buffer geometry created."))
  3246. # def paint(self, tooldia, overlap, margin, method):
  3247. # selected = self.get_selected()
  3248. #
  3249. # if len(selected) == 0:
  3250. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3251. # return
  3252. #
  3253. # for param in [tooldia, overlap, margin]:
  3254. # if not isinstance(param, float):
  3255. # param_name = [k for k, v in locals().items() if v is param][0]
  3256. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3257. #
  3258. # # Todo: Check for valid method.
  3259. #
  3260. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3261. #
  3262. # results = []
  3263. #
  3264. # def recurse(geo):
  3265. # try:
  3266. # for subg in geo:
  3267. # for subsubg in recurse(subg):
  3268. # yield subsubg
  3269. # except TypeError:
  3270. # if isinstance(geo, LinearRing):
  3271. # yield geo
  3272. #
  3273. # raise StopIteration
  3274. #
  3275. # for geo in selected:
  3276. # print(type(geo.geo))
  3277. #
  3278. # local_results = []
  3279. # for poly in recurse(geo.geo):
  3280. # if method == "seed":
  3281. # # Type(cp) == FlatCAMRTreeStorage | None
  3282. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3283. # tooldia, overlap=overlap)
  3284. #
  3285. # else:
  3286. # # Type(cp) == FlatCAMRTreeStorage | None
  3287. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3288. # tooldia, overlap=overlap)
  3289. #
  3290. # if cp is not None:
  3291. # local_results += list(cp.get_objects())
  3292. #
  3293. # results.append(cascaded_union(local_results))
  3294. #
  3295. # # This is a dirty patch:
  3296. # for r in results:
  3297. # self.add_shape(DrawToolShape(r))
  3298. #
  3299. # self.replot()
  3300. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3301. self.paint_tooldia = tooldia
  3302. selected = self.get_selected()
  3303. if len(selected) == 0:
  3304. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for painting."))
  3305. return
  3306. for param in [tooldia, overlap, margin]:
  3307. if not isinstance(param, float):
  3308. param_name = [k for k, v in locals().items() if v is param][0]
  3309. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3310. results = []
  3311. if overlap >= 1:
  3312. self.app.inform.emit(
  3313. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3314. return
  3315. def recurse(geometry, reset=True):
  3316. """
  3317. Creates a list of non-iterable linear geometry objects.
  3318. Results are placed in self.flat_geometry
  3319. :param geometry: Shapely type or list or list of list of such.
  3320. :param reset: Clears the contents of self.flat_geometry.
  3321. """
  3322. if geometry is None:
  3323. return
  3324. if reset:
  3325. self.flat_geo = []
  3326. ## If iterable, expand recursively.
  3327. try:
  3328. for geo in geometry:
  3329. if geo is not None:
  3330. recurse(geometry=geo, reset=False)
  3331. ## Not iterable, do the actual indexing and add.
  3332. except TypeError:
  3333. self.flat_geo.append(geometry)
  3334. return self.flat_geo
  3335. for geo in selected:
  3336. local_results = []
  3337. for geo_obj in recurse(geo.geo):
  3338. try:
  3339. if type(geo_obj) == Polygon:
  3340. poly_buf = geo_obj.buffer(-margin)
  3341. else:
  3342. poly_buf = Polygon(geo_obj).buffer(-margin)
  3343. if method == "seed":
  3344. cp = Geometry.clear_polygon2(poly_buf,
  3345. tooldia, self.app.defaults["geometry_circle_steps"],
  3346. overlap=overlap, contour=contour, connect=connect)
  3347. elif method == "lines":
  3348. cp = Geometry.clear_polygon3(poly_buf,
  3349. tooldia, self.app.defaults["geometry_circle_steps"],
  3350. overlap=overlap, contour=contour, connect=connect)
  3351. else:
  3352. cp = Geometry.clear_polygon(poly_buf,
  3353. tooldia, self.app.defaults["geometry_circle_steps"],
  3354. overlap=overlap, contour=contour, connect=connect)
  3355. if cp is not None:
  3356. local_results += list(cp.get_objects())
  3357. except Exception as e:
  3358. log.debug("Could not Paint the polygons. %s" % str(e))
  3359. self.app.inform.emit(
  3360. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3361. "Or a different method of Paint\n%s") % str(e))
  3362. return
  3363. # add the result to the results list
  3364. results.append(cascaded_union(local_results))
  3365. # This is a dirty patch:
  3366. for r in results:
  3367. self.add_shape(DrawToolShape(r))
  3368. self.app.inform.emit(
  3369. _("[success] Paint done."))
  3370. self.replot()
  3371. def distance(pt1, pt2):
  3372. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3373. def mag(vec):
  3374. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  3375. def poly2rings(poly):
  3376. return [poly.exterior] + [interior for interior in poly.interiors]