FlatCAMObj.py 262 KB

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