FlatCAMObj.py 261 KB

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