FlatCAMGeoEditor.py 149 KB

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