FlatCAMObj.py 239 KB

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