FlatCAMObj.py 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215
  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. from io import StringIO
  9. from PyQt5 import QtCore, QtGui
  10. from PyQt5.QtCore import Qt
  11. from copy import copy, deepcopy
  12. import inspect # TODO: For debugging only.
  13. from shapely.geometry.base import JOIN_STYLE
  14. from datetime import datetime
  15. import FlatCAMApp
  16. from ObjectUI import *
  17. from FlatCAMCommon import LoudDict
  18. from FlatCAMEditor import FlatCAMGeoEditor
  19. from camlib import *
  20. from VisPyVisuals import ShapeCollectionVisual
  21. import itertools
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. class ObjectDeleted(Exception):
  24. pass
  25. class ValidationError(Exception):
  26. def __init__(self, message, errors):
  27. super().__init__(message)
  28. self.errors = errors
  29. ########################################
  30. ## FlatCAMObj ##
  31. ########################################
  32. class FlatCAMObj(QtCore.QObject):
  33. """
  34. Base type of objects handled in FlatCAM. These become interactive
  35. in the GUI, can be plotted, and their options can be modified
  36. by the user in their respective forms.
  37. """
  38. # Instance of the application to which these are related.
  39. # The app should set this value.
  40. app = None
  41. def __init__(self, name):
  42. """
  43. Constructor.
  44. :param name: Name of the object given by the user.
  45. :return: FlatCAMObj
  46. """
  47. QtCore.QObject.__init__(self)
  48. # View
  49. self.ui = None
  50. self.options = LoudDict(name=name)
  51. self.options.set_change_callback(self.on_options_change)
  52. self.form_fields = {}
  53. self.kind = None # Override with proper name
  54. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  55. self.shapes = self.app.plotcanvas.new_shape_group()
  56. self.item = None # Link with project view item
  57. self.muted_ui = False
  58. self.deleted = False
  59. self._drawing_tolerance = 0.01
  60. # assert isinstance(self.ui, ObjectUI)
  61. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  62. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  63. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  64. def __del__(self):
  65. pass
  66. def __str__(self):
  67. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  68. def from_dict(self, d):
  69. """
  70. This supersedes ``from_dict`` in derived classes. Derived classes
  71. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  72. ``self.options`` is only updated, not overwritten. This ensures that
  73. options set by the app do not vanish when reading the objects
  74. from a project file.
  75. :param d: Dictionary with attributes to set.
  76. :return: None
  77. """
  78. for attr in self.ser_attrs:
  79. if attr == 'options':
  80. self.options.update(d[attr])
  81. else:
  82. setattr(self, attr, d[attr])
  83. def on_options_change(self, key):
  84. # Update form on programmatically options change
  85. self.set_form_item(key)
  86. # Set object visibility
  87. if key == 'plot':
  88. self.visible = self.options['plot']
  89. # self.emit(QtCore.SIGNAL("optionChanged"), key)
  90. self.optionChanged.emit(key)
  91. def set_ui(self, ui):
  92. self.ui = ui
  93. self.form_fields = {"name": self.ui.name_entry}
  94. assert isinstance(self.ui, ObjectUI)
  95. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  96. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  97. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  98. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  99. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  100. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  101. def build_ui(self):
  102. """
  103. Sets up the UI/form for this object. Show the UI
  104. in the App.
  105. :return: None
  106. :rtype: None
  107. """
  108. self.muted_ui = True
  109. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  110. # Remove anything else in the box
  111. # box_children = self.app.ui.notebook.selected_contents.get_children()
  112. # for child in box_children:
  113. # self.app.ui.notebook.selected_contents.remove(child)
  114. # while self.app.ui.selected_layout.count():
  115. # self.app.ui.selected_layout.takeAt(0)
  116. # Put in the UI
  117. # box_selected.pack_start(sw, True, True, 0)
  118. # self.app.ui.notebook.selected_contents.add(self.ui)
  119. # self.app.ui.selected_layout.addWidget(self.ui)
  120. try:
  121. self.app.ui.selected_scroll_area.takeWidget()
  122. except:
  123. self.app.log.debug("Nothing to remove")
  124. self.app.ui.selected_scroll_area.setWidget(self.ui)
  125. self.muted_ui = False
  126. def on_name_activate(self):
  127. old_name = copy(self.options["name"])
  128. new_name = self.ui.name_entry.get_value()
  129. # update the SHELL auto-completer model data
  130. try:
  131. self.app.myKeywords.remove(old_name)
  132. self.app.myKeywords.append(new_name)
  133. self.app.shell._edit.set_model_data(self.app.myKeywords)
  134. except:
  135. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  136. self.options["name"] = self.ui.name_entry.get_value()
  137. self.app.inform.emit("[success]Name changed from %s to %s" % (old_name, new_name))
  138. def on_offset_button_click(self):
  139. self.app.report_usage("obj_on_offset_button")
  140. self.read_form()
  141. vect = self.ui.offsetvector_entry.get_value()
  142. self.offset(vect)
  143. self.plot()
  144. self.app.object_changed.emit(self)
  145. def on_scale_button_click(self):
  146. self.app.report_usage("obj_on_scale_button")
  147. self.read_form()
  148. factor = self.ui.scale_entry.get_value()
  149. self.scale(factor)
  150. self.plot()
  151. self.app.object_changed.emit(self)
  152. def on_skew_button_click(self):
  153. self.app.report_usage("obj_on_skew_button")
  154. self.read_form()
  155. xangle = self.ui.xangle_entry.get_value()
  156. yangle = self.ui.yangle_entry.get_value()
  157. self.skew(xangle, yangle)
  158. self.plot()
  159. self.app.object_changed.emit(self)
  160. def to_form(self):
  161. """
  162. Copies options to the UI form.
  163. :return: None
  164. """
  165. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  166. for option in self.options:
  167. try:
  168. self.set_form_item(option)
  169. except:
  170. self.app.log.warning("Unexpected error:", sys.exc_info())
  171. def read_form(self):
  172. """
  173. Reads form into ``self.options``.
  174. :return: None
  175. :rtype: None
  176. """
  177. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  178. for option in self.options:
  179. try:
  180. self.read_form_item(option)
  181. except:
  182. self.app.log.warning("Unexpected error:", sys.exc_info())
  183. def set_form_item(self, option):
  184. """
  185. Copies the specified option to the UI form.
  186. :param option: Name of the option (Key in ``self.options``).
  187. :type option: str
  188. :return: None
  189. """
  190. try:
  191. self.form_fields[option].set_value(self.options[option])
  192. except KeyError:
  193. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  194. pass
  195. def read_form_item(self, option):
  196. """
  197. Reads the specified option from the UI form into ``self.options``.
  198. :param option: Name of the option.
  199. :type option: str
  200. :return: None
  201. """
  202. try:
  203. self.options[option] = self.form_fields[option].get_value()
  204. except KeyError:
  205. self.app.log.warning("Failed to read option from field: %s" % option)
  206. def plot(self):
  207. """
  208. Plot this object (Extend this method to implement the actual plotting).
  209. Call this in descendants before doing the plotting.
  210. :return: Whether to continue plotting or not depending on the "plot" option.
  211. :rtype: bool
  212. """
  213. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  214. if self.deleted:
  215. return False
  216. self.clear()
  217. return True
  218. def serialize(self):
  219. """
  220. Returns a representation of the object as a dictionary so
  221. it can be later exported as JSON. Override this method.
  222. :return: Dictionary representing the object
  223. :rtype: dict
  224. """
  225. return
  226. def deserialize(self, obj_dict):
  227. """
  228. Re-builds an object from its serialized version.
  229. :param obj_dict: Dictionary representing a FlatCAMObj
  230. :type obj_dict: dict
  231. :return: None
  232. """
  233. return
  234. def add_shape(self, **kwargs):
  235. if self.deleted:
  236. raise ObjectDeleted()
  237. else:
  238. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  239. return key
  240. @property
  241. def visible(self):
  242. return self.shapes.visible
  243. @visible.setter
  244. def visible(self, value):
  245. self.shapes.visible = value
  246. # Not all object types has annotations
  247. try:
  248. self.annotation.visible = value
  249. except AttributeError:
  250. pass
  251. @property
  252. def drawing_tolerance(self):
  253. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  254. @drawing_tolerance.setter
  255. def drawing_tolerance(self, value):
  256. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  257. def clear(self, update=False):
  258. self.shapes.clear(update)
  259. # Not all object types has annotations
  260. try:
  261. self.annotation.clear(update)
  262. except AttributeError:
  263. pass
  264. def delete(self):
  265. # Free resources
  266. del self.ui
  267. del self.options
  268. # Set flag
  269. self.deleted = True
  270. class FlatCAMGerber(FlatCAMObj, Gerber):
  271. """
  272. Represents Gerber code.
  273. """
  274. optionChanged = QtCore.pyqtSignal(str)
  275. ui_type = GerberObjectUI
  276. @staticmethod
  277. def merge(grb_list, grb_final):
  278. """
  279. Merges the geometry of objects in geo_list into
  280. the geometry of geo_final.
  281. :param grb_list: List of FlatCAMGerber Objects to join.
  282. :param grb_final: Destination FlatCAMGeometry object.
  283. :return: None
  284. """
  285. if grb_final.solid_geometry is None:
  286. grb_final.solid_geometry = []
  287. if type(grb_final.solid_geometry) is not list:
  288. grb_final.solid_geometry = [grb_final.solid_geometry]
  289. for grb in grb_list:
  290. for option in grb.options:
  291. if option is not 'name':
  292. try:
  293. grb_final.options[option] = grb.options[option]
  294. except:
  295. log.warning("Failed to copy option.", option)
  296. # Expand lists
  297. if type(grb) is list:
  298. FlatCAMGerber.merge(grb, grb_final)
  299. # If not list, just append
  300. else:
  301. grb_final.solid_geometry.append(grb.solid_geometry)
  302. def __init__(self, name):
  303. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  304. FlatCAMObj.__init__(self, name)
  305. self.kind = "gerber"
  306. # The 'name' is already in self.options from FlatCAMObj
  307. # Automatically updates the UI
  308. self.options.update({
  309. "plot": True,
  310. "multicolored": False,
  311. "solid": False,
  312. "isotooldia": 0.016,
  313. "isopasses": 1,
  314. "isooverlap": 0.15,
  315. "milling_type": "cl",
  316. "combine_passes": True,
  317. "ncctools": "1.0, 0.5",
  318. "nccoverlap": 0.4,
  319. "nccmargin": 1,
  320. "noncoppermargin": 0.0,
  321. "noncopperrounded": False,
  322. "bboxmargin": 0.0,
  323. "bboxrounded": False
  324. })
  325. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  326. self.iso_type = 2
  327. # Attributes to be included in serialization
  328. # Always append to it because it carries contents
  329. # from predecessors.
  330. self.ser_attrs += ['options', 'kind']
  331. self.multigeo = False
  332. # assert isinstance(self.ui, GerberObjectUI)
  333. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  334. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  335. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  336. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  337. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  338. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  339. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  340. def set_ui(self, ui):
  341. """
  342. Maps options with GUI inputs.
  343. Connects GUI events to methods.
  344. :param ui: GUI object.
  345. :type ui: GerberObjectUI
  346. :return: None
  347. """
  348. FlatCAMObj.set_ui(self, ui)
  349. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  350. self.form_fields.update({
  351. "plot": self.ui.plot_cb,
  352. "multicolored": self.ui.multicolored_cb,
  353. "solid": self.ui.solid_cb,
  354. "isotooldia": self.ui.iso_tool_dia_entry,
  355. "isopasses": self.ui.iso_width_entry,
  356. "isooverlap": self.ui.iso_overlap_entry,
  357. "milling_type": self.ui.milling_type_radio,
  358. "combine_passes": self.ui.combine_passes_cb,
  359. "noncoppermargin": self.ui.noncopper_margin_entry,
  360. "noncopperrounded": self.ui.noncopper_rounded_cb,
  361. "bboxmargin": self.ui.bbmargin_entry,
  362. "bboxrounded": self.ui.bbrounded_cb
  363. })
  364. # Fill form fields only on object create
  365. self.to_form()
  366. assert isinstance(self.ui, GerberObjectUI)
  367. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  368. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  369. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  370. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  371. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  372. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  373. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  374. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  375. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  376. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  377. def on_generatenoncopper_button_click(self, *args):
  378. self.app.report_usage("gerber_on_generatenoncopper_button")
  379. self.read_form()
  380. name = self.options["name"] + "_noncopper"
  381. def geo_init(geo_obj, app_obj):
  382. assert isinstance(geo_obj, FlatCAMGeometry)
  383. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  384. if not self.options["noncopperrounded"]:
  385. bounding_box = bounding_box.envelope
  386. non_copper = bounding_box.difference(self.solid_geometry)
  387. geo_obj.solid_geometry = non_copper
  388. # TODO: Check for None
  389. self.app.new_object("geometry", name, geo_init)
  390. def on_generatebb_button_click(self, *args):
  391. self.app.report_usage("gerber_on_generatebb_button")
  392. self.read_form()
  393. name = self.options["name"] + "_bbox"
  394. def geo_init(geo_obj, app_obj):
  395. assert isinstance(geo_obj, FlatCAMGeometry)
  396. # Bounding box with rounded corners
  397. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  398. if not self.options["bboxrounded"]: # Remove rounded corners
  399. bounding_box = bounding_box.envelope
  400. geo_obj.solid_geometry = bounding_box
  401. self.app.new_object("geometry", name, geo_init)
  402. def on_ext_iso_button_click(self, *args):
  403. if self.ui.follow_cb.get_value() == True:
  404. obj = self.app.collection.get_active()
  405. obj.follow()
  406. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  407. obj.ui.plot_cb.toggle()
  408. else:
  409. self.app.report_usage("gerber_on_iso_button")
  410. self.read_form()
  411. self.isolate(iso_type=0)
  412. def on_int_iso_button_click(self, *args):
  413. if self.ui.follow_cb.get_value() == True:
  414. obj = self.app.collection.get_active()
  415. obj.follow()
  416. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  417. obj.ui.plot_cb.toggle()
  418. else:
  419. self.app.report_usage("gerber_on_iso_button")
  420. self.read_form()
  421. self.isolate(iso_type=1)
  422. def on_iso_button_click(self, *args):
  423. if self.ui.follow_cb.get_value() == True:
  424. obj = self.app.collection.get_active()
  425. obj.follow()
  426. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  427. obj.ui.plot_cb.toggle()
  428. else:
  429. self.app.report_usage("gerber_on_iso_button")
  430. self.read_form()
  431. self.isolate()
  432. def follow(self, outname=None):
  433. """
  434. Creates a geometry object "following" the gerber paths.
  435. :return: None
  436. """
  437. # default_name = self.options["name"] + "_follow"
  438. # follow_name = outname or default_name
  439. if outname is None:
  440. follow_name = self.options["name"] + "_follow"
  441. else:
  442. follow_name = outname
  443. def follow_init(follow_obj, app):
  444. # Propagate options
  445. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  446. follow_obj.solid_geometry = self.solid_geometry
  447. # TODO: Do something if this is None. Offer changing name?
  448. try:
  449. self.app.new_object("geometry", follow_name, follow_init)
  450. except Exception as e:
  451. return "Operation failed: %s" % str(e)
  452. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  453. outname=None, combine=None, milling_type=None):
  454. """
  455. Creates an isolation routing geometry object in the project.
  456. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  457. :param dia: Tool diameter
  458. :param passes: Number of tool widths to cut
  459. :param overlap: Overlap between passes in fraction of tool diameter
  460. :param outname: Base name of the output object
  461. :return: None
  462. """
  463. if dia is None:
  464. dia = self.options["isotooldia"]
  465. if passes is None:
  466. passes = int(self.options["isopasses"])
  467. if overlap is None:
  468. overlap = self.options["isooverlap"]
  469. if combine is None:
  470. combine = self.options["combine_passes"]
  471. else:
  472. combine = bool(combine)
  473. if milling_type is None:
  474. milling_type = self.options["milling_type"]
  475. if iso_type is None:
  476. self.iso_type = 2
  477. else:
  478. self.iso_type = iso_type
  479. base_name = self.options["name"] + "_iso"
  480. base_name = outname or base_name
  481. def generate_envelope(offset, invert, envelope_iso_type=2):
  482. # isolation_geometry produces an envelope that is going on the left of the geometry
  483. # (the copper features). To leave the least amount of burrs on the features
  484. # the tool needs to travel on the right side of the features (this is called conventional milling)
  485. # the first pass is the one cutting all of the features, so it needs to be reversed
  486. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  487. # to cut on the right side of the left over copper i.e on the left side of the features.
  488. try:
  489. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type)
  490. except Exception as e:
  491. log.debug(str(e))
  492. return 'fail'
  493. if invert:
  494. try:
  495. if type(geom) is MultiPolygon:
  496. pl = []
  497. for p in geom:
  498. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  499. geom = MultiPolygon(pl)
  500. elif type(geom) is Polygon:
  501. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  502. else:
  503. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  504. except Exception as e:
  505. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  506. return geom
  507. if combine:
  508. if self.iso_type == 0:
  509. iso_name = self.options["name"] + "_ext_iso"
  510. elif self.iso_type == 1:
  511. iso_name = self.options["name"] + "_int_iso"
  512. else:
  513. iso_name = base_name
  514. # TODO: This is ugly. Create way to pass data into init function.
  515. def iso_init(geo_obj, app_obj):
  516. # Propagate options
  517. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  518. geo_obj.solid_geometry = []
  519. for i in range(passes):
  520. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  521. # if milling type is climb then the move is counter-clockwise around features
  522. if milling_type == 'cl':
  523. # geom = generate_envelope (offset, i == 0)
  524. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type)
  525. else:
  526. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type)
  527. geo_obj.solid_geometry.append(geom)
  528. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  529. # or just looking in the lists (they are one level depth) and if any is not empty
  530. # proceed with object creation, if there are empty and the number of them is the length
  531. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  532. empty_cnt = 0
  533. if not isinstance(geo_obj.solid_geometry, list):
  534. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  535. for g in geo_obj.solid_geometry:
  536. if g:
  537. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  538. break
  539. else:
  540. empty_cnt += 1
  541. if empty_cnt == len(geo_obj.solid_geometry):
  542. raise ValidationError("Empty Geometry", None)
  543. geo_obj.multigeo = False
  544. # TODO: Do something if this is None. Offer changing name?
  545. self.app.new_object("geometry", iso_name, iso_init)
  546. else:
  547. for i in range(passes):
  548. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  549. if passes > 1:
  550. if self.iso_type == 0:
  551. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  552. elif self.iso_type == 1:
  553. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  554. else:
  555. iso_name = base_name + str(i + 1)
  556. else:
  557. if self.iso_type == 0:
  558. iso_name = self.options["name"] + "_ext_iso"
  559. elif self.iso_type == 1:
  560. iso_name = self.options["name"] + "_int_iso"
  561. else:
  562. iso_name = base_name
  563. # TODO: This is ugly. Create way to pass data into init function.
  564. def iso_init(geo_obj, app_obj):
  565. # Propagate options
  566. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  567. # if milling type is climb then the move is counter-clockwise around features
  568. if milling_type == 'cl':
  569. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  570. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type)
  571. else:
  572. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type)
  573. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  574. # or just looking in the lists (they are one level depth) and if any is not empty
  575. # proceed with object creation, if there are empty and the number of them is the length
  576. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  577. empty_cnt = 0
  578. if not isinstance(geo_obj.solid_geometry, list):
  579. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  580. for g in geo_obj.solid_geometry:
  581. if g:
  582. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  583. break
  584. else:
  585. empty_cnt += 1
  586. if empty_cnt == len(geo_obj.solid_geometry):
  587. raise ValidationError("Empty Geometry", None)
  588. geo_obj.multigeo = False
  589. # TODO: Do something if this is None. Offer changing name?
  590. self.app.new_object("geometry", iso_name, iso_init)
  591. def on_plot_cb_click(self, *args):
  592. if self.muted_ui:
  593. return
  594. self.read_form_item('plot')
  595. def on_solid_cb_click(self, *args):
  596. if self.muted_ui:
  597. return
  598. self.read_form_item('solid')
  599. self.plot()
  600. def on_multicolored_cb_click(self, *args):
  601. if self.muted_ui:
  602. return
  603. self.read_form_item('multicolored')
  604. self.plot()
  605. def convert_units(self, units):
  606. """
  607. Converts the units of the object by scaling dimensions in all geometry
  608. and options.
  609. :param units: Units to which to convert the object: "IN" or "MM".
  610. :type units: str
  611. :return: None
  612. :rtype: None
  613. """
  614. factor = Gerber.convert_units(self, units)
  615. self.options['isotooldia'] *= factor
  616. self.options['cutoutmargin'] *= factor
  617. self.options['cutoutgapsize'] *= factor
  618. self.options['noncoppermargin'] *= factor
  619. self.options['bboxmargin'] *= factor
  620. def plot(self, **kwargs):
  621. """
  622. :param kwargs: color and face_color
  623. :return:
  624. """
  625. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  626. # Does all the required setup and returns False
  627. # if the 'ptint' option is set to False.
  628. if not FlatCAMObj.plot(self):
  629. return
  630. if 'color' in kwargs:
  631. color = kwargs['color']
  632. else:
  633. color = self.app.defaults['global_plot_line']
  634. if 'face_color' in kwargs:
  635. face_color = kwargs['face_color']
  636. else:
  637. face_color = self.app.defaults['global_plot_fill']
  638. geometry = self.solid_geometry
  639. # Make sure geometry is iterable.
  640. try:
  641. _ = iter(geometry)
  642. except TypeError:
  643. geometry = [geometry]
  644. def random_color():
  645. color = np.random.rand(4)
  646. color[3] = 1
  647. return color
  648. try:
  649. if self.options["solid"]:
  650. for g in geometry:
  651. if type(g) == Polygon or type(g) == LineString:
  652. self.add_shape(shape=g, color=color,
  653. face_color=random_color() if self.options['multicolored']
  654. else face_color, visible=self.options['plot'])
  655. else:
  656. for el in g:
  657. self.add_shape(shape=el, color=color,
  658. face_color=random_color() if self.options['multicolored']
  659. else face_color, visible=self.options['plot'])
  660. else:
  661. for g in geometry:
  662. if type(g) == Polygon or type(g) == LineString:
  663. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  664. visible=self.options['plot'])
  665. else:
  666. for el in g:
  667. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  668. visible=self.options['plot'])
  669. self.shapes.redraw()
  670. except (ObjectDeleted, AttributeError):
  671. self.shapes.clear(update=True)
  672. def serialize(self):
  673. return {
  674. "options": self.options,
  675. "kind": self.kind
  676. }
  677. class FlatCAMExcellon(FlatCAMObj, Excellon):
  678. """
  679. Represents Excellon/Drill code.
  680. """
  681. ui_type = ExcellonObjectUI
  682. optionChanged = QtCore.pyqtSignal(str)
  683. def __init__(self, name):
  684. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  685. FlatCAMObj.__init__(self, name)
  686. self.kind = "excellon"
  687. self.options.update({
  688. "plot": True,
  689. "solid": False,
  690. "drillz": -0.1,
  691. "travelz": 0.1,
  692. "feedrate": 5.0,
  693. "feedrate_rapid": 5.0,
  694. "tooldia": 0.1,
  695. "slot_tooldia": 0.1,
  696. "toolchange": False,
  697. "toolchangez": 1.0,
  698. "toolchangexy": "0.0, 0.0",
  699. "endz": 2.0,
  700. "startz": None,
  701. "spindlespeed": None,
  702. "dwell": True,
  703. "dwelltime": 1000,
  704. "ppname_e": 'defaults',
  705. "optimization_type": "R",
  706. "gcode_type": "drills"
  707. })
  708. # TODO: Document this.
  709. self.tool_cbs = {}
  710. # Attributes to be included in serialization
  711. # Always append to it because it carries contents
  712. # from predecessors.
  713. self.ser_attrs += ['options', 'kind']
  714. # variable to store the total amount of drills per job
  715. self.tot_drill_cnt = 0
  716. self.tool_row = 0
  717. # variable to store the total amount of slots per job
  718. self.tot_slot_cnt = 0
  719. self.tool_row_slots = 0
  720. self.multigeo = False
  721. @staticmethod
  722. def merge(exc_list, exc_final):
  723. """
  724. Merge Excellon objects found in exc_list parameter into exc_final object.
  725. Options are always copied from source .
  726. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  727. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  728. tool_name to be used in the final Excellon object, exc_final.
  729. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  730. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  731. :param exc_final: Destination FlatCAMExcellon object.
  732. :return: None
  733. """
  734. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  735. flag_order = False
  736. try:
  737. flattened_list = list(itertools.chain(*exc_list))
  738. except TypeError:
  739. flattened_list = exc_list
  740. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  741. # values will be list of Shapely Points; for drills
  742. custom_dict_drills = {}
  743. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  744. # values will be list of Shapely Points; for slots
  745. custom_dict_slots = {}
  746. for exc in flattened_list:
  747. # copy options of the current excellon obj to the final excellon obj
  748. for option in exc.options:
  749. if option is not 'name':
  750. try:
  751. exc_final.options[option] = exc.options[option]
  752. except:
  753. exc.app.log.warning("Failed to copy option.", option)
  754. for drill in exc.drills:
  755. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  756. if exc_tool_dia not in custom_dict_drills:
  757. custom_dict_drills[exc_tool_dia] = [drill['point']]
  758. else:
  759. custom_dict_drills[exc_tool_dia].append(drill['point'])
  760. for slot in exc.slots:
  761. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  762. if exc_tool_dia not in custom_dict_slots:
  763. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  764. else:
  765. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  766. # add the zeros and units to the exc_final object
  767. exc_final.zeros = exc.zeros
  768. exc_final.units = exc.units
  769. # variable to make tool_name for the tools
  770. current_tool = 0
  771. # Here we add data to the exc_final object
  772. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  773. # drills
  774. for tool_dia in custom_dict_drills:
  775. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  776. current_tool += 1
  777. tool_name = str(current_tool)
  778. spec = {"C": float(tool_dia)}
  779. exc_final.tools[tool_name] = spec
  780. # rebuild the drills list of dict's that belong to the exc_final object
  781. for point in custom_dict_drills[tool_dia]:
  782. exc_final.drills.append(
  783. {
  784. "point": point,
  785. "tool": str(current_tool)
  786. }
  787. )
  788. # Here we add data to the exc_final object
  789. # the tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  790. # of two Shapely Points in case of slots
  791. for tool_dia in custom_dict_slots:
  792. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  793. # but only if there are no drills
  794. if not exc_final.tools:
  795. current_tool += 1
  796. tool_name = str(current_tool)
  797. spec = {"C": float(tool_dia)}
  798. exc_final.tools[tool_name] = spec
  799. else:
  800. dia_list = []
  801. for v in exc_final.tools.values():
  802. dia_list.append(float(v["C"]))
  803. if tool_dia not in dia_list:
  804. flag_order = True
  805. current_tool = len(dia_list) + 1
  806. tool_name = str(current_tool)
  807. spec = {"C": float(tool_dia)}
  808. exc_final.tools[tool_name] = spec
  809. else:
  810. for k, v in exc_final.tools.items():
  811. if v["C"] == tool_dia:
  812. current_tool = int(k)
  813. break
  814. # rebuild the slots list of dict's that belong to the exc_final object
  815. for point in custom_dict_slots[tool_dia]:
  816. exc_final.slots.append(
  817. {
  818. "start": point[0],
  819. "stop": point[1],
  820. "tool": str(current_tool)
  821. }
  822. )
  823. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  824. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  825. current_tool = 0
  826. if flag_order is True:
  827. dia_list = []
  828. temp_drills = []
  829. temp_slots = []
  830. temp_tools = {}
  831. for v in exc_final.tools.values():
  832. dia_list.append(float(v["C"]))
  833. dia_list.sort()
  834. for ordered_dia in dia_list:
  835. current_tool += 1
  836. tool_name_temp = str(current_tool)
  837. spec_temp = {"C": float(ordered_dia)}
  838. temp_tools[tool_name_temp] = spec_temp
  839. for drill in exc_final.drills:
  840. exc_tool_dia = float('%.3f' % exc_final.tools[drill['tool']]['C'])
  841. if exc_tool_dia == ordered_dia:
  842. temp_drills.append(
  843. {
  844. "point": drill["point"],
  845. "tool": str(current_tool)
  846. }
  847. )
  848. for slot in exc_final.slots:
  849. slot_tool_dia = float('%.3f' % exc_final.tools[slot['tool']]['C'])
  850. if slot_tool_dia == ordered_dia:
  851. temp_slots.append(
  852. {
  853. "start": slot["start"],
  854. "stop": slot["stop"],
  855. "tool": str(current_tool)
  856. }
  857. )
  858. # delete the exc_final tools, drills and slots
  859. exc_final.tools = dict()
  860. exc_final.drills[:] = []
  861. exc_final.slots[:] = []
  862. # update the exc_final tools, drills and slots with the ordered values
  863. exc_final.tools = temp_tools
  864. exc_final.drills[:] = temp_drills
  865. exc_final.slots[:] = temp_slots
  866. # create the geometry for the exc_final object
  867. exc_final.create_geometry()
  868. def build_ui(self):
  869. FlatCAMObj.build_ui(self)
  870. n = len(self.tools)
  871. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  872. self.ui.tools_table.setRowCount(n + 2)
  873. self.tot_drill_cnt = 0
  874. self.tot_slot_cnt = 0
  875. self.tool_row = 0
  876. sort = []
  877. for k, v in list(self.tools.items()):
  878. sort.append((k, v.get('C')))
  879. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  880. tools = [i[0] for i in sorted_tools]
  881. for tool_no in tools:
  882. drill_cnt = 0 # variable to store the nr of drills per tool
  883. slot_cnt = 0 # variable to store the nr of slots per tool
  884. # Find no of drills for the current tool
  885. for drill in self.drills:
  886. if drill['tool'] == tool_no:
  887. drill_cnt += 1
  888. self.tot_drill_cnt += drill_cnt
  889. # Find no of slots for the current tool
  890. for slot in self.slots:
  891. if slot['tool'] == tool_no:
  892. slot_cnt += 1
  893. self.tot_slot_cnt += slot_cnt
  894. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  895. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  896. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  897. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  898. # There are no drill bits in MM with more than 3 decimals diameter
  899. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  900. if self.units == 'MM':
  901. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  902. else:
  903. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  904. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  905. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  906. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  907. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  908. if slot_cnt > 0:
  909. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  910. else:
  911. slot_count = QtWidgets.QTableWidgetItem('')
  912. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  913. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  914. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  915. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  916. self.tool_row += 1
  917. # add a last row with the Total number of drills
  918. empty = QtWidgets.QTableWidgetItem('')
  919. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  920. empty_1 = QtWidgets.QTableWidgetItem('')
  921. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  922. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  923. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  924. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  925. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  926. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  927. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  928. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  929. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  930. font = QtGui.QFont()
  931. font.setBold(True)
  932. font.setWeight(75)
  933. for k in [1, 2]:
  934. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  935. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  936. self.tool_row += 1
  937. # add a last row with the Total number of slots
  938. empty_2 = QtWidgets.QTableWidgetItem('')
  939. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  940. empty_3 = QtWidgets.QTableWidgetItem('')
  941. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  942. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  943. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  944. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  945. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  946. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  947. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  948. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  949. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  950. for kl in [1, 2, 3]:
  951. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  952. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  953. # sort the tool diameter column
  954. # self.ui.tools_table.sortItems(1)
  955. # all the tools are selected by default
  956. self.ui.tools_table.selectColumn(0)
  957. #
  958. self.ui.tools_table.resizeColumnsToContents()
  959. self.ui.tools_table.resizeRowsToContents()
  960. vertical_header = self.ui.tools_table.verticalHeader()
  961. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  962. vertical_header.hide()
  963. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  964. horizontal_header = self.ui.tools_table.horizontalHeader()
  965. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  966. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  967. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  968. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  969. # horizontal_header.setStretchLastSection(True)
  970. self.ui.tools_table.setSortingEnabled(False)
  971. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  972. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  973. if not self.drills:
  974. self.ui.tdlabel.hide()
  975. self.ui.tooldia_entry.hide()
  976. self.ui.generate_milling_button.hide()
  977. else:
  978. self.ui.tdlabel.show()
  979. self.ui.tooldia_entry.show()
  980. self.ui.generate_milling_button.show()
  981. if not self.slots:
  982. self.ui.stdlabel.hide()
  983. self.ui.slot_tooldia_entry.hide()
  984. self.ui.generate_milling_slots_button.hide()
  985. else:
  986. self.ui.stdlabel.show()
  987. self.ui.slot_tooldia_entry.show()
  988. self.ui.generate_milling_slots_button.show()
  989. def set_ui(self, ui):
  990. """
  991. Configures the user interface for this object.
  992. Connects options to form fields.
  993. :param ui: User interface object.
  994. :type ui: ExcellonObjectUI
  995. :return: None
  996. """
  997. FlatCAMObj.set_ui(self, ui)
  998. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  999. self.form_fields.update({
  1000. "plot": self.ui.plot_cb,
  1001. "solid": self.ui.solid_cb,
  1002. "drillz": self.ui.cutz_entry,
  1003. "travelz": self.ui.travelz_entry,
  1004. "feedrate": self.ui.feedrate_entry,
  1005. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1006. "tooldia": self.ui.tooldia_entry,
  1007. "slot_tooldia": self.ui.slot_tooldia_entry,
  1008. "toolchange": self.ui.toolchange_cb,
  1009. "toolchangez": self.ui.toolchangez_entry,
  1010. "spindlespeed": self.ui.spindlespeed_entry,
  1011. "dwell": self.ui.dwell_cb,
  1012. "dwelltime": self.ui.dwelltime_entry,
  1013. "startz": self.ui.estartz_entry,
  1014. "endz": self.ui.eendz_entry,
  1015. "ppname_e": self.ui.pp_excellon_name_cb,
  1016. "gcode_type": self.ui.excellon_gcode_type_radio
  1017. })
  1018. for name in list(self.app.postprocessors.keys()):
  1019. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1020. if name == 'hpgl':
  1021. continue
  1022. self.ui.pp_excellon_name_cb.addItem(name)
  1023. # Fill form fields
  1024. self.to_form()
  1025. assert isinstance(self.ui, ExcellonObjectUI), \
  1026. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1027. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1028. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1029. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1030. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1031. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1032. def get_selected_tools_list(self):
  1033. """
  1034. Returns the keys to the self.tools dictionary corresponding
  1035. to the selections on the tool list in the GUI.
  1036. :return: List of tools.
  1037. :rtype: list
  1038. """
  1039. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1040. def get_selected_tools_table_items(self):
  1041. """
  1042. Returns a list of lists, each list in the list is made out of row elements
  1043. :return: List of table_tools items.
  1044. :rtype: list
  1045. """
  1046. table_tools_items = []
  1047. for x in self.ui.tools_table.selectedItems():
  1048. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1049. for column in range(0, self.ui.tools_table.columnCount())])
  1050. for item in table_tools_items:
  1051. item[0] = str(item[0])
  1052. return table_tools_items
  1053. def export_excellon(self):
  1054. """
  1055. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1056. :return: has_slots and Excellon_code
  1057. """
  1058. excellon_code = ''
  1059. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  1060. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1061. has_slots = 0
  1062. # drills processing
  1063. try:
  1064. for tool in self.tools:
  1065. if int(tool) < 10:
  1066. excellon_code += 'T0' + str(tool) + '\n'
  1067. else:
  1068. excellon_code += 'T' + str(tool) + '\n'
  1069. for drill in self.drills:
  1070. if tool == drill['tool']:
  1071. if units == 'MM':
  1072. excellon_code += 'X' + '%.3f' % drill['point'].x + 'Y' + '%.3f' % drill['point'].y + '\n'
  1073. else:
  1074. excellon_code += 'X' + '%.4f' % drill['point'].x + 'Y' + '%.4f' % drill['point'].y + '\n'
  1075. except Exception as e:
  1076. log.debug(str(e))
  1077. # slots processing
  1078. try:
  1079. if self.slots:
  1080. has_slots = 1
  1081. for tool in self.tools:
  1082. if int(tool) < 10:
  1083. excellon_code += 'T0' + str(tool) + '\n'
  1084. else:
  1085. excellon_code += 'T' + str(tool) + '\n'
  1086. for slot in self.slots:
  1087. if tool == slot['tool']:
  1088. if units == 'MM':
  1089. excellon_code += 'G00' + 'X' + '%.3f' % slot['start'].x + 'Y' + \
  1090. '%.3f' % slot['start'].y + '\n'
  1091. excellon_code += 'M15\n'
  1092. excellon_code += 'G01' + 'X' + '%.3f' % slot['stop'].x + 'Y' + \
  1093. '%.3f' % slot['stop'].y + '\n'
  1094. excellon_code += 'M16\n'
  1095. else:
  1096. excellon_code += 'G00' + 'X' + '%.4f' % slot['start'].x + 'Y' + \
  1097. '%.4f' % slot['start'].y + '\n'
  1098. excellon_code += 'M15\n'
  1099. excellon_code += 'G01' + 'X' + '%.4f' % slot['stop'].x + 'Y' + \
  1100. '%.4f' % slot['stop'].y + '\n'
  1101. excellon_code += 'M16\n'
  1102. except Exception as e:
  1103. log.debug(str(e))
  1104. return has_slots, excellon_code
  1105. def export_excellon_altium(self):
  1106. """
  1107. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1108. :return: has_slots and Excellon_code
  1109. """
  1110. excellon_code = ''
  1111. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  1112. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1113. has_slots = 0
  1114. # drills processing
  1115. try:
  1116. for tool in self.tools:
  1117. if int(tool) < 10:
  1118. excellon_code += 'T0' + str(tool) + '\n'
  1119. else:
  1120. excellon_code += 'T' + str(tool) + '\n'
  1121. for drill in self.drills:
  1122. if tool == drill['tool']:
  1123. drill_x = drill['point'].x
  1124. drill_y = drill['point'].y
  1125. if units == 'MM':
  1126. drill_x /= 25.4
  1127. drill_y /= 25.4
  1128. exc_x_formatted = ('%.4f' % drill_x).replace('.', '')
  1129. if drill_x < 10:
  1130. exc_x_formatted = '0' + exc_x_formatted
  1131. exc_y_formatted = ('%.4f' % drill_y).replace('.', '')
  1132. if drill_y < 10:
  1133. exc_y_formatted = '0' + exc_y_formatted
  1134. excellon_code += 'X' + exc_x_formatted + 'Y' + exc_y_formatted + '\n'
  1135. except Exception as e:
  1136. log.debug(str(e))
  1137. # slots processing
  1138. try:
  1139. if self.slots:
  1140. has_slots = 1
  1141. for tool in self.tools:
  1142. if int(tool) < 10:
  1143. excellon_code += 'T0' + str(tool) + '\n'
  1144. else:
  1145. excellon_code += 'T' + str(tool) + '\n'
  1146. for slot in self.slots:
  1147. if tool == slot['tool']:
  1148. start_slot_x = slot['start'].x
  1149. start_slot_y = slot['start'].y
  1150. stop_slot_x = slot['stop'].x
  1151. stop_slot_y = slot['stop'].y
  1152. if units == 'MM':
  1153. start_slot_x /= 25.4
  1154. start_slot_y /= 25.4
  1155. stop_slot_x /= 25.4
  1156. stop_slot_y /= 25.4
  1157. start_slot_x_formatted = ('%.4f' % start_slot_x).replace('.', '')
  1158. if start_slot_x < 10:
  1159. start_slot_x_formatted = '0' + start_slot_x_formatted
  1160. start_slot_y_formatted = ('%.4f' % start_slot_y).replace('.', '')
  1161. if start_slot_y < 10:
  1162. start_slot_y_formatted = '0' + start_slot_y_formatted
  1163. stop_slot_x_formatted = ('%.4f' % stop_slot_x).replace('.', '')
  1164. if stop_slot_x < 10:
  1165. stop_slot_x_formatted = '0' + stop_slot_x_formatted
  1166. stop_slot_y_formatted = ('%.4f' % stop_slot_y).replace('.', '')
  1167. if stop_slot_y < 10:
  1168. stop_slot_y_formatted = '0' + stop_slot_y_formatted
  1169. excellon_code += 'G00' + 'X' + start_slot_x_formatted + 'Y' + \
  1170. start_slot_y_formatted + '\n'
  1171. excellon_code += 'M15\n'
  1172. excellon_code += 'G01' + 'X' + stop_slot_x_formatted + 'Y' + \
  1173. stop_slot_y_formatted + '\n'
  1174. excellon_code += 'M16\n'
  1175. except Exception as e:
  1176. log.debug(str(e))
  1177. return has_slots, excellon_code
  1178. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1179. """
  1180. Note: This method is a good template for generic operations as
  1181. it takes it's options from parameters or otherwise from the
  1182. object's options and returns a (success, msg) tuple as feedback
  1183. for shell operations.
  1184. :return: Success/failure condition tuple (bool, str).
  1185. :rtype: tuple
  1186. """
  1187. # Get the tools from the list. These are keys
  1188. # to self.tools
  1189. if tools is None:
  1190. tools = self.get_selected_tools_list()
  1191. if outname is None:
  1192. outname = self.options["name"] + "_mill"
  1193. if tooldia is None:
  1194. tooldia = self.options["tooldia"]
  1195. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1196. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1197. sort = []
  1198. for k, v in self.tools.items():
  1199. sort.append((k, v.get('C')))
  1200. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1201. if tools == "all":
  1202. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1203. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1204. if len(tools) == 0:
  1205. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1206. return False, "Error: No tools."
  1207. for tool in tools:
  1208. if tooldia > self.tools[tool]["C"]:
  1209. self.app.inform.emit("[error_notcl] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1210. return False, "Error: Milling tool is larger than hole."
  1211. def geo_init(geo_obj, app_obj):
  1212. assert isinstance(geo_obj, FlatCAMGeometry), \
  1213. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1214. app_obj.progress.emit(20)
  1215. ### Add properties to the object
  1216. # get the tool_table items in a list of row items
  1217. tool_table_items = self.get_selected_tools_table_items()
  1218. # insert an information only element in the front
  1219. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1220. geo_obj.options['Tools_in_use'] = tool_table_items
  1221. geo_obj.options['type'] = 'Excellon Geometry'
  1222. geo_obj.solid_geometry = []
  1223. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1224. # for FlatCAM is 6 decimals,
  1225. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1226. for hole in self.drills:
  1227. if hole['tool'] in tools:
  1228. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1229. if buffer_value == 0:
  1230. geo_obj.solid_geometry.append(
  1231. Point(hole['point']).buffer(0.0000001).exterior)
  1232. else:
  1233. geo_obj.solid_geometry.append(
  1234. Point(hole['point']).buffer(buffer_value).exterior)
  1235. if use_thread:
  1236. def geo_thread(app_obj):
  1237. app_obj.new_object("geometry", outname, geo_init)
  1238. app_obj.progress.emit(100)
  1239. # Create a promise with the new name
  1240. self.app.collection.promise(outname)
  1241. # Send to worker
  1242. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1243. else:
  1244. self.app.new_object("geometry", outname, geo_init)
  1245. return True, ""
  1246. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1247. """
  1248. Note: This method is a good template for generic operations as
  1249. it takes it's options from parameters or otherwise from the
  1250. object's options and returns a (success, msg) tuple as feedback
  1251. for shell operations.
  1252. :return: Success/failure condition tuple (bool, str).
  1253. :rtype: tuple
  1254. """
  1255. # Get the tools from the list. These are keys
  1256. # to self.tools
  1257. if tools is None:
  1258. tools = self.get_selected_tools_list()
  1259. if outname is None:
  1260. outname = self.options["name"] + "_mill"
  1261. if tooldia is None:
  1262. tooldia = self.options["slot_tooldia"]
  1263. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1264. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1265. sort = []
  1266. for k, v in self.tools.items():
  1267. sort.append((k, v.get('C')))
  1268. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1269. if tools == "all":
  1270. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1271. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1272. if len(tools) == 0:
  1273. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1274. return False, "Error: No tools."
  1275. for tool in tools:
  1276. if tooldia > self.tools[tool]["C"]:
  1277. self.app.inform.emit("[error_notcl] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1278. return False, "Error: Milling tool is larger than hole."
  1279. def geo_init(geo_obj, app_obj):
  1280. assert isinstance(geo_obj, FlatCAMGeometry), \
  1281. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1282. app_obj.progress.emit(20)
  1283. ### Add properties to the object
  1284. # get the tool_table items in a list of row items
  1285. tool_table_items = self.get_selected_tools_table_items()
  1286. # insert an information only element in the front
  1287. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1288. geo_obj.options['Tools_in_use'] = tool_table_items
  1289. geo_obj.options['type'] = 'Excellon Geometry'
  1290. geo_obj.solid_geometry = []
  1291. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1292. # for FlatCAM is 6 decimals,
  1293. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1294. for slot in self.slots:
  1295. if slot['tool'] in tools:
  1296. buffer_value = self.tools[slot['tool']]["C"] / 2 - tooldia / 2
  1297. if buffer_value == 0:
  1298. start = slot['start']
  1299. stop = slot['stop']
  1300. lines_string = LineString([start, stop])
  1301. poly = lines_string.buffer(0.0000001, self.geo_steps_per_circle).exterior
  1302. geo_obj.solid_geometry.append(poly)
  1303. else:
  1304. start = slot['start']
  1305. stop = slot['stop']
  1306. lines_string = LineString([start, stop])
  1307. poly = lines_string.buffer(buffer_value, self.geo_steps_per_circle).exterior
  1308. geo_obj.solid_geometry.append(poly)
  1309. if use_thread:
  1310. def geo_thread(app_obj):
  1311. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1312. app_obj.progress.emit(100)
  1313. # Create a promise with the new name
  1314. self.app.collection.promise(outname)
  1315. # Send to worker
  1316. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1317. else:
  1318. self.app.new_object("geometry", outname + '_slot', geo_init)
  1319. return True, ""
  1320. def on_generate_milling_button_click(self, *args):
  1321. self.app.report_usage("excellon_on_create_milling_drills button")
  1322. self.read_form()
  1323. self.generate_milling_drills(use_thread=False)
  1324. def on_generate_milling_slots_button_click(self, *args):
  1325. self.app.report_usage("excellon_on_create_milling_slots_button")
  1326. self.read_form()
  1327. self.generate_milling_slots(use_thread=False)
  1328. def on_create_cncjob_button_click(self, *args):
  1329. self.app.report_usage("excellon_on_create_cncjob_button")
  1330. self.read_form()
  1331. # Get the tools from the list
  1332. tools = self.get_selected_tools_list()
  1333. if len(tools) == 0:
  1334. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1335. return
  1336. job_name = self.options["name"] + "_cnc"
  1337. pp_excellon_name = self.options["ppname_e"]
  1338. # Object initialization function for app.new_object()
  1339. def job_init(job_obj, app_obj):
  1340. assert isinstance(job_obj, FlatCAMCNCjob), \
  1341. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1342. # get the tool_table items in a list of row items
  1343. tool_table_items = self.get_selected_tools_table_items()
  1344. # insert an information only element in the front
  1345. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1346. ### Add properties to the object
  1347. job_obj.options['Tools_in_use'] = tool_table_items
  1348. job_obj.options['type'] = 'Excellon'
  1349. app_obj.progress.emit(20)
  1350. job_obj.z_cut = self.options["drillz"]
  1351. job_obj.z_move = self.options["travelz"]
  1352. job_obj.feedrate = self.options["feedrate"]
  1353. job_obj.feedrate_rapid = self.options["feedrate_rapid"]
  1354. job_obj.spindlespeed = self.options["spindlespeed"]
  1355. job_obj.dwell = self.options["dwell"]
  1356. job_obj.dwelltime = self.options["dwelltime"]
  1357. job_obj.pp_excellon_name = pp_excellon_name
  1358. job_obj.toolchange_xy = "excellon"
  1359. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1360. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1361. # There could be more than one drill size...
  1362. # job_obj.tooldia = # TODO: duplicate variable!
  1363. # job_obj.options["tooldia"] =
  1364. tools_csv = ','.join(tools)
  1365. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1366. drillz=self.options['drillz'],
  1367. toolchange=self.options["toolchange"],
  1368. toolchangez=self.options["toolchangez"],
  1369. toolchangexy=self.options["toolchangexy"],
  1370. startz=self.options["startz"],
  1371. endz=self.options["endz"],
  1372. excellon_optimization_type=self.options["optimization_type"])
  1373. app_obj.progress.emit(50)
  1374. job_obj.gcode_parse()
  1375. app_obj.progress.emit(60)
  1376. job_obj.create_geometry()
  1377. app_obj.progress.emit(80)
  1378. # To be run in separate thread
  1379. def job_thread(app_obj):
  1380. with self.app.proc_container.new("Generating CNC Code"):
  1381. app_obj.new_object("cncjob", job_name, job_init)
  1382. app_obj.progress.emit(100)
  1383. # Create promise for the new name.
  1384. self.app.collection.promise(job_name)
  1385. # Send to worker
  1386. # self.app.worker.add_task(job_thread, [self.app])
  1387. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1388. def on_plot_cb_click(self, *args):
  1389. if self.muted_ui:
  1390. return
  1391. self.read_form_item('plot')
  1392. def on_solid_cb_click(self, *args):
  1393. if self.muted_ui:
  1394. return
  1395. self.read_form_item('solid')
  1396. self.plot()
  1397. def convert_units(self, units):
  1398. factor = Excellon.convert_units(self, units)
  1399. self.options['drillz'] *= factor
  1400. self.options['travelz'] *= factor
  1401. self.options['feedrate'] *= factor
  1402. self.options['feedrate_rapid'] *= factor
  1403. self.options['toolchangez'] *= factor
  1404. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1405. coords_xy[0] *= factor
  1406. coords_xy[1] *= factor
  1407. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1408. if self.options['startz'] is not None:
  1409. self.options['startz'] *= factor
  1410. self.options['endz'] *= factor
  1411. def plot(self):
  1412. # Does all the required setup and returns False
  1413. # if the 'ptint' option is set to False.
  1414. if not FlatCAMObj.plot(self):
  1415. return
  1416. try:
  1417. _ = iter(self.solid_geometry)
  1418. except TypeError:
  1419. self.solid_geometry = [self.solid_geometry]
  1420. try:
  1421. # Plot excellon (All polygons?)
  1422. if self.options["solid"]:
  1423. for geo in self.solid_geometry:
  1424. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1425. layer=2)
  1426. else:
  1427. for geo in self.solid_geometry:
  1428. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1429. for ints in geo.interiors:
  1430. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1431. self.shapes.redraw()
  1432. except (ObjectDeleted, AttributeError):
  1433. self.shapes.clear(update=True)
  1434. # try:
  1435. # # Plot excellon (All polygons?)
  1436. # if self.options["solid"]:
  1437. # for geo_type in self.solid_geometry:
  1438. # if geo_type is not None:
  1439. # if type(geo_type) is dict:
  1440. # for tooldia in geo_type:
  1441. # geo_list = geo_type[tooldia]
  1442. # for geo in geo_list:
  1443. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1444. # visible=self.options['plot'],
  1445. # layer=2)
  1446. # else:
  1447. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  1448. # visible=self.options['plot'],
  1449. # layer=2)
  1450. # else:
  1451. # for geo_type in self.solid_geometry:
  1452. # if geo_type is not None:
  1453. # if type(geo_type) is dict:
  1454. # for tooldia in geo_type:
  1455. # geo_list = geo_type[tooldia]
  1456. # for geo in geo_list:
  1457. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1458. # for ints in geo.interiors:
  1459. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1460. # else:
  1461. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  1462. # for ints in geo_type.interiors:
  1463. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1464. # self.shapes.redraw()
  1465. # except (ObjectDeleted, AttributeError):
  1466. # self.shapes.clear(update=True)
  1467. class FlatCAMGeometry(FlatCAMObj, Geometry):
  1468. """
  1469. Geometric object not associated with a specific
  1470. format.
  1471. """
  1472. optionChanged = QtCore.pyqtSignal(str)
  1473. ui_type = GeometryObjectUI
  1474. @staticmethod
  1475. def merge(geo_list, geo_final, multigeo=None):
  1476. """
  1477. Merges the geometry of objects in grb_list into
  1478. the geometry of geo_final.
  1479. :param geo_list: List of FlatCAMGerber Objects to join.
  1480. :param geo_final: Destination FlatCAMGerber object.
  1481. :return: None
  1482. """
  1483. if geo_final.solid_geometry is None:
  1484. geo_final.solid_geometry = []
  1485. if type(geo_final.solid_geometry) is not list:
  1486. geo_final.solid_geometry = [geo_final.solid_geometry]
  1487. for geo in geo_list:
  1488. for option in geo.options:
  1489. if option is not 'name':
  1490. try:
  1491. geo_final.options[option] = geo.options[option]
  1492. except:
  1493. log.warning("Failed to copy option.", option)
  1494. # Expand lists
  1495. if type(geo) is list:
  1496. FlatCAMGeometry.merge(geo, geo_final)
  1497. # If not list, just append
  1498. else:
  1499. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  1500. if multigeo is None or multigeo == False:
  1501. geo_final.multigeo = False
  1502. try:
  1503. geo_final.solid_geometry.append(geo.solid_geometry)
  1504. except Exception as e:
  1505. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  1506. else:
  1507. geo_final.multigeo = True
  1508. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  1509. # tools object attribute, as a key value
  1510. geo_final.solid_geometry = []
  1511. # find the tool_uid maximum value in the geo_final
  1512. geo_final_uid_list = []
  1513. for key in geo_final.tools:
  1514. geo_final_uid_list.append(int(key))
  1515. try:
  1516. max_uid = max(geo_final_uid_list, key=int)
  1517. except ValueError:
  1518. max_uid = 0
  1519. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  1520. # to merge the obj.tools as it is likely there is none to merge.
  1521. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  1522. for tool_uid in geo.tools:
  1523. max_uid += 1
  1524. geo_final.tools[max_uid] = dict(geo.tools[tool_uid])
  1525. @staticmethod
  1526. def get_pts(o):
  1527. """
  1528. Returns a list of all points in the object, where
  1529. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  1530. of such. Search is done recursively.
  1531. :param: geometric object
  1532. :return: List of points
  1533. :rtype: list
  1534. """
  1535. pts = []
  1536. ## Iterable: descend into each item.
  1537. try:
  1538. for subo in o:
  1539. pts += FlatCAMGeometry.get_pts(subo)
  1540. ## Non-iterable
  1541. except TypeError:
  1542. if o is not None:
  1543. if type(o) == MultiPolygon:
  1544. for poly in o:
  1545. pts += FlatCAMGeometry.get_pts(poly)
  1546. ## Descend into .exerior and .interiors
  1547. elif type(o) == Polygon:
  1548. pts += FlatCAMGeometry.get_pts(o.exterior)
  1549. for i in o.interiors:
  1550. pts += FlatCAMGeometry.get_pts(i)
  1551. elif type(o) == MultiLineString:
  1552. for line in o:
  1553. pts += FlatCAMGeometry.get_pts(line)
  1554. ## Has .coords: list them.
  1555. else:
  1556. pts += list(o.coords)
  1557. else:
  1558. return
  1559. return pts
  1560. def __init__(self, name):
  1561. FlatCAMObj.__init__(self, name)
  1562. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  1563. self.kind = "geometry"
  1564. self.options.update({
  1565. "plot": True,
  1566. "cutz": -0.002,
  1567. "vtipdia": 0.1,
  1568. "vtipangle": 30,
  1569. "travelz": 0.1,
  1570. "feedrate": 5.0,
  1571. "feedrate_z": 5.0,
  1572. "feedrate_rapid": 5.0,
  1573. "spindlespeed": None,
  1574. "dwell": True,
  1575. "dwelltime": 1000,
  1576. "multidepth": False,
  1577. "depthperpass": 0.002,
  1578. "extracut": False,
  1579. "endz": 2.0,
  1580. "toolchange": False,
  1581. "toolchangez": 1.0,
  1582. "toolchangexy": "0.0, 0.0",
  1583. "startz": None,
  1584. "ppname_g": 'default',
  1585. })
  1586. if "cnctooldia" not in self.options:
  1587. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  1588. self.options["startz"] = self.app.defaults["geometry_startz"]
  1589. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  1590. self.tooluid = 0
  1591. '''
  1592. self.tools = {}
  1593. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  1594. tool_id of the tools and the value is another dict that will hold the data under the following form:
  1595. {tooluid: {
  1596. 'tooldia': 1,
  1597. 'offset': 'Path',
  1598. 'offset_value': 0.0
  1599. 'type': 'Rough',
  1600. 'tool_type': 'C1',
  1601. 'data': self.default_tool_data
  1602. 'solid_geometry': []
  1603. }
  1604. }
  1605. '''
  1606. self.tools = {}
  1607. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  1608. # those elements are the ones used for generating GCode
  1609. self.sel_tools = {}
  1610. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  1611. self.type_item_options = ["Iso", "Rough", "Finish"]
  1612. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  1613. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  1614. self.v_tool_type = None
  1615. self.multigeo = False
  1616. # Attributes to be included in serialization
  1617. # Always append to it because it carries contents
  1618. # from predecessors.
  1619. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  1620. def build_ui(self):
  1621. self.ui_disconnect()
  1622. FlatCAMObj.build_ui(self)
  1623. offset = 0
  1624. tool_idx = 0
  1625. n = len(self.tools)
  1626. self.ui.geo_tools_table.setRowCount(n)
  1627. for tooluid_key, tooluid_value in self.tools.items():
  1628. tool_idx += 1
  1629. row_no = tool_idx - 1
  1630. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  1631. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1632. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  1633. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  1634. # There are no tool bits in MM with more than 3 decimals diameter.
  1635. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  1636. if self.units == 'MM':
  1637. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  1638. else:
  1639. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  1640. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1641. offset_item = QtWidgets.QComboBox()
  1642. for item in self.offset_item_options:
  1643. offset_item.addItem(item)
  1644. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  1645. idx = offset_item.findText(tooluid_value['offset'])
  1646. offset_item.setCurrentIndex(idx)
  1647. type_item = QtWidgets.QComboBox()
  1648. for item in self.type_item_options:
  1649. type_item.addItem(item)
  1650. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1651. idx = type_item.findText(tooluid_value['type'])
  1652. type_item.setCurrentIndex(idx)
  1653. tool_type_item = QtWidgets.QComboBox()
  1654. for item in self.tool_type_item_options:
  1655. tool_type_item.addItem(item)
  1656. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1657. idx = tool_type_item.findText(tooluid_value['tool_type'])
  1658. tool_type_item.setCurrentIndex(idx)
  1659. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  1660. plot_item = FCCheckBox()
  1661. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1662. if self.ui.plot_cb.isChecked():
  1663. plot_item.setChecked(True)
  1664. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  1665. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  1666. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  1667. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  1668. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  1669. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  1670. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  1671. try:
  1672. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  1673. except:
  1674. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  1675. # make the diameter column editable
  1676. for row in range(tool_idx):
  1677. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  1678. QtCore.Qt.ItemIsEditable |
  1679. QtCore.Qt.ItemIsEnabled)
  1680. # sort the tool diameter column
  1681. # self.ui.geo_tools_table.sortItems(1)
  1682. # all the tools are selected by default
  1683. # self.ui.geo_tools_table.selectColumn(0)
  1684. self.ui.geo_tools_table.resizeColumnsToContents()
  1685. self.ui.geo_tools_table.resizeRowsToContents()
  1686. vertical_header = self.ui.geo_tools_table.verticalHeader()
  1687. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1688. vertical_header.hide()
  1689. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1690. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  1691. horizontal_header.setMinimumSectionSize(10)
  1692. horizontal_header.setDefaultSectionSize(70)
  1693. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1694. horizontal_header.resizeSection(0, 20)
  1695. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1696. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1697. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1698. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  1699. horizontal_header.resizeSection(4, 40)
  1700. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  1701. horizontal_header.resizeSection(4, 17)
  1702. # horizontal_header.setStretchLastSection(True)
  1703. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1704. self.ui.geo_tools_table.setColumnWidth(0, 20)
  1705. self.ui.geo_tools_table.setColumnWidth(4, 40)
  1706. self.ui.geo_tools_table.setColumnWidth(6, 17)
  1707. # self.ui.geo_tools_table.setSortingEnabled(True)
  1708. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  1709. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  1710. # update UI for all rows - useful after units conversion but only if there is at least one row
  1711. row_cnt = self.ui.geo_tools_table.rowCount()
  1712. if row_cnt > 0:
  1713. for r in range(row_cnt):
  1714. self.update_ui(r)
  1715. # select only the first tool / row
  1716. selected_row = 0
  1717. try:
  1718. self.select_tools_table_row(selected_row, clearsel=True)
  1719. # update the Geometry UI
  1720. self.update_ui()
  1721. except Exception as e:
  1722. # when the tools table is empty there will be this error but once the table is populated it will go away
  1723. log.debug(str(e))
  1724. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  1725. # and can create some problems
  1726. if self.multigeo is False:
  1727. self.ui.geo_tools_table.setColumnHidden(6, True)
  1728. else:
  1729. self.ui.geo_tools_table.setColumnHidden(6, False)
  1730. self.set_tool_offset_visibility(selected_row)
  1731. self.ui_connect()
  1732. def set_ui(self, ui):
  1733. FlatCAMObj.set_ui(self, ui)
  1734. log.debug("FlatCAMGeometry.set_ui()")
  1735. assert isinstance(self.ui, GeometryObjectUI), \
  1736. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  1737. # populate postprocessor names in the combobox
  1738. for name in list(self.app.postprocessors.keys()):
  1739. self.ui.pp_geometry_name_cb.addItem(name)
  1740. self.form_fields.update({
  1741. "plot": self.ui.plot_cb,
  1742. "cutz": self.ui.cutz_entry,
  1743. "vtipdia": self.ui.tipdia_entry,
  1744. "vtipangle": self.ui.tipangle_entry,
  1745. "travelz": self.ui.travelz_entry,
  1746. "feedrate": self.ui.cncfeedrate_entry,
  1747. "feedrate_z": self.ui.cncplunge_entry,
  1748. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  1749. "spindlespeed": self.ui.cncspindlespeed_entry,
  1750. "dwell": self.ui.dwell_cb,
  1751. "dwelltime": self.ui.dwelltime_entry,
  1752. "multidepth": self.ui.mpass_cb,
  1753. "ppname_g": self.ui.pp_geometry_name_cb,
  1754. "depthperpass": self.ui.maxdepth_entry,
  1755. "extracut": self.ui.extracut_cb,
  1756. "toolchange": self.ui.toolchangeg_cb,
  1757. "toolchangez": self.ui.toolchangez_entry,
  1758. "endz": self.ui.gendz_entry,
  1759. })
  1760. # Fill form fields only on object create
  1761. self.to_form()
  1762. self.ui.tipdialabel.hide()
  1763. self.ui.tipdia_entry.hide()
  1764. self.ui.tipanglelabel.hide()
  1765. self.ui.tipangle_entry.hide()
  1766. self.ui.cutz_entry.setDisabled(False)
  1767. # store here the default data for Geometry Data
  1768. self.default_data = {}
  1769. self.default_data.update({
  1770. "name": None,
  1771. "plot": None,
  1772. "cutz": None,
  1773. "vtipdia": None,
  1774. "vtipangle": None,
  1775. "travelz": None,
  1776. "feedrate": None,
  1777. "feedrate_z": None,
  1778. "feedrate_rapid": None,
  1779. "dwell": None,
  1780. "dwelltime": None,
  1781. "multidepth": None,
  1782. "ppname_g": None,
  1783. "depthperpass": None,
  1784. "extracut": None,
  1785. "toolchange": None,
  1786. "toolchangez": None,
  1787. "endz": None,
  1788. "spindlespeed": None,
  1789. "toolchangexy": None,
  1790. "startz": None
  1791. })
  1792. # fill in self.default_data values from self.options
  1793. for def_key in self.default_data:
  1794. for opt_key, opt_val in self.options.items():
  1795. if def_key == opt_key:
  1796. self.default_data[def_key] = opt_val
  1797. self.tooluid += 1
  1798. if not self.tools:
  1799. self.tools.update({
  1800. self.tooluid: {
  1801. 'tooldia': self.options["cnctooldia"],
  1802. 'offset': 'Path',
  1803. 'offset_value': 0.0,
  1804. 'type': 'Rough',
  1805. 'tool_type': 'C1',
  1806. 'data': self.default_data,
  1807. 'solid_geometry': []
  1808. }
  1809. })
  1810. else:
  1811. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  1812. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  1813. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  1814. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  1815. # following convoluted way of changing the keys from string to float type
  1816. temp_tools = {}
  1817. new_key = 0.0
  1818. for tooluid_key in self.tools:
  1819. val = dict(self.tools[tooluid_key])
  1820. new_key = deepcopy(int(tooluid_key))
  1821. temp_tools[new_key] = val
  1822. self.tools.clear()
  1823. self.tools = dict(temp_tools)
  1824. self.ui.tool_offset_entry.hide()
  1825. self.ui.tool_offset_lbl.hide()
  1826. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  1827. self.old_pp_state = self.default_data['multidepth']
  1828. self.old_toolchangeg_state = self.default_data['toolchange']
  1829. if not isinstance(self.ui, GeometryObjectUI):
  1830. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  1831. return
  1832. self.ui.geo_tools_table.setupContextMenu()
  1833. self.ui.geo_tools_table.addContextMenu(
  1834. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  1835. self.ui.geo_tools_table.addContextMenu(
  1836. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  1837. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1838. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1839. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  1840. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  1841. def set_tool_offset_visibility(self, current_row):
  1842. if current_row is None:
  1843. return
  1844. try:
  1845. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  1846. if tool_offset is not None:
  1847. tool_offset_txt = tool_offset.currentText()
  1848. if tool_offset_txt == 'Custom':
  1849. self.ui.tool_offset_entry.show()
  1850. self.ui.tool_offset_lbl.show()
  1851. else:
  1852. self.ui.tool_offset_entry.hide()
  1853. self.ui.tool_offset_lbl.hide()
  1854. except Exception as e:
  1855. log.debug("set_tool_offset_visibility() --> " + str(e))
  1856. return
  1857. def on_offset_value_edited(self):
  1858. '''
  1859. This will save the offset_value into self.tools storage whenever the oofset value is edited
  1860. :return:
  1861. '''
  1862. for current_row in self.ui.geo_tools_table.selectedItems():
  1863. # sometime the header get selected and it has row number -1
  1864. # we don't want to do anything with the header :)
  1865. if current_row.row() < 0:
  1866. continue
  1867. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  1868. self.set_tool_offset_visibility(current_row.row())
  1869. for tooluid_key, tooluid_value in self.tools.items():
  1870. if int(tooluid_key) == tool_uid:
  1871. tooluid_value['offset_value'] = self.ui.tool_offset_entry.get_value()
  1872. def ui_connect(self):
  1873. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1874. # changes in geometry UI
  1875. for i in range(self.ui.grid3.count()):
  1876. try:
  1877. # works for CheckBoxes
  1878. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  1879. except:
  1880. # works for ComboBoxes
  1881. try:
  1882. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  1883. except:
  1884. # works for Entry
  1885. try:
  1886. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  1887. except:
  1888. pass
  1889. for row in range(self.ui.geo_tools_table.rowCount()):
  1890. for col in [2, 3, 4]:
  1891. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  1892. self.on_tooltable_cellwidget_change)
  1893. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1894. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  1895. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  1896. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  1897. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  1898. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  1899. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  1900. for row in range(self.ui.geo_tools_table.rowCount()):
  1901. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  1902. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1903. def ui_disconnect(self):
  1904. try:
  1905. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1906. # changes in geometry UI
  1907. for i in range(self.ui.grid3.count()):
  1908. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  1909. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  1910. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  1911. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  1912. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  1913. isinstance(self.ui.grid3.itemAt(i), IntEntry) or \
  1914. isinstance(self.ui.grid3.itemAt(i), FCEntry):
  1915. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  1916. except:
  1917. pass
  1918. try:
  1919. for row in range(self.ui.geo_tools_table.rowCount()):
  1920. for col in [2, 3, 4]:
  1921. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  1922. except:
  1923. pass
  1924. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1925. try:
  1926. self.ui.addtool_btn.clicked.disconnect()
  1927. except:
  1928. pass
  1929. try:
  1930. self.ui.copytool_btn.clicked.disconnect()
  1931. except:
  1932. pass
  1933. try:
  1934. self.ui.deltool_btn.clicked.disconnect()
  1935. except:
  1936. pass
  1937. try:
  1938. self.ui.geo_tools_table.currentItemChanged.disconnect()
  1939. except:
  1940. pass
  1941. try:
  1942. self.ui.geo_tools_table.itemChanged.disconnect()
  1943. except:
  1944. pass
  1945. try:
  1946. self.ui.tool_offset_entry.editingFinished.disconnect()
  1947. except:
  1948. pass
  1949. for row in range(self.ui.geo_tools_table.rowCount()):
  1950. try:
  1951. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  1952. except:
  1953. pass
  1954. try:
  1955. self.ui.plot_cb.stateChanged.disconnect()
  1956. except:
  1957. pass
  1958. def on_tool_add(self, dia=None):
  1959. self.ui_disconnect()
  1960. last_offset = None
  1961. last_offset_value = None
  1962. last_type = None
  1963. last_tool_type = None
  1964. last_data = None
  1965. last_solid_geometry = []
  1966. if dia is not None:
  1967. tooldia = dia
  1968. else:
  1969. tooldia = self.ui.addtool_entry.get_value()
  1970. if tooldia is None:
  1971. self.build_ui()
  1972. self.app.inform.emit("[error_notcl] Please enter the desired tool diameter in Float format.")
  1973. return
  1974. # construct a list of all 'tooluid' in the self.tools
  1975. tool_uid_list = []
  1976. for tooluid_key in self.tools:
  1977. tool_uid_item = int(tooluid_key)
  1978. tool_uid_list.append(tool_uid_item)
  1979. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1980. if not tool_uid_list:
  1981. max_uid = 0
  1982. else:
  1983. max_uid = max(tool_uid_list)
  1984. self.tooluid = max_uid + 1
  1985. if self.units == 'IN':
  1986. tooldia = float('%.4f' % tooldia)
  1987. else:
  1988. tooldia = float('%.2f' % tooldia)
  1989. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  1990. # otherwise we add a tool with data copied from last tool
  1991. if not self.tools:
  1992. self.tools.update({
  1993. self.tooluid: {
  1994. 'tooldia': tooldia,
  1995. 'offset': 'Path',
  1996. 'offset_value': 0.0,
  1997. 'type': 'Rough',
  1998. 'tool_type': 'C1',
  1999. 'data': dict(self.default_data),
  2000. 'solid_geometry': []
  2001. }
  2002. })
  2003. else:
  2004. # print("LAST", self.tools[maxuid])
  2005. last_data = self.tools[max_uid]['data']
  2006. last_offset = self.tools[max_uid]['offset']
  2007. last_offset_value = self.tools[max_uid]['offset_value']
  2008. last_type = self.tools[max_uid]['type']
  2009. last_tool_type = self.tools[max_uid]['tool_type']
  2010. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2011. self.tools.update({
  2012. self.tooluid: {
  2013. 'tooldia': tooldia,
  2014. 'offset': last_offset,
  2015. 'offset_value': last_offset_value,
  2016. 'type': last_type,
  2017. 'tool_type': last_tool_type,
  2018. 'data': dict(last_data),
  2019. 'solid_geometry': deepcopy(last_solid_geometry)
  2020. }
  2021. })
  2022. # print("CURRENT", self.tools[-1])
  2023. self.ui.tool_offset_entry.hide()
  2024. self.ui.tool_offset_lbl.hide()
  2025. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2026. try:
  2027. self.ser_attrs.remove('tools')
  2028. except:
  2029. pass
  2030. self.ser_attrs.append('tools')
  2031. self.app.inform.emit("[success] Tool added in Tool Table.")
  2032. self.build_ui()
  2033. def on_tool_copy(self, all=None):
  2034. self.ui_disconnect()
  2035. # find the tool_uid maximum value in the self.tools
  2036. uid_list = []
  2037. for key in self.tools:
  2038. uid_list.append(int(key))
  2039. try:
  2040. max_uid = max(uid_list, key=int)
  2041. except ValueError:
  2042. max_uid = 0
  2043. if all is None:
  2044. if self.ui.geo_tools_table.selectedItems():
  2045. for current_row in self.ui.geo_tools_table.selectedItems():
  2046. # sometime the header get selected and it has row number -1
  2047. # we don't want to do anything with the header :)
  2048. if current_row.row() < 0:
  2049. continue
  2050. try:
  2051. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2052. self.set_tool_offset_visibility(current_row.row())
  2053. max_uid += 1
  2054. self.tools[int(max_uid)] = dict(self.tools[tooluid_copy])
  2055. except AttributeError:
  2056. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  2057. self.build_ui()
  2058. return
  2059. except Exception as e:
  2060. log.debug("on_tool_copy() --> " + str(e))
  2061. # deselect the table
  2062. # self.ui.geo_tools_table.clearSelection()
  2063. else:
  2064. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  2065. self.build_ui()
  2066. return
  2067. else:
  2068. # we copy all tools in geo_tools_table
  2069. try:
  2070. temp_tools = dict(self.tools)
  2071. max_uid += 1
  2072. for tooluid in temp_tools:
  2073. self.tools[int(max_uid)] = dict(temp_tools[tooluid])
  2074. temp_tools.clear()
  2075. except Exception as e:
  2076. log.debug("on_tool_copy() --> " + str(e))
  2077. # if there are no more tools in geo tools table then hide the tool offset
  2078. if not self.tools:
  2079. self.ui.tool_offset_entry.hide()
  2080. self.ui.tool_offset_lbl.hide()
  2081. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2082. try:
  2083. self.ser_attrs.remove('tools')
  2084. except:
  2085. pass
  2086. self.ser_attrs.append('tools')
  2087. self.build_ui()
  2088. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  2089. def on_tool_edit(self, current_item):
  2090. self.ui_disconnect()
  2091. current_row = current_item.row()
  2092. tool_dia = float('%.4f' % float(self.ui.geo_tools_table.item(current_row, 1).text()))
  2093. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2094. self.tools[tooluid]['tooldia'] = tool_dia
  2095. try:
  2096. self.ser_attrs.remove('tools')
  2097. self.ser_attrs.append('tools')
  2098. except:
  2099. pass
  2100. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2101. self.build_ui()
  2102. def on_tool_delete(self, all=None):
  2103. self.ui_disconnect()
  2104. if all is None:
  2105. if self.ui.geo_tools_table.selectedItems():
  2106. for current_row in self.ui.geo_tools_table.selectedItems():
  2107. # sometime the header get selected and it has row number -1
  2108. # we don't want to do anything with the header :)
  2109. if current_row.row() < 0:
  2110. continue
  2111. try:
  2112. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2113. self.set_tool_offset_visibility(current_row.row())
  2114. temp_tools = dict(self.tools)
  2115. for tooluid_key in self.tools:
  2116. if int(tooluid_key) == tooluid_del:
  2117. temp_tools.pop(tooluid_del, None)
  2118. self.tools = dict(temp_tools)
  2119. temp_tools.clear()
  2120. except AttributeError:
  2121. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2122. self.build_ui()
  2123. return
  2124. except Exception as e:
  2125. log.debug("on_tool_delete() --> " + str(e))
  2126. # deselect the table
  2127. # self.ui.geo_tools_table.clearSelection()
  2128. else:
  2129. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2130. self.build_ui()
  2131. return
  2132. else:
  2133. # we delete all tools in geo_tools_table
  2134. self.tools.clear()
  2135. self.app.plot_all()
  2136. # if there are no more tools in geo tools table then hide the tool offset
  2137. if not self.tools:
  2138. self.ui.tool_offset_entry.hide()
  2139. self.ui.tool_offset_lbl.hide()
  2140. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2141. try:
  2142. self.ser_attrs.remove('tools')
  2143. except:
  2144. pass
  2145. self.ser_attrs.append('tools')
  2146. self.build_ui()
  2147. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2148. obj_active = self.app.collection.get_active()
  2149. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2150. # we make it back SingleGeo
  2151. if self.ui.geo_tools_table.rowCount() <= 0:
  2152. obj_active.multigeo = False
  2153. obj_active.options['xmin'] = 0
  2154. obj_active.options['ymin'] = 0
  2155. obj_active.options['xmax'] = 0
  2156. obj_active.options['ymax'] = 0
  2157. if obj_active.multigeo is True:
  2158. try:
  2159. xmin, ymin, xmax, ymax = obj_active.bounds()
  2160. obj_active.options['xmin'] = xmin
  2161. obj_active.options['ymin'] = ymin
  2162. obj_active.options['xmax'] = xmax
  2163. obj_active.options['ymax'] = ymax
  2164. except:
  2165. obj_active.options['xmin'] = 0
  2166. obj_active.options['ymin'] = 0
  2167. obj_active.options['xmax'] = 0
  2168. obj_active.options['ymax'] = 0
  2169. def on_row_selection_change(self):
  2170. self.update_ui()
  2171. def update_ui(self, row=None):
  2172. self.ui_disconnect()
  2173. if row is None:
  2174. try:
  2175. current_row = self.ui.geo_tools_table.currentRow()
  2176. except:
  2177. current_row = 0
  2178. else:
  2179. current_row = row
  2180. if current_row < 0:
  2181. current_row = 0
  2182. self.set_tool_offset_visibility(current_row)
  2183. # populate the form with the data from the tool associated with the row parameter
  2184. try:
  2185. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2186. except Exception as e:
  2187. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2188. return
  2189. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2190. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2191. try:
  2192. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2193. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2194. except Exception as e:
  2195. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2196. return
  2197. try:
  2198. # set the form with data from the newly selected tool
  2199. for tooluid_key, tooluid_value in self.tools.items():
  2200. if int(tooluid_key) == tooluid:
  2201. for key, value in tooluid_value.items():
  2202. if key == 'data':
  2203. form_value_storage = tooluid_value[key]
  2204. self.update_form(form_value_storage)
  2205. if key == 'offset_value':
  2206. # update the offset value in the entry even if the entry is hidden
  2207. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2208. if key == 'tool_type' and value == 'V':
  2209. self.update_cutz()
  2210. except Exception as e:
  2211. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2212. self.ui_connect()
  2213. def ui_update_v_shape(self, tool_type_txt):
  2214. if tool_type_txt == 'V':
  2215. self.ui.tipdialabel.show()
  2216. self.ui.tipdia_entry.show()
  2217. self.ui.tipanglelabel.show()
  2218. self.ui.tipangle_entry.show()
  2219. self.ui.cutz_entry.setDisabled(True)
  2220. self.update_cutz()
  2221. else:
  2222. self.ui.tipdialabel.hide()
  2223. self.ui.tipdia_entry.hide()
  2224. self.ui.tipanglelabel.hide()
  2225. self.ui.tipangle_entry.hide()
  2226. self.ui.cutz_entry.setDisabled(False)
  2227. def update_cutz(self):
  2228. vdia = float(self.ui.tipdia_entry.get_value())
  2229. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2230. row = self.ui.geo_tools_table.currentRow()
  2231. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2232. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2233. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2234. new_cutz = float('%.4f' % -new_cutz)
  2235. self.ui.cutz_entry.set_value(new_cutz)
  2236. # store the new CutZ value into storage (self.tools)
  2237. for tooluid_key, tooluid_value in self.tools.items():
  2238. if int(tooluid_key) == tool_uid:
  2239. tooluid_value['data']['cutz'] = new_cutz
  2240. def on_tooltable_cellwidget_change(self):
  2241. cw = self.sender()
  2242. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2243. cw_row = cw_index.row()
  2244. cw_col = cw_index.column()
  2245. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2246. # store the text of the cellWidget that changed it's index in the self.tools
  2247. for tooluid_key, tooluid_value in self.tools.items():
  2248. if int(tooluid_key) == current_uid:
  2249. cb_txt = cw.currentText()
  2250. if cw_col == 2:
  2251. tooluid_value['offset'] = cb_txt
  2252. if cb_txt == 'Custom':
  2253. self.ui.tool_offset_entry.show()
  2254. self.ui.tool_offset_lbl.show()
  2255. else:
  2256. self.ui.tool_offset_entry.hide()
  2257. self.ui.tool_offset_lbl.hide()
  2258. # reset the offset_value in storage self.tools
  2259. tooluid_value['offset_value'] = 0.0
  2260. elif cw_col == 3:
  2261. # force toolpath type as 'Iso' if the tool type is V-Shape
  2262. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2263. tooluid_value['type'] = 'Iso'
  2264. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2265. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2266. else:
  2267. tooluid_value['type'] = cb_txt
  2268. elif cw_col == 4:
  2269. tooluid_value['tool_type'] = cb_txt
  2270. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2271. if cb_txt == 'V':
  2272. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2273. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2274. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2275. def update_form(self, dict_storage):
  2276. for form_key in self.form_fields:
  2277. for storage_key in dict_storage:
  2278. if form_key == storage_key:
  2279. try:
  2280. self.form_fields[form_key].set_value(dict_storage[form_key])
  2281. except Exception as e:
  2282. log.debug(str(e))
  2283. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2284. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2285. self.ui.ois_dwell_geo.on_cb_change()
  2286. self.ui.ois_mpass_geo.on_cb_change()
  2287. self.ui.ois_tcz_geo.on_cb_change()
  2288. def gui_form_to_storage(self):
  2289. self.ui_disconnect()
  2290. widget_changed = self.sender()
  2291. try:
  2292. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2293. except:
  2294. return
  2295. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2296. if widget_idx == 1 or widget_idx == 3:
  2297. self.update_cutz()
  2298. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2299. # ui_diconnect() so I use this 'hack'
  2300. if isinstance(widget_changed, FCCheckBox):
  2301. if widget_changed.text() == 'Multi-Depth:':
  2302. self.ui.ois_mpass_geo.on_cb_change()
  2303. if widget_changed.text() == 'Tool change':
  2304. self.ui.ois_tcz_geo.on_cb_change()
  2305. if widget_changed.text() == 'Dwell:':
  2306. self.ui.ois_dwell_geo.on_cb_change()
  2307. row = self.ui.geo_tools_table.currentRow()
  2308. if row < 0:
  2309. row = 0
  2310. # store all the data associated with the row parameter to the self.tools storage
  2311. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2312. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2313. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2314. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2315. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2316. offset_value_item = self.ui.tool_offset_entry.get_value()
  2317. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2318. temp_tools = {}
  2319. temp_dia = {}
  2320. temp_data = {}
  2321. for tooluid_key, tooluid_value in self.tools.items():
  2322. if int(tooluid_key) == tooluid_item:
  2323. for key, value in tooluid_value.items():
  2324. if key == 'tooldia':
  2325. temp_dia[key] = tooldia_item
  2326. # update the 'offset', 'type' and 'tool_type' sections
  2327. if key == 'offset':
  2328. temp_dia[key] = offset_item
  2329. if key == 'type':
  2330. temp_dia[key] = type_item
  2331. if key == 'tool_type':
  2332. temp_dia[key] = tool_type_item
  2333. if key == 'offset_value':
  2334. temp_dia[key] = offset_value_item
  2335. if key == 'data':
  2336. # update the 'data' section
  2337. for data_key in tooluid_value[key].keys():
  2338. for form_key, form_value in self.form_fields.items():
  2339. if form_key == data_key:
  2340. temp_data[data_key] = form_value.get_value()
  2341. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2342. # updated from self.app.defaults
  2343. if data_key not in self.form_fields:
  2344. temp_data[data_key] = value[data_key]
  2345. temp_dia[key] = dict(temp_data)
  2346. temp_data.clear()
  2347. if key == 'solid_geometry':
  2348. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2349. temp_tools[tooluid_key] = dict(temp_dia)
  2350. else:
  2351. temp_tools[tooluid_key] = dict(tooluid_value)
  2352. self.tools.clear()
  2353. self.tools = dict(temp_tools)
  2354. temp_tools.clear()
  2355. self.ui_connect()
  2356. def select_tools_table_row(self, row, clearsel=None):
  2357. if clearsel:
  2358. self.ui.geo_tools_table.clearSelection()
  2359. if self.ui.geo_tools_table.rowCount() > 0:
  2360. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2361. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2362. def export_dxf(self):
  2363. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  2364. dwg = None
  2365. try:
  2366. dwg = ezdxf.new('R2010')
  2367. msp = dwg.modelspace()
  2368. def g2dxf(dxf_space, geo):
  2369. if isinstance(geo, MultiPolygon):
  2370. for poly in geo:
  2371. ext_points = list(poly.exterior.coords)
  2372. dxf_space.add_lwpolyline(ext_points)
  2373. for interior in poly.interiors:
  2374. dxf_space.add_lwpolyline(list(interior.coords))
  2375. if isinstance(geo, Polygon):
  2376. ext_points = list(geo.exterior.coords)
  2377. dxf_space.add_lwpolyline(ext_points)
  2378. for interior in geo.interiors:
  2379. dxf_space.add_lwpolyline(list(interior.coords))
  2380. if isinstance(geo, MultiLineString):
  2381. for line in geo:
  2382. dxf_space.add_lwpolyline(list(line.coords))
  2383. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2384. dxf_space.add_lwpolyline(list(geo.coords))
  2385. multigeo_solid_geometry = []
  2386. if self.multigeo:
  2387. for tool in self.tools:
  2388. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2389. else:
  2390. multigeo_solid_geometry = self.solid_geometry
  2391. for geo in multigeo_solid_geometry:
  2392. if type(geo) == list:
  2393. for g in geo:
  2394. g2dxf(msp, g)
  2395. else:
  2396. g2dxf(msp, geo)
  2397. # points = FlatCAMGeometry.get_pts(geo)
  2398. # msp.add_lwpolyline(points)
  2399. except Exception as e:
  2400. log.debug(str(e))
  2401. return dwg
  2402. def get_selected_tools_table_items(self):
  2403. """
  2404. Returns a list of lists, each list in the list is made out of row elements
  2405. :return: List of table_tools items.
  2406. :rtype: list
  2407. """
  2408. table_tools_items = []
  2409. for x in self.ui.geo_tools_table.selectedItems():
  2410. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2411. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2412. for item in table_tools_items:
  2413. item[0] = str(item[0])
  2414. return table_tools_items
  2415. def on_pp_changed(self):
  2416. current_pp = self.ui.pp_geometry_name_cb.get_value()
  2417. if current_pp == 'hpgl':
  2418. self.old_pp_state = self.ui.mpass_cb.get_value()
  2419. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  2420. self.ui.mpass_cb.set_value(False)
  2421. self.ui.mpass_cb.setDisabled(True)
  2422. self.ui.toolchangeg_cb.set_value(True)
  2423. self.ui.toolchangeg_cb.setDisabled(True)
  2424. else:
  2425. self.ui.mpass_cb.set_value(self.old_pp_state)
  2426. self.ui.mpass_cb.setDisabled(False)
  2427. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  2428. self.ui.toolchangeg_cb.setDisabled(False)
  2429. def on_generatecnc_button_click(self, *args):
  2430. self.app.report_usage("geometry_on_generatecnc_button")
  2431. self.read_form()
  2432. # test to see if we have tools available in the tool table
  2433. if self.ui.geo_tools_table.selectedItems():
  2434. for x in self.ui.geo_tools_table.selectedItems():
  2435. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  2436. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  2437. for tooluid_key, tooluid_value in self.tools.items():
  2438. if int(tooluid_key) == tooluid:
  2439. self.sel_tools.update({
  2440. tooluid: dict(tooluid_value)
  2441. })
  2442. self.mtool_gen_cncjob()
  2443. self.ui.geo_tools_table.clearSelection()
  2444. else:
  2445. self.app.inform.emit("[error_notcl] Failed. No tool selected in the tool table ...")
  2446. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  2447. """
  2448. Creates a multi-tool CNCJob out of this Geometry object.
  2449. The actual work is done by the target FlatCAMCNCjob object's
  2450. `generate_from_geometry_2()` method.
  2451. :param z_cut: Cut depth (negative)
  2452. :param z_move: Hight of the tool when travelling (not cutting)
  2453. :param feedrate: Feed rate while cutting on X - Y plane
  2454. :param feedrate_z: Feed rate while cutting on Z plane
  2455. :param feedrate_rapid: Feed rate while moving with rapids
  2456. :param tooldia: Tool diameter
  2457. :param outname: Name of the new object
  2458. :param spindlespeed: Spindle speed (RPM)
  2459. :param ppname_g Name of the postprocessor
  2460. :return: None
  2461. """
  2462. offset_str = ''
  2463. multitool_gcode = ''
  2464. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  2465. outname = "%s_%s" % (self.options["name"], 'cnc')
  2466. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  2467. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  2468. # Object initialization function for app.new_object()
  2469. # RUNNING ON SEPARATE THREAD!
  2470. def job_init_single_geometry(job_obj, app_obj):
  2471. assert isinstance(job_obj, FlatCAMCNCjob), \
  2472. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2473. # count the tools
  2474. tool_cnt = 0
  2475. dia_cnc_dict = {}
  2476. # this turn on the FlatCAMCNCJob plot for multiple tools
  2477. job_obj.multitool = True
  2478. job_obj.multigeo = False
  2479. job_obj.cnc_tools.clear()
  2480. # job_obj.create_geometry()
  2481. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  2482. job_obj.segx = segx
  2483. job_obj.segy = segy
  2484. for tooluid_key in self.sel_tools:
  2485. tool_cnt += 1
  2486. app_obj.progress.emit(20)
  2487. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2488. if diadict_key == 'tooldia':
  2489. tooldia_val = float('%.4f' % float(diadict_value))
  2490. dia_cnc_dict.update({
  2491. diadict_key: tooldia_val
  2492. })
  2493. if diadict_key == 'offset':
  2494. o_val = diadict_value.lower()
  2495. dia_cnc_dict.update({
  2496. diadict_key: o_val
  2497. })
  2498. if diadict_key == 'type':
  2499. t_val = diadict_value
  2500. dia_cnc_dict.update({
  2501. diadict_key: t_val
  2502. })
  2503. if diadict_key == 'tool_type':
  2504. tt_val = diadict_value
  2505. dia_cnc_dict.update({
  2506. diadict_key: tt_val
  2507. })
  2508. if diadict_key == 'data':
  2509. for data_key, data_value in diadict_value.items():
  2510. if data_key == "multidepth":
  2511. multidepth = data_value
  2512. if data_key == "depthperpass":
  2513. depthpercut = data_value
  2514. if data_key == "extracut":
  2515. extracut = data_value
  2516. if data_key == "startz":
  2517. startz = data_value
  2518. if data_key == "endz":
  2519. endz = data_value
  2520. if data_key == "toolchangez":
  2521. toolchangez =data_value
  2522. if data_key == "toolchangexy":
  2523. toolchangexy = data_value
  2524. if data_key == "toolchange":
  2525. toolchange = data_value
  2526. if data_key == "cutz":
  2527. z_cut = data_value
  2528. if data_key == "travelz":
  2529. z_move = data_value
  2530. if data_key == "feedrate":
  2531. feedrate = data_value
  2532. if data_key == "feedrate_z":
  2533. feedrate_z = data_value
  2534. if data_key == "feedrate_rapid":
  2535. feedrate_rapid = data_value
  2536. if data_key == "ppname_g":
  2537. pp_geometry_name = data_value
  2538. if data_key == "spindlespeed":
  2539. spindlespeed = data_value
  2540. if data_key == "dwell":
  2541. dwell = data_value
  2542. if data_key == "dwelltime":
  2543. dwelltime = data_value
  2544. datadict = dict(diadict_value)
  2545. dia_cnc_dict.update({
  2546. diadict_key: datadict
  2547. })
  2548. if dia_cnc_dict['offset'] == 'in':
  2549. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2550. offset_str = 'inside'
  2551. elif dia_cnc_dict['offset'].lower() == 'out':
  2552. tool_offset = dia_cnc_dict['tooldia'] / 2
  2553. offset_str = 'outside'
  2554. elif dia_cnc_dict['offset'].lower() == 'path':
  2555. offset_str = 'onpath'
  2556. tool_offset = 0.0
  2557. else:
  2558. offset_str = 'custom'
  2559. offset_value = self.ui.tool_offset_entry.get_value()
  2560. if offset_value:
  2561. tool_offset = float(offset_value)
  2562. else:
  2563. self.app.inform.emit(
  2564. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2565. "Add a Tool Offset or change the Offset Type."
  2566. )
  2567. return
  2568. dia_cnc_dict.update({
  2569. 'offset_value': tool_offset
  2570. })
  2571. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2572. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2573. # Propagate options
  2574. job_obj.options["tooldia"] = tooldia_val
  2575. job_obj.options['type'] = 'Geometry'
  2576. job_obj.options['tool_dia'] = tooldia_val
  2577. app_obj.progress.emit(40)
  2578. dia_cnc_dict['gcode'] = job_obj.generate_from_geometry_2(
  2579. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  2580. z_cut=z_cut, z_move=z_move,
  2581. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2582. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2583. multidepth=multidepth, depthpercut=depthpercut,
  2584. extracut=extracut, startz=startz, endz=endz,
  2585. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2586. pp_geometry_name=pp_geometry_name,
  2587. tool_no=tool_cnt)
  2588. app_obj.progress.emit(50)
  2589. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2590. # object is the source of gcode
  2591. job_obj.toolchange_xy = "geometry"
  2592. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2593. # TODO this serve for bounding box creation only; should be optimized
  2594. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2595. app_obj.progress.emit(80)
  2596. job_obj.cnc_tools.update({
  2597. tooluid_key: dict(dia_cnc_dict)
  2598. })
  2599. dia_cnc_dict.clear()
  2600. # Object initialization function for app.new_object()
  2601. # RUNNING ON SEPARATE THREAD!
  2602. def job_init_multi_geometry(job_obj, app_obj):
  2603. assert isinstance(job_obj, FlatCAMCNCjob), \
  2604. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2605. # count the tools
  2606. tool_cnt = 0
  2607. dia_cnc_dict = {}
  2608. current_uid = int(1)
  2609. # this turn on the FlatCAMCNCJob plot for multiple tools
  2610. job_obj.multitool = True
  2611. job_obj.multigeo = True
  2612. job_obj.cnc_tools.clear()
  2613. for tooluid_key in self.sel_tools:
  2614. tool_cnt += 1
  2615. app_obj.progress.emit(20)
  2616. # find the tool_dia associated with the tooluid_key
  2617. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  2618. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  2619. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  2620. for k, v in self.tools.items():
  2621. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  2622. current_uid = int(k)
  2623. break
  2624. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2625. if diadict_key == 'tooldia':
  2626. tooldia_val = float('%.4f' % float(diadict_value))
  2627. dia_cnc_dict.update({
  2628. diadict_key: tooldia_val
  2629. })
  2630. if diadict_key == 'offset':
  2631. o_val = diadict_value.lower()
  2632. dia_cnc_dict.update({
  2633. diadict_key: o_val
  2634. })
  2635. if diadict_key == 'type':
  2636. t_val = diadict_value
  2637. dia_cnc_dict.update({
  2638. diadict_key: t_val
  2639. })
  2640. if diadict_key == 'tool_type':
  2641. tt_val = diadict_value
  2642. dia_cnc_dict.update({
  2643. diadict_key: tt_val
  2644. })
  2645. if diadict_key == 'data':
  2646. for data_key, data_value in diadict_value.items():
  2647. if data_key == "multidepth":
  2648. multidepth = data_value
  2649. if data_key == "depthperpass":
  2650. depthpercut = data_value
  2651. if data_key == "extracut":
  2652. extracut = data_value
  2653. if data_key == "startz":
  2654. startz = data_value
  2655. if data_key == "endz":
  2656. endz = data_value
  2657. if data_key == "toolchangez":
  2658. toolchangez =data_value
  2659. if data_key == "toolchangexy":
  2660. toolchangexy = data_value
  2661. if data_key == "toolchange":
  2662. toolchange = data_value
  2663. if data_key == "cutz":
  2664. z_cut = data_value
  2665. if data_key == "travelz":
  2666. z_move = data_value
  2667. if data_key == "feedrate":
  2668. feedrate = data_value
  2669. if data_key == "feedrate_z":
  2670. feedrate_z = data_value
  2671. if data_key == "feedrate_rapid":
  2672. feedrate_rapid = data_value
  2673. if data_key == "ppname_g":
  2674. pp_geometry_name = data_value
  2675. if data_key == "spindlespeed":
  2676. spindlespeed = data_value
  2677. if data_key == "dwell":
  2678. dwell = data_value
  2679. if data_key == "dwelltime":
  2680. dwelltime = data_value
  2681. datadict = dict(diadict_value)
  2682. dia_cnc_dict.update({
  2683. diadict_key: datadict
  2684. })
  2685. if dia_cnc_dict['offset'] == 'in':
  2686. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2687. offset_str = 'inside'
  2688. elif dia_cnc_dict['offset'].lower() == 'out':
  2689. tool_offset = dia_cnc_dict['tooldia'] / 2
  2690. offset_str = 'outside'
  2691. elif dia_cnc_dict['offset'].lower() == 'path':
  2692. offset_str = 'onpath'
  2693. tool_offset = 0.0
  2694. else:
  2695. offset_str = 'custom'
  2696. offset_value = self.ui.tool_offset_entry.get_value()
  2697. if offset_value:
  2698. tool_offset = float(offset_value)
  2699. else:
  2700. self.app.inform.emit(
  2701. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2702. "Add a Tool Offset or change the Offset Type."
  2703. )
  2704. return
  2705. dia_cnc_dict.update({
  2706. 'offset_value': tool_offset
  2707. })
  2708. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2709. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2710. # Propagate options
  2711. job_obj.options["tooldia"] = tooldia_val
  2712. job_obj.options['type'] = 'Geometry'
  2713. job_obj.options['tool_dia'] = tooldia_val
  2714. app_obj.progress.emit(40)
  2715. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  2716. dia_cnc_dict['gcode'] = job_obj.generate_from_multitool_geometry(
  2717. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  2718. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  2719. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2720. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2721. multidepth=multidepth, depthpercut=depthpercut,
  2722. extracut=extracut, startz=startz, endz=endz,
  2723. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2724. pp_geometry_name=pp_geometry_name,
  2725. tool_no=tool_cnt)
  2726. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2727. # TODO this serve for bounding box creation only; should be optimized
  2728. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2729. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2730. # object is the source of gcode
  2731. job_obj.toolchange_xy = "geometry"
  2732. app_obj.progress.emit(80)
  2733. job_obj.cnc_tools.update({
  2734. tooluid_key: dict(dia_cnc_dict)
  2735. })
  2736. dia_cnc_dict.clear()
  2737. if use_thread:
  2738. # To be run in separate thread
  2739. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  2740. # separate solid_geometry in the self.tools dictionary
  2741. def job_thread(app_obj):
  2742. if self.solid_geometry:
  2743. with self.app.proc_container.new("Generating CNC Code"):
  2744. app_obj.new_object("cncjob", outname, job_init_single_geometry)
  2745. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2746. app_obj.progress.emit(100)
  2747. else:
  2748. with self.app.proc_container.new("Generating CNC Code"):
  2749. app_obj.new_object("cncjob", outname, job_init_multi_geometry)
  2750. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2751. app_obj.progress.emit(100)
  2752. # Create a promise with the name
  2753. self.app.collection.promise(outname)
  2754. # Send to worker
  2755. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2756. else:
  2757. if self.solid_geometry:
  2758. self.app.new_object("cncjob", outname, job_init_single_geometry)
  2759. else:
  2760. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  2761. def generatecncjob(self, outname=None,
  2762. tooldia=None, offset=None,
  2763. z_cut=None, z_move=None,
  2764. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  2765. spindlespeed=None, dwell=None, dwelltime=None,
  2766. multidepth=None, depthperpass=None,
  2767. toolchange=None, toolchangez=None, toolchangexy=None,
  2768. extracut=None, startz=None, endz=None,
  2769. ppname_g=None,
  2770. segx=None,
  2771. segy=None,
  2772. use_thread=True):
  2773. """
  2774. Only used for TCL Command.
  2775. Creates a CNCJob out of this Geometry object. The actual
  2776. work is done by the target FlatCAMCNCjob object's
  2777. `generate_from_geometry_2()` method.
  2778. :param z_cut: Cut depth (negative)
  2779. :param z_move: Hight of the tool when travelling (not cutting)
  2780. :param feedrate: Feed rate while cutting on X - Y plane
  2781. :param feedrate_z: Feed rate while cutting on Z plane
  2782. :param feedrate_rapid: Feed rate while moving with rapids
  2783. :param tooldia: Tool diameter
  2784. :param outname: Name of the new object
  2785. :param spindlespeed: Spindle speed (RPM)
  2786. :param ppname_g Name of the postprocessor
  2787. :return: None
  2788. """
  2789. tooldia = tooldia if tooldia else self.options["cnctooldia"]
  2790. outname = outname if outname is not None else self.options["name"]
  2791. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  2792. z_move = z_move if z_move is not None else self.options["travelz"]
  2793. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  2794. feedrate_z = feedrate_z if feedrate_z is not None else self.options["feedrate_z"]
  2795. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else self.options["feedrate_rapid"]
  2796. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  2797. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  2798. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  2799. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  2800. extracut = extracut if extracut is not None else self.options["extracut"]
  2801. startz = startz if startz is not None else self.options["startz"]
  2802. endz = endz if endz is not None else self.options["endz"]
  2803. toolchangez = toolchangez if toolchangez else self.options["toolchangez"]
  2804. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  2805. toolchange = toolchange if toolchange else self.options["toolchange"]
  2806. offset = offset if offset else 0.0
  2807. # int or None.
  2808. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  2809. dwell = dwell if dwell else self.options["dwell"]
  2810. dwelltime = dwelltime if dwelltime else self.options["dwelltime"]
  2811. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  2812. # Object initialization function for app.new_object()
  2813. # RUNNING ON SEPARATE THREAD!
  2814. def job_init(job_obj, app_obj):
  2815. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2816. # Propagate options
  2817. job_obj.options["tooldia"] = tooldia
  2818. app_obj.progress.emit(20)
  2819. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2820. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2821. app_obj.progress.emit(40)
  2822. job_obj.options['type'] = 'Geometry'
  2823. job_obj.options['tool_dia'] = tooldia
  2824. job_obj.segx = segx
  2825. job_obj.segy = segy
  2826. # TODO: The tolerance should not be hard coded. Just for testing.
  2827. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  2828. z_cut=z_cut, z_move=z_move,
  2829. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2830. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2831. multidepth=multidepth, depthpercut=depthperpass,
  2832. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2833. extracut=extracut, startz=startz, endz=endz,
  2834. pp_geometry_name=ppname_g
  2835. )
  2836. app_obj.progress.emit(50)
  2837. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  2838. # source of gcode
  2839. job_obj.toolchange_xy = "geometry"
  2840. job_obj.gcode_parse()
  2841. app_obj.progress.emit(80)
  2842. if use_thread:
  2843. # To be run in separate thread
  2844. def job_thread(app_obj):
  2845. with self.app.proc_container.new("Generating CNC Code"):
  2846. app_obj.new_object("cncjob", outname, job_init)
  2847. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2848. app_obj.progress.emit(100)
  2849. # Create a promise with the name
  2850. self.app.collection.promise(outname)
  2851. # Send to worker
  2852. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2853. else:
  2854. self.app.new_object("cncjob", outname, job_init)
  2855. # def on_plot_cb_click(self, *args): # TODO: args not needed
  2856. # if self.muted_ui:
  2857. # return
  2858. # self.read_form_item('plot')
  2859. def scale(self, xfactor, yfactor=None, point=None):
  2860. """
  2861. Scales all geometry by a given factor.
  2862. :param xfactor: Factor by which to scale the object's geometry/
  2863. :type xfactor: float
  2864. :param yfactor: Factor by which to scale the object's geometry/
  2865. :type yfactor: float
  2866. :return: None
  2867. :rtype: None
  2868. """
  2869. if yfactor is None:
  2870. yfactor = xfactor
  2871. if point is None:
  2872. px = 0
  2873. py = 0
  2874. else:
  2875. px, py = point
  2876. if type(self.solid_geometry) == list:
  2877. geo_list = self.flatten(self.solid_geometry)
  2878. self.solid_geometry = []
  2879. # for g in geo_list:
  2880. # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  2881. self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  2882. for g in geo_list]
  2883. else:
  2884. self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  2885. origin=(px, py))
  2886. def offset(self, vect):
  2887. """
  2888. Offsets all geometry by a given vector/
  2889. :param vect: (x, y) vector by which to offset the object's geometry.
  2890. :type vect: tuple
  2891. :return: None
  2892. :rtype: None
  2893. """
  2894. dx, dy = vect
  2895. def translate_recursion(geom):
  2896. if type(geom) == list:
  2897. geoms=list()
  2898. for local_geom in geom:
  2899. geoms.append(translate_recursion(local_geom))
  2900. return geoms
  2901. else:
  2902. return affinity.translate(geom, xoff=dx, yoff=dy)
  2903. if self.multigeo is True:
  2904. for tool in self.tools:
  2905. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  2906. else:
  2907. self.solid_geometry=translate_recursion(self.solid_geometry)
  2908. def convert_units(self, units):
  2909. self.ui_disconnect()
  2910. factor = Geometry.convert_units(self, units)
  2911. self.options['cutz'] *= factor
  2912. self.options['depthperpass'] *= factor
  2913. self.options['travelz'] *= factor
  2914. self.options['feedrate'] *= factor
  2915. self.options['feedrate_z'] *= factor
  2916. self.options['feedrate_rapid'] *= factor
  2917. self.options['endz'] *= factor
  2918. # self.options['cnctooldia'] *= factor
  2919. self.options['painttooldia'] *= factor
  2920. self.options['paintmargin'] *= factor
  2921. self.options['paintoverlap'] *= factor
  2922. self.options["toolchangez"] *= factor
  2923. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  2924. coords_xy[0] *= factor
  2925. coords_xy[1] *= factor
  2926. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2927. if self.options['startz'] is not None:
  2928. self.options['startz'] *= factor
  2929. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2930. 'endz', 'toolchangez']
  2931. temp_tools_dict = {}
  2932. tool_dia_copy = {}
  2933. data_copy = {}
  2934. for tooluid_key, tooluid_value in self.tools.items():
  2935. for dia_key, dia_value in tooluid_value.items():
  2936. if dia_key == 'tooldia':
  2937. dia_value *= factor
  2938. dia_value = float('%.4f' % dia_value)
  2939. tool_dia_copy[dia_key] = dia_value
  2940. if dia_key == 'offset':
  2941. tool_dia_copy[dia_key] = dia_value
  2942. if dia_key == 'offset_value':
  2943. dia_value *= factor
  2944. tool_dia_copy[dia_key] = dia_value
  2945. # convert the value in the Custom Tool Offset entry in UI
  2946. custom_offset = self.ui.tool_offset_entry.get_value()
  2947. if custom_offset:
  2948. custom_offset *= factor
  2949. self.ui.tool_offset_entry.set_value(custom_offset)
  2950. if dia_key == 'type':
  2951. tool_dia_copy[dia_key] = dia_value
  2952. if dia_key == 'tool_type':
  2953. tool_dia_copy[dia_key] = dia_value
  2954. if dia_key == 'data':
  2955. for data_key, data_value in dia_value.items():
  2956. # convert the form fields that are convertible
  2957. for param in param_list:
  2958. if data_key == param and data_value is not None:
  2959. data_copy[data_key] = data_value * factor
  2960. # copy the other dict entries that are not convertible
  2961. if data_key not in param_list:
  2962. data_copy[data_key] = data_value
  2963. tool_dia_copy[dia_key] = dict(data_copy)
  2964. data_copy.clear()
  2965. temp_tools_dict.update({
  2966. tooluid_key: dict(tool_dia_copy)
  2967. })
  2968. tool_dia_copy.clear()
  2969. self.tools.clear()
  2970. self.tools = dict(temp_tools_dict)
  2971. # if there is a value in the new tool field then convert that one too
  2972. tooldia = self.ui.addtool_entry.get_value()
  2973. if tooldia:
  2974. tooldia *= factor
  2975. # limit the decimals to 2 for METRIC and 3 for INCH
  2976. if units.lower() == 'in':
  2977. tooldia = float('%.4f' % tooldia)
  2978. else:
  2979. tooldia = float('%.2f' % tooldia)
  2980. self.ui.addtool_entry.set_value(tooldia)
  2981. return factor
  2982. def plot_element(self, element, color='red', visible=None):
  2983. visible = visible if visible else self.options['plot']
  2984. try:
  2985. for sub_el in element:
  2986. self.plot_element(sub_el)
  2987. except TypeError: # Element is not iterable...
  2988. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2989. def plot(self, visible=None):
  2990. """
  2991. Adds the object into collection.
  2992. :return: None
  2993. """
  2994. # Does all the required setup and returns False
  2995. # if the 'ptint' option is set to False.
  2996. if not FlatCAMObj.plot(self):
  2997. return
  2998. try:
  2999. # plot solid geometries found as members of self.tools attribute dict
  3000. # for MultiGeo
  3001. if self.multigeo == True: # geo multi tool usage
  3002. for tooluid_key in self.tools:
  3003. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3004. self.plot_element(solid_geometry, visible=visible)
  3005. # plot solid geometry that may be an direct attribute of the geometry object
  3006. # for SingleGeo
  3007. if self.solid_geometry:
  3008. self.plot_element(self.solid_geometry, visible=visible)
  3009. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  3010. self.shapes.redraw()
  3011. except (ObjectDeleted, AttributeError):
  3012. self.shapes.clear(update=True)
  3013. def on_plot_cb_click(self, *args):
  3014. if self.muted_ui:
  3015. return
  3016. self.plot()
  3017. self.read_form_item('plot')
  3018. self.ui_disconnect()
  3019. cb_flag = self.ui.plot_cb.isChecked()
  3020. for row in range(self.ui.geo_tools_table.rowCount()):
  3021. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  3022. if cb_flag:
  3023. table_cb.setChecked(True)
  3024. else:
  3025. table_cb.setChecked(False)
  3026. self.ui_connect()
  3027. def on_plot_cb_click_table(self):
  3028. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3029. self.ui_disconnect()
  3030. cw = self.sender()
  3031. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3032. cw_row = cw_index.row()
  3033. check_row = 0
  3034. self.shapes.clear(update=True)
  3035. for tooluid_key in self.tools:
  3036. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3037. # find the geo_tool_table row associated with the tooluid_key
  3038. for row in range(self.ui.geo_tools_table.rowCount()):
  3039. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3040. if tooluid_item == int(tooluid_key):
  3041. check_row = row
  3042. break
  3043. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  3044. self.plot_element(element=solid_geometry, visible=True)
  3045. self.shapes.redraw()
  3046. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3047. # if all the row plot's are enabled also enable the general plot checkbox
  3048. cb_cnt = 0
  3049. total_row = self.ui.geo_tools_table.rowCount()
  3050. for row in range(total_row):
  3051. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  3052. cb_cnt += 1
  3053. else:
  3054. cb_cnt -= 1
  3055. if cb_cnt < total_row:
  3056. self.ui.plot_cb.setChecked(False)
  3057. else:
  3058. self.ui.plot_cb.setChecked(True)
  3059. self.ui_connect()
  3060. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  3061. """
  3062. Represents G-Code.
  3063. """
  3064. optionChanged = QtCore.pyqtSignal(str)
  3065. ui_type = CNCObjectUI
  3066. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  3067. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  3068. spindlespeed=None):
  3069. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  3070. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  3071. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  3072. spindlespeed=spindlespeed, steps_per_circle=self.app.defaults["cncjob_steps_per_circle"])
  3073. FlatCAMObj.__init__(self, name)
  3074. self.kind = "cncjob"
  3075. self.options.update({
  3076. "plot": True,
  3077. "tooldia": 0.03937, # 0.4mm in inches
  3078. "append": "",
  3079. "prepend": "",
  3080. "dwell": False,
  3081. "dwelltime": 1,
  3082. "type": 'Geometry'
  3083. })
  3084. '''
  3085. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3086. diameter of the tools and the value is another dict that will hold the data under the following form:
  3087. {tooldia: {
  3088. 'tooluid': 1,
  3089. 'offset': 'Path',
  3090. 'type_item': 'Rough',
  3091. 'tool_type': 'C1',
  3092. 'data': {} # a dict to hold the parameters
  3093. 'gcode': "" # a string with the actual GCODE
  3094. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3095. 'solid_geometry': []
  3096. },
  3097. ...
  3098. }
  3099. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  3100. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3101. '''
  3102. self.cnc_tools = {}
  3103. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  3104. # (like the one in the TCL Command), False
  3105. self.multitool = False
  3106. # used for parsing the GCode lines to adjust the offset when the GCode was offseted
  3107. offsetx_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  3108. self.g_offsetx_re = re.compile(offsetx_re_string)
  3109. offsety_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  3110. self.g_offsety_re = re.compile(offsety_re_string)
  3111. # Attributes to be included in serialization
  3112. # Always append to it because it carries contents
  3113. # from predecessors.
  3114. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3115. self.annotation = self.app.plotcanvas.new_text_group()
  3116. def build_ui(self):
  3117. self.ui_disconnect()
  3118. FlatCAMObj.build_ui(self)
  3119. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3120. if self.cnc_tools:
  3121. self.ui.cnc_tools_table.show()
  3122. self.ui.plot_options_label.show()
  3123. else:
  3124. self.ui.cnc_tools_table.hide()
  3125. self.ui.plot_options_label.hide()
  3126. offset = 0
  3127. tool_idx = 0
  3128. n = len(self.cnc_tools)
  3129. self.ui.cnc_tools_table.setRowCount(n)
  3130. for dia_key, dia_value in self.cnc_tools.items():
  3131. tool_idx += 1
  3132. row_no = tool_idx - 1
  3133. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3134. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3135. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3136. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3137. # There are no tool bits in MM with more than 2 decimals diameter.
  3138. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3139. if self.units == 'MM':
  3140. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3141. else:
  3142. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3143. offset_txt = list(str(dia_value['offset']))
  3144. offset_txt[0] = offset_txt[0].upper()
  3145. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3146. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3147. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3148. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3149. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3150. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3151. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3152. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3153. # hack so the checkbox stay centered in the table cell
  3154. # used this:
  3155. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3156. # plot_item = QtWidgets.QWidget()
  3157. # checkbox = FCCheckBox()
  3158. # checkbox.setCheckState(QtCore.Qt.Checked)
  3159. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3160. # qhboxlayout.addWidget(checkbox)
  3161. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3162. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3163. plot_item = FCCheckBox()
  3164. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3165. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3166. if self.ui.plot_cb.isChecked():
  3167. plot_item.setChecked(True)
  3168. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3169. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3170. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3171. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3172. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3173. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3174. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3175. # make the diameter column editable
  3176. # for row in range(tool_idx):
  3177. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3178. # QtCore.Qt.ItemIsEnabled)
  3179. for row in range(tool_idx):
  3180. self.ui.cnc_tools_table.item(row, 0).setFlags(
  3181. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  3182. self.ui.cnc_tools_table.resizeColumnsToContents()
  3183. self.ui.cnc_tools_table.resizeRowsToContents()
  3184. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  3185. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3186. vertical_header.hide()
  3187. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3188. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  3189. horizontal_header.setMinimumSectionSize(10)
  3190. horizontal_header.setDefaultSectionSize(70)
  3191. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3192. horizontal_header.resizeSection(0, 20)
  3193. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3194. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3195. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3196. horizontal_header.resizeSection(4, 40)
  3197. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3198. horizontal_header.resizeSection(4, 17)
  3199. # horizontal_header.setStretchLastSection(True)
  3200. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3201. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  3202. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  3203. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  3204. # self.ui.geo_tools_table.setSortingEnabled(True)
  3205. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  3206. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  3207. self.ui_connect()
  3208. def set_ui(self, ui):
  3209. FlatCAMObj.set_ui(self, ui)
  3210. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  3211. assert isinstance(self.ui, CNCObjectUI), \
  3212. "Expected a CNCObjectUI, got %s" % type(self.ui)
  3213. self.form_fields.update({
  3214. "plot": self.ui.plot_cb,
  3215. # "tooldia": self.ui.tooldia_entry,
  3216. "append": self.ui.append_text,
  3217. "prepend": self.ui.prepend_text,
  3218. })
  3219. # Fill form fields only on object create
  3220. self.to_form()
  3221. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  3222. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  3223. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  3224. def ui_connect(self):
  3225. for row in range(self.ui.cnc_tools_table.rowCount()):
  3226. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3227. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3228. def ui_disconnect(self):
  3229. for row in range(self.ui.cnc_tools_table.rowCount()):
  3230. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  3231. try:
  3232. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  3233. except:
  3234. pass
  3235. def on_updateplot_button_click(self, *args):
  3236. """
  3237. Callback for the "Updata Plot" button. Reads the form for updates
  3238. and plots the object.
  3239. """
  3240. self.read_form()
  3241. self.plot()
  3242. def on_exportgcode_button_click(self, *args):
  3243. self.app.report_usage("cncjob_on_exportgcode_button")
  3244. self.read_form()
  3245. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3246. _filter_ = "RML1 Files (*.rol);;" \
  3247. "All Files (*.*)"
  3248. elif 'hpgl' in self.pp_geometry_name:
  3249. _filter_ = "HPGL Files (*.plt);;" \
  3250. "All Files (*.*)"
  3251. else:
  3252. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  3253. "G-Code Files (*.g-code);;All Files (*.*)"
  3254. try:
  3255. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3256. caption="Export Machine Code ...", directory=self.app.get_last_save_folder(), filter=_filter_)[0])
  3257. except TypeError:
  3258. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)[0])
  3259. preamble = str(self.ui.prepend_text.get_value())
  3260. postamble = str(self.ui.append_text.get_value())
  3261. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  3262. self.app.file_saved.emit("gcode", filename)
  3263. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  3264. def on_modifygcode_button_click(self, *args):
  3265. # add the tab if it was closed
  3266. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "CNC Code Editor")
  3267. # delete the absolute and relative position and messages in the infobar
  3268. self.app.ui.position_label.setText("")
  3269. self.app.ui.rel_position_label.setText("")
  3270. # Switch plot_area to CNCJob tab
  3271. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  3272. preamble = str(self.ui.prepend_text.get_value())
  3273. postamble = str(self.ui.append_text.get_value())
  3274. self.app.gcode_edited = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  3275. # first clear previous text in text editor (if any)
  3276. self.app.ui.code_editor.clear()
  3277. # then append the text from GCode to the text editor
  3278. for line in self.app.gcode_edited:
  3279. proc_line = str(line).strip('\n')
  3280. self.app.ui.code_editor.append(proc_line)
  3281. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3282. self.app.handleTextChanged()
  3283. self.app.ui.show()
  3284. def gcode_header(self):
  3285. log.debug("FlatCAMCNCJob.gcode_header()")
  3286. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  3287. marlin = False
  3288. hpgl = False
  3289. try:
  3290. for key in self.cnc_tools:
  3291. if self.cnc_tools[key]['data']['ppname_g'] == 'marlin':
  3292. marlin = True
  3293. break
  3294. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3295. hpgl = True
  3296. break
  3297. except Exception as e:
  3298. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  3299. try:
  3300. for key in self.cnc_tools:
  3301. if self.cnc_tools[key]['data']['ppname_e'] == 'marlin':
  3302. marlin = True
  3303. break
  3304. except:
  3305. pass
  3306. if marlin is True:
  3307. gcode = ';Marlin G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  3308. (str(self.app.version), str(self.app.version_date)) + '\n'
  3309. gcode += ';Name: ' + str(self.options['name']) + '\n'
  3310. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  3311. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3312. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3313. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  3314. gcode += ';Created on ' + time_str + '\n' + '\n'
  3315. elif hpgl is True:
  3316. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  3317. (str(self.app.version), str(self.app.version_date)) + '";\n'
  3318. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  3319. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  3320. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3321. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3322. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  3323. gcode += 'CO "Created on ' + time_str + '";\n'
  3324. else:
  3325. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  3326. (str(self.app.version), str(self.app.version_date)) + '\n'
  3327. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  3328. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  3329. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3330. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3331. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  3332. gcode += '(Created on ' + time_str + ')\n' + '\n'
  3333. return gcode
  3334. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  3335. gcode = ''
  3336. roland = False
  3337. hpgl = False
  3338. # detect if using Roland postprocessor
  3339. try:
  3340. for key in self.cnc_tools:
  3341. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  3342. roland = True
  3343. break
  3344. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3345. hpgl = True
  3346. break
  3347. except:
  3348. try:
  3349. for key in self.cnc_tools:
  3350. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  3351. roland = True
  3352. break
  3353. except:
  3354. pass
  3355. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  3356. if roland is False and hpgl is False:
  3357. gcode = self.gcode_header()
  3358. # detect if using multi-tool and make the Gcode summation correctly for each case
  3359. if self.multitool is True:
  3360. for tooluid_key in self.cnc_tools:
  3361. for key, value in self.cnc_tools[tooluid_key].items():
  3362. if key == 'gcode':
  3363. gcode += value
  3364. break
  3365. else:
  3366. gcode += self.gcode
  3367. if roland is True:
  3368. g = preamble + gcode + postamble
  3369. elif hpgl is True:
  3370. g = self.gcode_header() + preamble + gcode + postamble
  3371. else:
  3372. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  3373. g_idx = gcode.rfind('G20')
  3374. # if it did not find 'G20' then search for 'G21'
  3375. if g_idx == -1:
  3376. g_idx = gcode.rfind('G21')
  3377. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  3378. if g_idx == -1:
  3379. self.app.inform.emit("[error_notcl] G-code does not have a units code: either G20 or G21")
  3380. return
  3381. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  3382. # lines = StringIO(self.gcode)
  3383. lines = StringIO(g)
  3384. ## Write
  3385. if filename is not None:
  3386. try:
  3387. with open(filename, 'w') as f:
  3388. for line in lines:
  3389. f.write(line)
  3390. except FileNotFoundError:
  3391. self.app.inform.emit("[warning_notcl] No such file or directory")
  3392. return
  3393. elif to_file is False:
  3394. # Just for adding it to the recent files list.
  3395. self.app.file_opened.emit("cncjob", filename)
  3396. self.app.inform.emit("[success] Saved to: " + filename)
  3397. else:
  3398. return lines
  3399. def get_gcode(self, preamble='', postamble=''):
  3400. #we need this to be able get_gcode separatelly for shell command export_gcode
  3401. return preamble + '\n' + self.gcode + "\n" + postamble
  3402. def get_svg(self):
  3403. # we need this to be able get_svg separately for shell command export_svg
  3404. pass
  3405. def on_plot_cb_click(self, *args):
  3406. if self.muted_ui:
  3407. return
  3408. self.plot()
  3409. self.read_form_item('plot')
  3410. self.ui_disconnect()
  3411. cb_flag = self.ui.plot_cb.isChecked()
  3412. for row in range(self.ui.cnc_tools_table.rowCount()):
  3413. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  3414. if cb_flag:
  3415. table_cb.setChecked(True)
  3416. else:
  3417. table_cb.setChecked(False)
  3418. self.ui_connect()
  3419. def on_plot_cb_click_table(self):
  3420. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3421. self.ui_disconnect()
  3422. cw = self.sender()
  3423. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  3424. cw_row = cw_index.row()
  3425. self.shapes.clear(update=True)
  3426. for tooluid_key in self.cnc_tools:
  3427. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3428. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3429. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  3430. if self.ui.cnc_tools_table.cellWidget((tooluid_key - 1), 6).isChecked():
  3431. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed)
  3432. self.shapes.redraw()
  3433. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3434. # if all the row plot's are enabled also enable the general plot checkbox
  3435. cb_cnt = 0
  3436. total_row = self.ui.cnc_tools_table.rowCount()
  3437. for row in range(total_row):
  3438. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  3439. cb_cnt += 1
  3440. else:
  3441. cb_cnt -= 1
  3442. if cb_cnt < total_row:
  3443. self.ui.plot_cb.setChecked(False)
  3444. else:
  3445. self.ui.plot_cb.setChecked(True)
  3446. self.ui_connect()
  3447. def plot(self, visible=None):
  3448. # Does all the required setup and returns False
  3449. # if the 'ptint' option is set to False.
  3450. if not FlatCAMObj.plot(self):
  3451. return
  3452. visible = visible if visible else self.options['plot']
  3453. try:
  3454. if self.multitool is False: # single tool usage
  3455. self.plot2(tooldia=self.options["tooldia"], obj=self, visible=visible)
  3456. else:
  3457. # multiple tools usage
  3458. for tooluid_key in self.cnc_tools:
  3459. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3460. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3461. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed)
  3462. self.shapes.redraw()
  3463. except (ObjectDeleted, AttributeError):
  3464. self.shapes.clear(update=True)
  3465. self.annotation.clear(update=True)
  3466. def convert_units(self, units):
  3467. factor = CNCjob.convert_units(self, units)
  3468. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  3469. self.options["tooldia"] *= factor
  3470. # end of file