FlatCAMObj.py 253 KB

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