FlatCAMObj.py 216 KB

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