FlatCAMObj.py 259 KB

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