FlatCAMObj.py 163 KB

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