FlatCAMObj.py 213 KB

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