FlatCAMObj.py 236 KB

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