FlatCAMObj.py 162 KB

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