FlatCAMObj.py 235 KB

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