FlatCAMGeoEditor.py 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073
  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
  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. self.start_msg = _("Click on CENTER ...")
  1616. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1617. def click(self, point):
  1618. self.points.append(point)
  1619. if len(self.points) == 1:
  1620. self.draw_app.app.inform.emit(_("Click on Circle perimeter point to complete ..."))
  1621. return "Click on perimeter to complete ..."
  1622. if len(self.points) == 2:
  1623. self.make()
  1624. return "Done."
  1625. return ""
  1626. def utility_geometry(self, data=None):
  1627. if len(self.points) == 1:
  1628. p1 = self.points[0]
  1629. p2 = data
  1630. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1631. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1632. return None
  1633. def make(self):
  1634. p1 = self.points[0]
  1635. p2 = self.points[1]
  1636. radius = distance(p1, p2)
  1637. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1638. self.complete = True
  1639. self.draw_app.app.inform.emit(_("[success] Done. Adding Circle completed."))
  1640. class FCArc(FCShapeTool):
  1641. def __init__(self, draw_app):
  1642. DrawTool.__init__(self, draw_app)
  1643. self.name = 'arc'
  1644. self.start_msg = _("Click on CENTER ...")
  1645. # Direction of rotation between point 1 and 2.
  1646. # 'cw' or 'ccw'. Switch direction by hitting the
  1647. # 'o' key.
  1648. self.direction = "cw"
  1649. # Mode
  1650. # C12 = Center, p1, p2
  1651. # 12C = p1, p2, Center
  1652. # 132 = p1, p3, p2
  1653. self.mode = "c12" # Center, p1, p2
  1654. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1655. def click(self, point):
  1656. self.points.append(point)
  1657. if len(self.points) == 1:
  1658. if self.mode == 'c12':
  1659. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1660. elif self.mode == '132':
  1661. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1662. else:
  1663. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1664. return "Click on 1st point ..."
  1665. if len(self.points) == 2:
  1666. if self.mode == 'c12':
  1667. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1668. elif self.mode == '132':
  1669. self.draw_app.app.inform.emit(_("Click on Point2 ..."))
  1670. else:
  1671. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1672. return "Click on 2nd point to complete ..."
  1673. if len(self.points) == 3:
  1674. self.make()
  1675. return "Done."
  1676. return ""
  1677. def on_key(self, key):
  1678. if key == 'D' or key == QtCore.Qt.Key_D:
  1679. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1680. return _('Direction: %s') % self.direction.upper()
  1681. if key == 'M' or key == QtCore.Qt.Key_M:
  1682. if self.mode == 'c12':
  1683. self.mode = '12c'
  1684. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1685. elif self.mode == '12c':
  1686. self.mode = '132'
  1687. return _('Mode: Point1 -> Point3 -> Point2. Click on 1st point ...')
  1688. else:
  1689. self.mode = 'c12'
  1690. return _('Mode: Center -> Start -> Stop. Click on Center ...')
  1691. def utility_geometry(self, data=None):
  1692. if len(self.points) == 1: # Show the radius
  1693. center = self.points[0]
  1694. p1 = data
  1695. return DrawToolUtilityShape(LineString([center, p1]))
  1696. if len(self.points) == 2: # Show the arc
  1697. if self.mode == 'c12':
  1698. center = self.points[0]
  1699. p1 = self.points[1]
  1700. p2 = data
  1701. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1702. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1703. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1704. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1705. self.direction, self.steps_per_circ)),
  1706. Point(center)])
  1707. elif self.mode == '132':
  1708. p1 = array(self.points[0])
  1709. p3 = array(self.points[1])
  1710. p2 = array(data)
  1711. center, radius, t = three_point_circle(p1, p2, p3)
  1712. direction = 'cw' if sign(t) > 0 else 'ccw'
  1713. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1714. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1715. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1716. direction, self.steps_per_circ)),
  1717. Point(center), Point(p1), Point(p3)])
  1718. else: # '12c'
  1719. p1 = array(self.points[0])
  1720. p2 = array(self.points[1])
  1721. # Midpoint
  1722. a = (p1 + p2) / 2.0
  1723. # Parallel vector
  1724. c = p2 - p1
  1725. # Perpendicular vector
  1726. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1727. b /= norm(b)
  1728. # Distance
  1729. t = distance(data, a)
  1730. # Which side? Cross product with c.
  1731. # cross(M-A, B-A), where line is AB and M is test point.
  1732. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1733. t *= sign(side)
  1734. # Center = a + bt
  1735. center = a + b * t
  1736. radius = norm(center - p1)
  1737. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1738. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1739. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1740. self.direction, self.steps_per_circ)),
  1741. Point(center)])
  1742. return None
  1743. def make(self):
  1744. if self.mode == 'c12':
  1745. center = self.points[0]
  1746. p1 = self.points[1]
  1747. p2 = self.points[2]
  1748. radius = distance(center, p1)
  1749. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1750. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1751. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1752. self.direction, self.steps_per_circ)))
  1753. elif self.mode == '132':
  1754. p1 = array(self.points[0])
  1755. p3 = array(self.points[1])
  1756. p2 = array(self.points[2])
  1757. center, radius, t = three_point_circle(p1, p2, p3)
  1758. direction = 'cw' if sign(t) > 0 else 'ccw'
  1759. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1760. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1761. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1762. direction, self.steps_per_circ)))
  1763. else: # self.mode == '12c'
  1764. p1 = array(self.points[0])
  1765. p2 = array(self.points[1])
  1766. pc = array(self.points[2])
  1767. # Midpoint
  1768. a = (p1 + p2) / 2.0
  1769. # Parallel vector
  1770. c = p2 - p1
  1771. # Perpendicular vector
  1772. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1773. b /= norm(b)
  1774. # Distance
  1775. t = distance(pc, a)
  1776. # Which side? Cross product with c.
  1777. # cross(M-A, B-A), where line is AB and M is test point.
  1778. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1779. t *= sign(side)
  1780. # Center = a + bt
  1781. center = a + b * t
  1782. radius = norm(center - p1)
  1783. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1784. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1785. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1786. self.direction, self.steps_per_circ)))
  1787. self.complete = True
  1788. self.draw_app.app.inform.emit(_("[success] Done. Arc completed."))
  1789. class FCRectangle(FCShapeTool):
  1790. """
  1791. Resulting type: Polygon
  1792. """
  1793. def __init__(self, draw_app):
  1794. DrawTool.__init__(self, draw_app)
  1795. self.name = 'rectangle'
  1796. self.start_msg = _("Click on 1st corner ...")
  1797. def click(self, point):
  1798. self.points.append(point)
  1799. if len(self.points) == 1:
  1800. return "Click on opposite corner to complete ..."
  1801. if len(self.points) == 2:
  1802. self.make()
  1803. return "Done."
  1804. return ""
  1805. def utility_geometry(self, data=None):
  1806. if len(self.points) == 1:
  1807. p1 = self.points[0]
  1808. p2 = data
  1809. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1810. return None
  1811. def make(self):
  1812. p1 = self.points[0]
  1813. p2 = self.points[1]
  1814. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1815. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1816. self.complete = True
  1817. self.draw_app.app.inform.emit(_("[success] Done. Rectangle completed."))
  1818. class FCPolygon(FCShapeTool):
  1819. """
  1820. Resulting type: Polygon
  1821. """
  1822. def __init__(self, draw_app):
  1823. DrawTool.__init__(self, draw_app)
  1824. self.name = 'polygon'
  1825. self.start_msg = _("Click on 1st point ...")
  1826. def click(self, point):
  1827. self.draw_app.in_action = True
  1828. self.points.append(point)
  1829. if len(self.points) > 0:
  1830. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  1831. return "Click on next point or hit ENTER to complete ..."
  1832. return ""
  1833. def utility_geometry(self, data=None):
  1834. if len(self.points) == 1:
  1835. temp_points = [x for x in self.points]
  1836. temp_points.append(data)
  1837. return DrawToolUtilityShape(LineString(temp_points))
  1838. if len(self.points) > 1:
  1839. temp_points = [x for x in self.points]
  1840. temp_points.append(data)
  1841. return DrawToolUtilityShape(LinearRing(temp_points))
  1842. return None
  1843. def make(self):
  1844. # self.geometry = LinearRing(self.points)
  1845. self.geometry = DrawToolShape(Polygon(self.points))
  1846. self.draw_app.in_action = False
  1847. self.complete = True
  1848. self.draw_app.app.inform.emit(_("[success] Done. Polygon completed."))
  1849. def on_key(self, key):
  1850. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1851. if len(self.points) > 0:
  1852. self.points = self.points[0:-1]
  1853. # Remove any previous utility shape
  1854. self.draw_app.tool_shape.clear(update=False)
  1855. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1856. self.draw_app.draw_utility_geometry(geo=geo)
  1857. return _("Backtracked one point ...")
  1858. class FCPath(FCPolygon):
  1859. """
  1860. Resulting type: LineString
  1861. """
  1862. def make(self):
  1863. self.geometry = DrawToolShape(LineString(self.points))
  1864. self.name = 'path'
  1865. self.draw_app.in_action = False
  1866. self.complete = True
  1867. self.draw_app.app.inform.emit(_("[success] Done. Path completed."))
  1868. def utility_geometry(self, data=None):
  1869. if len(self.points) > 0:
  1870. temp_points = [x for x in self.points]
  1871. temp_points.append(data)
  1872. return DrawToolUtilityShape(LineString(temp_points))
  1873. return None
  1874. def on_key(self, key):
  1875. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1876. if len(self.points) > 0:
  1877. self.points = self.points[0:-1]
  1878. # Remove any previous utility shape
  1879. self.draw_app.tool_shape.clear(update=False)
  1880. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1881. self.draw_app.draw_utility_geometry(geo=geo)
  1882. return _("Backtracked one point ...")
  1883. class FCSelect(DrawTool):
  1884. def __init__(self, draw_app):
  1885. DrawTool.__init__(self, draw_app)
  1886. self.name = 'select'
  1887. self.storage = self.draw_app.storage
  1888. # self.shape_buffer = self.draw_app.shape_buffer
  1889. # self.selected = self.draw_app.selected
  1890. def click_release(self, point):
  1891. self.select_shapes(point)
  1892. return ""
  1893. def select_shapes(self, pos):
  1894. # list where we store the overlapped shapes under our mouse left click position
  1895. over_shape_list = []
  1896. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1897. for obj_shape in self.storage.get_objects():
  1898. # first method of click selection -> inconvenient
  1899. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1900. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1901. # over_shape_list.append(obj_shape)
  1902. # second method of click selection -> slow
  1903. # outside = obj_shape.geo.buffer(0.1)
  1904. # inside = obj_shape.geo.buffer(-0.1)
  1905. # shape_band = outside.difference(inside)
  1906. # if Point(pos).within(shape_band):
  1907. # over_shape_list.append(obj_shape)
  1908. # 3rd method of click selection -> inconvenient
  1909. try:
  1910. _, closest_shape = self.storage.nearest(pos)
  1911. except StopIteration:
  1912. return ""
  1913. over_shape_list.append(closest_shape)
  1914. try:
  1915. # if there is no shape under our click then deselect all shapes
  1916. # it will not work for 3rd method of click selection
  1917. if not over_shape_list:
  1918. self.draw_app.selected = []
  1919. FlatCAMGeoEditor.draw_shape_idx = -1
  1920. else:
  1921. # if there are shapes under our click then advance through the list of them, one at the time in a
  1922. # circular way
  1923. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1924. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1925. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1926. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  1927. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1928. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1929. if key_modifier == Qt.ControlModifier:
  1930. if obj_to_add in self.draw_app.selected:
  1931. self.draw_app.selected.remove(obj_to_add)
  1932. else:
  1933. self.draw_app.selected.append(obj_to_add)
  1934. else:
  1935. self.draw_app.selected = []
  1936. self.draw_app.selected.append(obj_to_add)
  1937. else:
  1938. if key_modifier == Qt.ShiftModifier:
  1939. if obj_to_add in self.draw_app.selected:
  1940. self.draw_app.selected.remove(obj_to_add)
  1941. else:
  1942. self.draw_app.selected.append(obj_to_add)
  1943. else:
  1944. self.draw_app.selected = []
  1945. self.draw_app.selected.append(obj_to_add)
  1946. except Exception as e:
  1947. log.error("[ERROR] Something went bad. %s" % str(e))
  1948. raise
  1949. class FCMove(FCShapeTool):
  1950. def __init__(self, draw_app):
  1951. FCShapeTool.__init__(self, draw_app)
  1952. self.name = 'move'
  1953. # self.shape_buffer = self.draw_app.shape_buffer
  1954. if not self.draw_app.selected:
  1955. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  1956. return
  1957. self.origin = None
  1958. self.destination = None
  1959. self.start_msg = _("Click on reference point.")
  1960. def set_origin(self, origin):
  1961. self.draw_app.app.inform.emit(_("Click on destination point."))
  1962. self.origin = origin
  1963. def click(self, point):
  1964. if len(self.draw_app.get_selected()) == 0:
  1965. return "Nothing to move."
  1966. if self.origin is None:
  1967. self.set_origin(point)
  1968. return "Click on final location."
  1969. else:
  1970. self.destination = point
  1971. self.make()
  1972. return "Done."
  1973. def make(self):
  1974. # Create new geometry
  1975. dx = self.destination[0] - self.origin[0]
  1976. dy = self.destination[1] - self.origin[1]
  1977. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  1978. for geom in self.draw_app.get_selected()]
  1979. # Delete old
  1980. self.draw_app.delete_selected()
  1981. # # Select the new
  1982. # for g in self.geometry:
  1983. # # Note that g is not in the app's buffer yet!
  1984. # self.draw_app.set_selected(g)
  1985. self.complete = True
  1986. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Move completed."))
  1987. def utility_geometry(self, data=None):
  1988. """
  1989. Temporary geometry on screen while using this tool.
  1990. :param data:
  1991. :return:
  1992. """
  1993. geo_list = []
  1994. if self.origin is None:
  1995. return None
  1996. if len(self.draw_app.get_selected()) == 0:
  1997. return None
  1998. dx = data[0] - self.origin[0]
  1999. dy = data[1] - self.origin[1]
  2000. try:
  2001. for geom in self.draw_app.get_selected():
  2002. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2003. except AttributeError:
  2004. self.draw_app.select_tool('select')
  2005. self.draw_app.selected = []
  2006. return
  2007. return DrawToolUtilityShape(geo_list)
  2008. # return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  2009. # for geom in self.draw_app.get_selected()])
  2010. class FCCopy(FCMove):
  2011. def __init__(self, draw_app):
  2012. FCMove.__init__(self, draw_app)
  2013. self.name = 'copy'
  2014. def make(self):
  2015. # Create new geometry
  2016. dx = self.destination[0] - self.origin[0]
  2017. dy = self.destination[1] - self.origin[1]
  2018. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2019. for geom in self.draw_app.get_selected()]
  2020. self.complete = True
  2021. self.draw_app.app.inform.emit(_("[success] Done. Geometry(s) Copy completed."))
  2022. class FCText(FCShapeTool):
  2023. def __init__(self, draw_app):
  2024. FCShapeTool.__init__(self, draw_app)
  2025. self.name = 'text'
  2026. # self.shape_buffer = self.draw_app.shape_buffer
  2027. self.draw_app = draw_app
  2028. self.app = draw_app.app
  2029. self.start_msg = _("Click on the Destination point...")
  2030. self.origin = (0, 0)
  2031. self.text_gui = TextInputTool(self.app)
  2032. self.text_gui.run()
  2033. def click(self, point):
  2034. # Create new geometry
  2035. dx = point[0]
  2036. dy = point[1]
  2037. try:
  2038. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2039. except Exception as e:
  2040. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2041. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2042. "supported. Error: %s") % str(e))
  2043. self.text_gui.text_path = []
  2044. self.text_gui.hide_tool()
  2045. self.draw_app.select_tool('select')
  2046. return
  2047. self.text_gui.text_path = []
  2048. self.text_gui.hide_tool()
  2049. self.complete = True
  2050. self.draw_app.app.inform.emit(_("[success] Done. Adding Text completed."))
  2051. def utility_geometry(self, data=None):
  2052. """
  2053. Temporary geometry on screen while using this tool.
  2054. :param data: mouse position coords
  2055. :return:
  2056. """
  2057. dx = data[0] - self.origin[0]
  2058. dy = data[1] - self.origin[1]
  2059. try:
  2060. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2061. except:
  2062. return
  2063. class FCBuffer(FCShapeTool):
  2064. def __init__(self, draw_app):
  2065. FCShapeTool.__init__(self, draw_app)
  2066. self.name = 'buffer'
  2067. # self.shape_buffer = self.draw_app.shape_buffer
  2068. self.draw_app = draw_app
  2069. self.app = draw_app.app
  2070. self.start_msg = _("Create buffer geometry ...")
  2071. self.origin = (0, 0)
  2072. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2073. self.buff_tool.run()
  2074. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2075. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2076. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2077. self.activate()
  2078. def on_buffer(self):
  2079. if not self.draw_app.selected:
  2080. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2081. return
  2082. try:
  2083. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2084. except ValueError:
  2085. # try to convert comma to decimal point. if it's still not working error message and return
  2086. try:
  2087. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2088. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2089. except ValueError:
  2090. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2091. "Add it and retry."))
  2092. return
  2093. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2094. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2095. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2096. self.draw_app.buffer(buffer_distance, join_style)
  2097. self.app.ui.notebook.setTabText(2, _("Tools"))
  2098. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2099. self.disactivate()
  2100. self.draw_app.app.inform.emit(_("[success] Done. Buffer Tool completed."))
  2101. def on_buffer_int(self):
  2102. if not self.draw_app.selected:
  2103. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2104. return
  2105. try:
  2106. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2107. except ValueError:
  2108. # try to convert comma to decimal point. if it's still not working error message and return
  2109. try:
  2110. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2111. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2112. except ValueError:
  2113. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2114. "Add it and retry."))
  2115. return
  2116. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2117. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2118. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2119. self.draw_app.buffer_int(buffer_distance, join_style)
  2120. self.app.ui.notebook.setTabText(2, _("Tools"))
  2121. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2122. self.disactivate()
  2123. self.draw_app.app.inform.emit(_("[success] Done. Buffer Int Tool completed."))
  2124. def on_buffer_ext(self):
  2125. if not self.draw_app.selected:
  2126. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2127. return
  2128. try:
  2129. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2130. except ValueError:
  2131. # try to convert comma to decimal point. if it's still not working error message and return
  2132. try:
  2133. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2134. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2135. except ValueError:
  2136. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2137. "Add it and retry."))
  2138. return
  2139. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2140. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2141. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2142. self.draw_app.buffer_ext(buffer_distance, join_style)
  2143. self.app.ui.notebook.setTabText(2, _("Tools"))
  2144. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2145. self.disactivate()
  2146. self.draw_app.app.inform.emit(_("[success] Done. Buffer Ext Tool completed."))
  2147. def activate(self):
  2148. self.buff_tool.buffer_button.clicked.disconnect()
  2149. self.buff_tool.buffer_int_button.clicked.disconnect()
  2150. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2151. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2152. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2153. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2154. def disactivate(self):
  2155. self.buff_tool.buffer_button.clicked.disconnect()
  2156. self.buff_tool.buffer_int_button.clicked.disconnect()
  2157. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2158. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2159. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2160. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2161. self.complete = True
  2162. self.draw_app.select_tool("select")
  2163. self.buff_tool.hide_tool()
  2164. class FCPaint(FCShapeTool):
  2165. def __init__(self, draw_app):
  2166. FCShapeTool.__init__(self, draw_app)
  2167. self.name = 'paint'
  2168. # self.shape_buffer = self.draw_app.shape_buffer
  2169. self.draw_app = draw_app
  2170. self.app = draw_app.app
  2171. self.start_msg = _("Create Paint geometry ...")
  2172. self.origin = (0, 0)
  2173. self.draw_app.paint_tool.run()
  2174. class FCTransform(FCShapeTool):
  2175. def __init__(self, draw_app):
  2176. FCShapeTool.__init__(self, draw_app)
  2177. self.name = 'transformation'
  2178. # self.shape_buffer = self.draw_app.shape_buffer
  2179. self.draw_app = draw_app
  2180. self.app = draw_app.app
  2181. self.start_msg = _("Shape transformations ...")
  2182. self.origin = (0, 0)
  2183. self.draw_app.transform_tool.run()
  2184. ########################
  2185. ### Main Application ###
  2186. ########################
  2187. class FlatCAMGeoEditor(QtCore.QObject):
  2188. transform_complete = QtCore.pyqtSignal()
  2189. draw_shape_idx = -1
  2190. def __init__(self, app, disabled=False):
  2191. assert isinstance(app, FlatCAMApp.App), \
  2192. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2193. super(FlatCAMGeoEditor, self).__init__()
  2194. self.app = app
  2195. self.canvas = app.plotcanvas
  2196. ## Toolbar events and properties
  2197. self.tools = {
  2198. "select": {"button": self.app.ui.geo_select_btn,
  2199. "constructor": FCSelect},
  2200. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2201. "constructor": FCArc},
  2202. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2203. "constructor": FCCircle},
  2204. "path": {"button": self.app.ui.geo_add_path_btn,
  2205. "constructor": FCPath},
  2206. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2207. "constructor": FCRectangle},
  2208. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2209. "constructor": FCPolygon},
  2210. "text": {"button": self.app.ui.geo_add_text_btn,
  2211. "constructor": FCText},
  2212. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2213. "constructor": FCBuffer},
  2214. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2215. "constructor": FCPaint},
  2216. "move": {"button": self.app.ui.geo_move_btn,
  2217. "constructor": FCMove},
  2218. "transform": {"button": self.app.ui.geo_transform_btn,
  2219. "constructor": FCTransform},
  2220. "copy": {"button": self.app.ui.geo_copy_btn,
  2221. "constructor": FCCopy}
  2222. }
  2223. ### Data
  2224. self.active_tool = None
  2225. self.storage = FlatCAMGeoEditor.make_storage()
  2226. self.utility = []
  2227. # VisPy visuals
  2228. self.fcgeometry = None
  2229. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2230. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2231. self.app.pool_recreated.connect(self.pool_recreated)
  2232. # Remove from scene
  2233. self.shapes.enabled = False
  2234. self.tool_shape.enabled = False
  2235. ## List of selected shapes.
  2236. self.selected = []
  2237. self.flat_geo = []
  2238. self.move_timer = QtCore.QTimer()
  2239. self.move_timer.setSingleShot(True)
  2240. # this var will store the state of the toolbar before starting the editor
  2241. self.toolbar_old_state = False
  2242. self.key = None # Currently pressed key
  2243. self.geo_key_modifiers = None
  2244. self.x = None # Current mouse cursor pos
  2245. self.y = None
  2246. # if we edit a multigeo geometry store here the tool number
  2247. self.multigeo_tool = None
  2248. # Current snapped mouse pos
  2249. self.snap_x = None
  2250. self.snap_y = None
  2251. self.pos = None
  2252. # signal that there is an action active like polygon or path
  2253. self.in_action = False
  2254. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2255. self.launched_from_shortcuts = False
  2256. def make_callback(thetool):
  2257. def f():
  2258. self.on_tool_select(thetool)
  2259. return f
  2260. for tool in self.tools:
  2261. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2262. self.tools[tool]["button"].setCheckable(True) # Checkable
  2263. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2264. self.app.ui.corner_snap_btn.setCheckable(True)
  2265. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2266. self.options = {
  2267. "global_gridx": 0.1,
  2268. "global_gridy": 0.1,
  2269. "global_snap_max": 0.05,
  2270. "grid_snap": True,
  2271. "corner_snap": False,
  2272. "grid_gap_link": True
  2273. }
  2274. self.app.options_read_form()
  2275. for option in self.options:
  2276. if option in self.app.options:
  2277. self.options[option] = self.app.options[option]
  2278. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2279. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2280. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2281. self.app.ui.grid_gap_link_cb.setChecked(True)
  2282. self.rtree_index = rtindex.Index()
  2283. def entry2option(option, entry):
  2284. try:
  2285. self.options[option] = float(entry.text())
  2286. except Exception as e:
  2287. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2288. return
  2289. def gridx_changed(goption, gentry):
  2290. entry2option(option=goption, entry=gentry)
  2291. # if the grid link is checked copy the value in the GridX field to GridY
  2292. if self.app.ui.grid_gap_link_cb.isChecked():
  2293. self.app.ui.grid_gap_y_entry.set_value(self.app.ui.grid_gap_x_entry.get_value())
  2294. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2295. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2296. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2297. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2298. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2299. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2300. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2301. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2302. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2303. # if using Paint store here the tool diameter used
  2304. self.paint_tooldia = None
  2305. self.paint_tool = PaintOptionsTool(self.app, self)
  2306. self.transform_tool = TransformEditorTool(self.app, self)
  2307. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2308. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2309. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2310. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2311. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2312. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2313. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2314. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2315. self.app.ui.geo_transform_menuitem.triggered.connect(self.transform_tool.run)
  2316. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2317. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2318. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2319. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2320. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2321. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2322. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2323. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2324. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2325. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2326. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2327. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2328. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2329. self.transform_complete.connect(self.on_transform_complete)
  2330. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2331. self.editor_active = False
  2332. def pool_recreated(self, pool):
  2333. self.shapes.pool = pool
  2334. self.tool_shape.pool = pool
  2335. def on_transform_complete(self):
  2336. self.delete_selected()
  2337. self.replot()
  2338. def activate(self):
  2339. # adjust the status of the menu entries related to the editor
  2340. self.app.ui.menueditedit.setDisabled(True)
  2341. self.app.ui.menueditok.setDisabled(False)
  2342. # adjust the visibility of some of the canvas context menu
  2343. self.app.ui.popmenu_edit.setVisible(False)
  2344. self.app.ui.popmenu_save.setVisible(True)
  2345. self.connect_canvas_event_handlers()
  2346. # initialize working objects
  2347. self.storage = FlatCAMGeoEditor.make_storage()
  2348. self.utility = []
  2349. self.selected = []
  2350. self.shapes.enabled = True
  2351. self.tool_shape.enabled = True
  2352. self.app.app_cursor.enabled = True
  2353. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2354. self.app.ui.corner_snap_btn.setEnabled(True)
  2355. self.app.ui.snap_magnet.setVisible(True)
  2356. self.app.ui.corner_snap_btn.setVisible(True)
  2357. self.app.ui.geo_editor_menu.setDisabled(False)
  2358. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2359. self.app.ui.update_obj_btn.setEnabled(True)
  2360. self.app.ui.g_editor_cmenu.setEnabled(True)
  2361. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2362. self.app.ui.geo_edit_toolbar.setVisible(True)
  2363. self.app.ui.snap_toolbar.setDisabled(False)
  2364. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2365. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2366. for w in sel_tab_widget_list:
  2367. w.setEnabled(False)
  2368. # Tell the App that the editor is active
  2369. self.editor_active = True
  2370. def deactivate(self):
  2371. # adjust the status of the menu entries related to the editor
  2372. self.app.ui.menueditedit.setDisabled(False)
  2373. self.app.ui.menueditok.setDisabled(True)
  2374. # adjust the visibility of some of the canvas context menu
  2375. self.app.ui.popmenu_edit.setVisible(True)
  2376. self.app.ui.popmenu_save.setVisible(False)
  2377. self.disconnect_canvas_event_handlers()
  2378. self.clear()
  2379. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2380. settings = QSettings("Open Source", "FlatCAM")
  2381. if settings.contains("layout"):
  2382. layout = settings.value('layout', type=str)
  2383. if layout == 'standard':
  2384. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2385. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2386. self.app.ui.corner_snap_btn.setEnabled(False)
  2387. self.app.ui.snap_magnet.setVisible(False)
  2388. self.app.ui.corner_snap_btn.setVisible(False)
  2389. elif layout == 'compact':
  2390. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2391. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2392. self.app.ui.corner_snap_btn.setEnabled(False)
  2393. else:
  2394. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2395. self.app.ui.snap_magnet.setVisible(False)
  2396. self.app.ui.corner_snap_btn.setVisible(False)
  2397. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2398. self.app.ui.corner_snap_btn.setEnabled(False)
  2399. # set the Editor Toolbar visibility to what was before entering in the Editor
  2400. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2401. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2402. # Disable visuals
  2403. self.shapes.enabled = False
  2404. self.tool_shape.enabled = False
  2405. self.app.app_cursor.enabled = False
  2406. self.app.ui.geo_editor_menu.setDisabled(True)
  2407. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2408. self.app.ui.update_obj_btn.setEnabled(False)
  2409. self.app.ui.g_editor_cmenu.setEnabled(False)
  2410. self.app.ui.e_editor_cmenu.setEnabled(False)
  2411. # Tell the app that the editor is no longer active
  2412. self.editor_active = False
  2413. try:
  2414. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  2415. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2416. for w in sel_tab_widget_list:
  2417. w.setEnabled(True)
  2418. except Exception as e:
  2419. log.debug("FlatCAMGeoEditor.deactivate() --> %s" % str(e))
  2420. # Show original geometry
  2421. if self.fcgeometry:
  2422. self.fcgeometry.visible = True
  2423. def connect_canvas_event_handlers(self):
  2424. ## Canvas events
  2425. # first connect to new, then disconnect the old handlers
  2426. # don't ask why but if there is nothing connected I've seen issues
  2427. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2428. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2429. self.canvas.vis_connect('mouse_release', self.on_geo_click_release)
  2430. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2431. # but those from FlatCAMGeoEditor
  2432. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2433. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2434. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2435. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2436. self.app.collection.view.clicked.disconnect()
  2437. def disconnect_canvas_event_handlers(self):
  2438. # we restore the key and mouse control to FlatCAMApp method
  2439. # first connect to new, then disconnect the old handlers
  2440. # don't ask why but if there is nothing connected I've seen issues
  2441. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2442. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2443. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2444. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2445. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2446. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2447. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2448. self.canvas.vis_disconnect('mouse_release', self.on_geo_click_release)
  2449. def add_shape(self, shape):
  2450. """
  2451. Adds a shape to the shape storage.
  2452. :param shape: Shape to be added.
  2453. :type shape: DrawToolShape
  2454. :return: None
  2455. """
  2456. # List of DrawToolShape?
  2457. if isinstance(shape, list):
  2458. for subshape in shape:
  2459. self.add_shape(subshape)
  2460. return
  2461. assert isinstance(shape, DrawToolShape), \
  2462. "Expected a DrawToolShape, got %s" % type(shape)
  2463. assert shape.geo is not None, \
  2464. "Shape object has empty geometry (None)"
  2465. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2466. not isinstance(shape.geo, list), \
  2467. "Shape objects has empty geometry ([])"
  2468. if isinstance(shape, DrawToolUtilityShape):
  2469. self.utility.append(shape)
  2470. else:
  2471. self.storage.insert(shape) # TODO: Check performance
  2472. def delete_utility_geometry(self):
  2473. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2474. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2475. for_deletion = [shape for shape in self.utility]
  2476. for shape in for_deletion:
  2477. self.delete_shape(shape)
  2478. self.tool_shape.clear(update=True)
  2479. self.tool_shape.redraw()
  2480. def cutpath(self):
  2481. selected = self.get_selected()
  2482. tools = selected[1:]
  2483. toolgeo = cascaded_union([shp.geo for shp in tools])
  2484. target = selected[0]
  2485. if type(target.geo) == Polygon:
  2486. for ring in poly2rings(target.geo):
  2487. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2488. self.delete_shape(target)
  2489. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2490. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2491. self.delete_shape(target)
  2492. elif type(target.geo) == MultiLineString:
  2493. try:
  2494. for linestring in target.geo:
  2495. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2496. except:
  2497. self.app.log.warning("Current LinearString does not intersect the target")
  2498. self.delete_shape(target)
  2499. else:
  2500. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2501. self.replot()
  2502. def toolbar_tool_toggle(self, key):
  2503. self.options[key] = self.sender().isChecked()
  2504. if self.options[key] == True:
  2505. return 1
  2506. else:
  2507. return 0
  2508. def clear(self):
  2509. self.active_tool = None
  2510. # self.shape_buffer = []
  2511. self.selected = []
  2512. self.shapes.clear(update=True)
  2513. self.tool_shape.clear(update=True)
  2514. # self.storage = FlatCAMGeoEditor.make_storage()
  2515. self.replot()
  2516. def edit_fcgeometry(self, fcgeometry, multigeo_tool=None):
  2517. """
  2518. Imports the geometry from the given FlatCAM Geometry object
  2519. into the editor.
  2520. :param fcgeometry: FlatCAMGeometry
  2521. :return: None
  2522. """
  2523. assert isinstance(fcgeometry, Geometry), \
  2524. "Expected a Geometry, got %s" % type(fcgeometry)
  2525. self.deactivate()
  2526. self.activate()
  2527. # Hide original geometry
  2528. self.fcgeometry = fcgeometry
  2529. fcgeometry.visible = False
  2530. # Set selection tolerance
  2531. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2532. self.select_tool("select")
  2533. # Link shapes into editor.
  2534. if multigeo_tool:
  2535. self.multigeo_tool = multigeo_tool
  2536. geo_to_edit = fcgeometry.flatten(geometry=fcgeometry.tools[self.multigeo_tool]['solid_geometry'])
  2537. self.app.inform.emit(_("[WARNING] Editing MultiGeo Geometry, tool: {tool} with diameter: {dia}").
  2538. format(tool=self.multigeo_tool, dia=fcgeometry.tools[self.multigeo_tool]['tooldia']))
  2539. else:
  2540. geo_to_edit = fcgeometry.flatten()
  2541. for shape in geo_to_edit:
  2542. if shape is not None: # TODO: Make flatten never create a None
  2543. if type(shape) == Polygon:
  2544. self.add_shape(DrawToolShape(shape.exterior))
  2545. for inter in shape.interiors:
  2546. self.add_shape(DrawToolShape(inter))
  2547. else:
  2548. self.add_shape(DrawToolShape(shape))
  2549. self.replot()
  2550. # start with GRID toolbar activated
  2551. if self.app.ui.grid_snap_btn.isChecked() == False:
  2552. self.app.ui.grid_snap_btn.trigger()
  2553. def on_buffer_tool(self):
  2554. buff_tool = BufferSelectionTool(self.app, self)
  2555. buff_tool.run()
  2556. def on_paint_tool(self):
  2557. paint_tool = PaintOptionsTool(self.app, self)
  2558. paint_tool.run()
  2559. def on_tool_select(self, tool):
  2560. """
  2561. Behavior of the toolbar. Tool initialization.
  2562. :rtype : None
  2563. """
  2564. self.app.log.debug("on_tool_select('%s')" % tool)
  2565. # This is to make the group behave as radio group
  2566. if tool in self.tools:
  2567. if self.tools[tool]["button"].isChecked():
  2568. self.app.log.debug("%s is checked." % tool)
  2569. for t in self.tools:
  2570. if t != tool:
  2571. self.tools[t]["button"].setChecked(False)
  2572. self.active_tool = self.tools[tool]["constructor"](self)
  2573. if not isinstance(self.active_tool, FCSelect):
  2574. self.app.inform.emit(self.active_tool.start_msg)
  2575. else:
  2576. self.app.log.debug("%s is NOT checked." % tool)
  2577. for t in self.tools:
  2578. self.tools[t]["button"].setChecked(False)
  2579. self.select_tool('select')
  2580. self.active_tool = FCSelect(self)
  2581. def draw_tool_path(self):
  2582. self.select_tool('path')
  2583. return
  2584. def draw_tool_rectangle(self):
  2585. self.select_tool('rectangle')
  2586. return
  2587. def on_grid_toggled(self):
  2588. self.toolbar_tool_toggle("grid_snap")
  2589. # make sure that the cursor shape is enabled/disabled, too
  2590. if self.options['grid_snap'] is True:
  2591. self.app.app_cursor.enabled = True
  2592. else:
  2593. self.app.app_cursor.enabled = False
  2594. def on_canvas_click(self, event):
  2595. """
  2596. event.x and .y have canvas coordinates
  2597. event.xdaya and .ydata have plot coordinates
  2598. :param event: Event object dispatched by Matplotlib
  2599. :return: None
  2600. """
  2601. if event.button is 1:
  2602. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2603. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2604. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2605. ### Snap coordinates
  2606. x, y = self.snap(self.pos[0], self.pos[1])
  2607. self.pos = (x, y)
  2608. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2609. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2610. if modifiers == QtCore.Qt.ShiftModifier:
  2611. self.app.clipboard.setText(
  2612. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2613. return
  2614. # Selection with left mouse button
  2615. if self.active_tool is not None and event.button is 1:
  2616. # Dispatch event to active_tool
  2617. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  2618. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  2619. # If it is a shape generating tool
  2620. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2621. self.on_shape_complete()
  2622. # MS: always return to the Select Tool if modifier key is not pressed
  2623. # else return to the current tool
  2624. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2625. if self.app.defaults["global_mselect_key"] == 'Control':
  2626. modifier_to_use = Qt.ControlModifier
  2627. else:
  2628. modifier_to_use = Qt.ShiftModifier
  2629. # if modifier key is pressed then we add to the selected list the current shape but if
  2630. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  2631. if key_modifier == modifier_to_use:
  2632. self.select_tool(self.active_tool.name)
  2633. else:
  2634. self.select_tool("select")
  2635. return
  2636. if isinstance(self.active_tool, FCSelect):
  2637. # self.app.log.debug("Replotting after click.")
  2638. self.replot()
  2639. else:
  2640. self.app.log.debug("No active tool to respond to click!")
  2641. def on_canvas_move(self, event):
  2642. """
  2643. Called on 'mouse_move' event
  2644. event.pos have canvas screen coordinates
  2645. :param event: Event object dispatched by VisPy SceneCavas
  2646. :return: None
  2647. """
  2648. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2649. event.xdata, event.ydata = pos[0], pos[1]
  2650. self.x = event.xdata
  2651. self.y = event.ydata
  2652. # Prevent updates on pan
  2653. # if len(event.buttons) > 0:
  2654. # return
  2655. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2656. if event.button == 2:
  2657. self.app.panning_action = True
  2658. return
  2659. else:
  2660. self.app.panning_action = False
  2661. try:
  2662. x = float(event.xdata)
  2663. y = float(event.ydata)
  2664. except TypeError:
  2665. return
  2666. if self.active_tool is None:
  2667. return
  2668. ### Snap coordinates
  2669. x, y = self.snap(x, y)
  2670. self.snap_x = x
  2671. self.snap_y = y
  2672. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2673. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2674. "<b>Y</b>: %.4f" % (x, y))
  2675. if self.pos is None:
  2676. self.pos = (0, 0)
  2677. dx = x - self.pos[0]
  2678. dy = y - self.pos[1]
  2679. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2680. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2681. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2682. ### Utility geometry (animated)
  2683. geo = self.active_tool.utility_geometry(data=(x, y))
  2684. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2685. # Remove any previous utility shape
  2686. self.tool_shape.clear(update=True)
  2687. self.draw_utility_geometry(geo=geo)
  2688. ### Selection area on canvas section ###
  2689. dx = pos[0] - self.pos[0]
  2690. if event.is_dragging == 1 and event.button == 1:
  2691. self.app.delete_selection_shape()
  2692. if dx < 0:
  2693. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  2694. color=self.app.defaults["global_alt_sel_line"],
  2695. face_color=self.app.defaults['global_alt_sel_fill'])
  2696. self.app.selection_type = False
  2697. else:
  2698. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  2699. self.app.selection_type = True
  2700. else:
  2701. self.app.selection_type = None
  2702. # Update cursor
  2703. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2704. def on_geo_click_release(self, event):
  2705. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2706. if self.app.grid_status():
  2707. pos = self.snap(pos_canvas[0], pos_canvas[1])
  2708. else:
  2709. pos = (pos_canvas[0], pos_canvas[1])
  2710. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2711. # canvas menu
  2712. try:
  2713. if event.button == 2: # right click
  2714. if self.app.panning_action is True:
  2715. self.app.panning_action = False
  2716. else:
  2717. if self.in_action is False:
  2718. self.app.cursor = QtGui.QCursor()
  2719. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2720. else:
  2721. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  2722. # right mouse click will finish the action
  2723. if isinstance(self.active_tool, FCShapeTool):
  2724. self.active_tool.click(self.snap(self.x, self.y))
  2725. self.active_tool.make()
  2726. if self.active_tool.complete:
  2727. self.on_shape_complete()
  2728. self.app.inform.emit(_("[success] Done."))
  2729. # MS: always return to the Select Tool if modifier key is not pressed
  2730. # else return to the current tool
  2731. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2732. if self.app.defaults["global_mselect_key"] == 'Control':
  2733. modifier_to_use = Qt.ControlModifier
  2734. else:
  2735. modifier_to_use = Qt.ShiftModifier
  2736. if key_modifier == modifier_to_use:
  2737. self.select_tool(self.active_tool.name)
  2738. else:
  2739. self.select_tool("select")
  2740. except Exception as e:
  2741. log.warning("Error: %s" % str(e))
  2742. return
  2743. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2744. # selection and then select a type of selection ("enclosing" or "touching")
  2745. try:
  2746. if event.button == 1: # left click
  2747. if self.app.selection_type is not None:
  2748. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2749. self.app.selection_type = None
  2750. elif isinstance(self.active_tool, FCSelect):
  2751. # Dispatch event to active_tool
  2752. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  2753. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  2754. # self.app.inform.emit(msg)
  2755. self.replot()
  2756. except Exception as e:
  2757. log.warning("Error: %s" % str(e))
  2758. return
  2759. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  2760. """
  2761. :param start_pos: mouse position when the selection LMB click was done
  2762. :param end_pos: mouse position when the left mouse button is released
  2763. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2764. :type Bool
  2765. :return:
  2766. """
  2767. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2768. self.app.delete_selection_shape()
  2769. for obj in self.storage.get_objects():
  2770. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2771. (sel_type is False and poly_selection.intersects(obj.geo)):
  2772. if self.key == self.app.defaults["global_mselect_key"]:
  2773. if obj in self.selected:
  2774. self.selected.remove(obj)
  2775. else:
  2776. # add the object to the selected shapes
  2777. self.selected.append(obj)
  2778. else:
  2779. if obj not in self.selected:
  2780. self.selected.append(obj)
  2781. self.replot()
  2782. def draw_utility_geometry(self, geo):
  2783. # Add the new utility shape
  2784. try:
  2785. # this case is for the Font Parse
  2786. for el in list(geo.geo):
  2787. if type(el) == MultiPolygon:
  2788. for poly in el:
  2789. self.tool_shape.add(
  2790. shape=poly,
  2791. color=(self.app.defaults["global_draw_color"] + '80'),
  2792. update=False,
  2793. layer=0,
  2794. tolerance=None
  2795. )
  2796. elif type(el) == MultiLineString:
  2797. for linestring in el:
  2798. self.tool_shape.add(
  2799. shape=linestring,
  2800. color=(self.app.defaults["global_draw_color"] + '80'),
  2801. update=False,
  2802. layer=0,
  2803. tolerance=None
  2804. )
  2805. else:
  2806. self.tool_shape.add(
  2807. shape=el,
  2808. color=(self.app.defaults["global_draw_color"] + '80'),
  2809. update=False,
  2810. layer=0,
  2811. tolerance=None
  2812. )
  2813. except TypeError:
  2814. self.tool_shape.add(
  2815. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2816. update=False, layer=0, tolerance=None)
  2817. self.tool_shape.redraw()
  2818. def on_delete_btn(self):
  2819. self.delete_selected()
  2820. self.replot()
  2821. def delete_selected(self):
  2822. tempref = [s for s in self.selected]
  2823. for shape in tempref:
  2824. self.delete_shape(shape)
  2825. self.selected = []
  2826. def delete_shape(self, shape):
  2827. if shape in self.utility:
  2828. self.utility.remove(shape)
  2829. return
  2830. self.storage.remove(shape)
  2831. if shape in self.selected:
  2832. self.selected.remove(shape) # TODO: Check performance
  2833. def on_move(self):
  2834. self.app.ui.geo_move_btn.setChecked(True)
  2835. self.on_tool_select('move')
  2836. def on_move_click(self):
  2837. if not self.selected:
  2838. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2839. return
  2840. self.on_move()
  2841. self.active_tool.set_origin(self.snap(self.x, self.y))
  2842. def on_copy_click(self):
  2843. if not self.selected:
  2844. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  2845. return
  2846. self.app.ui.geo_copy_btn.setChecked(True)
  2847. self.app.geo_editor.on_tool_select('copy')
  2848. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  2849. self.app.geo_editor.x, self.app.geo_editor.y))
  2850. self.app.inform.emit(_("Click on target point."))
  2851. def on_corner_snap(self):
  2852. self.app.ui.corner_snap_btn.trigger()
  2853. def get_selected(self):
  2854. """
  2855. Returns list of shapes that are selected in the editor.
  2856. :return: List of shapes.
  2857. """
  2858. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2859. return self.selected
  2860. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2861. """
  2862. Plots a geometric object or list of objects without rendering. Plotted objects
  2863. are returned as a list. This allows for efficient/animated rendering.
  2864. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2865. :param color: Shape color
  2866. :param linewidth: Width of lines in # of pixels.
  2867. :return: List of plotted elements.
  2868. """
  2869. plot_elements = []
  2870. if geometry is None:
  2871. geometry = self.active_tool.geometry
  2872. try:
  2873. for geo in geometry:
  2874. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2875. ## Non-iterable
  2876. except TypeError:
  2877. ## DrawToolShape
  2878. if isinstance(geometry, DrawToolShape):
  2879. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2880. ## Polygon: Descend into exterior and each interior.
  2881. if type(geometry) == Polygon:
  2882. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2883. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2884. if type(geometry) == LineString or type(geometry) == LinearRing:
  2885. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  2886. tolerance=self.fcgeometry.drawing_tolerance))
  2887. if type(geometry) == Point:
  2888. pass
  2889. return plot_elements
  2890. def plot_all(self):
  2891. """
  2892. Plots all shapes in the editor.
  2893. :return: None
  2894. :rtype: None
  2895. """
  2896. # self.app.log.debug("plot_all()")
  2897. self.shapes.clear(update=True)
  2898. for shape in self.storage.get_objects():
  2899. if shape.geo is None: # TODO: This shouldn't have happened
  2900. continue
  2901. if shape in self.selected:
  2902. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2903. continue
  2904. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2905. for shape in self.utility:
  2906. self.plot_shape(geometry=shape.geo, linewidth=1)
  2907. continue
  2908. self.shapes.redraw()
  2909. def replot(self):
  2910. self.plot_all()
  2911. def on_shape_complete(self):
  2912. self.app.log.debug("on_shape_complete()")
  2913. # Add shape
  2914. self.add_shape(self.active_tool.geometry)
  2915. # Remove any utility shapes
  2916. self.delete_utility_geometry()
  2917. self.tool_shape.clear(update=True)
  2918. # Replot and reset tool.
  2919. self.replot()
  2920. # self.active_tool = type(self.active_tool)(self)
  2921. @staticmethod
  2922. def make_storage():
  2923. ## Shape storage.
  2924. storage = FlatCAMRTreeStorage()
  2925. storage.get_points = DrawToolShape.get_pts
  2926. return storage
  2927. def select_tool(self, toolname):
  2928. """
  2929. Selects a drawing tool. Impacts the object and GUI.
  2930. :param toolname: Name of the tool.
  2931. :return: None
  2932. """
  2933. self.tools[toolname]["button"].setChecked(True)
  2934. self.on_tool_select(toolname)
  2935. def set_selected(self, shape):
  2936. # Remove and add to the end.
  2937. if shape in self.selected:
  2938. self.selected.remove(shape)
  2939. self.selected.append(shape)
  2940. def set_unselected(self, shape):
  2941. if shape in self.selected:
  2942. self.selected.remove(shape)
  2943. def snap(self, x, y):
  2944. """
  2945. Adjusts coordinates to snap settings.
  2946. :param x: Input coordinate X
  2947. :param y: Input coordinate Y
  2948. :return: Snapped (x, y)
  2949. """
  2950. snap_x, snap_y = (x, y)
  2951. snap_distance = Inf
  2952. ### Object (corner?) snap
  2953. ### No need for the objects, just the coordinates
  2954. ### in the index.
  2955. if self.options["corner_snap"]:
  2956. try:
  2957. nearest_pt, shape = self.storage.nearest((x, y))
  2958. nearest_pt_distance = distance((x, y), nearest_pt)
  2959. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  2960. snap_distance = nearest_pt_distance
  2961. snap_x, snap_y = nearest_pt
  2962. except (StopIteration, AssertionError):
  2963. pass
  2964. ### Grid snap
  2965. if self.options["grid_snap"]:
  2966. if self.options["global_gridx"] != 0:
  2967. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  2968. else:
  2969. snap_x_ = x
  2970. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  2971. # and it will use the snap distance from GridX entry
  2972. if self.app.ui.grid_gap_link_cb.isChecked():
  2973. if self.options["global_gridx"] != 0:
  2974. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  2975. else:
  2976. snap_y_ = y
  2977. else:
  2978. if self.options["global_gridy"] != 0:
  2979. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  2980. else:
  2981. snap_y_ = y
  2982. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  2983. if nearest_grid_distance < snap_distance:
  2984. snap_x, snap_y = (snap_x_, snap_y_)
  2985. return snap_x, snap_y
  2986. def update_fcgeometry(self, fcgeometry):
  2987. """
  2988. Transfers the geometry tool shape buffer to the selected geometry
  2989. object. The geometry already in the object are removed.
  2990. :param fcgeometry: FlatCAMGeometry
  2991. :return: None
  2992. """
  2993. if self.multigeo_tool:
  2994. fcgeometry.tools[self.multigeo_tool]['solid_geometry'] = []
  2995. # for shape in self.shape_buffer:
  2996. for shape in self.storage.get_objects():
  2997. fcgeometry.tools[self.multigeo_tool]['solid_geometry'].append(shape.geo)
  2998. self.multigeo_tool = None
  2999. else:
  3000. fcgeometry.solid_geometry = []
  3001. # for shape in self.shape_buffer:
  3002. for shape in self.storage.get_objects():
  3003. fcgeometry.solid_geometry.append(shape.geo)
  3004. def update_options(self, obj):
  3005. if self.paint_tooldia:
  3006. obj.options['cnctooldia'] = self.paint_tooldia
  3007. self.paint_tooldia = None
  3008. return True
  3009. else:
  3010. return False
  3011. def union(self):
  3012. """
  3013. Makes union of selected polygons. Original polygons
  3014. are deleted.
  3015. :return: None.
  3016. """
  3017. results = cascaded_union([t.geo for t in self.get_selected()])
  3018. # Delete originals.
  3019. for_deletion = [s for s in self.get_selected()]
  3020. for shape in for_deletion:
  3021. self.delete_shape(shape)
  3022. # Selected geometry is now gone!
  3023. self.selected = []
  3024. self.add_shape(DrawToolShape(results))
  3025. self.replot()
  3026. def intersection(self):
  3027. """
  3028. Makes intersectino of selected polygons. Original polygons are deleted.
  3029. :return: None
  3030. """
  3031. shapes = self.get_selected()
  3032. try:
  3033. results = shapes[0].geo
  3034. except Exception as e:
  3035. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3036. self.app.inform.emit(_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
  3037. self.select_tool('select')
  3038. return
  3039. for shape in shapes[1:]:
  3040. results = results.intersection(shape.geo)
  3041. # Delete originals.
  3042. for_deletion = [s for s in self.get_selected()]
  3043. for shape in for_deletion:
  3044. self.delete_shape(shape)
  3045. # Selected geometry is now gone!
  3046. self.selected = []
  3047. self.add_shape(DrawToolShape(results))
  3048. self.replot()
  3049. def subtract(self):
  3050. selected = self.get_selected()
  3051. try:
  3052. tools = selected[1:]
  3053. toolgeo = cascaded_union([shp.geo for shp in tools])
  3054. result = selected[0].geo.difference(toolgeo)
  3055. self.delete_shape(selected[0])
  3056. self.add_shape(DrawToolShape(result))
  3057. self.replot()
  3058. except Exception as e:
  3059. log.debug(str(e))
  3060. def buffer(self, buf_distance, join_style):
  3061. selected = self.get_selected()
  3062. if buf_distance < 0:
  3063. self.app.inform.emit(
  3064. _( "[ERROR_NOTCL] Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  3065. # deselect everything
  3066. self.selected = []
  3067. self.replot()
  3068. return
  3069. if len(selected) == 0:
  3070. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3071. return
  3072. if not isinstance(buf_distance, float):
  3073. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3074. # deselect everything
  3075. self.selected = []
  3076. self.replot()
  3077. return
  3078. pre_buffer = cascaded_union([t.geo for t in selected])
  3079. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3080. if results.is_empty:
  3081. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3082. # deselect everything
  3083. self.selected = []
  3084. self.replot()
  3085. return
  3086. self.add_shape(DrawToolShape(results))
  3087. self.replot()
  3088. self.app.inform.emit(_("[success] Full buffer geometry created."))
  3089. def buffer_int(self, buf_distance, join_style):
  3090. selected = self.get_selected()
  3091. if buf_distance < 0:
  3092. self.app.inform.emit(
  3093. _("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3094. "Use Buffer interior to generate an 'inside' shape")
  3095. )
  3096. # deselect everything
  3097. self.selected = []
  3098. self.replot()
  3099. return
  3100. if len(selected) == 0:
  3101. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3102. return
  3103. if not isinstance(buf_distance, float):
  3104. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3105. # deselect everything
  3106. self.selected = []
  3107. self.replot()
  3108. return
  3109. pre_buffer = cascaded_union([t.geo for t in selected])
  3110. results = pre_buffer.buffer(buf_distance + 1e-10, resolution=32, join_style=join_style)
  3111. if results.is_empty:
  3112. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a smaller buffer value."))
  3113. # deselect everything
  3114. self.selected = []
  3115. self.replot()
  3116. return
  3117. if type(results) == MultiPolygon:
  3118. for poly in results:
  3119. for interior in poly.interiors:
  3120. self.add_shape(DrawToolShape(interior))
  3121. else:
  3122. for interior in results:
  3123. self.add_shape(DrawToolShape(interior))
  3124. self.replot()
  3125. self.app.inform.emit(_("[success] Interior buffer geometry created."))
  3126. # selected = self.get_selected()
  3127. #
  3128. # if len(selected) == 0:
  3129. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3130. # return
  3131. #
  3132. # if not isinstance(buf_distance, float):
  3133. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3134. # return
  3135. #
  3136. # pre_buffer = cascaded_union([t.geo for t in selected])
  3137. # results = pre_buffer.buffer(buf_distance)
  3138. # if results.is_empty:
  3139. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3140. # return
  3141. #
  3142. # int_geo = []
  3143. # if type(results) == MultiPolygon:
  3144. # for poly in results:
  3145. # for g in poly.interiors:
  3146. # int_geo.append(g)
  3147. # res = cascaded_union(int_geo)
  3148. # self.add_shape(DrawToolShape(res))
  3149. # else:
  3150. # print(results.interiors)
  3151. # for g in results.interiors:
  3152. # int_geo.append(g)
  3153. # res = cascaded_union(int_geo)
  3154. # self.add_shape(DrawToolShape(res))
  3155. #
  3156. # self.replot()
  3157. # self.app.inform.emit("Interior buffer geometry created.")
  3158. def buffer_ext(self, buf_distance, join_style):
  3159. selected = self.get_selected()
  3160. if buf_distance < 0:
  3161. self.app.inform.emit(_("[ERROR_NOTCL] Negative buffer value is not accepted. "
  3162. "Use Buffer interior to generate an 'inside' shape"))
  3163. # deselect everything
  3164. self.selected = []
  3165. self.replot()
  3166. return
  3167. if len(selected) == 0:
  3168. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3169. return
  3170. if not isinstance(buf_distance, float):
  3171. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3172. # deselect everything
  3173. self.selected = []
  3174. self.replot()
  3175. return
  3176. pre_buffer = cascaded_union([t.geo for t in selected])
  3177. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3178. if results.is_empty:
  3179. self.app.inform.emit(_("[ERROR_NOTCL] Failed, the result is empty. Choose a different buffer value."))
  3180. # deselect everything
  3181. self.selected = []
  3182. self.replot()
  3183. return
  3184. if type(results) == MultiPolygon:
  3185. for poly in results:
  3186. self.add_shape(DrawToolShape(poly.exterior))
  3187. else:
  3188. self.add_shape(DrawToolShape(results.exterior))
  3189. self.replot()
  3190. self.app.inform.emit(_("[success] Exterior buffer geometry created."))
  3191. # def paint(self, tooldia, overlap, margin, method):
  3192. # selected = self.get_selected()
  3193. #
  3194. # if len(selected) == 0:
  3195. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3196. # return
  3197. #
  3198. # for param in [tooldia, overlap, margin]:
  3199. # if not isinstance(param, float):
  3200. # param_name = [k for k, v in locals().items() if v is param][0]
  3201. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3202. #
  3203. # # Todo: Check for valid method.
  3204. #
  3205. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3206. #
  3207. # results = []
  3208. #
  3209. # def recurse(geo):
  3210. # try:
  3211. # for subg in geo:
  3212. # for subsubg in recurse(subg):
  3213. # yield subsubg
  3214. # except TypeError:
  3215. # if isinstance(geo, LinearRing):
  3216. # yield geo
  3217. #
  3218. # raise StopIteration
  3219. #
  3220. # for geo in selected:
  3221. # print(type(geo.geo))
  3222. #
  3223. # local_results = []
  3224. # for poly in recurse(geo.geo):
  3225. # if method == "seed":
  3226. # # Type(cp) == FlatCAMRTreeStorage | None
  3227. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3228. # tooldia, overlap=overlap)
  3229. #
  3230. # else:
  3231. # # Type(cp) == FlatCAMRTreeStorage | None
  3232. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3233. # tooldia, overlap=overlap)
  3234. #
  3235. # if cp is not None:
  3236. # local_results += list(cp.get_objects())
  3237. #
  3238. # results.append(cascaded_union(local_results))
  3239. #
  3240. # # This is a dirty patch:
  3241. # for r in results:
  3242. # self.add_shape(DrawToolShape(r))
  3243. #
  3244. # self.replot()
  3245. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3246. self.paint_tooldia = tooldia
  3247. selected = self.get_selected()
  3248. if len(selected) == 0:
  3249. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for painting."))
  3250. return
  3251. for param in [tooldia, overlap, margin]:
  3252. if not isinstance(param, float):
  3253. param_name = [k for k, v in locals().items() if v is param][0]
  3254. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3255. results = []
  3256. if overlap >= 1:
  3257. self.app.inform.emit(
  3258. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3259. return
  3260. def recurse(geometry, reset=True):
  3261. """
  3262. Creates a list of non-iterable linear geometry objects.
  3263. Results are placed in self.flat_geometry
  3264. :param geometry: Shapely type or list or list of list of such.
  3265. :param reset: Clears the contents of self.flat_geometry.
  3266. """
  3267. if geometry is None:
  3268. return
  3269. if reset:
  3270. self.flat_geo = []
  3271. ## If iterable, expand recursively.
  3272. try:
  3273. for geo in geometry:
  3274. if geo is not None:
  3275. recurse(geometry=geo, reset=False)
  3276. ## Not iterable, do the actual indexing and add.
  3277. except TypeError:
  3278. self.flat_geo.append(geometry)
  3279. return self.flat_geo
  3280. for geo in selected:
  3281. local_results = []
  3282. for geo_obj in recurse(geo.geo):
  3283. try:
  3284. if type(geo_obj) == Polygon:
  3285. poly_buf = geo_obj.buffer(-margin)
  3286. else:
  3287. poly_buf = Polygon(geo_obj).buffer(-margin)
  3288. if method == "seed":
  3289. cp = Geometry.clear_polygon2(poly_buf,
  3290. tooldia, self.app.defaults["geometry_circle_steps"],
  3291. overlap=overlap, contour=contour, connect=connect)
  3292. elif method == "lines":
  3293. cp = Geometry.clear_polygon3(poly_buf,
  3294. tooldia, self.app.defaults["geometry_circle_steps"],
  3295. overlap=overlap, contour=contour, connect=connect)
  3296. else:
  3297. cp = Geometry.clear_polygon(poly_buf,
  3298. tooldia, self.app.defaults["geometry_circle_steps"],
  3299. overlap=overlap, contour=contour, connect=connect)
  3300. if cp is not None:
  3301. local_results += list(cp.get_objects())
  3302. except Exception as e:
  3303. log.debug("Could not Paint the polygons. %s" % str(e))
  3304. self.app.inform.emit(
  3305. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3306. "Or a different method of Paint\n%s") % str(e))
  3307. return
  3308. # add the result to the results list
  3309. results.append(cascaded_union(local_results))
  3310. # This is a dirty patch:
  3311. for r in results:
  3312. self.add_shape(DrawToolShape(r))
  3313. self.app.inform.emit(
  3314. _("[success] Paint done."))
  3315. self.replot()
  3316. def distance(pt1, pt2):
  3317. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3318. def mag(vec):
  3319. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  3320. def poly2rings(poly):
  3321. return [poly.exterior] + [interior for interior in poly.interiors]