FlatCAMObj.py 213 KB

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