FlatCAMObj.py 216 KB

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